code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
data DT = DT Integer deriving Show newtype NT = NT Integer deriving Show checkDT :: DT -> String checkDT (DT _) = "OK!" checkNT :: NT -> String checkNT (NT _) = "OK!"
YoshikuniJujo/funpaala
samples/26_type_class/newtypeDiff.hs
Haskell
bsd-3-clause
170
{-# LANGUAGE BangPatterns, MultiParamTypeClasses #-} {-# OPTIONS -fno-warn-orphans #-} module Data.Digest.Groestl384 ( groestl384, Groestl384Digest (..), GroestlCtx, Hash(..), hash, hash', printAsHex ) where import Data.Int (Int64) import Data.Word (Word64) import qualified Data.ByteString.Lazy as L (ByteString) import Data.Vector.Unboxed (Vector, fromList) import Control.Monad (foldM, liftM) import Control.Monad.ST (runST) import Crypto.Classes import Data.Tagged import Data.Serialize import Prelude hiding (truncate) import Data.Digest.GroestlMutable groestl384 :: Int64 -> L.ByteString -> L.ByteString groestl384 dataBitLen | dataBitLen < 0 = error "The data length can not be less than 0" | otherwise = truncate G384 . outputTransform 1024 . compress . parse where parse = parseMessage dataBitLen 1024 compress xs = runST $ foldM (fM 1024) h0_384 xs ---------------------- Crypto-api instance ------------- instance Hash GroestlCtx Groestl384Digest where outputLength = Tagged 384 blockLength = Tagged 1024 initialCtx = groestlInit G384 1024 h0_384 updateCtx = groestlUpdate finalize ctx = Digest . groestlFinalize ctx data Groestl384Digest = Digest L.ByteString deriving (Eq,Ord) instance Show Groestl384Digest where show (Digest h) = printAsHex h instance Serialize Groestl384Digest where put (Digest bs) = put bs get = liftM Digest get ------------------------------------------- Initial vector ------------------------------------- h0_384 :: Vector Word64 h0_384 = fromList [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0x0180]
hakoja/SHA3
Data/Digest/Groestl384.hs
Haskell
bsd-3-clause
1,720
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} -- | 'Lucid.HtmlT' inspired monad for creating 'ReactElement's module Glazier.React.Markup ( Markup , ReactMarkup(..) , BranchParam(..) , LeafParam(..) , fromMarkup , toElements , toElement , elementMarkup , textMarkup , leafMarkup , branchMarkup ) where import Control.Monad.Environ import qualified Data.DList as DL import Glazier.React.ReactElement import JS.Data type Markup = DL.DList ReactMarkup -- | The parameters required to create a branch ReactElement with children data BranchParam = BranchParam JSVal [(JSString, JSVal)] [ReactMarkup] -- | The parameters required to create a leaf ReactElement (no children) data LeafParam = LeafParam JSVal [(JSString, JSVal)] data ReactMarkup = ElementMarkup ReactElement | TextMarkup JSString | BranchMarkup BranchParam | LeafMarkup LeafParam -- | Create 'ReactElement's from a 'ReactMarkup' fromMarkup :: ReactMarkup -> IO ReactElement fromMarkup (BranchMarkup (BranchParam n props xs)) = do xs' <- sequenceA $ fromMarkup <$> xs mkBranchElement n props xs' fromMarkup (LeafMarkup (LeafParam n props)) = mkLeafElement n props fromMarkup (TextMarkup str) = pure $ rawTextElement str fromMarkup (ElementMarkup e) = pure e ------------------------------------------------- -- | Convert the ReactMlt to [ReactElement] toElements :: [ReactMarkup] -> IO [ReactElement] toElements xs = sequenceA $ fromMarkup <$> xs -- | 'Glazier.React.ReactDOM.renderDOM' only allows a single top most element. -- Provide a handly function to wrap a list of ReactElements inside a 'div' if required. -- If there is only one element in the list, then nothing is changed. toElement :: [ReactMarkup] -> IO ReactElement toElement xs = toElements xs >>= mkCombinedElements ------------------------------------------------- -- | To use an exisitng ReactElement elementMarkup :: MonadPut' Markup m => ReactElement -> m () elementMarkup e = modifyEnv' @Markup (`DL.snoc` ElementMarkup e) -- | For raw text content textMarkup :: MonadPut' Markup m => JSString -> m () textMarkup n = modifyEnv' @Markup (`DL.snoc` TextMarkup n) -- | For the contentless elements: eg 'br_'. -- Memonic: lf for leaf. -- Duplicate listeners with the same key will be combined, but it is a silent error -- if the same key is used across listeners and props. -- "If an attribute/prop is duplicated the last one defined wins." -- https://www.reactenlightenment.com/react-nodes/4.4.html leafMarkup :: MonadPut' Markup m => JSVal -> [(JSString, JSVal)] -> m () leafMarkup n props = modifyEnv' @Markup (`DL.snoc` LeafMarkup (LeafParam n props)) -- | For the contentful elements: eg 'div_'. -- Memonic: bh for branch. -- Duplicate listeners with the same key will be combined, but it is a silent error -- if the same key is used across listeners and props. -- "If an attribute/prop is duplicated the last one defined wins." -- https://www.reactenlightenment.com/react-nodes/4.4.html branchMarkup :: MonadPut' Markup m => JSVal -> [(JSString, JSVal)] -> m a -> m a branchMarkup n props child = do -- save state s <- getEnv' @Markup -- run children with mempty putEnv' @Markup mempty a <- child child' <- getEnv' @Markup -- restore state putEnv' @Markup s -- append the children markup modifyEnv' @Markup (`DL.snoc` BranchMarkup (BranchParam n props (DL.toList child'))) pure a -- -- Given a mapping function, apply it to children of the markup -- modifyMarkup :: MonadState (DL.DList ReactMarkup) m -- => (DL.DList ReactMarkup -> DL.DList ReactMarkup) -- -> m a -> m a -- modifyMarkup f = withMarkup (\childs' ms -> ms `DL.append` f childs') -- -- Given a mapping function, apply it to all child BranchMarkup or LeafMarkup (if possible) -- -- Does not recurse into decendants. -- overSurfaceProperties :: -- ((DL.DList JE.Property) -> (DL.DList JE.Property)) -- -> (DL.DList ReactMarkup -> DL.DList ReactMarkup) -- overSurfaceProperties f childs = DL.fromList $ case DL.toList childs of -- LeafMarkup (LeafParam j ps) : bs -> -- LeafMarkup (LeafParam j (f ps)) : bs -- BranchMarkup (BranchParam j ps as) : bs -> -- BranchMarkup (BranchParam j (f ps) as) : bs -- bs -> bs -- -- Given a mapping function, apply it to all child BranchMarkup or LeafMarkup (if possible) -- -- Recurse into decendants. -- overAllProperties :: -- ((DL.DList JE.Property) -> (DL.DList JE.Property)) -- -> (DL.DList ReactMarkup -> DL.DList ReactMarkup) -- overAllProperties f childs = DL.fromList $ case DL.toList childs of -- LeafMarkup (LeafParam j ps) : bs -> -- LeafMarkup (LeafParam j (f ps)) : bs -- BranchMarkup (BranchParam j ps as) : bs -> -- BranchMarkup (BranchParam j (f ps) (overAllProperties f as)) : bs -- bs -> bs
louispan/glazier-react
src/Glazier/React/Markup.hs
Haskell
bsd-3-clause
5,135
{-| Haskelm test suite For the moment, just contains some basic tests This file also serves as an example of how to translate Elm from different sources -} {-# LANGUAGE TemplateHaskell, QuasiQuotes, MultiWayIf #-} import Language.Elm.TH import Data.List (intercalate) import Control.Monad -- | Similarly, we can load a module from a file elmString = $(translateToElm (defaultOptions {moduleName="Foo"}) ("tests/files/module1.hs" ) ) -- | We can now access the elm strings we declared main = do putStrLn "Generated elm strings:" mapM_ putStrLn [elmString] writeFile "src/Test.elm" elmString return ()
JoeyEremondi/haskelm-old
tests/Main.hs
Haskell
bsd-3-clause
622
-- | -- Module: Data.Float.BinString -- License: BSD-style -- Maintainer: me@lelf.lu -- -- -- This module contains functions for formatting and parsing floating point -- values as C99 printf/scanf functions with format string @%a@ do. -- -- The format is [-]0x/h.hhhhh/p±/ddd/, where /h.hhhhh/ is significand -- as a hexadecimal floating-point number and /±ddd/ is exponent as a -- decimal number. Significand has as many digits as needed to exactly -- represent the value, fractional part may be ommitted. -- -- Infinity and NaN values are represented as @±inf@ and @nan@ accordingly. -- -- For example, @(π ∷ Double) = 0x1.921fb54442d18p+1@ (/exactly/). -- -- This assertion holds (assuming NaN ≡ NaN) -- -- prop> ∀x. Just x ≡ readFloat (showFloat x) -- -- Floating point radix is assumed to be 2. {-# LANGUAGE Trustworthy #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} module Data.Float.BinString (readFloat,showFloat,floatBuilder, readFloatStr,showFloatStr) where import qualified Numeric as Numeric import Data.List.Split import Data.Char import Data.Text (Text) import qualified Data.Text as T import Data.Text.Lazy (toStrict) import Data.Text.Lazy.Builder import Data.Text.Lazy.Builder.Int (decimal) import Data.Attoparsec.Text hiding (take,signed,decimal) import Control.Applicative ((<**>),(<|>),many) import Data.Monoid --- Printing -- | Format a value. Will provide enough digits to reconstruct the value exactly. showFloat :: RealFloat a => a -> Text showFloat = toStrict . toLazyText . floatBuilder -- | A 'Builder' for a value floatBuilder :: RealFloat a => a -> Builder floatBuilder x | isNaN x = fromText "nan" | isInfinite x = sign <> fromText "inf" | otherwise = sign <> fromText "0x" <> singleton (intToDigit d0) <> fromString [ '.' | length digs > 1 ] <> fromString [ intToDigit x | x <- dtail] <> singleton 'p' <> singleton (if ep>=0 then '+' else '-') <> decimal (abs ep) where (digs,ep) = floatToHexDigits $ abs x (d0:dtail) = digs sign = fromString [ '-' | x < 0 ] -- | Given a number, returns list of its mantissa digits and the -- exponent as a pair. E.g. as π = 0x1.921fb54442d18p+1 -- -- >>> floatToHexDigits pi -- ([1,9,2,1,15,11,5,4,4,4,2,13,1,8],1) floatToHexDigits :: RealFloat a => a -> ([Int], Int) floatToHexDigits x = (,ep') $ d0 : map to16 chunked where ((d0:ds),ep) = Numeric.floatToDigits 2 x ep' | x == 0 = ep | otherwise = ep-1 chunked = map (take 4 . (++ repeat 0)) . chunksOf 4 $ ds to16 = foldl1 (\a b -> 2*a+b) {-# DEPRECATED showFloatStr "use showFloat" #-} showFloatStr :: RealFloat a => a -> String showFloatStr = T.unpack . showFloat --- Parsing data Sign = Pos | Neg deriving Show data ParsedFloat = Inf Sign | NaN | Float Sign String Sign String deriving Show signed Pos x = x signed Neg x = -x -- | Parse a value from 'Text'. readFloat :: RealFloat a => Text -> Maybe a readFloat s = either (const Nothing) (Just . decode) pd where pd = parseOnly parser s parser = do r <- try parserPeculiar <|> parserNormal endOfInput return r decode :: (Eq a, Fractional a) => ParsedFloat -> a decode (Float sgn digs exp_sgn exp_digs) = signif * 2^^expon where signif = signed sgn v / 16^^(length digs - 1) [(v,_)] = Numeric.readHex digs expon = signed exp_sgn $ read exp_digs decode NaN = 0/0 decode (Inf sgn) = signed sgn $ 1/0 -- | Parse nans and infs parserPeculiar = do sgn <- optSign (string "nan" >> return NaN) <|> (string "inf" >> return (Inf sgn)) parserPeculiar' = optSign <**> ((string "nan" >> return (const NaN)) <|> (string "inf" >> return Inf)) -- | Parse vanilla numbers parserNormal = do positive <- optSign string "0x" digit0 <- hexDigit restDigits <- option [] $ char '.' >> many hexDigit char 'p' positiveExp <- optSign expDigits <- many digit return $ Float positive (digit0:restDigits) positiveExp expDigits hexDigit = satisfy isHexDigit optSign = option Pos $ (char '+' >> return Pos) <|> (char '-' >> return Neg) {-# DEPRECATED readFloatStr "use readFloat" #-} readFloatStr :: RealFloat a => String -> Maybe a readFloatStr = readFloat . T.pack
llelf/float-binstring
Data/Float/BinString.hs
Haskell
bsd-3-clause
4,694
{-# LANGUAGE CPP, BangPatterns #-} {-#LANGUAGE RankNTypes, OverloadedStrings, ScopedTypeVariables #-} -- | This library emulates "Data.ByteString.Lazy.Char8" but includes a monadic element -- and thus at certain points uses a `Stream`/`FreeT` type in place of lists. -- See the documentation for @Data.ByteString.Streaming@ and the examples of -- of use to implement simple shell operations <https://gist.github.com/michaelt/6c6843e6dd8030e95d58 here>. Examples of use -- with @http-client@, @attoparsec@, @aeson@, @zlib@ etc. can be found in the -- 'streaming-utils' library. module Data.ByteString.Streaming.Char8 ( -- * The @ByteString@ type ByteString -- * Introducing and eliminating 'ByteString's , empty -- empty :: ByteString m () , pack -- pack :: Monad m => String -> ByteString m () , unpack , string , unlines , unwords , singleton -- singleton :: Monad m => Char -> ByteString m () , fromChunks -- fromChunks :: Monad m => Stream (Of ByteString) m r -> ByteString m r , fromLazy -- fromLazy :: Monad m => ByteString -> ByteString m () , fromStrict -- fromStrict :: ByteString -> ByteString m () , toChunks -- toChunks :: Monad m => ByteString m r -> Stream (Of ByteString) m r , toLazy -- toLazy :: Monad m => ByteString m () -> m ByteString , toLazy_ , toStrict -- toStrict :: Monad m => ByteString m () -> m ByteString , toStrict_ , effects , copy , drained , mwrap -- * Transforming ByteStrings , map -- map :: Monad m => (Char -> Char) -> ByteString m r -> ByteString m r , intercalate -- intercalate :: Monad m => ByteString m () -> Stream (ByteString m) m r -> ByteString m r , intersperse -- intersperse :: Monad m => Char -> ByteString m r -> ByteString m r -- * Basic interface , cons -- cons :: Monad m => Char -> ByteString m r -> ByteString m r , cons' -- cons' :: Char -> ByteString m r -> ByteString m r , snoc , append -- append :: Monad m => ByteString m r -> ByteString m s -> ByteString m s , filter -- filter :: (Char -> Bool) -> ByteString m r -> ByteString m r , head -- head :: Monad m => ByteString m r -> m Char , head_ -- head' :: Monad m => ByteString m r -> m (Of Char r) , last -- last :: Monad m => ByteString m r -> m Char , last_ -- last' :: Monad m => ByteString m r -> m (Of Char r) , null -- null :: Monad m => ByteString m r -> m Bool , null_ , testNull , nulls -- null' :: Monad m => ByteString m r -> m (Of Bool r) , uncons -- uncons :: Monad m => ByteString m r -> m (Either r (Char, ByteString m r)) , nextChar -- * Substrings -- ** Breaking strings , break -- break :: Monad m => (Char -> Bool) -> ByteString m r -> ByteString m (ByteString m r) , drop -- drop :: Monad m => GHC.Int.Int64 -> ByteString m r -> ByteString m r , dropWhile , group -- group :: Monad m => ByteString m r -> Stream (ByteString m) m r , groupBy , span -- span :: Monad m => (Char -> Bool) -> ByteString m r -> ByteString m (ByteString m r) , splitAt -- splitAt :: Monad m => GHC.Int.Int64 -> ByteString m r -> ByteString m (ByteString m r) , splitWith -- splitWith :: Monad m => (Char -> Bool) -> ByteString m r -> Stream (ByteString m) m r , take -- take :: Monad m => GHC.Int.Int64 -> ByteString m r -> ByteString m () , takeWhile -- takeWhile :: (Char -> Bool) -> ByteString m r -> ByteString m () -- ** Breaking into many substrings , split -- split :: Monad m => Char -> ByteString m r -> Stream (ByteString m) m r , lines , words , denull -- ** Special folds , concat -- concat :: Monad m => Stream (ByteString m) m r -> ByteString m r -- * Builders , toStreamingByteString , toStreamingByteStringWith , toBuilder , concatBuilders -- * Building ByteStrings -- ** Infinite ByteStrings , repeat -- repeat :: Char -> ByteString m () , iterate -- iterate :: (Char -> Char) -> Char -> ByteString m () , cycle -- cycle :: Monad m => ByteString m r -> ByteString m s -- ** Unfolding ByteStrings , unfoldr -- unfoldr :: (a -> Maybe (Char, a)) -> a -> ByteString m () , unfoldM -- unfold :: (a -> Either r (Char, a)) -> a -> ByteString m r , reread -- * Folds, including support for `Control.Foldl` -- , foldr -- foldr :: Monad m => (Char -> a -> a) -> a -> ByteString m () -> m a , fold -- fold :: Monad m => (x -> Char -> x) -> x -> (x -> b) -> ByteString m () -> m b , fold_ -- fold' :: Monad m => (x -> Char -> x) -> x -> (x -> b) -> ByteString m r -> m (b, r) , length , length_ , count , count_ , readInt -- * I\/O with 'ByteString's -- ** Standard input and output , getContents -- getContents :: ByteString IO () , stdin -- stdin :: ByteString IO () , stdout -- stdout :: ByteString IO r -> IO r , interact -- interact :: (ByteString IO () -> ByteString IO r) -> IO r , putStr , putStrLn -- ** Files , readFile -- readFile :: FilePath -> ByteString IO () , writeFile -- writeFile :: FilePath -> ByteString IO r -> IO r , appendFile -- appendFile :: FilePath -> ByteString IO r -> IO r -- ** I\/O with Handles , fromHandle -- fromHandle :: Handle -> ByteString IO () , toHandle -- toHandle :: Handle -> ByteString IO r -> IO r , hGet -- hGet :: Handle -> Int -> ByteString IO () , hGetContents -- hGetContents :: Handle -> ByteString IO () , hGetContentsN -- hGetContentsN :: Int -> Handle -> ByteString IO () , hGetN -- hGetN :: Int -> Handle -> Int -> ByteString IO () , hGetNonBlocking -- hGetNonBlocking :: Handle -> Int -> ByteString IO () , hGetNonBlockingN -- hGetNonBlockingN :: Int -> Handle -> Int -> ByteString IO () , hPut -- hPut :: Handle -> ByteString IO r -> IO r -- , hPutNonBlocking -- hPutNonBlocking :: Handle -> ByteString IO r -> ByteString IO r -- * Simple chunkwise operations , unconsChunk , nextChunk , chunk , foldrChunks , foldlChunks , chunkFold , chunkFoldM , chunkMap , chunkMapM , chunkMapM_ -- * Etc. -- , zipWithStream -- zipWithStream :: Monad m => (forall x. a -> ByteString m x -> ByteString m x) -> [a] -> Stream (ByteString m) m r -> Stream (ByteString m) m r , distribute -- distribute :: ByteString (t m) a -> t (ByteString m) a , materialize , dematerialize ) where import Prelude hiding (reverse,head,tail,last,init,null,length,map,words, lines,foldl,foldr, unwords, unlines ,concat,any,take,drop,splitAt,takeWhile,dropWhile,span,break,elem,filter,maximum ,minimum,all,concatMap,foldl1,foldr1,scanl, scanl1, scanr, scanr1 ,repeat, cycle, interact, iterate,readFile,writeFile,appendFile,replicate ,getContents,getLine,putStr,putStrLn ,zip,zipWith,unzip,notElem) import qualified Prelude import qualified Data.ByteString as B import qualified Data.ByteString.Internal as B import Data.ByteString.Internal (c2w,w2c) import qualified Data.ByteString.Unsafe as B import qualified Data.ByteString.Char8 as Char8 import Streaming hiding (concats, unfold, distribute, mwrap) import Streaming.Internal (Stream (..)) import qualified Streaming.Prelude as S import qualified Streaming as S import qualified Data.ByteString.Streaming as R import Data.ByteString.Streaming.Internal import Data.ByteString.Streaming (fromLazy, toLazy, toLazy_, nextChunk, unconsChunk, fromChunks, toChunks, fromStrict, toStrict, toStrict_, concat, distribute, effects, drained, mwrap, toStreamingByteStringWith, toStreamingByteString, toBuilder, concatBuilders, empty, null, nulls, null_, testNull, length, length_, append, cycle, take, drop, splitAt, intercalate, group, denull, appendFile, stdout, stdin, fromHandle, toHandle, hGetContents, hGetContentsN, hGet, hGetN, hPut, getContents, hGetNonBlocking, hGetNonBlockingN, readFile, writeFile, interact, chunkFold, chunkFoldM, chunkMap, chunkMapM) -- hPutNonBlocking, import Control.Monad (liftM) import System.IO (Handle,openBinaryFile,IOMode(..) ,hClose) import qualified System.IO as IO import System.IO.Unsafe import Control.Exception (bracket) import Data.Char (isDigit) import Foreign.ForeignPtr (withForeignPtr) import Foreign.Ptr import Foreign.Storable import Data.Functor.Compose import Data.Functor.Sum import qualified Data.List as L unpack :: Monad m => ByteString m r -> Stream (Of Char) m r unpack bs = case bs of Empty r -> Return r Go m -> Effect (liftM unpack m) Chunk c cs -> unpackAppendCharsLazy c (unpack cs) where unpackAppendCharsLazy :: B.ByteString -> Stream (Of Char) m r -> Stream (Of Char) m r unpackAppendCharsLazy (B.PS fp off len) xs | len <= 100 = unpackAppendCharsStrict (B.PS fp off len) xs | otherwise = unpackAppendCharsStrict (B.PS fp off 100) remainder where remainder = unpackAppendCharsLazy (B.PS fp (off+100) (len-100)) xs unpackAppendCharsStrict :: B.ByteString -> Stream (Of Char) m r -> Stream (Of Char) m r unpackAppendCharsStrict (B.PS fp off len) xs = inlinePerformIO $ withForeignPtr fp $ \base -> do loop (base `plusPtr` (off-1)) (base `plusPtr` (off-1+len)) xs where loop !sentinal !p acc | p == sentinal = return acc | otherwise = do x <- peek p loop sentinal (p `plusPtr` (-1)) (Step (B.w2c x :> acc)) {-# INLINABLE unpack#-} -- | /O(n)/ Convert a stream of separate characters into a packed byte stream. pack :: Monad m => Stream (Of Char) m r -> ByteString m r pack = fromChunks . mapped (liftM (\(str :> r) -> Char8.pack str :> r) . S.toList) . chunksOf 32 {-# INLINABLE pack #-} -- | /O(1)/ Cons a 'Char' onto a byte stream. cons :: Monad m => Char -> ByteString m r -> ByteString m r cons c = R.cons (c2w c) {-# INLINE cons #-} -- | /O(1)/ Yield a 'Char' as a minimal 'ByteString' singleton :: Monad m => Char -> ByteString m () singleton = R.singleton . c2w {-# INLINE singleton #-} -- | /O(1)/ Unlike 'cons', 'cons\'' is -- strict in the ByteString that we are consing onto. More precisely, it forces -- the head and the first chunk. It does this because, for space efficiency, it -- may coalesce the new byte onto the first \'chunk\' rather than starting a -- new \'chunk\'. -- -- So that means you can't use a lazy recursive contruction like this: -- -- > let xs = cons\' c xs in xs -- -- You can however use 'cons', as well as 'repeat' and 'cycle', to build -- infinite lazy ByteStrings. -- cons' :: Char -> ByteString m r -> ByteString m r cons' c (Chunk bs bss) | B.length bs < 16 = Chunk (B.cons (c2w c) bs) bss cons' c cs = Chunk (B.singleton (c2w c)) cs {-# INLINE cons' #-} -- -- | /O(n\/c)/ Append a byte to the end of a 'ByteString' snoc :: Monad m => ByteString m r -> Char -> ByteString m r snoc cs = R.snoc cs . c2w {-# INLINE snoc #-} -- | /O(1)/ Extract the first element of a ByteString, which must be non-empty. head_ :: Monad m => ByteString m r -> m Char head_ = liftM (w2c) . R.head_ {-# INLINE head_ #-} -- | /O(1)/ Extract the first element of a ByteString, which may be non-empty head :: Monad m => ByteString m r -> m (Of (Maybe Char) r) head = liftM (\(m:>r) -> fmap w2c m :> r) . R.head {-# INLINE head #-} -- | /O(n\/c)/ Extract the last element of a ByteString, which must be finite -- and non-empty. last_ :: Monad m => ByteString m r -> m Char last_ = liftM (w2c) . R.last_ {-# INLINE last_ #-} last :: Monad m => ByteString m r -> m (Of (Maybe Char) r) last = liftM (\(m:>r) -> fmap (w2c) m :> r) . R.last {-# INLINE last #-} groupBy :: Monad m => (Char -> Char -> Bool) -> ByteString m r -> Stream (ByteString m) m r groupBy rel = R.groupBy (\w w' -> rel (w2c w) (w2c w')) {-#INLINE groupBy #-} -- | /O(1)/ Extract the head and tail of a ByteString, returning Nothing -- if it is empty. uncons :: Monad m => ByteString m r -> m (Either r (Char, ByteString m r)) uncons (Empty r) = return (Left r) uncons (Chunk c cs) = return $ Right (w2c (B.unsafeHead c) , if B.length c == 1 then cs else Chunk (B.unsafeTail c) cs ) uncons (Go m) = m >>= uncons {-# INLINABLE uncons #-} -- --------------------------------------------------------------------- -- Transformations -- | /O(n)/ 'map' @f xs@ is the ByteString obtained by applying @f@ to each -- element of @xs@. map :: Monad m => (Char -> Char) -> ByteString m r -> ByteString m r map f = R.map (c2w . f . w2c) {-# INLINE map #-} -- -- -- | /O(n)/ 'reverse' @xs@ returns the elements of @xs@ in reverse order. -- reverse :: ByteString -> ByteString -- reverse cs0 = rev Empty cs0 -- where rev a Empty = a -- rev a (Chunk c cs) = rev (Chunk (B.reverse c) a) cs -- {-# INLINE reverse #-} -- -- -- | The 'intersperse' function takes a 'Word8' and a 'ByteString' and -- -- \`intersperses\' that byte between the elements of the 'ByteString'. -- -- It is analogous to the intersperse function on Streams. intersperse :: Monad m => Char -> ByteString m r -> ByteString m r intersperse c = R.intersperse (c2w c) {-#INLINE intersperse #-} -- -- | The 'transpose' function transposes the rows and columns of its -- -- 'ByteString' argument. -- transpose :: [ByteString] -> [ByteString] -- transpose css = L.map (\ss -> Chunk (B.pack ss) Empty) -- (L.transpose (L.map unpack css)) -- --TODO: make this fast -- -- -- --------------------------------------------------------------------- -- -- Reducing 'ByteString's fold_ :: Monad m => (x -> Char -> x) -> x -> (x -> b) -> ByteString m () -> m b fold_ step begin done p0 = loop p0 begin where loop p !x = case p of Chunk bs bss -> loop bss $! Char8.foldl' step x bs Go m -> m >>= \p' -> loop p' x Empty _ -> return (done x) {-# INLINABLE fold_ #-} fold :: Monad m => (x -> Char -> x) -> x -> (x -> b) -> ByteString m r -> m (Of b r) fold step begin done p0 = loop p0 begin where loop p !x = case p of Chunk bs bss -> loop bss $! Char8.foldl' step x bs Go m -> m >>= \p' -> loop p' x Empty r -> return (done x :> r) {-# INLINABLE fold #-} -- --------------------------------------------------------------------- -- Unfolds and replicates -- | @'iterate' f x@ returns an infinite ByteString of repeated applications -- of @f@ to @x@: -- > iterate f x == [x, f x, f (f x), ...] iterate :: (Char -> Char) -> Char -> ByteString m r iterate f c = R.iterate (c2w . f . w2c) (c2w c) {-#INLINE iterate #-} -- | @'repeat' x@ is an infinite ByteString, with @x@ the value of every -- element. -- repeat :: Char -> ByteString m r repeat = R.repeat . c2w {-#INLINE repeat #-} -- -- | /O(n)/ @'replicate' n x@ is a ByteString of length @n@ with @x@ -- -- the value of every element. -- -- -- replicate :: Int64 -> Word8 -> ByteString -- replicate n w -- | n <= 0 = Empty -- | n < fromIntegral smallChunkSize = Chunk (B.replicate (fromIntegral n) w) Empty -- | r == 0 = cs -- preserve invariant -- | otherwise = Chunk (B.unsafeTake (fromIntegral r) c) cs -- where -- c = B.replicate smallChunkSize w -- cs = nChunks q -- (q, r) = quotRem n (fromIntegral smallChunkSize) -- nChunks 0 = Empty -- nChunks m = Chunk c (nChunks (m-1)) -- | 'cycle' ties a finite ByteString into a circular one, or equivalently, -- the infinite repetition of the original ByteString. -- -- | /O(n)/ The 'unfoldr' function is analogous to the Stream \'unfoldr\'. -- 'unfoldr' builds a ByteString from a seed value. The function takes -- the element and returns 'Nothing' if it is done producing the -- ByteString or returns 'Just' @(a,b)@, in which case, @a@ is a -- prepending to the ByteString and @b@ is used as the next element in a -- recursive call. unfoldM :: Monad m => (a -> Maybe (Char, a)) -> a -> ByteString m () unfoldM f = R.unfoldM go where go a = case f a of Nothing -> Nothing Just (c,a) -> Just (c2w c, a) {-#INLINE unfoldM #-} unfoldr :: (a -> Either r (Char, a)) -> a -> ByteString m r unfoldr step = R.unfoldr (either Left (\(c,a) -> Right (c2w c,a)) . step) {-#INLINE unfoldr #-} -- --------------------------------------------------------------------- -- | 'takeWhile', applied to a predicate @p@ and a ByteString @xs@, -- returns the longest prefix (possibly empty) of @xs@ of elements that -- satisfy @p@. takeWhile :: Monad m => (Char -> Bool) -> ByteString m r -> ByteString m () takeWhile f = R.takeWhile (f . w2c) {-#INLINE takeWhile #-} -- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@. dropWhile :: Monad m => (Char -> Bool) -> ByteString m r -> ByteString m r dropWhile f = R.dropWhile (f . w2c) {-#INLINE dropWhile #-} {- | 'break' @p@ is equivalent to @'span' ('not' . p)@. -} break :: Monad m => (Char -> Bool) -> ByteString m r -> ByteString m (ByteString m r) break f = R.break (f . w2c) {-#INLINE break #-} -- -- | 'span' @p xs@ breaks the ByteString into two segments. It is -- equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@ span :: Monad m => (Char -> Bool) -> ByteString m r -> ByteString m (ByteString m r) span p = break (not . p) {-#INLINE span #-} -- -- | /O(n)/ Splits a 'ByteString' into components delimited by -- -- separators, where the predicate returns True for a separator element. -- -- The resulting components do not contain the separators. Two adjacent -- -- separators result in an empty component in the output. eg. -- -- -- -- > splitWith (=='a') "aabbaca" == ["","","bb","c",""] -- -- > splitWith (=='a') [] == [] -- -- splitWith :: Monad m => (Char -> Bool) -> ByteString m r -> Stream (ByteString m) m r splitWith f = R.splitWith (f . w2c) {-# INLINE splitWith #-} {- | /O(n)/ Break a 'ByteString' into pieces separated by the byte argument, consuming the delimiter. I.e. > split '\n' "a\nb\nd\ne" == ["a","b","d","e"] > split 'a' "aXaXaXa" == ["","X","X","X",""] > split 'x' "x" == ["",""] and > intercalate [c] . split c == id > split == splitWith . (==) As for all splitting functions in this library, this function does not copy the substrings, it just constructs new 'ByteStrings' that are slices of the original. >>> Q.stdout $ Q.unlines $ Q.split 'n' "banana peel" ba a a peel -} split :: Monad m => Char -> ByteString m r -> Stream (ByteString m) m r split c = R.split (c2w c) {-# INLINE split #-} -- -- --------------------------------------------------------------------- -- -- Searching ByteStrings -- -- -- | /O(n)/ 'elem' is the 'ByteString' membership predicate. -- elem :: Word8 -> ByteString -> Bool -- elem w cs = case elemIndex w cs of Nothing -> False ; _ -> True -- -- -- | /O(n)/ 'notElem' is the inverse of 'elem' -- notElem :: Word8 -> ByteString -> Bool -- notElem w cs = not (elem w cs) -- | /O(n)/ 'filter', applied to a predicate and a ByteString, -- returns a ByteString containing those characters that satisfy the -- predicate. filter :: Monad m => (Char -> Bool) -> ByteString m r -> ByteString m r filter p = R.filter (p . w2c) {-# INLINE filter #-} {- | 'lines' turns a ByteString into a connected stream of ByteStrings at divide at newline characters. The resulting strings do not contain newlines. This is the genuinely streaming 'lines' which only breaks chunks, and thus never increases the use of memory. Because 'ByteString's are usually read in binary mode, with no line ending conversion, this function recognizes both @\\n@ and @\\r\\n@ endings (regardless of the current platform). -} lines :: forall m r . Monad m => ByteString m r -> Stream (ByteString m) m r lines text0 = loop1 text0 where loop1 :: ByteString m r -> Stream (ByteString m) m r loop1 text = case text of Empty r -> Return r Go m -> Effect $ liftM loop1 m Chunk c cs | B.null c -> loop1 cs | otherwise -> Step (loop2 text) loop2 :: ByteString m r -> ByteString m (Stream (ByteString m) m r) loop2 text = case text of Empty r -> Empty (Return r) Go m -> Go $ liftM loop2 m Chunk c cs -> case B.elemIndex 10 c of Nothing -> Chunk c (loop2 cs) Just i -> let prefixLength = if i >= 1 && B.unsafeIndex c (i-1) == 13 -- \r\n (dos) then i-1 else i rest = if B.length c > i+1 then Chunk (B.drop (i+1) c) cs else cs in Chunk (B.unsafeTake prefixLength c) (Empty (loop1 rest)) {-#INLINABLE lines #-} -- | The 'unlines' function restores line breaks between layers. -- -- Note that this is not a perfect inverse of 'lines': -- -- * @'lines' . 'unlines'@ can produce more strings than there were if some of -- the \"lines\" had embedded newlines. -- -- * @'unlines' . 'lines'@ will replace @\\r\\n@ with @\\n@. unlines :: Monad m => Stream (ByteString m) m r -> ByteString m r unlines = loop where loop str = case str of Return r -> Empty r Step bstr -> do st <- bstr let bs = unlines st case bs of Chunk "" (Empty r) -> Empty r Chunk "\n" (Empty r) -> bs _ -> cons' '\n' bs Effect m -> Go (liftM unlines m) {-#INLINABLE unlines #-} -- | 'words' breaks a byte stream up into a succession of byte streams -- corresponding to words, breaking Chars representing white space. This is -- the genuinely streaming 'words'. A function that returns individual -- strict bytestrings would concatenate even infinitely -- long words like @cycle "y"@ in memory. It is best for the user who -- has reflected on her materials to write `mapped toStrict . words` or the like, -- if strict bytestrings are needed. words :: Monad m => ByteString m r -> Stream (ByteString m) m r words = filtered . R.splitWith B.isSpaceWord8 where filtered stream = case stream of Return r -> Return r Effect m -> Effect (liftM filtered m) Step bs -> Effect $ bs_loop bs bs_loop bs = case bs of Empty r -> return $ filtered r Go m -> m >>= bs_loop Chunk b bs' -> if B.null b then bs_loop bs' else return $ Step $ Chunk b (fmap filtered bs') {-# INLINABLE words #-} -- | The 'unwords' function is analogous to the 'unlines' function, on words. unwords :: Monad m => Stream (ByteString m) m r -> ByteString m r unwords = intercalate (singleton ' ') {-# INLINE unwords #-} string :: String -> ByteString m () string = chunk . B.pack . Prelude.map B.c2w {-# INLINE string #-} count_ :: Monad m => Char -> ByteString m r -> m Int count_ c = R.count_ (c2w c) {-# INLINE count_ #-} count :: Monad m => Char -> ByteString m r -> m (Of Int r) count c = R.count (c2w c) {-# INLINE count #-} nextChar :: Monad m => ByteString m r -> m (Either r (Char, ByteString m r)) nextChar b = do e <- R.nextByte b case e of Left r -> return $! Left r Right (w,bs) -> return $! Right (w2c w, bs) putStr :: MonadIO m => ByteString m r -> m r putStr = hPut IO.stdout {-#INLINE putStr #-} putStrLn :: MonadIO m => ByteString m r -> m r putStrLn bs = hPut IO.stdout (snoc bs '\n') {-#INLINE putStrLn #-} -- , head' -- , last -- , last' -- , length -- , length' -- , null -- , null' -- , count -- , count' {-| This will read positive or negative Ints that require 18 or fewer characters. -} readInt :: Monad m => ByteString m r -> m (Compose (Of (Maybe Int)) (ByteString m) r) readInt = go . toStrict . splitAt 18 where go m = do (bs :> rest) <- m case Char8.readInt bs of Nothing -> return (Compose (Nothing :> (chunk bs >> rest))) Just (n,more) -> if B.null more then do e <- uncons rest return $ case e of Left r -> Compose (Just n :> return r) Right (c,rest') -> if isDigit c then Compose (Nothing :> (chunk bs >> cons' c rest')) else Compose (Just n :> (chunk more >> cons' c rest')) else return (Compose (Just n :> (chunk more >> rest))) {-#INLINABLE readInt #-} -- uncons :: Monad m => ByteString m r -> m (Either r (Char, ByteString m r))
michaelt/streaming-bytestring
Data/ByteString/Streaming/Char8.hs
Haskell
bsd-3-clause
25,121
{-# LANGUAGE ScopedTypeVariables #-} -- | Utilities for interleaving transition operators and running Markov chains. module Math.Probably.MCMC ( -- * Strategies module Strategy -- * Interleaving , interleave , polyInterleave , frequency , oneOfRandomly -- * Other , ezMC , trace ) where import Control.Applicative import Control.Monad import Control.Monad.State.Strict import Math.Probably.Sampler import Math.Probably.Types import Strategy.Hamiltonian as Strategy import Strategy.MALA as Strategy import Strategy.Metropolis as Strategy import Strategy.NUTS as Strategy import Strategy.NUTSDualAveraging as Strategy import Strategy.Slice as Strategy -- | Interleave a list of transitions together. -- -- > interleave [metropolis Nothing, mala Nothing] -- -- :: Transition Double interleave :: [Transition a] -> Transition a interleave = foldl1 (>>) -- | Select a transition operator from a list uniformly at random. oneOfRandomly :: [Transition a] -> Transition a oneOfRandomly ts = do j <- lift $ oneOf [0..(length ts - 1)] ts !! j -- | Select a transition operator from a list according to supplied -- frequencies. Mimics the similar function from QuickCheck. -- -- > frequency [(9, continuousSlice Nothing), (1, nutsDualAveraging Nothing)] -- -- probably a slice transition frequency :: [(Int, Transition a)] -> Transition a frequency xs = lift (oneOf [1..tot]) >>= (`pick` xs) where tot = sum . map fst $ xs pick n ((k, v):vs) | n <= k = v | otherwise = pick (n - k) vs pick _ [] = error "frequency: empty list" -- | Heterogeneous type interleaving. polyInterleave :: Transition t1 -> Transition t2 -> Transition (t1,t2) polyInterleave tr1 tr2 = do Chain current0 target val0 (tun1, tun2) <- get let chain1 = Chain current0 target val0 tun1 Chain current1 target1 val1 tun1next <- lift $ execStateT tr1 chain1 let chain2 = Chain current1 target1 val1 tun2 (ret, Chain current2 target2 val2 tun2next) <- lift $ runStateT tr2 chain2 put $ Chain current2 target2 val2 (tun1next, tun2next) return ret -- | Construct a transition from a supplied function. ezMC :: (Chain t -> Prob (Chain t)) -> Transition t ezMC f = get >>= lift . f >>= put >> gets parameterSpacePosition -- | Run a Markov Chain. trace :: Int -> Transition t -> Chain t -> Prob (Prob Parameters) trace n t o = Samples <$> replicateM n t `evalStateT` o
glutamate/probably-baysig
src/Math/Probably/MCMC.hs
Haskell
bsd-3-clause
2,457
{-# LANGUAGE MultiParamTypeClasses , FlexibleInstances , ViewPatterns , TupleSections #-} module Spire.Canonical.Evaluator (lookupValAndType , lookupType , sub , sub2 , elim , app , app2) where import Unbound.LocallyNameless hiding ( Spine ) import Spire.Canonical.Types import Spire.Surface.PrettyPrinter import Control.Applicative ((<$>) , (<*>)) import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State ---------------------------------------------------------------------- instance SubstM SpireM Value Spine instance SubstM SpireM Value Elim instance SubstM SpireM Value Value where substHookM (VNeut nm fs) = Just f where f nm' e = do fs' <- substM nm' e fs let head = if nm == nm' then e else vVar nm elims head fs' substHookM _ = Nothing ---------------------------------------------------------------------- sub :: Bind Nom Value -> Value -> SpireM Value sub b x = do (nm , f) <- unbind b substM nm x f elimB :: Bind Nom Value -> Elim -> SpireM (Bind Nom Value) elimB bnd_f g = do (nm , f) <- unbind bnd_f bind nm <$> elim f g subCompose :: Bind Nom Value -> (Value -> Value) -> SpireM (Bind Nom Value) subCompose bnd_f g = do (nm , f) <- unbind bnd_f bind nm <$> substM nm (g (vVar nm)) f sub2 :: Bind Nom2 Value -> (Value , Value) -> SpireM Value sub2 b (x1 , x2) = do ((nm1 , nm2) , f) <- unbind b substsM [(nm1 , x1) , (nm2 , x2)] f sub3 :: Bind Nom3 Value -> (Value , Value , Value) -> SpireM Value sub3 b (x1 , x2 , x3) = do ((nm1 , nm2 , nm3) , f) <- unbind b substsM [(nm1 , x1) , (nm2 , x2) , (nm3 , x3)] f app :: Value -> Value -> SpireM Value app f x = elim f (EApp x) app2 :: Value -> Value -> Value -> SpireM Value app2 f x y = elims f (Pipe (Pipe Id (EApp x)) (EApp y)) ---------------------------------------------------------------------- elim :: Value -> Elim -> SpireM Value elim (VNeut nm fs) f = return $ VNeut nm (Pipe fs f) elim (VLam f) (EApp a) = f `sub` a elim _ (EApp _) = throwError "Ill-typed evaluation of function application" elim VTT (EElimUnit _P ptt) = return ptt elim _ (EElimUnit _P ptt) = throwError "Ill-typed evaluation of elimUnit" elim VTrue (EElimBool _P pt _) = return pt elim VFalse (EElimBool _P _ pf) = return pf elim _ (EElimBool _P _ _) = throwError "Ill-typed evaluation of elimBool" elim (VPair a b) (EElimPair _A _B _P ppair) = do ppair `sub2` (a , b) elim _ (EElimPair _A _B _P ppair) = throwError "Ill-typed evaluation of elimPair" elim VRefl (EElimEq _A x _P prefl y) = return prefl elim _ (EElimEq _A x _P prefl y) = throwError "Ill-typed evaluation of elimEq" elim VNil (EElimEnum _P pn _) = return pn elim (VCons x xs) (EElimEnum _P pn pc) = do ih <- xs `elim` EElimEnum _P pn pc pc `sub3` (x , xs , ih) elim _ (EElimEnum _P _ _) = throwError "Ill-typed evaluation of elimEnum" elim VEmp (EElimTel _P pemp pext) = return pemp elim (VExt _A bnd_B) (EElimTel _P pemp pext) = do (nm_a , _B) <- unbind bnd_B ih <- elim _B (EElimTel _P pemp pext) pext `sub3` (_A , VLam (bind nm_a _B) , VLam (bind nm_a ih)) elim _ (EElimTel _P pemp pext) = throwError "Ill-typed evaluation of elimTel" elim (VEnd i) (EElimDesc _I _P pend prec parg) = pend `sub` i elim (VRec i _D) (EElimDesc _I _P pend prec parg) = do ih <- _D `elim` EElimDesc _I _P pend prec parg prec `sub3` (i , _D , ih) elim (VArg _A bnd_B) (EElimDesc _I _P pend prec parg) = do (nm_a , _B) <- unbind bnd_B ih <- elim _B (EElimDesc _I _P pend prec parg) parg `sub3` (_A , VLam (bind nm_a _B) , VLam (bind nm_a ih)) elim _ (EElimDesc _I _P pend prec parg) = throwError "Ill-typed evaluation of elimDesc" elim (VInit xs) (EInd l _P _I _D p _M m i) = do let _X = vBind "i" (VFix l _P _I _D p) let ih = rBind2 "i" "x" $ \ j x -> rInd l _P _I _D p _M m (vVar j) x ihs <- _D `elim` EProve _I _X _M ih i xs m `sub3` (i , xs , ihs) elim _ (EInd l _P _I _D p _M m i) = throwError "Ill-typed evaluation of ind" elim (VEnd j) (EFunc _I _X i) = return $ VEq _I j _I i elim (VRec j _D) (EFunc _I _X i) = vProd <$> _X `sub` j <*> _D `elim` EFunc _I _X i elim (VArg _A _B) (EFunc _I _X i) = VSg _A <$> _B `elimB` EFunc _I _X i elim _ (EFunc _I _X i) = throwError "Ill-typed evaluation of Func" elim (VEnd j) (EHyps _I _X _M i q) = return $ VUnit elim (VRec j _D) (EHyps _I _X _M i xxs) = do _A <- _X `sub` j _B <- _D `elim` EFunc _I _X i (x , xs) <- (,) <$> freshR "x" <*> freshR "xs" ppair <- vProd <$> _M `sub2` (j , vVar x) <*> _D `elim` EHyps _I _X _M i (vVar xs) xxs `elim` EElimPair _A (kBind _B) (kBind VType) (bind2 x xs ppair) elim (VArg _A bnd_B) (EHyps _I _X _M i axs) = do (a , _B) <- unbind bnd_B _B' <- _B `elim` EFunc _I _X i xs <- freshR "xs" ppair <- _B `elim` EHyps _I _X _M i (vVar xs) axs `elim` EElimPair _A (bind a _B') (kBind VType) (bind2 a xs ppair) elim _D (EHyps _I _X _M i xs) = throwError $ "Ill-typed evaluation of Hyps:" ++ "\nDescription:\n" ++ prettyPrint _D ++ "\nPair:\n" ++ prettyPrint xs elim (VEnd j) (EProve _I _X _M m i q) = return $ VTT elim (VRec j _D) (EProve _I _X _M m i xxs) = do _A <- _X `sub` j _B <- _D `elim` EFunc _I _X i (nm_xxs , x , xs) <- (,,) <$> freshR "xxs" <*> freshR "x" <*> freshR "xs" _M' <- VRec j _D `elim` EHyps _I _X _M i (vVar nm_xxs) ppair <- VPair <$> m `sub2` (j , vVar x) <*> _D `elim` EProve _I _X _M m i (vVar xs) xxs `elim` EElimPair _A (kBind _B) (bind nm_xxs _M') (bind2 x xs ppair) elim (VArg _A _B) (EProve _I _X _M m i axs) = do (nm_axs , a , xs) <- (,,) <$> freshR "axs" <*> freshR "a" <*> freshR "xs" _Ba <- _B `sub` vVar a _B' <- _Ba `elim` (EFunc _I _X i) _M' <- VArg _A _B `elim` EHyps _I _X _M i (vVar nm_axs) ppair <- _Ba `elim` EProve _I _X _M m i (vVar xs) axs `elim` EElimPair _A (bind a _B') (bind nm_axs _M') (bind2 a xs ppair) elim _ (EProve _I _X _M m i xs) = throwError "Ill-typed evaluation of prove" elim VNil (EBranches _P) = return VUnit elim (VCons l _E) (EBranches _P) = do _P' <- _P `subCompose` VThere vProd <$> _P `sub` VHere <*> _E `elim` EBranches _P' elim _ (EBranches _P) = throwError "Ill-typed evaluation of Branches" elim VHere (ECase (VCons l _E) _P ccs) = do _Pthere <- _P `subCompose` VThere _A <- _P `sub` VHere _B <- _E `elim` EBranches _Pthere let _M = _A c <- freshR "c" let ppair = vVar c ccs `elim` EElimPair _A (kBind _B) (kBind _M) (bind2 c wildcardR ppair) elim (VThere t) (ECase (VCons l _E) _P ccs) = do _Pthere <- _P `subCompose` VThere _A <- _P `sub` VHere _B <- _E `elim` EBranches _Pthere _M <- _P `sub` (VThere t) cs <- freshR "cs" ppair <- t `elim` ECase _E _Pthere (vVar cs) ccs `elim` EElimPair _A (kBind _B) (kBind _M) (bind2 wildcardR cs ppair) elim _ (ECase _E _P ccs) = throwError "Ill-typed evaluation of case" elims :: Value -> Spine -> SpireM Value elims x Id = return x elims x (Pipe fs f) = do x' <- elims x fs elim x' f ---------------------------------------------------------------------- -- Exported lookup functions. lookupValAndType :: Nom -> SpireM (Value , Type) lookupValAndType nm = do ctx <- asks ctx lookupCtx nm ctx lookupType :: Nom -> SpireM Type lookupType nm = snd <$> lookupValAndType nm ---------------------------------------------------------------------- -- Non-exported lookup functions. lookupCtx :: Nom -> Tel -> SpireM (Value , Type) lookupCtx nm (Extend (unrebind -> ((x , Embed _A) , xs))) = if nm == x then return (vVar nm , _A) else lookupCtx nm xs lookupCtx nm Empty = do env <- asks env lookupEnv nm env lookupEnv :: Nom -> Env -> SpireM (Value , Type) lookupEnv nm (VDef x a _A : xs) = if nm == x then return (a , _A) else lookupEnv nm xs lookupEnv nm [] = do env <- asks env ctx <- asks ctx uCtx <- gets unifierCtx throwError $ "Variable not in context or environment!\n" ++ "Referenced variable:\n" ++ prettyPrintError nm ++ "\n" ++ "\nCurrent context:\n" ++ prettyPrintError ctx ++ "\n" -- "\nCurrent environment:\n" ++ prettyPrintError env ++ "\n" ++ ----------------------------------------------------------------------
spire/spire
src/Spire/Canonical/Evaluator.hs
Haskell
bsd-3-clause
8,446
{-# LANGUAGE FlexibleContexts #-} module OpSem where import AST import Errors import qualified Control.Monad.Except as M import qualified Control.Monad.IO.Class as M -- (Recursion magic happens here) import qualified Data.Functor.Foldable as Rec import qualified Data.Map.Strict as Map import Data.Map.Strict (Map) import qualified Data.List as List paramsUnique :: ParamList -> Bool paramsUnique p = p == List.nub p -- uuuugly executeProg :: (M.MonadIO m, M.MonadError Error m) => Program -> Env -> m Env executeProg = Rec.fold executeDefList . reverse where executeDefList :: (M.MonadIO m, M.MonadError Error m) => Rec.ListF Definition (Env -> m Env) -> Env -> m Env executeDefList Rec.Nil env = return env executeDefList (Rec.Cons def prevDefs) env = execute def =<< prevDefs env -- definitions are executed execute :: (M.MonadIO m, M.MonadError Error m) => Definition -> Env -> m Env execute (Global x e) env = do (v, Env glob func param) <- evaluate e env let glob' = Map.insert x v glob return $ Env glob' func param execute (Function f paramList e) (Env glob func param) = do if paramsUnique paramList then return () else M.throwError $ ErrorString "nonunique paramater names" let func' = Map.insert f (UserFunc paramList e) func return $ Env glob func' param -- expressions are evaluated evaluate :: (M.MonadIO m, M.MonadError Error m) => Expr -> Env -> m (Value, Env) evaluate = Rec.fold evaluateF evaluateF :: (M.MonadIO m, M.MonadError Error m) => ExprF (Env -> m (Value, Env)) -> Env -> m (Value, Env) evaluateF (IfF p eT eF) env = do (b, env') <- p env if b /= 0 then eT env' else eF env' evaluateF (WhileF p e) env0 = let evalLoop env = do (b, env') <- p env if b == 0 then return env' else do (_, env'') <- e env' evalLoop env'' in fmap (\env1 -> (0, env1)) (evalLoop env0) evaluateF (BlockF []) env = return (0, env) evaluateF (BlockF es) env0 = let evalBlock [e] env = e env evalBlock (e:es) env = do (_, env') <- e env evalBlock es env' in evalBlock es env0 evaluateF (PrintF e) env = do (v, env') <- e env M.liftIO $ print v return (v, env') evaluateF (LocalF x e) env0 = do (v, Env glob func param) <- e env0 let param' = Map.insert x v param return (v, Env glob func param') evaluateF (SetF x e) env0 = do (v, Env glob func param) <- e env0 let result | x `Map.member` param = let param' = Map.adjust (const v) x param in return (v, Env glob func param') | x `Map.member` glob = let glob' = Map.adjust (const v) x glob in return (v, Env glob' func param) | otherwise = M.throwError . ErrorString $ "undefined var " ++ x ++ " is Set" result evaluateF (ApplyF fName argList) env0@(Env glob func param) | Just function <- Map.lookup fName func = do let evalArgs [] env = return ([], env) evalArgs (arg:args) env = do (v, env') <- arg env (vs, env'') <- evalArgs args env' return (v:vs, env'') (args, env'@(Env glob' _ param')) <- evalArgs argList env0 case function of BuiltinFunc f -> case f args of Nothing -> M.throwError . ErrorString $ "wrong number of args to " ++ fName Just n -> return (n, env') UserFunc argNames e -> do let argMap = Map.fromList $ zip argNames args (v, Env globFinal _ _) <- evaluate e (Env glob' func argMap) return (v, Env globFinal func param') | otherwise = M.throwError . ErrorString $ "undefined function " ++ fName ++ "is referenced" evaluateF (ReferenceF x) env@(Env glob func param) | Just v <- Map.lookup x param = return (v, env) | Just v <- Map.lookup x glob = return (v, env) | otherwise = M.throwError $ ErrorString "undefined var is referenced" -- well boy howdie this one is easy evaluateF (LiteralF n) env = return (n, env)
ClathomasPrime/ImpCore
Impcore/src/OpSem.hs
Haskell
bsd-3-clause
4,185
-- | -- Module : Network.TLS.Types -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : unknown -- module Network.TLS.Types ( Version(..) , SessionID , SessionData(..) , CipherID , CompressionID , Role(..) , invertRole , Direction(..) ) where import Data.ByteString (ByteString) import Data.Word type HostName = String -- | Versions known to TLS -- -- SSL2 is just defined, but this version is and will not be supported. data Version = SSL2 | SSL3 | TLS10 | TLS11 | TLS12 deriving (Show, Eq, Ord, Bounded) -- | A session ID type SessionID = ByteString -- | Session data to resume data SessionData = SessionData { sessionVersion :: Version , sessionCipher :: CipherID , sessionCompression :: CompressionID , sessionClientSNI :: Maybe HostName , sessionSecret :: ByteString } deriving (Show,Eq) -- | Cipher identification type CipherID = Word16 -- | Compression identification type CompressionID = Word8 -- | Role data Role = ClientRole | ServerRole deriving (Show,Eq) -- | Direction data Direction = Tx | Rx deriving (Show,Eq) invertRole :: Role -> Role invertRole ClientRole = ServerRole invertRole ServerRole = ClientRole
erikd/hs-tls
core/Network/TLS/Types.hs
Haskell
bsd-3-clause
1,296
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE GADTs #-} module Network.Krist.Transaction where import Data.Aeson import GHC.Generics import Data.Monoid import Control.Krist.Request import Control.Monad import Control.Monad.IO.Class import System.FilePath import Network.Krist.Node data Transaction = Transaction { transID :: Int , transFrom :: Maybe String , transTo :: String , transValue :: Int , transTime :: String , transName :: Maybe String , transMeta :: Maybe String } deriving (Eq, Show, Ord) data TrnsRequestResp = TrnsRequestResp { ok :: Bool , transaction :: Transaction } deriving (Eq, Show, Ord, Generic) data TransesRequestRep = TransesRequestRep { ok :: Bool , count :: Int , total :: Int , transactions :: [Transaction] } deriving (Eq, Show, Ord, Generic) instance FromJSON TrnsRequestResp instance FromJSON TransesRequestRep instance FromJSON Transaction where parseJSON (Object v) = Transaction <$> v .: "id" <*> v .: "from" <*> v .: "to" <*> v .: "value" <*> v .: "time" <*> v .: "name" <*> v .: "metadata" parseJSON _ = mzero data TransRequest a where GetTransaction :: Int -> TransRequest Transaction GetTransactions :: Int -> Int -> TransRequest [Transaction] GetLatest :: Int -> Int -> TransRequest [Transaction] GetLatestMined :: Int -> Int -> TransRequest [Transaction] GetAddrLatest :: String -> Int -> Int -> TransRequest [Transaction] GetAddrLatestMined :: String -> Int -> Int -> TransRequest [Transaction] instance Requestable TransRequest where makeRequest n (GetTransaction x) = selector transaction $ requestJSON n ("transactions" </> show x) makeRequest n (GetTransactions a o) = selector transactions $ requestJSON n ("transactions?limit=" <> show a <> "&offset=" <> show o) makeRequest n (GetLatest a o) = selector transactions $ requestJSON n $ concat [ "transactions/latest?limit=" , show a , "&offset=", show o , "&excludeMined=true" ] makeRequest n (GetLatestMined a o) = selector transactions $ requestJSON n $ concat [ "transactions/latest?limit=" , show a , "&offset=", show o , "&excludeMined=false" ] makeRequest n (GetAddrLatestMined a l o) = selector transactions $ requestJSON (n `nodeAt` ("addresses" </> a)) $ concat [ "transactions?limit=" , show l , "&offset=", show o , "&excludeMined=true" ] makeRequest n (GetAddrLatest a l o) = selector transactions $ requestJSON (n `nodeAt` ("addresses" </> a)) $ concat [ "transactions?limit=" , show l , "&offset=", show o , "&excludeMined=falsed" ] getTransaction :: MonadIO m => Node -> Int -> m (Either ReqError Transaction) getTransaction n x = makeRequest n (GetTransaction x) getTransactions :: MonadIO m => Node -> Int -> Int -> m (Either ReqError [Transaction]) getTransactions n a o = makeRequest n (GetTransactions a o) getLatestTransactions :: MonadIO m => Node -> Int -> Int -> m (Either ReqError [Transaction]) getLatestTransactions n a o = makeRequest n (GetLatest a o) getLatestMined :: MonadIO m => Node -> Int -> Int -> m (Either ReqError [Transaction]) getLatestMined n a o = makeRequest n (GetLatestMined a o) addressTransactions :: MonadIO m => Node -> String -> Int -> Int -> m (Either ReqError [Transaction]) addressTransactions n a l o = n `makeRequest` GetAddrLatest a l o addressMined :: MonadIO m => Node -> String -> Int -> Int -> m (Either ReqError [Transaction]) addressMined n a l o = n `makeRequest` GetAddrLatestMined a l o
demhydraz/krisths
src/Network/Krist/Transaction.hs
Haskell
bsd-3-clause
4,115
{-# LANGUAGE MagicHash #-} module Main where import GHC.Exts ( Float(F#), eqFloat#, neFloat#, ltFloat#, leFloat#, gtFloat#, geFloat# ) fcmp_eq, fcmp_ne, fcmp_lt, fcmp_le, fcmp_gt, fcmp_ge :: (String, Float -> Float -> Bool) fcmp_eq = ("==", \ (F# a) (F# b) -> a `eqFloat#` b) fcmp_ne = ("/=", \ (F# a) (F# b) -> a `neFloat#` b) fcmp_lt = ("< ", \ (F# a) (F# b) -> a `ltFloat#` b) fcmp_le = ("<=", \ (F# a) (F# b) -> a `leFloat#` b) fcmp_gt = ("> ", \ (F# a) (F# b) -> a `gtFloat#` b) fcmp_ge = (">=", \ (F# a) (F# b) -> a `geFloat#` b) float_fns = [fcmp_eq, fcmp_ne, fcmp_lt, fcmp_le, fcmp_gt, fcmp_ge] float_vals :: [Float] float_vals = [0.0, 1.0, read "NaN"] float_text = [show4 arg1 ++ " " ++ fn_name ++ " " ++ show4 arg2 ++ " = " ++ show (fn arg1 arg2) | (fn_name, fn) <- float_fns, arg1 <- float_vals, arg2 <- float_vals ] where show4 x = take 4 (show x ++ repeat ' ') main = putStrLn (unlines float_text)
kfish/const-math-ghc-plugin
tests/ghc-7.6/arith016.hs
Haskell
bsd-3-clause
982
{- Test Show instances Copyright (c) 2014 Richard Eisenberg -} module Tests.Show where import Data.Metrology import Data.Metrology.Show () import Data.Metrology.SI import Test.Tasty import Test.Tasty.HUnit five :: Double five = 5 tests :: TestTree tests = testGroup "Show" [ testCase "Meter" $ show (five % Meter) @?= "5.0 m" , testCase "Meter/Second" $ show (five % (Meter :/ Second)) @?= "5.0 m/s" , testCase "Meter/Second2" $ show (five % (Number :* Second :* Meter :/ (Second :^ sTwo))) @?= "5.0 m/s" , testCase "Hertz" $ show (five % Hertz) @?= "5.0 s^-1" , testCase "Joule" $ show (five % Joule) @?= "5.0 (kg * m^2)/s^2" ]
goldfirere/units
units-test/Tests/Show.hs
Haskell
bsd-3-clause
649
{-| Module : Idris.Parser Description : Idris' parser. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE ConstraintKinds, FlexibleContexts, GeneralizedNewtypeDeriving, PatternGuards #-} {-# OPTIONS_GHC -O0 #-} module Idris.Parser(module Idris.Parser, module Idris.Parser.Expr, module Idris.Parser.Data, module Idris.Parser.Helpers, module Idris.Parser.Ops) where import Idris.AbsSyntax hiding (namespace, params) import Idris.Core.Evaluate import Idris.Core.TT import Idris.Coverage import Idris.Delaborate import Idris.Docstrings hiding (Unchecked) import Idris.DSL import Idris.Elab.Term import Idris.Elab.Value import Idris.ElabDecls import Idris.Error import Idris.IBC import Idris.Imports import Idris.Options import Idris.Output import Idris.Parser.Data import Idris.Parser.Expr import Idris.Parser.Helpers import Idris.Parser.Ops import Idris.Providers import Idris.Termination import Idris.Unlit import Util.DynamicLinker import qualified Util.Pretty as P import Util.System (readSource, writeSource) import Paths_idris import Prelude hiding (pi) import Control.Applicative hiding (Const) import Control.Monad import Control.Monad.State.Strict import qualified Data.ByteString.UTF8 as UTF8 import Data.Char import Data.Foldable (asum) import Data.Function import Data.Generics.Uniplate.Data (descendM) import qualified Data.HashSet as HS import Data.List import qualified Data.List.Split as Spl import qualified Data.Map as M import Data.Maybe import Data.Monoid import Data.Ord import qualified Data.Set as S import qualified Data.Text as T import Debug.Trace import qualified System.Directory as Dir (makeAbsolute) import System.FilePath import System.IO import qualified Text.Parser.Char as Chr import Text.Parser.Expression import Text.Parser.LookAhead import qualified Text.Parser.Token as Tok import qualified Text.Parser.Token.Highlight as Hi import Text.PrettyPrint.ANSI.Leijen (Doc, plain) import qualified Text.PrettyPrint.ANSI.Leijen as ANSI import Text.Trifecta hiding (Err, char, charLiteral, natural, span, string, stringLiteral, symbol, whiteSpace) import Text.Trifecta.Delta {- @ grammar shortcut notation: ~CHARSEQ = complement of char sequence (i.e. any character except CHARSEQ) RULE? = optional rule (i.e. RULE or nothing) RULE* = repeated rule (i.e. RULE zero or more times) RULE+ = repeated rule with at least one match (i.e. RULE one or more times) RULE! = invalid rule (i.e. rule that is not valid in context, report meaningful error in case) RULE{n} = rule repeated n times @ -} {- * Main grammar -} {-| Parses module definition @ ModuleHeader ::= DocComment_t? 'module' Identifier_t ';'?; @ -} moduleHeader :: IdrisParser (Maybe (Docstring ()), [String], [(FC, OutputAnnotation)]) moduleHeader = try (do docs <- optional docComment noArgs docs reservedHL "module" (i, ifc) <- identifier option ';' (lchar ';') let modName = moduleName i return (fmap fst docs, modName, [(ifc, AnnNamespace (map T.pack modName) Nothing)])) <|> try (do lchar '%'; reserved "unqualified" return (Nothing, [], [])) <|> return (Nothing, moduleName "Main", []) where moduleName x = case span (/='.') x of (x, "") -> [x] (x, '.':y) -> x : moduleName y noArgs (Just (_, args)) | not (null args) = fail "Modules do not take arguments" noArgs _ = return () data ImportInfo = ImportInfo { import_reexport :: Bool , import_path :: FilePath , import_rename :: Maybe (String, FC) , import_namespace :: [T.Text] , import_location :: FC , import_modname_location :: FC } {-| Parses an import statement @ Import ::= 'import' Identifier_t ';'?; @ -} import_ :: IdrisParser ImportInfo import_ = do fc <- getFC reservedHL "import" reexport <- option False (do reservedHL "public" return True) (id, idfc) <- identifier newName <- optional (do reservedHL "as" identifier) option ';' (lchar ';') return $ ImportInfo reexport (toPath id) (fmap (\(n, fc) -> (toPath n, fc)) newName) (map T.pack $ ns id) fc idfc <?> "import statement" where ns = Spl.splitOn "." toPath = foldl1' (</>) . ns {-| Parses program source @ Prog ::= Decl* EOF; @ -} prog :: SyntaxInfo -> IdrisParser [PDecl] prog syn = do whiteSpace decls <- many (decl syn) let c = concat decls case maxline syn of Nothing -> do notOpenBraces; eof _ -> return () ist <- get fc <- getFC put ist { idris_parsedSpan = Just (FC (fc_fname fc) (0,0) (fc_end fc)), ibc_write = IBCParsedRegion fc : ibc_write ist } return c {-| Parses a top-level declaration @ Decl ::= Decl' | Using | Params | Mutual | Namespace | Interface | Implementation | DSL | Directive | Provider | Transform | Import! | RunElabDecl ; @ -} decl :: SyntaxInfo -> IdrisParser [PDecl] decl syn = try (externalDecl syn) <|> internalDecl syn <?> "declaration" internalDecl :: SyntaxInfo -> IdrisParser [PDecl] internalDecl syn = do fc <- getFC -- if we're after maxline, stop at the next type declaration -- (so we get all cases of a definition to preserve totality -- results, in particular). let continue = case maxline syn of Nothing -> True Just l -> if fst (fc_end fc) > l then mut_nesting syn /= 0 else True -- What I'd really like to do here is explicitly save the -- current state, then if reading ahead finds we've passed -- the end of the definition, reset the state. But I've lost -- patience with trying to find out how to do that from the -- trifecta docs, so this does the job instead. if continue then do notEndBlock declBody continue else try (do notEndBlock declBody continue) <|> fail "End of readable input" where declBody :: Bool -> IdrisParser [PDecl] declBody b = try (implementation True syn) <|> try (openInterface syn) <|> declBody' b <|> using_ syn <|> params syn <|> mutual syn <|> namespace syn <|> interface_ syn <|> do d <- dsl syn; return [d] <|> directive syn <|> provider syn <|> transform syn <|> do import_; fail "imports must be at top of file" <?> "declaration" declBody' :: Bool -> IdrisParser [PDecl] declBody' cont = do d <- decl' syn i <- get let d' = fmap (debindApp syn . (desugar syn i)) d if continue cont d' then return [d'] else fail "End of readable input" -- Keep going while we're still parsing clauses continue False (PClauses _ _ _ _) = True continue c _ = c {-| Parses a top-level declaration with possible syntax sugar @ Decl' ::= Fixity | FunDecl' | Data | Record | SyntaxDecl ; @ -} decl' :: SyntaxInfo -> IdrisParser PDecl decl' syn = fixity <|> syntaxDecl syn <|> fnDecl' syn <|> data_ syn <|> record syn <|> runElabDecl syn <?> "declaration" externalDecl :: SyntaxInfo -> IdrisParser [PDecl] externalDecl syn = do i <- get notEndBlock FC fn start _ <- getFC decls <- declExtensions syn (syntaxRulesList $ syntax_rules i) FC _ _ end <- getFC let outerFC = FC fn start end return $ map (mapPDeclFC (fixFC outerFC) (fixFCH fn outerFC)) decls where -- | Fix non-highlighting FCs to prevent spurious error location reports fixFC :: FC -> FC -> FC fixFC outer inner | inner `fcIn` outer = inner | otherwise = outer -- | Fix highlighting FCs by obliterating them, to avoid spurious highlights fixFCH fn outer inner | inner `fcIn` outer = inner | otherwise = FileFC fn declExtensions :: SyntaxInfo -> [Syntax] -> IdrisParser [PDecl] declExtensions syn rules = declExtension syn [] (filter isDeclRule rules) <?> "user-defined declaration" where isDeclRule (DeclRule _ _) = True isDeclRule _ = False declExtension :: SyntaxInfo -> [Maybe (Name, SynMatch)] -> [Syntax] -> IdrisParser [PDecl] declExtension syn ns rules = choice $ flip map (groupBy (ruleGroup `on` syntaxSymbols) rules) $ \rs -> case head rs of -- can never be [] DeclRule (symb:_) _ -> try $ do n <- extSymbol symb declExtension syn (n : ns) [DeclRule ss t | (DeclRule (_:ss) t) <- rs] -- If we have more than one Rule in this bucket, our grammar is -- nondeterministic. DeclRule [] dec -> let r = map (update (mapMaybe id ns)) dec in return r where update :: [(Name, SynMatch)] -> PDecl -> PDecl update ns = updateNs ns . fmap (updateRefs ns) . fmap (updateSynMatch ns) updateRefs ns = mapPT newref where newref (PRef fc fcs n) = PRef fc fcs (updateB ns n) newref t = t -- Below is a lot of tedious boilerplate which updates any top level -- names in the declaration. It will only change names which are bound in -- the declaration (including method names in interfaces and field names in -- record declarations, not including pattern variables) updateB :: [(Name, SynMatch)] -> Name -> Name updateB ns (NS n mods) = NS (updateB ns n) mods updateB ns n = case lookup n ns of Just (SynBind tfc t) -> t _ -> n updateNs :: [(Name, SynMatch)] -> PDecl -> PDecl updateNs ns (PTy doc argdoc s fc o n fc' t) = PTy doc argdoc s fc o (updateB ns n) fc' t updateNs ns (PClauses fc o n cs) = PClauses fc o (updateB ns n) (map (updateClause ns) cs) updateNs ns (PCAF fc n t) = PCAF fc (updateB ns n) t updateNs ns (PData ds cds s fc o dat) = PData ds cds s fc o (updateData ns dat) updateNs ns (PParams fc ps ds) = PParams fc ps (map (updateNs ns) ds) updateNs ns (PNamespace s fc ds) = PNamespace s fc (map (updateNs ns) ds) updateNs ns (PRecord doc syn fc o n fc' ps pdocs fields cname cdoc s) = PRecord doc syn fc o (updateB ns n) fc' ps pdocs (map (updateField ns) fields) (updateRecCon ns cname) cdoc s updateNs ns (PInterface docs s fc cs cn fc' ps pdocs pdets ds cname cdocs) = PInterface docs s fc cs (updateB ns cn) fc' ps pdocs pdets (map (updateNs ns) ds) (updateRecCon ns cname) cdocs updateNs ns (PImplementation docs pdocs s fc cs pnames acc opts cn fc' ps pextra ity ni ds) = PImplementation docs pdocs s fc cs pnames acc opts (updateB ns cn) fc' ps pextra ity (fmap (updateB ns) ni) (map (updateNs ns) ds) updateNs ns (PMutual fc ds) = PMutual fc (map (updateNs ns) ds) updateNs ns (PProvider docs s fc fc' pw n) = PProvider docs s fc fc' pw (updateB ns n) updateNs ns d = d updateRecCon ns Nothing = Nothing updateRecCon ns (Just (n, fc)) = Just (updateB ns n, fc) updateField ns (m, p, t, doc) = (updateRecCon ns m, p, t, doc) updateClause ns (PClause fc n t ts t' ds) = PClause fc (updateB ns n) t ts t' (map (update ns) ds) updateClause ns (PWith fc n t ts t' m ds) = PWith fc (updateB ns n) t ts t' m (map (update ns) ds) updateClause ns (PClauseR fc ts t ds) = PClauseR fc ts t (map (update ns) ds) updateClause ns (PWithR fc ts t m ds) = PWithR fc ts t m (map (update ns) ds) updateData ns (PDatadecl n fc t cs) = PDatadecl (updateB ns n) fc t (map (updateCon ns) cs) updateData ns (PLaterdecl n fc t) = PLaterdecl (updateB ns n) fc t updateCon ns (cd, ads, cn, fc, ty, fc', fns) = (cd, ads, updateB ns cn, fc, ty, fc', fns) ruleGroup [] [] = True ruleGroup (s1:_) (s2:_) = s1 == s2 ruleGroup _ _ = False extSymbol :: SSymbol -> IdrisParser (Maybe (Name, SynMatch)) extSymbol (Keyword n) = do fc <- reservedFC (show n) highlightP fc AnnKeyword return Nothing extSymbol (Expr n) = do tm <- expr syn return $ Just (n, SynTm tm) extSymbol (SimpleExpr n) = do tm <- simpleExpr syn return $ Just (n, SynTm tm) extSymbol (Binding n) = do (b, fc) <- name return $ Just (n, SynBind fc b) extSymbol (Symbol s) = do fc <- symbolFC s highlightP fc AnnKeyword return Nothing {-| Parses a syntax extension declaration (and adds the rule to parser state) @ SyntaxDecl ::= SyntaxRule; @ -} syntaxDecl :: SyntaxInfo -> IdrisParser PDecl syntaxDecl syn = do s <- syntaxRule syn i <- get put (i `addSyntax` s) fc <- getFC return (PSyntax fc s) -- | Extend an 'IState' with a new syntax extension. See also 'addReplSyntax'. addSyntax :: IState -> Syntax -> IState addSyntax i s = i { syntax_rules = updateSyntaxRules [s] rs, syntax_keywords = ks ++ ns, ibc_write = IBCSyntax s : map IBCKeyword ks ++ ibc } where rs = syntax_rules i ns = syntax_keywords i ibc = ibc_write i ks = map show (syntaxNames s) -- | Like 'addSyntax', but no effect on the IBC. addReplSyntax :: IState -> Syntax -> IState addReplSyntax i s = i { syntax_rules = updateSyntaxRules [s] rs, syntax_keywords = ks ++ ns } where rs = syntax_rules i ns = syntax_keywords i ks = map show (syntaxNames s) {-| Parses a syntax extension declaration @ SyntaxRuleOpts ::= 'term' | 'pattern'; @ @ SyntaxRule ::= SyntaxRuleOpts? 'syntax' SyntaxSym+ '=' TypeExpr Terminator; @ @ SyntaxSym ::= '[' Name_t ']' | '{' Name_t '}' | Name_t | StringLiteral_t ; @ -} syntaxRule :: SyntaxInfo -> IdrisParser Syntax syntaxRule syn = do sty <- try (do pushIndent sty <- option AnySyntax (do reservedHL "term"; return TermSyntax <|> do reservedHL "pattern"; return PatternSyntax) reservedHL "syntax" return sty) syms <- some syntaxSym when (all isExpr syms) $ unexpected "missing keywords in syntax rule" let ns = mapMaybe getName syms when (length ns /= length (nub ns)) $ unexpected "repeated variable in syntax rule" lchar '=' tm <- typeExpr (allowImp syn) >>= uniquifyBinders [n | Binding n <- syms] terminator return (Rule (mkSimple syms) tm sty) <|> do reservedHL "decl"; reservedHL "syntax" syms <- some syntaxSym when (all isExpr syms) $ unexpected "missing keywords in syntax rule" let ns = mapMaybe getName syms when (length ns /= length (nub ns)) $ unexpected "repeated variable in syntax rule" lchar '=' openBlock dec <- some (decl syn) closeBlock return (DeclRule (mkSimple syms) (concat dec)) where isExpr (Expr _) = True isExpr _ = False getName (Expr n) = Just n getName _ = Nothing -- Can't parse two full expressions (i.e. expressions with application) in a row -- so change them both to a simple expression mkSimple (Expr e : es) = SimpleExpr e : mkSimple' es mkSimple xs = mkSimple' xs mkSimple' (Expr e : Expr e1 : es) = SimpleExpr e : SimpleExpr e1 : mkSimple es -- Can't parse a full expression followed by operator like characters due to ambiguity mkSimple' (Expr e : Symbol s : es) | takeWhile (`elem` opChars) ts /= "" = SimpleExpr e : Symbol s : mkSimple' es where ts = dropWhile isSpace . dropWhileEnd isSpace $ s mkSimple' (e : es) = e : mkSimple' es mkSimple' [] = [] -- Prevent syntax variable capture by making all binders under syntax unique -- (the ol' Common Lisp GENSYM approach) uniquifyBinders :: [Name] -> PTerm -> IdrisParser PTerm uniquifyBinders userNames = fixBind 0 [] where fixBind :: Int -> [(Name, Name)] -> PTerm -> IdrisParser PTerm fixBind 0 rens (PRef fc hls n) | Just n' <- lookup n rens = return $ PRef fc hls n' fixBind 0 rens (PPatvar fc n) | Just n' <- lookup n rens = return $ PPatvar fc n' fixBind 0 rens (PLam fc n nfc ty body) | n `elem` userNames = liftM2 (PLam fc n nfc) (fixBind 0 rens ty) (fixBind 0 rens body) | otherwise = do ty' <- fixBind 0 rens ty n' <- gensym n body' <- fixBind 0 ((n,n'):rens) body return $ PLam fc n' nfc ty' body' fixBind 0 rens (PPi plic n nfc argTy body) | n `elem` userNames = liftM2 (PPi plic n nfc) (fixBind 0 rens argTy) (fixBind 0 rens body) | otherwise = do ty' <- fixBind 0 rens argTy n' <- gensym n body' <- fixBind 0 ((n,n'):rens) body return $ (PPi plic n' nfc ty' body') fixBind 0 rens (PLet fc n nfc ty val body) | n `elem` userNames = liftM3 (PLet fc n nfc) (fixBind 0 rens ty) (fixBind 0 rens val) (fixBind 0 rens body) | otherwise = do ty' <- fixBind 0 rens ty val' <- fixBind 0 rens val n' <- gensym n body' <- fixBind 0 ((n,n'):rens) body return $ PLet fc n' nfc ty' val' body' fixBind 0 rens (PMatchApp fc n) | Just n' <- lookup n rens = return $ PMatchApp fc n' -- Also rename resolved quotations, to allow syntax rules to -- have quoted references to their own bindings. fixBind 0 rens (PQuoteName n True fc) | Just n' <- lookup n rens = return $ PQuoteName n' True fc -- Don't mess with quoted terms fixBind q rens (PQuasiquote tm goal) = flip PQuasiquote goal <$> fixBind (q + 1) rens tm fixBind q rens (PUnquote tm) = PUnquote <$> fixBind (q - 1) rens tm fixBind q rens x = descendM (fixBind q rens) x gensym :: Name -> IdrisParser Name gensym n = do ist <- get let idx = idris_name ist put ist { idris_name = idx + 1 } return $ sMN idx (show n) {-| Parses a syntax symbol (either binding variable, keyword or expression) @ SyntaxSym ::= '[' Name_t ']' | '{' Name_t '}' | Name_t | StringLiteral_t ; @ -} syntaxSym :: IdrisParser SSymbol syntaxSym = try (do lchar '['; n <- fst <$> name; lchar ']' return (Expr n)) <|> try (do lchar '{'; n <- fst <$> name; lchar '}' return (Binding n)) <|> do n <- fst <$> iName [] return (Keyword n) <|> do sym <- fmap fst stringLiteral return (Symbol sym) <?> "syntax symbol" {-| Parses a function declaration with possible syntax sugar @ FunDecl ::= FunDecl'; @ -} fnDecl :: SyntaxInfo -> IdrisParser [PDecl] fnDecl syn = try (do notEndBlock d <- fnDecl' syn i <- get let d' = fmap (desugar syn i) d return [d']) <?> "function declaration" {-| Parses a function declaration @ FunDecl' ::= DocComment_t? FnOpts* Accessibility? FnOpts* FnName TypeSig Terminator | Postulate | Pattern | CAF ; @ -} fnDecl' :: SyntaxInfo -> IdrisParser PDecl fnDecl' syn = checkDeclFixity $ do (doc, argDocs, fc, opts', n, nfc, acc) <- try (do pushIndent (doc, argDocs) <- docstring syn (opts, acc) <- fnOpts (n_in, nfc) <- fnName let n = expandNS syn n_in fc <- getFC lchar ':' return (doc, argDocs, fc, opts, n, nfc, acc)) ty <- typeExpr (allowImp syn) terminator -- If it's a top level function, note the accessibility -- rules when (syn_toplevel syn) $ addAcc n acc return (PTy doc argDocs syn fc opts' n nfc ty) <|> postulate syn <|> caf syn <|> pattern syn <?> "function declaration" {-| Parses a series of function and accessbility options @ FnOpts ::= FnOpt* Accessibility FnOpt* @ -} fnOpts :: IdrisParser ([FnOpt], Accessibility) fnOpts = do opts <- many fnOpt acc <- accessibility opts' <- many fnOpt let allOpts = opts ++ opts' let existingTotality = allOpts `intersect` [TotalFn, CoveringFn, PartialFn] opts'' <- addDefaultTotality (nub existingTotality) allOpts return (opts'', acc) where prettyTot TotalFn = "total" prettyTot PartialFn = "partial" prettyTot CoveringFn = "covering" addDefaultTotality [] opts = do ist <- get case default_total ist of DefaultCheckingTotal -> return (TotalFn:opts) DefaultCheckingCovering -> return (CoveringFn:opts) DefaultCheckingPartial -> return opts -- Don't add partial so that --warn-partial still reports warnings if necessary addDefaultTotality [tot] opts = return opts -- Should really be a semantics error instead of a parser error addDefaultTotality (tot1:tot2:tots) opts = fail ("Conflicting totality modifiers specified " ++ prettyTot tot1 ++ " and " ++ prettyTot tot2) {-| Parses a function option @ FnOpt ::= 'total' | 'partial' | 'covering' | 'implicit' | '%' 'no_implicit' | '%' 'assert_total' | '%' 'error_handler' | '%' 'reflection' | '%' 'specialise' '[' NameTimesList? ']' ; @ @ NameTimes ::= FnName Natural?; @ @ NameTimesList ::= NameTimes | NameTimes ',' NameTimesList ; @ -} fnOpt :: IdrisParser FnOpt fnOpt = do reservedHL "total"; return TotalFn <|> do reservedHL "partial"; return PartialFn <|> do reservedHL "covering"; return CoveringFn <|> do try (lchar '%' *> reserved "export"); c <- fmap fst stringLiteral; return $ CExport c <|> do try (lchar '%' *> reserved "no_implicit"); return NoImplicit <|> do try (lchar '%' *> reserved "inline"); return Inlinable <|> do try (lchar '%' *> reserved "static"); return StaticFn <|> do try (lchar '%' *> reserved "assert_total"); fc <- getFC parserWarning fc Nothing (Msg "%assert_total is deprecated. Use the 'assert_total' function instead.") return AssertTotal <|> do try (lchar '%' *> reserved "error_handler"); return ErrorHandler <|> do try (lchar '%' *> reserved "error_reverse"); return ErrorReverse <|> do try (lchar '%' *> reserved "error_reduce"); return ErrorReduce <|> do try (lchar '%' *> reserved "reflection"); return Reflection <|> do try (lchar '%' *> reserved "hint"); return AutoHint <|> do try (lchar '%' *> reserved "overlapping"); return OverlappingDictionary <|> do lchar '%'; reserved "specialise"; lchar '['; ns <- sepBy nameTimes (lchar ','); lchar ']'; return $ Specialise ns <|> do reservedHL "implicit"; return Implicit <?> "function modifier" where nameTimes :: IdrisParser (Name, Maybe Int) nameTimes = do n <- fst <$> fnName t <- option Nothing (do reds <- fmap fst natural return (Just (fromInteger reds))) return (n, t) {-| Parses a postulate @ Postulate ::= DocComment_t? 'postulate' FnOpts* Accesibility? FnOpts* FnName TypeSig Terminator ; @ -} postulate :: SyntaxInfo -> IdrisParser PDecl postulate syn = do (doc, ext) <- try $ do (doc, _) <- docstring syn pushIndent ext <- ppostDecl return (doc, ext) ist <- get (opts, acc) <- fnOpts (n_in, nfc) <- fnName let n = expandNS syn n_in lchar ':' ty <- typeExpr (allowImp syn) fc <- getFC terminator addAcc n acc return (PPostulate ext doc syn fc nfc opts n ty) <?> "postulate" where ppostDecl = do fc <- reservedHL "postulate"; return False <|> do lchar '%'; reserved "extern"; return True {-| Parses a using declaration @ Using ::= 'using' '(' UsingDeclList ')' OpenBlock Decl* CloseBlock ; @ -} using_ :: SyntaxInfo -> IdrisParser [PDecl] using_ syn = do reservedHL "using" lchar '('; ns <- usingDeclList syn; lchar ')' openBlock let uvars = using syn ds <- many (decl (syn { using = uvars ++ ns })) closeBlock return (concat ds) <?> "using declaration" {-| Parses a parameters declaration @ Params ::= 'parameters' '(' TypeDeclList ')' OpenBlock Decl* CloseBlock ; @ -} params :: SyntaxInfo -> IdrisParser [PDecl] params syn = do reservedHL "parameters"; lchar '('; ns <- typeDeclList syn; lchar ')' let ns' = [(n, ty) | (_, n, _, ty) <- ns] openBlock let pvars = syn_params syn ds <- many (decl syn { syn_params = pvars ++ ns' }) closeBlock fc <- getFC return [PParams fc ns' (concat ds)] <?> "parameters declaration" -- | Parses an open block openInterface :: SyntaxInfo -> IdrisParser [PDecl] openInterface syn = do reservedHL "using" reservedHL "implementation" fc <- getFC ns <- sepBy1 fnName (lchar ',') openBlock ds <- many (decl syn) closeBlock return [POpenInterfaces fc (map fst ns) (concat ds)] <?> "open interface declaration" {-| Parses a mutual declaration (for mutually recursive functions) @ Mutual ::= 'mutual' OpenBlock Decl* CloseBlock ; @ -} mutual :: SyntaxInfo -> IdrisParser [PDecl] mutual syn = do reservedHL "mutual" openBlock let pvars = syn_params syn ds <- many (decl (syn { mut_nesting = mut_nesting syn + 1 } )) closeBlock fc <- getFC return [PMutual fc (concat ds)] <?> "mutual block" {-| Parses a namespace declaration @ Namespace ::= 'namespace' identifier OpenBlock Decl+ CloseBlock ; @ -} namespace :: SyntaxInfo -> IdrisParser [PDecl] namespace syn = do reservedHL "namespace" (n, nfc) <- identifier openBlock ds <- some (decl syn { syn_namespace = n : syn_namespace syn }) closeBlock return [PNamespace n nfc (concat ds)] <?> "namespace declaration" {-| Parses a methods block (for implementations) @ ImplementationBlock ::= 'where' OpenBlock FnDecl* CloseBlock @ -} implementationBlock :: SyntaxInfo -> IdrisParser [PDecl] implementationBlock syn = do reservedHL "where" openBlock ds <- many (fnDecl syn) closeBlock return (concat ds) <?> "implementation block" {-| Parses a methods and implementations block (for interfaces) @ MethodOrImplementation ::= FnDecl | Implementation ; @ @ InterfaceBlock ::= 'where' OpenBlock Constructor? MethodOrImplementation* CloseBlock ; @ -} interfaceBlock :: SyntaxInfo -> IdrisParser (Maybe (Name, FC), Docstring (Either Err PTerm), [PDecl]) interfaceBlock syn = do reservedHL "where" openBlock (cn, cd) <- option (Nothing, emptyDocstring) $ try (do (doc, _) <- option noDocs docComment n <- constructor return (Just n, doc)) ist <- get let cd' = annotate syn ist cd ds <- many (notEndBlock >> try (implementation True syn) <|> do x <- data_ syn return [x] <|> fnDecl syn) closeBlock return (cn, cd', concat ds) <?> "interface block" where constructor :: IdrisParser (Name, FC) constructor = reservedHL "constructor" *> fnName annotate :: SyntaxInfo -> IState -> Docstring () -> Docstring (Either Err PTerm) annotate syn ist = annotCode $ tryFullExpr syn ist {-| Parses an interface declaration @ InterfaceArgument ::= Name | '(' Name ':' Expr ')' ; @ @ Interface ::= DocComment_t? Accessibility? 'interface' ConstraintList? Name InterfaceArgument* InterfaceBlock? ; @ -} interface_ :: SyntaxInfo -> IdrisParser [PDecl] interface_ syn = do (doc, argDocs, acc) <- try (do (doc, argDocs) <- docstring syn acc <- accessibility interfaceKeyword return (doc, argDocs, acc)) fc <- getFC cons <- constraintList syn let cons' = [(c, ty) | (_, c, _, ty) <- cons] (n_in, nfc) <- fnName let n = expandNS syn n_in cs <- many carg fds <- option [(cn, NoFC) | (cn, _, _) <- cs] fundeps (cn, cd, ds) <- option (Nothing, fst noDocs, []) (interfaceBlock syn) accData acc n (concatMap declared ds) return [PInterface doc syn fc cons' n nfc cs argDocs fds ds cn cd] <?> "interface declaration" where fundeps :: IdrisParser [(Name, FC)] fundeps = do lchar '|'; sepBy name (lchar ',') interfaceKeyword :: IdrisParser () interfaceKeyword = reservedHL "interface" <|> do reservedHL "class" fc <- getFC parserWarning fc Nothing (Msg "The 'class' keyword is deprecated. Use 'interface' instead.") carg :: IdrisParser (Name, FC, PTerm) carg = do lchar '('; (i, ifc) <- name; lchar ':'; ty <- expr syn; lchar ')' return (i, ifc, ty) <|> do (i, ifc) <- name fc <- getFC return (i, ifc, PType fc) {-| Parses an interface implementation declaration @ Implementation ::= DocComment_t? 'implementation' ImplementationName? ConstraintList? Name SimpleExpr* ImplementationBlock? ; @ @ ImplementationName ::= '[' Name ']'; @ -} implementation :: Bool -> SyntaxInfo -> IdrisParser [PDecl] implementation kwopt syn = do ist <- get (doc, argDocs) <- docstring syn (opts, acc) <- fnOpts if kwopt then optional implementationKeyword else do implementationKeyword return (Just ()) fc <- getFC en <- optional implementationName cs <- constraintList syn let cs' = [(c, ty) | (_, c, _, ty) <- cs] (cn, cnfc) <- fnName args <- many (simpleExpr syn) let sc = PApp fc (PRef cnfc [cnfc] cn) (map pexp args) let t = bindList (\r -> PPi constraint { pcount = r }) cs sc pnames <- implementationUsing ds <- implementationBlock syn return [PImplementation doc argDocs syn fc cs' pnames acc opts cn cnfc args [] t en ds] <?> "implementation declaration" where implementationName :: IdrisParser Name implementationName = do lchar '['; n_in <- fst <$> fnName; lchar ']' let n = expandNS syn n_in return n <?> "implementation name" implementationKeyword :: IdrisParser () implementationKeyword = reservedHL "implementation" <|> do reservedHL "instance" fc <- getFC parserWarning fc Nothing (Msg "The 'instance' keyword is deprecated. Use 'implementation' (or omit it) instead.") implementationUsing :: IdrisParser [Name] implementationUsing = do reservedHL "using" ns <- sepBy1 fnName (lchar ',') return (map fst ns) <|> return [] -- | Parse a docstring docstring :: SyntaxInfo -> IdrisParser (Docstring (Either Err PTerm), [(Name,Docstring (Either Err PTerm))]) docstring syn = do (doc, argDocs) <- option noDocs docComment ist <- get let doc' = annotCode (tryFullExpr syn ist) doc argDocs' = [ (n, annotCode (tryFullExpr syn ist) d) | (n, d) <- argDocs ] return (doc', argDocs') {-| Parses a using declaration list @ UsingDeclList ::= UsingDeclList' | NameList TypeSig ; @ @ UsingDeclList' ::= UsingDecl | UsingDecl ',' UsingDeclList' ; @ @ NameList ::= Name | Name ',' NameList ; @ -} usingDeclList :: SyntaxInfo -> IdrisParser [Using] usingDeclList syn = try (sepBy1 (usingDecl syn) (lchar ',')) <|> do ns <- sepBy1 (fst <$> name) (lchar ',') lchar ':' t <- typeExpr (disallowImp syn) return (map (\x -> UImplicit x t) ns) <?> "using declaration list" {-| Parses a using declaration @ UsingDecl ::= FnName TypeSig | FnName FnName+ ; @ -} usingDecl :: SyntaxInfo -> IdrisParser Using usingDecl syn = try (do x <- fst <$> fnName lchar ':' t <- typeExpr (disallowImp syn) return (UImplicit x t)) <|> do c <- fst <$> fnName xs <- many (fst <$> fnName) return (UConstraint c xs) <?> "using declaration" {-| Parse a clause with patterns @ Pattern ::= Clause; @ -} pattern :: SyntaxInfo -> IdrisParser PDecl pattern syn = do fc <- getFC clause <- clause syn return (PClauses fc [] (sMN 2 "_") [clause]) -- collect together later <?> "pattern" {-| Parse a constant applicative form declaration @ CAF ::= 'let' FnName '=' Expr Terminator; @ -} caf :: SyntaxInfo -> IdrisParser PDecl caf syn = do reservedHL "let" n_in <- fst <$> fnName; let n = expandNS syn n_in pushIndent lchar '=' t <- indented $ expr syn terminator fc <- getFC return (PCAF fc n t) <?> "constant applicative form declaration" {-| Parse an argument expression @ ArgExpr ::= HSimpleExpr | {- In Pattern External (User-defined) Expression -}; @ -} argExpr :: SyntaxInfo -> IdrisParser PTerm argExpr syn = let syn' = syn { inPattern = True } in try (hsimpleExpr syn') <|> simpleExternalExpr syn' <?> "argument expression" {-| Parse a right hand side of a function @ RHS ::= '=' Expr | '?=' RHSName? Expr | Impossible ; @ @ RHSName ::= '{' FnName '}'; @ -} rhs :: SyntaxInfo -> Name -> IdrisParser PTerm rhs syn n = do lchar '=' indentPropHolds gtProp expr syn <|> do symbol "?="; fc <- getFC name <- option n' (do symbol "{"; n <- fst <$> fnName; symbol "}"; return n) r <- expr syn return (addLet fc name r) <|> impossible <?> "function right hand side" where mkN :: Name -> Name mkN (UN x) = if (tnull x || not (isAlpha (thead x))) then sUN "infix_op_lemma_1" else sUN (str x++"_lemma_1") mkN (NS x n) = NS (mkN x) n n' :: Name n' = mkN n addLet :: FC -> Name -> PTerm -> PTerm addLet fc nm (PLet fc' n nfc ty val r) = PLet fc' n nfc ty val (addLet fc nm r) addLet fc nm (PCase fc' t cs) = PCase fc' t (map addLetC cs) where addLetC (l, r) = (l, addLet fc nm r) addLet fc nm r = (PLet fc (sUN "value") NoFC Placeholder r (PMetavar NoFC nm)) {-|Parses a function clause @ RHSOrWithBlock ::= RHS WhereOrTerminator | 'with' SimpleExpr OpenBlock FnDecl+ CloseBlock ; @ @ Clause ::= WExpr+ RHSOrWithBlock | SimpleExpr '<==' FnName RHS WhereOrTerminator | ArgExpr Operator ArgExpr WExpr* RHSOrWithBlock {- Except "=" and "?=" operators to avoid ambiguity -} | FnName ConstraintArg* ImplicitOrArgExpr* WExpr* RHSOrWithBlock ; @ @ ImplicitOrArgExpr ::= ImplicitArg | ArgExpr; @ @ WhereOrTerminator ::= WhereBlock | Terminator; @ -} clause :: SyntaxInfo -> IdrisParser PClause clause syn = do wargs <- try (do pushIndent; some (wExpr syn)) fc <- getFC ist <- get n <- case lastParse ist of Just t -> return t Nothing -> fail "Invalid clause" (do r <- rhs syn n let ctxt = tt_ctxt ist let wsyn = syn { syn_namespace = [], syn_toplevel = False } (wheres, nmap) <- choice [do x <- whereBlock n wsyn popIndent return x, do terminator return ([], [])] return $ PClauseR fc wargs r wheres) <|> (do popIndent reservedHL "with" wval <- simpleExpr syn pn <- optProof openBlock ds <- some $ fnDecl syn let withs = concat ds closeBlock return $ PWithR fc wargs wval pn withs) <|> do ty <- try (do pushIndent ty <- simpleExpr syn symbol "<==" return ty) fc <- getFC n_in <- fst <$> fnName; let n = expandNS syn n_in r <- rhs syn n ist <- get let ctxt = tt_ctxt ist let wsyn = syn { syn_namespace = [] } (wheres, nmap) <- choice [do x <- whereBlock n wsyn popIndent return x, do terminator return ([], [])] let capp = PLet fc (sMN 0 "match") NoFC ty (PMatchApp fc n) (PRef fc [] (sMN 0 "match")) ist <- get put (ist { lastParse = Just n }) return $ PClause fc n capp [] r wheres <|> do (l, op, nfc) <- try (do pushIndent l <- argExpr syn (op, nfc) <- operatorFC when (op == "=" || op == "?=" ) $ fail "infix clause definition with \"=\" and \"?=\" not supported " return (l, op, nfc)) let n = expandNS syn (sUN op) r <- argExpr syn fc <- getFC wargs <- many (wExpr syn) (do rs <- rhs syn n let wsyn = syn { syn_namespace = [] } (wheres, nmap) <- choice [do x <- whereBlock n wsyn popIndent return x, do terminator return ([], [])] ist <- get let capp = PApp fc (PRef nfc [nfc] n) [pexp l, pexp r] put (ist { lastParse = Just n }) return $ PClause fc n capp wargs rs wheres) <|> (do popIndent reservedHL "with" wval <- bracketed syn pn <- optProof openBlock ds <- some $ fnDecl syn closeBlock ist <- get let capp = PApp fc (PRef fc [] n) [pexp l, pexp r] let withs = map (fillLHSD n capp wargs) $ concat ds put (ist { lastParse = Just n }) return $ PWith fc n capp wargs wval pn withs) <|> do pushIndent (n_in, nfc) <- fnName; let n = expandNS syn n_in fc <- getFC args <- many (try (implicitArg (syn { inPattern = True } )) <|> try (constraintArg (syn { inPattern = True })) <|> (fmap pexp (argExpr syn))) wargs <- many (wExpr syn) let capp = PApp fc (PRef nfc [nfc] n) args (do r <- rhs syn n ist <- get let ctxt = tt_ctxt ist let wsyn = syn { syn_namespace = [] } (wheres, nmap) <- choice [do x <- whereBlock n wsyn popIndent return x, do terminator return ([], [])] ist <- get put (ist { lastParse = Just n }) return $ PClause fc n capp wargs r wheres) <|> (do reservedHL "with" ist <- get put (ist { lastParse = Just n }) wval <- bracketed syn pn <- optProof openBlock ds <- some $ fnDecl syn let withs = map (fillLHSD n capp wargs) $ concat ds closeBlock popIndent return $ PWith fc n capp wargs wval pn withs) <?> "function clause" where optProof = option Nothing (do reservedHL "proof" n <- fnName return (Just n)) fillLHS :: Name -> PTerm -> [PTerm] -> PClause -> PClause fillLHS n capp owargs (PClauseR fc wargs v ws) = PClause fc n capp (owargs ++ wargs) v ws fillLHS n capp owargs (PWithR fc wargs v pn ws) = PWith fc n capp (owargs ++ wargs) v pn (map (fillLHSD n capp (owargs ++ wargs)) ws) fillLHS _ _ _ c = c fillLHSD :: Name -> PTerm -> [PTerm] -> PDecl -> PDecl fillLHSD n c a (PClauses fc o fn cs) = PClauses fc o fn (map (fillLHS n c a) cs) fillLHSD n c a x = x {-| Parses with pattern @ WExpr ::= '|' Expr'; @ -} wExpr :: SyntaxInfo -> IdrisParser PTerm wExpr syn = do lchar '|' expr' (syn { inPattern = True }) <?> "with pattern" {-| Parses a where block @ WhereBlock ::= 'where' OpenBlock Decl+ CloseBlock; @ -} whereBlock :: Name -> SyntaxInfo -> IdrisParser ([PDecl], [(Name, Name)]) whereBlock n syn = do reservedHL "where" ds <- indentedBlock1 (decl syn) let dns = concatMap (concatMap declared) ds return (concat ds, map (\x -> (x, decoration syn x)) dns) <?> "where block" {-|Parses a code generation target language name @ Codegen ::= 'C' | 'Java' | 'JavaScript' | 'Node' | 'LLVM' | 'Bytecode' ; @ -} codegen_ :: IdrisParser Codegen codegen_ = do n <- fst <$> identifier return (Via IBCFormat (map toLower n)) <|> do reserved "Bytecode"; return Bytecode <?> "code generation language" {-|Parses a compiler directive @ StringList ::= String | String ',' StringList ; @ @ Directive ::= '%' Directive'; @ @ Directive' ::= 'lib' CodeGen String_t | 'link' CodeGen String_t | 'flag' CodeGen String_t | 'include' CodeGen String_t | 'hide' Name | 'freeze' Name | 'thaw' Name | 'access' Accessibility | 'default' Totality | 'logging' Natural | 'dynamic' StringList | 'name' Name NameList | 'error_handlers' Name NameList | 'language' 'TypeProviders' | 'language' 'ErrorReflection' | 'deprecated' Name String | 'fragile' Name Reason ; @ -} directive :: SyntaxInfo -> IdrisParser [PDecl] directive syn = do try (lchar '%' *> reserved "lib") cgn <- codegen_ lib <- fmap fst stringLiteral return [PDirective (DLib cgn lib)] <|> do try (lchar '%' *> reserved "link") cgn <- codegen_; obj <- fst <$> stringLiteral return [PDirective (DLink cgn obj)] <|> do try (lchar '%' *> reserved "flag") cgn <- codegen_; flag <- fst <$> stringLiteral return [PDirective (DFlag cgn flag)] <|> do try (lchar '%' *> reserved "include") cgn <- codegen_ hdr <- fst <$> stringLiteral return [PDirective (DInclude cgn hdr)] <|> do try (lchar '%' *> reserved "hide"); n <- fst <$> fnName return [PDirective (DHide n)] <|> do try (lchar '%' *> reserved "freeze"); n <- fst <$> iName [] return [PDirective (DFreeze n)] <|> do try (lchar '%' *> reserved "thaw"); n <- fst <$> iName [] return [PDirective (DThaw n)] -- injectivity assertins are intended for debugging purposes -- only, and won't be documented/could be removed at any point <|> do try (lchar '%' *> reserved "assert_injective"); n <- fst <$> fnName return [PDirective (DInjective n)] -- Assert totality of something after definition. This is -- here as a debugging aid, so commented out... -- <|> do try (lchar '%' *> reserved "assert_set_total"); n <- fst <$> fnName -- return [PDirective (DSetTotal n)] <|> do try (lchar '%' *> reserved "access") acc <- accessibility ist <- get put ist { default_access = acc } return [PDirective (DAccess acc)] <|> do try (lchar '%' *> reserved "default"); tot <- totality i <- get put (i { default_total = tot } ) return [PDirective (DDefault tot)] <|> do try (lchar '%' *> reserved "logging") i <- fst <$> natural return [PDirective (DLogging i)] <|> do try (lchar '%' *> reserved "dynamic") libs <- sepBy1 (fmap fst stringLiteral) (lchar ',') return [PDirective (DDynamicLibs libs)] <|> do try (lchar '%' *> reserved "name") (ty, tyFC) <- fnName ns <- sepBy1 name (lchar ',') return [PDirective (DNameHint ty tyFC ns)] <|> do try (lchar '%' *> reserved "error_handlers") (fn, nfc) <- fnName (arg, afc) <- fnName ns <- sepBy1 name (lchar ',') return [PDirective (DErrorHandlers fn nfc arg afc ns) ] <|> do try (lchar '%' *> reserved "language"); ext <- pLangExt; return [PDirective (DLanguage ext)] <|> do try (lchar '%' *> reserved "deprecate") n <- fst <$> fnName alt <- option "" (fst <$> stringLiteral) return [PDirective (DDeprecate n alt)] <|> do try (lchar '%' *> reserved "fragile") n <- fst <$> fnName alt <- option "" (fst <$> stringLiteral) return [PDirective (DFragile n alt)] <|> do fc <- getFC try (lchar '%' *> reserved "used") fn <- fst <$> fnName arg <- fst <$> iName [] return [PDirective (DUsed fc fn arg)] <|> do try (lchar '%' *> reserved "auto_implicits") b <- on_off return [PDirective (DAutoImplicits b)] <?> "directive" where on_off = do reserved "on"; return True <|> do reserved "off"; return False pLangExt :: IdrisParser LanguageExt pLangExt = (reserved "TypeProviders" >> return TypeProviders) <|> (reserved "ErrorReflection" >> return ErrorReflection) <|> (reserved "UniquenessTypes" >> return UniquenessTypes) <|> (reserved "LinearTypes" >> return LinearTypes) <|> (reserved "DSLNotation" >> return DSLNotation) <|> (reserved "ElabReflection" >> return ElabReflection) <|> (reserved "FirstClassReflection" >> return FCReflection) {-| Parses a totality @ Totality ::= 'partial' | 'total' | 'covering' @ -} totality :: IdrisParser DefaultTotality totality = do reservedHL "total"; return DefaultCheckingTotal <|> do reservedHL "partial"; return DefaultCheckingPartial <|> do reservedHL "covering"; return DefaultCheckingCovering {-| Parses a type provider @ Provider ::= DocComment_t? '%' 'provide' Provider_What? '(' FnName TypeSig ')' 'with' Expr; ProviderWhat ::= 'proof' | 'term' | 'type' | 'postulate' @ -} provider :: SyntaxInfo -> IdrisParser [PDecl] provider syn = do doc <- try (do (doc, _) <- docstring syn fc1 <- getFC lchar '%' fc2 <- reservedFC "provide" highlightP (spanFC fc1 fc2) AnnKeyword return doc) provideTerm doc <|> providePostulate doc <?> "type provider" where provideTerm doc = do lchar '('; (n, nfc) <- fnName; lchar ':'; t <- typeExpr syn; lchar ')' fc <- getFC reservedHL "with" e <- expr syn <?> "provider expression" return [PProvider doc syn fc nfc (ProvTerm t e) n] providePostulate doc = do reservedHL "postulate" (n, nfc) <- fnName fc <- getFC reservedHL "with" e <- expr syn <?> "provider expression" return [PProvider doc syn fc nfc (ProvPostulate e) n] {-| Parses a transform @ Transform ::= '%' 'transform' Expr '==>' Expr @ -} transform :: SyntaxInfo -> IdrisParser [PDecl] transform syn = do try (lchar '%' *> reserved "transform") -- leave it unchecked, until we work out what this should -- actually mean... -- safety <- option True (do reserved "unsafe" -- return False) l <- expr syn fc <- getFC symbol "==>" r <- expr syn return [PTransform fc False l r] <?> "transform" {-| Parses a top-level reflected elaborator script @ RunElabDecl ::= '%' 'runElab' Expr @ -} runElabDecl :: SyntaxInfo -> IdrisParser PDecl runElabDecl syn = do kwFC <- try (do fc <- getFC lchar '%' fc' <- reservedFC "runElab" return (spanFC fc fc')) script <- expr syn <?> "elaborator script" highlightP kwFC AnnKeyword return $ PRunElabDecl kwFC script (syn_namespace syn) <?> "top-level elaborator script" {- * Loading and parsing -} {-| Parses an expression from input -} parseExpr :: IState -> String -> Result PTerm parseExpr st = runparser (fullExpr defaultSyntax) st "(input)" {-| Parses a constant form input -} parseConst :: IState -> String -> Result Const parseConst st = runparser (fmap fst constant) st "(input)" {-| Parses a tactic from input -} parseTactic :: IState -> String -> Result PTactic parseTactic st = runparser (fullTactic defaultSyntax) st "(input)" {-| Parses a do-step from input (used in the elab shell) -} parseElabShellStep :: IState -> String -> Result (Either ElabShellCmd PDo) parseElabShellStep ist = runparser (fmap Right (do_ defaultSyntax) <|> fmap Left elabShellCmd) ist "(input)" where elabShellCmd = char ':' >> (reserved "qed" >> pure EQED ) <|> (reserved "abandon" >> pure EAbandon ) <|> (reserved "undo" >> pure EUndo ) <|> (reserved "state" >> pure EProofState) <|> (reserved "term" >> pure EProofTerm ) <|> (expressionTactic ["e", "eval"] EEval ) <|> (expressionTactic ["t", "type"] ECheck) <|> (expressionTactic ["search"] ESearch ) <|> (do reserved "doc" doc <- (Right . fst <$> constant) <|> (Left . fst <$> fnName) eof return (EDocStr doc)) <?> "elab command" expressionTactic cmds tactic = do asum (map reserved cmds) t <- spaced (expr defaultSyntax) i <- get return $ tactic (desugar defaultSyntax i t) spaced parser = indentPropHolds gtProp *> parser -- | Parse module header and imports parseImports :: FilePath -> String -> Idris (Maybe (Docstring ()), [String], [ImportInfo], Maybe Delta) parseImports fname input = do i <- getIState case parseString (runInnerParser (evalStateT imports i)) (Directed (UTF8.fromString fname) 0 0 0 0) input of Failure (ErrInfo err _) -> fail (show err) Success (x, annots, i) -> do putIState i fname' <- runIO $ Dir.makeAbsolute fname sendHighlighting $ addPath annots fname' return x where imports :: IdrisParser ((Maybe (Docstring ()), [String], [ImportInfo], Maybe Delta), [(FC, OutputAnnotation)], IState) imports = do optional shebang whiteSpace (mdoc, mname, annots) <- moduleHeader ps_exp <- many import_ mrk <- mark isEof <- lookAheadMatches eof let mrk' = if isEof then Nothing else Just mrk i <- get -- add Builtins and Prelude, unless options say -- not to let ps = ps_exp -- imp "Builtins" : imp "Prelude" : ps_exp return ((mdoc, mname, ps, mrk'), annots, i) imp m = ImportInfo False (toPath m) Nothing [] NoFC NoFC ns = Spl.splitOn "." toPath = foldl1' (</>) . ns addPath :: [(FC, OutputAnnotation)] -> FilePath -> [(FC, OutputAnnotation)] addPath [] _ = [] addPath ((fc, AnnNamespace ns Nothing) : annots) path = (fc, AnnNamespace ns (Just path)) : addPath annots path addPath (annot:annots) path = annot : addPath annots path shebang :: IdrisParser () shebang = string "#!" *> many (satisfy $ not . isEol) *> eol *> pure () -- | There should be a better way of doing this... findFC :: Doc -> (FC, String) findFC x = let s = show (plain x) in findFC' s where findFC' s = case span (/= ':') s of -- Horrid kludge to prevent crashes on Windows (prefix, ':':'\\':rest) -> case findFC' rest of (NoFC, msg) -> (NoFC, msg) (FileFC f, msg) -> (FileFC (prefix ++ ":\\" ++ f), msg) (FC f start end, msg) -> (FC (prefix ++ ":\\" ++ f) start end, msg) (failname, ':':rest) -> case span isDigit rest of (line, ':':rest') -> case span isDigit rest' of (col, ':':msg) -> let pos = (read line, read col) in (FC failname pos pos, msg) -- | Check if the coloring matches the options and corrects if necessary fixColour :: Bool -> ANSI.Doc -> ANSI.Doc fixColour False doc = ANSI.plain doc fixColour True doc = doc -- | A program is a list of declarations, possibly with associated -- documentation strings. parseProg :: SyntaxInfo -> FilePath -> String -> Maybe Delta -> Idris [PDecl] parseProg syn fname input mrk = do i <- getIState case runparser mainProg i fname input of Failure (ErrInfo doc _) -> do -- FIXME: Get error location from trifecta -- this can't be the solution! -- Issue #1575 on the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1575 let (fc, msg) = findFC doc i <- getIState case idris_outputmode i of RawOutput h -> iputStrLn (show $ fixColour (idris_colourRepl i) doc) IdeMode n h -> iWarn fc (P.text msg) putIState (i { errSpan = Just fc }) return [] Success (x, i) -> do putIState i reportParserWarnings return $ collect x where mainProg :: IdrisParser ([PDecl], IState) mainProg = case mrk of Nothing -> do i <- get; return ([], i) Just mrk -> do release mrk ds <- prog syn i' <- get return (ds, i') {-| Load idris module and show error if something wrong happens -} loadModule :: FilePath -> IBCPhase -> Idris (Maybe String) loadModule f phase = idrisCatch (loadModule' f phase) (\e -> do setErrSpan (getErrSpan e) ist <- getIState iWarn (getErrSpan e) $ pprintErr ist e return Nothing) {-| Load idris module -} loadModule' :: FilePath -> IBCPhase -> Idris (Maybe String) loadModule' f phase = do i <- getIState let file = takeWhile (/= ' ') f ibcsd <- valIBCSubDir i ids <- allImportDirs fp <- findImport ids ibcsd file if file `elem` imported i then do logParser 1 $ "Already read " ++ file return Nothing else do putIState (i { imported = file : imported i }) case fp of IDR fn -> loadSource False fn Nothing LIDR fn -> loadSource True fn Nothing IBC fn src -> idrisCatch (loadIBC True phase fn) (\c -> do logParser 1 $ fn ++ " failed " ++ pshow i c case src of IDR sfn -> loadSource False sfn Nothing LIDR sfn -> loadSource True sfn Nothing) return $ Just file {-| Load idris code from file -} loadFromIFile :: Bool -> IBCPhase -> IFileType -> Maybe Int -> Idris () loadFromIFile reexp phase i@(IBC fn src) maxline = do logParser 1 $ "Skipping " ++ getSrcFile i idrisCatch (loadIBC reexp phase fn) (\err -> ierror $ LoadingFailed fn err) where getSrcFile (IDR fn) = fn getSrcFile (LIDR fn) = fn getSrcFile (IBC f src) = getSrcFile src loadFromIFile _ _ (IDR fn) maxline = loadSource' False fn maxline loadFromIFile _ _ (LIDR fn) maxline = loadSource' True fn maxline {-| Load idris source code and show error if something wrong happens -} loadSource' :: Bool -> FilePath -> Maybe Int -> Idris () loadSource' lidr r maxline = idrisCatch (loadSource lidr r maxline) (\e -> do setErrSpan (getErrSpan e) ist <- getIState case e of At f e' -> iWarn f (pprintErr ist e') _ -> iWarn (getErrSpan e) (pprintErr ist e)) {-| Load Idris source code-} loadSource :: Bool -> FilePath -> Maybe Int -> Idris () loadSource lidr f toline = do logParser 1 ("Reading " ++ f) iReport 2 ("Reading " ++ f) i <- getIState let def_total = default_total i file_in <- runIO $ readSource f file <- if lidr then tclift $ unlit f file_in else return file_in (mdocs, mname, imports_in, pos) <- parseImports f file ai <- getAutoImports let imports = map (\n -> ImportInfo True n Nothing [] NoFC NoFC) ai ++ imports_in ids <- allImportDirs ibcsd <- valIBCSubDir i mapM_ (\(re, f, ns, nfc) -> do fp <- findImport ids ibcsd f case fp of LIDR fn -> ifail $ "No ibc for " ++ f IDR fn -> ifail $ "No ibc for " ++ f IBC fn src -> do loadIBC True IBC_Building fn let srcFn = case src of IDR fn -> Just fn LIDR fn -> Just fn _ -> Nothing srcFnAbs <- case srcFn of Just fn -> fmap Just (runIO $ Dir.makeAbsolute fn) Nothing -> return Nothing sendHighlighting [(nfc, AnnNamespace ns srcFnAbs)]) [(re, fn, ns, nfc) | ImportInfo re fn _ ns _ nfc <- imports] reportParserWarnings sendParserHighlighting -- process and check module aliases let modAliases = M.fromList [ (prep alias, prep realName) | ImportInfo { import_reexport = reexport , import_path = realName , import_rename = Just (alias, _) , import_location = fc } <- imports ] prep = map T.pack . reverse . Spl.splitOn [pathSeparator] aliasNames = [ (alias, fc) | ImportInfo { import_rename = Just (alias, _) , import_location = fc } <- imports ] histogram = groupBy ((==) `on` fst) . sortBy (comparing fst) $ aliasNames case map head . filter ((/= 1) . length) $ histogram of [] -> logParser 3 $ "Module aliases: " ++ show (M.toList modAliases) (n,fc):_ -> throwError . At fc . Msg $ "import alias not unique: " ++ show n i <- getIState putIState (i { default_access = Private, module_aliases = modAliases }) clearIBC -- start a new .ibc file -- record package info in .ibc imps <- allImportDirs mapM_ addIBC (map IBCImportDir imps) mapM_ (addIBC . IBCImport) [ (reexport, realName) | ImportInfo { import_reexport = reexport , import_path = realName } <- imports ] let syntax = defaultSyntax{ syn_namespace = reverse mname, maxline = toline } ist <- getIState -- Save the span from parsing the module header, because -- an empty program parse might obliterate it. let oldSpan = idris_parsedSpan ist ds' <- parseProg syntax f file pos case (ds', oldSpan) of ([], Just fc) -> -- If no program elements were parsed, we dind't -- get a loaded region in the IBC file. That -- means we need to add it back. do ist <- getIState putIState ist { idris_parsedSpan = oldSpan , ibc_write = IBCParsedRegion fc : ibc_write ist } _ -> return () sendParserHighlighting -- Parsing done, now process declarations let ds = namespaces mname ds' logParser 3 (show $ showDecls verbosePPOption ds) i <- getIState logLvl 10 (show (toAlist (idris_implicits i))) logLvl 3 (show (idris_infixes i)) -- Now add all the declarations to the context iReport 1 $ "Type checking " ++ f -- we totality check after every Mutual block, so if -- anything is a single definition, wrap it in a -- mutual block on its own elabDecls (toplevelWith f) (map toMutual ds) i <- getIState -- simplify every definition do give the totality checker -- a better chance mapM_ (\n -> do logLvl 5 $ "Simplifying " ++ show n ctxt' <- do ctxt <- getContext tclift $ simplifyCasedef n [] [] (getErasureInfo i) ctxt setContext ctxt') (map snd (idris_totcheck i)) -- build size change graph from simplified definitions iReport 3 $ "Totality checking " ++ f logLvl 1 $ "Totality checking " ++ f i <- getIState mapM_ buildSCG (idris_totcheck i) mapM_ checkDeclTotality (idris_totcheck i) mapM_ verifyTotality (idris_totcheck i) -- Redo totality check for deferred names let deftots = idris_defertotcheck i logLvl 2 $ "Totality checking " ++ show deftots mapM_ (\x -> do tot <- getTotality x case tot of Total _ -> do let opts = case lookupCtxtExact x (idris_flags i) of Just os -> os Nothing -> [] when (AssertTotal `notElem` opts) $ setTotality x Unchecked _ -> return ()) (map snd deftots) mapM_ buildSCG deftots mapM_ checkDeclTotality deftots logLvl 1 ("Finished " ++ f) ibcsd <- valIBCSubDir i logLvl 1 $ "Universe checking " ++ f iReport 3 $ "Universe checking " ++ f iucheck let ibc = ibcPathNoFallback ibcsd f i <- getIState addHides (hide_list i) -- Save module documentation if applicable i <- getIState case mdocs of Nothing -> return () Just docs -> addModDoc syntax mname docs -- Finally, write an ibc and highlights if checking was successful ok <- noErrors when ok $ do idrisCatch (do writeIBC f ibc; clearIBC) (\c -> return ()) -- failure is harmless hl <- getDumpHighlighting when hl $ idrisCatch (writeHighlights f) (const $ return ()) -- failure is harmless clearHighlights i <- getIState putIState (i { default_total = def_total, hide_list = emptyContext }) return () where namespaces :: [String] -> [PDecl] -> [PDecl] namespaces [] ds = ds namespaces (x:xs) ds = [PNamespace x NoFC (namespaces xs ds)] toMutual :: PDecl -> PDecl toMutual m@(PMutual _ d) = m toMutual (PNamespace x fc ds) = PNamespace x fc (map toMutual ds) toMutual x = let r = PMutual (fileFC "single mutual") [x] in case x of PClauses{} -> r PInterface{} -> r PData{} -> r PImplementation{} -> r _ -> x addModDoc :: SyntaxInfo -> [String] -> Docstring () -> Idris () addModDoc syn mname docs = do ist <- getIState docs' <- elabDocTerms (toplevelWith f) (parsedDocs ist) let modDocs' = addDef docName docs' (idris_moduledocs ist) putIState ist { idris_moduledocs = modDocs' } addIBC (IBCModDocs docName) where docName = NS modDocName (map T.pack (reverse mname)) parsedDocs ist = annotCode (tryFullExpr syn ist) docs {-| Adds names to hide list -} addHides :: Ctxt Accessibility -> Idris () addHides xs = do i <- getIState let defh = default_access i mapM_ doHide (toAlist xs) where doHide (n, a) = do setAccessibility n a addIBC (IBCAccess n a)
Heather/Idris-dev
src/Idris/Parser.hs
Haskell
bsd-3-clause
73,853
{-# LANGUAGE Haskell2010 #-} {-# LINE 1 "Network/Sendfile/Types.hs" #-} module Network.Sendfile.Types where -- | -- File range for 'sendfile'. data FileRange = EntireFile | PartOfFile { rangeOffset :: Integer , rangeLength :: Integer }
phischu/fragnix
tests/packages/scotty/Network.Sendfile.Types.hs
Haskell
bsd-3-clause
307
{-# LANGUAGE OverloadedStrings #-} module Rede.SimpleHTTP1Response(exampleHTTP11Response, exampleHTTP20Response, shortResponse) where import qualified Data.ByteString as B -- Just to check what a browser thinks about this port exampleHTTP11Response :: B.ByteString exampleHTTP11Response = "HTTP/1.1 200 OK\r\n\ \Content-Length: 1418\r\n\ \Keep-Alive: timeout=5, max=100\r\n\ \Content-Type: text/html\r\n\ \\r\n\ \<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\r\n\ \<HTML>\r\n\ \ <HEAD>\r\n\ \ <TITLE> [Haskell-cafe] multiline strings in haskell?\r\n\ \ </TITLE>\r\n\ \ <LINK REL=\"Index\" HREF=\"index.html\" >\r\n\ \ <LINK REL=\"made\" HREF=\"mailto:haskell-cafe%40haskell.org?Subject=%5BHaskell-cafe%5D%20multiline%20strings%20in%20haskell%3F&In-Reply-To=Pine.LNX.4.44.0601121646300.23112-100000%40peano.math.uni-bremen.de\">\r\n\ \ <META NAME=\"robots\" CONTENT=\"index,nofollow\">\r\n\ \ <META http-equiv=\"Content-Type\" content=\"text/html; charset=us-ascii\">\r\n\ \ <LINK REL=\"Previous\" HREF=\"013910.html\">\r\n\ \ <LINK REL=\"Next\" HREF=\"013901.html\">\r\n\ \ </HEAD>\r\n\ \ <BODY BGCOLOR=\"#ffffff\">\r\n\ \ <H1>[Haskell-cafe] multiline strings in haskell?</H1>\r\n\ \ <B>Sebastian Sylvan</B> \r\n\ \ <A HREF=\"mailto:haskell-cafe%40haskell.org?Subject=%5BHaskell-cafe%5D%20multiline%20strings%20in%20haskell%3F&In-Reply-To=Pine.LNX.4.44.0601121646300.23112-100000%40peano.math.uni-bremen.de\"\r\n\ \ TITLE=\"[Haskell-cafe] multiline strings in haskell?\">sebastian.sylvan at gmail.com\r\n\ \ </A><BR>\r\n\ \ <I>Thu Jan 12 11:04:43 EST 2006</I>\r\n\ \ <P><UL>\r\n\ \ <LI>Previous message: <A HREF=\"013910.html\">[Haskell-cafe] multiline strings in haskell?\r\n\ \</A></li>\r\n\ \ <LI>Next message: <A HREF=\"013901.html\">[Haskell-cafe] multiline strings in haskell?\r\n\ \</A></li>\r\n\ \ <LI> <B>Messages sorted by:</B> \r\n\ \ <a href=\"date.html#13911\">[ date ]</a>\r\n\ \ <a href=\"thread.html#13911\">[ thread ]</a>\r\n\ \ <a href=\"subject.html#13911\">[ subject ]</a>\r\n\ \ <a href=\"author.html#13911\">[ author ]</a>\r\n\ \ </LI>\r\n\ \ </UL>\r\n\ \ <HR> \r\n\ \<!--beginarticle-->\r\n\ \<PRE>On 1/12/06, Henning Thielemann &lt;<A HREF=\"http://www.haskell.org/mailman/listinfo/haskell-cafe\">lemming at henning-thielemann.de</A>&gt; wrote:\r\n\ \&gt;<i>\r\n\ \</I>&gt;<i> On Thu, 12 Jan 2006, Jason Dagit wrote:\r\n\ \</I>&gt;<i>\r\n\ \</I>&gt;<i> &gt; On Jan 12, 2006, at 1:34 AM, Henning Thielemann wrote:\r\n\ \</I>&gt;<i> &gt;\r\n\ \</I>&gt;<i> &gt; &gt; On Wed, 11 Jan 2006, Michael Vanier wrote:\r\n\ \</I>&gt;<i> &gt; &gt;\r\n\ \</I>&gt;<i> &gt; &gt;&gt; Is there any support for multi-line string literals in Haskell? I've\r\n\ \</I>&gt;<i> &gt; &gt;&gt; done a web search and come up empty. I'm thinking of using\r\n\ \</I>&gt;<i> &gt; &gt;&gt; Haskell to\r\n\ \</I>&gt;<i> &gt; &gt;&gt; generate web pages and having multi-line strings would be very\r\n\ \</I>&gt;<i> &gt; &gt;&gt; useful.\r\n\ \</I>&gt;<i> &gt; &gt;\r\n\ \</I>&gt;<i> &gt; &gt; Do you mean\r\n\ \</I>&gt;<i> &gt; &gt;\r\n\ \</I>&gt;<i> &gt; &gt; unlines [&quot;first line&quot;, &quot;second line&quot;, &quot;third line&quot;]\r\n\ \</I>&gt;<i> &gt;\r\n\ \</I>&gt;<i> &gt; The original poster probably meant something like this:\r\n\ \</I>&gt;<i> &gt;\r\n\ \</I>&gt;<i> &gt; let foo = &quot;This is a\r\n\ \</I>&gt;<i> &gt; long string\r\n\ \</I>&gt;<i> &gt;\r\n\ \</I>&gt;<i> &gt;\r\n\ \</I>&gt;<i> &gt; Which does not end until the matching end quote.&quot;\r\n\ \</I>&gt;<i>\r\n\ \</I>&gt;<i> I don't see the need for it, since\r\n\ \</I>&gt;<i>\r\n\ \</I>&gt;<i> unlines [\r\n\ \</I>&gt;<i> &quot;first line&quot;,\r\n\ \</I>&gt;<i> &quot;second line&quot;,\r\n\ \</I>&gt;<i> &quot;third line&quot;]\r\n\ \</I>&gt;<i>\r\n\ \</I>&gt;<i> works as well.\r\n\ \</I>&gt;<i>\r\n\ \</I>\r\n\ \Nevertheless Haskell supports multiline strings (although it seems\r\n\ \like a lot of people don't know about it). You escape it using and\r\n\ \then another where the string starts again.\r\n\ \\r\n\ \str = &quot;multi \r\n\ \ \\line&quot; \r\n\ \\r\n\ \Prelude&gt;str\r\n\ \&quot;multiline&quot;\r\n\ \\r\n\ \\r\n\ \/S\r\n\ \\r\n\ \--\r\n\ \Sebastian Sylvan\r\n\ \+46(0)736-818655\r\n\ \UIN: 44640862\r\n\ \</PRE>\r\n\ \\r\n\ \\r\n\ \\r\n\ \\r\n\ \\r\n\ \\r\n\ \\r\n\ \\r\n\ \\r\n\ \\r\n\ \\r\n\ \<!--endarticle-->\r\n\ \ <HR>\r\n\ \ <P><UL>\r\n\ \ <!--threads-->\r\n\ \<a href=\"http://www.haskell.org/mailman/listinfo/haskell-cafe\">More information about the Haskell-Cafe\r\n\ \mailing list</a><br>\r\n\ \</body></html>\r\n\ \\r\n" exampleHTTP20Response :: B.ByteString exampleHTTP20Response = "\ \<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\r\n\ \<HTML>\r\n\ \ <HEAD>\r\n\ \ <TITLE> [Haskell-cafe] multiline strings in haskell?\r\n\ \ </TITLE>\r\n\ \ <LINK REL=\"Index\" HREF=\"index.html\" >\r\n\ \ <LINK REL=\"made\" HREF=\"mailto:haskell-cafe%40haskell.org?Subject=%5BHaskell-cafe%5D%20multiline%20strings%20in%20haskell%3F&In-Reply-To=Pine.LNX.4.44.0601121646300.23112-100000%40peano.math.uni-bremen.de\">\r\n\ \ <META NAME=\"robots\" CONTENT=\"index,nofollow\">\r\n\ \ <META http-equiv=\"Content-Type\" content=\"text/html; charset=us-ascii\">\r\n\ \ <LINK REL=\"Previous\" HREF=\"013910.html\">\r\n\ \ <LINK REL=\"Next\" HREF=\"013901.html\">\r\n\ \ </HEAD>\r\n\ \ <BODY BGCOLOR=\"#ffffff\">\r\n\ \ <H1>[Haskell-cafe] multiline strings in haskell?</H1>\r\n\ \ <B>Sebastian Sylvan</B> \r\n\ \ <A HREF=\"mailto:haskell-cafe%40haskell.org?Subject=%5BHaskell-cafe%5D%20multiline%20strings%20in%20haskell%3F&In-Reply-To=Pine.LNX.4.44.0601121646300.23112-100000%40peano.math.uni-bremen.de\"\r\n\ \ TITLE=\"[Haskell-cafe] multiline strings in haskell?\">sebastian.sylvan at gmail.com\r\n\ \ </A><BR>\r\n\ \ <I>Thu Jan 12 11:04:43 EST 2006</I>\r\n\ \ <P><UL>\r\n\ \ <LI>Previous message: <A HREF=\"013910.html\">[Haskell-cafe] multiline strings in haskell?\r\n\ \</A></li>\r\n\ \ <LI>Next message: <A HREF=\"013901.html\">[Haskell-cafe] multiline strings in haskell?\r\n\ \</A></li>\r\n\ \ <LI> <B>Messages sorted by:</B> \r\n\ \ <a href=\"date.html#13911\">[ date ]</a>\r\n\ \ <a href=\"thread.html#13911\">[ thread ]</a>\r\n\ \ <a href=\"subject.html#13911\">[ subject ]</a>\r\n\ \ <a href=\"author.html#13911\">[ author ]</a>\r\n\ \ </LI>\r\n\ \ </UL>\r\n\ \ <HR> \r\n\ \<!--beginarticle-->\r\n\ \<PRE>On 1/12/06, Henning Thielemann &lt;<A HREF=\"http://www.haskell.org/mailman/listinfo/haskell-cafe\">lemming at henning-thielemann.de</A>&gt; wrote:\r\n\ \&gt;<i>\r\n\ \</I>&gt;<i> On Thu, 12 Jan 2006, Jason Dagit wrote:\r\n\ \</I>&gt;<i>\r\n\ \</I>&gt;<i> &gt; On Jan 12, 2006, at 1:34 AM, Henning Thielemann wrote:\r\n\ \</I>&gt;<i> &gt;\r\n\ \</I>&gt;<i> &gt; &gt; On Wed, 11 Jan 2006, Michael Vanier wrote:\r\n\ \</I>&gt;<i> &gt; &gt;\r\n\ \</I>&gt;<i> &gt; &gt;&gt; Is there any support for multi-line string literals in Haskell? I've\r\n\ \</I>&gt;<i> &gt; &gt;&gt; done a web search and come up empty. I'm thinking of using\r\n\ \</I>&gt;<i> &gt; &gt;&gt; Haskell to\r\n\ \</I>&gt;<i> &gt; &gt;&gt; generate web pages and having multi-line strings would be very\r\n\ \</I>&gt;<i> &gt; &gt;&gt; useful.\r\n\ \</I>&gt;<i> &gt; &gt;\r\n\ \</I>&gt;<i> &gt; &gt; Do you mean\r\n\ \</I>&gt;<i> &gt; &gt;\r\n\ \</I>&gt;<i> &gt; &gt; unlines [&quot;first line&quot;, &quot;second line&quot;, &quot;third line&quot;]\r\n\ \</I>&gt;<i> &gt;\r\n\ \</I>&gt;<i> &gt; The original poster probably meant something like this:\r\n\ \</I>&gt;<i> &gt;\r\n\ \</I>&gt;<i> &gt; let foo = &quot;This is a\r\n\ \</I>&gt;<i> &gt; long string\r\n\ \</I>&gt;<i> &gt;\r\n\ \</I>&gt;<i> &gt;\r\n\ \</I>&gt;<i> &gt; Which does not end until the matching end quote.&quot;\r\n\ \</I>&gt;<i>\r\n\ \</I>&gt;<i> I don't see the need for it, since\r\n\ \</I>&gt;<i>\r\n\ \</I>&gt;<i> unlines [\r\n\ \</I>&gt;<i> &quot;first line&quot;,\r\n\ \</I>&gt;<i> &quot;second line&quot;,\r\n\ \</I>&gt;<i> &quot;third line&quot;]\r\n\ \</I>&gt;<i>\r\n\ \</I>&gt;<i> works as well.\r\n\ \</I>&gt;<i>\r\n\ \</I>\r\n\ \Nevertheless Haskell supports multiline strings (although it seems\r\n\ \like a lot of people don't know about it). You escape it using and\r\n\ \then another where the string starts again.\r\n\ \\r\n\ \str = &quot;multi \r\n\ \ \\line&quot; \r\n\ \\r\n\ \Prelude&gt;str\r\n\ \&quot;multiline&quot;\r\n\ \\r\n\ \\r\n\ \/S\r\n\ \\r\n\ \--\r\n\ \Sebastian Sylvan\r\n\ \+46(0)736-818655\r\n\ \UIN: 44640862\r\n\ \</PRE>\r\n\ \\r\n\ \\r\n\ \\r\n\ \\r\n\ \\r\n\ \\r\n\ \\r\n\ \\r\n\ \\r\n\ \\r\n\ \\r\n\ \<!--endarticle-->\r\n\ \ <HR>\r\n\ \ <P><UL>\r\n\ \ <!--threads-->\r\n\ \<a href=\"http://www.haskell.org/mailman/listinfo/haskell-cafe\">More information about the Haskell-Cafe\r\n\ \mailing list</a><br>\r\n\ \</body></html>\r\n\ \\r\n" shortResponse :: B.ByteString shortResponse = "<html><head>hello world!</head></html>\ \"
alcidesv/ReH
hs-src/Rede/SimpleHTTP1Response.hs
Haskell
bsd-3-clause
9,171
-- | -- Module : Network.SimpleIRC -- Copyright : (c) Dominik Picheta 2010 -- License : BSD3 -- -- Maintainer : morfeusz8@gmail.com -- Stability : Alpha -- Portability : portable -- -- Simple and efficient IRC Library -- module Network.SimpleIRC ( -- * Core module Network.SimpleIRC.Core -- * Messages , module Network.SimpleIRC.Messages ) where import Network.SimpleIRC.Core import Network.SimpleIRC.Messages
edwtjo/SimpleIRC
Network/SimpleIRC.hs
Haskell
bsd-3-clause
430
<?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="ru-RU"> <title>&gt;Запуск приложений | ZAP-расширения </title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Содержание</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Индекс</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Поиск</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Избранное</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/invoke/src/main/javahelp/org/zaproxy/zap/extension/invoke/resources/help_ru_RU/helpset_ru_RU.hs
Haskell
apache-2.0
1,042
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- | Create new a new project directory populated with a basic working -- project. module Stack.New ( new , NewOpts(..) , defaultTemplateName , templateNameArgument , getTemplates , TemplateName , listTemplates) where import Control.Monad import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Trans.Writer.Strict import Data.Aeson import Data.Aeson.Types import qualified Data.ByteString as SB import qualified Data.ByteString.Lazy as LB import Data.Conduit import Data.Foldable (asum) import qualified Data.HashMap.Strict as HM import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Maybe (fromMaybe) import Data.Maybe.Extra (mapMaybeM) import Data.Monoid import Data.Set (Set) import qualified Data.Set as S import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Encoding.Error as T (lenientDecode) import qualified Data.Text.IO as T import qualified Data.Text.Lazy as LT import Data.Time.Calendar import Data.Time.Clock import Data.Typeable import qualified Data.Yaml as Yaml import Network.HTTP.Download import Network.HTTP.Simple import Path import Path.IO import Prelude import Stack.Constants import Stack.Types.Config import Stack.Types.PackageName import Stack.Types.StackT import Stack.Types.TemplateName import System.Process.Run import Text.Hastache import Text.Hastache.Context import Text.Printf import Text.ProjectTemplate -------------------------------------------------------------------------------- -- Main project creation -- | Options for creating a new project. data NewOpts = NewOpts { newOptsProjectName :: PackageName -- ^ Name of the project to create. , newOptsCreateBare :: Bool -- ^ Whether to create the project without a directory. , newOptsTemplate :: Maybe TemplateName -- ^ Name of the template to use. , newOptsNonceParams :: Map Text Text -- ^ Nonce parameters specified just for this invocation. } -- | Create a new project with the given options. new :: (StackM env m, HasConfig env) => NewOpts -> Bool -> m (Path Abs Dir) new opts forceOverwrite = do pwd <- getCurrentDir absDir <- if bare then return pwd else do relDir <- parseRelDir (packageNameString project) liftM (pwd </>) (return relDir) exists <- doesDirExist absDir configTemplate <- view $ configL.to configDefaultTemplate let template = fromMaybe defaultTemplateName $ asum [ cliOptionTemplate , configTemplate ] if exists && not bare then throwM (AlreadyExists absDir) else do templateText <- loadTemplate template (logUsing absDir template) files <- applyTemplate project template (newOptsNonceParams opts) absDir templateText when (not forceOverwrite && bare) $ checkForOverwrite (M.keys files) writeTemplateFiles files runTemplateInits absDir return absDir where cliOptionTemplate = newOptsTemplate opts project = newOptsProjectName opts bare = newOptsCreateBare opts logUsing absDir template templateFrom = let loading = case templateFrom of LocalTemp -> "Loading local" RemoteTemp -> "Downloading" in $logInfo (loading <> " template \"" <> templateName template <> "\" to create project \"" <> packageNameText project <> "\" in " <> if bare then "the current directory" else T.pack (toFilePath (dirname absDir)) <> " ...") data TemplateFrom = LocalTemp | RemoteTemp -- | Download and read in a template's text content. loadTemplate :: forall env m. (StackM env m, HasConfig env) => TemplateName -> (TemplateFrom -> m ()) -> m Text loadTemplate name logIt = do templateDir <- view $ configL.to templatesDir case templatePath name of AbsPath absFile -> logIt LocalTemp >> loadLocalFile absFile UrlPath s -> do req <- parseRequest s let rel = fromMaybe backupUrlRelPath (parseRelFile s) downloadTemplate req (templateDir </> rel) RelPath relFile -> catch (do f <- loadLocalFile relFile logIt LocalTemp return f) (\(e :: NewException) -> case relRequest relFile of Just req -> downloadTemplate req (templateDir </> relFile) Nothing -> throwM e ) where loadLocalFile :: Path b File -> m Text loadLocalFile path = do $logDebug ("Opening local template: \"" <> T.pack (toFilePath path) <> "\"") exists <- doesFileExist path if exists then liftIO (fmap (T.decodeUtf8With T.lenientDecode) (SB.readFile (toFilePath path))) else throwM (FailedToLoadTemplate name (toFilePath path)) relRequest :: MonadThrow n => Path Rel File -> n Request relRequest rel = parseRequest (defaultTemplateUrl <> "/" <> toFilePath rel) downloadTemplate :: Request -> Path Abs File -> m Text downloadTemplate req path = do logIt RemoteTemp _ <- catch (redownload req path) (throwM . FailedToDownloadTemplate name) loadLocalFile path backupUrlRelPath = $(mkRelFile "downloaded.template.file.hsfiles") -- | Apply and unpack a template into a directory. applyTemplate :: (StackM env m, HasConfig env) => PackageName -> TemplateName -> Map Text Text -> Path Abs Dir -> Text -> m (Map (Path Abs File) LB.ByteString) applyTemplate project template nonceParams dir templateText = do config <- view configL currentYear <- do now <- liftIO getCurrentTime (year, _, _) <- return $ toGregorian . utctDay $ now return $ T.pack . show $ year let context = M.union (M.union nonceParams extraParams) configParams where nameAsVarId = T.replace "-" "_" $ packageNameText project nameAsModule = T.filter (/= '-') $ T.toTitle $ packageNameText project extraParams = M.fromList [ ("name", packageNameText project) , ("name-as-varid", nameAsVarId) , ("name-as-module", nameAsModule) , ("year", currentYear) ] configParams = configTemplateParams config (applied,missingKeys) <- runWriterT (hastacheStr defaultConfig { muEscapeFunc = id } templateText (mkStrContextM (contextFunction context))) unless (S.null missingKeys) ($logInfo ("\n" <> T.pack (show (MissingParameters project template missingKeys (configUserConfigPath config))) <> "\n")) files :: Map FilePath LB.ByteString <- catch (execWriterT $ yield (T.encodeUtf8 (LT.toStrict applied)) $$ unpackTemplate receiveMem id ) (\(e :: ProjectTemplateException) -> throwM (InvalidTemplate template (show e))) when (M.null files) $ throwM (InvalidTemplate template "Template does not contain any files") let isPkgSpec f = ".cabal" `isSuffixOf` f || f == "package.yaml" unless (any isPkgSpec . M.keys $ files) $ throwM (InvalidTemplate template "Template does not contain a .cabal \ \or package.yaml file") liftM M.fromList (mapM (\(fp,bytes) -> do path <- parseRelFile fp return (dir </> path, bytes)) (M.toList files)) where -- | Does a lookup in the context and returns a moustache value, -- on the side, writes out a set of keys that were requested but -- not found. contextFunction :: Monad m => Map Text Text -> String -> WriterT (Set String) m (MuType (WriterT (Set String) m)) contextFunction context key = case M.lookup (T.pack key) context of Nothing -> do tell (S.singleton key) return MuNothing Just value -> return (MuVariable value) -- | Check if we're going to overwrite any existing files. checkForOverwrite :: (MonadIO m, MonadThrow m) => [Path Abs File] -> m () checkForOverwrite files = do overwrites <- filterM doesFileExist files unless (null overwrites) $ throwM (AttemptedOverwrites overwrites) -- | Write files to the new project directory. writeTemplateFiles :: MonadIO m => Map (Path Abs File) LB.ByteString -> m () writeTemplateFiles files = forM_ (M.toList files) (\(fp,bytes) -> do ensureDir (parent fp) liftIO (LB.writeFile (toFilePath fp) bytes)) -- | Run any initialization functions, such as Git. runTemplateInits :: (StackM env m, HasConfig env) => Path Abs Dir -> m () runTemplateInits dir = do menv <- getMinimalEnvOverride config <- view configL case configScmInit config of Nothing -> return () Just Git -> catch (callProcess $ Cmd (Just dir) "git" menv ["init"]) (\(_ :: ProcessExitedUnsuccessfully) -> $logInfo "git init failed to run, ignoring ...") -- | Display the set of templates accompanied with description if available. listTemplates :: StackM env m => m () listTemplates = do templates <- getTemplates templateInfo <- getTemplateInfo if not . M.null $ templateInfo then do let keySizes = map (T.length . templateName) $ S.toList templates padWidth = show $ maximum keySizes outputfmt = "%-" <> padWidth <> "s %s\n" headerfmt = "%-" <> padWidth <> "s %s\n" liftIO $ printf headerfmt ("Template"::String) ("Description"::String) forM_ (S.toList templates) (\x -> do let name = templateName x desc = fromMaybe "" $ liftM (mappend "- ") (M.lookup name templateInfo >>= description) liftIO $ printf outputfmt (T.unpack name) (T.unpack desc)) else mapM_ (liftIO . T.putStrLn . templateName) (S.toList templates) -- | Get the set of templates. getTemplates :: StackM env m => m (Set TemplateName) getTemplates = do req <- liftM setGithubHeaders (parseUrlThrow defaultTemplatesList) resp <- catch (httpJSON req) (throwM . FailedToDownloadTemplates) case getResponseStatusCode resp of 200 -> return $ unTemplateSet $ getResponseBody resp code -> throwM (BadTemplatesResponse code) getTemplateInfo :: StackM env m => m (Map Text TemplateInfo) getTemplateInfo = do req <- liftM setGithubHeaders (parseUrlThrow defaultTemplateInfoUrl) resp <- catch (liftM Right $ httpLbs req) (\(ex :: HttpException) -> return . Left $ "Failed to download template info. The HTTP error was: " <> show ex) case resp >>= is200 of Left err -> do liftIO . putStrLn $ err return M.empty Right resp' -> case Yaml.decodeEither (LB.toStrict $ getResponseBody resp') :: Either String Object of Left err -> throwM $ BadTemplateInfo err Right o -> return (M.mapMaybe (Yaml.parseMaybe Yaml.parseJSON) (M.fromList . HM.toList $ o) :: Map Text TemplateInfo) where is200 resp = case getResponseStatusCode resp of 200 -> return resp code -> Left $ "Unexpected status code while retrieving templates info: " <> show code newtype TemplateSet = TemplateSet { unTemplateSet :: Set TemplateName } instance FromJSON TemplateSet where parseJSON = fmap TemplateSet . parseTemplateSet -- | Parser the set of templates from the JSON. parseTemplateSet :: Value -> Parser (Set TemplateName) parseTemplateSet a = do xs <- parseJSON a fmap S.fromList (mapMaybeM parseTemplate xs) where parseTemplate v = do o <- parseJSON v name <- o .: "name" if ".hsfiles" `isSuffixOf` name then case parseTemplateNameFromString name of Left{} -> fail ("Unable to parse template name from " <> name) Right template -> return (Just template) else return Nothing -------------------------------------------------------------------------------- -- Defaults -- | The default template name you can use if you don't have one. defaultTemplateName :: TemplateName defaultTemplateName = $(mkTemplateName "new-template") -- | Default web root URL to download from. defaultTemplateUrl :: String defaultTemplateUrl = "https://raw.githubusercontent.com/commercialhaskell/stack-templates/master" -- | Default web URL to get a yaml file containing template metadata. defaultTemplateInfoUrl :: String defaultTemplateInfoUrl = "https://raw.githubusercontent.com/commercialhaskell/stack-templates/master/template-info.yaml" -- | Default web URL to list the repo contents. defaultTemplatesList :: String defaultTemplatesList = "https://api.github.com/repos/commercialhaskell/stack-templates/contents/" -------------------------------------------------------------------------------- -- Exceptions -- | Exception that might occur when making a new project. data NewException = FailedToLoadTemplate !TemplateName !FilePath | FailedToDownloadTemplate !TemplateName !DownloadException | FailedToDownloadTemplates !HttpException | BadTemplatesResponse !Int | AlreadyExists !(Path Abs Dir) | MissingParameters !PackageName !TemplateName !(Set String) !(Path Abs File) | InvalidTemplate !TemplateName !String | AttemptedOverwrites [Path Abs File] | FailedToDownloadTemplateInfo !HttpException | BadTemplateInfo !String | BadTemplateInfoResponse !Int deriving (Typeable) instance Exception NewException instance Show NewException where show (FailedToLoadTemplate name path) = "Failed to load download template " <> T.unpack (templateName name) <> " from " <> path show (FailedToDownloadTemplate name (RedownloadFailed _ _ resp)) = case getResponseStatusCode resp of 404 -> "That template doesn't exist. Run `stack templates' to see a list of available templates." code -> "Failed to download template " <> T.unpack (templateName name) <> ": unknown reason, status code was: " <> show code show (AlreadyExists path) = "Directory " <> toFilePath path <> " already exists. Aborting." show (FailedToDownloadTemplates ex) = "Failed to download templates. The HTTP error was: " <> show ex show (BadTemplatesResponse code) = "Unexpected status code while retrieving templates list: " <> show code show (MissingParameters name template missingKeys userConfigPath) = intercalate "\n" [ "The following parameters were needed by the template but not provided: " <> intercalate ", " (S.toList missingKeys) , "You can provide them in " <> toFilePath userConfigPath <> ", like this:" , "templates:" , " params:" , intercalate "\n" (map (\key -> " " <> key <> ": value") (S.toList missingKeys)) , "Or you can pass each one as parameters like this:" , "stack new " <> packageNameString name <> " " <> T.unpack (templateName template) <> " " <> unwords (map (\key -> "-p \"" <> key <> ":value\"") (S.toList missingKeys))] show (InvalidTemplate name why) = "The template \"" <> T.unpack (templateName name) <> "\" is invalid and could not be used. " <> "The error was: \"" <> why <> "\"" show (AttemptedOverwrites fps) = "The template would create the following files, but they already exist:\n" <> unlines (map ((" " ++) . toFilePath) fps) <> "Use --force to ignore this, and overwite these files." show (FailedToDownloadTemplateInfo ex) = "Failed to download templates info. The HTTP error was: " <> show ex show (BadTemplateInfo err) = "Template info couldn't be parsed: " <> err show (BadTemplateInfoResponse code) = "Unexpected status code while retrieving templates info: " <> show code
Fuuzetsu/stack
src/Stack/New.hs
Haskell
bsd-3-clause
17,703
{-# LANGUAGE PolyKinds, GADTs #-} module T17541b where import Data.Kind data T k :: k -> Type where MkT1 :: T Type Int MkT2 :: T (Type -> Type) Maybe
sdiehl/ghc
testsuite/tests/dependent/should_fail/T17541b.hs
Haskell
bsd-3-clause
161
{-# LANGUAGE UndecidableInstances #-} module LargeNumberTest where import Data.Word import Init share [mkPersist sqlSettings { mpsGeneric = True }, mkMigrate "numberMigrate"] [persistLowerCase| Number intx Int int32 Int32 word32 Word32 int64 Int64 word64 Word64 deriving Show Eq |] cleanDB :: Runner backend m => ReaderT backend m () cleanDB = do deleteWhere ([] :: [Filter (NumberGeneric backend)]) specsWith :: Runner backend m => RunDb backend m -> Spec specsWith runDb = describe "Large Numbers" $ do it "preserves their values in the database" $ runDb $ do let go x = do xid <- insert x x' <- get xid liftIO $ x' @?= Just x go $ Number maxBound 0 0 0 0 go $ Number 0 maxBound 0 0 0 go $ Number 0 0 maxBound 0 0 go $ Number 0 0 0 maxBound 0 go $ Number 0 0 0 0 maxBound go $ Number minBound 0 0 0 0 go $ Number 0 minBound 0 0 0 go $ Number 0 0 minBound 0 0 go $ Number 0 0 0 minBound 0 go $ Number 0 0 0 0 minBound
yesodweb/persistent
persistent-test/src/LargeNumberTest.hs
Haskell
mit
1,070
<?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="sq-AL"> <title>Directory List v2.3 LC</title> <maps> <homeID>directorylistv2_3_lc</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/directorylistv2_3_lc/src/main/javahelp/help_sq_AL/helpset_sq_AL.hs
Haskell
apache-2.0
984
module SubSubPatternIn1 where f :: [Int] -> Int f ((x : (y : ys))) = case ys of ys@[] -> x + y ys@(b_1 : b_2) -> x + y f ((x : (y : ys))) = x + y
kmate/HaRe
old/testing/introCase/SubSubPatternIn1AST.hs
Haskell
bsd-3-clause
179
{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings, TupleSections, ViewPatterns #-} import Yesod.Routes.TH import Yesod.Routes.Parse import THHelper import Language.Haskell.TH.Syntax import Criterion.Main import Data.Text (words) import Prelude hiding (words) import Control.DeepSeq import Yesod.Routes.TH.Simple import Test.Hspec import Control.Monad (forM_, unless) $(do let (cons, decs) = mkRouteCons $ map (fmap parseType) resources clause1 <- mkDispatchClause settings resources clause2 <- mkSimpleDispatchClause settings resources return $ concat [ [FunD (mkName "dispatch1") [clause1]] , [FunD (mkName "dispatch2") [clause2]] , decs , [DataD [] (mkName "Route") [] cons [''Show, ''Eq]] ] ) instance NFData Route where rnf HomeR = () rnf FooR = () rnf (BarR i) = i `seq` () rnf BazR = () getHomeR :: Maybe Int getHomeR = Just 1 getFooR :: Maybe Int getFooR = Just 2 getBarR :: Int -> Maybe Int getBarR i = Just (i + 3) getBazR :: Maybe Int getBazR = Just 4 samples = take 10000 $ cycle [ words "foo" , words "foo bar" , words "" , words "bar baz" , words "bar 4" , words "bar 1234566789" , words "baz" , words "baz 4" , words "something else" ] dispatch2a = dispatch2 `asTypeOf` dispatch1 main :: IO () main = do forM_ samples $ \sample -> unless (dispatch1 True (sample, "GET") == dispatch2a True (sample, "GET")) (error $ show sample) defaultMain [ bench "dispatch1" $ nf (map (dispatch1 True . (, "GET"))) samples , bench "dispatch2" $ nf (map (dispatch2a True . (, "GET"))) samples , bench "dispatch1a" $ nf (map (dispatch1 True . (, "GET"))) samples , bench "dispatch2a" $ nf (map (dispatch2a True . (, "GET"))) samples ]
ygale/yesod
yesod-core/bench/th.hs
Haskell
mit
1,836
module Helper ( module Test.Hspec , module Control.Applicative , module Test.Mockery.Directory ) where import Test.Hspec import Test.Mockery.Directory import Control.Applicative
sol/reserve
test/Helper.hs
Haskell
mit
211
{-# LANGUAGE CPP #-} module GHCJS.DOM.HTMLMapElement ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.HTMLMapElement #else module Graphics.UI.Gtk.WebKit.DOM.HTMLMapElement #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.HTMLMapElement #else import Graphics.UI.Gtk.WebKit.DOM.HTMLMapElement #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/HTMLMapElement.hs
Haskell
mit
455
module Y2016.M07.D27.Solution where import Control.Arrow ((&&&)) import Control.Monad (liftM2) import Data.List (group, sort) import Data.Maybe (fromJust) import Data.Set (Set) import qualified Data.Set as Set import Y2016.M07.D19.Solution (figure2) import Y2016.M07.D20.Solution (FigureC, lineSegments) import Y2016.M07.D22.Solution (graphit) import Y2016.M07.D26.Solution (extendPath) -- Now, for the distance function, the question arises: as the crow flies? or -- only along a path? The latter is harder because it already solves -- shortestDistancePathing problem. So let's just go with 'as the crow flies.' distance :: FigureC -> Char -> Char -> Maybe Float distance fig@(gr, ptInfoF, vertF) start end = vertF start >>= \v0 -> let ((x1, y1), _, _) = ptInfoF v0 in vertF end >>= \v1 -> let ((x2, y2), _, _) = ptInfoF v1 in return (sqrt ((x1 - x2) ^ 2 + (y1 - y2) ^ 2)) {-- *Y2016.M07.D27.Solution> distance fig 'a' 'b' Just 18.027756 *Y2016.M07.D27.Solution> distance fig 'a' 'j' Just 15.0 Yay, and yay! --} -- Okay, shortest distance. One way to solve this problem is by brute force, -- another way is by iterative deepening on the distance (maintaining the -- in-the-running distances as we deepen) and others are from various search -- survey courses ACO, genetics, etc. -- let's start with Brute Force (caps), because I always start with that, then -- always regret starting with that, then improve if necessary: -- this is the agile approach: -- 1. Make it work -- 2. make it right -- 3. make it fast -- Let's make it work, first allPaths :: FigureC -> Char -> Char -> [String] allPaths fig start = -- now 'allPaths' is simply the work I did yesterday that accidently discovered -- all the paths by not stopping at the shortest ones whilst iteratively -- deepening: flip (allps fig) (extendPath fig (Set.empty, pure start)) allps :: FigureC -> Char -> [(Set Char, String)] -> [String] allps fig end vps = case filter ((== end) . head . snd) vps of [] -> concatMap (allps fig end . extendPath fig) vps anss -> map (reverse . snd) anss {-- *Y2016.M07.D27.Solution> let fig = graphit figure2 lineSegments *Y2016.M07.D27.Solution> let ab = allPaths fig 'a' 'b' ~> ["ab"] *Y2016.M07.D27.Solution> let ac = allPaths fig 'a' 'c' *Y2016.M07.D27.Solution> length ac ~> 191 *Y2016.M07.D27.Solution> take 5 ac ~> ["abjfkgc","abjfkhmgc","abjfkhmnc","abjfkhnc","abjfkhtdc"] --} -- brute force method: find all distances of all paths, sort by distance, -- then group-by shortestDistancePathing :: FigureC -> Char -> Char -> [String] shortestDistancePathing fig start = map snd . head . group . sort . map (distances fig &&& id) . allPaths fig start distances :: FigureC -> String -> Maybe Float distances fig [a,b] = distance fig a b distances fig (a:b:rest) = liftM2 (+) (distance fig a b) (distances fig (b:rest)) -- So, with shortestDistancePathing defined, find the shortest distance between -- nodf 'm' and 'a' in the figure from the value of: {-- *Y2016.M07.D27.Solution> shortestDistancePathing fig 'a' 'c' ~> ["abgc"] *Y2016.M07.D27.Solution> shortestDistancePathing fig 'm' 'a' ~> ["mkja"] YAY! We're a LITTLE bit closer to determining what trigons are (what we lead off with two weeks ago), now we must determine what points are in a straight line, shortestDistancePathing helps us. We'll look at finding straight lines tomorrow. --}
geophf/1HaskellADay
exercises/HAD/Y2016/M07/D27/Solution.hs
Haskell
mit
3,406
module Control.Foldl.Extended where import Control.Foldl (Fold(..)) import qualified Control.Foldl as L import qualified Data.Map as Map hiding (foldr) -- | turn a regular fold into a Map.Map fold keyFold :: (Ord c) => Fold a b -> Fold (c, a) [(c, b)] keyFold (Fold step begin done) = Fold step' begin' done' where step' x (key, a) = case Map.lookup key x of Nothing -> Map.insert key (step begin a) x Just x' -> Map.insert key (step x' a) x begin' = Map.empty done' x = Map.toList (Map.map done x) -- | count instances using a supplied function to generate a key countMap :: (Ord b) => (a -> b) -> L.Fold a (Map.Map b Int) countMap key = L.Fold step begin done where begin = Map.empty done = id step m x = Map.insertWith (+) (key x) 1 m -- | fold counting number of keys countK :: (Ord b) => (a -> b) -> Fold a (Map.Map b Int) countK key = Fold step begin done where begin = Map.empty done = id step m x = Map.insertWith (+) (key x) 1 m -- | fold counting number of keys, given a filter countKF :: (Ord b) => (a -> b) -> (a -> Bool) -> Fold a (Map.Map b Int) countKF key filt = Fold step begin done where begin = Map.empty done = id step m x = if filt x then Map.insertWith (+) (key x) 1 m else m -- | first difference delta :: (Num a) => Fold a (Maybe a) delta = Fold step (Nothing, Nothing) done where step (p', _) p = (Just p, p') done (Just p1, Just p2) = Just $ p1 - p2 done _ = Nothing -- | return (geometric first difference) ret :: Fold Double (Maybe Double) ret = Fold step (Nothing, Nothing) done where step (p', _) p = (Just p, p') done (Just p1, Just p2) = Just $ (p1 / p2) - 1 done _ = Nothing -- | lag n lag :: Int -> Fold a (Maybe a) lag l = Fold step (0, []) done where step (c, h) a | c > l = (c + 1, tail h ++ [a]) | otherwise = (c + 1, h ++ [a]) done (c, h) | c > l = Just $ head h | otherwise = Nothing -- list folds count :: Fold a Integer count = Fold (const . (1 +)) 0 id -- turn a regular fold into a list one listify :: Int -> Fold a b -> Fold [a] [b] listify n (Fold step' begin' done') = Fold stepL beginL doneL where stepL = zipWith step' beginL = replicate n begin' doneL = map done' -- | tuple 2 folds tuplefy :: Fold a b -> Fold c d -> Fold (a, c) (b, d) tuplefy (Fold step0 begin0 done0) (Fold step1 begin1 done1) = Fold stepL beginL doneL where stepL (a0, a1) (x0, x1) = (step0 a0 x0, step1 a1 x1) beginL = (begin0, begin1) doneL (x0, x1) = (done0 x0, done1 x1)
tonyday567/foldl-extended
src/Control/Foldl/Extended.hs
Haskell
mit
2,620
module Monoid1 where import Data.Semigroup import Test.QuickCheck import SemiGroupAssociativeLaw import MonoidLaws data Trivial = Trivial deriving (Eq, Show) instance Semigroup Trivial where _ <> _ = Trivial instance Monoid Trivial where mempty = Trivial mappend = (<>) instance Arbitrary Trivial where arbitrary = return Trivial type TrivialAssoc = Trivial -> Trivial -> Trivial -> Bool main :: IO () main = do quickCheck (semigroupAssoc :: TrivialAssoc) quickCheck (monoidLeftIdentity :: Trivial -> Bool) quickCheck (monoidRightIdentity :: Trivial -> Bool)
NickAger/LearningHaskell
HaskellProgrammingFromFirstPrinciples/Chapter15.hsproj/Monoid1.hs
Haskell
mit
595
{-# LANGUAGE OverloadedStrings #-} import Text.HTML.TagSoup import Text.HTML.TagSoup.Match import qualified Data.ByteString as B import qualified Data.ByteString.UTF8 as UB import Data.String.Utils (strip) import Safe import System.IO (stdin) import Control.Applicative main :: IO () main = do content <- readStdin let tags = parseTags content let title = getTitle tags case title of Just s -> putStrLn s Nothing -> putStrLn "no title found" where getTitle = fmap strip . headDef Nothing . fmap maybeTagText . getTitleBlock . getHeadBlock . getHtmlBlock getBlock name = takeWhile (not . tagCloseNameLit name) . drop 1 . dropWhile (not . tagOpenNameLit name) getHtmlBlock = getBlock "html" getHeadBlock = getBlock "head" getTitleBlock = getBlock "title" readStdin :: IO String readStdin = UB.toString <$> B.hGetContents stdin
sdroege/snippets.hs
html2.hs
Haskell
mit
950
module Core.Annotation where import qualified Data.Generics.Fixplate as Fix import Data.Set (Set) data Annotation typeId = Annotation { freeVars :: Set typeId } deriving (Eq, Ord, Show) type Annotated f id = Fix.Attr (f id) (Annotation id)
fredun/compiler
src/Core/Annotation.hs
Haskell
mit
252
{-# LANGUAGE CPP #-} {-# LANGUAGE Safe #-} {-# LANGUAGE NoImplicitPrelude #-} module Monad ( Monad(..) , MonadPlus(..) , (=<<) , (>=>) , (<=<) , forever , join , mfilter , filterM , mapAndUnzipM , zipWithM , zipWithM_ , foldM , foldM_ , replicateM , replicateM_ , concatMapM , guard , when , unless , liftM , liftM2 , liftM3 , liftM4 , liftM5 , liftM' , liftM2' , ap , (<$!>) ) where import Data.List (concat) import Prelude (seq) #if (__GLASGOW_HASKELL__ >= 710) import Control.Monad hiding ((<$!>)) #else import Control.Monad #endif concatMapM :: (Monad m) => (a -> m [b]) -> [a] -> m [b] concatMapM f xs = liftM concat (mapM f xs) liftM' :: Monad m => (a -> b) -> m a -> m b liftM' = (<$!>) {-# INLINE liftM' #-} liftM2' :: (Monad m) => (a -> b -> c) -> m a -> m b -> m c liftM2' f a b = do x <- a y <- b let z = f x y z `seq` return z {-# INLINE liftM2' #-} (<$!>) :: Monad m => (a -> b) -> m a -> m b f <$!> m = do x <- m let z = f x z `seq` return z {-# INLINE (<$!>) #-}
ardfard/protolude
src/Monad.hs
Haskell
mit
1,066
{-# htermination delete :: (Eq a, Eq k) => (Either a k) -> [(Either a k)] -> [(Either a k)] #-} import List
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/List_delete_11.hs
Haskell
mit
108
{-# LANGUAGE BangPatterns, OverloadedStrings #-} module Network.Wai.Handler.Warp.Buffer ( bufferSize , allocateBuffer , freeBuffer , mallocBS , newBufferPool , withBufferPool , toBlazeBuffer , copy , bufferIO ) where import qualified Data.ByteString as BS import Data.ByteString.Internal (ByteString(..), memcpy) import Data.ByteString.Unsafe (unsafeTake, unsafeDrop) import Data.IORef (newIORef, readIORef, writeIORef) import qualified Data.Streaming.ByteString.Builder.Buffer as B (Buffer (..)) import Foreign.ForeignPtr import Foreign.Marshal.Alloc (mallocBytes, free, finalizerFree) import Foreign.Ptr (castPtr, plusPtr) import Network.Wai.Handler.Warp.Types ---------------------------------------------------------------- -- | The default size of the write buffer: 16384 (2^14 = 1024 * 16). -- This is the maximum size of TLS record. -- This is also the maximum size of HTTP/2 frame payload -- (excluding frame header). bufferSize :: BufSize bufferSize = 16384 -- | Allocating a buffer with malloc(). allocateBuffer :: Int -> IO Buffer allocateBuffer = mallocBytes -- | Releasing a buffer with free(). freeBuffer :: Buffer -> IO () freeBuffer = free ---------------------------------------------------------------- largeBufferSize :: Int largeBufferSize = 16384 minBufferSize :: Int minBufferSize = 2048 newBufferPool :: IO BufferPool newBufferPool = newIORef BS.empty mallocBS :: Int -> IO ByteString mallocBS size = do ptr <- allocateBuffer size fptr <- newForeignPtr finalizerFree ptr return $! PS fptr 0 size {-# INLINE mallocBS #-} usefulBuffer :: ByteString -> Bool usefulBuffer buffer = BS.length buffer >= minBufferSize {-# INLINE usefulBuffer #-} getBuffer :: BufferPool -> IO ByteString getBuffer pool = do buffer <- readIORef pool if usefulBuffer buffer then return buffer else mallocBS largeBufferSize {-# INLINE getBuffer #-} putBuffer :: BufferPool -> ByteString -> IO () putBuffer pool buffer = writeIORef pool buffer {-# INLINE putBuffer #-} withForeignBuffer :: ByteString -> ((Buffer, BufSize) -> IO Int) -> IO Int withForeignBuffer (PS ps s l) f = withForeignPtr ps $ \p -> f (castPtr p `plusPtr` s, l) {-# INLINE withForeignBuffer #-} withBufferPool :: BufferPool -> ((Buffer, BufSize) -> IO Int) -> IO ByteString withBufferPool pool f = do buffer <- getBuffer pool consumed <- withForeignBuffer buffer f putBuffer pool $! unsafeDrop consumed buffer return $! unsafeTake consumed buffer {-# INLINE withBufferPool #-} ---------------------------------------------------------------- -- -- Utilities -- toBlazeBuffer :: Buffer -> BufSize -> IO B.Buffer toBlazeBuffer ptr size = do fptr <- newForeignPtr_ ptr return $ B.Buffer fptr ptr ptr (ptr `plusPtr` size) -- | Copying the bytestring to the buffer. -- This function returns the point where the next copy should start. copy :: Buffer -> ByteString -> IO Buffer copy !ptr (PS fp o l) = withForeignPtr fp $ \p -> do memcpy ptr (p `plusPtr` o) (fromIntegral l) return $! ptr `plusPtr` l {-# INLINE copy #-} bufferIO :: Buffer -> Int -> (ByteString -> IO ()) -> IO () bufferIO ptr siz io = do fptr <- newForeignPtr_ ptr io $ PS fptr 0 siz
mfine/wai
warp/Network/Wai/Handler/Warp/Buffer.hs
Haskell
mit
3,222
{-# OPTIONS_GHC -Wall -XFlexibleInstances #-} {- - - Copyright 2014 -- name removed for blind review, all rights reserved! Please push a git request to receive author's name! -- - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -} module Main (main) where import System.Environment (getArgs) import EParser (parse,tbrfun,pGetEMOD,pGetLisp,TermBuilder (..)) import ToNET (showNET) import System.IO main :: IO () main = do args <- getArgs s <- readContents args "i" case (parse pGetLisp "(stdin)" s) of (Left e) -> hPutStrLn stderr (show e) (Right [g]) -> case (tbrfun (pGetEMOD g) 0) of (TBError e) -> hPutStrLn stderr (show e) (TB v _) -> do let (dotGraph,proofObligations) = showNET v write args "g" dotGraph write args "p" proofObligations (Right []) -> hPutStrLn stderr "Please supply input at (stdin)" _ -> hPutStrLn stderr "More than one input not supported" readContents :: [String] -> String -> IO (String) readContents (('-':h):v:_) h' | h==h' = case v of "-" -> getContents "_" -> return "" f -> do hd <- openFile f ReadMode hGetContents hd readContents (_:as) x = readContents as x readContents [] f = do hPutStrLn stderr$ "No `-"++f++" filename' argument given, using stdin for input (use - as a filename to suppress this warning while still using stdin, or _ to read an empty string)." getContents write :: [String] -> String -> String -> IO () write (('-':h):v:_) h' s | h==h' = case v of "-" -> putStrLn s "_" -> return () f -> do hd <- openFile f WriteMode hPutStrLn hd s hClose hd write (_:as) x y = write as x y write [] f _ = hPutStrLn stderr$ "No `-"++f++" filename' argument given, some of the output is omitted (use - as a filename for stdout, or _ to suppress this warning)."
DatePaper616/code
eMOD.hs
Haskell
apache-2.0
2,447
unit = ["", "Man","Oku","Cho","Kei","Gai","Jo","Jou","Ko","Kan","Sei","Sai","Gok","Ggs","Asg","Nyt","Fks","Mts"] toStr 0 _ = [] toStr _ [] = [] toStr n (u:us) = let m = n `mod` 10000 n'= n `div` 10000 in if m == 0 then (toStr n' us) else (toStr n' us) ++ show(m) ++ u ans' :: Integer -> Integer -> String ans' a b = let n = a ^ b in toStr n unit ans :: [[Integer]] -> [String] ans ([0,0]:_) = [] ans ([a,b]:s) = (ans' a b):(ans s) main = do c <- getContents let i = map (map read) $ map words $ lines c :: [[Integer]] o = ans i mapM_ putStrLn o
a143753/AOJ
0287.hs
Haskell
apache-2.0
595
-- Copyright 2020 Google LLC -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. {-# LANGUAGE ForeignFunctionInterface #-} module CLib2 where foreign import ccall clib2 :: IO Int
google/hrepl
hrepl/tests/CLib2.hs
Haskell
apache-2.0
688
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QAbstractSpinBox.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:36 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Gui.QAbstractSpinBox ( StepEnabledFlag, StepEnabled, eStepNone, fStepNone, eStepUpEnabled, fStepUpEnabled, eStepDownEnabled, fStepDownEnabled , ButtonSymbols, eUpDownArrows, ePlusMinus, eNoButtons , CorrectionMode, eCorrectToPreviousValue, eCorrectToNearestValue ) where import Foreign.C.Types import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CStepEnabledFlag a = CStepEnabledFlag a type StepEnabledFlag = QEnum(CStepEnabledFlag Int) ieStepEnabledFlag :: Int -> StepEnabledFlag ieStepEnabledFlag x = QEnum (CStepEnabledFlag x) instance QEnumC (CStepEnabledFlag Int) where qEnum_toInt (QEnum (CStepEnabledFlag x)) = x qEnum_fromInt x = QEnum (CStepEnabledFlag x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> StepEnabledFlag -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () data CStepEnabled a = CStepEnabled a type StepEnabled = QFlags(CStepEnabled Int) ifStepEnabled :: Int -> StepEnabled ifStepEnabled x = QFlags (CStepEnabled x) instance QFlagsC (CStepEnabled Int) where qFlags_toInt (QFlags (CStepEnabled x)) = x qFlags_fromInt x = QFlags (CStepEnabled x) withQFlagsResult x = do ti <- x return $ qFlags_fromInt $ fromIntegral ti withQFlagsListResult x = do til <- x return $ map qFlags_fromInt til instance Qcs (QObject c -> StepEnabled -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qFlags_fromInt hint) return () eStepNone :: StepEnabledFlag eStepNone = ieStepEnabledFlag $ 0 eStepUpEnabled :: StepEnabledFlag eStepUpEnabled = ieStepEnabledFlag $ 1 eStepDownEnabled :: StepEnabledFlag eStepDownEnabled = ieStepEnabledFlag $ 2 fStepNone :: StepEnabled fStepNone = ifStepEnabled $ 0 fStepUpEnabled :: StepEnabled fStepUpEnabled = ifStepEnabled $ 1 fStepDownEnabled :: StepEnabled fStepDownEnabled = ifStepEnabled $ 2 data CButtonSymbols a = CButtonSymbols a type ButtonSymbols = QEnum(CButtonSymbols Int) ieButtonSymbols :: Int -> ButtonSymbols ieButtonSymbols x = QEnum (CButtonSymbols x) instance QEnumC (CButtonSymbols Int) where qEnum_toInt (QEnum (CButtonSymbols x)) = x qEnum_fromInt x = QEnum (CButtonSymbols x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> ButtonSymbols -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () eUpDownArrows :: ButtonSymbols eUpDownArrows = ieButtonSymbols $ 0 ePlusMinus :: ButtonSymbols ePlusMinus = ieButtonSymbols $ 1 eNoButtons :: ButtonSymbols eNoButtons = ieButtonSymbols $ 2 data CCorrectionMode a = CCorrectionMode a type CorrectionMode = QEnum(CCorrectionMode Int) ieCorrectionMode :: Int -> CorrectionMode ieCorrectionMode x = QEnum (CCorrectionMode x) instance QEnumC (CCorrectionMode Int) where qEnum_toInt (QEnum (CCorrectionMode x)) = x qEnum_fromInt x = QEnum (CCorrectionMode x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> CorrectionMode -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () eCorrectToPreviousValue :: CorrectionMode eCorrectToPreviousValue = ieCorrectionMode $ 0 eCorrectToNearestValue :: CorrectionMode eCorrectToNearestValue = ieCorrectionMode $ 1
keera-studios/hsQt
Qtc/Enums/Gui/QAbstractSpinBox.hs
Haskell
bsd-2-clause
7,971
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE Rank2Types #-} module EFA.Data.Vector where import qualified Data.Vector.Unboxed as UV import qualified Data.Vector as V import qualified Data.List as List import qualified Data.List.HT as ListHT import qualified Data.List.Match as Match import qualified Data.Set as Set import qualified Data.NonEmpty as NonEmpty import qualified Data.Foldable as Fold import Data.Functor (Functor) import Data.Tuple.HT (mapFst) import Data.Maybe.HT (toMaybe) import Data.Ord (Ordering, (>=), (<=), (<), (>)) import Data.Eq (Eq((==))) import Data.Function ((.), ($), id, flip) import Data.Maybe (Maybe(Just, Nothing), maybe, isJust, fromMaybe) import Data.Bool (Bool(False, True), (&&), not) import Data.Tuple (snd, fst) import Text.Show (Show, show) import Prelude (Num, Int, Integer, Ord, error, (++), (+), (-), subtract, min, max, fmap, succ) {- | We could replace this by suitable:Suitable. -} class Storage vector y where data Constraints vector y :: * constraints :: vector y -> Constraints vector y instance Storage [] y where data Constraints [] y = ListConstraints constraints _ = ListConstraints instance Storage V.Vector y where data Constraints V.Vector y = VectorConstraints constraints _ = VectorConstraints instance (UV.Unbox y) => Storage UV.Vector y where data Constraints UV.Vector y = UV.Unbox y => UnboxedVectorConstraints constraints _ = UnboxedVectorConstraints readUnbox :: (UV.Unbox a => UV.Vector a -> b) -> (Storage UV.Vector a => UV.Vector a -> b) readUnbox f x = case constraints x of UnboxedVectorConstraints -> f x writeUnbox :: (UV.Unbox a => UV.Vector a) -> (Storage UV.Vector a => UV.Vector a) writeUnbox x = let z = case constraints z of UnboxedVectorConstraints -> x in z instance (Storage v y) => Storage (NonEmpty.T v) y where data Constraints (NonEmpty.T v) y = (Storage v y) => NonEmptyConstraints constraints _ = NonEmptyConstraints readNonEmpty :: (Storage v a => NonEmpty.T v a -> b) -> (Storage (NonEmpty.T v) a => NonEmpty.T v a -> b) readNonEmpty f x = case constraints x of NonEmptyConstraints -> f x writeNonEmpty :: (Storage v a => NonEmpty.T v a) -> (Storage (NonEmpty.T v) a => NonEmpty.T v a) writeNonEmpty x = let z = case constraints z of NonEmptyConstraints -> x in z -------------------------------------------------------------- -- Singleton Class {- {-# DEPRECATED head, tail "use viewL instead" #-} {-# DEPRECATED last, init "use viewR instead" #-} -} class Singleton vec where maximum :: (Ord d, Storage vec d) => vec d -> d minimum :: (Ord d, Storage vec d) => vec d -> d minmax :: (Ord d, Storage vec d) => vec d -> (d, d) singleton :: (Storage vec d) => d -> vec d empty :: (Storage vec d) => vec d append :: (Storage vec d) => vec d -> vec d -> vec d concat :: (Storage vec d) => [vec d] -> vec d head :: (Storage vec d) => vec d -> d tail :: (Storage vec d) => vec d -> vec d last :: (Storage vec d) => vec d -> d init :: (Storage vec d) => vec d -> vec d viewL :: (Storage vec d) => vec d -> Maybe (d, vec d) viewR :: (Storage vec d) => vec d -> Maybe (vec d, d) all :: (Storage vec d) => (d -> Bool) -> vec d -> Bool any :: (Storage vec d) => (d -> Bool) -> vec d -> Bool _minmaxSemiStrict :: (Ord d) => (d, d) -> d -> (d, d) _minmaxSemiStrict acc@(mini, maxi) x = let mn = x >= mini mx = x <= maxi in if mn && mx then acc else if not mn then (x, maxi) else (mini, x) minmaxStrict :: (Ord d) => (d, d) -> d -> (d, d) minmaxStrict (mini, maxi) x = case (x < mini, x > maxi) of (False, False) -> (mini, maxi) (True, False) -> (x, maxi) (False, True) -> (mini, x) (True, True) -> error "minmax: lower bound larger than upper bound" -- space leak _minmaxLazy :: (Ord d) => (d, d) -> d -> (d, d) _minmaxLazy (a, b) x = (a `min` x, b `max` x) instance Singleton V.Vector where maximum x = V.maximum x minimum x = V.minimum x minmax xs = V.foldl' minmaxStrict (y, y) ys where (y, ys) = fromMaybe (error "Signal.Vector.minmax: empty UV-Vector") (viewL xs) singleton x = V.singleton x empty = V.empty append = (V.++) concat = V.concat head = V.head tail = V.tail last = V.last init = V.init viewL xs = toMaybe (not $ V.null xs) (V.head xs, V.tail xs) viewR xs = toMaybe (not $ V.null xs) (V.init xs, V.last xs) all = V.all any = V.any instance Singleton UV.Vector where maximum x = readUnbox UV.maximum x minimum x = readUnbox UV.minimum x minmax = readUnbox $ \xs -> let (y, ys) = fromMaybe (error "Signal.Vector.minmax: empty UV-Vector") (viewL xs) in UV.foldl' minmaxStrict (y, y) ys singleton x = writeUnbox (UV.singleton x) empty = writeUnbox UV.empty append = readUnbox (UV.++) concat xs = writeUnbox (UV.concat xs) head = readUnbox UV.head tail = readUnbox UV.tail last = readUnbox UV.last init = readUnbox UV.init viewL = readUnbox (\xs -> toMaybe (not $ UV.null xs) (UV.head xs, UV.tail xs)) viewR = readUnbox (\xs -> toMaybe (not $ UV.null xs) (UV.init xs, UV.last xs)) all f = readUnbox (UV.all f) any f = readUnbox (UV.any f) instance Singleton [] where maximum x = List.maximum x minimum x = List.minimum x minmax (x:xs) = List.foldl' minmaxStrict (x, x) xs minmax [] = error "Signal.Vector.minmax: empty list" singleton x = [x] empty = [] append = (++) concat = List.concat head = List.head tail = List.tail last = List.last init = List.init viewL = ListHT.viewL viewR = ListHT.viewR all = List.all any = List.any ------------------------------------------------------------ -- | Functor class Walker vec where map :: (Storage vec a, Storage vec b) => (a -> b) -> vec a -> vec b imap :: (Storage vec a, Storage vec b) => (Int -> a -> b) -> vec a -> vec b foldr :: (Storage vec a) => (a -> b -> b) -> b -> vec a -> b foldl :: (Storage vec a) => (b -> a -> b) -> b -> vec a -> b {- | For fully defined values it holds @equalBy f xs ys == (and (zipWith f xs ys) && length xs == length ys)@ but for lists @equalBy@ is lazier. -} equalBy :: (Storage vec a, Storage vec b) => (a -> b -> Bool) -> vec a -> vec b -> Bool instance Walker [] where map = List.map imap f = List.zipWith f [0..] foldr = List.foldr foldl = List.foldl' equalBy f = let go (x:xs) (y:ys) = f x y && go xs ys go [] [] = True go _ _ = False in go instance Walker UV.Vector where map f xs = writeUnbox (readUnbox (UV.map f) xs) imap f xs = writeUnbox (readUnbox (UV.imap f) xs) foldr f a = readUnbox (UV.foldr f a) foldl f a = readUnbox (UV.foldl' f a) equalBy f = readUnbox (\xs -> readUnbox (\ys -> UV.length xs == UV.length ys && UV.and (UV.zipWith f xs ys))) instance Walker V.Vector where map = V.map imap = V.imap foldr = V.foldr foldl = V.foldl' equalBy f xs ys = V.length xs == V.length ys && V.and (V.zipWith f xs ys) ------------------------------------------------------------ -- | Zipper class Zipper vec where zipWith :: (Storage vec a, Storage vec b, Storage vec c) => (a -> b -> c) -> vec a -> vec b -> vec c zip :: (Zipper vec, Storage vec a, Storage vec b, Storage vec (a,b)) => vec a -> vec b -> vec (a, b) zip = zipWith (,) instance Zipper [] where zipWith f x y = List.zipWith f x y -- if V.lenCheck x y then zipWith f x y else error "Error in V.lenCheck List -- unequal Length" instance Zipper V.Vector where zipWith f x y = V.zipWith f x y -- if V.lenCheck x y then V.zipWith f x y else error "Error in V.lenCheck V -- unequal Length" instance Zipper UV.Vector where zipWith f xs ys = writeUnbox (readUnbox (readUnbox (UV.zipWith f) xs) ys) -- if V.lenCheck x y then UV.zipWith f x y else error "Error in V.lenCheck UV -- unequal Length" instance Zipper (NonEmpty.T vec) where zipWith f xs ys = writeNonEmpty $ zipWith f (readNonEmpty id xs) (readNonEmpty id ys) deltaMap :: (Storage vec b, Storage vec c, Singleton vec, Zipper vec) => (b -> b -> c) -> vec b -> vec c deltaMap f l = maybe empty (zipWith f l . snd) $ viewL l ------------------------------------------------------------ -- | Zipper4 class Zipper4 vec where zipWith4 :: (Storage vec a, Storage vec b, Storage vec c, Storage vec d, Storage vec e) => (a -> b -> c -> d -> e) -> vec a -> vec b -> vec c -> vec d -> vec e instance Zipper4 [] where zipWith4 f w x y z = List.zipWith4 f w x y z -- if V.lenCheck x y then zipWith f x y else error "Error in V.lenCheck List -- unequal Length" instance Zipper4 V.Vector where zipWith4 f w x y z = V.zipWith4 f w x y z -- if V.lenCheck x y then V.zipWith f x y else error "Error in V.lenCheck V -- unequal Length" instance Zipper4 UV.Vector where zipWith4 f w x y z = writeUnbox (readUnbox (readUnbox (readUnbox (readUnbox (UV.zipWith4 f) w) x) y) z) -- if V.lenCheck x y then UV.zipWith f x y else error "Error in V.lenCheck UV -- unequal Length" {- deltaMap2:: (a -> a -> b -> b -> c) -> vec a -> vec a -> vec b -> vec b -> vec c deltaMap2 f xs ys = zipWith4 f xs (tail xs) ys (tail ys) deltaMapReverse2 :: (a -> a -> b -> b -> c) -> vec a -> vec a -> vec b -> vec b -> vec c deltaMapReverse2 f xs ys = zipWith4 f (tail xs) xs (tail ys) ys -} -------------------------------------------------------------- -- Vector conversion class Convert c1 c2 where convert :: (Storage c1 a, Storage c2 a) => c1 a -> c2 a instance Convert UV.Vector V.Vector where convert x = readUnbox UV.convert x instance Convert V.Vector UV.Vector where convert x = writeUnbox (V.convert x) instance Convert UV.Vector UV.Vector where convert = id instance Convert V.Vector V.Vector where convert = id instance Convert [] [] where convert = id instance Convert [] UV.Vector where convert x = writeUnbox (UV.fromList x) instance Convert [] V.Vector where convert x = V.fromList x instance Convert V.Vector [] where convert x = V.toList x instance Convert UV.Vector [] where convert x = readUnbox UV.toList x -------------------------------------------------------------- -- Length & Length Check class Len s where len :: s -> Int instance Len [d] where len = List.length instance Len (V.Vector d) where len = V.length instance UV.Unbox d => Len (UV.Vector d) where len = UV.length lenCheck :: (Len v1, Len v2) => v1 -> v2 -> Bool lenCheck x y = len x == len y class Length vec where length :: Storage vec a => vec a -> Int instance Length v => Length (NonEmpty.T v) where length = readNonEmpty $ succ . length . NonEmpty.tail instance Length [] where length = List.length instance Length V.Vector where length = V.length instance Length UV.Vector where length = readUnbox UV.length type family Core (v :: * -> *) :: * -> * type instance Core (NonEmpty.T f) = Core f type instance Core [] = [] type instance Core V.Vector = V.Vector type instance Core UV.Vector = UV.Vector data Remainder v a b = RemainderLeft (NonEmpty.T v a) | NoRemainder | RemainderRight (NonEmpty.T v b) class DiffLength v where diffLength :: (Storage v a, Storage (Core v) a, Storage v b, Storage (Core v) b) => v a -> v b -> Remainder (Core v) a b instance DiffLength v => DiffLength (NonEmpty.T v) where diffLength = readNonEmpty $ \(NonEmpty.Cons _ as) -> readNonEmpty $ \(NonEmpty.Cons _ bs) -> diffLength as bs -------------------------------------------------------------- -- Transpose Class class Transpose v1 v2 where transpose :: (Storage v1 d) => v2 (v1 d) -> v2 (v1 d) instance Transpose [] [] where transpose x = if List.all (== List.head lens) lens then List.transpose x else error "Error in V.Transpose -- unequal length" where lens = map len x instance Transpose V.Vector V.Vector where transpose xs = if all (== len0) lens then V.map (flip V.map xs) fs else error "Error in V.Transpose -- unequal length" where fs = V.map (flip (V.!)) $ V.fromList [0..len0-1] lens = V.map len xs len0 = V.head lens instance Transpose UV.Vector V.Vector where transpose xs = case constraints $ fst $ maybe (error("Error in EFA.Signal.Vector/transpose - empty head")) id $ viewL xs of UnboxedVectorConstraints -> let fs = V.map (flip (UV.!)) $ V.fromList [0..len0-1] lens = V.map len xs len0 = V.head lens in if all (== len0) lens then V.map (convert . flip V.map xs) fs else error "Error in V.Transpose -- unequal length" class FromList vec where fromList :: (Storage vec d) => [d] -> vec d toList :: (Storage vec d) => vec d -> [d] instance FromList [] where fromList x = x toList x = x instance FromList V.Vector where fromList = V.fromList toList = V.toList instance FromList UV.Vector where fromList x = writeUnbox (UV.fromList x) toList x = readUnbox UV.toList x class Sort vec where sort :: (Ord d, Storage vec d) => vec d -> vec d instance Sort [] where sort = List.sort instance Sort V.Vector where sort = V.fromList . List.sort . V.toList instance Sort UV.Vector where sort = readUnbox (UV.fromList . List.sort . UV.toList) class SortBy vec where sortBy :: (Storage vec d) => (d -> d -> Ordering) -> vec d -> vec d instance SortBy [] where sortBy f = List.sortBy f instance SortBy V.Vector where sortBy f = V.fromList . (List.sortBy f) . V.toList instance SortBy UV.Vector where sortBy f = readUnbox (UV.fromList . (List.sortBy f) . UV.toList) class Filter vec where filter :: Storage vec d => (d -> Bool) -> vec d -> vec d instance Filter [] where filter = List.filter instance Filter V.Vector where filter = V.filter instance Filter UV.Vector where filter f = readUnbox (UV.filter f) {- An according function in the vector library would save us from the 'error' and from the duplicate computation of 'f' (or alternatively from storing a Maybe in a vector). -} mapMaybe :: (Walker vec, Filter vec, Storage vec a, Storage vec b) => (a -> Maybe b) -> vec a -> vec b mapMaybe f = map (\a -> case f a of Just b -> b Nothing -> error "mapMaybe: filter has passed a Nothing") . filter (isJust . f) class Lookup vec where lookUp :: (Storage vec d, Eq d) => vec d -> [Int] -> vec d instance Lookup [] where lookUp xs = lookUpGen (V.fromList xs V.!? ) instance Lookup V.Vector where lookUp xs = V.fromList . lookUpGen (xs V.!?) instance Lookup UV.Vector where lookUp = readUnbox (\xs -> UV.fromList . lookUpGen (xs UV.!?)) {-# INLINE lookUpGen #-} lookUpGen :: Show i => (i -> Maybe a) -> [i] -> [a] lookUpGen look idxs = case ListHT.partitionMaybe look idxs of (ys, []) -> ys (_, invalidIdxs) -> error $ "lookUpGen: indices out of Range: " ++ show invalidIdxs ++ "\nAll indices: " ++ show idxs class LookupMaybe vec d where lookupMaybe :: vec d -> Int -> Maybe d instance LookupMaybe [] d where lookupMaybe xs idx = if idx >=0 && idx <= (length xs) then Just $ xs List.!! idx else Nothing instance LookupMaybe V.Vector d where lookupMaybe xs idx = xs V.!? idx instance UV.Unbox d => LookupMaybe UV.Vector d where lookupMaybe xs idx = xs UV.!? idx class LookupUnsafe vec d where lookupUnsafe :: vec d -> Int -> d instance UV.Unbox d => LookupUnsafe UV.Vector d where lookupUnsafe xs idx = xs UV.! idx instance LookupUnsafe V.Vector d where lookupUnsafe xs idx = xs V.! idx instance LookupUnsafe [] d where lookupUnsafe xs idx = xs List.!! idx class Reverse v where reverse :: (Storage v d) => v d -> v d instance Reverse [] where reverse = List.reverse instance Reverse V.Vector where reverse = V.reverse instance Reverse UV.Vector where reverse = readUnbox UV.reverse class Find v where findIndex :: (Storage v d) => (d -> Bool) -> v d -> Maybe Int findIndices :: (Storage v d) => (d -> Bool) -> v d -> v Int instance Find [] where findIndex x = List.findIndex x findIndices x = List.findIndices x instance Find V.Vector where findIndex x = V.findIndex x findIndices x = V.findIndices x instance Find UV.Vector where findIndex f xs = readUnbox (UV.findIndex f) xs findIndices f xs = readUnbox (UV.findIndices f) xs class Slice v where slice :: (Storage v d) => Int -> Int -> v d -> v d instance Slice [] where slice start num = List.take num . List.drop start instance Slice V.Vector where slice = V.slice instance Slice UV.Vector where slice start num = readUnbox (UV.slice start num) class Split v where drop, take :: (Storage v d) => Int -> v d -> v d splitAt :: (Storage v d) => Int -> v d -> (v d, v d) instance Split [] where drop = List.drop take = List.take splitAt = List.splitAt instance Split V.Vector where drop = V.drop take = V.take splitAt = V.splitAt instance Split UV.Vector where drop k = readUnbox (UV.drop k) take k = readUnbox (UV.take k) splitAt k = readUnbox (UV.splitAt k) class SplitMatch v where dropMatch :: (Storage v b, Storage v d, Storage (Core v) d) => v b -> v d -> Core v d takeMatch :: (Storage v b, Storage v d) => v b -> v d -> v d splitAtMatch :: (Storage v b, Storage v d) => v b -> v d -> (v d, Core v d) instance SplitMatch v => SplitMatch (NonEmpty.T v) where dropMatch = readNonEmpty $ \(NonEmpty.Cons _ xs) -> readNonEmpty $ \(NonEmpty.Cons _ ys) -> dropMatch xs ys takeMatch = readNonEmpty $ \(NonEmpty.Cons _ xs) -> readNonEmpty $ \(NonEmpty.Cons y ys) -> NonEmpty.Cons y $ takeMatch xs ys splitAtMatch = readNonEmpty $ \(NonEmpty.Cons _ xs) -> readNonEmpty $ \(NonEmpty.Cons y ys) -> mapFst (NonEmpty.Cons y) $ splitAtMatch xs ys instance SplitMatch [] where dropMatch = Match.drop takeMatch = Match.take splitAtMatch = Match.splitAt instance SplitMatch V.Vector where dropMatch = drop . length takeMatch = take . length splitAtMatch = splitAt . length instance SplitMatch UV.Vector where dropMatch = drop . length takeMatch = take . length splitAtMatch = splitAt . length cumulate :: (Num a) => NonEmpty.T [] a -> [a] -> [a] cumulate storage = NonEmpty.tail . NonEmpty.scanl (+) (NonEmpty.last storage) decumulate :: (Num a) => NonEmpty.T [] a -> [a] -> [a] decumulate inStorage outStorage = ListHT.mapAdjacent subtract $ NonEmpty.last inStorage : outStorage propCumulate :: NonEmpty.T [] Integer -> [Integer] -> Bool propCumulate storage incoming = decumulate storage (cumulate storage incoming) == incoming -- | creates a vector of unique and sorted elements class Unique v d where unique :: Ord d => v d -> v d instance Unique [] d where unique = Set.toList . Set.fromList instance Unique V.Vector d where unique = fromList . Set.toList . Set.fromList . toList instance (UV.Unbox d) => Unique UV.Vector d where unique = readUnbox (fromList . Set.toList . Set.fromList . toList) {- might be moved to non-empty package -} argMaximumKey :: (Fold.Foldable f, Ord b) => (a -> b) -> NonEmpty.T f a -> (Int, a) argMaximumKey f (NonEmpty.Cons x xs) = snd $ snd $ Fold.foldl (\(pos, (maxMeas, (maxPos, maxVal))) xi -> (succ pos, let fx = f xi in if fx>maxMeas then (fx, (pos,xi)) else (maxMeas, (maxPos,maxVal)))) (1, (f x, (0,x))) xs argMaximum :: (Fold.Foldable f, Ord a) => NonEmpty.T f a -> (Int, a) argMaximum = argMaximumKey id {- The Functor constraint could be saved by merging the fmap with the fold. 'f' is evaluated twice for every sub-maximum. Does this hurt? -} argMaximumKey2 :: (Functor f, Fold.Foldable f, Fold.Foldable g, Ord b) => (a -> b) -> NonEmpty.T f (NonEmpty.T g a) -> ((Int, Int), a) argMaximumKey2 f = (\(n,(m,a)) -> ((n,m), a)) . argMaximumKey (f . snd) . fmap (argMaximumKey f) argMaximum2 :: (Functor f, Fold.Foldable f, Fold.Foldable g, Ord a) => NonEmpty.T f (NonEmpty.T g a) -> ((Int, Int), a) argMaximum2 = argMaximumKey2 id
energyflowanalysis/efa-2.1
src/EFA/Data/Vector.hs
Haskell
bsd-3-clause
20,581
module Auto.Score ( BitString , bitStringToNum , mutateBitString , crossBitString , numToBitString , makeIndividual , makePopulation , flipBitAt ) where import Data.Array import System.Random -- type ScoreType = Double -- class Score a where -- score :: a -> ScoreType type BitString = Array Int Bool -- Make a bitstring of size i. makeBitString :: Int -> BitString makeBitString i = array (0,i-1) [(j,False) | j <- [0..i-1]] -- Convert bitstring to number. bitStringToNum :: BitString -> Int bitStringToNum arr = go $ assocs arr where go [] = 0 go ((_,False):xs) = go xs go ((i,True):xs) = (2^i) + (go xs) -- Flip bit at i in bitstring. mutateBitString :: BitString -> Int -> BitString mutateBitString arr i = arr // [(i,b)] where b = not $ arr ! i -- Crossover bitstrings arr1 and arr2. crossBitString :: BitString -> BitString -> Int -> BitString crossBitString arr1 arr2 i = array s l where s = bounds arr1 l = zipWith f (assocs arr1) (assocs arr2) f (i1,v1) (_,v2) | (i1 < i) = (i1,v1) | otherwise = (i1,v2) -- Convert int to list of 0s and 1s. numToBits :: Int -> [Int] numToBits 0 = [] numToBits y = let (a,b) = quotRem y 2 in [b] ++ numToBits a -- Make bitstring of number i and length s. numToBitString :: Int -> Int -> BitString numToBitString i s = makeBitString s // str where str = zip [0..] $ map (== 1) $ numToBits i makeIndividual :: Int -> Int -> StdGen -> Array Int BitString makeIndividual bits params g = listArray (0,params-1) strings where nums = take params $ randomRs (0, 2 ^ bits - 1) g strings = map (flip numToBitString bits) nums makePopulation :: Int -> Int -> Int -> StdGen -> [Array Int BitString] makePopulation 0 _ _ _ = [] makePopulation popSize bits params g = ind : restPop where (g',g'') = split g restPop = makePopulation (popSize-1) bits params g'' ind = makeIndividual bits params g' flipBitAt :: Int -> Int -> Array Int BitString -> Array Int BitString flipBitAt b p bstr = bstr // [(p,ind)] where ind = mutateBitString (bstr ! p) b
iu-parfunc/AutoObsidian
src/Auto/Score.hs
Haskell
bsd-3-clause
2,161
{-# LANGUAGE CPP #-} #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Trustworthy #-} #endif {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Monad.Trans.Either -- Copyright : (C) 2008-2014 Edward Kmett -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : provisional -- Portability : MPTCs -- -- This module provides a minimalist 'Either' monad transformer. ----------------------------------------------------------------------------- module Control.Monad.Trans.Either ( EitherT(..) , eitherT , bimapEitherT , mapEitherT , hoistEither , left , right ) where import Control.Applicative import Control.Monad (liftM, MonadPlus(..)) import Control.Monad.Base (MonadBase(..), liftBaseDefault) import Control.Monad.Cont.Class import Control.Monad.Error.Class import Control.Monad.Free.Class import Control.Monad.Catch as MonadCatch import Control.Monad.Fix import Control.Monad.IO.Class import Control.Monad.Reader.Class import Control.Monad.State (MonadState,get,put) import Control.Monad.Trans.Class import Control.Monad.Trans.Control (MonadBaseControl(..), MonadTransControl(..), defaultLiftBaseWith, defaultRestoreM) import Control.Monad.Writer.Class import Control.Monad.Random (MonadRandom,getRandom,getRandoms,getRandomR,getRandomRs) import Data.Foldable import Data.Function (on) import Data.Functor.Bind import Data.Functor.Plus import Data.Traversable import Data.Semigroup -- | 'EitherT' is a version of 'Control.Monad.Trans.Error.ErrorT' that does not -- require a spurious 'Control.Monad.Error.Class.Error' instance for the 'Left' -- case. -- -- 'Either' is a perfectly usable 'Monad' without such a constraint. 'ErrorT' is -- not the generalization of the current 'Either' monad, it is something else. -- -- This is necessary for both theoretical and practical reasons. For instance an -- apomorphism is the generalized anamorphism for this Monad, but it cannot be -- written with 'ErrorT'. -- -- In addition to the combinators here, the @errors@ package provides a large -- number of combinators for working with this type. newtype EitherT e m a = EitherT { runEitherT :: m (Either e a) } instance Show (m (Either e a)) => Show (EitherT e m a) where showsPrec d (EitherT m) = showParen (d > 10) $ showString "EitherT " . showsPrec 11 m {-# INLINE showsPrec #-} instance Read (m (Either e a)) => Read (EitherT e m a) where readsPrec d = readParen (d > 10) (\r' -> [ (EitherT m, t) | ("EitherT", s) <- lex r' , (m, t) <- readsPrec 11 s]) {-# INLINE readsPrec #-} instance Eq (m (Either e a)) => Eq (EitherT e m a) where (==) = (==) `on` runEitherT {-# INLINE (==) #-} instance Ord (m (Either e a)) => Ord (EitherT e m a) where compare = compare `on` runEitherT {-# INLINE compare #-} -- | Given a pair of actions, one to perform in case of failure, and one to perform -- in case of success, run an 'EitherT' and get back a monadic result. eitherT :: Monad m => (a -> m c) -> (b -> m c) -> EitherT a m b -> m c eitherT f g (EitherT m) = m >>= \z -> case z of Left a -> f a Right b -> g b {-# INLINE eitherT #-} -- | Analogous to 'Left'. Equivalent to 'throwError'. left :: Monad m => e -> EitherT e m a left = EitherT . return . Left {-# INLINE left #-} -- | Analogous to 'Right'. Equivalent to 'return'. right :: Monad m => a -> EitherT e m a right = return {-# INLINE right #-} -- | Map over both failure and success. bimapEitherT :: Functor m => (e -> f) -> (a -> b) -> EitherT e m a -> EitherT f m b bimapEitherT f g (EitherT m) = EitherT (fmap h m) where h (Left e) = Left (f e) h (Right a) = Right (g a) {-# INLINE bimapEitherT #-} -- | Map the unwrapped computation using the given function. -- -- @ -- 'runEitherT' ('mapEitherT' f m) = f ('runEitherT' m) -- @ mapEitherT :: (m (Either e a) -> n (Either e' b)) -> EitherT e m a -> EitherT e' n b mapEitherT f m = EitherT $ f (runEitherT m) {-# INLINE mapEitherT #-} -- | Lift an 'Either' into an 'EitherT' hoistEither :: Monad m => Either e a -> EitherT e m a hoistEither = EitherT . return {-# INLINE hoistEither #-} instance Monad m => Functor (EitherT e m) where fmap f = EitherT . liftM (fmap f) . runEitherT {-# INLINE fmap #-} instance Monad m => Apply (EitherT e m) where EitherT f <.> EitherT v = EitherT $ f >>= \mf -> case mf of Left e -> return (Left e) Right k -> v >>= \mv -> case mv of Left e -> return (Left e) Right x -> return (Right (k x)) {-# INLINE (<.>) #-} instance Monad m => Applicative (EitherT e m) where pure a = EitherT $ return (Right a) {-# INLINE pure #-} EitherT f <*> EitherT v = EitherT $ f >>= \mf -> case mf of Left e -> return (Left e) Right k -> v >>= \mv -> case mv of Left e -> return (Left e) Right x -> return (Right (k x)) {-# INLINE (<*>) #-} instance (Monad m, Monoid e) => Alternative (EitherT e m) where EitherT m <|> EitherT n = EitherT $ m >>= \a -> case a of Left l -> liftM (\b -> case b of Left l' -> Left (mappend l l') Right r -> Right r) n Right r -> return (Right r) {-# INLINE (<|>) #-} empty = EitherT $ return (Left mempty) {-# INLINE empty #-} instance (Monad m, Monoid e) => MonadPlus (EitherT e m) where mplus = (<|>) {-# INLINE mplus #-} mzero = empty {-# INLINE mzero #-} instance Monad m => Semigroup (EitherT e m a) where EitherT m <> EitherT n = EitherT $ m >>= \a -> case a of Left _ -> n Right r -> return (Right r) {-# INLINE (<>) #-} instance (Monad m, Semigroup e) => Alt (EitherT e m) where EitherT m <!> EitherT n = EitherT $ m >>= \a -> case a of Left l -> liftM (\b -> case b of Left l' -> Left (l <> l') Right r -> Right r) n Right r -> return (Right r) {-# INLINE (<!>) #-} instance Monad m => Bind (EitherT e m) where (>>-) = (>>=) {-# INLINE (>>-) #-} instance Monad m => Monad (EitherT e m) where return a = EitherT $ return (Right a) {-# INLINE return #-} m >>= k = EitherT $ do a <- runEitherT m case a of Left l -> return (Left l) Right r -> runEitherT (k r) {-# INLINE (>>=) #-} fail = EitherT . fail {-# INLINE fail #-} instance Monad m => MonadError e (EitherT e m) where throwError = EitherT . return . Left {-# INLINE throwError #-} EitherT m `catchError` h = EitherT $ m >>= \a -> case a of Left l -> runEitherT (h l) Right r -> return (Right r) {-# INLINE catchError #-} -- | Throws exceptions into the base monad. instance MonadThrow m => MonadThrow (EitherT e m) where throwM = lift . throwM {-# INLINE throwM #-} -- | Catches exceptions from the base monad. instance MonadCatch m => MonadCatch (EitherT e m) where catch (EitherT m) f = EitherT $ MonadCatch.catch m (runEitherT . f) {-# INLINE catch #-} instance MonadFix m => MonadFix (EitherT e m) where mfix f = EitherT $ mfix $ \a -> runEitherT $ f $ case a of Right r -> r _ -> error "empty mfix argument" {-# INLINE mfix #-} instance MonadTrans (EitherT e) where lift = EitherT . liftM Right {-# INLINE lift #-} instance MonadIO m => MonadIO (EitherT e m) where liftIO = lift . liftIO {-# INLINE liftIO #-} instance MonadCont m => MonadCont (EitherT e m) where callCC f = EitherT $ callCC $ \c -> runEitherT (f (\a -> EitherT $ c (Right a))) {-# INLINE callCC #-} instance MonadReader r m => MonadReader r (EitherT e m) where ask = lift ask {-# INLINE ask #-} local f (EitherT m) = EitherT (local f m) {-# INLINE local #-} instance MonadState s m => MonadState s (EitherT e m) where get = lift get {-# INLINE get #-} put = lift . put {-# INLINE put #-} instance MonadWriter s m => MonadWriter s (EitherT e m) where tell = lift . tell {-# INLINE tell #-} listen = mapEitherT $ \ m -> do (a, w) <- listen m return $! fmap (\ r -> (r, w)) a {-# INLINE listen #-} pass = mapEitherT $ \ m -> pass $ do a <- m return $! case a of Left l -> (Left l, id) Right (r, f) -> (Right r, f) {-# INLINE pass #-} instance MonadRandom m => MonadRandom (EitherT e m) where getRandom = lift getRandom {-# INLINE getRandom #-} getRandoms = lift getRandoms {-# INLINE getRandoms #-} getRandomR = lift . getRandomR {-# INLINE getRandomR #-} getRandomRs = lift . getRandomRs {-# INLINE getRandomRs #-} instance Foldable m => Foldable (EitherT e m) where foldMap f = foldMap (either mempty f) . runEitherT {-# INLINE foldMap #-} instance (Functor f, MonadFree f m) => MonadFree f (EitherT e m) where wrap = EitherT . wrap . fmap runEitherT instance (Monad f, Traversable f) => Traversable (EitherT e f) where traverse f (EitherT a) = EitherT <$> traverse (either (pure . Left) (fmap Right . f)) a {-# INLINE traverse #-} instance MonadBase b m => MonadBase b (EitherT e m) where liftBase = liftBaseDefault {-# INLINE liftBase #-} instance MonadTransControl (EitherT e) where newtype StT (EitherT e) a = StEitherT {unStEitherT :: Either e a} liftWith f = EitherT $ liftM return $ f $ liftM StEitherT . runEitherT {-# INLINE liftWith #-} restoreT = EitherT . liftM unStEitherT {-# INLINE restoreT #-} instance MonadBaseControl b m => MonadBaseControl b (EitherT e m) where newtype StM (EitherT e m) a = StMEitherT { unStMEitherT :: StM m (StT (EitherT e) a) } liftBaseWith = defaultLiftBaseWith StMEitherT {-# INLINE liftBaseWith #-} restoreM = defaultRestoreM unStMEitherT {-# INLINE restoreM #-}
phaazon/either
src/Control/Monad/Trans/Either.hs
Haskell
bsd-3-clause
9,810
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} -- import Data.Char (isPunctuation, isSpace) -- import Data.List (intercalate) -- import Data.Monoid (mappend) import Data.Text (Text) import qualified Data.Map.Strict as Map import Control.Exception (finally) import Control.Monad (forM_, forever) import Control.Concurrent (MVar, newMVar, modifyMVar_, modifyMVar, readMVar) import Control.Monad.IO.Class (liftIO) import qualified Data.Text as T import qualified Data.Text.IO as T import System.Environment (lookupEnv) import Data.Maybe (fromMaybe, fromJust) import Data.List (intercalate) import qualified Network.WebSockets as WS import System.Random (randomIO) import Warships.BattleField import Warships.Generator (brandNewField) type PlayerID = Int instance Show WS.Connection where show _ = "Connection" data Player = Player { connection :: !WS.Connection , field :: !BattleField } deriving Show type GameID = Int data ServerState = ServerState { players :: !(Map.Map PlayerID Player) } deriving Show -- | All messages that server can `broadcast` to players. data OutputMessage -- | Returns when a user searches for a game with specific ID, but it can't be found. = NotFoundGameID -- | Found game already has two players. | NoFreeSlots -- | User joined a game and received their ID. | PlayerID PlayerID | Own BattleField | Enemy BattleField deriving Eq instance Show OutputMessage where show NotFoundGameID = "NotFoundGameID" show NoFreeSlots = "NoFreeSlots" show (PlayerID pID) = "PlayerID " ++ show pID show (Own bf) = "Own " ++ displayOwnField bf show (Enemy bf) = "Enemy " ++ displayEnemysField bf -- | All messages that server accepts. data IntputMessage -- | User joins an existing game. = JoinGame PlayerID -- | User attacks enemy's field. | Attack deriving (Read, Show, Eq) getEnvWithDefault :: String -> String -> IO String getEnvWithDefault name defaultValue = do x <- lookupEnv name return $ fromMaybe defaultValue x newServerState :: ServerState newServerState = ServerState Map.empty addClient :: PlayerID -> Player -> ServerState -> ServerState addClient pID player state = state { players = Map.insert pID player (players state) } removeClient :: PlayerID -> ServerState -> ServerState removeClient pID s = s { players = Map.delete pID (players s) } broadcast :: Text -> ServerState -> IO () broadcast message ServerState{..} = do T.putStrLn message forM_ (map connection $ Map.elems players) (`WS.sendTextData` message) main :: IO () main = do state <- newMVar newServerState port <- read <$> getEnvWithDefault "PORT" "3636" :: IO Int host <- getEnvWithDefault "HOST" "0.0.0.0" putStrLn ("Running server on " ++ host ++ ":" ++ show port) WS.runServer host port $ application state application :: MVar ServerState -> WS.ServerApp application state pending = do client <- WS.acceptRequest pending pID <- abs <$> randomIO WS.forkPingThread client 30 msg <- WS.receiveData client :: IO T.Text let disconnect = modifyMVar_ state $ \s -> return (removeClient pID s) flip finally disconnect $ do liftIO $ modifyMVar_ state $ \s -> do field <- brandNewField return (addClient pID (Player client field) s) s <- readMVar state print s broadcastPlayer s pID talk pID client state broadcastM :: OutputMessage -> WS.Connection -> IO () broadcastM msg conn = do T.putStrLn (T.pack (show msg)) WS.sendTextData conn (T.pack (show msg)) broadcastPlayer :: ServerState -> PlayerID -> IO () broadcastPlayer ServerState{..} pID = case Map.lookup pID players of Just Player{..} -> do broadcastM (PlayerID pID) connection broadcastM (Own field) connection Nothing -> return () talk :: PlayerID -> WS.Connection -> MVar ServerState -> IO () talk pID conn state = forever $ do msg <- T.unpack <$> WS.receiveData conn :: IO String s' <- readMVar state print msg print s' case read msg of -- NewGame -> do -- gameID <- randomIO -- modifyMVar_ state $ \s -> return $ s { games = Map.insert gameID () (games s) } -- broadcastMessage (NewGameID gameID) s' JoinGame gID -> case Map.lookup gID (players s') of Just (Player c f) -> do broadcastM (Enemy f) conn broadcastM (Enemy (field $ fromJust $ Map.lookup pID (players s'))) c Nothing -> broadcastM NotFoundGameID conn -- Attack -> do -- let f' = attack (read msg) (field s') -- if gameComplete f' -- then do -- f'' <- brandNewField -- modifyMVar_ state $ \s -> return $ s { field = f'' } -- else -- modifyMVar_ state $ \s -> return $ s { field = f' } -- liftIO $ readMVar state >>= broadcastField -- gameComplete :: BattleField -> Bool -- gameComplete = all (==0) . Map.elems . ships -- broadcastField :: ServerState -> IO () -- broadcastField state@ServerState{..} = -- broadcast (displayField field) state displayOwnField :: BattleField -> String displayOwnField = displayField "H" displayEnemysField :: BattleField -> String displayEnemysField = displayField "E" displayField :: String -> BattleField -> String displayField hiddenShip bf = intercalate "" [ intercalate "" [ sc $ getCell (x, y) bf | y <- [0..height bf - 1] ] | x <- [0..width bf - 1] ] where sc Empty = "E" sc Miss = "M" sc (Ship Hidden _) = hiddenShip sc (Ship Injured _) = "I" sc (Ship Killed _) = "K"
triplepointfive/battleship
app/Main.hs
Haskell
bsd-3-clause
5,602
module Day1 where import Data.List (findIndex, inits) -- slower than a foldr (does 2 passes over input), but more readable/declarative floorCount :: String -> Int floorCount input = ups - downs where ups = charCount '(' input downs = charCount ')' input charCount c = length . filter (== c) floorCount2 :: String -> Int floorCount2 = foldr ((+) . parenvals) 0 where parenvals '(' = 1 parenvals ')' = -1 parenvals _ = 0 hitBasement :: String -> Maybe Int hitBasement input = findIndex (< 0) trip where trip = map floorCount $ inits input solution :: String -> IO () solution input = do print $ floorCount input -- part 1 print $ hitBasement input -- part 2
yarbroughw/advent
src/Day1.hs
Haskell
bsd-3-clause
706
{-# LANGUAGE TypeFamilies #-} module Language.Shelspel.Codegen.Bash where import Language.Shelspel.AST import Language.Shelspel.Codegen.Types import Control.Monad codegen :: Program -> String codegen prog = script where bash = flip execState empty $ cgen prog script = foldl (++) "" $ reverse bash type Bash = [String] empty :: Bash empty = [] type instance S = Bash type instance R = () -- -------------------------------------------------------------------------------- -- | Weave two actions through the code generator. The first is called -- on each element, then the second action is executed. weave :: (a -> State S R) -> State S R -> [a] -> State S R weave f a = mapM_ (\x -> f x >> a) -- | Weave a call to 'cgen' over each list. -- -- This can be used, eg, to to intercalate semicolons or newlines: -- > nl `cgweave` program -- > semic `cgweave` program cgweave :: CGen x => State S R -> [x] -> State S R cgweave = weave cgen -- | Insert an element into the stream stream :: String -> State S R stream s = modify (s:) -- | Insert a newline (\n) into the stream nl :: State S R nl = stream "\n" -- | Call the element as a subprocess. E.g. -- -- > $(echo "hello world") subproc :: CGen x => x -> State S R subproc x = do stream "$(" cgen x stream ")" -- | Evaluate the expression as a mathematical expression -- -- > $(( 40 + 2 )) math :: Expr -> State S R math e = do stream "$((" stream " " cgen e stream " " stream "))" -- | Insert a semicolon (;) semic :: State S R semic = stream ";" -- -------------------------------------------------------------------------------- -- instance CGen Expr where cgen (Literal s) = stream $ "\"" ++ s ++ "\"" cgen (Var i) = stream $ "${" ++ i ++ "}" cgen (BinOp o x y) = do stream "$(( " cgen x stream " " cgen o stream " " cgen y stream " ))" instance CGen Op where cgen Add = stream "+" cgen Sub = stream "-" cgen Mul = stream "*" cgen Div = stream "/" cgen (Compare o) = cgen o instance CGen Ordering where cgen LT = stream "-lt" cgen EQ = stream "-eq" cgen GT = stream "-gt" instance CGen CompoundStatement where cgen (Match e ms) = do stream "case " cgen e stream " in" nl forM_ ms $ \(m, as) -> do cgen m stream ")" nl nl `cgweave` as nl semic >> semic cgen (For i a cs) = do stream "for " stream i stream " in " subproc a semic stream "do" nl nl `cgweave` cs stream "done" cgen (While a cs) = do stream "while" stream " " stream "[[" stream " " cgen a stream " " stream "]]" nl stream "do" nl nl `cgweave` cs stream "done" instance CGen Action where cgen (Call i as) = do stream i stream " " (stream " ") `cgweave` as cgen (Cmpd s) = cgen s cgen (Pipe c a) = do cgen c stream " | " cgen a cgen (Sink a s p m) = do cgen a stream " " cgen m stream p stream " " cgen s cgen (Store i c) = do stream i stream "=" subproc c cgen (Eval e) = do stream "# Bare expressions are not supported: " cgen e cgen (Result c) = stream $ "return " ++ show c instance CGen Mode where cgen Write = stream ">" cgen Append = stream ">>" instance CGen Captured where cgen (Captured s a) = do cgen a stream " " cgen s instance CGen Stream where cgen Stdout = stream "" cgen Stderr = stream "3>&1 1>&2- 2>&3-" -- swap stderr and stdout cgen All = stream "2>&1" instance CGen Cmd where cgen (Execute a) = cgen a cgen (Funcdef i ps cs) = do stream "function" stream " " stream i stream "()" stream " " stream "{" nl let define i n = stream "local " >> def i n def i n = cgen $ Define n $ Literal $ "${" ++ show i ++ "}" weave (uncurry define) nl $ zip [1..] ps nl nl `cgweave` cs stream "}" nl cgen (Define i e) = do stream i stream "=" cgen e instance CGen Program where cgen (Program cs) = nl `cgweave` cs
badi/shelspel
src/Language/Shelspel/Codegen/Bash.hs
Haskell
bsd-3-clause
4,704
{-# LANGUAGE OverloadedStrings, ViewPatterns #-} import Control.Exception (catch, SomeException) import Control.Monad import Control.Monad.Trans (liftIO) import qualified Data.ByteString.UTF8 as B import Data.List (isPrefixOf, sortBy) import Data.Maybe import Safe (readMay) import System.Directory import System.Environment import System.Exit import System.IO (withFile, IOMode(ReadWriteMode)) import System.Process import Pygmalion.Config import Pygmalion.Core import Pygmalion.File import Pygmalion.Log import Pygmalion.Make import Pygmalion.RPC.Client --import Pygmalion.JSON main :: IO () main = do args <- getArgs parseConfiglessArgs args $ do cf <- getConfiguration initLogger (logLevel cf) wd <- getCurrentDirectory parseArgs cf wd args usage :: IO () usage = do putStrLn $ "Usage: " ++ queryExecutable ++ " [command]" putStrLn "where [command] is one of the following:" putStrLn " help Prints this message." putStrLn " start-server Starts the pygmalion daemon." putStrLn " stop-server Terminates the pygmalion daemon." putStrLn " init Initializes a pygmalion index rooted at" putStrLn " the current directory." putStrLn " make [command] Runs the provided command, observes the calls to" putStrLn " compilers it makes, and indexes the compiled files." putStrLn " index ([file]|[command]) Manually request indexing. If a single" putStrLn " argument is provided, it's interpreted" putStrLn " as a file to index using the default" putStrLn " compiler flags. Multiple arguments are" putStrLn " interpreted as a compiler invocation" putStrLn " (e.g. 'clang -c file.c') and the compiler" putStrLn " flags to use will be extracted appropriately." putStrLn " wait Blocks until all previous requests have been" putStrLn " handled by the pygmalion daemon." putStrLn " generate-compile-commands Prints a clang compilation database." putStrLn " compile-flags [file] Prints the compilation flags for the" putStrLn " given file, or nothing on failure. If" putStrLn " the file isn't in the database, a guess" putStrLn " will be printed if possible." putStrLn " working-directory [file] Prints the working directory at the time" putStrLn " the file was compiled. Guesses if needed." putStrLn " inclusions [file] Lists the files included by the given file." putStrLn " includers [file] Lists the files which include the given file." putStrLn " inclusion-hierarchy [file] Prints a graphviz graph showing the inclusion" putStrLn " hierarchy of the given file." putStrLn " definition [file] [line] [col]" putStrLn " declaration [file] [line] [col]" putStrLn " callers [file] [line] [col]" putStrLn " callees [file] [line] [col]" putStrLn " bases [file] [line] [col]" putStrLn " overrides [file] [line] [col]" putStrLn " members [file] [line] [col]" putStrLn " references [file] [line] [col]" putStrLn " hierarchy [file] [line] [col] Prints a graphviz graph showing the inheritance" putStrLn " hierarchy of the identifier at this location." bail parseConfiglessArgs :: [String] -> IO () -> IO () parseConfiglessArgs ["init"] _ = initialize parseConfiglessArgs ["help"] _ = usage parseConfiglessArgs [] _ = usage parseConfiglessArgs _ c = c parseArgs :: Config -> FilePath -> [String] -> IO () parseArgs _ _ ["start-server"] = startServer parseArgs c _ ["stop-server"] = stopServer c parseArgs c wd ("index" : file : []) = asSourceFile wd file >>= indexFile c parseArgs c _ ("index" : cmd : args) = indexUserCommand c cmd args parseArgs c _ ("make" : args) = makeCommand c args parseArgs c _ ("wait" : []) = waitForServer c parseArgs c _ ["generate-compile-commands"] = printCDB c parseArgs c wd ["compile-flags", f] = asSourceFile wd f >>= printFlags c parseArgs c wd ["working-directory", f] = asSourceFile wd f >>= printDir c parseArgs c wd ["inclusions", f] = asSourceFile wd f >>= printInclusions c parseArgs c wd ["includers", f] = asSourceFile wd f >>= printIncluders c parseArgs c wd ["inclusion-hierarchy", f] = asSourceFile wd f >>= printInclusionHierarchy c parseArgs c wd ["definition", f, line, col] = do sf <- asSourceFile wd f printDef c sf (readMay line) (readMay col) parseArgs c wd ["declaration", f, line, col] = do sf <- asSourceFile wd f printDecl c sf (readMay line) (readMay col) parseArgs c wd ["callers", f, line, col] = do sf <- asSourceFile wd f printCallers c sf (readMay line) (readMay col) parseArgs c wd ["callees", f, line, col] = do sf <- asSourceFile wd f printCallees c sf (readMay line) (readMay col) parseArgs c wd ["bases", f, line, col] = do sf <- asSourceFile wd f printBases c sf (readMay line) (readMay col) parseArgs c wd ["overrides", f, line, col] = do sf <- asSourceFile wd f printOverrides c sf (readMay line) (readMay col) parseArgs c wd ["members", f, line, col] = do sf <- asSourceFile wd f printMembers c sf (readMay line) (readMay col) parseArgs c wd ["references", f, line, col] = do sf <- asSourceFile wd f printRefs c sf (readMay line) (readMay col) parseArgs c wd ["hierarchy", f, line, col] = do sf <- asSourceFile wd f printHierarchy c sf (readMay line) (readMay col) parseArgs _ _ _ = usage startServer :: IO () startServer = void $ waitForProcess =<< runCommand "pygd" stopServer :: Config -> IO () stopServer cf = withRPC cf $ runRPC rpcStop initialize :: IO () initialize = do putStrLn "Initializing a pygmalion index..." createDirectoryIfMissing True pygmalionDir withFile configFile ReadWriteMode (\_ -> return ()) indexFile :: Config -> SourceFile -> IO () indexFile cf f = do mayMTime <- getMTime f case mayMTime of Just mtime -> withRPC cf $ runRPC (rpcIndexFile f mtime) Nothing -> putStrLn $ "Couldn't read file " ++ show f makeCommand :: Config -> [String] -> IO () makeCommand cf args = do let cmd = if null args then "" else head args args' = if null args then [] else tail args -- Make sure pygd is running. withRPC cf (runRPC rpcPing) `catch` handleRPCFailure -- Observe the build process. code <- observeMake cf cmd args' case code of ExitSuccess -> return () _ -> liftIO $ bailWith' code $ queryExecutable ++ ": Command failed" where handleRPCFailure :: SomeException -> IO () handleRPCFailure _ = putStrLn $ "Can't connect to pygd. " ++ "Build information will not be recorded." waitForServer :: Config -> IO () waitForServer cf = withRPC cf $ runRPC rpcWait -- FIXME: Reimplement with RPC. printCDB :: Config -> IO () {- printCDB = withDB $ \h -> getAllSourceFiles h >>= putStrLn . sourceRecordsToJSON -} printCDB = undefined printFlags :: Config -> SourceFile -> IO () printFlags cf f = getCommandInfoOr bail f cf >>= putFlags where putFlags (ciArgs -> args) = putStrLn . unwords . map B.toString $ args printDir :: Config -> SourceFile -> IO () printDir cf f = getCommandInfoOr bail f cf >>= putDir where putDir (ciWorkingPath -> wd) = putStrLn . B.toString $ wd getCommandInfoOr :: IO () -> SourceFile -> Config -> IO CommandInfo getCommandInfoOr a f cf = do cmd <- withRPC cf $ runRPC (rpcGetSimilarCommandInfo f) unless (isJust cmd) a return . fromJust $ cmd printInclusions :: Config -> SourceFile -> IO () printInclusions cf file = do is <- withRPC cf $ runRPC (rpcGetInclusions file) mapM_ putInclusion (sortBy (locationOrder cf) is) where putInclusion sf = putStrLn $ unSourceFile sf ++ ":1:1: Inclusion of " ++ unSourceFile file printIncluders :: Config -> SourceFile -> IO () printIncluders cf file = do is <- withRPC cf $ runRPC (rpcGetIncluders file) mapM_ putIncluder (sortBy (locationOrder cf) is) where putIncluder sf = putStrLn $ unSourceFile sf ++ ":1:1: Includer of " ++ unSourceFile file locationOrder :: Config -> SourceFile -> SourceFile -> Ordering locationOrder cf a b | inProject a && inProject b = compare a b | inProject a = LT | inProject b = GT | otherwise = compare a b where inProject f = projectDir cf `isPrefixOf` unSourceFile f printInclusionHierarchy :: Config -> SourceFile -> IO () printInclusionHierarchy cf file = do dotGraph <- withRPC cf $ runRPC (rpcGetInclusionHierarchy file) case dotGraph of [] -> putStrLn "diGraph G {}" -- Print an empty graph instead of an error. _ -> putStrLn dotGraph printDef :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO () printDef = queryCmd "definition" rpcGetDefinition putDef where putDef (DefInfo n _ (SourceLocation idF idLine idCol) k _) = putStrLn $ unSourceFile idF ++ ":" ++ show idLine ++ ":" ++ show idCol ++ ": Definition: " ++ B.toString n ++ " [" ++ show k ++ "]" printDecl :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO () printDecl = queryCmd "declaration" rpcGetDeclReferenced putDecl where putDecl (DefInfo n _ (SourceLocation idF idLine idCol) k _) = putStrLn $ unSourceFile idF ++ ":" ++ show idLine ++ ":" ++ show idCol ++ ": Declaration: " ++ B.toString n ++ " [" ++ show k ++ "]" printCallers :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO () printCallers = queryCmd "caller" rpcGetCallers putCaller where putCaller (Invocation (DefInfo n _ _ _ _) (SourceLocation idF idLine idCol)) = putStrLn $ unSourceFile idF ++ ":" ++ show idLine ++ ":" ++ show idCol ++ ": Caller: " ++ B.toString n printCallees :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO () printCallees = queryCmd "callee" rpcGetCallees putCallee where putCallee (DefInfo n _ (SourceLocation idF idLine idCol) k _) = putStrLn $ unSourceFile idF ++ ":" ++ show idLine ++ ":" ++ show idCol ++ ": Callee: " ++ B.toString n ++ " [" ++ show k ++ "]" printBases :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO () printBases = queryCmd "base" rpcGetBases putBase where putBase (DefInfo n _ (SourceLocation idF idLine idCol) k _) = putStrLn $ unSourceFile idF ++ ":" ++ show idLine ++ ":" ++ show idCol ++ ": Base: " ++ B.toString n ++ " [" ++ show k ++ "]" printOverrides :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO () printOverrides = queryCmd "override" rpcGetOverrides putOverride where putOverride (DefInfo n _ (SourceLocation idF idLine idCol) k _) = putStrLn $ unSourceFile idF ++ ":" ++ show idLine ++ ":" ++ show idCol ++ ": Override: " ++ B.toString n ++ " [" ++ show k ++ "]" printMembers :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO () printMembers = queryCmd "member" rpcGetMembers putMember where putMember (DefInfo n _ (SourceLocation idF idLine idCol) k _) = putStrLn $ unSourceFile idF ++ ":" ++ show idLine ++ ":" ++ show idCol ++ ": Member: " ++ B.toString n ++ " [" ++ show k ++ "]" printRefs :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO () printRefs = queryCmd "reference" rpcGetRefs putRef where putRef (SourceReference (SourceLocation idF idLine idCol) k ctx) = putStrLn $ unSourceFile idF ++ ":" ++ show idLine ++ ":" ++ show idCol ++ ": Reference: " ++ B.toString ctx ++ " [" ++ show k ++ "]" printHierarchy :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO () printHierarchy cf file (Just line) (Just col) = do dotGraph <- withRPC cf $ runRPC (rpcGetHierarchy (SourceLocation file line col)) case dotGraph of [] -> putStrLn "diGraph G {}" -- Print an empty graph instead of an error. _ -> putStrLn dotGraph printHierarchy _ _ _ _ = usage queryCmd :: String -> (SourceLocation -> RPC [a]) -> (a -> IO ()) -> Config -> SourceFile -> Maybe Int -> Maybe Int -> IO () queryCmd item rpcCall f cf file (Just line) (Just col) = do results <- withRPC cf $ runRPC (rpcCall (SourceLocation file line col)) case results of [] -> bailWith (errMsg item file line col) _ -> mapM_ f results queryCmd _ _ _ _ _ _ _ = usage errMsg :: String -> SourceFile -> SourceLine -> SourceCol -> String errMsg item f line col = errPrefix ++ "No " ++ item ++ " available for an identifier at this " ++ "location. Make sure the file compiles with no errors " ++ "and the index is up-to-date." where errPrefix = unSourceFile f ++ ":" ++ show line ++ ":" ++ show col ++ ": " bail :: IO () bail = exitWith (ExitFailure (-1)) bail' :: ExitCode -> IO () bail' = exitWith bailWith :: String -> IO () bailWith s = putStrLn s >> bail bailWith' :: ExitCode -> String -> IO () bailWith' code s = putStrLn s >> bail' code
sethfowler/pygmalion
tools/Pygmalion.hs
Haskell
bsd-3-clause
13,828
-- Copyright (c) 2012-2013, Christoph Pohl BSD License (see -- http://www.opensource.org/licenses/BSD-3-Clause) ------------------------------------------------------------------------------- -- -- Project Euler Problem 13 -- -- The following iterative sequence is defined for the set of positive -- integers: -- -- n → n/2 (n is even) n → 3n + 1 (n is odd) -- -- Using the rule above and starting with 13, we generate the following -- sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 -- -- It can be seen that this sequence (starting at 13 and finishing at 1) -- contains 10 terms. Although it has not been proved yet (Collatz Problem), it -- is thought that all starting numbers finish at 1. -- -- Which starting number, under one million, produces the longest chain? -- -- NOTE: Once the chain starts the terms are allowed to go above one million. module Main where import Data.List import Data.Maybe main :: IO () main = print result result = 1 + fromMaybe 0 (elemIndex (maximum(listOfLengths)) listOfLengths) listOfLengths :: [Int] listOfLengths = map collatzLength [1..1000000] collatzLength :: Integer -> Int collatzLength n = collatzLength' n 1 collatzLength' :: Integer -> Int -> Int collatzLength' n acc | n == 1 = acc | even n = collatzLength' (n `div` 2) (acc+1) | otherwise = collatzLength' (3*n + 1) (acc+1)
Psirus/euler
src/euler014.hs
Haskell
bsd-3-clause
1,403
{-# LANGUAGE CPP, MagicHash #-} #if __GLASGOW_HASKELL__ >= 703 {-# LANGUAGE Unsafe #-} #endif -- | -- Copyright : (c) 2010 Simon Meier -- -- Original serialization code from 'Data.Binary.Builder': -- (c) Lennart Kolmodin, Ross Patterson -- -- License : BSD3-style (see LICENSE) -- -- Maintainer : Simon Meier <iridcode@gmail.com> -- Portability : GHC -- -- Utilty module defining unchecked shifts. -- -- These functions are undefined when the amount being shifted by is -- greater than the size in bits of a machine Int#.- -- #if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__) #include "MachDeps.h" #endif module Data.ByteString.Builder.Prim.Internal.UncheckedShifts ( shiftr_w16 , shiftr_w32 , shiftr_w64 , shiftr_w , caseWordSize_32_64 ) where #if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__) import GHC.Base import GHC.Word (Word32(..),Word16(..),Word64(..)) #if WORD_SIZE_IN_BITS < 64 && __GLASGOW_HASKELL__ >= 608 import GHC.Word (uncheckedShiftRL64#) #endif #else import Data.Word #endif import Foreign ------------------------------------------------------------------------ -- Unchecked shifts -- | Right-shift of a 'Word16'. {-# INLINE shiftr_w16 #-} shiftr_w16 :: Word16 -> Int -> Word16 -- | Right-shift of a 'Word32'. {-# INLINE shiftr_w32 #-} shiftr_w32 :: Word32 -> Int -> Word32 -- | Right-shift of a 'Word64'. {-# INLINE shiftr_w64 #-} shiftr_w64 :: Word64 -> Int -> Word64 -- | Right-shift of a 'Word'. {-# INLINE shiftr_w #-} shiftr_w :: Word -> Int -> Word #if WORD_SIZE_IN_BITS < 64 shiftr_w w s = fromIntegral $ (`shiftr_w32` s) $ fromIntegral w #else shiftr_w w s = fromIntegral $ (`shiftr_w64` s) $ fromIntegral w #endif #if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__) shiftr_w16 (W16# w) (I# i) = W16# (w `uncheckedShiftRL#` i) shiftr_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftRL#` i) #if WORD_SIZE_IN_BITS < 64 shiftr_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftRL64#` i) #if __GLASGOW_HASKELL__ <= 606 -- Exported by GHC.Word in GHC 6.8 and higher foreign import ccall unsafe "stg_uncheckedShiftRL64" uncheckedShiftRL64# :: Word64# -> Int# -> Word64# #endif #else shiftr_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftRL#` i) #endif #else shiftr_w16 = shiftR shiftr_w32 = shiftR shiftr_w64 = shiftR #endif -- | Select an implementation depending on the bit-size of 'Word's. -- Currently, it produces a runtime failure if the bitsize is different. -- This is detected by the testsuite. {-# INLINE caseWordSize_32_64 #-} caseWordSize_32_64 :: a -- Value to use for 32-bit 'Word's -> a -- Value to use for 64-bit 'Word's -> a caseWordSize_32_64 f32 f64 = #if MIN_VERSION_base(4,7,0) case finiteBitSize (undefined :: Word) of #else case bitSize (undefined :: Word) of #endif 32 -> f32 64 -> f64 s -> error $ "caseWordSize_32_64: unsupported Word bit-size " ++ show s
DavidAlphaFox/ghc
libraries/bytestring/Data/ByteString/Builder/Prim/Internal/UncheckedShifts.hs
Haskell
bsd-3-clause
2,954
{-# LANGUAGE QuasiQuotes #-} import LiquidHaskell {-@ LIQUID "--no-termination "@-} import Language.Haskell.Liquid.Prelude incr x = (x, [x+1]) chk (x, [y]) = liquidAssertB (x <y) prop = chk $ incr n where n = choose 0 incr2 x = (True, 9, x, 'o', x+1) chk2 (_, _, x, _, y) = liquidAssertB (x <y) prop2 = chk2 $ incr2 n where n = choose 0 incr3 x = (x, ( (0, x+1))) chk3 (x, ((_, y))) = liquidAssertB (x <y) prop3 = chk3 (incr3 n) where n = choose 0
spinda/liquidhaskell
tests/gsoc15/unknown/pos/pair00.hs
Haskell
bsd-3-clause
471
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE AllowAmbiguousTypes #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} module Plots.API ( -- * Data types and classes PointLike , Axis , r2Axis , renderAxis , Plot , PlotState , PlotStateM , R2Backend -- * Plotable , addPlotable , addPlotable' , addPlotableL , addPlotableL' , diagramPlot -- ** Bounds , xMin, xMax , yMin, yMax , zMin, zMax -- ** Grid lines , noGridLines , addLegendEntry -- ** Ticks -- , ticks -- Grid lines -- , recentProps , cartesianLabels -- ** Axis labels -- ** Axis title -- * Legend , addLegendEntry -- Themes -- , corperateTheme -- , blackAndWhiteTheme -- * Diagrams essentials , (#) , Diagram, V2 (..), V3 (..) , SizeSpec , lc , fc , fcA -- * Optics -- ** Basis elements -- | These basis elements can be used to select a specific coordinate axis. -- These can be used henever a function has a @E v@ argument. , ex, ey, ez -- ** Common functions -- | These lens functions can be used to change some of the more advanced -- aspects of the axis. , (&) , set, (.~) , over, (%~) , (&~) , (.=), assign , (%=), modify -- * Axis adjustments -- ** Axis size -- ** Axis labels -- *** Label text , axisLabel , xAxisLabel , yAxisLabel , zAxisLabel , cartesianLabels -- *** Label position , AxisLabelPosition (..) , axesLabelPositions , axisLabelPosition -- , axisPlotProperties -- *** Label gaps , setAxisLabelGap , setAxesLabelGaps -- * Axis scaling , setAxisRatio , equalAxis -- ** Axis line type , AxisLineType (..) -- , allAxisLineType -- , xAxisLineType -- , yAxisLineType -- , zAxisLineType -- * Axis ticks -- | Placement of major and minor ticks. -- , noMinorTicks -- , noMajorTicks , module Plots.Axis.Ticks -- * Axis Tick Labels , module Plots.Axis.Labels -- ** Axis Grid , noGridLines , noGridLine , setMajorGridLines , setMajorGridLine , noMajorGridLines , noMajorGridLine , setMinorGridLines , setMinorGridLine , noMinorGridLines , noMinorGridLine , allGridLines -- ** Axis Lines , middleAxisLines , boxAxisLines -- ** Axis ticks , noAxisTicks , noMajorTicks , noMinorTicks , centerAxisTicks , insideAxisTicks -- ** Axis theme , PlotStyle , plotColor , plotMarker , axisTheme , module Plots.Themes -- *** Colour bar , ColourBarOpts , ColourMap -- , C , showColourBar ) where import Control.Lens hiding (( # )) import Control.Monad.State.Lazy import Data.Default import Data.Monoid.Recommend import Data.Typeable import Diagrams.Coordinates.Isomorphic import Diagrams.Prelude hiding (r2) import Diagrams.TwoD.Text import Linear import Plots.Axis import Plots.Axis.Grid import Plots.Axis.Labels import Plots.Axis.Render import Plots.Axis.Ticks import Plots.Axis.ColourBar import Plots.Types import Plots.Themes -- import Plots.Types.Bar -- import Plots.Types.Surface -- $ pointlike -- The 'PointLike' class is used for convienience so you don't have to -- convert whatever data type you're already using. Some common -- instances are: -- -- @ -- PointLike V2 Double (Double,Double) -- PointLike V2 Double (V2 Double) -- PointLike V3 Float (Float, Float, Float) -- @ -- -- This means whenever you see @PointLike (BaseSpace v) n p@ in a type constaint, -- the @p@ in the type signature could be @(Double, Double)@ or @V2 -- Double@ or anything -- $ data -- Since the plot making functions are super-polymorphic it is -- important the that data has a concrete type signature or the compiler -- won't be able to work out which type to use. The following data is -- used thoughout the examples: -- -- @ -- pointData1 = [(1,3), (2,5.5), (3.2, 6), (3.5, 6.1)] :: [(Double,Double)] -- pointData2 = U.fromList [V2 1.2 2.7, V2 2 5.1, V2 3.2 2.6, V2 3.5 5] :: U.Vector (V2 Double) -- barData1 = [55.3, 43.2, 12.5, 18.3, 32.0] :: [Double] -- barData2 = [("apples", 55), ("oranges",43), ("pears", 12), ("mangos", 18)] :: [(String, Double)] -- @ -- | Convienient type synonym for renderable types that all the standard -- 2D backends support. type R2Backend b n = (Renderable (Path V2 n) b, Renderable (Text n) b, Typeable b, TypeableFloat n, Enum n) -- type AxisStateM b v n = State (Axis b v n) -- type AxisState b v n = AxisStateM b v n () type PlotStateM a b = State (PropertiedPlot a b) -- | The plot state allows you to use lenses for the plot @a@ as well as -- the @PlotProperties@. type PlotState a b = PlotStateM a b () -- type PropertyStateM b v n a = State (PlotProperties b v n) a -- type PropertyState b v n = State (PlotProperties b v n) () -- newtype PlotStateM p b v n = PState (State (p, PlotProperties)) -- deriving (Functor, Applicative, Monad, MonadState (P.Axis b v n)) ------------------------------------------------------------------------ -- Plot properties ------------------------------------------------------------------------ -- $properties -- Every plot has a assosiating 'PlotProperties'. These contain general -- attributes like the legend entries and the style and the name for -- the plot. -- -- There are several ways to adjust the properties. ------------------------------------------------------------------------ -- Plotable ------------------------------------------------------------------------ -- $plotable -- The 'Plotable' class defines ways of converting the data type to a -- diagram for some axis. There are several variants for adding an axis -- with constraints @('InSpace' v n a, 'Plotable' a b)@: -- -- @ -- 'addPlotable' :: a -> 'AxisState' b v n -- 'addPlotable'' :: a -> 'PlotState' a b -> 'AxisState' b v n -- 'addPlotableL' :: 'String' -> a -> 'AxisState' b v n -- 'addPlotableL'' :: 'String' -> a -> 'PlotState' a b -> 'AxisState' b v n -- @ -- -- The last argument is a 'PlotState' so you can use @do@ notation to -- make adjustments to the plot. The @L@ suffix stands for \"legend\", -- it is equivalent of using 'addLegendEntry' in the 'PlotState'. Since -- legend entries are so common it has it's own suffix. The following -- are equivalent: -- -- @ -- myaxis = 'r2Axis' &~ do -- 'addPlotable'' myplot $ do -- 'addLegendEntry' "my plot" -- @ -- -- @ -- myaxis = 'r2Axis' &~ do -- 'addPlotableL' "my plot" myplot -- @ -- -- Most of the time you won't use these functions directly. However, -- other plotting functions follow this naming convention where instead -- of @a@, it takes the data needed to make the plot. -- | Add something 'Plotable' to the axis. -- addPlotable :: (InSpace (BaseSpace v) n a, MoPlotable a b) => a -> AxisState b v n addPlotable :: (InSpace (BaseSpace v) n a, MonadState (Axis b v n) m, Plotable a b) => a -> m () addPlotable a = axisPlots %= flip snoc (Plot' a mempty) -- | Add something 'Plotable' and modify the 'PlotState' of that plot. addPlotable' :: (InSpace (BaseSpace v) n a, MonadState (Axis b v n) m, Plotable a b) => a -> PlotState a b -> m () addPlotable' a s = axisPlots <>= [Plot' a (Endo $ execState s)] -- | Add something 'Plotable' with given legend entry. addPlotableL :: (InSpace (BaseSpace v) n a, MonadState (Axis b v n) m, Plotable a b) => String -> a -> m () addPlotableL l a = addPlotable' a $ addLegendEntry l -- | Add something 'Plotable' with given legend entry and modify the -- 'PlotState' of that plot. addPlotableL' :: (InSpace (BaseSpace v) n a, MonadState (Axis b v n) m, Plotable a b) => String -> a -> PlotState a b -> m () addPlotableL' l a s = addPlotable' a $ addLegendEntry l >> s ------------------------------------------------------------------------ -- Diagram Plot ------------------------------------------------------------------------ diagramPlot :: (v ~ BaseSpace c, Renderable (Path V2 n) b, MonadState (Axis b c n) m, Typeable b, Typeable v, Metric v, TypeableFloat n) => QDiagram b v n Any -> m () diagramPlot = addPlotable ------------------------------------------------------------------------ -- Axis properties ------------------------------------------------------------------------ -- | Traversal over the axis' most recent 'PlotProperties'. -- recentProps :: PropertyState b v n -> AxisState b v n -- recentProps s = axisPlots . _last . _2 %= (execState s .) -- Legend ------------ addLegendEntry :: (MonadState a m, HasPlotProperties a b, Num (N a)) => String -> m () addLegendEntry s = legendEntries <>= [mkLegendEntry s] -- axisState :: Axis b v n -> AxisStateM b v n a -> Axis b v n -- axisState a s = execState s a -- -- -- main = defaultMain myPlot -- @@ -- -- @@ -- $ runHaskell myPlot.hs -o myPlot.pdf -- @@ -- -- -- Currently @plots@ supports line, scatter, function and bar plots. Hopefully -- more will be added soon. -- -- -- | Standard 2D axis. r2Axis :: R2Backend b n => Axis b V2 n r2Axis = def -- | Standard 2D axis. -- r3Axis :: R2Backend b n => Axis b V3 n -- r3Axis = def -- | Set the label for the given axis. -- -- @@ -- myaxis = 'r2Axis' &~ 'axisLabel' 'ex' "x-axis" -- @@ axisLabel :: E v -> Lens' (Axis b v n) String axisLabel (E e) = axisLabels . e . axisLabelText -- | Lens onto the x axis label. xAxisLabel :: R1 v => Lens' (Axis b v n) String xAxisLabel = axisLabel ex -- | Lens onto the y axis label. yAxisLabel :: R2 v => Lens' (Axis b v n) String yAxisLabel = axisLabel ey -- | Lens onto the z axis label. zAxisLabel :: R3 v => Lens' (Axis b v n) String zAxisLabel = axisLabel ex -- | Set the position of the given axis label. axisLabelPosition :: E v -> Lens' (Axis b v n) AxisLabelPosition axisLabelPosition (E e) = axisLabels . e . axisLabelPos -- | Set the position of all axes labels. axesLabelPositions :: Traversable v => Traversal' (Axis b v n) AxisLabelPosition axesLabelPositions = axisLabels . traversed . axisLabelPos -- | Set the gap between the axis and the axis label. setAxisLabelGap :: E v -> Lens' (Axis b v n) n setAxisLabelGap (E e) = axisLabels . e . axisLabelGap -- | Set the gaps between all axes and the axis labels. setAxesLabelGaps :: Traversable v => Traversal' (Axis b v n) n setAxesLabelGaps = axisLabels . traverse . axisLabelGap -- | Label the x,y and z axis with \"x\", \"y\" and \"z\" respectively. cartesianLabels :: (Traversable v, MonadState (Axis b v n) m) => m () cartesianLabels = partsOf (axisLabels . traverse . axisLabelText) .= ["x", "y", "z"] -- | Set the aspect ratio of given axis. setAxisRatio :: MonadState (Axis b v n) m => E v -> n -> m () setAxisRatio e n = axisScaling . el e . aspectRatio .= Commit n -- | Make each axis have the same unit length. equalAxis :: (MonadState (Axis b v n) m, Functor v, Num n) => m () equalAxis = axisScaling . mapped . aspectRatio .= Commit 1 ------------------------------------------------------------------------ -- Grid lines ------------------------------------------------------------------------ -- | Set no major or minor grid lines for all axes. noGridLines :: (Functor v, MonadState (Axis b v n) m) => m () noGridLines = noMajorGridLines >> noMinorGridLines -- | Set no major or minor grid lines for given axes. noGridLine :: MonadState (Axis b v n) m => E v -> m () noGridLine e = noMajorGridLine e >> noMinorGridLine e -- Majors -- | Add major grid lines for all axes. setMajorGridLines :: (Functor v, MonadState (Axis b v n) m) => m () setMajorGridLines = axisGridLines . mapped . majorGridF .= tickGridF -- | Add major grid lines for given axis. setMajorGridLine :: MonadState (Axis b v n) m => E v -> m () setMajorGridLine (E e) = axisGridLines . e . majorGridF .= tickGridF -- | Set no major grid lines for all axes. noMajorGridLines :: (Functor v, MonadState (Axis b v n) m) => m () noMajorGridLines = axisGridLines . mapped . majorGridF .= noGridF -- | Set no major grid lines for given axis. noMajorGridLine :: MonadState (Axis b v n) m => E v -> m () noMajorGridLine (E l) = axisGridLines . l . majorGridF .= noGridF -- Minors -- | Add minor grid lines for all axes. setMinorGridLines :: (Functor v, MonadState (Axis b v n) m) => m () setMinorGridLines = axisGridLines . mapped . minorGridF .= tickGridF -- | Add minor grid lines for given axis. setMinorGridLine :: MonadState (Axis b v n) m => E v -> m () setMinorGridLine (E l) = axisGridLines . l . minorGridF .= tickGridF -- | Set no minor grid lines for all axes. noMinorGridLines :: (Functor v, MonadState (Axis b v n) m) => m () noMinorGridLines = axisGridLines . mapped . minorGridF .= noGridF -- | Set no minor grid lines for given axis. noMinorGridLine :: MonadState (Axis b v n) m => E v -> m () noMinorGridLine (E l) = axisGridLines . l . minorGridF .= noGridF -- | Traversal over both major and minor grid lines for all axes. allGridLines :: Traversable v => Traversal' (Axis b v n) (GridLines v n) allGridLines = axisGridLines . traverse ------------------------------------------------------------------------ -- Bounds ------------------------------------------------------------------------ boundMin :: HasBounds a c => E c -> Lens' a (Recommend (N a)) boundMin (E l) = bounds . _Wrapped . l . lowerBound boundMax :: HasBounds a c => E c -> Lens' a (Recommend (N a)) boundMax (E l) = bounds . _Wrapped . l . upperBound xMin :: (HasBounds a c, R1 c) => Lens' a (Recommend (N a)) xMin = boundMin ex xMax :: (HasBounds a c, R1 c) => Lens' a (Recommend (N a)) xMax = boundMax ex yMin :: (HasBounds a c, R2 c) => Lens' a (Recommend (N a)) yMin = boundMin ey yMax :: (HasBounds a c, R2 c) => Lens' a (Recommend (N a)) yMax = boundMax ey zMin :: (HasBounds a c, R3 c) => Lens' a (Recommend (N a)) zMin = boundMin ey zMax :: (HasBounds a c, R3 c) => Lens' a (Recommend (N a)) zMax = boundMin ey ------------------------------------------------------------------------ -- Grid lines ------------------------------------------------------------------------ -- | Set all axis grid lines to form a box. boxAxisLines :: (Functor v, MonadState (Axis b v n) m) => m () boxAxisLines = axisLines . mapped . axisLineType .= BoxAxisLine -- | Set all axis grid lines to pass though the origin. If the origin is -- not in bounds the line will be on the edge closest to the origin. middleAxisLines :: (Functor v, MonadState (Axis b v n) m) => m () middleAxisLines = axisLines . mapped . axisLineType .= MiddleAxisLine -- -- | Traversal over all axis line types. -- axisLineTypes :: HasAxisLines a v => Tranversal' a AxisLineType -- axisLineTypes = axisLines . traversed . axisLine -- -- | Lens onto x axis line type. -- xAxisLineType :: (L.R1 v, HasAxisLines a v) => Lens' a AxisLineType -- xAxisLineType = axisLine ex . axisLineType -- -- | Lens onto y axis line type. -- yAxisLineType :: (L.V2 n v, HasAxisLines a v) => Lens' a AxisLineType -- yAxisLineType = axisLine ey . axisLineType -- -- | Lens onto z axis line type. -- zAxisLineType :: (L.V3 n v, HasAxisLines a v) => Lens' a AxisLineType -- zAxisLineType = axisLine ez . axisLineType -- xAxisArrowOpts :: (L.R1 v, HasAxisLines a v) => Lens' a (Maybe ArrowOpts) -- xAxisArrowOpts = axisLine ex . axisArrowOpts -- yAxisArrowOpts :: (L.V2 n v, HasAxisLines a v) => Lens' a (Maybe ArrowOpts) -- yAxisArrowOpts = axisLine ey . axisArrowOpts -- zAxisArrowOpts :: (L.V3 n v, HasAxisLines a v) => Lens' a (Maybe ArrowOpts) -- zAxisArrowOpts = axisLines ez . axisArrowOpts -- ------------------------------------------------------------------------ -- Ticks ------------------------------------------------------------------------ -- | Remove minor ticks from all axes. noMinorTicks :: (Functor v, MonadState (Axis b v n) m) => m () noMinorTicks = axisTicks . mapped . minorTickAlign .= noTicks -- | Remove major ticks from all axes. noMajorTicks :: (Functor v, MonadState (Axis b v n) m) => m () noMajorTicks = axisTicks . mapped . majorTickAlign .= noTicks -- | Remove both major and minor ticks from all axes. noAxisTicks :: (Functor v, MonadState (Axis b v n) m) => m () noAxisTicks = noMinorTicks >> noMajorTicks centerAxisTicks :: (Functor v, MonadState (Axis b v n) m) => m () centerAxisTicks = axisTicks . mapped . tickAlign .= centerTicks insideAxisTicks :: (Functor v, MonadState (Axis b v n) m) => m () insideAxisTicks = axisTicks . mapped . tickAlign .= insideTicks ------------------------------------------------------------------------ -- Style ------------------------------------------------------------------------ -- $style -- Styles are a key part of a plot. It defines properties like colours -- and markers for each plot. The default way a plot gets it's style is -- from the axis theme. This is a list of plot styles that is zipped -- with the plots when the axis is rendered. ------------------------------------------------------------------------ -- Colour bar ------------------------------------------------------------------------ -- $colourbar -- The 'ColourBar' provides a visual key between a colour and value. The -- colour bar is not shown by default, it either needs a plot like -- 'addHeatMap' to turn it on or it can be turned on explicitly by -- 'showColorBar'. showColourBar :: MonadState (Axis b v n) m => m () showColourBar = axisColourBar . cbShow .= True {-# ANN module ("HLint: ignore Use import/export shortcut" :: String) #-}
bergey/plots
src/Plots/API.hs
Haskell
bsd-3-clause
17,846
module ETA.CodeGen.Env where import ETA.BasicTypes.Id import ETA.StgSyn.StgSyn import ETA.Types.Type import ETA.Types.TyCon import Codec.JVM import ETA.Util import ETA.Debug import ETA.CodeGen.Types import ETA.CodeGen.Closure import ETA.CodeGen.Monad import ETA.CodeGen.Utils import ETA.CodeGen.ArgRep import ETA.CodeGen.Name import Control.Monad (liftM) import Data.Maybe (catMaybes) getArgReferences :: [NonVoid StgArg] -> CodeGen [FieldRef] getArgReferences xs = fmap catMaybes $ traverse f xs where f (NonVoid (StgVarArg var)) = fmap g (getCgIdInfo var) f _ = return Nothing g CgIdInfo { cgLocation } = getLocField cgLocation getArgLoadCode :: NonVoid StgArg -> CodeGen Code getArgLoadCode (NonVoid (StgVarArg var)) = liftM idInfoLoadCode $ getCgIdInfo var getArgLoadCode (NonVoid (StgLitArg literal)) = return . snd $ cgLit literal getNonVoidArgCodes :: [StgArg] -> CodeGen [Code] getNonVoidArgCodes [] = return [] getNonVoidArgCodes (arg:args) | isVoidRep (argPrimRep arg) = getNonVoidArgCodes args | otherwise = do code <- getArgLoadCode (NonVoid arg) codes <- getNonVoidArgCodes args return (code:codes) getNonVoidArgFtCodes :: [StgArg] -> CodeGen [(FieldType, Code)] getNonVoidArgFtCodes [] = return [] getNonVoidArgFtCodes (arg:args) | isVoidRep (argPrimRep arg) = getNonVoidArgFtCodes args | otherwise = do code <- getArgLoadCode (NonVoid arg) ftCodes <- getNonVoidArgFtCodes args return ((ft, code) : ftCodes) where primRep = argPrimRep arg ft = expectJust "getNonVoidArgFtCodes" . primRepFieldType_maybe $ primRep getNonVoidArgRepCodes :: [StgArg] -> CodeGen [(PrimRep, Code)] getNonVoidArgRepCodes [] = return [] getNonVoidArgRepCodes (arg:args) | isVoidRep rep = getNonVoidArgRepCodes args | otherwise = do code <- getArgLoadCode (NonVoid arg) repCodes <- getNonVoidArgRepCodes args return ((rep, code) : repCodes) where rep = argPrimRep arg idInfoLoadCode :: CgIdInfo -> Code idInfoLoadCode CgIdInfo { cgLocation } = loadLoc cgLocation rebindId :: NonVoid Id -> CgLoc -> CodeGen () rebindId nvId@(NonVoid id) cgLoc = do info <- getCgIdInfo id bindId nvId (cgLambdaForm info) cgLoc bindId :: NonVoid Id -> LambdaFormInfo -> CgLoc -> CodeGen () bindId nvId@(NonVoid id) lfInfo cgLoc = addBinding (mkCgIdInfoWithLoc id lfInfo cgLoc) bindArg :: NonVoid Id -> CgLoc -> CodeGen () bindArg nvid@(NonVoid id) = bindId nvid (mkLFArgument id) bindArgs :: [(NonVoid Id, CgLoc)] -> CodeGen () bindArgs = mapM_ (\(nvId, cgLoc) -> bindArg nvId cgLoc) rhsIdInfo :: Id -> LambdaFormInfo -> CodeGen (CgIdInfo, CgLoc) rhsIdInfo id lfInfo = do dflags <- getDynFlags modClass <- getModClass let qualifiedClass = qualifiedName modClass (idNameText dflags id) rhsGenIdInfo id lfInfo (obj qualifiedClass) -- TODO: getJavaInfo generalize to unify rhsIdInfo and rhsConIdInfo rhsConIdInfo :: Id -> LambdaFormInfo -> CodeGen (CgIdInfo, CgLoc) rhsConIdInfo id lfInfo@(LFCon dataCon) = do dflags <- getDynFlags let dataClass = dataConClass dflags dataCon rhsGenIdInfo id lfInfo (obj dataClass) rhsGenIdInfo :: Id -> LambdaFormInfo -> FieldType -> CodeGen (CgIdInfo, CgLoc) rhsGenIdInfo id lfInfo ft = do cgLoc <- newTemp True ft return (mkCgIdInfoWithLoc id lfInfo cgLoc, cgLoc) mkRhsInit :: CgLoc -> Code -> Code mkRhsInit = storeLoc maybeLetNoEscape :: CgIdInfo -> Maybe (Label, [CgLoc]) maybeLetNoEscape CgIdInfo { cgLocation = LocLne label argLocs } = Just (label, argLocs) maybeLetNoEscape _ = Nothing
alexander-at-github/eta
compiler/ETA/CodeGen/Env.hs
Haskell
bsd-3-clause
3,536
module Rho.TrackerComms.PeerResponse where import Data.Monoid import Data.Word (Word32) import Network.Socket (SockAddr) data PeerResponse = PeerResponse { prInterval :: Word32 , prLeechers :: Maybe Word32 , prSeeders :: Maybe Word32 , prPeers :: [SockAddr] } deriving (Show, Eq) instance Monoid PeerResponse where mempty = PeerResponse 0 Nothing Nothing [] PeerResponse i1 ls1 ss1 ps1 `mappend` PeerResponse i2 ls2 ss2 ps2 = PeerResponse (max i1 i2) (ls1 `mw` ls2) (ss1 `mw` ss2) (ps1 <> ps2) where Nothing `mw` Nothing = Nothing Just w `mw` Nothing = Just w Nothing `mw` Just w = Just w Just w1 `mw` Just w2 = Just (w1 + w2)
osa1/rho-torrent
src/Rho/TrackerComms/PeerResponse.hs
Haskell
bsd-3-clause
735
-- | -- Module : Conway.Core.Types -- Description : -- Copyright : (c) Jonatan H Sundqvist, 2015 -- License : MIT -- Maintainer : Jonatan H Sundqvist -- Stability : experimental|stable -- Portability : POSIX (not sure) -- -- Created October 25 2015 -- TODO | - Use Foldable, Monoid and Traversable instances for Universe (?) -- - Define API, hide raw constructors (?) -- SPEC | - -- - -------------------------------------------------------------------------------------------------------------------------------------------- -- GHC Pragmas -------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------- -- API -------------------------------------------------------------------------------------------------------------------------------------------- module Conway.Core.Types where -------------------------------------------------------------------------------------------------------------------------------------------- -- We'll need these -------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------- -- Types -------------------------------------------------------------------------------------------------------------------------------------------- -- | newtype Universe = Universe { cells :: [[Cell]] } deriving (Eq, Show) -- | newtype Neighbours n = Neighbours [[(n, Cell)]] deriving (Eq, Show) -- | -- TODO: Rename (?) data Cell = Dead | Alive deriving (Eq, Ord, Show)
SwiftsNamesake/Conway
src/Conway/Core/Types.hs
Haskell
bsd-3-clause
1,866
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} -- | This module is intended to be imported @qualified@, for example: -- -- > import qualified Test.Tasty.Laws.Functor as Functor -- module Test.Tasty.Laws.Functor ( testUnit , test , testExhaustive , testSeries , testSeriesExhaustive , module Data.Functor.Laws ) where #if !MIN_VERSION_base(4,8,0) import Control.Applicative ((<$>)) #endif import Test.DumbCheck (Serial(series), Series, uncurry3, zipA3) import Test.Tasty (TestTree, testGroup) import Test.Tasty.DumbCheck (testSeriesProperty) import Data.Functor.Laws (identity, composition) import Text.Show.Functions () -- | @tasty@ 'TestTree' for 'Functor' laws. The type parameter for the -- 'Functor' is '()' which unless you are dealing with partial functions, -- should be enough to test any 'Functor'. testUnit :: (Functor f, Eq (f ()), Show (f ())) => Series (f ()) -> TestTree testUnit ss = testSeries1 $ zipA3 ss [const ()] [const ()] -- | @tasty@ 'TestTree' for 'Functor' laws. Monomorphic sum 'Series' for @f@ -- and @g@ in the compose law. -- -- @ -- fmap (\a -> a) . (\a -> a) == fmap (\a -> a) . fmap (\a -> a) -- fmap (\b -> b) . (\b -> b) == fmap (\b -> b) . fmap (\b -> b) -- ... -- @ test :: forall f a . (Eq (f a), Functor f, Show (f a), Serial a) => Series (f a) -> TestTree test ss = testSeries1 $ zip3 ss (series :: Series (a -> a)) (series :: Series (a -> a)) -- | @tasty@ 'TestTree' for 'Functor' laws. Monomorphic product 'Series' for -- @f@ and @g@ in the compose law. -- -- @ -- fmap (\a -> a) . (\a -> a) == fmap (\a -> a) . fmap (\a -> a) -- fmap (\a -> a) . (\a -> b) == fmap (\a -> a) . fmap (\a -> b) -- fmap (\a -> a) . (\b -> b) == fmap (\a -> a) . fmap (\b -> b) -- ... -- @ testExhaustive :: forall f a . (Eq (f a), Functor f, Show (f a), Serial a) => Series (f a) -> TestTree testExhaustive ss = testSeries1 $ zipA3 ss (series :: Series (a -> a)) (series :: Series (a -> a)) -- | @tasty@ 'TestTree' for 'Functor' laws. Polymorphic sum 'Series' for -- @f@ and @g@ in the compose law. -- -- @ -- fmap (\a0 -> b0) . (\b0 -> c0) == fmap (\a0 -> b0) . fmap (\b0 -> c0) -- fmap (\a1 -> b1) . (\b1 -> c1) == fmap (\a1 -> a1) . fmap (\b1 -> c1) -- fmap (\a2 -> b2) . (\b2 -> c2) == fmap (\a2 -> a2) . fmap (\b2 -> c2) -- ... -- @ -- testPoly -- :: forall f a b c . -- ( Functor f -- , Eq (f a), Show a, Show (f a) , Serial a -- , Eq (f b), Show b, Show (f b) , Serial b -- , Eq (f c), Show c, Show (f c) , Serial c -- , Serial (a -> b), Serial (b -> c) -- ) -- => Proxy b -> Proxy c -> Series (f a) -> TestTree -- testPoly _ _ = testWithComp $ \fs -> -- composition fs (series :: Series (b -> c)) -- (series :: Series (a -> b)) -- | @tasty@ 'TestTree' for 'Functor' laws with explict sum 'Series' for -- @f@ and @g@ in the compose law. -- -- @ -- fmap (\a0 -> b0) . (\b0 -> c0) == fmap (\a0 -> b0) . fmap (\b0 -> c0) -- fmap (\a1 -> b1) . (\b1 -> c1) == fmap (\a1 -> a1) . fmap (\b1 -> c1) -- fmap (\a1 -> b1) . (\b1 -> c1) == fmap (\a1 -> a1) . fmap (\b1 -> c1) -- ... -- @ testSeries :: ( Eq (f c), Eq (f b), Functor f, Show (f c)) => Series (f c) -> Series (a -> b) -> Series (c -> a) -> TestTree testSeries xs fs gs = testSeries1 (zip3 xs fs gs) -- | @tasty@ 'TestTree' for 'Functor' laws with explicit product 'Series' -- for @f@ and @g@ in the compose law. -- -- @ -- fmap (\a0 -> b0) . (\b0 -> c0) == fmap (\a0 -> b0) . fmap (\b0 -> c0) -- fmap (\a0 -> b0) . (\b0 -> c1) == fmap (\a0 -> a0) . fmap (\b0 -> c1) -- fmap (\a0 -> b0) . (\b0 -> c0) == fmap (\a0 -> a0) . fmap (\b1 -> c1) -- ... -- @ testSeriesExhaustive :: ( Eq (f c), Eq (f b), Functor f, Show (f c)) => Series (f c) -> Series (a -> b) -> Series (c -> a) -> TestTree testSeriesExhaustive xs fs gs = testSeries1 (zipA3 xs fs gs) testSeries1 :: (Eq (f c), Eq (f b), Functor f, Show (f c)) => Series (f c, a -> b, c -> a) -> TestTree testSeries1 ss = testGroup "Functor laws" [ testSeriesProperty "fmap id ≡ id" identity ((\(x,_,_) -> x) <$> ss) , testSeriesProperty "fmap (f . g) ≡ fmap f . fmap g" (uncurry3 composition) ss ]
jdnavarro/tasty-laws
Test/Tasty/Laws/Functor.hs
Haskell
bsd-3-clause
4,265
{-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} module Main where import Data.List (sort) import qualified Data.StringMap as M import qualified Data.StringMap.Dim2Search as D2 -- ---------------------------------------- -- -- auxiliary functions for mapping pairs of Ints to Strings and vice versa intToKey :: Int -> Int -> Int -> String intToKey base len val = tok len val "" where tok 0 _ acc = acc tok i v acc = tok (i - 1) v' (d : acc) where (v', r) = v `divMod` base d = toEnum (r + fromEnum '0') intPairToKey :: Int -> Int -> (Int, Int) -> String intPairToKey base len (x, y) = merge x' y' where x' = intToKey base len x y' = intToKey base len y merge :: [a] -> [a] -> [a] merge [] [] = [] merge (x : xs) (y : ys) = x : y : merge xs ys intFromKey :: String -> Int intFromKey = read unMerge :: [a] -> ([a], [a]) unMerge [] = ([], []) unMerge (x : y : s) = (x : xs, y : ys) where (xs, ys) = unMerge s -- ---------------------------------------- -- -- experiment to understand 2-dimensional location -- search implemented by using the StringMap impl. -- -- an ordering on strings (representing pairs of ints) -- that is isomorphic to the partial ordering -- used for 2-dimensional search instance Ord Point' where (P' s1) <= (P' s2) = s1 `le` s2 where le [] [] = True le (x1 : y1 : ds1) (x2 : y2 : ds2) | x1 == x2 && y1 == y2 = ds1 `le` ds2 | x1 == x2 && y1 < y2 = ds1 `leX` ds2 | x1 < x2 && y1 == y2 = ds1 `leY` ds2 | x1 < x2 && y1 < y2 = True | otherwise = False leX [] [] = True -- the result for the Y dimension is already known leX (x1 : y1 : ds1) (x2 : y2 : ds2) | x1 == x2 = ds1 `leX` ds2 | x1 < x2 = True | otherwise = False leY [] [] = True -- the result for the X dimension is already known leY (x1 : y1 : ds1) (x2 : y2 : ds2) | y1 == y2 = ds1 `leY` ds2 | y1 < y2 = True | otherwise = False -- toPoint' and fromPoint': the bijection Point <-> Point' toPoint' :: Point -> Point' toPoint' (P p) = P' $ intPairToKey base len p where base = 2 -- or 10 len = 10 -- or 3 (or something else) fromPoint' :: Point' -> Point fromPoint' (P' ds) = P (intFromKey xs, intFromKey ys) where (xs, ys) = unMerge ds -- the test, whether the `le` ordering is preserved, when working with Point' propOrdered :: Point -> Point -> Bool propOrdered p1 p2 = (p1 `le` p2) == (toPoint' p1 <= toPoint' p2) -- very quick check test propTest :: Int -> [(Point, Point)] propTest n = filter (not . uncurry propOrdered) qs where xs = [1..n] ps = [P (x, y) | x <- xs, y <- xs] qs = [(p1, p2) | p1 <- ps, p2 <- ps] test1 :: Bool test1 = null $ propTest 20 -- ---------------------------------------- newtype Point = P {unP :: (Int, Int) } deriving (Eq) newtype PointSet = PS {unPS :: [Point] } deriving (Eq) -- assuming only smart constructor mkPS is used newtype Point' = P' {unP' :: String } deriving (Eq) newtype PointSet' = PS' {unPS' :: M.StringMap ()} deriving (Eq) instance Show Point where show = show . unP instance Show Point' where show = show . unP' instance Show PointSet where show = show . unPS instance Show PointSet' where show = show . M.keys . unPS' class PartOrd a where le :: a -> a -> Bool ge :: a -> a -> Bool instance PartOrd Point where (P (x1, y1)) `le` (P (x2, y2)) = x1 <= x2 && y1 <= y2 (P (x1, y1)) `ge` (P (x2, y2)) = x1 >= x2 && y1 >= y2 instance PartOrd Point' where (P' p1) `le` (P' p2) = not . M.null . D2.lookupLE p2 $ (M.singleton p1 ()) (P' p1) `ge` (P' p2) = not . M.null . D2.lookupGE p2 $ (M.singleton p1 ()) class Lookup p s | s -> p where lookupLE :: p -> s -> s lookupGE :: p -> s -> s instance Lookup Point PointSet where lookupLE p ps = PS . filter (`le` p) . unPS $ ps lookupGE p ps = PS . filter (`ge` p) . unPS $ ps instance Lookup Point' PointSet' where lookupLE p ps = PS' . D2.lookupLE (unP' p) . unPS' $ ps lookupGE p ps = PS' . D2.lookupGE (unP' p) . unPS' $ ps -- the bijection between Point and Point' pToP' :: Point -> Point' pToP' = P' . intPairToKey 10 5 . unP -- base 10, 5 digits p'ToP :: Point' -> Point p'ToP (P' p') = P (intFromKey xs, intFromKey ys) where (xs, ys) = unMerge p' -- the bijection between PointSet and PointSet' psToPS' :: PointSet -> PointSet' psToPS' = PS' . M.fromList . map (\(P' x) -> (x, ())) . map pToP' . unPS ps'ToPS :: PointSet' -> PointSet ps'ToPS = mkPS . map (unP . p'ToP . P') . M.keys . unPS' mkP :: Int -> Int -> Point mkP x y = P (x, y) mkP' :: Int -> Int -> Point' mkP' x y = pToP' $ mkP x y mkPS :: [(Int, Int)] -> PointSet mkPS = PS . map P . sort mkPS' :: [(Int, Int)] -> PointSet' mkPS' = psToPS' . mkPS mkxx :: Int -> Point mkxx i = mkP i i mkxx' :: Int -> Point' mkxx' = pToP' . mkxx mkD2 :: [Int] -> PointSet mkD2 = PS . map mkxx mkD2' :: [Int] -> PointSet' mkD2' = psToPS' . mkD2 d1 :: PointSet d1 = mkD2 [1,10,100,105,107,125,200, 205, 222] d1' :: PointSet' d1' = psToPS' d1 d2 :: PointSet d2 = mkD2 [2,10,20,25,100,111,155,200,333,500] d2' :: PointSet' d2' = psToPS' d2 d0' :: PointSet' d0' = mkD2' [10,100] mkSquare :: Int -> Int -> PointSet mkSquare n m = mkPS [(i, j) | i <- [n..m], j <- [n..m]] -- input list must contain at least 3 different elements mkPointPointSet :: [Int] -> ([Point], PointSet) mkPointPointSet xs0 = (ps, ps') where xs@(_ : ys@(_:_:_)) = sort xs0 xs' = init ys ps = [mkP i j | i <- xs, j <- xs ] ps' = mkPS [ (i, j) | i <- xs', j <- xs'] ps1 :: PointSet xs1 :: [Point] (xs1, ps1) = mkPointPointSet [1,2,10,20,25,100,111,155,200,333,500,505] lawBijection :: PointSet -> Bool lawBijection ps = ps == (ps'ToPS . psToPS' $ ps) lawPredicateMorphism :: (Point -> Bool) -> (Point' -> Bool) -> Point -> Bool lawPredicateMorphism p p' x = p x == (p' $ pToP' x) lawPredicate2Morphism :: (Point -> Point -> Bool) -> (Point' -> Point' -> Bool) -> Point -> Point -> Bool lawPredicate2Morphism p2 p2' x y = lawPredicateMorphism (p2 x) (p2' $ pToP' x) y lawPointSetMorphism :: (PointSet -> PointSet) -> (PointSet' -> PointSet') -> PointSet -> Bool lawPointSetMorphism f f' ps = f ps == (ps'ToPS . f' . psToPS' $ ps) lawLookupGE :: Point -> PointSet -> Bool lawLookupGE p ps = lawPointSetMorphism (lookupGE p) (lookupGE $ pToP' p) ps lawLookupLE :: Point -> PointSet -> Bool lawLookupLE p ps = lawPointSetMorphism (lookupLE p) (lookupLE $ pToP' p) ps testPointPointSet :: (Point -> PointSet -> Bool) -> ([Point], PointSet) -> [Point] testPointPointSet law (xs, ps) = filter (\p -> not $ law p ps) xs testLookup :: ([Point], PointSet) -> Bool testLookup ps = null (testPointPointSet lawLookupLE ps) && null (testPointPointSet lawLookupGE ps) theTest :: Bool theTest = testLookup $ mkPointPointSet [1,2,10,20,25,100,111,155,200,333,500,505] main :: IO () main = print theTest >> return () -- ----------------------------------------
alexbiehl/StringMap
tests/Dim2Test.hs
Haskell
mit
7,588
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableInstances #-} {-| Copyright: Aaron Taylor, 2016 License: MIT Maintainer: aaron@hamsterdam.co Class, instances and transformer for monads capable of HTTP requests. In some cases, it is useful to generalize this capability. For example, it can be used provide mock responses for testing. -} module Control.Monad.Http ( -- * Class MonadHttp(..), -- * Transformer HttpT(..), runHttpT ) where import qualified Control.Monad.Catch as Catch import qualified Control.Monad.Except as Except import qualified Control.Monad.Reader as Reader import qualified Control.Monad.Trans as Trans import qualified Data.ByteString.Lazy as LBS import qualified Network.HTTP.Simple as HTTPSimple import qualified Network.HTTP.Client as HTTP import qualified Network.HTTP.Types as HTTP {-| The class of monads capable of HTTP requests. -} class Monad m => MonadHttp m where performRequest :: HTTP.Request -> m (HTTP.Response LBS.ByteString) instance MonadHttp IO where performRequest = HTTPSimple.httpLbs instance Catch.MonadThrow m => MonadHttp (HttpT m) where performRequest request = check where check = do response <- Reader.ask let status = HTTP.responseStatus response if status >= HTTP.ok200 && status < HTTP.multipleChoices300 then return response else let badResponse = response { HTTP.responseBody = () } body = LBS.toStrict . HTTP.responseBody $ response in Catch.throwM $ HTTP.HttpExceptionRequest request (HTTP.StatusCodeException badResponse body) instance Trans.MonadIO m => MonadHttp (Except.ExceptT e m) where performRequest = HTTPSimple.httpLbs {-| An HTTP transformer monad parameterized by an inner monad 'm'. -} newtype HttpT m a = HttpT { unHttpT :: Reader.ReaderT (HTTP.Response LBS.ByteString) m a } deriving (Functor, Applicative, Monad, Trans.MonadTrans, Catch.MonadThrow, Catch.MonadCatch, Trans.MonadIO, Reader.MonadReader (HTTP.Response LBS.ByteString)) {-| Run an HTTP monad action and extract the inner monad. -} runHttpT :: HttpT m a -- ^ The HTTP monad transformer -> HTTP.Response LBS.ByteString -- ^ The response -> m a -- ^ The resulting inner monad runHttpT = Reader.runReaderT . unHttpT instance Except.MonadError e m => Except.MonadError e (HttpT m) where throwError = Trans.lift . Except.throwError catchError m f = HttpT . Reader.ReaderT $ \r -> Except.catchError (runHttpT m r) (\e -> runHttpT (f e) r)
hamsterdam/kawhi
library/Control/Monad/Http.hs
Haskell
mit
2,822
{-# LANGUAGE TupleSections #-} {-# LANGUAGE OverloadedStrings #-} -------------------------------------------------------------------- -- | -- Copyright : (c) Edward Kmett and Dan Doel 2013 -- License : BSD2 -- Maintainer: Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability: non-portable -- -- This module provides the parser for terms -------------------------------------------------------------------- module Ermine.Parser.Pattern ( validate , pattern , pattern0 , pattern1 , PP ) where import Control.Applicative import Control.Lens hiding (op) import Data.Foldable as Foldable import Data.Text (Text) import Data.Void import qualified Data.Set as Set import Ermine.Builtin.Global import Ermine.Builtin.Pattern import Ermine.Builtin.Type (anyType) import Ermine.Parser.Literal import Ermine.Parser.Style import Ermine.Parser.Type import Ermine.Syntax import Text.Parser.Combinators import Text.Parser.Token -- | Check a 'Binder' for linearity. -- -- Each variable name must be used at most once in the pattern. validate :: (Functor m, Monad m, Ord v) => Binder v a -> (v -> m Void) -> m () validate b e = () <$ foldlM (\s n -> if n `Set.member` s then vacuous $ e n else return $ Set.insert n s) Set.empty (vars b) -- | The simple pattern type generated by pattern parsing. type PP = P Ann Text varP :: (Monad m, TokenParsing m) => m PP varP = termIdentifier <&> sigp ?? anyType -- | Parse a single pattern part (e.g. an argument to a lambda) pattern0 :: (Monad m, TokenParsing m) => m PP pattern0 = conp nothingg [] <$ symbol "Nothing" <|> varP <|> strictp <$ symbol "!" <*> pattern0 <|> _p <$ symbol "_" <|> litp <$> literal <|> parens (tup' <$> patterns) sigP :: (Monad m, TokenParsing m) => m PP sigP = sigp <$> try (termIdentifier <* colon) <*> annotation -- TODO: remove this when constructor patterns really work. eP, longhP, justP, nothingP :: (Monad m, TokenParsing m) => m PP eP = conp eg <$ symbol "E" <*> many pattern1 justP = conp justg <$ symbol "Just" <*> many pattern1 nothingP = conp nothingg <$ symbol "Nothing" <*> many pattern1 longhP = conp longhg <$ symbol "Long#" <*> many pattern1 -- as patterns pattern1 :: (Monad m, TokenParsing m) => m PP pattern1 = asp <$> try (termIdentifier <* symbol "@") <*> pattern1 <|> pattern0 -- | Parse a single pattern (e.g. a case statement alt pattern) pattern2 :: (Monad m, TokenParsing m) => m PP pattern2 = eP <|> justP <|> nothingP <|> longhP <|> pattern1 -- existentials sigP pattern3 :: (Monad m, TokenParsing m) => m PP pattern3 = sigP <|> pattern2 patterns :: (Monad m, TokenParsing m) => m [PP] patterns = commaSep pattern3 -- | Parse a single pattern (e.g. a case statement alt pattern) pattern :: (Monad m, TokenParsing m) => m PP pattern = pattern2
PipocaQuemada/ermine
src/Ermine/Parser/Pattern.hs
Haskell
bsd-2-clause
2,871
{-# LANGUAGE DeriveDataTypeable #-} module Distribution.Client.Cron ( cron , Signal(..) , ReceivedSignal(..) , rethrowSignalsAsExceptions ) where import Control.Monad (forM_) import Control.Exception (Exception) import Control.Concurrent (myThreadId, threadDelay, throwTo) import System.Random (randomRIO) import System.Locale (defaultTimeLocale) import Data.Time.Format (formatTime) import Data.Time.Clock (UTCTime, getCurrentTime, addUTCTime) import Data.Time.LocalTime (getCurrentTimeZone, utcToZonedTime) import Data.Typeable (Typeable) import qualified System.Posix.Signals as Posix import Distribution.Verbosity (Verbosity) import Distribution.Simple.Utils hiding (warn) data ReceivedSignal = ReceivedSignal Signal UTCTime deriving (Show, Typeable) data Signal = SIGABRT | SIGINT | SIGQUIT | SIGTERM deriving (Show, Typeable) instance Exception ReceivedSignal -- | "Re"throw signals as exceptions to the invoking thread rethrowSignalsAsExceptions :: [Signal] -> IO () rethrowSignalsAsExceptions signals = do tid <- myThreadId forM_ signals $ \s -> let handler = do time <- getCurrentTime throwTo tid (ReceivedSignal s time) in Posix.installHandler (toPosixSignal s) (Posix.Catch handler) Nothing toPosixSignal :: Signal -> Posix.Signal toPosixSignal SIGABRT = Posix.sigABRT toPosixSignal SIGINT = Posix.sigINT toPosixSignal SIGQUIT = Posix.sigQUIT toPosixSignal SIGTERM = Posix.sigTERM -- | @cron verbosity interval act@ runs @act@ over and over with -- the specified interval. cron :: Verbosity -> Int -> (a -> IO a) -> (a -> IO ()) cron verbosity interval action x = do x' <- action x interval' <- pertabate interval logNextSyncMessage interval' wait interval' cron verbosity interval action x' where -- to stop all mirror clients hitting the server at exactly the same time -- we randomly adjust the wait time by +/- 10% pertabate i = let deviation = i `div` 10 in randomRIO (i + deviation, i - deviation) -- Annoyingly, threadDelay takes an Int number of microseconds, so we cannot -- wait much longer than an hour. So have to wait repeatedly. Sigh. wait minutes | minutes > 60 = do threadDelay (60 * 60 * 1000000) wait (minutes - 60) | otherwise = threadDelay (minutes * 60 * 1000000) logNextSyncMessage minutes = do now <- getCurrentTime tz <- getCurrentTimeZone let nextSync = addUTCTime (fromIntegral (60 * minutes)) now notice verbosity $ "Next try will be in " ++ show minutes ++ " minutes, at " ++ formatTime defaultTimeLocale "%R %Z" (utcToZonedTime tz nextSync)
haskell-infra/hackage-server
Distribution/Client/Cron.hs
Haskell
bsd-3-clause
2,758
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} -- | Generate HPC (Haskell Program Coverage) reports module Stack.Coverage ( deleteHpcReports , updateTixFile , generateHpcReport , HpcReportOpts(..) , generateHpcReportForTargets , generateHpcUnifiedReport , generateHpcMarkupIndex ) where import Control.Applicative import Control.Exception.Lifted import Control.Monad (liftM, when, unless, void) import Control.Monad.Catch (MonadCatch) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Resource import qualified Data.ByteString.Char8 as S8 import Data.Foldable (forM_, asum, toList) import Data.Function import Data.List import qualified Data.Map.Strict as Map import Data.Maybe import Data.Monoid ((<>)) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.IO as T import qualified Data.Text.Lazy as LT import Data.Traversable (forM) import Trace.Hpc.Tix import Network.HTTP.Download (HasHttpManager) import Path import Path.IO import Prelude hiding (FilePath, writeFile) import Stack.Build.Source (parseTargetsFromBuildOpts) import Stack.Build.Target import Stack.Constants import Stack.Package import Stack.Types import qualified System.Directory as D import System.FilePath (dropExtension, isPathSeparator) import System.Process.Read import Text.Hastache (htmlEscape) -- | Invoked at the beginning of running with "--coverage" deleteHpcReports :: (MonadIO m, MonadThrow m, MonadReader env m, HasEnvConfig env) => m () deleteHpcReports = do hpcDir <- hpcReportDir removeTreeIfExists hpcDir -- | Move a tix file into a sub-directory of the hpc report directory. Deletes the old one if one is -- present. updateTixFile :: (MonadIO m,MonadReader env m,HasConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,HasEnvConfig env) => PackageName -> Path Abs File -> m () updateTixFile pkgName tixSrc = do exists <- fileExists tixSrc when exists $ do tixDest <- tixFilePath pkgName (dropExtension (toFilePath (filename tixSrc))) removeFileIfExists tixDest createTree (parent tixDest) -- Remove exe modules because they are problematic. This could be revisited if there's a GHC -- version that fixes https://ghc.haskell.org/trac/ghc/ticket/1853 mtix <- readTixOrLog tixSrc case mtix of Nothing -> $logError $ "Failed to read " <> T.pack (toFilePath tixSrc) Just tix -> do liftIO $ writeTix (toFilePath tixDest) (removeExeModules tix) removeFileIfExists tixSrc -- | Get the directory used for hpc reports for the given pkgId. hpcPkgPath :: (MonadIO m,MonadReader env m,HasConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,HasEnvConfig env) => PackageName -> m (Path Abs Dir) hpcPkgPath pkgName = do outputDir <- hpcReportDir pkgNameRel <- parseRelDir (packageNameString pkgName) return (outputDir </> pkgNameRel) -- | Get the tix file location, given the name of the file (without extension), and the package -- identifier string. tixFilePath :: (MonadIO m,MonadReader env m,HasConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,HasEnvConfig env) => PackageName -> String -> m (Path Abs File) tixFilePath pkgName tixName = do pkgPath <- hpcPkgPath pkgName tixRel <- parseRelFile (tixName ++ "/" ++ tixName ++ ".tix") return (pkgPath </> tixRel) -- | Generates the HTML coverage report and shows a textual coverage summary for a package. generateHpcReport :: (MonadIO m,MonadReader env m,HasConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,HasEnvConfig env) => Path Abs Dir -> Package -> [Text] -> m () generateHpcReport pkgDir package tests = do -- If we're using > GHC 7.10, the hpc 'include' parameter must specify a ghc package key. See -- https://github.com/commercialhaskell/stack/issues/785 let pkgName = packageNameText (packageName package) pkgId = packageIdentifierString (packageIdentifier package) compilerVersion <- asks (envConfigCompilerVersion . getEnvConfig) eincludeName <- -- Pre-7.8 uses plain PKG-version in tix files. if getGhcVersion compilerVersion < $(mkVersion "7.10") then return $ Right $ Just pkgId -- We don't expect to find a package key if there is no library. else if not (packageHasLibrary package) then return $ Right Nothing -- Look in the inplace DB for the package key. -- See https://github.com/commercialhaskell/stack/issues/1181#issuecomment-148968986 else do mghcPkgKey <- findPackageKeyForBuiltPackage pkgDir (packageIdentifier package) case mghcPkgKey of Nothing -> do let msg = "Failed to find GHC package key for " <> pkgName $logError msg return $ Left msg Just ghcPkgKey -> return $ Right $ Just $ T.unpack ghcPkgKey forM_ tests $ \testName -> do tixSrc <- tixFilePath (packageName package) (T.unpack testName) let report = "coverage report for " <> pkgName <> "'s test-suite \"" <> testName <> "\"" reportDir = parent tixSrc case eincludeName of Left err -> generateHpcErrorReport reportDir (sanitize (T.unpack err)) -- Restrict to just the current library code, if there is a library in the package (see -- #634 - this will likely be customizable in the future) Right mincludeName -> do let extraArgs = case mincludeName of Just includeName -> ["--include", includeName ++ ":"] Nothing -> [] generateHpcReportInternal tixSrc reportDir report extraArgs extraArgs generateHpcReportInternal :: (MonadIO m,MonadReader env m,HasConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,HasEnvConfig env) => Path Abs File -> Path Abs Dir -> Text -> [String] -> [String] -> m () generateHpcReportInternal tixSrc reportDir report extraMarkupArgs extraReportArgs = do -- If a .tix file exists, move it to the HPC output directory and generate a report for it. tixFileExists <- fileExists tixSrc if not tixFileExists then $logError $ T.concat [ "Didn't find .tix for " , report , " - expected to find it at " , T.pack (toFilePath tixSrc) , "." ] else (`catch` \err -> do let msg = show (err :: ReadProcessException) $logError (T.pack msg) generateHpcErrorReport reportDir $ sanitize msg) $ (`onException` $logError ("Error occurred while producing " <> report)) $ do -- Directories for .mix files. hpcRelDir <- hpcRelativeDir -- Compute arguments used for both "hpc markup" and "hpc report". pkgDirs <- Map.keys . envConfigPackages <$> asks getEnvConfig let args = -- Use index files from all packages (allows cross-package coverage results). concatMap (\x -> ["--srcdir", toFilePath x]) pkgDirs ++ -- Look for index files in the correct dir (relative to each pkgdir). ["--hpcdir", toFilePath hpcRelDir, "--reset-hpcdirs"] menv <- getMinimalEnvOverride $logInfo $ "Generating " <> report outputLines <- liftM S8.lines $ readProcessStdout Nothing menv "hpc" ( "report" : toFilePath tixSrc : (args ++ extraReportArgs) ) if all ("(0/0)" `S8.isSuffixOf`) outputLines then do let msg html = T.concat [ "Error: The " , report , " did not consider any code. One possible cause of this is" , " if your test-suite builds the library code (see stack " , if html then "<a href='https://github.com/commercialhaskell/stack/issues/1008'>" else "" , "issue #1008" , if html then "</a>" else "" , "). It may also indicate a bug in stack or" , " the hpc program. Please report this issue if you think" , " your coverage report should have meaningful results." ] $logError (msg False) generateHpcErrorReport reportDir (msg True) else do -- Print output, stripping @\r@ characters because Windows. forM_ outputLines ($logInfo . T.decodeUtf8 . S8.filter (not . (=='\r'))) $logInfo ("The " <> report <> " is available at " <> T.pack (toFilePath (reportDir </> $(mkRelFile "hpc_index.html")))) -- Generate the markup. void $ readProcessStdout Nothing menv "hpc" ( "markup" : toFilePath tixSrc : ("--destdir=" ++ toFilePath reportDir) : (args ++ extraMarkupArgs) ) data HpcReportOpts = HpcReportOpts { hroptsInputs :: [Text] , hroptsAll :: Bool , hroptsDestDir :: Maybe String } deriving (Show) generateHpcReportForTargets :: (MonadIO m, HasHttpManager env, MonadReader env m, MonadBaseControl IO m, MonadCatch m, MonadLogger m, HasEnvConfig env) => HpcReportOpts -> m () generateHpcReportForTargets opts = do let (tixFiles, targetNames) = partition (".tix" `T.isSuffixOf`) (hroptsInputs opts) targetTixFiles <- -- When there aren't any package component arguments, then -- don't default to all package components. if not (hroptsAll opts) && null targetNames then return [] else do when (hroptsAll opts && not (null targetNames)) $ $logWarn $ "Since --all is used, it is redundant to specify these targets: " <> T.pack (show targetNames) (_,_,targets) <- parseTargetsFromBuildOpts AllowNoTargets defaultBuildOpts { boptsTargets = if hroptsAll opts then [] else targetNames } liftM concat $ forM (Map.toList targets) $ \(name, target) -> case target of STUnknown -> fail $ packageNameString name ++ " isn't a known local page" STNonLocal -> fail $ "Expected a local package, but " ++ packageNameString name ++ " is either an extra-dep or in the snapshot." STLocalComps comps -> do pkgPath <- hpcPkgPath name forM (toList comps) $ \nc -> case nc of CTest testName -> liftM (pkgPath </>) $ parseRelFile (T.unpack testName ++ ".tix") _ -> fail $ "Can't specify anything except test-suites as hpc report targets (" ++ packageNameString name ++ " is used with a non test-suite target)" STLocalAll -> do pkgPath <- hpcPkgPath name exists <- dirExists pkgPath if exists then do (_, files) <- listDirectory pkgPath return (filter ((".tix" `isSuffixOf`) . toFilePath) files) else return [] tixPaths <- liftM (++ targetTixFiles) $ mapM (parseRelAsAbsFile . T.unpack) tixFiles when (null tixPaths) $ fail "Not generating combined report, because no targets or tix files are specified." reportDir <- case hroptsDestDir opts of Nothing -> liftM (</> $(mkRelDir "combined/custom")) hpcReportDir Just destDir -> do liftIO $ D.createDirectoryIfMissing True destDir parseRelAsAbsDir destDir generateUnionReport "combined report" reportDir tixPaths generateHpcUnifiedReport :: (MonadIO m,MonadReader env m,HasConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,HasEnvConfig env) => m () generateHpcUnifiedReport = do outputDir <- hpcReportDir createTree outputDir (dirs, _) <- listDirectory outputDir tixFiles <- liftM (concat . concat) $ forM (filter (("combined" /=) . dirnameString) dirs) $ \dir -> do (dirs', _) <- listDirectory dir forM dirs' $ \dir' -> do (_, files) <- listDirectory dir' return (filter ((".tix" `isSuffixOf`) . toFilePath) files) let reportDir = outputDir </> $(mkRelDir "combined/all") if length tixFiles < 2 then $logInfo $ T.concat [ if null tixFiles then "No tix files" else "Only one tix file" , " found in " , T.pack (toFilePath outputDir) , ", so not generating a unified coverage report." ] else generateUnionReport "unified report" reportDir tixFiles generateUnionReport :: (MonadIO m,MonadReader env m,HasConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,HasEnvConfig env) => Text -> Path Abs Dir -> [Path Abs File] -> m () generateUnionReport report reportDir tixFiles = do tixes <- mapM (liftM (fmap removeExeModules) . readTixOrLog) tixFiles $logDebug $ "Using the following tix files: " <> T.pack (show tixFiles) let (errs, tix) = unionTixes (catMaybes tixes) unless (null errs) $ $logWarn $ T.concat $ "The following modules are left out of the " : report : " due to version mismatches: " : intersperse ", " (map T.pack errs) tixDest <- liftM (reportDir </>) $ parseRelFile (dirnameString reportDir ++ ".tix") createTree (parent tixDest) liftIO $ writeTix (toFilePath tixDest) tix generateHpcReportInternal tixDest reportDir report [] [] readTixOrLog :: (MonadLogger m, MonadIO m, MonadBaseControl IO m) => Path b File -> m (Maybe Tix) readTixOrLog path = do mtix <- liftIO (readTix (toFilePath path)) `catch` \(ErrorCall err) -> do $logError $ "Error while reading tix: " <> T.pack err return Nothing when (isNothing mtix) $ $logError $ "Failed to read tix file " <> T.pack (toFilePath path) return mtix -- | Module names which contain '/' have a package name, and so they weren't built into the -- executable. removeExeModules :: Tix -> Tix removeExeModules (Tix ms) = Tix (filter (\(TixModule name _ _ _) -> '/' `elem` name) ms) unionTixes :: [Tix] -> ([String], Tix) unionTixes tixes = (Map.keys errs, Tix (Map.elems outputs)) where (errs, outputs) = Map.mapEither id $ Map.unionsWith merge $ map toMap tixes toMap (Tix ms) = Map.fromList (map (\x@(TixModule k _ _ _) -> (k, Right x)) ms) merge (Right (TixModule k hash1 len1 tix1)) (Right (TixModule _ hash2 len2 tix2)) | hash1 == hash2 && len1 == len2 = Right (TixModule k hash1 len1 (zipWith (+) tix1 tix2)) merge _ _ = Left () generateHpcMarkupIndex :: (MonadIO m,MonadReader env m,MonadLogger m,MonadCatch m,HasEnvConfig env) => m () generateHpcMarkupIndex = do outputDir <- hpcReportDir let outputFile = outputDir </> $(mkRelFile "index.html") createTree outputDir (dirs, _) <- listDirectory outputDir rows <- liftM (catMaybes . concat) $ forM dirs $ \dir -> do (subdirs, _) <- listDirectory dir forM subdirs $ \subdir -> do let indexPath = subdir </> $(mkRelFile "hpc_index.html") exists' <- fileExists indexPath if not exists' then return Nothing else do relPath <- stripDir outputDir indexPath let package = dirname dir testsuite = dirname subdir return $ Just $ T.concat [ "<tr><td>" , pathToHtml package , "</td><td><a href=\"" , pathToHtml relPath , "\">" , pathToHtml testsuite , "</a></td></tr>" ] liftIO $ T.writeFile (toFilePath outputFile) $ T.concat $ [ "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" -- Part of the css from HPC's output HTML , "<style type=\"text/css\">" , "table.dashboard { border-collapse: collapse; border: solid 1px black }" , ".dashboard td { border: solid 1px black }" , ".dashboard th { border: solid 1px black }" , "</style>" , "</head>" , "<body>" ] ++ (if null rows then [ "<b>No hpc_index.html files found in \"" , pathToHtml outputDir , "\".</b>" ] else [ "<table class=\"dashboard\" width=\"100%\" boder=\"1\"><tbody>" , "<p><b>NOTE: This is merely a listing of the html files found in the coverage reports directory. Some of these reports may be old.</b></p>" , "<tr><th>Package</th><th>TestSuite</th><th>Modification Time</th></tr>" ] ++ rows ++ ["</tbody></table>"]) ++ ["</body></html>"] unless (null rows) $ $logInfo $ "\nAn index of the generated HTML coverage reports is available at " <> T.pack (toFilePath outputFile) generateHpcErrorReport :: MonadIO m => Path Abs Dir -> Text -> m () generateHpcErrorReport dir err = do createTree dir liftIO $ T.writeFile (toFilePath (dir </> $(mkRelFile "hpc_index.html"))) $ T.concat [ "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></head><body>" , "<h1>HPC Report Generation Error</h1>" , "<p>" , err , "</p>" , "</body></html>" ] pathToHtml :: Path b t -> Text pathToHtml = T.dropWhileEnd (=='/') . sanitize . toFilePath sanitize :: String -> Text sanitize = LT.toStrict . htmlEscape . LT.pack dirnameString :: Path r Dir -> String dirnameString = dropWhileEnd isPathSeparator . toFilePath . dirname findPackageKeyForBuiltPackage :: (MonadIO m, MonadReader env m, MonadThrow m, HasEnvConfig env) => Path Abs Dir -> PackageIdentifier -> m (Maybe Text) findPackageKeyForBuiltPackage pkgDir pkgId = do distDir <- distDirFromDir pkgDir path <- liftM (distDir </>) $ parseRelFile ("package.conf.inplace/" ++ packageIdentifierString pkgId ++ "-inplace.conf") contents <- liftIO $ T.readFile (toFilePath path) return $ asum (map (T.stripPrefix "key: ") (T.lines contents))
mathhun/stack
src/Stack/Coverage.hs
Haskell
bsd-3-clause
20,063
{-| Module : Idris.IBC Description : Core representations and code to generate IBC files. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE TypeSynonymInstances #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Idris.IBC (loadIBC, loadPkgIndex, writeIBC, writePkgIndex, hasValidIBCVersion, IBCPhase(..)) where import Idris.Core.Evaluate import Idris.Core.TT import Idris.Core.Binary import Idris.Core.CaseTree import Idris.AbsSyntax import Idris.Imports import Idris.Error import Idris.DeepSeq import Idris.Delaborate import qualified Idris.Docstrings as D import Idris.Docstrings (Docstring) import Idris.Output import IRTS.System (getIdrisLibDir) import Paths_idris import qualified Cheapskate.Types as CT import Data.Binary import Data.Functor import Data.Vector.Binary import Data.List as L import Data.Maybe (catMaybes) import Data.ByteString.Lazy as B hiding (length, elem, map) import qualified Data.Text as T import qualified Data.Set as S import Control.Monad import Control.DeepSeq import Control.Monad.State.Strict hiding (get, put) import qualified Control.Monad.State.Strict as ST import System.FilePath import System.Directory import Codec.Archive.Zip import Debug.Trace ibcVersion :: Word16 ibcVersion = 144 -- | When IBC is being loaded - we'll load different things (and omit -- different structures/definitions) depending on which phase we're in. data IBCPhase = IBC_Building -- ^ when building the module tree | IBC_REPL Bool -- ^ when loading modules for the REPL Bool = True for top level module deriving (Show, Eq) data IBCFile = IBCFile { ver :: Word16 , sourcefile :: FilePath , ibc_reachablenames :: ![Name] , ibc_imports :: ![(Bool, FilePath)] , ibc_importdirs :: ![FilePath] , ibc_implicits :: ![(Name, [PArg])] , ibc_fixes :: ![FixDecl] , ibc_statics :: ![(Name, [Bool])] , ibc_classes :: ![(Name, ClassInfo)] , ibc_records :: ![(Name, RecordInfo)] , ibc_instances :: ![(Bool, Bool, Name, Name)] , ibc_dsls :: ![(Name, DSL)] , ibc_datatypes :: ![(Name, TypeInfo)] , ibc_optimise :: ![(Name, OptInfo)] , ibc_syntax :: ![Syntax] , ibc_keywords :: ![String] , ibc_objs :: ![(Codegen, FilePath)] , ibc_libs :: ![(Codegen, String)] , ibc_cgflags :: ![(Codegen, String)] , ibc_dynamic_libs :: ![String] , ibc_hdrs :: ![(Codegen, String)] , ibc_totcheckfail :: ![(FC, String)] , ibc_flags :: ![(Name, [FnOpt])] , ibc_fninfo :: ![(Name, FnInfo)] , ibc_cg :: ![(Name, CGInfo)] , ibc_docstrings :: ![(Name, (Docstring D.DocTerm, [(Name, Docstring D.DocTerm)]))] , ibc_moduledocs :: ![(Name, Docstring D.DocTerm)] , ibc_transforms :: ![(Name, (Term, Term))] , ibc_errRev :: ![(Term, Term)] , ibc_coercions :: ![Name] , ibc_lineapps :: ![(FilePath, Int, PTerm)] , ibc_namehints :: ![(Name, Name)] , ibc_metainformation :: ![(Name, MetaInformation)] , ibc_errorhandlers :: ![Name] , ibc_function_errorhandlers :: ![(Name, Name, Name)] -- fn, arg, handler , ibc_metavars :: ![(Name, (Maybe Name, Int, [Name], Bool, Bool))] , ibc_patdefs :: ![(Name, ([([(Name, Term)], Term, Term)], [PTerm]))] , ibc_postulates :: ![Name] , ibc_externs :: ![(Name, Int)] , ibc_parsedSpan :: !(Maybe FC) , ibc_usage :: ![(Name, Int)] , ibc_exports :: ![Name] , ibc_autohints :: ![(Name, Name)] , ibc_deprecated :: ![(Name, String)] , ibc_defs :: ![(Name, Def)] , ibc_total :: ![(Name, Totality)] , ibc_injective :: ![(Name, Injectivity)] , ibc_access :: ![(Name, Accessibility)] , ibc_fragile :: ![(Name, String)] , ibc_constraints :: ![(FC, UConstraint)] } deriving Show {-! deriving instance Binary IBCFile !-} initIBC :: IBCFile initIBC = IBCFile ibcVersion "" [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] Nothing [] [] [] [] [] [] [] [] [] [] hasValidIBCVersion :: FilePath -> Idris Bool hasValidIBCVersion fp = do archiveFile <- runIO $ B.readFile fp case toArchiveOrFail archiveFile of Left _ -> return False Right archive -> do ver <- getEntry 0 "ver" archive return (ver == ibcVersion) loadIBC :: Bool -- ^ True = reexport, False = make everything private -> IBCPhase -> FilePath -> Idris () loadIBC reexport phase fp = do imps <- getImported case lookup fp imps of Nothing -> load True Just p -> if (not p && reexport) then load False else return () where load fullLoad = do logIBC 1 $ "Loading ibc " ++ fp ++ " " ++ show reexport archiveFile <- runIO $ B.readFile fp case toArchiveOrFail archiveFile of Left _ -> do ifail $ fp ++ " isn't loadable, it may have an old ibc format.\n" ++ "Please clean and rebuild it." Right archive -> do if fullLoad then process reexport phase archive fp else unhide phase archive addImported reexport fp -- | Load an entire package from its index file loadPkgIndex :: String -> Idris () loadPkgIndex pkg = do ddir <- runIO getIdrisLibDir addImportDir (ddir </> pkg) fp <- findPkgIndex pkg loadIBC True IBC_Building fp makeEntry :: (Binary b) => String -> [b] -> Maybe Entry makeEntry name val = if L.null val then Nothing else Just $ toEntry name 0 (encode val) entries :: IBCFile -> [Entry] entries i = catMaybes [Just $ toEntry "ver" 0 (encode $ ver i), makeEntry "sourcefile" (sourcefile i), makeEntry "ibc_imports" (ibc_imports i), makeEntry "ibc_importdirs" (ibc_importdirs i), makeEntry "ibc_implicits" (ibc_implicits i), makeEntry "ibc_fixes" (ibc_fixes i), makeEntry "ibc_statics" (ibc_statics i), makeEntry "ibc_classes" (ibc_classes i), makeEntry "ibc_records" (ibc_records i), makeEntry "ibc_instances" (ibc_instances i), makeEntry "ibc_dsls" (ibc_dsls i), makeEntry "ibc_datatypes" (ibc_datatypes i), makeEntry "ibc_optimise" (ibc_optimise i), makeEntry "ibc_syntax" (ibc_syntax i), makeEntry "ibc_keywords" (ibc_keywords i), makeEntry "ibc_objs" (ibc_objs i), makeEntry "ibc_libs" (ibc_libs i), makeEntry "ibc_cgflags" (ibc_cgflags i), makeEntry "ibc_dynamic_libs" (ibc_dynamic_libs i), makeEntry "ibc_hdrs" (ibc_hdrs i), makeEntry "ibc_totcheckfail" (ibc_totcheckfail i), makeEntry "ibc_flags" (ibc_flags i), makeEntry "ibc_fninfo" (ibc_fninfo i), makeEntry "ibc_cg" (ibc_cg i), makeEntry "ibc_docstrings" (ibc_docstrings i), makeEntry "ibc_moduledocs" (ibc_moduledocs i), makeEntry "ibc_transforms" (ibc_transforms i), makeEntry "ibc_errRev" (ibc_errRev i), makeEntry "ibc_coercions" (ibc_coercions i), makeEntry "ibc_lineapps" (ibc_lineapps i), makeEntry "ibc_namehints" (ibc_namehints i), makeEntry "ibc_metainformation" (ibc_metainformation i), makeEntry "ibc_errorhandlers" (ibc_errorhandlers i), makeEntry "ibc_function_errorhandlers" (ibc_function_errorhandlers i), makeEntry "ibc_metavars" (ibc_metavars i), makeEntry "ibc_patdefs" (ibc_patdefs i), makeEntry "ibc_postulates" (ibc_postulates i), makeEntry "ibc_externs" (ibc_externs i), toEntry "ibc_parsedSpan" 0 . encode <$> ibc_parsedSpan i, makeEntry "ibc_usage" (ibc_usage i), makeEntry "ibc_exports" (ibc_exports i), makeEntry "ibc_autohints" (ibc_autohints i), makeEntry "ibc_deprecated" (ibc_deprecated i), makeEntry "ibc_defs" (ibc_defs i), makeEntry "ibc_total" (ibc_total i), makeEntry "ibc_injective" (ibc_injective i), makeEntry "ibc_access" (ibc_access i), makeEntry "ibc_fragile" (ibc_fragile i)] -- TODO: Put this back in shortly after minimising/pruning constraints -- makeEntry "ibc_constraints" (ibc_constraints i)] writeArchive :: FilePath -> IBCFile -> Idris () writeArchive fp i = do let a = L.foldl (\x y -> addEntryToArchive y x) emptyArchive (entries i) runIO $ B.writeFile fp (fromArchive a) writeIBC :: FilePath -> FilePath -> Idris () writeIBC src f = do logIBC 1 $ "Writing ibc " ++ show f i <- getIState -- case (Data.List.map fst (idris_metavars i)) \\ primDefs of -- (_:_) -> ifail "Can't write ibc when there are unsolved metavariables" -- [] -> return () resetNameIdx ibcf <- mkIBC (ibc_write i) (initIBC { sourcefile = src }) idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f) writeArchive f ibcf logIBC 1 "Written") (\c -> do logIBC 1 $ "Failed " ++ pshow i c) return () -- | Write a package index containing all the imports in the current -- IState Used for ':search' of an entire package, to ensure -- everything is loaded. writePkgIndex :: FilePath -> Idris () writePkgIndex f = do i <- getIState let imps = map (\ (x, y) -> (True, x)) $ idris_imported i logIBC 1 $ "Writing package index " ++ show f ++ " including\n" ++ show (map snd imps) resetNameIdx let ibcf = initIBC { ibc_imports = imps } idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f) writeArchive f ibcf logIBC 1 "Written") (\c -> do logIBC 1 $ "Failed " ++ pshow i c) return () mkIBC :: [IBCWrite] -> IBCFile -> Idris IBCFile mkIBC [] f = return f mkIBC (i:is) f = do ist <- getIState logIBC 5 $ show i ++ " " ++ show (L.length is) f' <- ibc ist i f mkIBC is f' ibc :: IState -> IBCWrite -> IBCFile -> Idris IBCFile ibc i (IBCFix d) f = return f { ibc_fixes = d : ibc_fixes f } ibc i (IBCImp n) f = case lookupCtxtExact n (idris_implicits i) of Just v -> return f { ibc_implicits = (n,v): ibc_implicits f } _ -> ifail "IBC write failed" ibc i (IBCStatic n) f = case lookupCtxtExact n (idris_statics i) of Just v -> return f { ibc_statics = (n,v): ibc_statics f } _ -> ifail "IBC write failed" ibc i (IBCClass n) f = case lookupCtxtExact n (idris_classes i) of Just v -> return f { ibc_classes = (n,v): ibc_classes f } _ -> ifail "IBC write failed" ibc i (IBCRecord n) f = case lookupCtxtExact n (idris_records i) of Just v -> return f { ibc_records = (n,v): ibc_records f } _ -> ifail "IBC write failed" ibc i (IBCInstance int res n ins) f = return f { ibc_instances = (int, res, n, ins) : ibc_instances f } ibc i (IBCDSL n) f = case lookupCtxtExact n (idris_dsls i) of Just v -> return f { ibc_dsls = (n,v): ibc_dsls f } _ -> ifail "IBC write failed" ibc i (IBCData n) f = case lookupCtxtExact n (idris_datatypes i) of Just v -> return f { ibc_datatypes = (n,v): ibc_datatypes f } _ -> ifail "IBC write failed" ibc i (IBCOpt n) f = case lookupCtxtExact n (idris_optimisation i) of Just v -> return f { ibc_optimise = (n,v): ibc_optimise f } _ -> ifail "IBC write failed" ibc i (IBCSyntax n) f = return f { ibc_syntax = n : ibc_syntax f } ibc i (IBCKeyword n) f = return f { ibc_keywords = n : ibc_keywords f } ibc i (IBCImport n) f = return f { ibc_imports = n : ibc_imports f } ibc i (IBCImportDir n) f = return f { ibc_importdirs = n : ibc_importdirs f } ibc i (IBCObj tgt n) f = return f { ibc_objs = (tgt, n) : ibc_objs f } ibc i (IBCLib tgt n) f = return f { ibc_libs = (tgt, n) : ibc_libs f } ibc i (IBCCGFlag tgt n) f = return f { ibc_cgflags = (tgt, n) : ibc_cgflags f } ibc i (IBCDyLib n) f = return f {ibc_dynamic_libs = n : ibc_dynamic_libs f } ibc i (IBCHeader tgt n) f = return f { ibc_hdrs = (tgt, n) : ibc_hdrs f } ibc i (IBCDef n) f = do f' <- case lookupDefExact n (tt_ctxt i) of Just v -> return f { ibc_defs = (n,v) : ibc_defs f } _ -> ifail "IBC write failed" case lookupCtxtExact n (idris_patdefs i) of Just v -> return f' { ibc_patdefs = (n,v) : ibc_patdefs f } _ -> return f' -- Not a pattern definition ibc i (IBCDoc n) f = case lookupCtxtExact n (idris_docstrings i) of Just v -> return f { ibc_docstrings = (n,v) : ibc_docstrings f } _ -> ifail "IBC write failed" ibc i (IBCCG n) f = case lookupCtxtExact n (idris_callgraph i) of Just v -> return f { ibc_cg = (n,v) : ibc_cg f } _ -> ifail "IBC write failed" ibc i (IBCCoercion n) f = return f { ibc_coercions = n : ibc_coercions f } ibc i (IBCAccess n a) f = return f { ibc_access = (n,a) : ibc_access f } ibc i (IBCFlags n a) f = return f { ibc_flags = (n,a) : ibc_flags f } ibc i (IBCFnInfo n a) f = return f { ibc_fninfo = (n,a) : ibc_fninfo f } ibc i (IBCTotal n a) f = return f { ibc_total = (n,a) : ibc_total f } ibc i (IBCInjective n a) f = return f { ibc_injective = (n,a) : ibc_injective f } ibc i (IBCTrans n t) f = return f { ibc_transforms = (n, t) : ibc_transforms f } ibc i (IBCErrRev t) f = return f { ibc_errRev = t : ibc_errRev f } ibc i (IBCLineApp fp l t) f = return f { ibc_lineapps = (fp,l,t) : ibc_lineapps f } ibc i (IBCNameHint (n, ty)) f = return f { ibc_namehints = (n, ty) : ibc_namehints f } ibc i (IBCMetaInformation n m) f = return f { ibc_metainformation = (n,m) : ibc_metainformation f } ibc i (IBCErrorHandler n) f = return f { ibc_errorhandlers = n : ibc_errorhandlers f } ibc i (IBCFunctionErrorHandler fn a n) f = return f { ibc_function_errorhandlers = (fn, a, n) : ibc_function_errorhandlers f } ibc i (IBCMetavar n) f = case lookup n (idris_metavars i) of Nothing -> return f Just t -> return f { ibc_metavars = (n, t) : ibc_metavars f } ibc i (IBCPostulate n) f = return f { ibc_postulates = n : ibc_postulates f } ibc i (IBCExtern n) f = return f { ibc_externs = n : ibc_externs f } ibc i (IBCTotCheckErr fc err) f = return f { ibc_totcheckfail = (fc, err) : ibc_totcheckfail f } ibc i (IBCParsedRegion fc) f = return f { ibc_parsedSpan = Just fc } ibc i (IBCModDocs n) f = case lookupCtxtExact n (idris_moduledocs i) of Just v -> return f { ibc_moduledocs = (n,v) : ibc_moduledocs f } _ -> ifail "IBC write failed" ibc i (IBCUsage n) f = return f { ibc_usage = n : ibc_usage f } ibc i (IBCExport n) f = return f { ibc_exports = n : ibc_exports f } ibc i (IBCAutoHint n h) f = return f { ibc_autohints = (n, h) : ibc_autohints f } ibc i (IBCDeprecate n r) f = return f { ibc_deprecated = (n, r) : ibc_deprecated f } ibc i (IBCFragile n r) f = return f { ibc_fragile = (n,r) : ibc_fragile f } ibc i (IBCConstraint fc u) f = return f { ibc_constraints = (fc, u) : ibc_constraints f } getEntry :: (Binary b, NFData b) => b -> FilePath -> Archive -> Idris b getEntry alt f a = case findEntryByPath f a of Nothing -> return alt Just e -> return $! (force . decode . fromEntry) e unhide :: IBCPhase -> Archive -> Idris () unhide phase ar = do processImports True phase ar processAccess True phase ar process :: Bool -- ^ Reexporting -> IBCPhase -> Archive -> FilePath -> Idris () process reexp phase archive fn = do ver <- getEntry 0 "ver" archive when (ver /= ibcVersion) $ do logIBC 1 "ibc out of date" let e = if ver < ibcVersion then " an earlier " else " a later " ifail $ "Incompatible ibc version.\nThis library was built with" ++ e ++ "version of Idris.\n" ++ "Please clean and rebuild." source <- getEntry "" "sourcefile" archive srcok <- runIO $ doesFileExist source when srcok $ timestampOlder source fn processImportDirs archive processImports reexp phase archive processImplicits archive processInfix archive processStatics archive processClasses archive processRecords archive processInstances archive processDSLs archive processDatatypes archive processOptimise archive processSyntax archive processKeywords archive processObjectFiles archive processLibs archive processCodegenFlags archive processDynamicLibs archive processHeaders archive processPatternDefs archive processFlags archive processFnInfo archive processTotalityCheckError archive processCallgraph archive processDocs archive processModuleDocs archive processCoercions archive processTransforms archive processErrRev archive processLineApps archive processNameHints archive processMetaInformation archive processErrorHandlers archive processFunctionErrorHandlers archive processMetaVars archive processPostulates archive processExterns archive processParsedSpan archive processUsage archive processExports archive processAutoHints archive processDeprecate archive processDefs archive processTotal archive processInjective archive processAccess reexp phase archive processFragile archive processConstraints archive timestampOlder :: FilePath -> FilePath -> Idris () timestampOlder src ibc = do srct <- runIO $ getModificationTime src ibct <- runIO $ getModificationTime ibc if (srct > ibct) then ifail $ unlines [ "Module needs reloading:" , unwords ["\tSRC :", show src] , unwords ["\tModified at:", show srct] , unwords ["\tIBC :", show ibc] , unwords ["\tModified at:", show ibct] ] else return () processPostulates :: Archive -> Idris () processPostulates ar = do ns <- getEntry [] "ibc_postulates" ar updateIState (\i -> i { idris_postulates = idris_postulates i `S.union` S.fromList ns }) processExterns :: Archive -> Idris () processExterns ar = do ns <- getEntry [] "ibc_externs" ar updateIState (\i -> i{ idris_externs = idris_externs i `S.union` S.fromList ns }) processParsedSpan :: Archive -> Idris () processParsedSpan ar = do fc <- getEntry Nothing "ibc_parsedSpan" ar updateIState (\i -> i { idris_parsedSpan = fc }) processUsage :: Archive -> Idris () processUsage ar = do ns <- getEntry [] "ibc_usage" ar updateIState (\i -> i { idris_erasureUsed = ns ++ idris_erasureUsed i }) processExports :: Archive -> Idris () processExports ar = do ns <- getEntry [] "ibc_exports" ar updateIState (\i -> i { idris_exports = ns ++ idris_exports i }) processAutoHints :: Archive -> Idris () processAutoHints ar = do ns <- getEntry [] "ibc_autohints" ar mapM_ (\(n,h) -> addAutoHint n h) ns processDeprecate :: Archive -> Idris () processDeprecate ar = do ns <- getEntry [] "ibc_deprecated" ar mapM_ (\(n,reason) -> addDeprecated n reason) ns processFragile :: Archive -> Idris () processFragile ar = do ns <- getEntry [] "ibc_fragile" ar mapM_ (\(n,reason) -> addFragile n reason) ns processConstraints :: Archive -> Idris () processConstraints ar = do cs <- getEntry [] "ibc_constraints" ar mapM_ (\ (fc, c) -> addConstraints fc (0, [c])) cs processImportDirs :: Archive -> Idris () processImportDirs ar = do fs <- getEntry [] "ibc_importdirs" ar mapM_ addImportDir fs processImports :: Bool -> IBCPhase -> Archive -> Idris () processImports reexp phase ar = do fs <- getEntry [] "ibc_imports" ar mapM_ (\(re, f) -> do i <- getIState ibcsd <- valIBCSubDir i ids <- allImportDirs fp <- findImport ids ibcsd f -- if (f `elem` imported i) -- then logLvl 1 $ "Already read " ++ f putIState (i { imported = f : imported i }) let phase' = case phase of IBC_REPL _ -> IBC_REPL False p -> p case fp of LIDR fn -> do logIBC 1 $ "Failed at " ++ fn ifail "Must be an ibc" IDR fn -> do logIBC 1 $ "Failed at " ++ fn ifail "Must be an ibc" IBC fn src -> loadIBC (reexp && re) phase' fn) fs processImplicits :: Archive -> Idris () processImplicits ar = do imps <- getEntry [] "ibc_implicits" ar mapM_ (\ (n, imp) -> do i <- getIState case lookupDefAccExact n False (tt_ctxt i) of Just (n, Hidden) -> return () Just (n, Private) -> return () _ -> putIState (i { idris_implicits = addDef n imp (idris_implicits i) })) imps processInfix :: Archive -> Idris () processInfix ar = do f <- getEntry [] "ibc_fixes" ar updateIState (\i -> i { idris_infixes = sort $ f ++ idris_infixes i }) processStatics :: Archive -> Idris () processStatics ar = do ss <- getEntry [] "ibc_statics" ar mapM_ (\ (n, s) -> updateIState (\i -> i { idris_statics = addDef n s (idris_statics i) })) ss processClasses :: Archive -> Idris () processClasses ar = do cs <- getEntry [] "ibc_classes" ar mapM_ (\ (n, c) -> do i <- getIState -- Don't lose instances from previous IBCs, which -- could have loaded in any order let is = case lookupCtxtExact n (idris_classes i) of Just (CI _ _ _ _ _ ins _) -> ins _ -> [] let c' = c { class_instances = class_instances c ++ is } putIState (i { idris_classes = addDef n c' (idris_classes i) })) cs processRecords :: Archive -> Idris () processRecords ar = do rs <- getEntry [] "ibc_records" ar mapM_ (\ (n, r) -> updateIState (\i -> i { idris_records = addDef n r (idris_records i) })) rs processInstances :: Archive -> Idris () processInstances ar = do cs <- getEntry [] "ibc_instances" ar mapM_ (\ (i, res, n, ins) -> addInstance i res n ins) cs processDSLs :: Archive -> Idris () processDSLs ar = do cs <- getEntry [] "ibc_dsls" ar mapM_ (\ (n, c) -> updateIState (\i -> i { idris_dsls = addDef n c (idris_dsls i) })) cs processDatatypes :: Archive -> Idris () processDatatypes ar = do cs <- getEntry [] "ibc_datatypes" ar mapM_ (\ (n, c) -> updateIState (\i -> i { idris_datatypes = addDef n c (idris_datatypes i) })) cs processOptimise :: Archive -> Idris () processOptimise ar = do cs <- getEntry [] "ibc_optimise" ar mapM_ (\ (n, c) -> updateIState (\i -> i { idris_optimisation = addDef n c (idris_optimisation i) })) cs processSyntax :: Archive -> Idris () processSyntax ar = do s <- getEntry [] "ibc_syntax" ar updateIState (\i -> i { syntax_rules = updateSyntaxRules s (syntax_rules i) }) processKeywords :: Archive -> Idris () processKeywords ar = do k <- getEntry [] "ibc_keywords" ar updateIState (\i -> i { syntax_keywords = k ++ syntax_keywords i }) processObjectFiles :: Archive -> Idris () processObjectFiles ar = do os <- getEntry [] "ibc_objs" ar mapM_ (\ (cg, obj) -> do dirs <- allImportDirs o <- runIO $ findInPath dirs obj addObjectFile cg o) os processLibs :: Archive -> Idris () processLibs ar = do ls <- getEntry [] "ibc_libs" ar mapM_ (uncurry addLib) ls processCodegenFlags :: Archive -> Idris () processCodegenFlags ar = do ls <- getEntry [] "ibc_cgflags" ar mapM_ (uncurry addFlag) ls processDynamicLibs :: Archive -> Idris () processDynamicLibs ar = do ls <- getEntry [] "ibc_dynamic_libs" ar res <- mapM (addDyLib . return) ls mapM_ checkLoad res where checkLoad (Left _) = return () checkLoad (Right err) = ifail err processHeaders :: Archive -> Idris () processHeaders ar = do hs <- getEntry [] "ibc_hdrs" ar mapM_ (uncurry addHdr) hs processPatternDefs :: Archive -> Idris () processPatternDefs ar = do ds <- getEntry [] "ibc_patdefs" ar mapM_ (\ (n, d) -> updateIState (\i -> i { idris_patdefs = addDef n (force d) (idris_patdefs i) })) ds processDefs :: Archive -> Idris () processDefs ar = do ds <- getEntry [] "ibc_defs" ar mapM_ (\ (n, d) -> do d' <- updateDef d case d' of TyDecl _ _ -> return () _ -> do logIBC 1 $ "SOLVING " ++ show n solveDeferred emptyFC n updateIState (\i -> i { tt_ctxt = addCtxtDef n d' (tt_ctxt i) })) ds where updateDef (CaseOp c t args o s cd) = do o' <- mapM updateOrig o cd' <- updateCD cd return $ CaseOp c t args o' s cd' updateDef t = return t updateOrig (Left t) = liftM Left (update t) updateOrig (Right (l, r)) = do l' <- update l r' <- update r return $ Right (l', r') updateCD (CaseDefs (ts, t) (cs, c) (is, i) (rs, r)) = do c' <- updateSC c r' <- updateSC r return $ CaseDefs (cs, c') (cs, c') (cs, c') (rs, r') updateSC (Case t n alts) = do alts' <- mapM updateAlt alts return (Case t n alts') updateSC (ProjCase t alts) = do alts' <- mapM updateAlt alts return (ProjCase t alts') updateSC (STerm t) = do t' <- update t return (STerm t') updateSC c = return c updateAlt (ConCase n i ns t) = do t' <- updateSC t return (ConCase n i ns t') updateAlt (FnCase n ns t) = do t' <- updateSC t return (FnCase n ns t') updateAlt (ConstCase c t) = do t' <- updateSC t return (ConstCase c t') updateAlt (SucCase n t) = do t' <- updateSC t return (SucCase n t') updateAlt (DefaultCase t) = do t' <- updateSC t return (DefaultCase t') -- We get a lot of repetition in sub terms and can save a fair chunk -- of memory if we make sure they're shared. addTT looks for a term -- and returns it if it exists already, while also keeping stats of -- how many times a subterm is repeated. update t = do tm <- addTT t case tm of Nothing -> update' t Just t' -> return t' update' (P t n ty) = do n' <- getSymbol n return $ P t n' ty update' (App s f a) = liftM2 (App s) (update' f) (update' a) update' (Bind n b sc) = do b' <- updateB b sc' <- update sc return $ Bind n b' sc' where updateB (Let t v) = liftM2 Let (update' t) (update' v) updateB b = do ty' <- update' (binderTy b) return (b { binderTy = ty' }) update' (Proj t i) = do t' <- update' t return $ Proj t' i update' t = return t processDocs :: Archive -> Idris () processDocs ar = do ds <- getEntry [] "ibc_docstrings" ar mapM_ (\(n, a) -> addDocStr n (fst a) (snd a)) ds processModuleDocs :: Archive -> Idris () processModuleDocs ar = do ds <- getEntry [] "ibc_moduledocs" ar mapM_ (\ (n, d) -> updateIState (\i -> i { idris_moduledocs = addDef n d (idris_moduledocs i) })) ds processAccess :: Bool -- ^ Reexporting? -> IBCPhase -> Archive -> Idris () processAccess reexp phase ar = do ds <- getEntry [] "ibc_access" ar mapM_ (\ (n, a_in) -> do let a = if reexp then a_in else Hidden logIBC 3 $ "Setting " ++ show (a, n) ++ " to " ++ show a updateIState (\i -> i { tt_ctxt = setAccess n a (tt_ctxt i) }) if (not reexp) then do logIBC 1 $ "Not exporting " ++ show n setAccessibility n Hidden else logIBC 1 $ "Exporting " ++ show n -- Everything should be available at the REPL from -- things imported publicly when (phase == IBC_REPL True) $ setAccessibility n Public) ds processFlags :: Archive -> Idris () processFlags ar = do ds <- getEntry [] "ibc_flags" ar mapM_ (\ (n, a) -> setFlags n a) ds processFnInfo :: Archive -> Idris () processFnInfo ar = do ds <- getEntry [] "ibc_fninfo" ar mapM_ (\ (n, a) -> setFnInfo n a) ds processTotal :: Archive -> Idris () processTotal ar = do ds <- getEntry [] "ibc_total" ar mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setTotal n a (tt_ctxt i) })) ds processInjective :: Archive -> Idris () processInjective ar = do ds <- getEntry [] "ibc_injective" ar mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setInjective n a (tt_ctxt i) })) ds processTotalityCheckError :: Archive -> Idris () processTotalityCheckError ar = do es <- getEntry [] "ibc_totcheckfail" ar updateIState (\i -> i { idris_totcheckfail = idris_totcheckfail i ++ es }) processCallgraph :: Archive -> Idris () processCallgraph ar = do ds <- getEntry [] "ibc_cg" ar mapM_ (\ (n, a) -> addToCG n a) ds processCoercions :: Archive -> Idris () processCoercions ar = do ns <- getEntry [] "ibc_coercions" ar mapM_ (\ n -> addCoercion n) ns processTransforms :: Archive -> Idris () processTransforms ar = do ts <- getEntry [] "ibc_transforms" ar mapM_ (\ (n, t) -> addTrans n t) ts processErrRev :: Archive -> Idris () processErrRev ar = do ts <- getEntry [] "ibc_errRev" ar mapM_ addErrRev ts processLineApps :: Archive -> Idris () processLineApps ar = do ls <- getEntry [] "ibc_lineapps" ar mapM_ (\ (f, i, t) -> addInternalApp f i t) ls processNameHints :: Archive -> Idris () processNameHints ar = do ns <- getEntry [] "ibc_namehints" ar mapM_ (\ (n, ty) -> addNameHint n ty) ns processMetaInformation :: Archive -> Idris () processMetaInformation ar = do ds <- getEntry [] "ibc_metainformation" ar mapM_ (\ (n, m) -> updateIState (\i -> i { tt_ctxt = setMetaInformation n m (tt_ctxt i) })) ds processErrorHandlers :: Archive -> Idris () processErrorHandlers ar = do ns <- getEntry [] "ibc_errorhandlers" ar updateIState (\i -> i { idris_errorhandlers = idris_errorhandlers i ++ ns }) processFunctionErrorHandlers :: Archive -> Idris () processFunctionErrorHandlers ar = do ns <- getEntry [] "ibc_function_errorhandlers" ar mapM_ (\ (fn,arg,handler) -> addFunctionErrorHandlers fn arg [handler]) ns processMetaVars :: Archive -> Idris () processMetaVars ar = do ns <- getEntry [] "ibc_metavars" ar updateIState (\i -> i { idris_metavars = L.reverse ns ++ idris_metavars i }) ----- For Cheapskate and docstrings instance Binary a => Binary (D.Docstring a) where put (D.DocString opts lines) = do put opts ; put lines get = do opts <- get lines <- get return (D.DocString opts lines) instance Binary CT.Options where put (CT.Options x1 x2 x3 x4) = do put x1 ; put x2 ; put x3 ; put x4 get = do x1 <- get x2 <- get x3 <- get x4 <- get return (CT.Options x1 x2 x3 x4) instance Binary D.DocTerm where put D.Unchecked = putWord8 0 put (D.Checked t) = putWord8 1 >> put t put (D.Example t) = putWord8 2 >> put t put (D.Failing e) = putWord8 3 >> put e get = do i <- getWord8 case i of 0 -> return D.Unchecked 1 -> fmap D.Checked get 2 -> fmap D.Example get 3 -> fmap D.Failing get _ -> error "Corrupted binary data for DocTerm" instance Binary a => Binary (D.Block a) where put (D.Para lines) = do putWord8 0 ; put lines put (D.Header i lines) = do putWord8 1 ; put i ; put lines put (D.Blockquote bs) = do putWord8 2 ; put bs put (D.List b t xs) = do putWord8 3 ; put b ; put t ; put xs put (D.CodeBlock attr txt src) = do putWord8 4 ; put attr ; put txt ; put src put (D.HtmlBlock txt) = do putWord8 5 ; put txt put D.HRule = putWord8 6 get = do i <- getWord8 case i of 0 -> fmap D.Para get 1 -> liftM2 D.Header get get 2 -> fmap D.Blockquote get 3 -> liftM3 D.List get get get 4 -> liftM3 D.CodeBlock get get get 5 -> liftM D.HtmlBlock get 6 -> return D.HRule _ -> error "Corrupted binary data for Block" instance Binary a => Binary (D.Inline a) where put (D.Str txt) = do putWord8 0 ; put txt put D.Space = putWord8 1 put D.SoftBreak = putWord8 2 put D.LineBreak = putWord8 3 put (D.Emph xs) = putWord8 4 >> put xs put (D.Strong xs) = putWord8 5 >> put xs put (D.Code xs tm) = putWord8 6 >> put xs >> put tm put (D.Link a b c) = putWord8 7 >> put a >> put b >> put c put (D.Image a b c) = putWord8 8 >> put a >> put b >> put c put (D.Entity a) = putWord8 9 >> put a put (D.RawHtml x) = putWord8 10 >> put x get = do i <- getWord8 case i of 0 -> liftM D.Str get 1 -> return D.Space 2 -> return D.SoftBreak 3 -> return D.LineBreak 4 -> liftM D.Emph get 5 -> liftM D.Strong get 6 -> liftM2 D.Code get get 7 -> liftM3 D.Link get get get 8 -> liftM3 D.Image get get get 9 -> liftM D.Entity get 10 -> liftM D.RawHtml get _ -> error "Corrupted binary data for Inline" instance Binary CT.ListType where put (CT.Bullet c) = putWord8 0 >> put c put (CT.Numbered nw i) = putWord8 1 >> put nw >> put i get = do i <- getWord8 case i of 0 -> liftM CT.Bullet get 1 -> liftM2 CT.Numbered get get _ -> error "Corrupted binary data for ListType" instance Binary CT.CodeAttr where put (CT.CodeAttr a b) = put a >> put b get = liftM2 CT.CodeAttr get get instance Binary CT.NumWrapper where put (CT.PeriodFollowing) = putWord8 0 put (CT.ParenFollowing) = putWord8 1 get = do i <- getWord8 case i of 0 -> return CT.PeriodFollowing 1 -> return CT.ParenFollowing _ -> error "Corrupted binary data for NumWrapper" ----- Generated by 'derive' instance Binary SizeChange where put x = case x of Smaller -> putWord8 0 Same -> putWord8 1 Bigger -> putWord8 2 Unknown -> putWord8 3 get = do i <- getWord8 case i of 0 -> return Smaller 1 -> return Same 2 -> return Bigger 3 -> return Unknown _ -> error "Corrupted binary data for SizeChange" instance Binary CGInfo where put (CGInfo x1 x2 x3) = do put x1 -- put x3 -- Already used SCG info for totality check put x3 get = do x1 <- get x3 <- get return (CGInfo x1 [] x3) instance Binary CaseType where put x = case x of Updatable -> putWord8 0 Shared -> putWord8 1 get = do i <- getWord8 case i of 0 -> return Updatable 1 -> return Shared _ -> error "Corrupted binary data for CaseType" instance Binary SC where put x = case x of Case x1 x2 x3 -> do putWord8 0 put x1 put x2 put x3 ProjCase x1 x2 -> do putWord8 1 put x1 put x2 STerm x1 -> do putWord8 2 put x1 UnmatchedCase x1 -> do putWord8 3 put x1 ImpossibleCase -> do putWord8 4 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get return (Case x1 x2 x3) 1 -> do x1 <- get x2 <- get return (ProjCase x1 x2) 2 -> do x1 <- get return (STerm x1) 3 -> do x1 <- get return (UnmatchedCase x1) 4 -> return ImpossibleCase _ -> error "Corrupted binary data for SC" instance Binary CaseAlt where put x = {-# SCC "putCaseAlt" #-} case x of ConCase x1 x2 x3 x4 -> do putWord8 0 put x1 put x2 put x3 put x4 ConstCase x1 x2 -> do putWord8 1 put x1 put x2 DefaultCase x1 -> do putWord8 2 put x1 FnCase x1 x2 x3 -> do putWord8 3 put x1 put x2 put x3 SucCase x1 x2 -> do putWord8 4 put x1 put x2 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (ConCase x1 x2 x3 x4) 1 -> do x1 <- get x2 <- get return (ConstCase x1 x2) 2 -> do x1 <- get return (DefaultCase x1) 3 -> do x1 <- get x2 <- get x3 <- get return (FnCase x1 x2 x3) 4 -> do x1 <- get x2 <- get return (SucCase x1 x2) _ -> error "Corrupted binary data for CaseAlt" instance Binary CaseDefs where put (CaseDefs x1 x2 x3 x4) = do -- don't need totality checked or inlined versions put x2 put x4 get = do x2 <- get x4 <- get return (CaseDefs x2 x2 x2 x4) instance Binary CaseInfo where put x@(CaseInfo x1 x2 x3) = do put x1 put x2 put x3 get = do x1 <- get x2 <- get x3 <- get return (CaseInfo x1 x2 x3) instance Binary Def where put x = {-# SCC "putDef" #-} case x of Function x1 x2 -> do putWord8 0 put x1 put x2 TyDecl x1 x2 -> do putWord8 1 put x1 put x2 -- all primitives just get added at the start, don't write Operator x1 x2 x3 -> do return () -- no need to add/load original patterns, because they're not -- used again after totality checking CaseOp x1 x2 x3 _ _ x4 -> do putWord8 3 put x1 put x2 put x3 put x4 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get return (Function x1 x2) 1 -> do x1 <- get x2 <- get return (TyDecl x1 x2) -- Operator isn't written, don't read 3 -> do x1 <- get x2 <- get x3 <- get -- x4 <- get -- x3 <- get always [] x5 <- get return (CaseOp x1 x2 x3 [] [] x5) _ -> error "Corrupted binary data for Def" instance Binary Accessibility where put x = case x of Public -> putWord8 0 Frozen -> putWord8 1 Private -> putWord8 2 Hidden -> putWord8 3 get = do i <- getWord8 case i of 0 -> return Public 1 -> return Frozen 2 -> return Private 3 -> return Hidden _ -> error "Corrupted binary data for Accessibility" safeToEnum :: (Enum a, Bounded a, Integral int) => String -> int -> a safeToEnum label x' = result where x = fromIntegral x' result | x < fromEnum (minBound `asTypeOf` result) || x > fromEnum (maxBound `asTypeOf` result) = error $ label ++ ": corrupted binary representation in IBC" | otherwise = toEnum x instance Binary PReason where put x = case x of Other x1 -> do putWord8 0 put x1 Itself -> putWord8 1 NotCovering -> putWord8 2 NotPositive -> putWord8 3 Mutual x1 -> do putWord8 4 put x1 NotProductive -> putWord8 5 BelieveMe -> putWord8 6 UseUndef x1 -> do putWord8 7 put x1 ExternalIO -> putWord8 8 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Other x1) 1 -> return Itself 2 -> return NotCovering 3 -> return NotPositive 4 -> do x1 <- get return (Mutual x1) 5 -> return NotProductive 6 -> return BelieveMe 7 -> do x1 <- get return (UseUndef x1) 8 -> return ExternalIO _ -> error "Corrupted binary data for PReason" instance Binary Totality where put x = case x of Total x1 -> do putWord8 0 put x1 Partial x1 -> do putWord8 1 put x1 Unchecked -> do putWord8 2 Productive -> do putWord8 3 Generated -> do putWord8 4 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Total x1) 1 -> do x1 <- get return (Partial x1) 2 -> return Unchecked 3 -> return Productive 4 -> return Generated _ -> error "Corrupted binary data for Totality" instance Binary MetaInformation where put x = case x of EmptyMI -> do putWord8 0 DataMI x1 -> do putWord8 1 put x1 get = do i <- getWord8 case i of 0 -> return EmptyMI 1 -> do x1 <- get return (DataMI x1) _ -> error "Corrupted binary data for MetaInformation" instance Binary DataOpt where put x = case x of Codata -> putWord8 0 DefaultEliminator -> putWord8 1 DataErrRev -> putWord8 2 DefaultCaseFun -> putWord8 3 get = do i <- getWord8 case i of 0 -> return Codata 1 -> return DefaultEliminator 2 -> return DataErrRev 3 -> return DefaultCaseFun _ -> error "Corrupted binary data for DataOpt" instance Binary FnOpt where put x = case x of Inlinable -> putWord8 0 TotalFn -> putWord8 1 Dictionary -> putWord8 2 AssertTotal -> putWord8 3 Specialise x -> do putWord8 4 put x Coinductive -> putWord8 5 PartialFn -> putWord8 6 Implicit -> putWord8 7 Reflection -> putWord8 8 ErrorHandler -> putWord8 9 ErrorReverse -> putWord8 10 CoveringFn -> putWord8 11 NoImplicit -> putWord8 12 Constructor -> putWord8 13 CExport x1 -> do putWord8 14 put x1 AutoHint -> putWord8 15 PEGenerated -> putWord8 16 get = do i <- getWord8 case i of 0 -> return Inlinable 1 -> return TotalFn 2 -> return Dictionary 3 -> return AssertTotal 4 -> do x <- get return (Specialise x) 5 -> return Coinductive 6 -> return PartialFn 7 -> return Implicit 8 -> return Reflection 9 -> return ErrorHandler 10 -> return ErrorReverse 11 -> return CoveringFn 12 -> return NoImplicit 13 -> return Constructor 14 -> do x1 <- get return $ CExport x1 15 -> return AutoHint 16 -> return PEGenerated _ -> error "Corrupted binary data for FnOpt" instance Binary Fixity where put x = case x of Infixl x1 -> do putWord8 0 put x1 Infixr x1 -> do putWord8 1 put x1 InfixN x1 -> do putWord8 2 put x1 PrefixN x1 -> do putWord8 3 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Infixl x1) 1 -> do x1 <- get return (Infixr x1) 2 -> do x1 <- get return (InfixN x1) 3 -> do x1 <- get return (PrefixN x1) _ -> error "Corrupted binary data for Fixity" instance Binary FixDecl where put (Fix x1 x2) = do put x1 put x2 get = do x1 <- get x2 <- get return (Fix x1 x2) instance Binary ArgOpt where put x = case x of HideDisplay -> putWord8 0 InaccessibleArg -> putWord8 1 AlwaysShow -> putWord8 2 UnknownImp -> putWord8 3 get = do i <- getWord8 case i of 0 -> return HideDisplay 1 -> return InaccessibleArg 2 -> return AlwaysShow 3 -> return UnknownImp _ -> error "Corrupted binary data for Static" instance Binary Static where put x = case x of Static -> putWord8 0 Dynamic -> putWord8 1 get = do i <- getWord8 case i of 0 -> return Static 1 -> return Dynamic _ -> error "Corrupted binary data for Static" instance Binary Plicity where put x = case x of Imp x1 x2 x3 x4 _ -> do putWord8 0 put x1 put x2 put x3 put x4 Exp x1 x2 x3 -> do putWord8 1 put x1 put x2 put x3 Constraint x1 x2 -> do putWord8 2 put x1 put x2 TacImp x1 x2 x3 -> do putWord8 3 put x1 put x2 put x3 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (Imp x1 x2 x3 x4 False) 1 -> do x1 <- get x2 <- get x3 <- get return (Exp x1 x2 x3) 2 -> do x1 <- get x2 <- get return (Constraint x1 x2) 3 -> do x1 <- get x2 <- get x3 <- get return (TacImp x1 x2 x3) _ -> error "Corrupted binary data for Plicity" instance (Binary t) => Binary (PDecl' t) where put x = case x of PFix x1 x2 x3 -> do putWord8 0 put x1 put x2 put x3 PTy x1 x2 x3 x4 x5 x6 x7 x8 -> do putWord8 1 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 PClauses x1 x2 x3 x4 -> do putWord8 2 put x1 put x2 put x3 put x4 PData x1 x2 x3 x4 x5 x6 -> do putWord8 3 put x1 put x2 put x3 put x4 put x5 put x6 PParams x1 x2 x3 -> do putWord8 4 put x1 put x2 put x3 PNamespace x1 x2 x3 -> do putWord8 5 put x1 put x2 put x3 PRecord x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 -> do putWord8 6 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 put x9 put x10 put x11 put x12 PClass x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 -> do putWord8 7 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 put x9 put x10 put x11 put x12 PInstance x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 -> do putWord8 8 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 put x9 put x10 put x11 put x12 put x13 put x14 put x15 PDSL x1 x2 -> do putWord8 9 put x1 put x2 PCAF x1 x2 x3 -> do putWord8 10 put x1 put x2 put x3 PMutual x1 x2 -> do putWord8 11 put x1 put x2 PPostulate x1 x2 x3 x4 x5 x6 x7 x8 -> do putWord8 12 put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 PSyntax x1 x2 -> do putWord8 13 put x1 put x2 PDirective x1 -> error "Cannot serialize PDirective" PProvider x1 x2 x3 x4 x5 x6 -> do putWord8 15 put x1 put x2 put x3 put x4 put x5 put x6 PTransform x1 x2 x3 x4 -> do putWord8 16 put x1 put x2 put x3 put x4 PRunElabDecl x1 x2 x3 -> do putWord8 17 put x1 put x2 put x3 POpenInterfaces x1 x2 x3 -> do putWord8 18 put x1 put x2 put x3 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get return (PFix x1 x2 x3) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get return (PTy x1 x2 x3 x4 x5 x6 x7 x8) 2 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PClauses x1 x2 x3 x4) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PData x1 x2 x3 x4 x5 x6) 4 -> do x1 <- get x2 <- get x3 <- get return (PParams x1 x2 x3) 5 -> do x1 <- get x2 <- get x3 <- get return (PNamespace x1 x2 x3) 6 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get x9 <- get x10 <- get x11 <- get x12 <- get return (PRecord x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12) 7 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get x9 <- get x10 <- get x11 <- get x12 <- get return (PClass x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12) 8 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get x9 <- get x10 <- get x11 <- get x12 <- get x13 <- get x14 <- get x15 <- get return (PInstance x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15) 9 -> do x1 <- get x2 <- get return (PDSL x1 x2) 10 -> do x1 <- get x2 <- get x3 <- get return (PCAF x1 x2 x3) 11 -> do x1 <- get x2 <- get return (PMutual x1 x2) 12 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get return (PPostulate x1 x2 x3 x4 x5 x6 x7 x8) 13 -> do x1 <- get x2 <- get return (PSyntax x1 x2) 14 -> do error "Cannot deserialize PDirective" 15 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PProvider x1 x2 x3 x4 x5 x6) 16 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PTransform x1 x2 x3 x4) 17 -> do x1 <- get x2 <- get x3 <- get return (PRunElabDecl x1 x2 x3) 18 -> do x1 <- get x2 <- get x3 <- get return (POpenInterfaces x1 x2 x3) _ -> error "Corrupted binary data for PDecl'" instance Binary t => Binary (ProvideWhat' t) where put (ProvTerm x1 x2) = do putWord8 0 put x1 put x2 put (ProvPostulate x1) = do putWord8 1 put x1 get = do y <- getWord8 case y of 0 -> do x1 <- get x2 <- get return (ProvTerm x1 x2) 1 -> do x1 <- get return (ProvPostulate x1) _ -> error "Corrupted binary data for ProvideWhat" instance Binary Using where put (UImplicit x1 x2) = do putWord8 0; put x1; put x2 put (UConstraint x1 x2) = do putWord8 1; put x1; put x2 get = do i <- getWord8 case i of 0 -> do x1 <- get; x2 <- get; return (UImplicit x1 x2) 1 -> do x1 <- get; x2 <- get; return (UConstraint x1 x2) _ -> error "Corrupted binary data for Using" instance Binary SyntaxInfo where put (Syn x1 x2 x3 x4 _ _ x5 x6 x7 _ _ x8 _ _ _) = do put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get return (Syn x1 x2 x3 x4 [] id x5 x6 x7 Nothing 0 x8 0 True True) instance (Binary t) => Binary (PClause' t) where put x = case x of PClause x1 x2 x3 x4 x5 x6 -> do putWord8 0 put x1 put x2 put x3 put x4 put x5 put x6 PWith x1 x2 x3 x4 x5 x6 x7 -> do putWord8 1 put x1 put x2 put x3 put x4 put x5 put x6 put x7 PClauseR x1 x2 x3 x4 -> do putWord8 2 put x1 put x2 put x3 put x4 PWithR x1 x2 x3 x4 x5 -> do putWord8 3 put x1 put x2 put x3 put x4 put x5 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PClause x1 x2 x3 x4 x5 x6) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get return (PWith x1 x2 x3 x4 x5 x6 x7) 2 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PClauseR x1 x2 x3 x4) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PWithR x1 x2 x3 x4 x5) _ -> error "Corrupted binary data for PClause'" instance (Binary t) => Binary (PData' t) where put x = case x of PDatadecl x1 x2 x3 x4 -> do putWord8 0 put x1 put x2 put x3 put x4 PLaterdecl x1 x2 x3 -> do putWord8 1 put x1 put x2 put x3 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PDatadecl x1 x2 x3 x4) 1 -> do x1 <- get x2 <- get x3 <- get return (PLaterdecl x1 x2 x3) _ -> error "Corrupted binary data for PData'" instance Binary PunInfo where put x = case x of TypeOrTerm -> putWord8 0 IsType -> putWord8 1 IsTerm -> putWord8 2 get = do i <- getWord8 case i of 0 -> return TypeOrTerm 1 -> return IsType 2 -> return IsTerm _ -> error "Corrupted binary data for PunInfo" instance Binary PTerm where put x = case x of PQuote x1 -> do putWord8 0 put x1 PRef x1 x2 x3 -> do putWord8 1 put x1 put x2 put x3 PInferRef x1 x2 x3 -> do putWord8 2 put x1 put x2 put x3 PPatvar x1 x2 -> do putWord8 3 put x1 put x2 PLam x1 x2 x3 x4 x5 -> do putWord8 4 put x1 put x2 put x3 put x4 put x5 PPi x1 x2 x3 x4 x5 -> do putWord8 5 put x1 put x2 put x3 put x4 put x5 PLet x1 x2 x3 x4 x5 x6 -> do putWord8 6 put x1 put x2 put x3 put x4 put x5 put x6 PTyped x1 x2 -> do putWord8 7 put x1 put x2 PAppImpl x1 x2 -> error "PAppImpl in final term" PApp x1 x2 x3 -> do putWord8 8 put x1 put x2 put x3 PAppBind x1 x2 x3 -> do putWord8 9 put x1 put x2 put x3 PMatchApp x1 x2 -> do putWord8 10 put x1 put x2 PCase x1 x2 x3 -> do putWord8 11 put x1 put x2 put x3 PTrue x1 x2 -> do putWord8 12 put x1 put x2 PResolveTC x1 -> do putWord8 15 put x1 PRewrite x1 x2 x3 x4 x5 -> do putWord8 17 put x1 put x2 put x3 put x4 put x5 PPair x1 x2 x3 x4 x5 -> do putWord8 18 put x1 put x2 put x3 put x4 put x5 PDPair x1 x2 x3 x4 x5 x6 -> do putWord8 19 put x1 put x2 put x3 put x4 put x5 put x6 PAlternative x1 x2 x3 -> do putWord8 20 put x1 put x2 put x3 PHidden x1 -> do putWord8 21 put x1 PType x1 -> do putWord8 22 put x1 PGoal x1 x2 x3 x4 -> do putWord8 23 put x1 put x2 put x3 put x4 PConstant x1 x2 -> do putWord8 24 put x1 put x2 Placeholder -> putWord8 25 PDoBlock x1 -> do putWord8 26 put x1 PIdiom x1 x2 -> do putWord8 27 put x1 put x2 PReturn x1 -> do putWord8 28 put x1 PMetavar x1 x2 -> do putWord8 29 put x1 put x2 PProof x1 -> do putWord8 30 put x1 PTactics x1 -> do putWord8 31 put x1 PImpossible -> putWord8 33 PCoerced x1 -> do putWord8 34 put x1 PUnifyLog x1 -> do putWord8 35 put x1 PNoImplicits x1 -> do putWord8 36 put x1 PDisamb x1 x2 -> do putWord8 37 put x1 put x2 PUniverse x1 -> do putWord8 38 put x1 PRunElab x1 x2 x3 -> do putWord8 39 put x1 put x2 put x3 PAs x1 x2 x3 -> do putWord8 40 put x1 put x2 put x3 PElabError x1 -> do putWord8 41 put x1 PQuasiquote x1 x2 -> do putWord8 42 put x1 put x2 PUnquote x1 -> do putWord8 43 put x1 PQuoteName x1 x2 x3 -> do putWord8 44 put x1 put x2 put x3 PIfThenElse x1 x2 x3 x4 -> do putWord8 45 put x1 put x2 put x3 put x4 PConstSugar x1 x2 -> do putWord8 46 put x1 put x2 PWithApp x1 x2 x3 -> do putWord8 47 put x1 put x2 put x3 get = do i <- getWord8 case i of 0 -> do x1 <- get return (PQuote x1) 1 -> do x1 <- get x2 <- get x3 <- get return (PRef x1 x2 x3) 2 -> do x1 <- get x2 <- get x3 <- get return (PInferRef x1 x2 x3) 3 -> do x1 <- get x2 <- get return (PPatvar x1 x2) 4 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PLam x1 x2 x3 x4 x5) 5 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PPi x1 x2 x3 x4 x5) 6 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PLet x1 x2 x3 x4 x5 x6) 7 -> do x1 <- get x2 <- get return (PTyped x1 x2) 8 -> do x1 <- get x2 <- get x3 <- get return (PApp x1 x2 x3) 9 -> do x1 <- get x2 <- get x3 <- get return (PAppBind x1 x2 x3) 10 -> do x1 <- get x2 <- get return (PMatchApp x1 x2) 11 -> do x1 <- get x2 <- get x3 <- get return (PCase x1 x2 x3) 12 -> do x1 <- get x2 <- get return (PTrue x1 x2) 15 -> do x1 <- get return (PResolveTC x1) 17 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PRewrite x1 x2 x3 x4 x5) 18 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PPair x1 x2 x3 x4 x5) 19 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (PDPair x1 x2 x3 x4 x5 x6) 20 -> do x1 <- get x2 <- get x3 <- get return (PAlternative x1 x2 x3) 21 -> do x1 <- get return (PHidden x1) 22 -> do x1 <- get return (PType x1) 23 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PGoal x1 x2 x3 x4) 24 -> do x1 <- get x2 <- get return (PConstant x1 x2) 25 -> return Placeholder 26 -> do x1 <- get return (PDoBlock x1) 27 -> do x1 <- get x2 <- get return (PIdiom x1 x2) 28 -> do x1 <- get return (PReturn x1) 29 -> do x1 <- get x2 <- get return (PMetavar x1 x2) 30 -> do x1 <- get return (PProof x1) 31 -> do x1 <- get return (PTactics x1) 33 -> return PImpossible 34 -> do x1 <- get return (PCoerced x1) 35 -> do x1 <- get return (PUnifyLog x1) 36 -> do x1 <- get return (PNoImplicits x1) 37 -> do x1 <- get x2 <- get return (PDisamb x1 x2) 38 -> do x1 <- get return (PUniverse x1) 39 -> do x1 <- get x2 <- get x3 <- get return (PRunElab x1 x2 x3) 40 -> do x1 <- get x2 <- get x3 <- get return (PAs x1 x2 x3) 41 -> do x1 <- get return (PElabError x1) 42 -> do x1 <- get x2 <- get return (PQuasiquote x1 x2) 43 -> do x1 <- get return (PUnquote x1) 44 -> do x1 <- get x2 <- get x3 <- get return (PQuoteName x1 x2 x3) 45 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PIfThenElse x1 x2 x3 x4) 46 -> do x1 <- get x2 <- get return (PConstSugar x1 x2) 47 -> do x1 <- get x2 <- get x3 <- get return (PWithApp x1 x2 x3) _ -> error "Corrupted binary data for PTerm" instance Binary PAltType where put x = case x of ExactlyOne x1 -> do putWord8 0 put x1 FirstSuccess -> putWord8 1 TryImplicit -> putWord8 2 get = do i <- getWord8 case i of 0 -> do x1 <- get return (ExactlyOne x1) 1 -> return FirstSuccess 2 -> return TryImplicit _ -> error "Corrupted binary data for PAltType" instance (Binary t) => Binary (PTactic' t) where put x = case x of Intro x1 -> do putWord8 0 put x1 Focus x1 -> do putWord8 1 put x1 Refine x1 x2 -> do putWord8 2 put x1 put x2 Rewrite x1 -> do putWord8 3 put x1 LetTac x1 x2 -> do putWord8 4 put x1 put x2 Exact x1 -> do putWord8 5 put x1 Compute -> putWord8 6 Trivial -> putWord8 7 Solve -> putWord8 8 Attack -> putWord8 9 ProofState -> putWord8 10 ProofTerm -> putWord8 11 Undo -> putWord8 12 Try x1 x2 -> do putWord8 13 put x1 put x2 TSeq x1 x2 -> do putWord8 14 put x1 put x2 Qed -> putWord8 15 ApplyTactic x1 -> do putWord8 16 put x1 Reflect x1 -> do putWord8 17 put x1 Fill x1 -> do putWord8 18 put x1 Induction x1 -> do putWord8 19 put x1 ByReflection x1 -> do putWord8 20 put x1 ProofSearch x1 x2 x3 x4 x5 x6 -> do putWord8 21 put x1 put x2 put x3 put x4 put x5 put x6 DoUnify -> putWord8 22 CaseTac x1 -> do putWord8 23 put x1 SourceFC -> putWord8 24 Intros -> putWord8 25 Equiv x1 -> do putWord8 26 put x1 Claim x1 x2 -> do putWord8 27 put x1 put x2 Unfocus -> putWord8 28 MatchRefine x1 -> do putWord8 29 put x1 LetTacTy x1 x2 x3 -> do putWord8 30 put x1 put x2 put x3 TCInstance -> putWord8 31 GoalType x1 x2 -> do putWord8 32 put x1 put x2 TCheck x1 -> do putWord8 33 put x1 TEval x1 -> do putWord8 34 put x1 TDocStr x1 -> do putWord8 35 put x1 TSearch x1 -> do putWord8 36 put x1 Skip -> putWord8 37 TFail x1 -> do putWord8 38 put x1 Abandon -> putWord8 39 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Intro x1) 1 -> do x1 <- get return (Focus x1) 2 -> do x1 <- get x2 <- get return (Refine x1 x2) 3 -> do x1 <- get return (Rewrite x1) 4 -> do x1 <- get x2 <- get return (LetTac x1 x2) 5 -> do x1 <- get return (Exact x1) 6 -> return Compute 7 -> return Trivial 8 -> return Solve 9 -> return Attack 10 -> return ProofState 11 -> return ProofTerm 12 -> return Undo 13 -> do x1 <- get x2 <- get return (Try x1 x2) 14 -> do x1 <- get x2 <- get return (TSeq x1 x2) 15 -> return Qed 16 -> do x1 <- get return (ApplyTactic x1) 17 -> do x1 <- get return (Reflect x1) 18 -> do x1 <- get return (Fill x1) 19 -> do x1 <- get return (Induction x1) 20 -> do x1 <- get return (ByReflection x1) 21 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (ProofSearch x1 x2 x3 x4 x5 x6) 22 -> return DoUnify 23 -> do x1 <- get return (CaseTac x1) 24 -> return SourceFC 25 -> return Intros 26 -> do x1 <- get return (Equiv x1) 27 -> do x1 <- get x2 <- get return (Claim x1 x2) 28 -> return Unfocus 29 -> do x1 <- get return (MatchRefine x1) 30 -> do x1 <- get x2 <- get x3 <- get return (LetTacTy x1 x2 x3) 31 -> return TCInstance 32 -> do x1 <- get x2 <- get return (GoalType x1 x2) 33 -> do x1 <- get return (TCheck x1) 34 -> do x1 <- get return (TEval x1) 35 -> do x1 <- get return (TDocStr x1) 36 -> do x1 <- get return (TSearch x1) 37 -> return Skip 38 -> do x1 <- get return (TFail x1) 39 -> return Abandon _ -> error "Corrupted binary data for PTactic'" instance (Binary t) => Binary (PDo' t) where put x = case x of DoExp x1 x2 -> do putWord8 0 put x1 put x2 DoBind x1 x2 x3 x4 -> do putWord8 1 put x1 put x2 put x3 put x4 DoBindP x1 x2 x3 x4 -> do putWord8 2 put x1 put x2 put x3 put x4 DoLet x1 x2 x3 x4 x5 -> do putWord8 3 put x1 put x2 put x3 put x4 put x5 DoLetP x1 x2 x3 -> do putWord8 4 put x1 put x2 put x3 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get return (DoExp x1 x2) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (DoBind x1 x2 x3 x4) 2 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (DoBindP x1 x2 x3 x4) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (DoLet x1 x2 x3 x4 x5) 4 -> do x1 <- get x2 <- get x3 <- get return (DoLetP x1 x2 x3) _ -> error "Corrupted binary data for PDo'" instance (Binary t) => Binary (PArg' t) where put x = case x of PImp x1 x2 x3 x4 x5 -> do putWord8 0 put x1 put x2 put x3 put x4 put x5 PExp x1 x2 x3 x4 -> do putWord8 1 put x1 put x2 put x3 put x4 PConstraint x1 x2 x3 x4 -> do putWord8 2 put x1 put x2 put x3 put x4 PTacImplicit x1 x2 x3 x4 x5 -> do putWord8 3 put x1 put x2 put x3 put x4 put x5 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PImp x1 x2 x3 x4 x5) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PExp x1 x2 x3 x4) 2 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (PConstraint x1 x2 x3 x4) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (PTacImplicit x1 x2 x3 x4 x5) _ -> error "Corrupted binary data for PArg'" instance Binary ClassInfo where put (CI x1 x2 x3 x4 x5 _ x6) = do put x1 put x2 put x3 put x4 put x5 put x6 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get return (CI x1 x2 x3 x4 x5 [] x6) instance Binary RecordInfo where put (RI x1 x2 x3) = do put x1 put x2 put x3 get = do x1 <- get x2 <- get x3 <- get return (RI x1 x2 x3) instance Binary OptInfo where put (Optimise x1 x2) = do put x1 put x2 get = do x1 <- get x2 <- get return (Optimise x1 x2) instance Binary FnInfo where put (FnInfo x1) = put x1 get = do x1 <- get return (FnInfo x1) instance Binary TypeInfo where put (TI x1 x2 x3 x4 x5) = do put x1 put x2 put x3 put x4 put x5 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (TI x1 x2 x3 x4 x5) instance Binary SynContext where put x = case x of PatternSyntax -> putWord8 0 TermSyntax -> putWord8 1 AnySyntax -> putWord8 2 get = do i <- getWord8 case i of 0 -> return PatternSyntax 1 -> return TermSyntax 2 -> return AnySyntax _ -> error "Corrupted binary data for SynContext" instance Binary Syntax where put (Rule x1 x2 x3) = do putWord8 0 put x1 put x2 put x3 put (DeclRule x1 x2) = do putWord8 1 put x1 put x2 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get return (Rule x1 x2 x3) 1 -> do x1 <- get x2 <- get return (DeclRule x1 x2) _ -> error "Corrupted binary data for Syntax" instance (Binary t) => Binary (DSL' t) where put (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9 x10) = do put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 put x9 put x10 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get x9 <- get x10 <- get return (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9 x10) instance Binary SSymbol where put x = case x of Keyword x1 -> do putWord8 0 put x1 Symbol x1 -> do putWord8 1 put x1 Expr x1 -> do putWord8 2 put x1 SimpleExpr x1 -> do putWord8 3 put x1 Binding x1 -> do putWord8 4 put x1 get = do i <- getWord8 case i of 0 -> do x1 <- get return (Keyword x1) 1 -> do x1 <- get return (Symbol x1) 2 -> do x1 <- get return (Expr x1) 3 -> do x1 <- get return (SimpleExpr x1) 4 -> do x1 <- get return (Binding x1) _ -> error "Corrupted binary data for SSymbol" instance Binary Codegen where put x = case x of Via ir str -> do putWord8 0 put ir put str Bytecode -> putWord8 1 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get return (Via x1 x2) 1 -> return Bytecode _ -> error "Corrupted binary data for Codegen" instance Binary IRFormat where put x = case x of IBCFormat -> putWord8 0 JSONFormat -> putWord8 1 get = do i <- getWord8 case i of 0 -> return IBCFormat 1 -> return JSONFormat _ -> error "Corrupted binary data for IRFormat"
tpsinnem/Idris-dev
src/Idris/IBC.hs
Haskell
bsd-3-clause
100,046
-- | Build instance tycons for the PData and PDatas type families. -- -- TODO: the PData and PDatas cases are very similar. -- We should be able to factor out the common parts. module Vectorise.Generic.PData ( buildPDataTyCon , buildPDatasTyCon ) where import Vectorise.Monad import Vectorise.Builtins import Vectorise.Generic.Description import Vectorise.Utils import Vectorise.Env( GlobalEnv( global_fam_inst_env ) ) import BuildTyCl import DataCon import TyCon import Type import FamInst import FamInstEnv import TcMType import Name import Util import MonadUtils import Control.Monad -- buildPDataTyCon ------------------------------------------------------------ -- | Build the PData instance tycon for a given type constructor. buildPDataTyCon :: TyCon -> TyCon -> SumRepr -> VM FamInst buildPDataTyCon orig_tc vect_tc repr = fixV $ \fam_inst -> do let repr_tc = dataFamInstRepTyCon fam_inst name' <- mkLocalisedName mkPDataTyConOcc orig_name rhs <- buildPDataTyConRhs orig_name vect_tc repr_tc repr pdata <- builtin pdataTyCon buildDataFamInst name' pdata vect_tc rhs where orig_name = tyConName orig_tc buildDataFamInst :: Name -> TyCon -> TyCon -> AlgTyConRhs -> VM FamInst buildDataFamInst name' fam_tc vect_tc rhs = do { axiom_name <- mkDerivedName mkInstTyCoOcc name' ; (_, tyvars') <- liftDs $ tcInstSigTyVars (getSrcSpan name') tyvars ; let ax = mkSingleCoAxiom Representational axiom_name tyvars' [] fam_tc pat_tys rep_ty tys' = mkTyVarTys tyvars' rep_ty = mkTyConApp rep_tc tys' pat_tys = [mkTyConApp vect_tc tys'] rep_tc = mkAlgTyCon name' (mkTyConBindersPreferAnon tyvars' liftedTypeKind) liftedTypeKind (map (const Nominal) tyvars') Nothing [] -- no stupid theta rhs (DataFamInstTyCon ax fam_tc pat_tys) False -- not GADT syntax ; liftDs $ newFamInst (DataFamilyInst rep_tc) ax } where tyvars = tyConTyVars vect_tc buildPDataTyConRhs :: Name -> TyCon -> TyCon -> SumRepr -> VM AlgTyConRhs buildPDataTyConRhs orig_name vect_tc repr_tc repr = do data_con <- buildPDataDataCon orig_name vect_tc repr_tc repr return $ DataTyCon { data_cons = [data_con], is_enum = False } buildPDataDataCon :: Name -> TyCon -> TyCon -> SumRepr -> VM DataCon buildPDataDataCon orig_name vect_tc repr_tc repr = do let tvs = tyConTyVars vect_tc dc_name <- mkLocalisedName mkPDataDataConOcc orig_name comp_tys <- mkSumTys repr_sel_ty mkPDataType repr fam_envs <- readGEnv global_fam_inst_env rep_nm <- liftDs $ newTyConRepName dc_name liftDs $ buildDataCon fam_envs dc_name False -- not infix rep_nm (map (const no_bang) comp_tys) (Just $ map (const HsLazy) comp_tys) [] -- no field labels (mkTyVarBinders Specified tvs) [] -- no existentials [] -- no eq spec [] -- no context comp_tys (mkFamilyTyConApp repr_tc (mkTyVarTys tvs)) repr_tc where no_bang = HsSrcBang Nothing NoSrcUnpack NoSrcStrict -- buildPDatasTyCon ----------------------------------------------------------- -- | Build the PDatas instance tycon for a given type constructor. buildPDatasTyCon :: TyCon -> TyCon -> SumRepr -> VM FamInst buildPDatasTyCon orig_tc vect_tc repr = fixV $ \fam_inst -> do let repr_tc = dataFamInstRepTyCon fam_inst name' <- mkLocalisedName mkPDatasTyConOcc orig_name rhs <- buildPDatasTyConRhs orig_name vect_tc repr_tc repr pdatas <- builtin pdatasTyCon buildDataFamInst name' pdatas vect_tc rhs where orig_name = tyConName orig_tc buildPDatasTyConRhs :: Name -> TyCon -> TyCon -> SumRepr -> VM AlgTyConRhs buildPDatasTyConRhs orig_name vect_tc repr_tc repr = do data_con <- buildPDatasDataCon orig_name vect_tc repr_tc repr return $ DataTyCon { data_cons = [data_con], is_enum = False } buildPDatasDataCon :: Name -> TyCon -> TyCon -> SumRepr -> VM DataCon buildPDatasDataCon orig_name vect_tc repr_tc repr = do let tvs = tyConTyVars vect_tc dc_name <- mkLocalisedName mkPDatasDataConOcc orig_name comp_tys <- mkSumTys repr_sels_ty mkPDatasType repr fam_envs <- readGEnv global_fam_inst_env rep_nm <- liftDs $ newTyConRepName dc_name liftDs $ buildDataCon fam_envs dc_name False -- not infix rep_nm (map (const no_bang) comp_tys) (Just $ map (const HsLazy) comp_tys) [] -- no field labels (mkTyVarBinders Specified tvs) [] -- no existentials [] -- no eq spec [] -- no context comp_tys (mkFamilyTyConApp repr_tc (mkTyVarTys tvs)) repr_tc where no_bang = HsSrcBang Nothing NoSrcUnpack NoSrcStrict -- Utils ---------------------------------------------------------------------- -- | Flatten a SumRepr into a list of data constructor types. mkSumTys :: (SumRepr -> Type) -> (Type -> VM Type) -> SumRepr -> VM [Type] mkSumTys repr_selX_ty mkTc repr = sum_tys repr where sum_tys EmptySum = return [] sum_tys (UnarySum r) = con_tys r sum_tys d@(Sum { repr_cons = cons }) = liftM (repr_selX_ty d :) (concatMapM con_tys cons) con_tys (ConRepr _ r) = prod_tys r prod_tys EmptyProd = return [] prod_tys (UnaryProd r) = liftM singleton (comp_ty r) prod_tys (Prod { repr_comps = comps }) = mapM comp_ty comps comp_ty r = mkTc (compOrigType r) {- mk_fam_inst :: TyCon -> TyCon -> (TyCon, [Type]) mk_fam_inst fam_tc arg_tc = (fam_tc, [mkTyConApp arg_tc . mkTyVarTys $ tyConTyVars arg_tc]) -}
vTurbine/ghc
compiler/vectorise/Vectorise/Generic/PData.hs
Haskell
bsd-3-clause
6,567
{-# OPTIONS -Wall -fno-warn-missing-signatures -fno-warn-name-shadowing #-} -- | Load the configuration file. module HN.Config (getConfig) where import HN.Types import Data.ConfigFile import Database.PostgreSQL.Simple (ConnectInfo(..)) import qualified Data.Text as T import Network.Mail.Mime import Github.Auth (GithubAuth(..)) import qualified Data.ByteString.Char8 as BS getConfig :: FilePath -> IO Config getConfig conf = do contents <- readFile conf let config = do c <- readstring emptyCP contents [pghost,pgport,pguser,pgpass,pgdb] <- mapM (get c "POSTGRESQL") ["host","port","user","pass","db"] [domain,cache] <- mapM (get c "WEB") ["domain","cache"] [admin,siteaddy] <- mapM (get c "ADDRESSES") ["admin","site_addy"] let gituser = BS.pack <$> getMaybe c "GITHUB" "user" gitpw = BS.pack <$> getMaybe c "GITHUB" "password" auth = GithubBasicAuth <$> gituser <*> gitpw return Config { configPostgres = ConnectInfo pghost (read pgport) pguser pgpass pgdb , configDomain = domain , configAdmin = Address Nothing (T.pack admin) , configSiteAddy = Address Nothing (T.pack siteaddy) , configCacheDir = cache , configGithubAuth = auth } case config of Left cperr -> error $ show cperr Right config -> return config getMaybe c section name = case get c section name of Left _ -> Nothing Right x -> Just x
lwm/haskellnews
src/HN/Config.hs
Haskell
bsd-3-clause
1,545
{-# LANGUAGE ForeignFunctionInterface #-} module Main where import Foreign.C.Types foreign import ccall "foo" foo :: IO CInt main :: IO () main = foo >>= print
sdiehl/ghc
testsuite/tests/ffi/should_run/T17471.hs
Haskell
bsd-3-clause
163
{-# LANGUAGE EmptyDataDecls #-} module Opaleye.SQLite.PGTypes (module Opaleye.SQLite.PGTypes) where import Opaleye.SQLite.Internal.Column (Column) import qualified Opaleye.SQLite.Internal.Column as C import qualified Opaleye.SQLite.Internal.PGTypes as IPT import qualified Opaleye.SQLite.Internal.HaskellDB.PrimQuery as HPQ import qualified Opaleye.SQLite.Internal.HaskellDB.Sql.Default as HSD (quote) import qualified Data.CaseInsensitive as CI import qualified Data.Text as SText import qualified Data.Text.Lazy as LText import qualified Data.ByteString as SByteString import qualified Data.ByteString.Lazy as LByteString import qualified Data.Time as Time import qualified Data.UUID as UUID import Data.Int (Int64) data PGBool data PGDate data PGFloat4 data PGFloat8 data PGInt8 data PGInt4 data PGInt2 data PGNumeric data PGText data PGTime data PGTimestamp data PGTimestamptz data PGUuid data PGCitext data PGArray a data PGBytea data PGJson data PGJsonb instance C.PGNum PGFloat8 where pgFromInteger = pgDouble . fromInteger instance C.PGNum PGInt4 where pgFromInteger = pgInt4 . fromInteger instance C.PGNum PGInt8 where pgFromInteger = pgInt8 . fromInteger instance C.PGFractional PGFloat8 where pgFromRational = pgDouble . fromRational literalColumn :: HPQ.Literal -> Column a literalColumn = IPT.literalColumn {-# WARNING literalColumn "'literalColumn' has been moved to Opaleye.Internal.PGTypes" #-} pgString :: String -> Column PGText pgString = IPT.literalColumn . HPQ.StringLit pgLazyByteString :: LByteString.ByteString -> Column PGBytea pgLazyByteString = IPT.literalColumn . HPQ.ByteStringLit . LByteString.toStrict pgStrictByteString :: SByteString.ByteString -> Column PGBytea pgStrictByteString = IPT.literalColumn . HPQ.ByteStringLit pgStrictText :: SText.Text -> Column PGText pgStrictText = IPT.literalColumn . HPQ.StringLit . SText.unpack pgLazyText :: LText.Text -> Column PGText pgLazyText = IPT.literalColumn . HPQ.StringLit . LText.unpack pgInt4 :: Int -> Column PGInt4 pgInt4 = IPT.literalColumn . HPQ.IntegerLit . fromIntegral pgInt8 :: Int64 -> Column PGInt8 pgInt8 = IPT.literalColumn . HPQ.IntegerLit . fromIntegral -- SQLite needs to be told that numeric literals without decimal -- points are actual REAL pgDouble :: Double -> Column PGFloat8 pgDouble = C.unsafeCast "REAL" . IPT.literalColumn . HPQ.DoubleLit pgBool :: Bool -> Column PGBool pgBool = IPT.literalColumn . HPQ.BoolLit pgUUID :: UUID.UUID -> Column PGUuid pgUUID = C.unsafeCoerceColumn . pgString . UUID.toString unsafePgFormatTime :: Time.FormatTime t => HPQ.Name -> String -> t -> Column c unsafePgFormatTime = IPT.unsafePgFormatTime {-# WARNING unsafePgFormatTime "'unsafePgFormatTime' has been moved to Opaleye.Internal.PGTypes" #-} pgDay :: Time.Day -> Column PGDate pgDay = IPT.unsafePgFormatTime "date" "'%F'" pgUTCTime :: Time.UTCTime -> Column PGTimestamptz pgUTCTime = IPT.unsafePgFormatTime "timestamptz" "'%FT%TZ'" pgLocalTime :: Time.LocalTime -> Column PGTimestamp pgLocalTime = IPT.unsafePgFormatTime "timestamp" "'%FT%T'" pgTimeOfDay :: Time.TimeOfDay -> Column PGTime pgTimeOfDay = IPT.unsafePgFormatTime "time" "'%T'" -- "We recommend not using the type time with time zone" -- http://www.postgresql.org/docs/8.3/static/datatype-datetime.html pgCiStrictText :: CI.CI SText.Text -> Column PGCitext pgCiStrictText = IPT.literalColumn . HPQ.StringLit . SText.unpack . CI.original pgCiLazyText :: CI.CI LText.Text -> Column PGCitext pgCiLazyText = IPT.literalColumn . HPQ.StringLit . LText.unpack . CI.original -- No CI String instance since postgresql-simple doesn't define FromField (CI String) -- The json data type was introduced in PostgreSQL version 9.2 -- JSON values must be SQL string quoted pgJSON :: String -> Column PGJson pgJSON = IPT.castToType "json" . HSD.quote pgStrictJSON :: SByteString.ByteString -> Column PGJson pgStrictJSON = pgJSON . IPT.strictDecodeUtf8 pgLazyJSON :: LByteString.ByteString -> Column PGJson pgLazyJSON = pgJSON . IPT.lazyDecodeUtf8 -- The jsonb data type was introduced in PostgreSQL version 9.4 -- JSONB values must be SQL string quoted -- -- TODO: We need to add literal JSON and JSONB types. pgJSONB :: String -> Column PGJsonb pgJSONB = IPT.castToType "jsonb" . HSD.quote pgStrictJSONB :: SByteString.ByteString -> Column PGJsonb pgStrictJSONB = pgJSONB . IPT.strictDecodeUtf8 pgLazyJSONB :: LByteString.ByteString -> Column PGJsonb pgLazyJSONB = pgJSONB . IPT.lazyDecodeUtf8
bergmark/haskell-opaleye
opaleye-sqlite/src/Opaleye/SQLite/PGTypes.hs
Haskell
bsd-3-clause
4,512
<?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="id-ID"> <title>Kode Dx | ZAP Perpanjangan</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Isi</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Indeks</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Mencari</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorit</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/codedx/src/main/javahelp/org/zaproxy/zap/extension/codedx/resources/help_id_ID/helpset_id_ID.hs
Haskell
apache-2.0
966
module CRC32 (crc32_tab, crc32, crc32String) where import Data.Bits import Data.Word import Data.Char -- table and sample code derived from -- http://www.opensource.apple.com/source/xnu/xnu-1456.1.26/bsd/libkern/crc32.c -- * COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or -- * code or tables extracted from it, as desired without restriction. crc32_tab :: [Word32] crc32_tab = [ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d ] crc32 :: [Word8] -> Word32 crc32 msg = go 0xffffffff msg where go crc [] = crc go crc (w:ws) = go crc' ws where crc' = (crc `shiftR` 8) `xor` (crc32_tab !! fI (fI crc `xor` w)) fI x = fromIntegral x crc32String :: String -> Word32 crc32String = crc32 . map (fromIntegral . ord)
seahug/parconc-examples
crc32/CRC32.hs
Haskell
bsd-3-clause
3,868
----------------------------------------------------------------------------- -- | -- Module : Xmobar.Commands -- Copyright : (c) Andrea Rossato -- License : BSD-style (see LICENSE) -- -- Maintainer : Jose A. Ortega Ruiz <jao@gnu.org> -- Stability : unstable -- Portability : unportable -- -- The 'Exec' class and the 'Command' data type. -- -- The 'Exec' class rappresents the executable types, whose constructors may -- appear in the 'Config.commands' field of the 'Config.Config' data type. -- -- The 'Command' data type is for OS commands to be run by xmobar -- ----------------------------------------------------------------------------- module Commands ( Command (..) , Exec (..) , tenthSeconds ) where import Prelude import Control.Concurrent import Control.Exception (handle, SomeException(..)) import Data.Char import System.Process import System.Exit import System.IO (hClose) import Signal import XUtil class Show e => Exec e where alias :: e -> String alias e = takeWhile (not . isSpace) $ show e rate :: e -> Int rate _ = 10 run :: e -> IO String run _ = return "" start :: e -> (String -> IO ()) -> IO () start e cb = go where go = run e >>= cb >> tenthSeconds (rate e) >> go trigger :: e -> (Maybe SignalType -> IO ()) -> IO () trigger _ sh = sh Nothing data Command = Com Program Args Alias Rate deriving (Show,Read,Eq) type Args = [String] type Program = String type Alias = String type Rate = Int instance Exec Command where alias (Com p _ a _) | p /= "" = if a == "" then p else a | otherwise = "" start (Com prog args _ r) cb = if r > 0 then go else exec where go = exec >> tenthSeconds r >> go exec = do (i,o,e,p) <- runInteractiveProcess prog args Nothing Nothing exit <- waitForProcess p let closeHandles = hClose o >> hClose i >> hClose e getL = handle (\(SomeException _) -> return "") (hGetLineSafe o) case exit of ExitSuccess -> do str <- getL closeHandles cb str _ -> do closeHandles cb $ "Could not execute command " ++ prog -- | Work around to the Int max bound: since threadDelay takes an Int, it -- is not possible to set a thread delay grater than about 45 minutes. -- With a little recursion we solve the problem. tenthSeconds :: Int -> IO () tenthSeconds s | s >= x = do threadDelay (x * 100000) tenthSeconds (s - x) | otherwise = threadDelay (s * 100000) where x = (maxBound :: Int) `div` 100000
dragosboca/xmobar
src/Commands.hs
Haskell
bsd-3-clause
2,869
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Foreign.C.String -- Copyright : (c) The FFI task force 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : ffi@haskell.org -- Stability : provisional -- Portability : portable -- -- Utilities for primitive marshalling of C strings. -- -- The marshalling converts each Haskell character, representing a Unicode -- code point, to one or more bytes in a manner that, by default, is -- determined by the current locale. As a consequence, no guarantees -- can be made about the relative length of a Haskell string and its -- corresponding C string, and therefore all the marshalling routines -- include memory allocation. The translation between Unicode and the -- encoding of the current locale may be lossy. -- ----------------------------------------------------------------------------- module Foreign.C.String ( -- representation of strings in C -- * C strings CString, CStringLen, -- ** Using a locale-dependent encoding -- | These functions are different from their @CAString@ counterparts -- in that they will use an encoding determined by the current locale, -- rather than always assuming ASCII. -- conversion of C strings into Haskell strings -- peekCString, peekCStringLen, -- conversion of Haskell strings into C strings -- newCString, newCStringLen, -- conversion of Haskell strings into C strings using temporary storage -- withCString, withCStringLen, charIsRepresentable, -- ** Using 8-bit characters -- | These variants of the above functions are for use with C libraries -- that are ignorant of Unicode. These functions should be used with -- care, as a loss of information can occur. castCharToCChar, castCCharToChar, castCharToCUChar, castCUCharToChar, castCharToCSChar, castCSCharToChar, peekCAString, peekCAStringLen, newCAString, newCAStringLen, withCAString, withCAStringLen, -- * C wide strings -- | These variants of the above functions are for use with C libraries -- that encode Unicode using the C @wchar_t@ type in a system-dependent -- way. The only encodings supported are -- -- * UTF-32 (the C compiler defines @__STDC_ISO_10646__@), or -- -- * UTF-16 (as used on Windows systems). CWString, CWStringLen, peekCWString, peekCWStringLen, newCWString, newCWStringLen, withCWString, withCWStringLen, ) where import Foreign.Marshal.Array import Foreign.C.Types import Foreign.Ptr import Foreign.Storable import Data.Word import Control.Monad import GHC.Char import GHC.List import GHC.Real import GHC.Num import GHC.Base import {-# SOURCE #-} GHC.IO.Encoding import qualified GHC.Foreign as GHC ----------------------------------------------------------------------------- -- Strings -- representation of strings in C -- ------------------------------ -- | A C string is a reference to an array of C characters terminated by NUL. type CString = Ptr CChar -- | A string with explicit length information in bytes instead of a -- terminating NUL (allowing NUL characters in the middle of the string). type CStringLen = (Ptr CChar, Int) -- exported functions -- ------------------ -- -- * the following routines apply the default conversion when converting the -- C-land character encoding into the Haskell-land character encoding -- | Marshal a NUL terminated C string into a Haskell string. -- peekCString :: CString -> IO String peekCString s = getForeignEncoding >>= flip GHC.peekCString s -- | Marshal a C string with explicit length into a Haskell string. -- peekCStringLen :: CStringLen -> IO String peekCStringLen s = getForeignEncoding >>= flip GHC.peekCStringLen s -- | Marshal a Haskell string into a NUL terminated C string. -- -- * the Haskell string may /not/ contain any NUL characters -- -- * new storage is allocated for the C string and must be -- explicitly freed using 'Foreign.Marshal.Alloc.free' or -- 'Foreign.Marshal.Alloc.finalizerFree'. -- newCString :: String -> IO CString newCString s = getForeignEncoding >>= flip GHC.newCString s -- | Marshal a Haskell string into a C string (ie, character array) with -- explicit length information. -- -- * new storage is allocated for the C string and must be -- explicitly freed using 'Foreign.Marshal.Alloc.free' or -- 'Foreign.Marshal.Alloc.finalizerFree'. -- newCStringLen :: String -> IO CStringLen newCStringLen s = getForeignEncoding >>= flip GHC.newCStringLen s -- | Marshal a Haskell string into a NUL terminated C string using temporary -- storage. -- -- * the Haskell string may /not/ contain any NUL characters -- -- * the memory is freed when the subcomputation terminates (either -- normally or via an exception), so the pointer to the temporary -- storage must /not/ be used after this. -- withCString :: String -> (CString -> IO a) -> IO a withCString s f = getForeignEncoding >>= \enc -> GHC.withCString enc s f -- | Marshal a Haskell string into a C string (ie, character array) -- in temporary storage, with explicit length information. -- -- * the memory is freed when the subcomputation terminates (either -- normally or via an exception), so the pointer to the temporary -- storage must /not/ be used after this. -- withCStringLen :: String -> (CStringLen -> IO a) -> IO a withCStringLen s f = getForeignEncoding >>= \enc -> GHC.withCStringLen enc s f -- -- | Determines whether a character can be accurately encoded in a 'CString'. -- -- Unrepresentable characters are converted to '?' or their nearest visual equivalent. charIsRepresentable :: Char -> IO Bool charIsRepresentable c = getForeignEncoding >>= flip GHC.charIsRepresentable c -- single byte characters -- ---------------------- -- -- ** NOTE: These routines don't handle conversions! ** -- | Convert a C byte, representing a Latin-1 character, to the corresponding -- Haskell character. castCCharToChar :: CChar -> Char castCCharToChar ch = unsafeChr (fromIntegral (fromIntegral ch :: Word8)) -- | Convert a Haskell character to a C character. -- This function is only safe on the first 256 characters. castCharToCChar :: Char -> CChar castCharToCChar ch = fromIntegral (ord ch) -- | Convert a C @unsigned char@, representing a Latin-1 character, to -- the corresponding Haskell character. castCUCharToChar :: CUChar -> Char castCUCharToChar ch = unsafeChr (fromIntegral (fromIntegral ch :: Word8)) -- | Convert a Haskell character to a C @unsigned char@. -- This function is only safe on the first 256 characters. castCharToCUChar :: Char -> CUChar castCharToCUChar ch = fromIntegral (ord ch) -- | Convert a C @signed char@, representing a Latin-1 character, to the -- corresponding Haskell character. castCSCharToChar :: CSChar -> Char castCSCharToChar ch = unsafeChr (fromIntegral (fromIntegral ch :: Word8)) -- | Convert a Haskell character to a C @signed char@. -- This function is only safe on the first 256 characters. castCharToCSChar :: Char -> CSChar castCharToCSChar ch = fromIntegral (ord ch) -- | Marshal a NUL terminated C string into a Haskell string. -- peekCAString :: CString -> IO String peekCAString cp = do l <- lengthArray0 nUL cp if l <= 0 then return "" else loop "" (l-1) where loop s i = do xval <- peekElemOff cp i let val = castCCharToChar xval val `seq` if i <= 0 then return (val:s) else loop (val:s) (i-1) -- | Marshal a C string with explicit length into a Haskell string. -- peekCAStringLen :: CStringLen -> IO String peekCAStringLen (cp, len) | len <= 0 = return "" -- being (too?) nice. | otherwise = loop [] (len-1) where loop acc i = do xval <- peekElemOff cp i let val = castCCharToChar xval -- blow away the coercion ASAP. if (val `seq` (i == 0)) then return (val:acc) else loop (val:acc) (i-1) -- | Marshal a Haskell string into a NUL terminated C string. -- -- * the Haskell string may /not/ contain any NUL characters -- -- * new storage is allocated for the C string and must be -- explicitly freed using 'Foreign.Marshal.Alloc.free' or -- 'Foreign.Marshal.Alloc.finalizerFree'. -- newCAString :: String -> IO CString newCAString str = do ptr <- mallocArray0 (length str) let go [] n = pokeElemOff ptr n nUL go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1) go str 0 return ptr -- | Marshal a Haskell string into a C string (ie, character array) with -- explicit length information. -- -- * new storage is allocated for the C string and must be -- explicitly freed using 'Foreign.Marshal.Alloc.free' or -- 'Foreign.Marshal.Alloc.finalizerFree'. -- newCAStringLen :: String -> IO CStringLen newCAStringLen str = do ptr <- mallocArray0 len let go [] n = n `seq` return () -- make it strict in n go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1) go str 0 return (ptr, len) where len = length str -- | Marshal a Haskell string into a NUL terminated C string using temporary -- storage. -- -- * the Haskell string may /not/ contain any NUL characters -- -- * the memory is freed when the subcomputation terminates (either -- normally or via an exception), so the pointer to the temporary -- storage must /not/ be used after this. -- withCAString :: String -> (CString -> IO a) -> IO a withCAString str f = allocaArray0 (length str) $ \ptr -> let go [] n = pokeElemOff ptr n nUL go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1) in do go str 0 f ptr -- | Marshal a Haskell string into a C string (ie, character array) -- in temporary storage, with explicit length information. -- -- * the memory is freed when the subcomputation terminates (either -- normally or via an exception), so the pointer to the temporary -- storage must /not/ be used after this. -- withCAStringLen :: String -> (CStringLen -> IO a) -> IO a withCAStringLen str f = allocaArray len $ \ptr -> let go [] n = n `seq` return () -- make it strict in n go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1) in do go str 0 f (ptr,len) where len = length str -- auxiliary definitions -- ---------------------- -- C's end of string character -- nUL :: CChar nUL = 0 -- allocate an array to hold the list and pair it with the number of elements newArrayLen :: Storable a => [a] -> IO (Ptr a, Int) newArrayLen xs = do a <- newArray xs return (a, length xs) ----------------------------------------------------------------------------- -- Wide strings -- representation of wide strings in C -- ----------------------------------- -- | A C wide string is a reference to an array of C wide characters -- terminated by NUL. type CWString = Ptr CWchar -- | A wide character string with explicit length information in 'CWchar's -- instead of a terminating NUL (allowing NUL characters in the middle -- of the string). type CWStringLen = (Ptr CWchar, Int) -- | Marshal a NUL terminated C wide string into a Haskell string. -- peekCWString :: CWString -> IO String peekCWString cp = do cs <- peekArray0 wNUL cp return (cWcharsToChars cs) -- | Marshal a C wide string with explicit length into a Haskell string. -- peekCWStringLen :: CWStringLen -> IO String peekCWStringLen (cp, len) = do cs <- peekArray len cp return (cWcharsToChars cs) -- | Marshal a Haskell string into a NUL terminated C wide string. -- -- * the Haskell string may /not/ contain any NUL characters -- -- * new storage is allocated for the C wide string and must -- be explicitly freed using 'Foreign.Marshal.Alloc.free' or -- 'Foreign.Marshal.Alloc.finalizerFree'. -- newCWString :: String -> IO CWString newCWString = newArray0 wNUL . charsToCWchars -- | Marshal a Haskell string into a C wide string (ie, wide character array) -- with explicit length information. -- -- * new storage is allocated for the C wide string and must -- be explicitly freed using 'Foreign.Marshal.Alloc.free' or -- 'Foreign.Marshal.Alloc.finalizerFree'. -- newCWStringLen :: String -> IO CWStringLen newCWStringLen str = newArrayLen (charsToCWchars str) -- | Marshal a Haskell string into a NUL terminated C wide string using -- temporary storage. -- -- * the Haskell string may /not/ contain any NUL characters -- -- * the memory is freed when the subcomputation terminates (either -- normally or via an exception), so the pointer to the temporary -- storage must /not/ be used after this. -- withCWString :: String -> (CWString -> IO a) -> IO a withCWString = withArray0 wNUL . charsToCWchars -- | Marshal a Haskell string into a C wide string (i.e. wide -- character array) in temporary storage, with explicit length -- information. -- -- * the memory is freed when the subcomputation terminates (either -- normally or via an exception), so the pointer to the temporary -- storage must /not/ be used after this. -- withCWStringLen :: String -> (CWStringLen -> IO a) -> IO a withCWStringLen str f = withArrayLen (charsToCWchars str) $ \ len ptr -> f (ptr, len) -- auxiliary definitions -- ---------------------- wNUL :: CWchar wNUL = 0 cWcharsToChars :: [CWchar] -> [Char] charsToCWchars :: [Char] -> [CWchar] #ifdef mingw32_HOST_OS -- On Windows, wchar_t is 16 bits wide and CWString uses the UTF-16 encoding. -- coding errors generate Chars in the surrogate range cWcharsToChars = map chr . fromUTF16 . map fromIntegral where fromUTF16 (c1:c2:wcs) | 0xd800 <= c1 && c1 <= 0xdbff && 0xdc00 <= c2 && c2 <= 0xdfff = ((c1 - 0xd800)*0x400 + (c2 - 0xdc00) + 0x10000) : fromUTF16 wcs fromUTF16 (c:wcs) = c : fromUTF16 wcs fromUTF16 [] = [] charsToCWchars = foldr utf16Char [] . map ord where utf16Char c wcs | c < 0x10000 = fromIntegral c : wcs | otherwise = let c' = c - 0x10000 in fromIntegral (c' `div` 0x400 + 0xd800) : fromIntegral (c' `mod` 0x400 + 0xdc00) : wcs #else /* !mingw32_HOST_OS */ cWcharsToChars xs = map castCWcharToChar xs charsToCWchars xs = map castCharToCWchar xs -- These conversions only make sense if __STDC_ISO_10646__ is defined -- (meaning that wchar_t is ISO 10646, aka Unicode) castCWcharToChar :: CWchar -> Char castCWcharToChar ch = chr (fromIntegral ch ) castCharToCWchar :: Char -> CWchar castCharToCWchar ch = fromIntegral (ord ch) #endif /* !mingw32_HOST_OS */
ryantm/ghc
libraries/base/Foreign/C/String.hs
Haskell
bsd-3-clause
14,693
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -- | Tag a Binary instance with the stack version number to ensure we're -- reading a compatible format. module Data.Binary.VersionTagged ( taggedDecodeOrLoad , taggedEncodeFile , Binary (..) , BinarySchema (..) , decodeFileOrFailDeep , encodeFile , NFData (..) , genericRnf ) where import Control.DeepSeq.Generics (NFData (..), genericRnf) import Control.Exception (Exception) import Control.Monad.Catch (MonadThrow (..)) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Binary (Binary (..), encodeFile, decodeFileOrFail, putWord8, getWord8) import Data.Binary.Get (ByteOffset) import Data.Typeable (Typeable) import Control.Exception.Enclosed (tryAnyDeep) import System.FilePath (takeDirectory) import System.Directory (createDirectoryIfMissing) import qualified Data.ByteString as S import Data.ByteString (ByteString) import Control.Monad (forM_, when) import Data.Proxy magic :: ByteString magic = "stack" -- | A @Binary@ instance that also has a schema version class (Binary a, NFData a) => BinarySchema a where binarySchema :: Proxy a -> Int newtype WithTag a = WithTag a deriving NFData instance forall a. BinarySchema a => Binary (WithTag a) where get = do forM_ (S.unpack magic) $ \w -> do w' <- getWord8 when (w /= w') $ fail "Mismatched magic string, forcing a recompute" tag' <- get if binarySchema (Proxy :: Proxy a) == tag' then fmap WithTag get else fail "Mismatched tags, forcing a recompute" put (WithTag x) = do mapM_ putWord8 $ S.unpack magic put (binarySchema (Proxy :: Proxy a)) put x -- | Write to the given file, with a version tag. taggedEncodeFile :: (BinarySchema a, MonadIO m) => FilePath -> a -> m () taggedEncodeFile fp x = liftIO $ do createDirectoryIfMissing True $ takeDirectory fp encodeFile fp $ WithTag x -- | Read from the given file. If the read fails, run the given action and -- write that back to the file. Always starts the file off with the version -- tag. taggedDecodeOrLoad :: (BinarySchema a, MonadIO m) => FilePath -> m a -> m a taggedDecodeOrLoad fp mx = do eres <- decodeFileOrFailDeep fp case eres of Left _ -> do x <- mx taggedEncodeFile fp x return x Right (WithTag x) -> return x -- | Ensure that there are no lurking exceptions deep inside the parsed -- value... because that happens unfortunately. See -- https://github.com/commercialhaskell/stack/issues/554 decodeFileOrFailDeep :: (Binary a, NFData a, MonadIO m, MonadThrow n) => FilePath -> m (n a) decodeFileOrFailDeep fp = liftIO $ fmap (either throwM return) $ tryAnyDeep $ do eres <- decodeFileOrFail fp case eres of Left (offset, str) -> throwM $ DecodeFileFailure fp offset str Right x -> return x data DecodeFileFailure = DecodeFileFailure FilePath ByteOffset String deriving Typeable instance Show DecodeFileFailure where show (DecodeFileFailure fp offset str) = concat [ "Decoding of " , fp , " failed at offset " , show offset , ": " , str ] instance Exception DecodeFileFailure
Denommus/stack
src/Data/Binary/VersionTagged.hs
Haskell
bsd-3-clause
3,538
{-# OPTIONS_GHC -fplugin LinkerTicklingPlugin #-} module Main where main :: IO () main = return ()
siddhanathan/ghc
testsuite/tests/plugins/plugins06.hs
Haskell
bsd-3-clause
101
{-# LANGUAGE FlexibleContexts #-} module XmlParse where import qualified Data.Char as Char import Data.Conduit.Attoparsec import Data.Text (Text) import qualified Data.Text as Text import qualified Data.XML.Types as XML import Text.Megaparsec import Text.Megaparsec.Prim import Text.Megaparsec.Pos import XmlEvents import qualified XmlTree as Tree getEventLocation :: Event -> Location getEventLocation (EventBeginElement _ _ r) = r getEventLocation (EventEndElement _ r) = r getEventLocation (EventContent _ r) = r getEventLocation (EventCDATA _ r) = r updatePosEvent :: Int -> SourcePos -> Event -> SourcePos updatePosEvent _ p e = buildPos src startPos where (Location src pos) = getEventLocation e startPos = posRangeStart pos buildPos n (Position l c) = flip setSourceName n . flip setSourceColumn c . flip setSourceLine l $ p tryHandle :: MonadParsec s m Event => (Event -> Either [Message] a) -> m a tryHandle f = token updatePosEvent f singleUnexpected :: String -> Either [Message] a singleUnexpected = Left . pure . Unexpected parseBegin :: Event -> Either [Message] (XML.Name, [(XML.Name, [XML.Content])], Location) parseBegin (EventBeginElement n a p) = Right (n, a, p) parseBegin e = singleUnexpected . show $ e parseEnd :: XML.Name -> Event -> Either [Message] Location parseEnd n1 (EventEndElement n2 p) | n1 == n2 = Right p parseEnd n e = singleUnexpected $ "Expected end element " ++ show n ++ " but found " ++ show e eventToTextContent :: Event -> Either [Message] Tree.Content eventToTextContent (EventContent (XML.ContentText t) p) = Right (Tree.Content (Tree.ContentText t) p) eventToTextContent (EventCDATA t p) = Right (Tree.Content (Tree.ContentText t) p) eventToTextContent e = singleUnexpected . show $ e eventToEntityContent :: Event -> Either [Message] Tree.Content eventToEntityContent (EventContent (XML.ContentEntity t) p) = Right (Tree.Content (Tree.ContentEntity t) p) eventToEntityContent e = singleUnexpected . show $ e mergePositionRange :: PositionRange -> PositionRange -> PositionRange mergePositionRange (PositionRange p1 p2) (PositionRange p3 p4) = PositionRange (minimum positions) (maximum positions) where positions = [p1, p2, p3, p4] mergeLocation :: Location -> Location -> Location mergeLocation (Location src1 p1) (Location _ p2) = Location src1 (mergePositionRange p1 p2) getTextContentOrEmpty :: Tree.Content -> Text getTextContentOrEmpty (Tree.Content (Tree.ContentText t) _) = t getTextContentOrEmpty _ = Text.empty concatContent :: MonadParsec s m Event => m Tree.Content concatContent = do contents <- some (tryHandle eventToTextContent) case contents of [] -> fail "Empty content list" (x : xs) -> let text = Text.concat . fmap getTextContentOrEmpty $ contents in if Text.null text then fail "Empty content" else return $ Tree.Content (Tree.ContentText text) (foldr mergeLocation (Tree.location x) (Tree.location <$> xs)) elementOrContentParser :: MonadParsec s m Event => m (Either Tree.Element Tree.Content) elementOrContentParser = (Left <$> elementParser) <|> (Right <$> concatContent) <|> (Right <$> (tryHandle eventToEntityContent)) elementParser :: MonadParsec s m Event => m Tree.Element elementParser = do (name, attr, beginPos) <- tryHandle parseBegin children <- many elementOrContentParser endPos <- tryHandle (parseEnd name) return $ Tree.Element name attr beginPos endPos children whitespaceContent :: MonadParsec s m Event => m () whitespaceContent = tryHandle whitespaceEvent where whitespaceEvent (EventContent (XML.ContentText t) _) | Text.all Char.isSpace t = Right () whitespaceEvent e = singleUnexpected . show $ e rootParser :: MonadParsec s m Event => m Tree.Element rootParser = do _ <- many whitespaceContent elementParser parseElementEvents :: [Event] -> Either [String] Tree.Element parseElementEvents events = do case runParser rootParser "" events of Left e -> Left (messageString <$> errorMessages e) Right x -> Right x
scott-fleischman/haskell-xml-infer
src/XmlParse.hs
Haskell
mit
4,024
module Main where import qualified ExpressionProblem1a as EP1a import qualified ExpressionProblem1b as EP1b import qualified ExpressionProblem2a as EP2a import qualified ExpressionProblem2b as EP2b import qualified ExpressionProblem3a as EP3a import qualified ExpressionProblem3b as EP3b -- References -- http://c2.com/cgi/wiki?ExpressionProblem -- http://koerbitz.me/posts/Solving-the-Expression-Problem-in-Haskell-and-Java.html -- http://koerbitz.me/posts/Sum-Types-Visitors-and-the-Expression-Problem.html -- https://www.staff.science.uu.nl/~swier004/Publications/DataTypesALaCarte.pdf -- https://oleksandrmanzyuk.wordpress.com/2014/06/18/from-object-algebras-to-finally-tagless-interpreters-2/ -- https://www.andres-loeh.de/OpenDatatypes.pdf -- http://wadler.blogspot.com/2008/02/data-types-la-carte.html -- Expression problem (1) -- Using single ADT -- -- Can add new functions: just create a new function, e.g. "perimeter" -- -- Can't add new shapes: "Shape" ADT and existing functions are closed expressionProblem1 :: IO () expressionProblem1 = do putStrLn "ExpressionProblem1" let shapes = [EP1a.Square 10.0, EP1a.Circle 10.0] print $ map EP1a.area shapes print $ map EP1b.perimeter shapes -- Expression problem (2) -- Using type classes and separate ADT for each shape -- -- Straightforward to add new functions: declare a new type class and -- implement an instance for each shape -- -- Straightforward to add new shapes: declare a new ADT and implement existing -- type classes -- -- Problem: Heterogeneous lists of shapes not possible expressionProblem2 :: IO () expressionProblem2 = do putStrLn "ExpressionProblem2" let squares = [EP2a.Square 10.0, EP2a.Square 20.0] circles = [EP2a.Circle 10.0, EP2a.Circle 20.0] rectangles = [EP2b.Rectangle 10.0 20.0, EP2b.Rectangle 20.0 30.0] print $ map EP2a.area squares print $ map EP2b.perimeter squares print $ map EP2a.area circles print $ map EP2b.perimeter circles print $ map EP2a.area rectangles print $ map EP2b.perimeter rectangles -- Expression problem (2) -- Use existential quantification to solve the previous problem expressionProblem3 :: IO () expressionProblem3 = do putStrLn "ExpressionProblem3" let shapes = [ EP3b.Shape $ EP3a.Square 10.0, EP3b.Shape $ EP3a.Circle 10.0, EP3b.Shape $ EP3b.Rectangle 10.0 20.0 ] print $ map EP3a.area shapes print $ map EP3b.perimeter shapes main :: IO () main = expressionProblem1 >> expressionProblem2 >> expressionProblem3
rcook/expression-problem
src/Main.hs
Haskell
mit
2,520
import Data.List (sortBy) import Data.Ord (comparing) collatz :: Integer -> [Integer] collatz n | n == 1 = [1] | n `mod` 2 == 0 = n : collatz (n `div` 2) | otherwise = n : collatz (3 * n + 1) collatzSequences :: Integer -> [[Integer]] collatzSequences n = map collatz [1..n] collatzSequenceLengths :: Integer -> [(Integer, Int)] collatzSequenceLengths n = zip [1..n] (map length (collatzSequences n)) solution = last $ sortBy (comparing snd ) $ collatzSequenceLengths 999999 --solution = maximumBy . comparing . snd $ collatzSequenceLengths 999999
DylanSp/Project-Euler-in-Haskell
prob14/solution.hs
Haskell
mit
611
module Rubik.Tables.Distances where import Rubik.Cube import Rubik.Solver import Rubik.Tables.Internal import Rubik.Tables.Moves import qualified Data.Vector.Storable.Allocated as S import qualified Data.Vector.HalfByte as HB d_CornerOrien_UDSlice = distanceTable2 "dist_CornerOrien_UDSlice" move18CornerOrien move18UDSlice d_EdgeOrien_UDSlice = distanceTable2 "dist_EdgeOrien_UDSlice" move18EdgeOrien move18UDSlice d_UDEdgePermu2_UDSlicePermu2 = distanceTable2 "dist_EdgePermu2" move10UDEdgePermu2 move10UDSlicePermu2 d_CornerPermu_UDSlicePermu2 = distanceTable2 "dist_CornerPermu_UDSlicePermu2" move10CornerPermu move10UDSlicePermu2 dSym_CornerOrien_FlipUDSlicePermu = saved' "dist_SymFlipUDSlicePermu_CornerOrien" $ distanceWithSym2' move18SymFlipUDSlicePermu move18CornerOrien invertedSym16CornerOrien symProjFlipUDSlicePermu rawProjection n1 n2 :: HB.Vector' where n1 = 1523864 n2 = range ([] :: [CornerOrien]) dSym_CornerOrien_CornerPermu = saved' "dist_SymCornerPermu_CornerOrien" $ distanceWithSym2' move18SymCornerPermu move18CornerOrien invertedSym16CornerOrien symProjCornerPermu rawProjection n1 n2 :: S.Vector DInt where n1 = 2768 n2 = range ([] :: [CornerOrien])
Lysxia/twentyseven
src/Rubik/Tables/Distances.hs
Haskell
mit
1,328
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ConstraintKinds #-} -- | Warning: This module should be considered highly experimental. module Data.Sequences where import Data.Maybe (fromJust, isJust) import Data.Monoid (Monoid, mconcat, mempty) import Data.MonoTraversable import Data.Int (Int64, Int) import qualified Data.List as List import qualified Control.Monad (filterM, replicateM) import Prelude (Bool (..), Monad (..), Maybe (..), Ordering (..), Ord (..), Eq (..), Functor (..), fromIntegral, otherwise, (-), fst, snd, Integral, ($), flip, maybe, error) import Data.Char (Char, isSpace) import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import qualified Data.Text as T import qualified Data.Text.Lazy as TL import Control.Category import Control.Arrow ((***), first, second) import Control.Monad (liftM) import qualified Data.Sequence as Seq import qualified Data.DList as DList import qualified Data.Vector as V import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Storable as VS import Data.String (IsString) import qualified Data.List.NonEmpty as NE import qualified Data.ByteString.Unsafe as SU import Data.GrowingAppend import Data.Vector.Instances () import qualified Data.Vector.Generic as VG import qualified Data.Vector.Algorithms.Merge as VAM import Data.Ord (comparing) -- | 'SemiSequence' was created to share code between 'IsSequence' and 'MinLen'. -- -- @Semi@ means 'SemiGroup' -- A 'SemiSequence' can accomodate a 'SemiGroup' such as 'NonEmpty' or 'MinLen' -- A Monoid should be able to fill out 'IsSequence'. -- -- 'SemiSequence' operations maintain the same type because they all maintain the same number of elements or increase them. -- However, a decreasing function such as filter may change they type. -- For example, from 'NonEmpty' to '[]' -- This type-changing function exists on 'NonNull' as 'nfilter' -- -- 'filter' and other such functions are placed in 'IsSequence' class (Integral (Index seq), GrowingAppend seq) => SemiSequence seq where -- | The type of the index of a sequence. type Index seq -- | 'intersperse' takes an element and intersperses that element between -- the elements of the sequence. -- -- @ -- > 'intersperse' ',' "abcde" -- "a,b,c,d,e" -- @ intersperse :: Element seq -> seq -> seq -- FIXME split :: (Element seq -> Bool) -> seq -> [seq] -- | Reverse a sequence -- -- @ -- > 'reverse' "hello world" -- "dlrow olleh" -- @ reverse :: seq -> seq -- | 'find' takes a predicate and a sequence and returns the first element in -- the sequence matching the predicate, or 'Nothing' if there isn't an element -- that matches the predicate. -- -- @ -- > 'find' (== 5) [1 .. 10] -- 'Just' 5 -- -- > 'find' (== 15) [1 .. 10] -- 'Nothing' -- @ find :: (Element seq -> Bool) -> seq -> Maybe (Element seq) -- | Sort a sequence using an supplied element ordering function. -- -- @ -- > let compare' x y = case 'compare' x y of LT -> GT; EQ -> EQ; GT -> LT -- > 'sortBy' compare' [5,3,6,1,2,4] -- [6,5,4,3,2,1] -- @ sortBy :: (Element seq -> Element seq -> Ordering) -> seq -> seq -- | Prepend an element onto a sequence. -- -- @ -- > 4 \``cons`` [1,2,3] -- [4,1,2,3] -- @ cons :: Element seq -> seq -> seq -- | Append an element onto a sequence. -- -- @ -- > [1,2,3] \``snoc`` 4 -- [1,2,3,4] -- @ snoc :: seq -> Element seq -> seq -- | Create a sequence from a single element. -- -- @ -- > 'singleton' 'a' :: 'String' -- "a" -- > 'singleton' 'a' :: 'Vector' 'Char' -- 'Data.Vector.fromList' "a" -- @ singleton :: IsSequence seq => Element seq -> seq singleton = opoint {-# INLINE singleton #-} -- | Sequence Laws: -- -- @ -- 'fromList' . 'otoList' = 'id' -- 'fromList' (x <> y) = 'fromList' x <> 'fromList' y -- 'otoList' ('fromList' x <> 'fromList' y) = x <> y -- @ class (Monoid seq, MonoTraversable seq, SemiSequence seq, MonoPointed seq) => IsSequence seq where -- | Convert a list to a sequence. -- -- @ -- > 'fromList' ['a', 'b', 'c'] :: Text -- "abc" -- @ fromList :: [Element seq] -> seq -- this definition creates the Monoid constraint -- However, all the instances define their own fromList fromList = mconcat . fmap singleton -- below functions change type fron the perspective of NonEmpty -- | 'break' applies a predicate to a sequence, and returns a tuple where -- the first element is the longest prefix (possibly empty) of elements that -- /do not satisfy/ the predicate. The second element of the tuple is the -- remainder of the sequence. -- -- @'break' p@ is equivalent to @'span' ('not' . p)@ -- -- @ -- > 'break' (> 3) ('fromList' [1,2,3,4,1,2,3,4] :: 'Vector' 'Int') -- (fromList [1,2,3],fromList [4,1,2,3,4]) -- -- > 'break' (< 'z') ('fromList' "abc" :: 'Text') -- ("","abc") -- -- > 'break' (> 'z') ('fromList' "abc" :: 'Text') -- ("abc","") -- @ break :: (Element seq -> Bool) -> seq -> (seq, seq) break f = (fromList *** fromList) . List.break f . otoList -- | 'span' applies a predicate to a sequence, and returns a tuple where -- the first element is the longest prefix (possibly empty) that -- /does satisfy/ the predicate. The second element of the tuple is the -- remainder of the sequence. -- -- @'span' p xs@ is equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@ -- -- @ -- > 'span' (< 3) ('fromList' [1,2,3,4,1,2,3,4] :: 'Vector' 'Int') -- (fromList [1,2],fromList [3,4,1,2,3,4]) -- -- > 'span' (< 'z') ('fromList' "abc" :: 'Text') -- ("abc","") -- -- > 'span' (< 0) [1,2,3] -- ([],[1,2,3]) -- @ span :: (Element seq -> Bool) -> seq -> (seq, seq) span f = (fromList *** fromList) . List.span f . otoList -- | 'dropWhile' returns the suffix remaining after 'takeWhile'. -- -- @ -- > 'dropWhile' (< 3) [1,2,3,4,5,1,2,3] -- [3,4,5,1,2,3] -- -- > 'dropWhile' (< 'z') ('fromList' "abc" :: 'Text') -- "" -- @ dropWhile :: (Element seq -> Bool) -> seq -> seq dropWhile f = fromList . List.dropWhile f . otoList -- | 'takeWhile' applies a predicate to a sequence, and returns the -- longest prefix (possibly empty) of the sequence of elements that -- /satisfy/ the predicate. -- -- @ -- > 'takeWhile' (< 3) [1,2,3,4,5,1,2,3] -- [1,2] -- -- > 'takeWhile' (< 'z') ('fromList' "abc" :: 'Text') -- "abc" -- @ takeWhile :: (Element seq -> Bool) -> seq -> seq takeWhile f = fromList . List.takeWhile f . otoList -- | @'splitAt' n se@ returns a tuple where the first element is the prefix of -- the sequence @se@ with length @n@, and the second element is the remainder of -- the sequence. -- -- @ -- > 'splitAt' 6 "Hello world!" -- ("Hello ","world!") -- -- > 'splitAt' 3 ('fromList' [1,2,3,4,5] :: 'Vector' 'Int') -- (fromList [1,2,3],fromList [4,5]) -- @ splitAt :: Index seq -> seq -> (seq, seq) splitAt i = (fromList *** fromList) . List.genericSplitAt i . otoList -- | Equivalent to 'splitAt'. unsafeSplitAt :: Index seq -> seq -> (seq, seq) unsafeSplitAt i seq = (unsafeTake i seq, unsafeDrop i seq) -- | @'take' n@ returns the prefix of a sequence of length @n@, or the -- sequence itself if @n > 'olength' seq@. -- -- @ -- > 'take' 3 "abcdefg" -- "abc" -- > 'take' 4 ('fromList' [1,2,3,4,5,6] :: 'Vector' 'Int') -- fromList [1,2,3,4] -- @ take :: Index seq -> seq -> seq take i = fst . splitAt i -- | Equivalent to 'take'. unsafeTake :: Index seq -> seq -> seq unsafeTake = take -- | @'drop' n@ returns the suffix of a sequence after the first @n@ -- elements, or an empty sequence if @n > 'olength' seq@. -- -- @ -- > 'drop' 3 "abcdefg" -- "defg" -- > 'drop' 4 ('fromList' [1,2,3,4,5,6] :: 'Vector' 'Int') -- fromList [5,6] -- @ drop :: Index seq -> seq -> seq drop i = snd . splitAt i -- | Equivalent to 'drop' unsafeDrop :: Index seq -> seq -> seq unsafeDrop = drop -- | 'partition' takes a predicate and a sequence and returns the pair of -- sequences of elements which do and do not satisfy the predicate. -- -- @ -- 'partition' p se = ('filter' p se, 'filter' ('not' . p) se) -- @ partition :: (Element seq -> Bool) -> seq -> (seq, seq) partition f = (fromList *** fromList) . List.partition f . otoList -- | 'uncons' returns the tuple of the first element of a sequence and the rest -- of the sequence, or 'Nothing' if the sequence is empty. -- -- @ -- > 'uncons' ('fromList' [1,2,3,4] :: 'Vector' 'Int') -- 'Just' (1,fromList [2,3,4]) -- -- > 'uncons' ([] :: ['Int']) -- 'Nothing' -- @ uncons :: seq -> Maybe (Element seq, seq) uncons = fmap (second fromList) . uncons . otoList -- | 'unsnoc' returns the tuple of the init of a sequence and the last element, -- or 'Nothing' if the sequence is empty. -- -- @ -- > 'uncons' ('fromList' [1,2,3,4] :: 'Vector' 'Int') -- 'Just' (fromList [1,2,3],4) -- -- > 'uncons' ([] :: ['Int']) -- 'Nothing' -- @ unsnoc :: seq -> Maybe (seq, Element seq) unsnoc = fmap (first fromList) . unsnoc . otoList -- | 'filter' given a predicate returns a sequence of all elements that satisfy -- the predicate. -- -- @ -- > 'filter' (< 5) [1 .. 10] -- [1,2,3,4] -- @ filter :: (Element seq -> Bool) -> seq -> seq filter f = fromList . List.filter f . otoList -- | The monadic version of 'filter'. filterM :: Monad m => (Element seq -> m Bool) -> seq -> m seq filterM f = liftM fromList . filterM f . otoList -- replicates are not in SemiSequence to allow for zero -- | @'replicate' n x@ is a sequence of length @n@ with @x@ as the -- value of every element. -- -- @ -- > 'replicate' 10 'a' :: Text -- "aaaaaaaaaa" -- @ replicate :: Index seq -> Element seq -> seq replicate i = fromList . List.genericReplicate i -- | The monadic version of 'replicateM'. replicateM :: Monad m => Index seq -> m (Element seq) -> m seq replicateM i = liftM fromList . Control.Monad.replicateM (fromIntegral i) -- below functions are not in SemiSequence because they return a List (instead of NonEmpty) -- | 'group' takes a sequence and returns a list of sequences such that the -- concatenation of the result is equal to the argument. Each subsequence in -- the result contains only equal elements, using the supplied equality test. -- -- @ -- > 'groupBy' (==) "Mississippi" -- ["M","i","ss","i","ss","i","pp","i"] -- @ groupBy :: (Element seq -> Element seq -> Bool) -> seq -> [seq] groupBy f = fmap fromList . List.groupBy f . otoList -- | Similar to standard 'groupBy', but operates on the whole collection, -- not just the consecutive items. groupAllOn :: Eq b => (Element seq -> b) -> seq -> [seq] groupAllOn f = fmap fromList . groupAllOn f . otoList -- | 'subsequences' returns a list of all subsequences of the argument. -- -- @ -- > 'subsequences' "abc" -- ["","a","b","ab","c","ac","bc","abc"] -- @ subsequences :: seq -> [seq] subsequences = List.map fromList . List.subsequences . otoList -- | 'permutations' returns a list of all permutations of the argument. -- -- @ -- > 'permutations' "abc" -- ["abc","bac","cba","bca","cab","acb"] -- @ permutations :: seq -> [seq] permutations = List.map fromList . List.permutations . otoList -- | __Unsafe__ -- -- Get the tail of a sequence, throw an exception if the sequence is empty. -- -- @ -- > 'tailEx' [1,2,3] -- [2,3] -- @ tailEx :: seq -> seq tailEx = snd . maybe (error "Data.Sequences.tailEx") id . uncons -- | __Unsafe__ -- -- Get the init of a sequence, throw an exception if the sequence is empty. -- -- @ -- > 'initEx' [1,2,3] -- [1,2] -- @ initEx :: seq -> seq initEx = fst . maybe (error "Data.Sequences.initEx") id . unsnoc -- | Equivalent to 'tailEx'. unsafeTail :: seq -> seq unsafeTail = tailEx -- | Equivalent to 'initEx'. unsafeInit :: seq -> seq unsafeInit = initEx -- | Get the element of a sequence at a certain index, returns 'Nothing' -- if that index does not exist. -- -- @ -- > 'index' ('fromList' [1,2,3] :: 'Vector' 'Int') 1 -- 'Just' 2 -- > 'index' ('fromList' [1,2,3] :: 'Vector' 'Int') 4 -- 'Nothing' -- @ index :: seq -> Index seq -> Maybe (Element seq) index seq' idx = headMay (drop idx seq') -- | __Unsafe__ -- -- Get the element of a sequence at a certain index, throws an exception -- if the index does not exist. indexEx :: seq -> Index seq -> Element seq indexEx seq' idx = maybe (error "Data.Sequences.indexEx") id (index seq' idx) -- | Equivalent to 'indexEx'. unsafeIndex :: seq -> Index seq -> Element seq unsafeIndex = indexEx {-# INLINE fromList #-} {-# INLINE break #-} {-# INLINE span #-} {-# INLINE dropWhile #-} {-# INLINE takeWhile #-} {-# INLINE splitAt #-} {-# INLINE unsafeSplitAt #-} {-# INLINE take #-} {-# INLINE unsafeTake #-} {-# INLINE drop #-} {-# INLINE unsafeDrop #-} {-# INLINE partition #-} {-# INLINE uncons #-} {-# INLINE unsnoc #-} {-# INLINE filter #-} {-# INLINE filterM #-} {-# INLINE replicate #-} {-# INLINE replicateM #-} {-# INLINE groupBy #-} {-# INLINE groupAllOn #-} {-# INLINE subsequences #-} {-# INLINE permutations #-} {-# INLINE tailEx #-} {-# INLINE initEx #-} {-# INLINE unsafeTail #-} {-# INLINE unsafeInit #-} {-# INLINE index #-} {-# INLINE indexEx #-} {-# INLINE unsafeIndex #-} -- | Use "Data.List"'s implementation of 'Data.List.find'. defaultFind :: MonoFoldable seq => (Element seq -> Bool) -> seq -> Maybe (Element seq) defaultFind f = List.find f . otoList {-# INLINE defaultFind #-} -- | Use "Data.List"'s implementation of 'Data.List.intersperse'. defaultIntersperse :: IsSequence seq => Element seq -> seq -> seq defaultIntersperse e = fromList . List.intersperse e . otoList {-# INLINE defaultIntersperse #-} -- | Use "Data.List"'s implementation of 'Data.List.reverse'. defaultReverse :: IsSequence seq => seq -> seq defaultReverse = fromList . List.reverse . otoList {-# INLINE defaultReverse #-} -- | Use "Data.List"'s implementation of 'Data.List.sortBy'. defaultSortBy :: IsSequence seq => (Element seq -> Element seq -> Ordering) -> seq -> seq defaultSortBy f = fromList . sortBy f . otoList {-# INLINE defaultSortBy #-} -- | Sort a vector using an supplied element ordering function. vectorSortBy :: VG.Vector v e => (e -> e -> Ordering) -> v e -> v e vectorSortBy f = VG.modify (VAM.sortBy f) {-# INLINE vectorSortBy #-} -- | Sort a vector. vectorSort :: (VG.Vector v e, Ord e) => v e -> v e vectorSort = VG.modify VAM.sort {-# INLINE vectorSort #-} -- | Use "Data.List"'s 'Data.List.:' to prepend an element to a sequence. defaultCons :: IsSequence seq => Element seq -> seq -> seq defaultCons e = fromList . (e:) . otoList {-# INLINE defaultCons #-} -- | Use "Data.List"'s 'Data.List.++' to append an element to a sequence. defaultSnoc :: IsSequence seq => seq -> Element seq -> seq defaultSnoc seq e = fromList (otoList seq List.++ [e]) {-# INLINE defaultSnoc #-} -- | like Data.List.tail, but an input of 'mempty' returns 'mempty' tailDef :: IsSequence seq => seq -> seq tailDef xs = case uncons xs of Nothing -> mempty Just tuple -> snd tuple {-# INLINE tailDef #-} -- | like Data.List.init, but an input of 'mempty' returns 'mempty' initDef :: IsSequence seq => seq -> seq initDef xs = case unsnoc xs of Nothing -> mempty Just tuple -> fst tuple {-# INLINE initDef #-} instance SemiSequence [a] where type Index [a] = Int intersperse = List.intersperse reverse = List.reverse find = List.find sortBy f = V.toList . sortBy f . V.fromList cons = (:) snoc = defaultSnoc {-# INLINE intersperse #-} {-# INLINE reverse #-} {-# INLINE find #-} {-# INLINE sortBy #-} {-# INLINE cons #-} {-# INLINE snoc #-} instance IsSequence [a] where fromList = id filter = List.filter filterM = Control.Monad.filterM break = List.break span = List.span dropWhile = List.dropWhile takeWhile = List.takeWhile splitAt = List.splitAt take = List.take drop = List.drop uncons [] = Nothing uncons (x:xs) = Just (x, xs) unsnoc [] = Nothing unsnoc (x0:xs0) = Just (loop id x0 xs0) where loop front x [] = (front [], x) loop front x (y:z) = loop (front . (x:)) y z partition = List.partition replicate = List.replicate replicateM = Control.Monad.replicateM groupBy = List.groupBy groupAllOn f (head : tail) = (head : matches) : groupAllOn f nonMatches where (matches, nonMatches) = partition ((== f head) . f) tail groupAllOn _ [] = [] {-# INLINE fromList #-} {-# INLINE break #-} {-# INLINE span #-} {-# INLINE dropWhile #-} {-# INLINE takeWhile #-} {-# INLINE splitAt #-} {-# INLINE unsafeSplitAt #-} {-# INLINE take #-} {-# INLINE unsafeTake #-} {-# INLINE drop #-} {-# INLINE unsafeDrop #-} {-# INLINE partition #-} {-# INLINE uncons #-} {-# INLINE unsnoc #-} {-# INLINE filter #-} {-# INLINE filterM #-} {-# INLINE replicate #-} {-# INLINE replicateM #-} {-# INLINE groupBy #-} {-# INLINE groupAllOn #-} {-# INLINE subsequences #-} {-# INLINE permutations #-} {-# INLINE tailEx #-} {-# INLINE initEx #-} {-# INLINE unsafeTail #-} {-# INLINE unsafeInit #-} instance SemiSequence (NE.NonEmpty a) where type Index (NE.NonEmpty a) = Int intersperse = NE.intersperse reverse = NE.reverse find x = find x . NE.toList cons = NE.cons snoc xs x = NE.fromList $ flip snoc x $ NE.toList xs sortBy f = NE.fromList . sortBy f . NE.toList {-# INLINE intersperse #-} {-# INLINE reverse #-} {-# INLINE find #-} {-# INLINE sortBy #-} {-# INLINE cons #-} {-# INLINE snoc #-} instance SemiSequence S.ByteString where type Index S.ByteString = Int intersperse = S.intersperse reverse = S.reverse find = S.find cons = S.cons snoc = S.snoc sortBy = defaultSortBy {-# INLINE intersperse #-} {-# INLINE reverse #-} {-# INLINE find #-} {-# INLINE sortBy #-} {-# INLINE cons #-} {-# INLINE snoc #-} instance IsSequence S.ByteString where fromList = S.pack replicate = S.replicate filter = S.filter break = S.break span = S.span dropWhile = S.dropWhile takeWhile = S.takeWhile splitAt = S.splitAt take = S.take unsafeTake = SU.unsafeTake drop = S.drop unsafeDrop = SU.unsafeDrop partition = S.partition uncons = S.uncons unsnoc s | S.null s = Nothing | otherwise = Just (S.init s, S.last s) groupBy = S.groupBy tailEx = S.tail initEx = S.init unsafeTail = SU.unsafeTail {-# INLINE fromList #-} {-# INLINE break #-} {-# INLINE span #-} {-# INLINE dropWhile #-} {-# INLINE takeWhile #-} {-# INLINE splitAt #-} {-# INLINE unsafeSplitAt #-} {-# INLINE take #-} {-# INLINE unsafeTake #-} {-# INLINE drop #-} {-# INLINE unsafeDrop #-} {-# INLINE partition #-} {-# INLINE uncons #-} {-# INLINE unsnoc #-} {-# INLINE filter #-} {-# INLINE filterM #-} {-# INLINE replicate #-} {-# INLINE replicateM #-} {-# INLINE groupBy #-} {-# INLINE groupAllOn #-} {-# INLINE subsequences #-} {-# INLINE permutations #-} {-# INLINE tailEx #-} {-# INLINE initEx #-} {-# INLINE unsafeTail #-} {-# INLINE unsafeInit #-} index bs i | i >= S.length bs = Nothing | otherwise = Just (S.index bs i) indexEx = S.index unsafeIndex = SU.unsafeIndex {-# INLINE index #-} {-# INLINE indexEx #-} {-# INLINE unsafeIndex #-} instance SemiSequence T.Text where type Index T.Text = Int intersperse = T.intersperse reverse = T.reverse find = T.find cons = T.cons snoc = T.snoc sortBy = defaultSortBy {-# INLINE intersperse #-} {-# INLINE reverse #-} {-# INLINE find #-} {-# INLINE sortBy #-} {-# INLINE cons #-} {-# INLINE snoc #-} instance IsSequence T.Text where fromList = T.pack replicate i c = T.replicate i (T.singleton c) filter = T.filter break = T.break span = T.span dropWhile = T.dropWhile takeWhile = T.takeWhile splitAt = T.splitAt take = T.take drop = T.drop partition = T.partition uncons = T.uncons unsnoc t | T.null t = Nothing | otherwise = Just (T.init t, T.last t) groupBy = T.groupBy tailEx = T.tail initEx = T.init {-# INLINE fromList #-} {-# INLINE break #-} {-# INLINE span #-} {-# INLINE dropWhile #-} {-# INLINE takeWhile #-} {-# INLINE splitAt #-} {-# INLINE unsafeSplitAt #-} {-# INLINE take #-} {-# INLINE unsafeTake #-} {-# INLINE drop #-} {-# INLINE unsafeDrop #-} {-# INLINE partition #-} {-# INLINE uncons #-} {-# INLINE unsnoc #-} {-# INLINE filter #-} {-# INLINE filterM #-} {-# INLINE replicate #-} {-# INLINE replicateM #-} {-# INLINE groupBy #-} {-# INLINE groupAllOn #-} {-# INLINE subsequences #-} {-# INLINE permutations #-} {-# INLINE tailEx #-} {-# INLINE initEx #-} {-# INLINE unsafeTail #-} {-# INLINE unsafeInit #-} index t i | i >= T.length t = Nothing | otherwise = Just (T.index t i) indexEx = T.index unsafeIndex = T.index {-# INLINE index #-} {-# INLINE indexEx #-} {-# INLINE unsafeIndex #-} instance SemiSequence L.ByteString where type Index L.ByteString = Int64 intersperse = L.intersperse reverse = L.reverse find = L.find cons = L.cons snoc = L.snoc sortBy = defaultSortBy {-# INLINE intersperse #-} {-# INLINE reverse #-} {-# INLINE find #-} {-# INLINE sortBy #-} {-# INLINE cons #-} {-# INLINE snoc #-} instance IsSequence L.ByteString where fromList = L.pack replicate = L.replicate filter = L.filter break = L.break span = L.span dropWhile = L.dropWhile takeWhile = L.takeWhile splitAt = L.splitAt take = L.take drop = L.drop partition = L.partition uncons = L.uncons unsnoc s | L.null s = Nothing | otherwise = Just (L.init s, L.last s) groupBy = L.groupBy tailEx = L.tail initEx = L.init {-# INLINE fromList #-} {-# INLINE break #-} {-# INLINE span #-} {-# INLINE dropWhile #-} {-# INLINE takeWhile #-} {-# INLINE splitAt #-} {-# INLINE unsafeSplitAt #-} {-# INLINE take #-} {-# INLINE unsafeTake #-} {-# INLINE drop #-} {-# INLINE unsafeDrop #-} {-# INLINE partition #-} {-# INLINE uncons #-} {-# INLINE unsnoc #-} {-# INLINE filter #-} {-# INLINE filterM #-} {-# INLINE replicate #-} {-# INLINE replicateM #-} {-# INLINE groupBy #-} {-# INLINE groupAllOn #-} {-# INLINE subsequences #-} {-# INLINE permutations #-} {-# INLINE tailEx #-} {-# INLINE initEx #-} {-# INLINE unsafeTail #-} {-# INLINE unsafeInit #-} indexEx = L.index unsafeIndex = L.index {-# INLINE index #-} {-# INLINE indexEx #-} {-# INLINE unsafeIndex #-} instance SemiSequence TL.Text where type Index TL.Text = Int64 intersperse = TL.intersperse reverse = TL.reverse find = TL.find cons = TL.cons snoc = TL.snoc sortBy = defaultSortBy {-# INLINE intersperse #-} {-# INLINE reverse #-} {-# INLINE find #-} {-# INLINE sortBy #-} {-# INLINE cons #-} {-# INLINE snoc #-} instance IsSequence TL.Text where fromList = TL.pack replicate i c = TL.replicate i (TL.singleton c) filter = TL.filter break = TL.break span = TL.span dropWhile = TL.dropWhile takeWhile = TL.takeWhile splitAt = TL.splitAt take = TL.take drop = TL.drop partition = TL.partition uncons = TL.uncons unsnoc t | TL.null t = Nothing | otherwise = Just (TL.init t, TL.last t) groupBy = TL.groupBy tailEx = TL.tail initEx = TL.init {-# INLINE fromList #-} {-# INLINE break #-} {-# INLINE span #-} {-# INLINE dropWhile #-} {-# INLINE takeWhile #-} {-# INLINE splitAt #-} {-# INLINE unsafeSplitAt #-} {-# INLINE take #-} {-# INLINE unsafeTake #-} {-# INLINE drop #-} {-# INLINE unsafeDrop #-} {-# INLINE partition #-} {-# INLINE uncons #-} {-# INLINE unsnoc #-} {-# INLINE filter #-} {-# INLINE filterM #-} {-# INLINE replicate #-} {-# INLINE replicateM #-} {-# INLINE groupBy #-} {-# INLINE groupAllOn #-} {-# INLINE subsequences #-} {-# INLINE permutations #-} {-# INLINE tailEx #-} {-# INLINE initEx #-} {-# INLINE unsafeTail #-} {-# INLINE unsafeInit #-} indexEx = TL.index unsafeIndex = TL.index {-# INLINE index #-} {-# INLINE indexEx #-} {-# INLINE unsafeIndex #-} instance SemiSequence (Seq.Seq a) where type Index (Seq.Seq a) = Int cons = (Seq.<|) snoc = (Seq.|>) reverse = Seq.reverse sortBy = Seq.sortBy intersperse = defaultIntersperse find = defaultFind {-# INLINE intersperse #-} {-# INLINE reverse #-} {-# INLINE find #-} {-# INLINE sortBy #-} {-# INLINE cons #-} {-# INLINE snoc #-} instance IsSequence (Seq.Seq a) where fromList = Seq.fromList replicate = Seq.replicate replicateM = Seq.replicateM filter = Seq.filter --filterM = Seq.filterM break = Seq.breakl span = Seq.spanl dropWhile = Seq.dropWhileL takeWhile = Seq.takeWhileL splitAt = Seq.splitAt take = Seq.take drop = Seq.drop partition = Seq.partition uncons s = case Seq.viewl s of Seq.EmptyL -> Nothing x Seq.:< xs -> Just (x, xs) unsnoc s = case Seq.viewr s of Seq.EmptyR -> Nothing xs Seq.:> x -> Just (xs, x) --groupBy = Seq.groupBy tailEx = Seq.drop 1 initEx xs = Seq.take (Seq.length xs - 1) xs {-# INLINE fromList #-} {-# INLINE break #-} {-# INLINE span #-} {-# INLINE dropWhile #-} {-# INLINE takeWhile #-} {-# INLINE splitAt #-} {-# INLINE unsafeSplitAt #-} {-# INLINE take #-} {-# INLINE unsafeTake #-} {-# INLINE drop #-} {-# INLINE unsafeDrop #-} {-# INLINE partition #-} {-# INLINE uncons #-} {-# INLINE unsnoc #-} {-# INLINE filter #-} {-# INLINE filterM #-} {-# INLINE replicate #-} {-# INLINE replicateM #-} {-# INLINE groupBy #-} {-# INLINE groupAllOn #-} {-# INLINE subsequences #-} {-# INLINE permutations #-} {-# INLINE tailEx #-} {-# INLINE initEx #-} {-# INLINE unsafeTail #-} {-# INLINE unsafeInit #-} index seq' i | i >= Seq.length seq' = Nothing | otherwise = Just (Seq.index seq' i) indexEx = Seq.index unsafeIndex = Seq.index {-# INLINE index #-} {-# INLINE indexEx #-} {-# INLINE unsafeIndex #-} instance SemiSequence (DList.DList a) where type Index (DList.DList a) = Int cons = DList.cons snoc = DList.snoc reverse = defaultReverse sortBy = defaultSortBy intersperse = defaultIntersperse find = defaultFind {-# INLINE intersperse #-} {-# INLINE reverse #-} {-# INLINE find #-} {-# INLINE sortBy #-} {-# INLINE cons #-} {-# INLINE snoc #-} instance IsSequence (DList.DList a) where fromList = DList.fromList replicate = DList.replicate tailEx = DList.tail {-# INLINE fromList #-} {-# INLINE replicate #-} {-# INLINE tailEx #-} instance SemiSequence (V.Vector a) where type Index (V.Vector a) = Int reverse = V.reverse find = V.find cons = V.cons snoc = V.snoc sortBy = vectorSortBy intersperse = defaultIntersperse {-# INLINE intersperse #-} {-# INLINE reverse #-} {-# INLINE find #-} {-# INLINE sortBy #-} {-# INLINE cons #-} {-# INLINE snoc #-} instance IsSequence (V.Vector a) where fromList = V.fromList replicate = V.replicate replicateM = V.replicateM filter = V.filter filterM = V.filterM break = V.break span = V.span dropWhile = V.dropWhile takeWhile = V.takeWhile splitAt = V.splitAt take = V.take drop = V.drop unsafeTake = V.unsafeTake unsafeDrop = V.unsafeDrop partition = V.partition uncons v | V.null v = Nothing | otherwise = Just (V.head v, V.tail v) unsnoc v | V.null v = Nothing | otherwise = Just (V.init v, V.last v) --groupBy = V.groupBy tailEx = V.tail initEx = V.init unsafeTail = V.unsafeTail unsafeInit = V.unsafeInit {-# INLINE fromList #-} {-# INLINE break #-} {-# INLINE span #-} {-# INLINE dropWhile #-} {-# INLINE takeWhile #-} {-# INLINE splitAt #-} {-# INLINE unsafeSplitAt #-} {-# INLINE take #-} {-# INLINE unsafeTake #-} {-# INLINE drop #-} {-# INLINE unsafeDrop #-} {-# INLINE partition #-} {-# INLINE uncons #-} {-# INLINE unsnoc #-} {-# INLINE filter #-} {-# INLINE filterM #-} {-# INLINE replicate #-} {-# INLINE replicateM #-} {-# INLINE groupBy #-} {-# INLINE groupAllOn #-} {-# INLINE subsequences #-} {-# INLINE permutations #-} {-# INLINE tailEx #-} {-# INLINE initEx #-} {-# INLINE unsafeTail #-} {-# INLINE unsafeInit #-} index v i | i >= V.length v = Nothing | otherwise = Just (v V.! i) indexEx = (V.!) unsafeIndex = V.unsafeIndex {-# INLINE index #-} {-# INLINE indexEx #-} {-# INLINE unsafeIndex #-} instance U.Unbox a => SemiSequence (U.Vector a) where type Index (U.Vector a) = Int intersperse = defaultIntersperse reverse = U.reverse find = U.find cons = U.cons snoc = U.snoc sortBy = vectorSortBy {-# INLINE intersperse #-} {-# INLINE reverse #-} {-# INLINE find #-} {-# INLINE sortBy #-} {-# INLINE cons #-} {-# INLINE snoc #-} instance U.Unbox a => IsSequence (U.Vector a) where fromList = U.fromList replicate = U.replicate replicateM = U.replicateM filter = U.filter filterM = U.filterM break = U.break span = U.span dropWhile = U.dropWhile takeWhile = U.takeWhile splitAt = U.splitAt take = U.take drop = U.drop unsafeTake = U.unsafeTake unsafeDrop = U.unsafeDrop partition = U.partition uncons v | U.null v = Nothing | otherwise = Just (U.head v, U.tail v) unsnoc v | U.null v = Nothing | otherwise = Just (U.init v, U.last v) --groupBy = U.groupBy tailEx = U.tail initEx = U.init unsafeTail = U.unsafeTail unsafeInit = U.unsafeInit {-# INLINE fromList #-} {-# INLINE break #-} {-# INLINE span #-} {-# INLINE dropWhile #-} {-# INLINE takeWhile #-} {-# INLINE splitAt #-} {-# INLINE unsafeSplitAt #-} {-# INLINE take #-} {-# INLINE unsafeTake #-} {-# INLINE drop #-} {-# INLINE unsafeDrop #-} {-# INLINE partition #-} {-# INLINE uncons #-} {-# INLINE unsnoc #-} {-# INLINE filter #-} {-# INLINE filterM #-} {-# INLINE replicate #-} {-# INLINE replicateM #-} {-# INLINE groupBy #-} {-# INLINE groupAllOn #-} {-# INLINE subsequences #-} {-# INLINE permutations #-} {-# INLINE tailEx #-} {-# INLINE initEx #-} {-# INLINE unsafeTail #-} {-# INLINE unsafeInit #-} index v i | i >= U.length v = Nothing | otherwise = Just (v U.! i) indexEx = (U.!) unsafeIndex = U.unsafeIndex {-# INLINE index #-} {-# INLINE indexEx #-} {-# INLINE unsafeIndex #-} instance VS.Storable a => SemiSequence (VS.Vector a) where type Index (VS.Vector a) = Int reverse = VS.reverse find = VS.find cons = VS.cons snoc = VS.snoc intersperse = defaultIntersperse sortBy = vectorSortBy {-# INLINE intersperse #-} {-# INLINE reverse #-} {-# INLINE find #-} {-# INLINE sortBy #-} {-# INLINE cons #-} {-# INLINE snoc #-} instance VS.Storable a => IsSequence (VS.Vector a) where fromList = VS.fromList replicate = VS.replicate replicateM = VS.replicateM filter = VS.filter filterM = VS.filterM break = VS.break span = VS.span dropWhile = VS.dropWhile takeWhile = VS.takeWhile splitAt = VS.splitAt take = VS.take drop = VS.drop unsafeTake = VS.unsafeTake unsafeDrop = VS.unsafeDrop partition = VS.partition uncons v | VS.null v = Nothing | otherwise = Just (VS.head v, VS.tail v) unsnoc v | VS.null v = Nothing | otherwise = Just (VS.init v, VS.last v) --groupBy = U.groupBy tailEx = VS.tail initEx = VS.init unsafeTail = VS.unsafeTail unsafeInit = VS.unsafeInit {-# INLINE fromList #-} {-# INLINE break #-} {-# INLINE span #-} {-# INLINE dropWhile #-} {-# INLINE takeWhile #-} {-# INLINE splitAt #-} {-# INLINE unsafeSplitAt #-} {-# INLINE take #-} {-# INLINE unsafeTake #-} {-# INLINE drop #-} {-# INLINE unsafeDrop #-} {-# INLINE partition #-} {-# INLINE uncons #-} {-# INLINE unsnoc #-} {-# INLINE filter #-} {-# INLINE filterM #-} {-# INLINE replicate #-} {-# INLINE replicateM #-} {-# INLINE groupBy #-} {-# INLINE groupAllOn #-} {-# INLINE subsequences #-} {-# INLINE permutations #-} {-# INLINE tailEx #-} {-# INLINE initEx #-} {-# INLINE unsafeTail #-} {-# INLINE unsafeInit #-} index v i | i >= VS.length v = Nothing | otherwise = Just (v VS.! i) indexEx = (VS.!) unsafeIndex = VS.unsafeIndex {-# INLINE index #-} {-# INLINE indexEx #-} {-# INLINE unsafeIndex #-} -- | A typeclass for sequences whose elements have the 'Eq' typeclass class (MonoFoldableEq seq, IsSequence seq, Eq (Element seq)) => EqSequence seq where -- | 'stripPrefix' drops the given prefix from a sequence. -- It returns 'Nothing' if the sequence did not start with the prefix -- given, or 'Just' the sequence after the prefix, if it does. -- -- @ -- > 'stripPrefix' "foo" "foobar" -- 'Just' "foo" -- > 'stripPrefix' "abc" "foobar" -- 'Nothing' -- @ stripPrefix :: seq -> seq -> Maybe seq stripPrefix x y = fmap fromList (otoList x `stripPrefix` otoList y) -- | 'stripSuffix' drops the given suffix from a sequence. -- It returns 'Nothing' if the sequence did not end with the suffix -- given, or 'Just' the sequence before the suffix, if it does. -- -- @ -- > 'stripSuffix' "bar" "foobar" -- 'Just' "foo" -- > 'stripSuffix' "abc" "foobar" -- 'Nothing' -- @ stripSuffix :: seq -> seq -> Maybe seq stripSuffix x y = fmap fromList (otoList x `stripSuffix` otoList y) -- | 'isPrefixOf' takes two sequences and returns 'True' if the first -- sequence is a prefix of the second. isPrefixOf :: seq -> seq -> Bool isPrefixOf x y = otoList x `isPrefixOf` otoList y -- | 'isSuffixOf' takes two sequences and returns 'True' if the first -- sequence is a suffix of the second. isSuffixOf :: seq -> seq -> Bool isSuffixOf x y = otoList x `isSuffixOf` otoList y -- | 'isInfixOf' takes two sequences and returns 'true' if the first -- sequence is contained, wholly and intact, anywhere within the second. isInfixOf :: seq -> seq -> Bool isInfixOf x y = otoList x `isInfixOf` otoList y -- | Equivalent to @'groupBy' (==)@ group :: seq -> [seq] group = groupBy (==) -- | Similar to standard 'group', but operates on the whole collection, -- not just the consecutive items. -- -- Equivalent to @'groupAllOn' id@ groupAll :: seq -> [seq] groupAll = groupAllOn id {-# INLINE isPrefixOf #-} {-# INLINE isSuffixOf #-} {-# INLINE isInfixOf #-} {-# INLINE stripPrefix #-} {-# INLINE stripSuffix #-} {-# INLINE group #-} {-# INLINE groupAll #-} {-# DEPRECATED elem "use oelem" #-} elem :: EqSequence seq => Element seq -> seq -> Bool elem = oelem {-# DEPRECATED notElem "use onotElem" #-} notElem :: EqSequence seq => Element seq -> seq -> Bool notElem = onotElem instance Eq a => EqSequence [a] where stripPrefix = List.stripPrefix stripSuffix x y = fmap reverse (List.stripPrefix (reverse x) (reverse y)) group = List.group isPrefixOf = List.isPrefixOf isSuffixOf x y = List.isPrefixOf (List.reverse x) (List.reverse y) isInfixOf = List.isInfixOf {-# INLINE stripPrefix #-} {-# INLINE stripSuffix #-} {-# INLINE group #-} {-# INLINE groupAll #-} {-# INLINE isPrefixOf #-} {-# INLINE isSuffixOf #-} {-# INLINE isInfixOf #-} instance EqSequence S.ByteString where stripPrefix x y | x `S.isPrefixOf` y = Just (S.drop (S.length x) y) | otherwise = Nothing stripSuffix x y | x `S.isSuffixOf` y = Just (S.take (S.length y - S.length x) y) | otherwise = Nothing group = S.group isPrefixOf = S.isPrefixOf isSuffixOf = S.isSuffixOf isInfixOf = S.isInfixOf {-# INLINE stripPrefix #-} {-# INLINE stripSuffix #-} {-# INLINE group #-} {-# INLINE groupAll #-} {-# INLINE isPrefixOf #-} {-# INLINE isSuffixOf #-} {-# INLINE isInfixOf #-} instance EqSequence L.ByteString where stripPrefix x y | x `L.isPrefixOf` y = Just (L.drop (L.length x) y) | otherwise = Nothing stripSuffix x y | x `L.isSuffixOf` y = Just (L.take (L.length y - L.length x) y) | otherwise = Nothing group = L.group isPrefixOf = L.isPrefixOf isSuffixOf = L.isSuffixOf isInfixOf x y = L.unpack x `List.isInfixOf` L.unpack y {-# INLINE stripPrefix #-} {-# INLINE stripSuffix #-} {-# INLINE group #-} {-# INLINE groupAll #-} {-# INLINE isPrefixOf #-} {-# INLINE isSuffixOf #-} {-# INLINE isInfixOf #-} instance EqSequence T.Text where stripPrefix = T.stripPrefix stripSuffix = T.stripSuffix group = T.group isPrefixOf = T.isPrefixOf isSuffixOf = T.isSuffixOf isInfixOf = T.isInfixOf {-# INLINE stripPrefix #-} {-# INLINE stripSuffix #-} {-# INLINE group #-} {-# INLINE groupAll #-} {-# INLINE isPrefixOf #-} {-# INLINE isSuffixOf #-} {-# INLINE isInfixOf #-} instance EqSequence TL.Text where stripPrefix = TL.stripPrefix stripSuffix = TL.stripSuffix group = TL.group isPrefixOf = TL.isPrefixOf isSuffixOf = TL.isSuffixOf isInfixOf = TL.isInfixOf {-# INLINE stripPrefix #-} {-# INLINE stripSuffix #-} {-# INLINE group #-} {-# INLINE groupAll #-} {-# INLINE isPrefixOf #-} {-# INLINE isSuffixOf #-} {-# INLINE isInfixOf #-} instance Eq a => EqSequence (Seq.Seq a) instance Eq a => EqSequence (V.Vector a) instance (Eq a, U.Unbox a) => EqSequence (U.Vector a) instance (Eq a, VS.Storable a) => EqSequence (VS.Vector a) -- | A typeclass for sequences whose elements have the 'Ord' typeclass class (EqSequence seq, MonoFoldableOrd seq) => OrdSequence seq where -- | Sort a ordered sequence. -- -- @ -- > 'sort' [4,3,1,2] -- [1,2,3,4] -- @ sort :: seq -> seq sort = fromList . sort . otoList {-# INLINE sort #-} instance Ord a => OrdSequence [a] where sort = V.toList . sort . V.fromList {-# INLINE sort #-} instance OrdSequence S.ByteString where sort = S.sort {-# INLINE sort #-} instance OrdSequence L.ByteString instance OrdSequence T.Text instance OrdSequence TL.Text instance Ord a => OrdSequence (Seq.Seq a) instance Ord a => OrdSequence (V.Vector a) where sort = vectorSort {-# INLINE sort #-} instance (Ord a, U.Unbox a) => OrdSequence (U.Vector a) where sort = vectorSort {-# INLINE sort #-} instance (Ord a, VS.Storable a) => OrdSequence (VS.Vector a) where sort = vectorSort {-# INLINE sort #-} -- | A typeclass for sequences whose elements are 'Char's. class (IsSequence t, IsString t, Element t ~ Char) => Textual t where -- | Break up a textual sequence into a list of words, which were delimited -- by white space. -- -- @ -- > 'words' "abc def ghi" -- ["abc","def","ghi"] -- @ words :: t -> [t] -- | Join a list of textual sequences using seperating spaces. -- -- @ -- > 'unwords' ["abc","def","ghi"] -- "abc def ghi" -- @ unwords :: [t] -> t -- | Break up a textual sequence at newline characters. -- -- -- @ -- > 'lines' "hello\\nworld" -- ["hello","world"] -- @ lines :: t -> [t] -- | Join a list of textual sequences using newlines. -- -- @ -- > 'unlines' ["abc","def","ghi"] -- "abc\\ndef\\nghi" -- @ unlines :: [t] -> t -- | Convert a textual sequence to lower-case. -- -- @ -- > 'toLower' "HELLO WORLD" -- "hello world" -- @ toLower :: t -> t -- | Convert a textual sequence to upper-case. -- -- @ -- > 'toUpper' "hello world" -- "HELLO WORLD" -- @ toUpper :: t -> t -- | Convert a textual sequence to folded-case. -- -- Slightly different from 'toLower', see @"Data.Text".'Data.Text.toCaseFold'@ toCaseFold :: t -> t -- | Split a textual sequence into two parts, split at the first space. -- -- @ -- > 'breakWord' "hello world" -- ("hello","world") -- @ breakWord :: t -> (t, t) breakWord = fmap (dropWhile isSpace) . break isSpace {-# INLINE breakWord #-} -- | Split a textual sequence into two parts, split at the newline. -- -- @ -- > 'breakLine' "abc\\ndef" -- ("abc","def") -- @ breakLine :: t -> (t, t) breakLine = (killCR *** drop 1) . break (== '\n') where killCR t = case unsnoc t of Just (t', '\r') -> t' _ -> t instance (c ~ Char) => Textual [c] where words = List.words unwords = List.unwords lines = List.lines unlines = List.unlines toLower = TL.unpack . TL.toLower . TL.pack toUpper = TL.unpack . TL.toUpper . TL.pack toCaseFold = TL.unpack . TL.toCaseFold . TL.pack {-# INLINE words #-} {-# INLINE unwords #-} {-# INLINE lines #-} {-# INLINE unlines #-} {-# INLINE toLower #-} {-# INLINE toUpper #-} {-# INLINE toCaseFold #-} instance Textual T.Text where words = T.words unwords = T.unwords lines = T.lines unlines = T.unlines toLower = T.toLower toUpper = T.toUpper toCaseFold = T.toCaseFold {-# INLINE words #-} {-# INLINE unwords #-} {-# INLINE lines #-} {-# INLINE unlines #-} {-# INLINE toLower #-} {-# INLINE toUpper #-} {-# INLINE toCaseFold #-} instance Textual TL.Text where words = TL.words unwords = TL.unwords lines = TL.lines unlines = TL.unlines toLower = TL.toLower toUpper = TL.toUpper toCaseFold = TL.toCaseFold {-# INLINE words #-} {-# INLINE unwords #-} {-# INLINE lines #-} {-# INLINE unlines #-} {-# INLINE toLower #-} {-# INLINE toUpper #-} {-# INLINE toCaseFold #-} -- | Takes all of the `Just` values from a sequence of @Maybe t@s and -- concatenates them into an unboxed sequence of @t@s. -- -- Since 0.6.2 catMaybes :: (IsSequence (f (Maybe t)), Functor f, Element (f (Maybe t)) ~ Maybe t) => f (Maybe t) -> f t catMaybes = fmap fromJust . filter isJust -- | Same as @sortBy . comparing@. -- -- Since 0.7.0 sortOn :: (Ord o, SemiSequence seq) => (Element seq -> o) -> seq -> seq sortOn = sortBy . comparing {-# INLINE sortOn #-}
pikajude/mono-traversable
src/Data/Sequences.hs
Haskell
mit
44,679
module SecretHandshake (handshake) where handshake :: Int -> [String] handshake n = error "You need to implement this function."
exercism/xhaskell
exercises/practice/secret-handshake/src/SecretHandshake.hs
Haskell
mit
130
module DebugDisplay (toBinaryRepresentation) where import Utilities(testBitAt) import Data.Word(Word8) import Data.Bits(Bits) -- Useful Debug Display Functions toBinaryRepresentation :: Bits a => [a] -> String toBinaryRepresentation [] = [] toBinaryRepresentation (x:xs) = (concat [show $ boolToInt . testBitAt n $ x | n <- [0..7]]) ++ toBinaryRepresentation xs where boolToInt :: Bool -> Int boolToInt False = 0 boolToInt True = 1
tombusby/haskell-des
debug/DebugDisplay.hs
Haskell
mit
443
module Jbobaf ( module Jbobaf.Jitro, module Jbobaf.Lerfendi, module Jbobaf.Selmaho, module Jbobaf.Valsi, module Jbobaf.Vlatai ) where import Jbobaf.Jitro import Jbobaf.Lerfendi import Jbobaf.Selmaho import Jbobaf.Valsi import Jbobaf.Vlatai
jwodder/jbobaf
haskell/Jbobaf.hs
Haskell
mit
245
{-# LANGUAGE OverloadedStrings #-} import CFDI (UUID(..)) import CFDI.PAC (ppCancelError, cancelCFDI) import CFDI.PAC.Dummy (Dummy(..)) import CFDI.PAC.Fel (Fel(Fel), FelEnv(..)) import CFDI.PAC.ITimbre (ITimbre(ITimbre), ITimbreEnv(..)) import qualified Data.ByteString.Char8 as C8 (putStrLn) import Data.Char (toLower) import Data.Text (pack) import Data.Text.Encoding (encodeUtf8) import System.Environment (getArgs, getEnv, lookupEnv) import System.Exit (ExitCode(ExitFailure), exitWith) import System.IO (hPutStrLn, stderr) main :: IO () main = do args <- getArgs case args of (pacName : pfxPem : pfxPass : uuidStr : _) -> do environment <- lookupEnv "CFDI_ENVIRONMENT" let uuid = UUID $ pack uuidStr isTest = (map toLower <$> environment) == Just "test" case map toLower pacName of "itimbre" -> do user <- getEnv "CFDI_ITIMBRE_USER" pass <- getEnv "CFDI_ITIMBRE_PASS" rfc <- getEnv "CFDI_ITIMBRE_RFC" let pac = ITimbre (pack user) (pack pass) (pack rfc) (pack pfxPass) (pack pfxPem) (if isTest then ItimbreTestingEnv else ItimbreProductionEnv ) eitherErrOrAck <- cancelCFDI pac uuid case eitherErrOrAck of Left cancelError -> do hPutStrLn stderr $ ppCancelError cancelError exitWith $ ExitFailure 4 Right ack -> C8.putStrLn $ encodeUtf8 ack "fel" -> do user <- getEnv "CFDI_FEL_USER" pass <- getEnv "CFDI_FEL_PASS" rfc <- getEnv "CFDI_FEL_RFC" let pac = Fel (pack user) (pack pass) (pack rfc) (pack pfxPem) (pack pfxPass) (if isTest then FelTestingEnv else FelProductionEnv) eitherErrOrAck <- cancelCFDI pac uuid case eitherErrOrAck of Left cancelError -> do hPutStrLn stderr $ ppCancelError cancelError exitWith $ ExitFailure 4 Right ack -> C8.putStrLn $ encodeUtf8 ack "dummy" -> do eitherErrOrAck <- cancelCFDI Dummy uuid case eitherErrOrAck of Left cancelError -> do hPutStrLn stderr $ ppCancelError cancelError exitWith $ ExitFailure 4 Right ack -> C8.putStrLn $ encodeUtf8 ack unknownPac -> do hPutStrLn stderr $ "Unknown PAC " ++ unknownPac exitWith $ ExitFailure 3 _ -> do hPutStrLn stderr "Usage: cfdi_cancel [PAC name] [CFDI UUID]" exitWith $ ExitFailure 2
yusent/cfdis
cancel_cfdi/main.hs
Haskell
mit
2,827
{-# LANGUAGE RecursiveDo #-} module Types.Parser.Types ( Imperative (..) , VerbPhrase (..) , NounPhrase (..) , PrepPhrase (..) , AdjPhrase (..) , Noun , Verb , Determiner , Preposition , Adjective ) where import Prelude import Data.Text data Imperative = Type1 VerbPhrase NounPhrase | Type2 VerbPhrase PrepPhrase | Type3 VerbPhrase NounPhrase PrepPhrase | ImperativeClause Verb deriving Show type Noun = Text type Verb = Text type Determiner = Text type Preposition = Text type Adjective = Text type Number = Text data VerbPhrase = VerbPhrase1 Verb NounPhrase | Verb Verb deriving Show data NounPhrase = NounPhrase1 Determiner NounPhrase | NounPhrase2 Determiner AdjPhrase NounPhrase | NounPhrase3 Number Noun | Noun Noun deriving Show data PrepPhrase = PrepPhrase Preposition NounPhrase | Preposition Preposition deriving Show data AdjPhrase = Adjective Adjective deriving Show
mlitchard/cosmos
library/Types/Parser/Types.hs
Haskell
mit
1,136
-- copied from stackoverflow. review later to reenact combinations :: Int -> [a] -> [[a]] combinations k xs = combinations' (length xs) k xs where combinations' n k' l@(y:ys) | k' == 0 = [[]] | k' >= n = [l] | null l = [] | otherwise = map (y :) (combinations' (n - 1) (k' - 1) ys) ++ combinations' (n - 1) k' ys cardinality :: [a] -> Int cardinality = length subset :: Eq a => [a] -> [a] -> [a] subset xs ys = filter (flip elem $ ys) xs subset' :: Eq a => [[a]] -> [a] subset' = foldl1 subset subsetCardinality :: Eq a => [[a]] -> Int subsetCardinality = cardinality . subset' sieveMethod' :: Eq a => Int -> Int -> [[a]] -> Int sieveMethod' acc k xs | k == length xs = acc + factor * subsetCardinality xs | otherwise = sieveMethod' (acc + factor * s) (k + 1) xs where factor = if k `mod` 2 == 0 then -1 else 1 comb = combinations k xs s = sum $ map subsetCardinality comb sieveMethod :: Eq a => [[a]] -> Int sieveMethod xs | null xs = 0 | length xs == 1 = cardinality (head xs) | otherwise = union + sieveMethod' 0 2 xs where union = sum $ map cardinality xs
HenningBrandt/Study
Sieve_Method/sieve.hs
Haskell
mit
1,159
module Palindrome where import Utils ((|>)) import Control.Monad import System.Exit (exitSuccess) import Data.Char palindrome :: IO () palindrome = forever $ do line1 <- getLine case (isPalindrome line1) of True -> do putStrLn "It's a palindrome" exitSuccess False -> putStrLn "Not a palindrome" isPalindrome :: String -> Bool isPalindrome xs = xs |> map toLower |> filter (flip elem ['a'..'z']) |> (\xs -> xs == reverse xs)
andrewMacmurray/haskell-book-solutions
src/ch13/palindrome.hs
Haskell
mit
480
{-# LANGUAGE NoMonomorphismRestriction #-} module Plugins.Gallery.Gallery.Manual52 where import Diagrams.Prelude example = hcat [ square 2 , circle 1 # withEnvelope (square 3 :: D R2) , square 2 , text "hi" <> phantom (circle 2 :: D R2) ]
andrey013/pluginstest
Plugins/Gallery/Gallery/Manual52.hs
Haskell
mit
311
{-# LANGUAGE OverloadedLists #-} module Irg.Lab1.Geometry.Shapes where import qualified Irg.Lab1.Geometry.Vector as V import qualified Data.Vector as V2 import Data.Maybe import Debug.Trace type Number = Float myTrace :: Show a => a -> a myTrace x = if False then traceShowId x else x polygonFill :: Polygon -> [(Dot, Dot)] polygonFill p@(Polygon poly) | polygonOrientation p /= Clockwise = error "The polygon has to be oriented clockwise" | otherwise = mapMaybe getPolyLineForY ([minimum ys .. maximum ys] :: [Number]) where edges = myTrace $ polygonEdges p len = length poly ys = map ((V2.! 1) . unpackDot) $ V.toList poly yOfNthVertex n = unpackDot (poly V2.! n) V2.! 1 leftEdges = myTrace $ map fst $ filter (\(_, i) -> yOfNthVertex i < yOfNthVertex ((i+1) `mod` len)) $ zip edges [0..] rightEdges = filter (`notElem` leftEdges) edges getXsOfEdgesOnY edgess y = mapMaybe (getXOfIntersection y) edgess getPolyLineForY y | null (getXsOfEdgesOnY rightEdges y) || null (getXsOfEdgesOnY leftEdges y) = Nothing | l < d = Just (Dot [l, y, 1], Dot [d, y, 1]) | otherwise = Nothing where l = maximum (myTrace $ getXsOfEdgesOnY leftEdges y) d = minimum (getXsOfEdgesOnY rightEdges y) toListWithValid :: Int -> V.Vector Number -> [Number] toListWithValid n vec | length vec == n = V.toList vec | otherwise = error $ "Invalid vector size (" ++ show (length vec) ++ ")" fromListWithValid :: Int -> [Number] -> V.Vector Number fromListWithValid n ls | length ls == n = V.fromList ls | otherwise = error $ "Invalid list size (" ++ show (length ls) ++ ")" data Dot = Dot (V.Vector Number) deriving (Eq, Show) data Line = Line (V.Vector Number) deriving (Eq, Show) data Polygon = Polygon (V.Vector Dot) deriving (Eq, Show) data Location = Above | On | Under deriving (Eq, Show) data InOut = Inside | Outside deriving (Eq, Show) data Orientation = Clockwise | Counterclockwise | Neither deriving (Eq, Show) relationDotLine :: Dot -> Line -> Location relationDotLine dot line | scalar > 0 = Above | scalar == 0 = On | otherwise = Under where scalar = V.scalarProduct (unpackDot dot) (unpackLine line) relationDotPolyNthEdge :: Int -> Dot -> Polygon -> Location relationDotPolyNthEdge n dot poly = relationDotLine dot (polygonEdges poly !! n) isDotInsidePolygon :: Dot -> Polygon -> Bool isDotInsidePolygon dot poly = above && (orientation == Counterclockwise) || under && (orientation == Clockwise) where under = all ((Above /=) . relationDotLine dot) $ polygonEdges poly above = all ((Under /=) . relationDotLine dot) $ polygonEdges poly orientation = polygonOrientation poly lineFromDots :: Dot -> Dot -> Line lineFromDots (Dot d1) (Dot d2) = Line $ V.vectorProduct d1 d2 polygonEdges :: Polygon -> [Line] polygonEdges (Polygon poly) = fmap (\i -> lineFromDots (poly V2.! i) (poly V2.! ((i+1) `mod` len))) lens where lens = [0..len-1] len = length poly polygonOrientation :: Polygon -> Orientation polygonOrientation p@(Polygon poly) | clockwise = Clockwise | counterclockwise = Counterclockwise | otherwise = Neither where edges = polygonEdges p len = length poly lens = [0..len-1] :: [Int] relationPolyEdgeAndNextVertex i = relationDotLine (poly V2.! ((i + 2) `mod` len)) (edges !! i) clockwise = all ((Above /=) . relationPolyEdgeAndNextVertex) lens counterclockwise = all ((Under /=) . relationPolyEdgeAndNextVertex) lens getXOfIntersection :: Number -> Line -> Maybe Number getXOfIntersection y (Line edge) | edge V2.! 0 == 0 = Nothing | otherwise = Just ((-(edge V2.! 1) * y - (edge V2.! 2)) / (edge V2.! 0)) reversePolygon :: Polygon -> Polygon reversePolygon = polygonFromLists . reverse . polygonToLists polygonToClockwise :: Polygon -> Polygon polygonToClockwise poly | polygonOrientation poly == Counterclockwise = reversePolygon poly | polygonOrientation poly == Neither = error "Neither clockwise nor counterclockwise" | otherwise = poly unpackDot :: Dot -> V.Vector Number unpackDot (Dot a) = a unpackLine :: Line -> V.Vector Number unpackLine (Line a) = a unpackPolygon :: Polygon -> V.Vector Dot unpackPolygon (Polygon a) = a dotFromList :: [Number] -> Dot dotFromList = Dot . fromListWithValid 3 dotToList :: Dot -> [Number] dotToList = toListWithValid 3 . unpackDot lineFromList :: [Number] -> Line lineFromList = Line . fromListWithValid 3 lineToList :: Line -> [Number] lineToList = toListWithValid 3 . unpackLine polygonFromLists :: [[Number]] -> Polygon polygonFromLists = Polygon . V.fromList . map dotFromList polygonToLists :: Polygon -> [[Number]] polygonToLists = map (V.toList . unpackDot) . V.toList . unpackPolygon
DominikDitoIvosevic/Uni
IRG/src/Irg/Lab1/Geometry/Shapes.hs
Haskell
mit
4,980
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} module Widgets.LoadingSplash ( loadingSplash, loadingSplashD ) where import qualified Reflex.Dom as Dom import Control.Lens ((.~), (&)) import Commons import Widgets.Generation -- | When the incoming event is Busy, it shows the loading splash. -- It hides as soon as Idle event is coming. -- -- Note, loadingSplash is a special widget. -- We need it load as soon as possible to show it during page loading. -- Therefore, I added its html code dirctly to qua-view.html, so it starts spinning even before -- the javascript code is loaded. -- Also note, that our static css is placed in a separate file (not in place of generated JS code), -- so we can safely write required css code below in a splice. loadingSplashD :: Reflex t => Event t (IsBusy "program") -> QuaWidget t x () loadingSplashD isBusyE = do let cfg = def & Dom.modifyAttributes .~ fmap setClass isBusyE void $ getElementById cfg "qua-view-loading-div" where setClass Busy = "class" =: Just "qua-view-loading-busy" setClass Idle = "class" =: Just "qua-view-loading-idle" -- | Show the loading splash, no events processed. loadingSplash :: Reflex t => QuaWidget t x () loadingSplash = void $ getElementById def "qua-view-loading-div" -- | This function is fully evaluated at compile time. -- It generates css code for existing Dom elements $(do -- create unique css identifiers rotRed <- newVar rotGrey <- newVar -- generate a chunk of css in qua-view.css qcss [cassius| #qua-view-loading-div z-index: 775 height: 0 width: 0 top: 0 left: 0 padding: 0 margin: 0 .qua-view-loading-idle display: none .qua-view-loading-busy display: block #qua-view-loading-splash z-index: 777 position: fixed height: 40% padding: 0 top: 50% left: 50% margin: 0 -50% 0 0 transform: translate(-50%, -50%) #qua-view-loading-background z-index: 776 position: fixed height: 100% width: 100% padding: 0 margin: 0 top: 0 left: 0 background-color: rgba(255,255,255,0.8) #qua-view-loading-splash-red-circle position: relative transform-origin: 36px 36px -ms-transform-origin: 36px 36px -moz-transform-origin: 36px 36px -webkit-transform-origin: 36px 36px -webkit-animation: #{rotRed} 3s linear infinite -moz-animation: #{rotRed} 3s linear infinite -ms-animation: #{rotRed} 3s linear infinite -o-animation: #{rotRed} 3s linear infinite animation: #{rotRed} 3s linear infinite #qua-view-loading-splash-grey-circle position: relative transform-origin: 36px 36px -ms-transform-origin: 36px 36px -moz-transform-origin: 36px 36px -webkit-transform-origin: 36px 36px -webkit-animation: #{rotGrey} 8s linear infinite -moz-animation: #{rotGrey} 8s linear infinite -ms-animation: #{rotGrey} 8s linear infinite -o-animation: #{rotGrey} 8s linear infinite animation: #{rotGrey} 8s linear infinite @-webkit-keyframes #{rotRed} from -ms-transform: rotate(0deg) -moz-transform: rotate(0deg) -webkit-transform: rotate(0deg) -o-transform: rotate(0deg) transform: rotate(0deg) to -ms-transform: rotate(360deg) -moz-transform: rotate(360deg) -webkit-transform: rotate(360deg) -o-transform: rotate(360deg) transform: rotate(360deg) @keyframes #{rotRed} from -ms-transform: rotate(0deg) -moz-transform: rotate(0deg) -webkit-transform: rotate(0deg) -o-transform: rotate(0deg) transform: rotate(0deg) to -ms-transform: rotate(360deg) -moz-transform: rotate(360deg) -webkit-transform: rotate(360deg) -o-transform: rotate(360deg) transform: rotate(360deg) @-webkit-keyframes #{rotGrey} from -ms-transform: rotate(360deg) -moz-transform: rotate(360deg) -webkit-transform: rotate(360deg) -o-transform: rotate(360deg) transform: rotate(360deg) to -ms-transform: rotate(0deg) -moz-transform: rotate(0deg) -webkit-transform: rotate(0deg) -o-transform: rotate(0deg) transform: rotate(0deg) @keyframes #{rotGrey} from -ms-transform: rotate(360deg) -moz-transform: rotate(360deg) -webkit-transform: rotate(360deg) -o-transform: rotate(360deg) transform: rotate(360deg) to -ms-transform: rotate(0deg) -moz-transform: rotate(0deg) -webkit-transform: rotate(0deg) -o-transform: rotate(0deg) transform: rotate(0deg) |] return [] )
achirkin/qua-view
src/Widgets/LoadingSplash.hs
Haskell
mit
5,130
{-# LANGUAGE OverloadedStrings #-} import Control.Monad.Trans.Resource import Data.Conduit (($$)) import Data.Conduit.List (sinkNull) import Data.Map (Map, empty, insert) import Data.Text (Text, unpack) import Text.XML.Stream.Parse import Text.XML (Name, nameLocalName) data Person = Person Int Text deriving Show parsePerson map = tagName "person" (requireAttr "age") (\age -> do name <- content return $ Person (read (unpack age)) name) parsePeople = parsePeople' empty parsePeople' map = tagNoAttr "people" (many (parsePerson map)) main = do people <- runResourceT (parseFile def "Person.xml" $$ force "people required" parsePeople) print people
kberger/xml-streaming
Xml.hs
Haskell
mit
674
module AuthBench (benchAuth, authEnv) where import Criterion.Main import Control.Monad import Control.DeepSeq import Control.Exception import Data.ByteString as BS import Crypto.Saltine.Core.Auth import BenchUtils authEnv :: IO Key authEnv = newKey benchAuth :: Key -> Benchmark benchAuth k = do let authVerify :: ByteString -> Bool authVerify message = do let authenticator = auth k message verify k authenticator message bgroup "Auth" [ bench "newKey" $ nfIO newKey , bgroup "auth" [ bench "128 B" $ nf (auth k) bs128 , bench "1 MB" $ nf (auth k) mb1 , bench "5 MB" $ nf (auth k) mb5 ] , bgroup "auth+verify" [ bench "128 B" $ nf authVerify bs128 , bench "1 MB" $ nf authVerify mb1 , bench "5 MB" $ nf authVerify mb5 ] ]
tel/saltine
bench/AuthBench.hs
Haskell
mit
825
module Coins.A265415 (a265415) where import Coins.A260643 (a260643_list) import Data.List (elemIndices) a265415 :: Int -> Int a265415 n = a265415_list !! (n - 1) a265415_list :: [Int] a265415_list = map (+1) $ elemIndices 1 a260643_list
peterokagey/haskellOEIS
src/Coins/A265415.hs
Haskell
apache-2.0
239
<?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="ru-RU"> <title>Highlighter</title> <maps> <homeID>highlighter</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>
secdec/zap-extensions
addOns/highlighter/src/main/javahelp/help_ru_RU/helpset_ru_RU.hs
Haskell
apache-2.0
964
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} module Spark.Core.Internal.ColumnStructures where import Control.Arrow ((&&&)) import Data.Function(on) import Data.Vector(Vector) import Spark.Core.Internal.DatasetStructures import Spark.Core.Internal.DatasetFunctions() import Spark.Core.Internal.RowStructures import Spark.Core.Internal.TypesStructures import Spark.Core.Internal.OpStructures import Spark.Core.StructuresInternal import Spark.Core.Try {-| The data structure that implements the notion of data columns. The type on this one may either be a Cell or a proper type. A column of data from a dataset The ref is a reference potentially to the originating dataset, but it may be more general than that to perform type-safe tricks. Unlike Spark, columns are always attached to a reference dataset or dataframe. One cannot materialize a column out of thin air. In order to broadcast a value along a given column, the `broadcast` function is provided. TODO: try something like this https://www.vidarholen.net/contents/junk/catbag.html -} data ColumnData ref a = ColumnData { _cOrigin :: !UntypedDataset, _cType :: !DataType, _cOp :: !GeneralizedColOp, -- The name in the dataset. -- If not set, it will be deduced from the operation. _cReferingPath :: !(Maybe FieldName) } {-| A generalization of the column operation. This structure is useful to performn some extra operations not supported by the Spark engine: - express joins with an observable - keep track of DAGs of column operations (not implemented yet) -} data GeneralizedColOp = GenColExtraction !FieldPath | GenColFunction !SqlFunctionName !(Vector GeneralizedColOp) | GenColLit !DataType !Cell -- This is the extra operation that needs to be flattened with a broadcast. | BroadcastColOp !UntypedLocalData | GenColStruct !(Vector GeneralizedTransField) deriving (Eq, Show) data GeneralizedTransField = GeneralizedTransField { gtfName :: !FieldName, gtfValue :: !GeneralizedColOp } deriving (Eq, Show) {-| A column of data from a dataset or a dataframe. This column is typed: the operations on this column will be validdated by Haskell' type inferenc. -} type Column ref a = ColumnData ref a {-| An untyped column of data from a dataset or a dataframe. This column is untyped and may not be properly constructed. Any error will be found during the analysis phase at runtime. This type encapsulates both Dataframes and datasets. -} data Column' = Column' !DynColumn {-| (internal) -} -- TODO: remove type DynColumn = Try (ColumnData UnknownReference Cell) -- | (dev) -- The type of untyped column data. type UntypedColumnData = ColumnData UnknownReference Cell {-| (dev) A column for which the type of the cells is unavailable (at the type level), but for which the origin is available at the type level. -} type GenericColumn ref = Column ref Cell {-| A dummy data type that indicates the data referenc is missing. -} data UnknownReference {-| A tag that carries the reference information of a column at a type level. This is useful when creating column. See ref and colRef. -} data ColumnReference a = ColumnReference instance forall ref a. Eq (ColumnData ref a) where (==) = (==) `on` (_cOrigin &&& _cType &&& _cOp &&& _cReferingPath)
tjhunter/karps
haskell/src/Spark/Core/Internal/ColumnStructures.hs
Haskell
apache-2.0
3,393
module Nanocoin.Network.RPC ( rpcServer ) where import Protolude hiding (get, intercalate, print, putText) import Data.Aeson hiding (json, json') import Data.Text (intercalate) import Web.Scotty import Data.List ((\\)) import qualified Data.Map as Map import Logger import Address import qualified Address import Nanocoin.Network.Message (Msg(..)) import Nanocoin.Network.Node as Node import Nanocoin.Network.Peer import qualified Key import qualified Nanocoin.Ledger as L import qualified Nanocoin.Block as B import qualified Nanocoin.MemPool as MP import qualified Nanocoin.Transaction as T import qualified Nanocoin.Network.Cmd as Cmd ------------------------------------------------------------------------------- -- RPC (HTTP) Server ------------------------------------------------------------------------------- runNodeActionM :: Logger -> NodeEnv -> NodeT (LoggerT IO) a -> ActionM a runNodeActionM logger nodeEnv = liftIO . runLoggerT logger . runNodeT nodeEnv -- | Starts an RPC server for interaction via HTTP rpcServer :: Logger -> NodeEnv -> Chan Cmd.Cmd -> IO () rpcServer logger nodeEnv cmdChan = do (NodeConfig hostName p2pPort rpcPort keys) <- liftIO $ nodeConfig <$> runNodeT nodeEnv ask let runNodeActionM' = runNodeActionM logger nodeEnv scotty rpcPort $ do -------------------------------------------------- -- Queries -------------------------------------------------- get "/address" $ json =<< runNodeActionM' getNodeAddress get "/blocks" $ json =<< runNodeActionM' getBlockChain get "/mempool" $ json =<< runNodeActionM' getMemPool get "/ledger" $ json =<< runNodeActionM' getLedger -------------------------------------------------- -- Commands -------------------------------------------------- get "/mineBlock" $ do eBlock <- runNodeActionM' mineBlock case eBlock of Left err -> text $ show err Right block -> do let blockCmd = Cmd.BlockCmd block liftIO $ writeChan cmdChan blockCmd json block get "/transfer/:toAddr/:amount" $ do toAddr' <- param "toAddr" amount <- param "amount" case mkAddress (encodeUtf8 toAddr') of Left err -> text $ toSL err Right toAddr -> do keys <- runNodeActionM' Node.getNodeKeys tx <- liftIO $ T.transferTransaction keys toAddr amount let txMsg = Cmd.TransactionCmd tx liftIO $ writeChan cmdChan txMsg json tx
tdietert/nanocoin
src/Nanocoin/Network/RPC.hs
Haskell
apache-2.0
2,533
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.APPLE.FloatPixels -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/APPLE/float_pixels.txt APPLE_float_pixels> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.APPLE.FloatPixels ( -- * Enums gl_ALPHA_FLOAT16_APPLE, gl_ALPHA_FLOAT32_APPLE, gl_COLOR_FLOAT_APPLE, gl_HALF_APPLE, gl_INTENSITY_FLOAT16_APPLE, gl_INTENSITY_FLOAT32_APPLE, gl_LUMINANCE_ALPHA_FLOAT16_APPLE, gl_LUMINANCE_ALPHA_FLOAT32_APPLE, gl_LUMINANCE_FLOAT16_APPLE, gl_LUMINANCE_FLOAT32_APPLE, gl_RGBA_FLOAT16_APPLE, gl_RGBA_FLOAT32_APPLE, gl_RGB_FLOAT16_APPLE, gl_RGB_FLOAT32_APPLE ) where import Graphics.Rendering.OpenGL.Raw.Tokens
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/APPLE/FloatPixels.hs
Haskell
bsd-3-clause
1,012
module Data.Strict.Maybe where data Maybe' a = Just' !a | Nothing' lazy :: Maybe' a -> Maybe a lazy Nothing' = Nothing lazy (Just' a) = Just a {-# INLINABLE lazy #-} strict :: Maybe a -> Maybe' a strict Nothing = Nothing' strict (Just a) = Just' a {-# INLINABLE strict #-} maybe' :: b -> (a -> b) -> Maybe' a -> b maybe' y f Nothing' = y maybe' y f (Just' x) = f x {-# INLINABLE maybe' #-}
effectfully/prefolds
src/Data/Strict/Maybe.hs
Haskell
bsd-3-clause
397
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-} module Lichen.Plagiarism.Render where import Data.Monoid ((<>)) import Text.Blaze.Html5 ((!)) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import Clay ((?)) import qualified Clay as C import qualified Clay.Size as C.S import qualified Clay.Render as C.R import qualified Clay.Text as C.T import qualified Clay.Font as C.F import Language.Javascript.JMacro import Lichen.Util hs :: Show a => a -> H.Html hs = H.toHtml . sq stylesheet :: C.Css stylesheet = mconcat [ ".centered" ? C.textAlign C.center , ".matches" ? C.color C.white <> C.backgroundColor C.grey , ".hovering" ? C.color C.white <> C.backgroundColor C.blue , ".selected-red" ? C.color C.white <> C.backgroundColor C.red , ".selected-orange" ? C.color C.white <> C.backgroundColor C.orange , ".selected-yellow" ? C.color C.white <> C.backgroundColor C.greenyellow , ".selected-green" ? C.color C.white <> C.backgroundColor C.green , ".selected-blue" ? C.color C.white <> C.backgroundColor C.turquoise , ".selected-indigo" ? C.color C.white <> C.backgroundColor C.indigo , ".selected-violet" ? C.color C.white <> C.backgroundColor C.violet , ".scrollable-pane" ? mconcat [ C.width $ C.S.pct 45 , C.height $ C.S.vh 80 , C.overflowY C.scroll , C.position C.absolute , C.whiteSpace C.T.pre , C.fontFamily [] [C.F.monospace] ] , "#left" ? C.left (C.S.px 0) , "#right" ? C.left (C.S.pct 50) ] javascript :: JStat javascript = [jmacro| var currentHighlight = "selected-red"; fun nextHighlight cur { switch (cur) { case "selected-red": return "selected-orange"; case "selected-orange": return "selected-yellow"; case "selected-yellow": return "selected-green"; case "selected-green": return "selected-blue"; case "selected-blue": return "selected-indigo"; case "selected-indigo": return "selected-violet"; case "selected-violet": return "selected-red"; } } $("#left > .matches").each(function() { $(this).on("click", function(_) { var hash = $(this).data("hash"); var pos = $("#right > .matches[data-hash=" + hash + "]")[0].offsetTop; $("#right").scrollTop(pos); }); }); $("#right > .matches").each(function() { $(this).on("click", function(_) { var hash = $(this).data("hash"); var pos = $("#left > .matches[data-hash=" + hash + "]")[0].offsetTop; $("#left").scrollTop(pos); }); }); $(".matches").each(function() { $(this).hover(function () { $(this).toggleClass("hovering"); var hash = $(this).data("hash"); var side = $(this).parent("#left").length ? "#right" : "#left"; $(side + " > .matches[data-hash=" + hash + "]").toggleClass("hovering"); }); $(this).on("contextmenu", function(_) { var hash = $(this).data("hash"); if ($(this).is("*[class*='selected']")) { $(".matches[data-hash=" + hash + "]").removeClass(\_ c -> (c.match(/(^|\s)selected-\S+/) || []).join(' ')); } else { $(".matches[data-hash=" + hash + "]").addClass(currentHighlight); currentHighlight = nextHighlight(currentHighlight); } return false; }); }); |] renderPage :: H.Html -> H.Html renderPage b = H.docTypeHtml $ mconcat [ H.head $ mconcat [ H.meta ! A.charset "utf-8" , H.meta ! A.httpEquiv "X-UA-Compatible" ! A.content "IE=edge" , H.meta ! A.name "viewport" ! A.content "width=device-width, initial-scale=1" , H.title "Plagiarism Detection" , H.style . H.toHtml $ C.renderWith C.R.compact [] stylesheet ] , H.body $ mconcat [ b , H.script ! A.src "https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" $ "" , H.script . hs $ renderJs javascript ] ]
Submitty/AnalysisTools
src/Lichen/Plagiarism/Render.hs
Haskell
bsd-3-clause
4,602
{-# LANGUAGE GADTs, KindSignatures, RankNTypes, ScopedTypeVariables, StandaloneDeriving, FlexibleInstances #-} module Binder where import Expr import Transport data Bindee :: * -> * where Temperature :: Bindee StringExpr deriving instance Show (Bindee a) instance Read (Bindee StringExpr) where readsPrec d = readParen False $ \ r0 -> [ (Temperature,r1) | ("Temperature",r1) <- lex r0 ] evalBindee :: Bindee a -> IO a evalBindee (Temperature) = return (Lit "76") readBindeeReply :: Bindee a -> String -> a readBindeeReply (Temperature {}) i = read i evalBindeeEnv :: Env -> Id -> Bindee StringExpr -> IO Env evalBindeeEnv env u p = do r <- evalBindee p let v = evalStringExpr env r let env' = (u,v) : env return env'
ku-fpg/remote-monad-examples
classic-examples/Deep/Binder.hs
Haskell
bsd-3-clause
769
{-# LANGUAGE TemplateHaskell #-} module Dir.Everything(module Data.List.Extra, module Dir.Everything) where import Data.List.Extra import Language.Haskell.TH.Syntax import System.Timeout usedFunction1 = undefined :: (T1 -> T1) -> () usedFunction2 = Other unusedFunction = 12 :: Int (=~=) a b = a == b -- used (==~==) a b = a == b class ClassWithFunc a where classWithFunc :: a data D1 = D1 {d1 :: Int} data D2 = D2 {d2 :: Int} data D3 = D3 {d3 :: Int} data D4 = D4 {d4 :: Int} data D5 = D5_ {d5 :: Int} data D6 = D6_ Int data D7 = D7 Int type T1 = D1 type T2 = D2 data Other = Other data Data = Ctor1 {field1 :: Int, field2 :: Int, field3 :: Int} | Ctor2 String type Type = Data data Orphan = Orphan templateHaskell :: Int templateHaskell = $(timeout `seq` lift (1 :: Int))
ndmitchell/weeder
test/foo/src/Dir/Everything.hs
Haskell
bsd-3-clause
797
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} -- | -- Module: $HEADER$ -- Description: Data type for RPM and DPKG package version -- Copyright: (c) 2014 Peter Trsko -- License: BSD3 -- -- Maintainer: peter.trsko@gmail.com -- Stability: experimental -- Portability: DeriveDataTypeable, DeriveGeneric, NoImplicitPrelude -- -- Data type for RPM and DPKG package version. module Data.PkgVersion.Internal.PkgVersion ( -- * PkgVersion PkgVersion(..) ) where import Data.Bool (otherwise) import Data.Data (Data) import Data.Eq (Eq((==))) import Data.Function ((.), flip) import Data.Functor (Functor(fmap)) import Data.Monoid ((<>)) import Data.Typeable (Typeable) import Data.Word (Word32) import GHC.Generics (Generic) import Text.Show (Show(show, showsPrec), showString) import Data.Text as Strict (Text) import Data.Text as Strict.Text (empty, null, pack, singleton) import Data.Default.Class (Default(def)) import Data.PkgVersion.Class ( HasEpoch(epoch) , HasVersion(version) , HasRelease(release) , Serializable(toStrictText, toString) ) -- | Generic package version that works for both RPM and DPKG, but 'Data.Eq.Eq' -- and 'Data.Ord.Ord' instances have to be defined separately for each. -- -- It rerpresents version in format: -- -- > [epoch:]version[-release] -- -- Both RPM and DPKG use similar versioning scheme, therefore this data type is -- used as basis for both 'Data.PkgVersion.Internal.RpmVersion.RpmVersion' and -- 'Data.PkgVersion.Internal.DpkgVersion.DpkgVersion'. data PkgVersion = PkgVersion { _pkgEpoch :: !Word32 , _pkgVersion :: !Strict.Text , _pkgRelease :: !Strict.Text } deriving (Data, Generic, Typeable) -- {{{ Instances for PkgVersion ----------------------------------------------- -- | Instance reflects the shared idea that if epoch is not present then it is -- considered to be zero and that release may be empty: -- -- @ -- 'def' = 'PkgVersion' -- { '_pkgEpoch' = 0 -- , '_pkgVersion' = \"\" -- , '_pkgRelease' = \"\" -- } -- @ instance Default PkgVersion where def = PkgVersion { _pkgEpoch = 0 , _pkgVersion = Strict.Text.empty , _pkgRelease = Strict.Text.empty } -- | Flipped version of 'fmap'. Not exported. (<$$>) :: Functor f => f a -> (a -> b) -> f b (<$$>) = flip fmap {-# INLINE (<$$>) #-} instance HasEpoch PkgVersion where epoch f s@(PkgVersion{_pkgEpoch = a}) = f a <$$> \b -> s{_pkgEpoch = b} instance HasVersion PkgVersion where version f s@(PkgVersion{_pkgVersion = a}) = f a <$$> \b -> s{_pkgVersion = b} instance HasRelease PkgVersion where release f s@(PkgVersion{_pkgRelease = a}) = f a <$$> \b -> s{_pkgRelease = b} instance Serializable PkgVersion where toStrictText (PkgVersion e v r) = e' <> v <> r' where colon = Strict.Text.singleton ':' dash = Strict.Text.singleton '-' e' | e == 0 = Strict.Text.empty | otherwise = Strict.Text.pack (show e) <> colon r' | Strict.Text.null r = Strict.Text.empty | otherwise = dash <> r instance Show PkgVersion where showsPrec _ = showString . toString -- }}} Instances for PkgVersion -----------------------------------------------
trskop/pkg-version
src/Data/PkgVersion/Internal/PkgVersion.hs
Haskell
bsd-3-clause
3,367
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} module Language.Rsc.Liquid.Qualifiers (scrapeQuals) where import Data.List (delete, nub) import Data.Maybe (fromMaybe) import Language.Fixpoint.Types hiding (quals) import Language.Rsc.Annotations import Language.Rsc.AST import Language.Rsc.Core.Env import Language.Rsc.Errors import Language.Rsc.Liquid.Refinements import Language.Rsc.Locations import Language.Rsc.Names import Language.Rsc.Pretty import Language.Rsc.Program import Language.Rsc.SystemUtils import Language.Rsc.Traversals import qualified Language.Rsc.Types as T import Language.Rsc.Visitor import Text.PrettyPrint.HughesPJ -- | Extracts all qualifiers from a RefScript program -- -- Excludes qualifier declarations (qualif Q(...): ...) -- -- XXX: No need to do `mkUq` here, since we're dropping common bindings later. -- --------------------------------------------------------------------------------- scrapeQuals :: RefScript -> [Qualifier] --------------------------------------------------------------------------------- scrapeQuals (Rsc { code = Src ss }) = qualifiers $ {- mkUq . -} foldStmts tbv [] [] $ filter nonLibFile ss where tbv = defaultVisitor { accStmt = gos, accCElt = goe, ctxStmt = ctx } gos c (FunctionStmt l x _ _) = [(qualify c x, t) | SigAnn _ _ t <- fFact l] gos c (VarDeclStmt _ vds) = [(qualify c x, t) | VarDecl l x _ <- vds , VarAnn _ _ _ (Just t) <- fFact l] gos _ _ = [] goe c (Constructor l _ _) = [(qualify c x, t) | CtorAnn t <- fFact l, let x = Id l "ctor" ] goe c (MemberVarDecl l _ x _) = [(qualify c x, t) | MemberAnn (T.FI _ _ _ t) <- fFact l ] goe c (MemberMethDecl l _ x _ _) = [(qualify c x, t) | MemberAnn (T.MI _ _ mts) <- fFact l, (_, t) <- mts ] -- XXX: Use this perhaps to make the bindings unique qualify _ (Id a x) = Id a x -- (mconcat c ++ x) ctx c (ModuleStmt _ m _ ) = symbolString (symbol m) : c ctx c (ClassStmt _ m _ ) = symbolString (symbol m) : c ctx c _ = c nonLibFile :: IsLocated a => Statement a -> Bool nonLibFile = not . isDeclarationFile -- not . isSuffixOf ".d.ts" . srcSpanFile -- mkUq = zipWith tx ([0..] :: [Int]) -- where -- tx i (Id l s, t) = (Id l $ s ++ "_" ++ show i, t) -- XXX: Will drop multiple bindings tp the same name -- To fix, replace envFromList' with something else -- qualifiers xts = concatMap (refTypeQualifiers γ0) xts where γ0 = envSEnv $ envMap rTypeSort $ envFromList' xts refTypeQualifiers γ0 (l, t) = efoldRType rTypeSort addQs γ0 [] t where addQs γ t qs = mkQuals l γ t ++ qs mkQuals l γ t = [ mkQual l γ v so pa | pa <- conjuncts ra, noThis (syms pa) ] where RR so (Reft (v, ra)) = rTypeSortedReft t noThis = all (not . isPrefixOfSym thisSym) mkQual l γ v so p = Q (symbol "Auto") ((v, so) : yts) (subst θ p) l0 where yts = [(y, lookupSort l x γ) | (x, y) <- xys ] θ = mkSubst [(x, eVar y) | (x, y) <- xys] xys = zipWith (\x i -> (x, symbol ("~A" ++ show i))) xs [0..] xs = delete v $ orderedFreeVars γ p l0 = sourcePos l -- XXX: The error won't be triggered cause we've dropped multiple bidings -- at `qualifiers`. -- lookupSort l x γ = fromMaybe errorMsg $ lookupSEnv x γ where errorMsg = die $ bug (srcPos l) $ "Unbound variable " ++ show x ++ " in specification for " ++ show (unId l) orderedFreeVars γ = nub . filter (`memberSEnv` γ) . syms instance {-# OVERLAPPING #-} PP [Qualifier] where pp = vcat . map toFix -- pp qs = vcat $ map (\q -> pp (q_name q) <+> colon <+> pp (q_body q)) qs instance PP Qualifier where pp = toFix
UCSD-PL/RefScript
src/Language/Rsc/Liquid/Qualifiers.hs
Haskell
bsd-3-clause
4,088
module Arbitrary where import Test.QuickCheck import qualified Data.ByteString.Lazy as BS import Frenetic.Common import Control.Monad import Nettle.Arbitrary import Frenetic.NetCore.Types hiding (Switch) import qualified Frenetic.NetCore.Types as NetCore import Frenetic.NetCore.Semantics import Frenetic.Topo arbPort :: Gen Port arbPort = oneof [ return n | n <- [1 .. 5] ] arbSwitch :: Gen Switch arbSwitch = oneof [ return n | n <- [1 .. 10] ] arbGenPktId :: Gen Id arbGenPktId = oneof [ return 900, return 901, return 902 ] arbCountersId :: Gen Id arbCountersId = oneof [ return 500, return 501, return 502 ] arbGetPktId :: Gen Id arbGetPktId = oneof [ return 600, return 601, return 602 ] arbMonSwitchId :: Gen Id arbMonSwitchId = oneof [ return 700, return 701, return 702 ] arbFwd :: Gen Act arbFwd = liftM2 ActFwd arbitrary arbitrary arbFwds :: Gen [Act] arbFwds = oneof [ liftM2 (:) arbFwd arbFwds, return [] ] arbInterval :: Gen Int arbInterval = oneof [ return (-1), return 0, return 1, return 30 ] instance Arbitrary Act where arbitrary = oneof [ arbFwd , liftM2 ActQueryPktCounter arbCountersId arbInterval , liftM2 ActQueryByteCounter arbCountersId arbInterval , liftM ActGetPkt arbGetPktId , liftM ActMonSwitch arbMonSwitchId ] instance Arbitrary Modification where arbitrary = sized $ \s -> frequency [ (2, return unmodified), (1, mod s) ] where mod s = do a1 <- if s < 1 then return Nothing else arbitrary a2 <- if s < 2 then return Nothing else arbitrary a3 <- if s < 3 then return Nothing else arbitrary a4 <- if s < 4 then return Nothing else arbitrary a5 <- if s < 5 then return Nothing else arbitrary a6 <- if s < 6 then return Nothing else arbitrary a7 <- if s < 7 then return Nothing else arbitrary a8 <- if s < 8 then return Nothing else arbitrary a9 <- if s < 9 then return Nothing else arbitrary return (Modification a1 a2 a3 a4 a5 a6 a7 a8 a9) instance Arbitrary Pol where arbitrary = sized $ \s -> case s of 0 -> return PolEmpty otherwise -> oneof [ liftM2 PolProcessIn (resize (s-1) arbitrary) (resize (s-1) arbitrary) , liftM2 PolUnion (resize (s-1) arbitrary) (resize (s-1) arbitrary) -- , liftM2 PolSeq (resize (s-1) arbitrary) (resize (s-1) arbitrary) , liftM2 PolRestrict (resize (s-1) arbitrary) (resize (s-1) arbitrary) , liftM PolGenPacket (resize (s-1) arbGenPktId) ] instance Arbitrary Predicate where arbitrary = sized $ \s -> let small = [ liftM DlSrc arbitrary , liftM DlDst arbitrary , liftM DlTyp arbitrary , liftM DlVlan arbitrary , liftM DlVlanPcp arbitrary , liftM NwSrc arbitrary , liftM NwDst arbitrary , liftM NwProto arbitrary , liftM NwTos arbitrary , liftM TpSrcPort arbitrary , liftM TpDstPort arbitrary , liftM IngressPort arbPort , liftM NetCore.Switch arbSwitch , return None , return Any ] large = [ liftM2 Or (resize (s-1) arbitrary) (resize (s-1) arbitrary) , liftM2 And (resize (s-1) arbitrary) (resize (s-1) arbitrary) , liftM Not (resize (s-1) arbitrary) ] in if s == 0 then oneof small else oneof (small ++ large) instance Arbitrary Loc where arbitrary = liftM2 Loc arbSwitch arbPort expectsNwFields :: Word16 -> Bool expectsNwFields 0x800 = True expectsNwFields 0x806 = True expectsNwFields _ = False -- Does not generate ToQueue instance Arbitrary PseudoPort where arbitrary = frequency [ (5, liftM Physical arbPort) , (1, return AllPorts) ] instance Arbitrary ByteString where arbitrary = return BS.empty -- This isn't perfect, but we attempt to build a reasonable set of headers. -- We favors building IP and ARP packets and fill out the Maybe-typed nw* -- fields for IP and ARP packets. instance Arbitrary Packet where arbitrary = do dlSrc <- arbitrary dlDst <- arbitrary -- generate IP and ARP packets most of the time dlTyp <- frequency [(10, return 0x800), (5, return 0x806), (1, arbitrary)] dlVlan <- arbitrary dlVlanPcp <- arbitrary let nwArbitrary :: Arbitrary a => Gen (Maybe a) -- do not ever use NoMonmorphismRestriction nwArbitrary = if expectsNwFields dlTyp then liftM Just arbitrary else return Nothing pktNwSrc <- nwArbitrary pktNwDst <- nwArbitrary pktNwProto <- arbitrary pktNwTos <- arbitrary pktTpSrc <- nwArbitrary pktTpDst <- nwArbitrary return (Packet dlSrc dlDst dlTyp dlVlan dlVlanPcp pktNwSrc pktNwDst pktNwProto pktNwTos pktTpSrc pktTpDst) arbInPkt = liftM3 InPkt arbitrary arbitrary (liftM Just arbitrary) arbInGenPkt = liftM5 InGenPkt arbGenPktId arbSwitch arbitrary arbitrary arbitrary arbInCounters = liftM5 InCounters arbCountersId arbSwitch arbitrary arbitrary arbitrary -- TODO(arjun): arbInSwitchEvt instance Arbitrary In where arbitrary = oneof [ arbInPkt, arbInGenPkt, arbInCounters ]
frenetic-lang/netcore-1.0
testsuite/Arbitrary.hs
Haskell
bsd-3-clause
5,323
#!/usr/bin/env runhaskell {-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-cse #-} -- This program can crashed by attempting to read an uninitialized 'IORef' with incorrect user input (when he chooses not to input a line after the confirmation) module Main where import Data.IORef import Data.Global import System.IO import Text.Printf un "input" =:: (uninitialized, ut [t| String |] :: UT IORef) main :: IO () main = do hSetBuffering stdout NoBuffering putStr $ printf "This program prints its input (after the confirmation prompt). Would you like to provide input? [y/N]: " getLine >>= \conf -> case conf of ('y':_) -> do putStr $ "Input: " getLine >>= writeIORef input _ -> return () putStrLn . printf "The input: %s" =<< readIORef input
bairyn/global
examples/uninitialized/Main.hs
Haskell
bsd-3-clause
815
{-# LANGUAGE DeriveDataTypeable, FlexibleContexts #-} {-# LANGUAGE NoMonomorphismRestriction, OverloadedStrings, TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module KeyFlags (Masked(..), testCode, compatible, Keyboard(..), decodeKeyboard, decodeModifiers, Modifier(..), encodeMask, decodeFunctionKey, functionKeys, isAlphabeticModifier, _Char, _JIS) where import KeyFlags.Macros import Control.Applicative ((<$>)) import Control.Lens (makePrisms) import Data.Bits import qualified Data.Text.IO as T import Foreign.C.Types import Language.Haskell.TH (runIO) do table <- runIO $ procLR . parse <$> T.readFile "data/keycodes.dat" defineKeyCode "Keyboard" [t| CLong |] table makePrisms ''Keyboard decodeModifiers :: Mask Modifier -> [Modifier] decodeModifiers b = [m | m <- modifiers, testCode m b] encodeMask :: (Masked a, Num (Mask a)) => [a] -> Mask a encodeMask = foldl (.|.) 0 . map toMask data Modifier = AlphaShift | Shift | Control | Alternate | Command | NumericPad | HelpM | Function | Independent deriving (Read, Show, Eq, Ord, Enum) instance Masked Modifier where type Mask Modifier = CULong toMask AlphaShift = alphaShiftMask toMask Alternate = alternateMask toMask Shift = shiftMask toMask Control = controlMask toMask Command = commandMask toMask NumericPad = numericPadMask toMask HelpM = helpMask toMask Function = functionMask toMask Independent = independentMask isAlphabeticModifier :: Modifier -> Bool isAlphabeticModifier a = compatible Shift a || compatible AlphaShift a modifiers :: [Modifier] modifiers = [ AlphaShift , Shift , Control , Alternate , Command , NumericPad , HelpM , Function , Independent ] alphaShiftMask :: Mask Modifier alphaShiftMask = 1 `shiftL` 16 shiftMask :: Mask Modifier shiftMask = 1 `shiftL` 17 controlMask :: Mask Modifier controlMask = 1 `shiftL` 18 alternateMask :: Mask Modifier alternateMask = 1 `shiftL` 19 commandMask :: Mask Modifier commandMask = 1 `shiftL` 20 numericPadMask :: Mask Modifier numericPadMask = 1 `shiftL` 21 helpMask :: Mask Modifier helpMask = 1 `shiftL` 22 functionMask :: Mask Modifier functionMask = 1 `shiftL` 23 independentMask :: Mask Modifier independentMask = 0xffff0000 functionKeys :: [Keyboard] functionKeys = case break (==Home) funs0 of (as, bs) -> as ++ head bs : drop 2 bs funs0 :: [Keyboard] funs0 = [CursorUp , CursorDown , CursorLeft , CursorRight ] ++ [ Fn n | n <- [1..35]] ++ [ PcInsert , Delete , Home , undefined , End , Pageup , Pagedown , PcPrintscreen , PcScrolllock ] decodeFunctionKey :: Char -> Maybe Keyboard decodeFunctionKey = flip lookup functionKeyDic functionKeyDic :: [(Char, Keyboard)] functionKeyDic = case break ((== Home) . snd) $ zip ['\xF700'..] funs0 of (as, bs) -> as ++ head bs : drop 2 bs
konn/hskk
cocoa/KeyFlags.hs
Haskell
bsd-3-clause
3,268