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
module Main where import System.Exit (ExitCode(..), exitSuccess, exitWith) import Control.Monad (unless, when) import Idris.AbsSyntax import Idris.CmdOptions import Idris.Error import Idris.Info.Show import Idris.Main import Idris.Options import Idris.Package import Util.System (setupBundledCC) processShowOptions :: [Opt] -> Idris () processShowOptions opts = runIO $ do when (ShowAll `elem` opts) $ showExitIdrisInfo when (ShowLoggingCats `elem` opts) $ showExitIdrisLoggingCategories when (ShowIncs `elem` opts) $ showExitIdrisFlagsInc when (ShowLibs `elem` opts) $ showExitIdrisFlagsLibs when (ShowLibDir `elem` opts) $ showExitIdrisLibDir when (ShowDocDir `elem` opts) $ showExitIdrisDocDir when (ShowPkgs `elem` opts) $ showExitIdrisInstalledPackages check :: [Opt] -> (Opt -> Maybe a) -> ([a] -> Idris ()) -> Idris () check opts extractOpts action = do case opt extractOpts opts of [] -> return () fs -> do action fs runIO exitSuccess processClientOptions :: [Opt] -> Idris () processClientOptions opts = check opts getClient $ \fs -> case fs of [] -> ifail "No --client argument. This indicates a bug. Please report." (c : _) -> do setVerbose 0 setQuiet True case getPort opts of Just DontListen -> ifail "\"--client\" and \"--port none\" are incompatible" Just (ListenPort port) -> runIO $ runClient (Just port) c Nothing -> runIO $ runClient Nothing c processPackageOptions :: [Opt] -> Idris () processPackageOptions opts = do check opts getPkgCheck $ \fs -> runIO $ do mapM_ (checkPkg opts (WarnOnly `elem` opts) True) fs check opts getPkgClean $ \fs -> runIO $ do mapM_ (cleanPkg opts) fs check opts getPkgMkDoc $ \fs -> runIO $ do mapM_ (documentPkg opts) fs check opts getPkgTest $ \fs -> runIO $ do codes <- mapM (testPkg opts) fs -- check if any of the tests exited with an exit code other -- than zero; if they did, exit with exit code 1 unless (null $ filter (/= ExitSuccess) codes) $ exitWith (ExitFailure 1) check opts getPkg $ \fs -> runIO $ do mapM_ (buildPkg opts (WarnOnly `elem` opts)) fs check opts getPkgREPL $ \fs -> case fs of [f] -> replPkg opts f _ -> ifail "Too many packages" -- | The main function for the Idris executable. runIdris :: [Opt] -> Idris () runIdris opts = do runIO setupBundledCC processShowOptions opts -- Show information then quit. processClientOptions opts -- Be a client to a REPL server. processPackageOptions opts -- Work with Idris packages. idrisMain opts -- Launch REPL or compile mode. -- Main program reads command line options, parses the main program, and gets -- on with the REPL. main :: IO () main = do opts <- runArgParser runMain (runIdris opts)
uuhan/Idris-dev
main/Main.hs
bsd-3-clause
2,861
0
18
661
901
451
450
64
4
{-# LANGUAGE PolyKinds #-} module DepFail1 where data Proxy k (a :: k) = P z :: Proxy Bool z = P a :: Proxy Int Bool a = P
sdiehl/ghc
testsuite/tests/dependent/should_fail/DepFail1.hs
bsd-3-clause
127
0
5
34
48
29
19
7
1
{-# LANGUAGE OverloadedStrings #-} module Yesod.Form.I18n.Norwegian where import Yesod.Form.Types (FormMessage (..)) import Data.Monoid (mappend) import Data.Text (Text) norwegianBokmålFormMessage :: FormMessage -> Text norwegianBokmålFormMessage (MsgInvalidInteger t) = "Ugyldig antall: " `mappend` t norwegianBokmålFormMessage (MsgInvalidNumber t) = "Ugyldig nummer: " `mappend` t norwegianBokmålFormMessage (MsgInvalidEntry t) = "Ugyldig oppføring: " `mappend` t norwegianBokmålFormMessage MsgInvalidTimeFormat = "Ugyldig klokkeslett, må være i formatet HH:MM[:SS]" norwegianBokmålFormMessage MsgInvalidDay = "Ugyldig dato, må være i formatet ÅÅÅÅ-MM-DD" norwegianBokmålFormMessage (MsgInvalidUrl t) = "Ugyldig URL: " `mappend` t norwegianBokmålFormMessage (MsgInvalidEmail t) = "Ugyldig e-postadresse: " `mappend` t norwegianBokmålFormMessage (MsgInvalidHour t) = "Ugyldig time: " `mappend` t norwegianBokmålFormMessage (MsgInvalidMinute t) = "Ugyldig minutt: " `mappend` t norwegianBokmålFormMessage (MsgInvalidSecond t) = "Ugyldig sekund: " `mappend` t norwegianBokmålFormMessage MsgValueRequired = "Feltet er obligatorisk" norwegianBokmålFormMessage (MsgInputNotFound t) = "Feltet ble ikke funnet: " `mappend` t norwegianBokmålFormMessage MsgSelectNone = "<Ingenting>" norwegianBokmålFormMessage (MsgInvalidBool t) = "Ugyldig sannhetsverdi: " `mappend` t norwegianBokmålFormMessage MsgBoolYes = "Ja" norwegianBokmålFormMessage MsgBoolNo = "Nei" norwegianBokmålFormMessage MsgDelete = "Slette?" norwegianBokmålFormMessage MsgCsrfWarning = "Som beskyttelse mot «cross-site request forgery»-angrep, vennligst bekreft innsendt skjema."
meteficha/yesod
yesod-form/Yesod/Form/I18n/Norwegian.hs
mit
1,671
2
7
171
356
195
161
24
1
-- !!! can't seek an AppendMode handle import System.IO import System.IO.Error main = do h <- openFile "hSeek004.out" AppendMode tryIOError (hSeek h AbsoluteSeek 0) >>= print
olsner/ghc
libraries/base/tests/IO/hSeek004.hs
bsd-3-clause
181
0
10
32
50
25
25
5
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} ------------------------------------------- -- | -- Module : Web.Stripe.Customer -- Copyright : (c) David Johnson, 2014 -- Maintainer : djohnson.m@gmail.com -- Stability : experimental -- Portability : POSIX -- -- < https:/\/\stripe.com/docs/api#customers > -- -- @ -- {-\# LANGUAGE OverloadedStrings \#-} -- import Web.Stripe -- import Web.Stripe.Customer -- -- main :: IO () -- main = do -- let config = StripeConfig (StripeKey "secret_key") -- result <- stripe config createCustomer -- case result of -- Right customer -> print customer -- Left stripeError -> print stripeError -- @ module Web.Stripe.Customer ( -- * API ---- * Create customer CreateCustomer , createCustomer ---- * Retrieve customer , GetCustomer , getCustomer ---- * Update customer , UpdateCustomer , updateCustomer ---- * Delete customer , DeleteCustomer , deleteCustomer ---- * List customers , GetCustomers , getCustomers -- * Types , AccountBalance (..) , CardId (..) , CardNumber (..) , CouponId (..) , Created (..) , Customer (..) , CustomerId (..) , CVC (..) , Description (..) , Email (..) , EndingBefore (..) , ExpandParams (..) , ExpMonth (..) , ExpYear (..) , Limit (..) , MetaData (..) , mkNewCard , NewCard (..) , PlanId (..) , Quantity (..) , StartingAfter (..) , StripeDeleteResult (..) , StripeList (..) , TokenId (..) , TrialEnd (..) ) where import Web.Stripe.StripeRequest (Method (GET, POST, DELETE), StripeHasParam, StripeRequest (..), StripeReturn, mkStripeRequest) import Web.Stripe.Util ((</>)) import Web.Stripe.Types (AccountBalance(..), CVC (..), CardId (..), CardNumber (..), CouponId (..), Created(..), Customer (..), CustomerId (..), DefaultCard(..), Description(..), Email (..), EndingBefore(..), ExpMonth (..), ExpYear (..), Limit(..), PlanId (..), Quantity (..), MetaData(..), mkNewCard, NewCard(..), StartingAfter(..), StripeDeleteResult (..), StripeList (..), TokenId (..), TrialEnd(..), ExpandParams(..)) import Web.Stripe.Types.Util ------------------------------------------------------------------------------ -- | Create a customer createCustomer :: StripeRequest CreateCustomer createCustomer = request where request = mkStripeRequest POST url params url = "customers" params = [] data CreateCustomer type instance StripeReturn CreateCustomer = Customer instance StripeHasParam CreateCustomer AccountBalance instance StripeHasParam CreateCustomer NewCard instance StripeHasParam CreateCustomer TokenId instance StripeHasParam CreateCustomer CouponId instance StripeHasParam CreateCustomer Description instance StripeHasParam CreateCustomer Email instance StripeHasParam CreateCustomer MetaData instance StripeHasParam CreateCustomer PlanId instance StripeHasParam CreateCustomer Quantity instance StripeHasParam CreateCustomer TrialEnd ------------------------------------------------------------------------------ -- | Retrieve a customer getCustomer :: CustomerId -- ^ `CustomerId` of `Customer` to retrieve -> StripeRequest GetCustomer getCustomer customerid = request where request = mkStripeRequest GET url params url = "customers" </> getCustomerId customerid params = [] data GetCustomer type instance StripeReturn GetCustomer = Customer instance StripeHasParam GetCustomer ExpandParams ------------------------------------------------------------------------------ -- | Update a `Customer` updateCustomer :: CustomerId -- ^ `CustomerId` of `Customer` to update -> StripeRequest UpdateCustomer updateCustomer customerid = request where request = mkStripeRequest POST url params url = "customers" </> getCustomerId customerid params = [] data UpdateCustomer type instance StripeReturn UpdateCustomer = Customer instance StripeHasParam UpdateCustomer AccountBalance instance StripeHasParam UpdateCustomer TokenId instance StripeHasParam UpdateCustomer NewCard instance StripeHasParam UpdateCustomer CouponId instance StripeHasParam UpdateCustomer DefaultCard instance StripeHasParam UpdateCustomer Description instance StripeHasParam UpdateCustomer Email instance StripeHasParam UpdateCustomer MetaData ------------------------------------------------------------------------------ -- | Deletes the specified `Customer` data DeleteCustomer type instance StripeReturn DeleteCustomer = StripeDeleteResult deleteCustomer :: CustomerId -- ^ The `CustomerId` of the `Customer` to delete -> StripeRequest DeleteCustomer deleteCustomer customerid = request where request = mkStripeRequest DELETE url params url = "customers" </> getCustomerId customerid params = [] ------------------------------------------------------------------------------ -- | Retrieve up to 100 customers at a time getCustomers :: StripeRequest GetCustomers getCustomers = request where request = mkStripeRequest GET url params url = "customers" params = [] data GetCustomers type instance StripeReturn GetCustomers = (StripeList Customer) instance StripeHasParam GetCustomers ExpandParams instance StripeHasParam GetCustomers Created instance StripeHasParam GetCustomers (EndingBefore CustomerId) instance StripeHasParam GetCustomers Limit instance StripeHasParam GetCustomers (StartingAfter CustomerId)
dmjio/stripe
stripe-core/src/Web/Stripe/Customer.hs
mit
6,489
0
8
1,860
1,034
634
400
-1
-1
{-# LANGUAGE RankNTypes #-} -- Walking trees with coroutines. -- Based on: -- <http://okmij.org/ftp/continuations/ContExample.hs> module Tree where import Control.Delimited -- Binary trees data Tree a = Leaf | Node (Tree a) (Tree a) a deriving (Show, Eq) make_tree :: Int -> Tree Int make_tree j = go j 1 where go 0 _ = Leaf go i x = Node (go (i-1) $ 2*x) (go (i-1) $ 2*x+1) x tree1 = make_tree 3 tree2 = make_tree 4 -- Coroutines as lazy monadic lists. data Coro a = Done | Resume a (forall s. Delim s s (Coro a)) walk_tree x = runDelim (walk_tree' x !>> returnI Done) walk_tree' Leaf = returnI () walk_tree' (Node l r x) = walk_tree' l !>> yield x !>> walk_tree' r where yield n = shift2 (\k -> returnI $ Resume n $ k ()) walk1 :: Show a => Tree a -> IO () walk1 t = go (walk_tree t) where go Done = return () go (Resume x k) = print x >> go (runDelim k) {- *Tree> walk1 tree1 4 2 5 1 6 3 7 *Tree> -}
thoughtpolice/hs-asai
examples/Tree.hs
mit
970
0
14
253
405
205
200
27
2
module Y2016.M06.D14.Exercise where import Data.Matrix {-- Okay, so now that you have solved what the determinant of a matrix is (yesterday's exercise), today, let's solve what the inverse of a matrix is and, with that, solve a system of equations. There are multiple methods on how to invert a matrix. One approach is: https://www.mathsisfun.com/algebra/matrix-inverse-minors-cofactors-adjugate.html Whatever approach you choose it must be that: (inverse a) `cross` a = identityMatrix and a `cross` (inverse a) = identityMatrix So, let's get to it: --} inverse :: Num a => Matrix a -> Matrix a inverse = undefined {-- With the above defined, you can solve systems of equations, for, as you recall AX = B represents A X B -------------------------- | 2 1 2 | | x | | 3 | | 1 -1 -1 | | y | = | 0 | | 1 1 3 | | z | | 12 | So: X = (inverse A) `cross` B So, given: --} a, b :: Matrix Float a = fromLists [[2,1,2], [1, -1, -1], [1,1,3]] b = transpose (fromLists [[3,0,12]]) -- note how b is defined {-- Recall that you can 'view' matrices with pprint. Now, set up the matrices and solve the below system of equations x + z = 6 z - 3y = 7 2x + y + 3z = 15 with the below solver --} solver :: Matrix Float -> Matrix Float -> Matrix Float solver = undefined
geophf/1HaskellADay
exercises/HAD/Y2016/M06/D14/Exercise.hs
mit
1,311
0
9
302
155
90
65
9
1
module Standard where import Data.Monoid -- TODO: replace with more general version of myAnd that uses `Foldable` instead of [] -- See: https://hackage.haskell.org/package/base-4.9.0.0/docs/src/Data.Foldable.html# myAnd :: [Bool] -> Bool myAnd [] = True myAnd (True : xs) = myAnd xs myAnd (False : xs) = False myAnd' :: [Bool] -> Bool myAnd' = foldr (&&) True myOr :: [Bool] -> Bool myOr [] = False myOr (True : xs) = True myOr (False : xs) = myOr xs myOr' :: [Bool] -> Bool myOr' = foldr (||) False myAny :: (a -> Bool) -> [a] -> Bool myAny _ [] = False myAny f (x:xs) | x' == True = True | otherwise = myAny f xs where x' = f x myAny' :: (a -> Bool) -> [a] -> Bool myAny' f = foldr ((||) . f) False myElem :: Eq a => a -> [a] -> Bool myElem _ [] = False myElem e (x:xs) | match == True = True | otherwise = myElem e xs where match = e == x myElem' :: Eq a => a -> [a] -> Bool myElem' x = myAny' (== x) myReverse :: [a] -> [a] myReverse [] = [] myReverse (x:xs) = (myReverse xs) ++ [x] myReverse' :: [a] -> [a] myReverse' = foldl (flip (:)) mempty squish :: [[a]] -> [a] squish [] = [] squish (x:xs) = x ++ (squish xs) squish' :: [[a]] -> [a] squish' = foldr (foldr (:)) mempty -- Test: -- > squish [[1,2,3], [4,5,6]] -- [1,2,3,4,5,6] squishMap :: (a -> [b]) -> [a] -> [b] squishMap = (squish .) . fmap -- Test: -- > squishMap (\x -> [1, x, 3]) [2] -- [1,2,3] -- > squishMap (\x -> "WO "++[x]++" HOO ") "123" -- "WO 1 HOO WO 2 HOO WO 3 HOO " -- Given an ordering function, an "extreme" ordering value (LT or GT), -- and a list, select the extreme value (the min or max). selectExtremeValue :: Ordering -> (a -> a -> Ordering) -> [a] -> a selectExtremeValue _ _ [] = undefined selectExtremeValue _ _ (x:[]) = x selectExtremeValue o f (x:(y:ys)) | f x y == o = selectExtremeValue o f (x:ys) | otherwise = selectExtremeValue o f (y:ys) myMaximumBy :: (a -> a -> Ordering) -> [a] -> a myMaximumBy = selectExtremeValue GT myMinimumBy :: (a -> a -> Ordering) -> [a] -> a myMinimumBy = selectExtremeValue LT myMaximum :: Ord a => [a] -> a myMaximum = myMaximumBy compare myMinimum :: Ord a => [a] -> a myMinimum = myMinimumBy compare
JoshuaGross/haskell-learning-log
Code/Haskellbook/Standard.hs
mit
2,176
0
9
475
924
499
425
56
1
import System.IO (openFile, hClose, IOMode(..)) import Options.Applicative import Data.ByteString.Lazy (ByteString) import Data.Binary (encode) import Data.Digest.CRC32 (crc32) import Control.Error (runScript, hoistEither, scriptIO) import qualified Data.ByteString.Lazy as B import Options -- PNG header has fixed size and we are going to use that fact in our -- calculations pngHeaderSize :: Int pngHeaderSize = 8 -- bytes -- IHDR chunk is the first chunk following PNG header and also has a fixed -- size which will also help us in our calculations ihdrChunkSize :: Int ihdrChunkSize = 25 -- 4 bytes length, 4 bytes identity, 13 bytes data, 4 bytes crc -- PNG header should be the same for all image files and we want to make -- sure that the provided input file at least has a correct header... verifyPNGHeader :: ByteString -> Either String () verifyPNGHeader h = if h == expectedHeader then Right () else Left "Incorrect PNG file provided (header mismatch)" where expectedHeader = B.pack . map fromIntegral $ ([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]::[Integer]) -- ... and that the first chunk following the PNG header is a chunk of IHDR -- type (here we only check the signature of the chunk and nothing else) verifyIHDRChunk :: ByteString -> Either String () verifyIHDRChunk h = if B.drop 4 (B.take 8 h) == expectedHeaderType then Right () else Left "Incorrect PNG file provided (IHDR chunk not found)" where expectedHeaderType = B.pack [73, 72, 68, 82] -- The only thing we disallow is for our increase size to be smaller than -- 14 bytes. This is due to the fact that adding a chunk with length -- 0 results in 12 bytes (4 bytes for length, 4 bytes for type and 4 bytes -- crc). But if we decide to add and empty value to tEXt key/value chunk -- then we end up with a minimum of 14 bytes increase verifyOptions :: Options -> Either String () verifyOptions options = if sizeIncrease options < 14 -- 4 bytes length, 4 bytes identity, min 2 bytes data, 4 bytes crc then Left "Unfortunately increasing size by less than 14 bytes is not supported" else Right () -- We are given the desired size increase and we need to calcuate what kind -- of data we need to generate based on those numbers: -- 4 bytes is for the length of the chunk -- 4 bytes is for the type of the chunk (tEXt) -- 4 bytes is for the crc32 of the chunk -- That is why you see -12 in these calculations genereateTEXTChunk :: Options -> ByteString genereateTEXTChunk options = lengthChunk `B.append` typeChunk `B.append` dataChunk `B.append` crcChunk where lengthChunk = encode (sizeIncrease options - 12) typeChunk = B.pack [116, 69, 88, 116] -- tEXt dataChunk = B.pack [70, 0] `B.append` B.replicate (fromIntegral (sizeIncrease options) - 2 - 12) 87 crcChunk = encode $ crc32 (typeChunk `B.append` dataChunk) -- Open an input file and read its header and IHDR chunk and write them to -- the output file. Then add our tEXt chunk to the output file and then -- read the rest from the input file and write it to the output file -- resulting in a PNG with a tEXt chunk of desired length right after the -- IHDR chunk appendChunkToFile :: Options -> ByteString -> IO () appendChunkToFile options chunk = do inputHandle <- openFile (inputFile options) ReadWriteMode outputHandle <- openFile (outputFile options) WriteMode B.hPut outputHandle =<< B.hGet inputHandle (pngHeaderSize + ihdrChunkSize) B.hPut outputHandle chunk B.hPut outputHandle =<< B.hGetContents inputHandle hClose inputHandle hClose outputHandle -- Do some simple verifications before we proceed to actually adding data increasePNGSize :: Options -> IO () increasePNGSize options = runScript $ do (fileHeader, ihdrChunk) <- scriptIO $ do handle <- openFile (inputFile options) ReadMode h <- B.hGet handle pngHeaderSize ihdr <- B.hGet handle ihdrChunkSize hClose handle return (h, ihdr) hoistEither $ do verifyOptions options verifyPNGHeader fileHeader verifyIHDRChunk ihdrChunk let textChunk = genereateTEXTChunk options scriptIO $ appendChunkToFile options textChunk return () main :: IO () main = execParser opts >>= increasePNGSize where opts = info (helper <*> optionsParser) (fullDesc <> progDesc "Increase size of a PNG input file by SIZE bytes" <> header "super-size-png - a tool for increasing size of a PNG file")
ksaveljev/super-size-png
src/Main.hs
mit
4,536
0
15
970
872
462
410
62
2
module Command.UpdateIndex ( Options , parserInfo , run ) where import Options.Applicative import Text.Read (step, readPrec) import qualified Blob data CacheInfoParams = NoCacheInfoParams | CacheInfoParams Int Blob.Id FilePath --instance Read CacheInfoParams where -- readPrec = do -- m <- step readPrec -- i <- step readPrec -- path <- step readPrec -- return $ CacheInfoParams m i path data Options = Options { _optAdd :: Bool , _optRemove :: Bool , _optRefresh :: Bool --, optForceRemove :: Bool --, optReplace :: Bool --, optQuiet :: Bool --, optUnmerged :: Bool --, optIgnoreMissing :: Bool --, optAssumeUnchanged :: Bool --, optSkipWorkTree :: Bool --, optReallyRefresh :: Bool --, _optCacheInfo :: CacheInfoParams --, optVerbose :: Bool , _optPath :: [FilePath] } parserInfo :: ParserInfo Options parserInfo = info parser (progDesc "Register file contents in the working tree to the index") parser :: Parser Options parser = Options <$> switch ( long "add" <> help "If a specified file isn't in the index already then it's added. Default behaviour is to ignore new files." ) <*> switch ( long "remove" <> help "If a specified file is in the index but is missing then it's removed. Default behavior is to ignore removed file." ) <*> switch ( long "refresh" <> help "Looks at the current index and checks to see if merges or updates are needed by checking stat() information." ) -- <*> option auto -- ( long "cacheinfo" -- <> value NoCacheInfoParams -- <> metavar "<mode> <object> <path>" -- <> help "Looks at the current index and checks to see if merges or updates are needed by checking stat() information." ) <*> many ( argument str (metavar "PATH")) run :: Options -> IO () run _ = undefined
danstiner/clod
src/Command/UpdateIndex.hs
mit
1,830
0
12
414
254
146
108
31
1
module Prepare.Tanach.IndexParser where import Prelude hiding (Word) import Prepare.Xml.Parser (NodeParser, many, optional) import qualified Prepare.Xml.Parser as Xml import qualified Text.Megaparsec.Lexer as MP import Prepare.Tanach.IndexModel import Prepare.Tanach.TeiHeaderParser (teiHeader) verseCount :: NodeParser Integer verseCount = Xml.elementContent "vs" >>= Xml.parseNested "verse count" MP.integer chapter :: NodeParser Chapter chapter = build <$> Xml.elementAttr "c" attributes children where build (n, vs) = Chapter n vs attributes = Xml.attribute "n" >>= Xml.parseNested "chapter number" MP.integer children = verseCount name :: NodeParser Name name = Xml.element "names" ( Name <$> Xml.elementContent "name" <*> Xml.elementContent "abbrev" <*> optional (Xml.elementContent "number") <*> Xml.elementContent "filename" <*> optional (Xml.elementContent "hebrewname") ) chapterCount :: NodeParser Integer chapterCount = Xml.elementContent "cs" >>= Xml.parseNested "chapter count" MP.integer book :: NodeParser Book book = Xml.element "book" ( Book <$> name <*> many chapter <*> chapterCount ) index :: NodeParser Index index = Xml.element "Tanach" ( Index <$> teiHeader <*> Xml.element "tanach" (many book) )
ancientlanguage/haskell-analysis
prepare/src/Prepare/Tanach/IndexParser.hs
mit
1,277
0
13
205
367
194
173
38
1
-- | This module holds the base data types and functions to interact with -- them. This is the lowest-level interface to interact with the datastore. module Database.Hasqueue.Core.Value ( -- * Base Types BucketID , ValueID , Value(..) -- * Error , HasqueueError(..) ) where import qualified Control.Monad.Error.Class as E import qualified Data.ByteString as B import qualified Data.Map as M import qualified Data.Sequence as SQ -- | Used to uniquely identify 'Bucket's in a 'World'. type BucketID = B.ByteString -- | Used to uniquely identify 'Value's in a 'Bucket'. type ValueID = B.ByteString -- | A 'Value' is any type that may be stored in the datastore. data Value = Null | Boolean Bool | Int Int | Double Double | String B.ByteString | List (SQ.Seq Value) | Hash (M.Map B.ByteString Value) deriving (Eq, Show) -- | A 'HasqueueError' is thrown when something unexpected happens during -- a datastore lookup. data HasqueueError = InternalError B.ByteString | ParseError B.ByteString | BucketExists BucketID | NoSuchBucket BucketID | NoSuchValue BucketID ValueID deriving (Eq, Show) instance E.Error HasqueueError where strMsg = InternalError . B.pack . map (toEnum . fromEnum)
nahiluhmot/hasqueue
src/Database/Hasqueue/Core/Value.hs
mit
1,583
0
9
587
240
149
91
27
0
import Data.Array ((!), Array, bounds, listArray) import Data.List (intercalate) import System.Random data Point = Point Double Double chaosGame :: RandomGen g => g -> Int -> Array Int (Point -> Point) -> [Point] chaosGame g n hutchinson = take n points where (x, g') = random g (y, g'') = random g' choices = randomRs (bounds hutchinson) g'' points = Point x y : zipWith (hutchinson !) choices points main :: IO () main = do g <- newStdGen let midPoint (Point a b) (Point x y) = Point ((a + x) / 2) ((b + y) / 2) sierpinski = listArray (1, 3) [ midPoint (Point 0 0), midPoint (Point 0.5 (sqrt 0.75)), midPoint (Point 1 0) ] points = chaosGame g 10000 sierpinski showPoint (Point x y) = show x ++ "\t" ++ show y writeFile "sierpinski.dat" $ intercalate "\n" $ map showPoint points
leios/algorithm-archive
contents/IFS/code/haskell/IFS.hs
mit
890
0
16
255
390
200
190
23
1
module Unison.Util.Range where import Unison.Lexer (Pos(..)) -- | True if `_x` contains `_y` contains :: Range -> Range -> Bool _x@(Range a b) `contains` _y@(Range c d) = a <= c && d <= b overlaps :: Range -> Range -> Bool overlaps (Range a b) (Range c d) = a < d && c < b inRange :: Pos -> Range -> Bool inRange p (Range a b) = p >= a && p < b isMultiLine :: Range -> Bool isMultiLine (Range (Pos startLine _) (Pos endLine _)) = startLine < endLine data Range = Range { start :: Pos, end :: Pos } deriving (Eq, Ord, Show) startingLine :: Range -> Range startingLine r@(Range start@(Pos startLine _) (Pos stopLine _)) = if stopLine == startLine then r else Range start (Pos (startLine+1) 0) instance Semigroup Range where (Range start end) <> (Range start2 end2) = Range (min start start2) (max end end2)
unisonweb/platform
parser-typechecker/src/Unison/Util/Range.hs
mit
823
0
11
173
392
208
184
18
2
module Typecrawl.Process (processSite) where import Pipes import qualified Pipes.Prelude as P import Control.Monad (join) import Typecrawl.Types import Typecrawl.Scrapper import Typecrawl.Exporter -- | Starts the whole scrapping shenanigan. -- This could be severely improved, most likely by -- making scrapping more parametrable, through a -- collection of commands (where to get nextPage, -- how to collect direct post links, etc.) processSite :: PlatformParseInstructions -> Url -> FilePath -> Maybe Int -> IO () processSite ppis url dest steps = let process (Just depth) = process' >-> P.take depth process Nothing = process' process' = postsOnPage ppis (Just url) in P.toListM (process steps) >>= storeScrapped dest . join
Raveline/typecrawl
lib/Typecrawl/Process.hs
mit
739
0
11
117
170
91
79
13
2
module Config( Arch(..), showArch, Program(..), Version, defaultVersion, source, dest, extractVersion ) where import Data.List.Extra import Development.Shake.FilePath import Data.Char data Arch = Arch32 | Arch64 showArch :: Arch -> String showArch Arch32 = "i386" showArch Arch64 = "x86_64" data Program = GHC | Git | Stack deriving (Eq,Show,Enum,Bounded) type Version = String defaultVersion :: Program -> Version -- Latest released versions of all defaultVersion GHC = "7.10.2" defaultVersion Git = "2.4.5.1" defaultVersion Stack = "0.1.6.0" source :: Arch -> Program -> Version -> String -- Official GHC release, available in xv and bz2, but the xv one is harder to extract on Windows systems source arch GHC ver = "https://www.haskell.org/ghc/dist/" ++ ver ++ "/ghc-" ++ ver ++ "-" ++ showArch arch ++ "-unknown-mingw32.tar.xz" source _ Git "2.4.5.1" = "https://github.com/git-for-windows/git/releases/download/v2.4.5.windows.1/PortableGit-2.4.5.1-4th-release-candidate-32-bit.7z.exe" source arch Stack ver = concat [ "https://github.com/commercialhaskell/stack/releases/download/v" , ver , "/stack-" , ver , "-windows-" , showArch arch , ".zip" ] dest :: Version -> Arch -> Program -> FilePath dest ver arch GHC = concat [ "ghc-" , ver , "-" , showArch arch , ".tar.xz" ] dest ver _arch Git = concat [ "git-" , ver , ".7z" ] dest ver arch Stack = concat [ "bin/bin/stack-" , ver , "-" , showArch arch , ".zip" ] -- | Given a filename containing a version-like bit, extract the version extractVersion :: String -> Version extractVersion = intercalate "." . takeWhile f . dropWhile (not . f) . wordsBy (`elem` "-.") . takeFileName where f = all isDigit
fpco/minghc
Config.hs
mit
1,801
0
10
393
443
246
197
52
1
module Helpers.Heroku (herokuConf) where import Prelude import Data.ByteString (ByteString) import Data.Text (Text) import Data.Text.Encoding (encodeUtf8) import Database.Persist.Postgresql (PostgresConf(..)) import Web.Heroku (dbConnParams) import qualified Data.Text as T herokuConf :: IO PostgresConf herokuConf = do params <- dbConnParams return PostgresConf { pgConnStr = formatParams params , pgPoolSize = 10 -- Adjust this as you see fit! } where formatParams :: [(Text, Text)] -> ByteString formatParams = encodeUtf8 . T.unwords . map toKeyValue toKeyValue :: (Text, Text) -> Text toKeyValue (k, v) = k `T.append` "=" `T.append` v
ackao/APRICoT
web/conference-management-system/Helpers/Heroku.hs
gpl-3.0
698
0
10
144
205
121
84
18
1
{-# LANGUAGE OverloadedStrings #-} module AboutResponse (aboutResponse) where import Text.Blaze ((!)) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import Data.Text.Lazy (Text) import Happstack.Server import MasterTemplate import Utilities (mdToHTML) aboutResponse :: Text -> ServerPart Response aboutResponse aboutContents = ok $ toResponse $ masterTemplate "Courseography - About" [] (do header "about" aboutHtml aboutContents ) "" -- | AboutHtml takes in the contents of the README.md file (the GitHub README file) and translates -- the markdown to blaze-HTML. aboutHtml :: Text -> H.Html aboutHtml contents = H.div ! A.id "aboutDiv" $ mdToHTML contents
arkon/courseography
hs/AboutResponse.hs
gpl-3.0
829
0
10
222
161
92
69
21
1
module Folsolver.Data.BinTree ( BinTree(..) , empty, leaf, (<#), (#>) , subtree, modRootValue ) where import Folsolver.TPTP import Text.PrettyPrint.HughesPJ as Pretty hiding (empty) import qualified Text.PrettyPrint.HughesPJ as Pretty (empty) import qualified Control.Arrow as Arrow (first) data BinTree v = BinNode {left :: BinTree v, value :: v, right :: BinTree v} | BinEmpty deriving (Eq) instance (Show v) => Show (BinTree v) where show BinEmpty = "^" show tree = "(" ++ (show $ left tree) ++ ") <# " ++ (show $ value tree) ++ " #> (" ++ (show $ right tree) ++ ")" instance (HasPretty v) => HasPretty (BinTree v) where pretty BinEmpty = Pretty.empty pretty tree = (pretty $ value tree) $$ Pretty.nest 2 ( (pretty $ left tree) $$ (pretty $ right tree) ) empty :: BinTree v empty = BinEmpty leaf :: v -> BinTree v leaf v = empty <# v #> empty -- | l <# v #> r creates a new binary tree -- | with l as the left child, v as the value an -- | r as the right child of the new tree (<#) :: BinTree v -> v -> (BinTree v -> BinTree v) (#>) :: (BinTree v -> BinTree v) -> BinTree v -> BinTree v infixl 9 <# infixr 2 #> left <# v = BinNode left v lefthalf #> right = lefthalf right instance Functor BinTree where fmap f BinEmpty = BinEmpty fmap f tree = (fmap f $ left tree) <# (f $ value tree) #> (fmap f $ right tree) -- | modifies the root value of a tree modRootValue :: (v -> v) -> BinTree v -> BinTree v modRootValue _ BinEmpty = BinEmpty modRootValue f t = left t <# f (value t) #> right t -- | subtree of a given path through the tree -- | each element on the path will be returned together with the -- | subtree where the path ends -- | when a False is find as a first element of a path the left subtree -- | will be chosen, otherwise (case True) the right subtree. subtree :: [Bool] -> BinTree v -> ([v], BinTree v) subtree _ BinEmpty = ([], BinEmpty) subtree [] t = ([], t) subtree (False:xs) t = Arrow.first (value t :) $ subtree xs (left t) subtree (True:xs) t = Arrow.first (value t :) $ subtree xs (right t)
traeger/fol-solver
Folsolver/Data/BinTree.hs
gpl-3.0
2,084
0
14
469
763
409
354
42
1
import Control.Monad as M import Control.Monad.IO.Class import Data.Char import Data.Conduit import Data.Conduit.List as CL import Data.List as L import Data.Text.Lazy as TL import Data.Text.Lazy.IO as TL import Data.Text.Lazy.Read as TL import Graphics.Rendering.Chart.Backend.Cairo import Graphics.Rendering.Chart.Easy import System.Environment import System.IO as IO data EnergyInfo = EnergyInfo !Int !Int !Double deriving (Show) {-# INLINE parseEnergyInfo #-} parseEnergyInfo :: Text -> EnergyInfo parseEnergyInfo txt = case (double . TL.dropWhile (not . isDigit) $ txt) of Left msg1 -> error msg1 Right (time, txt1) -> case (decimal . TL.dropWhile (not . isDigit) $ txt1) of Left msg2 -> error msg2 Right (batchNum, txt2) -> case (double . TL.dropWhile (not . isDigit) $ txt2) of Left msg3 -> error msg3 Right (e, txt2) -> EnergyInfo (round time) batchNum e energyFileSource :: FilePath -> Source IO EnergyInfo energyFileSource filePath = do h <- liftIO $ openFile filePath ReadMode x <- liftIO $ TL.hGetLine h xs <- liftIO $ TL.hGetContents h sourceList . L.map parseEnergyInfo . TL.lines $ xs liftIO $ hClose h sink :: Int -> Double -> Sink EnergyInfo IO [(Int,Double)] sink n m = do CL.drop n xs <- CL.consume return $! L.map (\(EnergyInfo t _ e) -> if e > m then (t, m) else (t, e)) xs takeOdd :: Int -> [a] -> [a] takeOdd 0 xs = xs takeOdd _ [] = [] takeOdd n xs = (L.take n xs) L.++ (takeOdd n . L.drop (2 * n) $ xs) takeEven :: Int -> [a] -> [a] takeEven 0 xs = xs takeEven _ [] = [] takeEven n xs = (L.drop n . L.take (2 * n) $ xs) L.++ (takeEven n . L.drop (2 * n) $ xs) main = do (folderPath:numBatchStr:numLastTakeStr:displayPeriodStr:thresholdStr:name:_) <- getArgs let -- str = "TopLayerEnergyProbe_batchElement_" str = name L.++ "EnergyProbe_batchElement_" fileNames = L.map (\i -> folderPath L.++ "/" L.++ str L.++ show i L.++ ".txt") [0 .. (read numBatchStr :: Int) - 1] print $ L.head fileNames numLines <- fmap (L.length . L.lines) . IO.readFile $ (L.head fileNames) print numLines xs <- M.mapM (\path -> energyFileSource path $$ sink (numLines - (read numLastTakeStr :: Int)) (read thresholdStr :: Double)) fileNames print . L.length . takeEven (read displayPeriodStr :: Int) . L.head $ xs toFile def (name L.++ "energy.png") $ do layout_title .= name L.++ "Energy" M.zipWithM_ -- (\i x -> plot (line (show i) [takeEven (read displayPeriodStr :: Int) x])) (\i x -> plot (line (show i) [x])) [0 ..] xs
XinhuaZhang/PetaVisionHaskell
Application/PVPAnalysis/PlotEnergy.hs
gpl-3.0
3,025
0
17
1,005
1,084
563
521
90
4
{-| Module : Multilinear.Tensor Description : Tensors constructors (finitely- or infinitely-dimensional) Copyright : (c) Artur M. Brodzki, 2018 License : BSD3 Maintainer : artur@brodzki.org Stability : experimental Portability : Windows/POSIX - This module provides convenient constructors that generate a arbitrary finitely- or infinitely-dimensional tensors. - Finitely-dimensional tensors provide much greater performance than inifitely-dimensional -} module Multilinear.Tensor ( -- * Generators Multilinear.Tensor.generate ) where import qualified Data.Vector as Boxed import qualified Data.Vector.Unboxed as Unboxed import Multilinear.Generic import Multilinear.Index.Finite as Finite invalidIndices :: (String, [Int]) -> (String, [Int]) -> String invalidIndices us ds = "Indices and its sizes incompatible, upper indices: " ++ show us ++", lower indices: " ++ show ds {-| Generate tensor composed of other tensors -} generate :: ( Num a, Unboxed.Unbox a ) => (String,[Int]) -- ^ Upper indices names (one character per index) and its sizes -> (String,[Int]) -- ^ Lower indices names (one character per index) and its sizes -> ([Int] -> [Int] -> Tensor a) -- ^ Generator function (f [u1,u2,...] [d1,d2,...] returns a tensor element at t [u1,u2,...] [d1,d2,...]) -> Tensor a -- ^ Generated tensor -- If no indices are given, generate a tensor by using generator function generate ([],[]) ([],[]) f = f [] [] -- If many indices are given, first generate upper indices recursively from indices list generate (u:us,s:size) d f = FiniteTensor (Contravariant s [u]) $ Boxed.generate s (\x -> generate (us,size) d (\uss dss -> f (x:uss) dss) ) -- After upper indices, generate lower indices recursively from indices list generate u (d:ds,s:size) f = FiniteTensor (Covariant s [d]) $ Boxed.generate s (\x -> generate u (ds,size) (\uss dss -> f uss (x:dss)) ) -- If there are indices without size or sizes without names, throw an error generate us ds _ = error $ invalidIndices us ds
ArturB/Multilinear
src/Multilinear/Tensor.hs
gpl-3.0
2,134
0
14
456
439
248
191
20
1
{-# LANGUAGE FlexibleContexts #-} module Solver.BooleanTransitionInvariant (checkBooleanTransitionInvariantSat ,checkBooleanTransitionInvariantWithSimpleCutSat) where import Data.SBV import Data.List import qualified Data.Map as M import qualified Data.Set as S import Util import PetriNet import Property import Solver import Solver.Simplifier tInvariantConstraints :: PetriNet -> SBMap Transition -> SBool tInvariantConstraints net x = bAnd $ map checkTransitionEquation $ places net where checkTransitionEquation p = let incoming = map (val x) $ pre net p \\ post net p outgoing = map (val x) $ post net p \\ pre net p in bOr outgoing ==> bOr incoming finalInvariantConstraints :: SBMap Transition -> SBool finalInvariantConstraints x = bOr $ vals x transitionVectorConstraints :: PetriNet -> SBMap Transition -> SBool transitionVectorConstraints net x = finalInvariantConstraints x &&& tInvariantConstraints net x formulaAndRefinementConstraints :: SimpleCut -> [Cut] -> SBMap Transition -> SBool formulaAndRefinementConstraints fcut cuts x = checkCuts cuts x &&& checkSimpleCut fcut x checkSimpleCut :: SimpleCut -> SBMap Transition -> SBool checkSimpleCut (t0, cs) x = checkNegative (S.toList t0) &&& bAnd (map (checkPositive . S.toList) cs) where checkNegative ts = bAnd (map (bnot . val x) ts) checkPositive ts = bOr (map (val x) ts) checkCuts :: [Cut] -> SBMap Transition -> SBool checkCuts cuts x = bAnd $ map checkCut cuts where checkCut (ts, u) = let cPre = map (bOr . map (val x) . snd) ts cPost = map (val x) u in bAnd cPre ==> bOr cPost checkBooleanTransitionInvariant :: PetriNet -> SimpleCut -> [Cut] -> SBMap Transition -> SBool checkBooleanTransitionInvariant net fcut cuts x = transitionVectorConstraints net x &&& formulaAndRefinementConstraints fcut cuts x checkBooleanTransitionInvariantSat :: PetriNet -> Formula Transition -> [Cut] -> ConstraintProblem Bool FiringVector checkBooleanTransitionInvariantSat net f cuts = let x = makeVarMap $ transitions net fcut = formulaToCut f in ("transition invariant constraints", "transition invariant", getNames x, \fm -> checkBooleanTransitionInvariant net fcut cuts (fmap fm x), \fm -> firingVectorFromAssignment (fmap fm x)) checkBooleanTransitionInvariantWithSimpleCut :: PetriNet -> SimpleCut -> SimpleCut -> SBMap Transition -> SBool checkBooleanTransitionInvariantWithSimpleCut net fcut cut x = transitionVectorConstraints net x &&& checkSimpleCut fcut x &&& checkSimpleCut cut x checkBooleanTransitionInvariantWithSimpleCutSat :: PetriNet -> Formula Transition -> SimpleCut -> ConstraintProblem Bool FiringVector checkBooleanTransitionInvariantWithSimpleCutSat net f cut = let x = makeVarMap $ transitions net fcut = formulaToCut f in ("transition invariant constraints with simple cut", "transition invariant", getNames x, \fm -> checkBooleanTransitionInvariantWithSimpleCut net fcut cut (fmap fm x), \fm -> firingVectorFromAssignment (fmap fm x)) firingVectorFromAssignment :: BMap Transition -> FiringVector firingVectorFromAssignment x = makeVector $ M.map (const 1) $ M.filter id x
cryptica/slapnet
src/Solver/BooleanTransitionInvariant.hs
gpl-3.0
3,496
0
17
845
946
473
473
72
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.DFAReporting.ChangeLogs.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves a list of change logs. This method supports paging. -- -- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.changeLogs.list@. module Network.Google.Resource.DFAReporting.ChangeLogs.List ( -- * REST Resource ChangeLogsListResource -- * Creating a Request , changeLogsList , ChangeLogsList -- * Request Lenses , cllUserProFileIds , cllObjectType , cllSearchString , cllIds , cllProFileId , cllAction , cllMinChangeTime , cllMaxChangeTime , cllPageToken , cllObjectIds , cllMaxResults ) where import Network.Google.DFAReporting.Types import Network.Google.Prelude -- | A resource alias for @dfareporting.changeLogs.list@ method which the -- 'ChangeLogsList' request conforms to. type ChangeLogsListResource = "dfareporting" :> "v2.7" :> "userprofiles" :> Capture "profileId" (Textual Int64) :> "changeLogs" :> QueryParams "userProfileIds" (Textual Int64) :> QueryParam "objectType" ChangeLogsListObjectType :> QueryParam "searchString" Text :> QueryParams "ids" (Textual Int64) :> QueryParam "action" ChangeLogsListAction :> QueryParam "minChangeTime" Text :> QueryParam "maxChangeTime" Text :> QueryParam "pageToken" Text :> QueryParams "objectIds" (Textual Int64) :> QueryParam "maxResults" (Textual Int32) :> QueryParam "alt" AltJSON :> Get '[JSON] ChangeLogsListResponse -- | Retrieves a list of change logs. This method supports paging. -- -- /See:/ 'changeLogsList' smart constructor. data ChangeLogsList = ChangeLogsList' { _cllUserProFileIds :: !(Maybe [Textual Int64]) , _cllObjectType :: !(Maybe ChangeLogsListObjectType) , _cllSearchString :: !(Maybe Text) , _cllIds :: !(Maybe [Textual Int64]) , _cllProFileId :: !(Textual Int64) , _cllAction :: !(Maybe ChangeLogsListAction) , _cllMinChangeTime :: !(Maybe Text) , _cllMaxChangeTime :: !(Maybe Text) , _cllPageToken :: !(Maybe Text) , _cllObjectIds :: !(Maybe [Textual Int64]) , _cllMaxResults :: !(Maybe (Textual Int32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ChangeLogsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cllUserProFileIds' -- -- * 'cllObjectType' -- -- * 'cllSearchString' -- -- * 'cllIds' -- -- * 'cllProFileId' -- -- * 'cllAction' -- -- * 'cllMinChangeTime' -- -- * 'cllMaxChangeTime' -- -- * 'cllPageToken' -- -- * 'cllObjectIds' -- -- * 'cllMaxResults' changeLogsList :: Int64 -- ^ 'cllProFileId' -> ChangeLogsList changeLogsList pCllProFileId_ = ChangeLogsList' { _cllUserProFileIds = Nothing , _cllObjectType = Nothing , _cllSearchString = Nothing , _cllIds = Nothing , _cllProFileId = _Coerce # pCllProFileId_ , _cllAction = Nothing , _cllMinChangeTime = Nothing , _cllMaxChangeTime = Nothing , _cllPageToken = Nothing , _cllObjectIds = Nothing , _cllMaxResults = Nothing } -- | Select only change logs with these user profile IDs. cllUserProFileIds :: Lens' ChangeLogsList [Int64] cllUserProFileIds = lens _cllUserProFileIds (\ s a -> s{_cllUserProFileIds = a}) . _Default . _Coerce -- | Select only change logs with the specified object type. cllObjectType :: Lens' ChangeLogsList (Maybe ChangeLogsListObjectType) cllObjectType = lens _cllObjectType (\ s a -> s{_cllObjectType = a}) -- | Select only change logs whose object ID, user name, old or new values -- match the search string. cllSearchString :: Lens' ChangeLogsList (Maybe Text) cllSearchString = lens _cllSearchString (\ s a -> s{_cllSearchString = a}) -- | Select only change logs with these IDs. cllIds :: Lens' ChangeLogsList [Int64] cllIds = lens _cllIds (\ s a -> s{_cllIds = a}) . _Default . _Coerce -- | User profile ID associated with this request. cllProFileId :: Lens' ChangeLogsList Int64 cllProFileId = lens _cllProFileId (\ s a -> s{_cllProFileId = a}) . _Coerce -- | Select only change logs with the specified action. cllAction :: Lens' ChangeLogsList (Maybe ChangeLogsListAction) cllAction = lens _cllAction (\ s a -> s{_cllAction = a}) -- | Select only change logs whose change time is before the specified -- minChangeTime.The time should be formatted as an RFC3339 date\/time -- string. For example, for 10:54 PM on July 18th, 2015, in the -- America\/New York time zone, the format is -- \"2015-07-18T22:54:00-04:00\". In other words, the year, month, day, the -- letter T, the hour (24-hour clock system), minute, second, and then the -- time zone offset. cllMinChangeTime :: Lens' ChangeLogsList (Maybe Text) cllMinChangeTime = lens _cllMinChangeTime (\ s a -> s{_cllMinChangeTime = a}) -- | Select only change logs whose change time is before the specified -- maxChangeTime.The time should be formatted as an RFC3339 date\/time -- string. For example, for 10:54 PM on July 18th, 2015, in the -- America\/New York time zone, the format is -- \"2015-07-18T22:54:00-04:00\". In other words, the year, month, day, the -- letter T, the hour (24-hour clock system), minute, second, and then the -- time zone offset. cllMaxChangeTime :: Lens' ChangeLogsList (Maybe Text) cllMaxChangeTime = lens _cllMaxChangeTime (\ s a -> s{_cllMaxChangeTime = a}) -- | Value of the nextPageToken from the previous result page. cllPageToken :: Lens' ChangeLogsList (Maybe Text) cllPageToken = lens _cllPageToken (\ s a -> s{_cllPageToken = a}) -- | Select only change logs with these object IDs. cllObjectIds :: Lens' ChangeLogsList [Int64] cllObjectIds = lens _cllObjectIds (\ s a -> s{_cllObjectIds = a}) . _Default . _Coerce -- | Maximum number of results to return. cllMaxResults :: Lens' ChangeLogsList (Maybe Int32) cllMaxResults = lens _cllMaxResults (\ s a -> s{_cllMaxResults = a}) . mapping _Coerce instance GoogleRequest ChangeLogsList where type Rs ChangeLogsList = ChangeLogsListResponse type Scopes ChangeLogsList = '["https://www.googleapis.com/auth/dfatrafficking"] requestClient ChangeLogsList'{..} = go _cllProFileId (_cllUserProFileIds ^. _Default) _cllObjectType _cllSearchString (_cllIds ^. _Default) _cllAction _cllMinChangeTime _cllMaxChangeTime _cllPageToken (_cllObjectIds ^. _Default) _cllMaxResults (Just AltJSON) dFAReportingService where go = buildClient (Proxy :: Proxy ChangeLogsListResource) mempty
rueshyna/gogol
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/ChangeLogs/List.hs
mpl-2.0
7,940
0
23
1,978
1,230
707
523
165
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Content.ShippingSettings.Custombatch -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves and updates the shipping settings of multiple accounts in a -- single request. -- -- /See:/ <https://developers.google.com/shopping-content/v2/ Content API for Shopping Reference> for @content.shippingsettings.custombatch@. module Network.Google.Resource.Content.ShippingSettings.Custombatch ( -- * REST Resource ShippingSettingsCustombatchResource -- * Creating a Request , shippingSettingsCustombatch , ShippingSettingsCustombatch -- * Request Lenses , sscXgafv , sscUploadProtocol , sscAccessToken , sscUploadType , sscPayload , sscCallback ) where import Network.Google.Prelude import Network.Google.ShoppingContent.Types -- | A resource alias for @content.shippingsettings.custombatch@ method which the -- 'ShippingSettingsCustombatch' request conforms to. type ShippingSettingsCustombatchResource = "content" :> "v2.1" :> "shippingsettings" :> "batch" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] ShippingSettingsCustomBatchRequest :> Post '[JSON] ShippingSettingsCustomBatchResponse -- | Retrieves and updates the shipping settings of multiple accounts in a -- single request. -- -- /See:/ 'shippingSettingsCustombatch' smart constructor. data ShippingSettingsCustombatch = ShippingSettingsCustombatch' { _sscXgafv :: !(Maybe Xgafv) , _sscUploadProtocol :: !(Maybe Text) , _sscAccessToken :: !(Maybe Text) , _sscUploadType :: !(Maybe Text) , _sscPayload :: !ShippingSettingsCustomBatchRequest , _sscCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ShippingSettingsCustombatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sscXgafv' -- -- * 'sscUploadProtocol' -- -- * 'sscAccessToken' -- -- * 'sscUploadType' -- -- * 'sscPayload' -- -- * 'sscCallback' shippingSettingsCustombatch :: ShippingSettingsCustomBatchRequest -- ^ 'sscPayload' -> ShippingSettingsCustombatch shippingSettingsCustombatch pSscPayload_ = ShippingSettingsCustombatch' { _sscXgafv = Nothing , _sscUploadProtocol = Nothing , _sscAccessToken = Nothing , _sscUploadType = Nothing , _sscPayload = pSscPayload_ , _sscCallback = Nothing } -- | V1 error format. sscXgafv :: Lens' ShippingSettingsCustombatch (Maybe Xgafv) sscXgafv = lens _sscXgafv (\ s a -> s{_sscXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). sscUploadProtocol :: Lens' ShippingSettingsCustombatch (Maybe Text) sscUploadProtocol = lens _sscUploadProtocol (\ s a -> s{_sscUploadProtocol = a}) -- | OAuth access token. sscAccessToken :: Lens' ShippingSettingsCustombatch (Maybe Text) sscAccessToken = lens _sscAccessToken (\ s a -> s{_sscAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). sscUploadType :: Lens' ShippingSettingsCustombatch (Maybe Text) sscUploadType = lens _sscUploadType (\ s a -> s{_sscUploadType = a}) -- | Multipart request metadata. sscPayload :: Lens' ShippingSettingsCustombatch ShippingSettingsCustomBatchRequest sscPayload = lens _sscPayload (\ s a -> s{_sscPayload = a}) -- | JSONP sscCallback :: Lens' ShippingSettingsCustombatch (Maybe Text) sscCallback = lens _sscCallback (\ s a -> s{_sscCallback = a}) instance GoogleRequest ShippingSettingsCustombatch where type Rs ShippingSettingsCustombatch = ShippingSettingsCustomBatchResponse type Scopes ShippingSettingsCustombatch = '["https://www.googleapis.com/auth/content"] requestClient ShippingSettingsCustombatch'{..} = go _sscXgafv _sscUploadProtocol _sscAccessToken _sscUploadType _sscCallback (Just AltJSON) _sscPayload shoppingContentService where go = buildClient (Proxy :: Proxy ShippingSettingsCustombatchResource) mempty
brendanhay/gogol
gogol-shopping-content/gen/Network/Google/Resource/Content/ShippingSettings/Custombatch.hs
mpl-2.0
5,183
0
18
1,164
713
416
297
106
1
-- This file is part of purebred -- Copyright (C) 2017-2019 Róman Joost and Fraser Tweedale -- -- purebred is free software: you can redistribute it and/or modify -- it under the terms of the GNU Affero General Public License as published by -- the Free Software Foundation, either version 3 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 Affero General Public License for more details. -- -- You should have received a copy of the GNU Affero General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. {-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE OverloadedStrings #-} module TestMail where import qualified Data.ByteString as B import qualified Data.Text.Encoding as T import Control.Lens (view) import Data.Time.Clock (UTCTime(..), secondsToDiffTime) import Data.Time.Calendar (fromGregorian) import Control.Monad (replicateM) import Test.Tasty.HUnit ((@=?), testCase) import Test.Tasty (TestTree, testGroup) import Test.Tasty.QuickCheck (testProperty, Arbitrary, arbitrary, choose) import Test.QuickCheck.Instances () import Notmuch (mkTag, tagMaxLen) import Purebred.Types import Purebred.Storage.Notmuch (addTags, removeTags, tagItem) import Purebred.Storage.Mail (findMatchingWords) import Purebred.Storage.Tags (TagOp(..)) mailTests :: TestTree mailTests = testGroup "mail parsing tests" [ testAddingTags , testRemovingTags , testTagOpsWithReset , testFindsMatchingWords ] testAddingTags :: TestTree testAddingTags = testProperty "no duplicates when adding tags" propNoDuplicatesAdded where propNoDuplicatesAdded :: NotmuchMail -> [Tag] -> Bool propNoDuplicatesAdded m as = addTags as (addTags as m) == addTags as m testRemovingTags :: TestTree testRemovingTags = testProperty "remove tags" propRemoveTags where propRemoveTags :: NotmuchMail -> [Tag] -> Bool propRemoveTags m as = removeTags as (removeTags as m) == removeTags as m testTagOpsWithReset :: TestTree testTagOpsWithReset = testCase "tag ops with reset" $ ["archive"] @=? view mailTags actual where m = NotmuchMail "subject" "from" time ["foo", "bar"] "asdf" time = UTCTime (fromGregorian 2018 1 15) (secondsToDiffTime 123) actual = tagItem [ResetTags, AddTag "archive"] m instance Arbitrary Tag where arbitrary = do n <- choose (1, tagMaxLen) bs <- fmap B.pack . replicateM n $ choose (0x21, 0x7e) maybe arbitrary{-try again-} pure (mkTag bs) instance Arbitrary NotmuchMail where arbitrary = NotmuchMail <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> (T.encodeUtf8 <$> arbitrary) testFindsMatchingWords :: TestTree testFindsMatchingWords = testCase "finds matching words" $ expected @=? actual where expected = MailBody mempty [Paragraph [Line [Match 9 3 1] 1 "Purebred finds matching words"]] actual = findMatchingWords "fin" $ MailBody mempty [Paragraph [Line [] 1 "Purebred finds matching words"]]
purebred-mua/purebred
test/TestMail.hs
agpl-3.0
3,229
0
13
597
673
380
293
62
1
{-# LANGUAGE RankNTypes, ImpredicativeTypes, OverloadedStrings #-} module Network.IRC.Cast.Main where import Data.Monoid import Data.String import Control.Concurrent (forkIO) import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TVar import Network.IRC.Pipes import Network.Simple.TCP import Pipes import Pipes.Network.TCP (fromSocket, toSocket) import qualified Pipes.Concurrent as PC import Pipes.FastCGI import Network.FastCGI (FastCGI, acceptLoop) intro :: [IRCMsg] intro = [ IRCMsg { msgPrefix = Nothing, msgCmd = "NICK", msgParams = ["ircast"], msgTrail = "" } , IRCMsg { msgPrefix = Nothing, msgCmd = "USER", msgParams = ["ircast", "0", "*"], msgTrail = "ircast" } ] main :: IO () main = do sseOutput <- newTVarIO mempty let broadcast x = atomically (readTVar sseOutput >>= flip PC.send x) >> return () _ <- forkIO $ do acceptLoop forkIO (runEffect $ handler sseOutput) withIRCPipes $ \output input -> do _ <- forkIO $ runEffect (each intro >-> output) runEffect $ for input (liftIO . broadcast) handler :: TVar (PC.Output IRCMsg) -> Effect FastCGI () handler output = do (newOutput, newInput) <- liftIO $ PC.spawn PC.Unbounded liftIO $ atomically $ modifyTVar output (<> newOutput) PC.fromInput newInput >-> ircMsgToSse >-> streamEvents ircMsgToSse :: Monad m => Pipe IRCMsg ServerSentEvent m r ircMsgToSse = for cat (yield . event) where event x = serverSentEvent { eventData = Just (fromString $ show x) } type IRCOutput = Consumer' IRCMsg IO () type IRCInput = Producer' IRCMsg IO () withIRCPipes :: (IRCOutput -> IRCInput -> IO ()) -> IO () withIRCPipes f = connect "irc.freenode.net" "6667" $ \(socket, _) -> do let producer = parseIrcMsgs (fromSocket socket 4096) consumer = writingIrcMsgs >-> toSocket socket f consumer (fmap (const ()) producer)
mbrock/ircast
lib/Network/IRC/Cast/Main.hs
agpl-3.0
1,922
0
16
401
645
344
301
52
1
module Betty.Pid ( writePidFile ) where ------------------------------------------------------------------------ -- -- Write process ID somewhere in the filesystem so that monitoring -- apps can monitor. If "/opt/keter/var" is writable or can be -- created, write betty.pid there; do not write anything otherwise. -- -- TODO: Ignoring failures silently is not a good idea! Fix. -- ------------------------------------------------------------------------ import ClassyPrelude.Yesod import System.Directory (createDirectoryIfMissing) import System.IO (IOMode (WriteMode), hPrint, withFile) import System.Posix.Process (getProcessID) ------------------------------------------------------------------------ writePidFile :: IO () writePidFile = do let pidDir = "/opt/keter/var" pidFile = pidDir </> "betty.pid" catchAny (do createDirectoryIfMissing True pidDir pid <- getProcessID withFile pidFile WriteMode $ \h -> hPrint h pid) (const $ return ()) ------------------------------------------------------------------------
sajith/betty-web
Betty/Pid.hs
agpl-3.0
1,102
0
13
190
161
91
70
13
1
{-# LANGUAGE MultiWayIf #-} {-# LANGUAGE OverloadedStrings #-} module Main where import Control.Monad import Data.List import System.Directory import System.FilePath import Util getAllUserDirs :: BuildMode -> IO [FilePath] getAllUserDirs bm = listDirectoryWithPrefix $ projectRootDir bm -- Project directories have no 3-letters prefix dirs inside. isProjectStructureCorrect :: FilePath -> IO Bool isProjectStructureCorrect path = do contents <- listDirectory path parts <- forM contents $ \f -> do isDir <- doesDirectoryExist (path </> f) if | isDir && length f == 3 && "D" `isPrefixOf` f -> return False | isDir -> isProjectStructureCorrect (path </> f) | otherwise -> return True return (and parts) move :: FilePath -> FilePath -> IO () move src dest = do isDir <- doesDirectoryExist src case isDir of True -> renameDirectory src dest False -> renameFile src dest migrateProjectStructure :: FilePath -> IO () migrateProjectStructure path = do isDir <- doesDirectoryExist path children <- if isDir then listDirectory path else return [] let parent = takeDirectory path sources = map (path </>) children destinations = map (parent </>) children case isDir of True -> case length (takeFileName path) == 3 of True -> do mapM_ migrateProjectStructure sources mapM_ (\(s, d) -> move s d) $ zip sources destinations removeDirectory path False -> do mapM_ migrateProjectStructure sources False -> return () migrateMode :: BuildMode -> IO () migrateMode bm = do userDirs <- getAllUserDirs bm mapM_ migrateProjectStructure userDirs main :: IO () main = do putStrLn "Running migration of codeworld-server project structure." alreadyDone <- (&&) <$> isProjectStructureCorrect (projectRootDir (BuildMode "codeworld")) <*> isProjectStructureCorrect (projectRootDir (BuildMode "haskell")) if alreadyDone then putStrLn "Migration already done." else do error "Migration should be done" migrateMode (BuildMode "haskell") migrateMode (BuildMode "codeworld") migrateMode (BuildMode "blocklyXML") putStrLn "Successfully migrated."
google/codeworld
codeworld-server/src/Migration.hs
apache-2.0
2,207
0
20
477
646
307
339
61
4
module Dis8.Disassemble where import Common.Core import Common.Instr import Control.Applicative import Data.Bits import Data.List import Data.Maybe -- | Pretty-print a list of instructions starting at 0x200 showProg :: Program -> String showProg p = showProg' 0x200 (genLabels $ parseInstrs p) p where maxAddr = 0x199 + fromIntegral (length p) lbls = pruneLabels 0x200 maxAddr $ genLabels $ parseInstrs p -- | An address label type Label = (Addr,String) -- | Pretty-print a list of instructions given an address, labels, and -- indentation. showProg' :: Addr -> [Label] -> Program -> String showProg' a _ [] = "" showProg' a lbls (b:[]) = showByte b ++ "\n" showProg' a lbls (b1:b2:bs) = lstr ++ istr ++ showProg' a' lbls bs where a' = a + 2 op = makeOp b1 b2 instr = parseOp op istr = either (const bytes) showi instr -- If there is an invalid -- opcode, then bytes = " " ++ showByte b1 ++ "\n " ++ showByte b2 ++ "\n" lstr = case lookup a lbls of -- If the current address is labeled, then -- give the label's name. Just n -> n ++ ":\n" Nothing -> "" showi i = " " ++ showInstr lbls i ++ "\n" -- | Tell if an instruction is a skip instruction. isSkip :: Instr -> Bool isSkip (SeC _ _) = True isSkip (SneC _ _) = True isSkip (SeV _ _) = True isSkip (SneV _ _) = True isSkip (Skp _ ) = True isSkip (Sknp _ ) = True isSkip _ = False -- | Remove labels with addresses outside of the given range. pruneLabels :: Addr -> Addr -> [Label] -> [Label] pruneLabels min max ls = filter ff ls where ff (a,_) = a >= min && a <= max -- | Generate labels from a list of instructions. genLabels :: [Instr] -> [Label] genLabels is = ls where as = nub $ map fromJust $ filter isJust $ map instrAddr is ls = zip (sort as) ["L" ++ show x | x <- [0..]] mkl i a = (a,"L" ++ show i) -- | Get an instruction's address if it has one. instrAddr :: Instr -> Maybe Addr instrAddr (Sys a) = Just a instrAddr (Jp a) = Just a instrAddr (Call a) = Just a instrAddr (LdI a) = Just a instrAddr (JpV0 a) = Just a instrAddr _ = Nothing -- | Convert a list of bytes to instructions, ignoring invalid opcodes. parseInstrs :: Program -> [Instr] parseInstrs [] = [] parseInstrs (p:[]) = [] parseInstrs (p:p':ps) = either (const next) (:next) $ parseOp op where op = makeOp p p' next = parseInstrs ps -- | Pretty-print an instruction. showInstr :: [Label] -> Instr -> String showInstr lbls i = case i of Cls -> "clr" Ret -> "ret" Sys a -> case lookup a lbls of Just l -> "sys " ++ l Nothing -> "sys " ++ show a Jp a -> case lookup a lbls of Just l -> "jump " ++ l Nothing -> "jump " ++ show a Call a -> case lookup a lbls of Just l -> "call " ++ l Nothing -> "call " ++ show a SeC x c -> "skipeq " ++ showReg x ++ " " ++ show c SneC x c -> "skipneq " ++ showReg x ++ " " ++ show c SeV x y -> "skipeq " ++ showReg x ++ " " ++ showReg y LdC x c -> "load " ++ showReg x ++ " " ++ show c AddC x c -> "add " ++ showReg x ++ " " ++ show c LdV x y -> "load " ++ showReg x ++ " " ++ showReg y Or x y -> "or " ++ showReg x ++ " " ++ showReg y And x y -> "and " ++ showReg x ++ " " ++ showReg y Xor x y -> "xor " ++ showReg x ++ " " ++ showReg y AddV x y -> "add " ++ showReg x ++ " " ++ showReg y Sub x y -> "sub " ++ showReg x ++ " " ++ showReg y Shr x -> "shr " ++ showReg x Subn x y -> "subn " ++ showReg x ++ " " ++ showReg y Shl x -> "shl " ++ showReg x SneV x y -> "skipneq " ++ showReg x ++ " " ++ showReg y LdI a -> case lookup a lbls of Just l -> "load I " ++ l Nothing -> "load I " ++ show a JpV0 a -> case lookup a lbls of Just l -> "jpv0 " ++ l Nothing -> "jpv0 " ++ show a Rnd x c -> "rnd " ++ showReg x ++ " " ++ show c Drw x y h->"drw " ++ showReg x ++ " " ++ showReg y ++ " " ++ show h Skp x -> "skipkey " ++ showReg x Sknp x -> "skipnkey " ++ showReg x LdDT x -> "load " ++ showReg x ++ " " ++ "DT" LdK x -> "key " ++ showReg x SetDT x -> "load DT " ++ showReg x SetST x -> "load ST " ++ showReg x AddI x -> "add I " ++ showReg x LdF x -> "char " ++ showReg x WrtB x -> "bcd " ++ showReg x WrtV x -> "push " ++ showReg x RdV x -> "read " ++ showReg x -- | Print out a byte pseudo-instruction. showByte :: Byte -> String showByte = ("byte " ++) . show -- | Print out a register name. showReg :: Vx -> String showReg x = 'V' : c : "" where c = case x of 0x0 -> '0' 0x1 -> '1' 0x2 -> '2' 0x3 -> '3' 0x4 -> '4' 0x5 -> '5' 0x6 -> '6' 0x7 -> '7' 0x8 -> '8' 0x9 -> '9' 0xa -> 'A' 0xb -> 'B' 0xc -> 'C' 0xd -> 'D' 0xe -> 'E' 0xf -> 'F'
jepugs/emul8
src/Dis8/Disassemble.hs
apache-2.0
5,031
0
13
1,653
1,946
948
998
122
40
module Model where import Prelude import Yesod import Data.Text (Text) import Database.Persist.Quasi import OAuthToken share [mkPersist sqlSettings, mkMigrate "migrateAll"] $(persistFileWith lowerCaseSettings "config/models")
JanAhrens/yesod-oauth-demo
Model.hs
bsd-2-clause
232
0
8
28
58
32
26
-1
-1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} module Main (main) where import Bucketeer.Persistence (storeBucketManager, restoreBuckets) import Bucketeer.Timers (startBucketManager) import Bucketeer.WebServer (BucketeerWeb(..), bucketeerServer) import Control.Applicative ((<$>), (<*>), pure) import Control.Exception (finally) import Data.ByteString.Char8 (pack) import Data.IORef (newIORef, readIORef) import Data.Maybe (catMaybes, fromMaybe) import Database.Redis (connect, runRedis, PortID(PortNumber), ConnectInfo(..)) import Filesystem.Path.CurrentOS (encodeString) import Network.Wai (Middleware) import Network.Wai.Handler.Warp (run) import Network.Wai.Middleware.RequestLogger (logCallback) import Options import System.Posix.Env (getEnvDefault) import System.Exit (exitFailure) import System.Log.FastLogger (initHandle, LogStr(LB), hPutLogStr) import System.IO (hPutStrLn, Handle, withFile, IOMode(AppendMode), stdout, stderr) import Web.Scotty defineOptions "WebServerOptions" $ do option "port" (\o -> o { optionLongFlags = ["port"], optionShortFlags = "p", optionDescription = "Port. Default 3000, can also be set with PORT env var (for keter deployment)", optionType = optionTypeMaybe optionTypeInt }) option "namespaceOpt" (\o -> o { optionLongFlags = ["namespcae"], optionShortFlags = "n", optionDescription = "Optional redis namespace so multiple bucketeers can run on the same Redis instance", optionType = optionTypeMaybe optionTypeString }) option "redisHost" (\o -> o { optionLongFlags = ["redis-host"], optionDescription = "Redis host. Default localhost", optionDefault = "localhost" }) option "redisPort" (\o -> o { optionLongFlags = ["redis-port"], optionDescription = "Redis port. Default 6379", optionDefault = "6379", optionType = optionTypeWord16 }) option "redisPassword" (\o -> o { optionLongFlags = ["redis-password"], optionDescription = "Redis password. Default no password.", optionType = optionTypeMaybe optionTypeString }) option "redisMaxConnections" (\o -> o { optionLongFlags = ["redis-max-connections"], optionDescription = "Redis max connections. Default 50.", optionType = optionTypeInt, optionDefault = "50" }) option "redisMaxIdle" (\o -> o { optionLongFlags = ["redis-max-idle"], optionDescription = "Redis max idle time in seconds. Default 30.", optionType = optionTypeInt, optionDefault = "30" }) option "logFile" (\o -> o { optionLongFlags = ["log-file"], optionShortFlags = "l", optionDescription = "Log file. Defaults to only logging to stdout.", optionType = optionTypeMaybe optionTypeFilePath }) main :: IO () main = runCommand $ \opts _ -> runServer opts ---- Helpers runServer :: WebServerOptions -> IO () runServer WebServerOptions { port = sPort, namespaceOpt = ns, redisHost = rHost, redisPort = rPort, redisPassword = rPass, redisMaxConnections = rMaxConn, redisMaxIdle = rMaxIdle, logFile = lFile } = do conn <- connect connectInfo buckets <- either exit (return . id) =<< runRedis conn (restoreBuckets ns') bmRef <- newIORef =<< startBucketManager buckets ns' conn let foundation = BucketeerWeb conn bmRef ns' app <- scottyApp $ bucketeerServer foundation sPort' <- fromMaybe <$> getPortFromEnv <*> pure sPort maybeWithHandle lFile' $ \mHandle -> do putStrLn $ "Server listening on port " ++ show sPort' runApp app mHandle sPort' `finally` cleanup foundation where connectInfo = ConnInfo { connectHost = rHost, connectPort = rPort', connectAuth = rPass', connectMaxConnections = rMaxConn, connectMaxIdleTime = rMaxIdle' } ns' = pack <$> ns rPass' = pack <$> rPass rPort' = PortNumber $ fromIntegral rPort rMaxIdle' = fromIntegral rMaxIdle lFile' = encodeString <$> lFile runApp app mHandle sPort' = run sPort' $ logWare mHandle app exit str = hPutStrLn stderr str >> exitFailure getPortFromEnv = read `fmap` getEnvDefault "PORT" "3000" maybeWithHandle :: Maybe FilePath -> (Maybe Handle -> IO a) -> IO a maybeWithHandle (Just fp) action = withFile fp AppendMode $ action . Just maybeWithHandle Nothing action = action Nothing logWare :: Maybe Handle -> Middleware logWare fileHandle = logCallback writeLogs where handles = catMaybes [fileHandle, Just stdout] writeLogs bs = mapM_ initHandle handles >> mapM_ (putLog bs) handles putLog bs h = hPutLogStr h [LB bs] cleanup :: BucketeerWeb -> IO () cleanup BucketeerWeb { connection = conn, bucketManager = bmRef, namespace = ns } = do bm <- readIORef bmRef runRedis conn $ storeBucketManager ns bm
MichaelXavier/Bucketeer
Bucketeer/WebServer/Main.hs
bsd-2-clause
6,488
0
13
2,640
1,276
712
564
119
1
-- | Utility functions to generate Primitives module CLaSH.Primitives.Util where import Data.Aeson (FromJSON, Result (..), fromJSON, json) import qualified Data.Attoparsec.Lazy as L import Data.ByteString.Lazy (ByteString) import qualified Data.ByteString.Lazy as LZ import qualified Data.HashMap.Lazy as HashMap import Data.List (isSuffixOf) import Data.Maybe (fromMaybe) import qualified System.Directory as Directory import qualified System.FilePath as FilePath import CLaSH.Primitives.Types import CLaSH.Util -- | Generate a set of primitives that are found in the primitive definition -- files in the given directories. generatePrimMap :: [FilePath] -- ^ Directories to search for primitive definitions -> IO PrimMap generatePrimMap filePaths = do primitiveFiles <- fmap concat $ mapM (\filePath -> fmap ( map (FilePath.combine filePath) . filter (isSuffixOf ".json") ) (Directory.getDirectoryContents filePath) ) filePaths primitives <- fmap concat $ mapM ( return . fromMaybe [] . decodeAndReport <=< LZ.readFile ) primitiveFiles let primMap = HashMap.fromList $ zip (map name primitives) primitives return primMap -- | Parse a ByteString according to the given JSON template. Prints failures -- on @stdout@, and returns 'Nothing' if parsing fails. decodeAndReport :: (FromJSON a) => ByteString -- ^ Bytestring to parse -> Maybe a decodeAndReport s = case L.parse json s of L.Done _ v -> case fromJSON v of Success a -> Just a Error msg -> traceIf True msg Nothing L.Fail _ _ msg -> traceIf True msg Nothing
christiaanb/clash-compiler
clash-lib/src/CLaSH/Primitives/Util.hs
bsd-2-clause
1,971
0
18
673
397
215
182
-1
-1
---------------------------------------------------------------------------- -- | -- Module : Language.Core.Interpreter.Libraries.GHC.Real -- Copyright : (c) Carlos López-Camey, University of Freiburg -- License : BSD-3 -- -- Maintainer : c.lopez@kmels.net -- Stability : stable -- -- -- Defines functions defined in GHC.real ----------------------------------------------------------------------------- module Language.Core.Interpreter.Libraries.GHC.Real(all) where import DART.CmdLine import Language.Core.Core import Language.Core.Interpreter(evalId) import Language.Core.Interpreter.Apply import Language.Core.Interpreter.Libraries.Monomophy(monomophy_2,mkMonomophier) import Language.Core.Interpreter.Structures import Prelude hiding (all) all :: [(Id, Either Thunk Value)] all = [ mod' , mkMonomophier "base:GHC.Real.$fIntegralInt" , mkMonomophier "base:GHC.Real.$p1Integral" , mkMonomophier "base:GHC.Real.$p1Real" , mkMonomophier "base:GHC.Real.$p2Real" ] -- | The polymorphic modulo function -- mod :: Integral a => a -> a -> a mod' :: (Id, Either Thunk Value) mod' = (id, Right $ Fun (monomophy_2 "mod" modulo) "polymorphic(mod)") where id = "base:GHC.Real.mod" modulo :: Value -> Value -> IM Value modulo (Num x) (Num y) = return . Num $ x `mod` y modulo x y = return . Wrong $ "Cannot calculate modulo between " ++ show x ++ " and " ++ show y
kmels/dart-haskell
src/Language/Core/Interpreter/Libraries/GHC/Real.hs
bsd-3-clause
1,436
0
11
241
280
166
114
20
2
{-# LANGUAGE GADTs, NoMonoLocalBinds #-} -- Norman likes local bindings -- If this module lives on I'd like to get rid of the NoMonoLocalBinds -- extension in due course -- Todo: remove -fno-warn-warnings-deprecations {-# OPTIONS_GHC -fno-warn-warnings-deprecations #-} module CmmBuildInfoTables ( CAFSet, CAFEnv, cafAnal , doSRTs, TopSRT, emptySRT, isEmptySRT, srtToData ) where #include "HsVersions.h" import Hoopl import Digraph import BlockId import Bitmap import CLabel import PprCmmDecl () import Cmm import CmmUtils import CmmInfo import Data.List import DynFlags import Maybes import Outputable import SMRep import UniqSupply import Util import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import Control.Monad import qualified Prelude as P import Prelude hiding (succ) foldSet :: (a -> b -> b) -> b -> Set a -> b foldSet = Set.foldr ----------------------------------------------------------------------- -- SRTs {- EXAMPLE f = \x. ... g ... where g = \y. ... h ... c1 ... h = \z. ... c2 ... c1 & c2 are CAFs g and h are local functions, but they have no static closures. When we generate code for f, we start with a CmmGroup of four CmmDecls: [ f_closure, f_entry, g_entry, h_entry ] we process each CmmDecl separately in cpsTop, giving us a list of CmmDecls. e.g. for f_entry, we might end up with [ f_entry, f1_ret, f2_proc ] where f1_ret is a return point, and f2_proc is a proc-point. We have a CAFSet for each of these CmmDecls, let's suppose they are [ f_entry{g_closure}, f1_ret{g_closure}, f2_proc{} ] [ g_entry{h_closure, c1_closure} ] [ h_entry{c2_closure} ] Now, note that we cannot use g_closure and h_closure in an SRT, because there are no static closures corresponding to these functions. So we have to flatten out the structure, replacing g_closure and h_closure with their contents: [ f_entry{c2_closure, c1_closure}, f1_ret{c2_closure,c1_closure}, f2_proc{} ] [ g_entry{c2_closure, c1_closure} ] [ h_entry{c2_closure} ] This is what flattenCAFSets is doing. -} ----------------------------------------------------------------------- -- Finding the CAFs used by a procedure type CAFSet = Set CLabel type CAFEnv = BlockEnv CAFSet -- First, an analysis to find live CAFs. cafLattice :: DataflowLattice CAFSet cafLattice = DataflowLattice "live cafs" Set.empty add where add _ (OldFact old) (NewFact new) = case old `Set.union` new of new' -> (changeIf $ Set.size new' > Set.size old, new') cafTransfers :: BwdTransfer CmmNode CAFSet cafTransfers = mkBTransfer3 first middle last where first _ live = live middle m live = foldExpDeep addCaf m live last l live = foldExpDeep addCaf l (joinOutFacts cafLattice l live) addCaf e set = case e of CmmLit (CmmLabel c) -> add c set CmmLit (CmmLabelOff c _) -> add c set CmmLit (CmmLabelDiffOff c1 c2 _) -> add c1 $ add c2 set _ -> set add l s = if hasCAF l then Set.insert (toClosureLbl l) s else s cafAnal :: CmmGraph -> CAFEnv cafAnal g = dataflowAnalBwd g [] $ analBwd cafLattice cafTransfers ----------------------------------------------------------------------- -- Building the SRTs -- Description of the SRT for a given module. -- Note that this SRT may grow as we greedily add new CAFs to it. data TopSRT = TopSRT { lbl :: CLabel , next_elt :: Int -- the next entry in the table , rev_elts :: [CLabel] , elt_map :: Map CLabel Int } -- map: CLabel -> its last entry in the table instance Outputable TopSRT where ppr (TopSRT lbl next elts eltmap) = text "TopSRT:" <+> ppr lbl <+> ppr next <+> ppr elts <+> ppr eltmap emptySRT :: MonadUnique m => m TopSRT emptySRT = do top_lbl <- getUniqueM >>= \ u -> return $ mkTopSRTLabel u return TopSRT { lbl = top_lbl, next_elt = 0, rev_elts = [], elt_map = Map.empty } isEmptySRT :: TopSRT -> Bool isEmptySRT srt = null (rev_elts srt) cafMember :: TopSRT -> CLabel -> Bool cafMember srt lbl = Map.member lbl (elt_map srt) cafOffset :: TopSRT -> CLabel -> Maybe Int cafOffset srt lbl = Map.lookup lbl (elt_map srt) addCAF :: CLabel -> TopSRT -> TopSRT addCAF caf srt = srt { next_elt = last + 1 , rev_elts = caf : rev_elts srt , elt_map = Map.insert caf last (elt_map srt) } where last = next_elt srt srtToData :: TopSRT -> CmmGroup srtToData srt = [CmmData RelocatableReadOnlyData (Statics (lbl srt) tbl)] where tbl = map (CmmStaticLit . CmmLabel) (reverse (rev_elts srt)) -- Once we have found the CAFs, we need to do two things: -- 1. Build a table of all the CAFs used in the procedure. -- 2. Compute the C_SRT describing the subset of CAFs live at each procpoint. -- -- When building the local view of the SRT, we first make sure that all the CAFs are -- in the SRT. Then, if the number of CAFs is small enough to fit in a bitmap, -- we make sure they're all close enough to the bottom of the table that the -- bitmap will be able to cover all of them. buildSRT :: DynFlags -> TopSRT -> CAFSet -> UniqSM (TopSRT, Maybe CmmDecl, C_SRT) buildSRT dflags topSRT cafs = do let -- For each label referring to a function f without a static closure, -- replace it with the CAFs that are reachable from f. sub_srt topSRT localCafs = let cafs = Set.elems localCafs mkSRT topSRT = do localSRTs <- procpointSRT dflags (lbl topSRT) (elt_map topSRT) cafs return (topSRT, localSRTs) in if length cafs > maxBmpSize dflags then mkSRT (foldl add_if_missing topSRT cafs) else -- make sure all the cafs are near the bottom of the srt mkSRT (add_if_too_far topSRT cafs) add_if_missing srt caf = if cafMember srt caf then srt else addCAF caf srt -- If a CAF is more than maxBmpSize entries from the young end of the -- SRT, then we add it to the SRT again. -- (Note: Not in the SRT => infinitely far.) add_if_too_far srt@(TopSRT {elt_map = m}) cafs = add srt (sortBy farthestFst cafs) where farthestFst x y = case (Map.lookup x m, Map.lookup y m) of (Nothing, Nothing) -> EQ (Nothing, Just _) -> LT (Just _, Nothing) -> GT (Just d, Just d') -> compare d' d add srt [] = srt add srt@(TopSRT {next_elt = next}) (caf : rst) = case cafOffset srt caf of Just ix -> if next - ix > maxBmpSize dflags then add (addCAF caf srt) rst else srt Nothing -> add (addCAF caf srt) rst (topSRT, subSRTs) <- sub_srt topSRT cafs let (sub_tbls, blockSRTs) = subSRTs return (topSRT, sub_tbls, blockSRTs) -- Construct an SRT bitmap. -- Adapted from simpleStg/SRT.lhs, which expects Id's. procpointSRT :: DynFlags -> CLabel -> Map CLabel Int -> [CLabel] -> UniqSM (Maybe CmmDecl, C_SRT) procpointSRT _ _ _ [] = return (Nothing, NoC_SRT) procpointSRT dflags top_srt top_table entries = do (top, srt) <- bitmap `seq` to_SRT dflags top_srt offset len bitmap return (top, srt) where ints = map (expectJust "constructSRT" . flip Map.lookup top_table) entries sorted_ints = sort ints offset = head sorted_ints bitmap_entries = map (subtract offset) sorted_ints len = P.last bitmap_entries + 1 bitmap = intsToBitmap dflags len bitmap_entries maxBmpSize :: DynFlags -> Int maxBmpSize dflags = widthInBits (wordWidth dflags) `div` 2 -- Adapted from codeGen/StgCmmUtils, which converts from SRT to C_SRT. to_SRT :: DynFlags -> CLabel -> Int -> Int -> Bitmap -> UniqSM (Maybe CmmDecl, C_SRT) to_SRT dflags top_srt off len bmp | len > maxBmpSize dflags || bmp == [toStgWord dflags (fromStgHalfWord (srtEscape dflags))] = do id <- getUniqueM let srt_desc_lbl = mkLargeSRTLabel id tbl = CmmData RelocatableReadOnlyData $ Statics srt_desc_lbl $ map CmmStaticLit ( cmmLabelOffW dflags top_srt off : mkWordCLit dflags (fromIntegral len) : map (mkStgWordCLit dflags) bmp) return (Just tbl, C_SRT srt_desc_lbl 0 (srtEscape dflags)) | otherwise = return (Nothing, C_SRT top_srt off (toStgHalfWord dflags (fromStgWord (head bmp)))) -- The fromIntegral converts to StgHalfWord -- Gather CAF info for a procedure, but only if the procedure -- doesn't have a static closure. -- (If it has a static closure, it will already have an SRT to -- keep its CAFs live.) -- Any procedure referring to a non-static CAF c must keep live -- any CAF that is reachable from c. localCAFInfo :: CAFEnv -> CmmDecl -> (CAFSet, Maybe CLabel) localCAFInfo _ (CmmData _ _) = (Set.empty, Nothing) localCAFInfo cafEnv proc@(CmmProc _ top_l _ (CmmGraph {g_entry=entry})) = case topInfoTable proc of Just (CmmInfoTable { cit_rep = rep }) | not (isStaticRep rep) && not (isStackRep rep) -> (cafs, Just (toClosureLbl top_l)) _other -> (cafs, Nothing) where cafs = expectJust "maybeBindCAFs" $ mapLookup entry cafEnv -- Once we have the local CAF sets for some (possibly) mutually -- recursive functions, we can create an environment mapping -- each function to its set of CAFs. Note that a CAF may -- be a reference to a function. If that function f does not have -- a static closure, then we need to refer specifically -- to the set of CAFs used by f. Of course, the set of CAFs -- used by f must be included in the local CAF sets that are input to -- this function. To minimize lookup time later, we return -- the environment with every reference to f replaced by its set of CAFs. -- To do this replacement efficiently, we gather strongly connected -- components, then we sort the components in topological order. mkTopCAFInfo :: [(CAFSet, Maybe CLabel)] -> Map CLabel CAFSet mkTopCAFInfo localCAFs = foldl addToTop Map.empty g where addToTop env (AcyclicSCC (l, cafset)) = Map.insert l (flatten env cafset) env addToTop env (CyclicSCC nodes) = let (lbls, cafsets) = unzip nodes cafset = foldr Set.delete (foldl Set.union Set.empty cafsets) lbls in foldl (\env l -> Map.insert l (flatten env cafset) env) env lbls g = stronglyConnCompFromEdgedVertices [ ((l,cafs), l, Set.elems cafs) | (cafs, Just l) <- localCAFs ] flatten :: Map CLabel CAFSet -> CAFSet -> CAFSet flatten env cafset = foldSet (lookup env) Set.empty cafset where lookup env caf cafset' = case Map.lookup caf env of Just cafs -> foldSet Set.insert cafset' cafs Nothing -> Set.insert caf cafset' bundle :: Map CLabel CAFSet -> (CAFEnv, CmmDecl) -> (CAFSet, Maybe CLabel) -> (BlockEnv CAFSet, CmmDecl) bundle flatmap (env, decl@(CmmProc infos lbl _ g)) (closure_cafs, mb_lbl) = ( mapMapWithKey get_cafs (info_tbls infos), decl ) where entry = g_entry g entry_cafs | Just l <- mb_lbl = expectJust "bundle" $ Map.lookup l flatmap | otherwise = flatten flatmap closure_cafs get_cafs l _ | l == entry = entry_cafs | otherwise = if not (mapMember l env) then pprPanic "bundle" (ppr l <+> ppr lbl <+> ppr (info_tbls infos)) else flatten flatmap $ expectJust "bundle" $ mapLookup l env bundle _flatmap (_, decl) _ = ( mapEmpty, decl ) flattenCAFSets :: [(CAFEnv, [CmmDecl])] -> [(BlockEnv CAFSet, CmmDecl)] flattenCAFSets cpsdecls = zipWith (bundle flatmap) zipped localCAFs where zipped = [ (env,decl) | (env,decls) <- cpsdecls, decl <- decls ] localCAFs = unzipWith localCAFInfo zipped flatmap = mkTopCAFInfo localCAFs -- transitive closure of localCAFs doSRTs :: DynFlags -> TopSRT -> [(CAFEnv, [CmmDecl])] -> IO (TopSRT, [CmmDecl]) doSRTs dflags topSRT tops = do let caf_decls = flattenCAFSets tops us <- mkSplitUniqSupply 'u' let (topSRT', gs') = initUs_ us $ foldM setSRT (topSRT, []) caf_decls return (topSRT', reverse gs' {- Note [reverse gs] -}) where setSRT (topSRT, rst) (caf_map, decl@(CmmProc{})) = do (topSRT, srt_tables, srt_env) <- buildSRTs dflags topSRT caf_map let decl' = updInfoSRTs srt_env decl return (topSRT, decl': srt_tables ++ rst) setSRT (topSRT, rst) (_, decl) = return (topSRT, decl : rst) buildSRTs :: DynFlags -> TopSRT -> BlockEnv CAFSet -> UniqSM (TopSRT, [CmmDecl], BlockEnv C_SRT) buildSRTs dflags top_srt caf_map = foldM doOne (top_srt, [], mapEmpty) (mapToList caf_map) where doOne (top_srt, decls, srt_env) (l, cafs) = do (top_srt, mb_decl, srt) <- buildSRT dflags top_srt cafs return ( top_srt, maybeToList mb_decl ++ decls , mapInsert l srt srt_env ) {- - In each CmmDecl there is a mapping from BlockId -> CmmInfoTable - The one corresponding to g_entry is the closure info table, the rest are continuations. - Each one needs an SRT. - We get the CAFSet for each one from the CAFEnv - flatten gives us [(BlockEnv CAFSet, CmmDecl)] - -} {- Note [reverse gs] It is important to keep the code blocks in the same order, otherwise binary sizes get slightly bigger. I'm not completely sure why this is, perhaps the assembler generates bigger jump instructions for forward refs. --SDM -} updInfoSRTs :: BlockEnv C_SRT -> CmmDecl -> CmmDecl updInfoSRTs srt_env (CmmProc top_info top_l live g) = CmmProc (top_info {info_tbls = mapMapWithKey updInfoTbl (info_tbls top_info)}) top_l live g where updInfoTbl l info_tbl = info_tbl { cit_srt = expectJust "updInfo" $ mapLookup l srt_env } updInfoSRTs _ t = t
ekmett/ghc
compiler/cmm/CmmBuildInfoTables.hs
bsd-3-clause
14,226
0
19
3,743
3,419
1,785
1,634
214
9
module PersistentPaint where import Rumpus import qualified Data.Sequence as Seq maxBlots = 1000 -- This paintbrush is persistent, via -- spawnPersistentEntity and sceneWatcherSaveEntity start :: Start start = do initialPosition <- getPosition setState (initialPosition, Seq.empty :: Seq EntityID) myDragContinues ==> \_ -> withState $ \(lastPosition, blots) -> do newPose <- getPose let newPosition = newPose ^. translation when (distance lastPosition newPosition > 0.05) $ do newBlot <- spawnPersistentEntity $ do myPose ==> newPose myShape ==> Cube mySize ==> 0.1 myBody ==> Animated myColor ==> colorHSL (newPosition ^. _x) 0.7 0.8 sceneWatcherSaveEntity newBlot let (newBlots, oldBlots) = Seq.splitAt maxBlots blots forM_ oldBlots removeEntity setState (newPosition, newBlot <| newBlots)
lukexi/rumpus
pristine/Painting/PersistentPaint.hs
bsd-3-clause
1,065
0
23
379
241
120
121
23
1
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.ARB.TextureCubeMapArray -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.ARB.TextureCubeMapArray ( -- * Extension Support glGetARBTextureCubeMapArray, gl_ARB_texture_cube_map_array, -- * Enums pattern GL_INT_SAMPLER_CUBE_MAP_ARRAY_ARB, pattern GL_PROXY_TEXTURE_CUBE_MAP_ARRAY_ARB, pattern GL_SAMPLER_CUBE_MAP_ARRAY_ARB, pattern GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_ARB, pattern GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB, pattern GL_TEXTURE_CUBE_MAP_ARRAY_ARB, pattern GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_ARB ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens
haskell-opengl/OpenGLRaw
src/Graphics/GL/ARB/TextureCubeMapArray.hs
bsd-3-clause
970
0
5
115
77
54
23
13
0
{-| Module : Grammar.CFG.Random Description : Functions to randomly expand symbols and words according to a grammar. Copyright : (c) Davide Mancusi, 2017 License : BSD3 Maintainer : arekfu@gmail.com Stability : experimental Portability : POSIX This module contains the relevant tools to sample random words from a context-free grammar. All computations take place in the 'MC' monad, which is simply a practical way to thread the pseudo-random-number generator (PRNG) state. Be careful: the expansion is currently totally unbiased -- it will expand a given nonterminal by assuming that all of the production rules have equal probability. Depending on the grammar, this may lead the size of the generated word to grow without bound, or to become very large. -} module Grammar.CFG.Random ( -- * Randomly expanding symbols and words RandomGrammar(..) , randomSymExpand , randomWordExpand , randomGrammarDerive , randomGrammarDeriveN , randomGrammarDeriveScan ) where -- system imports import Prelude hiding (words) -- local imports import Grammar.CFG import Grammar.MC import Grammar.Regex.Random (randomExpandRegex) --------------------------------------------------------- -- functions to randomly derive sequences of symbols -- --------------------------------------------------------- {- | A typeclass for random generation of language strings starting from a grammar specification, in the form of a type of the 'Grammar.CFG.Grammar' class. -} class (Grammar g, Ord (Repr g)) => RandomGrammar g where -- | Recursively and randomly expand a word until it consists solely of -- terminals. WARNING: may produce infinite lists! randomWordDerive :: g -- ^ the grammar -> [Repr g] -- ^ the word to expand -> MC [Repr g] -- ^ a fully expanded sequence of terminals randomWordDerive grammar word = do expanded <- randomWordExpand grammar word if word == expanded then return expanded else randomWordDerive grammar expanded -- | Recursively and randomly expand a word until it consists solely of -- terminals or until @n@ expansion steps have been performed, whichever -- comes first. randomWordDeriveN :: Int -- ^ the maximum number of expansions -> g -- ^ the grammar -> [Repr g] -- ^ the starting word -> MC [Repr g] -- ^ the resulting expansion randomWordDeriveN 0 _ word = return word randomWordDeriveN n grammar word = do expanded <- randomWordDerive grammar word randomWordDeriveN (n-1) grammar expanded -- | Recursively and randomly expand a word, and return all the -- intermediate expansion results. WARNING: may produce infinite lists! randomWordDeriveScan :: g -- ^ the grammar -> [Repr g] -- ^ the starting word -> MC [[Repr g]] -- ^ the list of all intermediate expansions randomWordDeriveScan grammar word = do expanded <- randomWordExpand grammar word if word == expanded then return [expanded] else fmap (expanded:) (randomWordDeriveScan grammar expanded) -- | Randomly expand a symbol using one of its production rules. randomSymExpand :: (Grammar g, Ord (Repr g)) => g -- ^ the grammar -> Repr g -- ^ the symbol to expand -> MC [Repr g] -- ^ the resulting word randomSymExpand gr sym = case productions gr sym of Nothing -> return [sym] Just regex -> randomExpandRegex regex -- | Expand a word (a sequence of symbols) using randomly selected -- production rules for each nonterminal. randomWordExpand :: (Grammar g, Ord (Repr g)) => g -- ^ the grammar -> [Repr g] -- ^ the word to expand -> MC [Repr g] -- ^ the resulting word randomWordExpand g syms = do words <- mapM (randomSymExpand g) syms return $ concat words -- | Recursively and randomly expand the start symbol of a grammar until it -- consists solely of terminals. WARNING: may produce infinite lists! randomGrammarDerive :: (RandomGrammar g, Ord (Repr g)) => g -- ^ the grammar -> MC [Repr g] -- ^ a fully expanded sequence of terminals randomGrammarDerive grammar = randomWordDerive grammar [startSymbol grammar] -- | Recursively and randomly expand the start symbol of a grammar until it -- consists solely of terminals or until @n@ expansion steps have been -- performed, whichever comes first. randomGrammarDeriveN :: (RandomGrammar g, Ord (Repr g)) => Int -- ^ the maximum number of expansions -> g -- ^ the grammar -> MC [Repr g] -- ^ the resulting expansion randomGrammarDeriveN n grammar = randomWordDeriveN n grammar [startSymbol grammar] -- | Recursively and randomly expand the start symbol of a grammar, and return -- all the intermediate expansion results. WARNING: may produce infinite -- lists! randomGrammarDeriveScan :: (RandomGrammar g, Ord (Repr g)) => g -- ^ the grammar -> MC [[Repr g]] -- ^ the list of all intermediate expansions randomGrammarDeriveScan grammar = randomWordDeriveScan grammar [startSymbol grammar] delegateCFGToIntCFG :: (Functor f, Ord b) => (forall g. RandomGrammar g => g -> f (Repr g) -> MC (f (Repr g))) -> CFG b -> f (Repr (CFG b)) -> MC (f (Repr (CFG b))) delegateCFGToIntCFG action (CFG _ iGr s2l l2s) word = let labelWord = ReprInt <$> symbolsToLabels s2l (unReprCFG <$> word) in do derived <- action iGr labelWord return (ReprCFG <$> labelsToSymbols l2s (unReprInt <$> derived)) delegateCFGToIntCFG2 :: (Functor f, Ord b) => (forall g. RandomGrammar g => g -> f (Repr g) -> MC (f (f (Repr g)))) -> CFG b -> f (Repr (CFG b)) -> MC (f (f (Repr (CFG b)))) delegateCFGToIntCFG2 action (CFG _ iGr s2l l2s) regex = let labelRegex = ReprInt <$> symbolsToLabels s2l (unReprCFG <$> regex) in do derived <- action iGr labelRegex return (fmap ReprCFG <$> fmap (labelsToSymbols l2s) (fmap unReprInt <$> derived)) instance RandomGrammar IntCFG instance (Ord a, Show a) => RandomGrammar (CFG a) where randomWordDerive = delegateCFGToIntCFG randomWordDerive randomWordDeriveN n = delegateCFGToIntCFG (randomWordDeriveN n) randomWordDeriveScan = delegateCFGToIntCFG2 randomWordDeriveScan instance RandomGrammar CharCFG where randomWordDerive (CharCFG g) word = map (ReprChar . unReprCFG) <$> delegateCFGToIntCFG randomWordDerive g (map (ReprCFG . unReprChar) word) randomWordDeriveN n (CharCFG g) word = map (ReprChar . unReprCFG) <$> delegateCFGToIntCFG (randomWordDeriveN n) g (map (ReprCFG . unReprChar) word) randomWordDeriveScan (CharCFG g) word = map (map (ReprChar . unReprCFG)) <$> delegateCFGToIntCFG2 randomWordDeriveScan g (map (ReprCFG . unReprChar) word) instance RandomGrammar StringCFG where randomWordDerive (StringCFG g) word = map (ReprString . unReprCFG) <$> delegateCFGToIntCFG randomWordDerive g (map (ReprCFG . unReprString) word) randomWordDeriveN n (StringCFG g) word = map (ReprString . unReprCFG) <$> delegateCFGToIntCFG (randomWordDeriveN n) g (map (ReprCFG . unReprString) word) randomWordDeriveScan (StringCFG g) word = map (map (ReprString . unReprCFG)) <$> delegateCFGToIntCFG2 randomWordDeriveScan g (map (ReprCFG . unReprString) word)
arekfu/grammar-haskell
src/Grammar/CFG/Random.hs
bsd-3-clause
8,040
0
18
2,298
1,614
828
786
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Config where import Control.Lens ((&), (.~), (^.)) import Data.Yaml (ParseException, decodeFileEither) import Filesystem.Path.CurrentOS (encodeString, fromText, parent, toText, (</>)) import Turtle.Prelude import Types {- Find the root of a project in order to find the config file, if it exists. -} projectRoot :: IO OSFilePath projectRoot = findProjectRoot pwd {-| A React project must have a node_modules directory. |-} findProjectRoot :: IO OSFilePath -> IO OSFilePath findProjectRoot dir = do isRoot <- hasConfigFile =<< dir isSystemRoot <- dir >>= (\d -> return $ d == fromText "/") if isSystemRoot then return $ fromText "." else if isRoot then dir else findProjectRoot $ recurseUp =<< dir recurseUp :: OSFilePath -> IO OSFilePath recurseUp dir = return $ parent dir hasConfigFile :: OSFilePath -> IO Bool hasConfigFile dir = testfile $ dir </> ".generate-component.yaml" readConfig :: IO Config readConfig = do rootDir <- projectRoot let configPath = rootDir </> ".generate-component.yaml" :: OSFilePath let configContents = decodeFileEither $ encodeString configPath configFromEither =<< configContents configFromEither :: Either ParseException Config -> IO Config configFromEither c = case c of Left _e -> defaultConfig Right config -> return config mergeConfig :: Config -> Settings -> Settings mergeConfig c s = s & sProjectType .~ (c ^. projectType) & sComponentDir .~ dir & sComponentType .~ cType where dir = case s ^. sComponentDir of Nothing -> Just $ fromText $ c ^. defaultDirectory Just d -> Just d cType = case s ^. sComponentType of Nothing -> Just $ c ^. componentType Just ct -> Just ct defaultConfig :: IO Config defaultConfig = do d <- pwd let dir = toText d let buildConfig = Config ReactNative ES6Class return $ either buildConfig buildConfig dir
tpoulsen/generate-component
src/Config.hs
bsd-3-clause
2,056
0
12
520
551
283
268
54
3
module Main where import qualified Data.Map.Strict as M import Data.Monoid import Data.List (delete) import Options.Applicative import qualified Sound.MIDI.File.Load as L import qualified Sound.MIDI.File.Save as S import qualified Sound.MIDI.Message.Channel as CM import qualified Sound.MIDI.Message.Channel.Voice as VM import Filter import Instances import Arguments testMap :: ChannelInstrumentMap testMap = M.fromList [(CM.toChannel 0, VM.toProgram 0) ,(CM.toChannel 1, VM.toProgram 0)] defaultMap :: VM.Program -> ChannelInstrumentMap defaultMap p = M.fromList $ map (\n -> (CM.toChannel n, p)) (delete 9 [0..15]) mapFromArgs :: Args -> ChannelInstrumentMap mapFromArgs args = let base = if useSameInstr args then defaultMap (defaultInstr args) else M.empty specified = M.fromList $ instrumentSpecs args in M.union specified base main = do args <- execParser (info parseArgs mempty) before <- L.fromFile (infile args) let instrumentMap = mapFromArgs args after <- return $ modifyFileWithMap instrumentMap before S.toSeekableFile (outfile args) after
jarmar/change-instrument
src/Main.hs
bsd-3-clause
1,155
0
12
235
354
195
159
31
2
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveDataTypeable, OverlappingInstances, FlexibleContexts #-} -- The Timber compiler <timber-lang.org> -- -- Copyright 2008-2009 Johan Nordlander <nordland@csee.ltu.se> -- 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. -- -- 3. Neither the names of the copyright holder and any identified -- contributors, nor the names of their affiliations, may be used to -- endorse or promote products derived from this software without -- specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE 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 AUTHORS 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 Common (module Common, module Name, isDigit) where import PP import qualified List import qualified Maybe import Monad(liftM2) import Control.Exception import Char import Config import Name import Data.Typeable import Data.Binary import Debug.Trace fromJust = Maybe.fromJust isJust = Maybe.isJust listToMaybe = Maybe.listToMaybe fst3 (a,b,c) = a snd3 (a,b,c) = b thd3 (a,b,c) = c dom = map fst rng = map snd partition p xs = List.partition p xs nub xs = List.nub xs xs \\ ys = filter (`notElem` ys) xs xs `intersect` ys = xs `List.intersect` ys xs `union` ys = xs `List.union` ys disjoint xs ys = xs `intersect` ys == [] overlaps xs ys = not (disjoint xs ys) intersperse x xs = List.intersperse x xs duplicates xs = filter (`elem` dups) xs1 where xs1 = nub xs dups = foldl (flip List.delete) xs xs1 rotate n xs = let (xs1,xs2) = splitAt n xs in xs2++xs1 separate [] = ([],[]) separate (Left x : xs) = let (ls,rs) = separate xs in (x:ls,rs) separate (Right x : xs) = let (ls,rs) = separate xs in (ls,x:rs) showids vs = concat (intersperse ", " (map show vs)) fmapM f g xs = do ys <- mapM g xs return (f ys) mapFst f xs = [ (f a, b) | (a,b) <- xs ] mapSnd f xs = [ (a, f b) | (a,b) <- xs ] zipFilter (f:fs) (x:xs) | f = x : zipFilter fs xs | otherwise = zipFilter fs xs zipFilter _ _ = [] zip4 = List.zip4 noDups mess vs | not (null dups) = errorIds mess dups | otherwise = vs where dups = duplicates vs uncurry3 f (x,y,z) = f x y z -- String manipulation ----------------------------------------------------- rmSuffix :: String -> String -> String rmSuffix suf = reverse . rmPrefix (reverse suf) . reverse rmPrefix :: String -> String -> String rmPrefix pre str | pre `List.isPrefixOf` str = drop (length pre) str | otherwise = internalError0 $ "rmPrefix: " ++ str ++ " is not a prefix of " ++ show pre rmDirs :: String -> String rmDirs = reverse . fst . span (/='/') . reverse dropPrefix [] s = (True, s) dropPrefix (x:xs) (y:ys) | x == y = dropPrefix xs ys dropPrefix xs ys = (False, ys) dropDigits xs = drop 0 xs where drop n (x:xs) | isDigit x = drop (10*n + ord x - ord '0') xs drop n xs = (n, xs) -- Error reporting --------------------------------------------------------- errorIds mess ns = compileError (unlines ((mess++":") : map pos ns)) where pos n = case loc n of Just (r,c) -> rJust 15 (show n) ++ " at line " ++ show r ++ ", column " ++ show c Nothing -> rJust 15 (show n) ++ modInfo n loc n = location (annot n) rJust w str = replicate (w-length str) ' ' ++ str modInfo (Name _ _ (Just m) a) = " defined in " ++ m modInfo _ = " (unknown position)" errorTree mess t = compileError (errorMsg mess t) compileError mess = throw (CompileError mess) errorMsg mess t = mess ++ pos ++ (if length (lines str) > 1 then "\n"++str++"\n" else str) where str = render (pr t) pos = " ("++ show (posInfo t) ++"): " internalError mess t = internalError0 (errorMsg mess t) internalError0 mess = throw (Panic mess) -- PosInfo --------------------------------------------------------- data PosInfo = Between {start :: (Int,Int), end :: (Int,Int)} | Unknown instance Show PosInfo where show (Between (l1,c1) (l2,c2)) = case l1==l2 of True -> case c1 == c2 of True -> "close to line "++show l1++", column "++show c1 False -> "close to line "++show l1++", columns "++show c1++" -- "++show c2 False -> "close to lines "++show l1++" -- "++show l2 show Unknown = "at unknown position" between (Between s1 e1) (Between s2 e2) = Between (min s1 s2) (max e1 e2) between b@(Between _ _) Unknown = b between Unknown b@(Between _ _) = b between Unknown Unknown = Unknown startPos (Between s _) = Just s startPos Unknown = Nothing class HasPos a where posInfo :: a -> PosInfo instance HasPos a => HasPos [a] where posInfo xs = foldr between Unknown (map posInfo xs) instance (HasPos a, HasPos b) => HasPos (a,b) where posInfo (a,b) = between (posInfo a) (posInfo b) instance HasPos a => HasPos (Maybe a) where posInfo Nothing = Unknown posInfo (Just a) = posInfo a instance HasPos Bool where posInfo _ = Unknown instance HasPos Name where posInfo n = case location (annot n) of Just (l,c) |l==0 && c==0 -> Unknown -- artificially introduced name |otherwise -> Between (l,c) (l,c+len n-1) Nothing -> Unknown where len(Name s _ _ _) = length s len(Prim p _) = length (strRep p) len(Tuple n _) = n+2 -- Literals ---------------------------------------------------------------- data Lit = LInt (Maybe (Int,Int)) Integer | LRat (Maybe (Int,Int)) Rational | LChr (Maybe (Int,Int)) Char | LStr (Maybe (Int,Int)) String -- deriving (Eq) instance Eq Lit where LInt _ m == LInt _ n = m == n LRat _ m == LRat _ n = m == n LChr _ m == LChr _ n = m == n LStr _ m == LStr _ n = m == n _ == _ = False instance Show Lit where show (LInt _ i) = "LInt " ++ show i show (LRat _ r) = "LRat " ++ show r show (LChr _ c) = "LChr " ++ show c show (LStr _ s) = "LStr " ++ show s instance Pr Lit where prn _ (LInt _ i) = integer i prn 0 (LRat _ r) = rational r prn _ (LRat _ r) = parens (rational r) prn _ (LChr _ c) = litChar c prn _ (LStr _ s) = litString s instance HasPos Lit where posInfo (LInt (Just (l,c)) i) = Between (l,c) (l,c+length(show i)-1) posInfo (LRat (Just (l,c)) r) = Between (l,c) (l,c) -- check length of rationals) posInfo (LChr (Just (l,c)) _) = Between (l,c) (l,c) posInfo (LStr (Just (l,c)) cs) = Between (l,c) (l,c+length cs+1) posInfo _ = Unknown lInt n = LInt Nothing (toInteger n) lRat r = LRat Nothing r lChr c = LChr Nothing c lStr s = LStr Nothing s -- Underlying monad ---------------------------------------------------------------------- newtype M s a = M ((Int,[s]) -> Either String ((Int,[s]), a)) instance Functor (M s) where fmap f x = x >>= (return . f) instance Monad (M s) where M m >>= f = M $ \k -> case m k of Right (k',a) -> m' k' where M m' = f a Left s -> Left s return a = M $ \k -> Right (k,a) fail s = M $ \k -> Left s handle (M m) f = M $ \k -> case m k of Right r -> Right r Left s -> m' k where M m' = f s expose (M m) = M $ \k -> case m k of Right (k',a) -> Right (k',Right a) Left s -> Right (k, Left s) unexpose (Right a) = return a unexpose (Left b) = fail b runM (M m) = case m (1,[]) of Right (_,x) -> x Left s -> compileError s newNum = M $ \(n,s) -> Right ((n+1,s), n) currentNum = M $ \(n,s) -> Right ((n,s), n) addToStore x = M $ \(n,s) -> Right ((n,x:s), ()) currentStore = M $ \(n,s) -> Right ((n,s), s) localStore (M m) = M $ \(n0,s0) -> case m (n0,[]) of Right ((n,s), x) -> Right ((n,s0), x) Left s -> Left s newNameMod m s = do n <- newNum return (Name s n m ann) where ann = if s `elem` explicitSyms then suppAnnot { explicit = True } else suppAnnot suppAnnot = genAnnot { suppress = True } newNameModPub m pub s = do n <- newNameMod m s return (n {annot = (annot n) {public = pub}}) newName s = newNameMod Nothing s newNames s n = mapM (const (newName s)) [1..n] newNamesPos s ps = mapM (newNamePos s) ps newNamePos s p = do n <- newName s return (n {annot = (annot n) {location = startPos(posInfo p)}}) renaming vs = mapM f vs where f v | tag v == 0 = do n <- newNum return (v, v { tag = n }) | otherwise = return (v, v) -- Merging renamings ------------------------------------------------------ -- Here we cannot use equality of names (Eq instance), since two unqualified -- imported names with the same string will have non-zero tags and hence not be compared -- for str equality. -- remove pairs from rn2 that are shadowed by rn1; return also shadowed names deleteRenamings [] rn2 = (rn2,[]) deleteRenamings ((n,_):rn1) rn2 | not (isQualified n) = (rn',if b then n:ns else ns) | otherwise = (rn,ns) where (rn,ns) = deleteRenamings rn1 rn2 (b,rn') = deleteName n rn deleteName _ [] = (False,[]) deleteName n ((Name s t Nothing a,_):rn) | str n == s = (True,rn) deleteName n (p:rn) = let (b,rn') = deleteName n rn in (b,p:rn') -- for merging renaming for locally bound names with ditto for imported names; -- removes unqualified form of imported name mergeRenamings1 rn1 rn2 = rn1 ++ rn2' where (rn2',_) = deleteRenamings rn1 rn2 -- for merging renamings from two imported modules; -- removes both occurrences when two unqualified names clash mergeRenamings2 rn1 rn2 = rn1' ++ rn2' where (rn2',ns) = deleteRenamings rn1 rn2 rn1' = deleteNames ns rn1 ns' = filter (not . isGenerated) ns deleteNames [] rn = rn deleteNames (n:ns) rn = deleteNames ns (snd (deleteName n rn)) -- Assertions ----------------------------------------------------------------------- assert e msg ns | e = return () | otherwise = errorIds msg ns assert1 e msg ts | e = return () | otherwise = errorTree msg ts -- Poor man's exception datatype ------------------------------------------------------ encodeError msg ids = msg ++ ": " ++ concat (intersperse " " (map packName ids)) decodeError str | msg `elem` encodedMsgs = Just (msg, map unpackName (words rest)) | otherwise = Nothing where (msg,_:rest) = span (/=':') str encodedMsgs = [circularSubMsg, ambigInstMsg, ambigSubMsg] circularSubMsg = "Circular subtyping" ambigInstMsg = "Ambiguous instances" ambigSubMsg = "Ambiguous subtyping" assert0 e msg | e = return () | otherwise = fail msg -- Tracing ----------------------------------------------------------------------------- tr m = trace (m++"\n") (return ()) tr' m e = trace ("\n"++m++"\n") e trNum str = do n <- currentNum tr ("At "++show n++": "++str) -- Free variables ----------------------------------------------------------------------- class Ids a where idents :: a -> [Name] instance Ids a => Ids [a] where idents xs = concatMap idents xs instance Ids a => Ids (Name,a) where idents (v,a) = idents a tycons x = filter isCon (idents x) tyvars x = filter isVar (idents x) evars x = filter isVar (idents x) svars x = filter isState (idents x) vclose vss vs | null vss2 = nub vs | otherwise = vclose vss1 (concat vss2 ++ vs) where (vss1,vss2) = partition (null . intersect vs) vss -- Bound variables ----------------------------------------------------------------------- class BVars a where bvars :: a -> [Name] bvars _ = [] -- Mappings ----------------------------------------------------------------------------- infixr 4 @@ type Map a b = [(a,b)] lookup' assoc x = case lookup x assoc of Just e -> e Nothing -> internalError "lookup': did not find" x lookup'' s assoc x = case lookup x assoc of Just e -> e Nothing -> internalError ("lookup' (" ++ s ++ "): did not find") x inv assoc = map (\(a,b) -> (b,a)) assoc delete k [] = [] delete k (x:xs) | fst x == k = xs | otherwise = x : delete k xs delete' ks xs = foldr delete xs ks insert k x [] = [(k,x)] insert k x ((k',x'):assoc) | k == k' = (k,x) : assoc | otherwise = (k',x') : insert k x assoc update k f [] = internalError0 "Internal: Common.update" update k f ((k',x):assoc) | k == k' = (k, f x) : assoc | otherwise = (k',x) : update k f assoc search p [] = Nothing search p (a:assoc) | p a = Just a | otherwise = search p assoc insertBefore kx ks [] = [kx] insertBefore kx ks ((k,x'):assoc) | k `elem` ks = kx:(k,x'):assoc | otherwise = (k,x') : insertBefore kx ks assoc (@@) :: Subst b a b => Map a b -> Map a b -> Map a b s1 @@ s2 = [(u,subst s1 t) | (u,t) <- s2] ++ s1 merge :: (Eq a, Eq b) => Map a b -> Map a b -> Maybe (Map a b) merge [] s' = Just s' merge ((v,t):s) s' = case lookup v s' of Nothing -> merge s ((v,t):s') Just t' | t==t' -> merge s s' _ -> Nothing nullSubst = [] a +-> b = [(a,b)] restrict s vs = filter ((`elem` vs) . fst) s prune s vs = filter ((`notElem` vs) . fst) s class Subst a i e where subst :: Map i e -> a -> a substVars s xs = map (substVar s) xs substVar s x = case lookup x s of Just x' -> x' Nothing -> x instance Subst Name Name Name where subst s x = case lookup x s of Just x' -> x' _ -> x instance Subst a i e => Subst [a] i e where subst [] xs = xs subst s xs = map (subst s) xs instance Subst a Name Name => Subst (Name,a) Name Name where subst s (v,a) = (subst s v, subst s a) instance Subst a i e => Subst (Name,a) i e where subst s (v,a) = (v, subst s a) instance Subst a i e => Subst (Maybe a) i e where subst s Nothing = Nothing subst s (Just a) = Just (subst s a) newEnv x ts = do vs <- mapM (const (newName x)) ts return (vs `zip` ts) newEnvPos x ts e = do vs <- mapM (const (newNamePos x e)) ts return (vs `zip` ts) -- Kinds --------------------------------------------------------------------------------- data Kind = Star | KFun Kind Kind | KWild | KVar Int deriving (Eq,Show) type KEnv = Map Name Kind instance HasPos Kind where posInfo _ = Unknown newKVar = do n <- newNum return (KVar n) kvars Star = [] kvars (KVar n) = [n] kvars (KFun k1 k2) = kvars k1 ++ kvars k2 kArgs (KFun k k') = k : kArgs k' kArgs k = [] kFlat k = (kArgs k, kRes k) kRes (KFun k k') = kRes k' kRes k = k instance Subst Kind Int Kind where subst s Star = Star subst s k@(KVar n) = case lookup n s of Just k' -> k' Nothing -> k subst s (KFun k1 k2) = KFun (subst s k1) (subst s k2) instance Subst (Kind,Kind) Int Kind where subst s (a,b) = (subst s a, subst s b) instance Pr (Name,Kind) where pr (n,k) = prId n <+> text "::" <+> pr k instance Pr Kind where prn 0 (KFun k1 k2) = prn 1 k1 <+> text "->" <+> prn 0 k2 prn 0 k = prn 1 k prn 1 Star = text "*" prn 1 (KVar n) = text ('_':show n) prn 1 KWild = text "_" prn 1 k = parens (prn 0 k) -- Defaults ------------------------------------------ data Default a = Default Bool Name Name -- First arg is True if declaration is in public part | Derive Name a deriving (Eq, Show) instance Pr a => Pr(Default a) where pr (Default _ a b) = pr a <+> text "<" <+> pr b pr (Derive v t) = pr v <+> text "::" <+> pr t instance HasPos a => HasPos (Default a) where posInfo (Default _ a b) = between (posInfo a) (posInfo b) posInfo (Derive v t) = between (posInfo v) (posInfo t) -- Externals ----------------------------------------- data Extern a = Extern Name a deriving (Eq, Show) instance Pr a => Pr (Extern a) where pr (Extern n t) = prId n <+> text "::" <+> pr t instance BVars [Extern a] where bvars (Extern n _ : es) = n : bvars es bvars [] = [] instance Binary a => Binary (Extern a) where put (Extern a b) = put a >> put b get = get >>= \a -> get >>= \b -> return (Extern a b) extsMap es = map (\(Extern v t) -> (v,t)) es -- Pattern matching --------------------------------------------------------------- -- The M prefix allows coexistence with older PMC primites data Match p e bs r = MCommit r | MFail | MFatbar (Match p e bs r) (Match p e bs r) | Case e [(p,Match p e bs r)] | Let bs (Match p e bs r) deriving (Eq,Show) alt p rhs = (p,rhs) foldMatch commit fail fatbar mcase mlet = f where f m = case m of MCommit r -> commit r MFail -> fail MFatbar m1 m2 -> fatbar (f m1) (f m2) Case e alts -> mcase e (mapSnd f alts) Let bs m -> mlet bs (f m) mapMatch pf ef bsf rf = foldMatch commit fail fatbar mcase mlet where commit r = MCommit (rf r) fail = MFail fatbar = MFatbar mcase e alts = Case (ef e) (mapFst pf alts) mlet bs e = Let (bsf bs) e mapMMatch pf ef bsf rf = foldMatch commit fail fatbar mcase mlet where commit r = MCommit `fmap` rf r fail = return MFail fatbar = liftM2 MFatbar mcase e alts = liftM2 Case (ef e) (sequence [liftM2 (,) (pf p) m|(p,m)<-alts]) mlet bs e = liftM2 Let (bsf bs) e instance (Ids p,Ids e, Ids bs,Ids r,BVars bs) => Ids (Match p e bs r) where idents m = case m of MCommit r -> idents r MFail -> [] MFatbar m1 m2 -> idents m1 ++ idents m2 Case e alts -> idents e ++ concat [idents m\\idents p|(p,m)<-alts] Let bs m -> idents bs ++ (idents m \\ bvars bs) instance (Subst e n e,Subst bs n e,Subst r n e) => Subst (Match p e bs r) n e where subst s = mapMatch id (subst s) (subst s) (subst s) instance (Pr p, Pr e,Pr bs,Pr r) => Pr (Match p e bs r) where prn 0 (MFatbar m1 m2) = text "Fatbar" <+> prn 12 m1 <+> prn 12 m2 prn 0 (Case e alts) = text "case" <+> pr e <+> text "of" $$ nest 2 (vcat (map pralt alts)) where pralt (p,m) = pr p <+> text "->" <+> pr m prn 0 (Let bs m) = text "let" <+> pr bs $$ text "in" <+> pr m prn 0 m = prn 11 m prn 11 (MCommit r) = text "Commit" <+> prn 12 r prn 11 m = prn 12 m prn 12 m = prn 13 m prn 13 MFail = text "Fail" prn 13 m = parens (prn 0 m) prn n e = prn 11 e instance (HasPos p, HasPos e,HasPos bs,HasPos r) => HasPos (Match p e bs r) where posInfo m = case m of MCommit r -> posInfo r MFail -> Unknown MFatbar m1 m2 -> posInfo (m1,m2) Case e alts -> posInfo (e,alts) Let bs m -> posInfo (bs,m) -- Binary -------------------------------------------- instance Binary Lit where put (LInt _ a) = putWord8 0 >> put a put (LRat _ a) = putWord8 1 >> put a put (LChr _ a) = putWord8 2 >> put a put (LStr _ a) = putWord8 3 >> put a get = do tag_ <- getWord8 case tag_ of 0 -> get >>= \a -> return (lInt (a::Integer)) 1 -> get >>= \a -> return (lRat a) 2 -> get >>= \a -> return (lChr a) 3 -> get >>= \a -> return (lStr a) _ -> fail "no parse" instance Binary Kind where put Star = putWord8 0 put (KFun a b) = putWord8 1 >> put a >> put b put KWild = putWord8 2 put (KVar a) = putWord8 3 >> put a get = do tag_ <- getWord8 case tag_ of 0 -> return Star 1 -> get >>= \a -> get >>= \b -> return (KFun a b) 2 -> return KWild 3 -> get >>= \a -> return (KVar a) _ -> fail "no parse" instance Binary a => Binary (Default a) where put (Default a b c) = putWord8 0 >> put a >> put b >> put c put (Derive a b) = putWord8 1 >> put a >> put b get = do tag_ <- getWord8 case tag_ of 0 -> get >>= \a -> get >>= \b -> get >>= \c -> return (Default a b c) 1 -> get >>= \a -> get >>= \b -> return (Derive a b)
mattias-lundell/timber-llvm
src/Common.hs
bsd-3-clause
26,557
0
19
11,232
9,177
4,642
4,535
466
5
import qualified Data.ByteString.Lazy as BL import Lib main :: IO () main = do putStrLn "read - this would fail with the output of relink1, but should work with the transformed pointers" serialized <- BL.readFile "serialized_transformed" print serialized unserialized <- unwrapFromBinary serialized putStrLn $ unserialized "qwe"
michaxm/packman-exploration
app/NoTopLevelFunctions2.hs
bsd-3-clause
341
0
9
58
72
34
38
9
1
{-# LANGUAGE JavaScriptFFI #-} module Famous.Components.Origin where import GHCJS.Types import GHCJS.Foreign import Famous.Core.Node import Famous.Components.Position data Origin_ a type Origin a = Position (Origin_ a) -- | Add a new Origin component to a node foreign import javascript unsafe "new window.famous.components.Origin($1)" fms_addOrigin :: Node a -> IO (Origin ()) addOrigin = fms_addOrigin
manyoo/ghcjs-famous
src/Famous/Components/Origin.hs
bsd-3-clause
412
4
8
60
89
52
37
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Parts ( Version(..), Parsable(..), Random(..), CipherSuite(..), HashAlgorithm(..), SignatureAlgorithm(..), parseSignatureAlgorithm, -- list1, whole, ByteStringM, runByteStringM, evalByteStringM, headBS, lenBodyToByteString, emptyBS, concat, fst3, fromInt, byteStringToInt, intToByteString, showKeySingle, showKey, section, takeWords, takeLen, take, NamedCurve(..), ) where import Prelude hiding (head, take, concat) import qualified Prelude import Numeric import Control.Applicative ((<$>)) import Basic import ByteStringMonad -- import ToByteString instance Show Random where show (Random r) = "(Random " ++ concatMap (`showHex` "") (unpack r) ++ ")" instance Parsable Random where parse = parseRandom toByteString = randomToByteString listLength _ = Nothing parseRandom :: ByteStringM Random parseRandom = Random <$> take 32 randomToByteString :: Random -> ByteString randomToByteString (Random r) = r instance Parsable CipherSuite where parse = parseCipherSuite toByteString = cipherSuiteToByteString listLength _ = Just 2 parseCipherSuite :: ByteStringM CipherSuite parseCipherSuite = do [w1, w2] <- takeWords 2 return $ case (w1, w2) of (0x00, 0x00) -> CipherSuite KeyExNULL MsgEncNULL (0x00, 0x2f) -> CipherSuite RSA AES_128_CBC_SHA (0x00, 0x33) -> CipherSuite DHE_RSA AES_128_CBC_SHA (0x00, 0x39) -> CipherSuite ECDHE_PSK NULL_SHA (0x00, 0x3c) -> CipherSuite RSA AES_128_CBC_SHA256 (0x00, 0x45) -> CipherSuite DHE_RSA CAMELLIA_128_CBC_SHA (0x00, 0x67) -> CipherSuite DHE_RSA AES_128_CBC_SHA256 (0xc0, 0x09) -> CipherSuite ECDHE_ECDSA AES_128_CBC_SHA (0xc0, 0x13) -> CipherSuite ECDHE_RSA AES_128_CBC_SHA (0xc0, 0x23) -> CipherSuite ECDHE_ECDSA AES_128_CBC_SHA256 (0xc0, 0x27) -> CipherSuite ECDHE_RSA AES_128_CBC_SHA256 _ -> CipherSuiteRaw w1 w2 cipherSuiteToByteString :: CipherSuite -> ByteString cipherSuiteToByteString (CipherSuite KeyExNULL MsgEncNULL) = "\x00\x00" cipherSuiteToByteString (CipherSuite RSA AES_128_CBC_SHA) = "\x00\x2f" cipherSuiteToByteString (CipherSuite DHE_RSA AES_128_CBC_SHA) = "\x00\x33" cipherSuiteToByteString (CipherSuite ECDHE_PSK NULL_SHA) = "\x00\x39" cipherSuiteToByteString (CipherSuite RSA AES_128_CBC_SHA256) = "\x00\x3c" cipherSuiteToByteString (CipherSuite DHE_RSA CAMELLIA_128_CBC_SHA) = "\x00\x45" cipherSuiteToByteString (CipherSuite DHE_RSA AES_128_CBC_SHA256) = "\x00\x67" cipherSuiteToByteString (CipherSuite ECDHE_ECDSA AES_128_CBC_SHA) = "\xc0\x09" cipherSuiteToByteString (CipherSuite ECDHE_RSA AES_128_CBC_SHA) = "\xc0\x13" cipherSuiteToByteString (CipherSuite ECDHE_ECDSA AES_128_CBC_SHA256) = "\xc0\x23" cipherSuiteToByteString (CipherSuite ECDHE_RSA AES_128_CBC_SHA256) = "\xc0\x27" cipherSuiteToByteString (CipherSuiteRaw w1 w2) = pack [w1, w2] cipherSuiteToByteString _ = error "Parts.cipherSuiteToByteString" data HashAlgorithm = HashAlgorithmSha1 | HashAlgorithmSha224 | HashAlgorithmSha256 | HashAlgorithmSha384 | HashAlgorithmSha512 | HashAlgorithmRaw Word8 deriving Show instance Parsable HashAlgorithm where parse = parseHashAlgorithm toByteString = hashAlgorithmToByteString listLength _ = Just 1 parseHashAlgorithm :: ByteStringM HashAlgorithm parseHashAlgorithm = do ha <- headBS return $ case ha of 2 -> HashAlgorithmSha1 3 -> HashAlgorithmSha224 4 -> HashAlgorithmSha256 5 -> HashAlgorithmSha384 6 -> HashAlgorithmSha512 _ -> HashAlgorithmRaw ha hashAlgorithmToByteString :: HashAlgorithm -> ByteString hashAlgorithmToByteString HashAlgorithmSha1 = "\x02" hashAlgorithmToByteString HashAlgorithmSha224 = "\x03" hashAlgorithmToByteString HashAlgorithmSha256 = "\x04" hashAlgorithmToByteString HashAlgorithmSha384 = "\x05" hashAlgorithmToByteString HashAlgorithmSha512 = "\x06" hashAlgorithmToByteString (HashAlgorithmRaw w) = pack [w] data SignatureAlgorithm = SignatureAlgorithmRsa | SignatureAlgorithmDsa | SignatureAlgorithmEcdsa | SignatureAlgorithmRaw Word8 deriving Show instance Parsable SignatureAlgorithm where parse = parseSignatureAlgorithm toByteString = signatureAlgorithmToByteString listLength _ = Just 1 parseSignatureAlgorithm :: ByteStringM SignatureAlgorithm parseSignatureAlgorithm = do sa <- headBS return $ case sa of 1 -> SignatureAlgorithmRsa 2 -> SignatureAlgorithmDsa 3 -> SignatureAlgorithmEcdsa _ -> SignatureAlgorithmRaw sa signatureAlgorithmToByteString :: SignatureAlgorithm -> ByteString signatureAlgorithmToByteString SignatureAlgorithmRsa = "\x01" signatureAlgorithmToByteString SignatureAlgorithmDsa = "\x02" signatureAlgorithmToByteString SignatureAlgorithmEcdsa = "\x03" signatureAlgorithmToByteString (SignatureAlgorithmRaw w) = pack [w] instance Parsable Version where parse = parseVersion toByteString = versionToByteString listLength _ = Nothing parseVersion :: ByteStringM Version parseVersion = do [vmjr, vmnr] <- takeWords 2 return $ Version vmjr vmnr instance Parsable NamedCurve where parse = parseNamedCurve toByteString = namedCurveToByteString listLength _ = Nothing parseNamedCurve :: ByteStringM NamedCurve parseNamedCurve = do nc <- takeWord16 return $ case nc of 23 -> Secp256r1 24 -> Secp384r1 25 -> Secp521r1 _ -> NamedCurveRaw nc namedCurveToByteString :: NamedCurve -> ByteString namedCurveToByteString (Secp256r1) = word16ToByteString 23 namedCurveToByteString (Secp384r1) = word16ToByteString 24 namedCurveToByteString (Secp521r1) = word16ToByteString 25 namedCurveToByteString (NamedCurveRaw nc) = word16ToByteString nc
YoshikuniJujo/forest
subprojects/tls-analysis/client/Parts.hs
bsd-3-clause
5,566
28
11
710
1,370
732
638
140
12
module Sim where import qualified Dummy as D import Message import Node import RoutingData import Utils import qualified Data.HashMap.Strict as HM import qualified Data.Text as T import Data.Time.Clock import System.Random idBits :: Int idBits = 10 idRange :: (Int, Int) idRange = (0, (2 ^ idBits) - 1) data Sim = Sim { nodes :: HM.HashMap IPInfo Node , queue :: [Message] , gen :: StdGen } testNode :: ID -> ID -> UTCTime -> Node testNode ours theirs now = Node { nPort = 0 , nIP = ours , nNodeID = ours , nTree = Leaf [theirs] , nStore = HM.empty , nFindValueQueries = HM.empty , nFindNodeQueries = HM.empty , nIncoming = [] , nOutgoing = [] , nPendingStores = [] , nPendingFinds = [] , nLastSeen = HM.fromList [(theirs, now)] , nLastSent = HM.empty , nNodeInfos = HM.fromList [(theirs, (theirs, 0))] , nPrintBuffer = [] } intToID :: Int -> ID intToID i = zeroPad idBits $ decToBitString i randLog :: (Random a, Show a) => String -> (a, a) -> IO a randLog logMe r@(lo, hi) = do putStrLn $ "Generating " ++ logMe ++ " between " ++ (show lo) ++ " - " ++ (show hi) getStdRandom $ randomR r getNode :: Int -> [Node] -> Node getNode i nodes = case get nodes i of Nothing -> error $ "Node list no index " ++ (show i) Just node -> node initNodes :: Int -> Int -> UTCTime -> HM.HashMap ID Node initNodes i1 i2 now = HM.fromList [(aID, nodeA), (bID, nodeB)] where aID = intToID i1 bID = intToID i2 nodeA = testNode aID bID now nodeB = testNode bID aID now execute :: Node -> Node execute node = node start :: StdGen -> IO () start gen = do now <- getCurrentTime setStdGen gen id1 <- randLog "node A ID" idRange id2 <- randLog "node B ID" idRange let nodes = initNodes id1 id2 now run nodes [] [] HM.empty data Command = Put { key :: ID , value :: T.Text , triggered :: UTCTime , success :: Bool } | Get { key :: ID , triggered :: UTCTime , success :: Bool } run :: HM.HashMap ID Node -- ^ ID -> Node with that ID -> [Message] -- ^ Message queue between nodes -> [Command] -- ^ Commands sent -> HM.HashMap ID T.Text -- ^ Reference hashmap (DHT map should emulate this) -> IO () run nodes messages commands refStore = do putStrLn "sup"
semaj/hademlia
src/Sim.hs
bsd-3-clause
2,990
0
12
1,281
846
468
378
74
2
module Language.C.Syntax.BinaryInstances where import Data.Binary import Language.C.Syntax.AST import Language.C.Syntax.Constants import Language.C.Syntax.Ops import Language.C.Syntax.ManualBinaryInstances instance (Binary a) => Binary (Language.C.Syntax.AST.CTranslationUnit a) where put (CTranslUnit a b) = put a >> put b get = get >>= \a -> get >>= \b -> return (CTranslUnit a b) instance (Binary a) => Binary (Language.C.Syntax.AST.CExternalDeclaration a) where put (CDeclExt a) = putWord8 0 >> put a put (CFDefExt a) = putWord8 1 >> put a put (CAsmExt a b) = putWord8 2 >> put a >> put b get = do tag_ <- getWord8 case tag_ of 0 -> get >>= \a -> return (CDeclExt a) 1 -> get >>= \a -> return (CFDefExt a) 2 -> get >>= \a -> get >>= \b -> return (CAsmExt a b) _ -> fail "no parse" instance (Binary a) => Binary (Language.C.Syntax.AST.CFunctionDef a) where put (CFunDef a b c d e) = put a >> put b >> put c >> put d >> put e get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> get >>= \e -> return (CFunDef a b c d e) instance (Binary a) => Binary (Language.C.Syntax.AST.CDeclaration a) where put (CDecl a b c) = put a >> put b >> put c get = get >>= \a -> get >>= \b -> get >>= \c -> return (CDecl a b c) instance (Binary a) => Binary (Language.C.Syntax.AST.CStructureUnion a) where put (CStruct a b c d e) = put a >> put b >> put c >> put d >> put e get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> get >>= \e -> return (CStruct a b c d e) instance Binary Language.C.Syntax.AST.CStructTag where put CStructTag = putWord8 0 put CUnionTag = putWord8 1 get = do tag_ <- getWord8 case tag_ of 0 -> return CStructTag 1 -> return CUnionTag _ -> fail "no parse" instance (Binary a) => Binary (Language.C.Syntax.AST.CEnumeration a) where put (CEnum a b c d) = put a >> put b >> put c >> put d get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CEnum a b c d) instance (Binary a) => Binary (Language.C.Syntax.AST.CDeclarationSpecifier a) where put (CStorageSpec a) = putWord8 0 >> put a put (CTypeSpec a) = putWord8 1 >> put a put (CTypeQual a) = putWord8 2 >> put a get = do tag_ <- getWord8 case tag_ of 0 -> get >>= \a -> return (CStorageSpec a) 1 -> get >>= \a -> return (CTypeSpec a) 2 -> get >>= \a -> return (CTypeQual a) _ -> fail "no parse" instance (Binary a) => Binary (Language.C.Syntax.AST.CStorageSpecifier a) where put (CAuto a) = putWord8 0 >> put a put (CRegister a) = putWord8 1 >> put a put (CStatic a) = putWord8 2 >> put a put (CExtern a) = putWord8 3 >> put a put (CTypedef a) = putWord8 4 >> put a put (CThread a) = putWord8 5 >> put a get = do tag_ <- getWord8 case tag_ of 0 -> get >>= \a -> return (CAuto a) 1 -> get >>= \a -> return (CRegister a) 2 -> get >>= \a -> return (CStatic a) 3 -> get >>= \a -> return (CExtern a) 4 -> get >>= \a -> return (CTypedef a) 5 -> get >>= \a -> return (CThread a) _ -> fail "no parse" instance (Binary a) => Binary (Language.C.Syntax.AST.CTypeSpecifier a) where put (CVoidType a) = putWord8 0 >> put a put (CCharType a) = putWord8 1 >> put a put (CShortType a) = putWord8 2 >> put a put (CIntType a) = putWord8 3 >> put a put (CLongType a) = putWord8 4 >> put a put (CFloatType a) = putWord8 5 >> put a put (CDoubleType a) = putWord8 6 >> put a put (CSignedType a) = putWord8 7 >> put a put (CUnsigType a) = putWord8 8 >> put a put (CBoolType a) = putWord8 9 >> put a put (CComplexType a) = putWord8 10 >> put a put (CSUType a b) = putWord8 11 >> put a >> put b put (CEnumType a b) = putWord8 12 >> put a >> put b put (CTypeDef a b) = putWord8 13 >> put a >> put b put (CTypeOfExpr a b) = putWord8 14 >> put a >> put b put (CTypeOfType a b) = putWord8 15 >> put a >> put b get = do tag_ <- getWord8 case tag_ of 0 -> get >>= \a -> return (CVoidType a) 1 -> get >>= \a -> return (CCharType a) 2 -> get >>= \a -> return (CShortType a) 3 -> get >>= \a -> return (CIntType a) 4 -> get >>= \a -> return (CLongType a) 5 -> get >>= \a -> return (CFloatType a) 6 -> get >>= \a -> return (CDoubleType a) 7 -> get >>= \a -> return (CSignedType a) 8 -> get >>= \a -> return (CUnsigType a) 9 -> get >>= \a -> return (CBoolType a) 10 -> get >>= \a -> return (CComplexType a) 11 -> get >>= \a -> get >>= \b -> return (CSUType a b) 12 -> get >>= \a -> get >>= \b -> return (CEnumType a b) 13 -> get >>= \a -> get >>= \b -> return (CTypeDef a b) 14 -> get >>= \a -> get >>= \b -> return (CTypeOfExpr a b) 15 -> get >>= \a -> get >>= \b -> return (CTypeOfType a b) _ -> fail "no parse" instance (Binary a) => Binary (Language.C.Syntax.AST.CTypeQualifier a) where put (CConstQual a) = putWord8 0 >> put a put (CVolatQual a) = putWord8 1 >> put a put (CRestrQual a) = putWord8 2 >> put a put (CInlineQual a) = putWord8 3 >> put a put (CAttrQual a) = putWord8 4 >> put a get = do tag_ <- getWord8 case tag_ of 0 -> get >>= \a -> return (CConstQual a) 1 -> get >>= \a -> return (CVolatQual a) 2 -> get >>= \a -> return (CRestrQual a) 3 -> get >>= \a -> return (CInlineQual a) 4 -> get >>= \a -> return (CAttrQual a) _ -> fail "no parse" instance (Binary a) => Binary (Language.C.Syntax.AST.CAttribute a) where put (CAttr a b c) = put a >> put b >> put c get = get >>= \a -> get >>= \b -> get >>= \c -> return (CAttr a b c) instance (Binary a) => Binary (Language.C.Syntax.AST.CDeclarator a) where put (CDeclr a b c d e) = put a >> put b >> put c >> put d >> put e get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> get >>= \e -> return (CDeclr a b c d e) instance (Binary a) => Binary (Language.C.Syntax.AST.CDerivedDeclarator a) where put (CPtrDeclr a b) = putWord8 0 >> put a >> put b put (CArrDeclr a b c) = putWord8 1 >> put a >> put b >> put c put (CFunDeclr a b c) = putWord8 2 >> put a >> put b >> put c get = do tag_ <- getWord8 case tag_ of 0 -> get >>= \a -> get >>= \b -> return (CPtrDeclr a b) 1 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CArrDeclr a b c) 2 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CFunDeclr a b c) _ -> fail "no parse" instance (Binary a) => Binary (Language.C.Syntax.AST.CArraySize a) where put (CNoArrSize a) = putWord8 0 >> put a put (CArrSize a b) = putWord8 1 >> put a >> put b get = do tag_ <- getWord8 case tag_ of 0 -> get >>= \a -> return (CNoArrSize a) 1 -> get >>= \a -> get >>= \b -> return (CArrSize a b) _ -> fail "no parse" instance (Binary a) => Binary (Language.C.Syntax.AST.CInitializer a) where put (CInitExpr a b) = putWord8 0 >> put a >> put b put (CInitList a b) = putWord8 1 >> put a >> put b get = do tag_ <- getWord8 case tag_ of 0 -> get >>= \a -> get >>= \b -> return (CInitExpr a b) 1 -> get >>= \a -> get >>= \b -> return (CInitList a b) _ -> fail "no parse" instance (Binary a) => Binary (Language.C.Syntax.AST.CPartDesignator a) where put (CArrDesig a b) = putWord8 0 >> put a >> put b put (CMemberDesig a b) = putWord8 1 >> put a >> put b put (CRangeDesig a b c) = putWord8 2 >> put a >> put b >> put c get = do tag_ <- getWord8 case tag_ of 0 -> get >>= \a -> get >>= \b -> return (CArrDesig a b) 1 -> get >>= \a -> get >>= \b -> return (CMemberDesig a b) 2 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CRangeDesig a b c) _ -> fail "no parse" instance (Binary a) => Binary (Language.C.Syntax.AST.CStatement a) where put (CLabel a b c d) = putWord8 0 >> put a >> put b >> put c >> put d put (CCase a b c) = putWord8 1 >> put a >> put b >> put c put (CCases a b c d) = putWord8 2 >> put a >> put b >> put c >> put d put (CDefault a b) = putWord8 3 >> put a >> put b put (CExpr a b) = putWord8 4 >> put a >> put b put (CCompound a b c) = putWord8 5 >> put a >> put b >> put c put (CIf a b c d) = putWord8 6 >> put a >> put b >> put c >> put d put (CSwitch a b c) = putWord8 7 >> put a >> put b >> put c put (CWhile a b c d) = putWord8 8 >> put a >> put b >> put c >> put d put (CFor a b c d e) = putWord8 9 >> put a >> put b >> put c >> put d >> put e put (CGoto a b) = putWord8 10 >> put a >> put b put (CGotoPtr a b) = putWord8 11 >> put a >> put b put (CCont a) = putWord8 12 >> put a put (CBreak a) = putWord8 13 >> put a put (CReturn a b) = putWord8 14 >> put a >> put b put (CAsm a b) = putWord8 15 >> put a >> put b get = do tag_ <- getWord8 case tag_ of 0 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CLabel a b c d) 1 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CCase a b c) 2 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CCases a b c d) 3 -> get >>= \a -> get >>= \b -> return (CDefault a b) 4 -> get >>= \a -> get >>= \b -> return (CExpr a b) 5 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CCompound a b c) 6 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CIf a b c d) 7 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CSwitch a b c) 8 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CWhile a b c d) 9 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> get >>= \e -> return (CFor a b c d e) 10 -> get >>= \a -> get >>= \b -> return (CGoto a b) 11 -> get >>= \a -> get >>= \b -> return (CGotoPtr a b) 12 -> get >>= \a -> return (CCont a) 13 -> get >>= \a -> return (CBreak a) 14 -> get >>= \a -> get >>= \b -> return (CReturn a b) 15 -> get >>= \a -> get >>= \b -> return (CAsm a b) _ -> fail "no parse" instance (Binary a) => Binary (Language.C.Syntax.AST.CCompoundBlockItem a) where put (CBlockStmt a) = putWord8 0 >> put a put (CBlockDecl a) = putWord8 1 >> put a put (CNestedFunDef a) = putWord8 2 >> put a get = do tag_ <- getWord8 case tag_ of 0 -> get >>= \a -> return (CBlockStmt a) 1 -> get >>= \a -> return (CBlockDecl a) 2 -> get >>= \a -> return (CNestedFunDef a) _ -> fail "no parse" instance (Binary a) => Binary (Language.C.Syntax.AST.CAssemblyStatement a) where put (CAsmStmt a b c d e f) = put a >> put b >> put c >> put d >> put e >> put f get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> get >>= \e -> get >>= \f -> return (CAsmStmt a b c d e f) instance (Binary a) => Binary (Language.C.Syntax.AST.CAssemblyOperand a) where put (CAsmOperand a b c d) = put a >> put b >> put c >> put d get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CAsmOperand a b c d) instance (Binary a) => Binary (Language.C.Syntax.AST.CExpression a) where put (CComma a b) = putWord8 0 >> put a >> put b put (CAssign a b c d) = putWord8 1 >> put a >> put b >> put c >> put d put (CCond a b c d) = putWord8 2 >> put a >> put b >> put c >> put d put (CBinary a b c d) = putWord8 3 >> put a >> put b >> put c >> put d put (CCast a b c) = putWord8 4 >> put a >> put b >> put c put (CUnary a b c) = putWord8 5 >> put a >> put b >> put c put (CSizeofExpr a b) = putWord8 6 >> put a >> put b put (CSizeofType a b) = putWord8 7 >> put a >> put b put (CAlignofExpr a b) = putWord8 8 >> put a >> put b put (CAlignofType a b) = putWord8 9 >> put a >> put b put (CComplexReal a b) = putWord8 10 >> put a >> put b put (CComplexImag a b) = putWord8 11 >> put a >> put b put (CIndex a b c) = putWord8 12 >> put a >> put b >> put c put (CCall a b c) = putWord8 13 >> put a >> put b >> put c put (CMember a b c d) = putWord8 14 >> put a >> put b >> put c >> put d put (CVar a b) = putWord8 15 >> put a >> put b put (CConst a) = putWord8 16 >> put a put (CCompoundLit a b c) = putWord8 17 >> put a >> put b >> put c put (CStatExpr a b) = putWord8 18 >> put a >> put b put (CLabAddrExpr a b) = putWord8 19 >> put a >> put b put (CBuiltinExpr a) = putWord8 20 >> put a get = do tag_ <- getWord8 case tag_ of 0 -> get >>= \a -> get >>= \b -> return (CComma a b) 1 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CAssign a b c d) 2 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CCond a b c d) 3 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CBinary a b c d) 4 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CCast a b c) 5 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CUnary a b c) 6 -> get >>= \a -> get >>= \b -> return (CSizeofExpr a b) 7 -> get >>= \a -> get >>= \b -> return (CSizeofType a b) 8 -> get >>= \a -> get >>= \b -> return (CAlignofExpr a b) 9 -> get >>= \a -> get >>= \b -> return (CAlignofType a b) 10 -> get >>= \a -> get >>= \b -> return (CComplexReal a b) 11 -> get >>= \a -> get >>= \b -> return (CComplexImag a b) 12 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CIndex a b c) 13 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CCall a b c) 14 -> get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (CMember a b c d) 15 -> get >>= \a -> get >>= \b -> return (CVar a b) 16 -> get >>= \a -> return (CConst a) 17 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CCompoundLit a b c) 18 -> get >>= \a -> get >>= \b -> return (CStatExpr a b) 19 -> get >>= \a -> get >>= \b -> return (CLabAddrExpr a b) 20 -> get >>= \a -> return (CBuiltinExpr a) _ -> fail "no parse" instance Binary Language.C.Syntax.Ops.CAssignOp where put CAssignOp = putWord8 0 put CMulAssOp = putWord8 1 put CDivAssOp = putWord8 2 put CRmdAssOp = putWord8 3 put CAddAssOp = putWord8 4 put CSubAssOp = putWord8 5 put CShlAssOp = putWord8 6 put CShrAssOp = putWord8 7 put CAndAssOp = putWord8 8 put CXorAssOp = putWord8 9 put COrAssOp = putWord8 10 get = do tag_ <- getWord8 case tag_ of 0 -> return CAssignOp 1 -> return CMulAssOp 2 -> return CDivAssOp 3 -> return CRmdAssOp 4 -> return CAddAssOp 5 -> return CSubAssOp 6 -> return CShlAssOp 7 -> return CShrAssOp 8 -> return CAndAssOp 9 -> return CXorAssOp 10 -> return COrAssOp _ -> fail "no parse" instance Binary Language.C.Syntax.Ops.CBinaryOp where put CMulOp = putWord8 0 put CDivOp = putWord8 1 put CRmdOp = putWord8 2 put CAddOp = putWord8 3 put CSubOp = putWord8 4 put CShlOp = putWord8 5 put CShrOp = putWord8 6 put CLeOp = putWord8 7 put CGrOp = putWord8 8 put CLeqOp = putWord8 9 put CGeqOp = putWord8 10 put CEqOp = putWord8 11 put CNeqOp = putWord8 12 put CAndOp = putWord8 13 put CXorOp = putWord8 14 put COrOp = putWord8 15 put CLndOp = putWord8 16 put CLorOp = putWord8 17 get = do tag_ <- getWord8 case tag_ of 0 -> return CMulOp 1 -> return CDivOp 2 -> return CRmdOp 3 -> return CAddOp 4 -> return CSubOp 5 -> return CShlOp 6 -> return CShrOp 7 -> return CLeOp 8 -> return CGrOp 9 -> return CLeqOp 10 -> return CGeqOp 11 -> return CEqOp 12 -> return CNeqOp 13 -> return CAndOp 14 -> return CXorOp 15 -> return COrOp 16 -> return CLndOp 17 -> return CLorOp _ -> fail "no parse" instance Binary Language.C.Syntax.Ops.CUnaryOp where put CPreIncOp = putWord8 0 put CPreDecOp = putWord8 1 put CPostIncOp = putWord8 2 put CPostDecOp = putWord8 3 put CAdrOp = putWord8 4 put CIndOp = putWord8 5 put CPlusOp = putWord8 6 put CMinOp = putWord8 7 put CCompOp = putWord8 8 put CNegOp = putWord8 9 get = do tag_ <- getWord8 case tag_ of 0 -> return CPreIncOp 1 -> return CPreDecOp 2 -> return CPostIncOp 3 -> return CPostDecOp 4 -> return CAdrOp 5 -> return CIndOp 6 -> return CPlusOp 7 -> return CMinOp 8 -> return CCompOp 9 -> return CNegOp _ -> fail "no parse" instance (Binary a) => Binary (Language.C.Syntax.AST.CBuiltinThing a) where put (CBuiltinVaArg a b c) = putWord8 0 >> put a >> put b >> put c put (CBuiltinOffsetOf a b c) = putWord8 1 >> put a >> put b >> put c put (CBuiltinTypesCompatible a b c) = putWord8 2 >> put a >> put b >> put c get = do tag_ <- getWord8 case tag_ of 0 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CBuiltinVaArg a b c) 1 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CBuiltinOffsetOf a b c) 2 -> get >>= \a -> get >>= \b -> get >>= \c -> return (CBuiltinTypesCompatible a b c) _ -> fail "no parse" instance (Binary a) => Binary (Language.C.Syntax.AST.CConstant a) where put (CIntConst a b) = putWord8 0 >> put a >> put b put (CCharConst a b) = putWord8 1 >> put a >> put b put (CFloatConst a b) = putWord8 2 >> put a >> put b put (CStrConst a b) = putWord8 3 >> put a >> put b get = do tag_ <- getWord8 case tag_ of 0 -> get >>= \a -> get >>= \b -> return (CIntConst a b) 1 -> get >>= \a -> get >>= \b -> return (CCharConst a b) 2 -> get >>= \a -> get >>= \b -> return (CFloatConst a b) 3 -> get >>= \a -> get >>= \b -> return (CStrConst a b) _ -> fail "no parse" instance (Binary a) => Binary (Language.C.Syntax.AST.CStringLiteral a) where put (CStrLit a b) = put a >> put b get = get >>= \a -> get >>= \b -> return (CStrLit a b)
atomb/language-c-binary
Language/C/Syntax/BinaryInstances.hs
bsd-3-clause
17,644
0
23
5,071
9,149
4,488
4,661
388
0
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.NV.ViewportSwizzle -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.NV.ViewportSwizzle ( -- * Extension Support glGetNVViewportSwizzle, gl_NV_viewport_swizzle, -- * Enums pattern GL_VIEWPORT_SWIZZLE_NEGATIVE_W_NV, pattern GL_VIEWPORT_SWIZZLE_NEGATIVE_X_NV, pattern GL_VIEWPORT_SWIZZLE_NEGATIVE_Y_NV, pattern GL_VIEWPORT_SWIZZLE_NEGATIVE_Z_NV, pattern GL_VIEWPORT_SWIZZLE_POSITIVE_W_NV, pattern GL_VIEWPORT_SWIZZLE_POSITIVE_X_NV, pattern GL_VIEWPORT_SWIZZLE_POSITIVE_Y_NV, pattern GL_VIEWPORT_SWIZZLE_POSITIVE_Z_NV, pattern GL_VIEWPORT_SWIZZLE_W_NV, pattern GL_VIEWPORT_SWIZZLE_X_NV, pattern GL_VIEWPORT_SWIZZLE_Y_NV, pattern GL_VIEWPORT_SWIZZLE_Z_NV, -- * Functions glViewportSwizzleNV ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
haskell-opengl/OpenGLRaw
src/Graphics/GL/NV/ViewportSwizzle.hs
bsd-3-clause
1,196
0
5
145
112
76
36
20
0
module Main where import Run main :: IO () main = runMain
nejla/auth-service
service/app/Main.hs
bsd-3-clause
60
0
6
14
22
13
9
4
1
{-# LANGUAGE RankNTypes #-} module Abstract.Interfaces.Stack.Push ( StackPush (..), push, pushBatch, stackToPush ) where import qualified Abstract.Interfaces.Stack as S data StackPush m t = StackPush { _sPush :: S.Stack m t } stackToPush :: S.Stack m t -> StackPush m t stackToPush s = StackPush { _sPush = s } push :: (Monad m) => forall t. StackPush m t -> t -> m () push (StackPush s') t = S.push s' t pushBatch :: (Monad m) => forall t. StackPush m t -> [t] -> m () pushBatch (StackPush s') ts = S.pushBatch s' ts
adarqui/Abstract-Interfaces
src/Abstract/Interfaces/Stack/Push.hs
bsd-3-clause
533
0
10
111
220
121
99
15
1
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple -- Copyright : Isaac Jones 2003-2005 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This is the command line front end to the Simple build system. When given -- the parsed command-line args and package information, is able to perform -- basic commands like configure, build, install, register, etc. -- -- This module exports the main functions that Setup.hs scripts use. It -- re-exports the 'UserHooks' type, the standard entry points like -- 'defaultMain' and 'defaultMainWithHooks' and the predefined sets of -- 'UserHooks' that custom @Setup.hs@ scripts can extend to add their own -- behaviour. -- -- This module isn't called \"Simple\" because it's simple. Far from -- it. It's called \"Simple\" because it does complicated things to -- simple software. -- -- The original idea was that there could be different build systems that all -- presented the same compatible command line interfaces. There is still a -- "Distribution.Make" system but in practice no packages use it. {- 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. -} {- Work around this warning: libraries/Cabal/Distribution/Simple.hs:78:0: Warning: In the use of `runTests' (imported from Distribution.Simple.UserHooks): Deprecated: "Please use the new testing interface instead!" -} {-# OPTIONS_GHC -fno-warn-deprecations #-} module Distribution.Simple ( module Distribution.Package, module Distribution.Version, module Distribution.License, module Distribution.Simple.Compiler, module Language.Haskell.Extension, -- * Simple interface defaultMain, defaultMainNoRead, defaultMainArgs, -- * Customization UserHooks(..), Args, defaultMainWithHooks, defaultMainWithHooksArgs, -- ** Standard sets of hooks simpleUserHooks, autoconfUserHooks, emptyUserHooks, -- ** Utils defaultHookedPackageDesc ) where -- local import Distribution.Simple.Compiler hiding (Flag) import Distribution.Simple.UserHooks import Distribution.Package --must not specify imports, since we're exporting moule. import Distribution.PackageDescription ( PackageDescription(..), GenericPackageDescription, Executable(..) , updatePackageDescription, hasLibs , HookedBuildInfo, emptyHookedBuildInfo ) import Distribution.PackageDescription.Parse ( readPackageDescription, readHookedBuildInfo ) import Distribution.PackageDescription.Configuration ( flattenPackageDescription ) import Distribution.Simple.Program ( defaultProgramConfiguration, addKnownPrograms, builtinPrograms , restoreProgramConfiguration, reconfigurePrograms ) import Distribution.Simple.PreProcess (knownSuffixHandlers, PPSuffixHandler) import Distribution.Simple.Setup import Distribution.Simple.Command import Distribution.Simple.Build ( build ) import Distribution.Simple.SrcDist ( sdist ) import Distribution.Simple.Register ( register, unregister ) import Distribution.Simple.Configure ( getPersistBuildConfig, maybeGetPersistBuildConfig , writePersistBuildConfig, checkPersistBuildConfigOutdated , configure, checkForeignDeps ) import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..) ) import Distribution.Simple.Bench (bench) import Distribution.Simple.BuildPaths ( srcPref) import Distribution.Simple.Test (test) import Distribution.Simple.Install (install) import Distribution.Simple.Haddock (haddock, hscolour) import Distribution.Simple.Utils (die, notice, info, setupMessage, chattyTry, defaultPackageDesc, defaultHookedPackageDesc, rawSystemExitWithEnv, factionVersion, topHandler ) import Distribution.System ( OS(..), buildOS ) import Distribution.Verbosity import Language.Haskell.Extension import Distribution.Version import Distribution.License import Distribution.Text ( display ) -- Base import System.Environment(getArgs, getProgName, getEnvironment) import System.Directory(removeFile, doesFileExist, doesDirectoryExist, removeDirectoryRecursive) import System.Exit import System.IO.Error (isDoesNotExistError) import Distribution.Compat.Exception (catchIO, throwIOIO) import Control.Monad (when) import Data.List (intersperse, unionBy, nub, (\\)) -- | A simple implementation of @main@ for a Faction setup script. -- It reads the package description file using IO, and performs the -- action specified on the command line. defaultMain :: IO () defaultMain = getArgs >>= defaultMainHelper simpleUserHooks -- | A version of 'defaultMain' that is passed the command line -- arguments, rather than getting them from the environment. defaultMainArgs :: [String] -> IO () defaultMainArgs = defaultMainHelper simpleUserHooks -- | A customizable version of 'defaultMain'. defaultMainWithHooks :: UserHooks -> IO () defaultMainWithHooks hooks = getArgs >>= defaultMainHelper hooks -- | A customizable version of 'defaultMain' that also takes the command -- line arguments. defaultMainWithHooksArgs :: UserHooks -> [String] -> IO () defaultMainWithHooksArgs = defaultMainHelper -- | Like 'defaultMain', but accepts the package description as input -- rather than using IO to read it. defaultMainNoRead :: GenericPackageDescription -> IO () defaultMainNoRead pkg_descr = getArgs >>= defaultMainHelper simpleUserHooks { readDesc = return (Just pkg_descr) } defaultMainHelper :: UserHooks -> Args -> IO () defaultMainHelper hooks args = topHandler $ case commandsRun globalCommand commands args of CommandHelp help -> printHelp help CommandList opts -> printOptionsList opts CommandErrors errs -> printErrors errs CommandReadyToGo (flags, commandParse) -> case commandParse of _ | fromFlag (globalVersion flags) -> printVersion | fromFlag (globalNumericVersion flags) -> printNumericVersion CommandHelp help -> printHelp help CommandList opts -> printOptionsList opts CommandErrors errs -> printErrors errs CommandReadyToGo action -> action where printHelp help = getProgName >>= putStr . help printOptionsList = putStr . unlines printErrors errs = do putStr (concat (intersperse "\n" errs)) exitWith (ExitFailure 1) printNumericVersion = putStrLn $ display factionVersion printVersion = putStrLn $ "Faction library version " ++ display factionVersion progs = addKnownPrograms (hookedPrograms hooks) defaultProgramConfiguration commands = [configureCommand progs `commandAddAction` \fs as -> configureAction hooks fs as >> return () ,buildCommand progs `commandAddAction` buildAction hooks ,installCommand `commandAddAction` installAction hooks ,copyCommand `commandAddAction` copyAction hooks ,haddockCommand `commandAddAction` haddockAction hooks ,cleanCommand `commandAddAction` cleanAction hooks ,sdistCommand `commandAddAction` sdistAction hooks ,hscolourCommand `commandAddAction` hscolourAction hooks ,registerCommand `commandAddAction` registerAction hooks ,unregisterCommand `commandAddAction` unregisterAction hooks ,testCommand `commandAddAction` testAction hooks ,benchmarkCommand `commandAddAction` benchAction hooks ] -- | Combine the preprocessors in the given hooks with the -- preprocessors built into faction. allSuffixHandlers :: UserHooks -> [PPSuffixHandler] allSuffixHandlers hooks = overridesPP (hookedPreProcessors hooks) knownSuffixHandlers where overridesPP :: [PPSuffixHandler] -> [PPSuffixHandler] -> [PPSuffixHandler] overridesPP = unionBy (\x y -> fst x == fst y) configureAction :: UserHooks -> ConfigFlags -> Args -> IO LocalBuildInfo configureAction hooks flags args = do let distPref = fromFlag $ configDistPref flags pbi <- preConf hooks args flags (mb_pd_file, pkg_descr0) <- confPkgDescr -- get_pkg_descr (configVerbosity flags') --let pkg_descr = updatePackageDescription pbi pkg_descr0 let epkg_descr = (pkg_descr0, pbi) --(warns, ers) <- sanityCheckPackage pkg_descr --errorOut (configVerbosity flags') warns ers localbuildinfo0 <- confHook hooks epkg_descr flags -- remember the .faction filename if we know it -- and all the extra command line args let localbuildinfo = localbuildinfo0 { pkgDescrFile = mb_pd_file, extraConfigArgs = args } writePersistBuildConfig distPref localbuildinfo let pkg_descr = localPkgDescr localbuildinfo postConf hooks args flags pkg_descr localbuildinfo return localbuildinfo where verbosity = fromFlag (configVerbosity flags) confPkgDescr :: IO (Maybe FilePath, GenericPackageDescription) confPkgDescr = do mdescr <- readDesc hooks case mdescr of Just descr -> return (Nothing, descr) Nothing -> do pdfile <- defaultPackageDesc verbosity descr <- readPackageDescription verbosity pdfile return (Just pdfile, descr) buildAction :: UserHooks -> BuildFlags -> Args -> IO () buildAction hooks flags args = do let distPref = fromFlag $ buildDistPref flags verbosity = fromFlag $ buildVerbosity flags lbi <- getBuildConfig hooks verbosity distPref progs <- reconfigurePrograms verbosity (buildProgramPaths flags) (buildProgramArgs flags) (withPrograms lbi) hookedAction preBuild buildHook postBuild (return lbi { withPrograms = progs }) hooks flags args hscolourAction :: UserHooks -> HscolourFlags -> Args -> IO () hscolourAction hooks flags args = do let distPref = fromFlag $ hscolourDistPref flags verbosity = fromFlag $ hscolourVerbosity flags hookedAction preHscolour hscolourHook postHscolour (getBuildConfig hooks verbosity distPref) hooks flags args haddockAction :: UserHooks -> HaddockFlags -> Args -> IO () haddockAction hooks flags args = do let distPref = fromFlag $ haddockDistPref flags verbosity = fromFlag $ haddockVerbosity flags lbi <- getBuildConfig hooks verbosity distPref progs <- reconfigurePrograms verbosity (haddockProgramPaths flags) (haddockProgramArgs flags) (withPrograms lbi) hookedAction preHaddock haddockHook postHaddock (return lbi { withPrograms = progs }) hooks flags args cleanAction :: UserHooks -> CleanFlags -> Args -> IO () cleanAction hooks flags args = do pbi <- preClean hooks args flags pdfile <- defaultPackageDesc verbosity ppd <- readPackageDescription verbosity pdfile let pkg_descr0 = flattenPackageDescription ppd -- We don't sanity check for clean as an error -- here would prevent cleaning: --sanityCheckHookedBuildInfo pkg_descr0 pbi let pkg_descr = updatePackageDescription pbi pkg_descr0 cleanHook hooks pkg_descr () hooks flags postClean hooks args flags pkg_descr () where verbosity = fromFlag (cleanVerbosity flags) copyAction :: UserHooks -> CopyFlags -> Args -> IO () copyAction hooks flags args = do let distPref = fromFlag $ copyDistPref flags verbosity = fromFlag $ copyVerbosity flags hookedAction preCopy copyHook postCopy (getBuildConfig hooks verbosity distPref) hooks flags args installAction :: UserHooks -> InstallFlags -> Args -> IO () installAction hooks flags args = do let distPref = fromFlag $ installDistPref flags verbosity = fromFlag $ installVerbosity flags hookedAction preInst instHook postInst (getBuildConfig hooks verbosity distPref) hooks flags args sdistAction :: UserHooks -> SDistFlags -> Args -> IO () sdistAction hooks flags args = do let distPref = fromFlag $ sDistDistPref flags pbi <- preSDist hooks args flags mlbi <- maybeGetPersistBuildConfig distPref pdfile <- defaultPackageDesc verbosity ppd <- readPackageDescription verbosity pdfile let pkg_descr0 = flattenPackageDescription ppd sanityCheckHookedBuildInfo pkg_descr0 pbi let pkg_descr = updatePackageDescription pbi pkg_descr0 sDistHook hooks pkg_descr mlbi hooks flags postSDist hooks args flags pkg_descr mlbi where verbosity = fromFlag (sDistVerbosity flags) testAction :: UserHooks -> TestFlags -> Args -> IO () testAction hooks flags args = do let distPref = fromFlag $ testDistPref flags verbosity = fromFlag $ testVerbosity flags localBuildInfo <- getBuildConfig hooks verbosity distPref let pkg_descr = localPkgDescr localBuildInfo -- It is safe to do 'runTests' before the new test handler because the -- default action is a no-op and if the package uses the old test interface -- the new handler will find no tests. runTests hooks args False pkg_descr localBuildInfo --FIXME: this is a hack, passing the args inside the flags -- it's because the args to not get passed to the main test hook let flags' = flags { testList = Flag args } hookedAction preTest testHook postTest (getBuildConfig hooks verbosity distPref) hooks flags' args benchAction :: UserHooks -> BenchmarkFlags -> Args -> IO () benchAction hooks flags args = do let distPref = fromFlag $ benchmarkDistPref flags verbosity = fromFlag $ benchmarkVerbosity flags hookedActionWithArgs preBench benchHook postBench (getBuildConfig hooks verbosity distPref) hooks flags args registerAction :: UserHooks -> RegisterFlags -> Args -> IO () registerAction hooks flags args = do let distPref = fromFlag $ regDistPref flags verbosity = fromFlag $ regVerbosity flags hookedAction preReg regHook postReg (getBuildConfig hooks verbosity distPref) hooks flags args unregisterAction :: UserHooks -> RegisterFlags -> Args -> IO () unregisterAction hooks flags args = do let distPref = fromFlag $ regDistPref flags verbosity = fromFlag $ regVerbosity flags hookedAction preUnreg unregHook postUnreg (getBuildConfig hooks verbosity distPref) hooks flags args hookedAction :: (UserHooks -> Args -> flags -> IO HookedBuildInfo) -> (UserHooks -> PackageDescription -> LocalBuildInfo -> UserHooks -> flags -> IO ()) -> (UserHooks -> Args -> flags -> PackageDescription -> LocalBuildInfo -> IO ()) -> IO LocalBuildInfo -> UserHooks -> flags -> Args -> IO () hookedAction pre_hook cmd_hook = hookedActionWithArgs pre_hook (\h _ pd lbi uh flags -> cmd_hook h pd lbi uh flags) hookedActionWithArgs :: (UserHooks -> Args -> flags -> IO HookedBuildInfo) -> (UserHooks -> Args -> PackageDescription -> LocalBuildInfo -> UserHooks -> flags -> IO ()) -> (UserHooks -> Args -> flags -> PackageDescription -> LocalBuildInfo -> IO ()) -> IO LocalBuildInfo -> UserHooks -> flags -> Args -> IO () hookedActionWithArgs pre_hook cmd_hook post_hook get_build_config hooks flags args = do pbi <- pre_hook hooks args flags localbuildinfo <- get_build_config let pkg_descr0 = localPkgDescr localbuildinfo --pkg_descr0 <- get_pkg_descr (get_verbose flags) sanityCheckHookedBuildInfo pkg_descr0 pbi let pkg_descr = updatePackageDescription pbi pkg_descr0 -- TODO: should we write the modified package descr back to the -- localbuildinfo? cmd_hook hooks args pkg_descr localbuildinfo hooks flags post_hook hooks args flags pkg_descr localbuildinfo sanityCheckHookedBuildInfo :: PackageDescription -> HookedBuildInfo -> IO () sanityCheckHookedBuildInfo PackageDescription { library = Nothing } (Just _,_) = die $ "The buildinfo contains info for a library, " ++ "but the package does not have a library." sanityCheckHookedBuildInfo pkg_descr (_, hookExes) | not (null nonExistant) = die $ "The buildinfo contains info for an executable called '" ++ head nonExistant ++ "' but the package does not have a " ++ "executable with that name." where pkgExeNames = nub (map exeName (executables pkg_descr)) hookExeNames = nub (map fst hookExes) nonExistant = hookExeNames \\ pkgExeNames sanityCheckHookedBuildInfo _ _ = return () getBuildConfig :: UserHooks -> Verbosity -> FilePath -> IO LocalBuildInfo getBuildConfig hooks verbosity distPref = do lbi_wo_programs <- getPersistBuildConfig distPref -- Restore info about unconfigured programs, since it is not serialized let lbi = lbi_wo_programs { withPrograms = restoreProgramConfiguration (builtinPrograms ++ hookedPrograms hooks) (withPrograms lbi_wo_programs) } case pkgDescrFile lbi of Nothing -> return lbi Just pkg_descr_file -> do outdated <- checkPersistBuildConfigOutdated distPref pkg_descr_file if outdated then reconfigure pkg_descr_file lbi else return lbi where reconfigure :: FilePath -> LocalBuildInfo -> IO LocalBuildInfo reconfigure pkg_descr_file lbi = do notice verbosity $ pkg_descr_file ++ " has been changed. " ++ "Re-configuring with most recently used options. " ++ "If this fails, please run configure manually.\n" let cFlags = configFlags lbi let cFlags' = cFlags { -- Since the list of unconfigured programs is not serialized, -- restore it to the same value as normally used at the beginning -- of a conigure run: configPrograms = restoreProgramConfiguration (builtinPrograms ++ hookedPrograms hooks) (configPrograms cFlags), -- Use the current, not saved verbosity level: configVerbosity = Flag verbosity } configureAction hooks cFlags' (extraConfigArgs lbi) -- -------------------------------------------------------------------------- -- Cleaning clean :: PackageDescription -> CleanFlags -> IO () clean pkg_descr flags = do let distPref = fromFlag $ cleanDistPref flags notice verbosity "cleaning..." maybeConfig <- if fromFlag (cleanSaveConf flags) then maybeGetPersistBuildConfig distPref else return Nothing -- remove the whole dist/ directory rather than tracking exactly what files -- we created in there. chattyTry "removing dist/" $ do exists <- doesDirectoryExist distPref when exists (removeDirectoryRecursive distPref) -- Any extra files the user wants to remove mapM_ removeFileOrDirectory (extraTmpFiles pkg_descr) -- If the user wanted to save the config, write it back maybe (return ()) (writePersistBuildConfig distPref) maybeConfig where removeFileOrDirectory :: FilePath -> IO () removeFileOrDirectory fname = do isDir <- doesDirectoryExist fname isFile <- doesFileExist fname if isDir then removeDirectoryRecursive fname else if isFile then removeFile fname else return () verbosity = fromFlag (cleanVerbosity flags) -- -------------------------------------------------------------------------- -- Default hooks -- | Hooks that correspond to a plain instantiation of the -- \"simple\" build system simpleUserHooks :: UserHooks simpleUserHooks = emptyUserHooks { confHook = configure, postConf = finalChecks, buildHook = defaultBuildHook, copyHook = \desc lbi _ f -> install desc lbi f, -- has correct 'copy' behavior with params testHook = defaultTestHook, benchHook = defaultBenchHook, instHook = defaultInstallHook, sDistHook = \p l h f -> sdist p l f srcPref (allSuffixHandlers h), cleanHook = \p _ _ f -> clean p f, hscolourHook = \p l h f -> hscolour p l (allSuffixHandlers h) f, haddockHook = \p l h f -> haddock p l (allSuffixHandlers h) f, regHook = defaultRegHook, unregHook = \p l _ f -> unregister p l f } where finalChecks _args flags pkg_descr lbi = checkForeignDeps distPref pkg_descr lbi (lessVerbose verbosity) where distPref = fromFlag (configDistPref flags) verbosity = fromFlag (configVerbosity flags) -- | Basic autoconf 'UserHooks': -- -- * 'postConf' runs @.\/configure@, if present. -- -- * the pre-hooks 'preBuild', 'preClean', 'preCopy', 'preInst', -- 'preReg' and 'preUnreg' read additional build information from -- /package/@.buildinfo@, if present. -- -- Thus @configure@ can use local system information to generate -- /package/@.buildinfo@ and possibly other files. autoconfUserHooks :: UserHooks autoconfUserHooks = simpleUserHooks { postConf = defaultPostConf, preBuild = readHook buildVerbosity, preClean = readHook cleanVerbosity, preCopy = readHook copyVerbosity, preInst = readHook installVerbosity, preHscolour = readHook hscolourVerbosity, preHaddock = readHook haddockVerbosity, preReg = readHook regVerbosity, preUnreg = readHook regVerbosity } where defaultPostConf :: Args -> ConfigFlags -> PackageDescription -> LocalBuildInfo -> IO () defaultPostConf args flags pkg_descr lbi = do let verbosity = fromFlag (configVerbosity flags) noExtraFlags args confExists <- doesFileExist "configure" if confExists then runConfigureScript verbosity backwardsCompatHack flags lbi else die "configure script not found." pbi <- getHookedBuildInfo verbosity sanityCheckHookedBuildInfo pkg_descr pbi let pkg_descr' = updatePackageDescription pbi pkg_descr postConf simpleUserHooks args flags pkg_descr' lbi backwardsCompatHack = False readHook :: (a -> Flag Verbosity) -> Args -> a -> IO HookedBuildInfo readHook get_verbosity a flags = do noExtraFlags a getHookedBuildInfo verbosity where verbosity = fromFlag (get_verbosity flags) runConfigureScript :: Verbosity -> Bool -> ConfigFlags -> LocalBuildInfo -> IO () runConfigureScript verbosity backwardsCompatHack flags lbi = do env <- getEnvironment let programConfig = withPrograms lbi (ccProg, ccFlags) <- configureCCompiler verbosity programConfig -- The C compiler's compilation and linker flags (e.g. -- "C compiler flags" and "Gcc Linker flags" from GHC) have already -- been merged into ccFlags, so we set both CFLAGS and LDFLAGS -- to ccFlags -- We don't try and tell configure which ld to use, as we don't have -- a way to pass its flags too let env' = appendToEnvironment ("CFLAGS", unwords ccFlags) env args' = args ++ ["--with-gcc=" ++ ccProg] handleNoWindowsSH $ rawSystemExitWithEnv verbosity "sh" args' env' where args = "configure" : configureArgs backwardsCompatHack flags appendToEnvironment (key, val) [] = [(key, val)] appendToEnvironment (key, val) (kv@(k, v) : rest) | key == k = (key, v ++ " " ++ val) : rest | otherwise = kv : appendToEnvironment (key, val) rest handleNoWindowsSH action | buildOS /= Windows = action | otherwise = action `catchIO` \ioe -> if isDoesNotExistError ioe then die notFoundMsg else throwIOIO ioe notFoundMsg = "The package has a './configure' script. This requires a " ++ "Unix compatibility toolchain such as MinGW+MSYS or Cygwin." getHookedBuildInfo :: Verbosity -> IO HookedBuildInfo getHookedBuildInfo verbosity = do maybe_infoFile <- defaultHookedPackageDesc case maybe_infoFile of Nothing -> return emptyHookedBuildInfo Just infoFile -> do info verbosity $ "Reading parameters from " ++ infoFile readHookedBuildInfo verbosity infoFile defaultTestHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> TestFlags -> IO () defaultTestHook pkg_descr localbuildinfo _ flags = test pkg_descr localbuildinfo flags defaultBenchHook :: Args -> PackageDescription -> LocalBuildInfo -> UserHooks -> BenchmarkFlags -> IO () defaultBenchHook args pkg_descr localbuildinfo _ flags = bench args pkg_descr localbuildinfo flags defaultInstallHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> InstallFlags -> IO () defaultInstallHook pkg_descr localbuildinfo _ flags = do let copyFlags = defaultCopyFlags { copyDistPref = installDistPref flags, copyDest = toFlag NoCopyDest, copyVerbosity = installVerbosity flags } install pkg_descr localbuildinfo copyFlags let registerFlags = defaultRegisterFlags { regDistPref = installDistPref flags, regInPlace = installInPlace flags, regPackageDB = installPackageDB flags, regVerbosity = installVerbosity flags } when (hasLibs pkg_descr) $ register pkg_descr localbuildinfo registerFlags defaultBuildHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> BuildFlags -> IO () defaultBuildHook pkg_descr localbuildinfo hooks flags = build pkg_descr localbuildinfo flags (allSuffixHandlers hooks) defaultRegHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> RegisterFlags -> IO () defaultRegHook pkg_descr localbuildinfo _ flags = if hasLibs pkg_descr then register pkg_descr localbuildinfo flags else setupMessage verbosity "Package contains no library to register:" (packageId pkg_descr) where verbosity = fromFlag (regVerbosity flags)
IreneKnapp/Faction
libfaction/Distribution/Simple.hs
bsd-3-clause
28,933
0
17
7,685
5,346
2,740
2,606
446
8
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE GADTs #-} {-# LANGUAGE NoRebindableSyntax #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Time.GA.Rules ( rules ) where import Data.Text (Text) import Prelude import Duckling.Dimensions.Types import Duckling.Duration.Helpers (isGrain) import Duckling.Numeral.Helpers (parseInt) import Duckling.Regex.Types import Duckling.Time.Helpers import Duckling.Types import qualified Duckling.Ordinal.Types as TOrdinal import qualified Duckling.TimeGrain.Types as TG ruleArInn :: Rule ruleArInn = Rule { name = "arú inné" , pattern = [ regex "ar(ú|u) inn(é|e)" ] , prod = \_ -> tt . cycleNth TG.Day $ - 2 } ruleNollaigNaMban :: Rule ruleNollaigNaMban = Rule { name = "Nollaig na mBan" , pattern = [ regex "(l(á|a) |an )?nollaig (bheag|na mban)" ] , prod = \_ -> tt $ monthDay 1 6 } ruleInniu :: Rule ruleInniu = Rule { name = "inniu" , pattern = [ regex "inniu" ] , prod = \_ -> tt today } ruleAnOrdinalCycleINdiaidhTime :: Rule ruleAnOrdinalCycleINdiaidhTime = Rule { name = "an <ordinal> <cycle> i ndiaidh <time>" , pattern = [ regex "an" , dimension Ordinal , dimension TimeGrain , regex "(i ndiaidh|tar (é|e)is)" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Ordinal od:Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter True grain (TOrdinal.value od - 1) td _ -> Nothing } ruleInn :: Rule ruleInn = Rule { name = "inné" , pattern = [ regex "inn(é|e)" ] , prod = \_ -> tt . cycleNth TG.Day $ - 1 } ruleLFhileBrde :: Rule ruleLFhileBrde = Rule { name = "Lá Fhéile Bríde" , pattern = [ regex "(l(á|a) )?(fh(e|é)ile|'?le) bh?r(í|i)de" ] , prod = \_ -> tt $ monthDay 2 1 } ruleLFhileVailintn :: Rule ruleLFhileVailintn = Rule { name = "Lá Fhéile Vailintín" , pattern = [ regex "(l(á|a) )?(fh(e|é)ile|'?le) vailint(í|i)n" ] , prod = \_ -> tt $ monthDay 2 14 } ruleTimeSeo :: Rule ruleTimeSeo = Rule { name = "<time> seo" , pattern = [ dimension Time , regex "seo" ] , prod = \tokens -> case tokens of (Token Time td:_) -> tt $ predNth 0 False td _ -> Nothing } ruleTimeSeoChaite :: Rule ruleTimeSeoChaite = Rule { name = "<time> seo chaite" , pattern = [ dimension Time , regex "seo ch?aite" ] , prod = \tokens -> case tokens of (Token Time td:_) -> tt $ predNth (-1) False td _ -> Nothing } ruleTimeSeoChugainn :: Rule ruleTimeSeoChugainn = Rule { name = "<time> seo chugainn" , pattern = [ Predicate isNotLatent , regex "seo (chugainn|at(a|á) ag teacht)" ] , prod = \tokens -> case tokens of (Token Time td:_) -> tt $ predNth 0 True td _ -> Nothing } ruleAmrach :: Rule ruleAmrach = Rule { name = "amárach" , pattern = [ regex "am(á|a)rach" ] , prod = \_ -> tt $ cycleNth TG.Day 1 } ruleYearLatent2 :: Rule ruleYearLatent2 = Rule { name = "year (latent)" , pattern = [ Predicate $ isIntegerBetween 2101 10000 ] , prod = \tokens -> case tokens of (token:_) -> do n <- getIntValue token tt . mkLatent $ year n _ -> Nothing } ruleOrdinalRithe :: Rule ruleOrdinalRithe = Rule { name = "<ordinal> ráithe" , pattern = [ dimension Ordinal , Predicate $ isGrain TG.Quarter ] , prod = \tokens -> case tokens of (token:_) -> do n <- getIntValue token tt . cycleNthAfter True TG.Quarter (n - 1) $ cycleNth TG.Year 0 _ -> Nothing } ruleAnnaCycleRoimhTime :: Rule ruleAnnaCycleRoimhTime = Rule { name = "(an|na) <cycle> roimh <time>" , pattern = [ regex "the" , dimension TimeGrain , regex "roimh" , dimension Time ] , prod = \tokens -> case tokens of (_:Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter False grain (-1) td _ -> Nothing } ruleCycleShin :: Rule ruleCycleShin = Rule { name = "<cycle> ó shin" , pattern = [ dimension TimeGrain , regex "(ó|o) shin" ] , prod = \tokens -> case tokens of (Token TimeGrain grain:_) -> tt . cycleNth grain $ 1 _ -> Nothing } ruleDdmm :: Rule ruleDdmm = Rule { name = "dd/mm" , pattern = [ regex "(3[01]|[12]\\d|0?[1-9])/(0?[1-9]|1[0-2])" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (m1:m2:_)):_) -> do m <- parseInt m2 d <- parseInt m1 tt $ monthDay m d _ -> Nothing } ruleIGceannCycle :: Rule ruleIGceannCycle = Rule { name = "i gceann <cycle>" , pattern = [ regex "(i|faoi) g?ch?eann" , Predicate $ isIntegerBetween 1 9999 , dimension TimeGrain ] , prod = \tokens -> case tokens of (_:Token Ordinal od:Token TimeGrain grain:_) -> tt $ cycleN True grain (TOrdinal.value od) _ -> Nothing } ruleAnCycleDeTime :: Rule ruleAnCycleDeTime = Rule { name = "an <cycle> de <time>" , pattern = [ regex "an" , dimension TimeGrain , regex "d[e']" , dimension Time ] , prod = \tokens -> case tokens of (_:Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter True grain 0 td _ -> Nothing } ruleDayofmonthordinalNamedmonth :: Rule ruleDayofmonthordinalNamedmonth = Rule { name = "<day-of-month>(ordinal) <named-month>" , pattern = [ Predicate isDOMOrdinal , Predicate isAMonth ] , prod = \tokens -> case tokens of (token:Token Time td:_) -> Token Time <$> intersectDOM td token _ -> Nothing } ruleIntersectBy :: Rule ruleIntersectBy = Rule { name = "intersect by \",\"" , pattern = [ Predicate isNotLatent , regex "," , Predicate isNotLatent ] , prod = \tokens -> case tokens of (Token Time td1:_:Token Time td2:_) -> Token Time <$> intersect td1 td2 _ -> Nothing } ruleOrdinalRitheYear :: Rule ruleOrdinalRitheYear = Rule { name = "<ordinal> ráithe <year>" , pattern = [ dimension Ordinal , Predicate $ isGrain TG.Quarter , dimension Time ] , prod = \tokens -> case tokens of (Token Ordinal od:_:Token Time td:_) -> tt $ cycleNthAfter False TG.Quarter (TOrdinal.value od - 1) td _ -> Nothing } ruleCycleInniu :: Rule ruleCycleInniu = Rule { name = "<cycle> ó inniu" , pattern = [ Predicate $ isIntegerBetween 1 9999 , dimension TimeGrain , regex "(ó|o)(n l(á|a) (at(á|a) )?)?inniu" ] , prod = \tokens -> case tokens of (token:Token TimeGrain grain:_) -> do v <- getIntValue token tt $ cycleN True grain v _ -> Nothing } ruleOrdinalCycleINdiaidhTime :: Rule ruleOrdinalCycleINdiaidhTime = Rule { name = "<ordinal> <cycle> i ndiaidh <time>" , pattern = [ dimension Ordinal , dimension TimeGrain , regex "(i ndiaidh|tar (é|e)is)" , dimension Time ] , prod = \tokens -> case tokens of (Token Ordinal od:Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter True grain (TOrdinal.value od - 1) td _ -> Nothing } ruleAnDayofmonthOrdinal :: Rule ruleAnDayofmonthOrdinal = Rule { name = "an <day-of-month> (ordinal)" , pattern = [ regex "an|na" , Predicate isDOMOrdinal ] , prod = \tokens -> case tokens of (_:token:_) -> do n <- getIntValue token tt $ dayOfMonth n _ -> Nothing } ruleIntersect :: Rule ruleIntersect = Rule { name = "intersect" , pattern = [ Predicate isNotLatent , Predicate isNotLatent ] , prod = \tokens -> case tokens of (Token Time td1:Token Time td2:_) -> Token Time <$> intersect td1 td2 _ -> Nothing } ruleAnOrdinalCycleDeTime :: Rule ruleAnOrdinalCycleDeTime = Rule { name = "an <ordinal> <cycle> de <time>" , pattern = [ regex "an" , dimension Ordinal , dimension TimeGrain , regex "d[e']" , dimension Time ] , prod = \tokens -> case tokens of (_:Token Ordinal od:Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter True grain (TOrdinal.value od - 1) td _ -> Nothing } ruleLNaNaithreacha :: Rule ruleLNaNaithreacha = Rule { name = "Lá na nAithreacha" , pattern = [ regex "l(á|a) na naithreacha" ] , prod = \_ -> tt $ nthDOWOfMonth 2 7 6 } ruleArAmrach :: Rule ruleArAmrach = Rule { name = "arú amárach" , pattern = [ regex "ar(ú|u) am(á|a)rach" ] , prod = \_ -> tt $ cycleNth TG.Day 2 } ruleOrdinalCycleDeTime :: Rule ruleOrdinalCycleDeTime = Rule { name = "<ordinal> <cycle> de <time>" , pattern = [ dimension Ordinal , dimension TimeGrain , regex "d[e']" , dimension Time ] , prod = \tokens -> case tokens of (Token Ordinal od:Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter True grain (TOrdinal.value od - 1) td _ -> Nothing } ruleYyyymmdd :: Rule ruleYyyymmdd = Rule { name = "yyyy-mm-dd" , pattern = [ regex "(\\d{2,4})-(0?[1-9]|1[0-2])-(3[01]|[12]\\d|0?[1-9])" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (m1:m2:m3:_)):_) -> do y <- parseInt m1 m <- parseInt m2 d <- parseInt m3 tt $ yearMonthDay y m d _ -> Nothing } ruleArDate :: Rule ruleArDate = Rule { name = "ar <date>" , pattern = [ regex "ar" , dimension Time ] , prod = \tokens -> case tokens of (_:x:_) -> Just x _ -> Nothing } ruleAnNollaig :: Rule ruleAnNollaig = Rule { name = "An Nollaig" , pattern = [ regex "(l(á|a) |an )?(nollai?g)" ] , prod = \_ -> tt $ monthDay 12 25 } ruleOnANamedday :: Rule ruleOnANamedday = Rule { name = "on a named-day" , pattern = [ regex "ar an" , Predicate isADayOfWeek ] , prod = \tokens -> case tokens of (_:x:_) -> Just x _ -> Nothing } ruleYearLatent :: Rule ruleYearLatent = Rule { name = "year (latent)" , pattern = [ Predicate $ isIntegerBetween (- 10000) 999 ] , prod = \tokens -> case tokens of (token:_) -> do n <- getIntValue token tt . mkLatent $ year n _ -> Nothing } ruleAnois :: Rule ruleAnois = Rule { name = "anois" , pattern = [ regex "anois|(ag an (t-?)?am seo)" ] , prod = \_ -> tt now } ruleLFhilePdraig :: Rule ruleLFhilePdraig = Rule { name = "Lá Fhéile Pádraig" , pattern = [ regex "(l(á|a) )?(fh(e|é)ile|'?le) ph?(á|a)draig" ] , prod = \_ -> tt $ monthDay 3 17 } ruleAnCycleINdiaidhTime :: Rule ruleAnCycleINdiaidhTime = Rule { name = "an <cycle> i ndiaidh <time>" , pattern = [ regex "the" , dimension TimeGrain , regex "(i ndiaidh|tar (é|e)is)" , dimension Time ] , prod = \tokens -> case tokens of (_:Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter False grain 1 td _ -> Nothing } ruleDayofmonthOrdinal :: Rule ruleDayofmonthOrdinal = Rule { name = "<day-of-month> (ordinal)" , pattern = [ Predicate isDOMOrdinal ] , prod = \tokens -> case tokens of (token:_) -> do n <- getIntValue token tt . mkLatent $ dayOfMonth n _ -> Nothing } ruleAnCycleSeo :: Rule ruleAnCycleSeo = Rule { name = "an <cycle> seo" , pattern = [ regex "an" , dimension TimeGrain , regex "seo" ] , prod = \tokens -> case tokens of (_:Token TimeGrain grain:_) -> tt $ cycleNth grain 0 _ -> Nothing } ruleAnDayofmonthNonOrdinal :: Rule ruleAnDayofmonthNonOrdinal = Rule { name = "an <day-of-month> (non ordinal)" , pattern = [ regex "an|na" , Predicate isDOMInteger ] , prod = \tokens -> case tokens of (_:token:_) -> do v <- getIntValue token tt . mkLatent $ dayOfMonth v _ -> Nothing } ruleDNamedday :: Rule ruleDNamedday = Rule { name = "dé named-day" , pattern = [ regex "d(é|e)" , Predicate isADayOfWeek ] , prod = \tokens -> case tokens of (_:x:_) -> Just x _ -> Nothing } ruleYear :: Rule ruleYear = Rule { name = "year" , pattern = [ Predicate $ isIntegerBetween 1000 2100 ] , prod = \tokens -> case tokens of (token:_) -> do v <- getIntValue token tt $ year v _ -> Nothing } ruleCycleRoimhTime :: Rule ruleCycleRoimhTime = Rule { name = "<cycle> roimh <time>" , pattern = [ dimension TimeGrain , regex "roimhe?" , dimension Time ] , prod = \tokens -> case tokens of (Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter False grain (-1) td _ -> Nothing } ruleAbsorptionOfAfterNamedDay :: Rule ruleAbsorptionOfAfterNamedDay = Rule { name = "absorption of , after named day" , pattern = [ Predicate isADayOfWeek , regex "," ] , prod = \tokens -> case tokens of (x:_) -> Just x _ -> Nothing } ruleDdmmyyyy :: Rule ruleDdmmyyyy = Rule { name = "dd/mm/yyyy" , pattern = [ regex "(3[01]|[12]\\d|0?[1-9])[-/](0?[1-9]|1[0-2])[/-](\\d{2,4})" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (m1:m2:m3:_)):_) -> do y <- parseInt m3 m <- parseInt m2 d <- parseInt m1 tt $ yearMonthDay y m d _ -> Nothing } ruleAnNamedday :: Rule ruleAnNamedday = Rule { name = "an named-day" , pattern = [ regex "an" , Predicate isADayOfWeek ] , prod = \tokens -> case tokens of (_:x:_) -> Just x _ -> Nothing } ruleDaysOfWeek :: [Rule] ruleDaysOfWeek = mkRuleDaysOfWeek [ ( "Monday" , "luai?n|lu\\.?" ) , ( "Tuesday" , "mh?(á|a)irt|m(á|a)?\\.?" ) , ( "Wednesday", "ch?(é|e)adaoin|c(é|e)\\.?" ) , ( "Thursday" , "d(é|e)ardaoin|d(é|e)?\\.?" ) , ( "Friday" , "h?aoine|ao\\.?" ) , ( "Saturday" , "sathai?rn|sa\\.?" ) , ( "Sunday" , "domhnai?[cg]h|do\\.?" ) ] ruleMonths :: [Rule] ruleMonths = mkRuleMonths [ ( "January" , "(mh?(í|i) )?(an )?t?ean(á|a)ir|ean\\.?" ) , ( "February" , "(mh?(í|i) )?(na )?feabhra|fea\\.?" ) , ( "March" , "(mh?(í|i) )?(an )?mh?(á|a)rta|m(á|a)r\\.?" ) , ( "April" , "(mh?(í|i) )?(an )?t?aibre(á|a)i?n|abr\\.?" ) , ( "May" , "(mh?(í|i) )?(na )?bh?ealtaine|bea\\.?" ) , ( "June" , "(mh?(í|i) )?(an )?mh?eith(ea|i)mh|mei\\.?" ) , ( "July" , "(mh?(í|i) )?i(ú|u)il|i(ú|u)i\\.?" ) , ( "August" , "(mh?(í|i) )?(na )?l(ú|u)nasa|l(ú|u)n\\.?" ) , ( "September", "(mh?(í|i) )?mh?e(á|a)n f(ó|o)mhair|mef?\\.?") , ( "October" , "(mh?(í|i) )?(na )?nollai?g|nol\\.?" ) , ( "November" , "(mh?(í|i) )?(na )?samh(ain|na)|sam\\.?" ) , ( "December" , "(mh?(í|i) )?(na )?nollai?g|nol\\.?" ) ] ruleCycleINdiaidhTime :: Rule ruleCycleINdiaidhTime = Rule { name = "<cycle> i ndiaidh <time>" , pattern = [ dimension TimeGrain , regex "(i ndiaidh|tar (é|e)is)" , dimension Time ] , prod = \tokens -> case tokens of (Token TimeGrain grain:_:Token Time td:_) -> tt $ cycleNthAfter False grain 1 td _ -> Nothing } ruleDayofmonthordinalNamedmonthYear :: Rule ruleDayofmonthordinalNamedmonthYear = Rule { name = "<day-of-month>(ordinal) <named-month> year" , pattern = [ Predicate isDOMOrdinal , Predicate isAMonth , regex "(\\d{2,4})" ] , prod = \tokens -> case tokens of (token:Token Time td:Token RegexMatch (GroupMatch (match:_)):_) -> do intVal <- parseInt match dom <- intersectDOM td token Token Time <$> intersect dom (year intVal) _ -> Nothing } rules :: [Rule] rules = [ ruleAbsorptionOfAfterNamedDay , ruleAmrach , ruleAnCycleDeTime , ruleAnCycleINdiaidhTime , ruleAnCycleSeo , ruleAnDayofmonthNonOrdinal , ruleAnDayofmonthOrdinal , ruleAnNamedday , ruleAnNollaig , ruleAnOrdinalCycleDeTime , ruleAnOrdinalCycleINdiaidhTime , ruleAnnaCycleRoimhTime , ruleAnois , ruleArAmrach , ruleArDate , ruleArInn , ruleCycleINdiaidhTime , ruleCycleInniu , ruleCycleRoimhTime , ruleCycleShin , ruleDNamedday , ruleDayofmonthOrdinal , ruleDayofmonthordinalNamedmonth , ruleDayofmonthordinalNamedmonthYear , ruleDdmm , ruleDdmmyyyy , ruleIGceannCycle , ruleInn , ruleInniu , ruleIntersect , ruleIntersectBy , ruleLFhileBrde , ruleLFhilePdraig , ruleLFhileVailintn , ruleLNaNaithreacha , ruleNollaigNaMban , ruleOnANamedday , ruleOrdinalCycleDeTime , ruleOrdinalCycleINdiaidhTime , ruleOrdinalRithe , ruleOrdinalRitheYear , ruleTimeSeo , ruleTimeSeoChaite , ruleTimeSeoChugainn , ruleYear , ruleYearLatent , ruleYearLatent2 , ruleYyyymmdd ] ++ ruleDaysOfWeek ++ ruleMonths
facebookincubator/duckling
Duckling/Time/GA/Rules.hs
bsd-3-clause
16,978
0
19
4,614
4,899
2,692
2,207
552
2
{-# LANGUAGE ImplicitParams #-} {-# LANGUAGE DoAndIfThenElse #-} ---------------------------------------------------------------------------- -- | -- Module : Language.Core.Interpreter.Acknowledge -- Copyright : (c) Carlos López-Camey, University of Freiburg -- License : BSD-3 -- -- Maintainer : c.lopez@kmels.net -- Stability : stable -- -- -- When the interpreter reads a module, it should acknowledge type and value definitions -- and save them in the heap, before going on to lazily evaluation. ----------------------------------------------------------------------------- module Language.Core.Interpreter.Acknowledge(acknowledgeModule,acknowledgeTypes,acknowledgeVdefgs,acknowledgeVdefg) where import DART.CmdLine(beVerboseM,showIncludeDefinitionM) import DART.DARTSettings import Language.Core.Core import Language.Core.Interpreter.Structures import Language.Core.Util import Language.Core.Vdefg(vdefId,vdefgNames,vdefQualId) -- | Given a parsed module, recognize type constructors and value definitions -- and save them in the heap acknowledgeModule :: Module -> IM Env acknowledgeModule modl@(Module mname tdefs vdefgs) = do tycons_env <- acknowledgeTypes tdefs -- type constructors vdefs_env <- acknowledgeVdefgs vdefgs -- value definitions --io . putStrLn $ "Types of: " ++ show mname --mapM (io . putStrLn) $ map fst tycons_env return $ tycons_env ++ vdefs_env -- | Given a module, recognize type constructors and put them in the heap -- so that we can build values for custom types afterwards. acknowledgeTypes :: [Tdef] -> IM Env acknowledgeTypes tdefs = mapM acknowledgeType tdefs >>= return . concat -- | Given a data type or a newtype definition, memorize their type constructors, -- create an environment variable for each of them and return an environment that holds -- all the created heap references acknowledgeType :: Tdef -> IM Env acknowledgeType tdef@(Data qdname@(_,dname) tbinds cdefs) = do let type_name = zDecodeQualified qdname type_constructors = map mkDataCon cdefs --io . putStrLn $ "Type constructors: " ++ show type_constructors --printTypesCons type_constructors beVerboseM $ "Acknowledging type " ++ type_name tyCon_refs <- mapM insertTyCon type_constructors -- the sum type itself sumtype_ref <- mkDataTypeRef type_constructors type_name -- make overall env return (sumtype_ref:tyCon_refs) where printTypesCons :: [DataCon] -> IM () printTypesCons [] = return () printTypesCons ((MkDataCon id tys _):ds) = do io . putStrLn $ id ++ " expects " ++ show tys printTypesCons ds mkDataTypeRef :: [DataCon] -> Id -> IM HeapReference mkDataTypeRef cons tname = memorize (mkVal . SumType $ cons) tname mkDataCon :: Cdef -> DataCon mkDataCon tcon@(Constr qcname tbinds' datacon_signature) = let no_types_applied = [] in MkDataCon (zDecodeQualified qcname) datacon_signature no_types_applied insertTyCon :: DataCon -> IM HeapReference insertTyCon tyCon@(MkDataCon tyConName tys _) = memorize (mkVal $ TyConApp tyCon []) (tyConName) -- | Given a module, recognize all of its value definitions, functions, and put them in the heap so that we can evaluate them when required. acknowledgeVdefgs :: [Vdefg] -> IM Env acknowledgeVdefgs vdefgs = acknowledgeVdefgs' vdefgs [] where acknowledgeVdefgs' :: [Vdefg] -> Env -> IM Env acknowledgeVdefgs' [vdefg] env = acknowledgeVdefg vdefg env >>= return . flip (++) env acknowledgeVdefgs' (v:vs) env = acknowledgeVdefg v env >>= \e -> acknowledgeVdefgs' vs (e ++ env) -- | Acknowledges a generic value definition acknowledgeVdefg :: Vdefg -> Env -> IM Env acknowledgeVdefg (Nonrec vdef) env = let mkList x = [x] in showIncludeDefinitionM vdef >> newAddress >>= storeVdef vdef env >>= return . mkList --beVerboseM $ "Acknowledging non-recursive definition: " ++ vdefQualId vdef --sequence [(flip acknowledgeVdef env) vdef] acknowledgeVdefg v@(Rec vdefs) env = do beVerboseM $ "Acknowledging recursive definitions: " ++ (show . vdefgNames $ v) --beVerboseM $ "with env: " ++ show (map fst env) addresses <- allocate $ length vdefs let ids = map vdefId vdefs let env' = env ++ zip ids addresses let vdefsWithAddress = zip vdefs addresses beVerboseM $ "Made extended environment: " ++ show (map fst env') mapM (\(vdef,address) -> storeVdef vdef env' address) vdefsWithAddress -- | Stores a value definition in the given address. storeVdef :: Vdef -> Env -> HeapAddress -> IM HeapReference storeVdef (Vdef (qid, ty, exp)) env address= do beVerboseM $ "Acknowledging value definition " ++ zDecodeQualified qid --beVerboseM $ "\twith env = " ++ show (map fst env) --beVerboseM $ "\tin address = " ++ show address store address (Left $ Thunk exp env) (zDecodeQualified qid)
kmels/dart-haskell
src/Language/Core/Interpreter/Acknowledge.hs
bsd-3-clause
4,932
0
12
948
1,010
527
483
60
2
{-# LANGUAGE PackageImports #-} import "ouch-web" Application (getApplicationDev) import Network.Wai.Handler.Warp (runSettings, defaultSettings, settingsPort) import Control.Concurrent (forkIO) import System.Directory (doesFileExist, removeFile) import System.Exit (exitSuccess) import Control.Concurrent (threadDelay) main :: IO () main = do putStrLn "Starting devel application" (port, app) <- getApplicationDev forkIO $ runSettings defaultSettings { settingsPort = port } app loop loop :: IO () loop = do threadDelay 100000 e <- doesFileExist "yesod-devel/devel-terminate" if e then terminateDevel else loop terminateDevel :: IO () terminateDevel = exitSuccess
mkrauskopf/ouch-web
devel.hs
bsd-3-clause
709
0
10
123
186
101
85
23
2
module Doukaku.DiceTest (tests) where import Distribution.TestSuite import Doukaku.TestHelper import qualified Doukaku.Dice as Dice tests :: IO [Test] tests = createTests $ newDoukakuTest { tsvPath = "test/Doukaku/dice.tsv" , solve = Dice.solve }
hiratara/doukaku-past-questions-advent-2013
test/Doukaku/DiceTest.hs
bsd-3-clause
255
0
8
39
65
40
25
8
1
{-# LANGUAGE OverloadedStrings #-} module Network.Monitoring.Riemann ( module Network.Monitoring.Riemann.Types, module Data.Int, Client, makeClient, sendEvent, sendEvent' {-, sendEvent'-} ) where import Network.Monitoring.Riemann.Types import Data.Default import Data.Int import Data.ProtocolBuffers import Data.Serialize.Put import Data.Time.Clock import Data.Time.Clock.POSIX import Control.Applicative import qualified Control.Error as Error import Control.Exception import Control.Lens import qualified Control.Monad as CM import qualified Control.Monad.IO.Class as CMIC import Control.Monad.Trans.Either import qualified Control.Monad.Trans.Except as Except import Network.Socket hiding (recv, recvFrom, send, sendTo) import Network.Socket.ByteString {-% In brief, a Riemann client has two operating conditions: (a) as a decoration of *real* code or (b) as a component of self-reflecting system component. In 95% of cases the client will be used for (a), so that's the easiest way to use the client. An (a)-style Riemann client should allow for liberal *decoration* of code with monitoring keys. These decorations should trivially reduce to nops if there is no connection to a Riemann server and they should silently ignore all server errors. The (a)-style Riemann decorations should never slow real code and thus must either be very, very fast or asynchronous. As a tradeoff, we can never be sure that *all* (a)-style decorations fire and are observed by a Riemann server. Neither the client or the server can take note of or be affected by packet failure. A (b)-style Riemann client should allow for smart load balancing. It should be able to guarantee connectivity to the Riemann server and failover along with the server should Riemann ever die or become partitioned. (To this end, there's some need for pools of Riemann servers, but this may be non-critical.) Riemann (b)-style interactions also include querying the Riemann server --- so we'll need a query combinator language. -} {-% API Design ---------- Basic events ought to be generated very easily. Sane defaults ought to be built-in---we shouldn't be specifying the host in every decorated call, we shouldn't have any concept of the current time when we decorate an action. To this end the Monoid instances for `Event`s, `State`s, `Msg`s, and `Query`s are designed to either grow or be overridden to the right (using lots of `Last` newtypes over maybes and inner `(<>)` applications). The Client also should be defaulted at as high a level as possible. e.g. ``` withClient :: Client -> IO a -> IO a withDefaultEvent :: Event -> IO a -> IO a withEventTiming :: IO a -> IO a withHostname :: Text -> IO a -> IO a ``` -} {-% Implementation -------------- There are roughly two independent factors for library design. First, we can use UDP or TCP---Riemann size limits UDP datagrams, but the limit is high (16 mb by default), so there's theoretically a corner case there but it's a fair bet that we won't hit it---and secondly we can deliver them in the main thread or asynchronously via a concurrent process. There's a tradeoff here between throughput and assurance. Asynch+UDP has the highest throughput, while Synch+TCP has the greatest assurance. We'll optimize for (a)-type decoration via Asynch+UDP. Can we do the same and optimize (b)-type calls as Synch+TCP? Probably. -} {-% Syntax ------ riemann $ ev "<service>" <metric> & tags <>~ "foo" -} data Client = UDP (Maybe (Socket, AddrInfo)) deriving (Show, Eq) type Hostname = String type Port = Int -- | Attempts to bind a UDP client at the passed 'Hostname' and -- 'Port'. Failures are silently ignored---failure in monitoring -- should not cause an application failure... makeClient :: Hostname -> Port -> IO Client makeClient hn po = UDP . Error.rightMay <$> sock where sock :: IO (Either SomeException (Socket, AddrInfo)) sock = try $ do addrs <- getAddrInfo (Just $ defaultHints { addrFlags = [AI_NUMERICSERV] }) (Just hn) (Just $ show po) case addrs of [] -> fail "No accessible addresses" (addy:_) -> do s <- socket (addrFamily addy) Datagram (addrProtocol addy) return (s, addy) -- | Attempts to forward an event to a client. Fails silently. sendEvent :: CMIC.MonadIO m => Client -> Event -> m () sendEvent c = CMIC.liftIO . CM.void . runEitherT . sendEvent' c -- | Attempts to forward an event to a client. If it fails, it'll -- return an 'IOException' in the 'Either'. sendEvent' :: Client -> Event -> EitherT IOException IO () sendEvent' (UDP Nothing) _ = return () sendEvent' (UDP (Just (s, addy))) e = Error.tryIO $ do current <- getCurrentTime let now = round (utcTimeToPOSIXSeconds current) let msg = def & events .~ [e & time ?~ now] CM.void $ sendTo s (runPut $ encodeMessage msg) (addrAddress addy)
telser/riemann-hs
src/Network/Monitoring/Riemann.hs
mit
5,379
0
18
1,390
618
347
271
53
2
module Codec.Encryption.Historical.XOR.Analysis ( crack , crack_key_length ) where -- Module to Analyse import Codec.Encryption.Historical.XOR.Implementation import Codec.Encryption.Historical.Utilities.Histogram import Data.Ord import Data.List import Data.List.Split import Control.Arrow import qualified Data.ByteString.Internal as B -- TODO: Take advantage of some of the properties of XOR to crack this better crack :: Int -> Histogram Char -> String -> String crack mkl h cypher = xor_decode key cypher where key = map (crackPart h) chopped chopped = transpose $ chunksOf klen cypher klen = crack_key_length mkl h cypher crackPart :: Histogram Char -> String -> Char crackPart h cypher = fst $ head $ sortBy (comparing best) goodSolutions where best :: (Char, Histogram Char) -> Float best = histogramDelta h . snd goodSolutions :: [(Char, Histogram Char)] goodSolutions = filter ((>20) . length . snd) solutions solutions :: [(Char, Histogram Char)] solutions = map ((id &&& histogram . singletonDecode cypher) . B.w2c) [minBound..maxBound] singletonDecode :: String -> Char -> String singletonDecode cypher c = xor_decode [c] cypher crack_key_length :: Int -> Histogram a -> String -> Int crack_key_length keyLen h s = head $ sortBy (comparing best) [1..keyLen] where hv = histogramVar h best :: Int -> (Float, Int) best n = (abs (hv - compute n), n) compute :: Int -> Float compute n = average $ map (histogramVar . histogram) $ transpose $ chunksOf n s average :: [Float] -> Float average l = sum l / fromIntegral (length l)
beni55/Historical-Cryptography
Codec/Encryption/Historical/XOR/Analysis.hs
mit
1,672
0
12
373
535
289
246
-1
-1
module Command.TyProjection ( tyValue , tyEither , tyAddress , tyPublicKey , tyTxOut , tyAddrStakeDistr , tyFilePath , tyInt , tyWord , tyWord32 , tyByte , tySecond , tyBool , tyScriptVersion , tyCoin , tyCoinPortion , tyStakeholderId , tyAddrDistrPart , tyEpochIndex , tyHash , tyBlockVersion , tySoftwareVersion , tyBlockVersionModifier , tyProposeUpdateSystem , tySystemTag , tyApplicationName , tyString ) where import Universum import Data.Scientific (Scientific, floatingOrInteger, toBoundedInteger, toRealFloat) import Data.Time.Units (Microsecond, TimeUnit, convertUnit, fromMicroseconds) import Serokell.Data.Memory.Units (Byte, fromBytes) import Pos.Chain.Txp (TxOut (..)) import Pos.Chain.Update (ApplicationName (..), BlockVersion, BlockVersionModifier (..), SoftwareVersion, SystemTag (..)) import Pos.Core (AddrStakeDistribution (..), Address, Coin, CoinPortion, EpochIndex, ScriptVersion, StakeholderId, mkCoin, unsafeCoinPortionFromDouble, unsafeGetCoin) import Pos.Crypto (AHash (..), Hash, PublicKey) import Lang.Argument (TyProjection (..), TypeName (..)) import Lang.Value (AddrDistrPart (..), ProposeUpdateSystem (..), Value (..), _ValueAddrDistrPart, _ValueAddrStakeDistribution, _ValueAddress, _ValueBlockVersion, _ValueBlockVersionModifier, _ValueBool, _ValueFilePath, _ValueHash, _ValueNumber, _ValueProposeUpdateSystem, _ValuePublicKey, _ValueSoftwareVersion, _ValueStakeholderId, _ValueString, _ValueTxOut) tyValue :: TyProjection Value tyValue = TyProjection "Value" Just infixr `tyEither` tyEither :: TyProjection a -> TyProjection b -> TyProjection (Either a b) tyEither tpa tpb = TyProjection { tpTypeName = TypeNameEither (tpTypeName tpa) (tpTypeName tpb) , tpMatcher = \v -> Left <$> tpMatcher tpa v <|> Right <$> tpMatcher tpb v } tyAddress :: TyProjection Address tyAddress = TyProjection "Address" (preview _ValueAddress) tyPublicKey :: TyProjection PublicKey tyPublicKey = TyProjection "PublicKey" (preview _ValuePublicKey) tyTxOut :: TyProjection TxOut tyTxOut = TyProjection "TxOut" (preview _ValueTxOut) tyAddrStakeDistr :: TyProjection AddrStakeDistribution tyAddrStakeDistr = TyProjection "AddrStakeDistribution" (preview _ValueAddrStakeDistribution) tyFilePath :: TyProjection FilePath tyFilePath = TyProjection "FilePath" (preview _ValueFilePath) tyInt :: TyProjection Int tyInt = TyProjection "Int" (toBoundedInteger <=< preview _ValueNumber) tyWord :: TyProjection Word tyWord = TyProjection "Word" (toBoundedInteger <=< preview _ValueNumber) tyWord32 :: TyProjection Word32 tyWord32 = TyProjection "Word32" (toBoundedInteger <=< preview _ValueNumber) tyByte :: TyProjection Byte tyByte = fromBytes <$> TyProjection "Byte" (sciToInteger <=< preview _ValueNumber) sciToInteger :: Scientific -> Maybe Integer sciToInteger = either (const Nothing) Just . floatingOrInteger @Double @Integer tySecond :: forall a . TimeUnit a => TyProjection a tySecond = convertUnit . (fromMicroseconds . fromIntegral . (*) 1000000 :: Int -> Microsecond) <$> TyProjection "Second" (toBoundedInteger <=< preview _ValueNumber) tyScriptVersion :: TyProjection ScriptVersion tyScriptVersion = TyProjection "ScriptVersion" (toBoundedInteger <=< preview _ValueNumber) tyBool :: TyProjection Bool tyBool = TyProjection "Bool" (preview _ValueBool) -- | Small hack to use 'toBoundedInteger' for 'Coin'. newtype PreCoin = PreCoin { getPreCoin :: Word64 } deriving (Eq, Ord, Num, Enum, Real, Integral) instance Bounded PreCoin where minBound = PreCoin . unsafeGetCoin $ minBound maxBound = PreCoin . unsafeGetCoin $ maxBound fromPreCoin :: PreCoin -> Coin fromPreCoin = mkCoin . getPreCoin tyCoin :: TyProjection Coin tyCoin = fromPreCoin <$> TyProjection "Coin" (toBoundedInteger <=< preview _ValueNumber) coinPortionFromDouble :: Double -> Maybe CoinPortion coinPortionFromDouble a | a >= 0, a <= 1 = Just $ unsafeCoinPortionFromDouble a | otherwise = Nothing tyCoinPortion :: TyProjection CoinPortion tyCoinPortion = TyProjection "CoinPortion" (coinPortionFromDouble . toRealFloat <=< preview _ValueNumber) tyStakeholderId :: TyProjection StakeholderId tyStakeholderId = TyProjection "StakeholderId" (preview _ValueStakeholderId) tyAddrDistrPart :: TyProjection AddrDistrPart tyAddrDistrPart = TyProjection "AddrDistrPart" (preview _ValueAddrDistrPart) tyEpochIndex :: TyProjection EpochIndex tyEpochIndex = TyProjection "EpochIndex" (toBoundedInteger <=< preview _ValueNumber) tyHash :: TyProjection (Hash a) tyHash = getAHash <$> TyProjection "Hash" (preview _ValueHash) tyBlockVersion :: TyProjection BlockVersion tyBlockVersion = TyProjection "BlockVersion" (preview _ValueBlockVersion) tySoftwareVersion :: TyProjection SoftwareVersion tySoftwareVersion = TyProjection "SoftwareVersion" (preview _ValueSoftwareVersion) tyBlockVersionModifier :: TyProjection BlockVersionModifier tyBlockVersionModifier = TyProjection "BlockVersionModifier" (preview _ValueBlockVersionModifier) tyProposeUpdateSystem :: TyProjection ProposeUpdateSystem tyProposeUpdateSystem = TyProjection "ProposeUpdateSystem" (preview _ValueProposeUpdateSystem) tySystemTag :: TyProjection SystemTag tySystemTag = TyProjection "SystemTag" ((fmap . fmap) (SystemTag) (preview _ValueString)) tyApplicationName :: TyProjection ApplicationName tyApplicationName = TyProjection "ApplicationName" ((fmap . fmap) (ApplicationName) (preview _ValueString)) tyString :: TyProjection Text tyString = TyProjection "String" (preview _ValueString)
input-output-hk/pos-haskell-prototype
auxx/src/Command/TyProjection.hs
mit
6,086
0
11
1,250
1,398
764
634
-1
-1
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-} {- | Module : $Header$ Description : Coding CSMOF into CASL Copyright : (c) Daniel Calegari Universidad de la Republica, Uruguay 2013 License : GPLv2 or higher, see LICENSE.txt Maintainer : dcalegar@fing.edu.uy Stability : provisional Portability : portable -} module Comorphisms.CSMOF2CASL ( CSMOF2CASL (..), mapSign, generateVars ) where import Logic.Logic import Logic.Comorphism import Common.DefaultMorphism -- CSMOF import CSMOF.Logic_CSMOF as CSMOF import CSMOF.As as CSMOFAs import CSMOF.Sign as CSMOF -- CASL import CASL.Logic_CASL import CASL.AS_Basic_CASL as C import CASL.Sublogic import CASL.Sign as C import CASL.Morphism as C import Common.AS_Annotation import Common.GlobalAnnotations import Common.Id import Common.ProofTree import Common.Result import qualified Common.Lib.Rel as Rel import qualified Common.Lib.MapSet as MapSet import qualified Data.Set as Set import qualified Data.Map as Map import Data.Maybe (fromMaybe) -- | lid of the morphism data CSMOF2CASL = CSMOF2CASL deriving Show instance Language CSMOF2CASL -- default is ok instance Comorphism CSMOF2CASL CSMOF.CSMOF () CSMOFAs.Metamodel CSMOF.Sen () () CSMOF.Sign CSMOF.Morphism () () () CASL CASL_Sublogics CASLBasicSpec CASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS CASLSign CASLMor C.Symbol C.RawSymbol ProofTree where sourceLogic CSMOF2CASL = CSMOF sourceSublogic CSMOF2CASL = () targetLogic CSMOF2CASL = CASL mapSublogic CSMOF2CASL _ = Just $ caslTop { has_part = False , sub_features = LocFilSub , cons_features = SortGen True True } map_theory CSMOF2CASL = mapTheory map_sentence CSMOF2CASL s = return . mapSen (mapSign s) map_morphism CSMOF2CASL = mapMor -- map_symbol CSMOF2CASL _ = Set.singleton . mapSym is_model_transportable CSMOF2CASL = True has_model_expansion CSMOF2CASL = True is_weakly_amalgamable CSMOF2CASL = True isInclusionComorphism CSMOF2CASL = True mapTheory :: (CSMOF.Sign, [Named CSMOF.Sen]) -> Result (CASLSign, [Named CASLFORMULA]) mapTheory (s, ns) = let cs = mapSign s in return (cs, map (mapNamed $ mapSen cs) ns ++ sentences cs) mapSign :: CSMOF.Sign -> CASLSign mapSign s = let sorts = getSorts (types s) (typeRel s) ops = getOperations (instances s) predd = getPredicates (properties s) sent = getSentencesRels (links s) (instances s) sentDisEmb = getSortGen (typeRel s) (abstractClasses s) (types s) (instances s) noConfBetOps = getNoConfusionBetweenSets (instances s) (typeRel s) in C.Sign { sortRel = sorts , revSortRel = Just $ Rel.fromList (map revertOrder (Rel.toList sorts)) , emptySortSet = Set.empty , opMap = ops , assocOps = MapSet.empty , predMap = fst predd , varMap = Map.empty , sentences = snd predd ++ sent ++ sentDisEmb ++ noConfBetOps , declaredSymbols = Set.empty , envDiags = [] , annoMap = MapSet.empty , globAnnos = emptyGlobalAnnos , extendedInfo = () } getSorts :: Set.Set TypeClass -> Rel.Rel TypeClass -> Rel.Rel SORT getSorts setC relC = let relS = Set.fold (insertSort . name) Rel.empty setC in foldr insertPair relS (Rel.toList relC) insertSort :: String -> Rel.Rel SORT -> Rel.Rel SORT insertSort s = Rel.insertPair (stringToId s) (stringToId s) insertPair :: (TypeClass, TypeClass) -> Rel.Rel SORT -> Rel.Rel SORT insertPair (t1, t2) = Rel.insertPair (stringToId $ name t1) (stringToId $ name t2) revertOrder :: (SORT, SORT) -> (SORT, SORT) revertOrder (a, b) = (b, a) getPredicates :: Set.Set PropertyT -> (PredMap, [Named (FORMULA f)]) getPredicates = Set.fold insertPredicate (MapSet.empty, []) insertPredicate :: PropertyT -> (PredMap, [Named (FORMULA f)]) -> (PredMap, [Named (FORMULA f)]) insertPredicate prop (predM, form) = let sort1 = stringToId $ name $ sourceType prop sort2 = stringToId $ name $ targetType prop pname1 = stringToId $ targetRole prop ptype1 = PredType $ sort1 : [sort2] pname2 = stringToId $ sourceRole prop ptype2 = PredType $ sort2 : [sort1] nam = "equiv_" ++ targetRole prop ++ "_" ++ sourceRole prop varsD = [Var_decl [mkSimpleId "x"] sort2 nullRange, Var_decl [mkSimpleId "y"] sort1 nullRange] sentRel = C.Relation (C.Predication (C.Qual_pred_name pname2 (Pred_type [sort2, sort1] nullRange) nullRange) (C.Qual_var (mkSimpleId "x") sort2 nullRange : [C.Qual_var (mkSimpleId "y") sort1 nullRange]) nullRange) C.Equivalence (C.Predication (C.Qual_pred_name pname1 (Pred_type [sort1, sort2] nullRange) nullRange) (C.Qual_var (mkSimpleId "y") sort1 nullRange : [C.Qual_var (mkSimpleId "x") sort2 nullRange]) nullRange) nullRange sent = Quantification Universal varsD sentRel nullRange in {- MapSet does not allows repeated elements, but predicate names can be repeated (this must be corrected by creating a more complex ID) -} if sourceRole prop == "_" then (MapSet.insert pname1 ptype1 predM, form) else if targetRole prop == "_" then (MapSet.insert pname2 ptype2 predM, form) else (MapSet.insert pname1 ptype1 $ MapSet.insert pname2 ptype2 predM, makeNamed nam sent : form) getOperations :: Map.Map String TypeClass -> OpMap getOperations ops = foldr insertOperations MapSet.empty (Map.toList ops) insertOperations :: (String, TypeClass) -> OpMap -> OpMap insertOperations (na, tc) opM = let opName = stringToId na opType = OpType Total [] (stringToId $ name tc) in MapSet.insert opName opType opM getSentencesRels :: Set.Set LinkT -> Map.Map String TypeClass -> [Named CASLFORMULA] getSentencesRels = completenessOfRelations completenessOfRelations :: Set.Set LinkT -> Map.Map String TypeClass -> [Named CASLFORMULA] completenessOfRelations linkk ops = let ordLinks = getLinksByProperty linkk in foldr ((++) . createComplFormula ops) [] (Map.toList ordLinks) createComplFormula :: Map.Map String TypeClass -> (String, [LinkT]) -> [Named CASLFORMULA] createComplFormula ops (nam, linksL) = let varA = mkSimpleId "x" varB = mkSimpleId "y" in case linksL of [] -> [] LinkT _ _ pr : _ -> let sorA = stringToId $ name $ sourceType pr sorB = stringToId $ name $ targetType pr varsD = [Var_decl [varA] sorA nullRange, Var_decl [varB] sorB nullRange] sent = C.Relation (C.Predication (C.Qual_pred_name (stringToId $ targetRole pr) (Pred_type [sorA, sorB] nullRange) nullRange) (C.Qual_var varA sorA nullRange : [C.Qual_var varB sorB nullRange]) nullRange) C.Equivalence (Junction Dis (foldr ((:) . getPropHold ops varA sorA varB sorB) [] linksL) nullRange) nullRange sentQuan = Quantification Universal varsD sent nullRange in [makeNamed ("compRel_" ++ nam) sentQuan] getPropHold :: Map.Map String TypeClass -> VAR -> SORT -> VAR -> SORT -> LinkT -> CASLFORMULA getPropHold ops varA sorA varB sorB lin = let souObj = Map.lookup (sourceVar lin) ops tarObj = Map.lookup (targetVar lin) ops typSou = case souObj of Nothing -> sourceVar lin -- if happens then is an error Just tSou -> name tSou typTar = case tarObj of Nothing -> targetVar lin -- if happens then is an error Just tTar -> name tTar eqA = Equation (Qual_var varA sorA nullRange) Strong (Application (Qual_op_name (stringToId (sourceVar lin)) (Op_type Total [] (stringToId typSou) nullRange) nullRange) [] nullRange) nullRange eqB = Equation (Qual_var varB sorB nullRange) Strong (Application (Qual_op_name (stringToId (targetVar lin)) (Op_type Total [] (stringToId typTar) nullRange) nullRange) [] nullRange) nullRange in Junction Con (eqA : [eqB]) nullRange getLinksByProperty :: Set.Set LinkT -> Map.Map String [LinkT] getLinksByProperty linkk = let elems = Set.elems linkk in foldr getByProperty Map.empty elems getByProperty :: LinkT -> Map.Map String [LinkT] -> Map.Map String [LinkT] getByProperty lin mapL = let prope = CSMOF.property lin nameLook = sourceRole prope ++ name (sourceType prope) ++ targetRole prope ++ name (targetType prope) setProp = Map.lookup nameLook mapL in case setProp of Nothing -> Map.insert nameLook [lin] (Map.delete nameLook mapL) Just s -> Map.insert nameLook (lin : s) (Map.delete nameLook mapL) getSortGen :: Rel.Rel TypeClass -> Set.Set TypeClass -> Set.Set TypeClass -> Map.Map String TypeClass -> [Named CASLFORMULA] getSortGen typpR absCl typCl inst = disjointEmbedding absCl typpR ++ sortGeneration inst ++ sortGenerationNonAbstractSuperClasses typpR typCl absCl inst -- Free type of non-abstract superclasses sortGenerationNonAbstractSuperClasses :: Rel.Rel TypeClass -> Set.Set TypeClass -> Set.Set TypeClass -> Map.Map String TypeClass -> [Named CASLFORMULA] sortGenerationNonAbstractSuperClasses typpR typCl absCl inst = let ordObj = foldr orderByClass Map.empty (Map.toList inst) nonAbsClasses = getNonAbstractClasess absCl typCl nonAbsClassesWChilds = filter (not . null . snd) (Set.fold ((:) . getSubClasses typpR) [] nonAbsClasses) childObjects = foldr ((:) . getClassSubObjects ordObj) [] nonAbsClassesWChilds -- [(TypeClass,[String])] in foldr ((:) . toSortConstraintNonAbsClass inst) [] childObjects -- Takes the objects, and a class with its child classes and returns the descendent objects of such class getClassSubObjects :: Map.Map TypeClass [String] -> (TypeClass, [TypeClass]) -> (TypeClass, [String]) getClassSubObjects objs (tc, subCl) = let objTC = findObjectInMap objs tc in (tc, objTC ++ foldr ((++) . findObjectInMap objs) [] subCl) findObjectInMap :: Map.Map TypeClass [String] -> TypeClass -> [String] findObjectInMap objs tc = fromMaybe [] $ Map.lookup tc objs getNonAbstractClasess :: Set.Set TypeClass -> Set.Set TypeClass -> Set.Set TypeClass getNonAbstractClasess absCl classes = Set.difference classes absCl getSubClasses :: Rel.Rel TypeClass -> TypeClass -> (TypeClass, [TypeClass]) getSubClasses typpR tc = let subCla = map fst (filter (isParent tc) (Rel.toList typpR)) rec = foldr ((++) . snd . getSubClasses typpR) [] subCla in (tc, subCla ++ rec) isParent :: TypeClass -> (TypeClass, TypeClass) -> Bool isParent tc (_, tc2) = tc == tc2 toSortConstraintNonAbsClass :: Map.Map String TypeClass -> (TypeClass, [String]) -> Named CASLFORMULA toSortConstraintNonAbsClass inst (tc, lisObj) = let sor = stringToId $ name tc varA = Var_decl [mkSimpleId "x"] sor nullRange sent = Junction Dis (foldr ((:) . getEqualityVarObject sor inst) [] lisObj) nullRange constr = Quantification Universal [varA] sent nullRange in makeNamed ("sortGenCon_" ++ name tc) constr getEqualityVarObject :: SORT -> Map.Map String TypeClass -> String -> CASLFORMULA getEqualityVarObject sor inst obj = let oTyp = case Map.lookup obj inst of Nothing -> stringToId obj -- If happens, there is an error Just ob -> stringToId $ name ob in Equation (Qual_var (mkSimpleId "x") sor nullRange) Strong (Application (Qual_op_name (stringToId obj) (Op_type Total [] oTyp nullRange) nullRange) [] nullRange) nullRange -- Sorts are generated as a free type of object functions sortGeneration :: Map.Map String TypeClass -> [Named CASLFORMULA] sortGeneration inst = let ordObj = foldr orderByClass Map.empty (Map.toList inst) noJunk = foldr ((:) . toSortConstraint) [] (Map.toList ordObj) in noJunk mapFilterJust :: [Maybe a] -> [a] mapFilterJust list = case list of [] -> [] a : rest -> case a of Nothing -> mapFilterJust rest Just el -> el : mapFilterJust rest orderByClass :: (String, TypeClass) -> Map.Map TypeClass [String] -> Map.Map TypeClass [String] orderByClass (ob, tc) mapTC = case Map.lookup tc mapTC of Nothing -> Map.insert tc [ob] mapTC Just listObj -> Map.insert tc (ob : listObj) (Map.delete tc mapTC) getNoConfusionBetweenSets :: Map.Map String TypeClass -> Rel.Rel TypeClass -> [Named CASLFORMULA] getNoConfusionBetweenSets inst relC = let ordObj = Map.toList $ foldr orderByClass Map.empty (Map.toList inst) in mapFilterJust $ foldr ((:) . getNoConfusionBSetsAxiom ordObj relC) [] ordObj getNoConfusionBSetsAxiom :: [(TypeClass, [String])] -> Rel.Rel TypeClass -> (TypeClass, [String]) -> Maybe (Named CASLFORMULA) getNoConfusionBSetsAxiom ordObj relC (tc, lisObj) = case lisObj of [] -> Nothing _ : _ -> let filteredObj = removeUntilType tc ordObj diffForm = foldr ((++) . diffOfRestConstants (tc, lisObj) relC) [] filteredObj in case diffForm of [] -> Nothing _ : _ -> let constr = Junction Con diffForm nullRange in Just $ makeNamed ("noConfusion_" ++ name tc) constr removeUntilType :: TypeClass -> [(TypeClass, [String])] -> [(TypeClass, [String])] removeUntilType tc lis = case lis of [] -> [] (tc2, lisObj2) : rest -> if tc == tc2 then (tc2, lisObj2) : rest else removeUntilType tc rest diffOfRestConstants :: (TypeClass, [String]) -> Rel.Rel TypeClass -> (TypeClass, [String]) -> [CASLFORMULA] diffOfRestConstants (tc1, lisObj1) relC (tc2, lisObj2) | tc1 == tc2 = foldr ((++) . diffOfRestOps tc1 lisObj1) [] lisObj1 | haveCommonSort tc1 tc2 relC = concatMap (diffOfRestOpsDiffSort (tc1, lisObj1) tc2) lisObj2 | otherwise = [] haveCommonSort :: TypeClass -> TypeClass -> Rel.Rel TypeClass -> Bool haveCommonSort t1 t2 relT = let succT1 = superSorts relT t1 succT2 = superSorts relT t2 in not $ Set.null $ Set.intersection succT1 succT2 -- This is the non exported function reachable in Rel superSorts :: Rel.Rel TypeClass -> TypeClass -> Set.Set TypeClass superSorts relT tc = Set.fold reach Set.empty $ Rel.succs relT tc where reach e s = if Set.member e s then s else Set.fold reach (Set.insert e s) $ Rel.succs relT e diffOfRestOpsDiffSort :: (TypeClass, [String]) -> TypeClass -> String -> [CASLFORMULA] diffOfRestOpsDiffSort (tc1, lisObj1) tc2 objName = concatMap (diffOpsDiffSorts tc2 objName tc1) lisObj1 diffOpsDiffSorts :: TypeClass -> String -> TypeClass -> String -> [CASLFORMULA] diffOpsDiffSorts tc2 objName2 tc1 objName1 = [Negation (Equation (Application (Qual_op_name (stringToId objName1) (Op_type Total [] (stringToId $ name tc1) nullRange) nullRange) [] nullRange) Strong (Application (Qual_op_name (stringToId objName2) (Op_type Total [] (stringToId $ name tc2) nullRange) nullRange) [] nullRange) nullRange) nullRange] diffOfRestOps :: TypeClass -> [String] -> String -> [CASLFORMULA] diffOfRestOps tc lisObj objName = let lis = removeUntil lisObj objName in concatMap (diffOps tc objName) lis removeUntil :: [String] -> String -> [String] removeUntil lis str = case lis of [] -> [] a : rest -> if a == str then rest else removeUntil rest str diffOps :: TypeClass -> String -> String -> [CASLFORMULA] diffOps tc objName1 objName2 = [Negation (Equation (Application (Qual_op_name (stringToId objName1) (Op_type Total [] (stringToId $ name tc) nullRange) nullRange) [] nullRange) Strong (Application (Qual_op_name (stringToId objName2) (Op_type Total [] (stringToId $ name tc) nullRange) nullRange) [] nullRange) nullRange) nullRange | objName1 /= objName2] toSortConstraint :: (TypeClass, [String]) -> Named CASLFORMULA toSortConstraint (tc, lisObj) = let sor = stringToId $ name tc simplCon = Constraint sor (foldr ((:) . toConstraint sor) [] lisObj) sor constr = mkSort_gen_ax [simplCon] True in makeNamed ("sortGenCon_" ++ name tc) constr toConstraint :: Id -> String -> (OP_SYMB, [Int]) toConstraint sor obName = let obj = stringToId obName in (Qual_op_name obj (Op_type Total [] sor nullRange) nullRange, []) -- Each abstract class is the disjoint embedding of it subsorts disjointEmbedding :: Set.Set TypeClass -> Rel.Rel TypeClass -> [Named CASLFORMULA] disjointEmbedding absCl rel = let injSyms = map (\ (s, t) -> (Qual_op_name (mkUniqueInjName (stringToId $ name s) (stringToId $ name t)) (Op_type Total [stringToId $ name s] (stringToId $ name t) nullRange) nullRange, [])) $ Rel.toList $ Rel.irreflex rel resType _ (Op_name _, _) = False resType s (Qual_op_name _ t _, _) = res_OP_TYPE t == s collectOps s = Constraint (stringToId $ name s) (filter (resType (stringToId $ name s)) injSyms) (stringToId $ name s) sortList = Set.toList absCl constrs = map collectOps sortList in [makeNamed "disjEmbedd" (Sort_gen_ax constrs True)] mapSen :: CASLSign -> CSMOF.Sen -> CASLFORMULA mapSen sig (Sen con car cot) = -- trueForm case cot of EQUAL -> let minC = minConstraint con car (predMap sig) maxC = maxConstraint con car (predMap sig) in Junction Con (minC : [maxC]) nullRange LEQ -> maxConstraint con car (predMap sig) GEQ -> minConstraint con car (predMap sig) minConstraint :: MultConstr -> Integer -> PredMap -> CASLFORMULA minConstraint con int predM = let predTypes = MapSet.lookup (stringToId $ getRole con) predM -- Set PredType souVars = generateVars "x" 1 tarVars = generateVars "y" int correctPredType = Set.fold (getCorrectPredType con) [] predTypes souVarDec = Var_decl souVars (head (predArgs (head correctPredType))) nullRange tarVarDec = Var_decl tarVars (last (predArgs (head correctPredType))) nullRange in if int > 1 then Quantification Universal [souVarDec] (Quantification Existential [tarVarDec] (Junction Con (generateVarDiff tarVarDec : [generateProp souVarDec tarVarDec (stringToId $ getRole con)]) nullRange) nullRange) nullRange else Quantification Universal [souVarDec] (Quantification Existential [tarVarDec] (generateProp souVarDec tarVarDec (stringToId $ getRole con)) nullRange) nullRange getCorrectPredType :: MultConstr -> PredType -> [PredType] -> [PredType] getCorrectPredType con pt ptLis = if stringToId (name (CSMOF.getType con)) == head (predArgs pt) then pt : ptLis else ptLis generateVars :: String -> Integer -> [VAR] generateVars varRoot int = case int of 1 -> [mkSimpleId (varRoot ++ "_" ++ show int)] n -> mkSimpleId (varRoot ++ "_" ++ show int) : generateVars varRoot (n - 1) generateVarDiff :: VAR_DECL -> CASLFORMULA generateVarDiff (Var_decl vars sor _) = Junction Con (foldr ((++) . diffOfRest sor vars) [] vars) nullRange diffOfRest :: SORT -> [VAR] -> VAR -> [CASLFORMULA] diffOfRest sor vars var = map (diffVar sor var) vars diffVar :: SORT -> VAR -> VAR -> CASLFORMULA diffVar sor var1 var2 = if var1 /= var2 then Negation (Equation (Qual_var var1 sor nullRange) Strong (Qual_var var2 sor nullRange) nullRange) nullRange else trueForm generateProp :: VAR_DECL -> VAR_DECL -> Id -> CASLFORMULA generateProp (Var_decl varD sort _) (Var_decl varD2 sort2 _) rol = Junction Con (map (createPropRel (head varD) sort rol sort2) varD2) nullRange createPropRel :: VAR -> SORT -> Id -> SORT -> VAR -> CASLFORMULA createPropRel souVar sor rol sor2 tarVar = Predication (C.Qual_pred_name rol (Pred_type [sor, sor2] nullRange) nullRange) (Qual_var souVar sor nullRange : [Qual_var tarVar sor2 nullRange]) nullRange maxConstraint :: MultConstr -> Integer -> PredMap -> CASLFORMULA maxConstraint con int predM = let predTypes = MapSet.lookup (stringToId $ getRole con) predM -- Set PredType souVars = generateVars "x" 1 tarVars = generateVars "y" (int + 1) correctPredType = Set.fold (getCorrectPredType con) [] predTypes souVarDec = Var_decl souVars (head (predArgs (head correctPredType))) nullRange tarVarDec = Var_decl tarVars (last (predArgs (head correctPredType))) nullRange in Quantification Universal (souVarDec : [tarVarDec]) (Relation (Junction Con [generateProp souVarDec tarVarDec (stringToId $ getRole con)] nullRange) Implication (Junction Dis (generateExEqual tarVarDec) nullRange) nullRange) nullRange generateExEqual :: VAR_DECL -> [CASLFORMULA] generateExEqual (Var_decl varD sor _) = generateExEqualList varD sor generateExEqualList :: [VAR] -> SORT -> [CASLFORMULA] generateExEqualList vars sor = case vars of [] -> [] v : rest -> generateExEqualVar rest sor v ++ generateExEqualList rest sor generateExEqualVar :: [VAR] -> SORT -> VAR -> [CASLFORMULA] generateExEqualVar vars sor var = foldr ((++) . (\ el -> if el == var then [] else [Equation (Qual_var var sor nullRange) Strong (Qual_var el sor nullRange) nullRange])) [] vars -- | Translation of morphisms mapMor :: CSMOF.Morphism -> Result CASLMor mapMor m = return C.Morphism { msource = mapSign $ domOfDefaultMorphism m , mtarget = mapSign $ codOfDefaultMorphism m , sort_map = Map.empty , op_map = Map.empty , pred_map = Map.empty , extended_map = () } -- mapSym :: CSMOF.Symbol -> C.Symbol
mariefarrell/Hets
Comorphisms/CSMOF2CASL.hs
gpl-2.0
22,609
0
21
5,748
7,238
3,727
3,511
476
3
{- Copyright (C) 2010-2015 Paul Rivier <paul*rivier#demotera*com> | tr '*#' '.@' and John MacFarlane This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Readers.Textile Copyright : Copyright (C) 2010-2015 Paul Rivier and John MacFarlane License : GNU GPL, version 2 or above Maintainer : Paul Rivier <paul*rivier#demotera*com> Stability : alpha Portability : portable Conversion from Textile to 'Pandoc' document, based on the spec available at http://redcloth.org/textile. Implemented and parsed: - Paragraphs - Code blocks - Lists - blockquote - Inlines : strong, emph, cite, code, deleted, superscript, subscript, links - footnotes - HTML-specific and CSS-specific attributes on headers Left to be implemented: - dimension sign - all caps - continued blocks (ex bq..) TODO : refactor common patterns across readers : - more ... -} module Text.Pandoc.Readers.Textile ( readTextile) where import Text.Pandoc.Definition import Text.Pandoc.Builder (Inlines, Blocks, trimInlines) import qualified Text.Pandoc.Builder as B import Text.Pandoc.Options import Text.Pandoc.Parsing import Text.Pandoc.Readers.HTML ( htmlTag, isBlockTag ) import Text.Pandoc.Shared (trim) import Text.Pandoc.Readers.LaTeX ( rawLaTeXInline, rawLaTeXBlock ) import Text.HTML.TagSoup (parseTags, innerText, fromAttrib, Tag(..)) import Text.HTML.TagSoup.Match import Data.List ( intercalate ) import Data.Char ( digitToInt, isUpper) import Control.Monad ( guard, liftM, when ) import Text.Pandoc.Compat.Monoid ((<>)) import Text.Printf import Debug.Trace (trace) import Text.Pandoc.Error -- | Parse a Textile text and return a Pandoc document. readTextile :: ReaderOptions -- ^ Reader options -> String -- ^ String to parse (assuming @'\n'@ line endings) -> Either PandocError Pandoc readTextile opts s = (readWith parseTextile) def{ stateOptions = opts } (s ++ "\n\n") -- | Generate a Pandoc ADT from a textile document parseTextile :: Parser [Char] ParserState Pandoc parseTextile = do -- textile allows raw HTML and does smart punctuation by default, -- but we do not enable smart punctuation unless it is explicitly -- asked for, for better conversion to other light markup formats oldOpts <- stateOptions `fmap` getState updateState $ \state -> state{ stateOptions = oldOpts{ readerParseRaw = True , readerOldDashes = True } } many blankline startPos <- getPosition -- go through once just to get list of reference keys and notes -- docMinusKeys is the raw document with blanks where the keys/notes were... let firstPassParser = noteBlock <|> lineClump manyTill firstPassParser eof >>= setInput . concat setPosition startPos st' <- getState let reversedNotes = stateNotes st' updateState $ \s -> s { stateNotes = reverse reversedNotes } -- now parse it for real... blocks <- parseBlocks return $ Pandoc nullMeta (B.toList blocks) -- FIXME noteMarker :: Parser [Char] ParserState [Char] noteMarker = skipMany spaceChar >> string "fn" >> manyTill digit (char '.') noteBlock :: Parser [Char] ParserState [Char] noteBlock = try $ do startPos <- getPosition ref <- noteMarker optional blankline contents <- liftM unlines $ many1Till anyLine (blanklines <|> noteBlock) endPos <- getPosition let newnote = (ref, contents ++ "\n") st <- getState let oldnotes = stateNotes st updateState $ \s -> s { stateNotes = newnote : oldnotes } -- return blanks so line count isn't affected return $ replicate (sourceLine endPos - sourceLine startPos) '\n' -- | Parse document blocks parseBlocks :: Parser [Char] ParserState Blocks parseBlocks = mconcat <$> manyTill block eof -- | Block parsers list tried in definition order blockParsers :: [Parser [Char] ParserState Blocks] blockParsers = [ codeBlock , header , blockQuote , hrule , commentBlock , anyList , rawHtmlBlock , rawLaTeXBlock' , maybeExplicitBlock "table" table , maybeExplicitBlock "p" para , mempty <$ blanklines ] -- | Any block in the order of definition of blockParsers block :: Parser [Char] ParserState Blocks block = do res <- choice blockParsers <?> "block" pos <- getPosition tr <- getOption readerTrace when tr $ trace (printf "line %d: %s" (sourceLine pos) (take 60 $ show $ B.toList res)) (return ()) return res commentBlock :: Parser [Char] ParserState Blocks commentBlock = try $ do string "###." manyTill anyLine blanklines return mempty codeBlock :: Parser [Char] ParserState Blocks codeBlock = codeBlockBc <|> codeBlockPre codeBlockBc :: Parser [Char] ParserState Blocks codeBlockBc = try $ do string "bc. " contents <- manyTill anyLine blanklines return $ B.codeBlock (unlines contents) -- | Code Blocks in Textile are between <pre> and </pre> codeBlockPre :: Parser [Char] ParserState Blocks codeBlockPre = try $ do (t@(TagOpen _ attrs),_) <- htmlTag (tagOpen (=="pre") (const True)) result' <- (innerText . parseTags) `fmap` -- remove internal tags manyTill anyChar (htmlTag (tagClose (=="pre"))) optional blanklines -- drop leading newline if any let result'' = case result' of '\n':xs -> xs _ -> result' -- drop trailing newline if any let result''' = case reverse result'' of '\n':_ -> init result'' _ -> result'' let classes = words $ fromAttrib "class" t let ident = fromAttrib "id" t let kvs = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"] return $ B.codeBlockWith (ident,classes,kvs) result''' -- | Header of the form "hN. content" with N in 1..6 header :: Parser [Char] ParserState Blocks header = try $ do char 'h' level <- digitToInt <$> oneOf "123456" attr <- attributes char '.' lookAhead whitespace name <- trimInlines . mconcat <$> many inline attr' <- registerHeader attr name return $ B.headerWith attr' level name -- | Blockquote of the form "bq. content" blockQuote :: Parser [Char] ParserState Blocks blockQuote = try $ do string "bq" >> attributes >> char '.' >> whitespace B.blockQuote <$> para -- Horizontal rule hrule :: Parser [Char] st Blocks hrule = try $ do skipSpaces start <- oneOf "-*" count 2 (skipSpaces >> char start) skipMany (spaceChar <|> char start) newline optional blanklines return B.horizontalRule -- Lists handling -- | Can be a bullet list or an ordered list. This implementation is -- strict in the nesting, sublist must start at exactly "parent depth -- plus one" anyList :: Parser [Char] ParserState Blocks anyList = try $ anyListAtDepth 1 <* blanklines -- | This allow one type of list to be nested into an other type, -- provided correct nesting anyListAtDepth :: Int -> Parser [Char] ParserState Blocks anyListAtDepth depth = choice [ bulletListAtDepth depth, orderedListAtDepth depth, definitionList ] -- | Bullet List of given depth, depth being the number of leading '*' bulletListAtDepth :: Int -> Parser [Char] ParserState Blocks bulletListAtDepth depth = try $ B.bulletList <$> many1 (bulletListItemAtDepth depth) -- | Bullet List Item of given depth, depth being the number of -- leading '*' bulletListItemAtDepth :: Int -> Parser [Char] ParserState Blocks bulletListItemAtDepth = genericListItemAtDepth '*' -- | Ordered List of given depth, depth being the number of -- leading '#' orderedListAtDepth :: Int -> Parser [Char] ParserState Blocks orderedListAtDepth depth = try $ do items <- many1 (orderedListItemAtDepth depth) return $ B.orderedList items -- | Ordered List Item of given depth, depth being the number of -- leading '#' orderedListItemAtDepth :: Int -> Parser [Char] ParserState Blocks orderedListItemAtDepth = genericListItemAtDepth '#' -- | Common implementation of list items genericListItemAtDepth :: Char -> Int -> Parser [Char] ParserState Blocks genericListItemAtDepth c depth = try $ do count depth (char c) >> attributes >> whitespace p <- mconcat <$> many listInline newline sublist <- option mempty (anyListAtDepth (depth + 1)) return $ (B.plain p) <> sublist -- | A definition list is a set of consecutive definition items definitionList :: Parser [Char] ParserState Blocks definitionList = try $ B.definitionList <$> many1 definitionListItem -- | List start character. listStart :: Parser [Char] ParserState () listStart = genericListStart '*' <|> () <$ genericListStart '#' <|> () <$ definitionListStart genericListStart :: Char -> Parser [Char] st () genericListStart c = () <$ try (many1 (char c) >> whitespace) definitionListStart :: Parser [Char] ParserState Inlines definitionListStart = try $ do char '-' whitespace trimInlines . mconcat <$> many1Till inline (try (string ":=")) <* optional whitespace listInline :: Parser [Char] ParserState Inlines listInline = try (notFollowedBy newline >> inline) <|> try (endline <* notFollowedBy listStart) -- | A definition list item in textile begins with '- ', followed by -- the term defined, then spaces and ":=". The definition follows, on -- the same single line, or spaned on multiple line, after a line -- break. definitionListItem :: Parser [Char] ParserState (Inlines, [Blocks]) definitionListItem = try $ do term <- definitionListStart def' <- multilineDef <|> inlineDef return (term, def') where inlineDef :: Parser [Char] ParserState [Blocks] inlineDef = liftM (\d -> [B.plain d]) $ optional whitespace >> (trimInlines . mconcat <$> many listInline) <* newline multilineDef :: Parser [Char] ParserState [Blocks] multilineDef = try $ do optional whitespace >> newline s <- many1Till anyChar (try (string "=:" >> newline)) -- this ++ "\n\n" does not look very good ds <- parseFromString parseBlocks (s ++ "\n\n") return [ds] -- raw content -- | A raw Html Block, optionally followed by blanklines rawHtmlBlock :: Parser [Char] ParserState Blocks rawHtmlBlock = try $ do skipMany spaceChar (_,b) <- htmlTag isBlockTag optional blanklines return $ B.rawBlock "html" b -- | Raw block of LaTeX content rawLaTeXBlock' :: Parser [Char] ParserState Blocks rawLaTeXBlock' = do guardEnabled Ext_raw_tex B.rawBlock "latex" <$> (rawLaTeXBlock <* spaces) -- | In textile, paragraphs are separated by blank lines. para :: Parser [Char] ParserState Blocks para = B.para . trimInlines . mconcat <$> many1 inline -- Tables -- | A table cell spans until a pipe | tableCell :: Bool -> Parser [Char] ParserState Blocks tableCell headerCell = try $ do char '|' when headerCell $ () <$ string "_." notFollowedBy blankline raw <- trim <$> many (noneOf "|\n" <|> try (char '\n' <* notFollowedBy blankline)) content <- mconcat <$> parseFromString (many inline) raw return $ B.plain content -- | A table row is made of many table cells tableRow :: Parser [Char] ParserState [Blocks] tableRow = many1 (tableCell False) <* char '|' <* newline tableHeader :: Parser [Char] ParserState [Blocks] tableHeader = many1 (tableCell True) <* char '|' <* newline -- | A table with an optional header. Current implementation can -- handle tables with and without header, but will parse cells -- alignment attributes as content. table :: Parser [Char] ParserState Blocks table = try $ do headers <- option mempty $ tableHeader rows <- many1 tableRow blanklines let nbOfCols = max (length headers) (length $ head rows) return $ B.table mempty (zip (replicate nbOfCols AlignDefault) (replicate nbOfCols 0.0)) headers rows -- | Blocks like 'p' and 'table' do not need explicit block tag. -- However, they can be used to set HTML/CSS attributes when needed. maybeExplicitBlock :: String -- ^ block tag name -> Parser [Char] ParserState Blocks -- ^ implicit block -> Parser [Char] ParserState Blocks maybeExplicitBlock name blk = try $ do optional $ try $ string name >> attributes >> char '.' >> optional whitespace >> optional endline blk ---------- -- Inlines ---------- -- | Any inline element inline :: Parser [Char] ParserState Inlines inline = do choice inlineParsers <?> "inline" -- | Inline parsers tried in order inlineParsers :: [Parser [Char] ParserState Inlines] inlineParsers = [ str , whitespace , endline , code , escapedInline , inlineMarkup , groupedInlineMarkup , rawHtmlInline , rawLaTeXInline' , note , link , image , mark , (B.str . (:[])) <$> characterReference , smartPunctuation inline , symbol ] -- | Inline markups inlineMarkup :: Parser [Char] ParserState Inlines inlineMarkup = choice [ simpleInline (string "??") (B.cite []) , simpleInline (string "**") B.strong , simpleInline (string "__") B.emph , simpleInline (char '*') B.strong , simpleInline (char '_') B.emph , simpleInline (char '+') B.emph -- approximates underline , simpleInline (char '-' <* notFollowedBy (char '-')) B.strikeout , simpleInline (char '^') B.superscript , simpleInline (char '~') B.subscript , simpleInline (char '%') id ] -- | Trademark, registered, copyright mark :: Parser [Char] st Inlines mark = try $ char '(' >> (try tm <|> try reg <|> copy) reg :: Parser [Char] st Inlines reg = do oneOf "Rr" char ')' return $ B.str "\174" tm :: Parser [Char] st Inlines tm = do oneOf "Tt" oneOf "Mm" char ')' return $ B.str "\8482" copy :: Parser [Char] st Inlines copy = do oneOf "Cc" char ')' return $ B.str "\169" note :: Parser [Char] ParserState Inlines note = try $ do ref <- (char '[' *> many1 digit <* char ']') notes <- stateNotes <$> getState case lookup ref notes of Nothing -> fail "note not found" Just raw -> B.note <$> parseFromString parseBlocks raw -- | Special chars markupChars :: [Char] markupChars = "\\*#_@~-+^|%=[]&" -- | Break strings on following chars. Space tab and newline break for -- inlines breaking. Open paren breaks for mark. Quote, dash and dot -- break for smart punctuation. Punctuation breaks for regular -- punctuation. Double quote breaks for named links. > and < break -- for inline html. stringBreakers :: [Char] stringBreakers = " \t\n\r.,\"'?!;:<>«»„“”‚‘’()[]" wordBoundaries :: [Char] wordBoundaries = markupChars ++ stringBreakers -- | Parse a hyphened sequence of words hyphenedWords :: Parser [Char] ParserState String hyphenedWords = do x <- wordChunk xs <- many (try $ char '-' >> wordChunk) return $ intercalate "-" (x:xs) wordChunk :: Parser [Char] ParserState String wordChunk = try $ do hd <- noneOf wordBoundaries tl <- many ( (noneOf wordBoundaries) <|> try (notFollowedBy' note *> oneOf markupChars <* lookAhead (noneOf wordBoundaries) ) ) return $ hd:tl -- | Any string str :: Parser [Char] ParserState Inlines str = do baseStr <- hyphenedWords -- RedCloth compliance : if parsed word is uppercase and immediatly -- followed by parens, parens content is unconditionally word acronym fullStr <- option baseStr $ try $ do guard $ all isUpper baseStr acro <- enclosed (char '(') (char ')') anyChar' return $ concat [baseStr, " (", acro, ")"] updateLastStrPos return $ B.str fullStr -- | Some number of space chars whitespace :: Parser [Char] st Inlines whitespace = many1 spaceChar >> return B.space <?> "whitespace" -- | In Textile, an isolated endline character is a line break endline :: Parser [Char] ParserState Inlines endline = try $ do newline notFollowedBy blankline notFollowedBy listStart notFollowedBy rawHtmlBlock return B.linebreak rawHtmlInline :: Parser [Char] ParserState Inlines rawHtmlInline = B.rawInline "html" . snd <$> htmlTag (const True) -- | Raw LaTeX Inline rawLaTeXInline' :: Parser [Char] ParserState Inlines rawLaTeXInline' = try $ do guardEnabled Ext_raw_tex B.singleton <$> rawLaTeXInline -- | Textile standard link syntax is "label":target. But we -- can also have ["label":target]. link :: Parser [Char] ParserState Inlines link = try $ do bracketed <- (True <$ char '[') <|> return False char '"' *> notFollowedBy (oneOf " \t\n\r") attr <- attributes name <- trimInlines . mconcat <$> withQuoteContext InDoubleQuote (many1Till inline (char '"')) char ':' let stop = if bracketed then char ']' else lookAhead $ space <|> try (oneOf "!.,;:" *> (space <|> newline)) url <- manyTill nonspaceChar stop let name' = if B.toList name == [Str "$"] then B.str url else name return $ if attr == nullAttr then B.link url "" name' else B.spanWith attr $ B.link url "" name' -- | image embedding image :: Parser [Char] ParserState Inlines image = try $ do char '!' >> notFollowedBy space src <- manyTill anyChar' (lookAhead $ oneOf "!(") alt <- option "" (try $ (char '(' >> manyTill anyChar' (char ')'))) char '!' return $ B.image src alt (B.str alt) escapedInline :: Parser [Char] ParserState Inlines escapedInline = escapedEqs <|> escapedTag escapedEqs :: Parser [Char] ParserState Inlines escapedEqs = B.str <$> (try $ string "==" *> manyTill anyChar' (try $ string "==")) -- | literal text escaped btw <notextile> tags escapedTag :: Parser [Char] ParserState Inlines escapedTag = B.str <$> (try $ string "<notextile>" *> manyTill anyChar' (try $ string "</notextile>")) -- | Any special symbol defined in wordBoundaries symbol :: Parser [Char] ParserState Inlines symbol = B.str . singleton <$> (notFollowedBy newline *> notFollowedBy rawHtmlBlock *> oneOf wordBoundaries) -- | Inline code code :: Parser [Char] ParserState Inlines code = code1 <|> code2 -- any character except a newline before a blank line anyChar' :: Parser [Char] ParserState Char anyChar' = satisfy (/='\n') <|> (try $ char '\n' <* notFollowedBy blankline) code1 :: Parser [Char] ParserState Inlines code1 = B.code <$> surrounded (char '@') anyChar' code2 :: Parser [Char] ParserState Inlines code2 = do htmlTag (tagOpen (=="tt") null) B.code <$> manyTill anyChar' (try $ htmlTag $ tagClose (=="tt")) -- | Html / CSS attributes attributes :: Parser [Char] ParserState Attr attributes = (foldl (flip ($)) ("",[],[])) `fmap` many attribute attribute :: Parser [Char] ParserState (Attr -> Attr) attribute = classIdAttr <|> styleAttr <|> langAttr classIdAttr :: Parser [Char] ParserState (Attr -> Attr) classIdAttr = try $ do -- (class class #id) char '(' ws <- words `fmap` manyTill anyChar' (char ')') case reverse ws of [] -> return $ \(_,_,keyvals) -> ("",[],keyvals) (('#':ident'):classes') -> return $ \(_,_,keyvals) -> (ident',classes',keyvals) classes' -> return $ \(_,_,keyvals) -> ("",classes',keyvals) styleAttr :: Parser [Char] ParserState (Attr -> Attr) styleAttr = do style <- try $ enclosed (char '{') (char '}') anyChar' return $ \(id',classes,keyvals) -> (id',classes,("style",style):keyvals) langAttr :: Parser [Char] ParserState (Attr -> Attr) langAttr = do lang <- try $ enclosed (char '[') (char ']') alphaNum return $ \(id',classes,keyvals) -> (id',classes,("lang",lang):keyvals) -- | Parses material surrounded by a parser. surrounded :: Parser [Char] st t -- ^ surrounding parser -> Parser [Char] st a -- ^ content parser (to be used repeatedly) -> Parser [Char] st [a] surrounded border = enclosed (border *> notFollowedBy (oneOf " \t\n\r")) (try border) simpleInline :: Parser [Char] ParserState t -- ^ surrounding parser -> (Inlines -> Inlines) -- ^ Inline constructor -> Parser [Char] ParserState Inlines -- ^ content parser (to be used repeatedly) simpleInline border construct = try $ do st <- getState pos <- getPosition let afterString = stateLastStrPos st == Just pos guard $ not afterString border *> notFollowedBy (oneOf " \t\n\r") attr <- attributes body <- trimInlines . mconcat <$> withQuoteContext InSingleQuote (manyTill (notFollowedBy newline >> inline) (try border <* notFollowedBy alphaNum)) return $ construct $ if attr == nullAttr then body else B.spanWith attr body groupedInlineMarkup :: Parser [Char] ParserState Inlines groupedInlineMarkup = try $ do char '[' sp1 <- option mempty $ B.space <$ whitespace result <- withQuoteContext InSingleQuote inlineMarkup sp2 <- option mempty $ B.space <$ whitespace char ']' return $ sp1 <> result <> sp2 -- | Create a singleton list singleton :: a -> [a] singleton x = [x]
alexvong1995/pandoc
src/Text/Pandoc/Readers/Textile.hs
gpl-2.0
22,245
0
17
5,345
5,793
2,950
2,843
424
4
{-# 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.OpsWorks.StopStack -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- 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 <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Stops a specified stack. -- -- Required Permissions: To use this action, an IAM user must have a Manage -- permissions level for the stack, or an attached policy that explicitly grants -- permissions. For more information on user permissions, see <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing UserPermissions>. -- -- <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_StopStack.html> module Network.AWS.OpsWorks.StopStack ( -- * Request StopStack -- ** Request constructor , stopStack -- ** Request lenses , ss1StackId -- * Response , StopStackResponse -- ** Response constructor , stopStackResponse ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.OpsWorks.Types import qualified GHC.Exts newtype StopStack = StopStack { _ss1StackId :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'StopStack' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ss1StackId' @::@ 'Text' -- stopStack :: Text -- ^ 'ss1StackId' -> StopStack stopStack p1 = StopStack { _ss1StackId = p1 } -- | The stack ID. ss1StackId :: Lens' StopStack Text ss1StackId = lens _ss1StackId (\s a -> s { _ss1StackId = a }) data StopStackResponse = StopStackResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'StopStackResponse' constructor. stopStackResponse :: StopStackResponse stopStackResponse = StopStackResponse instance ToPath StopStack where toPath = const "/" instance ToQuery StopStack where toQuery = const mempty instance ToHeaders StopStack instance ToJSON StopStack where toJSON StopStack{..} = object [ "StackId" .= _ss1StackId ] instance AWSRequest StopStack where type Sv StopStack = OpsWorks type Rs StopStack = StopStackResponse request = post "StopStack" response = nullResponse StopStackResponse
romanb/amazonka
amazonka-opsworks/gen/Network/AWS/OpsWorks/StopStack.hs
mpl-2.0
3,029
0
9
667
360
221
139
48
1
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} -- Module : Gen.Model -- Copyright : (c) 2013-2015 Brendan Hay <brendan.g.hay@gmail.com> -- 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 <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) module Gen.Model where import Control.Applicative import Control.Error import Control.Monad import Data.List (sort) import Gen.IO import Gen.JSON import Gen.Types import System.Directory import System.FilePath loadRetries :: FilePath -> Script Retries loadRetries = requireObject >=> parse loadModel :: FilePath -> FilePath -> Script Model loadModel d o = do v <- version m1 <- requireObject override m2 <- merge <$> sequence [ return m1 , requireObject (normal v) , optionalObject "waiters" (waiters v) , optionalObject "pagination" (pagers v) ] Model name v d m2 <$> parse m1 where version = do fs <- reverse . sort . filter dots <$> scriptIO (getDirectoryContents d) f <- tryHead ("Failed to get model version from " ++ d) fs return (takeWhile (/= '.') f) normal = path "normal.json" waiters = path "waiters.json" pagers = path "paginators.json" path e v = d </> v <.> e override = o </> name <.> "json" name = takeBaseName (dropTrailingPathSeparator d)
romanb/amazonka
gen/src/Gen/Model.hs
mpl-2.0
1,749
0
13
512
354
184
170
34
1
-- Unpack a tarball containing a Cabal package {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Distribution.Server.Packages.Unpack ( unpackPackage, unpackPackageRaw, ) where import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar import qualified Codec.Archive.Tar.Check as Tar import Distribution.Version ( Version(..) ) import Distribution.Package ( PackageIdentifier, packageVersion, packageName, PackageName(..) ) import Distribution.PackageDescription ( GenericPackageDescription(..), PackageDescription(..) , exposedModules ) import Distribution.PackageDescription.Parse ( parsePackageDescription ) import Distribution.PackageDescription.Configuration ( flattenPackageDescription ) import Distribution.PackageDescription.Check ( PackageCheck(..), checkPackage ) import Distribution.ParseUtils ( ParseResult(..), locatedErrorMsg, showPWarning ) import Distribution.Text ( display, simpleParse ) import Distribution.ModuleName ( components ) import Distribution.Server.Util.Parse ( unpackUTF8 ) import Data.List ( nub, (\\), partition, intercalate ) import Data.Time ( UTCTime(..), fromGregorian, addUTCTime ) import Data.Time.Clock.POSIX ( posixSecondsToUTCTime ) import Control.Monad ( unless, when ) import Control.Monad.Error ( ErrorT(..) ) import Control.Monad.Writer ( WriterT(..), MonadWriter, tell ) import Control.Monad.Identity ( Identity(..) ) import qualified Distribution.Server.Util.GZip as GZip import Data.ByteString.Lazy ( ByteString ) import qualified Data.ByteString.Lazy as LBS import System.FilePath ( (</>), (<.>), splitDirectories, splitExtension, normalise ) import qualified System.FilePath.Windows ( takeFileName ) -- | Upload or check a tarball containing a Cabal package. -- Returns either an fatal error or a package description and a list -- of warnings. unpackPackage :: UTCTime -> FilePath -> ByteString -> Either String ((GenericPackageDescription, ByteString), [String]) unpackPackage now tarGzFile contents = runUploadMonad $ do (pkgDesc, warnings, cabalEntry) <- basicChecks False now tarGzFile contents mapM_ fail warnings extraChecks pkgDesc return (pkgDesc, cabalEntry) unpackPackageRaw :: FilePath -> ByteString -> Either String ((GenericPackageDescription, ByteString), [String]) unpackPackageRaw tarGzFile contents = runUploadMonad $ do (pkgDesc, _warnings, cabalEntry) <- basicChecks True noTime tarGzFile contents return (pkgDesc, cabalEntry) where noTime = UTCTime (fromGregorian 1970 1 1) 0 basicChecks :: Bool -> UTCTime -> FilePath -> ByteString -> UploadMonad (GenericPackageDescription, [String], ByteString) basicChecks lax now tarGzFile contents = do let (pkgidStr, ext) = (base, tar ++ gz) where (tarFile, gz) = splitExtension (portableTakeFileName tarGzFile) (base, tar) = splitExtension tarFile unless (ext == ".tar.gz") $ fail $ tarGzFile ++ " is not a gzipped tar file, it must have the .tar.gz extension" pkgid <- case simpleParse pkgidStr of Just pkgid | null . versionBranch . packageVersion $ pkgid -> fail $ "Invalid package id " ++ quote pkgidStr ++ ". It must include the package version number, and not just " ++ "the package name, e.g. 'foo-1.0'." | display pkgid == pkgidStr -> return (pkgid :: PackageIdentifier) | not . null . versionTags . packageVersion $ pkgid -> fail $ "Hackage no longer accepts packages with version tags: " ++ intercalate ", " (versionTags (packageVersion pkgid)) _ -> fail $ "Invalid package id " ++ quote pkgidStr ++ ". The tarball must use the name of the package." -- Extract entries and check the tar format / portability let entries = tarballChecks lax now expectedDir $ Tar.read (GZip.decompressNamed tarGzFile contents) expectedDir = display pkgid -- Extract the .cabal file from the tarball let selectEntry entry = case Tar.entryContent entry of Tar.NormalFile bs _ | cabalFileName == normalise (Tar.entryPath entry) -> Just bs _ -> Nothing PackageName name = packageName pkgid cabalFileName = display pkgid </> name <.> "cabal" cabalEntries <- selectEntries explainTarError selectEntry entries cabalEntry <- case cabalEntries of -- NB: tar files *can* contain more than one entry for the same filename. -- (This was observed in practice with the package CoreErlang-0.0.1). -- In this case, after extracting the tar the *last* file in the archive -- wins. Since selectEntries returns results in reverse order we use the head: cabalEntry:_ -> -- We tend to keep hold of the .cabal file, but -- cabalEntry itself is part of a much larger -- ByteString (the whole tar file), so we make a -- copy of it return $ LBS.copy cabalEntry [] -> fail $ "The " ++ quote cabalFileName ++ " file is missing from the package tarball." -- Parse the Cabal file let cabalFileContent = unpackUTF8 cabalEntry (pkgDesc, warnings) <- case parsePackageDescription cabalFileContent of ParseFailed err -> fail $ showError (locatedErrorMsg err) ParseOk warnings pkgDesc -> return (pkgDesc, map (showPWarning cabalFileName) warnings) -- Check that the name and version in Cabal file match when (packageName pkgDesc /= packageName pkgid) $ fail "Package name in the cabal file does not match the file name." when (packageVersion pkgDesc /= packageVersion pkgid) $ fail "Package version in the cabal file does not match the file name." return (pkgDesc, warnings, cabalEntry) where showError (Nothing, msg) = msg showError (Just n, msg) = "line " ++ show n ++ ": " ++ msg -- | The issue is that browsers can upload the file name using either unix -- or windows convention, so we need to take the basename using either -- convention. Since windows allows the unix '/' as a separator then we can -- use the Windows.takeFileName as a portable solution. -- portableTakeFileName :: FilePath -> String portableTakeFileName = System.FilePath.Windows.takeFileName -- Miscellaneous checks on package description extraChecks :: GenericPackageDescription -> UploadMonad () extraChecks genPkgDesc = do let pkgDesc = flattenPackageDescription genPkgDesc -- various checks --FIXME: do the content checks. The dev version of Cabal generalises -- checkPackageContent to work in any monad, we just need to provide -- a record of ops that will do checks inside the tarball. We should -- gather a map of files and dirs and have these just to map lookups: -- -- > checkTarballContents = CheckPackageContentOps { -- > doesFileExist = Set.member fileMap, -- > doesDirectoryExist = Set.member dirsMap -- > } -- > fileChecks <- checkPackageContent checkTarballContents pkgDesc let pureChecks = checkPackage genPkgDesc (Just pkgDesc) checks = pureChecks -- ++ fileChecks isDistError (PackageDistSuspicious {}) = False isDistError _ = True (errors, warnings) = partition isDistError checks mapM_ (fail . explanation) errors mapM_ (warn . explanation) warnings -- Check reasonableness of names of exposed modules let topLevel = case library pkgDesc of Nothing -> [] Just l -> nub $ map head $ filter (not . null) $ map components $ exposedModules l badTopLevel = topLevel \\ allocatedTopLevelNodes unless (null badTopLevel) $ warn $ "Exposed modules use unallocated top-level names: " ++ unwords badTopLevel -- Monad for uploading packages: -- WriterT for warning messages -- Either for fatal errors newtype UploadMonad a = UploadMonad (WriterT [String] (ErrorT String Identity) a) deriving (Monad, MonadWriter [String]) warn :: String -> UploadMonad () warn msg = tell [msg] runUploadMonad :: UploadMonad a -> Either String (a, [String]) runUploadMonad (UploadMonad m) = runIdentity . runErrorT . runWriterT $ m -- | Registered top-level nodes in the class hierarchy. allocatedTopLevelNodes :: [String] allocatedTopLevelNodes = [ "Algebra", "Codec", "Control", "Data", "Database", "Debug", "Distribution", "DotNet", "Foreign", "Graphics", "Language", "Network", "Numeric", "Prelude", "Sound", "System", "Test", "Text"] selectEntries :: (err -> String) -> (Tar.Entry -> Maybe a) -> Tar.Entries err -> UploadMonad [a] selectEntries formatErr select = extract [] where extract _ (Tar.Fail err) = fail (formatErr err) extract selected Tar.Done = return selected extract selected (Tar.Next entry entries) = case select entry of Nothing -> extract selected entries Just saved -> extract (saved : selected) entries data CombinedTarErrs = FormatError Tar.FormatError | PortabilityError Tar.PortabilityError | TarBombError FilePath FilePath | FutureTimeError FilePath UTCTime tarballChecks :: Bool -> UTCTime -> FilePath -> Tar.Entries Tar.FormatError -> Tar.Entries CombinedTarErrs tarballChecks lax now expectedDir = (if not lax then checkFutureTimes now else id) . checkTarbomb expectedDir . (if lax then ignoreShortTrailer else fmapTarError (either id PortabilityError) . Tar.checkPortability) . fmapTarError FormatError where ignoreShortTrailer = Tar.foldEntries Tar.Next Tar.Done (\e -> case e of FormatError Tar.ShortTrailer -> Tar.Done _ -> Tar.Fail e) fmapTarError f = Tar.foldEntries Tar.Next Tar.Done (Tar.Fail . f) checkFutureTimes :: UTCTime -> Tar.Entries CombinedTarErrs -> Tar.Entries CombinedTarErrs checkFutureTimes now = checkEntries checkEntry where -- Allow 30s for client clock skew now' = addUTCTime 30 now checkEntry entry | entryUTCTime > now' = Just (FutureTimeError posixPath entryUTCTime) where entryUTCTime = posixSecondsToUTCTime (realToFrac (Tar.entryTime entry)) posixPath = Tar.fromTarPathToPosixPath (Tar.entryTarPath entry) checkEntry _ = Nothing checkTarbomb :: FilePath -> Tar.Entries CombinedTarErrs -> Tar.Entries CombinedTarErrs checkTarbomb expectedTopDir = checkEntries checkEntry where checkEntry entry = case splitDirectories (Tar.entryPath entry) of (topDir:_) | topDir == expectedTopDir -> Nothing _ -> Just $ TarBombError (Tar.entryPath entry) expectedTopDir checkEntries :: (Tar.Entry -> Maybe e) -> Tar.Entries e -> Tar.Entries e checkEntries checkEntry = Tar.foldEntries (\entry rest -> maybe (Tar.Next entry rest) Tar.Fail (checkEntry entry)) Tar.Done Tar.Fail explainTarError :: CombinedTarErrs -> String explainTarError (TarBombError filename expectedDir) = "Bad file name in package tarball: " ++ quote filename ++ "\nAll the file in the package tarball must be in the subdirectory " ++ quote expectedDir ++ "." explainTarError (PortabilityError (Tar.NonPortableFormat Tar.GnuFormat)) = "This tarball is in the non-standard GNU tar format. " ++ "For portability and long-term data preservation, hackage requires that " ++ "package tarballs use the standard 'ustar' format. If you are using GNU " ++ "tar, use --format=ustar to get the standard portable format." explainTarError (PortabilityError (Tar.NonPortableFormat Tar.V7Format)) = "This tarball is in the old Unix V7 tar format. " ++ "For portability and long-term data preservation, hackage requires that " ++ "package tarballs use the standard 'ustar' format. Virtually all tar " ++ "programs can now produce ustar format (POSIX 1988). For example if you " ++ "are using GNU tar, use --format=ustar to get the standard portable format." explainTarError (PortabilityError (Tar.NonPortableFormat Tar.UstarFormat)) = error "explainTarError: impossible UstarFormat" explainTarError (PortabilityError Tar.NonPortableFileType) = "The package tarball contains a non-portable entry type. " ++ "For portability, package tarballs should use the 'ustar' format " ++ "and only contain normal files, directories and file links." explainTarError (PortabilityError (Tar.NonPortableEntryNameChar _)) = "The package tarball contains an entry with a non-ASCII file name. " ++ "For portability, package tarballs should contain only ASCII file names " ++ "(e.g. not UTF8 encoded Unicode)." explainTarError (PortabilityError (err@Tar.NonPortableFileName {})) = show err ++ ". For portability, hackage requires that file names be valid on both Unix " ++ "and Windows systems, and not refer outside of the tarball." explainTarError (FormatError formateror) = "There is an error in the format of the tar file: " ++ show formateror ++ ". Check that it is a valid tar file (e.g. 'tar -xtf thefile.tar'). " ++ "You may need to re-create the package tarball and try again." explainTarError (FutureTimeError entryname time) = "The tarball entry " ++ quote entryname ++ " has a file timestamp that is " ++ "in the future (" ++ show time ++ "). This tends to cause problems " ++ "for build systems and other tools, so hackage does not allow it. This " ++ "problem can be caused by having a misconfigured system time, or by bugs " ++ "in the tools (tarballs created by 'cabal sdist' on Windows with " ++ "cabal-install-1.18.0.2 or older have this problem)." quote :: String -> String quote s = "'" ++ s ++ "'"
haskell-infra/hackage-server
Distribution/Server/Packages/Unpack.hs
bsd-3-clause
14,144
0
20
3,352
2,844
1,502
1,342
244
6
{-# OPTIONS_GHC -fglasgow-exts #-} {-# OPTIONS_GHC -fno-spec-constr-count #-} -- -- TODO: -- permute operations, which are fairly important for this algorithm, are currently -- all sequential module QSortPar (qsortPar) where import Data.Array.Parallel.Unlifted.Distributed import Data.Array.Parallel.Unlifted.Parallel import Data.Array.Parallel.Unlifted import Debug.Trace -- I'm lazy here and use the lifted qsort instead of writing a flat version qsortPar :: UArr Double -> UArr Double {-# NOINLINE qsortPar #-} qsortPar = concatSU . qsortLifted . singletonSU -- Remove the trivially sorted segments qsortLifted:: SUArr Double -> SUArr Double qsortLifted xssArr = splitApplySUP flags qsortLifted' id xssArr where flags = mapUP ((> 1)) $ lengthsSU xssArr -- Actual sorting qsortLifted' xssarr = if (xssLen == 0) then xssarr else (takeCU xssLen sorted) ^+:+^ equal ^+:+^ (dropCU xssLen sorted) where xssLen = lengthSU xssarr xsLens = lengthsSU xssarr pivots = xssarr !:^ mapUP (flip div 2) xsLens pivotss = replicateSUP xsLens pivots xarrLens = zipSU xssarr pivotss sorted = qsortLifted (smaller +:+^ greater) smaller = fstSU $ filterSUP (uncurryS (<)) xarrLens greater = fstSU $ filterSUP (uncurryS (>)) xarrLens equal = fstSU $ filterSUP (uncurryS (==)) xarrLens splitApplySUP:: (UA e, UA e', Show e, Show e') => UArr Bool -> (SUArr e -> SUArr e') -> (SUArr e -> SUArr e') -> SUArr e -> SUArr e' {-# INLINE splitApplySUP #-} splitApplySUP flags f1 f2 xssArr = if (lengthSU xssArr == 0) then segmentArrU emptyU emptyU else combineCU flags res1 res2 where res1 = f1 $ packCUP flags xssArr res2 = f2 $ packCUP (mapUP not flags) xssArr
mainland/dph
icebox/examples/qsort/QSortPar.hs
bsd-3-clause
1,777
0
11
394
485
259
226
36
2
module Language.Haskell.GhcMod.Debug (debugInfo, rootInfo) where import Control.Applicative ((<$>)) import Data.List (intercalate) import Data.Maybe (isJust, fromJust) import Language.Haskell.GhcMod.Convert import Language.Haskell.GhcMod.Monad import Language.Haskell.GhcMod.Types import Language.Haskell.GhcMod.Internal ---------------------------------------------------------------- -- | Obtaining debug information. debugInfo :: IOish m => GhcModT m String debugInfo = cradle >>= \c -> convert' =<< do CompilerOptions gopts incDir pkgs <- if isJust $ cradleCabalFile c then fromCabalFile c ||> simpleCompilerOption else simpleCompilerOption return [ "Root directory: " ++ cradleRootDir c , "Current directory: " ++ cradleCurrentDir c , "Cabal file: " ++ show (cradleCabalFile c) , "GHC options: " ++ unwords gopts , "Include directories: " ++ unwords incDir , "Dependent packages: " ++ intercalate ", " (map showPkg pkgs) , "System libraries: " ++ ghcLibDir ] where simpleCompilerOption = options >>= \op -> return $ CompilerOptions (ghcUserOptions op) [] [] fromCabalFile c = options >>= \opts -> do pkgDesc <- parseCabalFile c $ fromJust $ cradleCabalFile c getCompilerOptions (ghcUserOptions opts) c pkgDesc ---------------------------------------------------------------- -- | Obtaining root information. rootInfo :: IOish m => GhcModT m String rootInfo = convert' =<< cradleRootDir <$> cradle
cabrera/ghc-mod
Language/Haskell/GhcMod/Debug.hs
bsd-3-clause
1,569
0
15
342
364
195
169
29
2
import ChineseCheckers import Table import Test.QuickCheck import Haste.Graphics.Canvas newtype TableCoords = TableCoords (Table, Content, (Int,Int)) deriving (Show) newtype OnlyPiece = OnlyPiece Content deriving (Show) newtype TableCoords2 = TableCoords2 (Table, Content, (Int,Int)) deriving (Show) instance Arbitrary OnlyPiece where arbitrary = do con <- arbitrary :: Gen Color return $ OnlyPiece (Piece con) -- | Generates non-empty tables with a coord that exists in the table instance Arbitrary TableCoords where arbitrary = do con <- arbitrary :: Gen Content table <- listOf1 arbitrary :: Gen Table coord <- elements $ map getCoord' table return $ TableCoords (table,con,coord) instance Arbitrary TableCoords2 where arbitrary = do con <- arbitrary :: Gen Content coord <- elements $ map getCoord' startTable return $ TableCoords2 (startTable,con,coord) getCoord' :: Square -> Coord getCoord' (Square _ _ c) = c instance Arbitrary Color where arbitrary = elements [white, red, blue, green] instance Arbitrary Content where arbitrary = do col <- arbitrary frequency [(1, return Empty),(4,return (Piece col))] instance Arbitrary Square where arbitrary = do content <- arbitrary :: Gen Content color <- arbitrary :: Gen Color x <- arbitrary :: Gen Int y <- arbitrary :: Gen Int return $ Square content color (x,y) prop_removePiece :: TableCoords -> Bool prop_removePiece (TableCoords (t, c, coord)) = squareContent (removePiece (putPiece t c coord) coord) coord == Empty prop_putPiece :: TableCoords -> OnlyPiece -> Bool prop_putPiece (TableCoords (t, _, coord)) (OnlyPiece p) = squareContent (putPiece t p coord) coord /= Empty prop_move :: TableCoords2 -> Bool prop_move (TableCoords2 (t, _, coord)) = all (dist coord) (canMove coord t) dist :: Coord -> Square -> Bool dist (x2,y2) (Square _ _ (x1,y1)) = sqrt(fromIntegral(x2-x1)^2 + fromIntegral(y2-y1)^2) <= 4 --test startTable if all squares with no pieces are white testStartTable :: Table -> Bool testStartTable xs |testStartTable' xs > 1 = False |otherwise = True testStartTable' :: Table -> Int testStartTable' [] = 0 testStartTable' (Square (Piece _) color _ :xs) = testStartTable' xs testStartTable' (Square Empty color _ :xs) |color == white = testStartTable' xs |otherwise = 1 + testStartTable' xs
DATx02-16-14/Hastings
test/Tests.hs
bsd-3-clause
2,636
0
13
711
871
450
421
58
1
----------------------------------------------------------------------------- -- | -- Module : CppIfdef -- Copyright : 1999-2004 Malcolm Wallace -- Licence : LGPL -- -- Maintainer : Malcolm Wallace <Malcolm.Wallace@cs.york.ac.uk> -- Stability : experimental -- Portability : All -- -- Perform a cpp.first-pass, gathering \#define's and evaluating \#ifdef's. -- and \#include's. ----------------------------------------------------------------------------- module Language.Preprocessor.Cpphs.CppIfdef ( cppIfdef -- :: FilePath -> [(String,String)] -> [String] -> Bool -> Bool -- -> String -> [(Posn,String)] ) where import Language.Preprocessor.Cpphs.SymTab import Text.ParserCombinators.HuttonMeijer -- import HashDefine import Language.Preprocessor.Cpphs.Position (Posn,newfile,newline,newlines,cppline,newpos) import Language.Preprocessor.Cpphs.ReadFirst (readFirst) import Language.Preprocessor.Cpphs.Tokenise (linesCpp,reslash) import Char (isDigit) import Numeric (readHex,readOct,readDec) import System.IO.Unsafe (unsafePerformIO) import IO (hPutStrLn,stderr) -- | Run a first pass of cpp, evaluating \#ifdef's and processing \#include's, -- whilst taking account of \#define's and \#undef's as we encounter them. cppIfdef :: FilePath -- ^ File for error reports -> [(String,String)] -- ^ Pre-defined symbols and their values -> [String] -- ^ Search path for \#includes -> Bool -- ^ Leave \#define and \#undef in output? -> Bool -- ^ Place \#line droppings in output? -> String -- ^ The input file content -> [(Posn,String)] -- ^ The file after processing (in lines) cppIfdef fp syms search leave locat = cpp posn defs search leave locat Keep . (cppline posn:) . linesCpp where posn = newfile fp defs = foldr insertST emptyST syms -- Notice that the symbol table is a very simple one mapping strings -- to strings. This pass does not need anything more elaborate, in -- particular it is not required to deal with any parameterised macros. -- | Internal state for whether lines are being kept or dropped. -- In @Drop n b@, @n@ is the depth of nesting, @b@ is whether -- we have already succeeded in keeping some lines in a chain of -- @elif@'s data KeepState = Keep | Drop Int Bool -- | Return just the list of lines that the real cpp would decide to keep. cpp :: Posn -> SymTab String -> [String] -> Bool -> Bool -> KeepState -> [String] -> [(Posn,String)] cpp _ _ _ _ _ _ [] = [] cpp p syms path leave ln Keep (l@('#':x):xs) = let ws = words x cmd = head ws sym = head (tail ws) rest = tail (tail ws) val = maybe "1" id (un rest) un v = if null v then Nothing else Just (unwords v) down = if definedST sym syms then (Drop 1 False) else Keep up = if definedST sym syms then Keep else (Drop 1 False) keep str = if gatherDefined p syms str then Keep else (Drop 1 False) skipn cpp' p' syms' path' ud xs' = let n = 1 + length (filter (=='\n') l) in (if leave then ((p,reslash l):) else (replicate n (p,"") ++)) $ cpp' (newlines n p') syms' path' leave ln ud xs' in case cmd of "define" -> skipn cpp p (insertST (sym,val) syms) path Keep xs "undef" -> skipn cpp p (deleteST sym syms) path Keep xs "ifndef" -> skipn cpp p syms path down xs "ifdef" -> skipn cpp p syms path up xs "if" -> skipn cpp p syms path (keep (unwords (tail ws))) xs "else" -> skipn cpp p syms path (Drop 1 False) xs "elif" -> skipn cpp p syms path (Drop 1 True) xs "endif" -> skipn cpp p syms path Keep xs "pragma" -> skipn cpp p syms path Keep xs ('!':_) -> skipn cpp p syms path Keep xs -- \#!runhs scripts "include"-> let (inc,content) = unsafePerformIO (readFirst (unwords (tail ws)) p path syms) in cpp p syms path leave ln Keep (("#line 1 "++show inc) : linesCpp content ++ cppline p :"": xs) "warning"-> unsafePerformIO $ do hPutStrLn stderr (l++"\nin "++show p) return $ skipn cpp p syms path Keep xs "error" -> error (l++"\nin "++show p) "line" | all isDigit sym -> (if ln then ((p,l):) else id) $ cpp (newpos (read sym) (un rest) p) syms path leave ln Keep xs n | all isDigit n -> (if ln then ((p,l):) else id) $ cpp (newpos (read n) (un (tail ws)) p) syms path leave ln Keep xs | otherwise -> unsafePerformIO $ do hPutStrLn stderr ("Warning: unknown directive #"++n ++"\nin "++show p) return $ ((p,l): cpp (newline p) syms path leave ln Keep xs) cpp p syms path leave ln (Drop n b) (('#':x):xs) = let ws = words x cmd = head ws delse | n==1 && b = Drop 1 b | n==1 = Keep | otherwise = Drop n b dend | n==1 = Keep | otherwise = Drop (n-1) b keep str | n==1 = if not b && gatherDefined p syms str then Keep else (Drop 1) b | otherwise = Drop n b skipn cpp' p' syms' path' ud xs' = let n' = 1 + length (filter (=='\n') x) in replicate n' (p,"") ++ cpp' (newlines n' p') syms' path' leave ln ud xs' in if cmd == "ifndef" || cmd == "if" || cmd == "ifdef" then skipn cpp p syms path (Drop (n+1) b) xs else if cmd == "elif" then skipn cpp p syms path (keep (unwords (tail ws))) xs else if cmd == "else" then skipn cpp p syms path delse xs else if cmd == "endif" then skipn cpp p syms path dend xs else skipn cpp p syms path (Drop n b) xs -- define, undef, include, error, warning, pragma, line cpp p syms path leave ln Keep (x:xs) = let p' = newline p in seq p' $ (p,x): cpp p' syms path leave ln Keep xs cpp p syms path leave ln d@(Drop _ _) (_:xs) = let p' = newline p in seq p' $ (p,""): cpp p' syms path leave ln d xs ---- gatherDefined :: Posn -> SymTab String -> String -> Bool gatherDefined p st inp = case papply (parseBoolExp st) inp of [] -> error ("Cannot parse #if directive in file "++show p) [(b,_)] -> b _ -> error ("Ambiguous parse for #if directive in file "++show p) parseBoolExp :: SymTab String -> Parser Bool parseBoolExp st = do a <- parseExp1 st skip (string "||") b <- first (skip (parseBoolExp st)) return (a || b) +++ parseExp1 st parseExp1 :: SymTab String -> Parser Bool parseExp1 st = do a <- parseExp0 st skip (string "&&") b <- first (skip (parseExp1 st)) return (a && b) +++ parseExp0 st parseExp0 :: SymTab String -> Parser Bool parseExp0 st = do skip (string "defined") sym <- bracket (skip (char '(')) (skip (many1 alphanum)) (skip (char ')')) return (definedST sym st) +++ do bracket (skip (char '(')) (parseBoolExp st) (skip (char ')')) +++ do skip (char '!') a <- parseExp0 st return (not a) +++ do sym1 <- skip (many1 alphanum) op <- parseOp st sym2 <- skip (many1 alphanum) let val1 = convert sym1 st let val2 = convert sym2 st return (op val1 val2) +++ do sym <- skip (many1 alphanum) case convert sym st of 0 -> return False _ -> return True where convert sym st' = case lookupST sym st' of Nothing -> safeRead sym (Just a) -> safeRead a safeRead s = case s of '0':'x':s' -> number readHex s' '0':'o':s' -> number readOct s' _ -> number readDec s number rd s = case rd s of [] -> 0 :: Integer ((n,_):_) -> n :: Integer parseOp :: SymTab String -> Parser (Integer -> Integer -> Bool) parseOp _ = do skip (string ">=") return (>=) +++ do skip (char '>') return (>) +++ do skip (string "<=") return (<=) +++ do skip (char '<') return (<) +++ do skip (string "==") return (==) +++ do skip (string "!=") return (/=)
FranklinChen/hugs98-plus-Sep2006
cpphs/Language/Preprocessor/Cpphs/CppIfdef.hs
bsd-3-clause
8,470
25
20
2,726
2,947
1,484
1,463
181
27
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} ------------------------------------------------------------------------------------- -- | -- Copyright : (c) Hans Hoglund 2012-2014 -- -- License : BSD-style -- -- Maintainer : hans@hanshoglund.se -- Stability : experimental -- Portability : non-portable (TF,GNTD) -- -- Provides various forms of title, subtitle etc. and related meta-data. -- ------------------------------------------------------------------------------------- module Music.Score.Meta.Title ( -- * Title type Title, -- ** Creating and modifying -- titleFromString, denoteTitle, getTitle, getTitleAt, -- * Adding titles to scores title, titleDuring, subtitle, subtitleDuring, subsubtitle, subsubtitleDuring, -- * Extracting titles withTitle, ) where import Control.Lens (view) import Control.Monad.Plus import Data.Foldable (Foldable) import qualified Data.Foldable as F import qualified Data.List as List import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe import Data.Semigroup import Data.Set (Set) import qualified Data.Set as Set import Data.String import Data.Traversable (Traversable) import qualified Data.Traversable as T import Data.Typeable import Music.Pitch.Literal import Music.Score.Meta import Music.Score.Part import Music.Score.Pitch import Music.Score.Internal.Util import Music.Time import Music.Time.Reactive -- | -- A title is a sequence of 'String' values, representing the name of a work or part of a work. -- An arbitrary depth of title sections can be used. -- -- Title is an instance of 'IsString' and can be used with the 'OverloadedStrings' extension as -- follows: -- -- > title "Le Nozze di Figaro" -- > -- > subtitle "Atto primo" -- > subsubtitle "Scena I" -- > subsubtitle "Scena II" -- > ... -- > -- > subtitle "Atto secundo" -- > ... -- newtype Title = Title (Int -> Option (Last String)) deriving (Typeable, Monoid, Semigroup) instance IsString Title where fromString x = Title $ \n -> if n == 0 then Option (Just (Last x)) else Option Nothing instance Show Title where show = List.intercalate " " . getTitle -- | Create a title from a string. See also 'fromString'. titleFromString :: String -> Title titleFromString = fromString -- | Denote a title to a lower level, i.e title becomes subtitle, subtitle becomes subsubtitle etc. denoteTitle :: Title -> Title denoteTitle (Title t) = Title (t . subtract 1) -- | Extract the title as a descending list of title levels (i.e. title, subtitle, subsubtitle...). getTitle :: Title -> [String] getTitle t = untilFail . fmap (getTitleAt t) $ [0..] where untilFail = fmap fromJust . takeWhile isJust -- | Extract the title of the given level. Semantic function. getTitleAt :: Title -> Int -> Maybe String getTitleAt (Title t) n = fmap getLast . getOption . t $ n -- | Set title of the given score. title :: (HasMeta a, HasPosition a) => Title -> a -> a title t x = titleDuring (_era x) t x -- | Set title of the given part of a score. titleDuring :: HasMeta a => Span -> Title -> a -> a titleDuring s t = addMetaNote $ view event (s, t) -- | Set subtitle of the given score. subtitle :: (HasMeta a, HasPosition a) => Title -> a -> a subtitle t x = subtitleDuring (_era x) t x -- | Set subtitle of the given part of a score. subtitleDuring :: HasMeta a => Span -> Title -> a -> a subtitleDuring s t = addMetaNote $ view event (s, denoteTitle t) -- | Set subsubtitle of the given score. subsubtitle :: (HasMeta a, HasPosition a) => Title -> a -> a subsubtitle t x = subsubtitleDuring (_era x) t x -- | Set subsubtitle of the given part of a score. subsubtitleDuring :: HasMeta a => Span -> Title -> a -> a subsubtitleDuring s t = addMetaNote $ view event (s, denoteTitle (denoteTitle t)) -- | Extract the title in from the given score. withTitle :: (Title -> Score a -> Score a) -> Score a -> Score a withTitle = withMetaAtStart
music-suite/music-score
src/Music/Score/Meta/Title.hs
bsd-3-clause
4,776
0
13
1,258
882
507
375
74
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Language.Nix.Identifier ( Identifier(..), ident, quote, needsQuoting ) where import Control.Lens import Data.Char import Data.Function ( on ) import Data.String import Distribution.Nixpkgs.Util.PrettyPrinting ( Pretty(..), text ) import Text.Regex.Posix -- | Identifiers in Nix are essentially strings. Reasonable people restrict -- themselves to identifiers of the form @[a-zA-Z\_][a-zA-Z0-9\_\'\-]*@, -- because these don't need quoting. The @Identifier@ type is an instance of -- the 'IsString' class for convenience. The methods of the 'Pretty' class can -- be used to pretty-print an identifier with proper quoting. -- -- >>> let i = Identifier "test" in (i, pPrint i) -- (Identifier "test",test) -- >>> let i = Identifier "foo.bar" in (i, pPrint i) -- (Identifier "foo.bar","foo.bar") -- -- The 'Ord' instance for identifiers is unusual in that it's aware of -- character's case: -- -- >>> Identifier "abc" == Identifier "ABC" -- False -- >>> Identifier "abc" > Identifier "ABC" -- True -- >>> Identifier "abc" > Identifier "ABC" -- True -- >>> Identifier "X" > Identifier "a" -- True -- >>> Identifier "x" > Identifier "A" -- True -- -- prop> \str -> Identifier str == Identifier str -- prop> \str -> any (`elem` ['a'..'z']) str ==> Identifier (map toLower str) /= Identifier (map toUpper str) newtype Identifier = Identifier String deriving (Show, Eq, IsString) instance Pretty Identifier where pPrint i = text (i ^. ident . to quote) instance Ord Identifier where compare (Identifier a) (Identifier b) = case (compare `on` map toLower) a b of EQ -> compare a b r -> r -- | Checks whether a given string would need quoting when interpreted as an -- intentifier. needsQuoting :: String -> Bool needsQuoting str = not (str =~ grammar) where grammar :: String -- TODO: should be a compiled regular expression grammar = "^[a-zA-Z\\_][a-zA-Z0-9\\_\\'\\-]*$" -- | Lens that allows conversion from/to the standard 'String' type. The setter -- does not evaluate its input, so it's safe to use with 'undefined'. -- -- >>> putStrLn $ Identifier "abc.def" ^. ident -- abc.def -- -- >>> pPrint $ undefined & ident .~ "abcdef" -- abcdef ident :: Lens' Identifier String ident f (Identifier str) = Identifier `fmap` f str -- | Help function that quotes a given identifier string (if necessary). -- -- >>> putStrLn (quote "abc") -- abc -- -- >>> putStrLn (quote "abc.def") -- "abc.def" quote :: String -> String quote s = if needsQuoting s then show s else s
spencerjanssen/cabal2nix
src/Language/Nix/Identifier.hs
bsd-3-clause
2,554
0
10
457
350
213
137
-1
-1
{-# LANGUAGE OverloadedStrings, ExtendedDefaultRules #-} module Queries.Coverage where import Database.MongoDB import Queries.Utils import ActionRunner queryCoverage :: Pipe -> IO [(String,[String])] queryCoverage pipe = do maybeDocs <- run pipe $ find (select [] "coverage") {project = ["title" =: 1, "features" =: 1, "_id" =: 0]} >>= rest return $ case maybeDocs of Right docs -> map (\doc -> (getString $ valueAt "title" $ doc, getFeatures $ valueAt "features" $ doc)) docs Left e -> error $ show e where getFeatures (Array fs) = map getString fs
hendrysuwanda/101dev
tools/mongo2Tex/Queries/Coverage.hs
gpl-3.0
772
0
17
307
210
109
101
15
2
{-# LANGUAGE DeriveDataTypeable, TemplateHaskell, FlexibleInstances, FlexibleContexts, MultiParamTypeClasses #-} -- TypeOperators, TypeSynonymInstances, TypeFamilies module Distribution.Server.Util.NameIndex where import Data.Map (Map) import Data.Typeable (Typeable) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import Data.Char (toLower) import Data.List (unfoldr, foldl') import Data.Maybe (maybeToList) import Control.DeepSeq import Data.SafeCopy import Distribution.Server.Framework.MemSize -- | Case-insensitive name search. This is meant to be an enhanced set of -- names, not a full text search. It's also meant to be a sort of a short-term -- solution for name suggestion searches; e.g., package searches should also -- consider the tagline of a package. data NameIndex = NameIndex { -- | This is the mapping from case-insensitive search term -> name. nameIndex :: Map String (Set String), -- | This is the set of names. storedNamesIndex :: Set String, -- | This is the specification of the type of generator, mainly here because -- functions can't be serialized. Just str means to break on any char in -- str (breakGenerator); Nothing is defaultGenerator. nameGenType :: Maybe [Char], -- | This is the generator of search terms from names. nameSearchGenerator :: String -> [String] } deriving (Typeable) emptyNameIndex :: Maybe [Char] -> NameIndex emptyNameIndex gen = NameIndex Map.empty Set.empty gen $ case gen of Nothing -> defaultGenerator Just st -> breakGenerator st defaultGenerator :: String -> [String] defaultGenerator name = [name] breakGenerator :: [Char] -> String -> [String] breakGenerator breakStr name = name:unfoldr unfoldName name where unfoldName str = case break (`elem` breakStr) str of ([], _) -> Nothing (_, []) -> Nothing (_, _:str') -> Just (str', str') constructIndex :: [String] -> Maybe [Char] -> NameIndex constructIndex strs gen = foldl' (flip addName) (emptyNameIndex gen) strs addName :: String -> NameIndex -> NameIndex addName caseName (NameIndex index stored gen' gen) = let name = map toLower caseName nameSet = Set.singleton caseName forName = Map.fromList $ map (\term -> (term, nameSet)) (gen name) in NameIndex (Map.unionWith Set.union index forName) (Set.insert caseName stored) gen' gen deleteName :: String -> NameIndex -> NameIndex deleteName caseName (NameIndex index stored gen' gen) = let name = map toLower caseName nameSet = Set.singleton caseName forName = Map.fromList $ map (\term -> (term, nameSet)) (gen name) in NameIndex (Map.differenceWith (\a b -> keepSet $ Set.difference a b) index forName) (Set.delete caseName stored) gen' gen where keepSet s = if Set.null s then Nothing else Just s lookupName :: String -> NameIndex -> Set String lookupName caseName (NameIndex index _ _ _) = Map.findWithDefault Set.empty (map toLower caseName) index lookupPrefix :: String -> NameIndex -> Set String lookupPrefix caseName (NameIndex index _ _ _) = let name = map toLower caseName (_, mentry, startTree) = Map.splitLookup name index -- the idea is, select all names in the range [name, mapLast succ name) -- an alternate idea would just be to takeWhile (`isPrefixOf` name) (totalTree, _, _) = Map.splitLookup (mapLast succ name) startTree nameSets = maybeToList mentry ++ Map.elems totalTree in Set.unions nameSets takeSetPrefix :: String -> Set String -> Set String takeSetPrefix name strs = let (_, present, startSet) = Set.splitMember name strs (totalSet, _, _) = Set.splitMember (mapLast succ name) startSet in (if present then Set.insert name else id) totalSet -- | Map only the last element of a list mapLast :: (a -> a) -> [a] -> [a] mapLast f (x:[]) = f x:[] mapLast f (x:xs) = x:mapLast f xs mapLast _ [] = [] -- store arguments which can be sent to constructIndex :: [String] -> Maybe [Char] -> NameIndex instance SafeCopy NameIndex where putCopy index = contain $ safePut (nameGenType index) >> safePut (storedNamesIndex index) getCopy = contain $ do gen <- safeGet index <- safeGet return $ constructIndex (Set.toList index) gen instance NFData NameIndex where rnf (NameIndex a b _ _) = rnf a `seq` rnf b instance MemSize NameIndex where memSize (NameIndex a b c d) = memSize4 a b c d
mpickering/hackage-server
Distribution/Server/Util/NameIndex.hs
bsd-3-clause
4,508
0
14
954
1,289
681
608
78
3
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="hr-HR"> <title>Port Scan | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/zest/src/main/javahelp/org/zaproxy/zap/extension/zest/resources/help_hr_HR/helpset_hr_HR.hs
apache-2.0
971
85
52
160
398
210
188
-1
-1
module FunIn2 where --The application of a function is replaced by the right-hand side of the definition, --with actual parameters replacing formals. --In this example, unfold 'addthree'. --This example aims to test unfolding a function defintion. main :: Int -> Int main = \x -> case x of 1 -> 1 + main 0 0 ->((1 + 2) + 3) addthree :: Int -> Int -> Int -> Int addthree a b c = a + b + c
mpickering/HaRe
old/testing/unfoldDef/FunIn2_TokOut.hs
bsd-3-clause
424
0
12
115
101
56
45
7
2
import Test.Cabal.Prelude import Data.Maybe main = cabalTest $ do withPackageDb $ do withSandbox $ do fails $ cabal "exec" ["my-executable"] cabal "install" [] -- The library should not be available outside the sandbox ghcPkg' "list" [] >>= assertOutputDoesNotContain "my-0.1" -- Execute ghc-pkg inside the sandbox; it should find my-0.1 cabal' "exec" ["ghc-pkg", "list"] >>= assertOutputContains "my-0.1"
mydaum/cabal
cabal-testsuite/PackageTests/Exec/sandbox-ghc-pkg.test.hs
bsd-3-clause
506
0
16
156
100
48
52
10
1
module Foo where -- TODO: return a civilized error message about the line number with the -- problematic predicate application, instead of just a groan about safeZip -- failing. {-@ predicate Rng Lo V Hi = (Lo <= V && V < Hi) @-} {-@ type NNN a b = {v:[(a, b)] | 0 <= 0} @-} {-@ bog :: {v:Int | (Rng 0 10 11)} @-} bog :: Int bog = 5 {-@ foo :: NNN Int @-} foo :: [(Int, Char)] foo = [(1, 'c')]
mightymoose/liquidhaskell
tests/todo/aliasError.hs
bsd-3-clause
399
0
6
92
49
34
15
5
1
module IdIn2 where {-To rename an identifier name, stop the cursor at any occurrence of the name, then input the new name in the mini-buffer, after that, select the 'rename' command from the 'Refactor' menu.-} --Any value variable name declared in this module can be renamed. --Rename local 'x' to 'x1' x=5 foo=x+3 bar z=x+y+z where x=7 y=3 main=(foo,bar x, foo)
kmate/HaRe
test/testdata/Renaming/IdIn2.hs
bsd-3-clause
390
0
6
88
66
39
27
7
1
{-# LANGUAGE CPP #-} import Control.Concurrent import Control.Exception import Foreign import System.IO (hFlush,stdout) #if __GLASGOW_HASKELL__ < 705 import Prelude hiding (catch) #endif -- !!! Try to get two threads into a knot depending on each other. -- This should result in the main thread being sent a NonTermination -- exception (in GHC 5.02, the program is terminated with "no threads -- to run" instead). main = do Foreign.newStablePtr stdout -- HACK, because when these two threads get blocked on each other, -- there's nothing keeping stdout alive so it will get finalized. -- SDM 12/3/2004 let a = last ([1..10000] ++ [b]) b = last ([2..10000] ++ [a]) -- we have to be careful to ensure that the strictness analyser -- can't see that a and b are both bottom, otherwise the -- simplifier will go to town here, resulting in something like -- a = a and b = a. forkIO (print a `catch` \NonTermination -> return ()) -- we need to catch in the child thread too, because it might -- get sent the NonTermination exception first. r <- Control.Exception.try (print b) print (r :: Either NonTermination ())
lukexi/ghc
testsuite/tests/concurrent/should_run/conc034.hs
bsd-3-clause
1,140
0
13
222
181
103
78
13
1
-- A second test for trac #3001, which segfaults when compiled by -- GHC 6.10.1 and run with +RTS -hb. Most of the code is from the -- binary 0.4.4 package. {-# LANGUAGE CPP, FlexibleInstances, FlexibleContexts, MagicHash #-} module Main (main) where import Data.Monoid import Data.ByteString.Internal (inlinePerformIO) import qualified Data.ByteString as S import qualified Data.ByteString.Internal as S import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Internal as L import GHC.Exts import GHC.Word import Control.Monad import Foreign import System.IO.Unsafe import System.IO import Data.Char (chr,ord) import Control.Applicative main :: IO () main = do encodeFile "test.bin" $ replicate 10000 'x' print =<< (decodeFile "test.bin" :: IO String) class Binary t where put :: t -> Put get :: Get t encodeFile :: Binary a => FilePath -> a -> IO () encodeFile f v = L.writeFile f $ runPut $ put v decodeFile :: Binary a => FilePath -> IO a decodeFile f = do s <- L.readFile f return $ runGet (do v <- get m <- isEmpty m `seq` return v) s instance Binary Word8 where put = putWord8 get = getWord8 instance Binary Word32 where put = putWord32be get = getWord32be instance Binary Int32 where put i = put (fromIntegral i :: Word32) get = liftM fromIntegral (get :: Get Word32) instance Binary Int where put i = put (fromIntegral i :: Int32) get = liftM fromIntegral (get :: Get Int32) instance Binary Char where put a = put (ord a) get = do w <- get return $! chr w instance Binary a => Binary [a] where put l = put (length l) >> mapM_ put l get = do n <- get replicateM n get data PairS a = PairS a !Builder sndS :: PairS a -> Builder sndS (PairS _ b) = b newtype PutM a = Put { unPut :: PairS a } type Put = PutM () instance Functor PutM where fmap f m = Put $ let PairS a w = unPut m in PairS (f a) w instance Monad PutM where return a = Put $ PairS a mempty m >>= k = Put $ let PairS a w = unPut m PairS b w' = unPut (k a) in PairS b (w `mappend` w') m >> k = Put $ let PairS _ w = unPut m PairS b w' = unPut k in PairS b (w `mappend` w') instance Applicative PutM where pure = return (<*>) = ap tell :: Builder -> Put tell b = Put $ PairS () b runPut :: Put -> L.ByteString runPut = toLazyByteString . sndS . unPut putWord8 :: Word8 -> Put putWord8 = tell . singletonB putWord32be :: Word32 -> Put putWord32be = tell . putWord32beB ----- newtype Get a = Get { unGet :: S -> (a, S) } data S = S {-# UNPACK #-} !S.ByteString -- current chunk L.ByteString -- the rest of the input {-# UNPACK #-} !Int64 -- bytes read runGet :: Get a -> L.ByteString -> a runGet m str = case unGet m (initState str) of (a, _) -> a isEmpty :: Get Bool isEmpty = do S s ss _ <- getZ return (S.null s && L.null ss) initState :: L.ByteString -> S initState xs = mkState xs 0 getWord32be :: Get Word32 getWord32be = do s <- readN 4 id return $! (fromIntegral (s `S.index` 0) `shiftl_w32` 24) .|. (fromIntegral (s `S.index` 1) `shiftl_w32` 16) .|. (fromIntegral (s `S.index` 2) `shiftl_w32` 8) .|. (fromIntegral (s `S.index` 3) ) getWord8 :: Get Word8 getWord8 = getPtr (sizeOf (undefined :: Word8)) mkState :: L.ByteString -> Int64 -> S mkState l = case l of L.Empty -> S S.empty L.empty L.Chunk x xs -> S x xs readN :: Int -> (S.ByteString -> a) -> Get a readN n f = fmap f $ getBytes n shiftl_w32 :: Word32 -> Int -> Word32 shiftl_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftL#` i) getPtr :: Storable a => Int -> Get a getPtr n = do (fp,o,_) <- readN n S.toForeignPtr return . S.inlinePerformIO $ withForeignPtr fp $ \p -> peek (castPtr $ p `plusPtr` o) getBytes :: Int -> Get S.ByteString getBytes n = do S s ss bytes <- getZ if n <= S.length s then do let (consume,rest) = S.splitAt n s putZ $! S rest ss (bytes + fromIntegral n) return $! consume else case L.splitAt (fromIntegral n) (s `joinZ` ss) of (consuming, rest) -> do let now = S.concat . L.toChunks $ consuming putZ $! mkState rest (bytes + fromIntegral n) -- forces the next chunk before this one is returned if (S.length now < n) then fail "too few bytes" else return now joinZ :: S.ByteString -> L.ByteString -> L.ByteString joinZ bb lb | S.null bb = lb | otherwise = L.Chunk bb lb instance Monad Get where return a = Get (\s -> (a, s)) {-# INLINE return #-} m >>= k = Get (\s -> let (a, s') = unGet m s in unGet (k a) s') {-# INLINE (>>=) #-} fail = error "failDesc" instance Applicative Get where pure = return (<*>) = ap getZ :: Get S getZ = Get (\s -> (s, s)) putZ :: S -> Get () putZ s = Get (\_ -> ((), s)) instance Functor Get where fmap f m = Get (\s -> case unGet m s of (a, s') -> (f a, s')) ----- singletonB :: Word8 -> Builder singletonB = writeN 1 . flip poke writeN :: Int -> (Ptr Word8 -> IO ()) -> Builder writeN n f = ensureFree n `append` unsafeLiftIO (writeNBuffer n f) unsafeLiftIO :: (Buffer -> IO Buffer) -> Builder unsafeLiftIO f = Builder $ \ k buf -> inlinePerformIO $ do buf' <- f buf return (k buf') append :: Builder -> Builder -> Builder append (Builder f) (Builder g) = Builder (f . g) writeNBuffer :: Int -> (Ptr Word8 -> IO ()) -> Buffer -> IO Buffer writeNBuffer n f (Buffer fp o u l) = do withForeignPtr fp (\p -> f (p `plusPtr` (o+u))) return (Buffer fp o (u+n) (l-n)) newtype Builder = Builder { -- Invariant (from Data.ByteString.Lazy): -- The lists include no null ByteStrings. runBuilder :: (Buffer -> [S.ByteString]) -> Buffer -> [S.ByteString] } data Buffer = Buffer {-# UNPACK #-} !(ForeignPtr Word8) {-# UNPACK #-} !Int -- offset {-# UNPACK #-} !Int -- used bytes {-# UNPACK #-} !Int -- length left toLazyByteString :: Builder -> L.ByteString toLazyByteString m = L.fromChunks $ unsafePerformIO $ do buf <- newBuffer defaultSize return (runBuilder (m `append` flush) (const []) buf) ensureFree :: Int -> Builder ensureFree n = n `seq` withSize $ \ l -> if n <= l then emptyBuilder else flush `append` unsafeLiftIO (const (newBuffer (max n defaultSize))) withSize :: (Int -> Builder) -> Builder withSize f = Builder $ \ k buf@(Buffer _ _ _ l) -> runBuilder (f l) k buf defaultSize :: Int defaultSize = 32 * k - overhead where k = 1024 overhead = 2 * sizeOf (undefined :: Int) newBuffer :: Int -> IO Buffer newBuffer size = do fp <- S.mallocByteString size return $! Buffer fp 0 0 size putWord32beB :: Word32 -> Builder putWord32beB w = writeN 4 $ \p -> do poke p (fromIntegral (shiftr_w32 w 24) :: Word8) poke (p `plusPtr` 1) (fromIntegral (shiftr_w32 w 16) :: Word8) poke (p `plusPtr` 2) (fromIntegral (shiftr_w32 w 8) :: Word8) poke (p `plusPtr` 3) (fromIntegral (w) :: Word8) shiftr_w32 :: Word32 -> Int -> Word32 shiftr_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftRL#` i) flush :: Builder flush = Builder $ \ k buf@(Buffer p o u l) -> if u == 0 then k buf else S.PS p o u : k (Buffer p (o+u) 0 l) emptyBuilder :: Builder emptyBuilder = Builder id instance Monoid Builder where mempty = emptyBuilder mappend = append
urbanslug/ghc
testsuite/tests/profiling/should_run/T3001-2.hs
bsd-3-clause
8,019
0
18
2,499
3,057
1,584
1,473
206
3
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} module Data.CBar where import Control.Lens hiding (to, each) import Control.Monad.Trans.State.Strict (State) import Control.SFold import Control.SFold.Util import Data.Binary (Binary) import Data.ByteString (ByteString) import qualified Data.Map as Map import Data.Mark import Data.Monoid import qualified Data.Semigroup as Semi import Data.Text (Text) import Data.Text.Encoding import Data.Time import Data.Time.Extended import Formatting import GHC.Generics (Generic) data CBar = CBar {_cbarCloseTime :: UTCTime ,_cbarFirstTime :: UTCTime ,_cbarLastTime :: UTCTime ,_cbarBidPrice :: Double ,_cbarAskPrice :: Double ,_cbarPrice :: Double ,_cbarBidVolume :: Int ,_cbarAskVolume :: Int ,_cbarVolume :: Int} deriving (Show,Eq,Generic) makeLenses ''CBar instance Binary CBar instance Semi.Semigroup CBar where (CBar ct ft lt _ _ _ _ _ v) <> (CBar ct' ft' lt' bp' ap' p' bv' av' v') = CBar ct'' ft'' lt'' bp' ap' p' bv' av' (v + v') where ct'' = max ct ct' ft'' = min ft ft' lt'' = max lt lt' data CBarX = CBarX {_xOpen :: Maybe CBar ,_xClosed :: [CBar]} deriving (Show,Eq) makeLenses ''CBarX toCbar :: Mark -> CBar toCbar (Mark t bp ap' p bv av v _ _ _) = CBar t t t bp ap' p bv av v instance Monoid CBarX where mempty = CBarX Nothing [] mappend (CBarX o0 c0) (CBarX o1 c1) = case o0 of Nothing -> CBarX o1 c Just m0 -> case o1 of Nothing -> CBarX o0 c Just m1 -> case compare (m0 ^. cbarCloseTime) (m1 ^. cbarCloseTime) of EQ -> CBarX (Just (m0 Semi.<> m1)) c LT -> CBarX (Just m1) (c <> [m0]) GT -> CBarX (Just m0) (c <> [m1]) where c = c0 <> c1 release :: CBarX -> (CBarX,[CBar]) release (CBarX o c) = (CBarX o [],c) flush :: CBarX -> CBarX flush (CBarX o c) = case o of Nothing -> CBarX Nothing c Just o' -> CBarX Nothing (c <> [o']) timeFold :: NominalDiffTime -> SFold Mark CBar timeFold grain = SFold toNextClose mappend mempty release flush where toNextClose (Mark t bp ap' p bv av v _ _ _) = CBarX (Just $ CBar (ceilingTime t grain) t t bp ap' p bv av v) [] volumeFold :: Int -> SFold Mark CBar volumeFold grain = SFold toVol step mempty release flush where step x0 x1 = case o0' of Nothing -> CBarX o1' c' Just m0 -> case o1' of Nothing -> CBarX o0' c' Just m1 -> if m0 ^. cbarVolume + m1 ^. cbarVolume < grain then CBarX (Just (m0 Semi.<> m1)) c' else CBarX mrem (c' <> [mfirst] <> mquot) where m' = m0 Semi.<> m1 (_,cm') = budVol m' mfirst = cbarVolume .~ grain $ head cm' (mrem,mquot) = budVol (cbarVolume .~ (m1 ^. cbarVolume - (grain - m0 ^. cbarVolume)) $ m1) where (CBarX o0' c0') = budVolCBarX x0 (CBarX o1' c1') = budVolCBarX x1 c' = c0' <> c1' toVol m = uncurry CBarX (budVol (toCbar m)) budVol :: CBar -> (Maybe CBar,[CBar]) budVol x = (,) (if vrem > 0 then Just (cbarVolume .~ vrem $ x) else Nothing) (replicate vquot (cbarVolume .~ grain $ x)) where (vquot,vrem) = quotRem (x ^. cbarVolume) grain budVolCBarX :: CBarX -> CBarX budVolCBarX x@(CBarX o c) = case o of Nothing -> x Just m -> CBarX o' (c <> c') where (o',c') = budVol m mark2TimeBar :: NominalDiffTime -> SFold (ByteString,Mark) (ByteString,CBar) mark2TimeBar grain = keyFold (timeFold grain) mark2VolumeBar :: Int -> SFold (ByteString,Mark) (ByteString,CBar) mark2VolumeBar grain = keyFold (volumeFold grain) renderCBar :: CBar -> Text renderCBar cbar = fTimeMilli (utctDayTime $ _cbarCloseTime cbar) <> sformat (left 15 ' ' %. (" " % float % ":" % float % ":" % float)) (_cbarBidPrice cbar) (_cbarAskPrice cbar) (_cbarPrice cbar) <> sformat (left 10 ' ' %. (" " % int % ":" % int % ":" % int)) (_cbarBidVolume cbar) (_cbarAskVolume cbar) (_cbarVolume cbar) renderCBar' :: (ByteString,CBar) -> Text renderCBar' (sym,cbar) = sformat (stext % " ") (decodeUtf8 sym) <> fTimeMilli (utctDayTime $ _cbarCloseTime cbar) <> sformat (left 15 ' ' %. (" " % float % ":" % float % ":" % float)) (_cbarBidPrice cbar) (_cbarAskPrice cbar) (_cbarPrice cbar) <> sformat (left 10 ' ' %. (" " % int % ":" % int % ":" % int)) (_cbarBidVolume cbar) (_cbarAskVolume cbar) (_cbarVolume cbar) -- statistics data StatsCBar = StatsCBar {_scbarCount :: Int ,_scbarSymbolCount :: Map.Map ByteString Int ,_scbarSymbolVolumeSum :: Map.Map ByteString Int} deriving (Show,Eq,Read,Generic) instance Binary StatsCBar makeLenses ''StatsCBar initialScbar :: StatsCBar initialScbar = StatsCBar 0 mempty mempty scbarUpdate :: (ByteString,CBar) -> (State StatsCBar) () scbarUpdate (sym,c) = do scbarCount += 1 scbarSymbolCount %= Map.insertWith (+) sym 1 scbarSymbolVolumeSum %= Map.insertWith (+) sym (c ^. cbarVolume) scbarRender :: StatsCBar -> Text scbarRender s = sformat ("Count: " % int % "\n") (s ^. scbarCount) <> "Count by Symbol: " <> Map.foldWithKey (\k a b -> b <> sformat (stext % ":" % int % " ") (decodeUtf8 k) a) mempty (s ^. scbarSymbolCount) <> "\n" <> "Volume by Symbol: " <> Map.foldWithKey (\k a b -> b <> sformat (stext % ":" % int % " ") (decodeUtf8 k) a) mempty (s ^. scbarSymbolVolumeSum)
tonyday567/trade
src/Data/CBar.hs
mit
6,865
0
23
2,634
2,198
1,152
1,046
206
6
module Proteome.Test.DiagTest where import Hedgehog ((===)) import Path (Abs, Dir, Path, absdir, toFilePath) import Ribosome.Api.Buffer (currentBufferContent) import Ribosome.Test.Run (UnitTest) import Proteome.Data.Env (Env) import qualified Proteome.Data.Env as Env (configLog, mainProject) import Proteome.Data.Project (Project(Project)) import Proteome.Data.ProjectMetadata (ProjectMetadata(DirProject)) import Proteome.Data.ProjectRoot (ProjectRoot(ProjectRoot)) import Proteome.Diag (proDiag) import Proteome.Test.Config (vars) import Proteome.Test.Project (ag, flag, fn, hask, idr, l, la, li, ti, tp) import Proteome.Test.Unit (ProteomeTest, testWithDef) root :: Path Abs Dir root = [absdir|/projects/flagellum|] main :: Project main = Project (DirProject fn (ProjectRoot root) (Just tp)) [ti] (Just l) [la, li] confLog :: [Text] confLog = ["/conf/project/haskell/flagellum.vim", "/conf/project_after/all.vim"] target :: [Text] target = [ "Diagnostics", "", "Main project", "", "name: " <> flag, "root: " <> toText (toFilePath root), "type: " <> hask, "tags cmd: ctags -R --languages=agda,idris -f /projects/flagellum/.tags.tmp /projects/flagellum/", "types: " <> idr, "main language: " <> hask, "languages: " <> ag <> ", " <> idr, "", "loaded config files:" ] <> confLog diagSpec :: ProteomeTest () diagSpec = do setL @Env Env.mainProject main setL @Env Env.configLog confLog proDiag def content <- currentBufferContent target === content test_diag :: UnitTest test_diag = vars >>= testWithDef diagSpec
tek/proteome
packages/test/test/Proteome/Test/DiagTest.hs
mit
1,559
0
10
230
476
282
194
-1
-1
{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls #-} import Foreign import Foreign.C.Types import System.IO.Unsafe data CFoo foreign import ccall unsafe "foo_c.h foo_ctor" c_foo_ctor :: CInt -> IO (Ptr CFoo) data Foo = Foo !(Ptr CFoo) deriving (Eq, Ord, Show) newFoo :: Int -> Either String Foo newFoo x = unsafePerformIO $ do foo_ptr <- c_foo_ctor (fromIntegral x) if foo_ptr == nullPtr then return (Left "Failed to construct Foo") else return (Right (Foo foo_ptr)) foreign import ccall unsafe "foo_c.h foo_get" c_foo_get :: Ptr CFoo -> IO CInt getFoo :: Foo -> Int getFoo (Foo foo_ptr) = unsafePerformIO $ do c <- c_foo_get foo_ptr return $ fromIntegral c foreign import ccall unsafe "foo_c.h foo_dtor" c_foo_dtor :: Ptr CFoo -> IO () delFoo :: Foo -> IO () delFoo (Foo foo_ptr) = c_foo_dtor foo_ptr main :: IO () main = do let r = newFoo 10 case r of Left e -> print e Right f -> do print (getFoo f) delFoo f print "foo deleted"
hnfmr/cpp-class-ffi
ffi.hs
mit
1,026
1
14
249
365
178
187
-1
-1
-- https://www.fpcomplete.com/blog/2017/09/all-about-strictness {-# LANGUAGE BangPatterns #-} {- Run with: stack --resolver lts-8.6 ghc --package conduit-combinators --package deepseq -- StrictnessPlayground.hs -O2 ./StrictnessPlayground +RTS -s -} import Debug.Trace import Control.DeepSeq (NFData, rnf, deepseq, force) import Prelude hiding (($!)) import Conduit -- What would happen if, instead of in part1, the code said in part2? How about in answer? add :: Int -> Int -> Int add x y = let part1 = seq x part2 part2 = seq y answer answer = x + y in part1 -- part2 -- x isn't evaluated -- answer -- x and y aren't evaluated main1 :: IO () main1 = do let five = trace "five" $ add (1 + 1) (1 + 2) seven = trace "seven" $ add (1 + 2) undefined -- (1 + 3) putStrLn $ "Five: " ++ show five where add :: Int -> Int -> Int add !x !y = x + y main2 :: IO () main2 = do putStrLn $ ((+) undefined) `seq` "Not throwing. I'm in WHNF." putStrLn $ Just undefined `seq` "Not throwing. I'm in WHNF." putStrLn $ undefined 5 `seq` "Throwing" putStrLn $ (error "foo" :: Int -> Double) `seq` "Throwing" myDeepSeq :: NFData a => a -> b -> b myDeepSeq x y = rnf x `seq` y data Foo = Foo Int data Bar = Bar !Int newtype Baz = Baz Int -- it throws since `Baz undefined` ~= `undefined` and `seq` forces -- its evaluation main3 :: IO () main3 = Baz undefined `seq` putStrLn "Still alive!" mysum :: [Int] -> Int mysum list0 = go list0 0 where go [] total = total go (x:xs) total = go xs $! total + x -- go (x:xs) total = -- let newTotal = total + x in newTotal `seq` go xs newTotal -- go (x:xs) total = -- let !newTotal = total + x in go xs newTotal ($!) :: (a -> b) -> a -> b f $! x = let y = f x in y `seq` y ($!!) :: NFData b => (a -> b) -> a -> b f $!! x = let y = f x in y `deepseq` y infixr 0 $! infixr 0 $!! {- Data.Sequence.Seq is defined as follows: `newtype Seq a = Seq (FingerTree (Elem a))` and FingerTree as follows: ``` data FingerTree a = Empty | Single a | Deep {-# UNPACK #-} !Int !(Digit a) (FingerTree (Node a)) !(Digit a) ``` To me Seq seems to be just spine strict since the evaluation of the value `a` is never forced. -} average :: Monad m => ConduitM Int o m Double average = divide <$> foldlC add (0, 0) where divide (total, count) = fromIntegral total / count add (total, count) x = (total + x, count + 1) averageForce :: Monad m => ConduitM Int o m Double averageForce = divide <$> foldlC add (0, 0) where divide (total, count) = fromIntegral total / count add (total, count) x = force (total + x, count + 1) averageBangs :: Monad m => ConduitM Int o m Double averageBangs = divide <$> foldlC add (0, 0) where divide (total, count) = fromIntegral total / count add (total, count) x = let !total' = total + x !count' = count + 1 in (total', count') data StrictPair = P !Int !Int averageCustom :: Monad m => ConduitM Int o m Double averageCustom = divide <$> foldlC add (P 0 0) where divide :: StrictPair -> Double divide (P total count) = fromIntegral total / fromIntegral count add (P total count) x = P (total + x) (count + 1) main :: IO () main = print $ runConduitPure $ enumFromToC 1 1000000 .| averageCustom data StrictList a = Cons !a !(StrictList a) | Nil strictMap :: (a -> b) -> StrictList a -> StrictList b strictMap _ Nil = Nil strictMap f (Cons a list) = let !b = f a !list' = strictMap f list in b `seq` list' `seq` Cons b list' strictEnum :: Int -> Int -> StrictList Int strictEnum low high = go low where go !x | x == high = Cons x Nil | otherwise = Cons x (go $! x + 1) double :: Int -> Int double !x = x * 2 evens :: StrictList Int evens = strictMap double $! strictEnum 1 1000000 main5 :: IO () main5 = do let string = "Hello World" -- !string' = evens `seq` string -- max mem usage string' = evens `seq` string -- putStrLn $ string' `seq` string -- max mem usage putStrLn string
futtetennista/IntroductionToFunctionalProgramming
src/StrictnessPlayground.hs
mit
4,098
2
13
1,067
1,381
708
673
113
2
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DuplicateRecordFields #-} module Language.LSP.Types.DocumentSymbol where import Data.Aeson import Data.Aeson.TH import Data.Scientific import Data.Text (Text) import Language.LSP.Types.TextDocument import Language.LSP.Types.Common import Language.LSP.Types.Location import Language.LSP.Types.Progress import Language.LSP.Types.Utils -- --------------------------------------------------------------------- makeExtendingDatatype "DocumentSymbolOptions" [''WorkDoneProgressOptions] [ ("_label", [t| Maybe Bool |])] deriveJSON lspOptions ''DocumentSymbolOptions makeExtendingDatatype "DocumentSymbolRegistrationOptions" [ ''TextDocumentRegistrationOptions , ''DocumentSymbolOptions ] [] deriveJSON lspOptions ''DocumentSymbolRegistrationOptions -- --------------------------------------------------------------------- makeExtendingDatatype "DocumentSymbolParams" [ ''WorkDoneProgressParams , ''PartialResultParams ] [ ("_textDocument", [t| TextDocumentIdentifier |])] deriveJSON lspOptions ''DocumentSymbolParams -- ------------------------------------- data SymbolKind = SkFile | SkModule | SkNamespace | SkPackage | SkClass | SkMethod | SkProperty | SkField | SkConstructor | SkEnum | SkInterface | SkFunction | SkVariable | SkConstant | SkString | SkNumber | SkBoolean | SkArray | SkObject | SkKey | SkNull | SkEnumMember | SkStruct | SkEvent | SkOperator | SkTypeParameter | SkUnknown Scientific deriving (Read,Show,Eq) instance ToJSON SymbolKind where toJSON SkFile = Number 1 toJSON SkModule = Number 2 toJSON SkNamespace = Number 3 toJSON SkPackage = Number 4 toJSON SkClass = Number 5 toJSON SkMethod = Number 6 toJSON SkProperty = Number 7 toJSON SkField = Number 8 toJSON SkConstructor = Number 9 toJSON SkEnum = Number 10 toJSON SkInterface = Number 11 toJSON SkFunction = Number 12 toJSON SkVariable = Number 13 toJSON SkConstant = Number 14 toJSON SkString = Number 15 toJSON SkNumber = Number 16 toJSON SkBoolean = Number 17 toJSON SkArray = Number 18 toJSON SkObject = Number 19 toJSON SkKey = Number 20 toJSON SkNull = Number 21 toJSON SkEnumMember = Number 22 toJSON SkStruct = Number 23 toJSON SkEvent = Number 24 toJSON SkOperator = Number 25 toJSON SkTypeParameter = Number 26 toJSON (SkUnknown x) = Number x instance FromJSON SymbolKind where parseJSON (Number 1) = pure SkFile parseJSON (Number 2) = pure SkModule parseJSON (Number 3) = pure SkNamespace parseJSON (Number 4) = pure SkPackage parseJSON (Number 5) = pure SkClass parseJSON (Number 6) = pure SkMethod parseJSON (Number 7) = pure SkProperty parseJSON (Number 8) = pure SkField parseJSON (Number 9) = pure SkConstructor parseJSON (Number 10) = pure SkEnum parseJSON (Number 11) = pure SkInterface parseJSON (Number 12) = pure SkFunction parseJSON (Number 13) = pure SkVariable parseJSON (Number 14) = pure SkConstant parseJSON (Number 15) = pure SkString parseJSON (Number 16) = pure SkNumber parseJSON (Number 17) = pure SkBoolean parseJSON (Number 18) = pure SkArray parseJSON (Number 19) = pure SkObject parseJSON (Number 20) = pure SkKey parseJSON (Number 21) = pure SkNull parseJSON (Number 22) = pure SkEnumMember parseJSON (Number 23) = pure SkStruct parseJSON (Number 24) = pure SkEvent parseJSON (Number 25) = pure SkOperator parseJSON (Number 26) = pure SkTypeParameter parseJSON (Number x) = pure (SkUnknown x) parseJSON _ = fail "SymbolKind" {-| Symbol tags are extra annotations that tweak the rendering of a symbol. @since 3.16.0 -} data SymbolTag = StDeprecated -- ^ Render a symbol as obsolete, usually using a strike-out. | StUnknown Scientific deriving (Read, Show, Eq) instance ToJSON SymbolTag where toJSON StDeprecated = Number 1 toJSON (StUnknown x) = Number x instance FromJSON SymbolTag where parseJSON (Number 1) = pure StDeprecated parseJSON (Number x) = pure (StUnknown x) parseJSON _ = fail "SymbolTag" -- ------------------------------------- data DocumentSymbolKindClientCapabilities = DocumentSymbolKindClientCapabilities { -- | The symbol kind values the client supports. When this -- property exists the client also guarantees that it will -- handle values outside its set gracefully and falls back -- to a default value when unknown. -- -- If this property is not present the client only supports -- the symbol kinds from `File` to `Array` as defined in -- the initial version of the protocol. _valueSet :: Maybe (List SymbolKind) } deriving (Show, Read, Eq) deriveJSON lspOptions ''DocumentSymbolKindClientCapabilities data DocumentSymbolTagClientCapabilities = DocumentSymbolTagClientCapabilities { -- | The tags supported by the client. _valueSet :: Maybe (List SymbolTag) } deriving (Show, Read, Eq) deriveJSON lspOptions ''DocumentSymbolTagClientCapabilities data DocumentSymbolClientCapabilities = DocumentSymbolClientCapabilities { -- | Whether document symbol supports dynamic registration. _dynamicRegistration :: Maybe Bool -- | Specific capabilities for the `SymbolKind`. , _symbolKind :: Maybe DocumentSymbolKindClientCapabilities , _hierarchicalDocumentSymbolSupport :: Maybe Bool -- | The client supports tags on `SymbolInformation`. -- Clients supporting tags have to handle unknown tags gracefully. -- -- @since 3.16.0 , _tagSupport :: Maybe DocumentSymbolTagClientCapabilities -- | The client supports an additional label presented in the UI when -- registering a document symbol provider. -- -- @since 3.16.0 , _labelSupport :: Maybe Bool } deriving (Show, Read, Eq) deriveJSON lspOptions ''DocumentSymbolClientCapabilities -- --------------------------------------------------------------------- -- | Represents programming constructs like variables, classes, interfaces etc. -- that appear in a document. Document symbols can be hierarchical and they -- have two ranges: one that encloses its definition and one that points to its -- most interesting range, e.g. the range of an identifier. data DocumentSymbol = DocumentSymbol { _name :: Text -- ^ The name of this symbol. -- | More detail for this symbol, e.g the signature of a function. If not -- provided the name is used. , _detail :: Maybe Text , _kind :: SymbolKind -- ^ The kind of this symbol. , _tags :: Maybe (List SymbolTag) -- ^ Tags for this document symbol. , _deprecated :: Maybe Bool -- ^ Indicates if this symbol is deprecated. Deprecated, use tags instead. -- | The range enclosing this symbol not including leading/trailing -- whitespace but everything else like comments. This information is -- typically used to determine if the the clients cursor is inside the symbol -- to reveal in the symbol in the UI. , _range :: Range -- | The range that should be selected and revealed when this symbol is being -- picked, e.g the name of a function. Must be contained by the the '_range'. , _selectionRange :: Range -- | Children of this symbol, e.g. properties of a class. , _children :: Maybe (List DocumentSymbol) } deriving (Read,Show,Eq) deriveJSON lspOptions ''DocumentSymbol -- --------------------------------------------------------------------- -- | Represents information about programming constructs like variables, classes, -- interfaces etc. data SymbolInformation = SymbolInformation { _name :: Text -- ^ The name of this symbol. , _kind :: SymbolKind -- ^ The kind of this symbol. , _tags :: Maybe (List SymbolTag) -- ^ Tags for this symbol. , _deprecated :: Maybe Bool -- ^ Indicates if this symbol is deprecated. Deprecated, use tags instead. -- | The location of this symbol. The location's range is used by a tool -- to reveal the location in the editor. If the symbol is selected in the -- tool the range's start information is used to position the cursor. So -- the range usually spans more then the actual symbol's name and does -- normally include things like visibility modifiers. -- -- The range doesn't have to denote a node range in the sense of a abstract -- syntax tree. It can therefore not be used to re-construct a hierarchy of -- the symbols. , _location :: Location -- | The name of the symbol containing this symbol. This information is for -- user interface purposes (e.g. to render a qualifier in the user interface -- if necessary). It can't be used to re-infer a hierarchy for the document -- symbols. , _containerName :: Maybe Text } deriving (Read,Show,Eq) {-# DEPRECATED _deprecated "Use tags instead" #-} deriveJSON lspOptions ''SymbolInformation
wz1000/haskell-lsp
lsp-types/src/Language/LSP/Types/DocumentSymbol.hs
mit
9,390
0
11
2,252
1,635
866
769
165
0
-- | Main module module Main where import Network.HTTP.Conduit import System.Environment (getArgs) import qualified Data.Text as T import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as L import Control.Monad.IO.Class (liftIO) import Text.Playlist import Control.Concurrent import Control.Monad -- | Fetches the playlist from the given url fetchPlaylist :: String -> IO BS.ByteString fetchPlaylist urlString = do case parseUrl urlString of Nothing -> fail "Sorry, invalid URL" Just req -> withManager $ \manager -> do res <- httpLbs req manager return $ L.toStrict $ responseBody res runJob urlString = threadDelay (1000 * 1000) >> do content <- fetchPlaylist urlString case parsePlaylist M3U content of Left err -> fail $ "failed to parse playlist on stdin: " ++ err Right x -> liftIO $ putStr $ unlines $ map (T.unpack . trackURL) x -- | Application entry point main :: IO () main = do args <- getArgs case args of [urlString] -> forever $ runJob urlString _ -> putStrLn "Sorry, please provide exactly one URL"
DavidKlassen/haschup
src/Haschup.hs
mit
1,135
0
16
260
312
163
149
28
2
----------------------------------------------------------------------------- -- -- Module : TypeNum.Test.Int -- Copyright : -- License : MIT -- -- Maintainer : - -- Stability : -- Portability : -- -- | -- ----------------------------------------------------------------------------- module TypeNum.Test.Int where import TypeNum.Test.Common import TypeNum.Integer ----------------------------------------------------------------------------- intSpec = describe "TypeNum.Integer.TInt" $ do describe "is comparable at type-level ((==), TypesEq and TypesOrd)" $ do specify "==" $ correct (B::B (Pos 1 == Pos 1)) && correct (B::B (Pos 1 ~=~ 1)) && correct (B::B (Neg 5 == Neg 5)) && correct (B::B (Pos 0 == Neg 0)) && correct (B::B (Pos 0 ~=~ 0)) && mistake (B::B (Neg 1 ~=~ 1)) && mistake (B::B (Pos 5 == Pos 2)) specify ">" $ correct (B::B (Pos 2 > Pos 1)) && correct (B::B (Neg 1 > Neg 2)) && correct (B::B (Pos 0 > Neg 2)) && mistake (B::B (Pos 2 > Pos 5)) && mistake (B::B (Pos 0 > Pos 1)) && mistake (B::B (Neg 1 > Pos 1)) specify "<" $ correct (B::B (Pos 1 < Pos 2)) && correct (B::B (Neg 1 < Pos 2)) && correct (B::B (Neg 2 < Neg 1)) && mistake (B::B (Neg 4 < Neg 4)) && mistake (B::B (Pos 4 < Neg 1)) specify ">=" $ correct (B::B (Pos 2 >= Pos 1)) && correct (B::B (Neg 1 >= Neg 2)) && correct (B::B (Pos 0 >= Neg 2)) && correct (B::B (Pos 2 >= Pos 2)) && mistake (B::B (Pos 0 >= Pos 1)) && mistake (B::B (Neg 1 >= Pos 1)) -- specify "<=" $ correct (B::B (Pos 1 <= Pos 2)) && correct (B::B (Neg 1 <= Pos 2)) && correct (B::B (Neg 2 <= Neg 1)) && correct (B::B (Neg 4 <= Neg 4)) && mistake (B::B (Pos 4 <= Neg 1)) describe "has natural number operations at type-level (TypesNat)" $ do it "provides type-level sum '(+)'" $ correct (B::B ((Pos 1 + Pos 1 :: TInt) == Pos 2)) && correct (B::B ((Pos 4 + Pos 5 :: TInt) == Pos 9)) && correct (B::B ((Neg 4 + Pos 5 :: TInt) == Pos 1)) && correct (B::B ((Neg 5 + Pos 5 :: TInt) == Pos 0)) && correct (B::B ((Pos 4 + Pos 5 :: TInt) == (Pos 2 + Pos 7 :: TInt))) && correct (B::B ((Neg 4 + Pos 5 :: TInt) == (Pos 5 + Neg 4 :: TInt))) && correct (B::B ((Neg 5 + Pos 5 :: TInt) == (Pos 4 + Neg 4 :: TInt))) && mistake (B::B ((Neg 4 + Pos 5 :: TInt) == Pos 4)) && mistake (B::B ((Neg 5 + Pos 5 :: TInt) == Neg 1)) && mistake (B::B ((Pos 4 + Pos 5 :: TInt) == (Pos 2 + Pos 2 :: TInt))) && mistake (B::B ((Neg 4 + Pos 5 :: TInt) == (Pos 5 + Pos 4 :: TInt))) it "provides type-level absolute difference '(/-)'" $ correct (B::B ((Pos 1 /- Pos 3 :: TInt) ~=~ 2)) && correct (B::B ((Pos 3 /- Pos 1 :: TInt) ~=~ 2)) && correct (B::B ((Pos 3 /- Pos 3 :: TInt) ~=~ 0)) && correct (B::B ((Neg 1 /- Neg 3 :: TInt) ~=~ 2)) && correct (B::B ((Neg 1 /- Pos 3 :: TInt) ~=~ 4)) && correct (B::B ((Pos 1 /- Neg 3 :: TInt) ~=~ 4)) && mistake (B::B ((Pos 3 /- Pos 3 :: TInt) ~=~ 2)) it "provides type-level multiplication '(*)'" $ correct (B::B ((Pos 1 * Pos 3 :: TInt) ~=~ 3)) && correct (B::B ((Pos 3 * Pos 1 :: TInt) ~=~ 3)) && correct (B::B ((Neg 3 * Pos 1 :: TInt) == Neg 3)) && correct (B::B ((Neg 3 * Neg 1 :: TInt) == Pos 3)) && correct (B::B ((Neg 3 * Zero :: TInt) ~=~ 0)) && correct (B::B ((Zero * Pos 9 :: TInt) ~=~ 0)) && mistake (B::B ((Pos 2 * Pos 3 :: TInt) ~=~ 9)) it "provides type-level power '(^)'" $ pending describe "has integral number operations at type-level (TypesIntegral)" $ do it "provides type-level integer division truncated toward zero 'Quot'" $ correct (B::B (((QuotRem (Pos 3) (Pos 3)) :: (TInt, TInt)) == ('(Pos 1, Zero)))) && correct (B::B (((QuotRem (Pos 1) (Pos 2)) :: (TInt, TInt)) == ('(Zero, Pos 1)))) && correct (B::B (((QuotRem (Pos 2) (Pos 1)) :: (TInt, TInt)) == ('(Pos 2, Zero)))) && correct (B::B (((QuotRem (Pos 4) (Pos 3)) :: (TInt, TInt)) == ('(Pos 1, Pos 1)))) && correct (B::B (((QuotRem (Neg 4) (Pos 3)) :: (TInt, TInt)) == ('(Neg 1, Neg 1)))) && correct (B::B (((Rem (Pos 3) (Pos 3)) :: TInt) == Zero)) && correct (B::B (((Rem (Pos 3) (Pos 3)) :: TInt) < Pos 1)) && correct (B::B (((Rem (Pos 4) (Pos 3)) :: TInt) == Pos 1)) && correct (B::B (Zero < Pos 1)) && correct (B::B ( ((Rem (Pos 3) (Pos 3)) :: TInt) < ((Rem (Pos 4) (Pos 3)) :: TInt) )) it "provides type-level integer division truncated toward negative infinity 'Div'" $ example pending describe "has sign operations at type-level (TypeSign)" $ do it "provides type-level sign" $ example pending it "provides type-level absolute value" $ example pending it "provides type-level unary negation" $ example pending it "provides type-level sign to number transformation" $ example pending describe "has subtraction operation at type-level (TypesSubtraction)" $ it "provides type-level subtraction (-)" $ example pending
fehu/TypeNumerics
test/TypeNum/Test/Int.hs
mit
5,791
106
30
2,035
2,569
1,344
1,225
-1
-1
{-# htermination (until :: (a -> MyBool) -> (a -> a) -> a -> a) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil until0 x p f MyTrue = x; until0 x p f MyFalse = until p f (f x); until :: (a -> MyBool) -> (a -> a) -> a -> a; until p f x = until0 x p f (p x);
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/until_1.hs
mit
331
0
8
103
140
76
64
7
1
import System.Environment (getArgs) interactWith function inputFile outputFile = do input <- readFile inputFile writeFile outputFile (function input) main = mainWith myFunction where mainWith function = do args <- getArgs case args of [input, output] -> interactWith function input output _ -> putStrLn "error: exactly two arguments needed" myFunction = id
zhangjiji/real-world-haskell
ch4-interactWith.hs
mit
418
1
11
111
114
54
60
11
2
module Main where import Test.HUnit (runTestTT, Test(TestList)) import Tests.IRC.Commands (respondTest) main :: IO () main = do _ <- runTestTT $ TestList [respondTest] return ()
jdiez17/HaskellHawk
test/Main.hs
mit
191
0
10
38
72
40
32
7
1
module Lexer where import Text.Parsec.String (Parser) import Text.Parsec.Language (emptyDef) import qualified Text.Parsec.Token as Tok lexer :: Tok.TokenParser () lexer = Tok.makeTokenParser style where ops = ["+","*","-","/",";",",","<"] names = ["def","extern"] style = emptyDef { Tok.commentLine = "#" , Tok.reservedOpNames = ops , Tok.reservedNames = names } integer = Tok.integer lexer float = Tok.float lexer parens = Tok.parens lexer commaSep = Tok.commaSep lexer semiSep = Tok.semiSep lexer identifier = Tok.identifier lexer whitespace = Tok.whiteSpace lexer reserved = Tok.reserved lexer reservedOp = Tok.reservedOp lexer
TorosFanny/kaleidoscope
src/chapter3/Lexer.hs
mit
722
0
8
172
217
124
93
21
1
{-# htermination max :: () -> () -> () #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_max_1.hs
mit
43
0
2
10
3
2
1
1
0
module System.Random.PCG ( mkPCGGen , getPCGGen , newPCGGen , getPCGRandom ) where import System.CPUTime (getCPUTime) import Data.Time.Clock.POSIX (getPOSIXTime) import System.Random import System.Random.PCG.Internal import Data.IORef import System.IO.Unsafe ( unsafePerformIO ) {-# NOINLINE globalGen #-} globalGen :: IORef PCGGen globalGen = unsafePerformIO $ do gen <- mkPCGGen' newIORef gen -- | This is not really robust. mkPCGGen' :: IO PCGGen mkPCGGen' = do pTime <- getPOSIXTime sTime <- getCPUTime pure $ mkPCGGen (floor pTime) (fromInteger sTime) newPCGGen :: IO PCGGen newPCGGen = atomicModifyIORef' globalGen split getPCGGen :: IO PCGGen getPCGGen = readIORef globalGen getPCGRandom :: (PCGGen -> (a, PCGGen)) -> IO a getPCGRandom f = atomicModifyIORef' globalGen (swap . f) where swap (b, a) = (a, b)
wmarvel/haskellrogue
src/System/Random/PCG.hs
mit
849
0
10
150
255
140
115
29
1
module Vacchi.Fractals.Types where ------------------------------------------ -- config types (used in config.hs) ------------------------------------------ data Fractal = Fractal { fractal :: [IFS], -- IFS list scaleFactor :: Float, -- scaling factor iterations :: Int, -- number of iterations offsetX :: Float, -- horizontal offset on the canvas offsetY :: Float -- vertical offset on the canvas } data Params = Params { penSize :: Float, -- size of the circles on the canvas palette :: (Float,Float), -- color interval of the palette (subrange in [0,1]) alpha :: Float -> Float, -- function from a hue value to an alpha value [0,1] saturation :: Float->Float, -- function from a hue value to a saturation value [0,1] lightness :: Float->Float, -- function from a hue value to a lightness value [0,1] animated :: Bool -- True for an animated visualization, False for static } ------------------------------------------ -- types used in actual computations ------------------------------------------ -- A variation is just a function R^2->R^2 type Variation = (Float,Float) -> (Float,Float) -- IFS data type -- -- it represents a IFS function as a pair of triples -- specifying the coefficients for x, y -- the last float value is a probability -- -- the IfsVar alternate datatype provides a Variation type, which is a function data IFS = Ifs (Float,Float,Float) (Float,Float,Float) Float | IfsVar (Float,Float,Float) (Float,Float,Float) Float Variation -- definition of an IFS function: ifs_def :: (Float,Float) -- input point (x_0,y_0) -> (Float,Float,Float) -- coefficients for the x coord -> (Float,Float,Float) -- coefficients for the y coord -> (Float,Float) -- result (x_1, y_1) ifs_def (x,y) (a,b,c) (d,e,f) = (a*x + b*y + c, d*x + e*y + f) -- default implementation for non-variated IFS ifs :: (Float,Float) -> IFS -> (Float,Float) ifs point (Ifs param1 param2 _) = let result = ifs_def point param1 param2 in (fst result, snd result) -- implementation for variated IFS ifs point (IfsVar param1 param2 _ variation_function) = let result = variation_function (ifs_def point param1 param2) in (fst result, snd result)
evacchi/chaosgame
src/Vacchi/Fractals/Types.hs
mit
2,207
36
11
408
518
311
207
29
1
-- | Author : John Allard -- | Date : Feb 5th 2016 -- | Class : CMPS 112 UCSC -- | I worked alone, no partners to list. -- | Homework #3 |-- import Data.Char import Data.List -- | 1. Suppose we have the following type of binary search trees with -- keys of type k and values of type v: data BST k v = Empty | Node k v (BST k v) (BST k v) -- | Write a val function that returns Just the stored value at the -- root node of the tree. If the tree is empty, val returns Nothing. val :: BST k v -> Maybe v val Empty = Nothing val (Node key val lbst rbst) = Just val -- | 2. Write a size function that returns the number of nodes in the tree. size :: BST k v -> Int size Empty = 0 size (Node key val lbst rbst) = 1 + (size lbst) + (size rbst) -- | 3. Write an ins function that inserts a value v using k as key. If the -- key is already used in the tree, it just updates the value, otherwise -- it will add a new node while maintaining the order of the binary search tree. ins :: (Ord k) => k -> v -> BST k v -> BST k v ins key val Empty = (Node key val (Empty) (Empty)) ins key val (Node k v lbst rbst) = if key < k then Node k v (ins key val (lbst)) rbst else Node k v lbst (ins key val (rbst)) -- | 4. Make BST an instance of the Show type class. You will have to implement the -- show function such that the result every node of the tree is shown as "(leftTree value rightTree)". instance (Show v) => Show (BST k v) where show Empty = "" show (Node k v left right) = "(" ++ show left ++ " " ++ show v ++ " " ++ show right ++ ")" -- | 5. Suppose we had the following datatype data JSON = JStr String | JNum Double | JArr [JSON] | JObj [(String, JSON)] -- | make JSON an instance of the Show type class. You will have to implement the show function such that the -- output looks like normal JSON. instance Show JSON where show (JStr s) = show s show (JNum d) = show d show (JArr a) = "[" ++ intercalate ", " (map show a) ++ "]" show (JObj lst) = "{" ++ intercalate ", " (map (\x -> show (fst x) ++ ":" ++ show (snd x)) lst) ++ "}"
jhallard/WinterClasses16
CS112/hw/hw3/hw3.hs
mit
2,208
0
16
634
599
310
289
27
2
module HandBrake.Encode ( AudioTracks(..), Chapters(..), EncodeDetails, EncodeRequest, Numbering(..) , Profile(..), SubtitleTracks( SubtitleTracks ), TwoPass(..) , audioEncoder, audios, chapters, details, encodeArgs, encodeRequest , encodeRequest1, input, name, numbering, options, outputDir, outputName , profile, quality, subtitles, titleID, twoPass , parseEncodeDetails , readNT ) where import Prelude ( Float, (+), (-), fromIntegral ) -- base -------------------------------- import Control.Applicative ( optional, pure, some ) import Control.Monad ( mapM, return ) import Data.Eq ( Eq ) import Data.Function ( ($), id ) import Data.List.NonEmpty ( NonEmpty( (:|) ) ) import Data.Maybe ( maybe ) import Data.Ord ( Ordering( GT, EQ, LT ), (<), compare ) import Data.String ( unwords ) import GHC.Generics ( Generic ) import Text.Read ( read ) import Text.Show ( Show( show ) ) -- base-unicode-symbols ---------------- import Data.Eq.Unicode ( (≡) ) import Data.Function.Unicode ( (∘) ) import Data.Monoid.Unicode ( (⊕) ) import Numeric.Natural.Unicode ( ℕ ) import Prelude.Unicode ( ℤ ) -- data-textual ------------------------ import Data.Textual ( Printable( print ), toText ) -- deepseq ----------------------------- import Control.DeepSeq ( NFData ) -- fpath ------------------------------- import qualified FPath.Parseable import FPath.AbsDir ( AbsDir ) import FPath.AbsFile ( AbsFile ) import FPath.AppendableFPath ( (⫻) ) import FPath.Error.FPathError ( AsFPathError ) import FPath.Parseable ( readM ) import FPath.PathComponent ( PathComponent ) import FPath.RelFile ( RelFile ) -- lens -------------------------------- import Control.Lens.Lens ( Lens', lens ) -- more-unicode ------------------------ import Data.MoreUnicode.Applicative ( (⋪), (⋫), (⊵), (∤) ) import Data.MoreUnicode.Functor ( (⊳) ) import Data.MoreUnicode.Lens ( (⊣) ) import Data.MoreUnicode.Maybe ( 𝕄, pattern 𝕵, pattern 𝕹 ) import Data.MoreUnicode.Monad ( (≫) ) import Data.MoreUnicode.Monoid ( ю ) import Data.MoreUnicode.Text ( 𝕋 ) -- mtl --------------------------------- import Control.Monad.Except ( MonadError ) -- optparse-applicative ---------------- import Options.Applicative.Builder ( auto, flag, flag', help , long, option, short, strOption, value ) import Options.Applicative.Types ( Parser ) -- optparse-plus ----------------------- import OptParsePlus ( parsecReader, parsecReadM, readNT ) -- parsec-plus ------------------------- import ParsecPlus ( Parsecable( parser ) ) -- parsers ----------------------------- import Text.Parser.Char ( CharParsing, char, digit, string ) import Text.Parser.Combinators ( sepBy, eof ) -- parser-plus ------------------------- import ParserPlus ( parseFloat2_1, sepByNE, tries ) -- range ------------------------------- import Data.Range ( Bound( Bound ), BoundType( Exclusive, Inclusive ), Range( InfiniteRange, LowerBoundRange, SingletonRange , SpanRange, UpperBoundRange ) , (+=+) ) -- stdmain ----------------------------- import StdMain.UsageError ( AsUsageError, throwUsage ) -- text -------------------------------- import Data.Text ( map, pack ) -- text-printer ------------------------ import qualified Text.Printer as P -- tfmt -------------------------------- import Text.Fmt ( fmt, fmtT ) -------------------------------------------------------------------------------- data TwoPass = TwoPass | NoTwoPass deriving (Eq,Generic,NFData,Show) parseTwoPass ∷ Parser TwoPass parseTwoPass = flag TwoPass NoTwoPass (ю [ short 'S' , long "--single-pass" , help "single-pass encoding (faster, worse" ]) ------------------------------------------------------------ data Numbering = NoNumber | Number ℤ {- with output offset -} | Series (ℕ,𝕋) ℤ {- title, series number, output offset -} deriving (Eq,Generic,NFData,Show) parseNumbering ∷ Parser Numbering parseNumbering = let parseNumber ∷ Parser (ℤ → Numbering) parseNumber = pure Number parseSeries ∷ Parser (ℤ → Numbering) parseSeries = Series ⊳ option readNT (ю [ short 'e', long "series" , help "series NUM=NAME" ]) parseOffset ∷ Parser ℤ parseOffset = option auto (ю [ short 'i', long "input-offset", value 0 , help "offset output numbers" ]) parseNoNumber ∷ Parser Numbering parseNoNumber = flag' NoNumber (short 'N' ⊕ long "no-number") in (((parseNumber ∤ parseSeries) ⊵ parseOffset) ∤ parseNoNumber) ------------------------------------------------------------ data Profile = ProfileH265_2160P | ProfileH265_1080P | ProfileH265_720P | ProfileH265_576P | ProfileH265_480P -- Dead Video is a super-simple video profile, meant for -- throwaway video (e.g., tracks where the video is static, -- that we'll later just rip the audio from) | Profile_DeadVideo deriving (Eq,Generic,NFData,Show) instance Printable Profile where print ProfileH265_2160P = P.text "H.265 MKV 2160p60" print ProfileH265_1080P = P.text "H.265 MKV 1080p30" print ProfileH265_720P = P.text "H.265 MKV 720p30" print ProfileH265_576P = P.text "H.265 MKV 576p25" print ProfileH265_480P = P.text "H.265 MKV 480p30" print Profile_DeadVideo = P.text "H.265 MKV 480p30" instance Parsecable Profile where parser = let names ∷ CharParsing ψ ⇒ (NonEmpty (ψ Profile)) names = (pure ProfileH265_2160P ⋪ string "2160") :| [ pure ProfileH265_1080P ⋪ string "1080" , pure ProfileH265_2160P ⋪ string "1080" , pure ProfileH265_720P ⋪ string "720" , pure ProfileH265_576P ⋪ string "576" , pure ProfileH265_480P ⋪ string "480" , pure Profile_DeadVideo ⋪ string "D" ] in tries names ⋪ optional (char 'p' ∤ char 'P') ⋪ eof parseProfile ∷ Parser Profile parseProfile = option parsecReader (ю [ short 'p', long "profile" , help "encoding profile" , value ProfileH265_2160P ]) ------------------------------------------------------------ newtype Chapters = Chapters { unChapters ∷ 𝕄 (Range ℕ) } instance Show Chapters where show c = [fmt|Chapters «%T»|] c instance Printable Chapters where print (Chapters 𝕹) = P.text "" print (Chapters (𝕵 (SingletonRange n))) = P.text $ [fmt|%d|] n print (Chapters (𝕵 (InfiniteRange))) = P.text $ [fmt|-|] print (Chapters (𝕵 (LowerBoundRange (Bound a Inclusive)))) = P.text $ [fmt|[%d-|] a print (Chapters (𝕵 (LowerBoundRange (Bound a Exclusive)))) = P.text $ [fmt|(%d-|] a print (Chapters (𝕵 (UpperBoundRange (Bound a Inclusive)))) = P.text $ [fmt|-%d]|] a print (Chapters (𝕵 (UpperBoundRange (Bound a Exclusive)))) = P.text $ [fmt|-%d)|] a print (Chapters (𝕵 (SpanRange (Bound a Inclusive) (Bound b Inclusive)))) = P.text $ [fmt|[%d-%d]|] a b print (Chapters (𝕵 (SpanRange (Bound a Exclusive) (Bound b Inclusive)))) = P.text $ [fmt|(%d-%d]|] a b print (Chapters (𝕵 (SpanRange (Bound a Inclusive) (Bound b Exclusive)))) = P.text $ [fmt|[%d-%d)|] a b print (Chapters (𝕵 (SpanRange (Bound a Exclusive) (Bound b Exclusive)))) = P.text $ [fmt|(%d-%d)|] a b parseSimpleNRange ∷ CharParsing γ ⇒ γ (Range ℕ) parseSimpleNRange = let readN ∷ CharParsing γ ⇒ γ ℕ readN = read ⊳ some digit toRange ∷ ℕ → 𝕄 ℕ → Range ℕ toRange a 𝕹 = SingletonRange a toRange a (𝕵 b) = a +=+ b in toRange ⊳ readN ⊵ optional (char '-' ⋫ readN) instance Parsecable Chapters where parser = Chapters ∘ 𝕵 ⊳ parseSimpleNRange parseChapters ∷ Parser Chapters parseChapters = option parsecReader (ю [ short 'c', long "chapters", value (Chapters 𝕹) , help "select chapters to encode" ]) ------------------------------------------------------------ defaultQuality ∷ Float defaultQuality = 26 parseQuality ∷ Parser Float parseQuality = option (parsecReadM "-q" parseFloat2_1) (ю [ short 'q', long "quality", value defaultQuality , help $ [fmt|encoding quality (default %3.1f)|] defaultQuality ]) ---------------------------------------- parseOutputName ∷ Parser (𝕄 PathComponent) parseOutputName = let mods = ю [ short 'o', long "output", help "output file base name" ] in optional (option readM mods) ---------------------------------------- parseAudioEncoder ∷ Parser (𝕄 𝕋) parseAudioEncoder = let mods = ю [ short 'E', long "aencoder", long "audio-encoder" , help "set audio encoder(s) (see HandBrakeCLI -E)" ] in optional (strOption mods) ------------------------------------------------------------ {- | Options that have standard values, but may be adjusted for encodes. -} data EncodeOptions = EncodeOptions { _numbering ∷ Numbering , _chapters ∷ Chapters , _twoPass ∷ TwoPass , _profile ∷ Profile -- 20 is default, use 26 for 1080p , _quality ∷ Float , _outputName ∷ 𝕄 PathComponent , _audioEncoder ∷ 𝕄 𝕋 } deriving Show ------------------------------------------------------------ class HasEncodeOptions α where _EncodeOptions ∷ Lens' α EncodeOptions numbering ∷ Lens' α Numbering numbering = _EncodeOptions ∘ numbering chapters ∷ Lens' α Chapters chapters = _EncodeOptions ∘ chapters twoPass ∷ Lens' α TwoPass twoPass = _EncodeOptions ∘ twoPass profile ∷ Lens' α Profile profile = _EncodeOptions ∘ profile quality ∷ Lens' α Float quality = _EncodeOptions ∘ quality outputName ∷ Lens' α (𝕄 PathComponent) outputName = _EncodeOptions ∘ outputName audioEncoder ∷ Lens' α (𝕄 𝕋) audioEncoder = _EncodeOptions ∘ audioEncoder instance HasEncodeOptions EncodeOptions where _EncodeOptions = id numbering = lens _numbering (\ eo x → eo { _numbering = x }) chapters = lens _chapters (\ eo x → eo { _chapters = x }) twoPass = lens _twoPass (\ eo x → eo { _twoPass = x }) profile = lens _profile (\ eo x → eo { _profile = x }) quality = lens _quality (\ eo x → eo { _quality = x }) audioEncoder = lens _audioEncoder (\ eo x → eo { _audioEncoder = x }) outputName = lens _outputName (\ eo n → eo { _outputName = n }) ---------------------------------------- parseEncodeOptions ∷ Parser EncodeOptions parseEncodeOptions = EncodeOptions ⊳ parseNumbering ⊵ parseChapters ⊵ parseTwoPass ⊵ parseProfile ⊵ parseQuality ⊵ parseOutputName ⊵ parseAudioEncoder ------------------------------------------------------------ newtype AudioTracks = AudioTracks { unAudioTracks ∷ NonEmpty ℕ } deriving Show instance Parsecable AudioTracks where parser = AudioTracks ⊳ sepByNE (read ⊳ some digit) (char ',') parseAudioTracks ∷ Parser AudioTracks parseAudioTracks = option parsecReader (ю [ short 'a', long "audios" , help (unwords [ "audio track ids; as reported by scan. These will" , "be a 1-based index." ]) ] ) ------------------------------------------------------------ newtype SubtitleTracks = SubtitleTracks { unSubtitleTracks ∷ [ℕ] } deriving Show instance Parsecable SubtitleTracks where parser = SubtitleTracks ⊳ sepBy (read ⊳ some digit) (char ',') parseSubtitleTracks ∷ Parser SubtitleTracks parseSubtitleTracks = option parsecReader (ю [ help (unwords [ "subtitle track ids; as reported by scan. These" , "will be a 1-based index. The first subtitle" , "selected will be set as the default." ] ) , value $ SubtitleTracks [] , short 's' , long "subs" , long "subtitles" ]) ------------------------------------------------------------ {- | Everything that must be specified for an encode, 'cept input, titleID & name. -} data EncodeDetails = EncodeDetails { _audios ∷ AudioTracks -- first, if any, is the default -- this is because --subtitle-default -- a HandBrakeCLI argument is actually an -- index into the --subtitle list argument , _subtitles ∷ SubtitleTracks , _options ∷ EncodeOptions } deriving Show parseEncodeDetails ∷ Parser EncodeDetails parseEncodeDetails = EncodeDetails ⊳ parseAudioTracks ⊵ parseSubtitleTracks ⊵ parseEncodeOptions class HasEncodeDetails α where _EncodeDetails ∷ Lens' α EncodeDetails audios ∷ Lens' α AudioTracks audios = _EncodeDetails ∘ audios subtitles ∷ Lens' α SubtitleTracks subtitles = _EncodeDetails ∘ subtitles options ∷ Lens' α EncodeOptions options = _EncodeDetails ∘ options instance HasEncodeDetails EncodeDetails where _EncodeDetails = id audios = lens _audios (\ ed x → ed { _audios = x }) subtitles = lens _subtitles (\ ed x → ed { _subtitles = x }) options = lens _options (\ ed x → ed { _options = x }) instance HasEncodeOptions EncodeDetails where _EncodeOptions = options ------------------------------------------------------------ data EncodeRequest = EncodeRequest { _input ∷ AbsFile , _titleID ∷ ℕ , _name ∷ 𝕄 𝕋 , _details ∷ EncodeDetails , _outputDir ∷ AbsDir } deriving Show class HasEncodeRequest α where _EncodeRequest ∷ Lens' α EncodeRequest input ∷ Lens' α AbsFile input = _EncodeRequest ∘ input titleID ∷ Lens' α ℕ titleID = _EncodeRequest ∘ titleID name ∷ Lens' α (𝕄 𝕋) name = _EncodeRequest ∘ name details ∷ Lens' α EncodeDetails details = _EncodeRequest ∘ details outputDir ∷ Lens' α AbsDir outputDir = _EncodeRequest ∘ outputDir instance HasEncodeRequest EncodeRequest where _EncodeRequest = id titleID = lens _titleID (\ er t → er { _titleID = t }) name = lens _name (\ er n → er { _name = n }) input = lens _input (\ er f → er { _input = f }) details = lens _details (\ er d → er { _details = d }) outputDir = lens _outputDir (\ er d → er { _outputDir = d }) instance HasEncodeDetails EncodeRequest where _EncodeDetails = details instance HasEncodeOptions EncodeRequest where _EncodeOptions = details ∘ options ------------------------------------------------------------ {- Output basename, sanitized for safety. -} nameSafe ∷ EncodeRequest → 𝕄 𝕋 nameSafe er = map go ⊳ er ⊣ name where go '/' = '-' go ':' = '-' go c = c -------------------- outputNum ∷ (AsUsageError ε, MonadError ε η) ⇒ EncodeRequest → η ℕ outputNum er = let (on,oo) = case er ⊣ numbering of NoNumber → (0,0) Number o → (o + (fromIntegral $ er ⊣ titleID),o) Series _ o → (o + (fromIntegral $ er ⊣ titleID),o) in if on < 1 then throwUsage $ [fmtT|output number %d (%d+(%d)) < 0|] on (er ⊣ titleID) oo else return $ fromIntegral on ---------------------------------------- {- | Create a basic `EncodeRequest` with mandatory arguments. -} encodeRequest ∷ AbsFile -- ^ video input → AbsDir -- ^ output directory → ℕ -- ^ titleID within input to encode → 𝕄 𝕋 -- ^ output base name → AudioTracks -- ^ input audio IDs to encode → EncodeRequest encodeRequest i d t n as = EncodeRequest { _input = i , _titleID = t , _name = n , _outputDir = d , _details = EncodeDetails { _audios = as , _subtitles = SubtitleTracks $ [] , _options = EncodeOptions { _numbering = Number 0 , _chapters = Chapters 𝕹 , _twoPass = TwoPass , _profile = ProfileH265_2160P , _quality = defaultQuality , _outputName = 𝕹 , _audioEncoder = 𝕹 } } } {- | `encodeRequest` with single audio track 1. -} encodeRequest1 ∷ AbsFile -- ^ video input → AbsDir -- ^ output dir → ℕ -- ^ titleID within input to encode → 𝕄 𝕋 -- ^ output base name → EncodeRequest encodeRequest1 i d t n = encodeRequest i d t n (AudioTracks $ pure 1) ---------------------------------------- {- | Implied output file of an `EncodeRequest`. -} erImpliedName ∷ (AsUsageError ε, AsFPathError ε, MonadError ε η) ⇒ EncodeRequest → η 𝕋 erImpliedName er = do case er ⊣ numbering of NoNumber → case nameSafe er of 𝕵 n → return $ [fmtT|%t.mkv|] n 𝕹 → throwUsage $ [fmtT|no number & no title|] Number _ → do output_num ← outputNum er case nameSafe er of 𝕵 n → return $ [fmtT|%02d-%t.mkv|] output_num n 𝕹 → return $ [fmtT|%02d.mkv|] output_num Series (s,nm) _ → do output_num ← outputNum er case nameSafe er of 𝕵 n → return $ [fmtT|%t - %02dx%02d - %t.mkv|] nm s output_num n 𝕹 → return $ [fmtT|%t - %02dx%02d.mkv|] nm s output_num -------------------- {- | Chosen output file of an `EncodeRequest`. -} erOutput ∷ (AsUsageError ε, AsFPathError ε, MonadError ε η) ⇒ EncodeRequest → η AbsFile erOutput er = do p ← case er ⊣ outputName of 𝕹 → erImpliedName er ≫ FPath.Parseable.parse @RelFile 𝕵 f → FPath.Parseable.parse @RelFile f return $ (er ⊣ outputDir) ⫻ p -------------------- {- | Arguments to HandBrakeCLI for a given `EncodeRequest`. -} encodeArgs ∷ ∀ ε η . (AsUsageError ε, AsFPathError ε, MonadError ε η) ⇒ EncodeRequest → η ([𝕋],AbsFile) encodeArgs er = do output ← erOutput er cs ← mapM formatBoundedNRange (unChapters $ er ⊣ chapters) let args = ю [ [ "--input" , toText $ er ⊣ input , "--title" , pack (show $ er ⊣ titleID) , "--markers" -- chapter markers ] , if er ⊣ profile ≡ Profile_DeadVideo then [] else [ "--deinterlace" ] , [ "--audio-copy-mask" , "aac,ac3,eac3,truehd,dts,dtshd,mp3,flac" ] , case er ⊣ twoPass of TwoPass → if er ⊣ profile ≡ Profile_DeadVideo then [] else [ "--two-pass", "--turbo" ] NoTwoPass → [] , [ "--preset", toText $ er ⊣ profile ] , case er ⊣ audioEncoder of 𝕹 → [ "--aencoder", "copy" ] 𝕵 t → [ "--aencoder", t ] , [ "--audio", [fmt|%L|] (show ⊳ unAudioTracks (er ⊣ audios)) ] , case unSubtitleTracks (er ⊣ subtitles) of [] → [] ss → [ "--subtitle", [fmt|%L|] (show ⊳ ss) -- note that with HandBrakeCLI, subtitle-default is an -- index into the list provided to --subtitle. If -- this doesn't work, maybe it's 1-based… , "--subtitle-default", "0" ] , [ "--quality", [fmt|%03.1f|] (er ⊣ quality) ] , maybe [] (\ c → ["--chapters" , [fmt|%t|] c]) cs , [ "--output", toText output ] ] return (args,output) {- | Take a range, which must be a single SingletonRange or a single SpanRange, and format that as `x` or `y-z`. For a span range, the lower bound must be less than or equal to the upper bound; XXX -} formatBoundedNRange ∷ (AsUsageError ε, MonadError ε μ) ⇒ Range ℕ → μ 𝕋 formatBoundedNRange InfiniteRange = throwUsage $ [fmtT|illegal range «-»|] formatBoundedNRange (SingletonRange n) = return $ [fmt|%d|] n formatBoundedNRange (LowerBoundRange (Bound a Inclusive)) = throwUsage $ [fmtT|illegal range «[%d-»|] a formatBoundedNRange (LowerBoundRange (Bound a Exclusive)) = throwUsage $ [fmtT|illegal range «(%d-»|] a formatBoundedNRange (UpperBoundRange (Bound a Inclusive)) = throwUsage $ [fmtT|illegal range «-%d]»|] a formatBoundedNRange (UpperBoundRange (Bound a Exclusive)) = throwUsage $ [fmtT|illegal range «-%d)»|] a formatBoundedNRange (SpanRange (Bound a Inclusive) (Bound b Inclusive)) = case compare a b of LT → return $ [fmt|%d-%d|] a b EQ → return $ [fmt|%d|] a GT → throwUsage $ [fmtT|Range [%d-%d] is inverted|] a b formatBoundedNRange (SpanRange (Bound a Exclusive) (Bound b Inclusive)) = case compare (a+1) b of LT → return $ [fmt|%d-%d|] (a+1) b EQ → return $ [fmt|%d|] b GT → throwUsage $ [fmtT|Range (%d-%d] is inverted|] a b formatBoundedNRange (SpanRange (Bound a Inclusive) (Bound b Exclusive)) = if b ≡ 0 then throwUsage $ [fmtT|Range [%d-%d) is illegal|] a b else case compare a (b-1) of LT → return $ [fmt|%d-%d|] a (b-1) EQ → return $ [fmt|%d|] a GT → throwUsage $ [fmtT|Range [%d-%d) is inverted|] a b formatBoundedNRange (SpanRange (Bound a Exclusive) (Bound b Exclusive)) = if b ≡ 0 then throwUsage $ [fmtT|Range [%d-%d) is illegal|] a b else case compare (a+1) (b-1) of LT → return $ [fmt|%d-%d|] (a+1) (b-1) EQ → return $ [fmt|%d|] (a+1) GT → throwUsage $ [fmtT|Range (%d-%d) is inverted|] a b -- that's all, folks! ----------------------------------------------------------
sixears/handbrake
src/HandBrake/Encode.hs
mit
24,206
127
21
7,633
5,708
3,213
2,495
-1
-1
module Audit.Options ( Opts(..), fullOpts, module Options.Applicative.Extra ) where import Options.Applicative import Options.Applicative.Extra data Opts = Opts { cabalFile :: Maybe FilePath } deriving Show opts :: Parser Opts opts = Opts <$> optional (argument str ( metavar "FILE" <> help ".cabal file to parse" )) fullOpts :: ParserInfo Opts fullOpts = info (helper <*> opts) ( fullDesc <> progDesc "Audit your .cabal file" )
pikajude/cabal-audit
src/Audit/Options.hs
mit
508
0
11
144
133
74
59
14
1
module Triangle (TriangleType(..), triangleType) where data TriangleType = Equilateral | Isosceles | Scalene | Illegal | Degenerate deriving (Eq, Show) triangleType :: Float -> Float -> Float -> TriangleType triangleType a b c | a > (b+c) || b > (a+c) || c > (a+b) = Illegal | a <= 0.0 || b <= 0.0 || c <= 0.0 = Illegal | a == (b+c) || b == (a+c) || c == (a+b) = Degenerate | a == b && a == c = Equilateral | a == b || a == c || b == c = Isosceles | a /= b && a /= c && b /= c = Scalene | otherwise = Illegal
vaibhav276/exercism_haskell
triangle/src/Triangle.hs
mit
713
0
14
321
289
150
139
16
1
main :: IO () main = do contents <- getContents putStrLn contents let myLines = lines contents mapM putStrLn myLines mainloop myLines return () mainloop :: [String] -> IO () mainloop contents@(x:xs) = do words x mapM putStrLn words if xs == [] then return () else mainloop xs
doylew/practice
haskell/readthenwrite.hs
mit
315
0
10
88
137
62
75
15
2
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Hadoop.Protos.RpcHeaderProtos.RpcResponseHeaderProto.RpcErrorCodeProto (RpcErrorCodeProto(..)) where import Prelude ((+), (/), (.)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' data RpcErrorCodeProto = ERROR_APPLICATION | ERROR_NO_SUCH_METHOD | ERROR_NO_SUCH_PROTOCOL | ERROR_RPC_SERVER | ERROR_SERIALIZING_RESPONSE | ERROR_RPC_VERSION_MISMATCH | FATAL_UNKNOWN | FATAL_UNSUPPORTED_SERIALIZATION | FATAL_INVALID_RPC_HEADER | FATAL_DESERIALIZING_REQUEST | FATAL_VERSION_MISMATCH | FATAL_UNAUTHORIZED deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data) instance P'.Mergeable RpcErrorCodeProto instance Prelude'.Bounded RpcErrorCodeProto where minBound = ERROR_APPLICATION maxBound = FATAL_UNAUTHORIZED instance P'.Default RpcErrorCodeProto where defaultValue = ERROR_APPLICATION toMaybe'Enum :: Prelude'.Int -> P'.Maybe RpcErrorCodeProto toMaybe'Enum 1 = Prelude'.Just ERROR_APPLICATION toMaybe'Enum 2 = Prelude'.Just ERROR_NO_SUCH_METHOD toMaybe'Enum 3 = Prelude'.Just ERROR_NO_SUCH_PROTOCOL toMaybe'Enum 4 = Prelude'.Just ERROR_RPC_SERVER toMaybe'Enum 5 = Prelude'.Just ERROR_SERIALIZING_RESPONSE toMaybe'Enum 6 = Prelude'.Just ERROR_RPC_VERSION_MISMATCH toMaybe'Enum 10 = Prelude'.Just FATAL_UNKNOWN toMaybe'Enum 11 = Prelude'.Just FATAL_UNSUPPORTED_SERIALIZATION toMaybe'Enum 12 = Prelude'.Just FATAL_INVALID_RPC_HEADER toMaybe'Enum 13 = Prelude'.Just FATAL_DESERIALIZING_REQUEST toMaybe'Enum 14 = Prelude'.Just FATAL_VERSION_MISMATCH toMaybe'Enum 15 = Prelude'.Just FATAL_UNAUTHORIZED toMaybe'Enum _ = Prelude'.Nothing instance Prelude'.Enum RpcErrorCodeProto where fromEnum ERROR_APPLICATION = 1 fromEnum ERROR_NO_SUCH_METHOD = 2 fromEnum ERROR_NO_SUCH_PROTOCOL = 3 fromEnum ERROR_RPC_SERVER = 4 fromEnum ERROR_SERIALIZING_RESPONSE = 5 fromEnum ERROR_RPC_VERSION_MISMATCH = 6 fromEnum FATAL_UNKNOWN = 10 fromEnum FATAL_UNSUPPORTED_SERIALIZATION = 11 fromEnum FATAL_INVALID_RPC_HEADER = 12 fromEnum FATAL_DESERIALIZING_REQUEST = 13 fromEnum FATAL_VERSION_MISMATCH = 14 fromEnum FATAL_UNAUTHORIZED = 15 toEnum = P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type Hadoop.Protos.RpcHeaderProtos.RpcResponseHeaderProto.RpcErrorCodeProto") . toMaybe'Enum succ ERROR_APPLICATION = ERROR_NO_SUCH_METHOD succ ERROR_NO_SUCH_METHOD = ERROR_NO_SUCH_PROTOCOL succ ERROR_NO_SUCH_PROTOCOL = ERROR_RPC_SERVER succ ERROR_RPC_SERVER = ERROR_SERIALIZING_RESPONSE succ ERROR_SERIALIZING_RESPONSE = ERROR_RPC_VERSION_MISMATCH succ ERROR_RPC_VERSION_MISMATCH = FATAL_UNKNOWN succ FATAL_UNKNOWN = FATAL_UNSUPPORTED_SERIALIZATION succ FATAL_UNSUPPORTED_SERIALIZATION = FATAL_INVALID_RPC_HEADER succ FATAL_INVALID_RPC_HEADER = FATAL_DESERIALIZING_REQUEST succ FATAL_DESERIALIZING_REQUEST = FATAL_VERSION_MISMATCH succ FATAL_VERSION_MISMATCH = FATAL_UNAUTHORIZED succ _ = Prelude'.error "hprotoc generated code: succ failure for type Hadoop.Protos.RpcHeaderProtos.RpcResponseHeaderProto.RpcErrorCodeProto" pred ERROR_NO_SUCH_METHOD = ERROR_APPLICATION pred ERROR_NO_SUCH_PROTOCOL = ERROR_NO_SUCH_METHOD pred ERROR_RPC_SERVER = ERROR_NO_SUCH_PROTOCOL pred ERROR_SERIALIZING_RESPONSE = ERROR_RPC_SERVER pred ERROR_RPC_VERSION_MISMATCH = ERROR_SERIALIZING_RESPONSE pred FATAL_UNKNOWN = ERROR_RPC_VERSION_MISMATCH pred FATAL_UNSUPPORTED_SERIALIZATION = FATAL_UNKNOWN pred FATAL_INVALID_RPC_HEADER = FATAL_UNSUPPORTED_SERIALIZATION pred FATAL_DESERIALIZING_REQUEST = FATAL_INVALID_RPC_HEADER pred FATAL_VERSION_MISMATCH = FATAL_DESERIALIZING_REQUEST pred FATAL_UNAUTHORIZED = FATAL_VERSION_MISMATCH pred _ = Prelude'.error "hprotoc generated code: pred failure for type Hadoop.Protos.RpcHeaderProtos.RpcResponseHeaderProto.RpcErrorCodeProto" instance P'.Wire RpcErrorCodeProto where wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum) wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum) wireGet 14 = P'.wireGetEnum toMaybe'Enum wireGet ft' = P'.wireGetErr ft' wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum wireGetPacked ft' = P'.wireGetErr ft' instance P'.GPB RpcErrorCodeProto instance P'.MessageAPI msg' (msg' -> RpcErrorCodeProto) RpcErrorCodeProto where getVal m' f' = f' m' instance P'.ReflectEnum RpcErrorCodeProto where reflectEnum = [(1, "ERROR_APPLICATION", ERROR_APPLICATION), (2, "ERROR_NO_SUCH_METHOD", ERROR_NO_SUCH_METHOD), (3, "ERROR_NO_SUCH_PROTOCOL", ERROR_NO_SUCH_PROTOCOL), (4, "ERROR_RPC_SERVER", ERROR_RPC_SERVER), (5, "ERROR_SERIALIZING_RESPONSE", ERROR_SERIALIZING_RESPONSE), (6, "ERROR_RPC_VERSION_MISMATCH", ERROR_RPC_VERSION_MISMATCH), (10, "FATAL_UNKNOWN", FATAL_UNKNOWN), (11, "FATAL_UNSUPPORTED_SERIALIZATION", FATAL_UNSUPPORTED_SERIALIZATION), (12, "FATAL_INVALID_RPC_HEADER", FATAL_INVALID_RPC_HEADER), (13, "FATAL_DESERIALIZING_REQUEST", FATAL_DESERIALIZING_REQUEST), (14, "FATAL_VERSION_MISMATCH", FATAL_VERSION_MISMATCH), (15, "FATAL_UNAUTHORIZED", FATAL_UNAUTHORIZED)] reflectEnumInfo _ = P'.EnumInfo (P'.makePNF (P'.pack ".hadoop.common.RpcResponseHeaderProto.RpcErrorCodeProto") ["Hadoop", "Protos"] ["RpcHeaderProtos", "RpcResponseHeaderProto"] "RpcErrorCodeProto") ["Hadoop", "Protos", "RpcHeaderProtos", "RpcResponseHeaderProto", "RpcErrorCodeProto.hs"] [(1, "ERROR_APPLICATION"), (2, "ERROR_NO_SUCH_METHOD"), (3, "ERROR_NO_SUCH_PROTOCOL"), (4, "ERROR_RPC_SERVER"), (5, "ERROR_SERIALIZING_RESPONSE"), (6, "ERROR_RPC_VERSION_MISMATCH"), (10, "FATAL_UNKNOWN"), (11, "FATAL_UNSUPPORTED_SERIALIZATION"), (12, "FATAL_INVALID_RPC_HEADER"), (13, "FATAL_DESERIALIZING_REQUEST"), (14, "FATAL_VERSION_MISMATCH"), (15, "FATAL_UNAUTHORIZED")] instance P'.TextType RpcErrorCodeProto where tellT = P'.tellShow getT = P'.getRead
alexbiehl/hoop
hadoop-protos/src/Hadoop/Protos/RpcHeaderProtos/RpcResponseHeaderProto/RpcErrorCodeProto.hs
mit
6,436
0
11
1,023
1,218
672
546
118
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-ondemandoptionsrequest.html module Stratosphere.ResourceProperties.EC2EC2FleetOnDemandOptionsRequest where import Stratosphere.ResourceImports -- | Full data type definition for EC2EC2FleetOnDemandOptionsRequest. See -- 'ec2EC2FleetOnDemandOptionsRequest' for a more convenient constructor. data EC2EC2FleetOnDemandOptionsRequest = EC2EC2FleetOnDemandOptionsRequest { _eC2EC2FleetOnDemandOptionsRequestAllocationStrategy :: Maybe (Val Text) } deriving (Show, Eq) instance ToJSON EC2EC2FleetOnDemandOptionsRequest where toJSON EC2EC2FleetOnDemandOptionsRequest{..} = object $ catMaybes [ fmap (("AllocationStrategy",) . toJSON) _eC2EC2FleetOnDemandOptionsRequestAllocationStrategy ] -- | Constructor for 'EC2EC2FleetOnDemandOptionsRequest' containing required -- fields as arguments. ec2EC2FleetOnDemandOptionsRequest :: EC2EC2FleetOnDemandOptionsRequest ec2EC2FleetOnDemandOptionsRequest = EC2EC2FleetOnDemandOptionsRequest { _eC2EC2FleetOnDemandOptionsRequestAllocationStrategy = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ec2fleet-ondemandoptionsrequest.html#cfn-ec2-ec2fleet-ondemandoptionsrequest-allocationstrategy ececfodorAllocationStrategy :: Lens' EC2EC2FleetOnDemandOptionsRequest (Maybe (Val Text)) ececfodorAllocationStrategy = lens _eC2EC2FleetOnDemandOptionsRequestAllocationStrategy (\s a -> s { _eC2EC2FleetOnDemandOptionsRequestAllocationStrategy = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/EC2EC2FleetOnDemandOptionsRequest.hs
mit
1,687
0
12
157
173
100
73
22
1
import Data.Set data Pos = Pos Int Int deriving (Eq, Ord, Show) data Mov = Mov Int Int deriving Show add :: Pos -> Mov -> Pos add (Pos a b) (Mov x y) = Pos (a Prelude.+ x) (b Prelude.+ y) in_bounds :: Pos -> Bool in_bounds (Pos x y) = (elem x [0..7]) && (elem y [0..7]) type Gen = Pos -> Set Pos gen_horse :: Gen gen_horse p = let moves = [Mov 2 1, Mov 1 2, Mov (-1) 2, Mov (-2) 1, Mov (-2) (-1), Mov (-1) (-2), Mov 1 (-2), Mov 2 (-1)] in fromList [add p m | m <- moves, in_bounds $ add p m] trace_gen :: Gen -> [Pos] -> Set [Pos] trace_gen g ps = let raw_hist = Data.Set.map (:ps) (g $ head ps) in Data.Set.filter (\l -> (length l) == (length $ fromList l)) raw_hist --instance Monad Set where -- return = singleton -- fail _ = empty (>>=) :: Ord b => Set a -> (a -> Set b) -> Set b (>>=) s f = let l = toList s in Prelude.foldl union empty (Prelude.map f l) reachability :: Gen -> Int -> Pos -> Set Pos reachability g 0 p = singleton p reachability g t p = (g p) Main.>>= reachability g (t-1) reach_trace :: Gen -> Int -> [Pos] -> Set [Pos] reach_trace g 0 p = singleton p reach_trace g t p = (trace_gen g p) Main.>>= reach_trace g (t-1) path_to_from :: Gen -> Int -> Pos -> Pos -> Set [Pos] path_to_from g t i f = Data.Set.filter (\l -> f == (head l)) $ reach_trace g t [i] main = do print $ reachability gen_horse 2 (Pos 4 4) print $ reachability gen_horse 2 (Pos 0 0) print $ reach_trace gen_horse 2 [Pos 0 0] print $ path_to_from gen_horse 2 (Pos 3 3) (Pos 0 0)
candide-guevara/programming_challenges
haskell_learning/chess_movement.hs
gpl-2.0
1,493
0
13
340
855
437
418
29
1
-- Copyright (C) 2003 David Roundy -- -- 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, 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; see the file COPYING. If not, write to -- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -- Boston, MA 02110-1301, USA. -- | -- Module : Darcs.UI.Commands.Dist -- Copyright : 2003 David Roundy -- License : GPL -- Maintainer : darcs-devel@darcs.net -- Stability : experimental -- Portability : portable module Darcs.UI.Commands.Dist ( dist , doFastZip -- libdarcs export , doFastZip' ) where import Prelude hiding ( (^), writeFile ) import Data.ByteString.Lazy ( writeFile ) import Data.Char ( isAlphaNum ) import Control.Monad ( when ) import System.Directory ( setCurrentDirectory ) import System.Process ( system ) import System.Exit ( ExitCode(..), exitWith ) import System.FilePath.Posix ( takeFileName, (</>) ) import Darcs.Util.Workaround ( getCurrentDirectory ) import Codec.Archive.Tar ( pack, write ) import Codec.Archive.Tar.Entry ( entryPath ) import Codec.Compression.GZip ( compress ) import Codec.Archive.Zip ( emptyArchive, fromArchive, addEntryToArchive, toEntry ) import Darcs.Repository.External ( fetchFilePS, Cachable( Uncachable ) ) import Darcs.Util.Global ( darcsdir ) import Darcs.Repository.HashedRepo ( inv2pris ) import Darcs.Repository.HashedIO ( pathsAndContents ) import Darcs.Repository.InternalTypes ( Repository (..) ) import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString as B import Darcs.UI.Flags ( DarcsFlag(Verbose, Quiet, DistName, DistZip, SetScriptsExecutable), useCache ) import Darcs.UI.Options ( DarcsOption, (^), oid, odesc, ocheck, onormalise , defaultFlags, parseFlags ) import qualified Darcs.UI.Options.All as O import Darcs.UI.Commands ( DarcsCommand(..), withStdOpts, nodefaults, amInHashedRepository ) import Darcs.Repository.Lock ( withTempDir ) import Darcs.Patch.Match ( haveNonrangeMatch , firstMatch ) import Darcs.Repository.Match ( getFirstMatch , getNonrangeMatch ) import Darcs.Repository ( withRepository, withRepositoryDirectory, RepoJob(..), setScriptsExecutable, repoPatchType, createPartialsPristineDirectoryTree ) import Darcs.Repository.Prefs ( getPrefval ) import Darcs.Util.DateTime ( getCurrentTime, toSeconds ) import Darcs.Util.Path ( AbsolutePath, toFilePath ) import Darcs.Util.File ( withCurrentDirectory ) distDescription :: String distDescription = "Create a distribution archive." distHelp :: String distHelp = unlines [ "`darcs dist` creates a compressed archive in the repository's root" , "directory, containing the recorded state of the working tree" , "(unrecorded changes and the `_darcs` directory are excluded)." , "The command accepts matchers to create an archive of some past" , "repository state, for instance `--tag`." , "" , "By default, the archive (and the top-level directory within the" , "archive) has the same name as the repository, but this can be" , "overridden with the `--dist-name` option." , "" , "If a predist command is set (see `darcs setpref`), that command will" , "be run on the recorded state prior to archiving. For example," , "autotools projects would set it to `autoconf && automake`." , "" , "If `--zip` is used, matchers and the predist command are ignored." ] distBasicOpts :: DarcsOption a (Maybe String -> Bool -> Maybe String -> [O.MatchFlag] -> O.SetScriptsExecutable -> Bool -> a) distBasicOpts = O.distname ^ O.distzip ^ O.workingRepoDir ^ O.matchOne ^ O.setScriptsExecutable ^ O.storeInMemory distOpts :: DarcsOption a (Maybe String -> Bool -> Maybe String -> [O.MatchFlag] -> O.SetScriptsExecutable -> Bool -> Maybe O.StdCmdAction -> Bool -> Bool -> O.Verbosity -> Bool -> O.UseCache -> Maybe String -> Bool -> Maybe String -> Bool -> a) distOpts = distBasicOpts `withStdOpts` oid dist :: DarcsCommand [DarcsFlag] dist = DarcsCommand { commandProgramName = "darcs" , commandName = "dist" , commandHelp = distHelp , commandDescription = distDescription , commandExtraArgs = 0 , commandExtraArgHelp = [] , commandCommand = distCmd , commandPrereq = amInHashedRepository , commandGetArgPossibilities = return [] , commandArgdefaults = nodefaults , commandAdvancedOptions = [] , commandBasicOptions = odesc distBasicOpts , commandDefaults = defaultFlags distOpts , commandCheckOptions = ocheck distOpts , commandParseOptions = onormalise distOpts } distCmd :: (AbsolutePath, AbsolutePath) -> [DarcsFlag] -> [String] -> IO () distCmd _ opts _ | DistZip `elem` opts = doFastZip opts distCmd _ opts _ = withRepository (useCache opts) $ RepoJob $ \repository -> do let matchFlags = parseFlags O.matchOne opts formerdir <- getCurrentDirectory let distname = getDistName formerdir [x | DistName x <- opts] predist <- getPrefval "predist" let resultfile = formerdir </> distname ++ ".tar.gz" withTempDir "darcsdist" $ \tempdir -> do setCurrentDirectory formerdir withTempDir (toFilePath tempdir </> takeFileName distname) $ \ddir -> do if haveNonrangeMatch (repoPatchType repository) matchFlags then if firstMatch matchFlags then withCurrentDirectory ddir $ getFirstMatch repository matchFlags else withCurrentDirectory ddir $ getNonrangeMatch repository matchFlags else createPartialsPristineDirectoryTree repository [""] (toFilePath ddir) ec <- case predist of Nothing -> return ExitSuccess Just pd -> system pd if ec == ExitSuccess then do withCurrentDirectory ddir $ when (SetScriptsExecutable `elem` opts) setScriptsExecutable doDist opts tempdir ddir resultfile else do putStrLn "Dist aborted due to predist failure" exitWith ec -- | This function performs the actual distribution action itself. -- NB - it does /not/ perform the pre-dist, that should already -- have completed successfully before this is invoked. doDist :: [DarcsFlag] -> AbsolutePath -> AbsolutePath -> FilePath -> IO () doDist opts tempdir ddir resultfile = do setCurrentDirectory (toFilePath tempdir) let safeddir = safename $ takeFileName $ toFilePath ddir entries <- pack "." [safeddir] when (Verbose `elem` opts) $ putStr $ unlines $ map entryPath entries writeFile resultfile $ compress $ write entries when (Quiet `notElem` opts) $ putStrLn $ "Created dist as " ++ resultfile where safename n@(c:_) | isAlphaNum c = n safename n = "./" ++ n getDistName :: FilePath -> [String] -> FilePath getDistName _ (dn:_) = dn getDistName currentDirectory _ = takeFileName currentDirectory doFastZip :: [DarcsFlag] -> IO () doFastZip opts = do currentdir <- getCurrentDirectory let distname = getDistName currentdir [x | DistName x <- opts] let resultfile = currentdir </> distname ++ ".zip" doFastZip' opts currentdir (writeFile resultfile) when (Quiet `notElem` opts) $ putStrLn $ "Created " ++ resultfile doFastZip' :: [DarcsFlag] -- ^ Flags/options -> FilePath -- ^ The path to the repository -> (BL.ByteString -> IO a) -- ^ An action to perform on the archive contents -> IO a doFastZip' opts path act = withRepositoryDirectory (useCache opts) path $ RepoJob $ \(Repo _ _ _ c) -> do when (SetScriptsExecutable `elem` opts) $ putStrLn "WARNING: Zip archives cannot store executable flag." let distname = getDistName path [x | DistName x <- opts] i <- fetchFilePS (path </> darcsdir </> "hashed_inventory") Uncachable pristine <- pathsAndContents (distname ++ "/") c (inv2pris i) epochtime <- toSeconds `fmap` getCurrentTime let entries = [ toEntry filepath epochtime (toLazy contents) | (filepath,contents) <- pristine ] let archive = foldr addEntryToArchive emptyArchive entries act (fromArchive archive) toLazy :: B.ByteString -> BL.ByteString toLazy bs = BL.fromChunks [bs]
DavidAlphaFox/darcs
src/Darcs/UI/Commands/Dist.hs
gpl-2.0
9,083
0
23
2,191
1,965
1,082
883
182
5
-- Copyright (c) 2015 Nicola Bonelli <nicola@pfq.io> -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -- {-# LANGUAGE DeriveDataTypeable #-} module Main where import Data.Semigroup import Data.List import Data.List.Split import Data.Maybe import Data.Char import Control.Applicative import Control.Monad import Control.Monad.State import Control.Concurrent (threadDelay) import Data.Data import System.Console.ANSI import System.Console.CmdArgs import System.Directory (getHomeDirectory) import System.IO.Unsafe import System.IO.Error import System.Process import System.Exit import System.FilePath import System.Posix.Signals import System.Posix.Types proc_cpuinfo, proc_modules :: String proc_cpuinfo = "/proc/cpuinfo" proc_modules = "/proc/modules" bold = setSGRCode [SetConsoleIntensity BoldIntensity] reset = setSGRCode [] version = "4.4.3" data YesNo = Yes | No | Unspec deriving (Show, Read, Eq) newtype OptString = OptString { getOptString :: String } deriving (Show, Read, Eq) newtype OptList a = OptList { getOptList :: [a] } deriving (Show, Read, Eq) instance Semigroup OptString where a <> OptString "" = a _ <> b = b instance Semigroup (OptList a) where a <> OptList [] = a _ <> b = b data Device = Device { devname :: String , devspeed :: Maybe Int , channels :: Maybe Int , flowctrl :: YesNo , ethopt :: [(String, String, Int)] } deriving (Show, Read, Eq) data Driver = Driver { drvmod :: String , drvopt :: [String] , instances :: Int , devices :: [Device] } deriving (Show, Read, Eq) data Config = Config { pfq_module :: String , pfq_options :: [String] , exclude_core :: [Int] , irq_affinity :: [String] , cpu_governor :: String , drivers :: [Driver] } deriving (Show, Read, Eq) instance Semigroup Config where (Config mod1 opt1 excl1 algo1 gov1 drvs1) <> (Config mod2 opt2 excl2 algo2 gov2 drvs2) = Config { pfq_module = getOptString $ OptString mod1 <> OptString mod2, pfq_options = getOptList $ OptList opt1 <> OptList opt2, exclude_core = excl1 <> excl2, irq_affinity = algo1 <> algo2, cpu_governor = getOptString $ OptString gov1 <> OptString gov2, drivers = drvs1 <> drvs2 } data Options = Options { config :: Maybe String , kmodule :: String , algorithm :: String , governor :: String , first_core :: Int , exclude :: [Int] , queues :: Maybe Int , others :: [String] } deriving (Show, Read, Data, Typeable) options :: Mode (CmdArgs Options) options = cmdArgsMode $ Options { config = Nothing &= typ "FILE" &= help "Specify config file (default ~/.pfq.conf)" , kmodule = "" &= help "Override the kmodule specified in config file" , queues = Nothing &= help "Specify hardware channels (i.e. Intel RSS)" , algorithm = "" &= help "Irq affinity algorithm: naive, round-robin, even, odd, all-in:id, comb:id" , governor = "" &= help "Set cpufreq governor" , first_core = 0 &= typ "NUM" &= help "First core used for irq affinity" , exclude = [] &= typ "CORE" &= help "Exclude core from irq affinity" , others = [] &= args } &= summary ("pfq-load " ++ version) &= program "pfq-load" ------------------------------------------------------------------------------------------- main :: IO () main = do -- load options... home <- getHomeDirectory opt <- cmdArgsRun options conf <- (<> mkConfig opt) <$> loadConfig (fromMaybe (home </> ".pfq.conf") (config opt)) opt pmod <- getProcModules core <- getNumberOfPhyCores bal <- getProcessID "irqbalance" frd <- getProcessID "cpufreqd" -- check queues when (maybe False (> core) (queues opt)) $ error "queues number too big!" -- unload pfq and drivers that depend on it... evalStateT (unloadModule "pfq") pmod -- check irqbalance deaemon unless (null bal) $ do putStrBoldLn $ "Irqbalance daemon detected @pid " ++ show bal ++ ". Sending SIGKILL..." forM_ bal $ signalProcess sigKILL -- check cpufreqd deaemon unless (null frd) $ do putStrBoldLn $ "Cpufreqd daemon detected @pid " ++ show frd ++ ". Sending SIGKILL..." forM_ frd $ signalProcess sigKILL -- set cpufreq governor... runSystem ("/usr/bin/cpufreq-set -g " ++ cpu_governor conf) ("*** cpfreq-set error! Make sure you have cpufrequtils installed! *** ", True) -- load PFQ... if null (pfq_module conf) then loadModule ProbeMod "pfq" (pfq_options conf) else loadModule InsertMod (pfq_module conf) (pfq_options conf) -- update current loaded proc/modules pmod2 <- getProcModules -- unload drivers... unless (null (drivers conf)) $ do putStrBoldLn "Unloading vanilla/standard drivers..." evalStateT (mapM_ (unloadModule . takeBaseName . drvmod) (drivers conf)) pmod2 -- load and configure device drivers... forM_ (drivers conf) $ \drv -> do let rss = maybe [] (mkRssOption (drvmod drv) (instances drv)) (queues opt) loadModule InsertMod (drvmod drv) (drvopt drv ++ rss) threadDelay 1000000 mapM_ (setupDevice (queues opt)) (devices drv) -- set interrupt affinity... putStrBoldLn "Setting irq affinity..." setupIRQAffinity (first_core opt) (exclude_core conf) (irq_affinity conf) (getDevices conf) putStrBoldLn "PFQ ready." mkRssOption :: String -> Int -> Int -> [String] mkRssOption driver numdev queues = case () of _ | "ixgbe.ko" `isSuffixOf` driver -> [ "RSS=" ++ intercalate "," (replicate numdev (show queues)) ] | "igb.ko" `isSuffixOf` driver -> [ "RSS=" ++ intercalate "," (replicate numdev (show queues)) ] | otherwise -> [] mkConfig :: Options -> Config mkConfig Options { config = _ , kmodule = mod , algorithm = algo , exclude = excl , governor = gov , others = opt } = Config { pfq_module = mod , pfq_options = opt , exclude_core = excl , irq_affinity = [algo | not (null algo)] , cpu_governor = gov , drivers = [] } notCommentLine :: String -> Bool notCommentLine = (not . ("#" `isPrefixOf`)) . (dropWhile isSpace) loadConfig :: FilePath -> Options -> IO Config loadConfig conf opt = catchIOError (liftM (read . unlines . filter notCommentLine . lines) (readFile conf)) (\_ -> return $ mkConfig opt) getNumberOfPhyCores :: IO Int getNumberOfPhyCores = readFile proc_cpuinfo >>= \file -> return $ (length . filter (isInfixOf "processor") . lines) file type ProcModules = [ (String, [String]) ] type ModStateT = StateT ProcModules getProcModules :: IO ProcModules getProcModules = readFile proc_modules >>= \file -> return $ map (\l -> let ts = words l in (head ts, filter (\s -> (not . null) s && s /= "-") $ splitOn "," (ts !! 3))) $ lines file rmmodFromProcMOdules :: String -> ProcModules -> ProcModules rmmodFromProcMOdules name = filter (\(m,ds) -> m /= name ) getProcessID :: String -> IO [ProcessID] getProcessID name = liftM (map read . words) $ catchIOError (readProcess "/bin/pidof" [name] "") (\_-> return []) moduleDependencies :: String -> ProcModules -> [String] moduleDependencies name = concatMap (\(m,ds) -> if m == name then ds else []) unloadModule :: String -> ModStateT IO () unloadModule name = do proc_mods <- get mapM_ unloadModule (moduleDependencies name proc_mods) when (isModuleLoaded name proc_mods) $ do liftIO $ rmmod name put $ rmmodFromProcMOdules name proc_mods where rmmod name = do putStrBoldLn $ "Unloading " ++ name ++ "..." runSystem ("/sbin/rmmod " ++ name) ("rmmod " ++ name ++ " error.", True) isModuleLoaded name = any (\(mod,_) -> mod == name) data LoadMode = InsertMod | ProbeMod deriving Eq loadModule :: LoadMode -> String -> [String] -> IO () loadModule mode name opts = do putStrBoldLn $ "Loading " ++ name ++ "..." runSystem (tool ++ " " ++ name ++ " " ++ unwords opts) ("insmod " ++ name ++ " error.", True) where tool = if mode == InsertMod then "/sbin/insmod" else "/sbin/modprobe" setupDevice :: Maybe Int -> Device -> IO () setupDevice queues (Device dev speed channels fctrl opts) = do putStrBoldLn $ "Activating " ++ dev ++ "..." runSystem ("/sbin/ifconfig " ++ dev ++ " up") ("ifconfig error!", True) case fctrl of No -> do putStrBoldLn $ "Disabling flow control for " ++ dev ++ "..." runSystem ("/sbin/ethtool -A " ++ dev ++ " autoneg off rx off tx off") ("ethtool: flowctrl error!", False) Yes -> do putStrBoldLn $ "Enabling flow control for " ++ dev ++ "..." runSystem ("/sbin/ethtool -A " ++ dev ++ " autoneg on rx on tx on") ("ethtool: flowctrl error!", False) Unspec -> return () when (isJust speed) $ do let s = fromJust speed putStrBoldLn $ "Setting speed (" ++ show s ++ ") for " ++ dev ++ "..." runSystem ("/sbin/ethtool -s " ++ dev ++ " speed " ++ show s ++ " duplex full") ("ethtool: set speed error!", False) when (isJust queues || isJust channels) $ do let c = fromJust (queues <|> channels) putStrBoldLn $ "Setting channels to " ++ show c ++ "..." runSystem ("/sbin/ethtool -L " ++ dev ++ " combined " ++ show c) ("", False) forM_ opts $ \(opt, arg, value) -> runSystem ("/sbin/ethtool " ++ opt ++ " " ++ dev ++ " " ++ arg ++ " " ++ show value) ("ethtool:" ++ opt ++ " error!", True) getDevices :: Config -> [String] getDevices conf = map devname (concatMap devices (drivers conf)) setupIRQAffinity :: Int -> [Int] -> [String] -> [String] -> IO () setupIRQAffinity fc excl algs devs = do let excl_opt = unwords (map (\n -> " -e " ++ show n) excl) let affinity = zip algs (tails devs) unless (null affinity) $ forM_ affinity $ \(alg, devs') -> runSystem ("/root/.cabal/bin/irq-affinity -f " ++ show fc ++ " " ++ excl_opt ++ " -a " ++ alg ++ " -m TxRx " ++ unwords devs') ("irq-affinity error!", True) runSystem :: String -> (String,Bool) -> IO () runSystem cmd (errmsg,term) = do putStrLn $ "-> " ++ cmd system cmd >>= \ec -> when (ec /= ExitSuccess) $ (if term then error else putStrLn) errmsg putStrBoldLn :: String -> IO () putStrBoldLn msg = putStrLn $ bold ++ msg ++ reset
Mr-Click/PFQ
user/pfq-load/pfq-load.hs
gpl-2.0
11,484
0
23
3,011
3,354
1,752
1,602
227
3