code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Cortex.Saffron.Apps.RailsDev ( prepare , run ) where ----- import Control.Concurrent.Lifted import Control.Monad.Trans (liftIO) import System.Environment (getEnvironment) import Cortex.Saffron.GrandMonadStack import qualified Cortex.Saffron.Apps.Common as Common ----- makeEnv :: AppManagerMonadStack (Maybe [(String, String)]) makeEnv = do e <- liftIO getEnvironment return $ Just (("RAILS_ENV", "development"):e) ----- prepare :: String -> AppManagerMonadStack () prepare _ = return () ----- run :: Int -> String -> AppManagerMonadStack (MVar (), MVar Int) run port location = do env <- makeEnv Common.run port "rails" [ "server" , "--port" , show port ] (Just $ location ++ "/repo") env -----
maarons/Cortex
Saffron/Apps/RailsDev.hs
agpl-3.0
773
0
11
163
238
133
105
22
1
{- Copyright (C) 2015 Yuval Langer This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. -} import Distribution.Simple main = defaultMain
yuvallanger/yasamsim
Setup.hs
agpl-3.0
750
0
4
151
12
7
5
2
1
module HLol.API.LolStatus ( getShards, getShardByRegion ) where import HLol.Data.LolStatus (Shard, ShardStatus) import HLol.Network.Rest import HLol.Utils import Control.Monad import Data.Aeson getShards :: IO (Either LolError [Shard]) getShards = fmap (join . mapR (liftError. eitherDecode)) $ sendAPIRequest_ "http://status.leagueoflegends.com/shards" getShardByRegion :: Region -> IO (Either LolError ShardStatus) getShardByRegion region = fmap (join . mapR (liftError . eitherDecode)) $ sendAPIRequest_ $ "http://status.leagueoflegends.com/shards/" ++ show region
tetigi/hlol
src/HLol/API/LolStatus.hs
agpl-3.0
592
0
13
85
164
89
75
14
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE TemplateHaskell #-} module Relational.Types where import Control.Monad.State import Data.Aeson import Data.Dynamic import qualified Data.HashTable.IO as H import Data.Label (mkLabel) -- Related a :: Contraint type Related a = (Typeable a, ToJSON a, FromJSON a) type RelationId = Integer -- TODO: How about a base26 or more string? data Relation a = Relation RelationId newtype Relational s a = Relational { unwrapRelational :: StateT (Context s) IO a } deriving (Functor, Applicative, Monad, MonadState (Context s)) -- TODO: labels data Context s = Context { _ctxCache :: H.LinearHashTable RelationId (Dynamic, StateT s IO ()) -- TODO: Should this tuple become a record? , _ctxStore :: s } mkLabel ''Context
nitrix/lspace
relational/Relational/Types.hs
unlicense
845
0
12
165
196
117
79
18
0
{-# LANGUAGE NoImplicitPrelude #-} module Types where import RIO import RIO.Process data App = App { appLogFunc :: !LogFunc , appProcessContext :: !ProcessContext } instance HasLogFunc App where logFuncL = lens appLogFunc (\x y -> x { appLogFunc = y }) instance HasProcessContext App where processContextL = lens appProcessContext (\x y -> x { appProcessContext = y })
haroldcarr/learn-haskell-coq-ml-etc
haskell/course/2018-06-snoyman-applied-haskell-at-lambdaconf/use-rio-example/src/Types.hs
unlicense
382
0
10
71
108
62
46
15
0
{- package.yaml name: more-math version: 0.1.0.0 synopsis: More Math for Haskell (Big integers, fractions, etc). category: Math author: dmitmel maintainer: [email protected] license: Apache-2.0 github: dmitmel/more-math extra-source-files: - ChangeLog.md dependencies: - base >=4.9 && <4.10 library: source-dirs: src ghc-options: -Wall exposed-modules: - Math.MoreMath - Math.MoreMath.BigInt - Math.MoreMath.Fraction - Math.MoreMath.Color -} {- cabalw #!/bin/sh # Wrapper for Cabal executable # Recompiles hpack's configuration file (package.yaml) if any changes detected CHECKSUM_FILE=".package.yaml.checksum.txt" prevHash="$([ -f "$CHECKSUM_FILE" ] && cat "$CHECKSUM_FILE")" thisHash="$(sha1sum package.yaml)" if [ "$prevHash" != "$thisHash" ]; then echo "Detected changes in package.yaml" echo "$thisHash" > $CHECKSUM_FILE echo "Aligning package.yaml" align package.yaml 1> /dev/null echo "Generating more-math.cabal" hpack --silent echo fi cabal $@ -} {- listing.txt Permissions Size User Group Date Modified Name drwxr-xr-x - dmitmel staff 31 Mar 2017 ./ drwxr-xr-x - dmitmel staff 15 Dec 2016 β”œβ”€β”€ src/ drwxr-xr-x - dmitmel staff 31 Mar 2017 β”‚ └── Math/ drwxr-xr-x - dmitmel staff 31 Mar 2017 β”‚ β”œβ”€β”€ MoreMath/ .rw-r--r-- 4,9Ki dmitmel staff 11 Jan 2017 β”‚ β”‚ β”œβ”€β”€ BigInt.hs .rw-r--r-- 1020 dmitmel staff 31 Mar 2017 β”‚ β”‚ β”œβ”€β”€ Color.hs .rw-r--r-- 1005 dmitmel staff 12 Jan 2017 β”‚ β”‚ └── Fraction.hs .rw-r--r-- 170 dmitmel staff 12 Jan 2017 β”‚ └── MoreMath.hs .rwxr-xr-x 534 dmitmel staff 11 Jan 2017 β”œβ”€β”€ cabalw* .rw-r--r-- 115 dmitmel staff 14 Dec 2016 β”œβ”€β”€ ChangeLog.md .rw-r--r-- 11Ki dmitmel staff 14 Dec 2016 β”œβ”€β”€ LICENSE .rw-r--r-- 957 dmitmel staff 31 Mar 2017 β”œβ”€β”€ more-math.cabal .rw-r--r-- 588 dmitmel staff 31 Mar 2017 β”œβ”€β”€ package.yaml .rw-r--r-- 46 dmitmel staff 14 Dec 2016 β”œβ”€β”€ Setup.hs .rw-r--r-- 2,2Ki dmitmel staff 11 Jan 2017 └── stack.yaml -} module Math.MoreMath ( module Math.MoreMath.BigInt , module Math.MoreMath.Fraction ) where import Math.MoreMath.BigInt import Math.MoreMath.Fraction
dmitmel/goiteens-hw-in-haskell
Utils/Math/MoreMath.hs
apache-2.0
2,431
0
5
596
37
26
11
5
0
-- voting algorithms -- sample data votes1 :: [String] votes1 = ["Red","Blue","Green","Blue","Blue","Red","Yellow","Blue","Blue"] ballots :: [[String]] ballots = [["Red", "Green", "Blue"], ["Blue"], ["Green","Yellow","Red","Blue"], ["Blue","Green","Red"], ["Green"]] -- helper functions -- (observe that we have used composition and excluded the list parameter from the definition -- (but it is included in the type signature)) count :: Eq a => a -> [a] -> Int count x = length . filter (== x) removeDups :: Eq a => [a] -> [a] removeDups [] = [] removeDups (x:xs) = x : filter (/= x) (removeDups xs) result :: Ord a => [a] -> [(a, Int)] result vs = sort [(v, count v vs) | v <- removeDups vs] -- more helper functions (used only in the alternative vote algorithm) removeEmpty :: Eq a => [[a]] -> [[a]] removeEmpty = filter (/= []) eliminate :: Eq a => a -> [[a]] -> [[a]] eliminate x = map (filter (/= x)) rank :: Ord a => [[a]] -> [a] rank = map fst.result.map head -- as implemented, this will return the member that appears last in the sorted list -- this does not mean this member had more votes than everyone else (the second-last -- etc might have the same number of votes) nor does it mean that the member was -- 'first past the post' as it does not check that the member's share was >50% of the total mostVotes :: Ord a => [a] -> a mostVotes = fst . last . result lastStanding :: Ord a => [[a]] -> a lastStanding bs = case rank (removeEmpty bs) of [c] -> c (c:cs) -> lastStanding (eliminate c bs)
Crossroadsman/ProgrammingInHaskell
07/voting.hs
apache-2.0
1,611
0
10
379
534
302
232
27
2
module StatNLP.Corpus ( initCorpus , makeCorpus , addDocument , updateDocumentFilters , loadCorpusDirectory , indexCorpus , indexCorpus' , inverseIndexCorpus , readCorpusVectors , transformer ) where import Control.Arrow ((&&&)) import Control.Lens hiding (transform) import Data.Foldable import qualified Data.HashMap.Strict as M import Data.Traversable import qualified Data.Vector as V import System.Directory import StatNLP.Document import StatNLP.Input import qualified StatNLP.Text.Index as I import StatNLP.Text.Tokens hiding (tokenizer) import StatNLP.Types import StatNLP.Utils initCorpus :: Tokenizer (Token p PlainToken) -> DocumentReader b () -> Corpus b p initCorpus = Corpus M.empty makeCorpus :: Foldable t => Tokenizer (Token p PlainToken) -> DocumentReader b () -> t (Document b ()) -> Corpus b p makeCorpus tokenizer rdr docs = Corpus (foldl' insert M.empty docs) tokenizer rdr where insert m d = M.insert (documentKey d) d m addDocument :: Corpus b p -> Document b () -> Corpus b p addDocument c d = c & corpusDocuments %~ M.insert (documentKey d) d updateDocumentFilters :: Corpus (Token p PlainToken) p -> IO (Corpus (Token p PlainToken) p) updateDocumentFilters c = fmap (flip (set corpusDocuments) c . M.fromList) . mapM (sequenceA . (documentKey &&& readDocumentTypes c)) . M.elems $ c ^. corpusDocuments loadCorpusDirectory :: Tokenizer (Token p PlainToken) -> DocumentReader b () -> DocumentTransformer b () -> FilePath -> IO (Corpus b p) loadCorpusDirectory tokenizer rdr transform root = fmap (makeCorpus tokenizer rdr) . mapM (transform . initDocument) =<< walk =<< makeAbsolute root where walk filename = do isDir <- doesDirectoryExist filename if isDir then walkDirectory filename else return [filename] indexCorpus :: Corpus b p -> IO (IxIndex PlainToken, [Document Int [Token p Int]]) indexCorpus c = fmap (mapAccumL indexDocumentTokens I.empty) . mapM (tokenizeDocument c) . M.elems $ _corpusDocuments c indexCorpus' :: Corpus b p -> IO (IxIndex PlainToken) indexCorpus' c = foldlM (fmap (fmap fst) . readIndexDocumentTokens c) I.empty . M.elems $ _corpusDocuments c inverseIndexCorpus :: Corpus b p -> IO (InverseIndex PlainToken (DocumentPos p)) inverseIndexCorpus c = fmap mconcat . mapM (readInverseIndexDocument c) . M.elems $ _corpusDocuments c readCorpusVectors :: Maybe PlainToken -> Corpus LineToken LinePos -> IO (M.HashMap DocumentId (VectorDoc LineToken)) readCorpusVectors mtarget corpus = fmap ( M.fromList . fmap (_documentId &&& fmap (V.fromList . posTokenIndex)) ) . mapM (tokenizeDocument corpus) . maybe id (filter . filterToken) mtarget . M.elems $ _corpusDocuments corpus transformer :: StopWords -> DocumentTransformer LineToken () transformer stopwords = readDocumentTypes' (fmap (tokenizerStop stopwords) . reader)
erochest/stat-nlp
src/StatNLP/Corpus.hs
apache-2.0
3,408
0
18
1,024
1,014
511
503
79
2
----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files -- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. ----------------------------------------------------------------------------- -- | -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable (depends on ghc) -- -- Support for the UTF8 encoding -- ----------------------------------------------------------------------------- module Ideas.Text.UTF8 ( encode, encodeM, decode, decodeM , isUTF8, allBytes, propEncoding ) where import Control.Monad import Data.Char import Data.Maybe import Test.QuickCheck ------------------------------------------------------------------ -- Interface -- | Encode a string to UTF8 format encode :: String -> String encode = either error id . encodeM -- | Decode an UTF8 format string to unicode points decode :: String -> String decode = either error id . decodeM -- | Encode a string to UTF8 format (monadic) encodeM :: Monad m => String -> m String encodeM = fmap (map chr . concat) . mapM (toUTF8 . ord) -- | Decode an UTF8 format string to unicode points (monadic) decodeM :: Monad m => String -> m String decodeM = fmap (map chr) . fromUTF8 . map ord -- | Test whether the argument is a proper UTF8 string isUTF8 :: String -> Bool isUTF8 = isJust . decodeM -- | Test whether all characters are in the range 0-255 allBytes :: String -> Bool allBytes = all ((`between` (0, 255)) . ord) ------------------------------------------------------------------ -- Helper functions toUTF8 :: Monad m => Int -> m [Int] toUTF8 n | n < 128 = -- one byte return [n] | n < 2048 = -- two bytes let (a, d) = n `divMod` 64 in return [a+192, d+128] | n < 65536 = -- three bytes let (a, d1) = n `divMod` 4096 (b, d2) = d1 `divMod` 64 in return [a+224, b+128, d2+128] | n < 1114112 = -- four bytes let (a, d1) = n `divMod` 262144 (b, d2) = d1 `divMod` 4096 (c, d3) = d2 `divMod` 64 in return [a+240, b+128, c+128, d3+128] | otherwise = fail "invalid character in UTF8" fromUTF8 :: Monad m => [Int] -> m [Int] fromUTF8 xs | null xs = return [] | otherwise = do (i, rest) <- f xs is <- fromUTF8 rest return (i:is) where f (a:rest) | a < 128 = -- one byte return (a, rest) f (a:b:rest) | a `between` (192, 223) = do -- two bytes unless (isHigh b) $ fail "invalid UTF8 character (two bytes)" return ((a-192)*64 + b-128, rest) f (a:b:c:rest) | a `between` (224, 239) = do -- three bytes unless (isHigh b && isHigh c) $ fail "invalid UTF8 character (three bytes)" return ((a-224)*4096 + (b-128)*64 + c-128, rest) f (a:b:c:d:rest) | a >= 240 && a < 248 = do -- four bytes let value = (a-240)*262144 + (b-128)*4096 + (c-128)*64 + d-128 unless (isHigh b && isHigh c && isHigh d && value <= 1114111) $ fail "invalid UTF8 character (four bytes)" return (value, rest) f _ = fail "invalid character in UTF8" isHigh :: Int -> Bool isHigh i = i `between` (128, 191) between :: Ord a => a -> (a, a) -> Bool between a (low, high) = low <= a && a <= high ------------------------------------------------------------------ -- Test encoding -- | QuickCheck internal encoding/decoding functions propEncoding :: Property propEncoding = forAll (sized gen) valid where gen n = replicateM n someChar someChar = chr <$> oneof -- To get a nice distribution over the number of bytes used -- in the encoding [ choose (0, 127), choose (128, 2047) , choose (2048, 65535), choose (65536, 1114111) ] valid :: String -> Bool valid xs = fromMaybe False $ do us <- encodeM xs bs <- decodeM us return (xs == bs)
ideas-edu/ideas
src/Ideas/Text/UTF8.hs
apache-2.0
4,117
0
21
1,073
1,310
694
616
75
5
{- | Module : Bio.Motions.Callback.Parser.Parser Description : Contains the definitions of various 'Callback' parsing-related types. License : Apache Stability : experimental Portability : unportable -} {-# LANGUAGE GADTs #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE FlexibleContexts #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} module Bio.Motions.Callback.Parser.Parser ( CallbackFrequency(..) , AtomType(..) , CallbackResult(..) , ParsedCallback(..) , ParsedCallbackWrapper(..) , MaxNConstraint , Both , Nat(..) , Expr(..) , Node(..) , EC , ToNode(..) , parseCallback) where import Bio.Motions.Common import Bio.Motions.Types import Bio.Motions.Utils.Common import Data.Maybe import GHC.Prim import Text.Parsec import Text.Parsec.Language (javaStyle) import qualified Text.Parsec.Token as P -- |Represents the frequency a callback has to be run data CallbackFrequency = EveryNFrames Int | EveryNAcceptedFrames Int -- |Represents the type of an atom data AtomType = AtomTypeBinder BinderType -- ^ A binder with the given 'BinderType' | AtomTypeBeadBindingTo BinderType -- ^ A bead with non-zero value for the given 'BinderType' -- in its 'EnergyVector' | AtomTypeAnyBinder -- ^ Any binder | AtomTypeAnyBead -- ^ Any bead -- |The return value of a callback data CallbackResult c n a where CallbackSum :: Expr c n a -> CallbackResult c n a CallbackProduct :: Expr c n a -> CallbackResult c n a CallbackList :: Expr c n a -> CallbackResult c n a -- |Represents a parsed callback data ParsedCallback c n a = ParsedCallback { callbackFrequency :: CallbackFrequency , callbackName :: String , callbackCondition :: Expr c n Bool -- ^The result should be computed only for tuples of atoms that satisfy the specified condition. , callbackResult :: CallbackResult c n a } -- |Natural numbers data Nat where Zero :: Nat Succ :: Nat -> Nat deriving (Eq, Show) -- |A wrapper around node argument identifiers. -- -- 'Node' 'n' keeps a natural number that is guaranteed to be less than 'n'. data Node (n :: Nat) where FirstNode :: Node ('Succ n) NextNode :: Node n -> Node ('Succ n) -- |Convert runtime natural 'Int's to type-level naturals. class ToNode (n :: Nat) where -- |Converts an non-negative 'Int' to a 'Node' if it is strictly less than 'n'. -- Fails otherwise. toNode :: Int -> Maybe (Node n) -- |No non-negative 'Int' is smaller than 'Zero' instance ToNode 'Zero where toNode _ = Nothing instance ToNode n => ToNode ('Succ n) where toNode 0 = Just FirstNode toNode n | n < 0 = Nothing toNode n = NextNode <$> toNode (n - 1) -- |A useful constraint. 'EC' 'c' 'n' '[a_0, a_1, ...] means: -- 'ToNode' 'n' and all of 'c' a_0, 'c' a_1, ... type EC (c :: * -> Constraint) (n :: Nat) (a :: [*]) = (ToNode n, All c a) -- |The AST of the callback DSL. -- -- 'c' is a Constraint on the types of all subexpressions. -- 'n' is the arity (i.e. the number of node arguments). -- 'a' is the type the expression evaluates to. data Expr c n a where EAnd :: (EC c n '[Bool]) => Expr c n Bool -> Expr c n Bool -> Expr c n Bool EOr :: (EC c n '[Bool]) => Expr c n Bool -> Expr c n Bool -> Expr c n Bool ENot :: (EC c n '[Bool]) => Expr c n Bool -> Expr c n Bool ELt :: (EC c n '[a, Bool], Ord a) => Expr c n a -> Expr c n a -> Expr c n Bool ELte :: (EC c n '[a, Bool], Ord a) => Expr c n a -> Expr c n a -> Expr c n Bool EGt :: (EC c n '[a, Bool], Ord a) => Expr c n a -> Expr c n a -> Expr c n Bool EGte :: (EC c n '[a, Bool], Ord a) => Expr c n a -> Expr c n a -> Expr c n Bool EEq :: (EC c n '[a, Bool], Eq a) => Expr c n a -> Expr c n a -> Expr c n Bool ENeq :: (EC c n '[a, Bool], Eq a) => Expr c n a -> Expr c n a -> Expr c n Bool EDist :: (EC c n '[Double]) => Node n -> Node n -> Expr c n Double EInt :: (EC c n '[a, Int], RealFrac a) => Expr c n a -> Expr c n Int EFlt :: (EC c n '[Int, Double]) => Expr c n Int -> Expr c n Double EGr :: (EC c n '[Double]) => Expr c n Double EAdd :: (EC c n '[a], Num a) => Expr c n a -> Expr c n a -> Expr c n a ESub :: (EC c n '[a], Num a) => Expr c n a -> Expr c n a -> Expr c n a EMul :: (EC c n '[a], Num a) => Expr c n a -> Expr c n a -> Expr c n a EDiv :: (EC c n '[a], Fractional a) => Expr c n a -> Expr c n a -> Expr c n a EIDiv :: (EC c n '[a], Integral a) => Expr c n a -> Expr c n a -> Expr c n a EMod :: (EC c n '[a], Integral a) => Expr c n a -> Expr c n a -> Expr c n a EMin :: (EC c n '[a], Ord a) => Expr c n a -> Expr c n a -> Expr c n a EMax :: (EC c n '[a], Ord a) => Expr c n a -> Expr c n a -> Expr c n a ELit :: (EC c n '[a]) => a -> Expr c n a EAtomIx :: (EC c n '[Int]) => Node n -> Expr c n Int EChainIx :: (EC c n '[Int]) => Node n -> Expr c n Int EChromoIx :: (EC c n '[Int]) => Node n -> Expr c n Int EBelongs :: (EC c n '[Bool]) => Node n -> AtomType -> Expr c n Bool EEnergy :: (EC c n '[Int]) => Node n -> Node n -> Expr c n Int -- |An alias, for simplicity. type Parser a = Parsec String () a -- |An existential type wrapper, hiding the arity and the result type. data ParsedCallbackWrapper c cn where ParsedCallbackWrapper :: (EC c n '[Int, Double, Bool, a], cn n) => ParsedCallback c n a -> ParsedCallbackWrapper c cn -- |Convert a term-level 'Int' into a type-level 'Nat' and perform an arbitrary computation -- parameterized by such a 'Nat'. Only 'Nat's less than 'limit' are considered (if the provided 'Int' -- is either negative or not less than 'limit', the function returns 'Nothing'). -- -- Since the computation to be performed (passed as a continuation) may require some constraint -- on 'm' to hold, 'tryNatsBelow' is parameterized by an additional 'Constraint' constructor -- @'c' :: 'Nat' -> 'Constraint'@. -- -- Because the correct 'm' is not known statically, 'tryNatsBelow' requires @'c' 'm'@ to hold -- for every 'm' less than 'limit'. tryNatsBelow :: forall c limit r. (TryNatsBelow c limit) => Proxy# '(limit, c) -> Int -- ^A runtime natural number. -> (forall (m :: Nat). c m => Proxy# m -> r) -- ^The continuation to be called when the correct @'m' :: 'Nat'@ equal to the 'Int' provided -- is found. -> Maybe r -- ^Its return value iff the 'Int' provided is non-negative and less than 'limit', -- Nothing otherwise. tryNatsBelow _ n f | n >= 0 = tryNatsBelow' (proxy# :: Proxy# '( 'Zero, limit, c)) n f | otherwise = Nothing -- | See 'tryNatsBelow'. -- -- This class performs one step of the 'Int'-to-'Nat' conversion, which is done by induction -- on 'limit'. -- -- It keeps the invariant: @n + 'acc' == result@, where n is the provided 'Int' and result is the -- target 'Nat', where @n < 'limit'@. class TryNatsBelow' c (limit :: Nat) (acc :: Nat) where tryNatsBelow' :: Proxy# '(acc, limit, c) -> Int -- ^ A non-negative integer -> (forall (m :: Nat). c m => Proxy# m -> x) -> Maybe x -- | Conversion should start with the accumulator equal to 'Zero' type TryNatsBelow c limit = TryNatsBelow' c limit 'Zero -- |@n < 'Zero'@ -- absurd. instance TryNatsBelow' c 'Zero acc where tryNatsBelow' _ _ _ = Nothing -- | @(n + 1) + 'acc' == n + ('Succ' 'acc')@ and @(n + 1) < ('Succ' 'limit')@ iff @n < 'limit'@, -- i.e. "move" one +1 from the term-level 'Int' to the type-level 'Nat'. instance (c acc, TryNatsBelow' c limit ('Succ acc)) => TryNatsBelow' c ('Succ limit) acc where tryNatsBelow' _ 0 run = Just $ run (proxy# :: Proxy# acc) tryNatsBelow' _ n run = tryNatsBelow' (proxy# :: Proxy# '( 'Succ acc, limit, c)) (n - 1) run -- |'EC' with its arguments flipped. class EC c n a => ECc c a n instance EC c n a => ECc c a n -- |@Both c1 c2 a@ iff @(c1 a, c2 a)@. class (c1 a, c2 a) => Both c1 c2 a instance (c1 a, c2 a) => Both c1 c2 a -- |A convenient wrapper. See 'parseCallback'. type MaxNConstraint c cn maxn = ( EC c maxn '[Int, Double, Bool] , TryNatsBelow (Both (ECc c '[Int, Double, Bool]) cn) maxn ) -- |Parses a callback with arity strictly less than 'maxn', whose internal types -- must satisfy the constraint 'c'. The callback is parsed as Int-returning where possible, -- Double-returning otherwise. Moreover, it is required that all all numbers between -- 'Zero' (incl.) and 'maxn' (excl.) satsify the constraint 'cn'. parseCallback :: forall c cn maxn. MaxNConstraint c cn maxn => Proxy# maxn -> Parser (ParsedCallbackWrapper c cn) parseCallback _ = do reserved "CALLBACK" name <- stringLiteral reserved "EVERY" freq <- (reserved "ACCEPTED" >> EveryNAcceptedFrames . fromIntegral <$> natural) <|> EveryNFrames . fromIntegral <$> natural reserved "NODES" arity <- fromIntegral <$> natural fromMaybe (fail $ "The arity " ++ show arity ++ " exceeds the bound") $ tryNatsBelow (proxy# :: Proxy# '(maxn, Both (ECc c '[Int, Double, Bool]) cn)) arity $ withArity name freq where -- | Parses a callback from the point the arity is known (at the type-level). withArity :: forall n. (EC c n '[Int, Double, Bool], cn n) => String -> CallbackFrequency -> Proxy# n -> Parser (ParsedCallbackWrapper c cn) withArity name freq _ = do reserved "WHERE" cond <- expr :: Parser (Expr c n Bool) reserved "COMPUTE" try (finish name freq cond (withArityAndType :: Parser (CallbackResult c n Int))) <|> finish name freq cond (withArityAndType :: Parser (CallbackResult c n Double)) withArityAndType :: (EC c n '[Int, Double, Bool, a], Parseable c n a) => Parser (CallbackResult c n a) withArityAndType = (reserved "SUM" >> CallbackSum <$> expr) <|> (reserved "PRODUCT" >> CallbackProduct <$> expr) <|> (reserved "LIST" >> CallbackList <$> expr) finish :: (EC c n '[a], cn n) => String -> CallbackFrequency -> Expr c n Bool -> Parser (CallbackResult c n a) -> Parser (ParsedCallbackWrapper c cn) finish name freq cond parser = do result <- parser pure $ ParsedCallbackWrapper ParsedCallback { callbackFrequency = freq , callbackName = name , callbackCondition = cond , callbackResult = result } -- |Parses an expression, where @expr ::= 'term' | 'term' 'addop' expr@ expr :: Parseable c n a => Parser (Expr c n a) expr = term `chainl1` addop -- |Parses a term, where @term ::= 'factor' | 'factor' 'mulop' term@ term :: Parseable c n a => Parser (Expr c n a) term = factor `chainl1` mulop -- |Parses a factor, where @factor ::= (expr) | 'atom'@. factor :: Parseable c n a => Parser (Expr c n a) factor = parens expr <|> atom -- |An auxiliary class providing common parsers. class EC c n '[a] => Parseable c n a where -- |Parses an atom. atom :: Parser (Expr c n a) -- |Parses an additive binary operator. addop :: Parser (Expr c n a -> Expr c n a -> Expr c n a) -- |Parses a multiplicative binary operator. mulop :: Parser (Expr c n a -> Expr c n a -> Expr c n a) -- |Integral expressions. instance EC c n '[Int, Double] => Parseable c n Int where addop = (reservedOp "+" >> pure EAdd) <|> (reservedOp "-" >> pure ESub) mulop = (reservedOp "*" >> pure EMul) <|> (reservedOp "//" >> pure EIDiv) <|> (reservedOp "%" >> pure EMod) atom = literal <|> (reserved "ATOM_INDEX" >> EAtomIx <$> parens constant) <|> (reserved "CHAIN_INDEX" >> EChainIx <$> parens constant) <|> (reserved "CHROMOSOME" >> EChromoIx <$> parens constant) <|> (reserved "INT" >> parens int) <|> (reserved "MIN" >> parens (EMin <$> expr <* comma <*> expr)) <|> (reserved "MAX" >> parens (EMax <$> expr <* comma <*> expr)) <|> (reserved "ENERGY" >> parens (EEnergy <$> constant <* comma <*> constant)) where int = try expr <|> EInt <$> (expr :: Parser (Expr c n Double)) -- |Floating-point expressions. instance EC c n '[Int, Double] => Parseable c n Double where addop = (reservedOp "+" >> pure EAdd) <|> (reservedOp "-" >> pure ESub) mulop = (reservedOp "*" >> pure EMul) <|> (reservedOp "/" >> pure EDiv) atom = literal <|> (reserved "GR" >> parens (pure EGr)) <|> (reserved "DIST" >> parens (EDist <$> constant <* comma <*> constant)) <|> (reserved "MIN" >> parens (EMin <$> expr <* comma <*> expr)) <|> (reserved "MAX" >> parens (EMax <$> expr <* comma <*> expr)) <|> (reserved "FLT" >> parens flt) where flt = try expr <|> EFlt <$> (expr :: Parser (Expr c n Int)) -- |Boolean expressions. instance EC c n '[Bool, Int, Double] => Parseable c n Bool where addop = reserved "OR" >> pure EOr mulop = reserved "AND" >> pure EAnd atom = (reserved "NOT" >> ENot <$> atom) <|> (reserved "BELONGS" >> parens (EBelongs <$> constant <* comma <*> constant)) <|> (try (cmp (expr :: Parser (Expr c n Int))) <|> cmp (expr :: Parser (Expr c n Double))) where cmp sub = do lhs <- sub op <- choice [ reservedOp "==" >> pure EEq , reservedOp "!=" >> pure ENeq , reservedOp "<" >> pure ELt , reservedOp "<=" >> pure ELte , reservedOp ">" >> pure EGt , reservedOp ">=" >> pure EGte ] op lhs <$> sub -- |A literal. literal :: (EC c n '[a], ParseConstant a) => Parser (Expr c n a) literal = ELit <$> constant -- |A helper class providing 'constant' parsers. class ParseConstant a where -- |Parses an immediate constant. constant :: Parser a -- |Integral constants. instance ParseConstant Int where constant = fromIntegral <$> integer instance ParseConstant BinderType where constant = BinderType <$> constant <|> (reserved "LAMIN" >> pure laminType) -- |Floating-point or integral constants. instance ParseConstant Double where constant = try float <|> fromIntegral <$> integer -- |Node (parameter) identifier constants. instance ToNode n => ParseConstant (Node n) where constant = do reserved "X" val <- constant case toNode val of Just node -> pure node Nothing -> fail $ "Out of bounds: " ++ show val -- |Atom class constants. instance ParseConstant AtomType where constant = (reserved "BEAD_BINDING_TO" >> AtomTypeBeadBindingTo <$> constant) <|> (reserved "BINDER" >> option AtomTypeAnyBinder (AtomTypeBinder <$> constant)) <|> (reserved "BEAD" >> pure AtomTypeAnyBead) -- |The language definition. dslDef :: P.LanguageDef st dslDef = javaStyle { P.reservedOpNames = ["+", "-", "/", "*", "%", "//", "<=", ">=", "==", "!=", "<", ">"] , P.reservedNames = ["AND", "OR", "NOT", "DIST", "INT", "GR", "ATOM_INDEX", "CHAIN_INDEX", "CHROMOSOME", "MIN", "MAX", "BELONGS", "X", "BEAD", "BINDER", "CALLBACK", "EVERY", "ACCEPTED", "NODES", "WHERE", "COMPUTE", "SUM", "PRODUCT", "LIST", "BEAD_BINDING_TO", "LAMIN", "ENERGY"] } -- |The token parser. P.TokenParser{..} = P.makeTokenParser dslDef
Motions/motions
src/Bio/Motions/Callback/Parser/Parser.hs
apache-2.0
16,231
0
18
4,523
4,905
2,589
2,316
-1
-1
----------------------------------------------------------------------------- -- | -- Module : FFICXX.Generate.QQ.Verbatim -- Copyright : (c) 2011-2013 Ian-Woo Kim -- -- License : BSD3 -- Maintainer : Ian-Woo Kim <[email protected]> -- Stability : experimental -- Portability : GHC -- ----------------------------------------------------------------------------- module FFICXX.Generate.QQ.Verbatim where import Language.Haskell.TH.Quote import Language.Haskell.TH.Lib verbatim :: QuasiQuoter verbatim = QuasiQuoter { quoteExp = litE . stringL -- , quotePat = litP . stringP }
Gabriel439/fficxx
lib/FFICXX/Generate/QQ/Verbatim.hs
bsd-2-clause
632
0
7
116
56
41
15
6
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QHttp.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:31 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Network.QHttp ( QqHttp(..) ,clearPendingRequests ,closeConnection ,currentDestinationDevice ,QcurrentRequest(..), QcurrentRequest_nf(..) ,currentSourceDevice ,hasPendingRequests ,qhead ,QlastResponse(..), QlastResponse_nf(..) ,Qpost(..) ,Qrequest(..) ,setSocket ,qHttp_delete ,qHttp_deleteLater ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Network.QHttp import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Network import Qtc.ClassTypes.Network instance QuserMethod (QHttp ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QHttp_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QHttp_userMethod" qtc_QHttp_userMethod :: Ptr (TQHttp a) -> CInt -> IO () instance QuserMethod (QHttpSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QHttp_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QHttp ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QHttp_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QHttp_userMethodVariant" qtc_QHttp_userMethodVariant :: Ptr (TQHttp a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QHttpSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QHttp_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj class QqHttp x1 where qHttp :: x1 -> IO (QHttp ()) instance QqHttp (()) where qHttp () = withQHttpResult $ qtc_QHttp foreign import ccall "qtc_QHttp" qtc_QHttp :: IO (Ptr (TQHttp ())) instance QqHttp ((String)) where qHttp (x1) = withQHttpResult $ withCWString x1 $ \cstr_x1 -> qtc_QHttp1 cstr_x1 foreign import ccall "qtc_QHttp1" qtc_QHttp1 :: CWString -> IO (Ptr (TQHttp ())) instance QqHttp ((QObject t1)) where qHttp (x1) = withQHttpResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QHttp2 cobj_x1 foreign import ccall "qtc_QHttp2" qtc_QHttp2 :: Ptr (TQObject t1) -> IO (Ptr (TQHttp ())) instance QqHttp ((String, Int)) where qHttp (x1, x2) = withQHttpResult $ withCWString x1 $ \cstr_x1 -> qtc_QHttp3 cstr_x1 (toCUShort x2) foreign import ccall "qtc_QHttp3" qtc_QHttp3 :: CWString -> CUShort -> IO (Ptr (TQHttp ())) instance QqHttp ((String, ConnectionMode)) where qHttp (x1, x2) = withQHttpResult $ withCWString x1 $ \cstr_x1 -> qtc_QHttp4 cstr_x1 (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QHttp4" qtc_QHttp4 :: CWString -> CLong -> IO (Ptr (TQHttp ())) instance QqHttp ((String, ConnectionMode, Int)) where qHttp (x1, x2, x3) = withQHttpResult $ withCWString x1 $ \cstr_x1 -> qtc_QHttp5 cstr_x1 (toCLong $ qEnum_toInt x2) (toCUShort x3) foreign import ccall "qtc_QHttp5" qtc_QHttp5 :: CWString -> CLong -> CUShort -> IO (Ptr (TQHttp ())) instance QqHttp ((String, Int, QObject t3)) where qHttp (x1, x2, x3) = withQHttpResult $ withCWString x1 $ \cstr_x1 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QHttp6 cstr_x1 (toCUShort x2) cobj_x3 foreign import ccall "qtc_QHttp6" qtc_QHttp6 :: CWString -> CUShort -> Ptr (TQObject t3) -> IO (Ptr (TQHttp ())) instance QqHttp ((String, ConnectionMode, Int, QObject t4)) where qHttp (x1, x2, x3, x4) = withQHttpResult $ withCWString x1 $ \cstr_x1 -> withObjectPtr x4 $ \cobj_x4 -> qtc_QHttp7 cstr_x1 (toCLong $ qEnum_toInt x2) (toCUShort x3) cobj_x4 foreign import ccall "qtc_QHttp7" qtc_QHttp7 :: CWString -> CLong -> CUShort -> Ptr (TQObject t4) -> IO (Ptr (TQHttp ())) instance Qabort (QHttp a) (()) (IO ()) where abort x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_abort cobj_x0 foreign import ccall "qtc_QHttp_abort" qtc_QHttp_abort :: Ptr (TQHttp a) -> IO () instance QbytesAvailable (QHttp a) (()) where bytesAvailable x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_bytesAvailable cobj_x0 foreign import ccall "qtc_QHttp_bytesAvailable" qtc_QHttp_bytesAvailable :: Ptr (TQHttp a) -> IO CLLong clearPendingRequests :: QHttp a -> (()) -> IO () clearPendingRequests x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_clearPendingRequests cobj_x0 foreign import ccall "qtc_QHttp_clearPendingRequests" qtc_QHttp_clearPendingRequests :: Ptr (TQHttp a) -> IO () instance Qclose (QHttp a) (()) (IO (Int)) where close x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_close cobj_x0 foreign import ccall "qtc_QHttp_close" qtc_QHttp_close :: Ptr (TQHttp a) -> IO CInt closeConnection :: QHttp a -> (()) -> IO (Int) closeConnection x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_closeConnection cobj_x0 foreign import ccall "qtc_QHttp_closeConnection" qtc_QHttp_closeConnection :: Ptr (TQHttp a) -> IO CInt currentDestinationDevice :: QHttp a -> (()) -> IO (QIODevice ()) currentDestinationDevice x0 () = withQIODeviceResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_currentDestinationDevice cobj_x0 foreign import ccall "qtc_QHttp_currentDestinationDevice" qtc_QHttp_currentDestinationDevice :: Ptr (TQHttp a) -> IO (Ptr (TQIODevice ())) instance QcurrentId (QHttp a) (()) where currentId x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_currentId cobj_x0 foreign import ccall "qtc_QHttp_currentId" qtc_QHttp_currentId :: Ptr (TQHttp a) -> IO CInt class QcurrentRequest x0 x1 where currentRequest :: x0 -> x1 -> IO (QHttpRequestHeader ()) class QcurrentRequest_nf x0 x1 where currentRequest_nf :: x0 -> x1 -> IO (QHttpRequestHeader ()) instance QcurrentRequest (QHttp ()) (()) where currentRequest x0 () = withQHttpRequestHeaderResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_currentRequest cobj_x0 foreign import ccall "qtc_QHttp_currentRequest" qtc_QHttp_currentRequest :: Ptr (TQHttp a) -> IO (Ptr (TQHttpRequestHeader ())) instance QcurrentRequest (QHttpSc a) (()) where currentRequest x0 () = withQHttpRequestHeaderResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_currentRequest cobj_x0 instance QcurrentRequest_nf (QHttp ()) (()) where currentRequest_nf x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_currentRequest cobj_x0 instance QcurrentRequest_nf (QHttpSc a) (()) where currentRequest_nf x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_currentRequest cobj_x0 currentSourceDevice :: QHttp a -> (()) -> IO (QIODevice ()) currentSourceDevice x0 () = withQIODeviceResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_currentSourceDevice cobj_x0 foreign import ccall "qtc_QHttp_currentSourceDevice" qtc_QHttp_currentSourceDevice :: Ptr (TQHttp a) -> IO (Ptr (TQIODevice ())) instance Qqerror (QHttp a) (()) (IO (QHttpError)) where qerror x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_error cobj_x0 foreign import ccall "qtc_QHttp_error" qtc_QHttp_error :: Ptr (TQHttp a) -> IO CLong instance QerrorString (QHttp a) (()) where errorString x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_errorString cobj_x0 foreign import ccall "qtc_QHttp_errorString" qtc_QHttp_errorString :: Ptr (TQHttp a) -> IO (Ptr (TQString ())) instance Qqget (QHttp a) ((String)) where qget x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QHttp_get cobj_x0 cstr_x1 foreign import ccall "qtc_QHttp_get" qtc_QHttp_get :: Ptr (TQHttp a) -> CWString -> IO CInt instance Qqget (QHttp a) ((String, QIODevice t2)) where qget x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QHttp_get1 cobj_x0 cstr_x1 cobj_x2 foreign import ccall "qtc_QHttp_get1" qtc_QHttp_get1 :: Ptr (TQHttp a) -> CWString -> Ptr (TQIODevice t2) -> IO CInt hasPendingRequests :: QHttp a -> (()) -> IO (Bool) hasPendingRequests x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_hasPendingRequests cobj_x0 foreign import ccall "qtc_QHttp_hasPendingRequests" qtc_QHttp_hasPendingRequests :: Ptr (TQHttp a) -> IO CBool qhead :: QHttp a -> ((String)) -> IO (Int) qhead x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QHttp_head cobj_x0 cstr_x1 foreign import ccall "qtc_QHttp_head" qtc_QHttp_head :: Ptr (TQHttp a) -> CWString -> IO CInt class QlastResponse x0 x1 where lastResponse :: x0 -> x1 -> IO (QHttpResponseHeader ()) class QlastResponse_nf x0 x1 where lastResponse_nf :: x0 -> x1 -> IO (QHttpResponseHeader ()) instance QlastResponse (QHttp ()) (()) where lastResponse x0 () = withQHttpResponseHeaderResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_lastResponse cobj_x0 foreign import ccall "qtc_QHttp_lastResponse" qtc_QHttp_lastResponse :: Ptr (TQHttp a) -> IO (Ptr (TQHttpResponseHeader ())) instance QlastResponse (QHttpSc a) (()) where lastResponse x0 () = withQHttpResponseHeaderResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_lastResponse cobj_x0 instance QlastResponse_nf (QHttp ()) (()) where lastResponse_nf x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_lastResponse cobj_x0 instance QlastResponse_nf (QHttpSc a) (()) where lastResponse_nf x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_lastResponse cobj_x0 class Qpost x1 where post :: QHttp a -> x1 -> IO (Int) instance Qpost ((String, QIODevice t2)) where post x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QHttp_post1 cobj_x0 cstr_x1 cobj_x2 foreign import ccall "qtc_QHttp_post1" qtc_QHttp_post1 :: Ptr (TQHttp a) -> CWString -> Ptr (TQIODevice t2) -> IO CInt instance Qpost ((String, QIODevice t2, QIODevice t3)) where post x0 (x1, x2, x3) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QHttp_post3 cobj_x0 cstr_x1 cobj_x2 cobj_x3 foreign import ccall "qtc_QHttp_post3" qtc_QHttp_post3 :: Ptr (TQHttp a) -> CWString -> Ptr (TQIODevice t2) -> Ptr (TQIODevice t3) -> IO CInt instance Qpost ((String, String)) where post x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> withCWString x2 $ \cstr_x2 -> qtc_QHttp_post cobj_x0 cstr_x1 cstr_x2 foreign import ccall "qtc_QHttp_post" qtc_QHttp_post :: Ptr (TQHttp a) -> CWString -> CWString -> IO CInt instance Qpost ((String, String, QIODevice t3)) where post x0 (x1, x2, x3) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> withCWString x2 $ \cstr_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QHttp_post2 cobj_x0 cstr_x1 cstr_x2 cobj_x3 foreign import ccall "qtc_QHttp_post2" qtc_QHttp_post2 :: Ptr (TQHttp a) -> CWString -> CWString -> Ptr (TQIODevice t3) -> IO CInt instance QreadAll (QHttp a) (()) where readAll x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_readAll cobj_x0 foreign import ccall "qtc_QHttp_readAll" qtc_QHttp_readAll :: Ptr (TQHttp a) -> IO (Ptr (TQString ())) class Qrequest x1 where request :: QHttp a -> x1 -> IO (Int) instance Qrequest ((QHttpRequestHeader t1)) where request x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHttp_request cobj_x0 cobj_x1 foreign import ccall "qtc_QHttp_request" qtc_QHttp_request :: Ptr (TQHttp a) -> Ptr (TQHttpRequestHeader t1) -> IO CInt instance Qrequest ((QHttpRequestHeader t1, QIODevice t2)) where request x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QHttp_request2 cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QHttp_request2" qtc_QHttp_request2 :: Ptr (TQHttp a) -> Ptr (TQHttpRequestHeader t1) -> Ptr (TQIODevice t2) -> IO CInt instance Qrequest ((QHttpRequestHeader t1, QIODevice t2, QIODevice t3)) where request x0 (x1, x2, x3) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QHttp_request4 cobj_x0 cobj_x1 cobj_x2 cobj_x3 foreign import ccall "qtc_QHttp_request4" qtc_QHttp_request4 :: Ptr (TQHttp a) -> Ptr (TQHttpRequestHeader t1) -> Ptr (TQIODevice t2) -> Ptr (TQIODevice t3) -> IO CInt instance Qrequest ((QHttpRequestHeader t1, String)) where request x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withCWString x2 $ \cstr_x2 -> qtc_QHttp_request1 cobj_x0 cobj_x1 cstr_x2 foreign import ccall "qtc_QHttp_request1" qtc_QHttp_request1 :: Ptr (TQHttp a) -> Ptr (TQHttpRequestHeader t1) -> CWString -> IO CInt instance Qrequest ((QHttpRequestHeader t1, String, QIODevice t3)) where request x0 (x1, x2, x3) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withCWString x2 $ \cstr_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QHttp_request3 cobj_x0 cobj_x1 cstr_x2 cobj_x3 foreign import ccall "qtc_QHttp_request3" qtc_QHttp_request3 :: Ptr (TQHttp a) -> Ptr (TQHttpRequestHeader t1) -> CWString -> Ptr (TQIODevice t3) -> IO CInt instance QsetHost (QHttp a) ((String)) (IO (Int)) where setHost x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QHttp_setHost cobj_x0 cstr_x1 foreign import ccall "qtc_QHttp_setHost" qtc_QHttp_setHost :: Ptr (TQHttp a) -> CWString -> IO CInt instance QsetHost (QHttp a) ((String, ConnectionMode)) (IO (Int)) where setHost x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QHttp_setHost2 cobj_x0 cstr_x1 (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QHttp_setHost2" qtc_QHttp_setHost2 :: Ptr (TQHttp a) -> CWString -> CLong -> IO CInt instance QsetHost (QHttp a) ((String, ConnectionMode, Int)) (IO (Int)) where setHost x0 (x1, x2, x3) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QHttp_setHost3 cobj_x0 cstr_x1 (toCLong $ qEnum_toInt x2) (toCUShort x3) foreign import ccall "qtc_QHttp_setHost3" qtc_QHttp_setHost3 :: Ptr (TQHttp a) -> CWString -> CLong -> CUShort -> IO CInt instance QsetHost (QHttp a) ((String, Int)) (IO (Int)) where setHost x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QHttp_setHost1 cobj_x0 cstr_x1 (toCUShort x2) foreign import ccall "qtc_QHttp_setHost1" qtc_QHttp_setHost1 :: Ptr (TQHttp a) -> CWString -> CUShort -> IO CInt instance QsetProxy (QHttp a) ((QNetworkProxy t1)) (IO (Int)) where setProxy x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHttp_setProxy cobj_x0 cobj_x1 foreign import ccall "qtc_QHttp_setProxy" qtc_QHttp_setProxy :: Ptr (TQHttp a) -> Ptr (TQNetworkProxy t1) -> IO CInt instance QsetProxy (QHttp a) ((String, Int)) (IO (Int)) where setProxy x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QHttp_setProxy1 cobj_x0 cstr_x1 (toCInt x2) foreign import ccall "qtc_QHttp_setProxy1" qtc_QHttp_setProxy1 :: Ptr (TQHttp a) -> CWString -> CInt -> IO CInt instance QsetProxy (QHttp a) ((String, Int, String)) (IO (Int)) where setProxy x0 (x1, x2, x3) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> withCWString x3 $ \cstr_x3 -> qtc_QHttp_setProxy2 cobj_x0 cstr_x1 (toCInt x2) cstr_x3 foreign import ccall "qtc_QHttp_setProxy2" qtc_QHttp_setProxy2 :: Ptr (TQHttp a) -> CWString -> CInt -> CWString -> IO CInt instance QsetProxy (QHttp a) ((String, Int, String, String)) (IO (Int)) where setProxy x0 (x1, x2, x3, x4) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> withCWString x3 $ \cstr_x3 -> withCWString x4 $ \cstr_x4 -> qtc_QHttp_setProxy3 cobj_x0 cstr_x1 (toCInt x2) cstr_x3 cstr_x4 foreign import ccall "qtc_QHttp_setProxy3" qtc_QHttp_setProxy3 :: Ptr (TQHttp a) -> CWString -> CInt -> CWString -> CWString -> IO CInt setSocket :: QHttp a -> ((QTcpSocket t1)) -> IO (Int) setSocket x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHttp_setSocket cobj_x0 cobj_x1 foreign import ccall "qtc_QHttp_setSocket" qtc_QHttp_setSocket :: Ptr (TQHttp a) -> Ptr (TQTcpSocket t1) -> IO CInt instance QsetUser (QHttp a) ((String)) (IO (Int)) where setUser x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QHttp_setUser cobj_x0 cstr_x1 foreign import ccall "qtc_QHttp_setUser" qtc_QHttp_setUser :: Ptr (TQHttp a) -> CWString -> IO CInt instance QsetUser (QHttp a) ((String, String)) (IO (Int)) where setUser x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> withCWString x2 $ \cstr_x2 -> qtc_QHttp_setUser1 cobj_x0 cstr_x1 cstr_x2 foreign import ccall "qtc_QHttp_setUser1" qtc_QHttp_setUser1 :: Ptr (TQHttp a) -> CWString -> CWString -> IO CInt instance Qstate (QHttp a) (()) (IO (QHttpState)) where state x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_state cobj_x0 foreign import ccall "qtc_QHttp_state" qtc_QHttp_state :: Ptr (TQHttp a) -> IO CLong qHttp_delete :: QHttp a -> IO () qHttp_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_delete cobj_x0 foreign import ccall "qtc_QHttp_delete" qtc_QHttp_delete :: Ptr (TQHttp a) -> IO () qHttp_deleteLater :: QHttp a -> IO () qHttp_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_deleteLater cobj_x0 foreign import ccall "qtc_QHttp_deleteLater" qtc_QHttp_deleteLater :: Ptr (TQHttp a) -> IO () instance QchildEvent (QHttp ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHttp_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QHttp_childEvent" qtc_QHttp_childEvent :: Ptr (TQHttp a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QHttpSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHttp_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QHttp ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QHttp_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QHttp_connectNotify" qtc_QHttp_connectNotify :: Ptr (TQHttp a) -> CWString -> IO () instance QconnectNotify (QHttpSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QHttp_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QHttp ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHttp_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QHttp_customEvent" qtc_QHttp_customEvent :: Ptr (TQHttp a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QHttpSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHttp_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QHttp ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QHttp_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QHttp_disconnectNotify" qtc_QHttp_disconnectNotify :: Ptr (TQHttp a) -> CWString -> IO () instance QdisconnectNotify (QHttpSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QHttp_disconnectNotify cobj_x0 cstr_x1 instance Qevent (QHttp ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHttp_event_h cobj_x0 cobj_x1 foreign import ccall "qtc_QHttp_event_h" qtc_QHttp_event_h :: Ptr (TQHttp a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QHttpSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHttp_event_h cobj_x0 cobj_x1 instance QeventFilter (QHttp ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QHttp_eventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QHttp_eventFilter_h" qtc_QHttp_eventFilter_h :: Ptr (TQHttp a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QHttpSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QHttp_eventFilter_h cobj_x0 cobj_x1 cobj_x2 instance Qreceivers (QHttp ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QHttp_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QHttp_receivers" qtc_QHttp_receivers :: Ptr (TQHttp a) -> CWString -> IO CInt instance Qreceivers (QHttpSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QHttp_receivers cobj_x0 cstr_x1 instance Qsender (QHttp ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_sender cobj_x0 foreign import ccall "qtc_QHttp_sender" qtc_QHttp_sender :: Ptr (TQHttp a) -> IO (Ptr (TQObject ())) instance Qsender (QHttpSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHttp_sender cobj_x0 instance QtimerEvent (QHttp ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHttp_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QHttp_timerEvent" qtc_QHttp_timerEvent :: Ptr (TQHttp a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QHttpSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHttp_timerEvent cobj_x0 cobj_x1
keera-studios/hsQt
Qtc/Network/QHttp.hs
bsd-2-clause
23,294
0
16
4,262
8,143
4,157
3,986
-1
-1
{-# LANGUAGE KindSignatures, TypeFamilies, ConstraintKinds, PolyKinds, MultiParamTypeClasses #-} module Control.Effect where import Prelude hiding (Monad(..)) import GHC.Exts ( Constraint ) {-| Specifies "parametric effect monads" which are essentially monads but annotated by a type-level monoid formed by 'Plus' and 'Unit' -} class Effect (m :: k -> * -> *) where {-| Effect of a trivially effectful computation |-} type Unit m :: k {-| Cominbing effects of two subcomputations |-} type Plus m (f :: k) (g :: k) :: k {-| 'Inv' provides a way to give instances of 'Effect' their own constraints for '>>=' -} type Inv m (f :: k) (g :: k) :: Constraint type Inv m f g = () {-| Effect-parameterised version of 'return'. Annotated with the 'Unit m' effect, denoting pure compuation -} return :: a -> m (Unit m) a {-| Effect-parameterise version of '>>=' (bind). Combines two effect annotations 'f' and 'g' on its parameter computations into 'Plus' -} (>>=) :: (Inv m f g) => m f a -> (a -> m g b) -> m (Plus m f g) b (>>) :: (Inv m f g) => m f a -> m g b -> m (Plus m f g) b x >> y = x >>= (\_ -> y) fail = undefined {-| Specifies subeffecting behaviour -} class Subeffect (m :: k -> * -> *) f g where sub :: m f a -> m g a
dorchard/effect-monad
src/Control/Effect.hs
bsd-2-clause
1,298
0
12
318
331
188
143
16
1
{-# OPTIONS_GHC -fno-warn-orphans #-} module Application ( makeApplication , getApplicationDev , makeFoundation ) where import Import import Settings import Yesod.Auth import Yesod.Fay import Yesod.Default.Config import Yesod.Default.Main import Yesod.Default.Handlers import Network.Wai.Middleware.RequestLogger (logStdout, logStdoutDev) import qualified Database.Persist.Store import Database.Persist.GenericSql (runMigration) import Network.HTTP.Conduit (newManager, def) -- Import all relevant handler modules here. -- Don't forget to add new modules to your cabal file! import Handler.Home import Handler.IncomingList import Handler.Incoming import Handler.Image import Handler.PostList import Handler.Post import Handler.ToPostList import Handler.UnPost import Handler.Fay -- This line actually creates our YesodDispatch instance. It is the second half -- of the call to mkYesodData which occurs in Foundation.hs. Please see the -- comments there for more details. mkYesodDispatch "App" resourcesApp -- This function allocates resources (such as a database connection pool), -- performs initialization and creates a WAI application. This is also the -- place to put your migrate statements to have automatic database -- migrations handled by Yesod. makeApplication :: AppConfig DefaultEnv Extra -> IO Application makeApplication conf = do foundation <- makeFoundation conf app <- toWaiAppPlain foundation return $ logWare app where logWare = if development then logStdoutDev else logStdout makeFoundation :: AppConfig DefaultEnv Extra -> IO App makeFoundation conf = do manager <- newManager def s <- staticSite dbconf <- withYamlEnvironment "config/postgresql.yml" (appEnv conf) Database.Persist.Store.loadConfig >>= Database.Persist.Store.applyEnv p <- Database.Persist.Store.createPoolConfig (dbconf :: Settings.PersistConfig) Database.Persist.Store.runPool dbconf (runMigration migrateAll) p return $ App conf s p manager dbconf onCommand -- for yesod devel getApplicationDev :: IO (Int, Application) getApplicationDev = defaultDevelApp loader makeApplication where loader = loadConfig (configSettings Development) { csParseExtra = parseExtra }
snoyberg/photosorter
Application.hs
bsd-2-clause
2,306
0
11
409
414
230
184
-1
-1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Main where import Prelude () import MyLittlePrelude import Control.Monad (forM_, when) import Control.Monad.Except (runExceptT) import Data.Monoid ((<>)) import qualified Data.Set as Set import qualified Data.Text as Text import System.FilePath ((</>)) import System.Directory (doesDirectoryExist, removeDirectoryRecursive, setCurrentDirectory, getCurrentDirectory, withCurrentDirectory) import System.IO.Temp (withSystemTempDirectory) import System.Environment (lookupEnv) import System.Exit (ExitCode (..)) import Web.HttpApiData import Network.HTTP.Client (newManager) import Network.HTTP.Client.TLS (tlsManagerSettings) import Inspection.Data import Inspection.Data.TaskQueue import Inspection.API.BuildMatrix import qualified Inspection.BuildLogStorage as BuildLogStorage import Bower import Client import Compiler data Query = Query { qCompiler :: Maybe Compiler , qCompilerVersion :: Maybe (ReleaseTag Compiler) , qPackage :: Maybe PackageName , qPackageVersion :: Maybe (ReleaseTag Package) } deriving (Show) toString :: (ToHttpApiData a) => a -> String toString = Text.unpack . toUrlPiece getQuery :: IO Query getQuery = Query <$> lookupFlag "COMPILER" <*> lookupFlag "COMPILER_VERSION" <*> lookupFlag "PACKAGE_NAME" <*> lookupFlag "PACKAGE_VERSION" lookupFlag :: FromHttpApiData a => String -> IO (Maybe a) lookupFlag name = (either (const Nothing) Just . parseUrlPiece . Text.pack =<<) <$> lookupEnv name main :: IO () main = do manager <- newManager tlsManagerSettings Query{..} <- getQuery authToken <- lookupFlag "AUTH_TOKEN" Right (TaskQueue tasks) <- runExceptT $ getTasks manager qCompiler qCompilerVersion qPackage qPackageVersion False putStrLn ("Got " <> show (length tasks) <> " tasks.") forM_ (zip [1..] (Set.toList tasks)) $ \(index :: Int, (Task{ taskBuildConfig = BuildConfig { buildConfigCompiler = compiler , buildConfigCompilerRelease = compilerVersion } , taskTarget = Target packageName packageVersion })) -> do putStrLn $ concat [ "[", show index, "/", show (length tasks), "]: " , toString packageName, "-", toString packageVersion, " using " , toString compiler, "-", toString compilerVersion ] psc <- fromMaybe (error " Failed to fetch the compiler.") <$> getPsc compilerVersion withSystemTempDirectory "purescript-inspection-build" $ \tmpDir -> withCurrentDirectory tmpDir $ do dir <- getCurrentDirectory bowerExitCode <- install dir packageName packageVersion case bowerExitCode of ExitFailure _code -> do putStrLn " Reporting: bower failure" runExceptT $ addBuildResult manager authToken packageName packageVersion compiler compilerVersion (AddBuildResultBody Failure mempty) ExitSuccess -> do buildResultBody <- runBuild dir psc "bower_components/purescript-*/src/**/*.purs" "bower_components/purescript-*/src/**/*.js" putStrLn (" Reporting: " <> show (buildResult buildResultBody)) runExceptT $ addBuildResult manager authToken packageName packageVersion compiler compilerVersion buildResultBody
zudov/purescript-inspection
worker/Main.hs
bsd-3-clause
4,187
0
26
1,495
841
447
394
85
2
{-# OPTIONS_GHC -fno-warn-orphans #-} module Test.Util where import Control.Applicative import Data.Vector (Vector) import qualified Data.Vector as Vector import Test.QuickCheck import Data.Patch nonEmpty :: Vector a -> Bool nonEmpty = (>0) . Vector.length editsTo :: Arbitrary a => Vector a -> Gen (Edit a) editsTo v = do i <- choose (0, Vector.length v -1) c <- elements [const (Insert i), \o _ -> Delete i o, Replace i] x <- arbitrary return $ c (v Vector.! i) x patchesFrom' :: (Eq a, Arbitrary a) => Vector a -> Gen (Patch a) patchesFrom' v | Vector.length v > 0 = fromList <$> listOf (editsTo v) patchesFrom' _ | otherwise = fromList <$> listOf (Insert 0 <$> arbitrary) patchesFrom :: Vector Int -> Gen (Patch Int) patchesFrom = patchesFrom' divergingPatchesFrom :: Vector Int -> Gen (Patch Int, Patch Int) divergingPatchesFrom v = (,) <$> patchesFrom v <*> patchesFrom v historyFrom :: Vector Int -> Int -> Gen [Patch Int] historyFrom _ 0 = return [] historyFrom d m = do p <- patchesFrom d r <- historyFrom (apply p d) $ m - 1 return (p:r) instance Arbitrary a => Arbitrary (Vector a) where arbitrary = Vector.fromList <$> listOf arbitrary
liamoc/patches-vector
test/Test/Util.hs
bsd-3-clause
1,224
0
12
274
514
253
261
30
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} module Instrument.Worker ( initWorkerCSV, initWorkerCSV', initWorkerGraphite, initWorkerGraphite', work, initWorker, AggProcess (..), -- * Configuring agg processes AggProcessConfig (..), standardQuantiles, noQuantiles, quantileMap, defAggProcessConfig, -- * Exported for testing expandDims, ) where ------------------------------------------------------------------------------- import Control.Error import Control.Monad import Control.Monad.IO.Class import qualified Data.ByteString.Char8 as B import Data.CSV.Conduit import Data.Conduit (runConduit, (.|)) import qualified Data.Conduit.List as CL import Data.Default import qualified Data.Map as M import qualified Data.SafeCopy as SC import Data.Semigroup as Semigroup import Data.Serialize import qualified Data.Set as Set import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Data.Vector.Unboxed as V import Database.Redis as R hiding (decode) ------------------------------------------------------------------------------- import Instrument.Client ( packetsKey, stripTimerPrefix, timerMetricName, ) import qualified Instrument.Measurement as TM import Instrument.Types import Instrument.Utils import Network.Socket as N import qualified Statistics.Quantile as Q import Statistics.Sample import System.IO import System.Posix ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- | A CSV backend to store aggregation results in a CSV initWorkerCSV :: ConnectInfo -> -- | Target file name FilePath -> -- | Aggregation period / flush interval in seconds Int -> AggProcessConfig -> IO () initWorkerCSV conn fp n cfg = initWorker "CSV Worker" conn n =<< initWorkerCSV' fp cfg ------------------------------------------------------------------------------- -- | Create an AggProcess that dumps to CSV. Use this to compose with -- other AggProcesses initWorkerCSV' :: -- | Target file name FilePath -> AggProcessConfig -> IO AggProcess initWorkerCSV' fp cfg = do !res <- fileExist fp !h <- openFile fp AppendMode hSetBuffering h LineBuffering unless res $ T.hPutStrLn h $ rowToStr defCSVSettings . M.keys $ aggToCSV def return $ putAggregateCSV h cfg ------------------------------------------------------------------------------- -- | Initialize a Graphite backend initWorkerGraphite :: -- | Redis connection ConnectInfo -> -- | Aggregation period / flush interval in seconds Int -> -- | Graphite host HostName -> -- | Graphite port Int -> AggProcessConfig -> IO () initWorkerGraphite conn n server port cfg = initWorker "Graphite Worker" conn n =<< initWorkerGraphite' server port cfg ------------------------------------------------------------------------------- -- | Crete an AggProcess that dumps to graphite. Use this to compose -- with other AggProcesses initWorkerGraphite' :: -- | Graphite host HostName -> -- | Graphite port Int -> AggProcessConfig -> IO AggProcess initWorkerGraphite' server port cfg = do addr <- resolve server (fromIntegral port) sock <- open addr h <- N.socketToHandle sock ReadWriteMode hSetBuffering h LineBuffering return $ putAggregateGraphite h cfg where portNumberToServiceName :: N.PortNumber -> N.ServiceName portNumberToServiceName = show resolve host portNumber = do let hints = N.defaultHints {N.addrSocketType = N.Stream} addr : _ <- N.getAddrInfo (Just hints) (Just host) (Just (portNumberToServiceName portNumber)) return addr open addr = do sock <- N.socket (N.addrFamily addr) (N.addrSocketType addr) (N.addrProtocol addr) N.connect sock (N.addrAddress addr) return sock ------------------------------------------------------------------------------- -- | Generic utility for making worker backends. Will retry -- indefinitely with exponential backoff. initWorker :: String -> ConnectInfo -> Int -> AggProcess -> IO () initWorker wname conn n f = do p <- createInstrumentPool conn indefinitely' $ work p n f where indefinitely' = indefinitely wname (seconds n) ------------------------------------------------------------------------------- -- | Extract statistics out of the given sample for this flush period mkStats :: Set.Set Quantile -> Sample -> Stats mkStats qs s = Stats { smean = mean s, ssum = V.sum s, scount = V.length s, smax = V.maximum s, smin = V.minimum s, srange = range s, sstdev = stdDev s, sskewness = skewness s, skurtosis = kurtosis s, squantiles = quantiles } where quantiles = M.fromList (mkQ 100 . quantile <$> Set.toList qs) mkQ mx i = (i, Q.weightedAvg i mx s) ------------------------------------------------------------------------------- -- | Go over all pending stats buffers in redis. work :: R.Connection -> Int -> AggProcess -> IO () work r n f = runRedis r $ do dbg "entered work block" estimate <- either (const 0) id <$> scard packetsKey runConduit $ CL.unfoldM nextKey estimate .| CL.mapM_ (processSampler n f) where nextKey estRemaining | estRemaining > 0 = do mk <- spop packetsKey return $ case mk of Right (Just k) -> Just (k, estRemaining - 1) _ -> Nothing | otherwise = return Nothing ------------------------------------------------------------------------------- processSampler :: -- | Flush interval - determines resolution Int -> -- | What to do with aggregation results AggProcess -> -- | Redis buffer for this metric B.ByteString -> Redis () processSampler n (AggProcess cfg f) k = do packets <- popLAll k case packets of [] -> return () _ -> do let nm = spName . head $ packets -- with and without timer prefix qs = quantilesFn (stripTimerPrefix nm) <> quantilesFn (timerMetricName nm) byDims :: M.Map Dimensions [SubmissionPacket] byDims = collect packets spDimensions id mkAgg xs = case spPayload $ head xs of Samples _ -> AggStats . mkStats qs . V.fromList . concatMap (unSamples . spPayload) $ xs Counter _ -> AggCount . sum . map (unCounter . spPayload) $ xs t <- (fromIntegral . (* n) . (`div` n) . round) `liftM` liftIO TM.getTime let aggs = map mkDimsAgg $ M.toList $ expandDims $ byDims mkDimsAgg (dims, ps) = Aggregated t nm (mkAgg ps) dims mapM_ f aggs return () where quantilesFn = metricQuantiles cfg ------------------------------------------------------------------------------- -- | Take a map of packets by dimensions and *add* aggregations of the -- existing dims that isolate each distinct dimension/dimensionvalue -- pair + one more entry with an empty dimension set that aggregates -- the whole thing. -- worked example: -- -- Given: -- { {d1=>d1v1,d2=>d2v1} => p1 -- , {d1=>d1v1,d2=>d2v2} => p2 -- } -- Produces: -- { {d1=>d1v1,d2=>d2v1} => p1 -- , {d1=>d1v1,d2=>d2v2} => p2 -- , {d1=>d1v1} => p1 + p2 -- , {d2=>d2v1} => p1 -- , {d2=>d2v2} => p2 -- , {} => p1 + p2 -- } expandDims :: forall packets. (Monoid packets, Eq packets) => M.Map Dimensions packets -> M.Map Dimensions packets expandDims m = -- left-biased so technically if we have anything occupying the aggregated spots, leave them be m <> additions <> fullAggregation where distinctPairs :: Set.Set (DimensionName, DimensionValue) distinctPairs = Set.fromList (mconcat (M.toList <$> M.keys m)) additions = foldMap mkIsolatedMap distinctPairs mkIsolatedMap :: (DimensionName, DimensionValue) -> M.Map Dimensions packets mkIsolatedMap dPair = let matches = snd <$> filter ((== dPair) . fst) mFlat in if matches == mempty then mempty else M.singleton (uncurry M.singleton dPair) (mconcat matches) mFlat :: [((DimensionName, DimensionValue), packets)] mFlat = [ ((dn, dv), packets) | (dimensionsMap, packets) <- M.toList m, (dn, dv) <- M.toList dimensionsMap ] -- All packets across any combination of dimensions fullAggregation = M.singleton mempty (mconcat (M.elems m)) -- | A function that does something with the aggregation results. Can -- implement multiple backends simply using this. Note that Semigroup and Monoid instances are provided for defaulting and combining agg processes. data AggProcess = AggProcess { apConfig :: AggProcessConfig, apProc :: Aggregated -> Redis () } instance Semigroup.Semigroup AggProcess where (AggProcess cfg1 prc1) <> (AggProcess cfg2 prc2) = AggProcess (cfg1 <> cfg2) (\agg -> prc1 agg >> prc2 agg) instance Monoid AggProcess where mempty = AggProcess mempty (const (pure ())) mappend = (<>) ------------------------------------------------------------------------------- -- | General configuration for agg processes. Defaulted with 'def', -- 'defAggProcessConfig', and 'mempty'. Configurations can be combined -- with (<>) from Monoid or Semigroup. data AggProcessConfig = AggProcessConfig { -- | What quantiles should we calculate for any given metric, if -- any? We offer some common patterns for this in 'quantileMap', -- 'standardQuantiles', and 'noQuantiles'. metricQuantiles :: MetricName -> Set.Set Quantile } instance Semigroup AggProcessConfig where AggProcessConfig f1 <> AggProcessConfig f2 = let f3 = f1 <> f2 in AggProcessConfig f3 instance Monoid AggProcessConfig where mempty = AggProcessConfig mempty mappend = (<>) -- | Uses 'standardQuantiles'. defAggProcessConfig :: AggProcessConfig defAggProcessConfig = AggProcessConfig standardQuantiles instance Default AggProcessConfig where def = defAggProcessConfig -- | Regardless of metric, produce no quantiles. noQuantiles :: MetricName -> Set.Set Quantile noQuantiles = const mempty -- | This is usually a good, comprehensive default. Produces quantiles -- 10,20,30,40,50,60,70,80,90,99. *Note:* for some backends like -- cloudwatch, each quantile produces an additional metric, so you -- should probably consider using something more limited than this. standardQuantiles :: MetricName -> Set.Set Quantile standardQuantiles _ = Set.fromList [Q 10, Q 20, Q 30, Q 40, Q 50, Q 60, Q 70, Q 80, Q 90, Q 99] -- | If you have a fixed set of metric names, this is often a -- convenient way to express quantiles-per-metric. quantileMap :: M.Map MetricName (Set.Set Quantile) -> -- | What to return on miss Set.Set Quantile -> (MetricName -> Set.Set Quantile) quantileMap m qdef mn = fromMaybe qdef (M.lookup mn m) ------------------------------------------------------------------------------- -- | Store aggregation results in a CSV file putAggregateCSV :: Handle -> AggProcessConfig -> AggProcess putAggregateCSV h cfg = AggProcess cfg $ \agg -> let d = rowToStr defCSVSettings $ aggToCSV agg in liftIO $ T.hPutStrLn h d typePrefix :: AggPayload -> T.Text typePrefix AggStats {} = "samples" typePrefix AggCount {} = "counts" ------------------------------------------------------------------------------- -- | Push data into a Graphite database using the plaintext protocol putAggregateGraphite :: Handle -> AggProcessConfig -> AggProcess putAggregateGraphite h cfg = AggProcess cfg $ \agg -> let (ss, ts) = mkStatsFields agg -- Expand dimensions into one datum per dimension pair as the group mkLines (m, val) = for (M.toList (aggDimensions agg)) $ \(DimensionName dimName, DimensionValue dimVal) -> T.concat [ "inst.", typePrefix (aggPayload agg), ".", T.pack (metricName (aggName agg)), ".", m, ".", dimName, ".", dimVal, " ", val, " ", ts ] in liftIO $ mapM_ (mapM_ (T.hPutStrLn h) . mkLines) ss ------------------------------------------------------------------------------- -- | Pop all keys in a redis List popLAll :: (Serialize a, SC.SafeCopy a) => B.ByteString -> Redis [a] popLAll k = do res <- popLMany k 100 case res of [] -> return res _ -> (res ++) `liftM` popLAll k ------------------------------------------------------------------------------- -- | Pop up to N items from a queue. It will pop from left and preserve order. popLMany :: (Serialize a, SC.SafeCopy a) => B.ByteString -> Int -> Redis [a] popLMany k n = do res <- replicateM n pop case sequence res of Left _ -> return [] Right xs -> return $ mapMaybe conv $ catMaybes xs where pop = R.lpop k conv x = hush $ decodeCompress x ------------------------------------------------------------------------------- -- | Need to pull in a debugging library here. dbg :: (Monad m) => String -> m () dbg _ = return () -- ------------------------------------------------------------------------------ -- dbg :: (MonadIO m) => String -> m () -- dbg s = debug $ "Instrument.Worker: " ++ s ------------------------------------------------------------------------------- -- | Expand count aggregation to have the full columns aggToCSV :: Aggregated -> M.Map T.Text T.Text aggToCSV agg@Aggregated {..} = els <> defFields <> dimFields where els :: MapRow T.Text els = M.fromList $ ("metric", T.pack (metricName aggName)) : ("timestamp", ts) : fields (fields, ts) = mkStatsFields agg defFields = M.fromList $ fst $ mkStatsFields $ agg {aggPayload = (AggStats def)} dimFields = M.fromList [(k, v) | (DimensionName k, DimensionValue v) <- M.toList aggDimensions] ------------------------------------------------------------------------------- -- | Get agg results into a form ready to be output mkStatsFields :: Aggregated -> ([(T.Text, T.Text)], T.Text) mkStatsFields Aggregated {..} = (els, ts) where els = case aggPayload of AggStats Stats {..} -> [ ("mean", formatDecimal 6 False smean), ("count", showT scount), ("max", formatDecimal 6 False smax), ("min", formatDecimal 6 False smin), ("srange", formatDecimal 6 False srange), ("stdDev", formatDecimal 6 False sstdev), ("sum", formatDecimal 6 False ssum), ("skewness", formatDecimal 6 False sskewness), ("kurtosis", formatDecimal 6 False skurtosis) ] ++ (map mkQ $ M.toList squantiles) AggCount i -> [("count", showT i)] mkQ (k, v) = (T.concat ["percentile_", showT k], formatDecimal 6 False v) ts = formatInt aggTS
Soostone/instrument
instrument/src/Instrument/Worker.hs
bsd-3-clause
15,064
0
22
3,310
3,486
1,850
1,636
296
3
{-# OPTIONS_GHC -fno-warn-orphans #-} module ArbitraryInstances ( MediumWord(..) ) where import Test.QuickCheck import Test.QuickCheck.Instances () import qualified Crypto.PubKey.ECC.ECDSA as Crypto import qualified Crypto.PubKey.ECC.Types as Crypto import qualified Data.ByteString.Char8 as BS import Data.Monoid ((<>)) import qualified Data.Word as Word import Data.Blockchain -- Blockchain types instance Arbitrary BlockchainConfig where arbitrary = BlockchainConfig <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary Block where arbitrary = Block <$> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary BlockHeader where arbitrary = BlockHeader <$> arbitrary <*> arbitrary <*> arbitrary <*> (hashTreeRoot <$> arbitrary) <*> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary CoinbaseTransaction where arbitrary = CoinbaseTransaction <$> arbitrary instance Arbitrary Transaction where arbitrary = resize 5 $ Transaction <$> arbitrary <*> arbitrary instance Arbitrary TransactionIn where arbitrary = resize 5 $ TransactionIn <$> arbitrary <*> arbitrary instance Arbitrary TransactionOut where arbitrary = resize 5 $ TransactionOut <$> arbitrary <*> arbitrary instance Arbitrary TransactionOutRef where arbitrary = TransactionOutRef <$> arbitrary <*> arbitrary instance Arbitrary Difficulty where arbitrary = Difficulty <$> arbitrary -- Crypto Types instance Arbitrary (Hash a) where arbitrary = unsafeFromByteString . BS.pack <$> vectorOf 64 hexChar where hexChar = elements $ ['0' .. '9'] <> ['a' .. 'f'] instance Arbitrary Signature where arbitrary = Signature <$> arbitrarySig where arbitrarySig = Crypto.Signature <$> arbitraryPositive <*> arbitraryPositive instance Arbitrary PublicKey where arbitrary = PublicKey <$> arbitraryPoint where arbitraryPoint = Crypto.Point <$> arbitraryPositive <*> arbitraryPositive instance Arbitrary PrivateKey where arbitrary = PrivateKey <$> arbitraryPositive -- Other Types instance Arbitrary Hex256 where arbitrary = Hex256 <$> arbitrary newtype MediumWord = MediumWord Word.Word deriving (Eq, Show) instance Arbitrary MediumWord where arbitrary = elements $ MediumWord <$> [0..1000] -- Utils arbitraryPositive :: (Num a, Ord a, Arbitrary a) => Gen a arbitraryPositive = getPositive <$> arbitrary
TGOlson/blockchain
test/ArbitraryInstances.hs
bsd-3-clause
2,691
0
12
678
583
324
259
67
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DataKinds #-} module BSP.Tests.UART.DebugApp (app) where import Ivory.Language import Ivory.Stdlib import Ivory.Tower import BSP.Tests.Platforms import Ivory.BSP.STM32.PlatformClock import Ivory.BSP.STM32.Driver.UART import Ivory.BSP.STM32F405.GPIO ready :: Uint8 ready = 0 sent :: Uint8 sent = 1 got :: Uint8 got = 2 failed_timeout :: Uint8 failed_timeout = 3 failed_badval :: Uint8 failed_badval = 3 garbage_vals :: Uint8 garbage_vals = 4 pollingLoopback :: ChannelSource ('Stored Uint8) -> ChannelSink ('Stored Uint8) -> GPIOPin -> String -> Uint8 -> Tower p () pollingLoopback src' snk' handlepin n correctval = task (named "pollingLoopback") $ do timer <- withPeriodicEvent (Milliseconds 1) out <- withChannelEmitter src' "out" inp <- withChannelReceiver snk' "in" success <- taskLocalInit (named "success") (ival (0 :: Uint32)) state <- taskLocalInit (named "state") (ival ready) time <- taskLocal (named "time") taskInit $ do gpioSetup handlepin handleV timer "periodic" $ \t -> do s <- deref state cond_ [ s ==? ready ==> do -- Flush: arrayMap $ \(_v :: Ix 99) -> do (_, _) <- receiveV inp return () -- Send one byte: emitV_ out correctval gpioOn handlepin store time t store state sent , s ==? sent ==> do sendtime <- deref time (rxd, val) <- receiveV inp ifte_ rxd (do store time t gpioOff handlepin ifte_ (val ==? correctval) (store state got) (store state failed_badval)) (when (t >? (sendtime + (fromIMilliseconds (2 :: Sint64)))) $ do store time t (store state failed_timeout)) , s ==? got ==> do a <- local (ival false) arrayMap $ \(_v :: Ix 99) -> do (rxd, _) <- receiveV inp when rxd $ store a true anythingelse <- deref a ifte_ anythingelse (store state garbage_vals) (do success %= (+1) store state ready) , true ==> gpioOff handlepin ] where named s = n ++ "_" ++ s gpioSetup :: GPIOPin -> Ivory eff () gpioSetup p = do pinEnable p pinSetOutputType p gpio_outputtype_pushpull pinSetSpeed p gpio_speed_50mhz pinSetPUPD p gpio_pupd_none gpioOff p gpioOff :: GPIOPin -> Ivory eff () gpioOff p = do pinClear p pinSetMode p gpio_mode_output gpioOn :: GPIOPin -> Ivory eff () gpioOn p = do pinSet p pinSetMode p gpio_mode_output app :: forall p . (ColoredLEDs p, PlatformClock p, BoardInitializer p, TestUART p) => Tower p () app = do boardInitializer (u1snk, u1src) <- uartTowerDebuggable (testUART (Proxy :: Proxy p)) 57600 (Proxy :: Proxy 256) debugger pollingLoopback u1src u1snk pinD12 "uart1" 0x66 where debugger = UARTTowerDebugger { debug_init = do gpioSetup pinD3 gpioSetup pinD4 gpioSetup pinD5 gpioSetup pinD6 gpioSetup pinD7 , debug_isr = do gpioOn pinD3 gpioOff pinD3 , debug_evthandler_start = do gpioOn pinD4 , debug_evthandler_end = do gpioOff pinD4 , debug_txcheck = do gpioOn pinD5 gpioOff pinD5 , debug_txcheck_pend = do gpioOn pinD6 gpioOff pinD6 , debug_txeie = \en -> do ifte_ en (gpioOn pinD7) (gpioOff pinD7) }
GaloisInc/ivory-tower-stm32
ivory-bsp-tests/BSP/Tests/UART/DebugApp.hs
bsd-3-clause
3,946
0
27
1,424
1,163
565
598
121
1
module Experiments.Concurrency.Simple where import Control.Concurrent import Control.Monad import Data.Monoid data PingPong = Ping | Pong deriving (Eq, Show) threadHandler :: MVar PingPong -> IO () threadHandler ppMVar = do val <- takeMVar ppMVar myId <- myThreadId putStrLn $ "Thread: " <> (show myId) <> " says " <> (show val) threadDelay 5000 putMVar ppMVar $ case val of Ping -> Pong Pong -> Ping pingPongThread :: MVar PingPong -> Int -> IO ThreadId pingPongThread ppMVar times = forkIO $ replicateM_ times $ threadHandler ppMVar simpleConcurrencyMain :: IO () simpleConcurrencyMain = do ppMVar <- newEmptyMVar _ <- pingPongThread ppMVar 10 _ <- pingPongThread ppMVar 10 _ <- pingPongThread ppMVar 10 putMVar ppMVar Ping return ()
rumblesan/haskell-experiments
src/Experiments/Concurrency/Simple.hs
bsd-3-clause
816
0
11
194
265
126
139
28
2
fib :: Int -> Int fib n | n == 0 = 0 | n == 1 = 1 | True = fib (n-1) + fib (n-2) main = fib 33
atzedijkstra/uhc-doc
text/llvm/code/Fib.hs
bsd-3-clause
119
0
9
55
85
40
45
5
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} module Stack.Types.PackageIndex ( PackageDownload (..) , HSPackageDownload (..) , PackageCache (..) , PackageCacheMap (..) , OffsetSize (..) -- ** PackageIndex, IndexName & IndexLocation , PackageIndex(..) , IndexName(..) , indexNameText , IndexType (..) , HackageSecurity (..) ) where import Control.DeepSeq (NFData) import Control.Monad (mzero) import Data.Aeson.Extended import Data.ByteString (ByteString) import qualified Data.Foldable as F import Data.Hashable (Hashable) import Data.Data (Data, Typeable) import Data.HashMap.Strict (HashMap) import Data.Int (Int64) import Data.Map (Map) import qualified Data.Map.Strict as Map import Data.Store (Store) import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8, decodeUtf8) import Data.Word (Word64) import GHC.Generics (Generic) import Path import Stack.Types.PackageIdentifier data PackageCache = PackageCache { pcOffsetSize :: {-# UNPACK #-}!OffsetSize , pcDownload :: !(Maybe PackageDownload) } deriving (Generic, Eq, Show, Data, Typeable) instance Store PackageCache instance NFData PackageCache -- | offset in bytes into the 01-index.tar file for the .cabal file -- contents, and size in bytes of the .cabal file data OffsetSize = OffsetSize !Int64 !Int64 deriving (Generic, Eq, Show, Data, Typeable) instance Store OffsetSize instance NFData OffsetSize data PackageCacheMap = PackageCacheMap { pcmIdent :: !(Map PackageIdentifier PackageCache) -- ^ most recent revision of the package , pcmSHA :: !(HashMap CabalHash OffsetSize) -- ^ lookup via the cabal hash of the cabal file contents } deriving (Generic, Eq, Show, Data, Typeable) instance Store PackageCacheMap instance NFData PackageCacheMap data PackageDownload = PackageDownload { pdSHA256 :: !ByteString , pdUrl :: !ByteString , pdSize :: !Word64 } deriving (Show, Generic, Eq, Data, Typeable) instance Store PackageDownload instance NFData PackageDownload instance FromJSON PackageDownload where parseJSON = withObject "PackageDownload" $ \o -> do hashes <- o .: "package-hashes" sha256 <- maybe mzero return (Map.lookup ("SHA256" :: Text) hashes) locs <- o .: "package-locations" url <- case reverse locs of [] -> mzero x:_ -> return x size <- o .: "package-size" return PackageDownload { pdSHA256 = encodeUtf8 sha256 , pdUrl = encodeUtf8 url , pdSize = size } -- | Hackage Security provides a different JSON format, we'll have our -- own JSON parser for it. newtype HSPackageDownload = HSPackageDownload { unHSPackageDownload :: PackageDownload } instance FromJSON HSPackageDownload where parseJSON = withObject "HSPackageDownload" $ \o1 -> do o2 <- o1 .: "signed" Object o3 <- o2 .: "targets" Object o4:_ <- return $ F.toList o3 len <- o4 .: "length" hashes <- o4 .: "hashes" sha256 <- hashes .: "sha256" return $ HSPackageDownload PackageDownload { pdSHA256 = encodeUtf8 sha256 , pdSize = len , pdUrl = "" } -- | Unique name for a package index newtype IndexName = IndexName { unIndexName :: ByteString } deriving (Show, Eq, Ord, Hashable, Store) indexNameText :: IndexName -> Text indexNameText = decodeUtf8 . unIndexName instance ToJSON IndexName where toJSON = toJSON . indexNameText instance FromJSON IndexName where parseJSON = withText "IndexName" $ \t -> case parseRelDir (T.unpack t) of Left e -> fail $ "Invalid index name: " ++ show e Right _ -> return $ IndexName $ encodeUtf8 t data IndexType = ITHackageSecurity !HackageSecurity | ITVanilla deriving (Show, Eq, Ord) data HackageSecurity = HackageSecurity { hsKeyIds :: ![Text] , hsKeyThreshold :: !Int } deriving (Show, Eq, Ord) instance FromJSON HackageSecurity where parseJSON = withObject "HackageSecurity" $ \o -> HackageSecurity <$> o .: "keyids" <*> o .: "key-threshold" -- | Information on a single package index data PackageIndex = PackageIndex { indexName :: !IndexName , indexLocation :: !Text -- ^ URL for the tarball or, in the case of Hackage Security, the -- root of the directory , indexType :: !IndexType , indexDownloadPrefix :: !Text -- ^ URL prefix for downloading packages , indexRequireHashes :: !Bool -- ^ Require that hashes and package size information be available for packages in this index } deriving Show instance FromJSON (WithJSONWarnings PackageIndex) where parseJSON = withObjectWarnings "PackageIndex" $ \o -> do name <- o ..: "name" prefix <- o ..: "download-prefix" http <- o ..: "http" mhackageSecurity <- o ..:? "hackage-security" let indexType' = maybe ITVanilla ITHackageSecurity mhackageSecurity reqHashes <- o ..:? "require-hashes" ..!= False return PackageIndex { indexName = name , indexLocation = http , indexType = indexType' , indexDownloadPrefix = prefix , indexRequireHashes = reqHashes }
martin-kolinek/stack
src/Stack/Types/PackageIndex.hs
bsd-3-clause
5,676
0
14
1,505
1,291
707
584
160
1
module PSBT.SemVer.Util ( positiveDigit ) where import Text.Megaparsec ((<|>)) import Text.Megaparsec.Char (char) import Text.Megaparsec.String (Parser) positiveDigit :: Parser Char positiveDigit = char '1' <|> char '2' <|> char '3' <|> char '4' <|> char '5' <|> char '6' <|> char '7' <|> char '8' <|> char '9'
LightAndLight/psbt
src/PSBT/SemVer/Util.hs
bsd-3-clause
440
0
13
176
118
62
56
15
1
{-# LANGUAGE FlexibleInstances #-} module AI.DataLoader where import Control.Monad import Debug.Trace import System.IO import Text.ParserCombinators.Parsec import AI.Classification ------------------------------------------------------------------------------- data DatafileDesc = DatafileDesc { datafileName :: String , datafileTrueClass :: String , datafileMissingStr :: Maybe String , datafileForce :: Maybe [String -> DataItem] } deriving Show instance Show (String->DataItem) where show xs = "" applyDirPrefix :: String -> DatafileDesc -> DatafileDesc applyDirPrefix dir df = df {datafileName = dir++"/"++(datafileName df)} defDatafileDesc=DatafileDesc { datafileName = error "datafileName empty" , datafileTrueClass = error "datafileTrueClass empty" , datafileMissingStr = Nothing , datafileForce = Nothing } ------------------------------------------------------------------------------- -- IO functions loadData :: DatafileDesc -> IO (Either ParseError (TrainingData String)) loadData file = do csv <- loadCSV $ datafileName file return $ liftM (csv2data (datafileMissingStr file) (datafileForce file)) csv loadCSV :: String -> IO (Either ParseError [[String]]) loadCSV filename = do hin <- openFile filename ReadMode str <- hGetContents hin let ds = parseCSV str return ds --------------- csv2data :: Maybe String -> Maybe [String -> DataItem] -> [[String]] -> TrainingData String csv2data missingStr Nothing csv = csv2dataAuto missingStr csv csv2data missingStr (Just fs) csv = csv2dataForce missingStr fs csv csv2dataAuto :: Maybe String -> [[String]] -> TrainingData String csv2dataAuto missingStr csv = map (\dp -> (last dp, map cell2sql $ init dp)) csv where cell2sql x = if Just x==missingStr then Missing else case (reads x::[(Double,String)]) of [] -> toDataItem (x::String) (x:xs) -> toDataItem $ fst x csv2dataForce :: Maybe String -> [String -> DataItem] -> [[String]] -> TrainingData String csv2dataForce missingStr fs csv = [(last line, [ if Just cell==missingStr then Missing else f cell | (f,cell) <- zip fs $ init line ]) | line <- csv ] -- | Converts a list into CSV format for writing -- list2csv :: (Show a) => [a] -> String list2csv :: [String] -> String list2csv xs = foldl addcommas "" $ map addquotes xs where addcommas x y = if x=="" then y else x++","++y addquotes x = show x -- list2csv xs = init $ tail $ show xs -- CSV parser from "Real World Haskell," p. 391 -- modified to allow multiple spaces between cells parseCSV :: String -> Either ParseError [[String]] parseCSV input = parse csvFile "(unknown)" input csvFile = endBy line eol line = sepBy cell (char ',' <|> char ' ') cell = do spaces quotedCell <|> many (noneOf " ,\n\r") quotedCell = do char '"' content <- many quotedChar char '"' <?> "Quote at end of cell" return content quotedChar = noneOf "\"" <|> try (string "\"\"" >> return '"') eol = try (string "\n\r") <|> try (string "\r\n") <|> try (string "\n") <|> try (string "\r") <?> "end of line" -- test csv parsing csv_test = do dm <- loadData $ defDatafileDesc {datafileName="../testdata/ringnorm.data"} putStrLn $ func dm where func (Left x) = show x func (Right x) = show $ take 10 x
mikeizbicki/Classification
src/AI/DataLoader.hs
bsd-3-clause
3,573
0
12
908
1,063
544
519
81
3
{-# OPTIONS_HADDOCK show-extensions #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-| Module : Control.THEff Description : Main module of TH Eff package. Copyright : (c) Kolodezny Diver, 2015 License : GPL-3 Maintainer : [email protected] Stability : experimental Portability : Portable -} module Control.THEff ( -- * Overview -- | -- This package implements effects, as alternative to monad -- transformers. Actually, the effects themselves are created without -- the use of TH, but the binding of nested effects described by -- mkEff splice. For example. -- -- > {-# LANGUAGE KindSignatures #-} -- > {-# LANGUAGE FlexibleInstances #-} -- > {-# LANGUAGE MultiParamTypeClasses #-} -- > {-# LANGUAGE TemplateHaskell #-} -- > {-# LANGUAGE ScopedTypeVariables #-} -- > -- > import Control.THEff -- > import Control.THEff.Reader -- > import Control.THEff.State -- > -- > mkEff "MyReader" ''Reader ''Int ''Lift -- > mkEff "SomeState" ''State ''Bool ''MyReader -- > mkEff "OtherRdr" ''Reader ''Float ''SomeState -- > -- > main:: IO () -- > main = do -- > r <- runMyReader 100 -- > $ runSomeState False -- > $ runOtherRdr pi $ do -- > i :: Int <- ask -- MyReader -- > f :: Float <- ask -- OtherRdr -- > b <- get -- SomeState -- > put $ not b -- SomeState -- > lift $ putStrLn "print from effect!" -- Lift -- > return $ show $ fromIntegral i * f -- > print r -- -- For more information about extensible effects , see the original paper at -- <http://okmij.org/ftp/Haskell/extensible/exteff.pdf>. -- But, this package is significantly different from the original. -- It uses a chains of ordinary GADTs created by TH. -- No Typeable, unsafe... , ExistentialQuantification ... -- -- Note. Further, wherever referred to __/runEEEE/__ is meant `mkEff' generated function, e.g. -- runMyReader, runSomeState, runOtherRdr . -- -- See more in samples/*.hs -- * Base THEff support mkEff , Eff(..) , EffClass(..) -- * No monadic start effect , NoEff(..) , effNoEff , runNoEff -- * Monadic start effect , Lift'(..) , EffClassM(..) , lift , Lift(..) , runLift ) where import Control.THEff.TH.Internal(mkEff) -- | The Monad of effects newtype Eff w a = Eff {runEff :: (a -> w) -> w} instance Functor (Eff w) where fmap f (Eff g) = Eff $ \k -> g (k . f) instance Applicative (Eff w) where pure = return Eff f <*> Eff g = Eff $ \k -> f (\v -> g (k . v)) instance Monad (Eff w) where return x = Eff $ \k -> k x m >>= f = Eff $ \k -> runEff m (\v -> runEff (f v) k) -- | Helper class to transfer the action effects by chain. -- Instances of this class are created in @mkEff@. class EffClass w v e where effAction:: ((r -> e) -> w v e) -> Eff e r effAction f = Eff $ \k -> toEff $ f k toEff:: w v e -> e -- | The first effect in a chain of effects not use monads. -- The chain of effects should start or that type, or @Lift@ (See below.) newtype NoEff (m:: * -> *) a = NoEff { unNoEff :: a} -- | This function is used in the 'mkEff' generated runEEEE... functions. -- @effNoEff _ = error "THEff: Attempting to call the effect NoEff that does not have any actions!"@ effNoEff :: a -> b effNoEff _ = error "THEff: Attempting to call the effect NoEff that does not have any actions!" -- | This function is used in the 'mkEff' generated runEEEE... functions. -- Do not use it alone. runNoEff :: Eff (NoEff m a) a -> a runNoEff m = unNoEff $ runEff m NoEff -- | Helper data type for transfer the monadic action effects by chain. data Lift' m v = forall a. Lift' (m a) (a -> v) -- | Helper class to transfer the monadic action effects by chain. -- Instances of this class are created in @mkEff@. class EffClassM m e where effLift:: Lift' m r -> Eff e r effLift (Lift' m g) = Eff $ \k -> toEffM $ Lift' m (k . g) -- | toEffM:: Lift' m e -> e -- | Lift a Monad to an Effect. lift:: EffClassM m e => m a -> Eff e a lift m = effLift $ Lift' m id -- | The first effect in a chain of monadic effects. -- The chain of effects should start or that type, or @NoEff@. data Lift m a = Lift_ (Lift' m (Lift m a)) | LiftResult a instance EffClassM m (Lift m a) where toEffM = Lift_ -- | This function is used in the @mkEff@ generated runEEEE... functions. -- Do not use it alone. runLift :: Monad m => Eff (Lift m a) a -> m a runLift e = loop $ runEff e LiftResult where loop (Lift_ (Lift' m g)) = m >>= loop . g loop (LiftResult r) = return r
KolodeznyDiver/THEff
src/Control/THEff.hs
bsd-3-clause
5,165
0
13
1,598
848
484
364
-1
-1
{-# LANGUAGE LambdaCase #-} module Data.StructuralTraversal.Indexing where import Data.StructuralTraversal.Class import Control.Monad.State import Control.Applicative indexedTraverse :: StructuralTraversable t => (a -> [Int] -> b) -> t a -> t b indexedTraverse f = flip evalState [] . traverseUp ( modify (0:) ) ( modify tail ) ( \a -> f a <$> get <* modify ( \case s:st -> (s+1):st [] -> [] ))
nboldi/structural-traversal
src/Data/StructuralTraversal/Indexing.hs
bsd-3-clause
530
0
17
198
165
88
77
12
2
{-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} module Main (main) where import Prelude () import Prelude.Compat import Criterion.Main import qualified Data.Aeson.Parser.UnescapeFFI as FFI import qualified Data.Aeson.Parser.UnescapePure as Pure import qualified Data.ByteString.Char8 as BS import System.Environment (getArgs, withArgs) main :: IO () main = do args_ <- getArgs let (args, p, n) = case args_ of "--pattern" : p : args_ -> k p args_ _ -> k "\\\"" args_ k p args_ = case args_ of "--repeat" : n : args_ -> (args_, p, read n) args_ -> (args_, p, 10000) input = BS.concat $ replicate n $ BS.pack p withArgs args $ defaultMain [ bench "ffi" $ whnf FFI.unescapeText input , bench "pure" $ whnf Pure.unescapeText input ]
sol/aeson
benchmarks/Escape.hs
bsd-3-clause
855
0
14
212
269
148
121
25
3
----------------------------------------------------------------------------- -- | -- Module : RefacAddField -- Copyright : (c) Christopher Brown 2007 -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- This module contains a transformation for HaRe. -- Add a field to a constructor and resolve -- pattern matching by placing references to said -- field by calls to error; also resolves type signatures (by making them -- more general if necessary). ----------------------------------------------------------------------------- module RefacAddField where import PrettyPrint import PrettyPrint import PosSyntax import AbstractIO import Maybe import TypedIds import UniqueNames hiding (srcLoc) import PNT import TiPNT import List import RefacUtils hiding (getParams) import PFE0 (findFile) import MUtils (( # )) import RefacLocUtils import System import IO import Char refacAddField args = do when (length args /= 5) (error "Please enter a field name ( _ to omit) and a field type!") let fileName = args!!0 fName = args!!1 fType = args!!2 row = read (args!!3)::Int col = read (args!!4)::Int AbstractIO.putStrLn "refacAddField" modInfo@(inscps, exps, mod, tokList) <- parseSourceFile (fileName) case checkCursor fileName row col mod of Left errMsg -> do error errMsg Right dat -> do let res = locToPNT fileName (row, col) mod let res2 = locToPN fileName (row, col) mod let decs = hsDecls mod let datDec = definingDecls [res2] decs False True let datName = (declToName (head datDec)) let datPNT = (declToPNT (head datDec)) -- if the field in question is a record we must get -- the name of the record... ((_,m), (newToks, newMod)) <- applyRefac (addField datPNT datName res fName fType tokList) (Just (inscps, exps, mod, tokList)) fileName writeRefactoredFiles False [((fileName, m), (newToks, newMod))] AbstractIO.putStrLn "Completed.\n" checkCursor :: String -> Int -> Int -> HsModuleP -> Either String HsDeclP checkCursor fileName row col mod = case locToTypeDecl of Nothing -> Left ("Invalid cursor position. Please place cursor at the beginning of the constructor name!") Just decl@(Dec (HsDataDecl loc c tp xs _)) -> Right decl where locToTypeDecl = find (definesTypeCon (locToPNT fileName (row, col) mod)) (hsModDecls mod) -- definesTypeCon pnt (Dec (HsDataDecl loc c tp xs _)) -- = isDataCon pnt && (findPNT pnt tp) definesTypeCon pnt (Dec (HsDataDecl _ _ _ i _)) = isDataCon pnt && (findPNT pnt i) definesTypeCon pnt _ = False getRecordName (Dec (HsDataDecl s c tp recs i)) pos = getRecordName' recs pos 1 where getRecordName' :: [HsConDeclP] -> Int -> Int -> PNT getRecordName' ((HsRecDecl _ _ _ _ recs):cons) pos n = getRecordName'' recs pos n getRecordName'' :: [ ([PNT], HsBangType t)] -> Int -> Int -> PNT getRecordName'' [] _ _ = error "Not a valid field position!" getRecordName'' (([], _): types) pos n = getRecordName'' types pos n getRecordName'' ( ((l:ls), t) :types) pos n | pos == n = error $ show l | otherwise = getRecordName'' ((ls, t):types) pos (n+1) addField datPNT datName pnt fName fType tok (_, _, t) = do newMod <- addingField pnt fName fType t newMod' <- addingFieldInPat datName pnt fType tok newMod newMod'' <- addTypeVar datPNT pnt fType tok newMod return newMod'' addTypeVar datName pnt fType toks t = applyTP (full_buTP (idTP `adhocTP` inDatDeclaration)) t where inDatDeclaration (dat@(Dec (HsDataDecl a b tp c d))::HsDeclP) | (defineLoc datName == (defineLoc.typToPNT.(ghead "inDatDeclaration").flatternTApp) tp) && (fType `elem` (map (pNTtoName.typToPNT) (flatternTApp tp))) == False && isLower (head fType) = update dat (Dec (HsDataDecl a b (createTypFunc ((typToPNT.(ghead "inDatDeclaration").flatternTApp) tp) ( ((nameToTyp fType) : (tail (flatternTApp tp))) )) c d)) dat inDatDeclaration (dat@(Dec (HsTypeSig s is c t))::HsDeclP) | (pNTtoName datName) `elem` (map (pNTtoName.typToPNT) (flatternTApp t) ) = do let res = changeType t if res == t then return dat else update dat (Dec (HsTypeSig s is c res)) dat inDatDeclaration t = return t changeType :: HsTypeP -> HsTypeP changeType t@(Typ (HsTyFun t1 t2)) = (Typ (HsTyFun (changeType t1) (changeType t2))) changeType t@(Typ (HsTyApp (Typ (HsTyCon p)) t2)) | (defineLoc datName) == (defineLoc p) && (fType `elem` (map (pNTtoName.typToPNT) (flatternTApp t))) == False && isLower (head fType) = (createTypFunc ((typToPNT.(ghead "inDatDeclaration").flatternTApp) t) ( ((nameToTyp fType) : (tail (flatternTApp t))))) changeType t = t flatternTApp :: HsTypeP -> [HsTypeP] flatternTApp (Typ (HsTyFun t1 t2)) = flatternTApp t1 ++ flatternTApp t2 flatternTApp (Typ (HsTyApp t1 t2)) = flatternTApp t1 ++ flatternTApp t2 flatternTApp x = [x] addingField pnt fName fType t = applyTP (stop_tdTP (failTP `adhocTP` inDat)) t where inDat (dat@(HsConDecl s i c p types)::HsConDeclP) | p == pnt = do r <- update dat (HsConDecl s i c p (newTypes types fType)) dat return r inDat (dat@(HsRecDecl s i c p types)::HsConDeclP) | p == pnt = do r <- update dat (HsRecDecl s i c p (newRecTypes types fName fType)) dat return r inDat _ = fail "" -- newRecTypes must check that the name is not already declared as a field name -- within that constructor. newRecTypes xs n a | n `elem` (map pNTtoName (unFlattern xs)) = error "There is already a field declared with that name!" | otherwise = ([nameToPNT n], (HsUnBangedType (Typ (HsTyCon (nameToPNT a))))) : xs unFlattern :: [([a],b)] -> [a] unFlattern [] = [] unFlattern ((xs, y):xss) = xs ++ (unFlattern xss) newTypes xs a = HsUnBangedType (Typ (HsTyCon (nameToPNT a))) : xs addingFieldInPat datName pnt fType tok t = applyTP (stop_tdTP (failTP `adhocTP` inPat)) t where inPat d@(Dec _::HsDeclP) = do d' <- checkPat1 pnt pos d d'' <- checkCall pnt pos d' return d' where -- checkPat :: (Term t) => PNT -> String -> t -> HsPatP checkPat1 pnt pos t = applyTP (full_buTP (idTP `adhocTP` inP)) t inP pat@(Pat (HsPApp i p)) | (defineLoc i) == (defineLoc pnt) = update pat (Pat (HsPApp i ([nameToPat newName] ++ p))) pat -- RefacUtils.delete (p !! ((read pos::Int)-1)) pat inP x = return x newName = mkNewName (nameLowered (pNTtoName pnt)) (map pNtoName (definedPNs d)) 1 nameLowered (x:xs) = toLower x : xs checkCall pnt pos t = applyTP (stop_tdTP (failTP `adhocTP` conApp)) t -- a constructor application... conApp exp@(Exp (HsApp e1 e2)) | defineLoc pnt == (defineLoc.expToPNT.(ghead "inE").flatternApp) exp = update exp (createFuncFromPat ((expToPNT.(ghead "inE").flatternApp) exp) ([nameToExp "undefined"] ++ ( (tail.flatternApp) exp) )) exp conApp _ = mzero flatternApp :: HsExpP -> [HsExpP] flatternApp (Exp (HsApp e1 e2)) = flatternApp e1 ++ flatternApp e2 flatternApp x = [x] (!-) :: Int -> Int -> [a] -> [a] (!-) _ _ [] = [] (!-) n pos (x:xs) | n == pos = xs | otherwise = x : (!-) n (pos + 1) xs newPats :: [HsPatP] -> Int -> Int -> [HsPatP] newPats (p:ps) pos n | n == pos = ps | otherwise = p : (newPats ps pos (n+1)) -- inPat x = fail "" checkPat2 datName pnt pos t = applyTP (stop_tdTP (failTP `adhocTP` inPat)) t where inPat d@(Dec _::HsDeclP) = do d'' <- addCall (declToName d) pnt pos d return d'' addCall funcName pnt pos t = applyTP (stop_tdTP (failTP `adhocTP` (inE funcName))) t -- a name associated to a pattern binding somewhere... inE funcName exp@(Exp (HsId (HsVar x))) | (findPatBind pnt x (read pos::Int) t) = update exp (Exp (HsApp (Exp (HsApp (Exp (HsApp (nameToExp ("error" ++ datName)) (nameToExp ("\"" ++ (pNTtoName x) ++ "\"")))) (nameToExp ("\"" ++ (pNTtoName pnt) ++ "\"")))) (nameToExp ("\"" ++ funcName ++ "\"")))) exp inE _ x = mzero findPatBind :: (Term t) => PNT -> PNT -> Int -> t -> Bool findPatBind pnt x pos = (fromMaybe False).(applyTU (once_tdTU (failTU `adhocTU` inBind))) where inBind (dat@(Pat (HsPApp i types))::HsPatP) | pnt == i && checkInTypes x (types!!(pos-1)) = Just True inBind _ = Nothing checkInTypes x (Pat (HsPId (HsVar typePnt))) | defineLoc x == defineLoc typePnt = True checkInTypes _ x = False -- thePNT id = (PNT (PN (UnQual id) (G (PlainModule "unknown") id (N (Just loc0)))) (Type (TypeInfo (Just Primitive) [] [])) (N (Just loc0)))
forste/haReFork
refactorer/RefacAddField.hs
bsd-3-clause
10,744
6
27
3,985
3,356
1,724
1,632
-1
-1
module CommandLine.ResolveFiles (resolveElmFiles, Error(..)) where -- This module provides reusable functions to resolve command line arguments into a list of Elm files import Prelude () import Relude import CommandLine.InfoFormatter (ToConsole(..)) import qualified CommandLine.Filesystem as Filesystem import CommandLine.World (World, FileType(..)) import qualified CommandLine.World as World import Data.Either.Extra (collectErrors) import qualified Data.Text as Text data Error = FileDoesNotExist FilePath | NoElmFiles FilePath instance ToConsole Error where toConsole = \case FileDoesNotExist path -> Text.pack path <> ": No such file or directory" NoElmFiles path -> Text.pack path <> ": Directory does not contain any *.elm files" resolveFile :: World m => FilePath -> m (Either Error [FilePath]) resolveFile path = do fileType <- World.stat path case fileType of IsFile -> return $ Right [path] IsDirectory -> do elmFiles <- Filesystem.findAllElmFiles path case elmFiles of [] -> return $ Left $ NoElmFiles path _ -> return $ Right elmFiles DoesNotExist -> return $ Left $ FileDoesNotExist path resolveElmFiles :: World m => [FilePath] -> m (Either [Error] [FilePath]) resolveElmFiles inputFiles = do result <- collectErrors <$> mapM resolveFile inputFiles case result of Left ls -> return $ Left ls Right files -> return $ Right $ concat files
avh4/elm-format
elm-format-lib/src/CommandLine/ResolveFiles.hs
bsd-3-clause
1,664
0
16
505
409
214
195
-1
-1
module RSS ( checkFeeds ) where import Control.Lens ((^.)) import Control.Monad (when) import Control.Monad.IO.Class (liftIO) import Data.Maybe (fromMaybe) import Data.Monoid ((<>)) import Data.Text.Lazy as TL import Data.Time.Calendar (toGregorian) import Data.Time.Clock (getCurrentTime, utctDay) import Database.Persist import qualified Network.Wreq as Wreq import Text.Feed.Import (parseFeedSource) import Text.Feed.Query import qualified Text.Feed.Types as RF import Text.Regex.Posix ((=~)) import Types import DB (runDB) import Model import Slack (slack, slackA) checkFeeds :: Z () checkFeeds = getFeeds >>= mapM_ runFeed getFeeds :: Z [Entity Feed] getFeeds = runDB $ selectList [] [] runFeed :: Entity Feed -> Z () runFeed (Entity _id feed) = do slack "#_robots" $ "Checking *" <> (toStrict $ feedTitle feed) <> "* for new entries" es <- liftIO $ fetchFeed feed mapM_ (process _id) es fetchFeed :: Feed -> IO [RF.Item] fetchFeed feed = do r <- Wreq.get . TL.unpack $ feedUrl feed let rss = r ^. Wreq.responseBody mf = parseFeedSource rss case mf of Nothing -> return [] Just f -> return $ feedItems f -- TODO: clean this up process :: FeedId -> RF.Item -> Z () process _id item = case getItemId item of Nothing -> return () Just (_, guid) -> do note <- liftIO $ noteworthy item when note $ do record <- liftIO $ feedItemFromRemote _id guid item r <- runDB $ insertBy record case r of Left _ -> return () -- Record already exists Right _ -> do let msg = TL.toStrict $ feedItemTitle record url = TL.toStrict $ feedItemDownloadUrl record slackA "#rss" msg [("Download", url)] noteworthy :: RF.Item -> IO Bool noteworthy = recent recent :: RF.Item -> IO Bool recent item = do cy <- getCurrentYear case itemYear item of Nothing -> return True Just iy -> return $ iy >= cy - 1 getCurrentYear :: IO Integer getCurrentYear = do t <- getCurrentTime let (y,_,_) = toGregorian . utctDay $ t -- Ignoring time zone issues at year boundaries return y itemYear :: RF.Item -> Maybe Integer itemYear item = let title = fromMaybe "" $ getItemTitle item patt = "\\[(20[0-9][0-9])\\]" :: String in case title =~ patt of (_:match:_) : _ -> Just $ read match _ -> Nothing feedItemFromRemote :: FeedId -> String -> RF.Item -> IO FeedItem feedItemFromRemote feedId itemId ri = do let f t = TL.pack $ fromMaybe "" t title = f $ getItemTitle ri desc = f $ getItemDescription ri url = f $ getItemLink ri now <- getCurrentTime return $ FeedItem feedId (TL.pack itemId) title desc url now
jamesdabbs/zorya
src/RSS.hs
bsd-3-clause
2,897
0
22
845
987
504
483
79
3
-- |Authentication related functions. module MSF.Auth ( module Types.Auth , auth_login , auth_logout , auth_token_add , auth_token_remove , auth_token_generate , auth_token_list ) where import MSF.Monad import Types.Auth import qualified RPC.Auth as RPC -- | Login to a given host with user and pass, returning -- authentication token if successful. Typically use -- 'MSF.Monad.login'. auth_login :: (SilentCxt s) => Username -> Password -> MSF s (Either String Token) auth_login user pass = prim $ \ addr _ -> RPC.auth_login addr user pass -- | Log a given authentication token out. Attempts to diagnose failure. auth_logout :: (SilentCxt s) => Token -> MSF s () auth_logout tok = prim $ \ addr auth -> RPC.auth_logout addr auth tok -- | Add a permanent authentication token. auth_token_add :: (SilentCxt s) => Token -> MSF s () auth_token_add candidate = prim $ \ addr auth -> RPC.auth_token_add addr auth candidate -- | Remove either a temporary or permanent auth token. auth_token_remove :: (SilentCxt s) => Token -> MSF s () auth_token_remove target = prim $ \ addr auth -> RPC.auth_token_remove addr auth target -- | Generate a new authentication token. auth_token_generate :: (SilentCxt s) => MSF s Token auth_token_generate = prim RPC.auth_token_generate -- | Get a list of all the auth tokens. auth_token_list :: (SilentCxt s) => MSF s [Token] auth_token_list = prim RPC.auth_token_list
GaloisInc/msf-haskell
src/MSF/Auth.hs
bsd-3-clause
1,428
0
10
252
344
188
156
27
1
module Data.Povray.Camera where import Data.Povray.Types import Data.Povray.Base import Data.Maybe data Camera = Camera { _location :: Vect, _lookAt :: Vect, _angle :: Maybe Double, _sky :: Maybe Vect } instance Povray Camera where toPov (Camera loc at ang sky) = join [ "camera {", "location " `mappend` toPov loc, maybeToPovWithName "angle" ang, maybeToPovWithName "sky" sky, "look_at " `mappend` toPov at, "}" ]
lesguillemets/hspov_proto
src/Data/Povray/Camera.hs
bsd-3-clause
495
0
9
142
140
80
60
17
0
-------------------------------------------------------------------------------- module Copilot.Kind.Kind2.PrettyPrint ( prettyPrint ) where import Copilot.Kind.Misc.SExpr import qualified Copilot.Kind.Misc.SExpr as SExpr import Copilot.Kind.Kind2.AST import Data.List (intercalate) -------------------------------------------------------------------------------- type SSExpr = SExpr String kwPrime = "prime" -------------------------------------------------------------------------------- prettyPrint :: File -> String prettyPrint ast = intercalate "\n\n" . map (SExpr.toString shouldIndent id) . ppFile $ ast -- Defines the indentation policy of the S-Expressions shouldIndent :: SSExpr -> Bool shouldIndent (Atom _) = False shouldIndent (List [Atom a, Atom _]) = a `notElem` [kwPrime] shouldIndent _ = True -------------------------------------------------------------------------------- ppFile :: File -> [SSExpr] ppFile (File preds props) = map ppPredDef preds ++ ppProps props ppProps :: [Prop] -> [SSExpr] ppProps ps = [ node "check-prop" [ list $ map ppProp ps ] ] ppProp :: Prop -> SSExpr ppProp (Prop n t) = list [atom n, ppTerm t] ppPredDef :: PredDef -> SSExpr ppPredDef pd = list [ atom "define-pred" , atom (predId pd) , list . map ppStateVarDef . predStateVars $ pd , node "init" [ppTerm $ predInit pd] , node "trans" [ppTerm $ predTrans pd] ] ppStateVarDef :: StateVarDef -> SSExpr ppStateVarDef svd = list [atom (varId svd), ppType (varType svd)] ppType :: Type -> SSExpr ppType Int = atom "Int" ppType Real = atom "Real" ppType Bool = atom "Bool" ppTerm :: Term -> SSExpr ppTerm (ValueLitteral c) = atom c ppTerm (PrimedStateVar v) = list [atom kwPrime, atom v] ppTerm (StateVar v) = atom v ppTerm (FunApp f args) = node f $ map ppTerm args ppTerm (PredApp p t args) = node (p ++ "." ++ ext) $ map ppTerm args where ext = case t of Init -> "init" Trans -> "trans" --------------------------------------------------------------------------------
jonathan-laurent/copilot-kind
src/Copilot/Kind/Kind2/PrettyPrint.hs
bsd-3-clause
2,128
0
11
437
643
335
308
46
2
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- | <http://www.libtorrent.org/reference-Create_Torrents.html#create_torrent create_torrent> structure for "Libtorrent" module Network.Libtorrent.CreateTorrent( CreateTorrent(..) , createTorrent , createTorrentFromTorrentInfo , createTorrentGenerate , createTorrentFiles , createTorrentSetComment , createTorrentSetCreator , createTorrentSetHash , createTorrentSetFileHash , createTorrentAddUrlSeed , createTorrentAddHttpSeed , createTorrentAddNode , createTorrentAddTracker , createTorrentSetRootCert , createTorrentPriv , createTorrentSetPriv , createTorrentNumPieces , createTorrentPieceLength , createTorrentPieceSize , createTorrentMerkleTree , createTorrentSetPieceHashes ) where import Control.Monad (void) import Control.Monad.Catch (bracket) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Maybe (fromMaybe) import Data.Text (Text) import qualified Data.Text as T import Foreign.C.String (withCString) import Foreign.ForeignPtr (ForeignPtr, withForeignPtr) import Foreign.Marshal.Utils (fromBool, toBool) import Foreign.Ptr (freeHaskellFunPtr) import qualified Language.C.Inline as C import qualified Language.C.Inline.Cpp as C import System.Mem.Weak (mkWeak) import Network.Libtorrent.Bencode import Network.Libtorrent.Exceptions import Network.Libtorrent.FileStorage (FileStorage) import Network.Libtorrent.Inline import Network.Libtorrent.Internal import Network.Libtorrent.Sha1Hash import Network.Libtorrent.String import Network.Libtorrent.TorrentInfo (TorrentInfo) import Network.Libtorrent.Types C.context libtorrentCtx C.include "<libtorrent/create_torrent.hpp>" C.verbatim "typedef std::vector<libtorrent::sha1_hash> VectorSha1Hash;" C.verbatim "typedef void SetPieceHashesCb (int);" C.using "namespace libtorrent" C.using "namespace std" data CreateTorrentFlags = Optimize | Merkle | ModificationTime | Symlinks | CalculateFileHashes deriving (Show, Enum, Bounded, Eq, Ord) newtype CreateTorrent = CreateTorrent { unCreateTorrent :: ForeignPtr (CType CreateTorrent) } instance Show CreateTorrent where show _ = "CreateTorrent" instance Inlinable CreateTorrent where type (CType CreateTorrent) = C'CreateTorrent instance FromPtr CreateTorrent where fromPtr = objFromPtr CreateTorrent $ \ptr -> [C.exp| void { delete $(create_torrent * ptr); } |] instance WithPtr CreateTorrent where withPtr (CreateTorrent fptr) = withForeignPtr fptr createTorrent :: MonadIO m => FileStorage -> Maybe C.CInt -- ^ piece size -> Maybe C.CInt -- ^ pad file limit -> Maybe (BitFlags CreateTorrentFlags) -> m CreateTorrent createTorrent fs mps mpfl mflags = liftIO . withPtr fs $ \fsPtr -> do let ps = fromMaybe 0 mps pfl = fromMaybe (-1) mpfl flags = fromIntegral . fromEnum $ fromMaybe ([Optimize]) mflags res <- fromPtr [C.exp| create_torrent * { new create_torrent(*$(file_storage * fsPtr) , $(int ps) , $(int pfl) , $(int flags)) } |] -- FileStorage object must be kept during CreateTorrent life void $ mkWeak res fs Nothing return res createTorrentFromTorrentInfo :: MonadIO m => TorrentInfo -> m CreateTorrent createTorrentFromTorrentInfo ti = liftIO . withPtr ti $ \tiPtr -> do fromPtr [C.exp| create_torrent * { new create_torrent(*$(torrent_info * tiPtr)) } |] createTorrentGenerate :: MonadIO m => CreateTorrent -> m Bencoded createTorrentGenerate ho = liftIO . withPtr ho $ \hoPtr -> do entry <- [C.exp| entry * { new entry($(create_torrent * hoPtr)->generate()) } |] entryToBencoded entry createTorrentFiles :: MonadIO m => CreateTorrent -> m FileStorage createTorrentFiles ho = liftIO . withPtr ho $ \hoPtr -> fromPtr [C.exp| file_storage * { new file_storage($(create_torrent * hoPtr)->files()) } |] createTorrentSetComment :: MonadIO m => CreateTorrent -> Text -> m () createTorrentSetComment ho val = liftIO . withPtr ho $ \hoPtr -> withCString (T.unpack val) $ \ valPtr -> [C.exp| void { $(create_torrent * hoPtr)->set_comment($(char const * valPtr)) } |] createTorrentSetCreator :: MonadIO m => CreateTorrent -> Text -> m () createTorrentSetCreator ho val = liftIO . withPtr ho $ \hoPtr -> withCString (T.unpack val) $ \ valPtr -> [C.exp| void { $(create_torrent * hoPtr)->set_creator($(char const * valPtr)) } |] createTorrentSetHash :: MonadIO m => CreateTorrent -> C.CInt -> Sha1Hash -> m () createTorrentSetHash ho idx h = liftIO . withPtr ho $ \hoPtr -> withPtr h $ \hPtr -> [C.exp| void { $(create_torrent * hoPtr)->set_hash($(int idx), *$(sha1_hash * hPtr)) } |] createTorrentSetFileHash :: MonadIO m => CreateTorrent -> C.CInt -> Sha1Hash -> m () createTorrentSetFileHash ho idx h = liftIO . withPtr ho $ \hoPtr -> withPtr h $ \hPtr -> [C.exp| void { $(create_torrent * hoPtr)->set_file_hash($(int idx), *$(sha1_hash * hPtr)) } |] createTorrentAddUrlSeed :: MonadIO m => CreateTorrent -> Text -> m () createTorrentAddUrlSeed ho url = liftIO . withPtr ho $ \hoPtr -> do url' <- textToStdString url withPtr url' $ \urlPtr -> [C.exp| void { $(create_torrent * hoPtr)->add_url_seed(*$(string * urlPtr)) } |] createTorrentAddHttpSeed :: MonadIO m => CreateTorrent -> Text -> m () createTorrentAddHttpSeed ho url = liftIO . withPtr ho $ \hoPtr -> do url' <- textToStdString url withPtr url' $ \urlPtr -> [C.exp| void { $(create_torrent * hoPtr)->add_http_seed(*$(string * urlPtr)) } |] createTorrentAddNode :: MonadIO m => CreateTorrent -> (Text, C.CInt) -> m () createTorrentAddNode ho (txt, i) = liftIO . withPtr ho $ \hoPtr -> do txt' <- textToStdString txt withPtr txt' $ \txtPtr -> [C.exp| void { $(create_torrent * hoPtr)->add_node(pair<string, int>(*$(string * txtPtr), $(int i))) } |] createTorrentAddTracker :: MonadIO m => CreateTorrent -> Text -> Maybe C.CInt -> m () createTorrentAddTracker ho url mtier = liftIO . withPtr ho $ \hoPtr -> do let tier = fromMaybe 0 mtier url' <- textToStdString url withPtr url' $ \urlPtr -> [C.exp| void { $(create_torrent * hoPtr)->add_tracker(*$(string * urlPtr), $(int tier)) } |] createTorrentSetRootCert :: MonadIO m => CreateTorrent -> Text -> m () createTorrentSetRootCert ho pem = liftIO . withPtr ho $ \hoPtr -> do pem' <- textToStdString pem withPtr pem' $ \pemPtr -> [C.exp| void { $(create_torrent * hoPtr)->set_root_cert(*$(string * pemPtr)) } |] createTorrentPriv :: MonadIO m => CreateTorrent -> m Bool createTorrentPriv ho = liftIO . withPtr ho $ \hoPtr -> toBool <$> [C.exp| bool { $(create_torrent * hoPtr)->priv() } |] createTorrentSetPriv :: MonadIO m => CreateTorrent -> Bool -> m () createTorrentSetPriv ho val = liftIO . withPtr ho $ \hoPtr -> do let val' = fromBool val [C.exp| void { $(create_torrent * hoPtr)->set_priv($(bool val')) } |] createTorrentNumPieces :: MonadIO m => CreateTorrent -> m C.CInt createTorrentNumPieces ho = liftIO . withPtr ho $ \hoPtr -> [C.exp| int { $(create_torrent * hoPtr)->num_pieces() } |] createTorrentPieceLength :: MonadIO m => CreateTorrent -> m C.CInt createTorrentPieceLength ho = liftIO . withPtr ho $ \hoPtr -> [C.exp| int { $(create_torrent * hoPtr)->piece_length() } |] createTorrentPieceSize :: MonadIO m => CreateTorrent -> C.CInt -> m C.CInt createTorrentPieceSize ho idx = liftIO . withPtr ho $ \hoPtr -> [C.exp| int { $(create_torrent * hoPtr)->piece_size($(int idx)) } |] createTorrentMerkleTree :: MonadIO m => CreateTorrent -> m (StdVector Sha1Hash) createTorrentMerkleTree ho = liftIO . withPtr ho $ \hoPtr -> fromPtr [C.exp| VectorSha1Hash * { new VectorSha1Hash($(create_torrent * hoPtr)->merkle_tree()) } |] -- | Can throw 'LibtorrentException'. createTorrentSetPieceHashes :: MonadIO m => CreateTorrent -> Text -> (C.CInt -> IO ()) -> m () createTorrentSetPieceHashes ho fp cb = liftIO . withPtr ho $ \hoPtr -> do fpStr <- textToStdString fp withPtr fpStr $ \fpPtr -> withErrorCode CreateTorrentError $ \ePtr -> bracket ($(C.mkFunPtr [t| C.CInt -> IO () |]) cb) freeHaskellFunPtr $ \cbPtr -> [C.block| void { boost::function<void(int)> cb = $(SetPieceHashesCb cbPtr); set_piece_hashes(*$(create_torrent * hoPtr), *$(string * fpPtr), cb, *$(error_code * ePtr)) ; } |]
eryx67/haskell-libtorrent
src/Network/Libtorrent/CreateTorrent.hs
bsd-3-clause
9,765
0
20
2,700
2,085
1,109
976
185
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-| Module : Numeric.AERN.Basics.SizeLimits Description : intrinsic size limit such as precision Copyright : (c) Michal Konecny License : BSD3 Maintainer : [email protected] Stability : experimental Portability : portable Intrinsic size limit such as precision. -} module Numeric.AERN.Basics.SizeLimits where import Numeric.AERN.Basics.Effort {-| An abstraction of concepts such as precision in MPFR numbers, maximum degree of a polynomial. An intrinsic limitation on the size or precision of a value and values derived from it by common operations. -} class HasSizeLimits f where type SizeLimits f getSizeLimits :: f -> SizeLimits f defaultSizeLimits :: f -> SizeLimits f {-| Ability to increase or decrease a size limit, leading to a value conversion. For most types, the instance will define either the Up/Dn operations or the In/Out operations and let the others throw an exception. -} class (EffortIndicator (SizeLimitsChangeEffort f)) => CanChangeSizeLimits f where type SizeLimitsChangeEffort f sizeLimitsChangeDefaultEffort :: f -> SizeLimitsChangeEffort f changeSizeLimitsDnEff :: SizeLimitsChangeEffort f -> SizeLimits f -> f -> f changeSizeLimitsUpEff :: SizeLimitsChangeEffort f -> SizeLimits f -> f -> f changeSizeLimitsOutEff :: SizeLimitsChangeEffort f -> SizeLimits f -> f -> f changeSizeLimitsInEff :: SizeLimitsChangeEffort f -> SizeLimits f -> f -> f changeSizeLimitsOut :: CanChangeSizeLimits f => SizeLimits f -> f -> f changeSizeLimitsOut limits a = changeSizeLimitsOutEff (sizeLimitsChangeDefaultEffort a) limits a changeSizeLimitsIn :: CanChangeSizeLimits f => SizeLimits f -> f -> f changeSizeLimitsIn limits a = changeSizeLimitsInEff (sizeLimitsChangeDefaultEffort a) limits a changeSizeLimitsDn :: CanChangeSizeLimits f => SizeLimits f -> f -> f changeSizeLimitsDn limits a = changeSizeLimitsDnEff (sizeLimitsChangeDefaultEffort a) limits a changeSizeLimitsUp :: CanChangeSizeLimits f => SizeLimits f -> f -> f changeSizeLimitsUp limits a = changeSizeLimitsUpEff (sizeLimitsChangeDefaultEffort a) limits a
michalkonecny/aern
aern-order/src/Numeric/AERN/Basics/SizeLimits.hs
bsd-3-clause
2,307
0
9
489
373
188
185
37
1
{-# LANGUAGE MultiParamTypeClasses , FunctionalDependencies , FlexibleInstances , UndecidableInstances #-} --------------------------------------------------------------------------- -- TypeCast from HList. --------------------------------------------------------------------------- module Language.Haskell.Polycephaly.Typecast where class TypeCast a b | a -> b, b->a where typeCast :: a -> b class TypeCast' t a b | t a -> b, t b -> a where typeCast' :: t->a->b class TypeCast'' t a b | t a -> b, t b -> a where typeCast'' :: t->a->b instance TypeCast' () a b => TypeCast a b where typeCast x = typeCast' () x instance TypeCast'' t a b => TypeCast' t a b where typeCast' = typeCast'' instance TypeCast'' () a a where typeCast'' _ x = x
jkarni/polycephalous-instances
src/Language/Haskell/Polycephaly/Typecast.hs
bsd-3-clause
783
0
8
157
211
118
93
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE CPP #-} -- | Define the types used to describes CSS elements module Graphics.Svg.CssTypes ( CssSelector( .. ) , CssSelectorRule , CssRule( .. ) , CssDescriptor( .. ) , CssDeclaration( .. ) , CssElement( .. ) , CssMatcheable( .. ) , CssContext , Dpi , Number( .. ) , serializeNumber , findMatchingDeclarations , toUserUnit , mapNumber , tserialize ) where #if !MIN_VERSION_base(4,8,0) import Data.Monoid( mconcat ) #endif import Data.Monoid( (<>) ) import Data.List( intersperse ) import qualified Data.Text as T import qualified Data.Text.Lazy.Builder as TB import Text.Printf import Codec.Picture( PixelRGBA8( .. ) ) {-import Debug.Trace-} -- | Alias describing a "dot per inch" information -- used for size calculation (see toUserUnit). type Dpi = Int -- | Helper typeclass for serialization to Text. class TextBuildable a where -- | Serialize an element to a text builder. tserialize :: a -> TB.Builder -- | Describe an element of a CSS selector. Multiple -- elements can be combined in a CssSelector type. data CssDescriptor = OfClass T.Text -- ^ .IDENT | OfName T.Text -- ^ IDENT | OfId T.Text -- ^ #IDENT | OfPseudoClass T.Text -- ^ `:IDENT` (ignore function syntax) | AnyElem -- ^ '*' | WithAttrib T.Text T.Text -- ^ `` deriving (Eq, Show) instance TextBuildable CssDescriptor where tserialize d = case d of OfClass c -> si '.' <> ft c OfName n -> ft n OfId i -> si '#' <> ft i OfPseudoClass c -> si '#' <> ft c AnyElem -> si '*' WithAttrib a b -> mconcat [si '[', ft a, si '=', ft b, si ']'] where ft = TB.fromText si = TB.singleton -- | Define complex selector. data CssSelector = Nearby -- ^ Correspond to the `+` CSS selector. | DirectChildren -- ^ Correspond to the `>` CSS selectro. | AllOf [CssDescriptor] -- ^ Grouping construct, all the elements -- of the list must be matched. deriving (Eq, Show) instance TextBuildable CssSelector where tserialize s = case s of Nearby -> si '+' DirectChildren -> si '>' AllOf lst -> mconcat . intersperse (si ' ') $ map tserialize lst where si = TB.singleton -- | A CssSelectorRule is a list of all the elements -- that must be meet in a depth first search fashion. type CssSelectorRule = [CssSelector] -- | Represent a CSS selector and the different declarations -- to apply to the matched elemens. data CssRule = CssRule { -- | At the first level represent a list of elements -- to be matched. If any match is made, you can apply -- the declarations. At the second level cssRuleSelector :: ![CssSelectorRule] -- | Declarations to apply to the matched element. , cssDeclarations :: ![CssDeclaration] } deriving (Eq, Show) instance TextBuildable CssRule where tserialize (CssRule selectors decl) = mconcat tselectors <> ft " {\n" <> mconcat (fmap tserializeDecl decl) <> ft "}\n" where ft = TB.fromText tserializeDecl d = ft " " <> tserialize d <> ft ";\n" tselectors = intersperse (ft ",\n") . fmap tserialize $ concat selectors -- | Interface for elements to be matched against -- some CssRule. class CssMatcheable a where -- | For an element, tell its optional ID attribute. cssIdOf :: a -> Maybe T.Text -- | For an element, return all of it's class attributes. cssClassOf :: a -> [T.Text] -- | Return the name of the tagname of the element cssNameOf :: a -> T.Text -- | Return a value of a given attribute if present cssAttribOf :: a -> T.Text -> Maybe T.Text -- | Represent a zipper in depth at the first list -- level, and the previous nodes at in the second -- list level. type CssContext a = [[a]] isDescribedBy :: CssMatcheable a => a -> [CssDescriptor] -> Bool isDescribedBy e = all tryMatch where tryMatch (OfClass t) = t `elem` cssClassOf e tryMatch (OfId i) = cssIdOf e == Just i tryMatch (OfName n) = cssNameOf e == n tryMatch (OfPseudoClass _) = False tryMatch (WithAttrib a v) = cssAttribOf e a == Just v tryMatch AnyElem = True isMatching :: CssMatcheable a => CssContext a -> [CssSelector] -> Bool isMatching = go where go _ [] = True go [] _ = False go ((_ : near):upper) (Nearby : rest) = go (near:upper) rest go ((e:_):upper) (DirectChildren:AllOf descr:rest) | isDescribedBy e descr = go upper rest go _ (DirectChildren:_) = False go ((e:_):upper) (AllOf descr : rest) | isDescribedBy e descr = go upper rest | otherwise = False go (_:upper) selector = go upper selector -- | Given CSS rules, find all the declaration to apply to the -- element in a given context. findMatchingDeclarations :: CssMatcheable a => [CssRule] -> CssContext a -> [CssDeclaration] findMatchingDeclarations rules context = concat [cssDeclarations rule | rule <- rules , selector <- cssRuleSelector rule , isMatching context $ reverse selector ] -- | Represent the content to apply to some -- CSS matched rules. data CssDeclaration = CssDeclaration { -- | Property name to change (like font-family or color). _cssDeclarationProperty :: T.Text -- | List of values , _cssDecarationlValues :: [[CssElement]] } deriving (Eq, Show) instance TextBuildable CssDeclaration where tserialize (CssDeclaration n elems) = mconcat $ ft n : ft ": " : intersperse (si ' ') finalElems where finalElems = map tserialize (concat elems) ft = TB.fromText si = TB.singleton -- | Encode complex number possibly dependant to the current -- render size. data Number = Num Double -- ^ Simple coordinate in current user coordinate. | Px Double -- ^ With suffix "px" | Em Double -- ^ Number relative to the current font size. | Percent Double -- ^ Number relative to the current viewport size. | Pc Double | Mm Double -- ^ Number in millimeters, relative to DPI. | Cm Double -- ^ Number in centimeters, relative to DPI. | Point Double -- ^ Number in points, relative to DPI. | Inches Double -- ^ Number in inches, relative to DPI. deriving (Eq, Show) -- | Helper function to modify inner value of a number mapNumber :: (Double -> Double) -> Number -> Number mapNumber f nu = case nu of Num n -> Num $ f n Px n -> Px $ f n Em n -> Em $ f n Percent n -> Percent $ f n Pc n -> Pc $ f n Mm n -> Mm $ f n Cm n -> Cm $ f n Point n -> Point $ f n Inches n -> Inches $ f n -- | Encode the number to string which can be used in a -- CSS or a svg attributes. serializeNumber :: Number -> String serializeNumber n = case n of Num c -> printf "%g" c Px c -> printf "%gpx" c Em cc -> printf "%gem" cc Percent p -> printf "%d%%" (floor $ 100 * p :: Int) Pc p -> printf "%gpc" p Mm m -> printf "%gmm" m Cm c -> printf "%gcm" c Point p -> printf "%gpt" p Inches i -> printf "%gin" i instance TextBuildable Number where tserialize = TB.fromText . T.pack . serializeNumber -- | Value of a CSS property. data CssElement = CssIdent !T.Text | CssString !T.Text | CssReference !T.Text | CssNumber !Number | CssColor !PixelRGBA8 | CssFunction !T.Text ![CssElement] | CssOpComa | CssOpSlash deriving (Eq, Show) instance TextBuildable CssElement where tserialize e = case e of CssIdent n -> ft n CssString s -> si '"' <> ft s <> si '"' CssReference r -> si '#' <> ft r CssNumber n -> tserialize n CssColor (PixelRGBA8 r g b _) -> ft . T.pack $ printf "#%02X%02X%02X" r g b CssFunction t els -> mconcat $ ft t : si '(' : args ++ [si ')'] where args = intersperse (ft ", ") (map tserialize els) CssOpComa -> si ',' CssOpSlash -> si '/' where ft = TB.fromText si = TB.singleton -- | This function replace all device dependant units to user -- units given it's DPI configuration. -- Preserve percentage and "em" notation. toUserUnit :: Dpi -> Number -> Number toUserUnit dpi = go where go nu = case nu of Num _ -> nu Px p -> go $ Num p Em _ -> nu Percent _ -> nu Pc n -> go . Inches $ (12 * n) / 72 Inches n -> Num $ n * fromIntegral dpi Mm n -> go . Inches $ n / 25.4 Cm n -> go . Inches $ n / 2.54 Point n -> go . Inches $ n / 72
jhegedus42/svg-tree
src/Graphics/Svg/CssTypes.hs
bsd-3-clause
8,633
0
13
2,391
2,334
1,208
1,126
207
9
-- In extensible effects, the operators are dumb data types. -- We need to enable a few language extensions... {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE UndecidableInstances #-} -- ... and import some machinery here. import Unsafe.Coerce(unsafeCoerce) -- Included at end of file: -- import Eff.Internal.OpenUnion51 -- import Eff.Internal.FTCQueue1 f :: Eff '[State Int] () f = do x :: Int <- get put (x * x) return () -- We run it with: runF = run (runState f 100) -- and runF == 10000 ranF = (runF == ((), 10000)) -- returns True -- Here's our State data type: just defines two operations, Get and Put. data State s v where Get :: State s s Put :: !s -> State s () -- Now get and put are really simple: get = send Get put s = send (Put s) -- But unlike with regular monads, instead of "runState" being really simple -- here it's quite a bit more involved! -- But note that it now contains all of the logic here: runState :: Eff (State s ': r) w -> s -> Eff r (w,s) runState (Val x) s = return (x,s) runState (E u q) s = case decomp u of -- If it's a "get", apply (qApp) the state parameter, and recurse: Right Get -> runState (qApp q s) s -- If it's a "put", apply (qApp) the unit value (), and recurse with the new state: Right (Put new) -> runState (qApp q ()) new -- And this is how it handles layering multiple effects, but we can ignore it. Left u -> E u (tsingleton (\x -> runState (qApp q x) s)) -- But we need to define our central data type, this wacky thing: data Eff r a where Val :: a -> Eff r a E :: Union r b -> FTCQueue (Eff r) b a -> Eff r a -- And this method of adding effects: send :: Member t r => t v -> Eff r v send t = E (inj t) (tsingleton Val) -- Get the value out at the end: run :: Eff '[] w -> w run (Val x) = x -- A helper function: qApp :: FTCQueue (Eff r) b w -> b -> Eff r w qApp q x = case tviewl q of TOne k -> k x k :| t -> case k x of Val y -> qApp t y E u q -> E u (q >< t) -- Finally, the type class definitions just seem to move values around without doing anything: instance Monad (Eff r) where {-# INLINE return #-} {-# INLINE [2] (>>=) #-} return x = Val x Val x >>= k = k x E u q >>= k = E u (q |> k) -- just accumulates continuations instance Applicative (Eff r) where {-# INLINE pure #-} pure = Val {-# INLINE (<*>) #-} Val f <*> Val x = Val $ f x Val f <*> E u q = E u (q |> (Val . f)) E u q <*> Val x = E u (q |> (Val . ($ x))) E u q <*> m = E u (q |> (`fmap` m)) instance Functor (Eff r) where {-# INLINE fmap #-} fmap f (Val x) = Val (f x) fmap f (E u q) = E u (q |> (Val . f)) -- does no mapping yet! -- Eff/Internal/OpenUnion51.hs: -- The data constructors of Union are not exported -- Strong Sum (Existential with the evidence) is an open union -- t is can be a GADT and hence not necessarily a Functor. -- Int is the index of t in the list r; that is, the index of t in the -- universe r data Union (r :: [ * -> * ]) (v :: k) where Union :: {-# UNPACK #-} !Int -> t v -> Union r v {-# INLINE prj' #-} {-# INLINE inj' #-} inj' :: Int -> t v -> Union r v inj' = Union prj' :: Int -> Union r v -> Maybe (t v) prj' n (Union n' x) | n == n' = Just (unsafeCoerce x) | otherwise = Nothing newtype P t r = P{unP :: Int} class (FindElem t r) => Member (t :: * -> *) r where inj :: t v -> Union r v prj :: Union r v -> Maybe (t v) -- Optimized specialized instance instance {-# INCOHERENT #-} Member t '[t] where {-# INLINE inj #-} {-# INLINE prj #-} inj x = Union 0 x prj (Union _ x) = Just (unsafeCoerce x) instance {-# INCOHERENT #-} (FindElem t r) => Member t r where {-# INLINE inj #-} {-# INLINE prj #-} inj = inj' (unP $ (elemNo :: P t r)) prj = prj' (unP $ (elemNo :: P t r)) {-# INLINE [2] decomp #-} decomp :: Union (t ': r) v -> Either (Union r v) (t v) decomp (Union 0 v) = Right $ unsafeCoerce v decomp (Union n v) = Left $ Union (n-1) v -- Specialized version {-# RULES "decomp/singleton" decomp = decomp0 #-} {-# INLINE decomp0 #-} decomp0 :: Union '[t] v -> Either (Union '[] v) (t v) decomp0 (Union _ v) = Right $ unsafeCoerce v -- No other case is possible weaken :: Union r w -> Union (any ': r) w weaken (Union n v) = Union (n+1) v -- Find an index of an element in a `list' -- The element must exist -- This is essentially a compile-time computation. class FindElem (t :: * -> *) r where elemNo :: P t r instance {-# OVERLAPPING #-} FindElem t (t ': r) where elemNo = P 0 instance {-# OVERLAPS #-} FindElem t r => FindElem t (t' ': r) where elemNo = P $ 1 + (unP $ (elemNo :: P t r)) type family EQU (a :: k) (b :: k) :: Bool where EQU a a = 'True EQU a b = 'False -- This class is used for emulating monad transformers class Member t r => MemberU2 (tag :: k -> * -> *) (t :: * -> *) r | tag r -> t instance (MemberU' (EQU t1 t2) tag t1 (t2 ': r)) => MemberU2 tag t1 (t2 ': r) class Member t r => MemberU' (f::Bool) (tag :: k -> * -> *) (t :: * -> *) r | tag r -> t instance MemberU' 'True tag (tag e) (tag e ': r) instance (Member t (t' ': r), MemberU2 tag t r) => MemberU' 'False tag t (t' ': r) -- Eff/Internal/FTCQueue1.hs -- Non-empty tree. Deconstruction operations make it more and more -- left-leaning data FTCQueue m a b where Leaf :: (a -> m b) -> FTCQueue m a b Node :: FTCQueue m a x -> FTCQueue m x b -> FTCQueue m a b -- Exported operations -- There is no tempty: use (tsingleton return), which works just the same. -- The names are chosen for compatibility with FastTCQueue {-# INLINE tsingleton #-} tsingleton :: (a -> m b) -> FTCQueue m a b tsingleton r = Leaf r -- snoc: clearly constant-time {-# INLINE (|>) #-} (|>) :: FTCQueue m a x -> (x -> m b) -> FTCQueue m a b t |> r = Node t (Leaf r) -- append: clearly constant-time {-# INLINE (><) #-} (><) :: FTCQueue m a x -> FTCQueue m x b -> FTCQueue m a b t1 >< t2 = Node t1 t2 -- Left-edge deconstruction data ViewL m a b where TOne :: (a -> m b) -> ViewL m a b (:|) :: (a -> m x) -> (FTCQueue m x b) -> ViewL m a b {-# INLINABLE tviewl #-} tviewl :: FTCQueue m a b -> ViewL m a b tviewl (Leaf r) = TOne r tviewl (Node t1 t2) = go t1 t2 where go :: FTCQueue m a x -> FTCQueue m x b -> ViewL m a b go (Leaf r) tr = r :| tr go (Node tl1 tl2) tr = go tl1 (Node tl2 tr)
AaronFriel/eff-experiments
examples/eff.hs
bsd-3-clause
6,762
1
15
1,685
2,428
1,262
1,166
-1
-1
-- | Support for command-line completion at the REPL and in the prover module Idris.Completion (replCompletion, proverCompletion) where import Core.Evaluate (ctxtAlist) import Core.TT import Core.CoreParser (opChars) import Idris.AbsSyntaxTree import Idris.Help import Control.Monad.State.Strict import Data.List import Data.Maybe import System.Console.Haskeline fst3 :: (a, b, c) -> a fst3 (a, b, c) = a commands = concatMap fst3 help -- | A specification of the arguments that tactics can take data TacticArg = NameTArg -- ^ Names: n1, n2, n3, ... n | ExprTArg | AltsTArg -- | A list of available tactics and their argument requirements tacticArgs :: [(String, Maybe TacticArg)] tacticArgs = [ ("intro", Nothing) -- FIXME syntax for intro (fresh name) , ("refine", Just ExprTArg) , ("mrefine", Just ExprTArg) , ("rewrite", Just ExprTArg) , ("let", Nothing) -- FIXME syntax for let , ("focus", Just ExprTArg) , ("exact", Just ExprTArg) , ("applyTactic", Just ExprTArg) , ("reflect", Just ExprTArg) , ("fill", Just ExprTArg) , ("try", Just AltsTArg) ] ++ map (\x -> (x, Nothing)) [ "intros", "compute", "trivial", "solve", "attack", "state", "term", "undo", "qed", "abandon", ":q" ] tactics = map fst tacticArgs -- | Convert a name into a string usable for completion. Filters out names -- that users probably don't want to see. nameString :: Name -> Maybe String nameString (UN ('@':_)) = Nothing nameString (UN ('#':_)) = Nothing nameString (UN n) = Just n nameString (NS n _) = nameString n nameString _ = Nothing -- FIXME: Respect module imports -- | Get the user-visible names from the current interpreter state. names :: Idris [String] names = do i <- get let ctxt = tt_ctxt i return . nub $ mapMaybe (nameString . fst) (ctxtAlist ctxt) ++ -- Explicitly add primitive types, as these are special-cased in the parser ["Int", "Integer", "Float", "Char", "String", "Type", "Ptr", "Bits8", "Bits16", "Bits32", "Bits64", "Bits8x16", "Bits16x8", "Bits32x4", "Bits64x2"] metavars :: Idris [String] metavars = do i <- get return . map (show . nsroot) $ idris_metavars i \\ primDefs modules :: Idris [String] modules = do i <- get return $ map show $ imported i completeWith :: [String] -> String -> [Completion] completeWith ns n = if uniqueExists then [simpleCompletion n] else map simpleCompletion prefixMatches where prefixMatches = filter (isPrefixOf n) ns uniqueExists = [n] == prefixMatches completeName :: [String] -> String -> Idris [Completion] completeName extra n = do ns <- names return $ completeWith (extra ++ ns) n completeExpr :: [String] -> CompletionFunc Idris completeExpr extra = completeWord Nothing (" \t(){}:" ++ opChars) (completeName extra) completeMetaVar :: CompletionFunc Idris completeMetaVar = completeWord Nothing (" \t(){}:" ++ opChars) completeM where completeM m = do mvs <- metavars return $ completeWith mvs m completeOption :: CompletionFunc Idris completeOption = completeWord Nothing " \t" completeOpt where completeOpt = return . (completeWith ["errorcontext", "showimplicits"]) isWhitespace :: Char -> Bool isWhitespace = (flip elem) " \t\n" lookupInHelp :: String -> Maybe CmdArg lookupInHelp cmd = lookupInHelp' cmd help where lookupInHelp' cmd ((cmds, arg, _):xs) | elem cmd cmds = Just arg | otherwise = lookupInHelp' cmd xs lookupInHelp' cmd [] = Nothing -- | Get the completion function for a particular command completeCmd :: String -> CompletionFunc Idris completeCmd cmd (prev, next) = fromMaybe completeCmdName $ fmap completeArg $ lookupInHelp cmd where completeArg FileArg = completeFilename (prev, next) completeArg NameArg = completeExpr [] (prev, next) -- FIXME only complete one name completeArg OptionArg = completeOption (prev, next) completeArg ModuleArg = noCompletion (prev, next) -- FIXME do later completeArg ExprArg = completeExpr [] (prev, next) completeArg MetaVarArg = completeMetaVar (prev, next) -- FIXME only complete one name completeArg NoArg = noCompletion (prev, next) completeCmdName = return $ ("", completeWith commands cmd) -- | Complete REPL commands and defined identifiers replCompletion :: CompletionFunc Idris replCompletion (prev, next) = case firstWord of ':':cmdName -> completeCmd (':':cmdName) (prev, next) _ -> completeExpr [] (prev, next) where firstWord = fst $ break isWhitespace $ dropWhile isWhitespace $ reverse prev completeTactic :: [String] -> String -> CompletionFunc Idris completeTactic as tac (prev, next) = fromMaybe completeTacName $ fmap completeArg $ lookup tac tacticArgs where completeTacName = return $ ("", completeWith tactics tac) completeArg Nothing = noCompletion (prev, next) completeArg (Just NameTArg) = noCompletion (prev, next) -- this is for binding new names! completeArg (Just ExprTArg) = completeExpr as (prev, next) completeArg (Just AltsTArg) = noCompletion (prev, next) -- TODO -- | Complete tactics and their arguments proverCompletion :: [String] -- ^ The names of current local assumptions -> CompletionFunc Idris proverCompletion assumptions (prev, next) = completeTactic assumptions firstWord (prev, next) where firstWord = fst $ break isWhitespace $ dropWhile isWhitespace $ reverse prev
christiaanb/Idris-dev
src/Idris/Completion.hs
bsd-3-clause
5,911
0
12
1,553
1,593
859
734
103
7
{-# LANGUAGE TypeFamilies #-} {-| Module : Numeric.AERN.RmToRn.Plot.CairoDrawable Description : abstraction for drawing on a Cairo canvas Copyright : (c) Michal Konecny License : BSD3 Maintainer : [email protected] Stability : experimental Portability : portable Abstraction for drawing on a Cairo canvas. -} module Numeric.AERN.RmToRn.Plot.CairoDrawable ( CairoDrawableFn(..), ) where import Numeric.AERN.RmToRn.Plot.Params (CanvasParams,FnPlotStyle) import Numeric.AERN.RmToRn.Domain import Graphics.Rendering.Cairo (Render) class CairoDrawableFn f where type CairoDrawFnEffortIndicator f cairoDrawFnDefaultEffort :: f -> (CairoDrawFnEffortIndicator f) {-| Plot the graph of a uni-variate function on the active cairo canvas. A multi-variate function is transformed into an univariate function by ranging all other variables over their entire domains and taking the union of all the uni-variate functions thus obtained. -} cairoDrawFnGraph :: CairoDrawFnEffortIndicator f -> CanvasParams (Domain f) -> ((Domain f, Domain f) -> (Double, Double)) {-^ conversion from [0,1]^2 (origin bottom left) to screen coords -} -> FnPlotStyle -> Var f {-^ the variable to map to the horizontal axis; the remaining variables are all substituted with their full range -} -> [f] {-^ a function to plot, given piecewise -} -> Render () {-| Plot the graph of a uni-variate function on the active cairo canvas. A multi-variate function is transformed into an univariate function by ranging all other variables over their entire domains and taking the union of all the uni-variate functions thus obtained. -} cairoDrawFnParameteric :: CairoDrawFnEffortIndicator f -> CanvasParams (Domain f) -> ((Domain f, Domain f) -> (Double, Double)) {-^ conversion from [0,1]^2 (origin bottom left) to screen coords -} -> FnPlotStyle -> Var f {-^ the variable to parametrise by; the remaining variables are all substituted with their full range -} -> [Var f] {-^ variables that should not be substituted with their full domain but sampled, potentially resulting in a non-rectangular shape -} -> [(f, f)] {-^ one function to map to the x axis, one to the y axis, the function pair is given piecewise -} -> Render ()
michalkonecny/aern
aern-realfn-plot-gtk/src/Numeric/AERN/RmToRn/Plot/CairoDrawable.hs
bsd-3-clause
2,493
0
15
626
262
150
112
29
0
{-# LANGUAGE ScopedTypeVariables #-} module EncodeDecode ( tests ) where import Control.Exception (catch,evaluate) import Data.Binary (Binary) import Data.ByteString (ByteString) import qualified Data.ByteString as S import Distribution.TestSuite (Test) import Distribution.TestSuite.QuickCheck (testProperty) import System.IO.Streams (write) import System.IO.Streams.Binary (binaryInputStream, binaryOutputStream, DecodeException) import System.IO.Streams.List (outputToList, fromList, toList, writeList) import Test.QuickCheck.Property (Property) import Test.QuickCheck.Monadic (monadicIO, assert, run) -- Using binary-streams, decode from a list of bytestrings decode :: Binary a => [ByteString] -> IO [a] decode ss = fromList ss >>= binaryInputStream >>= toList -- Using binary-streams, encode to a list of bytestrings encode :: Binary a => [a] -> IO [ByteString] encode xs = outputToList $ \os -> do bos <- binaryOutputStream os writeList xs bos write Nothing bos -- Encode something, then decode it and make sure we get the same thing back. encodeDecodeEq :: (Binary a,Eq a) => [a] -> Property encodeDecodeEq xs = monadicIO $ do xs' <- run go assert $ xs == xs' where go = encode xs >>= decode -- corrupt something, remove the last byte of the last bytestring corrupt :: [ByteString] -> [ByteString] corrupt = reverse . go . reverse where go (h:t) = ((S.reverse $ S.drop 1 $ S.reverse h):t) go [] = [] -- Encode something, corrupt the encoded data, and make sure we get a -- decode error when we try do decode it. encodeDecodeError :: forall a. (Binary a,Eq a) => [a] -> Property encodeDecodeError [] = monadicIO $ return () encodeDecodeError xs = monadicIO $ do run $ catch go $ \(_ :: DecodeException) -> return () where go = do bList <- encode xs (xs' :: [a]) <- decode $ corrupt bList evaluate xs' fail "decoding succeeded when it should fail" tests :: IO [Test] tests = return [testProperty "encode-decode-equality Int" (encodeDecodeEq :: [Int] -> Property), testProperty "encode-decode-equality String" (encodeDecodeEq :: [String] -> Property), testProperty "encode-decode-equality Maybe Int" (encodeDecodeEq :: [Maybe Int] -> Property), testProperty "encode-decode-equality Either Int String" (encodeDecodeEq :: [Either Int String] -> Property), testProperty "encode-decode-equality (Int,Int)" (encodeDecodeEq :: [(Int,Int)] -> Property), testProperty "encode-decode-equality (String,String)" (encodeDecodeEq :: [(Int,Int)] -> Property), testProperty "encode-decode-error Int" (encodeDecodeError :: [Int] -> Property), testProperty "encode-decode-error String" (encodeDecodeError :: [String] -> Property), testProperty "encode-decode-error Maybe Int" (encodeDecodeError :: [Maybe Int] -> Property), testProperty "encode-decode-error Either Int String" (encodeDecodeError :: [Either Int String] -> Property), testProperty "encode-decode-error (Int,Int)" (encodeDecodeError :: [(Int,Int)] -> Property), testProperty "encode-decode-error (String,String)" (encodeDecodeError :: [(String,String)] -> Property)]
jonpetterbergman/binary-streams
test/EncodeDecode.hs
bsd-3-clause
4,084
0
13
1,461
887
488
399
73
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} module Language.Haskell.Liquid.Spec.Extract ( -- * Extract Specifications from Annotations extractGhcSpec ) where import GHC hiding (Located) import Annotations import Class import CoreSyn import DataCon import Id import IdInfo import Name import NameEnv import Serialized import TyCon import Type import Var import VarEnv import VarSet import Control.Arrow import Control.Monad import Control.Monad.Trans import Data.Data (Data) import Data.List import Data.Maybe import Data.Typeable (Typeable) import qualified Data.HashMap.Strict as M import qualified Language.Haskell.TH.Syntax as TH import Text.PrettyPrint.HughesPJ hiding (first) import Language.Fixpoint.Misc import Language.Fixpoint.Types import Language.Haskell.Liquid.GhcMisc import Language.Haskell.Liquid.Measure import Language.Haskell.Liquid.PredType hiding (freeTyVars) import Language.Haskell.Liquid.RefType import Language.Haskell.Liquid.Types hiding (freeTyVars) import Language.Haskell.Liquid.TH.Types import Language.Haskell.Liquid.Spec.Check import Language.Haskell.Liquid.Spec.CoreToLogic import Language.Haskell.Liquid.Spec.Lookup import Language.Haskell.Liquid.Spec.Reify -------------------------------------------------------------------------------- -- Extract Specifications from Annotations ------------------------------------- -------------------------------------------------------------------------------- extractGhcSpec :: Module -> Maybe Module -> [Var] -> [Annotation] -> [CoreBind] -> GhcSpec -> Ghc GhcSpec extractGhcSpec mod sig letVs anns cbs scope = do (tySigs', asmSigs', ctors') <- extractVarSpecs (isJust sig) letVs anns rtEnv' <- extractSynSpecs anns tcEmbeds' <- extractTcEmbeds mod sig anns (tinlines', meas', qualifiers') <- extractLiftedLogic (mappend tcEmbeds' $ tcEmbeds scope) anns cbs return $ mempty { tySigs = tySigs' , asmSigs = asmSigs' , ctors = ctors' , rtEnv = rtEnv' , tcEmbeds = tcEmbeds' , tinlines = tinlines' , meas = meas' , qualifiers = qualifiers' } extractVarSpecs :: Bool -> [Var] -> [Annotation] -> Ghc ( M.HashMap Var (Located SpecType) , M.HashMap Var (Located SpecType) , M.HashMap Var (Located SpecType) ) extractVarSpecs isSig letVs anns = do sigs <- mapM ofAnn $ annotationsOfType anns let (tys, asms, ctors) = foldl' categorize ([],[],[]) sigs return (M.fromList tys, M.fromList asms, M.fromList ctors) where ofAnn (name, LiquidVar full assumed ty span) = do var <- lookupVar $ spanLocated span name ty' <- traverse reifyRTy ty return (var, assumed, completeRTy full var <$> ty') categorize (tys, asms, ctors) (var, assumed, ty) | isDataConId var = (tys, asms, (var, ty):ctors) | assumed || isSig = (tys, (var, ty):asms, ctors) | otherwise = ((var, ty):tys, asms, ctors) lookupVar name = case lookupNameEnv varEnv $ val name of Just v -> return v Nothing -> lookupGhcVar name varEnv = mkNameEnv $ map (\v -> (getName v, v)) letVs extractSynSpecs :: [Annotation] -> Ghc RTEnv extractSynSpecs anns = M.fromList <$> mapM ofAnn (annotationsOfType anns) where ofAnn (name, LiquidSyn evs rhs span) = do tc <- lookupGhcTyCon $ spanLocated span name rhs' <- traverse reifyRTy rhs let Just (tvs, _) = synTyConDefn_maybe tc let tvs' = map (stringRTyVar . getOccString) tvs return (tc, RTA tvs' (map symbol evs) rhs') extractTcEmbeds :: Module -> Maybe Module -> [Annotation] -> Ghc (TCEmb TyCon) extractTcEmbeds mod sig anns = do emb <- mapM ofAnn $ annotationsOfType anns throwsGhc $ checkDupEmbeds emb ++ checkLocalEmbeds mod sig emb return $ M.fromList $ second val <$> emb where ofAnn (name, EmbedAs ftc span) = do tc <- lookupGhcTyCon $ spanLocated span name return (tc, ftc) extractLiftedLogic :: TCEmb TyCon -> [Annotation] -> [CoreBind] -> Ghc ( M.HashMap Var TInline , M.HashMap LocSymbol SpecMeasure , M.HashMap Var Qualifier ) extractLiftedLogic tce anns cbs = do (inlines, measures, qualifiers) <- foldM ofAnn ([],[],[]) $ annotationsOfType anns throwsGhc $ checkDupLogic (fst <$> inlines) (fst <$> measures) (fst <$> qualifiers) return ( M.fromList $ map (first val) inlines , M.fromList measures , M.fromList $ map (first val) qualifiers ) where coreEnv = buildCoreEnv cbs ofAnn (inlines, measures, qualifiers) (name, LiftToLogic kind span) = do var <- lookupGhcVar $ spanLocated span name let sym = spanLocated span $ plainVarSymbol var let Just bind = lookupVarEnv coreEnv var let liftToLogic dsc tx = case runToLogic mempty $ tx sym var bind of Left res -> return res Right err -> throwGhc $ liftErr span var dsc err case kind of InlineKind -> do ti <- mkInline <$> liftToLogic "measure" coreToFun return ((spanLocated span var, ti) : inlines, measures, qualifiers) BoundKind -> error "extractLiftedLogic: lifting bounds not yet implemented" MeasureKind -> do me <- mkMeasure var <$> liftToLogic "inline" coreToDef return (inlines, (sym, me) : measures, qualifiers) QualifKind -> do qu <- mkQualifier var sym =<< liftToLogic "qualifier" coreToFun return (inlines, measures, (spanLocated span var, qu) : qualifiers) mkInline (xs, e) = TI (symbol <$> xs) e mkMeasure var defs = M (logicType $ varType var) (dataConTypes defs) mkQualifier _ sym (xs, Left p) = return $ Q (val sym) (mkQualParam <$> xs) (mkQualBody xs p) (loc sym) mkQualifier var sym (_, Right _) = throwGhc $ qualErr var sym mkQualBody xs p = subst (mkSubst $ map (symbol &&& (EVar . plainVarSymbol)) xs) p mkQualParam x = (plainVarSymbol x, typeSort tce $ varType x) liftErr :: SourceSpan -> Var -> String -> String -> Error liftErr (SourceSpan start end) var dsc err = ErrLiftToLogic (mkSrcSpan' start end) (pprint var) (text dsc) (text err) qualErr :: Var -> LocSymbol -> Error qualErr var sym = ErrQualifType (locatedSrcSpan sym) (pprint var) (ofType $ varType var) -------------------------------------------------------------------------------- -- Utility Functions ----------------------------------------------------------- -------------------------------------------------------------------------------- annotationsOfType :: (Data a, Typeable a) => [Annotation] -> [(Name, a)] annotationsOfType = mapMaybe go where go (Annotation (NamedTarget name) payload) | Just val <- fromSerialized deserializeWithData payload = Just (name, val) go _ = Nothing buildCoreEnv :: [CoreBind] -> VarEnv CoreExpr buildCoreEnv = mkVarEnv . concatMap go where go (NonRec v def) = [(v, def)] go (Rec xes) = xes completeRTy :: Bool -> Var -> SpecType -> SpecType completeRTy full var ty | full = ty | isId var, Just cls <- isClassOpId_maybe var = let tc = classTyCon cls tvs = map plainRTyVar (classTyVars cls) in quantifyRTy tvs $ rFun dummySymbol (rApp tc (flip RVar mempty <$> tvs) [] mempty) $ quantifyRTy (freeTyVars ty \\ tvs) ty | isId var, isRecordSelector var = let dc = recordSelectorDataCon var dcTy = dataConOrigResTy dc dcTvs = plainRTyVar <$> varSetElemsKvsFirst (tyVarsOfType dcTy) tvs = nub $ dcTvs ++ freeTyVars ty in quantifyRTy tvs $ foldr (rFun dummySymbol) ty $ map ofType $ dataConStupidTheta dc ++ [dcTy] | otherwise = quantifyFreeRTy ty
spinda/liquidhaskell
src/Language/Haskell/Liquid/Spec/Extract.hs
bsd-3-clause
8,083
0
18
2,053
2,539
1,312
1,227
171
6
{-# LANGUAGE CPP #-} module Main where import Test.Tasty (defaultMain, testGroup) import qualified ParensParsec main = defaultMain $ testGroup "All tests" $ [ ParensParsec.allTests ]
lambdageek/indentation
indentation-parsec/tests/all-tests.hs
bsd-3-clause
196
0
7
38
43
26
17
8
1
module Air.Extra where import Control.Parallel import Data.Char import Data.List ((\\)) import Data.Maybe import Data.Time import Data.Time.Clock.POSIX import Air.Light hiding (reduce, reduce') import Numeric import Prelude hiding ((.), (^), (>), (<), (/), elem, foldl, (-)) import System.Directory import System.IO -- import System.Locale (defaultTimeLocale) import Text.RegexPR import qualified Data.List as L import qualified Prelude as Prelude import qualified System.IO.Unsafe as Unsafe import Data.List (foldl1') import qualified Data.Text as T import qualified Data.Text.Encoding as E import qualified Data.ByteString.Char8 as B -- BEGIN !!!!!! partial, use with extra care -- backport reduce, reduce' :: (a -> a -> a) -> [a] -> a reduce = foldl1 reduce' = foldl1' -- Parallel p_eval, p_eval' :: [a] -> [a] p_reduce, p_reduce' :: (a -> a -> a) -> [a] -> a p_map, p_map' :: (a -> b) -> [a] -> [b] p_split_to :: Int -> [t] -> [[t]] p_map_reduce_to :: Int -> ([a] -> b) -> (b -> b -> b) -> [a] -> b p_map_reduce :: ([a] -> b) -> (b -> b -> b) -> [a] -> b p_eval xs = xs.par(xs.reduce(par)) p_reduce op xs = xs.p_eval.reduce(op) p_map op xs = xs.map(op).p_eval p_eval' xs = xs.pseq( xs.reduce par ) p_reduce' op xs = xs.p_eval'.reduce op p_map' op xs = xs.map op .p_eval' p_split_to n xs = xs.in_group_of(n).L.transpose p_map_reduce_to n m r xs = xs.split_to n .map m .p_reduce' r p_map_reduce m r xs = p_map_reduce_to 16 m r xs -- END !!!!!! b2u, u2b :: String -> String b2u = B.pack > E.decodeUtf8 > T.unpack u2b = T.pack > E.encodeUtf8 > B.unpack -- Date date :: Integer -> Int -> Int -> Data.Time.Day splash_date :: Data.Time.Day -> (Integer, Int, Int) date = fromGregorian splash_date = toGregorian -- String split_raw :: String -> String -> [String] split_raw re xs | xs.match re .isJust = splitRegexPR re xs | otherwise = [xs] split :: String -> String -> [String] split re xs = split_raw re xs .reject empty split' :: String -> [String] split' s = s.lines.reject empty sub :: String -> String -> String -> String sub = subRegexPR gsub :: String -> String -> String -> String gsub = gsubRegexPR type RegexResult = ( String, (String, String) ) type MatchList = [ (Int, String) ] match :: String -> String -> Maybe (RegexResult, MatchList) match = matchRegexPR strip :: String -> String strip s = s.sub "^\\s*" "" .reverse .sub "^\\s*" "" .reverse empty :: String -> Bool empty s = case s.match("\\S") of Just _ -> False Nothing -> True -- Integer collapse :: (Integral a, Num b) => [a] -> b collapse xs = collapse' (xs.reverse.map from_i) (0 :: Int) (0 :: Int) .fromIntegral where collapse' [] _ r = r collapse' (x:xs') q r = collapse' xs' (q+1) (r + x * 10 Prelude.^ q) base :: (Integral a, Show a) => a -> a -> String base p n = showIntAtBase p intToDigit n "" -- String camel_case, snake_case :: String -> String camel_case = split "_" > map capitalize > concat snake_case = gsub "\\B[A-Z]" "_\\&" > lower -- IO -- Should only be used to initialize IORefs, etc. purify :: IO a -> a purify = Unsafe.unsafePerformIO ls :: String -> IO [String] ls s = getDirectoryContents s ^ (\\ [".", ".."]) file_size :: String -> IO Integer file_size path = withFile path ReadMode hFileSize file_mtime :: String -> IO UTCTime file_mtime = getModificationTime read_binary_file :: String -> IO String read_binary_file path = path.u2b.B.readFile ^ B.unpack get_permissions :: String -> IO Permissions get_permissions path = getPermissions path get_current_directory :: IO String get_current_directory = getCurrentDirectory ^ b2u -- Time now :: IO UTCTime now = getCurrentTime format_time :: String -> UTCTime -> String format_time = formatTime defaultTimeLocale simple_time_format :: String simple_time_format = "%Y-%m-%d %H:%M:%S %Z" now_in_zoned_time :: IO String now_in_zoned_time = do timestamp <- now tz <- getCurrentTimeZone let zoned_time = utcToZonedTime tz timestamp let time_str = formatTime defaultTimeLocale simple_time_format zoned_time return time_str parse_time :: String -> String -> UTCTime parse_time = readTime defaultTimeLocale t2i :: UTCTime -> Integer t2i = utcTimeToPOSIXSeconds > floor t2f :: (Fractional a) => UTCTime -> a t2f = utcTimeToPOSIXSeconds > toRational > fromRational i2t :: Integer -> UTCTime i2t = from_i > posixSecondsToUTCTime f2t :: (Real a) => a -> UTCTime f2t = toRational > fromRational > posixSecondsToUTCTime -- Text filter_comment :: String -> String filter_comment = lines > map strip > reject null > reject (first > (== Just '#')) > unlines -- IO line_buffer :: IO () line_buffer = do hSetBuffering stdout LineBuffering hSetBuffering stderr LineBuffering
nfjinjing/air-extra
src/Air/Extra.hs
bsd-3-clause
4,797
11
11
955
1,731
952
779
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Report where import FattyAcid import Spectra import Results import Numeric (showFFloat) import Data.List (sortBy, maximumBy, intersperse) import Data.Ord (comparing, Down(..)) import Data.Monoid ((<>)) import Data.ByteString (ByteString) import Data.ByteString.Char8 (pack) nMostAbundantFAs :: Int -> [IdentifiedFA] -> [IdentifiedFA] nMostAbundantFAs n = take n . sortBy (comparing (Down . identifiedFAAbund)) mostAbundantFA' :: (IdentifiedFA -> Bool) -> [IdentifiedFA] -> Maybe IdentifiedFA mostAbundantFA' f fas = if null fas then Nothing else Just . maximumBy (comparing identifiedFAAbund) $ filter f fas mostAbundantSaturatedFA :: [IdentifiedFA] -> Maybe IdentifiedFA mostAbundantSaturatedFA = mostAbundantFA' isSaturated mostAbundantMonounsaturatedFA :: [IdentifiedFA] -> Maybe IdentifiedFA mostAbundantMonounsaturatedFA = mostAbundantFA' isMonounsaturated mostAbundantFAPolyunsaturated :: [IdentifiedFA] -> Maybe IdentifiedFA mostAbundantFAPolyunsaturated = mostAbundantFA' isPolyunsaturated spectraWithIdentifiedTAGs :: [TAGSummary] -> [TAGSummary] spectraWithIdentifiedTAGs = filter (not . null . condensedTriacylglycerols) mostAbundantTAG :: [TAGSummary] -> Maybe TAGSummary mostAbundantTAG tags = if null tags then Nothing else Just $ maximumBy (comparing tagSummayNormalisedAbundance) (spectraWithIdentifiedTAGs tags) normalisedAbundanceTotalTAGs :: [TAGSummary] -> NormalisedAbundance normalisedAbundanceTotalTAGs = sum . fmap tagSummayNormalisedAbundance . spectraWithIdentifiedTAGs -- Adapted from https://stackoverflow.com/questions/1559590/haskell-force-floats-to-have-two-decimals formatFloatN :: RealFloat a => Int -> a-> String formatFloatN numOfDecimals floatNum = showFFloat (Just numOfDecimals) floatNum "" formatListToString :: Show a => [a] -> String formatListToString l = case reverse (intersperse ", " (show <$> l)) of [] -> "" [x] -> x (x:_:xs) -> concat . reverse $ x : " and " : xs formatListToString' :: [String] -> String formatListToString' l = case reverse (intersperse ", " l) of [] -> "" [x] -> x (x:_:xs) -> concat . reverse $ x : " and " : xs abundanceAssignedFAs :: RealFloat a => a -> ByteString abundanceAssignedFAs a = "Of the neutral losses observed, " <> n <> "% (by normalised abundance) were assigned to fatty neutral losses. " where n = pack $ formatFloatN 2 a faDescription :: [IdentifiedFA] -> ByteString faDescription fas = case topThree of [] -> "No fatty acids were identified." [_] -> "The most abundant fatty acid identified was " <> topThreeFA <> " with a normalised abundance of " <> topThreeAbun <> "%, respectively. " _ -> "The " <> n <> " most abundant fatty acids identified were " <> topThreeFA <> " with normalised abundances of " <> topThreeAbun <> "%, respectively. " <> saturationFAs where topThree = nMostAbundantFAs 3 fas n = pack . show $ length topThree topThreeFA = pack . formatListToString $ identifiedFA <$> topThree topThreeAbun = pack . formatListToString' $ formatFloatN 2 . identifiedFAAbund <$> topThree saturationFAs = let sat = mostAbundantSaturatedFA fas mono = mostAbundantMonounsaturatedFA fas poly = mostAbundantFAPolyunsaturated fas in case (sat, mono, poly) of (Nothing, Nothing, Nothing) -> "" (Just fa, Nothing, Nothing) -> "The most abundant saturated fatty acids was " <> pack (show (identifiedFA fa)) <> " with an abundance of " <> pack (formatFloatN 2 (identifiedFAAbund fa)) <> "%. " (Nothing, Just fa, Nothing) -> "The most abundant monounsaturated fatty acids was " <> pack (show (identifiedFA fa)) <> " with an abundance of " <> pack (formatFloatN 2 (identifiedFAAbund fa)) <> "%. " (Nothing, Nothing, Just fa) -> "The most abundant polyunsaturated fatty acids was " <> pack (show (identifiedFA fa)) <> " with an abundance of " <> pack (formatFloatN 2 (identifiedFAAbund fa)) <> "%. " (Just sat', Just mono', Nothing) -> "The most abundant monounsaturated and saturated fatty acids were " <> pack (formatListToString (identifiedFA <$> [mono', sat'])) <> " with abundances of " <> pack (formatListToString' (formatFloatN 2 . identifiedFAAbund <$> [mono', sat'])) <> "%, respectively. " (Just sat', Nothing, Just poly') -> "The most abundant polyunsaturated, and saturated fatty acids were " <> pack (formatListToString (identifiedFA <$> [poly', sat'])) <> " with abundances of " <> pack (formatListToString' (formatFloatN 2 . identifiedFAAbund <$> [poly', sat'])) <> "%, respectively. " (Nothing, Just mono', Just poly') -> "The most abundant polyunsaturated, monounsaturated fatty acids were " <> pack (formatListToString (identifiedFA <$> [poly', mono'])) <> " with abundances of " <> pack (formatListToString' (formatFloatN 2 . identifiedFAAbund <$> [poly', mono'])) <> "%, respectively. " (Just sat', Just mono', Just poly') -> "The most abundant polyunsaturated, monounsaturated and saturated fatty acids were " <> pack (formatListToString (identifiedFA <$> [poly', mono', sat'])) <> " with abundances of " <> pack (formatListToString' (formatFloatN 2 . identifiedFAAbund <$> [poly', mono', sat'])) <> "%, respectively. " identifedTAGInfo :: [TAGSummary] -> ByteString identifedTAGInfo tags = "Triacylglycerols were identified for " <> pack (show (length (spectraWithIdentifiedTAGs tags))) <> " of the " <> pack (show (length tags)) <> " collision-induced dissociation spectra (" <> pack (formatFloatN 2 (normalisedAbundanceTotalTAGs tags)) <> "% by normalised abundance). " <> case mostAbundantTAG tags of Nothing -> "No triacylglycerols were identified." Just tag -> case condensedTriacylglycerols tag of [] -> "No triacylglycerols were identified." [tag'] -> "The most abundant triacylglycerol identified at the \ \species level was " <> pack (show tag') <> " with a normalised abundance of " <> pack (formatFloatN 2 (tagSummayNormalisedAbundance tag)) <> "%. This species level triacylglycerol corresponds to the following \ \possible alkyl bond level triacylglycerols: " <> pack (formatListToString (triacylglycerols tag)) <> "." tags' -> "The most abundant triacylglycerols identified at the \ \species level were " <> pack (formatListToString tags') <> " with a combined normalised abundance of " <> pack ((formatFloatN 2 . tagSummayNormalisedAbundance) tag) <> "% (Note: Using low-resolution mass spectrometry, these species level \ \triacylglycerols have the same m/z ratio). These species level \ \triacylglycerols correspond to the following possible alkyl bond \ \level triacylglycerols: " <> pack (formatListToString (triacylglycerols tag)) <> "." report :: NormalisedAbundance -> [IdentifiedFA] -> [TAGSummary] -> ByteString report a fas tags = "Fatty acids were identified from neutral losses observed in collision-induced \ \dissociation spectra of protonated triacylglycerol ions. " <> abundanceAssignedFAs a <> faDescription fas <> "\n\nTriacylglycerols were identified by analysing the neutral losses observed in \ \collision-induced dissociation spectra. " <> identifedTAGInfo tags
Michaelt293/lipase
src/Report.hs
bsd-3-clause
7,869
0
21
1,890
1,796
929
867
175
10
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UnicodeSyntax #-} {-| [@ISO639-1@] af [@ISO639-2@] afr [@ISO639-3@] afr [@Native name@] Afrikaans [@English name@] Afrikaans -} module Text.Numeral.Language.AFR ( -- * Language entry entry -- * Conversions , cardinal , ordinal -- * Structure , struct -- * Bounds , bounds ) where -------------------------------------------------------------------------------- -- Imports -------------------------------------------------------------------------------- import "base" Data.Bool ( otherwise ) import "base" Data.Function ( ($), const, fix ) import "base" Data.Maybe ( Maybe(Just) ) import "base" Data.Ord ( (<) ) import "base" Prelude ( Integral, (-), negate ) import "base-unicode-symbols" Data.Function.Unicode ( (∘) ) import qualified "containers" Data.Map as M ( fromList, lookup ) import "this" Text.Numeral import qualified "this" Text.Numeral.BigNum as BN import qualified "this" Text.Numeral.Exp as E import "this" Text.Numeral.Misc ( dec ) import "this" Text.Numeral.Entry import "text" Data.Text ( Text ) -------------------------------------------------------------------------------- -- AF -------------------------------------------------------------------------------- entry ∷ Entry entry = emptyEntry { entIso639_1 = Just "af" , entIso639_2 = ["afr"] , entIso639_3 = Just "afr" , entNativeNames = ["Afrikaans"] , entEnglishName = Just "Afrikaans" , entCardinal = Just Conversion { toNumeral = cardinal , toStructure = struct } , entOrdinal = Just Conversion { toNumeral = ordinal , toStructure = struct } } cardinal ∷ (Integral Ξ±, E.Scale Ξ±) β‡’ i β†’ Ξ± β†’ Maybe Text cardinal inf = cardinalRepr inf ∘ struct ordinal ∷ (Integral Ξ±, E.Scale Ξ±) β‡’ i β†’ Ξ± β†’ Maybe Text ordinal inf = ordinalRepr inf ∘ struct struct ∷ ( Integral Ξ±, E.Scale Ξ± , E.Unknown Ξ², E.Lit Ξ², E.Neg Ξ², E.Add Ξ², E.Mul Ξ², E.Scale Ξ² ) β‡’ Ξ± β†’ Ξ² struct = pos $ fix $ findRule ( 0, lit ) [ ( 13, add 10 L ) , ( 20, mul 10 L L) , ( 100, step1 100 10 R L) , (1000, step1 1000 1000 R L) ] (dec 6 - 1) `combine` pelletierScale1 R L BN.rule bounds ∷ (Integral Ξ±) β‡’ (Ξ±, Ξ±) bounds = let x = dec 60000 - 1 in (negate x, x) genericRepr ∷ Repr i genericRepr = defaultRepr { reprAdd = Just (⊞) , reprMul = Just (⊑) , reprNeg = Just $ \_ _ β†’ "min " } where (_ ⊞ Lit 10) _ = "" (Lit n ⊞ _) _ | n < 10 = "-en-" | otherwise = "" (_ ⊞ _) _ = " " (_ ⊑ Lit _) _ = "" (_ ⊑ _ ) _ = " " cardinalRepr ∷ i β†’ Exp i β†’ Maybe Text cardinalRepr = render genericRepr { reprValue = \_ n β†’ M.lookup n syms , reprScale = BN.pelletierRepr (\_ _ β†’ "iljoen") (\_ _ β†’ "iljard") [] } where syms = M.fromList [ (0, const "nul") , (1, const "een") , (2, forms "twee" "twin") , (3, forms "drie" "der") , (4, forms "vier" "veer") , (5, const "vyf") , (6, const "ses") , (7, forms "sewe" "sewen") , (8, \c β†’ case c of CtxMul _ (Lit 10) _ β†’ "tag" _ β†’ "ag" ) , (9, \c β†’ case c of CtxAdd _ (Lit 10) _ β†’ "negen" CtxMul _ (Lit 10) _ β†’ "neΓ«n" _ β†’ "nege" ) , (10, \c β†’ case c of CtxMul R _ _ β†’ "tig" _ β†’ "tien" ) , (11, const "elf") , (12, const "twaalf") , (100, const "honderd") , (1000, const "duisend") ] forms ∷ s β†’ s β†’ Ctx (Exp i) β†’ s forms n t ctx = case ctx of CtxMul _ (Lit 10) _ β†’ t CtxAdd _ (Lit 10) _ β†’ t CtxAdd _ (Lit _) _ β†’ n _ β†’ n ordinalRepr ∷ i β†’ Exp i β†’ Maybe Text ordinalRepr = render genericRepr { reprValue = \_ n β†’ M.lookup n syms , reprScale = BN.pelletierRepr (\_ _ β†’ "iljoen") (\_ _ β†’ "iljard") [] } where syms = M.fromList [ (0, const "nul") , (1, \c β†’ case c of CtxEmpty β†’ "eerste" _ | isOutside R c β†’ "eende" | otherwise β†’ "een" ) , (2, forms "tweede" "twee" "twin") , (3, forms "derde" "drie" "der") , (4, forms "vierde" "vier" "veer") , (5, \c β†’ if isOutside R c then "vyfde" else "vyf") , (6, \c β†’ if isOutside R c then "sesde" else "ses") , (7, forms "sewende" "sewe" "sewen") , (8, \c β†’ case c of _ | isOutside R c β†’ "agtste" CtxMul _ (Lit 10) _ β†’ "tag" _ β†’ "ag" ) , (9, \c β†’ case c of _ | isOutside R c β†’ "negende" CtxAdd _ (Lit 10) _ β†’ "negen" CtxMul _ (Lit 10) _ β†’ "neΓ«n" _ β†’ "nege" ) , (10, \c β†’ case c of CtxMul R _ _ | isOutside R c β†’ "tigste" | otherwise β†’ "tig" _ | isOutside R c β†’ "tiende" | otherwise β†’ "tien" ) , (11, \c β†’ if isOutside R c then "elfde" else "elf") , (12, \c β†’ if isOutside R c then "twaalfde" else "twaalf") , (100, \c β†’ if isOutside R c then "honderste" else "honderd") , (1000, \c β†’ if isOutside R c then "duisendste" else "duisend") ] forms ∷ s β†’ s β†’ s β†’ Ctx (Exp i) β†’ s forms o c t ctx = case ctx of _ | isOutside R ctx β†’ o CtxMul _ (Lit 10) _ β†’ t CtxAdd _ (Lit 10) _ β†’ t CtxAdd _ (Lit _) _ β†’ c _ β†’ c
telser/numerals
src/Text/Numeral/Language/AFR.hs
bsd-3-clause
7,193
74
12
3,272
1,572
994
578
147
18
module ProjectEuler.Problem034 (solution034) where import Control.Monad import Data.Digits import Data.Function.Memoize import Util mFact :: Integer -> Integer mFact = memoize fact equalToSumOfDigitsFactorials :: Integer -> Bool equalToSumOfDigitsFactorials = ap (==) (sum . map mFact . digits 10) genericSolution :: Integer -> Integer genericSolution = sum . filter equalToSumOfDigitsFactorials . enumFromTo 10 solution034 :: Integer solution034 = genericSolution 1e5
guillaume-nargeot/project-euler-haskell
src/ProjectEuler/Problem034.hs
bsd-3-clause
474
0
9
63
126
69
57
13
1
module Main where import System.Cmd import System.Directory import Paths_const_math_ghc_plugin main = do testdir <- getDataFileName "tests" setCurrentDirectory testdir system "make && make clean"
kfish/const-math-ghc-plugin
tests/Make.hs
bsd-3-clause
211
0
8
38
44
22
22
8
1
{-# LANGUAGE RebindableSyntax #-} -- Copyright : (C) 2009 Corey O'Connor -- License : BSD-style (see the file LICENSE) import Bind.Marshal.Prelude import Bind.Marshal.Verify import Bind.Marshal.StdLib main = run_test $ do returnM () :: Test ()
coreyoconnor/bind-marshal
test/verify_stdlib.hs
bsd-3-clause
260
1
9
51
50
27
23
6
1
module NameGenerator where import Network import System.IO import Data.List getName :: IO String getName = do h <- connectTo "www.urbandictionary.com" (PortNumber 80) hSetBuffering h LineBuffering hPutStr h "GET /random.php HTTP/1.1\r\nHost: www.urbandictionary.com\r\n\r\n" contents <- searchLines h let term = findTerm contents hClose h return term searchLines :: Handle -> IO String searchLines h = do l <- hGetLine h if "<html><body>" `isPrefixOf` l then return l else searchLines h findTerm :: String -> String findTerm [] = [] findTerm ('t':'e':'r':'m':'=':s) = replaces (takeWhile (/='\"') s) [("+"," "),("%27","'"),("%24","$"),("%23","#")] findTerm (_:rest) = findTerm rest replace :: (Eq a) => [a] -> ([a],[a]) -> [a] replace [] _ = [] replace ls@(a:s) (x,y) | x `isPrefixOf` ls = y ++ replace ((drop $ length x) ls) (x,y) | otherwise = a:replace s (x,y) replaces :: (Eq a) => [a] -> [([a],[a])] -> [a] replaces = foldl' replace
thomasathorne/h-chu
src/NameGenerator.hs
bsd-3-clause
1,001
2
12
206
442
240
202
29
2
{-# LANGUAGE OverloadedStrings, OverloadedLists #-} -- | Tests the @toLess@ function in "Penny.Stream". -- -- Expected output: -- -- @less@ appears with numbers from 0 to 1000 appearing, one number on -- each line. module Main where import Penny.Stream (toLess, streamToStdin) import Data.Sequence (fromList) import qualified Data.Text as X import Rainbow (chunk, byteStringMakerFromEnvironment) main :: IO () main = do maker <- byteStringMakerFromEnvironment let chunks = fmap (chunk . flip X.snoc '\n' . X.pack . show) . fromList $ [0..1000] str = streamToStdin toLess str maker chunks
massysett/penny
penny/testExe/testLess.hs
bsd-3-clause
612
0
18
111
140
79
61
13
1
{-# LANGUAGE RecordWildCards, ScopedTypeVariables, TupleSections #-} module Development.Shake.Internal.History.Shared( Shared, newShared, addShared, lookupShared, removeShared, listShared, sanityShared ) where import Control.Exception import Development.Shake.Internal.Value import Development.Shake.Internal.History.Types import Development.Shake.Internal.History.Symlink import Development.Shake.Internal.Core.Database import Development.Shake.Classes import General.Binary import General.Extra import Data.List import Control.Monad.Extra import System.Directory.Extra import System.FilePath import System.IO.Extra import Numeric import Development.Shake.Internal.FileInfo import General.Wait import Development.Shake.Internal.FileName import Data.Monoid import Control.Monad.IO.Class import Data.Maybe import qualified Data.ByteString as BS import Prelude data Shared = Shared {globalVersion :: !Ver ,keyOp :: BinaryOp Key ,sharedRoot :: FilePath ,useSymlink :: Bool } newShared :: Bool -> BinaryOp Key -> Ver -> FilePath -> IO Shared newShared useSymlink keyOp globalVersion sharedRoot = pure Shared{..} data Entry = Entry {entryKey :: Key ,entryGlobalVersion :: !Ver ,entryBuiltinVersion :: !Ver ,entryUserVersion :: !Ver ,entryDepends :: [[(Key, BS_Identity)]] ,entryResult :: BS_Store ,entryFiles :: [(FilePath, FileHash)] } deriving (Show, Eq) putEntry :: BinaryOp Key -> Entry -> Builder putEntry binop Entry{..} = putExStorable entryGlobalVersion <> putExStorable entryBuiltinVersion <> putExStorable entryUserVersion <> putExN (putOp binop entryKey) <> putExN (putExList $ map (putExList . map putDepend) entryDepends) <> putExN (putExList $ map putFile entryFiles) <> putEx entryResult where putDepend (a,b) = putExN (putOp binop a) <> putEx b putFile (a,b) = putExStorable b <> putEx a getEntry :: BinaryOp Key -> BS.ByteString -> Entry getEntry binop x | (x1, x2, x3, x) <- binarySplit3 x , (x4, x) <- getExN x , (x5, x) <- getExN x , (x6, x7) <- getExN x = Entry {entryGlobalVersion = x1 ,entryBuiltinVersion = x2 ,entryUserVersion = x3 ,entryKey = getOp binop x4 ,entryDepends = map (map getDepend . getExList) $ getExList x5 ,entryFiles = map getFile $ getExList x6 ,entryResult = getEx x7 } where getDepend x | (a, b) <- getExN x = (getOp binop a, getEx b) getFile x | (b, a) <- binarySplit x = (getEx a, b) hexed x = showHex (abs $ hash x) "" -- | The path under which everything relating to a Key lives sharedFileDir :: Shared -> Key -> FilePath sharedFileDir shared key = sharedRoot shared </> ".shake.cache" </> hexed key -- | The list of files containing Entry values, given a result of 'sharedFileDir' sharedFileKeys :: FilePath -> IO [FilePath] sharedFileKeys dir = do b <- doesDirectoryExist_ $ dir </> "_key" if not b then pure [] else listFiles $ dir </> "_key" loadSharedEntry :: Shared -> Key -> Ver -> Ver -> IO [IO (Maybe Entry)] loadSharedEntry shared@Shared{..} key builtinVersion userVersion = map f <$> sharedFileKeys (sharedFileDir shared key) where f file = do e@Entry{..} <- getEntry keyOp <$> BS.readFile file let valid = entryKey == key && entryGlobalVersion == globalVersion && entryBuiltinVersion == builtinVersion && entryUserVersion == userVersion pure $ if valid then Just e else Nothing -- | Given a way to get the identity, see if you can find a stored cloud version lookupShared :: Shared -> (Key -> Wait Locked (Maybe BS_Identity)) -> Key -> Ver -> Ver -> Wait Locked (Maybe (BS_Store, [[Key]], IO ())) lookupShared shared ask key builtinVersion userVersion = do ents <- liftIO $ loadSharedEntry shared key builtinVersion userVersion flip firstJustWaitUnordered ents $ \act -> do me <- liftIO act case me of Nothing -> pure Nothing Just Entry{..} -> do -- use Nothing to indicate success, Just () to bail out early on mismatch let result x = if isJust x then Nothing else Just $ (entryResult, map (map fst) entryDepends, ) $ do let dir = sharedFileDir shared entryKey forM_ entryFiles $ \(file, hash) -> copyFileLink (useSymlink shared) (dir </> show hash) file result <$> firstJustM id [ firstJustWaitUnordered id [ test <$> ask k | (k, i1) <- kis , let test = maybe (Just ()) (\i2 -> if i1 == i2 then Nothing else Just ())] | kis <- entryDepends] saveSharedEntry :: Shared -> Entry -> IO () saveSharedEntry shared entry = do let dir = sharedFileDir shared (entryKey entry) createDirectoryRecursive dir forM_ (entryFiles entry) $ \(file, hash) -> unlessM (doesFileExist_ $ dir </> show hash) $ copyFileLink (useSymlink shared) file (dir </> show hash) -- Write key after files to make sure cache is always useable let v = runBuilder $ putEntry (keyOp shared) entry let dirName = dir </> "_key" createDirectoryRecursive dirName -- #757, make sure we write this file atomically (tempFile, cleanUp) <- newTempFileWithin dir (BS.writeFile tempFile v >> renameFile tempFile (dirName </> hexed v)) `onException` cleanUp addShared :: Shared -> Key -> Ver -> Ver -> [[(Key, BS_Identity)]] -> BS_Store -> [FilePath] -> IO () addShared shared entryKey entryBuiltinVersion entryUserVersion entryDepends entryResult files = do files <- mapM (\x -> (x,) <$> getFileHash (fileNameFromString x)) files saveSharedEntry shared Entry{entryFiles = files, entryGlobalVersion = globalVersion shared, ..} removeShared :: Shared -> (Key -> Bool) -> IO () removeShared Shared{..} test = do dirs <- listDirectories $ sharedRoot </> ".shake.cache" deleted <- forM dirs $ \dir -> do files <- sharedFileKeys dir -- if any key matches, clean them all out b <- flip anyM files $ \file -> handleSynchronous (\e -> putStrLn ("Warning: " ++ show e) >> pure False) $ evaluate . test . entryKey . getEntry keyOp =<< BS.readFile file when b $ removePathForcibly dir pure b liftIO $ putStrLn $ "Deleted " ++ show (length (filter id deleted)) ++ " entries" listShared :: Shared -> IO () listShared Shared{..} = do dirs <- listDirectories $ sharedRoot </> ".shake.cache" forM_ dirs $ \dir -> do putStrLn $ "Directory: " ++ dir keys <- sharedFileKeys dir forM_ keys $ \key -> handleSynchronous (\e -> putStrLn $ "Warning: " ++ show e) $ do Entry{..} <- getEntry keyOp <$> BS.readFile key putStrLn $ " Key: " ++ show entryKey forM_ entryFiles $ \(file,_) -> putStrLn $ " File: " ++ file sanityShared :: Shared -> IO () sanityShared Shared{..} = do dirs <- listDirectories $ sharedRoot </> ".shake.cache" forM_ dirs $ \dir -> do putStrLn $ "Directory: " ++ dir keys <- sharedFileKeys dir forM_ keys $ \key -> handleSynchronous (\e -> putStrLn $ "Warning: " ++ show e) $ do Entry{..} <- getEntry keyOp <$> BS.readFile key putStrLn $ " Key: " ++ show entryKey putStrLn $ " Key file: " ++ key forM_ entryFiles $ \(file,hash) -> checkFile file dir hash where checkFile filename dir keyHash = do let cachefile = dir </> show keyHash putStrLn $ " File: " ++ filename putStrLn $ " Cache file: " ++ cachefile ifM (not <$> doesFileExist_ cachefile) (putStrLn " Error: cache file does not exist") $ ifM ((/= keyHash) <$> getFileHash (fileNameFromString cachefile)) (putStrLn " Error: cache file hash does not match stored hash") (putStrLn " OK")
ndmitchell/shake
src/Development/Shake/Internal/History/Shared.hs
bsd-3-clause
8,124
4
34
2,171
2,552
1,291
1,261
170
4
module BookExactly ( T(..) , V(..) , eval , simplify , eval2 ) where data T = TRUE | FALSE | If T T T data V = TRUEv | FALSEv deriving Show eval :: T->V eval TRUE = TRUEv eval FALSE = FALSEv eval (If TRUE y z) = eval y eval (If FALSE y z) = eval z eval (If x y z) = eval (If (simplify x) y z) simplify :: T -> T simplify TRUE = TRUE simplify FALSE = FALSE simplify (If TRUE y z) = y simplify (If FALSE y z) = z simplify (If x y z) = If (simplify x) y z {- Alternatively, if separate term and value spaces aren't too complex, we can combine them. -} eval2 :: T -> T eval2 (If TRUE y _) = eval2 y eval2 (If FALSE _ z) = eval2 z eval2 (If x y z) = If (eval2 x) y z eval2 x = x
armoredsoftware/protocol
demos/PaulPractice/BookExactly.hs
bsd-3-clause
733
0
9
221
348
181
167
28
1
{-# LANGUAGE FlexibleContexts, CPP #-} module AWS.RDS.DBSubnetGroup ( describeDBSubnetGroups , createDBSubnetGroup , deleteDBSubnetGroup ) where import Control.Applicative ((<$>)) #if MIN_VERSION_conduit(1,1,0) import Control.Monad.Trans.Resource (MonadResource, MonadBaseControl) #else import Data.Conduit #endif import Data.Text (Text) import AWS.Lib.Parser (element) import AWS.Lib.Query ((|=), (|=?), (|.#=)) import AWS.RDS.Internal import AWS.RDS.Types (DBSubnetGroup) import AWS.Util (toText) describeDBSubnetGroups :: (MonadBaseControl IO m, MonadResource m) => Maybe Text -- ^ DBSubnetGroupName -> Maybe Text -- ^ Marker -> Maybe Int -- ^ MaxRecords -> RDS m [DBSubnetGroup] describeDBSubnetGroups name marker maxRecords = rdsQuery "DescribeDBSubnetGroups" params $ elements "DBSubnetGroup" dbSubnetGroupSink where params = [ "DBSubnetGroupName" |=? name , "Marker" |=? marker , "MaxRecords" |=? toText <$> maxRecords ] createDBSubnetGroup :: (MonadBaseControl IO m, MonadResource m) => Text -- ^ DBSubnetGroupName -> [Text] -- ^ SubnetIds -> Text -- ^ DBSubnetGroupDescription -> RDS m DBSubnetGroup createDBSubnetGroup name ids desc = rdsQuery "CreateDBSubnetGroup" params $ element "DBSubnetGroup" dbSubnetGroupSink where params = [ "DBSubnetGroupName" |= name , "SubnetIds.member" |.#= ids , "DBSubnetGroupDescription" |= desc ] deleteDBSubnetGroup :: (MonadBaseControl IO m, MonadResource m) => Text -- ^ DBSubnetGroupName -> RDS m () deleteDBSubnetGroup name = rdsQueryOnlyMetadata "DeleteDBSubnetGroup" ["DBSubnetGroupName" |= name]
IanConnolly/aws-sdk-fork
AWS/RDS/DBSubnetGroup.hs
bsd-3-clause
1,734
0
10
370
385
220
165
46
1
module Manifesto.FileList ( FileList(..) , mkFileList , mkPathProducer ) where import Control.Monad import Control.Monad.Catch (MonadThrow) import qualified Data.Text as T import qualified Data.Text.IO as T import Data.Time import qualified Data.Vector as V import Path import Pipes hiding (for, each) import System.IO (hFlush, stdout) import System.Process import Manifesto.Types data FileList = FileList { _flHeader :: !Header , _flFiles :: !(V.Vector (Path Rel File)) -- ^ NOTE: This use of Vector probably doesn't buy us much over List, -- and the conversion may not be worth it. Benchmark. } -- | Create a Producer which yields the paths in the given FileList. mkPathProducer :: (Monad m, Monoid a) => FileList -> Producer (Maybe (Path Rel File)) m a mkPathProducer (FileList _ files) = do foldr (\a p -> yield (Just a) >> p) (yield Nothing >> return mempty) files mkFileList :: Path Abs Dir -> Maybe (Path Abs File) -> IO FileList mkFileList root excludeFile = do putStr "Generating file list..."; hFlush stdout header <- mkHeader root excludeFile paths <- mkPaths header putStrLn $ " done (" ++ show (V.length paths) ++ " files)" return (FileList header paths) mkHeader :: Path Abs Dir -> Maybe (Path Abs File) -> IO Header mkHeader root excludeFile = do host <- getHostname ts <- getCurrentTime excludePatterns <- case excludeFile of Nothing -> return [] Just p -> T.lines <$> T.readFile (toFilePath p) return $ Header { _hHost = host , _hRoot = root , _hExcludePatterns = excludePatterns , _hTimestamp = ts } -- | TODO: better exclude patterns mkPaths :: Header -> IO (V.Vector (Path Rel File)) mkPaths header = do filePaths <- V.fromList <$> listDirectoryRecursive (_hRoot header) return $ V.filter (not . isExcluded) filePaths where isExcluded path = any (\x -> not (T.null x) && x `T.isPrefixOf` T.pack (toFilePath path)) (_hExcludePatterns header) listDirectoryRecursive :: (MonadIO m,MonadThrow m) => Path Abs Dir -> m [Path Rel File] listDirectoryRecursive root = do output <- liftIO $ readProcess "find" [toFilePath root, "-type", "f"] "" mapM (stripDir root <=< parseAbsFile) (lines output) {- listDirectoryRecursive' :: (MonadIO m,MonadThrow m) => Path Abs Dir -> m [Path Rel File] listDirectoryRecursive' root = do (subdirs, files) <- listDirectory root subfiles <- mapM handleSub subdirs return $ files ++ concat subfiles where handleSub dir = map (dir </>) <$> listDirectoryRecursive (root </> dir) -- | List objects in a directory, excluding "." and "..". Entries are not -- sorted. Stolen from stack.Path.IO. -- TODO: optimise. listDirectory :: (MonadIO m,MonadThrow m) => Path Abs Dir -> m ([Path Rel Dir], [Path Rel File]) listDirectory dir = do let dirFP = toFilePath dir entriesFP <- liftIO (getDirectoryContents dirFP) maybeEntries <- forM (map (dirFP ++) entriesFP) (\entryFP -> do isDir <- liftIO (doesDirectoryExist entryFP) if isDir then case parseAbsDir entryFP of Nothing -> return Nothing Just entryDir -> if dir `isParentOf` entryDir then return (Just (Left entryDir)) else return Nothing else case parseAbsFile entryFP of Nothing -> return Nothing Just entryFile -> return (Just (Right entryFile))) let absEntries = catMaybes maybeEntries let relDirs = mapMaybe (stripDir dir) $ lefts absEntries let relFiles = mapMaybe (stripDir dir) $ rights absEntries return (relDirs, relFiles) -}
asayers/mkmanifests
src/Manifesto/FileList.hs
bsd-2-clause
3,908
0
15
1,104
754
389
365
58
2
module Haddock.Backends.Hyperlinker.ParserSpec (main, spec) where import Test.Hspec import Test.QuickCheck import qualified GHC import Control.Monad.IO.Class import Haddock (getGhcDirs) import Haddock.Backends.Hyperlinker.Parser import Haddock.Backends.Hyperlinker.Types withDynFlags :: (GHC.DynFlags -> IO ()) -> IO () withDynFlags cont = do libDir <- fmap snd (getGhcDirs []) GHC.runGhc (Just libDir) $ do dflags <- GHC.getSessionDynFlags liftIO $ cont dflags main :: IO () main = hspec spec spec :: Spec spec = describe "parse" parseSpec -- | Defined for its instance of 'Arbitrary'. Represents strings that, when -- considered as GHC source, won't be rewritten. newtype NoGhcRewrite = NoGhcRewrite String deriving (Show, Eq) -- | Filter out strings where GHC would replace/remove some characters during -- lexing. noGhcRewrite :: String -> Bool noGhcRewrite ('\t':_) = False -- GHC replaces tabs with 8 spaces noGhcRewrite ('\r':_) = False noGhcRewrite ('\f':_) = False noGhcRewrite ('\v':_) = False noGhcRewrite (' ':'\n':_) = False -- GHC strips whitespace on empty lines noGhcRewrite (_:s) = noGhcRewrite s noGhcRewrite "" = True instance Arbitrary NoGhcRewrite where arbitrary = fmap NoGhcRewrite (arbitrary `suchThat` noGhcRewrite) shrink (NoGhcRewrite src) = [ NoGhcRewrite shrunk | shrunk <- shrink src , noGhcRewrite shrunk ] parseSpec :: Spec parseSpec = around withDynFlags $ do it "is total" $ \dflags -> property $ \src -> length (parse dflags "" src) `shouldSatisfy` (>= 0) it "retains file layout" $ \dflags -> property $ \(NoGhcRewrite src) -> concatMap tkValue (parse dflags "" src) == src context "when parsing single-line comments" $ do it "should ignore content until the end of line" $ \dflags -> shouldParseTo "-- some very simple comment\nidentifier" [TkComment, TkSpace, TkIdentifier] dflags it "should allow endline escaping" $ \dflags -> shouldParseTo "#define first line\\\nsecond line\\\nand another one" [TkCpp] dflags context "when parsing multi-line comments" $ do it "should support nested comments" $ \dflags -> shouldParseTo "{- comment {- nested -} still comment -} {- next comment -}" [TkComment, TkSpace, TkComment] dflags it "should distinguish compiler pragma" $ \dflags -> shouldParseTo "{- comment -}{-# LANGUAGE GADTs #-}{- comment -}" [TkComment, TkPragma, TkComment] dflags it "should recognize preprocessor directives" $ \dflags -> do shouldParseTo "\n#define foo bar" [TkSpace, TkCpp] dflags shouldParseTo "x # y" [TkIdentifier, TkSpace, TkOperator, TkSpace,TkIdentifier] dflags it "should distinguish basic language constructs" $ \dflags -> do shouldParseTo "(* 2) <$> (\"abc\", foo)" [ TkSpecial, TkOperator, TkSpace, TkNumber, TkSpecial , TkSpace, TkOperator, TkSpace , TkSpecial, TkString, TkSpecial, TkSpace, TkIdentifier, TkSpecial ] dflags shouldParseTo "let foo' = foo in foo' + foo'" [ TkKeyword, TkSpace, TkIdentifier , TkSpace, TkGlyph, TkSpace , TkIdentifier, TkSpace, TkKeyword, TkSpace , TkIdentifier, TkSpace, TkOperator, TkSpace, TkIdentifier ] dflags shouldParseTo "square x = y^2 where y = x" [ TkIdentifier, TkSpace, TkIdentifier , TkSpace, TkGlyph, TkSpace , TkIdentifier, TkOperator, TkNumber , TkSpace, TkKeyword, TkSpace , TkIdentifier, TkSpace, TkGlyph, TkSpace, TkIdentifier ] dflags it "should parse do-notation syntax" $ \dflags -> do shouldParseTo "do { foo <- getLine; putStrLn foo }" [ TkKeyword, TkSpace, TkSpecial, TkSpace , TkIdentifier, TkSpace, TkGlyph, TkSpace , TkIdentifier, TkSpecial, TkSpace , TkIdentifier, TkSpace, TkIdentifier, TkSpace, TkSpecial ] dflags shouldParseTo (unlines [ "do" , " foo <- getLine" , " putStrLn foo" ]) [ TkKeyword, TkSpace, TkIdentifier , TkSpace, TkGlyph, TkSpace, TkIdentifier, TkSpace , TkIdentifier, TkSpace, TkIdentifier, TkSpace ] dflags where shouldParseTo :: String -> [TokenType] -> GHC.DynFlags -> Expectation shouldParseTo str tokens dflags = map tkType (parse dflags "" str) `shouldBe` tokens
Fuuzetsu/haddock
haddock-api/test/Haddock/Backends/Hyperlinker/ParserSpec.hs
bsd-2-clause
5,060
0
15
1,687
1,070
586
484
110
1
{-# LANGUAGE TemplateHaskellQuotes #-} {-# LANGUAGE PatternSynonyms #-} module T8759a where foo = [d| pattern Q = False |]
mpickering/ghc-exactprint
tests/examples/ghc8/T8759a.hs
bsd-3-clause
125
0
4
21
15
12
3
-1
-1
{-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE CPP #-} -- | Module implementing TIFF decoding. -- -- Supported compression schemes: -- -- * Uncompressed -- -- * PackBits -- -- * LZW -- -- Supported bit depth: -- -- * 2 bits -- -- * 4 bits -- -- * 8 bits -- -- * 16 bits -- module Codec.Picture.Tiff( decodeTiff , decodeTiffWithMetadata , TiffSaveable , encodeTiff , writeTiff ) where #if !MIN_VERSION_base(4,8,0) import Control.Applicative( (<$>), (<*>), pure ) import Data.Monoid( mempty ) #endif import Control.Monad( when, foldM_, unless, forM_ ) import Control.Monad.ST( ST, runST ) import Control.Monad.Writer.Strict( execWriter, tell, Writer ) import Data.Int( Int8 ) import Data.Word( Word8, Word16, Word32 ) import Data.Bits( (.&.), (.|.), unsafeShiftL, unsafeShiftR ) import Data.Binary.Get( Get ) import Data.Binary.Put( runPut ) import qualified Data.Vector as V import qualified Data.Vector.Storable as VS import qualified Data.Vector.Storable.Mutable as M import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as Lb import qualified Data.ByteString.Unsafe as BU import Foreign.Storable( sizeOf ) import Codec.Picture.Metadata.Exif import Codec.Picture.Metadata( Metadatas ) import Codec.Picture.InternalHelper import Codec.Picture.BitWriter import Codec.Picture.Types import Codec.Picture.Gif.LZW import Codec.Picture.Tiff.Types import Codec.Picture.Tiff.Metadata import Codec.Picture.VectorByteConversion( toByteString ) data TiffInfo = TiffInfo { tiffHeader :: TiffHeader , tiffWidth :: Word32 , tiffHeight :: Word32 , tiffColorspace :: TiffColorspace , tiffSampleCount :: Word32 , tiffRowPerStrip :: Word32 , tiffPlaneConfiguration :: TiffPlanarConfiguration , tiffSampleFormat :: [TiffSampleFormat] , tiffBitsPerSample :: V.Vector Word32 , tiffCompression :: TiffCompression , tiffStripSize :: V.Vector Word32 , tiffOffsets :: V.Vector Word32 , tiffPalette :: Maybe (Image PixelRGB16) , tiffYCbCrSubsampling :: V.Vector Word32 , tiffExtraSample :: Maybe ExtraSample , tiffPredictor :: Predictor , tiffMetadatas :: Metadatas } unLong :: String -> ExifData -> Get (V.Vector Word32) unLong _ (ExifShorts v) = pure $ V.map fromIntegral v unLong _ (ExifLongs v) = pure v unLong errMessage _ = fail errMessage findIFD :: String -> ExifTag -> [ImageFileDirectory] -> Get ImageFileDirectory findIFD errorMessage tag lst = case [v | v <- lst, ifdIdentifier v == tag] of [] -> fail errorMessage (x:_) -> pure x findPalette :: [ImageFileDirectory] -> Get (Maybe (Image PixelRGB16)) findPalette ifds = case [v | v <- ifds, ifdIdentifier v == TagColorMap] of (ImageFileDirectory { ifdExtended = ExifShorts vec }:_) -> pure . Just . Image pixelCount 1 $ VS.generate (V.length vec) axx where pixelCount = V.length vec `div` 3 axx v = vec `V.unsafeIndex` (idx + color * pixelCount) where (idx, color) = v `divMod` 3 _ -> pure Nothing findIFDData :: String -> ExifTag -> [ImageFileDirectory] -> Get Word32 findIFDData msg tag lst = ifdOffset <$> findIFD msg tag lst findIFDDefaultData :: Word32 -> ExifTag -> [ImageFileDirectory] -> Get Word32 findIFDDefaultData d tag lst = case [v | v <- lst, ifdIdentifier v == tag] of [] -> pure d (x:_) -> pure $ ifdOffset x findIFDExt :: String -> ExifTag -> [ImageFileDirectory] -> Get ExifData findIFDExt msg tag lst = do val <- findIFD msg tag lst case val of ImageFileDirectory { ifdCount = 1, ifdOffset = ofs, ifdType = TypeShort } -> pure . ExifShorts . V.singleton $ fromIntegral ofs ImageFileDirectory { ifdCount = 1, ifdOffset = ofs, ifdType = TypeLong } -> pure . ExifLongs . V.singleton $ fromIntegral ofs ImageFileDirectory { ifdExtended = v } -> pure v findIFDExtDefaultData :: [Word32] -> ExifTag -> [ImageFileDirectory] -> Get [Word32] findIFDExtDefaultData d tag lst = case [v | v <- lst, ifdIdentifier v == tag] of [] -> pure d (ImageFileDirectory { ifdExtended = ExifNone }:_) -> return d (x:_) -> V.toList <$> unLong errorMessage (ifdExtended x) where errorMessage = "Can't parse tag " ++ show tag ++ " " ++ show (ifdExtended x) -- It's temporary, remove once tiff decoding is better -- handled. {- instance Show (Image PixelRGB16) where show _ = "Image PixelRGB16" -} copyByteString :: B.ByteString -> M.STVector s Word8 -> Int -> Int -> (Word32, Word32) -> ST s Int copyByteString str vec stride startWrite (from, count) = inner startWrite fromi where fromi = fromIntegral from maxi = fromi + fromIntegral count inner writeIdx i | i >= maxi = pure writeIdx inner writeIdx i = do let v = str `BU.unsafeIndex` i (vec `M.unsafeWrite` writeIdx) v inner (writeIdx + stride) $ i + 1 unpackPackBit :: B.ByteString -> M.STVector s Word8 -> Int -> Int -> (Word32, Word32) -> ST s Int unpackPackBit str outVec stride writeIndex (offset, size) = loop fromi writeIndex where fromi = fromIntegral offset maxi = fromi + fromIntegral size replicateByte writeIdx _ 0 = pure writeIdx replicateByte writeIdx v count = do (outVec `M.unsafeWrite` writeIdx) v replicateByte (writeIdx + stride) v $ count - 1 loop i writeIdx | i >= maxi = pure writeIdx loop i writeIdx = choice {-where v = fromIntegral (str `BU.unsafeIndex` i) :: Int8-} where v = fromIntegral (str `B.index` i) :: Int8 choice -- data | 0 <= v = copyByteString str outVec stride writeIdx (fromIntegral $ i + 1, fromIntegral v + 1) >>= loop (i + 2 + fromIntegral v) -- run | -127 <= v = do {-let nextByte = str `BU.unsafeIndex` (i + 1)-} let nextByte = str `B.index` (i + 1) count = negate (fromIntegral v) + 1 :: Int replicateByte writeIdx nextByte count >>= loop (i + 2) -- noop | otherwise = loop writeIdx $ i + 1 uncompressAt :: TiffCompression -> B.ByteString -> M.STVector s Word8 -> Int -> Int -> (Word32, Word32) -> ST s Int uncompressAt CompressionNone = copyByteString uncompressAt CompressionPackBit = unpackPackBit uncompressAt CompressionLZW = \str outVec _stride writeIndex (offset, size) -> do let toDecode = B.take (fromIntegral size) $ B.drop (fromIntegral offset) str runBoolReader $ decodeLzwTiff toDecode outVec writeIndex return 0 uncompressAt _ = error "Unhandled compression" class Unpackable a where type StorageType a :: * outAlloc :: a -> Int -> ST s (M.STVector s (StorageType a)) -- | Final image and size, return offset and vector allocTempBuffer :: a -> M.STVector s (StorageType a) -> Int -> ST s (M.STVector s Word8) offsetStride :: a -> Int -> Int -> (Int, Int) mergeBackTempBuffer :: a -- ^ Type witness, just for the type checker. -> Endianness -> M.STVector s Word8 -- ^ Temporary buffer handling decompression. -> Int -- ^ Line size in pixels -> Int -- ^ Write index, in bytes -> Word32 -- ^ size, in bytes -> Int -- ^ Stride -> M.STVector s (StorageType a) -- ^ Final buffer -> ST s () -- | The Word8 instance is just a passthrough, to avoid -- copying memory twice instance Unpackable Word8 where type StorageType Word8 = Word8 offsetStride _ i stride = (i, stride) allocTempBuffer _ buff _ = pure buff mergeBackTempBuffer _ _ _ _ _ _ _ _ = pure () outAlloc _ count = M.replicate count 0 -- M.new instance Unpackable Word16 where type StorageType Word16 = Word16 offsetStride _ _ _ = (0, 1) outAlloc _ = M.new allocTempBuffer _ _ s = M.new $ s * 2 mergeBackTempBuffer _ EndianLittle tempVec _ index size stride outVec = looperLe index 0 where looperLe _ readIndex | readIndex >= fromIntegral size = pure () looperLe writeIndex readIndex = do v1 <- tempVec `M.read` readIndex v2 <- tempVec `M.read` (readIndex + 1) let finalValue = (fromIntegral v2 `unsafeShiftL` 8) .|. fromIntegral v1 (outVec `M.write` writeIndex) finalValue looperLe (writeIndex + stride) (readIndex + 2) mergeBackTempBuffer _ EndianBig tempVec _ index size stride outVec = looperBe index 0 where looperBe _ readIndex | readIndex >= fromIntegral size = pure () looperBe writeIndex readIndex = do v1 <- tempVec `M.read` readIndex v2 <- tempVec `M.read` (readIndex + 1) let finalValue = (fromIntegral v1 `unsafeShiftL` 8) .|. fromIntegral v2 (outVec `M.write` writeIndex) finalValue looperBe (writeIndex + stride) (readIndex + 2) instance Unpackable Word32 where type StorageType Word32 = Word32 offsetStride _ _ _ = (0, 1) outAlloc _ = M.new allocTempBuffer _ _ s = M.new $ s * 4 mergeBackTempBuffer _ EndianLittle tempVec _ index size stride outVec = looperLe index 0 where looperLe _ readIndex | readIndex >= fromIntegral size = pure () looperLe writeIndex readIndex = do v1 <- tempVec `M.read` readIndex v2 <- tempVec `M.read` (readIndex + 1) v3 <- tempVec `M.read` (readIndex + 2) v4 <- tempVec `M.read` (readIndex + 3) let finalValue = (fromIntegral v4 `unsafeShiftL` 24) .|. (fromIntegral v3 `unsafeShiftL` 16) .|. (fromIntegral v2 `unsafeShiftL` 8) .|. fromIntegral v1 (outVec `M.write` writeIndex) finalValue looperLe (writeIndex + stride) (readIndex + 4) mergeBackTempBuffer _ EndianBig tempVec _ index size stride outVec = looperBe index 0 where looperBe _ readIndex | readIndex >= fromIntegral size = pure () looperBe writeIndex readIndex = do v1 <- tempVec `M.read` readIndex v2 <- tempVec `M.read` (readIndex + 1) v3 <- tempVec `M.read` (readIndex + 2) v4 <- tempVec `M.read` (readIndex + 3) let finalValue = (fromIntegral v1 `unsafeShiftL` 24) .|. (fromIntegral v2 `unsafeShiftL` 16) .|. (fromIntegral v3 `unsafeShiftL` 8) .|. fromIntegral v4 (outVec `M.write` writeIndex) finalValue looperBe (writeIndex + stride) (readIndex + 4) data Pack4 = Pack4 instance Unpackable Pack4 where type StorageType Pack4 = Word8 allocTempBuffer _ _ = M.new offsetStride _ _ _ = (0, 1) outAlloc _ = M.new mergeBackTempBuffer _ _ tempVec lineSize index size stride outVec = inner 0 index pxCount where pxCount = lineSize `div` stride maxWrite = M.length outVec inner readIdx writeIdx _ | readIdx >= fromIntegral size || writeIdx >= maxWrite = pure () inner readIdx writeIdx line | line <= 0 = inner readIdx (writeIdx + line * stride) pxCount inner readIdx writeIdx line = do v <- tempVec `M.read` readIdx let high = (v `unsafeShiftR` 4) .&. 0xF low = v .&. 0xF (outVec `M.write` writeIdx) high when (writeIdx + stride < maxWrite) $ (outVec `M.write` (writeIdx + stride)) low inner (readIdx + 1) (writeIdx + 2 * stride) (line - 2) data Pack2 = Pack2 instance Unpackable Pack2 where type StorageType Pack2 = Word8 allocTempBuffer _ _ = M.new offsetStride _ _ _ = (0, 1) outAlloc _ = M.new mergeBackTempBuffer _ _ tempVec lineSize index size stride outVec = inner 0 index pxCount where pxCount = lineSize `div` stride maxWrite = M.length outVec inner readIdx writeIdx _ | readIdx >= fromIntegral size || writeIdx >= maxWrite = pure () inner readIdx writeIdx line | line <= 0 = inner readIdx (writeIdx + line * stride) pxCount inner readIdx writeIdx line = do v <- tempVec `M.read` readIdx let v0 = (v `unsafeShiftR` 6) .&. 0x3 v1 = (v `unsafeShiftR` 4) .&. 0x3 v2 = (v `unsafeShiftR` 2) .&. 0x3 v3 = v .&. 0x3 (outVec `M.write` writeIdx) v0 when (writeIdx + 1 * stride < maxWrite) $ (outVec `M.write` (writeIdx + stride)) v1 when (writeIdx + 2 * stride < maxWrite) $ (outVec `M.write` (writeIdx + stride * 2)) v2 when (writeIdx + 3 * stride < maxWrite) $ (outVec `M.write` (writeIdx + stride * 3)) v3 inner (readIdx + 1) (writeIdx + 4 * stride) (line - 4) data Pack12 = Pack12 instance Unpackable Pack12 where type StorageType Pack12 = Word16 allocTempBuffer _ _ = M.new offsetStride _ _ _ = (0, 1) outAlloc _ = M.new mergeBackTempBuffer _ _ tempVec lineSize index size stride outVec = inner 0 index pxCount where pxCount = lineSize `div` stride maxWrite = M.length outVec inner readIdx writeIdx _ | readIdx >= fromIntegral size || writeIdx >= maxWrite = pure () inner readIdx writeIdx line | line <= 0 = inner readIdx (writeIdx + line * stride) pxCount inner readIdx writeIdx line = do v0 <- tempVec `M.read` readIdx v1 <- if readIdx + 1 < fromIntegral size then tempVec `M.read` (readIdx + 1) else pure 0 v2 <- if readIdx + 2 < fromIntegral size then tempVec `M.read` (readIdx + 2) else pure 0 let high0 = fromIntegral v0 `unsafeShiftL` 4 low0 = (fromIntegral v1 `unsafeShiftR` 4) .&. 0xF p0 = high0 .|. low0 high1 = (fromIntegral v1 .&. 0xF) `unsafeShiftL` 8 low1 = fromIntegral v2 p1 = high1 .|. low1 (outVec `M.write` writeIdx) p0 when (writeIdx + 1 * stride < maxWrite) $ (outVec `M.write` (writeIdx + stride)) p1 inner (readIdx + 3) (writeIdx + 2 * stride) (line - 2) data YCbCrSubsampling = YCbCrSubsampling { ycbcrWidth :: !Int , ycbcrHeight :: !Int , ycbcrImageWidth :: !Int , ycbcrStripHeight :: !Int } instance Unpackable YCbCrSubsampling where type StorageType YCbCrSubsampling = Word8 offsetStride _ _ _ = (0, 1) outAlloc _ = M.new allocTempBuffer _ _ = M.new mergeBackTempBuffer subSampling _ tempVec _ index size _ outVec = foldM_ unpacker 0 [(bx, by) | by <- [0, h .. lineCount - 1] , bx <- [0, w .. imgWidth - 1]] where w = ycbcrWidth subSampling h = ycbcrHeight subSampling imgWidth = ycbcrImageWidth subSampling lineCount = ycbcrStripHeight subSampling lumaCount = w * h blockSize = lumaCount + 2 maxOut = M.length outVec unpacker readIdx _ | readIdx >= fromIntegral size * 3 = pure readIdx unpacker readIdx (bx, by) = do cb <- tempVec `M.read` (readIdx + lumaCount) cr <- tempVec `M.read` (readIdx + lumaCount + 1) let pixelIndices = [index + ((by + y) * imgWidth + bx + x) * 3 | y <- [0 .. h - 1], x <- [0 .. w - 1]] writer readIndex writeIdx | writeIdx + 3 > maxOut = pure readIndex writer readIndex writeIdx = do y <- tempVec `M.read` readIndex (outVec `M.write` writeIdx) y (outVec `M.write` (writeIdx + 1)) cb (outVec `M.write` (writeIdx + 2)) cr return $ readIndex + 1 foldM_ writer readIdx pixelIndices return $ readIdx + blockSize gatherStrips :: ( Unpackable comp , Pixel pixel , StorageType comp ~ PixelBaseComponent pixel ) => comp -> B.ByteString -> TiffInfo -> Image pixel gatherStrips comp str nfo = runST $ do let width = fromIntegral $ tiffWidth nfo height = fromIntegral $ tiffHeight nfo sampleCount = if tiffSampleCount nfo /= 0 then fromIntegral $ tiffSampleCount nfo else V.length $ tiffBitsPerSample nfo rowPerStrip = fromIntegral $ tiffRowPerStrip nfo endianness = hdrEndianness $ tiffHeader nfo stripCount = V.length $ tiffOffsets nfo compression = tiffCompression nfo outVec <- outAlloc comp $ width * height * sampleCount tempVec <- allocTempBuffer comp outVec (rowPerStrip * width * sampleCount) let mutableImage = MutableImage { mutableImageWidth = fromIntegral width , mutableImageHeight = fromIntegral height , mutableImageData = outVec } case tiffPlaneConfiguration nfo of PlanarConfigContig -> V.mapM_ unpacker sizes where unpacker (idx, stripSampleCount, offset, packedSize) = do let (writeIdx, tempStride) = offsetStride comp idx 1 _ <- uncompressAt compression str tempVec tempStride writeIdx (offset, packedSize) let typ :: M.MVector s a -> a typ = const undefined sampleSize = sizeOf (typ outVec) mergeBackTempBuffer comp endianness tempVec (width * sampleCount) idx (fromIntegral $ stripSampleCount * sampleSize) 1 outVec fullStripSampleCount = rowPerStrip * width * sampleCount startWriteOffset = V.generate stripCount (fullStripSampleCount *) stripSampleCounts = V.map strip startWriteOffset where strip start = min fullStripSampleCount (width * height * sampleCount - start) sizes = V.zip4 startWriteOffset stripSampleCounts (tiffOffsets nfo) (tiffStripSize nfo) PlanarConfigSeparate -> V.mapM_ unpacker sizes where unpacker (idx, offset, size) = do let (writeIdx, tempStride) = offsetStride comp idx stride _ <- uncompressAt compression str tempVec tempStride writeIdx (offset, size) mergeBackTempBuffer comp endianness tempVec (width * sampleCount) idx size stride outVec stride = V.length $ tiffOffsets nfo idxVector = V.enumFromN 0 stride sizes = V.zip3 idxVector (tiffOffsets nfo) (tiffStripSize nfo) when (tiffPredictor nfo == PredictorHorizontalDifferencing) $ do let f _ c1 c2 = c1 + c2 forM_ [0 .. height - 1] $ \y -> forM_ [1 .. width - 1] $ \x -> do p <- readPixel mutableImage (x - 1) y q <- readPixel mutableImage x y writePixel mutableImage x y $ mixWith f p q unsafeFreezeImage mutableImage ifdSingleLong :: ExifTag -> Word32 -> Writer [ImageFileDirectory] () ifdSingleLong tag = ifdMultiLong tag . V.singleton ifdSingleShort :: Endianness -> ExifTag -> Word16 -> Writer [ImageFileDirectory] () ifdSingleShort endian tag = ifdMultiShort endian tag . V.singleton . fromIntegral ifdMultiLong :: ExifTag -> V.Vector Word32 -> Writer [ImageFileDirectory] () ifdMultiLong tag v = tell . pure $ ImageFileDirectory { ifdIdentifier = tag , ifdType = TypeLong , ifdCount = fromIntegral $ V.length v , ifdOffset = offset , ifdExtended = extended } where (offset, extended) | V.length v > 1 = (0, ExifLongs v) | otherwise = (V.head v, ExifNone) ifdMultiShort :: Endianness -> ExifTag -> V.Vector Word32 -> Writer [ImageFileDirectory] () ifdMultiShort endian tag v = tell . pure $ ImageFileDirectory { ifdIdentifier = tag , ifdType = TypeShort , ifdCount = size , ifdOffset = offset , ifdExtended = extended } where size = fromIntegral $ V.length v (offset, extended) | size > 2 = (0, ExifShorts $ V.map fromIntegral v) | size == 2 = let v1 = fromIntegral $ V.head v v2 = fromIntegral $ v `V.unsafeIndex` 1 in case endian of EndianLittle -> (v2 `unsafeShiftL` 16 .|. v1, ExifNone) EndianBig -> (v1 `unsafeShiftL` 16 .|. v2, ExifNone) | otherwise = case endian of EndianLittle -> (V.head v, ExifNone) EndianBig -> (V.head v `unsafeShiftL` 16, ExifNone) instance BinaryParam B.ByteString TiffInfo where putP rawData nfo = putP rawData (tiffHeader nfo, list) where endianness = hdrEndianness $ tiffHeader nfo ifdShort = ifdSingleShort endianness ifdShorts = ifdMultiShort endianness list = execWriter $ do ifdSingleLong TagImageWidth $ tiffWidth nfo ifdSingleLong TagImageLength $ tiffHeight nfo ifdShorts TagBitsPerSample $ tiffBitsPerSample nfo ifdSingleLong TagSamplesPerPixel $ tiffSampleCount nfo ifdSingleLong TagRowPerStrip $ tiffRowPerStrip nfo ifdShort TagPhotometricInterpretation . packPhotometricInterpretation $ tiffColorspace nfo ifdShort TagPlanarConfiguration . constantToPlaneConfiguration $ tiffPlaneConfiguration nfo ifdShort TagCompression . packCompression $ tiffCompression nfo ifdMultiLong TagStripOffsets $ tiffOffsets nfo ifdMultiLong TagStripByteCounts $ tiffStripSize nfo maybe (return ()) (ifdShort TagExtraSample . codeOfExtraSample) $ tiffExtraSample nfo let subSampling = tiffYCbCrSubsampling nfo unless (V.null subSampling) $ ifdShorts TagYCbCrSubsampling subSampling getP rawData = do (hdr, cleaned) <- getP rawData let dataFind str tag = findIFDData str tag cleaned dataDefault def tag = findIFDDefaultData def tag cleaned extFind str tag = findIFDExt str tag cleaned extDefault def tag = findIFDExtDefaultData def tag cleaned TiffInfo hdr <$> dataFind "Can't find width" TagImageWidth <*> dataFind "Can't find height" TagImageLength <*> (dataFind "Can't find color space" TagPhotometricInterpretation >>= unpackPhotometricInterpretation) <*> dataFind "Can't find sample per pixel" TagSamplesPerPixel <*> dataFind "Can't find row per strip" TagRowPerStrip <*> (dataDefault 1 TagPlanarConfiguration >>= planarConfgOfConstant) <*> (extDefault [1] TagSampleFormat >>= mapM unpackSampleFormat) <*> (extFind "Can't find bit per sample" TagBitsPerSample >>= unLong "Can't find bit depth") <*> (dataFind "Can't find Compression" TagCompression >>= unPackCompression) <*> (extFind "Can't find byte counts" TagStripByteCounts >>= unLong "Can't find bit per sample") <*> (extFind "Strip offsets missing" TagStripOffsets >>= unLong "Can't find strip offsets") <*> findPalette cleaned <*> (V.fromList <$> extDefault [2, 2] TagYCbCrSubsampling) <*> pure Nothing <*> (dataDefault 1 TagPredictor >>= predictorOfConstant) <*> pure (extractTiffMetadata cleaned) unpack :: B.ByteString -> TiffInfo -> Either String DynamicImage -- | while mandatory some images don't put correct -- rowperstrip. So replacing 0 with actual image height. unpack file nfo@TiffInfo { tiffRowPerStrip = 0 } = unpack file $ nfo { tiffRowPerStrip = tiffHeight nfo } unpack file nfo@TiffInfo { tiffColorspace = TiffPaleted , tiffBitsPerSample = lst , tiffSampleFormat = format , tiffPalette = Just p } | lst == V.singleton 8 && format == [TiffSampleUint] = let applyPalette = pixelMap (\v -> pixelAt p (fromIntegral v) 0) gathered :: Image Pixel8 gathered = gatherStrips (0 :: Word8) file nfo in pure . ImageRGB16 $ applyPalette gathered | lst == V.singleton 4 && format == [TiffSampleUint] = let applyPalette = pixelMap (\v -> pixelAt p (fromIntegral v) 0) gathered :: Image Pixel8 gathered = gatherStrips Pack4 file nfo in pure . ImageRGB16 $ applyPalette gathered | lst == V.singleton 2 && format == [TiffSampleUint] = let applyPalette = pixelMap (\v -> pixelAt p (fromIntegral v) 0) gathered :: Image Pixel8 gathered = gatherStrips Pack2 file nfo in pure . ImageRGB16 $ applyPalette gathered unpack file nfo@TiffInfo { tiffColorspace = TiffCMYK , tiffBitsPerSample = lst , tiffSampleFormat = format } | lst == V.fromList [8, 8, 8, 8] && all (TiffSampleUint ==) format = pure . ImageCMYK8 $ gatherStrips (0 :: Word8) file nfo | lst == V.fromList [16, 16, 16, 16] && all (TiffSampleUint ==) format = pure . ImageCMYK16 $ gatherStrips (0 :: Word16) file nfo unpack file nfo@TiffInfo { tiffColorspace = TiffMonochromeWhite0 } = do img <- unpack file (nfo { tiffColorspace = TiffMonochrome }) case img of ImageY8 i -> pure . ImageY8 $ pixelMap (maxBound -) i ImageY16 i -> pure . ImageY16 $ pixelMap (maxBound -) i ImageYA8 i -> let negative (PixelYA8 y a) = PixelYA8 (maxBound - y) a in pure . ImageYA8 $ pixelMap negative i ImageYA16 i -> let negative (PixelYA16 y a) = PixelYA16 (maxBound - y) a in pure . ImageYA16 $ pixelMap negative i _ -> fail "Unsupported color type used with colorspace MonochromeWhite0" unpack file nfo@TiffInfo { tiffColorspace = TiffMonochrome , tiffBitsPerSample = lst , tiffSampleFormat = format } | lst == V.singleton 2 && all (TiffSampleUint ==) format = pure . ImageY8 . pixelMap (colorMap (0x55 *)) $ gatherStrips Pack2 file nfo | lst == V.singleton 4 && all (TiffSampleUint ==) format = pure . ImageY8 . pixelMap (colorMap (0x11 *)) $ gatherStrips Pack4 file nfo | lst == V.singleton 8 && all (TiffSampleUint ==) format = pure . ImageY8 $ gatherStrips (0 :: Word8) file nfo | lst == V.singleton 12 && all (TiffSampleUint ==) format = pure . ImageY16 . pixelMap (colorMap expand12to16) $ gatherStrips Pack12 file nfo | lst == V.singleton 16 && all (TiffSampleUint ==) format = pure . ImageY16 $ gatherStrips (0 :: Word16) file nfo | lst == V.singleton 32 && all (TiffSampleUint ==) format = let toWord16 v = fromIntegral $ v `unsafeShiftR` 16 img = gatherStrips (0 :: Word32) file nfo :: Image Pixel32 in pure . ImageY16 $ pixelMap toWord16 img | lst == V.fromList [2, 2] && all (TiffSampleUint ==) format = pure . ImageYA8 . pixelMap (colorMap (0x55 *)) $ gatherStrips Pack2 file nfo | lst == V.fromList [4, 4] && all (TiffSampleUint ==) format = pure . ImageYA8 . pixelMap (colorMap (0x11 *)) $ gatherStrips Pack4 file nfo | lst == V.fromList [8, 8] && all (TiffSampleUint ==) format = pure . ImageYA8 $ gatherStrips (0 :: Word8) file nfo | lst == V.fromList [12, 12] && all (TiffSampleUint ==) format = pure . ImageYA16 . pixelMap (colorMap expand12to16) $ gatherStrips Pack12 file nfo | lst == V.fromList [16, 16] && all (TiffSampleUint ==) format = pure . ImageYA16 $ gatherStrips (0 :: Word16) file nfo where expand12to16 x = x `unsafeShiftL` 4 + x `unsafeShiftR` (12 - 4) unpack file nfo@TiffInfo { tiffColorspace = TiffYCbCr , tiffBitsPerSample = lst , tiffPlaneConfiguration = PlanarConfigContig , tiffSampleFormat = format } | lst == V.fromList [8, 8, 8] && all (TiffSampleUint ==) format = pure . ImageYCbCr8 $ gatherStrips cbcrConf file nfo where defaulting 0 = 2 defaulting n = n w = defaulting $ tiffYCbCrSubsampling nfo V.! 0 h = defaulting $ tiffYCbCrSubsampling nfo V.! 1 cbcrConf = YCbCrSubsampling { ycbcrWidth = fromIntegral w , ycbcrHeight = fromIntegral h , ycbcrImageWidth = fromIntegral $ tiffWidth nfo , ycbcrStripHeight = fromIntegral $ tiffRowPerStrip nfo } unpack file nfo@TiffInfo { tiffColorspace = TiffRGB , tiffBitsPerSample = lst , tiffSampleFormat = format } | lst == V.fromList [2, 2, 2] && all (TiffSampleUint ==) format = pure . ImageRGB8 . pixelMap (colorMap (0x55 *)) $ gatherStrips Pack2 file nfo | lst == V.fromList [4, 4, 4] && all (TiffSampleUint ==) format = pure . ImageRGB8 . pixelMap (colorMap (0x11 *)) $ gatherStrips Pack4 file nfo | lst == V.fromList [8, 8, 8] && all (TiffSampleUint ==) format = pure . ImageRGB8 $ gatherStrips (0 :: Word8) file nfo | lst == V.fromList [8, 8, 8, 8] && all (TiffSampleUint ==) format = pure . ImageRGBA8 $ gatherStrips (0 :: Word8) file nfo | lst == V.fromList [16, 16, 16] && all (TiffSampleUint ==) format = pure . ImageRGB16 $ gatherStrips (0 :: Word16) file nfo | lst == V.fromList [16, 16, 16, 16] && all (TiffSampleUint ==) format = pure . ImageRGBA16 $ gatherStrips (0 :: Word16) file nfo unpack file nfo@TiffInfo { tiffColorspace = TiffMonochrome , tiffBitsPerSample = lst , tiffSampleFormat = format } -- some files are a little bit borked... | lst == V.fromList [8, 8, 8] && all (TiffSampleUint ==) format = pure . ImageRGB8 $ gatherStrips (0 :: Word8) file nfo unpack _ _ = fail "Failure to unpack TIFF file" -- | Decode a tiff encoded image while preserving the underlying -- pixel type (except for Y32 which is truncated to 16 bits). -- -- This function can output the following pixel types: -- -- * PixelY8 -- -- * PixelY16 -- -- * PixelYA8 -- -- * PixelYA16 -- -- * PixelRGB8 -- -- * PixelRGB16 -- -- * PixelRGBA8 -- -- * PixelRGBA16 -- -- * PixelCMYK8 -- -- * PixelCMYK16 -- decodeTiff :: B.ByteString -> Either String DynamicImage decodeTiff = fmap fst . decodeTiffWithMetadata -- | Like 'decodeTiff' but also provides some metdata present -- in the Tiff file. -- -- The metadata extracted are the DpiX & DpiY information alongside -- the EXIF informations. decodeTiffWithMetadata :: B.ByteString -> Either String (DynamicImage, Metadatas) decodeTiffWithMetadata file = runGetStrict (getP file) file >>= go where go tinfo = (, tiffMetadatas tinfo) <$> unpack file tinfo -- | Class defining which pixel types can be serialized in a -- Tiff file. class (Pixel px) => TiffSaveable px where colorSpaceOfPixel :: px -> TiffColorspace extraSampleCodeOfPixel :: px -> Maybe ExtraSample extraSampleCodeOfPixel _ = Nothing subSamplingInfo :: px -> V.Vector Word32 subSamplingInfo _ = V.empty instance TiffSaveable Pixel8 where colorSpaceOfPixel _ = TiffMonochrome instance TiffSaveable Pixel16 where colorSpaceOfPixel _ = TiffMonochrome instance TiffSaveable PixelYA8 where colorSpaceOfPixel _ = TiffMonochrome extraSampleCodeOfPixel _ = Just ExtraSampleUnassociatedAlpha instance TiffSaveable PixelYA16 where colorSpaceOfPixel _ = TiffMonochrome extraSampleCodeOfPixel _ = Just ExtraSampleUnassociatedAlpha instance TiffSaveable PixelCMYK8 where colorSpaceOfPixel _ = TiffCMYK instance TiffSaveable PixelCMYK16 where colorSpaceOfPixel _ = TiffCMYK instance TiffSaveable PixelRGB8 where colorSpaceOfPixel _ = TiffRGB instance TiffSaveable PixelRGB16 where colorSpaceOfPixel _ = TiffRGB instance TiffSaveable PixelRGBA8 where colorSpaceOfPixel _ = TiffRGB extraSampleCodeOfPixel _ = Just ExtraSampleUnassociatedAlpha instance TiffSaveable PixelRGBA16 where colorSpaceOfPixel _ = TiffRGB extraSampleCodeOfPixel _ = Just ExtraSampleUnassociatedAlpha instance TiffSaveable PixelYCbCr8 where colorSpaceOfPixel _ = TiffYCbCr subSamplingInfo _ = V.fromListN 2 [1, 1] -- | Transform an image into a Tiff encoded bytestring, ready to be -- written as a file. encodeTiff :: forall px. (TiffSaveable px) => Image px -> Lb.ByteString encodeTiff img = runPut $ putP rawPixelData hdr where intSampleCount = componentCount (undefined :: px) sampleCount = fromIntegral intSampleCount sampleType = undefined :: PixelBaseComponent px pixelData = imageData img rawPixelData = toByteString pixelData width = fromIntegral $ imageWidth img height = fromIntegral $ imageHeight img intSampleSize = sizeOf sampleType sampleSize = fromIntegral intSampleSize bitPerSample = sampleSize * 8 imageSize = width * height * sampleCount * sampleSize headerSize = 8 hdr = TiffInfo { tiffHeader = TiffHeader { hdrEndianness = EndianLittle , hdrOffset = headerSize + imageSize } , tiffWidth = width , tiffHeight = height , tiffColorspace = colorSpaceOfPixel (undefined :: px) , tiffSampleCount = fromIntegral sampleCount , tiffRowPerStrip = fromIntegral $ imageHeight img , tiffPlaneConfiguration = PlanarConfigContig , tiffSampleFormat = [TiffSampleUint] , tiffBitsPerSample = V.replicate intSampleCount bitPerSample , tiffCompression = CompressionNone , tiffStripSize = V.singleton imageSize , tiffOffsets = V.singleton headerSize , tiffPalette = Nothing , tiffYCbCrSubsampling = subSamplingInfo (undefined :: px) , tiffExtraSample = extraSampleCodeOfPixel (undefined :: px) , tiffPredictor = PredictorNone -- not used when writing , tiffMetadatas = mempty } -- | Helper function to directly write an image as a tiff on disk. writeTiff :: (TiffSaveable pixel) => FilePath -> Image pixel -> IO () writeTiff path img = Lb.writeFile path $ encodeTiff img {-# ANN module "HLint: ignore Reduce duplication" #-}
Chobbes/Juicy.Pixels
src/Codec/Picture/Tiff.hs
bsd-3-clause
36,073
0
24
11,440
10,293
5,343
4,950
678
6
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TupleSections #-} module Control.Concurrent.STM.Notify ( STMEnvelope , Address , spawnIO , spawn , spawnEnvelope , recvIO , recv , sendIO , send , forkOnChange , onChange , foldOnChange , STMMailbox , notify , waitForChanges , watchOn , addListener , foldOnChangeWith )where import Control.Applicative import Control.Concurrent.Async import Control.Concurrent.STM import Control.Monad hiding (mapM, sequence) import Data.Traversable (traverse) import Prelude hiding (mapM, sequence) type STMMailbox a = (STMEnvelope a, Address a) data STMEnvelope a = STMEnvelope { stmEnvelopeTMvar :: STM ([TMVar ()],a) -- ^ Current list of waiting listeners and the current value , stmAddListener :: TMVar () -> STM () -- ^ Add a listener to the envelope } -- A wrapper to send an item to its paried container newtype Address a = Address { _unAddress :: a -> STM () } instance Functor STMEnvelope where fmap f (STMEnvelope stmVal insertListener) = STMEnvelope newStmVal newInsertListener where newInsertListener = insertListener -- Keep the same listener newStmVal = fmap f <$> stmVal -- Apply f to the current value -- (<$> over STM and fmap over the tuple) instance Applicative STMEnvelope where pure r = STMEnvelope (return ([], r)) (const $ return ()) -- Empty list of listeners and a function that doesn't add anything -- Because there is no way to modify this value by default (STMEnvelope env1 insertListener1) <*> (STMEnvelope env2 insertListener2) = STMEnvelope newStmVal newAddListener where newStmVal = (\(fList,f) (valList, val) -> (fList ++ valList, f val)) <$> env1 <*> env2 -- Apply the function to the value newAddListener t = insertListener1 t >> insertListener2 t -- Use both listeners to allow for listening to multiple changes instance Alternative STMEnvelope where empty = STMEnvelope empty (const $ return ()) (STMEnvelope val listener) <|> (STMEnvelope val' listener') = STMEnvelope (val <|> val') (\t -> listener t >> listener' t) instance Monad STMEnvelope where return r = STMEnvelope (return ([], r)) (const $ return ()) (STMEnvelope stmVal insertListener) >>= f = STMEnvelope stmNewVal newInsertListener where stmNewVal = fst <$> updateFcnVal newInsertListener = fixAddFunc $ snd <$> updateFcnVal updateFcnVal = do (listeners, currentVal) <- stmVal let (STMEnvelope stmRes insertListener') = f currentVal add t = insertListener' t >> insertListener t (listeners', newVal) <- stmRes return ((listeners' ++ listeners, newVal), add) fixAddFunc func tm = ($ tm) =<< func -- | Spawn a new envelope and an address to send new data to spawnIO :: a -> IO (STMEnvelope a, Address a) spawnIO = atomically . spawn -- | Spawn a new envelope and address inside of an envelope computation spawnEnvelope :: a -> STMEnvelope (STMEnvelope a, Address a) spawnEnvelope x = STMEnvelope (([],) <$> spawned) addListener where spawned = spawn x addListener = fixStm (stmAddListener . fst <$> spawned) fixStm f x = ($ x) =<< f -- | Spawn a new envelope and an address to send new data to spawn :: a -> STM (STMEnvelope a, Address a) spawn val = do tValue <- newTMVar ([],val) -- Contents with no listeners let envelope = STMEnvelope (readTMVar tValue) insertListener -- read the current value and an add function insertListener listener = do (listeners, a) <- takeTMVar tValue -- Get the list of listeners to add putTMVar tValue (listener:listeners, a) -- append the new listener address = Address $ \newVal -> do (listeners,_) <- takeTMVar tValue -- Find the listeners putTMVar tValue ([],newVal) -- put the new value with no listeners mapM_ (`tryPutTMVar` ()) listeners -- notify all the listeners of the change return (envelope, address) -- | Force a notification event. This doesn't clear the listeners notify :: STMEnvelope a -> STM () notify (STMEnvelope stmVal _) = do (listeners, _) <- stmVal -- Get a list of all current listeners mapM_ (`tryPutTMVar` ()) listeners -- Fill all of the tmvars -- | Read the current contents of a envelope recvIO :: STMEnvelope a -> IO a recvIO = atomically . recv -- | Read the current contents of a envelope recv :: STMEnvelope a -> STM a recv = fmap snd . stmEnvelopeTMvar -- | Update the contents of a envelope for a specific address -- and notify the watching thread sendIO :: Address a -> a -> IO () sendIO m v = atomically $ send m v -- | Update the contents of a envelope for a specific address -- and notify the watching thread send :: Address a -> a -> STM () send (Address sendF) = sendF -- | Watch the envelope in a thread. This is the only thread that -- can watch the envelope. This never ends forkOnChange :: STMEnvelope a -- ^ Envelope to watch -> (a -> IO b) -- ^ Action to perform -> IO (Async b) -- ^ Resulting async value so that you can cancel forkOnChange v f = async $ onChange v f -- | Watch the envelope for changes. This never ends onChange :: STMEnvelope a -- ^ Envelope to watch -> (a -> IO b) -- ^ Action to perform -> IO b onChange env f = forever $ waitForChange env >> (f =<< recvIO env) onChangeWith :: (a -> [STMEnvelope a]) -> STMEnvelope a -> (a -> IO b) -> IO () onChangeWith children env f = void . forever $ do watch <- newEmptyTMVarIO go children watch env atomically $ readTMVar watch _ <- f =<< recvIO env return () where go getChildren watch env = do current <- recvIO env atomically $ stmAddListener env watch mapM_ (go getChildren watch) $ getChildren current forkOnChangeWith :: (a -> [STMEnvelope a]) -> STMEnvelope a -> (a -> IO b) -> IO (Async ()) forkOnChangeWith getC env f = async $ onChangeWith getC env f waitForChange :: STMEnvelope a -> IO () waitForChange (STMEnvelope _ insertListener) = do x <- newEmptyTMVarIO atomically $ insertListener x -- This is two seperate transactions because readTMVar will fail atomically $ readTMVar x -- Causing insertListener to retry waitForChanges :: (a -> [a]) -> (a -> STMEnvelope b) -> a -> IO () waitForChanges getChildren getEnv start = do listener <- newEmptyTMVarIO go listener getChildren getEnv start where go listener getCh env val = do let insertListener = stmAddListener $ getEnv start atomically $ insertListener listener mapM_ (go listener getCh env) $ getCh val -- -- | fold across a value each time the envelope is updated foldOnChange :: STMEnvelope a -- ^ Envelop to watch -> (b -> a -> IO b) -- ^ fold like function -> b -- ^ Initial value -> IO () foldOnChange = foldOnChangeWith waitForChange foldOnChangeWith :: (STMEnvelope a -> IO ()) -- ^ Function to wait for a change -> STMEnvelope a -- ^ Envelop to watch -> (b -> a -> IO b) -- ^ fold like function -> b -- ^ Initial value -> IO () foldOnChangeWith waitFunc env fld accum = do _ <- waitFunc env val <- recvIO env -- wait for the lock and then read the value accum' <- fld accum val foldOnChangeWith waitFunc env fld accum' watchOn :: (a -> STMEnvelope [a]) -> STMEnvelope a -> IO () watchOn f stmVal = do listener <- newEmptyTMVarIO atomically $ stmAddListener stmVal listener currentVal <- recvIO stmVal let envCh = f currentVal children <- recvIO envCh mapM_ (go listener f) children atomically $ readTMVar listener where go listener func val = do let envChildren = func val atomically $ stmAddListener envChildren listener ch <- recvIO envChildren mapM_ (go listener func) ch addListener :: STMEnvelope a -> TMVar () -> STM () addListener = stmAddListener
plow-technologies/stm-notify
src/Control/Concurrent/STM/Notify.hs
bsd-3-clause
8,392
0
16
2,336
2,197
1,121
1,076
158
1
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Futhark.Representation.AST.AttributesTests ( tests ) where import Test.Framework import Futhark.Representation.AST.SyntaxTests () import qualified Futhark.Representation.AST.Attributes.ValuesTests import qualified Futhark.Representation.AST.Attributes.ReshapeTests import qualified Futhark.Representation.AST.Attributes.RearrangeTests tests :: [Test] tests = Futhark.Representation.AST.Attributes.ValuesTests.tests ++ Futhark.Representation.AST.Attributes.ReshapeTests.tests ++ Futhark.Representation.AST.Attributes.RearrangeTests.tests
ihc/futhark
unittests/Futhark/Representation/AST/AttributesTests.hs
isc
662
0
7
62
96
69
27
13
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Main where import Import import Settings import Yesod.Logger (defaultDevelopmentLogger) import Yesod.Default.Config import Yesod.Test import Application (makeFoundation) main :: IO a main = do conf <- loadConfig $ (configSettings Testing) { csParseExtra = parseExtra } logger <- defaultDevelopmentLogger foundation <- makeFoundation conf logger app <- toWaiAppPlain foundation runTests app (connPool foundation) homeSpecs
JerrySun/league-famous
tests/main.hs
bsd-2-clause
568
0
11
87
125
67
58
17
1
module HERMIT.Dictionary.Local.Bind ( -- * Rewrites on Binding Groups externals , nonrecToRecR , recToNonrecR ) where import HERMIT.Core import HERMIT.External import HERMIT.GHC import HERMIT.Kure import HERMIT.Dictionary.Common ------------------------------------------------------------------------------ -- | Externals for manipulating binding groups. externals :: [External] externals = [ external "nonrec-to-rec" (promoteBindR nonrecToRecR :: RewriteH LCore) [ "Convert a non-recursive binding into a recursive binding group with a single definition." , "NonRec v e ==> Rec [Def v e]" ] .+ Shallow , external "rec-to-nonrec" (promoteBindR recToNonrecR :: RewriteH LCore) [ "Convert a singleton recursive binding into a non-recursive binding group." , "Rec [Def v e] ==> NonRec v e, (v not free in e)" ] ] ------------------------------------------------------------------------------ -- | @'NonRec' v e@ ==> @'Rec' [(v,e)]@ nonrecToRecR :: MonadCatch m => Rewrite c m CoreBind nonrecToRecR = prefixFailMsg "Converting non-recursive binding to recursive binding failed: " $ withPatFailMsg (wrongExprForm "NonRec v e") $ do NonRec v e <- idR guardMsg (isId v) "type variables cannot be defined recursively." return $ Rec [(v,e)] -- | @'Rec' [(v,e)]@ ==> @'NonRec' v e@ recToNonrecR :: MonadCatch m => Rewrite c m CoreBind recToNonrecR = prefixFailMsg "Converting singleton recursive binding to non-recursive binding failed: " $ withPatFailMsg (wrongExprForm "Rec [Def v e]") $ do Rec [(v,e)] <- idR guardMsg (v `notElemVarSet` freeIdsExpr e) ("'" ++ unqualifiedName v ++ " is recursively defined.") return (NonRec v e) ------------------------------------------------------------------------------
conal/hermit
src/HERMIT/Dictionary/Local/Bind.hs
bsd-2-clause
1,857
0
12
379
325
172
153
30
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE AutoDeriveTypeable #-} module IHaskell.Display.Widgets.Types where -- | This module houses all the type-trickery needed to make widgets happen. -- -- All widgets have a corresponding 'WidgetType', and some fields/attributes/properties as defined -- by the 'WidgetFields' type-family. -- -- Each widget field corresponds to a concrete haskell type, as given by the 'FieldType' -- type-family. -- -- Vinyl records are used to wrap together widget fields into a single 'WidgetState'. -- -- Singletons are used as a way to represent the promoted types of kind Field. For example: -- -- @ -- SViewName :: SField ViewName -- @ -- -- This allows the user to pass the type 'ViewName' without using Data.Proxy. In essence, a -- singleton is the only inhabitant (other than bottom) of a promoted type. Single element set/type -- == singleton. -- -- It also allows the record to wrap values of properties with information about their Field type. A -- vinyl record is represented as @Rec f ts@, which means that a record is a list of @f x@, where -- @x@ is a type present in the type-level list @ts@. Thus a 'WidgetState' is essentially a list of -- field properties wrapped together with the corresponding promoted Field type. See ('=::') for -- more. -- -- The properties function can be used to view all the @Field@s associated with a widget object. -- -- Attributes are represented by the @Attr@ data type, which holds the value of a field, along with -- the actual @Field@ object and a function to verify validity of changes to the value. -- -- The IPython widgets expect state updates of the form {"property": value}, where an empty string -- for numeric values is ignored by the frontend and the default value is used instead. Some numbers -- need to be sent as numbers (represented by @Integer@), whereas some (css lengths) need to be sent -- as Strings (@PixCount@). -- -- Child widgets are expected to be sent as strings of the form "IPY_MODEL_<uuid>", where @<uuid>@ -- represents the uuid of the widget's comm. -- -- To know more about the IPython messaging specification (as implemented in this package) take a -- look at the supplied MsgSpec.md. -- -- Widgets are not able to do console input, the reason for that can be found in the messaging -- specification. import Control.Monad (unless, join, when, void) import Control.Applicative ((<$>)) import qualified Control.Exception as Ex import Data.Typeable (Typeable, TypeRep, typeOf) import Data.IORef (IORef, readIORef, modifyIORef) import Data.Text (Text, pack) import System.IO.Error import System.Posix.IO import Text.Printf (printf) import Data.Aeson import Data.Aeson.Types (Pair) import Data.Vinyl (Rec(..), (<+>), recordToList, reifyConstraint, rmap, Dict(..)) import Data.Vinyl.Functor (Compose(..), Const(..)) import Data.Vinyl.Lens (rget, rput, type (∈)) import Data.Vinyl.TypeLevel (RecAll) import Data.Singletons.Prelude ((:++)) import Data.Singletons.TH import GHC.IO.Exception import IHaskell.Eval.Widgets (widgetSendUpdate) import IHaskell.Display (Base64, IHaskellWidget(..)) import IHaskell.IPython.Message.UUID import IHaskell.Display.Widgets.Singletons (Field, SField) import qualified IHaskell.Display.Widgets.Singletons as S import IHaskell.Display.Widgets.Common -- Classes from IPython's widget hierarchy. Defined as such to reduce code duplication. type WidgetClass = '[S.ViewModule, S.ViewName, S.ModelModule, S.ModelName, S.MsgThrottle, S.Version, S.DisplayHandler] type DOMWidgetClass = WidgetClass :++ '[S.Visible, S.CSS, S.DOMClasses, S.Width, S.Height, S.Padding, S.Margin, S.Color, S.BackgroundColor, S.BorderColor, S.BorderWidth, S.BorderRadius, S.BorderStyle, S.FontStyle, S.FontWeight, S.FontSize, S.FontFamily] type StringClass = DOMWidgetClass :++ '[S.StringValue, S.Disabled, S.Description, S.Placeholder] type BoolClass = DOMWidgetClass :++ '[S.BoolValue, S.Disabled, S.Description, S.ChangeHandler] type SelectionClass = DOMWidgetClass :++ '[S.Options, S.SelectedValue, S.SelectedLabel, S.Disabled, S.Description, S.SelectionHandler] type MultipleSelectionClass = DOMWidgetClass :++ '[S.Options, S.SelectedValues, S.SelectedLabels, S.Disabled, S.Description, S.SelectionHandler] type IntClass = DOMWidgetClass :++ '[S.IntValue, S.Disabled, S.Description, S.ChangeHandler] type BoundedIntClass = IntClass :++ '[S.StepInt, S.MinInt, S.MaxInt] type IntRangeClass = IntClass :++ '[S.IntPairValue, S.LowerInt, S.UpperInt] type BoundedIntRangeClass = IntRangeClass :++ '[S.StepInt, S.MinInt, S.MaxInt] type FloatClass = DOMWidgetClass :++ '[S.FloatValue, S.Disabled, S.Description, S.ChangeHandler] type BoundedFloatClass = FloatClass :++ '[S.StepFloat, S.MinFloat, S.MaxFloat] type FloatRangeClass = FloatClass :++ '[S.FloatPairValue, S.LowerFloat, S.UpperFloat] type BoundedFloatRangeClass = FloatRangeClass :++ '[S.StepFloat, S.MinFloat, S.MaxFloat] type BoxClass = DOMWidgetClass :++ '[S.Children, S.OverflowX, S.OverflowY, S.BoxStyle] type SelectionContainerClass = BoxClass :++ '[S.Titles, S.SelectedIndex, S.ChangeHandler] -- Types associated with Fields. type family FieldType (f :: Field) :: * where FieldType S.ViewModule = Text FieldType S.ViewName = Text FieldType S.ModelModule = Text FieldType S.ModelName = Text FieldType S.MsgThrottle = Integer FieldType S.Version = Integer FieldType S.DisplayHandler = IO () FieldType S.Visible = Bool FieldType S.CSS = [(Text, Text, Text)] FieldType S.DOMClasses = [Text] FieldType S.Width = PixCount FieldType S.Height = PixCount FieldType S.Padding = PixCount FieldType S.Margin = PixCount FieldType S.Color = Text FieldType S.BackgroundColor = Text FieldType S.BorderColor = Text FieldType S.BorderWidth = PixCount FieldType S.BorderRadius = PixCount FieldType S.BorderStyle = BorderStyleValue FieldType S.FontStyle = FontStyleValue FieldType S.FontWeight = FontWeightValue FieldType S.FontSize = PixCount FieldType S.FontFamily = Text FieldType S.Description = Text FieldType S.ClickHandler = IO () FieldType S.SubmitHandler = IO () FieldType S.Disabled = Bool FieldType S.StringValue = Text FieldType S.Placeholder = Text FieldType S.Tooltip = Text FieldType S.Icon = Text FieldType S.ButtonStyle = ButtonStyleValue FieldType S.B64Value = Base64 FieldType S.ImageFormat = ImageFormatValue FieldType S.BoolValue = Bool FieldType S.Options = SelectionOptions FieldType S.SelectedLabel = Text FieldType S.SelectedValue = Text FieldType S.SelectionHandler = IO () FieldType S.Tooltips = [Text] FieldType S.Icons = [Text] FieldType S.SelectedLabels = [Text] FieldType S.SelectedValues = [Text] FieldType S.IntValue = Integer FieldType S.StepInt = Integer FieldType S.MinInt = Integer FieldType S.MaxInt = Integer FieldType S.LowerInt = Integer FieldType S.UpperInt = Integer FieldType S.IntPairValue = (Integer, Integer) FieldType S.Orientation = OrientationValue FieldType S.ShowRange = Bool FieldType S.ReadOut = Bool FieldType S.SliderColor = Text FieldType S.BarStyle = BarStyleValue FieldType S.FloatValue = Double FieldType S.StepFloat = Double FieldType S.MinFloat = Double FieldType S.MaxFloat = Double FieldType S.LowerFloat = Double FieldType S.UpperFloat = Double FieldType S.FloatPairValue = (Double, Double) FieldType S.ChangeHandler = IO () FieldType S.Children = [ChildWidget] FieldType S.OverflowX = OverflowValue FieldType S.OverflowY = OverflowValue FieldType S.BoxStyle = BoxStyleValue FieldType S.Flex = Int FieldType S.Pack = LocationValue FieldType S.Align = LocationValue FieldType S.Titles = [Text] FieldType S.SelectedIndex = Integer FieldType S.ReadOutMsg = Text FieldType S.Child = Maybe ChildWidget FieldType S.Selector = Text -- | Can be used to put different widgets in a list. Useful for dealing with children widgets. data ChildWidget = forall w. RecAll Attr (WidgetFields w) ToPairs => ChildWidget (IPythonWidget w) instance ToJSON ChildWidget where toJSON (ChildWidget x) = toJSON . pack $ "IPY_MODEL_" ++ uuidToString (uuid x) -- Will use a custom class rather than a newtype wrapper with an orphan instance. The main issue is -- the need of a Bounded instance for Float / Double. class CustomBounded a where lowerBound :: a upperBound :: a -- Set according to what IPython widgets use instance CustomBounded PixCount where upperBound = 10 ^ 16 - 1 lowerBound = -(10 ^ 16 - 1) instance CustomBounded Integer where lowerBound = -(10 ^ 16 - 1) upperBound = 10 ^ 16 - 1 instance CustomBounded Double where lowerBound = -(10 ** 16 - 1) upperBound = 10 ** 16 - 1 -- Different types of widgets. Every widget in IPython has a corresponding WidgetType data WidgetType = ButtonType | ImageType | OutputType | HTMLType | LatexType | TextType | TextAreaType | CheckBoxType | ToggleButtonType | ValidType | DropdownType | RadioButtonsType | SelectType | ToggleButtonsType | SelectMultipleType | IntTextType | BoundedIntTextType | IntSliderType | IntProgressType | IntRangeSliderType | FloatTextType | BoundedFloatTextType | FloatSliderType | FloatProgressType | FloatRangeSliderType | BoxType | ProxyType | PlaceProxyType | FlexBoxType | AccordionType | TabType -- Fields associated with a widget type family WidgetFields (w :: WidgetType) :: [Field] where WidgetFields ButtonType = DOMWidgetClass :++ '[S.Description, S.Tooltip, S.Disabled, S.Icon, S.ButtonStyle, S.ClickHandler] WidgetFields ImageType = DOMWidgetClass :++ '[S.ImageFormat, S.Width, S.Height, S.B64Value] WidgetFields OutputType = DOMWidgetClass WidgetFields HTMLType = StringClass WidgetFields LatexType = StringClass WidgetFields TextType = StringClass :++ '[S.SubmitHandler, S.ChangeHandler] WidgetFields TextAreaType = StringClass :++ '[S.ChangeHandler] WidgetFields CheckBoxType = BoolClass WidgetFields ToggleButtonType = BoolClass :++ '[S.Tooltip, S.Icon, S.ButtonStyle] WidgetFields ValidType = BoolClass :++ '[S.ReadOutMsg] WidgetFields DropdownType = SelectionClass :++ '[S.ButtonStyle] WidgetFields RadioButtonsType = SelectionClass WidgetFields SelectType = SelectionClass WidgetFields ToggleButtonsType = SelectionClass :++ '[S.Tooltips, S.Icons, S.ButtonStyle] WidgetFields SelectMultipleType = MultipleSelectionClass WidgetFields IntTextType = IntClass WidgetFields BoundedIntTextType = BoundedIntClass WidgetFields IntSliderType = BoundedIntClass :++ '[S.Orientation, S.ShowRange, S.ReadOut, S.SliderColor] WidgetFields IntProgressType = BoundedIntClass :++ '[S.Orientation, S.BarStyle] WidgetFields IntRangeSliderType = BoundedIntRangeClass :++ '[S.Orientation, S.ShowRange, S.ReadOut, S.SliderColor] WidgetFields FloatTextType = FloatClass WidgetFields BoundedFloatTextType = BoundedFloatClass WidgetFields FloatSliderType = BoundedFloatClass :++ '[S.Orientation, S.ShowRange, S.ReadOut, S.SliderColor] WidgetFields FloatProgressType = BoundedFloatClass :++ '[S.Orientation, S.BarStyle] WidgetFields FloatRangeSliderType = BoundedFloatRangeClass :++ '[S.Orientation, S.ShowRange, S.ReadOut, S.SliderColor] WidgetFields BoxType = BoxClass WidgetFields ProxyType = WidgetClass :++ '[S.Child] WidgetFields PlaceProxyType = WidgetFields ProxyType :++ '[S.Selector] WidgetFields FlexBoxType = BoxClass :++ '[S.Orientation, S.Flex, S.Pack, S.Align] WidgetFields AccordionType = SelectionContainerClass WidgetFields TabType = SelectionContainerClass -- Wrapper around a field's value. A dummy value is sent as an empty string to the frontend. data AttrVal a = Dummy a | Real a unwrap :: AttrVal a -> a unwrap (Dummy x) = x unwrap (Real x) = x -- Wrapper around a field. data Attr (f :: Field) where Attr :: Typeable (FieldType f) => { _value :: AttrVal (FieldType f) , _verify :: FieldType f -> IO (FieldType f) , _field :: Field } -> Attr f getFieldType :: Attr f -> TypeRep getFieldType Attr { _value = attrval } = typeOf $ unwrap attrval instance ToJSON (FieldType f) => ToJSON (Attr f) where toJSON attr = case _value attr of Dummy _ -> "" Real x -> toJSON x -- Types that can be converted to Aeson Pairs. class ToPairs a where toPairs :: a -> [Pair] -- Attributes that aren't synced with the frontend give [] on toPairs instance ToPairs (Attr S.ViewModule) where toPairs x = ["_view_module" .= toJSON x] instance ToPairs (Attr S.ViewName) where toPairs x = ["_view_name" .= toJSON x] instance ToPairs (Attr S.ModelModule) where toPairs x = ["_model_module" .= toJSON x] instance ToPairs (Attr S.ModelName) where toPairs x = ["_model_name" .= toJSON x] instance ToPairs (Attr S.MsgThrottle) where toPairs x = ["msg_throttle" .= toJSON x] instance ToPairs (Attr S.Version) where toPairs x = ["version" .= toJSON x] instance ToPairs (Attr S.DisplayHandler) where toPairs _ = [] -- Not sent to the frontend instance ToPairs (Attr S.Visible) where toPairs x = ["visible" .= toJSON x] instance ToPairs (Attr S.CSS) where toPairs x = ["_css" .= toJSON x] instance ToPairs (Attr S.DOMClasses) where toPairs x = ["_dom_classes" .= toJSON x] instance ToPairs (Attr S.Width) where toPairs x = ["width" .= toJSON x] instance ToPairs (Attr S.Height) where toPairs x = ["height" .= toJSON x] instance ToPairs (Attr S.Padding) where toPairs x = ["padding" .= toJSON x] instance ToPairs (Attr S.Margin) where toPairs x = ["margin" .= toJSON x] instance ToPairs (Attr S.Color) where toPairs x = ["color" .= toJSON x] instance ToPairs (Attr S.BackgroundColor) where toPairs x = ["background_color" .= toJSON x] instance ToPairs (Attr S.BorderColor) where toPairs x = ["border_color" .= toJSON x] instance ToPairs (Attr S.BorderWidth) where toPairs x = ["border_width" .= toJSON x] instance ToPairs (Attr S.BorderRadius) where toPairs x = ["border_radius" .= toJSON x] instance ToPairs (Attr S.BorderStyle) where toPairs x = ["border_style" .= toJSON x] instance ToPairs (Attr S.FontStyle) where toPairs x = ["font_style" .= toJSON x] instance ToPairs (Attr S.FontWeight) where toPairs x = ["font_weight" .= toJSON x] instance ToPairs (Attr S.FontSize) where toPairs x = ["font_size" .= toJSON x] instance ToPairs (Attr S.FontFamily) where toPairs x = ["font_family" .= toJSON x] instance ToPairs (Attr S.Description) where toPairs x = ["description" .= toJSON x] instance ToPairs (Attr S.ClickHandler) where toPairs _ = [] -- Not sent to the frontend instance ToPairs (Attr S.SubmitHandler) where toPairs _ = [] -- Not sent to the frontend instance ToPairs (Attr S.Disabled) where toPairs x = ["disabled" .= toJSON x] instance ToPairs (Attr S.StringValue) where toPairs x = ["value" .= toJSON x] instance ToPairs (Attr S.Placeholder) where toPairs x = ["placeholder" .= toJSON x] instance ToPairs (Attr S.Tooltip) where toPairs x = ["tooltip" .= toJSON x] instance ToPairs (Attr S.Icon) where toPairs x = ["icon" .= toJSON x] instance ToPairs (Attr S.ButtonStyle) where toPairs x = ["button_style" .= toJSON x] instance ToPairs (Attr S.B64Value) where toPairs x = ["_b64value" .= toJSON x] instance ToPairs (Attr S.ImageFormat) where toPairs x = ["format" .= toJSON x] instance ToPairs (Attr S.BoolValue) where toPairs x = ["value" .= toJSON x] instance ToPairs (Attr S.SelectedLabel) where toPairs x = ["selected_label" .= toJSON x] instance ToPairs (Attr S.SelectedValue) where toPairs x = ["value" .= toJSON x] instance ToPairs (Attr S.Options) where toPairs x = case _value x of Dummy _ -> labels ("" :: Text) Real (OptionLabels xs) -> labels xs Real (OptionDict xps) -> labels $ map fst xps where labels xs = ["_options_labels" .= xs] instance ToPairs (Attr S.SelectionHandler) where toPairs _ = [] -- Not sent to the frontend instance ToPairs (Attr S.Tooltips) where toPairs x = ["tooltips" .= toJSON x] instance ToPairs (Attr S.Icons) where toPairs x = ["icons" .= toJSON x] instance ToPairs (Attr S.SelectedLabels) where toPairs x = ["selected_labels" .= toJSON x] instance ToPairs (Attr S.SelectedValues) where toPairs x = ["values" .= toJSON x] instance ToPairs (Attr S.IntValue) where toPairs x = ["value" .= toJSON x] instance ToPairs (Attr S.StepInt) where toPairs x = ["step" .= toJSON x] instance ToPairs (Attr S.MinInt) where toPairs x = ["min" .= toJSON x] instance ToPairs (Attr S.MaxInt) where toPairs x = ["max" .= toJSON x] instance ToPairs (Attr S.IntPairValue) where toPairs x = ["value" .= toJSON x] instance ToPairs (Attr S.LowerInt) where toPairs x = ["min" .= toJSON x] instance ToPairs (Attr S.UpperInt) where toPairs x = ["max" .= toJSON x] instance ToPairs (Attr S.FloatValue) where toPairs x = ["value" .= toJSON x] instance ToPairs (Attr S.StepFloat) where toPairs x = ["step" .= toJSON x] instance ToPairs (Attr S.MinFloat) where toPairs x = ["min" .= toJSON x] instance ToPairs (Attr S.MaxFloat) where toPairs x = ["max" .= toJSON x] instance ToPairs (Attr S.FloatPairValue) where toPairs x = ["value" .= toJSON x] instance ToPairs (Attr S.LowerFloat) where toPairs x = ["min" .= toJSON x] instance ToPairs (Attr S.UpperFloat) where toPairs x = ["max" .= toJSON x] instance ToPairs (Attr S.Orientation) where toPairs x = ["orientation" .= toJSON x] instance ToPairs (Attr S.ShowRange) where toPairs x = ["_range" .= toJSON x] instance ToPairs (Attr S.ReadOut) where toPairs x = ["readout" .= toJSON x] instance ToPairs (Attr S.SliderColor) where toPairs x = ["slider_color" .= toJSON x] instance ToPairs (Attr S.BarStyle) where toPairs x = ["bar_style" .= toJSON x] instance ToPairs (Attr S.ChangeHandler) where toPairs _ = [] -- Not sent to the frontend instance ToPairs (Attr S.Children) where toPairs x = ["children" .= toJSON x] instance ToPairs (Attr S.OverflowX) where toPairs x = ["overflow_x" .= toJSON x] instance ToPairs (Attr S.OverflowY) where toPairs x = ["overflow_y" .= toJSON x] instance ToPairs (Attr S.BoxStyle) where toPairs x = ["box_style" .= toJSON x] instance ToPairs (Attr S.Flex) where toPairs x = ["flex" .= toJSON x] instance ToPairs (Attr S.Pack) where toPairs x = ["pack" .= toJSON x] instance ToPairs (Attr S.Align) where toPairs x = ["align" .= toJSON x] instance ToPairs (Attr S.Titles) where toPairs x = ["_titles" .= toJSON x] instance ToPairs (Attr S.SelectedIndex) where toPairs x = ["selected_index" .= toJSON x] instance ToPairs (Attr S.ReadOutMsg) where toPairs x = ["readout" .= toJSON x] instance ToPairs (Attr S.Child) where toPairs x = ["child" .= toJSON x] instance ToPairs (Attr S.Selector) where toPairs x = ["selector" .= toJSON x] -- | Store the value for a field, as an object parametrized by the Field. No verification is done -- for these values. (=::) :: (SingI f, Typeable (FieldType f)) => Sing f -> FieldType f -> Attr f s =:: x = Attr { _value = Real x, _verify = return, _field = reflect s } -- | If the number is in the range, return it. Otherwise raise the appropriate (over/under)flow -- exception. rangeCheck :: (Num a, Ord a) => (a, a) -> a -> IO a rangeCheck (l, u) x | l <= x && x <= u = return x | l > x = Ex.throw Ex.Underflow | u < x = Ex.throw Ex.Overflow | otherwise = error "The impossible happened in IHaskell.Display.Widgets.Types.rangeCheck" -- | Store a numeric value, with verification mechanism for its range. ranged :: (SingI f, Num (FieldType f), Ord (FieldType f), Typeable (FieldType f)) => Sing f -> (FieldType f, FieldType f) -> AttrVal (FieldType f) -> Attr f ranged s range x = Attr x (rangeCheck range) (reflect s) -- | Store a numeric value, with the invariant that it stays non-negative. The value set is set as a -- dummy value if it's equal to zero. (=:+) :: (SingI f, Num (FieldType f), CustomBounded (FieldType f), Ord (FieldType f), Typeable (FieldType f)) => Sing f -> FieldType f -> Attr f s =:+ val = Attr ((if val == 0 then Dummy else Real) val) (rangeCheck (0, upperBound)) (reflect s) -- | Get a field from a singleton Adapted from: http://stackoverflow.com/a/28033250/2388535 reflect :: forall (f :: Field). (SingI f, SingKind ('KProxy :: KProxy Field)) => Sing f -> Field reflect = fromSing -- | A record representing an object of the Widget class from IPython defaultWidget :: FieldType S.ViewName -> Rec Attr WidgetClass defaultWidget viewName = (ViewModule =:: "") :& (ViewName =:: viewName) :& (ModelModule =:: "") :& (ModelName =:: "WidgetModel") :& (MsgThrottle =:+ 3) :& (Version =:: 0) :& (DisplayHandler =:: return ()) :& RNil -- | A record representing an object of the DOMWidget class from IPython defaultDOMWidget :: FieldType S.ViewName -> Rec Attr DOMWidgetClass defaultDOMWidget viewName = defaultWidget viewName <+> domAttrs where domAttrs = (Visible =:: True) :& (CSS =:: []) :& (DOMClasses =:: []) :& (Width =:+ 0) :& (Height =:+ 0) :& (Padding =:+ 0) :& (Margin =:+ 0) :& (Color =:: "") :& (BackgroundColor =:: "") :& (BorderColor =:: "") :& (BorderWidth =:+ 0) :& (BorderRadius =:+ 0) :& (BorderStyle =:: DefaultBorder) :& (FontStyle =:: DefaultFont) :& (FontWeight =:: DefaultWeight) :& (FontSize =:+ 0) :& (FontFamily =:: "") :& RNil -- | A record representing a widget of the _String class from IPython defaultStringWidget :: FieldType S.ViewName -> Rec Attr StringClass defaultStringWidget viewName = defaultDOMWidget viewName <+> strAttrs where strAttrs = (StringValue =:: "") :& (Disabled =:: False) :& (Description =:: "") :& (Placeholder =:: "") :& RNil -- | A record representing a widget of the _Bool class from IPython defaultBoolWidget :: FieldType S.ViewName -> Rec Attr BoolClass defaultBoolWidget viewName = defaultDOMWidget viewName <+> boolAttrs where boolAttrs = (BoolValue =:: False) :& (Disabled =:: False) :& (Description =:: "") :& (ChangeHandler =:: return ()) :& RNil -- | A record representing a widget of the _Selection class from IPython defaultSelectionWidget :: FieldType S.ViewName -> Rec Attr SelectionClass defaultSelectionWidget viewName = defaultDOMWidget viewName <+> selectionAttrs where selectionAttrs = (Options =:: OptionLabels []) :& (SelectedValue =:: "") :& (SelectedLabel =:: "") :& (Disabled =:: False) :& (Description =:: "") :& (SelectionHandler =:: return ()) :& RNil -- | A record representing a widget of the _MultipleSelection class from IPython defaultMultipleSelectionWidget :: FieldType S.ViewName -> Rec Attr MultipleSelectionClass defaultMultipleSelectionWidget viewName = defaultDOMWidget viewName <+> mulSelAttrs where mulSelAttrs = (Options =:: OptionLabels []) :& (SelectedValues =:: []) :& (SelectedLabels =:: []) :& (Disabled =:: False) :& (Description =:: "") :& (SelectionHandler =:: return ()) :& RNil -- | A record representing a widget of the _Int class from IPython defaultIntWidget :: FieldType S.ViewName -> Rec Attr IntClass defaultIntWidget viewName = defaultDOMWidget viewName <+> intAttrs where intAttrs = (IntValue =:: 0) :& (Disabled =:: False) :& (Description =:: "") :& (ChangeHandler =:: return ()) :& RNil -- | A record representing a widget of the _BoundedInt class from IPython defaultBoundedIntWidget :: FieldType S.ViewName -> Rec Attr BoundedIntClass defaultBoundedIntWidget viewName = defaultIntWidget viewName <+> boundedIntAttrs where boundedIntAttrs = (StepInt =:: 1) :& (MinInt =:: 0) :& (MaxInt =:: 100) :& RNil -- | A record representing a widget of the _BoundedInt class from IPython defaultIntRangeWidget :: FieldType S.ViewName -> Rec Attr IntRangeClass defaultIntRangeWidget viewName = defaultIntWidget viewName <+> rangeAttrs where rangeAttrs = (IntPairValue =:: (25, 75)) :& (LowerInt =:: 0) :& (UpperInt =:: 100) :& RNil -- | A record representing a widget of the _BoundedIntRange class from IPython defaultBoundedIntRangeWidget :: FieldType S.ViewName -> Rec Attr BoundedIntRangeClass defaultBoundedIntRangeWidget viewName = defaultIntRangeWidget viewName <+> boundedIntRangeAttrs where boundedIntRangeAttrs = (StepInt =:+ 1) :& (MinInt =:: 0) :& (MaxInt =:: 100) :& RNil -- | A record representing a widget of the _Float class from IPython defaultFloatWidget :: FieldType S.ViewName -> Rec Attr FloatClass defaultFloatWidget viewName = defaultDOMWidget viewName <+> intAttrs where intAttrs = (FloatValue =:: 0) :& (Disabled =:: False) :& (Description =:: "") :& (ChangeHandler =:: return ()) :& RNil -- | A record representing a widget of the _BoundedFloat class from IPython defaultBoundedFloatWidget :: FieldType S.ViewName -> Rec Attr BoundedFloatClass defaultBoundedFloatWidget viewName = defaultFloatWidget viewName <+> boundedFloatAttrs where boundedFloatAttrs = (StepFloat =:+ 1) :& (MinFloat =:: 0) :& (MaxFloat =:: 100) :& RNil -- | A record representing a widget of the _BoundedFloat class from IPython defaultFloatRangeWidget :: FieldType S.ViewName -> Rec Attr FloatRangeClass defaultFloatRangeWidget viewName = defaultFloatWidget viewName <+> rangeAttrs where rangeAttrs = (FloatPairValue =:: (25, 75)) :& (LowerFloat =:: 0) :& (UpperFloat =:: 100) :& RNil -- | A record representing a widget of the _BoundedFloatRange class from IPython defaultBoundedFloatRangeWidget :: FieldType S.ViewName -> Rec Attr BoundedFloatRangeClass defaultBoundedFloatRangeWidget viewName = defaultFloatRangeWidget viewName <+> boundedFloatRangeAttrs where boundedFloatRangeAttrs = (StepFloat =:+ 1) :& (MinFloat =:: 0) :& (MaxFloat =:: 100) :& RNil -- | A record representing a widget of the _Box class from IPython defaultBoxWidget :: FieldType S.ViewName -> Rec Attr BoxClass defaultBoxWidget viewName = domAttrs <+> boxAttrs where defaultDOM = defaultDOMWidget viewName domAttrs = rput (ModelName =:: "BoxModel") defaultDOM boxAttrs = (Children =:: []) :& (OverflowX =:: DefaultOverflow) :& (OverflowY =:: DefaultOverflow) :& (BoxStyle =:: DefaultBox) :& RNil -- | A record representing a widget of the _SelectionContainer class from IPython defaultSelectionContainerWidget :: FieldType S.ViewName -> Rec Attr SelectionContainerClass defaultSelectionContainerWidget viewName = defaultBoxWidget viewName <+> selAttrs where selAttrs = (Titles =:: []) :& (SelectedIndex =:: 0) :& (ChangeHandler =:: return ()) :& RNil newtype WidgetState w = WidgetState { _getState :: Rec Attr (WidgetFields w) } -- All records with ToPair instances for their Attrs will automatically have a toJSON instance now. instance RecAll Attr (WidgetFields w) ToPairs => ToJSON (WidgetState w) where toJSON record = object . concat . recordToList . rmap (\(Compose (Dict x)) -> Const $ toPairs x) $ reifyConstraint (Proxy :: Proxy ToPairs) $ _getState record data IPythonWidget (w :: WidgetType) = IPythonWidget { uuid :: UUID , state :: IORef (WidgetState w) } -- | Change the value for a field, and notify the frontend about it. setField :: (f ∈ WidgetFields w, IHaskellWidget (IPythonWidget w), ToPairs (Attr f)) => IPythonWidget w -> SField f -> FieldType f -> IO () setField widget sfield fval = do !newattr <- setField' widget sfield fval let pairs = toPairs newattr unless (null pairs) $ widgetSendUpdate widget (object pairs) -- | Change the value of a field, without notifying the frontend. For internal use. setField' :: (f ∈ WidgetFields w, IHaskellWidget (IPythonWidget w)) => IPythonWidget w -> SField f -> FieldType f -> IO (Attr f) setField' widget sfield val = do attr <- getAttr widget sfield newval <- _verify attr val let newattr = attr { _value = Real newval } modifyIORef (state widget) (WidgetState . rput newattr . _getState) return newattr -- | Pluck an attribute from a record getAttr :: (f ∈ WidgetFields w) => IPythonWidget w -> SField f -> IO (Attr f) getAttr widget sfield = rget sfield <$> _getState <$> readIORef (state widget) -- | Get the value of a field. getField :: (f ∈ WidgetFields w) => IPythonWidget w -> SField f -> IO (FieldType f) getField widget sfield = unwrap . _value <$> getAttr widget sfield -- | Useful with toJSON and OverloadedStrings str :: String -> String str = id properties :: IPythonWidget w -> IO () properties widget = do st <- readIORef $ state widget let convert :: Attr f -> Const (Field, TypeRep) f convert attr = Const (_field attr, getFieldType attr) renderRow (fname, ftype) = printf "%s ::: %s" (show fname) (show ftype) rows = map renderRow . recordToList . rmap convert $ _getState st mapM_ putStrLn rows -- Helper function for widget to enforce their inability to fetch console input noStdin :: IO a -> IO () noStdin action = let handler :: IOException -> IO () handler e = when (ioeGetErrorType e == InvalidArgument) (error "Widgets cannot do console input, sorry :)") in Ex.handle handler $ do nullFd <- openFd "/dev/null" WriteOnly Nothing defaultFileFlags oldStdin <- dup stdInput void $ dupTo nullFd stdInput closeFd nullFd void action void $ dupTo oldStdin stdInput -- Trigger events triggerEvent :: (FieldType f ~ IO (), f ∈ WidgetFields w) => SField f -> IPythonWidget w -> IO () triggerEvent sfield w = noStdin . join $ getField w sfield triggerChange :: (S.ChangeHandler ∈ WidgetFields w) => IPythonWidget w -> IO () triggerChange = triggerEvent ChangeHandler triggerClick :: (S.ClickHandler ∈ WidgetFields w) => IPythonWidget w -> IO () triggerClick = triggerEvent ClickHandler triggerSelection :: (S.SelectionHandler ∈ WidgetFields w) => IPythonWidget w -> IO () triggerSelection = triggerEvent SelectionHandler triggerSubmit :: (S.SubmitHandler ∈ WidgetFields w) => IPythonWidget w -> IO () triggerSubmit = triggerEvent SubmitHandler triggerDisplay :: (S.DisplayHandler ∈ WidgetFields w) => IPythonWidget w -> IO () triggerDisplay = triggerEvent DisplayHandler
artuuge/IHaskell
ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Types.hs
mit
34,151
1
26
8,882
8,920
4,683
4,237
-1
-1
{-# LANGUAGE CPP, MagicHash, NondecreasingIndentation, UnboxedTuples, RecordWildCards, BangPatterns #-} -- ----------------------------------------------------------------------------- -- -- (c) The University of Glasgow, 2005-2007 -- -- Running statements interactively -- -- ----------------------------------------------------------------------------- module InteractiveEval ( #ifdef GHCI Resume(..), History(..), execStmt, ExecOptions(..), execOptions, ExecResult(..), resumeExec, runDecls, runDeclsWithLocation, isStmt, hasImport, isImport, isDecl, parseImportDecl, SingleStep(..), resume, abandon, abandonAll, getResumeContext, getHistorySpan, getModBreaks, getHistoryModule, back, forward, setContext, getContext, availsToGlobalRdrEnv, getNamesInScope, getRdrNamesInScope, moduleIsInterpreted, getInfo, exprType, typeKind, parseName, showModule, isModuleInterpreted, parseExpr, compileParsedExpr, compileExpr, dynCompileExpr, compileExprRemote, compileParsedExprRemote, Term(..), obtainTermFromId, obtainTermFromVal, reconstructType, -- * Depcreated API (remove in GHC 7.14) RunResult(..), runStmt, runStmtWithLocation, #endif ) where #ifdef GHCI #include "HsVersions.h" import InteractiveEvalTypes import GHCi import GHCi.Run import GHCi.RemoteTypes import GhcMonad import HscMain import HsSyn import HscTypes import InstEnv import IfaceEnv ( newInteractiveBinder ) import FamInstEnv ( FamInst ) import CoreFVs ( orphNamesOfFamInst ) import TyCon import Type hiding( typeKind ) import RepType import TcType hiding( typeKind ) import Var import Id import Name hiding ( varName ) import NameSet import Avail import RdrName import VarSet import VarEnv import ByteCodeTypes import Linker import DynFlags import Unique import UniqSupply import MonadUtils import Module import PrelNames ( toDynName, pretendNameIsInScope ) import Panic import Maybes import ErrUtils import SrcLoc import RtClosureInspect import Outputable import FastString import Bag import qualified Lexer (P (..), ParseResult(..), unP, mkPState) import qualified Parser (parseStmt, parseModule, parseDeclaration, parseImport) import System.Directory import Data.Dynamic import Data.Either import qualified Data.IntMap as IntMap import Data.List (find,intercalate) import StringBuffer (stringToStringBuffer) import Control.Monad import GHC.Exts import Data.Array import Exception import Control.Concurrent -- ----------------------------------------------------------------------------- -- running a statement interactively getResumeContext :: GhcMonad m => m [Resume] getResumeContext = withSession (return . ic_resume . hsc_IC) mkHistory :: HscEnv -> ForeignHValue -> BreakInfo -> History mkHistory hsc_env hval bi = History hval bi (findEnclosingDecls hsc_env bi) getHistoryModule :: History -> Module getHistoryModule = breakInfo_module . historyBreakInfo getHistorySpan :: HscEnv -> History -> SrcSpan getHistorySpan hsc_env History{..} = let BreakInfo{..} = historyBreakInfo in case lookupHpt (hsc_HPT hsc_env) (moduleName breakInfo_module) of Just hmi -> modBreaks_locs (getModBreaks hmi) ! breakInfo_number _ -> panic "getHistorySpan" getModBreaks :: HomeModInfo -> ModBreaks getModBreaks hmi | Just linkable <- hm_linkable hmi, [BCOs cbc] <- linkableUnlinked linkable = fromMaybe emptyModBreaks (bc_breaks cbc) | otherwise = emptyModBreaks -- probably object code {- | Finds the enclosing top level function name -} -- ToDo: a better way to do this would be to keep hold of the decl_path computed -- by the coverage pass, which gives the list of lexically-enclosing bindings -- for each tick. findEnclosingDecls :: HscEnv -> BreakInfo -> [String] findEnclosingDecls hsc_env (BreakInfo modl ix) = let hmi = expectJust "findEnclosingDecls" $ lookupHpt (hsc_HPT hsc_env) (moduleName modl) mb = getModBreaks hmi in modBreaks_decls mb ! ix -- | Update fixity environment in the current interactive context. updateFixityEnv :: GhcMonad m => FixityEnv -> m () updateFixityEnv fix_env = do hsc_env <- getSession let ic = hsc_IC hsc_env setSession $ hsc_env { hsc_IC = ic { ic_fix_env = fix_env } } -- ----------------------------------------------------------------------------- -- execStmt -- | default ExecOptions execOptions :: ExecOptions execOptions = ExecOptions { execSingleStep = RunToCompletion , execSourceFile = "<interactive>" , execLineNumber = 1 , execWrap = EvalThis -- just run the statement, don't wrap it in anything } -- | Run a statement in the current interactive context. execStmt :: GhcMonad m => String -- ^ a statement (bind or expression) -> ExecOptions -> m ExecResult execStmt stmt ExecOptions{..} = do hsc_env <- getSession -- Turn off -fwarn-unused-local-binds when running a statement, to hide -- warnings about the implicit bindings we introduce. let ic = hsc_IC hsc_env -- use the interactive dflags idflags' = ic_dflags ic `wopt_unset` Opt_WarnUnusedLocalBinds hsc_env' = hsc_env{ hsc_IC = ic{ ic_dflags = idflags' } } -- compile to value (IO [HValue]), don't run r <- liftIO $ hscStmtWithLocation hsc_env' stmt execSourceFile execLineNumber case r of -- empty statement / comment Nothing -> return (ExecComplete (Right []) 0) Just (ids, hval, fix_env) -> do updateFixityEnv fix_env status <- withVirtualCWD $ liftIO $ evalStmt hsc_env' (isStep execSingleStep) (execWrap hval) let ic = hsc_IC hsc_env bindings = (ic_tythings ic, ic_rn_gbl_env ic) size = ghciHistSize idflags' handleRunStatus execSingleStep stmt bindings ids status (emptyHistory size) -- | The type returned by the deprecated 'runStmt' and -- 'runStmtWithLocation' API data RunResult = RunOk [Name] -- ^ names bound by this evaluation | RunException SomeException -- ^ statement raised an exception | RunBreak ThreadId [Name] (Maybe BreakInfo) -- | Conver the old result type to the new result type execResultToRunResult :: ExecResult -> RunResult execResultToRunResult r = case r of ExecComplete{ execResult = Left ex } -> RunException ex ExecComplete{ execResult = Right names } -> RunOk names ExecBreak{..} -> RunBreak (error "no breakThreadId") breakNames breakInfo -- Remove in GHC 7.14 {-# DEPRECATED runStmt "use execStmt" #-} -- | Run a statement in the current interactive context. Statement -- may bind multple values. runStmt :: GhcMonad m => String -> SingleStep -> m RunResult runStmt stmt step = execResultToRunResult <$> execStmt stmt execOptions { execSingleStep = step } -- Remove in GHC 7.14 {-# DEPRECATED runStmtWithLocation "use execStmtWithLocation" #-} runStmtWithLocation :: GhcMonad m => String -> Int -> String -> SingleStep -> m RunResult runStmtWithLocation source linenumber expr step = do execResultToRunResult <$> execStmt expr execOptions { execSingleStep = step , execSourceFile = source , execLineNumber = linenumber } runDecls :: GhcMonad m => String -> m [Name] runDecls = runDeclsWithLocation "<interactive>" 1 -- | Run some declarations and return any user-visible names that were brought -- into scope. runDeclsWithLocation :: GhcMonad m => String -> Int -> String -> m [Name] runDeclsWithLocation source linenumber expr = do hsc_env <- getSession (tyThings, ic) <- liftIO $ hscDeclsWithLocation hsc_env expr source linenumber setSession $ hsc_env { hsc_IC = ic } hsc_env <- getSession hsc_env' <- liftIO $ rttiEnvironment hsc_env setSession hsc_env' return $ filter (not . isDerivedOccName . nameOccName) -- For this filter, see Note [What to show to users] $ map getName tyThings {- Note [What to show to users] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We don't want to display internally-generated bindings to users. Things like the coercion axiom for newtypes. These bindings all get OccNames that users can't write, to avoid the possiblity of name clashes (in linker symbols). That gives a convenient way to suppress them. The relevant predicate is OccName.isDerivedOccName. See Trac #11051 for more background and examples. -} withVirtualCWD :: GhcMonad m => m a -> m a withVirtualCWD m = do hsc_env <- getSession -- a virtual CWD is only necessary when we're running interpreted code in -- the same process as the compiler. if gopt Opt_ExternalInterpreter (hsc_dflags hsc_env) then m else do let ic = hsc_IC hsc_env let set_cwd = do dir <- liftIO $ getCurrentDirectory case ic_cwd ic of Just dir -> liftIO $ setCurrentDirectory dir Nothing -> return () return dir reset_cwd orig_dir = do virt_dir <- liftIO $ getCurrentDirectory hsc_env <- getSession let old_IC = hsc_IC hsc_env setSession hsc_env{ hsc_IC = old_IC{ ic_cwd = Just virt_dir } } liftIO $ setCurrentDirectory orig_dir gbracket set_cwd reset_cwd $ \_ -> m parseImportDecl :: GhcMonad m => String -> m (ImportDecl RdrName) parseImportDecl expr = withSession $ \hsc_env -> liftIO $ hscImport hsc_env expr emptyHistory :: Int -> BoundedList History emptyHistory size = nilBL size handleRunStatus :: GhcMonad m => SingleStep -> String-> ([TyThing],GlobalRdrEnv) -> [Id] -> EvalStatus_ [ForeignHValue] [HValueRef] -> BoundedList History -> m ExecResult handleRunStatus step expr bindings final_ids status history | RunAndLogSteps <- step = tracing | otherwise = not_tracing where tracing | EvalBreak is_exception apStack_ref ix mod_uniq resume_ctxt _ccs <- status , not is_exception = do hsc_env <- getSession let hmi = expectJust "handleRunStatus" $ lookupHptDirectly (hsc_HPT hsc_env) (mkUniqueGrimily mod_uniq) modl = mi_module (hm_iface hmi) breaks = getModBreaks hmi b <- liftIO $ breakpointStatus hsc_env (modBreaks_flags breaks) ix if b then not_tracing -- This breakpoint is explicitly enabled; we want to stop -- instead of just logging it. else do apStack_fhv <- liftIO $ mkFinalizedHValue hsc_env apStack_ref let bi = BreakInfo modl ix !history' = mkHistory hsc_env apStack_fhv bi `consBL` history -- history is strict, otherwise our BoundedList is pointless. fhv <- liftIO $ mkFinalizedHValue hsc_env resume_ctxt status <- liftIO $ GHCi.resumeStmt hsc_env True fhv handleRunStatus RunAndLogSteps expr bindings final_ids status history' | otherwise = not_tracing not_tracing -- Hit a breakpoint | EvalBreak is_exception apStack_ref ix mod_uniq resume_ctxt ccs <- status = do hsc_env <- getSession resume_ctxt_fhv <- liftIO $ mkFinalizedHValue hsc_env resume_ctxt apStack_fhv <- liftIO $ mkFinalizedHValue hsc_env apStack_ref let hmi = expectJust "handleRunStatus" $ lookupHptDirectly (hsc_HPT hsc_env) (mkUniqueGrimily mod_uniq) modl = mi_module (hm_iface hmi) bp | is_exception = Nothing | otherwise = Just (BreakInfo modl ix) (hsc_env1, names, span, decl) <- liftIO $ bindLocalsAtBreakpoint hsc_env apStack_fhv bp let resume = Resume { resumeStmt = expr, resumeContext = resume_ctxt_fhv , resumeBindings = bindings, resumeFinalIds = final_ids , resumeApStack = apStack_fhv , resumeBreakInfo = bp , resumeSpan = span, resumeHistory = toListBL history , resumeDecl = decl , resumeCCS = ccs , resumeHistoryIx = 0 } hsc_env2 = pushResume hsc_env1 resume setSession hsc_env2 return (ExecBreak names bp) -- Completed successfully | EvalComplete allocs (EvalSuccess hvals) <- status = do hsc_env <- getSession let final_ic = extendInteractiveContextWithIds (hsc_IC hsc_env) final_ids final_names = map getName final_ids liftIO $ Linker.extendLinkEnv (zip final_names hvals) hsc_env' <- liftIO $ rttiEnvironment hsc_env{hsc_IC=final_ic} setSession hsc_env' return (ExecComplete (Right final_names) allocs) -- Completed with an exception | EvalComplete alloc (EvalException e) <- status = return (ExecComplete (Left (fromSerializableException e)) alloc) | otherwise = panic "not_tracing" -- actually exhaustive, but GHC can't tell resume :: GhcMonad m => (SrcSpan->Bool) -> SingleStep -> m RunResult resume canLogSpan step = execResultToRunResult <$> resumeExec canLogSpan step resumeExec :: GhcMonad m => (SrcSpan->Bool) -> SingleStep -> m ExecResult resumeExec canLogSpan step = do hsc_env <- getSession let ic = hsc_IC hsc_env resume = ic_resume ic case resume of [] -> liftIO $ throwGhcExceptionIO (ProgramError "not stopped at a breakpoint") (r:rs) -> do -- unbind the temporary locals by restoring the TypeEnv from -- before the breakpoint, and drop this Resume from the -- InteractiveContext. let (resume_tmp_te,resume_rdr_env) = resumeBindings r ic' = ic { ic_tythings = resume_tmp_te, ic_rn_gbl_env = resume_rdr_env, ic_resume = rs } setSession hsc_env{ hsc_IC = ic' } -- remove any bindings created since the breakpoint from the -- linker's environment let old_names = map getName resume_tmp_te new_names = [ n | thing <- ic_tythings ic , let n = getName thing , not (n `elem` old_names) ] liftIO $ Linker.deleteFromLinkEnv new_names case r of Resume { resumeStmt = expr, resumeContext = fhv , resumeBindings = bindings, resumeFinalIds = final_ids , resumeApStack = apStack, resumeBreakInfo = mb_brkpt , resumeSpan = span , resumeHistory = hist } -> do withVirtualCWD $ do status <- liftIO $ GHCi.resumeStmt hsc_env (isStep step) fhv let prevHistoryLst = fromListBL 50 hist hist' = case mb_brkpt of Nothing -> prevHistoryLst Just bi | not $canLogSpan span -> prevHistoryLst | otherwise -> mkHistory hsc_env apStack bi `consBL` fromListBL 50 hist handleRunStatus step expr bindings final_ids status hist' back :: GhcMonad m => Int -> m ([Name], Int, SrcSpan, String) back n = moveHist (+n) forward :: GhcMonad m => Int -> m ([Name], Int, SrcSpan, String) forward n = moveHist (subtract n) moveHist :: GhcMonad m => (Int -> Int) -> m ([Name], Int, SrcSpan, String) moveHist fn = do hsc_env <- getSession case ic_resume (hsc_IC hsc_env) of [] -> liftIO $ throwGhcExceptionIO (ProgramError "not stopped at a breakpoint") (r:rs) -> do let ix = resumeHistoryIx r history = resumeHistory r new_ix = fn ix -- when (new_ix > length history) $ liftIO $ throwGhcExceptionIO (ProgramError "no more logged breakpoints") when (new_ix < 0) $ liftIO $ throwGhcExceptionIO (ProgramError "already at the beginning of the history") let update_ic apStack mb_info = do (hsc_env1, names, span, decl) <- liftIO $ bindLocalsAtBreakpoint hsc_env apStack mb_info let ic = hsc_IC hsc_env1 r' = r { resumeHistoryIx = new_ix } ic' = ic { ic_resume = r':rs } setSession hsc_env1{ hsc_IC = ic' } return (names, new_ix, span, decl) -- careful: we want apStack to be the AP_STACK itself, not a thunk -- around it, hence the cases are carefully constructed below to -- make this the case. ToDo: this is v. fragile, do something better. if new_ix == 0 then case r of Resume { resumeApStack = apStack, resumeBreakInfo = mb_brkpt } -> update_ic apStack mb_brkpt else case history !! (new_ix - 1) of History{..} -> update_ic historyApStack (Just historyBreakInfo) -- ----------------------------------------------------------------------------- -- After stopping at a breakpoint, add free variables to the environment result_fs :: FastString result_fs = fsLit "_result" bindLocalsAtBreakpoint :: HscEnv -> ForeignHValue -> Maybe BreakInfo -> IO (HscEnv, [Name], SrcSpan, String) -- Nothing case: we stopped when an exception was raised, not at a -- breakpoint. We have no location information or local variables to -- bind, all we can do is bind a local variable to the exception -- value. bindLocalsAtBreakpoint hsc_env apStack Nothing = do let exn_occ = mkVarOccFS (fsLit "_exception") span = mkGeneralSrcSpan (fsLit "<unknown>") exn_name <- newInteractiveBinder hsc_env exn_occ span let e_fs = fsLit "e" e_name = mkInternalName (getUnique e_fs) (mkTyVarOccFS e_fs) span e_tyvar = mkRuntimeUnkTyVar e_name liftedTypeKind exn_id = Id.mkVanillaGlobal exn_name (mkTyVarTy e_tyvar) ictxt0 = hsc_IC hsc_env ictxt1 = extendInteractiveContextWithIds ictxt0 [exn_id] -- Linker.extendLinkEnv [(exn_name, apStack)] return (hsc_env{ hsc_IC = ictxt1 }, [exn_name], span, "<exception thrown>") -- Just case: we stopped at a breakpoint, we have information about the location -- of the breakpoint and the free variables of the expression. bindLocalsAtBreakpoint hsc_env apStack_fhv (Just BreakInfo{..}) = do let hmi = expectJust "bindLocalsAtBreakpoint" $ lookupHpt (hsc_HPT hsc_env) (moduleName breakInfo_module) breaks = getModBreaks hmi info = expectJust "bindLocalsAtBreakpoint2" $ IntMap.lookup breakInfo_number (modBreaks_breakInfo breaks) vars = cgb_vars info result_ty = cgb_resty info occs = modBreaks_vars breaks ! breakInfo_number span = modBreaks_locs breaks ! breakInfo_number decl = intercalate "." $ modBreaks_decls breaks ! breakInfo_number -- Filter out any unboxed ids; -- we can't bind these at the prompt pointers = filter (\(id,_) -> isPointer id) vars isPointer id | UnaryRep ty <- repType (idType id) , PtrRep <- typePrimRep ty = True | otherwise = False (ids, offsets) = unzip pointers free_tvs = tyCoVarsOfTypesList (result_ty:map idType ids) -- It might be that getIdValFromApStack fails, because the AP_STACK -- has been accidentally evaluated, or something else has gone wrong. -- So that we don't fall over in a heap when this happens, just don't -- bind any free variables instead, and we emit a warning. mb_hValues <- mapM (getBreakpointVar hsc_env apStack_fhv . fromIntegral) offsets when (any isNothing mb_hValues) $ debugTraceMsg (hsc_dflags hsc_env) 1 $ text "Warning: _result has been evaluated, some bindings have been lost" us <- mkSplitUniqSupply 'I' -- Dodgy; will give the same uniques every time let tv_subst = newTyVars us free_tvs filtered_ids = [ id | (id, Just _hv) <- zip ids mb_hValues ] (_,tidy_tys) = tidyOpenTypes emptyTidyEnv $ map (substTy tv_subst . idType) filtered_ids new_ids <- zipWith3M mkNewId occs tidy_tys filtered_ids result_name <- newInteractiveBinder hsc_env (mkVarOccFS result_fs) span let result_id = Id.mkVanillaGlobal result_name (substTy tv_subst result_ty) result_ok = isPointer result_id final_ids | result_ok = result_id : new_ids | otherwise = new_ids ictxt0 = hsc_IC hsc_env ictxt1 = extendInteractiveContextWithIds ictxt0 final_ids names = map idName new_ids let fhvs = catMaybes mb_hValues Linker.extendLinkEnv (zip names fhvs) when result_ok $ Linker.extendLinkEnv [(result_name, apStack_fhv)] hsc_env1 <- rttiEnvironment hsc_env{ hsc_IC = ictxt1 } return (hsc_env1, if result_ok then result_name:names else names, span, decl) where -- We need a fresh Unique for each Id we bind, because the linker -- state is single-threaded and otherwise we'd spam old bindings -- whenever we stop at a breakpoint. The InteractveContext is properly -- saved/restored, but not the linker state. See #1743, test break026. mkNewId :: OccName -> Type -> Id -> IO Id mkNewId occ ty old_id = do { name <- newInteractiveBinder hsc_env occ (getSrcSpan old_id) ; return (Id.mkVanillaGlobalWithInfo name ty (idInfo old_id)) } newTyVars :: UniqSupply -> [TcTyVar] -> TCvSubst -- Similarly, clone the type variables mentioned in the types -- we have here, *and* make them all RuntimeUnk tyvars newTyVars us tvs = mkTvSubstPrs [ (tv, mkTyVarTy (mkRuntimeUnkTyVar name (tyVarKind tv))) | (tv, uniq) <- tvs `zip` uniqsFromSupply us , let name = setNameUnique (tyVarName tv) uniq ] rttiEnvironment :: HscEnv -> IO HscEnv rttiEnvironment hsc_env@HscEnv{hsc_IC=ic} = do let tmp_ids = [id | AnId id <- ic_tythings ic] incompletelyTypedIds = [id | id <- tmp_ids , not $ noSkolems id , (occNameFS.nameOccName.idName) id /= result_fs] hsc_env' <- foldM improveTypes hsc_env (map idName incompletelyTypedIds) return hsc_env' where noSkolems = isEmptyVarSet . tyCoVarsOfType . idType improveTypes hsc_env@HscEnv{hsc_IC=ic} name = do let tmp_ids = [id | AnId id <- ic_tythings ic] Just id = find (\i -> idName i == name) tmp_ids if noSkolems id then return hsc_env else do mb_new_ty <- reconstructType hsc_env 10 id let old_ty = idType id case mb_new_ty of Nothing -> return hsc_env Just new_ty -> do case improveRTTIType hsc_env old_ty new_ty of Nothing -> return $ WARN(True, text (":print failed to calculate the " ++ "improvement for a type")) hsc_env Just subst -> do let dflags = hsc_dflags hsc_env when (dopt Opt_D_dump_rtti dflags) $ printInfoForUser dflags alwaysQualify $ fsep [text "RTTI Improvement for", ppr id, equals, ppr subst] let ic' = substInteractiveContext ic subst return hsc_env{hsc_IC=ic'} pushResume :: HscEnv -> Resume -> HscEnv pushResume hsc_env resume = hsc_env { hsc_IC = ictxt1 } where ictxt0 = hsc_IC hsc_env ictxt1 = ictxt0 { ic_resume = resume : ic_resume ictxt0 } -- ----------------------------------------------------------------------------- -- Abandoning a resume context abandon :: GhcMonad m => m Bool abandon = do hsc_env <- getSession let ic = hsc_IC hsc_env resume = ic_resume ic case resume of [] -> return False r:rs -> do setSession hsc_env{ hsc_IC = ic { ic_resume = rs } } liftIO $ abandonStmt hsc_env (resumeContext r) return True abandonAll :: GhcMonad m => m Bool abandonAll = do hsc_env <- getSession let ic = hsc_IC hsc_env resume = ic_resume ic case resume of [] -> return False rs -> do setSession hsc_env{ hsc_IC = ic { ic_resume = [] } } liftIO $ mapM_ (abandonStmt hsc_env. resumeContext) rs return True -- ----------------------------------------------------------------------------- -- Bounded list, optimised for repeated cons data BoundedList a = BL {-# UNPACK #-} !Int -- length {-# UNPACK #-} !Int -- bound [a] -- left [a] -- right, list is (left ++ reverse right) nilBL :: Int -> BoundedList a nilBL bound = BL 0 bound [] [] consBL :: a -> BoundedList a -> BoundedList a consBL a (BL len bound left right) | len < bound = BL (len+1) bound (a:left) right | null right = BL len bound [a] $! tail (reverse left) | otherwise = BL len bound (a:left) $! tail right toListBL :: BoundedList a -> [a] toListBL (BL _ _ left right) = left ++ reverse right fromListBL :: Int -> [a] -> BoundedList a fromListBL bound l = BL (length l) bound l [] -- lenBL (BL len _ _ _) = len -- ----------------------------------------------------------------------------- -- | Set the interactive evaluation context. -- -- (setContext imports) sets the ic_imports field (which in turn -- determines what is in scope at the prompt) to 'imports', and -- constructs the ic_rn_glb_env environment to reflect it. -- -- We retain in scope all the things defined at the prompt, and kept -- in ic_tythings. (Indeed, they shadow stuff from ic_imports.) setContext :: GhcMonad m => [InteractiveImport] -> m () setContext imports = do { hsc_env <- getSession ; let dflags = hsc_dflags hsc_env ; all_env_err <- liftIO $ findGlobalRdrEnv hsc_env imports ; case all_env_err of Left (mod, err) -> liftIO $ throwGhcExceptionIO (formatError dflags mod err) Right all_env -> do { ; let old_ic = hsc_IC hsc_env !final_rdr_env = all_env `icExtendGblRdrEnv` ic_tythings old_ic ; setSession hsc_env{ hsc_IC = old_ic { ic_imports = imports , ic_rn_gbl_env = final_rdr_env }}}} where formatError dflags mod err = ProgramError . showSDoc dflags $ text "Cannot add module" <+> ppr mod <+> text "to context:" <+> text err findGlobalRdrEnv :: HscEnv -> [InteractiveImport] -> IO (Either (ModuleName, String) GlobalRdrEnv) -- Compute the GlobalRdrEnv for the interactive context findGlobalRdrEnv hsc_env imports = do { idecls_env <- hscRnImportDecls hsc_env idecls -- This call also loads any orphan modules ; return $ case partitionEithers (map mkEnv imods) of ([], imods_env) -> Right (foldr plusGlobalRdrEnv idecls_env imods_env) (err : _, _) -> Left err } where idecls :: [LImportDecl RdrName] idecls = [noLoc d | IIDecl d <- imports] imods :: [ModuleName] imods = [m | IIModule m <- imports] mkEnv mod = case mkTopLevEnv (hsc_HPT hsc_env) mod of Left err -> Left (mod, err) Right env -> Right env availsToGlobalRdrEnv :: ModuleName -> [AvailInfo] -> GlobalRdrEnv availsToGlobalRdrEnv mod_name avails = mkGlobalRdrEnv (gresFromAvails (Just imp_spec) avails) where -- We're building a GlobalRdrEnv as if the user imported -- all the specified modules into the global interactive module imp_spec = ImpSpec { is_decl = decl, is_item = ImpAll} decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name, is_qual = False, is_dloc = srcLocSpan interactiveSrcLoc } mkTopLevEnv :: HomePackageTable -> ModuleName -> Either String GlobalRdrEnv mkTopLevEnv hpt modl = case lookupHpt hpt modl of Nothing -> Left "not a home module" Just details -> case mi_globals (hm_iface details) of Nothing -> Left "not interpreted" Just env -> Right env -- | Get the interactive evaluation context, consisting of a pair of the -- set of modules from which we take the full top-level scope, and the set -- of modules from which we take just the exports respectively. getContext :: GhcMonad m => m [InteractiveImport] getContext = withSession $ \HscEnv{ hsc_IC=ic } -> return (ic_imports ic) -- | Returns @True@ if the specified module is interpreted, and hence has -- its full top-level scope available. moduleIsInterpreted :: GhcMonad m => Module -> m Bool moduleIsInterpreted modl = withSession $ \h -> if moduleUnitId modl /= thisPackage (hsc_dflags h) then return False else case lookupHpt (hsc_HPT h) (moduleName modl) of Just details -> return (isJust (mi_globals (hm_iface details))) _not_a_home_module -> return False -- | Looks up an identifier in the current interactive context (for :info) -- Filter the instances by the ones whose tycons (or clases resp) -- are in scope (qualified or otherwise). Otherwise we list a whole lot too many! -- The exact choice of which ones to show, and which to hide, is a judgement call. -- (see Trac #1581) getInfo :: GhcMonad m => Bool -> Name -> m (Maybe (TyThing,Fixity,[ClsInst],[FamInst])) getInfo allInfo name = withSession $ \hsc_env -> do mb_stuff <- liftIO $ hscTcRnGetInfo hsc_env name case mb_stuff of Nothing -> return Nothing Just (thing, fixity, cls_insts, fam_insts) -> do let rdr_env = ic_rn_gbl_env (hsc_IC hsc_env) -- Filter the instances based on whether the constituent names of their -- instance heads are all in scope. let cls_insts' = filter (plausible rdr_env . orphNamesOfClsInst) cls_insts fam_insts' = filter (plausible rdr_env . orphNamesOfFamInst) fam_insts return (Just (thing, fixity, cls_insts', fam_insts')) where plausible rdr_env names -- Dfun involving only names that are in ic_rn_glb_env = allInfo || nameSetAll ok names where -- A name is ok if it's in the rdr_env, -- whether qualified or not ok n | n == name = True -- The one we looked for in the first place! | pretendNameIsInScope n = True | isBuiltInSyntax n = True | isExternalName n = isJust (lookupGRE_Name rdr_env n) | otherwise = True -- | Returns all names in scope in the current interactive context getNamesInScope :: GhcMonad m => m [Name] getNamesInScope = withSession $ \hsc_env -> do return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env)))) -- | Returns all 'RdrName's in scope in the current interactive -- context, excluding any that are internally-generated. getRdrNamesInScope :: GhcMonad m => m [RdrName] getRdrNamesInScope = withSession $ \hsc_env -> do let ic = hsc_IC hsc_env gbl_rdrenv = ic_rn_gbl_env ic gbl_names = concatMap greRdrNames $ globalRdrEnvElts gbl_rdrenv -- Exclude internally generated names; see e.g. Trac #11328 return (filter (not . isDerivedOccName . rdrNameOcc) gbl_names) -- | Parses a string as an identifier, and returns the list of 'Name's that -- the identifier can refer to in the current interactive context. parseName :: GhcMonad m => String -> m [Name] parseName str = withSession $ \hsc_env -> liftIO $ do { lrdr_name <- hscParseIdentifier hsc_env str ; hscTcRnLookupRdrName hsc_env lrdr_name } -- | Returns @True@ if passed string is a statement. isStmt :: DynFlags -> String -> Bool isStmt dflags stmt = case parseThing Parser.parseStmt dflags stmt of Lexer.POk _ _ -> True Lexer.PFailed _ _ -> False -- | Returns @True@ if passed string has an import declaration. hasImport :: DynFlags -> String -> Bool hasImport dflags stmt = case parseThing Parser.parseModule dflags stmt of Lexer.POk _ thing -> hasImports thing Lexer.PFailed _ _ -> False where hasImports = not . null . hsmodImports . unLoc -- | Returns @True@ if passed string is an import declaration. isImport :: DynFlags -> String -> Bool isImport dflags stmt = case parseThing Parser.parseImport dflags stmt of Lexer.POk _ _ -> True Lexer.PFailed _ _ -> False -- | Returns @True@ if passed string is a declaration but __/not a splice/__. isDecl :: DynFlags -> String -> Bool isDecl dflags stmt = do case parseThing Parser.parseDeclaration dflags stmt of Lexer.POk _ thing -> case unLoc thing of SpliceD _ -> False _ -> True Lexer.PFailed _ _ -> False parseThing :: Lexer.P thing -> DynFlags -> String -> Lexer.ParseResult thing parseThing parser dflags stmt = do let buf = stringToStringBuffer stmt loc = mkRealSrcLoc (fsLit "<interactive>") 1 1 Lexer.unP parser (Lexer.mkPState dflags buf loc) -- ----------------------------------------------------------------------------- -- Getting the type of an expression -- | Get the type of an expression -- Returns the type as described by 'TcRnExprMode' exprType :: GhcMonad m => TcRnExprMode -> String -> m Type exprType mode expr = withSession $ \hsc_env -> do ty <- liftIO $ hscTcExpr hsc_env mode expr return $ tidyType emptyTidyEnv ty -- ----------------------------------------------------------------------------- -- Getting the kind of a type -- | Get the kind of a type typeKind :: GhcMonad m => Bool -> String -> m (Type, Kind) typeKind normalise str = withSession $ \hsc_env -> do liftIO $ hscKcType hsc_env normalise str ----------------------------------------------------------------------------- -- Compile an expression, run it and deliver the result -- | Parse an expression, the parsed expression can be further processed and -- passed to compileParsedExpr. parseExpr :: GhcMonad m => String -> m (LHsExpr RdrName) parseExpr expr = withSession $ \hsc_env -> do liftIO $ runInteractiveHsc hsc_env $ hscParseExpr expr -- | Compile an expression, run it and deliver the resulting HValue. compileExpr :: GhcMonad m => String -> m HValue compileExpr expr = do parsed_expr <- parseExpr expr compileParsedExpr parsed_expr -- | Compile an expression, run it and deliver the resulting HValue. compileExprRemote :: GhcMonad m => String -> m ForeignHValue compileExprRemote expr = do parsed_expr <- parseExpr expr compileParsedExprRemote parsed_expr -- | Compile an parsed expression (before renaming), run it and deliver -- the resulting HValue. compileParsedExprRemote :: GhcMonad m => LHsExpr RdrName -> m ForeignHValue compileParsedExprRemote expr@(L loc _) = withSession $ \hsc_env -> do -- > let _compileParsedExpr = expr -- Create let stmt from expr to make hscParsedStmt happy. -- We will ignore the returned [Id], namely [expr_id], and not really -- create a new binding. let expr_fs = fsLit "_compileParsedExpr" expr_name = mkInternalName (getUnique expr_fs) (mkTyVarOccFS expr_fs) loc let_stmt = L loc . LetStmt . L loc . HsValBinds $ ValBindsIn (unitBag $ mkHsVarBind loc (getRdrName expr_name) expr) [] Just ([_id], hvals_io, fix_env) <- liftIO $ hscParsedStmt hsc_env let_stmt updateFixityEnv fix_env status <- liftIO $ evalStmt hsc_env False (EvalThis hvals_io) case status of EvalComplete _ (EvalSuccess [hval]) -> return hval EvalComplete _ (EvalException e) -> liftIO $ throwIO (fromSerializableException e) _ -> panic "compileParsedExpr" compileParsedExpr :: GhcMonad m => LHsExpr RdrName -> m HValue compileParsedExpr expr = do fhv <- compileParsedExprRemote expr dflags <- getDynFlags liftIO $ wormhole dflags fhv -- | Compile an expression, run it and return the result as a Dynamic. dynCompileExpr :: GhcMonad m => String -> m Dynamic dynCompileExpr expr = do parsed_expr <- parseExpr expr -- > Data.Dynamic.toDyn expr let loc = getLoc parsed_expr to_dyn_expr = mkHsApp (L loc . HsVar . L loc $ getRdrName toDynName) parsed_expr hval <- compileParsedExpr to_dyn_expr return (unsafeCoerce# hval :: Dynamic) ----------------------------------------------------------------------------- -- show a module and it's source/object filenames showModule :: GhcMonad m => ModSummary -> m String showModule mod_summary = withSession $ \hsc_env -> do interpreted <- isModuleInterpreted mod_summary let dflags = hsc_dflags hsc_env return (showModMsg dflags (hscTarget dflags) interpreted mod_summary) isModuleInterpreted :: GhcMonad m => ModSummary -> m Bool isModuleInterpreted mod_summary = withSession $ \hsc_env -> case lookupHpt (hsc_HPT hsc_env) (ms_mod_name mod_summary) of Nothing -> panic "missing linkable" Just mod_info -> return (not obj_linkable) where obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info)) ---------------------------------------------------------------------------- -- RTTI primitives obtainTermFromVal :: HscEnv -> Int -> Bool -> Type -> a -> IO Term obtainTermFromVal hsc_env bound force ty x = cvObtainTerm hsc_env bound force ty (unsafeCoerce# x) obtainTermFromId :: HscEnv -> Int -> Bool -> Id -> IO Term obtainTermFromId hsc_env bound force id = do let dflags = hsc_dflags hsc_env hv <- Linker.getHValue hsc_env (varName id) >>= wormhole dflags cvObtainTerm hsc_env bound force (idType id) hv -- Uses RTTI to reconstruct the type of an Id, making it less polymorphic reconstructType :: HscEnv -> Int -> Id -> IO (Maybe Type) reconstructType hsc_env bound id = do let dflags = hsc_dflags hsc_env hv <- Linker.getHValue hsc_env (varName id) >>= wormhole dflags cvReconstructType hsc_env bound (idType id) hv mkRuntimeUnkTyVar :: Name -> Kind -> TyVar mkRuntimeUnkTyVar name kind = mkTcTyVar name kind RuntimeUnk #endif /* GHCI */
mettekou/ghc
compiler/main/InteractiveEval.hs
bsd-3-clause
38,445
13
30
10,063
8,709
4,442
4,267
3
0
module Case2 where data T = C2 Int caseIt x = case x of 42 -> error "f (C1 1 2) no longer defined for T at line: 3"
kmate/HaRe
old/testing/removeCon/Case2AST.hs
bsd-3-clause
163
0
8
76
34
18
16
6
1
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.BuildPaths -- Copyright : Isaac Jones 2003-2004, -- Duncan Coutts 2008 -- License : BSD3 -- -- Maintainer : [email protected] -- Portability : portable -- -- A bunch of dirs, paths and file names used for intermediate build steps. -- module Distribution.Simple.BuildPaths ( defaultDistPref, srcPref, hscolourPref, haddockPref, autogenModulesDir, autogenModuleName, cppHeaderName, haddockName, mkLibName, mkProfLibName, mkSharedLibName, exeExtension, objExtension, dllExtension, ) where import System.FilePath ((</>), (<.>)) import Distribution.Package ( packageName, LibraryName, getHSLibraryName ) import Distribution.ModuleName (ModuleName) import qualified Distribution.ModuleName as ModuleName import Distribution.Compiler ( CompilerId(..) ) import Distribution.PackageDescription (PackageDescription) import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(buildDir) ) import Distribution.Simple.Setup (defaultDistPref) import Distribution.Text ( display ) import Distribution.System (OS(..), buildOS) -- --------------------------------------------------------------------------- -- Build directories and files srcPref :: FilePath -> FilePath srcPref distPref = distPref </> "src" hscolourPref :: FilePath -> PackageDescription -> FilePath hscolourPref = haddockPref haddockPref :: FilePath -> PackageDescription -> FilePath haddockPref distPref pkg_descr = distPref </> "doc" </> "html" </> display (packageName pkg_descr) -- |The directory in which we put auto-generated modules autogenModulesDir :: LocalBuildInfo -> String autogenModulesDir lbi = buildDir lbi </> "autogen" cppHeaderName :: String cppHeaderName = "cabal_macros.h" -- |The name of the auto-generated module associated with a package autogenModuleName :: PackageDescription -> ModuleName autogenModuleName pkg_descr = ModuleName.fromString $ "Paths_" ++ map fixchar (display (packageName pkg_descr)) where fixchar '-' = '_' fixchar c = c haddockName :: PackageDescription -> FilePath haddockName pkg_descr = display (packageName pkg_descr) <.> "haddock" -- --------------------------------------------------------------------------- -- Library file names mkLibName :: LibraryName -> String mkLibName lib = "lib" ++ getHSLibraryName lib <.> "a" mkProfLibName :: LibraryName -> String mkProfLibName lib = "lib" ++ getHSLibraryName lib ++ "_p" <.> "a" -- Implement proper name mangling for dynamical shared objects -- libHS<packagename>-<compilerFlavour><compilerVersion> -- e.g. libHSbase-2.1-ghc6.6.1.so mkSharedLibName :: CompilerId -> LibraryName -> String mkSharedLibName (CompilerId compilerFlavor compilerVersion) lib = "lib" ++ getHSLibraryName lib ++ "-" ++ comp <.> dllExtension where comp = display compilerFlavor ++ display compilerVersion -- ------------------------------------------------------------ -- * Platform file extensions -- ------------------------------------------------------------ -- ToDo: This should be determined via autoconf (AC_EXEEXT) -- | Extension for executable files -- (typically @\"\"@ on Unix and @\"exe\"@ on Windows or OS\/2) exeExtension :: String exeExtension = case buildOS of Windows -> "exe" _ -> "" -- TODO: This should be determined via autoconf (AC_OBJEXT) -- | Extension for object files. For GHC the extension is @\"o\"@. objExtension :: String objExtension = "o" -- | Extension for dynamically linked (or shared) libraries -- (typically @\"so\"@ on Unix and @\"dll\"@ on Windows) dllExtension :: String dllExtension = case buildOS of Windows -> "dll" OSX -> "dylib" _ -> "so"
rimmington/cabal
Cabal/Distribution/Simple/BuildPaths.hs
bsd-3-clause
3,907
0
10
706
615
356
259
65
3
module D (b) where import B import C
ezyang/ghc
testsuite/tests/driver/recomp017/D.hs
bsd-3-clause
37
0
4
8
15
10
5
3
0
module IntroductionToHaskellSpec where import SpecHelper -- import Test.Hspec -- import Test.QuickCheck -- import Control.Exception (evaluate) main :: IO () main = hspec spec spec :: Spec spec = do describe "simple test" $ do it "trus is true" $ do True `shouldBe` True -- double :: Int -> Int -- double x = x * x -- -- succ :: Int -> Int -- -- succ x = x + 1 -- main :: IO () -- main = hspec $ do -- describe "Introduction to Functional Programming using Haskell" $ do -- it "define lambda expression" $ do -- succ 10 `shouldBe` (4 :: Int) -- it "double returns the doubled value" $ do -- double 2 `shouldBe` (4 :: Int) -- describe "Prelude.head" $ do -- it "returns the first element of a list" $ do -- head [23 ..] `shouldBe` (23 :: Int) -- it "returns the first element of an *arbitrary* list" $ -- property $ \x xs -> head (x:xs) == (x :: Int) -- it "throws an exception if used with an empty list" $ do -- evaluate (head []) `shouldThrow` anyException
akimichi/haskell-labo
test/IntroductionToHaskellSpec.hs
mit
1,045
0
13
275
85
54
31
9
1
module Main (main) where import DecisionTrees import RunID3Weka import System.Environment import System.Exit import Data.Maybe (listToMaybe, fromMaybe) main :: IO() main = getArgs >>= parse maybeRead = fmap fst . listToMaybe . reads maybeReadInUnit :: String -> Maybe Float maybeReadInUnit s = (maybeRead s :: Maybe Float) >>= f where f x | x <= 1 && x >= 0 = Just x | otherwise = Nothing parse ["-h"] = usage >> exitSuccess parse [fname, clazz, thr] = do let threshold = fromMaybe thrError $ maybeReadInUnit thr res <- run fname clazz (FinishedSplittingThreshold threshold) putStrLn "" drawDecisionTree res parse [fname, clazz, thr, "--iter", tp] = do let threshold = fromMaybe thrError $ maybeReadInUnit thr let tperc = fromMaybe tpError $ maybeReadInUnit tp res <- runIterative fname clazz (FinishedSplittingThreshold threshold) tperc putStrLn "" drawDecisionTree res parse _ = unknownCmd >> usage >> exitFailure unknownCmd = putStrLn "unknown command" usage = do putStrLn "Usage: ID3Weka [-h] file class fsth [--iter p]\n" putStrLn " file | *.arff nominal data file" -- TODO: numerics! putStrLn " class | name of the class attribute" putStrLn " fsth | finished splitting threshold" putStrLn " --iter p | run in iterative mode with 'p' percent forming test set" inUnitError name = error $ name ++ " must must be a Float in [0, 1]" tpError = inUnitError "--iter argument" thrError = inUnitError "finished splitting threshold"
fehu/min-dat--decision-trees
src/RunID3Weka/Main.hs
mit
1,599
0
12
398
419
203
216
35
1
{-| Module : Network.CircleCI.Common.Run Copyright : (c) Denis Shevchenko, 2016 License : MIT Maintainer : [email protected] Stability : alpha Run 'CircleCIResponse' monad. -} module Network.CircleCI.Common.Run ( runCircleCI ) where import Control.Monad.Reader -- | All API calls require account API token, so move it into 'ReaderT' monad -- instead of passing it as an explicit argument. runCircleCI :: ReaderT t IO a -> t -> IO a runCircleCI = runReaderT
denisshevchenko/circlehs
src/Network/CircleCI/Common/Run.hs
mit
491
0
7
102
50
30
20
5
1
module Ptt.Time.ClockSpec where import Test.Hspec import Test.QuickCheck import Ptt.Time.Clock spec :: Spec spec = describe "time parsing and formatting" $ it "can be repeated to produce the original value" $ property $ \(Positive seconds) -> secondsFromText (secondsToText seconds) == Just seconds
jkpl/ptt
test/Ptt/Time/ClockSpec.hs
mit
314
0
10
56
78
42
36
9
1
{-# LANGUAGE LambdaCase, OverloadedStrings #-} module Chapter7.Exception where import qualified Data.Text.Lazy.Builder as LB import Data.Monoid import Data.Display import Chapter7.Identifier data RuntimeException = WrongContextDepth Int Int Int | OutOfContextIndex Int | UnboundIdentifier Name deriving (Eq, Show) instance Display RuntimeException where toDisplay = \case WrongContextDepth vi vl cl -> let [i,l,s] = map toDisplay [vi,vl,cl] in "[BAD_INDEX] Value has wrong index " <> "(index: " <> i <> ", length: " <> l <> ")\n" <> "[INFO] Context has (length: " <> s <> ")" OutOfContextIndex i -> "[NOT_FOUND] Not found variable " <> "(index: " <> toDisplay i <> ") in this context" UnboundIdentifier n -> "[UNBOUND_ID] Identifier \"" <> toDisplay n <> "\" is unbound" eitherDisplay :: (Display a, Display b) => Either a b -> LB.Builder eitherDisplay = either toDisplay toDisplay
VoQn/tapl-hs
src/Chapter7/Exception.hs
mit
954
0
18
204
246
131
115
25
1
{-# LANGUAGE OverloadedStrings #-} module AuthTest where import TestImport authSpecs :: Spec authSpecs = ydescribe "VK authentication" $ do yit "Should accept random token and IP. Validation should failed." $ do --postBody (AuthR LoginR) "{\"ip\" : \"12.3.13.167\", \"token\": \"as2342sdq\"}" printBody statusIs 500
TimeAttack/time-attack-server
tests/AuthTest.hs
mit
379
0
11
105
45
23
22
9
1
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.HTMLInputElement (stepUp, stepDown, checkValidity, checkValidity_, reportValidity, reportValidity_, setCustomValidity, select, setRangeText, setRangeText4, setSelectionRange, setAccept, getAccept, setAlt, getAlt, setAutocomplete, getAutocomplete, setAutofocus, getAutofocus, setDefaultChecked, getDefaultChecked, setChecked, getChecked, setDirName, getDirName, setDisabled, getDisabled, getForm, setFiles, getFiles, getFilesUnsafe, getFilesUnchecked, setFormAction, getFormAction, setFormEnctype, getFormEnctype, setFormMethod, getFormMethod, setFormNoValidate, getFormNoValidate, setFormTarget, getFormTarget, setHeight, getHeight, setIndeterminate, getIndeterminate, getList, setMax, getMax, setMinLength, getMinLength, setMaxLength, getMaxLength, setMin, getMin, setMultiple, getMultiple, setName, getName, setPattern, getPattern, setPlaceholder, getPlaceholder, setReadOnly, getReadOnly, setRequired, getRequired, setSize, getSize, setSrc, getSrc, setStep, getStep, setType, getType, setDefaultValue, getDefaultValue, setValue, getValue, setValueAsDate, getValueAsDate, getValueAsDateUnsafe, getValueAsDateUnchecked, setValueAsNumber, getValueAsNumber, setWidth, getWidth, getWillValidate, getValidity, getValidationMessage, getLabels, setSelectionStart, getSelectionStart, setSelectionEnd, getSelectionEnd, setSelectionDirection, getSelectionDirection, setAlign, getAlign, setUseMap, getUseMap, setIncremental, getIncremental, setCapture, getCapture, HTMLInputElement(..), gTypeHTMLInputElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.stepUp Mozilla HTMLInputElement.stepUp documentation> stepUp :: (MonadDOM m) => HTMLInputElement -> Maybe Int -> m () stepUp self n = liftDOM (void (self ^. jsf "stepUp" [toJSVal n])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.stepDown Mozilla HTMLInputElement.stepDown documentation> stepDown :: (MonadDOM m) => HTMLInputElement -> Maybe Int -> m () stepDown self n = liftDOM (void (self ^. jsf "stepDown" [toJSVal n])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.checkValidity Mozilla HTMLInputElement.checkValidity documentation> checkValidity :: (MonadDOM m) => HTMLInputElement -> m Bool checkValidity self = liftDOM ((self ^. jsf "checkValidity" ()) >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.checkValidity Mozilla HTMLInputElement.checkValidity documentation> checkValidity_ :: (MonadDOM m) => HTMLInputElement -> m () checkValidity_ self = liftDOM (void (self ^. jsf "checkValidity" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.reportValidity Mozilla HTMLInputElement.reportValidity documentation> reportValidity :: (MonadDOM m) => HTMLInputElement -> m Bool reportValidity self = liftDOM ((self ^. jsf "reportValidity" ()) >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.reportValidity Mozilla HTMLInputElement.reportValidity documentation> reportValidity_ :: (MonadDOM m) => HTMLInputElement -> m () reportValidity_ self = liftDOM (void (self ^. jsf "reportValidity" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.setCustomValidity Mozilla HTMLInputElement.setCustomValidity documentation> setCustomValidity :: (MonadDOM m, ToJSString error) => HTMLInputElement -> error -> m () setCustomValidity self error = liftDOM (void (self ^. jsf "setCustomValidity" [toJSVal error])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.select Mozilla HTMLInputElement.select documentation> select :: (MonadDOM m) => HTMLInputElement -> m () select self = liftDOM (void (self ^. jsf "select" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.setRangeText Mozilla HTMLInputElement.setRangeText documentation> setRangeText :: (MonadDOM m, ToJSString replacement) => HTMLInputElement -> replacement -> m () setRangeText self replacement = liftDOM (void (self ^. jsf "setRangeText" [toJSVal replacement])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.setRangeText Mozilla HTMLInputElement.setRangeText documentation> setRangeText4 :: (MonadDOM m, ToJSString replacement, ToJSString selectionMode) => HTMLInputElement -> replacement -> Word -> Word -> Maybe selectionMode -> m () setRangeText4 self replacement start end selectionMode = liftDOM (void (self ^. jsf "setRangeText" [toJSVal replacement, toJSVal start, toJSVal end, toJSVal selectionMode])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.setSelectionRange Mozilla HTMLInputElement.setSelectionRange documentation> setSelectionRange :: (MonadDOM m, ToJSString direction) => HTMLInputElement -> Int -> Int -> Maybe direction -> m () setSelectionRange self start end direction = liftDOM (void (self ^. jsf "setSelectionRange" [toJSVal start, toJSVal end, toJSVal direction])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.accept Mozilla HTMLInputElement.accept documentation> setAccept :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setAccept self val = liftDOM (self ^. jss "accept" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.accept Mozilla HTMLInputElement.accept documentation> getAccept :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getAccept self = liftDOM ((self ^. js "accept") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.alt Mozilla HTMLInputElement.alt documentation> setAlt :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setAlt self val = liftDOM (self ^. jss "alt" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.alt Mozilla HTMLInputElement.alt documentation> getAlt :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getAlt self = liftDOM ((self ^. js "alt") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autocomplete Mozilla HTMLInputElement.autocomplete documentation> setAutocomplete :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setAutocomplete self val = liftDOM (self ^. jss "autocomplete" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autocomplete Mozilla HTMLInputElement.autocomplete documentation> getAutocomplete :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getAutocomplete self = liftDOM ((self ^. js "autocomplete") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autofocus Mozilla HTMLInputElement.autofocus documentation> setAutofocus :: (MonadDOM m) => HTMLInputElement -> Bool -> m () setAutofocus self val = liftDOM (self ^. jss "autofocus" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autofocus Mozilla HTMLInputElement.autofocus documentation> getAutofocus :: (MonadDOM m) => HTMLInputElement -> m Bool getAutofocus self = liftDOM ((self ^. js "autofocus") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.defaultChecked Mozilla HTMLInputElement.defaultChecked documentation> setDefaultChecked :: (MonadDOM m) => HTMLInputElement -> Bool -> m () setDefaultChecked self val = liftDOM (self ^. jss "defaultChecked" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.defaultChecked Mozilla HTMLInputElement.defaultChecked documentation> getDefaultChecked :: (MonadDOM m) => HTMLInputElement -> m Bool getDefaultChecked self = liftDOM ((self ^. js "defaultChecked") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.checked Mozilla HTMLInputElement.checked documentation> setChecked :: (MonadDOM m) => HTMLInputElement -> Bool -> m () setChecked self val = liftDOM (self ^. jss "checked" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.checked Mozilla HTMLInputElement.checked documentation> getChecked :: (MonadDOM m) => HTMLInputElement -> m Bool getChecked self = liftDOM ((self ^. js "checked") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.dirName Mozilla HTMLInputElement.dirName documentation> setDirName :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setDirName self val = liftDOM (self ^. jss "dirName" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.dirName Mozilla HTMLInputElement.dirName documentation> getDirName :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getDirName self = liftDOM ((self ^. js "dirName") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.disabled Mozilla HTMLInputElement.disabled documentation> setDisabled :: (MonadDOM m) => HTMLInputElement -> Bool -> m () setDisabled self val = liftDOM (self ^. jss "disabled" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.disabled Mozilla HTMLInputElement.disabled documentation> getDisabled :: (MonadDOM m) => HTMLInputElement -> m Bool getDisabled self = liftDOM ((self ^. js "disabled") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.form Mozilla HTMLInputElement.form documentation> getForm :: (MonadDOM m) => HTMLInputElement -> m HTMLFormElement getForm self = liftDOM ((self ^. js "form") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.files Mozilla HTMLInputElement.files documentation> setFiles :: (MonadDOM m) => HTMLInputElement -> Maybe FileList -> m () setFiles self val = liftDOM (self ^. jss "files" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.files Mozilla HTMLInputElement.files documentation> getFiles :: (MonadDOM m) => HTMLInputElement -> m (Maybe FileList) getFiles self = liftDOM ((self ^. js "files") >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.files Mozilla HTMLInputElement.files documentation> getFilesUnsafe :: (MonadDOM m, HasCallStack) => HTMLInputElement -> m FileList getFilesUnsafe self = liftDOM (((self ^. js "files") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.files Mozilla HTMLInputElement.files documentation> getFilesUnchecked :: (MonadDOM m) => HTMLInputElement -> m FileList getFilesUnchecked self = liftDOM ((self ^. js "files") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formAction Mozilla HTMLInputElement.formAction documentation> setFormAction :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setFormAction self val = liftDOM (self ^. jss "formAction" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formAction Mozilla HTMLInputElement.formAction documentation> getFormAction :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getFormAction self = liftDOM ((self ^. js "formAction") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formEnctype Mozilla HTMLInputElement.formEnctype documentation> setFormEnctype :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setFormEnctype self val = liftDOM (self ^. jss "formEnctype" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formEnctype Mozilla HTMLInputElement.formEnctype documentation> getFormEnctype :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getFormEnctype self = liftDOM ((self ^. js "formEnctype") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formMethod Mozilla HTMLInputElement.formMethod documentation> setFormMethod :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setFormMethod self val = liftDOM (self ^. jss "formMethod" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formMethod Mozilla HTMLInputElement.formMethod documentation> getFormMethod :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getFormMethod self = liftDOM ((self ^. js "formMethod") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formNoValidate Mozilla HTMLInputElement.formNoValidate documentation> setFormNoValidate :: (MonadDOM m) => HTMLInputElement -> Bool -> m () setFormNoValidate self val = liftDOM (self ^. jss "formNoValidate" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formNoValidate Mozilla HTMLInputElement.formNoValidate documentation> getFormNoValidate :: (MonadDOM m) => HTMLInputElement -> m Bool getFormNoValidate self = liftDOM ((self ^. js "formNoValidate") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formTarget Mozilla HTMLInputElement.formTarget documentation> setFormTarget :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setFormTarget self val = liftDOM (self ^. jss "formTarget" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formTarget Mozilla HTMLInputElement.formTarget documentation> getFormTarget :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getFormTarget self = liftDOM ((self ^. js "formTarget") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.height Mozilla HTMLInputElement.height documentation> setHeight :: (MonadDOM m) => HTMLInputElement -> Word -> m () setHeight self val = liftDOM (self ^. jss "height" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.height Mozilla HTMLInputElement.height documentation> getHeight :: (MonadDOM m) => HTMLInputElement -> m Word getHeight self = liftDOM (round <$> ((self ^. js "height") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.indeterminate Mozilla HTMLInputElement.indeterminate documentation> setIndeterminate :: (MonadDOM m) => HTMLInputElement -> Bool -> m () setIndeterminate self val = liftDOM (self ^. jss "indeterminate" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.indeterminate Mozilla HTMLInputElement.indeterminate documentation> getIndeterminate :: (MonadDOM m) => HTMLInputElement -> m Bool getIndeterminate self = liftDOM ((self ^. js "indeterminate") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.list Mozilla HTMLInputElement.list documentation> getList :: (MonadDOM m) => HTMLInputElement -> m HTMLElement getList self = liftDOM ((self ^. js "list") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.max Mozilla HTMLInputElement.max documentation> setMax :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setMax self val = liftDOM (self ^. jss "max" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.max Mozilla HTMLInputElement.max documentation> getMax :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getMax self = liftDOM ((self ^. js "max") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.minLength Mozilla HTMLInputElement.minLength documentation> setMinLength :: (MonadDOM m) => HTMLInputElement -> Int -> m () setMinLength self val = liftDOM (self ^. jss "minLength" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.minLength Mozilla HTMLInputElement.minLength documentation> getMinLength :: (MonadDOM m) => HTMLInputElement -> m Int getMinLength self = liftDOM (round <$> ((self ^. js "minLength") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.maxLength Mozilla HTMLInputElement.maxLength documentation> setMaxLength :: (MonadDOM m) => HTMLInputElement -> Int -> m () setMaxLength self val = liftDOM (self ^. jss "maxLength" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.maxLength Mozilla HTMLInputElement.maxLength documentation> getMaxLength :: (MonadDOM m) => HTMLInputElement -> m Int getMaxLength self = liftDOM (round <$> ((self ^. js "maxLength") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.min Mozilla HTMLInputElement.min documentation> setMin :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setMin self val = liftDOM (self ^. jss "min" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.min Mozilla HTMLInputElement.min documentation> getMin :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getMin self = liftDOM ((self ^. js "min") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.multiple Mozilla HTMLInputElement.multiple documentation> setMultiple :: (MonadDOM m) => HTMLInputElement -> Bool -> m () setMultiple self val = liftDOM (self ^. jss "multiple" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.multiple Mozilla HTMLInputElement.multiple documentation> getMultiple :: (MonadDOM m) => HTMLInputElement -> m Bool getMultiple self = liftDOM ((self ^. js "multiple") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.name Mozilla HTMLInputElement.name documentation> setName :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setName self val = liftDOM (self ^. jss "name" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.name Mozilla HTMLInputElement.name documentation> getName :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getName self = liftDOM ((self ^. js "name") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.pattern Mozilla HTMLInputElement.pattern documentation> setPattern :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setPattern self val = liftDOM (self ^. jss "pattern" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.pattern Mozilla HTMLInputElement.pattern documentation> getPattern :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getPattern self = liftDOM ((self ^. js "pattern") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.placeholder Mozilla HTMLInputElement.placeholder documentation> setPlaceholder :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setPlaceholder self val = liftDOM (self ^. jss "placeholder" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.placeholder Mozilla HTMLInputElement.placeholder documentation> getPlaceholder :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getPlaceholder self = liftDOM ((self ^. js "placeholder") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.readOnly Mozilla HTMLInputElement.readOnly documentation> setReadOnly :: (MonadDOM m) => HTMLInputElement -> Bool -> m () setReadOnly self val = liftDOM (self ^. jss "readOnly" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.readOnly Mozilla HTMLInputElement.readOnly documentation> getReadOnly :: (MonadDOM m) => HTMLInputElement -> m Bool getReadOnly self = liftDOM ((self ^. js "readOnly") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.required Mozilla HTMLInputElement.required documentation> setRequired :: (MonadDOM m) => HTMLInputElement -> Bool -> m () setRequired self val = liftDOM (self ^. jss "required" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.required Mozilla HTMLInputElement.required documentation> getRequired :: (MonadDOM m) => HTMLInputElement -> m Bool getRequired self = liftDOM ((self ^. js "required") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.size Mozilla HTMLInputElement.size documentation> setSize :: (MonadDOM m) => HTMLInputElement -> Word -> m () setSize self val = liftDOM (self ^. jss "size" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.size Mozilla HTMLInputElement.size documentation> getSize :: (MonadDOM m) => HTMLInputElement -> m Word getSize self = liftDOM (round <$> ((self ^. js "size") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.src Mozilla HTMLInputElement.src documentation> setSrc :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setSrc self val = liftDOM (self ^. jss "src" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.src Mozilla HTMLInputElement.src documentation> getSrc :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getSrc self = liftDOM ((self ^. js "src") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.step Mozilla HTMLInputElement.step documentation> setStep :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setStep self val = liftDOM (self ^. jss "step" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.step Mozilla HTMLInputElement.step documentation> getStep :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getStep self = liftDOM ((self ^. js "step") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.type Mozilla HTMLInputElement.type documentation> setType :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setType self val = liftDOM (self ^. jss "type" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.type Mozilla HTMLInputElement.type documentation> getType :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getType self = liftDOM ((self ^. js "type") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.defaultValue Mozilla HTMLInputElement.defaultValue documentation> setDefaultValue :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setDefaultValue self val = liftDOM (self ^. jss "defaultValue" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.defaultValue Mozilla HTMLInputElement.defaultValue documentation> getDefaultValue :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getDefaultValue self = liftDOM ((self ^. js "defaultValue") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.value Mozilla HTMLInputElement.value documentation> setValue :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setValue self val = liftDOM (self ^. jss "value" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.value Mozilla HTMLInputElement.value documentation> getValue :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getValue self = liftDOM ((self ^. js "value") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.valueAsDate Mozilla HTMLInputElement.valueAsDate documentation> setValueAsDate :: (MonadDOM m, IsDate val) => HTMLInputElement -> Maybe val -> m () setValueAsDate self val = liftDOM (self ^. jss "valueAsDate" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.valueAsDate Mozilla HTMLInputElement.valueAsDate documentation> getValueAsDate :: (MonadDOM m) => HTMLInputElement -> m (Maybe Date) getValueAsDate self = liftDOM ((self ^. js "valueAsDate") >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.valueAsDate Mozilla HTMLInputElement.valueAsDate documentation> getValueAsDateUnsafe :: (MonadDOM m, HasCallStack) => HTMLInputElement -> m Date getValueAsDateUnsafe self = liftDOM (((self ^. js "valueAsDate") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.valueAsDate Mozilla HTMLInputElement.valueAsDate documentation> getValueAsDateUnchecked :: (MonadDOM m) => HTMLInputElement -> m Date getValueAsDateUnchecked self = liftDOM ((self ^. js "valueAsDate") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.valueAsNumber Mozilla HTMLInputElement.valueAsNumber documentation> setValueAsNumber :: (MonadDOM m) => HTMLInputElement -> Double -> m () setValueAsNumber self val = liftDOM (self ^. jss "valueAsNumber" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.valueAsNumber Mozilla HTMLInputElement.valueAsNumber documentation> getValueAsNumber :: (MonadDOM m) => HTMLInputElement -> m Double getValueAsNumber self = liftDOM ((self ^. js "valueAsNumber") >>= valToNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.width Mozilla HTMLInputElement.width documentation> setWidth :: (MonadDOM m) => HTMLInputElement -> Word -> m () setWidth self val = liftDOM (self ^. jss "width" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.width Mozilla HTMLInputElement.width documentation> getWidth :: (MonadDOM m) => HTMLInputElement -> m Word getWidth self = liftDOM (round <$> ((self ^. js "width") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.willValidate Mozilla HTMLInputElement.willValidate documentation> getWillValidate :: (MonadDOM m) => HTMLInputElement -> m Bool getWillValidate self = liftDOM ((self ^. js "willValidate") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.validity Mozilla HTMLInputElement.validity documentation> getValidity :: (MonadDOM m) => HTMLInputElement -> m ValidityState getValidity self = liftDOM ((self ^. js "validity") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.validationMessage Mozilla HTMLInputElement.validationMessage documentation> getValidationMessage :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getValidationMessage self = liftDOM ((self ^. js "validationMessage") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.labels Mozilla HTMLInputElement.labels documentation> getLabels :: (MonadDOM m) => HTMLInputElement -> m NodeList getLabels self = liftDOM ((self ^. js "labels") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionStart Mozilla HTMLInputElement.selectionStart documentation> setSelectionStart :: (MonadDOM m) => HTMLInputElement -> Int -> m () setSelectionStart self val = liftDOM (self ^. jss "selectionStart" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionStart Mozilla HTMLInputElement.selectionStart documentation> getSelectionStart :: (MonadDOM m) => HTMLInputElement -> m Int getSelectionStart self = liftDOM (round <$> ((self ^. js "selectionStart") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionEnd Mozilla HTMLInputElement.selectionEnd documentation> setSelectionEnd :: (MonadDOM m) => HTMLInputElement -> Int -> m () setSelectionEnd self val = liftDOM (self ^. jss "selectionEnd" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionEnd Mozilla HTMLInputElement.selectionEnd documentation> getSelectionEnd :: (MonadDOM m) => HTMLInputElement -> m Int getSelectionEnd self = liftDOM (round <$> ((self ^. js "selectionEnd") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionDirection Mozilla HTMLInputElement.selectionDirection documentation> setSelectionDirection :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setSelectionDirection self val = liftDOM (self ^. jss "selectionDirection" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionDirection Mozilla HTMLInputElement.selectionDirection documentation> getSelectionDirection :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getSelectionDirection self = liftDOM ((self ^. js "selectionDirection") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.align Mozilla HTMLInputElement.align documentation> setAlign :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setAlign self val = liftDOM (self ^. jss "align" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.align Mozilla HTMLInputElement.align documentation> getAlign :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getAlign self = liftDOM ((self ^. js "align") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.useMap Mozilla HTMLInputElement.useMap documentation> setUseMap :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setUseMap self val = liftDOM (self ^. jss "useMap" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.useMap Mozilla HTMLInputElement.useMap documentation> getUseMap :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getUseMap self = liftDOM ((self ^. js "useMap") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.incremental Mozilla HTMLInputElement.incremental documentation> setIncremental :: (MonadDOM m) => HTMLInputElement -> Bool -> m () setIncremental self val = liftDOM (self ^. jss "incremental" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.incremental Mozilla HTMLInputElement.incremental documentation> getIncremental :: (MonadDOM m) => HTMLInputElement -> m Bool getIncremental self = liftDOM ((self ^. js "incremental") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.capture Mozilla HTMLInputElement.capture documentation> setCapture :: (MonadDOM m, ToJSString val) => HTMLInputElement -> val -> m () setCapture self val = liftDOM (self ^. jss "capture" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.capture Mozilla HTMLInputElement.capture documentation> getCapture :: (MonadDOM m, FromJSString result) => HTMLInputElement -> m result getCapture self = liftDOM ((self ^. js "capture") >>= fromJSValUnchecked)
ghcjs/jsaddle-dom
src/JSDOM/Generated/HTMLInputElement.hs
mit
33,342
0
12
4,649
6,841
3,603
3,238
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} module Pos.Util.UnitsOfMeasure ( UnitOfMeasure (..) , MeasuredIn(..) ) where import Control.Lens (at, (?~)) import Data.Aeson (FromJSON (..), ToJSON (..), Value (..), object, withObject, (.:), (.=)) import qualified Data.Text.Lazy as T import qualified Data.Text.Lazy.Builder as B import Formatting ((%)) import qualified Formatting as F import Formatting.Buildable (Buildable (..)) import Pos.Core.Util.LogSafe (BuildableSafeGen (..)) import Universum import Data.Swagger (NamedSchema (..), Referenced (..), SwaggerType (..), ToSchema (..), enum_, properties, required, type_) -- | A finite sum type representing time units we might want to show to -- clients. The idea is that whenever we have a quantity represeting some -- form of time, we should render it together with the relevant unit, to -- not leave anything to guessing. data UnitOfMeasure = Seconds | Milliseconds | Microseconds -- | % ranging from 0 to 100. | Percentage100 -- | Number of blocks. | Blocks -- | Number of blocks per second. | BlocksPerSecond | Bytes | Lovelace | LovelacePerByte deriving (Show, Eq, Ord) instance Buildable UnitOfMeasure where build = \case Bytes -> "bytes" LovelacePerByte -> "lovelace/byte" Lovelace -> "lovelace" Seconds -> "seconds" Milliseconds -> "milliseconds" Microseconds -> "microseconds" Percentage100 -> "percent" Blocks -> "blocks" BlocksPerSecond -> "blocks/second" instance ToJSON UnitOfMeasure where toJSON = String . T.toStrict . B.toLazyText . build -- | Represent data with a given unit of measure data MeasuredIn (u :: UnitOfMeasure) a = MeasuredIn a deriving (Show, Eq, Ord) instance (Demote u, Buildable a) => BuildableSafeGen (MeasuredIn u a) where buildSafeGen _ = build instance (Demote u, Buildable a) => Buildable (MeasuredIn u a) where build (MeasuredIn a) = F.bprint (F.build % " " % F.build) a (demote $ Proxy @u) instance (Demote u, ToJSON a) => ToJSON (MeasuredIn u a) where toJSON (MeasuredIn a) = object [ "unit" .= demote (Proxy @u) , "quantity" .= toJSON a ] instance (Demote u, FromJSON a) => FromJSON (MeasuredIn u a) where parseJSON = withObject "MeasuredIn" $ \o -> do verifyUnit =<< o .: "unit" MeasuredIn <$> o .: "quantity" where unitS = toString $ T.toStrict $ B.toLazyText $ build $ demote $ Proxy @u verifyUnit = \case u@(String _) | u == toJSON (demote $ Proxy @u) -> pure () _ -> fail $ "failed to parse quantified value. Expected value in '" <> unitS <> "' but got something else. e.g.: " <> "{ \"unit\": \"" <> unitS <> "\", \"quantity\": ...}" instance (Demote u, ToSchema a) => ToSchema (MeasuredIn u a) where declareNamedSchema _ = do NamedSchema _ schema <- declareNamedSchema (Proxy @a) pure $ NamedSchema (Just "MeasuredIn") $ mempty & type_ .~ SwaggerObject & required .~ ["quantity", "unit"] & properties .~ (mempty & at "quantity" ?~ Inline schema & at "unit" ?~ (Inline $ mempty & type_ .~ SwaggerString & enum_ ?~ [toJSON $ demote $ Proxy @u] ) ) -- -- Internal -- -- | Bring a type back to the world of value (invert of promote) class Demote (u :: UnitOfMeasure) where demote :: Proxy u -> UnitOfMeasure instance Demote 'Bytes where demote _ = Bytes instance Demote 'LovelacePerByte where demote _ = LovelacePerByte instance Demote 'Lovelace where demote _ = Lovelace instance Demote 'Seconds where demote _ = Seconds instance Demote 'Milliseconds where demote _ = Milliseconds instance Demote 'Microseconds where demote _ = Microseconds instance Demote 'Percentage100 where demote _ = Percentage100 instance Demote 'Blocks where demote _ = Blocks instance Demote 'BlocksPerSecond where demote _ = BlocksPerSecond
input-output-hk/pos-haskell-prototype
lib/src/Pos/Util/UnitsOfMeasure.hs
mit
4,399
0
19
1,341
1,139
624
515
-1
-1
module Urbit.Vere.Serf.Types where import Urbit.Prelude import Urbit.Arvo (Desk, Ev, FX) import Urbit.Noun.Time (Wen) -- Types ----------------------------------------------------------------------- type EventId = Word64 type PlayBail = (EventId, Mug, Goof) type Slog = (Atom, Tank) data SerfState = SerfState { ssLast :: !EventId , ssHash :: !Mug } deriving (Show, Eq) data RipeInfo = RipeInfo { riProt :: !Atom , riHoon :: !Atom , riNock :: !Atom } deriving (Show) data SerfInfo = SerfInfo { siRipe :: !RipeInfo , siStat :: !SerfState } deriving (Show) data Fact = Fact { factEve :: EventId , factMug :: Mug , factWen :: Wen , factNon :: Noun } data Flag = DebugRam | DebugCpu | CheckCorrupt | CheckFatal | Verbose | DryRun | Quiet | Hashless | Trace deriving (Eq, Ord, Show, Enum, Bounded) data Config = Config { scSerf :: FilePath -- Where is the urbit-worker executable? , scPier :: FilePath -- Where is the pier directory? , scFlag :: [Flag] -- Serf execution flags. , scSlog :: Slog -> IO () -- What to do with slogs? , scStdr :: Text -> IO () -- What to do with lines from stderr? , scDead :: IO () -- What to do when the serf process goes down? } -- Serf Commands --------------------------------------------------------------- type Gang = Maybe (HoonSet Ship) type Goof = (Term, [Tank]) data EvErr = EvErr Ev (WorkError -> IO ()) {-| Two types of serf failures. - `RunSwap`: Event processing failed, but the serf replaced it with another event which succeeded. - `RunBail`: Event processing failed and all attempt to replace it with a failure-notice event also caused crashes. We are really fucked. -} data WorkError -- TODO Rename type and constructors = RunSwap EventId Mug Wen Noun FX -- TODO Maybe provide less info here? | RunBail [Goof] | RunOkay EventId FX {- - RRWork: Ask the serf to do work, will output (Fact, FX) if work succeeded and call callback on failure. - RRSave: Wait for the serf to finish all pending work -} data RunReq = RRWork EvErr | RRSave () | RRKill () | RRPack () | RRScry Gang ScryReq (Maybe (Term, Noun) -> IO ()) type ScryReq = (Each Path Demi) data Demi = DemiOnce Term Desk Path | DemiBeam Term Beam deriving (Show) -- TODO type Beam = Void deriveNoun ''Demi -- Exceptions ------------------------------------------------------------------ data SerfExn = UnexpectedPlea Noun Text | BadPleaAtom Atom | BadPleaNoun Noun [Text] Text | PeekBail Goof | SerfConnectionClosed | SerfHasShutdown | BailDuringReplay EventId [Goof] | SwapDuringReplay EventId Mug (Wen, Noun) FX | SerfNotRunning | MissingBootEventsInEventLog Word Word | SnapshotAheadOfLog EventId EventId | BailDuringWyrd [Goof] | SwapDuringWyrd Mug (Wen, Noun) FX deriving (Show, Exception) -- Instances ------------------------------------------------------------------- deriveNoun ''RipeInfo deriveNoun ''SerfInfo deriveNoun ''SerfState
urbit/urbit
pkg/hs/urbit-king/lib/Urbit/Vere/Serf/Types.hs
mit
3,052
0
11
662
688
403
285
-1
-1
module GitHub.PullRequests.ReviewComments where import GitHub.Internal --| GET /repos/:owner/:repo/pulls/:number/comments listPullRequestComments :: OwnerName -> RepoName -> Int -> GitHub ReviewComments listRepoPullRequestComments :: OwnerName -> RepoName -> ReviewCommentSortBy -> SortOrder -> UTCTime -> GitHub ReviewComments getPullRequestComment :: OwnerName -> RepoName -> Int -> GitHub ReviewComment createPullRequestComment :: OwnerName -> RepoName -> Int -> ReviewComment -> GitHub ReviewComment editPullRequestComment :: OwnerName -> RepoName -> Int -> ReviewCommentPatch -> GitHub ReviewComment deletePullRequestComment :: OwnerName -> RepoName -> Int -> GitHub ()
SaneApp/github-api
src/GitHub/PullRequests/ReviewComments.hs
mit
709
56
12
110
239
121
118
-1
-1
{-# LANGUAGE NumericUnderscores #-} {-# LANGUAGE QuasiQuotes #-} module B9.B9ConfigSpec ( spec, ) where import Data.Maybe (fromMaybe) import Control.Lens ((^.)) import B9.B9Config import B9.B9Monad import Control.Exception import Control.Monad import System.Directory import System.Environment import System.FilePath import System.IO.B9Extras import Test.Hspec(Spec, it, shouldBe, HasCallStack, describe) import Test.QuickCheck (property, (===), (==>)) import Text.Printf import qualified Data.Text as Text import Data.ConfigFile.B9Extras ( CPError ) import NeatInterpolation as Neat import Data.Either (isRight) spec :: HasCallStack => Spec spec = do it "forall valid configs: parse . render == id" $ property $ \cfg -> let actual = renderThenParseB9Config cfg in isRight actual ==> (Right cfg === actual) describe "parse textual configuration" $ do let exampleConfig = Text.unpack [Neat.text| [global] build_dir_root: Nothing keep_temp_dirs: False log_file: Nothing max_cached_shared_images: Just 2 repository: Nothing repository_cache: Just (InB9UserDir "repo-cache") unique_build_dirs: True verbosity: Just LogNothing timeout_factor: 3 default_timeout_seconds: 10 ext4_attributes: ["attr1", "attr2"] |] it "correctly parses verbosity" $ do cfg <- withConfig exampleConfig getB9Config _verbosity cfg `shouldBe` Just LogNothing it "correctly parses timeout_factor" $ do cfg <- withConfig exampleConfig getB9Config _timeoutFactor cfg `shouldBe` Just 3 it "correctly parses default_timeout" $ do cfg <- withConfig exampleConfig getB9Config _defaultTimeout cfg `shouldBe` Just (TimeoutMicros 10_000_000) it "correctly parses ext4_attributes" $ do cfg <- withConfig exampleConfig getB9Config _ext4Attributes cfg `shouldBe` ["attr1", "attr2"] it "correctly parses missing ext4_attributes" $ do let exampleConfigNoExt4 = Text.unpack [Neat.text| [global] build_dir_root: Nothing keep_temp_dirs: False log_file: Nothing max_cached_shared_images: Just 2 repository: Nothing repository_cache: Just (InB9UserDir "repo-cache") unique_build_dirs: True verbosity: Just LogNothing timeout_factor: 3 default_timeout_seconds: 10 |] cfg <- withConfig exampleConfigNoExt4 getB9Config _ext4Attributes cfg `shouldBe` ["^64bit"] renderThenParseB9Config :: B9Config -> Either CPError B9Config renderThenParseB9Config = b9ConfigToCPDocument >=> parseB9Config withConfig :: String -> B9 a -> IO a withConfig cfgFileContents testAction = withTempBuildDirs $ \cfg -> do let cfgFileName = fromMaybe (error "Internal Error") (cfg ^. customDefaulB9ConfigPath) cfgFilePath <- resolve cfgFileName writeFile cfgFilePath cfgFileContents runB9ConfigActionWithOverrides (runB9 testAction) cfg withTempBuildDirs :: HasCallStack => (B9ConfigOverride -> IO a) -> IO a withTempBuildDirs k = bracket acquire release use where acquire = do nixOutDirEnv <- lookupEnv "NIX_BUILD_TOP" let rootDir = maybe InTempDir (((.) . (.)) Path (</>)) nixOutDirEnv repoRelPath <- printf "testsRepositoryIOSpec-test-repo-%U" <$> randomUUID buildRelPath <- printf "RepositoryIOSpec-root-%U" <$> randomUUID cfgRelPath <- printf "RepositoryIOSpec-b9cfg-%U" <$> randomUUID let tmpRepoPath = rootDir ("tests" </> repoRelPath) tmpBuildPath = rootDir ("tests" </> buildRelPath) tmpCfgPath = rootDir ("tests" </> cfgRelPath) ensureSystemPath tmpRepoPath ensureSystemPath tmpBuildPath tmpBuildPathFileName <- resolve tmpBuildPath return (tmpRepoPath, tmpBuildPathFileName, tmpCfgPath) release (tmpRepoPath, tmpBuildPathFileName, tmpCfgPath) = do let cleanupTmpPath = removePathForcibly <=< resolve cleanupTmpPath tmpRepoPath cleanupTmpPath tmpCfgPath removePathForcibly tmpBuildPathFileName use (tmpRepoPath, tmpBuildPathFileName, tmpCfgPath) = let mkCfg cfgIn = cfgIn { _repositoryCache = Just tmpRepoPath, _projectRoot = Just tmpBuildPathFileName } oCfg = overrideB9Config mkCfg ( overrideWorkingDirectory tmpBuildPathFileName ( overrideDefaultB9ConfigPath tmpCfgPath noB9ConfigOverride ) ) in k oCfg
sheyll/b9-vm-image-builder
src/tests/B9/B9ConfigSpec.hs
mit
4,757
0
17
1,263
939
475
464
-1
-1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.HTMLTableCaptionElement (js_setAlign, setAlign, js_getAlign, getAlign, HTMLTableCaptionElement, castToHTMLTableCaptionElement, gTypeHTMLTableCaptionElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"align\"] = $2;" js_setAlign :: HTMLTableCaptionElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCaptionElement.align Mozilla HTMLTableCaptionElement.align documentation> setAlign :: (MonadIO m, ToJSString val) => HTMLTableCaptionElement -> val -> m () setAlign self val = liftIO (js_setAlign (self) (toJSString val)) foreign import javascript unsafe "$1[\"align\"]" js_getAlign :: HTMLTableCaptionElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCaptionElement.align Mozilla HTMLTableCaptionElement.align documentation> getAlign :: (MonadIO m, FromJSString result) => HTMLTableCaptionElement -> m result getAlign self = liftIO (fromJSString <$> (js_getAlign (self)))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/HTMLTableCaptionElement.hs
mit
1,899
14
10
256
463
284
179
31
1
{-| This module provides @pipes@ utilities for \"byte streams\", which are streams of strict 'BS.ByteString's chunks. Use byte streams to interact with both 'Handle's and lazy 'ByteString's. To stream from 'Handle's, use 'fromHandleS' or 'toHandleD' to convert them into the equivalent proxies. For example, the following program copies data from one file to another: > import Control.Proxy > import Control.Proxy.ByteString > > main = > withFile "inFile.txt" ReadMode $ \hIn -> > withFile "outFile.txt" WriteMode $ \hOut -> > runProxy $ fromHandleS hIn >-> toHandleD hOut You can also stream to and from 'stdin' and 'stdout' using the predefined 'stdinS' and 'stdoutD' proxies, like in the following \"echo\" program: > main = runProxy $ stdinS >-> stdoutD You can also translate pure lazy 'BL.ByteString's to and from proxies: > import qualified Data.ByteString.Lazy.Char8 as BL > > main = runProxy $ fromLazyS (BL.pack "Hello, world!\n") >-> stdoutD In addition, this module provides many functions equivalent to lazy 'ByteString' functions so that you can transform byte streams. -} module Control.Proxy.ByteString ( ---- * Introducing and Eliminating ByteStrings --fromLazyS, --toLazyD, ---- * Basic Interface --headD, --headD_, --lastD, --tailD, --initD, --nullD, --nullD_, --lengthD, ---- * Transforming ByteStrings --mapD, --intersperseD, --intercalateD, ---- * Reducing ByteStrings (folds) --foldlD', --foldrD, ---- ** Special folds --concatMapD, --anyD, --anyD_, --allD, --allD_, ---- * Substrings ---- ** Breaking strings --takeD, --dropD, --takeWhileD, --dropWhileD, --groupD, --groupByD, ---- ** Breaking into many substrings --splitD, --splitWithD, ---- * Searching ByteStrings ---- ** Searching by equality --elemD, --elemD_, --notElemD, ---- ** Searching with a predicate --findD, --findD_, --filterD, ---- * Indexing ByteStrings --indexD, --indexD_, --elemIndexD, --elemIndexD_, --elemIndicesD, --findIndexD, --findIndexD_, --findIndicesD, --countD, -- * I/O with ByteStrings -- ** Standard input and output stdinS, stdoutD, -- ** I/O with Handles fromHandleS, toHandleD, hGetSomeS, hGetSomeS_ ) where import Control.Monad import Control.Monad.Trans.Class (lift) import qualified Control.Proxy as P import Control.Proxy.Trans.State (StateP(StateP)) import Control.Proxy.Trans.Writer (WriterP, tell) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Internal as BLI import qualified Data.ByteString.Unsafe as BU import qualified Data.Monoid as M import Data.Int (Int64) import Data.Word (Word8) import System.IO (Handle, hIsEOF, stdin, stdout) --[>| Convert a lazy 'BL.ByteString' into a 'P.Producer' of strict -- 'BS.ByteString's -} --fromLazyS -- :: (Monad m, P.Proxy p) -- => BL.ByteString -> () -> P.Producer p BS.ByteString m () --fromLazyS bs () = -- P.runIdentityP $ BLI.foldrChunks (\e a -> P.respond e >> a) (return ()) bs --[>| Fold strict 'BS.ByteString's flowing \'@D@\'ownstream into a lazy -- 'BL.ByteString'. -- The fold generates a difference 'BL.ByteString' that you must apply to -- 'BS.empty'. -} --toLazyD -- :: (Monad m, P.Proxy p) -- => x -> WriterP (M.Endo BL.ByteString) p x BS.ByteString x BS.ByteString m r --toLazyD = P.foldrD BLI.Chunk ---- | Store the 'M.First' 'Word8' that flows \'@D@\'ownstream --headD -- :: (Monad m, P.Proxy p) -- => x -> WriterP (M.First Word8) p x BS.ByteString x BS.ByteString m r --headD = P.foldD (\bs -> M.First $ -- if (BS.null bs) -- then Nothing -- else Just $ BU.unsafeHead bs ) --[>| Store the 'M.First' 'Word8' that flows \'@D@\'ownstream -- Terminates after receiving a single 'Word8'. -} --headD_ -- :: (Monad m, P.Proxy p) -- => x -> WriterP (M.First Word8) p x BS.ByteString x BS.ByteString m () --headD_ = go where -- go x = do -- bs <- P.request x -- if (BS.null bs) -- then do -- x2 <- P.respond bs -- go x2 -- else tell . M.First . Just $ BU.unsafeHead bs ---- | Store the 'M.Last' 'Word8' that flows \'@D@\'ownstream --lastD -- :: (Monad m, P.Proxy p) -- => x -> WriterP (M.Last Word8) p x BS.ByteString x BS.ByteString m r --lastD = P.foldD (\bs -> M.Last $ -- if (BS.null bs) -- then Nothing -- else Just $ BS.last bs ) ---- | Drop the first byte in the stream --tailD :: (Monad m, P.Proxy p) => x -> p x BS.ByteString x BS.ByteString m r --tailD = P.runIdentityK go where -- go x = do -- bs <- P.request x -- if (BS.null bs) -- then do -- x2 <- P.respond bs -- go x2 -- else do -- x2 <- P.respond (BU.unsafeTail bs) -- P.pull x2 ---- | Pass along all but the last byte in the stream --initD :: (Monad m, P.Proxy p) => x -> p x BS.ByteString x BS.ByteString m r --initD = P.runIdentityK go0 where -- go0 x = do -- bs <- P.request x -- if (BS.null bs) -- then do -- x2 <- P.respond bs -- go0 x2 -- else do -- x2 <- P.respond (BS.init bs) -- go1 (BS.last bs) x2 -- go1 w8 x = do -- bs <- P.request x -- if (BS.null bs) -- then do -- x2 <- P.respond bs -- go1 w8 x2 -- else do -- x2 <- P.respond (BS.cons w8 (BS.init bs)) -- go1 (BS.last bs) x2 ---- | Store whether 'M.All' received 'ByteString's are empty --nullD -- :: (Monad m, P.Proxy p) -- => x -> WriterP M.All p x BS.ByteString x BS.ByteString m r --nullD = P.foldD (M.All . BS.null) --[>| Store whether 'M.All' received 'ByteString's are empty -- 'nullD_' terminates on the first non-empty 'ByteString'. -} --nullD_ -- :: (Monad m, P.Proxy p) -- => x -> WriterP M.All p x BS.ByteString x BS.ByteString m () --nullD_ = go where -- go x = do -- bs <- P.request x -- if (BS.null bs) -- then do -- x2 <- P.respond bs -- go x2 -- else tell (M.All False) ---- | Store the length of all input flowing \'@D@\'ownstream --lengthD -- :: (Monad m, P.Proxy p) -- => x -> WriterP (M.Sum Int) p x BS.ByteString x BS.ByteString m r --lengthD = P.foldD (M.Sum . BS.length) ---- | Apply a transformation to each 'Word8' in the stream --mapD -- :: (Monad m, P.Proxy p) -- => (Word8 -> Word8) -> x -> p x BS.ByteString x BS.ByteString m r --mapD f = P.mapD (BS.map f) ---- | Intersperse a 'Word8' between each byte in the stream --intersperseD -- :: (Monad m, P.Proxy p) => Word8 -> x -> p x BS.ByteString x BS.ByteString m r --intersperseD w8 = P.runIdentityK go0 where -- go0 x = do -- bs0 <- P.request x -- x2 <- P.respond (BS.intersperse w8 bs0) -- go1 x2 -- go1 x = do -- bs <- P.request x -- x2 <- P.respond (BS.cons w8 (BS.intersperse w8 bs)) -- go1 x2 ---- | Intercalate a 'BS.ByteString' between each chunk in the stream --intercalateD -- :: (Monad m, P.Proxy p) -- => BS.ByteString -> x -> p x BS.ByteString x BS.ByteString m r --intercalateD bsi = P.runIdentityK go0 where -- go0 x = do -- bs <- P.request x -- x2 <- P.respond bs -- go1 x2 -- go1 x = do -- bs <- P.request x -- x2 <- P.respond (BS.append bsi bs) -- go1 x2 ---- | Reduce the stream of bytes using a strict left fold --foldlD' -- :: (Monad m, P.Proxy p) -- => (s -> Word8 -> s) -> x -> StateP s p x BS.ByteString x BS.ByteString m r --foldlD' f = go where -- go x = do -- bs <- P.request x -- StateP (\s -> let s' = BS.foldl' f s bs -- in s' `seq` P.return_P ((), s')) -- go =<< P.respond bs ---- | Reduce the stream of bytes using a right fold --foldrD -- :: (Monad m, P.Proxy p) -- => (Word8 -> w -> w) -- -> x -> WriterP (M.Endo w) p x BS.ByteString x BS.ByteString m r --foldrD f = P.foldrD (\e w -> BS.foldr f w e) ---- | Map a function over the byte stream and concatenate the results --concatMapD -- :: (Monad m, P.Proxy p) -- => (Word8 -> BS.ByteString) -> x -> p x BS.ByteString x BS.ByteString m r --concatMapD f = P.mapD (BS.concatMap f) ---- | Fold that returns whether 'M.Any' received 'Word8's satisfy the predicate --anyD -- :: (Monad m, P.Proxy p) -- => (Word8 -> Bool) -- -> x -> WriterP M.Any p x BS.ByteString x BS.ByteString m r --anyD pred = P.foldD (M.Any . BS.any pred) --[>| Fold that returns whether 'M.Any' received 'Word8's satisfy the predicate -- 'anyD_' terminates on the first 'Word8' that satisfies the predicate. -} --anyD_ -- :: (Monad m, P.Proxy p) -- => (Word8 -> Bool) -- -> x -> WriterP M.Any p x BS.ByteString x BS.ByteString m () --anyD_ pred = go where -- go x = do -- bs <- P.request x -- if (BS.any pred bs) -- then tell (M.Any True) -- else do -- x2 <- P.respond bs -- go x2 ---- | Fold that returns whether 'M.All' received 'Word8's satisfy the predicate --allD -- :: (Monad m, P.Proxy p) -- => (Word8 -> Bool) -- -> x -> WriterP M.All p x BS.ByteString x BS.ByteString m r --allD pred = P.foldD (M.All . BS.all pred) --[>| Fold that returns whether 'M.All' received 'Word8's satisfy the predicate -- 'allD_' terminates on the first 'Word8' that fails the predicate. -} --allD_ -- :: (Monad m, P.Proxy p) -- => (Word8 -> Bool) -- -> x -> WriterP M.All p x BS.ByteString x BS.ByteString m () --allD_ pred = go where -- go x = do -- bs <- P.request x -- if (BS.all pred bs) -- then do -- x2 <- P.respond bs -- go x2 -- else tell (M.All False) --[> --newtype Maximum a = Maximum { getMaximum :: Maybe a } --instance (Ord a) => Monoid (Maximum a) where -- mempty = Maximum Nothing -- mappend m1 (Maximum Nothing) = m1 -- mappend (Maximum Nothing) m2 = m2 -- mappend (Maximum (Just a1)) (Maximum (Just a2)) = Maximum (Just (max a1 a2)) --maximumD -- :: (Monad m, P.Proxy p) -- => x -> p x BS.ByteString x BS.ByteString (WriterT (Maximum Word8) m) r --maximumD = P.foldD (\bs -> Maximum $ -- if (BS.null bs) -- then Nothing -- else Just $ BS.maximum bs ) --newtype Minimum a = Minimum { getMinimum :: Maybe a } --instance (Ord a) => Monoid (Minimum a) where -- mempty = Minimum Nothing -- mappend m1 (Minimum Nothing) = m1 -- mappend (Minimum Nothing) m2 = m2 -- mappend (Minimum (Just a1)) (Minimum (Just a2)) = Minimum (Just (min a1 a2)) --minimumD -- :: (Monad m, P.Proxy p) -- => x -> p x BS.ByteString x BS.ByteString (WriterT (Minimum Word8) m) r --minimumD = P.foldD (\bs -> Minimum $ -- if (BS.null bs) -- then Nothing -- else Just $ BS.minimum bs ) ---} ---- | @(takeD n)@ only allows @n@ bytes to flow \'@D@\'ownstream --takeD -- :: (Monad m, P.Proxy p) => Int64 -> x -> p x BS.ByteString x BS.ByteString m () --takeD n0 = P.runIdentityK (go n0) where -- go n -- | n <= 0 = \_ -> return () -- | otherwise = \x -> do -- bs <- P.request x -- let len = fromIntegral $ BS.length bs -- if (len > n) -- then do -- P.respond (BU.unsafeTake (fromIntegral n) bs) -- return () -- else do -- x2 <- P.respond bs -- go (n - len) x2 ---- | @(dropD n)@ drops the first @n@ bytes flowing \'@D@\'ownstream --dropD -- :: (Monad m, P.Proxy p) -- => Int64 -> () -> P.Pipe p BS.ByteString BS.ByteString m r --dropD n0 () = P.runIdentityP (go n0) where -- go n -- | n <= 0 = P.pull () -- | otherwise = do -- bs <- P.request () -- let len = fromIntegral $ BS.length bs -- if (len >= n) -- then do -- P.respond (BU.unsafeDrop (fromIntegral n) bs) -- P.pull () -- else go (n - len) ---- | Take bytes until they fail the predicate --takeWhileD -- :: (Monad m, P.Proxy p) -- => (Word8 -> Bool) -> x -> p x BS.ByteString x BS.ByteString m () --takeWhileD pred = P.runIdentityK go where -- go x = do -- bs <- P.request x -- case BS.findIndex (not . pred) bs of -- Nothing -> do -- x2 <- P.respond bs -- go x2 -- Just i -> do -- P.respond (BU.unsafeTake i bs) -- return () ---- | Drop bytes until they pass the predicate --dropWhileD -- :: (Monad m, P.Proxy p) -- => (Word8 -> Bool) -> () -> P.Pipe p BS.ByteString BS.ByteString m r --dropWhileD pred () = P.runIdentityP go where -- go = do -- bs <- P.request () -- case BS.findIndex (not . pred) bs of -- Nothing -> go -- Just i -> do -- P.respond (BU.unsafeDrop i bs) -- P.pull () ---- | Group 'Nothing'-delimited streams of bytes into segments of equal bytes --groupD -- :: (Monad m, P.Proxy p) -- => () -> P.Pipe p (Maybe BS.ByteString) BS.ByteString m r --groupD = groupByD (==) --[>| Group 'Nothing'-delimited streams of bytes using the supplied equality -- function -} --groupByD -- :: (Monad m, P.Proxy p) -- => (Word8 -> Word8 -> Bool) -- -> () -> P.Pipe p (Maybe BS.ByteString) BS.ByteString m r --groupByD eq () = P.runIdentityP go1 where -- go1 = do -- mbs <- P.request () -- case mbs of -- Nothing -> go1 -- Just bs -- | BS.null bs -> go1 -- | otherwise -> do -- let groups = BS.groupBy eq bs -- mapM_ P.respond (init groups) -- go2 (last groups) -- go2 group0 = do -- mbs <- P.request () -- case mbs of -- Nothing -> do -- P.respond group0 -- go1 -- Just bs -- | BS.null bs -> go2 group0 -- | otherwise -> do -- let groups = BS.groupBy eq bs -- case groups of -- [] -> go2 group0 -- [group1] -> go2 (BS.append group0 group1) -- gs@(group1:gs') -> do -- if (BS.head group0 == BS.head group1) -- then do -- P.respond (BS.append group0 group1) -- mapM_ P.respond (init gs') -- go2 (last gs') -- else do -- P.respond group0 -- mapM_ P.respond (init gs ) -- go2 (last gs ) ---- | Split 'Nothing'-delimited streams of bytes using the given 'Word8' boundary --splitD -- :: (Monad m, P.Proxy p) -- => Word8 -> () -> P.Pipe p (Maybe BS.ByteString) BS.ByteString m r --splitD w8 = splitWithD (w8 ==) --[>| Split 'Nothing'-delimited streams of bytes using the given predicate to -- define boundaries -} --splitWithD -- :: (Monad m, P.Proxy p) -- => (Word8 -> Bool) -> () -> P.Pipe p (Maybe BS.ByteString) BS.ByteString m r --splitWithD pred () = P.runIdentityP go1 where -- go1 = do -- mbs <- P.request () -- case mbs of -- Nothing -> go1 -- Just bs -> case BS.splitWith pred bs of -- [] -> go1 -- gs -> do -- mapM_ P.respond (init gs) -- go2 (last gs) -- go2 group0 = do -- mbs <- P.request () -- case mbs of -- Nothing -> do -- P.respond group0 -- go1 -- Just bs -> case BS.splitWith pred bs of -- [] -> go2 group0 -- [group1] -> go2 (BS.append group0 group1) -- group1:gs -> do -- P.respond (BS.append group0 group1) -- mapM_ P.respond (init gs) -- go2 (last gs) ---- | Store whether 'M.Any' element in the byte stream matches the given 'Word8' --elemD -- :: (Monad m, P.Proxy p) -- => Word8 -> x -> WriterP M.Any p x BS.ByteString x BS.ByteString m r --elemD w8 = P.foldD (M.Any . BS.elem w8) --[>| Store whether 'M.Any' element in the byte stream matches the given 'Word8' -- 'elemD_' terminates once a single 'Word8' matches the predicate. -} --elemD_ -- :: (Monad m, P.Proxy p) -- => Word8 -> x -> WriterP M.Any p x BS.ByteString x BS.ByteString m () --elemD_ w8 = go where -- go x = do -- bs <- P.request x -- if (BS.elem w8 bs) -- then tell (M.Any True) -- else do -- x2 <- P.respond bs -- go x2 --[>| Store whether 'M.All' elements in the byte stream do not match the given -- 'Word8' -} --notElemD -- :: (Monad m, P.Proxy p) -- => Word8 -> x -> WriterP M.All p x BS.ByteString x BS.ByteString m r --notElemD w8 = P.foldD (M.All . BS.notElem w8) ---- | Store the 'M.First' element in the stream that matches the predicate --findD -- :: (Monad m, P.Proxy p) -- => (Word8 -> Bool) -- -> x -> WriterP (M.First Word8) p x BS.ByteString x BS.ByteString m r --findD pred = P.foldD (M.First . BS.find pred) --[>| Store the 'M.First' element in the stream that matches the predicate -- 'findD_' terminates when a 'Word8' matches the predicate -} --findD_ -- :: (Monad m, P.Proxy p) -- => (Word8 -> Bool) -- -> x -> WriterP (M.First Word8) p x BS.ByteString x BS.ByteString m () --findD_ pred = go where -- go x = do -- bs <- P.request x -- case BS.find pred bs of -- Nothing -> do -- x2 <- P.respond bs -- go x2 -- Just w8 -> tell . M.First $ Just w8 ---- | Only allows 'Word8's to pass if they satisfy the predicate --filterD -- :: (Monad m, P.Proxy p) -- => (Word8 -> Bool) -> x -> p x BS.ByteString x BS.ByteString m r --filterD pred = P.mapD (BS.filter pred) ---- | Stores the element located at a given index, starting from 0 --indexD -- :: (Monad m, P.Proxy p) -- => Int64 -- -> x -> WriterP (M.First Word8) p x BS.ByteString x BS.ByteString m r --indexD n = go n where -- go n x = do -- bs <- P.request x -- let len = fromIntegral $ BS.length bs -- if (len <= n) -- then do -- x2 <- P.respond bs -- go (n - len) x2 -- else do -- tell . M.First . Just . BS.index bs $ fromIntegral n -- x2 <- P.respond bs -- P.pull x2 --[>| Stores the element located at a given index, starting from 0 -- 'indexD_' terminates once it reaches the given index. -} --indexD_ -- :: (Monad m, P.Proxy p) -- => Int64 -- -> x -> WriterP (M.First Word8) p x BS.ByteString x BS.ByteString m () --indexD_ n = go n where -- go n x = do -- bs <- P.request x -- let len = fromIntegral $ BS.length bs -- if (len <= n) -- then do -- x2 <- P.respond bs -- go (n - len) x2 -- else tell . M.First . Just . BS.index bs $ fromIntegral n ---- | Stores the 'M.First' index of an element that matches the given 'Word8' --elemIndexD -- :: (Monad m, P.Proxy p) -- => Word8 -- -> x -> WriterP (M.First Int64) p x BS.ByteString x BS.ByteString m r --elemIndexD w8 = go 0 where -- go n x = do -- bs <- P.request x -- case BS.elemIndex w8 bs of -- Nothing -> do -- x2 <- P.respond bs -- go (n + fromIntegral (BS.length bs)) x2 -- Just i -> do -- tell . M.First . Just $ n + fromIntegral i -- x2 <- P.respond bs -- P.pull x2 --[>| Stores the 'M.First' index of an element that matches the given 'Word8' -- 'elemIndexD_' terminates when it encounters a matching 'Word8' -} --elemIndexD_ -- :: (Monad m, P.Proxy p) -- => Word8 -- -> x -> WriterP (M.First Int64) p x BS.ByteString x BS.ByteString m () --elemIndexD_ w8 = go 0 where -- go n x = do -- bs <- P.request x -- case BS.elemIndex w8 bs of -- Nothing -> do -- x2 <- P.respond bs -- go (n + fromIntegral (BS.length bs)) x2 -- Just i -> tell . M.First . Just $ n + fromIntegral i ---- | Store a list of all indices whose elements match the given 'Word8' --elemIndicesD -- :: (Monad m, P.Proxy p) -- => Word8 -- -> x -> WriterP [Int64] p x BS.ByteString x BS.ByteString m r --elemIndicesD w8 = P.foldD (map fromIntegral . BS.elemIndices w8) ---- | Store the 'M.First' index of an element that satisfies the predicate --findIndexD -- :: (Monad m, P.Proxy p) -- => (Word8 -> Bool) -- -> x -> WriterP (M.First Int64) p x BS.ByteString x BS.ByteString m r --findIndexD pred = go 0 where -- go n x = do -- bs <- P.request x -- case BS.findIndex pred bs of -- Nothing -> do -- x2 <- P.respond bs -- go (n + fromIntegral (BS.length bs)) x2 -- Just i -> do -- tell . M.First . Just $ n + fromIntegral i -- x2 <- P.respond bs -- P.pull x2 --[>| Store the 'M.First' index of an element that satisfies the predicate -- 'findIndexD_' terminates when an element satisfies the predicate -} --findIndexD_ -- :: (Monad m, P.Proxy p) -- => (Word8 -> Bool) -- -> x -> WriterP (M.First Int64) p x BS.ByteString x BS.ByteString m () --findIndexD_ pred = go 0 where -- go n x = do -- bs <- P.request x -- case BS.findIndex pred bs of -- Nothing -> do -- x2 <- P.respond bs -- go (n + fromIntegral (BS.length bs)) x2 -- Just i -> tell . M.First . Just $ n + fromIntegral i ---- | Store a list of all indices whose elements satisfy the given predicate --findIndicesD -- :: (Monad m, P.Proxy p) -- => (Word8 -> Bool) -- -> x -> WriterP [Int64] p x BS.ByteString x BS.ByteString m r --findIndicesD pred = go 0 where -- go n x = do -- bs <- P.request x -- tell . map (\i -> n + fromIntegral i) $ BS.findIndices pred bs -- x2 <- P.respond bs -- go (n + fromIntegral (BS.length bs)) x2 ---- | Store a tally of how many elements match the given 'Word8' --countD -- :: (Monad m, P.Proxy p) -- => Word8 -> x -> WriterP (M.Sum Int64) p x BS.ByteString x BS.ByteString m r --countD w8 = P.foldD (M.Sum . fromIntegral . BS.count w8) -- | Stream bytes from 'stdin' stdinS :: (P.Proxy p) => () -> P.Producer p BS.ByteString IO () stdinS = fromHandleS stdin -- | Stream bytes to 'stdout' stdoutD :: (P.Proxy p) => x -> p x BS.ByteString x BS.ByteString IO () stdoutD = toHandleD stdout -- | Convert a 'Handle' into a byte stream fromHandleS :: (P.Proxy p) => Handle -> () -> P.Producer p BS.ByteString IO () fromHandleS = hGetSomeS BLI.defaultChunkSize -- | Convert a byte stream into a 'Handle' toHandleD :: (P.Proxy p) => Handle -> x -> p x BS.ByteString x BS.ByteString IO r toHandleD h = P.useD (BS.hPut h) -- | Convert a handle into a byte stream using a fixed chunk size hGetSomeS :: (P.Proxy p) => Int -> Handle -> () -> P.Producer p BS.ByteString IO () hGetSomeS size h () = P.runIdentityP go where go = do eof <- lift $ hIsEOF h unless eof $ do bs <- lift $ BS.hGetSome h size P.respond bs go -- | Convert a handle into a byte stream that serves variable chunk sizes hGetSomeS_ :: (P.Proxy p) => Handle -> Int -> P.Server p Int BS.ByteString IO () hGetSomeS_ h = P.runIdentityK go where go size = do eof <- lift $ hIsEOF h unless eof $ do bs <- lift $ BS.hGetSome h size size2 <- P.respond bs go size2
fhaust/pipes-eep
src/Pipes/ByteString.hs
mit
24,010
0
15
7,362
1,201
915
286
46
1
{-# LANGUAGE TupleSections, OverloadedStrings #-} module Handler.Home where import qualified Data.Map as M import qualified Data.Text as T import Import import Barch.Adaptors import Barch.Widgets (shortReferenceView) pageLimit::Int pageLimit = 30 getHomeR::Handler Html getHomeR = do citations <- runDB $ selectList [] [Desc ReferenceLastModified, LimitTo (pageLimit + 1), OffsetBy 0] let action = "Home" :: Text page = 0 submission = Nothing :: Maybe (FileInfo, Text) handlerName = "getHomeR" :: Text moreCitations = False citations' = take pageLimit citations defaultLayout $ do aDomId <- newIdent setTitle "Barch Homepage" $(widgetFile "browse")
klarh/barch
Handler/Home.hs
mit
728
0
13
167
194
106
88
22
1
module LabeledAst where import qualified Ast as Ast import qualified Data.Map as Map import qualified Data.Set as Set import Data.Set (Set, union, delete, singleton, (\\)) import Control.Monad.State import Control.Applicative ((<*>)) type Label = Integer data LAst = Var String Label | Function String LAst Label | Application LAst LAst Label | IfExpr LAst LAst LAst Label | LetExpr [(String, LAst)] LAst Label | LetRec [(String, LAst)] LAst Label | Bool Bool Label | String String Label | Unit Label | Number Integer Label | BinaryExpr String LAst LAst Label | List [LAst] Label | Car LAst Label | Cdr LAst Label | Cons LAst LAst Label | IsNil LAst Label deriving (Eq, Ord) convert :: Ast.Ast -> (LAst, Label) convert old = let (program, l) = runState (convertM old) 1 in (program, l + 1) convertM :: Ast.Ast -> State Label LAst convertM (Ast.Var v) = do l <- freshLabel return $ Var v l convertM (Ast.Function arg body) = do body' <- convertM body l <- freshLabel return $ Function arg body' l convertM (Ast.Application e1 e2) = do e1' <- convertM e1 e2' <- convertM e2 l <- freshLabel return $ Application e1' e2' l convertM (Ast.IfExpr cond e1 e2) = do cond' <- convertM cond e1' <- convertM e1 e2' <- convertM e2 l <- freshLabel return $ IfExpr cond' e1' e2' l convertM (Ast.LetRec binds body) = do let decls = map fst binds inits = map snd binds inits' <- mapM convertM inits body' <- convertM body l <- freshLabel return $ LetRec (zip decls inits') body' l convertM (Ast.LetExpr binds body) = do let decls = map fst binds inits = map snd binds inits' <- mapM convertM inits body' <- convertM body l <- freshLabel return $ LetExpr (zip decls inits') body' l convertM (Ast.BinaryExpr op e1 e2) = do e1' <- convertM e1 e2' <- convertM e2 l <- freshLabel return $ BinaryExpr op e1' e2' l convertM (Ast.List as) = do as' <- mapM convertM as l <- freshLabel return $ List as' l convertM (Ast.Car lst) = do lst' <- convertM lst l <- freshLabel return $ Car lst' l convertM (Ast.Cdr lst) = do lst' <- convertM lst l <- freshLabel return $ Cdr lst' l convertM (Ast.Cons e lst) = do e' <- convertM e lst' <- convertM lst l <- freshLabel return $ Cons e' lst' l convertM (Ast.IsNil lst) = do lst' <- convertM lst l <- freshLabel return $ IsNil lst' l convertM (Ast.Bool b) = do l <- freshLabel return $ Bool b l convertM (Ast.String s) = do l <- freshLabel return $ String s l convertM (Ast.Number n) = do l <- freshLabel return $ Number n l convertM Ast.Unit = do l <- freshLabel return $ Unit l allVar :: LAst -> Set String allVar (Function x body _) = Set.singleton x `union` allVar body allVar (LetRec binds body _) = Set.fromList (map fst binds) `union` Set.unions (map allVar (map snd binds))`union` allVar body allVar (IfExpr cond e1 e2 _) = allVar cond `union` allVar e1 `union` allVar e2 allVar (BinaryExpr _ e1 e2 _) = allVar e1 `union` allVar e2 allVar (Application e1 e2 _) = allVar e1 `union` allVar e2 allVar _ = Set.empty allFunction :: LAst -> Set LAst allFunction f@(Function _ body _) = Set.singleton f `union` allFunction body allFunction (LetRec binds body _) = let inits = map snd binds funsList = map allFunction inits in allFunction body `union` Set.unions funsList allFunction (IfExpr cond e1 e2 _) = allFunction cond `union` allFunction e1 `union` allFunction e2 allFunction (BinaryExpr _ e1 e2 _) = allFunction e1 `union` allFunction e2 allFunction (Application e1 e2 _) = allFunction e1 `union` allFunction e2 allFunction _ = Set.empty fv :: LAst -> Set String fv (Function x body _) = delete x $ fv body fv (Var x _) = singleton x fv (LetRec binds body _) = let vars = Set.fromList $ map fst binds inits = map snd binds in fv body `union` Set.unions (map fv inits) \\ vars fv (IfExpr cond e1 e2 _) = fv cond `union` fv e1 `union` fv e2 fv (BinaryExpr _ e1 e2 _) = fv e1 `union` fv e2 fv (Application e1 e2 _) = fv e1 `union` fv e2 fv _ = Set.empty labelOf :: LAst -> Label labelOf (Var _ l) = l labelOf (Function _ _ l) = l labelOf (Application _ _ l) = l labelOf (IfExpr _ _ _ l) = l labelOf (LetRec _ _ l) = l labelOf (BinaryExpr _ _ _ l) = l labelOf (Number _ l) = l labelOf (Bool _ l) = l labelOf (String _ l) = l labelOf (Unit l) = l labelOf _ = error "No Label" freshLabel = do l <- get put $ l + 1 return l addLable l = " @<" ++ show l ++ "> " instance Show LAst where show (Var v l) = v ++ addLable l show (Function v body l) = "function (" ++ v ++ ") {" ++ show body ++ "}" ++ addLable l show (IfExpr cond e1 e2 l) = "if (" ++ show cond ++ ") {" ++ show e1 ++ "} else {" ++ show e2 ++ "}" ++ addLable l show (LetRec binds body l) = let vs = unwords $ map (\(v,i) -> "var " ++ v ++ " = " ++ show i ++ ";\n" ) binds in vs ++ show body ++ addLable l show (Bool False l) = "false" ++ addLable l show (Bool True l) = "true" ++ addLable l show (String s l) = s ++ addLable l show (Number n l) = show n ++ addLable l show (Unit l) = "()" ++ addLable l show (BinaryExpr op e1 e2 l) = show e1 ++ op ++ show e2 ++ addLable l show (Application e1 e2 l) = show e1 ++ "(" ++ show e2 ++ ")" ++ addLable l show _ = "&&&&"
fiigii/AbstractInterpretation
LabeledAst.hs
mit
6,730
0
17
2,698
2,514
1,229
1,285
154
1
module TestPrograms where import Expr -- Natural numbers natBody :: Type natBody = TVari [ ("Z", []), ("S", [TRecTypeVar "nat"]) ] natRec :: Type natRec = TRecInd "nat" natBody nat :: Defi nat = DData "nat" natRec zero = (EVar "Z") one = EApp (EVar "S") [zero] -- Nat Stream natStreamBody :: [(Sym, Type)] natStreamBody = [ ("head", TGlobTypeVar "nat"), ("tail", TRecTypeVar "natStream") ] natStreamRec :: Type natStreamRec = TRecCoind "natStream" natStreamBody natStream :: Defi natStream = DCodata "natStream" natStreamRec -- List of natural numbers natListBody :: Type natListBody = TVari [ ("nil", []), ("cons", [(TGlobTypeVar "nat"), (TRecTypeVar "natList")]) ] natListRec :: Type natListRec = TRecInd "natList" natListBody natList :: Defi natList = DData "natList" natListRec emptyList = (EVar "nil") -- Functions on natural numbers subtractSlowly :: Defi subtractSlowlyBody :: Expr -- let subtractSlowly n = -- case n of -- Z -> Z -- S n' -> n' subtractSlowly = DGlobLet "subtractSlowly" (TArr [TGlobTypeVar "nat"] (TGlobTypeVar "nat")) (Just [("n", TGlobTypeVar "nat")]) subtractSlowlyBody subtractSlowlyBody = ECase (EApp (EUnfold (TGlobTypeVar "nat")) [(EVar "n")]) [ ("Z", ([], EApp (EFold (TGlobTypeVar "nat")) [(ETag "Z" [] natBody)])), ("S", (["n'"], (EApp (EVar "subtractSlowly") [(EVar "n'")]))) ] subtractSlowlyWithPred :: Defi subtractSlowlyWithPredBody :: Expr -- let subtractSlowlyWithPred n = -- let pred m = -- case m of -- Z -> Z -- S m' -> m' -- in case n of -- Z -> Z -- S n' -> subtractSlowlyWithPred (pred n) subtractSlowlyWithPred = DGlobLet "subtractSlowlyWithPred" (TArr [TGlobTypeVar "nat"] (TGlobTypeVar "nat")) (Just [("n", TGlobTypeVar "nat")]) subtractSlowlyWithPredBody subtractSlowlyWithPredBody = ELet "pred" (TArr [TGlobTypeVar "nat"] (TGlobTypeVar "nat")) (Just [("m", TGlobTypeVar "nat")]) (ECase (EApp (EUnfold (TGlobTypeVar "nat")) [EVar "m"]) [ ("Z", ([], EVar "Z")), ("S", (["m'"], EVar "m'")) ]) (ECase (EApp (EUnfold (TGlobTypeVar "nat")) [EVar "n"]) [ ("Z", ([], EVar "Z")), ("S", (["n'"], EApp (EVar "subtractSlowlyWithPred") [(EApp (EVar "pred") [EVar "n"])])) ]) forever :: Defi foreverBody :: Expr -- let forever x = forever x forever = DGlobLet "forever" (TArr [TGlobTypeVar "nat"] (TGlobTypeVar "nat")) (Just [("x", TGlobTypeVar "nat")]) foreverBody foreverBody = EApp (EVar "forever") [(EVar "x")] -- Third example from original size-change paper scEx3 :: Defi scEx3Body :: Expr -- let scEx3 m n = -- case m of -- Z -> S n -- S m' -> case n of -- Z -> scEx3 m' 1 -- S n' -> scEx3 m' (scEx3 m n') scEx3 = DGlobLet "scEx3" (TArr [TGlobTypeVar "nat", TGlobTypeVar "nat"] (TGlobTypeVar "nat")) (Just [("m", TGlobTypeVar "nat"), ("n", TGlobTypeVar "nat")]) scEx3Body scEx3Body = ECase (EApp (EUnfold (TGlobTypeVar "nat")) [(EVar "m")]) [ ("Z", ([], EApp (EVar "S") [(EVar "n")])), ("S", (["m'"], (ECase (EApp (EUnfold (TGlobTypeVar "nat")) [(EVar "n")]) [ ("Z", ([], EApp (EVar "scEx3") [(EVar "m'"), one])), ("S", (["n'"], EApp (EVar "scEx3") [(EVar "m'"), (EApp (EVar "scEx3") [(EVar "m"), (EVar "n'")])])) ]))) ] -- Third example from original size-change paper (negative test) scEx3neg :: Defi scEx3negBody :: Expr -- let scEx3neg m n = -- case m of -- Z -> S n -- S m' -> case n of -- Z -> scEx3neg m' 1 -- S n' -> scEx3neg m' (scEx3neg m n') scEx3neg = DGlobLet "scEx3neg" (TArr [TGlobTypeVar "nat", TGlobTypeVar "nat"] (TGlobTypeVar "nat")) (Just [("m", TGlobTypeVar "nat"), ("n", TGlobTypeVar "nat")]) scEx3negBody scEx3negBody = ECase (EApp (EUnfold (TGlobTypeVar "nat")) [(EVar "m")]) [ ("Z", ([], EApp (EVar "S") [(EVar "n")])), ("S", (["m'"], (ECase (EApp (EUnfold (TGlobTypeVar "nat")) [(EVar "n")]) [ ("Z", ([], EApp (EVar "scEx3neg") [(EVar "m'"), one])), ("S", (["n'"], EApp (EVar "scEx3neg") [(EVar "m'"), (EApp (EVar "scEx3neg") [(EVar "m"), (EVar "n")])])) ]))) ] -- Fourth example from original size-change paper scEx4 :: Defi scEx4Body :: Expr -- let scEx4 m n r = -- case r of -- Z -> case n of -- Z -> m -- S n' -> scEx4 r n' m -- S r' -> scEx4 m r' n scEx4 = DGlobLet "scEx4" (TArr [TGlobTypeVar "nat", TGlobTypeVar "nat", TGlobTypeVar "nat"] (TGlobTypeVar "nat")) (Just [("m", TGlobTypeVar "nat"), ("n", TGlobTypeVar "nat"), ("r", TGlobTypeVar "nat")]) scEx4Body scEx4Body = ECase (EApp (EUnfold (TGlobTypeVar "nat")) [(EVar "r")]) [ ("Z", ([], ECase (EApp (EUnfold (TGlobTypeVar "nat")) [(EVar "n")]) [ ("Z", ([], EVar "m")), ("S", (["n'"], EApp (EVar "scEx4") [(EVar "r"), (EVar "n'"), (EVar "m")])) ])), ("S", (["r'"], EApp (EVar "scEx4") [(EVar "m"), (EVar "r'"), (EVar "n")])) ] -- Fourth example from original size-change paper (negative test) scEx4neg :: Defi scEx4negBody :: Expr -- let scEx4neg m n r = -- case r of -- Z -> case n of -- Z -> m -- S n' -> scEx4neg r n' m -- S r' -> scEx4neg m r' n scEx4neg = DGlobLet "scEx4neg" (TArr [TGlobTypeVar "nat", TGlobTypeVar "nat", TGlobTypeVar "nat"] (TGlobTypeVar "nat")) (Just [("m", TGlobTypeVar "nat"), ("n", TGlobTypeVar "nat"), ("r", TGlobTypeVar "nat")]) scEx4negBody scEx4negBody = ECase (EApp (EUnfold (TGlobTypeVar "nat")) [(EVar "r")]) [ ("Z", ([], ECase (EApp (EUnfold (TGlobTypeVar "nat")) [(EVar "n")]) [ ("Z", ([], EVar "m")), ("S", (["n'"], EApp (EVar "scEx4neg") [(EVar "r"), (EVar "n'"), (EVar "m")])) ])), ("S", (["r'"], EApp (EVar "scEx4neg") [(EVar "m"), (EVar "r"), (EVar "n")])) ] -- Functions on lists of natural numbers -- First example from the original size-change paper (reverse) scEx1 :: Defi scEx1Body :: Expr -- let scEx1 ls = -- let r1 ls a = -- case ls of -- nil -> a -- (cons x xs) -> r1 xs (cons x a) -- in r1 ls nil scEx1 = DGlobLet "scEx1" (TArr [TGlobTypeVar "natList"] (TGlobTypeVar "natList")) (Just [("ls", TGlobTypeVar "natList")]) scEx1Body scEx1Body = ELet "r1" (TArr [TGlobTypeVar "natList", TGlobTypeVar "natList"] (TGlobTypeVar "natList")) (Just [("ls", TGlobTypeVar "natList"), ("a", TGlobTypeVar "natList")]) (ECase (EApp (EUnfold (TGlobTypeVar "natList")) [(EVar "ls")]) [ ("nil", ([], EVar "a")), ("cons", (["x", "xs"], EApp (EVar "r1") [(EVar "xs"), (EApp (EVar "cons") [(EVar "x"), (EVar "a")])])) ]) (EApp (EVar "r1") [(EVar "ls"), emptyList]) -- Second example from original size-change paper -- let scEx2f i x = -- case i of -- nil -> x -- cons hd tl -> scEx2g tl x i scEx2f = DGlobLet "scEx2f" (TArr [TGlobTypeVar "natList", TGlobTypeVar "nat"] (TGlobTypeVar "nat")) (Just [("i", TGlobTypeVar "natList"), ("x", TGlobTypeVar "nat")]) scEx2fBody scEx2fBody = (ECase (EApp (EUnfold (TGlobTypeVar "natList")) [(EVar "i")]) [ ("nil", ([], EVar "x")), ("cons", (["hd", "tl"], EApp (EVar "scEx2g") [(EVar "tl"), (EVar "x"), (EVar "i")])) ]) -- let scEx2g a b c = -- f a (cons b c) scEx2g = DGlobLet "scEx2g" (TArr [TGlobTypeVar "natList", TGlobTypeVar "nat", TGlobTypeVar "natList"] (TGlobTypeVar "nat")) (Just [("a", TGlobTypeVar "natList"), ("b", TGlobTypeVar "nat"), ("c", TGlobTypeVar "natList")]) scEx2gBody scEx2gBody = EApp (EVar "scEx2f") [(EVar "a"), (EApp (EVar "S") [EVar "b"])] -- Fifth example from original size-change paper -- let scEx5 x y = -- case y of -- nil -> x -- cons yhd ytl -> -- case x of -- nil -> scEx5 y ytl -- cons xhd xtl -> scEx5 y xtl scEx5 = DGlobLet "scEx5" (TArr [TGlobTypeVar "natList", TGlobTypeVar "natList"] (TGlobTypeVar "natList")) (Just [("x", TGlobTypeVar "natList"), ("y", TGlobTypeVar "natList")]) scEx5Body scEx5Body = (ECase (EApp (EUnfold (TGlobTypeVar "natList")) [(EVar "y")]) [ ("nil", ([], EVar "x")), ("cons", (["yhd", "ytl"], (ECase (EApp (EUnfold (TGlobTypeVar "natList")) [(EVar "x")]) [ ("nil", ([], EApp (EVar "scEx5") [(EVar "y"), (EVar "ytl")])), ("cons", (["xhd", "xtl"], EApp (EVar "scEx5") [(EVar "y"), (EVar "xtl")])) ]) )) ]) -- Sixth example from original size-change paper -- let scEx6f a b = -- case b of -- nil -> scEx6g a nil -- cons bhd btl -> scEx6f (cons bhd a) btl scEx6f = DGlobLet "scEx6f" (TArr [TGlobTypeVar "natList", TGlobTypeVar "natList"] (TGlobTypeVar "natList")) (Just [("a", TGlobTypeVar "natList"), ("b", TGlobTypeVar "natList")]) scEx6fBody scEx6fBody = (ECase (EApp (EUnfold (TGlobTypeVar "natList")) [(EVar "b")]) [ ("nil", ([], EApp (EVar "scEx6g") [(EVar "a"), emptyList])), ("cons", (["bhd", "btl"], EApp (EVar "scEx6f") [(EApp (EVar "cons") [EVar "bhd", EVar "a"]), (EVar "btl")])) ]) -- let scEx6g c d = -- case c of -- nil -> d -- cons chd ctl -> scEx6g ctl (cons chd d) scEx6g = DGlobLet "scEx6g" (TArr [TGlobTypeVar "natList", TGlobTypeVar "natList"] (TGlobTypeVar "natList")) (Just [("c", TGlobTypeVar "natList"), ("d", TGlobTypeVar "natList")]) scEx6gBody scEx6gBody = (ECase (EApp (EUnfold (TGlobTypeVar "natList")) [(EVar "c")]) [ ("nil", ([], EVar "d")), ("cons", (["chd", "ctl"], EApp (EVar "scEx6g") [(EVar "ctl"), (EApp (EVar "cons") [EVar "chd", EVar "d"])])) ])
tdidriksen/copatterns
src/findus/test/TestPrograms.hs
mit
9,623
0
20
2,215
3,541
1,980
1,561
124
1
module PiEstimator where import Control.Parallel (par, pseq) radius = 10^9 batchSize = radius `div` 2 sqRadius = radius^2 estimateSectionArea :: Integer -> Integer -> Integer estimateSectionArea yi yf = batchOne `par` (batchTwo + batchOne) where batchOne = estimateSectionArea' yi batchSize (findX radius (yi^2)) 0 batchTwo = estimateSectionArea' batchSize radius (findX radius (batchSize^2)) 0 estimateSectionArea' :: Integer -> Integer -> Integer -> Integer -> Integer estimateSectionArea' y yf x area | y < yf = let nextX = findX x (y^2) nextY = y + 1 accArea = area + x in nextX `pseq` nextY `seq` accArea `seq` estimateSectionArea' nextY yf nextX accArea | otherwise = area findX :: Integer -> Integer -> Integer findX x sqY | (x^2 + sqY) > sqRadius = findX (x - 1) sqY | otherwise = x computePi :: Double computePi = fromIntegral (4 * areaCircle) / fromIntegral areaSquare where areaCircle = (4 * estimateSectionArea 0 radius) areaSquare = (2 * radius) ^ 2
danielqo/PiAlgorithms
haskell/PiEstimator.hs
mit
1,055
0
12
251
391
207
184
24
1
{-# htermination plusFM :: Ord a => FiniteMap [a] b -> FiniteMap [a] b -> FiniteMap [a] b #-} import FiniteMap
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_plusFM_4.hs
mit
111
0
3
21
5
3
2
1
0
module GHCJS.DOM.SVGAngle ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/SVGAngle.hs
mit
38
0
3
7
10
7
3
1
0
{-# OPTIONS_GHC -fno-warn-missing-signatures #-} module ZMachine.ZTypes where import Control.Applicative import qualified Data.Map as M import Data.Word type Number = Word16 data BitNumber = BitNumber Int bit0 = BitNumber 0 bit1 = BitNumber 1 bit2 = BitNumber 2 bit3 = BitNumber 3 bit4 = BitNumber 4 bit5 = BitNumber 5 bit6 = BitNumber 6 bit7 = BitNumber 7 bit8 = BitNumber 8 bit9 = BitNumber 9 bit10 = BitNumber 10 bit11 = BitNumber 11 bit12 = BitNumber 12 bit13 = BitNumber 13 bit14 = BitNumber 14 bit15 = BitNumber 15 data BitSize = BitSize Int size1 = BitSize 1 size2 = BitSize 2 size3 = BitSize 3 size4 = BitSize 4 size5 = BitSize 5 size6 = BitSize 6 size7 = BitSize 7 data ByteAddress = ByteAddress Int isInRange :: ByteAddress -> Int -> Bool isInRange (ByteAddress address) size = 0 <= address && address < size isOutOfRange :: ByteAddress -> Int -> Bool isOutOfRange address size = not $ isInRange address size type IntMap = M.Map Int data ImmutableBytes = ImmutableBytes { originalBytes :: [Word8], edits :: IntMap Word8 } make :: [Word8] -> ImmutableBytes make bytes = ImmutableBytes bytes M.empty size :: ImmutableBytes -> Int size = length . originalBytes readByte :: ImmutableBytes -> ByteAddress -> Maybe Word8 readByte bytes address@(ByteAddress addr) = if isOutOfRange address (size bytes) then Nothing else M.lookup addr (edits bytes) <|> Just (originalBytes bytes !! addr) writeByte :: ImmutableBytes -> ByteAddress -> Word8 -> Maybe ImmutableBytes writeByte bytes address@(ByteAddress addr) value = if isOutOfRange address (size bytes) then Nothing else Just $ ImmutableBytes (originalBytes bytes) (M.insert addr value (edits bytes)) newEdits :: ImmutableBytes -> IntMap Word8 -> ImmutableBytes newEdits (ImmutableBytes b _) = ImmutableBytes b
RaphMad/ZMachine
src/lib/ZMachine/ZTypes.hs
mit
1,804
0
11
322
610
317
293
55
2
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS -fno-warn-unused-top-binds #-} -- for lenses -- | Parameters for launching everything. module Pos.Launcher.Param ( LoggingParams (..) , BaseParams (..) , NodeParams (..) ) where import Universum import Control.Lens (makeLensesWith) import Pos.Behavior (BehaviorConfig (..)) import Pos.Chain.Security (SecurityParams) import Pos.Chain.Ssc (SscBehavior) import Pos.Chain.Update (UpdateParams) import Pos.Core (HasPrimaryKey (..)) import Pos.Core.NetworkAddress (NetworkAddress) import Pos.Crypto (SecretKey) import Pos.Infra.DHT.Real.Param (KademliaParams) import Pos.Infra.InjectFail (FInjects) import Pos.Infra.Network.Types (NetworkConfig) import Pos.Infra.Statistics (EkgParams, StatsdParams) import Pos.Util.Lens (postfixLFields) import Pos.Util.UserSecret (UserSecret) import Pos.Util.Util (HasLens (..)) import Pos.Util.Wlog (LoggerName) -- | Contains all parameters required for hierarchical logger initialization. data LoggingParams = LoggingParams { lpDefaultName :: !LoggerName -- ^ Logger name which will be used by default , lpHandlerPrefix :: !(Maybe FilePath) -- ^ Prefix of path for all logs , lpConfigPath :: !(Maybe FilePath) -- ^ Path to logger configuration , lpConsoleLog :: !(Maybe Bool) -- ^ Enable console logging (override) } deriving (Show) -- | Contains basic & networking parameters for running node. data BaseParams = BaseParams { bpLoggingParams :: !LoggingParams -- ^ Logger parameters } deriving (Show) -- | This data type contains all data necessary to launch node and -- known in advance (from CLI, configs, etc.) data NodeParams = NodeParams { npDbPathM :: !(Maybe FilePath) -- ^ Path to node's database , npRebuildDb :: !Bool -- ^ @True@ if data-base should be rebuilt , npSecretKey :: !SecretKey -- ^ Primary secret key of node , npUserSecret :: !UserSecret -- ^ All node secret keys , npBaseParams :: !BaseParams -- ^ See 'BaseParams' , npJLFile :: !(Maybe FilePath) -- ^ File to use for JSON logging. , npReportServers :: ![Text] -- ^ List of report server URLs , npUpdateParams :: !UpdateParams -- ^ Params for update system , npRoute53Params :: !(Maybe NetworkAddress) -- ^ Where to listen for the Route53 DNS health-check. , npEnableMetrics :: !Bool -- ^ Gather runtime statistics. , npEkgParams :: !(Maybe EkgParams) -- ^ EKG statistics monitoring. , npStatsdParams :: !(Maybe StatsdParams) -- ^ statsd statistics backend. , npNetworkConfig :: !(NetworkConfig KademliaParams) , npBehaviorConfig :: !BehaviorConfig -- ^ Behavior (e.g. SSC settings) , npAssetLockPath :: !(Maybe FilePath) -- ^ Path to assetLocked source address file. , npFInjects :: !(FInjects IO) -- ^ Failure injection handle } makeLensesWith postfixLFields ''NodeParams makeLensesWith postfixLFields ''BehaviorConfig instance HasLens UpdateParams NodeParams UpdateParams where lensOf = npUpdateParams_L instance HasLens BehaviorConfig NodeParams BehaviorConfig where lensOf = npBehaviorConfig_L instance HasLens SecurityParams NodeParams SecurityParams where lensOf = npBehaviorConfig_L . bcSecurityParams_L instance HasLens SscBehavior NodeParams SscBehavior where lensOf = npBehaviorConfig_L . bcSscBehavior_L instance HasLens (NetworkConfig KademliaParams) NodeParams (NetworkConfig KademliaParams) where lensOf = npNetworkConfig_L instance HasPrimaryKey NodeParams where primaryKey = npSecretKey_L
input-output-hk/pos-haskell-prototype
lib/src/Pos/Launcher/Param.hs
mit
3,881
0
11
957
646
385
261
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} module Main where import Pipes.MongoDB as MP import Pipes import Data.Text import Database.MongoDB import Control.Monad.Trans.Control (MonadBaseControl) import Control.Monad ((>=>)) import qualified Pipes.Prelude as P runAction :: Action IO a -> IO a runAction a = do pipe <- connect (host "127.0.0.1") access pipe master "pipes-mongodb-example" a main :: IO () main = runAction tasks cities :: Producer (Maybe Text) (Action IO) () cities = MP.find (select [] "team") >-> P.map (look "home" >=> cast >=> look "city" >=> cast) tasks :: Action IO () tasks = do clearTeams insertTeams -- pipes stuff runEffect (cities >-> P.print) clearTeams :: MonadIO m => Action m () clearTeams = delete (select [] "team") t :: Text -> Text t v = v insertTeams :: MonadIO m => Action m [Value] insertTeams = insertMany "team" [ ["name" =: t "Yankees", "home" =: ["city" =: t "New York", "state" =: t "NY"], "league" =: t "American"], ["name" =: t "Mets", "home" =: ["city" =: t "New York", "state" =: t "NY"], "league" =: t "National"], ["name" =: t "Phillies", "home" =: ["city" =: t "Philadelphia", t "state" =: t "PA"], "league" =: t "National"], ["name" =: t "Red Sox", "home" =: ["city" =: t "Boston", "state" =: t "MA"], "league" =: t "American"] ]
jb55/pipes-mongodb
test/Test.hs
mit
1,346
0
11
256
531
276
255
34
1
{-# LANGUAGE OverloadedStrings #-} {- Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan <[email protected]> This file is part of FuncTorrent. FuncTorrent is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. FuncTorrent is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FuncTorrent; if not, see <http://www.gnu.org/licenses/> -} module Main where import Prelude hiding (log, length, readFile, getContents) import Control.Concurrent (forkIO, killThread) import Data.ByteString.Char8 (ByteString, getContents, readFile) import qualified FuncTorrent.FileSystem as FS (createMsgChannel, pieceMapFromFile, run) import FuncTorrent.Logger (initLogger, logMessage, logStop) import FuncTorrent.MagnetURI import FuncTorrent.Metainfo (Info(..), Metainfo(..), torrentToMetainfo) import FuncTorrent.Peer (handlePeerMsgs) import FuncTorrent.PieceManager (initPieceMap) import qualified FuncTorrent.Server as Server import FuncTorrent.Tracker (runTracker, getConnectedPeers, newTracker) import Network (PortID (PortNumber)) import System.Directory (doesFileExist) import System.Environment (getArgs) import System.Exit (exitSuccess) import System.IO (withFile, IOMode (ReadWriteMode)) import System.Random (getStdGen, randomRs) logError :: String -> (String -> IO ()) -> IO () logError e logMsg = logMsg $ "parse error: \n" ++ e exit :: IO ByteString exit = exitSuccess usage :: String usage = "usage: functorrent torrent-file" parse :: [String] -> IO ByteString parse [] = getContents parse [a] = do fileExist <- doesFileExist a if fileExist then readFile a else error "file does not exist" parse _ = exit -- peer id is exactly 20 bytes long. -- peer id starts with '-', followed by 2 char client id' -- followed by 4 ascii digits for version number, followed by -- a '-'. Rest are random digits to fill the 20 bytes. mkPeerID :: IO String mkPeerID = do stdgen <- getStdGen let digits = randomRs (0, 9) stdgen :: [Integer] return $ "-HS9001-" ++ (concatMap show $ take (20 - 8) digits) main :: IO () main = do args <- getArgs logR <- initLogger peerId <- mkPeerID let log = logMessage logR case args of [] -> do log usage _ -> do log "Starting up functorrent" log $ "Parsing arguments " ++ concat args torrentStr <- parse args case torrentToMetainfo torrentStr of Left e -> logError e log Right m -> do -- if we had downloaded the file before (partly or completely) -- then we should check the current directory for the existence -- of the file and then update the map of each piece' availability. -- This can be done by reading each piece and verifying the checksum. -- If the checksum does not match, we don't have that piece. let filePath = name (info m) -- really this is just the file name, not file path fileLen = lengthInBytes (info m) pieceHash = pieces (info m) pLen = pieceLength (info m) infohash = infoHash m defaultPieceMap = initPieceMap pieceHash fileLen pLen log $ "create FS msg channel" fsMsgChannel <- FS.createMsgChannel log $ "Downloading file : " ++ filePath pieceMap <- FS.pieceMapFromFile filePath fileLen defaultPieceMap log $ "start filesystem manager thread" fsTid <- forkIO $ withFile filePath ReadWriteMode (FS.run pieceMap fsMsgChannel) log $ "starting server" (serverSock, (PortNumber portnum)) <- Server.start log $ "server started on " ++ show portnum log "Trying to fetch peers" _ <- forkIO $ Server.run serverSock peerId m pieceMap fsMsgChannel log $ "Trackers: " ++ head (announceList m) trackerMsgChan <- newTracker _ <- forkIO $ runTracker trackerMsgChan fsMsgChannel infohash portnum peerId (announceList m) fileLen ps <- getConnectedPeers trackerMsgChan log $ "Peers List : " ++ (show ps) let p1 = head ps handlePeerMsgs p1 peerId m pieceMap True fsMsgChannel logStop logR killThread fsTid
vu3rdd/functorrent
src/main/Main.hs
gpl-3.0
4,810
0
22
1,297
959
495
464
80
3
module Updater.DownloadWithMD5 where import Import import Updater.Manifest(MD5Sum, renderMD5) import Network.HTTP.Conduit import Crypto.Classes -- | Download file from URL and compare it's md5sum with supplied. -- returns Just file if sums match. downloadWithMD5 :: String -> MD5Sum -> IO (Maybe LByteString) downloadWithMD5 url md5 = do u <- parseUrl url lbs <- responseBody <$> withManager (httpLbs u) if renderMD5 (hash lbs) == md5 then return $ Just lbs else return Nothing
exbb2/BlastItWithPiss
src/Updater/DownloadWithMD5.hs
gpl-3.0
507
0
11
99
131
68
63
12
2
-- | XHtml form handling module Dragonfly.Forms where import Control.Applicative.Error import Control.Applicative.State import Control.Arrow (second) import Data.List as List import Happstack.Server import Text.Formlets import qualified Text.XHtml.Strict as X import Text.XHtml.Strict ((+++), (<<)) import qualified Text.XHtml.Strict.Formlets as F import Dragonfly.ApplicationState type XForm a = F.XHtmlForm IO a -- | Process form if URL path matches name withForm :: String -> XForm a -> (X.Html -> [String] -> MyServerPartT Response) -> (a -> MyServerPartT Response) -> MyServerPartT Response withForm name frm handleErrors handleOk = dir (tail name) $ msum [methodSP GET $ createForm X.noHtml [] frm >>= okHtml , withDataFn lookPairs $ methodSP POST . handleOk' . simple ] where handleOk' d = do let (extractor, html, _) = runFormState d frm v <- liftIO extractor case v of Failure faults -> do f <- createForm X.noHtml d frm handleErrors f faults Success s -> handleOk s simple = List.map (second Left) -- | Prepend errors to the rendered form showErrorsInline :: X.Html -> [String] -> MyServerPartT Response showErrorsInline renderedForm errors = okHtml $ X.toHtml (show errors) +++ renderedForm -- | Display a form to the user with optional prologue and additional buttons createBasicForm :: (X.HTML b, X.HTML c) => c -> Env -> XForm a -> b -> MyServerPartT X.Html createBasicForm prologue env frm xhtml = do let (extractor, xml, endState) = runFormState env frm xml' <- liftIO xml let form = X.form X.! [X.method "POST", X.enctype "multipart/form-data"] << (xml' +++ xhtml) return $ prologue +++ form -- | Display a form to the user with a submit button createForm :: X.HTML b => b -> Env -> XForm a -> MyServerPartT X.Html createForm prologue env frm = createBasicForm prologue env frm (X.submit "submit" "Submit") -- | Display a form to the user with a preview button createPreview :: X.HTML b => b -> Env -> XForm a -> MyServerPartT X.Html createPreview prologue env frm = createBasicForm prologue env frm (X.submit "preview" "Preview") -- | Display a form to the user with both a preview and a submit button createPreviewSubmit :: X.HTML b => b -> Env -> XForm a -> MyServerPartT X.Html createPreviewSubmit prologue env frm = createBasicForm prologue env frm (X.submit "preview" "Preview" +++ X.submit "submit" "Submit") -- | Render an html page as a good response okHtml :: (X.HTML a) => a -> MyServerPartT Response okHtml = ok . toResponse . htmlPage -- | Render content within a standatd html template htmlPage :: (X.HTML a) => a -> X.Html htmlPage content = (X.header << (X.thetitle << "Colin's dragonflies")) +++ (X.body << content)
colin-adams/dragonfly-website
Dragonfly/Forms.hs
gpl-3.0
2,788
0
16
562
858
441
417
45
2
import System.IO import System.Environment import System.Exit import Sync main :: IO [[String]] main = getArgs >>= parse parse::[[Char]]-> IO [[String]] parse [] = usage >> exit parse ["-h"] = usage >> exit parse ["-v"] = version >> exit parse ["brayfordlets"] = brayfordlets parse ["bookclub"] = bookclub parse _ = undefined usage :: IO () usage = putStrLn "Usage: Sync [brayfordlets|bookclub]" version :: IO () version = putStrLn "Haskell Sync 0.1" exit :: IO a exit = exitWith ExitSuccess die :: IO a die = exitWith (ExitFailure 1)
b1g3ar5/Sync
app/Main.hs
gpl-3.0
595
5
8
146
239
115
124
21
1
module SIR ( AgentId , AgentMessage , AgentIn , AgentOut , SIRState (..) , SIRMsg (..) , SIRAgentIn , SIRAgentOut , agentId , agentObservable , agentIn , agentOut , agentOutObs , initAgents , sendMessage , sendMessageM , onMessageM , onMessage , distributeMessages , gotInfected , respondToContactWithM , aggregateAllStates , aggregateStates , writeAggregatesToFile , randomBoolM , randomExpM , randomElem ) where import qualified Data.Map as Map import System.IO import Text.Printf import Control.Monad.Random import Control.Monad.State type AgentId = Int type AgentMessage m = (AgentId, m) data AgentIn m = AgentIn { aiId :: AgentId , aiMsgs :: [AgentMessage m] } deriving (Show) data AgentOut s m = AgentOut { aoMsgs :: [AgentMessage m] , aoObsState :: Maybe s } deriving (Show) data SIRState = Susceptible | Infected | Recovered deriving (Show, Eq) data SIRMsg = Contact SIRState deriving (Show, Eq) type SIRAgentIn = AgentIn SIRMsg type SIRAgentOut = AgentOut SIRState SIRMsg agentId :: AgentIn m -> AgentId agentId AgentIn { aiId = aid } = aid agentObservable :: AgentOut s m -> Maybe s agentObservable AgentOut { aoObsState = os } = os agentIn :: AgentId -> AgentIn m agentIn aid = AgentIn { aiId = aid , aiMsgs = [] } agentOut :: AgentOut s m agentOut = AgentOut { aoMsgs = [] , aoObsState = Nothing } agentOutObs :: s -> AgentOut s m agentOutObs s = AgentOut { aoMsgs = [] , aoObsState = Just s } initAgents :: Int -> Int -> [SIRState] initAgents n i = sus ++ inf where sus = replicate (n - i) Susceptible inf = replicate i Infected sendMessage :: AgentMessage m -> AgentOut s m -> AgentOut s m sendMessage msg ao = ao { aoMsgs = msg : aoMsgs ao } sendMessageM :: (Monad mo) => AgentMessage m -> StateT (AgentOut s m) mo () sendMessageM msg = state (\ao -> ((), sendMessage msg ao)) onMessageM :: (Monad mon) => (acc -> AgentMessage m -> mon acc) -> AgentIn m -> acc -> mon acc onMessageM msgHdl ai acc | null msgs = return acc | otherwise = foldM msgHdl acc msgs where msgs = aiMsgs ai onMessage :: (AgentMessage m -> acc -> acc) -> AgentIn m -> acc -> acc onMessage msgHdl ai a | null msgs = a | otherwise = foldr (\msg acc'-> msgHdl msg acc') a msgs where msgs = aiMsgs ai gotInfected :: RandomGen g => Double -> SIRAgentIn -> Rand g Bool gotInfected infectionProb ain = onMessageM gotInfectedAux ain False where gotInfectedAux :: RandomGen g => Bool -> AgentMessage SIRMsg -> Rand g Bool gotInfectedAux False (_, Contact Infected) = randomBoolM infectionProb gotInfectedAux x _ = return x respondToContactWithM :: Monad m => SIRState -> SIRAgentIn -> StateT SIRAgentOut m () respondToContactWithM state ain = onMessageM respondToContactWithMAux ain () where respondToContactWithMAux :: Monad m => () -> AgentMessage SIRMsg -> StateT SIRAgentOut m () respondToContactWithMAux _ (senderId, Contact _) = sendMessageM (senderId, Contact state) distributeMessages :: [AgentIn m] -> [(AgentId, AgentOut s m)] -> [AgentIn m] distributeMessages ains aouts = map (distributeMessagesAux allMsgs) ains -- NOTE: speedup by running in parallel (if +RTS -Nx) where allMsgs = collectAllMessages aouts distributeMessagesAux :: Map.Map AgentId [AgentMessage m] -> AgentIn m -> AgentIn m distributeMessagesAux allMsgs ain = ain' where receiverId = aiId ain msgs = aiMsgs ain -- NOTE: ain may have already messages, they would be overridden if not incorporating them mayReceiverMsgs = Map.lookup receiverId allMsgs msgsEvt = maybe msgs (\receiverMsgs -> receiverMsgs ++ msgs) mayReceiverMsgs ain' = ain { aiMsgs = msgsEvt } collectAllMessages :: [(AgentId, AgentOut s m)] -> Map.Map AgentId [AgentMessage m] collectAllMessages aos = foldr collectAllMessagesAux Map.empty aos where collectAllMessagesAux :: (AgentId, AgentOut s m) -> Map.Map AgentId [AgentMessage m] -> Map.Map AgentId [AgentMessage m] collectAllMessagesAux (senderId, ao) accMsgs | not $ null msgs = foldr collectAllMessagesAuxAux accMsgs msgs | otherwise = accMsgs where msgs = aoMsgs ao collectAllMessagesAuxAux :: AgentMessage m -> Map.Map AgentId [AgentMessage m] -> Map.Map AgentId [AgentMessage m] collectAllMessagesAuxAux (receiverId, m) accMsgs = accMsgs' where msg = (senderId, m) mayReceiverMsgs = Map.lookup receiverId accMsgs newMsgs = maybe [msg] (\receiverMsgs -> (msg : receiverMsgs)) mayReceiverMsgs -- NOTE: force evaluation of messages, will reduce memory-overhead EXTREMELY accMsgs' = seq newMsgs (Map.insert receiverId newMsgs accMsgs) aggregateAllStates :: [[SIRState]] -> [(Int, Int, Int)] aggregateAllStates = map aggregateStates aggregateStates :: [SIRState] -> (Int, Int, Int) aggregateStates as = (susceptibleCount, infectedCount, recoveredCount) where susceptibleCount = length $ filter (Susceptible==) as infectedCount = length $ filter (Infected==) as recoveredCount = length $ filter (Recovered==) as writeAggregatesToFile :: String -> [(Int, Int, Int)] -> IO () writeAggregatesToFile fileName dynamics = do fileHdl <- openFile fileName WriteMode hPutStrLn fileHdl "dynamics = [" mapM_ (hPutStrLn fileHdl . sirAggregateToString) dynamics hPutStrLn fileHdl "];" hPutStrLn fileHdl "susceptible = dynamics (:, 1);" hPutStrLn fileHdl "infected = dynamics (:, 2);" hPutStrLn fileHdl "recovered = dynamics (:, 3);" hPutStrLn fileHdl "totalPopulation = susceptible(1) + infected(1) + recovered(1);" hPutStrLn fileHdl "susceptibleRatio = susceptible ./ totalPopulation;" hPutStrLn fileHdl "infectedRatio = infected ./ totalPopulation;" hPutStrLn fileHdl "recoveredRatio = recovered ./ totalPopulation;" hPutStrLn fileHdl "steps = length (susceptible);" hPutStrLn fileHdl "indices = 0 : steps - 1;" hPutStrLn fileHdl "figure" hPutStrLn fileHdl "plot (indices, susceptibleRatio.', 'color', 'blue', 'linewidth', 2);" hPutStrLn fileHdl "hold on" hPutStrLn fileHdl "plot (indices, infectedRatio.', 'color', 'red', 'linewidth', 2);" hPutStrLn fileHdl "hold on" hPutStrLn fileHdl "plot (indices, recoveredRatio.', 'color', 'green', 'linewidth', 2);" hPutStrLn fileHdl "set(gca,'YTick',0:0.05:1.0);" hPutStrLn fileHdl "xlabel ('Time');" hPutStrLn fileHdl "ylabel ('Population Ratio');" hPutStrLn fileHdl "legend('Susceptible','Infected', 'Recovered');" hClose fileHdl sirAggregateToString :: (Int, Int, Int) -> String sirAggregateToString (susceptibleCount, infectedCount, recoveredCount) = printf "%d" susceptibleCount ++ "," ++ printf "%d" infectedCount ++ "," ++ printf "%d" recoveredCount ++ ";" randomBoolM :: RandomGen g => Double -> Rand g Bool randomBoolM p = getRandomR (0, 1) >>= (\r -> return $ r <= p) randomExpM :: RandomGen g => Double -> Rand g Double randomExpM lambda = avoid 0 >>= (\r -> return $ ((-log r) / lambda)) where avoid :: (Random a, Eq a, RandomGen g) => a -> Rand g a avoid x = do r <- getRandom if r == x then avoid x else return r randomElem :: RandomGen g => [a] -> Rand g a randomElem as = getRandomR (0, len - 1) >>= (\idx -> return $ as !! idx) where len = length as
thalerjonathan/phd
coding/papers/FrABS/Haskell/prototyping/Utils/SIR.hs
gpl-3.0
7,710
1
18
1,879
2,238
1,154
1,084
172
2
{-# LANGUAGE Rank2Types #-} module Heqet.List where import Heqet.Types import Control.Lens -- like groupBy but doesn't preserve list order, -- instead grouping as much as possible. -- makeBucketsBy (==) [1,2,3,1,3,4] -> makeBucketsBy :: (a -> a -> Bool) -> [a] -> [[a]] makeBucketsBy comp xs = foldr f [] xs where f x [] = [[x]] f x (y:ys) = if x `comp` (head y) -- y can never be [] then (x:y):ys else y:(f x ys) -- note: does NOT preserve order! -- or rather, preserves the order of the items -- we're filtering for, but not the order -- of the whole list filteringBy :: (a -> Bool) -> Lens' [a] [a] filteringBy p = lens (filter p) (\s a -> s++a) atIndex :: Int -> Lens' [a] a atIndex i = lens (!! i) (\s a -> (take i s) ++ [a] ++ (drop (i+1) s)) removeAdjacentDuplicatesBy :: (a -> a -> Bool) -> [a] -> [a] removeAdjacentDuplicatesBy _ [] = [] removeAdjacentDuplicatesBy _ [x] = [x] removeAdjacentDuplicatesBy f (a:b:xs) = if a `f` b then removeAdjacentDuplicatesBy f (a:xs) else a:(removeAdjacentDuplicatesBy f (b:xs))
Super-Fluid/heqet
Heqet/List.hs
gpl-3.0
1,081
0
12
244
421
234
187
21
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AdSense.Accounts.Alerts.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- List the alerts for the specified AdSense account. -- -- /See:/ <https://developers.google.com/adsense/management/ AdSense Management API Reference> for @adsense.accounts.alerts.list@. module Network.Google.Resource.AdSense.Accounts.Alerts.List ( -- * REST Resource AccountsAlertsListResource -- * Creating a Request , accountsAlertsList , AccountsAlertsList -- * Request Lenses , aalLocale , aalAccountId ) where import Network.Google.AdSense.Types import Network.Google.Prelude -- | A resource alias for @adsense.accounts.alerts.list@ method which the -- 'AccountsAlertsList' request conforms to. type AccountsAlertsListResource = "adsense" :> "v1.4" :> "accounts" :> Capture "accountId" Text :> "alerts" :> QueryParam "locale" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Alerts -- | List the alerts for the specified AdSense account. -- -- /See:/ 'accountsAlertsList' smart constructor. data AccountsAlertsList = AccountsAlertsList' { _aalLocale :: !(Maybe Text) , _aalAccountId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountsAlertsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aalLocale' -- -- * 'aalAccountId' accountsAlertsList :: Text -- ^ 'aalAccountId' -> AccountsAlertsList accountsAlertsList pAalAccountId_ = AccountsAlertsList' { _aalLocale = Nothing , _aalAccountId = pAalAccountId_ } -- | The locale to use for translating alert messages. The account locale -- will be used if this is not supplied. The AdSense default (English) will -- be used if the supplied locale is invalid or unsupported. aalLocale :: Lens' AccountsAlertsList (Maybe Text) aalLocale = lens _aalLocale (\ s a -> s{_aalLocale = a}) -- | Account for which to retrieve the alerts. aalAccountId :: Lens' AccountsAlertsList Text aalAccountId = lens _aalAccountId (\ s a -> s{_aalAccountId = a}) instance GoogleRequest AccountsAlertsList where type Rs AccountsAlertsList = Alerts type Scopes AccountsAlertsList = '["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"] requestClient AccountsAlertsList'{..} = go _aalAccountId _aalLocale (Just AltJSON) adSenseService where go = buildClient (Proxy :: Proxy AccountsAlertsListResource) mempty
rueshyna/gogol
gogol-adsense/gen/Network/Google/Resource/AdSense/Accounts/Alerts/List.hs
mpl-2.0
3,414
0
14
775
392
236
156
62
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.GamesManagement.Scores.ResetMultipleForAllPlayers -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Resets scores for the leaderboards with the given IDs for all players. -- This method is only available to user accounts for your developer -- console. Only draft leaderboards may be reset. -- -- /See:/ <https://developers.google.com/games/ Google Play Game Management Reference> for @gamesManagement.scores.resetMultipleForAllPlayers@. module Network.Google.Resource.GamesManagement.Scores.ResetMultipleForAllPlayers ( -- * REST Resource ScoresResetMultipleForAllPlayersResource -- * Creating a Request , scoresResetMultipleForAllPlayers , ScoresResetMultipleForAllPlayers -- * Request Lenses , srmfapXgafv , srmfapUploadProtocol , srmfapAccessToken , srmfapUploadType , srmfapPayload , srmfapCallback ) where import Network.Google.GamesManagement.Types import Network.Google.Prelude -- | A resource alias for @gamesManagement.scores.resetMultipleForAllPlayers@ method which the -- 'ScoresResetMultipleForAllPlayers' request conforms to. type ScoresResetMultipleForAllPlayersResource = "games" :> "v1management" :> "scores" :> "resetMultipleForAllPlayers" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] ScoresResetMultipleForAllRequest :> Post '[JSON] () -- | Resets scores for the leaderboards with the given IDs for all players. -- This method is only available to user accounts for your developer -- console. Only draft leaderboards may be reset. -- -- /See:/ 'scoresResetMultipleForAllPlayers' smart constructor. data ScoresResetMultipleForAllPlayers = ScoresResetMultipleForAllPlayers' { _srmfapXgafv :: !(Maybe Xgafv) , _srmfapUploadProtocol :: !(Maybe Text) , _srmfapAccessToken :: !(Maybe Text) , _srmfapUploadType :: !(Maybe Text) , _srmfapPayload :: !ScoresResetMultipleForAllRequest , _srmfapCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ScoresResetMultipleForAllPlayers' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'srmfapXgafv' -- -- * 'srmfapUploadProtocol' -- -- * 'srmfapAccessToken' -- -- * 'srmfapUploadType' -- -- * 'srmfapPayload' -- -- * 'srmfapCallback' scoresResetMultipleForAllPlayers :: ScoresResetMultipleForAllRequest -- ^ 'srmfapPayload' -> ScoresResetMultipleForAllPlayers scoresResetMultipleForAllPlayers pSrmfapPayload_ = ScoresResetMultipleForAllPlayers' { _srmfapXgafv = Nothing , _srmfapUploadProtocol = Nothing , _srmfapAccessToken = Nothing , _srmfapUploadType = Nothing , _srmfapPayload = pSrmfapPayload_ , _srmfapCallback = Nothing } -- | V1 error format. srmfapXgafv :: Lens' ScoresResetMultipleForAllPlayers (Maybe Xgafv) srmfapXgafv = lens _srmfapXgafv (\ s a -> s{_srmfapXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). srmfapUploadProtocol :: Lens' ScoresResetMultipleForAllPlayers (Maybe Text) srmfapUploadProtocol = lens _srmfapUploadProtocol (\ s a -> s{_srmfapUploadProtocol = a}) -- | OAuth access token. srmfapAccessToken :: Lens' ScoresResetMultipleForAllPlayers (Maybe Text) srmfapAccessToken = lens _srmfapAccessToken (\ s a -> s{_srmfapAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). srmfapUploadType :: Lens' ScoresResetMultipleForAllPlayers (Maybe Text) srmfapUploadType = lens _srmfapUploadType (\ s a -> s{_srmfapUploadType = a}) -- | Multipart request metadata. srmfapPayload :: Lens' ScoresResetMultipleForAllPlayers ScoresResetMultipleForAllRequest srmfapPayload = lens _srmfapPayload (\ s a -> s{_srmfapPayload = a}) -- | JSONP srmfapCallback :: Lens' ScoresResetMultipleForAllPlayers (Maybe Text) srmfapCallback = lens _srmfapCallback (\ s a -> s{_srmfapCallback = a}) instance GoogleRequest ScoresResetMultipleForAllPlayers where type Rs ScoresResetMultipleForAllPlayers = () type Scopes ScoresResetMultipleForAllPlayers = '["https://www.googleapis.com/auth/games"] requestClient ScoresResetMultipleForAllPlayers'{..} = go _srmfapXgafv _srmfapUploadProtocol _srmfapAccessToken _srmfapUploadType _srmfapCallback (Just AltJSON) _srmfapPayload gamesManagementService where go = buildClient (Proxy :: Proxy ScoresResetMultipleForAllPlayersResource) mempty
brendanhay/gogol
gogol-games-management/gen/Network/Google/Resource/GamesManagement/Scores/ResetMultipleForAllPlayers.hs
mpl-2.0
5,709
0
18
1,251
719
420
299
111
1
{-| Module : $Header$ Description : Operations on the AST of a mathematical equation. Copyright : (c) Joshua Gutow, 2016 License : GNU AGPL-3 Maintainer : [email protected] Stability : experimental Portability : portable This module provides a data structure to represent that AST of an equation and it provides tools to manipulate that structure. -} module Expression where import Atomic import Operations import Floating import Data.List (intercalate) import Data.Ratio -- | Node of an expression tree. data Node = Leaf {atom :: Atomic} | BinaryOp {bop :: BOp, left :: Node, right :: Node} | UnaryOp {uop :: UOp, val :: Node} | Operation {op :: Op, children :: [Node]} deriving (Eq) instance Show Node where show (Leaf v) = show v show (BinaryOp o l r) = "(" ++ show l ++ show o ++ show r ++ ")" show (UnaryOp o (Leaf a)) | o == Factorial = "(" ++ show a ++ show o ++ ")" | otherwise = show o ++ "(" ++ show a ++ ")" show (UnaryOp o l) | o == Factorial = "(" ++ show l ++ show o ++ ")" | otherwise = show o ++ show l show (Operation o c) = "(" ++ intercalate (show o) (map show c) ++ ")" -- | Simplifies all identities given to it. simplifyIds :: [(Node -> Node)] -> Node -> Node simplifyIds [] node = node simplifyIds ids node = simplifyIds (tail ids) $ simplify (head ids) node -- | Simplifies an expression tree as best as possible. simplifyAll :: Node -> Node simplifyAll = simplifyIds [constants, addId, multId] -- | Given a function that simplifies a single node, this walks the entire -- expression tree. -- This is designed to walk through every simplification at every step. simplify :: (Node -> Node) -> Node -> Node simplify fn (UnaryOp o v) = fn $ UnaryOp o (simplifyAll v) simplify fn (BinaryOp o l r) = fn $ BinaryOp o (simplifyAll l) (simplifyAll r) simplify fn (Operation o c) = fn $ Operation o (map simplifyAll c) simplify _ x@(Leaf _) = x -- | Simplifies basic addition identities. addId :: Node -> Node addId (Operation Addition [x@(Leaf _)]) = x addId (Operation Addition xs) | length output == 1 = head output | otherwise = Operation Addition output where output = (filter (Leaf (Num (0%1)) /=) xs) addId x = x -- | Simplifies basic multiplication identities. multId :: Node -> Node multId (Operation Multiplication [x@(Leaf _)]) = x multId (Operation Multiplication xs) | length output == 1 = head output | otherwise = Operation Multiplication output where output = (filter (Leaf (Num (1%1)) /=) xs) multId x = x -- | This simplifies a node where the chilren are constants. constants :: Node -> Node constants (UnaryOp o (Leaf (Num n))) = Leaf $ Num (uopFn o n) constants (BinaryOp o (Leaf (Num l)) (Leaf (Num r))) = Leaf $ Num (bopFn o l r) constants (Operation o c) = Operation o (nums:vars) where val = foldl (opFn o) (baseId o) (map (num . atom) $ filter isNum c) nums = Leaf $ Num val vars = filter (not . isNum) c constants x = x isNum :: Node -> Bool isNum (Leaf (Num _)) = True isNum _ = False uopFn :: UOp -> (Rational -> Rational) uopFn Negation = negate -- | I need a formula that works on rational numbers. -- uopFn Factorial = factorial uopFn Ln = log uopFn (Log r) = logBase r uopFn Tan = tan uopFn Sin = sin uopFn Cos = cos bopFn :: BOp -> (Rational -> Rational -> Rational) bopFn Division = (/) bopFn Subtraction = (-) bopFn Exp = (**) opFn :: Op -> (Rational -> Rational -> Rational) opFn Multiplication = (*) opFn Addition = (+) baseId :: Num a => Op -> a baseId Multiplication = 1 baseId Addition = 0
trianglesphere/hcas
src/Expression.hs
agpl-3.0
3,846
0
14
1,055
1,326
685
641
69
1
module ProjectM36.AtomFunctions.Primitive where import ProjectM36.Base import ProjectM36.Relation (relFold, oneTuple) import ProjectM36.Tuple import ProjectM36.AtomFunctionError import ProjectM36.AtomFunction import qualified Data.HashSet as HS import qualified Data.Vector as V import Control.Monad import qualified Data.UUID as U import qualified Data.Text as T import qualified Data.Attoparsec.Text as APT import Data.Scientific primitiveAtomFunctions :: AtomFunctions primitiveAtomFunctions = HS.fromList [ --match on any relation type Function { funcName = "add", funcType = [IntegerAtomType, IntegerAtomType, IntegerAtomType], funcBody = body (\(IntegerAtom i1:IntegerAtom i2:_) -> pure (IntegerAtom (i1 + i2)))}, Function { funcName = "id", funcType = [TypeVariableType "a", TypeVariableType "a"], funcBody = body (\(x:_) -> pure x)}, Function { funcName = "sum", funcType = foldAtomFuncType IntegerAtomType IntegerAtomType, funcBody = body (\(RelationAtom rel:_) -> relationSum rel)}, Function { funcName = "count", funcType = foldAtomFuncType (TypeVariableType "a") IntegerAtomType, funcBody = body (\(RelationAtom relIn:_) -> relationCount relIn)}, Function { funcName = "max", funcType = foldAtomFuncType IntegerAtomType IntegerAtomType, funcBody = body (\(RelationAtom relIn:_) -> relationMax relIn)}, Function { funcName = "min", funcType = foldAtomFuncType IntegerAtomType IntegerAtomType, funcBody = body (\(RelationAtom relIn:_) -> relationMin relIn)}, Function { funcName = "eq", funcType = [IntegerAtomType, IntegerAtomType, BoolAtomType], funcBody = body $ \(i1:i2:_) -> pure (BoolAtom (i1 == i2))}, Function { funcName = "lt", funcType = [IntegerAtomType, IntegerAtomType, BoolAtomType], funcBody = body $ integerAtomFuncLessThan False}, Function { funcName = "lte", funcType = [IntegerAtomType, IntegerAtomType, BoolAtomType], funcBody = body $ integerAtomFuncLessThan True}, Function { funcName = "gte", funcType = [IntegerAtomType, IntegerAtomType, BoolAtomType], funcBody = body $ integerAtomFuncLessThan False >=> boolAtomNot}, Function { funcName = "gt", funcType = [IntegerAtomType, IntegerAtomType, BoolAtomType], funcBody = body $ integerAtomFuncLessThan True >=> boolAtomNot}, Function { funcName = "not", funcType = [BoolAtomType, BoolAtomType], funcBody = body $ \(b:_) -> boolAtomNot b }, Function { funcName = "int", funcType = [IntegerAtomType, IntAtomType], funcBody = body $ \(IntegerAtom v:_) -> if v < fromIntegral (maxBound :: Int) then pure (IntAtom (fromIntegral v)) else Left InvalidIntBoundError }, Function { funcName = "integer", funcType = [IntAtomType, IntegerAtomType], funcBody = body $ \(IntAtom v:_) -> Right $ IntegerAtom $ fromIntegral v}, Function { funcName = "uuid", funcType = [TextAtomType, UUIDAtomType], funcBody = body $ \(TextAtom v:_) -> let mUUID = U.fromString (T.unpack v) in case mUUID of Just u -> pure $ UUIDAtom u Nothing -> Left $ InvalidUUIDString v } ] <> scientificAtomFunctions where body = FunctionBuiltInBody integerAtomFuncLessThan :: Bool -> [Atom] -> Either AtomFunctionError Atom integerAtomFuncLessThan equality (IntegerAtom i1:IntegerAtom i2:_) = pure (BoolAtom (i1 `op` i2)) where op = if equality then (<=) else (<) integerAtomFuncLessThan _ _= pure (BoolAtom False) boolAtomNot :: Atom -> Either AtomFunctionError Atom boolAtomNot (BoolAtom b) = pure (BoolAtom (not b)) boolAtomNot _ = error "boolAtomNot called on non-Bool atom" --used by sum atom function relationSum :: Relation -> Either AtomFunctionError Atom relationSum relIn = pure (IntegerAtom (relFold (\tupIn acc -> acc + newVal tupIn) 0 relIn)) where --extract Integer from Atom newVal tupIn = castInteger (tupleAtoms tupIn V.! 0) relationCount :: Relation -> Either AtomFunctionError Atom relationCount relIn = pure (IntegerAtom (relFold (\_ acc -> acc + 1) (0::Integer) relIn)) relationMax :: Relation -> Either AtomFunctionError Atom relationMax relIn = case oneTuple relIn of Nothing -> Left AtomFunctionEmptyRelationError Just oneTup -> pure (IntegerAtom (relFold (\tupIn acc -> max acc (newVal tupIn)) (newVal oneTup) relIn)) where newVal tupIn = castInteger (tupleAtoms tupIn V.! 0) relationMin :: Relation -> Either AtomFunctionError Atom relationMin relIn = case oneTuple relIn of Nothing -> Left AtomFunctionEmptyRelationError Just oneTup -> pure (IntegerAtom (relFold (\tupIn acc -> min acc (newVal tupIn)) (newVal oneTup) relIn)) where newVal tupIn = castInteger (tupleAtoms tupIn V.! 0) castInt :: Atom -> Int castInt (IntAtom i) = i castInt _ = error "attempted to cast non-IntAtom to Int" castInteger :: Atom -> Integer castInteger (IntegerAtom i) = i castInteger _ = error "attempted to cast non-IntegerAtom to Int" scientificAtomFunctions :: AtomFunctions scientificAtomFunctions = HS.fromList [ Function { funcName = "read_scientific", funcType = [TextAtomType, ScientificAtomType], funcBody = body $ \(TextAtom t:_) -> case APT.parseOnly (APT.scientific <* APT.endOfInput) t of Left err -> Left (AtomFunctionParseError err) Right sci -> pure (ScientificAtom sci) }, Function { funcName = "scientific", funcType = [IntegerAtomType, IntAtomType, ScientificAtomType], funcBody = body $ \(IntegerAtom c:IntAtom e:_) -> pure (ScientificAtom $ scientific c e) }, Function { funcName = "scientific_add", funcType = binaryFuncType, funcBody = binaryFuncBody (+) }, Function { funcName = "scientific_subtract", funcType = binaryFuncType, funcBody = binaryFuncBody (-) }, Function { funcName = "scientific_multiply", funcType = binaryFuncType, funcBody = binaryFuncBody (*) }, Function { funcName = "scientific_divide", funcType = binaryFuncType, funcBody = binaryFuncBody (/) } ] where body = FunctionBuiltInBody binaryFuncType = [ScientificAtomType, ScientificAtomType, ScientificAtomType] binaryFuncBody op = body $ \(ScientificAtom s1:ScientificAtom s2:_) -> pure (ScientificAtom (s1 `op` s2))
agentm/project-m36
src/lib/ProjectM36/AtomFunctions/Primitive.hs
unlicense
7,067
0
19
1,978
1,982
1,100
882
124
3
module Chemicals where data Legend = OTC | Rx | CI | CII | CIII | CIV | CV | Dual data TherapeuticClass = SABA | LABA | Glucocorticoid | Anticholinergic | Salicylate | NonaspirinNonNSAID | Opiate instance Show TherapeuticClass where show SABA = "short-acting beta2-adrenergic agonist" show LABA = "long-acting beta2-adrenergic agonist" show Glucocorticoid = "Glucocorticoid" show Anticholinergic = "Anticholinergic" show Salicylate = "Salicylate" show NonaspirinNonNSAID = "Non-aspirin,Non-NSAID" show Opiate = "Opiate" data Route = Oral | Nasal | Tracheal | Rectal | Inhalation | IV | Topical | OralInhalation | NasalInhalation | IM | SC deriving Show data Chemical = Chemical { name :: String , legend :: Legend , class_ :: TherapeuticClass , routes :: [Route] , tradeNames :: [String] , indications :: String } chemicals = [ Chemical { name = "albuterol (salbutamol) sulfate" , legend = Rx , class_ = SABA , routes = [Oral, Inhalation, IV] , tradeNames = ["Ventolin HFA","Proventil HFA" ,"ProAir HFA","Combivent (with ipratropium)" ,"DuoNeb (with ipratropium)" ] , indications = "relief of conditions such as asthma and COPD" } , Chemical { name = "acetylsalicyclic acid (aspirin)" , legend = OTC , class_ = Salicylate , routes = [Oral, Rectal, IV, IM] , tradeNames = ["Bayer", "Excedrin (with acetaminophen & caffeine)"] , indications = "relieve minor aches & pains, fever reducer (antipyretic), and anti-inflammatory" } , Chemical { name = "acetaminophen (paracetamol) or (apap)" , legend = OTC , class_ = NonaspirinNonNSAID , routes = [Oral, Rectal, IV] , tradeNames = ["Tylenol","Excedrin (with aspirin & caffeine)"] , indications = "relief of headaches, fever reducer (antipyretic), minor aches & pains" } , Chemical { name = "ibuprofen" , legend = OTC , class_ = NSAID , routes = [Oral, Rectal, Topical, IV] , tradeNames = ["Advil","Motrin"] , indications = "relieving pain, helping with fever, reducing inflammation" } , Chemical { name = "naproxen" , legend = OTC , class_ = NSAID , routes = [Oral] , tradeNames = ["Aleva","Naprosyn"] , indications = "relief pain, fever, swelling, and stiffness" } , Chemical { name = "morphine" , legend = CII , class_ = Opiate , routes = [Oral, Inhalation, Rectal, SC, IM, IV] , tradeNames = ["MS Contin"] , indications = "treat acute and chronic severe pain" } , Chemical { name = "meperidine (pethidine)" , legend = CII , class_ = Opiate , routes = [Oral, IV, IM, SC] , tradeNames = ["Demerol"] , indications = "used as an analgesic in labour and delivery" } , Chemical { name = "beclomethasone dipropionate" , legend = Rx , class_ = Glucocorticoid , routes = [OralInhalation, NasalInhalation, Topical] , tradeNames = ["QVAR","Beconase","Qnasl"] , indications = "prophylaxis of asthma, rhinitus treatment, and inflammatory skin disorders" } , Chemical { name = "budesonide" , legend = Rx , class_ = Glucocorticoid , routes = [Oral, Nasal, Tracheal, Rectal] , tradeNames = ["Pulmicort","Symbicort (with formoterol)"] , indications = "treatment of asthma, COPD, and non-infectious rhinitis" } , Chemical { name = "diclofenac sodium" , legend = Rx , class_ = NSAID , routes = [Oral, Rectal, IM, IV, Topical] , tradeNames = ["Voltaren", "Voltaren Gel", "Arthrotec (with misoprostol)"] , indications = "reduce inflammation and reducing pain in certain conditions" } , Chemical { name = "celecoxib" , legend = Rx , class_ = NSAID , routes = [Oral] , tradeNames = ["Celebrex"] , indications = "treat osteoarthritis, rheumatoid arthritis, ankylosing spindylitis, acute pain, painful mestruation" } , Chemical { name = "oxymorphone" , legend = CII , class_ = Opiate , routes = [IV, IM, SC, Oral, Rectal, Nasal] , tradeNames = ["Opana"] , indications = "relief of moderate to severe pain" } , Chemical { name = "oxycodone" , legend = CII , class_ = Opiate , routes = [Oral, IM, IV, Nasal, SC, Rectal] , tradeNames = ["OxyContin"] , indications = "treat moderate to moderately severe acute or chronic pain" } , Chemical { name = "levalbuterol (levosalbutamol) tartrate" , legend = Rx , class_ = SABA , routes = [Oral, Inhalation] , tradeNames = ["Xopenex"] , indications = "treatment of asthma and COPD" } , Chemical { name = "formoterol fumarate" , legend = Rx , class_ = LABA , routes = [Oral, Inhalation] , tradeNames = ["Foradil","Perforomist","Symbicort (with budesonide)","Dulera (with mometasone)"] , indications = "management of asthma and COPD" } , Chemical { name = "fluticasone propionate" , legend = OTC , class_ = Glucocorticoid , routes = [Nasal, Inhalation, Topical] , tradeNames = ["Flovent","Advair (with salmeterol)"] , indications = "treat asthma, allergic rhinitus, nasal polyps, various skin disorders" } , Chemical { name = "fluticasone furoate" , legend = Rx , class_ = Glucocorticoid , routes = [Nasal] , tradeNames = ["Veramyst"] , indications = "treatment of allergic rhinitus" } , Chemical { name = "ipratropium bromide" , legend = Rx , class_ = Anticholinergic , routes = [Inhalation] , tradeNames = ["Atrovent","Combivent (with albuterol)","Duoneb (with albuterol)"] , indications = "treatment of COPD and acute asthma" } , Chemical { name = "mometasone furoate" , legend = Rx , class_ = Glucocorticoid , routes = [Topical, Inhalation] , tradeNames = ["Elocon","Novasone","Nasonex","Asmanex" ,"Mometamax","Dulera (with formoterol)"] , indications = "treatment of inflammatory skin disorders, allergic rhinitus, and asthma" } , Chemical { name = "salmeterol" , legend = Rx , class_ = LABA , routes = [Inhalation] , tradeNames = ["Serevent","Advair (with fluticasone)"] , indications = "maintenace and prevention of asthma and maintenance of COPD" } , Chemical { name = "tiotropium bromide" , legend = Rx , class_ = Anticholinergic , routes = [Inhalation] , tradeNames = ["Spiriva"] , indications = "maintenance treatment of COPD" } ]
kohabi/rxquiz
src/Chemicals.hs
unlicense
9,429
3
9
4,563
1,406
916
490
-1
-1