code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
module Qi.Program.Config.Ipret.State where
import Control.Lens hiding (view)
import Control.Monad.Freer
import Control.Monad.Freer.State
import Data.Default (def)
import qualified Data.HashMap.Strict as SHM
import Data.Proxy (Proxy (Proxy))
import Protolude hiding (State, get,
gets, modify,
runState)
import Qi.Config.AWS
import Qi.Config.AWS.ApiGw
import Qi.Config.AWS.CF
import qualified Qi.Config.AWS.CfCustomResource.Accessors as CustomResource
import Qi.Config.AWS.CW
import Qi.Config.AWS.DDB
import Qi.Config.AWS.Lambda
import Qi.Config.AWS.S3
import Qi.Config.AWS.SQS
import Qi.Config.Identifier
import Qi.Program.Config.Lang (ConfigEff (..))
run
:: forall effs a
. (Member (State Config) effs)
=> Eff (ConfigEff ': effs) a -> Eff effs a
run = interpret (\case
GetConfig -> get
-- get a resource-specific identifier based on the next autoincremented numeric id
-- while keeping the autoincrement state in the global Config
{- GetNextId -> getNextId -}
RegGenericLambda inProxy outProxy name f profile ->
withNextId (Proxy :: Proxy LambdaId) $ \id -> do
let lbd = GenericLambda name profile inProxy outProxy f
insertLambda id name lbd
-- S3
RegS3Bucket name profile -> do
withNextId (Proxy :: Proxy S3BucketId) $ \id -> do
let newBucket = def & s3bName .~ name
& s3bProfile .~ profile
insertIdToBucket = s3IdToBucket %~ SHM.insert id newBucket
insertNameToId = s3NameToId %~ SHM.insert name id
modify (s3Config %~ insertNameToId . insertIdToBucket)
RegS3BucketLambda name bucketId f profile ->
withNextId (Proxy :: Proxy LambdaId) $ \id -> do
let lbd = S3BucketLambda name profile f
modifyBucket = s3bEventConfigs %~ ((S3EventConfig S3ObjectCreatedAll id):)
modify (s3Config . s3IdToBucket %~ SHM.adjust modifyBucket bucketId)
insertLambda id name lbd
{-
-- DDB
RDdbTable name hashAttrDef profile -> send . QiConfig $
withNextId $ \id -> do
let newDdbTable = DdbTable {
_dtName = name
, _dtHashAttrDef = hashAttrDef
, _dtProfile = profile
, _dtStreamHandler = Nothing
}
ddbConfig . dcTables %= SHM.insert id newDdbTable
RDdbStreamLambda name tableId programFunc profile -> send . QiConfig $
withNextId $ \id -> do
let lbd = DdbStreamLambda name profile programFunc
ddbConfig.dcTables %= SHM.adjust (dtStreamHandler .~ Just id) tableId
lbdConfig.lcLambdas %= SHM.insert id lbd
insertLambda id name lbd
-}
-- Sqs
RegSqsQueue name ->
withNextId (Proxy :: Proxy SqsQueueId) $ \id -> do
modify (sqsConfig . sqsQueues %~ SHM.insert id SqsQueue{ _sqsQueueName = name })
-- Custom
RegCustomResource name programFunc profile -> do
id <- getNextId
let customResource = CfCustomResource id
(newCustomId, cfConfigModifier) = CustomResource.insert customResource
lbd = CfCustomLambda name profile programFunc
insertLambda id name lbd
modify $ cfConfig %~ cfConfigModifier
pure newCustomId
-- CloudWatch
RegCwEventLambda name ruleProfile programFunc profile -> do
eventsRuleId <- getNextId
withNextId (Proxy :: Proxy LambdaId) $ \id -> do
let lbd = CwEventLambda name profile programFunc
eventsRule = CwEventsRule {
_cerName = name
, _cerProfile = ruleProfile
, _cerLbdId = id
}
modify $ cwConfig . ccRules %~ SHM.insert eventsRuleId eventsRule
insertLambda id name lbd
)
where
getNextId
:: FromInt id
=> Eff effs id
getNextId = do
id <- gets (fromInt . (^. nextId))
modify (nextId %~ (+1))
pure id
withNextId
:: FromInt id
=> Proxy id
-> (id -> Eff effs c)
-> Eff effs id
withNextId _ f = do
id <- gets (fromInt . (^. nextId))
modify (nextId %~ (+1))
f id
pure id
insertLambda
:: LambdaId
-> Text
-> Lambda
-> Eff effs ()
insertLambda id name lbd = do
let insertIdToLambda = lbdIdToLambda %~ SHM.insert id lbd
insertNameToId = lbdNameToId %~ SHM.insert name id
void $ modify (lbdConfig %~ insertNameToId . insertIdToLambda)
{-
-- Api
rApi name = do
newApiId <- getNextId
let newApi = def & aName .~ name
insertIdToApi = acApis %~ SHM.insert newApiId newApi
insertIdToApiResourceDeps = acApiResourceDeps %~ SHM.insert (Left newApiId) []
insertIdToApiAuthorizerDeps = acApiAuthorizerDeps %~ SHM.insert newApiId []
apiGwConfig %= insertIdToApi . insertIdToApiResourceDeps . insertIdToApiAuthorizerDeps
pure newApiId
rApiAuthorizer name cognitoId apiId = do
newApiAuthorizerId <- getNextId
let newApiAuthorizer = ApiAuthorizer name cognitoId apiId
insertIdToApiAuthorizer = acApiAuthorizers %~ SHM.insert newApiAuthorizerId newApiAuthorizer
insertIdToApiAuthorizerDeps = acApiAuthorizerDeps %~ SHM.unionWith (++) (SHM.singleton apiId [newApiAuthorizerId])
apiGwConfig %= insertIdToApiAuthorizer . insertIdToApiAuthorizerDeps
pure newApiAuthorizerId
rApiResource
:: ParentResource a
=> Text
-> a
-> QiConfig ApiResourceId
rApiResource name pid = do
newApiResourceId <- getNextId
let parentId = toParentId pid
newApiResource = apiResource name parentId
insertIdToApiResource = acApiResources %~ SHM.insert newApiResourceId newApiResource
insertIdToApiResourceDeps = acApiResourceDeps %~ SHM.unionWith (++) (SHM.singleton parentId [newApiResourceId])
apiGwConfig %= insertIdToApiResource . insertIdToApiResourceDeps
pure newApiResourceId
rApiMethodLambda name verb apiResourceId methodProfile programFunc profile = do
newLambdaId <- getNextId
let newLambda = ApiLambda name profile programFunc
apiMethodConfig = ApiMethodConfig {
amcVerb = verb
, amcProfile = methodProfile
, amcLbdId = newLambdaId
}
apiGwConfig . acApiResources %= SHM.adjust (arMethodConfigs %~ (apiMethodConfig:)) apiResourceId
lbdConfig . lcLambdas %= SHM.insert newLambdaId newLambda
pure newLambdaId
-}
|
qmuli/qmuli
|
library/Qi/Program/Config/Ipret/State.hs
|
mit
| 7,342
| 0
| 22
| 2,235
| 1,081
| 575
| 506
| -1
| -1
|
module Main where
import Test.Hspec
import qualified Spec
main :: IO ()
main = do
putStrLn "before spec"
hspec Spec.spec
putStrLn "after spec"
|
beni55/hspec
|
hspec-discover/integration-test/with-module-name/Main.hs
|
mit
| 161
| 0
| 8
| 41
| 48
| 24
| 24
| 8
| 1
|
-----------------------------------------------------------------------------
-- |
-- Module : Control.Functor.End
-- Copyright : (C) 2008 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : non-portable (rank-2 polymorphism)
--
----------------------------------------------------------------------------
module Control.Functor.End where
newtype End f = End { runEnd :: forall i. f i i }
data Coend f = forall i. Coend { runCoend :: f i i }
|
urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav
|
Control/Functor/End.hs
|
apache-2.0
| 568
| 0
| 9
| 95
| 68
| 46
| 22
| -1
| -1
|
-- |
-- Module: Network.Riak.CRDT.Types
-- Copyright: (c) 2016 Sentenai
-- Author: Antonio Nikishaev <me@lelf.lu>
-- License: Apache
-- Maintainer: Tim McGilchrist <timmcgil@gmail.com>, Mark Hibberd <mark@hibberd.id.au>
-- Stability: experimental
-- Portability: portable
--
-- Haskell-side view of CRDT
--
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveGeneric #-}
module Network.Riak.CRDT.Types (
-- * Types
DataType(..)
-- ** Counters
, Counter(..), Count
-- *** Modification
, CounterOp(..)
-- ** Sets
, Set(..)
-- *** Modification
, SetOp(..)
-- ** Maps
, Map(..), MapContent
, MapField(..)
, MapEntry(..)
-- *** Inspection
, xlookup
-- *** Modification
, MapOp(..), MapPath(..), MapValueOp(..), mapUpdate, (-/)
-- ** Registers
, Register(..)
-- *** Modification
, RegisterOp(..)
-- ** Flags
, Flag(..)
-- *** Modification
, FlagOp(..)
-- * Misc
, NonEmpty(..), mapEntryTag, setFromSeq, MapEntryTag(..)
) where
import Control.DeepSeq (NFData)
import Data.ByteString.Lazy (ByteString)
import Data.Default.Class
import qualified Data.Foldable as F
import Data.Int (Int64)
import Data.List.NonEmpty
import qualified Data.Map.Strict as M
import Data.Semigroup
import qualified Data.Sequence as Seq
import qualified Data.Set as S
import Data.String (IsString(..))
import GHC.Generics (Generic)
-- | CRDT Map is indexed by MapField, which is a name tagged by a type
-- (there may be different entries with the same name, but different
-- types)
data MapField = MapField MapEntryTag ByteString deriving (Eq,Ord,Show,Generic)
instance NFData MapField
-- | CRDT Map is a Data.Map indexed by 'MapField' and holding
-- 'MapEntry'.
--
-- Maps are specials in a way that they can additionally
-- hold 'Flag's, 'Register's, and most importantly, other 'Map's.
newtype Map = Map MapContent deriving (Eq,Show,Generic)
instance NFData Map
type MapContent = M.Map MapField MapEntry
instance Default Map where
def = Map M.empty
data MapEntryTag = MapCounterTag
| MapSetTag
| MapRegisterTag
| MapFlagTag
| MapMapTag
deriving (Eq,Ord,Show,Generic)
instance NFData MapEntryTag
-- | CRDT Map holds values of type 'MapEntry'
data MapEntry = MapCounter !Counter
| MapSet !Set
| MapRegister !Register
| MapFlag !Flag
| MapMap !Map
deriving (Eq,Show,Generic)
instance NFData MapEntry
mapEntryTag :: MapValueOp -> MapEntryTag
mapEntryTag MapCounterOp{} = MapCounterTag
mapEntryTag MapSetOp{} = MapSetTag
mapEntryTag MapRegisterOp{} = MapRegisterTag
mapEntryTag MapFlagOp{} = MapFlagTag
mapEntryTag MapMapOp{} = MapMapTag
-- | Selector (“xpath”) inside 'Map'
newtype MapPath = MapPath (NonEmpty ByteString) deriving (Eq,Show)
-- | map operations
-- It's easier to use 'mapUpdate':
--
-- >>> "x" -/ "y" -/ "z" `mapUpdate` SetAdd "elem"
-- MapUpdate (MapPath ("x" :| ["y","z"])) (MapCounterOp (CounterInc 1))
data MapOp = MapRemove MapField -- ^ remove value in map
| MapUpdate MapPath MapValueOp -- ^ update value on path by operation
deriving (Eq,Show)
-- | Polymprhic version of MapOp for nicer syntax
data MapOp_ op = MapRemove_ MapField
| MapUpdate_ MapPath op
deriving Show
instance IsString MapPath where
fromString s = MapPath (fromString s :| [])
(-/) :: ByteString -> MapPath -> MapPath
e -/ (MapPath p) = MapPath (e <| p)
infixr 6 -/
class IsMapOp op where toValueOp :: op -> MapValueOp
instance IsMapOp CounterOp where toValueOp = MapCounterOp
instance IsMapOp FlagOp where toValueOp = MapFlagOp
instance IsMapOp RegisterOp where toValueOp = MapRegisterOp
instance IsMapOp SetOp where toValueOp = MapSetOp
mapUpdate :: IsMapOp o => MapPath -> o -> MapOp
p `mapUpdate` op = MapUpdate p (toValueOp op)
infixr 5 `mapUpdate`
-- | Lookup a value of a given 'MapEntryTag' type on a given 'MapPath'
-- inside a map
--
-- >>> lookup ("a" -/ "b") MapFlagTag $ { "a"/Map: { "b"/Flag: Flag False } } -- pseudo
-- Just (MapFlag (Flag False))
xlookup :: MapPath -> MapEntryTag -> Map -> Maybe MapEntry
xlookup (MapPath (e :| [])) tag (Map m) = M.lookup (MapField tag e) m
xlookup (MapPath (e :| (r:rs))) tag (Map m)
| Just (MapMap m') <- inner = xlookup (MapPath (r :| rs)) tag m'
| otherwise = Nothing
where inner = M.lookup (MapField MapMapTag e) m
-- | Registers can be set to a value
--
-- >>> RegisterSet "foo"
data RegisterOp = RegisterSet !ByteString deriving (Eq,Show)
-- | Flags can be enabled / disabled
--
-- >>> FlagSet True
data FlagOp = FlagSet !Bool deriving (Eq,Show)
-- | Flags can only be held as a 'Map' element.
--
-- Flag can be set or unset
--
-- >>> Flag False
newtype Flag = Flag Bool deriving (Eq,Ord,Show,Generic)
instance NFData Flag
-- | Last-wins monoid for 'Flag'
instance Monoid Flag where
mempty = Flag False
mappend = (<>)
-- | Last-wins semigroup for 'Flag'
instance Semigroup Flag where
a <> b = getLast (Last a <> Last b)
instance Default Flag where
def = mempty
-- | Registers can only be held as a 'Map' element.
--
-- Register holds a 'ByteString'.
newtype Register = Register ByteString deriving (Eq,Show,Generic)
instance NFData Register
-- | Last-wins monoid for 'Register'
instance Monoid Register where
mempty = Register ""
mappend = (<>)
instance Semigroup Register where
a <> b = getLast (Last a <> Last b)
instance Default Register where
def = mempty
-- | Operations on map values
data MapValueOp = MapCounterOp !CounterOp
| MapSetOp !SetOp
| MapRegisterOp !RegisterOp
| MapFlagOp !FlagOp
| MapMapOp !MapOp
deriving (Eq,Show)
-- | CRDT ADT.
--
-- 'Network.Riak.CRDT.Riak.get' operations return value of this type
data DataType = DTCounter Counter
| DTSet Set
| DTMap Map
deriving (Eq,Show,Generic)
instance NFData DataType
-- | CRDT Set is a Data.Set
--
-- >>> Set (Data.Set.fromList ["foo","bar"])
newtype Set = Set (S.Set ByteString) deriving (Eq,Ord,Show,Generic,Monoid)
instance NFData Set
instance Semigroup Set where
Set a <> Set b = Set (a <> b)
instance Default Set where
def = Set mempty
-- | CRDT Set operations
data SetOp = SetAdd ByteString -- ^ add element to the set
--
-- >>> SetAdd "foo"
| SetRemove ByteString -- ^ remove element from the set
--
-- >>> SetRemove "bar"
deriving (Eq,Show)
setFromSeq :: Seq.Seq ByteString -> Set
setFromSeq = Set . S.fromList . F.toList
-- | CRDT Counter hold a integer 'Count'
--
-- >>> Counter 42
newtype Counter = Counter Count deriving (Eq,Ord,Num,Show,Generic)
type Count = Int64
instance NFData Counter
instance Semigroup Counter where
Counter a <> Counter b = Counter . getSum $ Sum a <> Sum b
instance Monoid Counter where
mempty = Counter 0
mappend = (<>)
instance Default Counter where
def = mempty
-- | Counters can be incremented/decremented
--
-- >>> CounterInc 1
data CounterOp = CounterInc !Count deriving (Eq,Show)
instance Semigroup CounterOp where
CounterInc x <> CounterInc y = CounterInc . getSum $ Sum x <> Sum y
instance Monoid CounterOp where
mempty = CounterInc 0
CounterInc x `mappend` CounterInc y = CounterInc . getSum $ Sum x <> Sum y
|
tmcgilchrist/riak-haskell-client
|
riak/src/Network/Riak/CRDT/Types.hs
|
apache-2.0
| 7,791
| 0
| 11
| 1,963
| 1,787
| 1,006
| 781
| 169
| 1
|
{-# LANGUAGE ScopedTypeVariables #-}
-----------------------------------------------------------------------------
-- |
-- Module : Network.HTTP.Base
-- Copyright : See LICENSE file
-- License : BSD
--
-- Maintainer : Ganesh Sittampalam <http@projects.haskell.org>
-- Stability : experimental
-- Portability : non-portable (not tested)
--
-- Definitions of @Request@ and @Response@ types along with functions
-- for normalizing them. It is assumed to be an internal module; user
-- code should, if possible, import @Network.HTTP@ to access the functionality
-- that this module provides.
--
-- Additionally, the module exports internal functions for working with URLs,
-- and for handling the processing of requests and responses coming back.
--
-----------------------------------------------------------------------------
module Network.HTTP.Base
(
-- ** Constants
httpVersion -- :: String
-- ** HTTP
, Request(..)
, Response(..)
, RequestMethod(..)
, Request_String
, Response_String
, HTTPRequest
, HTTPResponse
-- ** URL Encoding
, urlEncode
, urlDecode
, urlEncodeVars
-- ** URI authority parsing
, URIAuthority(..)
, parseURIAuthority
-- internal
, uriToAuthorityString -- :: URI -> String
, uriAuthToString -- :: URIAuth -> String
, uriAuthPort -- :: Maybe URI -> URIAuth -> Int
, reqURIAuth -- :: Request ty -> URIAuth
, parseResponseHead -- :: [String] -> Result ResponseData
, parseRequestHead -- :: [String] -> Result RequestData
, ResponseNextStep(..)
, matchResponse
, ResponseData
, ResponseCode
, RequestData
, NormalizeRequestOptions(..)
, defaultNormalizeRequestOptions -- :: NormalizeRequestOptions ty
, RequestNormalizer
, normalizeRequest -- :: NormalizeRequestOptions ty -> Request ty -> Request ty
, splitRequestURI
, getAuth
, normalizeRequestURI
, normalizeHostHeader
, findConnClose
-- internal export (for the use by Network.HTTP.{Stream,ByteStream} )
, linearTransfer
, hopefulTransfer
, chunkedTransfer
, uglyDeathTransfer
, readTillEmpty1
, readTillEmpty2
, defaultGETRequest
, defaultGETRequest_
, mkRequest
, setRequestBody
, defaultUserAgent
, httpPackageVersion
, libUA {- backwards compatibility, will disappear..soon -}
, catchIO
, catchIO_
, responseParseError
, getRequestVersion
, getResponseVersion
, setRequestVersion
, setResponseVersion
, failHTTPS
) where
import Network.URI
( URI(uriAuthority, uriPath, uriScheme)
, URIAuth(URIAuth, uriUserInfo, uriRegName, uriPort)
, parseURIReference
)
import Control.Monad ( guard )
import Control.Monad.Error ()
import Data.Bits ( (.&.), (.|.), shiftL, shiftR )
import Data.Word ( Word8 )
import Data.Char ( digitToInt, intToDigit, toLower, isDigit,
isAscii, isAlphaNum, ord, chr )
import Data.List ( partition, find )
import Data.Maybe ( listToMaybe, fromMaybe )
import Numeric ( readHex )
import Network.Stream
import Network.BufferType ( BufferOp(..), BufferType(..) )
import Network.HTTP.Headers
import Network.HTTP.Utils ( trim, crlf, sp, readsOne )
import Text.Read.Lex (readDecP)
import Text.ParserCombinators.ReadP
( ReadP, readP_to_S, char, (<++), look, munch )
import Control.Exception as Exception (catch, IOException)
import qualified Paths_HTTP as Self (version)
import Data.Version (showVersion)
-----------------------------------------------------------------
------------------ URI Authority parsing ------------------------
-----------------------------------------------------------------
data URIAuthority = URIAuthority { user :: Maybe String,
password :: Maybe String,
host :: String,
port :: Maybe Int
} deriving (Eq,Show)
-- | Parse the authority part of a URL.
--
-- > RFC 1732, section 3.1:
-- >
-- > //<user>:<password>@<host>:<port>/<url-path>
-- > Some or all of the parts "<user>:<password>@", ":<password>",
-- > ":<port>", and "/<url-path>" may be excluded.
parseURIAuthority :: String -> Maybe URIAuthority
parseURIAuthority s = listToMaybe (map fst (readP_to_S pURIAuthority s))
pURIAuthority :: ReadP URIAuthority
pURIAuthority = do
(u,pw) <- (pUserInfo `before` char '@')
<++ return (Nothing, Nothing)
h <- munch (/=':')
p <- orNothing (char ':' >> readDecP)
look >>= guard . null
return URIAuthority{ user=u, password=pw, host=h, port=p }
pUserInfo :: ReadP (Maybe String, Maybe String)
pUserInfo = do
u <- orNothing (munch (`notElem` ":@"))
p <- orNothing (char ':' >> munch (/='@'))
return (u,p)
before :: Monad m => m a -> m b -> m a
before a b = a >>= \x -> b >> return x
orNothing :: ReadP a -> ReadP (Maybe a)
orNothing p = fmap Just p <++ return Nothing
-- This function duplicates old Network.URI.authority behaviour.
uriToAuthorityString :: URI -> String
uriToAuthorityString u = maybe "" uriAuthToString (uriAuthority u)
uriAuthToString :: URIAuth -> String
uriAuthToString ua =
concat [ uriUserInfo ua
, uriRegName ua
, uriPort ua
]
uriAuthPort :: Maybe URI -> URIAuth -> Int
uriAuthPort mbURI u =
case uriPort u of
(':':s) -> readsOne id (default_port mbURI) s
_ -> default_port mbURI
where
default_port Nothing = default_http
default_port (Just url) =
case map toLower $ uriScheme url of
"http:" -> default_http
"https:" -> default_https
-- todo: refine
_ -> default_http
default_http = 80
default_https = 443
failHTTPS :: Monad m => URI -> m ()
failHTTPS uri
| map toLower (uriScheme uri) == "https:" = fail "https not supported"
| otherwise = return ()
-- Fish out the authority from a possibly normalized Request, i.e.,
-- the information may either be in the request's URI or inside
-- the Host: header.
reqURIAuth :: Request ty -> URIAuth
reqURIAuth req =
case uriAuthority (rqURI req) of
Just ua -> ua
_ -> case lookupHeader HdrHost (rqHeaders req) of
Nothing -> error ("reqURIAuth: no URI authority for: " ++ show req)
Just h ->
case toHostPort h of
(ht,p) -> URIAuth { uriUserInfo = ""
, uriRegName = ht
, uriPort = p
}
where
-- Note: just in case you're wondering..the convention is to include the ':'
-- in the port part..
toHostPort h = break (==':') h
-----------------------------------------------------------------
------------------ HTTP Messages --------------------------------
-----------------------------------------------------------------
-- Protocol version
httpVersion :: String
httpVersion = "HTTP/1.1"
-- | The HTTP request method, to be used in the 'Request' object.
-- We are missing a few of the stranger methods, but these are
-- not really necessary until we add full TLS.
data RequestMethod = HEAD | PUT | GET | POST | DELETE | OPTIONS | TRACE | CONNECT | Custom String
deriving(Eq)
instance Show RequestMethod where
show x =
case x of
HEAD -> "HEAD"
PUT -> "PUT"
GET -> "GET"
POST -> "POST"
DELETE -> "DELETE"
OPTIONS -> "OPTIONS"
TRACE -> "TRACE"
CONNECT -> "CONNECT"
Custom c -> c
rqMethodMap :: [(String, RequestMethod)]
rqMethodMap = [("HEAD", HEAD),
("PUT", PUT),
("GET", GET),
("POST", POST),
("DELETE", DELETE),
("OPTIONS", OPTIONS),
("TRACE", TRACE),
("CONNECT", CONNECT)]
--
-- for backwards-ish compatibility; suggest
-- migrating to new Req/Resp by adding type param.
--
type Request_String = Request String
type Response_String = Response String
-- Hmm..I really want to use these for the record
-- type, but it will upset codebases wanting to
-- migrate (and live with using pre-HTTPbis versions.)
type HTTPRequest a = Request a
type HTTPResponse a = Response a
-- | An HTTP Request.
-- The 'Show' instance of this type is used for message serialisation,
-- which means no body data is output.
data Request a =
Request { rqURI :: URI -- ^ might need changing in future
-- 1) to support '*' uri in OPTIONS request
-- 2) transparent support for both relative
-- & absolute uris, although this should
-- already work (leave scheme & host parts empty).
, rqMethod :: RequestMethod
, rqHeaders :: [Header]
, rqBody :: a
}
-- Notice that request body is not included,
-- this show function is used to serialise
-- a request for the transport link, we send
-- the body separately where possible.
instance Show (Request a) where
show req@(Request u m h _) =
show m ++ sp ++ alt_uri ++ sp ++ ver ++ crlf
++ foldr (++) [] (map show (dropHttpVersion h)) ++ crlf
where
ver = fromMaybe httpVersion (getRequestVersion req)
alt_uri = show $ if null (uriPath u) || head (uriPath u) /= '/'
then u { uriPath = '/' : uriPath u }
else u
instance HasHeaders (Request a) where
getHeaders = rqHeaders
setHeaders rq hdrs = rq { rqHeaders=hdrs }
-- | For easy pattern matching, HTTP response codes @xyz@ are
-- represented as @(x,y,z)@.
type ResponseCode = (Int,Int,Int)
-- | @ResponseData@ contains the head of a response payload;
-- HTTP response code, accompanying text description + header
-- fields.
type ResponseData = (ResponseCode,String,[Header])
-- | @RequestData@ contains the head of a HTTP request; method,
-- its URL along with the auxillary/supporting header data.
type RequestData = (RequestMethod,URI,[Header])
-- | An HTTP Response.
-- The 'Show' instance of this type is used for message serialisation,
-- which means no body data is output, additionally the output will
-- show an HTTP version of 1.1 instead of the actual version returned
-- by a server.
data Response a =
Response { rspCode :: ResponseCode
, rspReason :: String
, rspHeaders :: [Header]
, rspBody :: a
}
-- This is an invalid representation of a received response,
-- since we have made the assumption that all responses are HTTP/1.1
instance Show (Response a) where
show rsp@(Response (a,b,c) reason headers _) =
ver ++ ' ' : map intToDigit [a,b,c] ++ ' ' : reason ++ crlf
++ foldr (++) [] (map show (dropHttpVersion headers)) ++ crlf
where
ver = fromMaybe httpVersion (getResponseVersion rsp)
instance HasHeaders (Response a) where
getHeaders = rspHeaders
setHeaders rsp hdrs = rsp { rspHeaders=hdrs }
------------------------------------------------------------------
------------------ Request Building ------------------------------
------------------------------------------------------------------
-- | Deprecated. Use 'defaultUserAgent'
libUA :: String
libUA = "hs-HTTP-4000.0.9"
{-# DEPRECATED libUA "Use defaultUserAgent instead (but note the user agent name change)" #-}
-- | A default user agent string. The string is @\"haskell-HTTP/$version\"@
-- where @$version@ is the version of this HTTP package.
--
defaultUserAgent :: String
defaultUserAgent = "haskell-HTTP/" ++ httpPackageVersion
-- | The version of this HTTP package as a string, e.g. @\"4000.1.2\"@. This
-- may be useful to include in a user agent string so that you can determine
-- from server logs what version of this package HTTP clients are using.
-- This can be useful for tracking down HTTP compatibility quirks.
--
httpPackageVersion :: String
httpPackageVersion = showVersion Self.version
defaultGETRequest :: URI -> Request_String
defaultGETRequest uri = defaultGETRequest_ uri
defaultGETRequest_ :: BufferType a => URI -> Request a
defaultGETRequest_ uri = mkRequest GET uri
-- | 'mkRequest method uri' constructs a well formed
-- request for the given HTTP method and URI. It does not
-- normalize the URI for the request _nor_ add the required
-- Host: header. That is done either explicitly by the user
-- or when requests are normalized prior to transmission.
mkRequest :: BufferType ty => RequestMethod -> URI -> Request ty
mkRequest meth uri = req
where
req =
Request { rqURI = uri
, rqBody = empty
, rqHeaders = [ Header HdrContentLength "0"
, Header HdrUserAgent defaultUserAgent
]
, rqMethod = meth
}
empty = buf_empty (toBufOps req)
-- set rqBody, Content-Type and Content-Length headers.
setRequestBody :: Request_String -> (String, String) -> Request_String
setRequestBody req (typ, body) = req' { rqBody=body }
where
req' = replaceHeader HdrContentType typ .
replaceHeader HdrContentLength (show $ length body) $
req
{-
-- stub out the user info.
updAuth = fmap (\ x -> x{uriUserInfo=""}) (uriAuthority uri)
withHost =
case uriToAuthorityString uri{uriAuthority=updAuth} of
"" -> id
h -> ((Header HdrHost h):)
uri_req
| forProxy = uri
| otherwise = snd (splitRequestURI uri)
-}
toBufOps :: BufferType a => Request a -> BufferOp a
toBufOps _ = bufferOps
-----------------------------------------------------------------
------------------ Parsing --------------------------------------
-----------------------------------------------------------------
-- Parsing a request
parseRequestHead :: [String] -> Result RequestData
parseRequestHead [] = Left ErrorClosed
parseRequestHead (com:hdrs) = do
(version,rqm,uri) <- requestCommand com (words com)
hdrs' <- parseHeaders hdrs
return (rqm,uri,withVer version hdrs')
where
withVer [] hs = hs
withVer (h:_) hs = withVersion h hs
requestCommand l _yes@(rqm:uri:version) =
case (parseURIReference uri, lookup rqm rqMethodMap) of
(Just u, Just r) -> return (version,r,u)
(Just u, Nothing) -> return (version,Custom rqm,u)
_ -> parse_err l
requestCommand l _
| null l = failWith ErrorClosed
| otherwise = parse_err l
parse_err l = responseParseError "parseRequestHead"
("Request command line parse failure: " ++ l)
-- Parsing a response
parseResponseHead :: [String] -> Result ResponseData
parseResponseHead [] = failWith ErrorClosed
parseResponseHead (sts:hdrs) = do
(version,code,reason) <- responseStatus sts (words sts)
hdrs' <- parseHeaders hdrs
return (code,reason, withVersion version hdrs')
where
responseStatus _l _yes@(version:code:reason) =
return (version,match code,concatMap (++" ") reason)
responseStatus l _no
| null l = failWith ErrorClosed -- an assumption
| otherwise = parse_err l
parse_err l =
responseParseError
"parseResponseHead"
("Response status line parse failure: " ++ l)
match [a,b,c] = (digitToInt a,
digitToInt b,
digitToInt c)
match _ = (-1,-1,-1) -- will create appropriate behaviour
-- To avoid changing the @RequestData@ and @ResponseData@ types
-- just for this (and the upstream backwards compat. woes that
-- will result in), encode version info as a custom header.
-- Used by 'parseResponseData' and 'parseRequestData'.
--
-- Note: the Request and Response types do not currently represent
-- the version info explicitly in their record types. You have to use
-- {get,set}{Request,Response}Version for that.
withVersion :: String -> [Header] -> [Header]
withVersion v hs
| v == httpVersion = hs -- don't bother adding it if the default.
| otherwise = (Header (HdrCustom "X-HTTP-Version") v) : hs
-- | @getRequestVersion req@ returns the HTTP protocol version of
-- the request @req@. If @Nothing@, the default 'httpVersion' can be assumed.
getRequestVersion :: Request a -> Maybe String
getRequestVersion r = getHttpVersion r
-- | @setRequestVersion v req@ returns a new request, identical to
-- @req@, but with its HTTP version set to @v@.
setRequestVersion :: String -> Request a -> Request a
setRequestVersion s r = setHttpVersion r s
-- | @getResponseVersion rsp@ returns the HTTP protocol version of
-- the response @rsp@. If @Nothing@, the default 'httpVersion' can be
-- assumed.
getResponseVersion :: Response a -> Maybe String
getResponseVersion r = getHttpVersion r
-- | @setResponseVersion v rsp@ returns a new response, identical to
-- @rsp@, but with its HTTP version set to @v@.
setResponseVersion :: String -> Response a -> Response a
setResponseVersion s r = setHttpVersion r s
-- internal functions for accessing HTTP-version info in
-- requests and responses. Not exported as it exposes ho
-- version info is represented internally.
getHttpVersion :: HasHeaders a => a -> Maybe String
getHttpVersion r =
fmap toVersion $
find isHttpVersion $
getHeaders r
where
toVersion (Header _ x) = x
setHttpVersion :: HasHeaders a => a -> String -> a
setHttpVersion r v =
setHeaders r $
withVersion v $
dropHttpVersion $
getHeaders r
dropHttpVersion :: [Header] -> [Header]
dropHttpVersion hs = filter (not.isHttpVersion) hs
isHttpVersion :: Header -> Bool
isHttpVersion (Header (HdrCustom "X-HTTP-Version") _) = True
isHttpVersion _ = False
-----------------------------------------------------------------
------------------ HTTP Send / Recv ----------------------------------
-----------------------------------------------------------------
data ResponseNextStep
= Continue
| Retry
| Done
| ExpectEntity
| DieHorribly String
matchResponse :: RequestMethod -> ResponseCode -> ResponseNextStep
matchResponse rqst rsp =
case rsp of
(1,0,0) -> Continue
(1,0,1) -> Done -- upgrade to TLS
(1,_,_) -> Continue -- default
(2,0,4) -> Done
(2,0,5) -> Done
(2,_,_) -> ans
(3,0,4) -> Done
(3,0,5) -> Done
(3,_,_) -> ans
(4,1,7) -> Retry -- Expectation failed
(4,_,_) -> ans
(5,_,_) -> ans
(a,b,c) -> DieHorribly ("Response code " ++ map intToDigit [a,b,c] ++ " not recognised")
where
ans | rqst == HEAD = Done
| otherwise = ExpectEntity
-----------------------------------------------------------------
------------------ A little friendly funtionality ---------------
-----------------------------------------------------------------
{-
I had a quick look around but couldn't find any RFC about
the encoding of data on the query string. I did find an
IETF memo, however, so this is how I justify the urlEncode
and urlDecode methods.
Doc name: draft-tiwari-appl-wxxx-forms-01.txt (look on www.ietf.org)
Reserved chars: ";", "/", "?", ":", "@", "&", "=", "+", ",", and "$" are reserved.
Unwise: "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"
URI delims: "<" | ">" | "#" | "%" | <">
Unallowed ASCII: <US-ASCII coded characters 00-1F and 7F hexadecimal>
<US-ASCII coded character 20 hexadecimal>
Also unallowed: any non-us-ascii character
Escape method: char -> '%' a b where a, b :: Hex digits
-}
replacement_character :: Char
replacement_character = '\xfffd'
-- | Encode a single Haskell Char to a list of Word8 values, in UTF8 format.
--
-- Shamelessly stolen from utf-8string-0.3.7
encodeChar :: Char -> [Word8]
encodeChar = map fromIntegral . go . ord
where
go oc
| oc <= 0x7f = [oc]
| oc <= 0x7ff = [ 0xc0 + (oc `shiftR` 6)
, 0x80 + oc .&. 0x3f
]
| oc <= 0xffff = [ 0xe0 + (oc `shiftR` 12)
, 0x80 + ((oc `shiftR` 6) .&. 0x3f)
, 0x80 + oc .&. 0x3f
]
| otherwise = [ 0xf0 + (oc `shiftR` 18)
, 0x80 + ((oc `shiftR` 12) .&. 0x3f)
, 0x80 + ((oc `shiftR` 6) .&. 0x3f)
, 0x80 + oc .&. 0x3f
]
-- | Decode a UTF8 string packed into a list of Word8 values, directly to String
--
-- Shamelessly stolen from utf-8string-0.3.7
decode :: [Word8] -> String
decode [ ] = ""
decode (c:cs)
| c < 0x80 = chr (fromEnum c) : decode cs
| c < 0xc0 = replacement_character : decode cs
| c < 0xe0 = multi1
| c < 0xf0 = multi_byte 2 0xf 0x800
| c < 0xf8 = multi_byte 3 0x7 0x10000
| c < 0xfc = multi_byte 4 0x3 0x200000
| c < 0xfe = multi_byte 5 0x1 0x4000000
| otherwise = replacement_character : decode cs
where
multi1 = case cs of
c1 : ds | c1 .&. 0xc0 == 0x80 ->
let d = ((fromEnum c .&. 0x1f) `shiftL` 6) .|. fromEnum (c1 .&. 0x3f)
in if d >= 0x000080 then toEnum d : decode ds
else replacement_character : decode ds
_ -> replacement_character : decode cs
multi_byte :: Int -> Word8 -> Int -> [Char]
multi_byte i mask overlong = aux i cs (fromEnum (c .&. mask))
where
aux 0 rs acc
| overlong <= acc && acc <= 0x10ffff &&
(acc < 0xd800 || 0xdfff < acc) &&
(acc < 0xfffe || 0xffff < acc) = chr acc : decode rs
| otherwise = replacement_character : decode rs
aux n (r:rs) acc
| r .&. 0xc0 == 0x80 = aux (n-1) rs
$ shiftL acc 6 .|. fromEnum (r .&. 0x3f)
aux _ rs _ = replacement_character : decode rs
-- This function is a bit funny because potentially the input String could contain some actual Unicode
-- characters (though this shouldn't happen for most use cases), so we have to preserve those characters
-- while simultaneously decoding any UTF-8 data
urlDecode :: String -> String
urlDecode = go []
where
go bs ('%':a:b:rest) = go (fromIntegral (16 * digitToInt a + digitToInt b) : bs) rest
go bs (h:t) | fromEnum h < 256 = go (fromIntegral (fromEnum h) : bs) t -- Treat ASCII as just another byte of UTF-8
go [] [] = []
go [] (h:t) = h : go [] t -- h >= 256, so can't be part of any UTF-8 byte sequence
go bs rest = decode (reverse bs) ++ go [] rest
urlEncode :: String -> String
urlEncode [] = []
urlEncode (ch:t)
| (isAscii ch && isAlphaNum ch) || ch `elem` "-_.~" = ch : urlEncode t
| not (isAscii ch) = foldr escape (urlEncode t) (encodeChar ch)
| otherwise = escape (fromIntegral (fromEnum ch)) (urlEncode t)
where
escape b rs = '%':showH (b `div` 16) (showH (b `mod` 16) rs)
showH :: Word8 -> String -> String
showH x xs
| x <= 9 = to (o_0 + x) : xs
| otherwise = to (o_A + (x-10)) : xs
where
to = toEnum . fromIntegral
fro = fromIntegral . fromEnum
o_0 = fro '0'
o_A = fro 'A'
-- Encode form variables, useable in either the
-- query part of a URI, or the body of a POST request.
-- I have no source for this information except experience,
-- this sort of encoding worked fine in CGI programming.
urlEncodeVars :: [(String,String)] -> String
urlEncodeVars ((n,v):t) =
let (same,diff) = partition ((==n) . fst) t
in urlEncode n ++ '=' : foldl (\x y -> x ++ ',' : urlEncode y) (urlEncode $ v) (map snd same)
++ urlEncodeRest diff
where urlEncodeRest [] = []
urlEncodeRest diff = '&' : urlEncodeVars diff
urlEncodeVars [] = []
-- | @getAuth req@ fishes out the authority portion of the URL in a request's @Host@
-- header.
getAuth :: Monad m => Request ty -> m URIAuthority
getAuth r =
-- ToDo: verify that Network.URI functionality doesn't take care of this (now.)
case parseURIAuthority auth of
Just x -> return x
Nothing -> fail $ "Network.HTTP.Base.getAuth: Error parsing URI authority '" ++ auth ++ "'"
where
auth = maybe (uriToAuthorityString uri) id (findHeader HdrHost r)
uri = rqURI r
{-# DEPRECATED normalizeRequestURI "Please use Network.HTTP.Base.normalizeRequest instead" #-}
normalizeRequestURI :: Bool{-do close-} -> {-URI-}String -> Request ty -> Request ty
normalizeRequestURI doClose h r =
(if doClose then replaceHeader HdrConnection "close" else id) $
insertHeaderIfMissing HdrHost h $
r { rqURI = (rqURI r){ uriScheme = ""
, uriAuthority = Nothing
}}
-- | @NormalizeRequestOptions@ brings together the various defaulting\/normalization options
-- over 'Request's. Use 'defaultNormalizeRequestOptions' for the standard selection of option
data NormalizeRequestOptions ty
= NormalizeRequestOptions
{ normDoClose :: Bool
, normForProxy :: Bool
, normUserAgent :: Maybe String
, normCustoms :: [RequestNormalizer ty]
}
-- | @RequestNormalizer@ is the shape of a (pure) function that rewrites
-- a request into some normalized form.
type RequestNormalizer ty = NormalizeRequestOptions ty -> Request ty -> Request ty
defaultNormalizeRequestOptions :: NormalizeRequestOptions ty
defaultNormalizeRequestOptions = NormalizeRequestOptions
{ normDoClose = False
, normForProxy = False
, normUserAgent = Just defaultUserAgent
, normCustoms = []
}
-- | @normalizeRequest opts req@ is the entry point to use to normalize your
-- request prior to transmission (or other use.) Normalization is controlled
-- via the @NormalizeRequestOptions@ record.
normalizeRequest :: NormalizeRequestOptions ty
-> Request ty
-> Request ty
normalizeRequest opts req = foldr (\ f -> f opts) req normalizers
where
--normalizers :: [RequestNormalizer ty]
normalizers =
( normalizeHostURI
: normalizeConnectionClose
: normalizeUserAgent
: normCustoms opts
)
-- | @normalizeUserAgent ua x req@ augments the request @req@ with
-- a @User-Agent: ua@ header if @req@ doesn't already have a
-- a @User-Agent:@ set.
normalizeUserAgent :: RequestNormalizer ty
normalizeUserAgent opts req =
case normUserAgent opts of
Nothing -> req
Just ua ->
case findHeader HdrUserAgent req of
Just u | u /= defaultUserAgent -> req
_ -> replaceHeader HdrUserAgent ua req
-- | @normalizeConnectionClose opts req@ sets the header @Connection: close@
-- to indicate one-shot behavior iff @normDoClose@ is @True@. i.e., it then
-- _replaces_ any an existing @Connection:@ header in @req@.
normalizeConnectionClose :: RequestNormalizer ty
normalizeConnectionClose opts req
| normDoClose opts = replaceHeader HdrConnection "close" req
| otherwise = req
-- | @normalizeHostURI forProxy req@ rewrites your request to have it
-- follow the expected formats by the receiving party (proxy or server.)
--
normalizeHostURI :: RequestNormalizer ty
normalizeHostURI opts req =
case splitRequestURI uri of
("",_uri_abs)
| forProxy ->
case findHeader HdrHost req of
Nothing -> req -- no host/authority in sight..not much we can do.
Just h -> req{rqURI=uri{ uriAuthority=Just URIAuth{uriUserInfo="", uriRegName=hst, uriPort=pNum}
, uriScheme=if (null (uriScheme uri)) then "http" else uriScheme uri
}}
where
hst = case span (/='@') user_hst of
(as,'@':bs) ->
case span (/=':') as of
(_,_:_) -> bs
_ -> user_hst
_ -> user_hst
(user_hst, pNum) =
case span isDigit (reverse h) of
(ds,':':bs) -> (reverse bs, ':':reverse ds)
_ -> (h,"")
| otherwise ->
case findHeader HdrHost req of
Nothing -> req -- no host/authority in sight..not much we can do...complain?
Just{} -> req
(h,uri_abs)
| forProxy -> insertHeaderIfMissing HdrHost h req
| otherwise -> replaceHeader HdrHost h req{rqURI=uri_abs} -- Note: _not_ stubbing out user:pass
where
uri0 = rqURI req
-- stub out the user:pass
uri = uri0{uriAuthority=fmap (\ x -> x{uriUserInfo=""}) (uriAuthority uri0)}
forProxy = normForProxy opts
{- Comments re: above rewriting:
RFC 2616, section 5.1.2:
"The most common form of Request-URI is that used to identify a
resource on an origin server or gateway. In this case the absolute
path of the URI MUST be transmitted (see section 3.2.1, abs_path) as
the Request-URI, and the network location of the URI (authority) MUST
be transmitted in a Host header field."
We assume that this is the case, so we take the host name from
the Host header if there is one, otherwise from the request-URI.
Then we make the request-URI an abs_path and make sure that there
is a Host header.
-}
splitRequestURI :: URI -> ({-authority-}String, URI)
splitRequestURI uri = (uriToAuthorityString uri, uri{uriScheme="", uriAuthority=Nothing})
-- Adds a Host header if one is NOT ALREADY PRESENT..
{-# DEPRECATED normalizeHostHeader "Please use Network.HTTP.Base.normalizeRequest instead" #-}
normalizeHostHeader :: Request ty -> Request ty
normalizeHostHeader rq =
insertHeaderIfMissing HdrHost
(uriToAuthorityString $ rqURI rq)
rq
-- Looks for a "Connection" header with the value "close".
-- Returns True when this is found.
findConnClose :: [Header] -> Bool
findConnClose hdrs =
maybe False
(\ x -> map toLower (trim x) == "close")
(lookupHeader HdrConnection hdrs)
-- | Used when we know exactly how many bytes to expect.
linearTransfer :: (Int -> IO (Result a)) -> Int -> IO (Result ([Header],a))
linearTransfer readBlk n = fmapE (\str -> Right ([],str)) (readBlk n)
-- | Used when nothing about data is known,
-- Unfortunately waiting for a socket closure
-- causes bad behaviour. Here we just
-- take data once and give up the rest.
hopefulTransfer :: BufferOp a
-> IO (Result a)
-> [a]
-> IO (Result ([Header],a))
hopefulTransfer bufOps readL strs
= readL >>=
either (\v -> return $ Left v)
(\more -> if (buf_isEmpty bufOps more)
then return (Right ([],foldr (flip (buf_append bufOps)) (buf_empty bufOps) strs))
else hopefulTransfer bufOps readL (more:strs))
-- | A necessary feature of HTTP\/1.1
-- Also the only transfer variety likely to
-- return any footers.
chunkedTransfer :: BufferOp a
-> IO (Result a)
-> (Int -> IO (Result a))
-> IO (Result ([Header], a))
chunkedTransfer bufOps readL readBlk = chunkedTransferC bufOps readL readBlk [] 0
chunkedTransferC :: BufferOp a
-> IO (Result a)
-> (Int -> IO (Result a))
-> [a]
-> Int
-> IO (Result ([Header], a))
chunkedTransferC bufOps readL readBlk acc n = do
v <- readL
case v of
Left e -> return (Left e)
Right line
| size == 0 ->
-- last chunk read; look for trailing headers..
fmapE (\ strs -> do
ftrs <- parseHeaders (map (buf_toStr bufOps) strs)
-- insert (computed) Content-Length header.
let ftrs' = Header HdrContentLength (show n) : ftrs
return (ftrs',buf_concat bufOps (reverse acc)))
(readTillEmpty2 bufOps readL [])
| otherwise -> do
some <- readBlk size
case some of
Left e -> return (Left e)
Right cdata -> do
_ <- readL -- CRLF is mandated after the chunk block; ToDo: check that the line is empty.?
chunkedTransferC bufOps readL readBlk (cdata:acc) (n+size)
where
size
| buf_isEmpty bufOps line = 0
| otherwise =
case readHex (buf_toStr bufOps line) of
(hx,_):_ -> hx
_ -> 0
-- | Maybe in the future we will have a sensible thing
-- to do here, at that time we might want to change
-- the name.
uglyDeathTransfer :: String -> IO (Result ([Header],a))
uglyDeathTransfer loc = return (responseParseError loc "Unknown Transfer-Encoding")
-- | Remove leading crlfs then call readTillEmpty2 (not required by RFC)
readTillEmpty1 :: BufferOp a
-> IO (Result a)
-> IO (Result [a])
readTillEmpty1 bufOps readL =
readL >>=
either (return . Left)
(\ s ->
if buf_isLineTerm bufOps s
then readTillEmpty1 bufOps readL
else readTillEmpty2 bufOps readL [s])
-- | Read lines until an empty line (CRLF),
-- also accepts a connection close as end of
-- input, which is not an HTTP\/1.1 compliant
-- thing to do - so probably indicates an
-- error condition.
readTillEmpty2 :: BufferOp a
-> IO (Result a)
-> [a]
-> IO (Result [a])
readTillEmpty2 bufOps readL list =
readL >>=
either (return . Left)
(\ s ->
if buf_isLineTerm bufOps s || buf_isEmpty bufOps s
then return (Right $ reverse (s:list))
else readTillEmpty2 bufOps readL (s:list))
--
-- Misc
--
-- | @catchIO a h@ handles IO action exceptions throughout codebase; version-specific
-- tweaks better go here.
catchIO :: IO a -> (IOException -> IO a) -> IO a
catchIO a h = Exception.catch a h
catchIO_ :: IO a -> IO a -> IO a
catchIO_ a h = Exception.catch a (\(_ :: IOException) -> h)
responseParseError :: String -> String -> Result a
responseParseError loc v = failWith (ErrorParse (loc ++ ' ':v))
|
beni55/HTTP
|
Network/HTTP/Base.hs
|
bsd-3-clause
| 33,862
| 777
| 18
| 8,894
| 7,066
| 4,112
| 2,954
| 557
| 13
|
{-# LANGUAGE OverloadedStrings #-}
module Formalize.Internal.Util
( saveAsPdf
, createFormData
, createEmptyFormData
, emptyFlash
) where
import qualified Data.ByteString as BS
import qualified Data.Text as T
import Data.Time.Format
import Data.Time.LocalTime
import Formalize.Internal.Pdf
import Formalize.Types
import System.FilePath
-- Save form data as PDF.
saveAsPdf :: FormData -> FilePath -> IO PDF
saveAsPdf fd path = do
let ts = fdFileTimestamp fd
file <- createPDF fd
BS.writeFile (filename path ts) file
return file
-- Construct form data from input, flash message and timestamp.
createFormData :: FormInput -> FlashMessage -> IO FormData
createFormData fi fm = do
fileTs <- timestamp "%Y%m%d-%H:%M:%S"
humanTs <- T.pack <$> timestamp "%d.%m.%Y"
return $ FormData fi fm fileTs humanTs
createEmptyFormData :: IO FormData
createEmptyFormData = createFormData emptyForm emptyFlash
-- Create timestamp for filename.
timestamp :: String -> IO FilePath
timestamp format = fmap (formatTime defaultTimeLocale format) getZonedTime
-- Generate filename.
filename :: FilePath -> FilePath -> FilePath
filename path ts = path </> ts <.> "pdf"
emptyForm :: FormInput
emptyForm = FormInput "" "" "" "" "" "" "" "" "" "" "" "" ""
emptyFlash :: FlashMessage
emptyFlash = FlashMessage ""
|
thevangelist/Crystallize
|
src/Formalize/Internal/Util.hs
|
bsd-3-clause
| 1,402
| 0
| 10
| 305
| 342
| 179
| 163
| 34
| 1
|
{-
(c) The GRASP Project, Glasgow University, 1994-1998
\section[TysWiredIn]{Wired-in knowledge about {\em non-primitive} types}
-}
{-# LANGUAGE CPP #-}
-- | This module is about types that can be defined in Haskell, but which
-- must be wired into the compiler nonetheless. C.f module TysPrim
module TysWiredIn (
-- * All wired in things
wiredInTyCons, isBuiltInOcc_maybe,
-- * Bool
boolTy, boolTyCon, boolTyCon_RDR, boolTyConName,
trueDataCon, trueDataConId, true_RDR,
falseDataCon, falseDataConId, false_RDR,
promotedBoolTyCon, promotedFalseDataCon, promotedTrueDataCon,
-- * Ordering
ltDataCon, ltDataConId,
eqDataCon, eqDataConId,
gtDataCon, gtDataConId,
promotedOrderingTyCon,
promotedLTDataCon, promotedEQDataCon, promotedGTDataCon,
-- * Char
charTyCon, charDataCon, charTyCon_RDR,
charTy, stringTy, charTyConName,
-- * Double
doubleTyCon, doubleDataCon, doubleTy, doubleTyConName,
-- * Float
floatTyCon, floatDataCon, floatTy, floatTyConName,
-- * Int
intTyCon, intDataCon, intTyCon_RDR, intDataCon_RDR, intTyConName,
intTy,
-- * Word
wordTyCon, wordDataCon, wordTyConName, wordTy,
-- * List
listTyCon, listTyCon_RDR, listTyConName, listTyConKey,
nilDataCon, nilDataConName, nilDataConKey,
consDataCon_RDR, consDataCon, consDataConName,
mkListTy, mkPromotedListTy,
-- * Tuples
mkTupleTy, mkBoxedTupleTy,
tupleTyCon, tupleDataCon, tupleTyConName,
promotedTupleTyCon, promotedTupleDataCon,
unitTyCon, unitDataCon, unitDataConId, unitTy, unitTyConKey,
pairTyCon,
unboxedUnitTyCon, unboxedUnitDataCon,
unboxedSingletonTyCon, unboxedSingletonDataCon,
unboxedPairTyCon, unboxedPairDataCon,
cTupleTyConName, cTupleTyConNames, isCTupleTyConName,
-- * Kinds
typeNatKindCon, typeNatKind, typeSymbolKindCon, typeSymbolKind,
-- * Parallel arrays
mkPArrTy,
parrTyCon, parrFakeCon, isPArrTyCon, isPArrFakeCon,
parrTyCon_RDR, parrTyConName,
-- * Equality predicates
eqTyCon_RDR, eqTyCon, eqTyConName, eqBoxDataCon,
coercibleTyCon, coercibleDataCon, coercibleClass,
mkWiredInTyConName -- This is used in TcTypeNats to define the
-- built-in functions for evaluation.
) where
#include "HsVersions.h"
import {-# SOURCE #-} MkId( mkDataConWorkId )
-- friends:
import PrelNames
import TysPrim
-- others:
import Constants ( mAX_TUPLE_SIZE, mAX_CTUPLE_SIZE )
import Module ( Module )
import Type ( mkTyConApp )
import DataCon
import ConLike
import Var
import TyCon
import Class ( Class, mkClass )
import TypeRep
import RdrName
import Name
import NameSet ( NameSet, mkNameSet, elemNameSet )
import BasicTypes ( Arity, RecFlag(..), Boxity(..),
TupleSort(..) )
import ForeignCall
import Unique ( incrUnique,
mkTupleTyConUnique, mkTupleDataConUnique,
mkCTupleTyConUnique, mkPArrDataConUnique )
import SrcLoc ( noSrcSpan )
import Data.Array
import FastString
import Outputable
import Util
import BooleanFormula ( mkAnd )
alpha_tyvar :: [TyVar]
alpha_tyvar = [alphaTyVar]
alpha_ty :: [Type]
alpha_ty = [alphaTy]
{-
************************************************************************
* *
\subsection{Wired in type constructors}
* *
************************************************************************
If you change which things are wired in, make sure you change their
names in PrelNames, so they use wTcQual, wDataQual, etc
-}
-- This list is used only to define PrelInfo.wiredInThings. That in turn
-- is used to initialise the name environment carried around by the renamer.
-- This means that if we look up the name of a TyCon (or its implicit binders)
-- that occurs in this list that name will be assigned the wired-in key we
-- define here.
--
-- Because of their infinite nature, this list excludes tuples, Any and implicit
-- parameter TyCons. Instead, we have a hack in lookupOrigNameCache to deal with
-- these names.
--
-- See also Note [Known-key names]
wiredInTyCons :: [TyCon]
wiredInTyCons = [ unitTyCon -- Not treated like other tuples, because
-- it's defined in GHC.Base, and there's only
-- one of it. We put it in wiredInTyCons so
-- that it'll pre-populate the name cache, so
-- the special case in lookupOrigNameCache
-- doesn't need to look out for it
, boolTyCon
, charTyCon
, doubleTyCon
, floatTyCon
, intTyCon
, wordTyCon
, listTyCon
, parrTyCon
, eqTyCon
, coercibleTyCon
, typeNatKindCon
, typeSymbolKindCon
]
mkWiredInTyConName :: BuiltInSyntax -> Module -> FastString -> Unique -> TyCon -> Name
mkWiredInTyConName built_in modu fs unique tycon
= mkWiredInName modu (mkTcOccFS fs) unique
(ATyCon tycon) -- Relevant TyCon
built_in
mkWiredInDataConName :: BuiltInSyntax -> Module -> FastString -> Unique -> DataCon -> Name
mkWiredInDataConName built_in modu fs unique datacon
= mkWiredInName modu (mkDataOccFS fs) unique
(AConLike (RealDataCon datacon)) -- Relevant DataCon
built_in
-- See Note [Kind-changing of (~) and Coercible]
eqTyConName, eqBoxDataConName :: Name
eqTyConName = mkWiredInTyConName BuiltInSyntax gHC_TYPES (fsLit "~") eqTyConKey eqTyCon
eqBoxDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "Eq#") eqBoxDataConKey eqBoxDataCon
-- See Note [Kind-changing of (~) and Coercible]
coercibleTyConName, coercibleDataConName :: Name
coercibleTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Coercible") coercibleTyConKey coercibleTyCon
coercibleDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "MkCoercible") coercibleDataConKey coercibleDataCon
charTyConName, charDataConName, intTyConName, intDataConName :: Name
charTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Char") charTyConKey charTyCon
charDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "C#") charDataConKey charDataCon
intTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Int") intTyConKey intTyCon
intDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "I#") intDataConKey intDataCon
boolTyConName, falseDataConName, trueDataConName :: Name
boolTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Bool") boolTyConKey boolTyCon
falseDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "False") falseDataConKey falseDataCon
trueDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "True") trueDataConKey trueDataCon
listTyConName, nilDataConName, consDataConName :: Name
listTyConName = mkWiredInTyConName BuiltInSyntax gHC_TYPES (fsLit "[]") listTyConKey listTyCon
nilDataConName = mkWiredInDataConName BuiltInSyntax gHC_TYPES (fsLit "[]") nilDataConKey nilDataCon
consDataConName = mkWiredInDataConName BuiltInSyntax gHC_TYPES (fsLit ":") consDataConKey consDataCon
wordTyConName, wordDataConName, floatTyConName, floatDataConName, doubleTyConName, doubleDataConName :: Name
wordTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Word") wordTyConKey wordTyCon
wordDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "W#") wordDataConKey wordDataCon
floatTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Float") floatTyConKey floatTyCon
floatDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "F#") floatDataConKey floatDataCon
doubleTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Double") doubleTyConKey doubleTyCon
doubleDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "D#") doubleDataConKey doubleDataCon
-- Kinds
typeNatKindConName, typeSymbolKindConName :: Name
typeNatKindConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Nat") typeNatKindConNameKey typeNatKindCon
typeSymbolKindConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Symbol") typeSymbolKindConNameKey typeSymbolKindCon
parrTyConName, parrDataConName :: Name
parrTyConName = mkWiredInTyConName BuiltInSyntax
gHC_PARR' (fsLit "[::]") parrTyConKey parrTyCon
parrDataConName = mkWiredInDataConName UserSyntax
gHC_PARR' (fsLit "PArr") parrDataConKey parrDataCon
boolTyCon_RDR, false_RDR, true_RDR, intTyCon_RDR, charTyCon_RDR,
intDataCon_RDR, listTyCon_RDR, consDataCon_RDR, parrTyCon_RDR, eqTyCon_RDR :: RdrName
boolTyCon_RDR = nameRdrName boolTyConName
false_RDR = nameRdrName falseDataConName
true_RDR = nameRdrName trueDataConName
intTyCon_RDR = nameRdrName intTyConName
charTyCon_RDR = nameRdrName charTyConName
intDataCon_RDR = nameRdrName intDataConName
listTyCon_RDR = nameRdrName listTyConName
consDataCon_RDR = nameRdrName consDataConName
parrTyCon_RDR = nameRdrName parrTyConName
eqTyCon_RDR = nameRdrName eqTyConName
{-
************************************************************************
* *
\subsection{mkWiredInTyCon}
* *
************************************************************************
-}
pcNonRecDataTyCon :: Name -> Maybe CType -> [TyVar] -> [DataCon] -> TyCon
-- Not an enumeration, not promotable
pcNonRecDataTyCon = pcTyCon False NonRecursive False
-- This function assumes that the types it creates have all parameters at
-- Representational role!
pcTyCon :: Bool -> RecFlag -> Bool -> Name -> Maybe CType -> [TyVar] -> [DataCon] -> TyCon
pcTyCon is_enum is_rec is_prom name cType tyvars cons
= buildAlgTyCon name
tyvars
(map (const Representational) tyvars)
cType
[] -- No stupid theta
(DataTyCon cons is_enum)
is_rec
is_prom
False -- Not in GADT syntax
NoParentTyCon
pcDataCon :: Name -> [TyVar] -> [Type] -> TyCon -> DataCon
pcDataCon = pcDataConWithFixity False
pcDataConWithFixity :: Bool -> Name -> [TyVar] -> [Type] -> TyCon -> DataCon
pcDataConWithFixity infx n = pcDataConWithFixity' infx n (incrUnique (nameUnique n))
-- The Name's unique is the first of two free uniques;
-- the first is used for the datacon itself,
-- the second is used for the "worker name"
--
-- To support this the mkPreludeDataConUnique function "allocates"
-- one DataCon unique per pair of Ints.
pcDataConWithFixity' :: Bool -> Name -> Unique -> [TyVar] -> [Type] -> TyCon -> DataCon
-- The Name should be in the DataName name space; it's the name
-- of the DataCon itself.
pcDataConWithFixity' declared_infix dc_name wrk_key tyvars arg_tys tycon
= data_con
where
data_con = mkDataCon dc_name declared_infix
(map (const HsNoBang) arg_tys)
[] -- No labelled fields
tyvars
[] -- No existential type variables
[] -- No equality spec
[] -- No theta
arg_tys (mkTyConApp tycon (mkTyVarTys tyvars))
tycon
[] -- No stupid theta
(mkDataConWorkId wrk_name data_con)
NoDataConRep -- Wired-in types are too simple to need wrappers
modu = ASSERT( isExternalName dc_name )
nameModule dc_name
wrk_occ = mkDataConWorkerOcc (nameOccName dc_name)
wrk_name = mkWiredInName modu wrk_occ wrk_key
(AnId (dataConWorkId data_con)) UserSyntax
{-
************************************************************************
* *
Kinds
* *
************************************************************************
-}
typeNatKindCon, typeSymbolKindCon :: TyCon
-- data Nat
-- data Symbol
typeNatKindCon = pcTyCon False NonRecursive True typeNatKindConName Nothing [] []
typeSymbolKindCon = pcTyCon False NonRecursive True typeSymbolKindConName Nothing [] []
typeNatKind, typeSymbolKind :: Kind
typeNatKind = TyConApp (promoteTyCon typeNatKindCon) []
typeSymbolKind = TyConApp (promoteTyCon typeSymbolKindCon) []
{-
************************************************************************
* *
Stuff for dealing with tuples
* *
************************************************************************
Note [How tuples work] See also Note [Known-key names] in PrelNames
~~~~~~~~~~~~~~~~~~~~~~
* There are three families of tuple TyCons and corresponding
DataCons, expressed by the type BasicTypes.TupleSort:
data TupleSort = BoxedTuple | UnboxedTuple | ConstraintTuple
* All three families are AlgTyCons, whose AlgTyConRhs is TupleTyCon
* BoxedTuples
- A wired-in type
- Data type declarations in GHC.Tuple
- The data constructors really have an info table
* UnboxedTuples
- A wired-in type
- Have a pretend DataCon, defined in GHC.Prim,
but no actual declaration and no info table
* ConstraintTuples
- Are known-key rather than wired-in. Reason: it's awkward to
have all the superclass selectors wired-in.
- Declared as classes in GHC.Classes, e.g.
class (c1,c2) => (c1,c2)
- Given constraints: the superclasses automatically become available
- Wanted constraints: there is a built-in instance
instance (c1,c2) => (c1,c2)
- Currently just go up to 16; beyond that
you have to use manual nesting
- Their OccNames look like (%,,,%), so they can easily be
distinguished from term tuples. But (following Haskell) we
pretty-print saturated constraint tuples with round parens; see
BasicTypes.tupleParens.
* In quite a lot of places things are restrcted just to
BoxedTuple/UnboxedTuple, and then we used BasicTypes.Boxity to distinguish
E.g. tupleTyCon has a Boxity argument
* When looking up an OccName in the original-name cache
(IfaceEnv.lookupOrigNameCache), we spot the tuple OccName to make sure
we get the right wired-in name. This guy can't tell the difference
betweeen BoxedTuple and ConstraintTuple (same OccName!), so tuples
are not serialised into interface files using OccNames at all.
-}
isBuiltInOcc_maybe :: OccName -> Maybe Name
-- Built in syntax isn't "in scope" so these OccNames
-- map to wired-in Names with BuiltInSyntax
isBuiltInOcc_maybe occ
= case occNameString occ of
"[]" -> choose_ns listTyConName nilDataConName
":" -> Just consDataConName
"[::]" -> Just parrTyConName
"()" -> tup_name Boxed 0
"(##)" -> tup_name Unboxed 0
'(':',':rest -> parse_tuple Boxed 2 rest
'(':'#':',':rest -> parse_tuple Unboxed 2 rest
_other -> Nothing
where
ns = occNameSpace occ
parse_tuple sort n rest
| (',' : rest2) <- rest = parse_tuple sort (n+1) rest2
| tail_matches sort rest = tup_name sort n
| otherwise = Nothing
tail_matches Boxed ")" = True
tail_matches Unboxed "#)" = True
tail_matches _ _ = False
tup_name boxity arity
= choose_ns (getName (tupleTyCon boxity arity))
(getName (tupleDataCon boxity arity))
choose_ns tc dc
| isTcClsNameSpace ns = Just tc
| isDataConNameSpace ns = Just dc
| otherwise = pprPanic "tup_name" (ppr occ)
mkTupleOcc :: NameSpace -> Boxity -> Arity -> OccName
mkTupleOcc ns sort ar = mkOccName ns str
where
-- No need to cache these, the caching is done in mk_tuple
str = case sort of
Unboxed -> '(' : '#' : commas ++ "#)"
Boxed -> '(' : commas ++ ")"
commas = take (ar-1) (repeat ',')
mkCTupleOcc :: NameSpace -> Arity -> OccName
mkCTupleOcc ns ar = mkOccName ns str
where
str = "(%" ++ commas ++ "%)"
commas = take (ar-1) (repeat ',')
cTupleTyConName :: Arity -> Name
cTupleTyConName arity
= mkExternalName (mkCTupleTyConUnique arity) gHC_CLASSES
(mkCTupleOcc tcName arity) noSrcSpan
-- The corresponding DataCon does not have a known-key name
cTupleTyConNames :: [Name]
cTupleTyConNames = map cTupleTyConName (0 : [2..mAX_CTUPLE_SIZE])
cTupleTyConNameSet :: NameSet
cTupleTyConNameSet = mkNameSet cTupleTyConNames
isCTupleTyConName :: Name -> Bool
isCTupleTyConName n
= ASSERT2( isExternalName n, ppr n )
nameModule n == gHC_CLASSES
&& n `elemNameSet` cTupleTyConNameSet
tupleTyCon :: Boxity -> Arity -> TyCon
tupleTyCon sort i | i > mAX_TUPLE_SIZE = fst (mk_tuple sort i) -- Build one specially
tupleTyCon Boxed i = fst (boxedTupleArr ! i)
tupleTyCon Unboxed i = fst (unboxedTupleArr ! i)
tupleTyConName :: TupleSort -> Arity -> Name
tupleTyConName ConstraintTuple a = cTupleTyConName a
tupleTyConName BoxedTuple a = tyConName (tupleTyCon Boxed a)
tupleTyConName UnboxedTuple a = tyConName (tupleTyCon Unboxed a)
promotedTupleTyCon :: Boxity -> Arity -> TyCon
promotedTupleTyCon boxity i = promoteTyCon (tupleTyCon boxity i)
promotedTupleDataCon :: Boxity -> Arity -> TyCon
promotedTupleDataCon boxity i = promoteDataCon (tupleDataCon boxity i)
tupleDataCon :: Boxity -> Arity -> DataCon
tupleDataCon sort i | i > mAX_TUPLE_SIZE = snd (mk_tuple sort i) -- Build one specially
tupleDataCon Boxed i = snd (boxedTupleArr ! i)
tupleDataCon Unboxed i = snd (unboxedTupleArr ! i)
boxedTupleArr, unboxedTupleArr :: Array Int (TyCon,DataCon)
boxedTupleArr = listArray (0,mAX_TUPLE_SIZE) [mk_tuple Boxed i | i <- [0..mAX_TUPLE_SIZE]]
unboxedTupleArr = listArray (0,mAX_TUPLE_SIZE) [mk_tuple Unboxed i | i <- [0..mAX_TUPLE_SIZE]]
mk_tuple :: Boxity -> Int -> (TyCon,DataCon)
mk_tuple boxity arity = (tycon, tuple_con)
where
tycon = mkTupleTyCon tc_name tc_kind arity tyvars tuple_con
tup_sort
prom_tc NoParentTyCon
tup_sort = case boxity of
Boxed -> BoxedTuple
Unboxed -> UnboxedTuple
prom_tc = case boxity of
Boxed -> Just (mkPromotedTyCon tycon (promoteKind tc_kind))
Unboxed -> Nothing
modu = case boxity of
Boxed -> gHC_TUPLE
Unboxed -> gHC_PRIM
tc_name = mkWiredInName modu (mkTupleOcc tcName boxity arity) tc_uniq
(ATyCon tycon) BuiltInSyntax
tc_kind = mkArrowKinds (map tyVarKind tyvars) res_kind
res_kind = case boxity of
Boxed -> liftedTypeKind
Unboxed -> unliftedTypeKind
tyvars = take arity $ case boxity of
Boxed -> alphaTyVars
Unboxed -> openAlphaTyVars
tuple_con = pcDataCon dc_name tyvars tyvar_tys tycon
tyvar_tys = mkTyVarTys tyvars
dc_name = mkWiredInName modu (mkTupleOcc dataName boxity arity) dc_uniq
(AConLike (RealDataCon tuple_con)) BuiltInSyntax
tc_uniq = mkTupleTyConUnique boxity arity
dc_uniq = mkTupleDataConUnique boxity arity
unitTyCon :: TyCon
unitTyCon = tupleTyCon Boxed 0
unitTyConKey :: Unique
unitTyConKey = getUnique unitTyCon
unitDataCon :: DataCon
unitDataCon = head (tyConDataCons unitTyCon)
unitDataConId :: Id
unitDataConId = dataConWorkId unitDataCon
pairTyCon :: TyCon
pairTyCon = tupleTyCon Boxed 2
unboxedUnitTyCon :: TyCon
unboxedUnitTyCon = tupleTyCon Unboxed 0
unboxedUnitDataCon :: DataCon
unboxedUnitDataCon = tupleDataCon Unboxed 0
unboxedSingletonTyCon :: TyCon
unboxedSingletonTyCon = tupleTyCon Unboxed 1
unboxedSingletonDataCon :: DataCon
unboxedSingletonDataCon = tupleDataCon Unboxed 1
unboxedPairTyCon :: TyCon
unboxedPairTyCon = tupleTyCon Unboxed 2
unboxedPairDataCon :: DataCon
unboxedPairDataCon = tupleDataCon Unboxed 2
{-
************************************************************************
* *
\subsection[TysWiredIn-boxed-prim]{The ``boxed primitive'' types (@Char@, @Int@, etc)}
* *
************************************************************************
-}
eqTyCon :: TyCon
eqTyCon = mkAlgTyCon eqTyConName
(ForAllTy kv $ mkArrowKinds [k, k] constraintKind)
[kv, a, b]
[Nominal, Nominal, Nominal]
Nothing
[] -- No stupid theta
(DataTyCon [eqBoxDataCon] False)
NoParentTyCon
NonRecursive
False
Nothing -- No parent for constraint-kinded types
where
kv = kKiVar
k = mkTyVarTy kv
a:b:_ = tyVarList k
eqBoxDataCon :: DataCon
eqBoxDataCon = pcDataCon eqBoxDataConName args [TyConApp eqPrimTyCon (map mkTyVarTy args)] eqTyCon
where
kv = kKiVar
k = mkTyVarTy kv
a:b:_ = tyVarList k
args = [kv, a, b]
coercibleTyCon :: TyCon
coercibleTyCon = mkClassTyCon
coercibleTyConName kind tvs [Nominal, Representational, Representational]
rhs coercibleClass NonRecursive
where kind = (ForAllTy kv $ mkArrowKinds [k, k] constraintKind)
kv = kKiVar
k = mkTyVarTy kv
a:b:_ = tyVarList k
tvs = [kv, a, b]
rhs = DataTyCon [coercibleDataCon] False
coercibleDataCon :: DataCon
coercibleDataCon = pcDataCon coercibleDataConName args [TyConApp eqReprPrimTyCon (map mkTyVarTy args)] coercibleTyCon
where
kv = kKiVar
k = mkTyVarTy kv
a:b:_ = tyVarList k
args = [kv, a, b]
coercibleClass :: Class
coercibleClass = mkClass (tyConTyVars coercibleTyCon) [] [] [] [] [] (mkAnd []) coercibleTyCon
charTy :: Type
charTy = mkTyConTy charTyCon
charTyCon :: TyCon
charTyCon = pcNonRecDataTyCon charTyConName
(Just (CType "" Nothing (fsLit "HsChar")))
[] [charDataCon]
charDataCon :: DataCon
charDataCon = pcDataCon charDataConName [] [charPrimTy] charTyCon
stringTy :: Type
stringTy = mkListTy charTy -- convenience only
intTy :: Type
intTy = mkTyConTy intTyCon
intTyCon :: TyCon
intTyCon = pcNonRecDataTyCon intTyConName
(Just (CType "" Nothing (fsLit "HsInt"))) []
[intDataCon]
intDataCon :: DataCon
intDataCon = pcDataCon intDataConName [] [intPrimTy] intTyCon
wordTy :: Type
wordTy = mkTyConTy wordTyCon
wordTyCon :: TyCon
wordTyCon = pcNonRecDataTyCon wordTyConName
(Just (CType "" Nothing (fsLit "HsWord"))) []
[wordDataCon]
wordDataCon :: DataCon
wordDataCon = pcDataCon wordDataConName [] [wordPrimTy] wordTyCon
floatTy :: Type
floatTy = mkTyConTy floatTyCon
floatTyCon :: TyCon
floatTyCon = pcNonRecDataTyCon floatTyConName
(Just (CType "" Nothing (fsLit "HsFloat"))) []
[floatDataCon]
floatDataCon :: DataCon
floatDataCon = pcDataCon floatDataConName [] [floatPrimTy] floatTyCon
doubleTy :: Type
doubleTy = mkTyConTy doubleTyCon
doubleTyCon :: TyCon
doubleTyCon = pcNonRecDataTyCon doubleTyConName
(Just (CType "" Nothing (fsLit "HsDouble"))) []
[doubleDataCon]
doubleDataCon :: DataCon
doubleDataCon = pcDataCon doubleDataConName [] [doublePrimTy] doubleTyCon
{-
************************************************************************
* *
\subsection[TysWiredIn-Bool]{The @Bool@ type}
* *
************************************************************************
An ordinary enumeration type, but deeply wired in. There are no
magical operations on @Bool@ (just the regular Prelude code).
{\em BEGIN IDLE SPECULATION BY SIMON}
This is not the only way to encode @Bool@. A more obvious coding makes
@Bool@ just a boxed up version of @Bool#@, like this:
\begin{verbatim}
type Bool# = Int#
data Bool = MkBool Bool#
\end{verbatim}
Unfortunately, this doesn't correspond to what the Report says @Bool@
looks like! Furthermore, we get slightly less efficient code (I
think) with this coding. @gtInt@ would look like this:
\begin{verbatim}
gtInt :: Int -> Int -> Bool
gtInt x y = case x of I# x# ->
case y of I# y# ->
case (gtIntPrim x# y#) of
b# -> MkBool b#
\end{verbatim}
Notice that the result of the @gtIntPrim@ comparison has to be turned
into an integer (here called @b#@), and returned in a @MkBool@ box.
The @if@ expression would compile to this:
\begin{verbatim}
case (gtInt x y) of
MkBool b# -> case b# of { 1# -> e1; 0# -> e2 }
\end{verbatim}
I think this code is a little less efficient than the previous code,
but I'm not certain. At all events, corresponding with the Report is
important. The interesting thing is that the language is expressive
enough to describe more than one alternative; and that a type doesn't
necessarily need to be a straightforwardly boxed version of its
primitive counterpart.
{\em END IDLE SPECULATION BY SIMON}
-}
boolTy :: Type
boolTy = mkTyConTy boolTyCon
boolTyCon :: TyCon
boolTyCon = pcTyCon True NonRecursive True boolTyConName
(Just (CType "" Nothing (fsLit "HsBool")))
[] [falseDataCon, trueDataCon]
falseDataCon, trueDataCon :: DataCon
falseDataCon = pcDataCon falseDataConName [] [] boolTyCon
trueDataCon = pcDataCon trueDataConName [] [] boolTyCon
falseDataConId, trueDataConId :: Id
falseDataConId = dataConWorkId falseDataCon
trueDataConId = dataConWorkId trueDataCon
orderingTyCon :: TyCon
orderingTyCon = pcTyCon True NonRecursive True orderingTyConName Nothing
[] [ltDataCon, eqDataCon, gtDataCon]
ltDataCon, eqDataCon, gtDataCon :: DataCon
ltDataCon = pcDataCon ltDataConName [] [] orderingTyCon
eqDataCon = pcDataCon eqDataConName [] [] orderingTyCon
gtDataCon = pcDataCon gtDataConName [] [] orderingTyCon
ltDataConId, eqDataConId, gtDataConId :: Id
ltDataConId = dataConWorkId ltDataCon
eqDataConId = dataConWorkId eqDataCon
gtDataConId = dataConWorkId gtDataCon
{-
************************************************************************
* *
\subsection[TysWiredIn-List]{The @List@ type (incl ``build'' magic)}
* *
************************************************************************
Special syntax, deeply wired in, but otherwise an ordinary algebraic
data types:
\begin{verbatim}
data [] a = [] | a : (List a)
data () = ()
data (,) a b = (,,) a b
...
\end{verbatim}
-}
mkListTy :: Type -> Type
mkListTy ty = mkTyConApp listTyCon [ty]
listTyCon :: TyCon
listTyCon = pcTyCon False Recursive True
listTyConName Nothing alpha_tyvar [nilDataCon, consDataCon]
mkPromotedListTy :: Type -> Type
mkPromotedListTy ty = mkTyConApp promotedListTyCon [ty]
promotedListTyCon :: TyCon
promotedListTyCon = promoteTyCon listTyCon
nilDataCon :: DataCon
nilDataCon = pcDataCon nilDataConName alpha_tyvar [] listTyCon
consDataCon :: DataCon
consDataCon = pcDataConWithFixity True {- Declared infix -}
consDataConName
alpha_tyvar [alphaTy, mkTyConApp listTyCon alpha_ty] listTyCon
-- Interesting: polymorphic recursion would help here.
-- We can't use (mkListTy alphaTy) in the defn of consDataCon, else mkListTy
-- gets the over-specific type (Type -> Type)
{-
************************************************************************
* *
\subsection[TysWiredIn-Tuples]{The @Tuple@ types}
* *
************************************************************************
The tuple types are definitely magic, because they form an infinite
family.
\begin{itemize}
\item
They have a special family of type constructors, of type @TyCon@
These contain the tycon arity, but don't require a Unique.
\item
They have a special family of constructors, of type
@Id@. Again these contain their arity but don't need a Unique.
\item
There should be a magic way of generating the info tables and
entry code for all tuples.
But at the moment we just compile a Haskell source
file\srcloc{lib/prelude/...} containing declarations like:
\begin{verbatim}
data Tuple0 = Tup0
data Tuple2 a b = Tup2 a b
data Tuple3 a b c = Tup3 a b c
data Tuple4 a b c d = Tup4 a b c d
...
\end{verbatim}
The print-names associated with the magic @Id@s for tuple constructors
``just happen'' to be the same as those generated by these
declarations.
\item
The instance environment should have a magic way to know
that each tuple type is an instances of classes @Eq@, @Ix@, @Ord@ and
so on. \ToDo{Not implemented yet.}
\item
There should also be a way to generate the appropriate code for each
of these instances, but (like the info tables and entry code) it is
done by enumeration\srcloc{lib/prelude/InTup?.hs}.
\end{itemize}
-}
mkTupleTy :: Boxity -> [Type] -> Type
-- Special case for *boxed* 1-tuples, which are represented by the type itself
mkTupleTy Boxed [ty] = ty
mkTupleTy boxity tys = mkTyConApp (tupleTyCon boxity (length tys)) tys
-- | Build the type of a small tuple that holds the specified type of thing
mkBoxedTupleTy :: [Type] -> Type
mkBoxedTupleTy tys = mkTupleTy Boxed tys
unitTy :: Type
unitTy = mkTupleTy Boxed []
{-
************************************************************************
* *
\subsection[TysWiredIn-PArr]{The @[::]@ type}
* *
************************************************************************
Special syntax for parallel arrays needs some wired in definitions.
-}
-- | Construct a type representing the application of the parallel array constructor
mkPArrTy :: Type -> Type
mkPArrTy ty = mkTyConApp parrTyCon [ty]
-- | Represents the type constructor of parallel arrays
--
-- * This must match the definition in @PrelPArr@
--
-- NB: Although the constructor is given here, it will not be accessible in
-- user code as it is not in the environment of any compiled module except
-- @PrelPArr@.
--
parrTyCon :: TyCon
parrTyCon = pcNonRecDataTyCon parrTyConName Nothing alpha_tyvar [parrDataCon]
parrDataCon :: DataCon
parrDataCon = pcDataCon
parrDataConName
alpha_tyvar -- forall'ed type variables
[intTy, -- 1st argument: Int
mkTyConApp -- 2nd argument: Array# a
arrayPrimTyCon
alpha_ty]
parrTyCon
-- | Check whether a type constructor is the constructor for parallel arrays
isPArrTyCon :: TyCon -> Bool
isPArrTyCon tc = tyConName tc == parrTyConName
-- | Fake array constructors
--
-- * These constructors are never really used to represent array values;
-- however, they are very convenient during desugaring (and, in particular,
-- in the pattern matching compiler) to treat array pattern just like
-- yet another constructor pattern
--
parrFakeCon :: Arity -> DataCon
parrFakeCon i | i > mAX_TUPLE_SIZE = mkPArrFakeCon i -- build one specially
parrFakeCon i = parrFakeConArr!i
-- pre-defined set of constructors
--
parrFakeConArr :: Array Int DataCon
parrFakeConArr = array (0, mAX_TUPLE_SIZE) [(i, mkPArrFakeCon i)
| i <- [0..mAX_TUPLE_SIZE]]
-- build a fake parallel array constructor for the given arity
--
mkPArrFakeCon :: Int -> DataCon
mkPArrFakeCon arity = data_con
where
data_con = pcDataCon name [tyvar] tyvarTys parrTyCon
tyvar = head alphaTyVars
tyvarTys = replicate arity $ mkTyVarTy tyvar
nameStr = mkFastString ("MkPArr" ++ show arity)
name = mkWiredInName gHC_PARR' (mkDataOccFS nameStr) unique
(AConLike (RealDataCon data_con)) UserSyntax
unique = mkPArrDataConUnique arity
-- | Checks whether a data constructor is a fake constructor for parallel arrays
isPArrFakeCon :: DataCon -> Bool
isPArrFakeCon dcon = dcon == parrFakeCon (dataConSourceArity dcon)
-- Promoted Booleans
promotedBoolTyCon, promotedFalseDataCon, promotedTrueDataCon :: TyCon
promotedBoolTyCon = promoteTyCon boolTyCon
promotedTrueDataCon = promoteDataCon trueDataCon
promotedFalseDataCon = promoteDataCon falseDataCon
-- Promoted Ordering
promotedOrderingTyCon
, promotedLTDataCon
, promotedEQDataCon
, promotedGTDataCon
:: TyCon
promotedOrderingTyCon = promoteTyCon orderingTyCon
promotedLTDataCon = promoteDataCon ltDataCon
promotedEQDataCon = promoteDataCon eqDataCon
promotedGTDataCon = promoteDataCon gtDataCon
|
fmthoma/ghc
|
compiler/prelude/TysWiredIn.hs
|
bsd-3-clause
| 34,170
| 0
| 14
| 8,985
| 5,385
| 2,942
| 2,443
| 474
| 10
|
{-# LANGUAGE OverloadedStrings #-}
module Css.Post
(postStyles) where
import Clay
import Prelude hiding ((**))
import Css.Constants
-- Post Styles
postStyles :: Css
postStyles = do
body ?
do color grey1
fontWeight $ normal
tabsCSS
postCSS
tabsCSS :: Css
tabsCSS = do
"#posts" & do
fontFamily ["HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", "Lucida Grande"][sansSerif]
fontSize $ (px 17)
width $ pct 97
backgroundColor white
border solid (px 1) grey2
"border-radius" -: "4px"
"box-shadow" -: "0 2px 2px -1px rgba(0, 0, 0, 0.055)"
display block
overflow hidden
margin (px 8) (px 22) (px 8) (px 22)
ul ? do
width $ (pct 100)
margin0
li ? do
"list-style-type" -: "none"
display inlineBlock
width (pct 32)
--textAlign $ alignSide sideCenter
"-webkit-transition" -: "all 0.2s"
"-moz-transition" -: "all 0.2s"
"-ms-transition" -: "all 0.2s"
"-o-transition" -: "all 0.2s"
"transition" -: "all 0.2s"
":hover" & do
"background-color" -: "#9C9C9C !important"
a ? do
"color" -: "white !important"
cursor pointer
a ? do
color black
display inlineBlock
lineHeight (px 50)
paddingLeft (px 24)
width (pct 70)
textDecoration none
".nav_selected" ? do
backgroundColor grey6
".nav_not_selected" ? do
backgroundColor white
".credits_completed" ? do
color green
".credits_not_completed" ? do
color red
postCSS :: Css
postCSS = do
"input" ? do
fontSize (px 14)
"#button_wrapper" ? do
textAlign $ alignSide sideCenter
height (px 50)
paddingLeft (px 20)
"#update" ? do
height (px 40)
fontSize (px 14)
cursor pointer
semiVisible
":hover" & do
fullyVisible
".selected" ? do
".code" ? do
backgroundColor green2
".full_name" ? do
backgroundColor green1
"div" ? do
".code" ? do
backgroundColor beige1
fontFamily ["HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", "Lucida Grande"][sansSerif]
fontSize (px 20)
paddingLeft (px 20)
"box-shadow" -: "0 2px 2px -1px rgba(0, 0, 0, 0.055)"
borderBottom solid (px 1) grey5
lineHeight (px 50)
"list-style-type" -: "none"
textAlign $ alignSide sideCenter
margin0
width (pct 99)
"margin-right" -: "10px"
"-webkit-transition" -: "all 0.2s"
"-moz-transition" -: "all 0.2s"
"-ms-transition" -: "all 0.2s"
"-o-transition" -: "all 0.2s"
"transition" -: "all 0.2s"
".courseName" ? do
display inlineBlock
fontFamily ["HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", "Lucida Grande"][sansSerif]
lineHeight (px 50)
paddingLeft (px 5)
paddingRight (px 5)
cursor pointer
":hover" & do
fontWeight bold
i ? do
color red
"#post_specialist, #post_major, #post_minor" ? do
position absolute
"margin-above" -: "30px"
paddingBottom (px 30)
height (pct 70)
marginLeft (px 25)
width (pct 97)
"#spec_creds, #maj_creds, #min_creds" ? do
display inlineBlock
marginLeft nil
".more-info" ? do
cursor pointer
border solid (px 2) grey3
"border-radius" -: "4px"
backgroundColor grey4
"box-shadow" -: "0 2px 2px -1px rgba(0, 0, 0, 0.055)"
lineHeight (px 40)
"list-style-type" -: "none"
textAlign $ alignSide sideCenter
margin0
display none
"margin-right" -: "10px"
"-webkit-transition" -: "all 0.2s"
"-moz-transition" -: "all 0.2s"
"-ms-transition" -: "all 0.2s"
"-o-transition" -: "all 0.2s"
"transition" -: "all 0.2s"
".info_opened > div" ? do
display block
".full_name" ? do
paddingLeft (px 20)
textAlign $ alignSide sideCenter
margin0
"input" ? do
textAlign $ alignSide sideCenter
height $ (px 40)
"#notes" ? do
textAlign $ alignSide sideCenter
".valid_extra_course" ? do
color green
".not_valid_extra_course" ? do
color red
".post_selected" ? do
display block
".post_not_selected" ? do
display none
|
alexbaluta/courseography
|
app/Css/Post.hs
|
gpl-3.0
| 5,033
| 0
| 24
| 2,003
| 1,248
| 535
| 713
| 154
| 1
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE GADTs #-}
-- This module is full of orphans, unfortunately
module GHCi.TH.Binary () where
import Data.Binary
import qualified Data.ByteString as B
import GHC.Serialized
import qualified Language.Haskell.TH as TH
import qualified Language.Haskell.TH.Syntax as TH
#if !MIN_VERSION_base(4,10,0)
import Data.Typeable
#endif
-- Put these in a separate module because they take ages to compile
instance Binary TH.Loc
instance Binary TH.Name
instance Binary TH.ModName
instance Binary TH.NameFlavour
instance Binary TH.PkgName
instance Binary TH.NameSpace
instance Binary TH.Module
instance Binary TH.Info
instance Binary TH.Type
instance Binary TH.TyLit
instance Binary TH.TyVarBndr
instance Binary TH.Role
instance Binary TH.Lit
instance Binary TH.Range
instance Binary TH.Stmt
instance Binary TH.Pat
instance Binary TH.Exp
instance Binary TH.Dec
instance Binary TH.Overlap
instance Binary TH.DerivClause
instance Binary TH.DerivStrategy
instance Binary TH.Guard
instance Binary TH.Body
instance Binary TH.Match
instance Binary TH.Fixity
instance Binary TH.TySynEqn
instance Binary TH.FamFlavour
instance Binary TH.FunDep
instance Binary TH.AnnTarget
instance Binary TH.RuleBndr
instance Binary TH.Phases
instance Binary TH.RuleMatch
instance Binary TH.Inline
instance Binary TH.Pragma
instance Binary TH.Safety
instance Binary TH.Callconv
instance Binary TH.Foreign
instance Binary TH.Bang
instance Binary TH.SourceUnpackedness
instance Binary TH.SourceStrictness
instance Binary TH.DecidedStrictness
instance Binary TH.FixityDirection
instance Binary TH.OccName
instance Binary TH.Con
instance Binary TH.AnnLookup
instance Binary TH.ModuleInfo
instance Binary TH.Clause
instance Binary TH.InjectivityAnn
instance Binary TH.FamilyResultSig
instance Binary TH.TypeFamilyHead
instance Binary TH.PatSynDir
instance Binary TH.PatSynArgs
-- We need Binary TypeRep for serializing annotations
instance Binary Serialized where
put (Serialized tyrep wds) = put tyrep >> put (B.pack wds)
get = Serialized <$> get <*> (B.unpack <$> get)
-- Typeable and related instances live in binary since GHC 8.2
#if !MIN_VERSION_base(4,10,0)
instance Binary TyCon where
put tc = put (tyConPackage tc) >> put (tyConModule tc) >> put (tyConName tc)
get = mkTyCon3 <$> get <*> get <*> get
instance Binary TypeRep where
put type_rep = put (splitTyConApp type_rep)
get = do
(ty_con, child_type_reps) <- get
return (mkTyConApp ty_con child_type_reps)
#endif
|
ezyang/ghc
|
libraries/ghci/GHCi/TH/Binary.hs
|
bsd-3-clause
| 2,651
| 0
| 10
| 377
| 723
| 352
| 371
| 76
| 0
|
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Program.Ar
-- Copyright : Duncan Coutts 2009
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This module provides an library interface to the @ar@ program.
module Distribution.Simple.Program.Ar (
createArLibArchive,
multiStageProgramInvocation
) where
import Control.Monad (when, unless)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.Char (isSpace)
import Distribution.Compat.CopyFile (filesEqual)
import Distribution.Simple.LocalBuildInfo (LocalBuildInfo(..))
import Distribution.Simple.Program
( arProgram, requireProgram )
import Distribution.Simple.Program.Run
( programInvocation, multiStageProgramInvocation
, runProgramInvocation )
import qualified Distribution.Simple.Program.Strip as Strip
( stripLib )
import Distribution.Simple.Utils
( dieWithLocation, withTempDirectory )
import Distribution.System
( Arch(..), OS(..), Platform(..) )
import Distribution.Verbosity
( Verbosity, deafening, verbose )
import System.Directory (doesFileExist, renameFile)
import System.FilePath ((</>), splitFileName)
import System.IO
( Handle, IOMode(ReadWriteMode), SeekMode(AbsoluteSeek)
, hFileSize, hSeek, withBinaryFile )
-- | Call @ar@ to create a library archive from a bunch of object files.
--
createArLibArchive :: Verbosity -> LocalBuildInfo
-> FilePath -> [FilePath] -> IO ()
createArLibArchive verbosity lbi targetPath files = do
(ar, _) <- requireProgram verbosity arProgram progConf
let (targetDir, targetName) = splitFileName targetPath
withTempDirectory verbosity targetDir "objs" $ \ tmpDir -> do
let tmpPath = tmpDir </> targetName
-- The args to use with "ar" are actually rather subtle and system-dependent.
-- In particular we have the following issues:
--
-- -- On OS X, "ar q" does not make an archive index. Archives with no
-- index cannot be used.
--
-- -- GNU "ar r" will not let us add duplicate objects, only "ar q" lets us
-- do that. We have duplicates because of modules like "A.M" and "B.M"
-- both make an object file "M.o" and ar does not consider the directory.
--
-- Our solution is to use "ar r" in the simple case when one call is enough.
-- When we need to call ar multiple times we use "ar q" and for the last
-- call on OSX we use "ar qs" so that it'll make the index.
let simpleArgs = case hostOS of
OSX -> ["-r", "-s"]
_ -> ["-r"]
initialArgs = ["-q"]
finalArgs = case hostOS of
OSX -> ["-q", "-s"]
_ -> ["-q"]
extraArgs = verbosityOpts verbosity ++ [tmpPath]
simple = programInvocation ar (simpleArgs ++ extraArgs)
initial = programInvocation ar (initialArgs ++ extraArgs)
middle = initial
final = programInvocation ar (finalArgs ++ extraArgs)
sequence_
[ runProgramInvocation verbosity inv
| inv <- multiStageProgramInvocation
simple (initial, middle, final) files ]
when stripLib $ Strip.stripLib verbosity platform progConf tmpPath
unless (hostArch == Arm) $ -- See #1537
wipeMetadata tmpPath
equal <- filesEqual tmpPath targetPath
unless equal $ renameFile tmpPath targetPath
where
progConf = withPrograms lbi
stripLib = stripLibs lbi
platform@(Platform hostArch hostOS) = hostPlatform lbi
verbosityOpts v | v >= deafening = ["-v"]
| v >= verbose = []
| otherwise = ["-c"]
-- | @ar@ by default includes various metadata for each object file in their
-- respective headers, so the output can differ for the same inputs, making
-- it difficult to avoid re-linking. GNU @ar@(1) has a deterministic mode
-- (@-D@) flag that always writes zero for the mtime, UID and GID, and 0644
-- for the file mode. However detecting whether @-D@ is supported seems
-- rather harder than just re-implementing this feature.
wipeMetadata :: FilePath -> IO ()
wipeMetadata path = do
-- Check for existence first (ReadWriteMode would create one otherwise)
exists <- doesFileExist path
unless exists $ wipeError "Temporary file disappeared"
withBinaryFile path ReadWriteMode $ \ h -> hFileSize h >>= wipeArchive h
where
wipeError msg = dieWithLocation path Nothing $
"Distribution.Simple.Program.Ar.wipeMetadata: " ++ msg
archLF = "!<arch>\x0a" -- global magic, 8 bytes
x60LF = "\x60\x0a" -- header magic, 2 bytes
metadata = BS.concat
[ "0 " -- mtime, 12 bytes
, "0 " -- UID, 6 bytes
, "0 " -- GID, 6 bytes
, "0644 " -- mode, 8 bytes
]
headerSize :: Int
headerSize = 60
-- http://en.wikipedia.org/wiki/Ar_(Unix)#File_format_details
wipeArchive :: Handle -> Integer -> IO ()
wipeArchive h archiveSize = do
global <- BS.hGet h (BS.length archLF)
unless (global == archLF) $ wipeError "Bad global header"
wipeHeader (toInteger $ BS.length archLF)
where
wipeHeader :: Integer -> IO ()
wipeHeader offset = case compare offset archiveSize of
EQ -> return ()
GT -> wipeError (atOffset "Archive truncated")
LT -> do
header <- BS.hGet h headerSize
unless (BS.length header == headerSize) $
wipeError (atOffset "Short header")
let magic = BS.drop 58 header
unless (magic == x60LF) . wipeError . atOffset $
"Bad magic " ++ show magic ++ " in header"
let name = BS.take 16 header
let size = BS.take 10 $ BS.drop 48 header
objSize <- case reads (BS8.unpack size) of
[(n, s)] | all isSpace s -> return n
_ -> wipeError (atOffset "Bad file size in header")
let replacement = BS.concat [ name, metadata, size, magic ]
unless (BS.length replacement == headerSize) $
wipeError (atOffset "Something has gone terribly wrong")
hSeek h AbsoluteSeek offset
BS.hPut h replacement
let nextHeader = offset + toInteger headerSize +
-- Odd objects are padded with an extra '\x0a'
if odd objSize then objSize + 1 else objSize
hSeek h AbsoluteSeek nextHeader
wipeHeader nextHeader
where
atOffset msg = msg ++ " at offset " ++ show offset
|
fugyk/cabal
|
Cabal/Distribution/Simple/Program/Ar.hs
|
bsd-3-clause
| 6,773
| 0
| 21
| 1,884
| 1,381
| 732
| 649
| -1
| -1
|
-- Test newtype derived instances
newtype Age = MkAge Int deriving (Eq, Show)
instance Num Age where
(+) (MkAge a) (MkAge b) = MkAge (a+b)
(*) = undefined
negate = undefined
abs = undefined
signum = undefined
fromInteger = undefined
main = print (MkAge 3 + MkAge 5)
|
ghc-android/ghc
|
testsuite/tests/deriving/should_run/drvrun001.hs
|
bsd-3-clause
| 307
| 0
| 8
| 89
| 111
| 61
| 50
| 9
| 1
|
{-# LANGUAGE TypeFamilies #-}
module J2S.Game.Mock where
import Control.Applicative
import Control.Monad.Except
import Control.Monad.Identity
import Control.Monad.Trans.Except
import qualified Data.List.NonEmpty as NE
import Numeric.Natural
import Test.QuickCheck
import qualified J2S as J
data MockGame
= MockGame
{ players :: [J.Player MockGame]
, board :: Integer
, boardActions :: NE.NonEmpty (J.Action MockGame, Either EndMockGame MockGame) }
deriving (Eq, Show, Read)
data EndMockGame = EndMockGame { finalBoard :: Integer }
deriving (Eq, Show, Read)
data instance J.Err MockGame = Err ()
type instance J.Inter MockGame = Identity
type instance J.Action MockGame = Int
type instance J.End MockGame = EndMockGame
type instance J.Player MockGame = Natural
instance J.Game MockGame where
nextPlayer = head . players
executeAction b a = maybe (throwError $ Err ()) return
. lookup a . NE.toList $ boardActions b
informAction = const $ const $ except
askAction = const . const $ return 42
informOnError = const $ return ()
instance J.ListableActions MockGame where
actions = fmap fst . boardActions
instance Arbitrary MockGame where
arbitrary = do
n <- fromIntegral . getPositive <$> (arbitrary :: Gen (Positive Int))
gameForN n
instance Arbitrary EndMockGame where
arbitrary = EndMockGame <$> arbitrary
gameForN :: Natural -> Gen MockGame
gameForN n = MockGame
<$> (replicate <$> arbitrary <*> elements [0.. pred n])
<*> arbitrary
<*> ((NE.:|) <$> arbitrary <*> arbitrary)
|
berewt/J2S
|
test/J2S/Game/Mock.hs
|
mit
| 1,699
| 0
| 13
| 438
| 490
| 267
| 223
| 43
| 1
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Handler.Repo where
import Data.ElmPackage
import Data.PersistSemVer
import Data.SemVer (toText)
import Database.Esqueleto
import Handler.Common
import Import.App hiding (Value, groupBy, on)
import qualified Import.App as Prelude
import Text.Blaze (toMarkup)
getRepoR :: RepoId -> Handler Html
getRepoR repoId = do
(versions, repo) <-
runDB $ do
repo <- get404 repoId
versions <-
select $
from $ \version -> do
where_ $ version ^. RepoVersionRepo ==. val repoId
orderBy [desc $ version ^. RepoVersionVersion]
pure version
pure (versions, repo)
defaultLayout $ do
setTitle $
toMarkup $
fromMaybe (repoGitUrl repo) $ gitUrlToLibraryName $ repoGitUrl repo
[whamlet|
<div .container>
<div .row>
<div .col-lg-4 .col-md-4 .col-sm-6 .col-xs-12>
<div .panel.panel-default>
<div .panel-heading>
<h3 .panel-title>Tags
<table .table .table-striped .table-responsive>
$forall Entity _ version <- versions
<tr>
<td align="right">
<a href=@{RepoVersionR (repoVersionRepo version) (repoVersionTag version)}>
<span .label.#{labelForVersion $ repoVersionVersion version}>
#{toText $ repoVersionVersion version}
<td>
<a href=@{RepoVersionR (repoVersionRepo version) (repoVersionTag version)}>
#{tshow $ utctDay $ repoVersionCommittedAt version}
|]
data SubmissionForm = SubmissionForm
{ gitUrl :: Text
} deriving (Show)
submissionForm :: Form SubmissionForm
submissionForm =
renderBootstrap3 BootstrapBasicForm $
SubmissionForm <$> areq textField (bfs ("Git URL" :: Text)) Nothing
getReposR :: Handler Html
getReposR = do
elmVersion <- lookupRequestedElmVersion
(widget, enctype) <- generateFormPost submissionForm
repos <-
fmap
(Prelude.groupBy
(Prelude.on (==) (\(Entity repoId _, _, _) -> repoId))) $
runDB $
select $
from $ \(r `LeftOuterJoin` rv `LeftOuterJoin` p) -> do
on $ rv ?. RepoVersionId ==. p ?. PackageRepoVersion
on $
(just (r ^. RepoId) ==. rv ?. RepoVersionRepo) &&.
(rv ?. RepoVersionVersion ==. maxRepoVersion elmVersion r)
orderBy [asc $ r ^. RepoGitUrl]
pure (r, rv, p ?. PackageSummary)
isLoggedIn <- isJust <$> maybeAuth
repoClass <- newIdent
versionClass <- newIdent
repoNameClass <- newIdent
listClass <- newIdent
defaultLayout $ do
setTitle "Elm Repositories"
[whamlet|
<div .container>
<div .row>
<div .col-md-6>
<p>
This is a list of all the repositories which we
check for new versions.
<p>
Note that we list the repositories below according to
where we actually found them, not necessarily what is
declared in the <code>repository</code> field of an
<code>elm-package.json</code> file. For a list that
is based on the <code>repository</code> field, see the
<a href="@{LibrariesR}">libraries page</a>.
<div .col-md-6>
<p>
If you have published a package to the
<a href="http://package.elm-lang.org">official Elm package site</a>,
then your repository should appear here automatically
(eventually -- we check about once per day).
<p>
If you'd like to add a repository here manually,
you can do so using the form below, by submitting a
Git URL that looks something like the examples.
That is the URL we will use to fetch your package
via operations such as `git ls-remote` and `git
clone`.
$if isLoggedIn
<p>
<form method=post action=@{ReposR} enctype=#{enctype}>
^{widget}
<button type="submit" .btn .btn-default>Submit Git URL to monitor
$else
<p>
<a href="@{AuthR LoginR}">Login</a> to submit a Git URL for us to monitor.
<div .row .text-center>
^{elmVersionWidget}
<div .row>
<div .col-lg-12 .#{listClass}>
$forall byRepo <- repos
$forall (Entity repoId repo, rv, _) <- listToMaybe byRepo
$if Prelude.isJust rv || Prelude.isNothing elmVersion
<div .#{repoClass}>
<a href=@{RepoR repoId} .#{repoNameClass}>
#{repoGitUrl repo}
$forall (_, version, Value summary) <- byRepo
$forall Entity _ v <- version
<div .#{versionClass}>
<a href="@{RepoVersionR (repoVersionRepo v) (repoVersionTag v)}">
<span .label.#{labelForVersion $ repoVersionVersion v}>
#{toText $ repoVersionVersion v}
$forall s <- summary
<a href="@{RepoVersionR (repoVersionRepo v) (repoVersionTag v)}">
#{s}
$else
<span>
|]
toWidget
[cassius|
.#{listClass}
margin-top: 1em
.#{repoClass}
margin-top: 0.5em
a:visited, a:link
color: black
.#{repoNameClass}
font-weight: bold
.#{versionClass}
margin-left: 2em
.label
position: relative
top: -1px
|]
postReposR :: Handler Html
postReposR = do
((result, _), _) <- runFormPost submissionForm
case result of
FormSuccess submittedForm -> do
currentUser <- requireAuthId
let repo =
Repo
{ repoGitUrl = gitUrl submittedForm
, repoSubmittedBy = Just currentUser
}
repoId <- runDB (insert repo)
setMessage $ toHtml ("Repo saved" :: Text)
redirect $ RepoR repoId
FormMissing -> do
setMessage $ toHtml ("Form data was missing" :: Text)
redirect ReposR
FormFailure err -> do
setMessage $
toHtml ("Invalid input, let's try again: " ++ tshow err)
redirect ReposR
|
rgrempel/frelm.org
|
src/Handler/Repo.hs
|
mit
| 8,192
| 0
| 20
| 3,881
| 795
| 407
| 388
| 86
| 3
|
{-# htermination toInteger :: Int -> Integer #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_toInteger_1.hs
|
mit
| 49
| 0
| 2
| 8
| 3
| 2
| 1
| 1
| 0
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
module CountdownGame.Spiel.Phasen
( SpielParameter (..)
, Phasen (..)
, Versuche
, Ergebnisse, Ergebnis (..)
, startGameLoop
, versuchHinzufuegen
)where
import GHC.Generics (Generic)
import Control.Concurrent.Async (Async, async, wait, poll, asyncThreadId, waitBoth)
import Control.Concurrent (forkIO, threadDelay, ThreadId)
import Data.Aeson (ToJSON)
import Data.Function (on)
import Data.Int (Int64)
import Data.IORef (IORef(..), newIORef, readIORef, atomicModifyIORef')
import Data.List (sortBy)
import qualified Data.Map.Strict as M
import Data.Text (Text)
import Data.Time (UTCTime, NominalDiffTime, getCurrentTime, addUTCTime)
import CountdownGame.References
import CountdownGame.Database (ConnectionPool, insertChallange)
import Countdown.Game (Attempt, AttemptsMap, Challange)
import qualified Countdown.Game as G
-- $doc
-- Es gibt zwei Zustände:
--
-- - warten auf den Begin der nächsten Runde
-- - die Runde läuft
--
-- Beide Zustände laufen nur eine bestimmte Zeitland und
-- wechseln dann in den jeweils anderen Zustand
--
-- Während des Wartens wird zusätzlich die Challange für die nächste
-- Runde berechnet und die Ergebnise der letzen Runde (falls vorhanden)
-- sind verfügbar.
-- Am Ende dieser Wartezeit ist ist die nächste Challange verfügbar
--
-- Während einer Runde ist die aktuelle Challange verfügbar und die
-- Spieler können ihre Attempts schicken (die gespeichert werden)
-- Am Ende dieser Phase sind die Ergebnise der Runde verfügbar
data SpielParameter =
SpielParameter
{ warteZeit :: NominalDiffTime
, rundenZeit :: NominalDiffTime
}
data Phasen
= Start
| WartePhase
{ startNaechsteRunde :: UTCTime
, letzteErgebnisse :: Ergebnisse
, naechsteChallange :: Async Challange }
| RundePhase
{ endeRunde :: UTCTime
, aufgabe :: Challange
, spielerVersuche :: Versuche
, databaseKey :: Int64
, ergebnisse :: Async Ergebnisse }
startGameLoop :: ConnectionPool -> SpielParameter -> IO (Reference Phasen)
startGameLoop pool params = do
ref <- createRef Start
_ <- forkIO $ gameLoop pool params [] ref
return ref
type Versuche = Reference AttemptsMap
versuchHinzufuegen :: Reference Phasen -> (Int64 -> G.PlayerId -> Int -> IO ()) -> G.Player -> Text -> IO (Maybe Attempt)
versuchHinzufuegen ref saveScore p f = do
phase <- readRef id ref
case phase of
(RundePhase _ chal vers key _) -> do
v <- modifyRef (G.attempt chal f p) vers
saveScore key (G.playerId p) (G.score v)
return $ Just v
_ -> return Nothing
type Ergebnisse = [Ergebnis]
data Ergebnis =
Ergebnis
{ name :: Text
, score :: Int
, value :: Maybe Int
, difference :: Maybe Int
, formula :: Text
} deriving (Generic, Show)
instance ToJSON Ergebnis
berechneErgebnisse :: AttemptsMap -> Ergebnisse
berechneErgebnisse attMap =
sortBy (compare `on` (negate . score)) scores
where
scores = map calcScore . M.toList $ attMap
calcScore (_, att) =
Ergebnis (G.nickName $ G.fromPlayer att) (G.score att) (G.value att) (G.difference att) (G.formula att)
gameLoop :: ConnectionPool -> SpielParameter -> Ergebnisse -> Reference Phasen -> IO ()
gameLoop pool params ltErg phase = do
warten <- wartePhase params ltErg
modifyRef (const (warten, ())) phase
aufg <- wait . naechsteChallange $ warten
runde <- rundenPhase pool params aufg
modifyRef (const (runde, ())) phase
erg <- wait . ergebnisse $ runde
gameLoop pool params erg phase
wartePhase :: SpielParameter -> Ergebnisse -> IO Phasen
wartePhase params ltErg = do
wartenBis <- (warteZeit params `addUTCTime`) <$> getCurrentTime
start <- async $ warteStart wartenBis
return $ WartePhase wartenBis ltErg start
warteStart :: UTCTime -> IO Challange
warteStart startZeit = do
neue <- async G.generateChallange
warte <- async $ warteBis startZeit
(chal, _) <- waitBoth neue warte
return chal
rundenPhase :: ConnectionPool -> SpielParameter -> Challange -> IO Phasen
rundenPhase pool params chal = do
chId <- insertChallange pool chal
rundeBis <- (rundenZeit params `addUTCTime`) <$> getCurrentTime
vers <- createRef M.empty
erg <- async $ warteErgebnise rundeBis chal vers
return $ RundePhase rundeBis chal vers chId erg
warteErgebnise :: UTCTime -> Challange -> Versuche -> IO Ergebnisse
warteErgebnise endeZeit aufg refVers = do
warteBis endeZeit
readRef berechneErgebnisse refVers
warteBis :: UTCTime -> IO ()
warteBis zeit = do
now <- getCurrentTime
if now < zeit then do
threadDelay 250000
warteBis zeit
else return ()
|
CarstenKoenig/Countdown
|
src/web/CountdownGame/Spiel/Phasen.hs
|
mit
| 4,728
| 0
| 16
| 969
| 1,325
| 702
| 623
| 109
| 2
|
module LogicProblem.Solver.SDef (
SolveResult(..)
, SolveInnerResult(..)
, solveResult
, hasFinished
) where
import LogicProblem.Solver.Def
import LogicProblem.Solver.Hypotheses
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
data SolveInnerResult r e = NewHypotheses (HypothesesLevel r e)
| FallbackRequired [RuleResult (r e) e]
| RulesApplied [RuleResult (r e) e]
| CanDoNothing
| Stopped
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
data SolveResult r e = SolveFinish (SolveInnerResult r e)
| SolveFailure (SolveInnerResult r e)
solveResult (SolveFinish res) = res
solveResult (SolveFailure res) = res
hasFinished (SolveFinish _) = True
hasFinished _ = False
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
|
fehu/h-logic-einstein
|
src/LogicProblem/Solver/SDef.hs
|
mit
| 1,006
| 0
| 10
| 319
| 189
| 109
| 80
| 18
| 1
|
{-# LANGUAGE FlexibleContexts, GADTs, TypeFamilies, ViewPatterns, RankNTypes #-}
module BiFlux.Trans.Translation where
import Lang.AST as BiGUL
import Lang.MonadBiGULError
import Control.Monad
import Control.Monad.Except
import GHC.InOut
import BiFlux.Lang.AST as BiFlux
import BiFlux.DTD.Type as BType
import Text.PrettyPrint
import qualified BiFlux.XPath.HXT.XPathDataTypes as XPath hiding (Name(..),Env(..))
import Text.XML.HaXml.DtdToHaskell.TypeDef hiding (List,Maybe,List1,Any,String,mkAtt)
import Text.XML.HXT.DOM.QualifiedName
import Data.Map as Map
import BiFlux.Trans.Patterns (inferAstType)
stmt2bigul :: (MonadError Doc m, MonadError' ErrorInfo m') => Stmt -> Type s -> Type v -> DynRPat -> DirectionEnv -> TypeEnv -> m (BiGUL m' s v)
---- example 1. update $book in $s/book by ... for view ... where $book/year > 2012
---- example 2. update $book in $s/book by ... for view p[$v1, $v2] in $v where $v1 := $v2
---- In summarise, whereConds is either a conjunction of where conditons on source or view dependency bindings.
---- whereConds shall be passed into, and decide how to do the translation later.
stmt2bigul (StmtUpd upd whereConds) ts tv dynRPat dirEnv typeEnv = update2bigul upd whereConds ts tv dynRPat dirEnv typeEnv
update2bigul :: (MonadError Doc m, MonadError' ErrorInfo m') => Upd -> [WhereCond] -> Type s -> Type v -> DynRPat -> DirectionEnv -> TypeEnv -> m (BiGUL m' s v)
-- example 1. REPLACE $s/a WITH <b>{$v}</b>
-- SingleReplace Nothing (CPathSlash (CPathVar "$s") (CPathString "a")) (XQElem "b" (XQPath (CPathVar "$v")))
-- Version 0.1: ignore whereConds
-- Computation Steps:
-- Step 1. CPath to UPat
-- Step 2. (Maybe Pat) to UPat
-- Step 3. XQExpr -> Rearr
-- Step 4. Replace
-- Comment: Step 2 and Step 3 shall be combined together.
update2bigul (SingleReplace Nothing cpath xqexpr ) whereConds ts tv dynRPat dirEnv typeEnv = undefined
-- CUPat ts' fupat <- cpath2UPat ts tv typeEnv
--update2bigul (SingleReplace (Just pat) cpath xqexpr ) whereConds ts tv dynRPat dirEnv typeEnv = undefined
-- exist a s', and a UPat m' s' v, we could compute UPat m' s v.
-- not all s' is accetable.
data CUPat m m' s v where
CUPat :: Type s' -> (forall v'. Eq v' => Type v' -> UPat m' s' v' -> Expr v v' -> m (UPatExprTuple m' s v)) -> CUPat m m' s v
data UPatExprTuple m' s v where
UPatExprTuple :: Eq v'' => Type v'' -> UPat m' s v'' -> Expr v v'' -> UPatExprTuple m' s v
cpath2UPat :: (MonadError Doc m, MonadError' ErrorInfo m') => CPath -> Type s -> Type v -> TypeEnv -> m (CUPat m m' s v)
cpath2UPat CPathSelf ts tv typeEnv =
return $ CUPat ts (\tv' upat' expr' -> return (UPatExprTuple tv' upat' expr'))
cpath2UPat CPathChild (Data _ subts) tv typeEnv =
return $ CUPat subts (\tv' upat' expr' -> return (UPatExprTuple tv' (UOut upat') expr'))
cpath2UPat CPathAttribute (Tag (isAtt -> True) subts) tv typeEnv =
return $ CUPat subts (\tv' upat' expr' -> return (UPatExprTuple tv' upat' expr'))
cpath2UPat CPathDoS _ _ _ = throwError $ text "CPathDoS not support yet"
cpath2UPat (CPathNodeTest nt) ts tv typeEnv = cpathNodeTest2UPat nt ts tv
cpath2UPat p@(CPathSlash p1 p2) ts tv typeEnv =
catchError
(do
CUPat ts1' bigf1 <- cpath2UPat p1 ts tv typeEnv
CUPat ts2' bigf2 <- cpath2UPat p2 ts1' tv typeEnv
return $ CUPat ts2' (\tv' upat' expr' -> do
UPatExprTuple tv2' upat2' expr2' <- bigf2 tv' upat' expr'
bigf1 tv2' upat2' expr2'
)
)
(\e -> throwError $ text "CPathSlash error on left hand" <+> text (show e))
cpath2UPat (CPathFilter expr) ts tv typeEnv = throwError $ text "CPathFilter not supported yet"
cpath2UPat (CPathVar var ) ts tv typeEnv =
case Map.lookup var typeEnv of
Just (DynT ts') -> case teq ts ts' of
Just BType.Eq -> return $ CUPat ts (\tv' upat' expr' -> return(UPatExprTuple tv' upat' expr'))
Nothing -> throwError $ text "CPathVar type mismatch"
Nothing -> throwError $ text "CPathVar cannot find var in typeEnv"
cpath2UPat (CPathString str ) ts tv typeEnv =
case teq ts BType.String of
Just BType.Eq -> return $ CUPat ts (\tv' upat' expr' -> return (UPatExprTuple tv' upat' expr'))
Nothing -> throwError $ text "CPathString: source type shall be String."
cpath2UPat (CPathBool b ) ts tv typeEnv =
case teq ts BType.Bool of
Just BType.Eq -> return $ CUPat ts (\tv' upat' expr' -> return (UPatExprTuple tv' upat' expr'))
Nothing -> throwError $ text "CPathBool: source type shall be Bool."
cpath2UPat (CPathSnapshot pat cpath) ts ts' bigul' = throwError $ text "CPathSnapshot not supported yet"
cpath2UPat (CPathFct _ _) _ _ _ = throwError $ text "CPath function call unsupported"
cpath2UPat (CPathIndex int ) ts ts' bigul' =
case ts of
BType.List ta -> throwError $ text "CPathIndex: not supported yet" --TODO
BType.List1 ta -> throwError $ text "CPathIndex: not supported yet" --TODO
_ -> throwError $ text "CPathIndex: source shall be a list type"
cpathNodeTest2UPat :: (MonadError Doc m, MonadError' ErrorInfo m') => XPath.NodeTest -> Type s -> Type v -> m (CUPat m m' s v)
-- NameTest for Data Name is just a filter, nothing else.
-- Previously, I wrote UOut, not correct.
-- $s/a is CPathVar "$s"/ CPathChild / CPathNodeTest ...
-- In the CPathChild step, we will use UOut.
cpathNodeTest2UPat (XPath.NameTest qname) ts@(Data (Name dtdName _) subts) tv =
if qualifiedName qname == dtdName
then return $ CUPat ts (\tv' upat' expr' -> return (UPatExprTuple tv' (upat') expr'))
else throwError $ text "NameTest: name not match"
cpathNodeTest2UPat ntqname@(XPath.NameTest qname) (Either ta tb) tv =
catchError
( do
CUPat ts' bigf <- cpathNodeTest2UPat ntqname ta tv
return $ CUPat ts' (\tv' upat' expr' -> liftM (\(UPatExprTuple tv'' upat'' expr'') -> UPatExprTuple tv'' (ULeft upat'') expr'') (bigf tv' upat' expr'))
)
(\e -> do
CUPat ts' bigf <- cpathNodeTest2UPat ntqname tb tv
return $ CUPat ts' (\tv' upat' expr' -> liftM (\(UPatExprTuple tv'' upat'' expr'') -> UPatExprTuple tv'' (URight upat'') expr'') (bigf tv' upat' expr'))
)
cpathNodeTest2UPat ntqname@(XPath.NameTest qname) (Prod ta tb) tv =
catchError
( do
CUPat ts' bigf <- cpathNodeTest2UPat ntqname ta tv
return $ CUPat ts' (\tv' upat' expr' -> liftM (\(UPatExprTuple tv'' upat'' expr'') -> UPatExprTuple (Prod tv'' One) (UProd upat'' (UVar Skip)) (EProd expr'' (EConst ()))) (bigf tv' upat' expr'))
)
(\e -> do
CUPat ts' bigf <- cpathNodeTest2UPat ntqname tb tv
return $ CUPat ts' (\tv' upat' expr' -> liftM (\(UPatExprTuple tv'' upat'' expr'') -> UPatExprTuple (Prod One tv'') (UProd (UVar Skip) upat'') (EProd (EConst ()) expr'')) (bigf tv' upat' expr'))
)
-- We do not support filter yet.
-- So only if the whole List matches, we put then all into source. Otherwise fail.
-- We also not support complex List type, for example: (a|b)
cpathNodeTest2UPat ntqname@(XPath.NameTest qname) lta@(List ta@(Data (Name dtdName _) subts)) tv =
if qualifiedName qname == dtdName
then return $ CUPat lta (\tv' upat' expr' -> return (UPatExprTuple tv' upat' expr'))
else throwError $ text "CPath NameTest name not match"
cpathNodeTest2UPat ntqname@(XPath.NameTest qname) _ _ = throwError $ text "NameTest type not match"
cpathNodeTest2UPat (XPath.PI str) _ _ = throwError $ text "PI not supported"
cpathNodeTest2UPat (XPath.TypeTest XPath.XPNode) ts tv =
return $ CUPat ts (\tv' upat' expr' -> return (UPatExprTuple tv' upat' expr'))
cpathNodeTest2UPat (XPath.TypeTest XPath.XPCommentNode) _ _ = throwError $ text "XPCommentNode not suppoted"
cpathNodeTest2UPat (XPath.TypeTest XPath.XPPINode) _ _ = throwError $ text "XPINode not support"
cpathNodeTest2UPat (XPath.TypeTest XPath.XPTextNode) ts tv =
return $ CUPat ts (\tv' upat' expr' -> do
case teq tv' String of
Just BType.Eq -> return (UPatExprTuple tv' upat' expr')
_ -> throwError $ text "view expression type shall be String"
)
cpathNodeTest2UPat (XPath.TypeTest XPath.XPString) ts tv =
return $ CUPat ts (\tv' upat' expr' -> do
case teq tv' String of
Just BType.Eq -> return (UPatExprTuple tv' upat' expr')
_ -> throwError $ text "view expression type shall be String"
)
-- in the pattern pat, we need construct the following information for later usage.
data DynDirection where
DynD :: (Eq t, Eq v) => Type v -> Type origin -> Type t -> Direction origin t -> RPat v origin con -> DynDirection
data DynExpr env where
DynE :: (Eq v') => Type v' -> Expr env v' -> DynExpr env
type DirectionEnv = Map.Map String DynDirection
-- I don't know it is correct or not !
data EBiGUL m m' s v where
EBiGUL :: Eq v' => Type v' -> (forall v'. BiGUL m' s v' -> m (BiGUL m' s v)) -> EBiGUL m m' s v
-- | Rearrange XQExpr to a proper type
-- How to construct RPat ?
-- suppose given from existing from Pattern procedure
-- Seems need another env to build the mapping between $v and Direction, so these two are constructed from Pattern.
-- xqexpr2BiGUL :: (MonadError Doc m, MonadError' ErrorInfo m') => XQExpr -> Type v -> RPat v env con -> DirectionEnv -> TypeEnv -> m (EBiGUL m m' s v)
-- xqexpr2BiGUL xqexpr tv rpat directionEnv typeEnv = do
-- DynE tv' expr <- xqexpr2expr xqexpr tv rpat directionEnv typeEnv
-- return $ EBiGUL tv' (\bigul' -> return (Rearr rpat expr bigul'))
xqexpr2expr :: (MonadError Doc m) => XQExpr -> Type v -> RPat v env con -> DirectionEnv -> TypeEnv -> m (DynExpr env)
xqexpr2expr XQEmpty tv rpat directionEnv typeEnv = return $ DynE One (EConst ())
xqexpr2expr (XQProd xqexprl xqexprr) tv rpat directionEnv typeEnv = do
--TODO: split directionEnv according to xqexprl and xqexprr
DynE vl' exprl <- xqexpr2expr xqexprl tv rpat directionEnv typeEnv
DynE vr' exprr <- xqexpr2expr xqexprr tv rpat directionEnv typeEnv
return $ DynE (Prod vl' vr') (EProd exprl exprr)
-- we need 1. type env to find type of n
-- 2. DynE shall wrap the type v', which is used for comparison here.
xqexpr2expr (XQElem n xqexpr) tv rpat directionEnv typeEnv = do
DynE subv' expr <- xqexpr2expr xqexpr tv rpat directionEnv typeEnv
--TODO: there is a problem, how to distinguish source and view type env ?
-- 2. how about list type ? if n points to a Data Name ...; while we need in fact maybe a list type
case Map.lookup n typeEnv of
Just (DynT tv) -> case tv of
Data (Name _ _) subtv -> case teq subv' subtv of
Just BType.Eq -> return $ DynE tv (EIn expr)
Nothing -> throwError $ text "XQElem subelem type mismatch"
otherwise -> throwError $ text "shall not happen"
Nothing -> throwError $ text "cannot find n in typeEnv"
xqexpr2expr (XQAttr str xqexpr) tv rpat directionEnv typeEnv = do
DynE subv' expr <- xqexpr2expr xqexpr tv rpat directionEnv typeEnv
case Map.lookup str typeEnv of
Just (DynT tv) -> case tv of
Tag _ subtv -> case teq subtv subv' of
Just BType.Eq -> return $ DynE tv expr
Nothing -> throwError $ text "XQAttr type mismatch"
otherwise -> throwError $ text "attribute type not match with Tag" --TODO: need check whether having Data case for attr.
Nothing -> throwError $ text "cannot find attribute in typeEnv"
--TODO
xqexpr2expr (XQLet pat xqexpr1 xqexpr2) tv rpat directionEnv typeEnv = throwError $ text "Haven't implemented yet"
--TODO
xqexpr2expr (XQIf xqexpr0 xqexpr1 xqexpr2) tv rpat directionEnv typeEnv = throwError $ text "Haven't implemented yet"
--TODO
xqexpr2expr (XQBinOp op xqexprl xqexprr) tv rpat directionEnv typeEnv = throwError $ text "Haven't implemented yet"
-- TODO
xqexpr2expr (XQFor var xqexprl xqexprr) tv rpat directionEnv typeEnv = throwError $ text "Haven't implemented yet"
xqexpr2expr (XQPath cpath) tv rpat directionEnv typeEnv = cpath2expr cpath tv rpat directionEnv typeEnv
cpath2expr :: (MonadError Doc m) => CPath -> Type v -> RPat v env con -> DirectionEnv -> TypeEnv -> m (DynExpr env)
cpath2expr (CPathVar var) tv rpat directionEnv typeEnv =
case Map.lookup var directionEnv of
Just (DynD tv' tenv' tt d rpat') -> case req tv rpat tv' rpat' of
Just REq -> return $ DynE tt (EDir d)
otherwise -> throwError $ text "wrong direction"
Nothing -> throwError $ text "cannot find var in Direction Env"
cpath2expr _ _ _ _ _ = throwError $ text "other CPath in expr not supported yet"
-- | The following is for judging two RPat is the same.
data REqual a1 a2 b1 b2 c1 c2 where
REq :: REqual a1 a1 b1 b1 c1 c1
req :: MonadPlus m => Type v -> RPat v env con -> Type v' -> RPat v' env' con' -> m (REqual v v' env env' con con')
req tv RVar tv' RVar =
case teq tv tv' of
Just BType.Eq -> return REq
otherwise -> mzero
req tv (RConst c1) tv' (RConst c2) =
case teq tv tv' of
Just BType.Eq -> if c1 == c2 then return REq else mzero
otherwise -> mzero
req tv@(Prod tl tr) (RProd rpatl rpatr) tv'@(Prod tl' tr') (RProd rpatl' rpatr') =
case teq tv tv' of
Just BType.Eq -> do
REq <- req tl rpatl tl' rpatl'
REq <- req tr rpatr tr' rpatr'
return REq
otherwise -> mzero
req tv (RProd rpatl rpatr) tv' (RProd rpatl' rpatr') = mzero
req tv@(Either tl tr) (RLeft rpat) tv'@(Either tl' tr') (RLeft rpat') =
case teq tv tv' of
Just BType.Eq -> do
REq <- req tl rpat tl' rpat'
return REq
otherwise -> mzero
req tv@(Either tl tr) (RRight rpat) tv'@(Either tl' tr') (RRight rpat') =
case teq tv tv' of
Just BType.Eq -> do
REq <- req tr rpat tr' rpat'
return REq
otherwise -> mzero
req tv@(Data (Name dtdName _) subtv) (ROut rpat) tv'@(Data (Name dtdName' _) subtv') (ROut rpat') =
case teq tv tv' of
Just BType.Eq -> do
REq <- req subtv rpat subtv' rpat'
return REq
otherwise -> mzero
-- RElem :: RPat a b c -> RPat [a] b' c' -> RPat [a] (b, b') (c, c')
req tv@(List subtv) (RElem rpath rpatrest) tv'@(List subtv') (RElem rpath' rpatrest') =
case teq tv tv' of
Just BType.Eq -> do
REq <- req subtv rpath subtv' rpath'
REq <- req tv rpatrest tv' rpatrest' -- TODO: I am not sure it will terminated !!!
return REq
otherwise -> mzero
-- Here wrap Type v is for the comparion for PElem
data DynPat where
DynP :: (Eq v', Eq v) => Type v -> Type v' -> BiGUL.Pat v v' -> DynPat
-- | View Pattern handling
-- Translate into: Rearr rPat expr bigul'
-- giving a Pattern, I shall compute:
-- 1. RPat
-- 2. Direction for each view var in expr
-- And suppose you will give me bigul' :: m' s v'.
-- The type of v' is the same with rearranged expr type
-- In summarise, use Pat to construct a Pat and an env for Direction at the same time.
-- Finally, we could compute RPat from Pat, so we do not store RPat here.
viewPat2BigulPat :: (MonadError Doc m, Eq v) => BiFlux.Pat -> Type v -> TypeEnv -> m DynPat
viewPat2BigulPat (SequencePat []) tv typeEnv =
case teq tv One of
Just BType.Eq -> return $ DynP tv One (PConst ())
Nothing -> throwError $ text "view type must be ()"
viewPat2BigulPat (SequencePat (pat : pats)) (Prod th tt) typeEnv = do
DynP th th' ph <- viewPat2BigulPat pat th typeEnv
DynP tt tt' pt <- viewPat2BigulPat pat tt typeEnv
return $ DynP (Prod th tt) (Prod th' tt') (PProd ph pt)
-- if view is a list, there is possibility it is empty and the pattern fails.
viewPat2BigulPat (SequencePat (pat : pats)) ltv@(List tv) typeEnv = do
DynP tv th' ph <- viewPat2BigulPat pat tv typeEnv
DynP ltv@(List tv') tt' pt <- viewPat2BigulPat (SequencePat pats) ltv typeEnv
case teq tv tv' of
Just BType.Eq -> return $ DynP ltv (Prod th' tt') (PElem ph pt)
otherwise -> throwError $ text "list type shall match"
viewPat2BigulPat (SequencePat (pat : pats)) (List1 tv) typeEnv = do
DynP tv th' ph <- viewPat2BigulPat pat tv typeEnv
DynP ltv@(List tv') tt' pt <- viewPat2BigulPat (SequencePat pats) (List tv) typeEnv
case teq tv tv' of
Just BType.Eq -> return $ DynP ltv (Prod th' tt') (PElem ph pt)
otherwise -> throwError $ text "list type shall match"
viewPat2BigulPat (SequencePat (pat : pats)) _ _ = throwError $ text "type mismatch"
viewPat2BigulPat (ElementPat name pats) tv@(Data (Name dtdName _) subtv) typeEnv =
if name == dtdName
then do
DynP osubtv subtv' psub <- viewPat2BigulPat (SequencePat pats) subtv typeEnv
case teq osubtv subtv of
Just BType.Eq -> return $ DynP tv subtv' (POut psub)
otherwise -> throwError $ text "type mismatch"
else ttext "Element pat name not match with type"
viewPat2BigulPat (ElementPat name pats) _ _ = ttext " type mismatch"
viewPat2BigulPat (AttributePat name varp) (Tag ('@':attName) tv) typeEnv =
if name == attName
then viewVarP2BigulPat varp tv typeEnv
else ttext "attribute name mismatch"
viewPat2BigulPat (StringPat str) tv typeEnv =
case teq tv String of
Just BType.Eq -> return $ DynP tv One (PConst (BType.Str str))
_ -> ttext "view type must be string"
viewPat2BigulPat (VarPat varp) tv typeEnv = viewVarP2BigulPat varp tv typeEnv
viewVarP2BigulPat :: (MonadError Doc m, Eq v) => BiFlux.VarP -> Type v -> TypeEnv -> m DynPat
viewVarP2BigulPat (VarV var) tv typeEnv = ttext "var without type not supported yet"
viewVarP2BigulPat (VarT var asttype) tv typeEnv =
maybe (ttext "infer Ast type fails")
(
\(DynT tv') ->
case teq tv tv' of --tv' `isSubtypeOf` tv TODO: in fact, need better reaarrange from v to v'
Just BType.Eq -> return $ DynP tv tv PVar
otherwise -> ttext "inferred ast type cannot match with exptected type"
)
(inferAstType typeEnv asttype)
viewVarP2BigulPat (VarTP asttype) tv typeEnv = ttext "on view pattern, not supported"
ttext str = throwError $ text str
data DynRPat where
DynR :: (Eq v, Eq env) => Type v -> Type env -> RPat v env con -> DynRPat
-- Pat and RPat are different for (Data Name ..) type.
viewPat2DirectionEnv :: (MonadError Doc m) => BiFlux.Pat -> DynRPat -> m DirectionEnv
viewPat2DirectionEnv (SequencePat []) _ = return Map.empty
viewPat2DirectionEnv (SequencePat (path: patt)) (DynR tv@(Prod tvh tvt) ev@(Prod evh evt) rpat@(RProd rpath rpatt)) = do
deh <- viewPat2DirectionEnv path (DynR tvh evh rpath)
det <- viewPat2DirectionEnv (SequencePat patt) (DynR tvt evt rpatt)
return $ Map.union (wrapDLeft deh tv ev rpat) (wrapDRight det tv ev rpat)
viewPat2DirectionEnv (SequencePat _) _ = ttext "pattern not match"
viewPat2DirectionEnv (ElementPat name pats) dynRPat = viewPat2DirectionEnv (SequencePat pats) dynRPat --already handled from Pat to RPat
viewPat2DirectionEnv (AttributePat name varp) dynRPat = varPat2DirectionEnv varp dynRPat
viewPat2DirectionEnv (StringPat str) _ = return Map.empty
viewPat2DirectionEnv (VarPat varp) dynRPat = varPat2DirectionEnv varp dynRPat
-- how to wrap with MonadError ?
wrapDLeft :: DirectionEnv -> Type v -> Type env -> RPat v env con -> DirectionEnv
wrapDLeft denv tv tenv rpat = Map.mapWithKey (\_ dir -> uDLeft dir tv tenv rpat) denv
-- data DynDirection where
-- DynD :: (Eq t, Eq v) => Type v -> Type env -> Type t -> Direction env t -> RPat v env con -> DynDirection
-- | compute Direction Env from pat
uDLeft :: DynDirection -> Type v -> Type env -> RPat v env con -> DynDirection
uDLeft (DynD tv' tenv' t' d' rpat') tv@(Prod tvl tvr) tenv@(Prod tenvl tenvr) rpat =
case teq tv' tvl of
Just BType.Eq -> case teq tenv' tenvl of
Just BType.Eq -> DynD tv tenv t' (DLeft d') rpat
Nothing -> error "wrap direction DLeft fail"
Nothing -> error "wrap direction DLeft fail"
wrapDRight :: DirectionEnv -> Type v -> Type env -> RPat v env con -> DirectionEnv
wrapDRight denv tv tenv rpat = Map.mapWithKey (\_ dir -> uDRight dir tv tenv rpat) denv
uDRight :: DynDirection -> Type v -> Type env -> RPat v env con -> DynDirection
uDRight (DynD tv' tenv' t' d' rpat') tv@(Prod tvl tvr) tenv@(Prod tenvl tenvr) rpat =
case teq tv' tvr of
Just BType.Eq -> case teq tenv' tenvr of
Just BType.Eq -> DynD tv tenv t' (DRight d') rpat
Nothing -> error "wrap direction DRight fail"
Nothing -> error "wrap direction DRight fail"
varPat2DirectionEnv :: MonadError Doc m => BiFlux.VarP -> DynRPat -> m DirectionEnv
varPat2DirectionEnv (VarV var ) _ = ttext "var pattern without asttype not supported"
varPat2DirectionEnv (VarT var _) dynRPat@(DynR tv' ev' RVar) = return $ Map.singleton var (DynD tv' ev' tv' DVar RVar)
varPat2DirectionEnv (VarT var _) _ = ttext "RPat shall be RVar"
varPat2DirectionEnv (VarTP _ ) _ = return Map.empty
-- | Compute RPat v' env con from Pat v v'
-- Memo: this is different from directly computing RPat v env con from view v
pat2rpat :: (MonadError Doc m) => DynPat -> m DynRPat
pat2rpat (DynP tv tv' PVar) = return $ DynR tv' (BType.VVar tv') RVar -- TODO: is it correct ?
pat2rpat (DynP tv One (PConst c)) = return $ DynR One One (RConst ())
pat2rpat (DynP (Prod tvl tvr) (Prod tvl' tvr') (PProd patl patr))= do
DynR tvl'' evl'' rpatl <- pat2rpat (DynP tvl tvl' patl)
DynR tvr'' evr'' rpatr <- pat2rpat (DynP tvr tvr' patr)
return $ DynR (Prod tvl'' tvr'') (Prod evl'' evr'') (RProd rpatl rpatr)
pat2rpat (DynP (Either tvl tvr) tvl' (PLeft patl)) = do
DynR tvl'' evl'' rpatl <- pat2rpat (DynP tvl tvl' patl)
return $ DynR tvl'' evl'' rpatl
pat2rpat (DynP (Either tvl tvr) tvr' (PRight patr)) = do
DynR tvr'' evr'' rpatr <- pat2rpat (DynP tvr tvr' patr)
return $ DynR tvr'' evr'' rpatr
pat2rpat (DynP (Data _ subtv) tv' (POut pat)) = do
DynR tv'' ev'' pat' <- pat2rpat (DynP subtv tv' pat)
case teq tv'' tv' of
Just BType.Eq -> return $ DynR tv'' ev'' pat'
_ -> ttext "type mismatch"
pat2rpat (DynP tv tv' (POut pat)) = ttext "POut shall be type of Data"
pat2rpat (DynP (List tv) (Prod tvh' tvt') (PElem path patt)) = do
DynR tvh'' evh'' path' <- pat2rpat (DynP tv tvh' path)
DynR tvt'' evt'' patt' <- pat2rpat (DynP (List tv) tvt' patt)
return $ DynR (Prod tvh'' tvt'') (Prod evh'' evt'') (RProd path' patt')
-- | Source Pat handling
--
|
prl-tokyo/bigul-configuration-adaptation
|
Transformations/src/BiFlux/Trans/Translation.hs
|
mit
| 23,236
| 0
| 22
| 5,811
| 7,186
| 3,546
| 3,640
| 305
| 9
|
-- Type where we specify the shape of each of the elements
-- Algebraic operations
-- "sum" is alternation (A | B, meaning A or B but not both)
-- "product" is combination (A B, meaning A and B together)
data Pair = P Int Double -- Pair of numbers, an Int and a Double
data Pair = I Int | D Double -- Either an Int or a double
|
domenicosolazzo/practice-haskell
|
basics/algebraic_datatype.hs
|
mit
| 332
| 2
| 5
| 75
| 36
| 20
| 16
| 2
| 0
|
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}
module Y2018.M01.D08.Exercise where
{--
Okay, one more, then a thought on generalization.
Friday, we looked at sections classifying newspaper articles as a graph, but
now we want to store unique sections in a table and relate those sections back
to the articles they classify.
Like before. So.
--}
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.SqlQQ
import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.ToRow
-- below imports available via 1HaskellADay git repository
import Data.MemoizingTable (MemoizingS)
import qualified Data.MemoizingTable as MT
import Store.SQL.Connection (withConnection)
import Store.SQL.Util.Indexed
import Store.SQL.Util.Pivots
import Y2017.M12.D20.Exercise -- for Block
import Y2017.M12.D27.Exercise -- for DatedArticle
import Y2017.M12.D29.Exercise -- for filtering out AP articles
import Y2018.M01.D02.Exercise -- for keywords and etl
import Y2018.M01.D04.Exercise -- for Author
-- Okay, sections are like subjects are like keywords, but not quite like
-- authors (not quite). In Prolog we call a simple value with typing information
-- a tagged-type. We don't have those here, but maybe we should?
-- first thought on generalization
data Section = Sect { section :: String }
deriving (Eq, Ord, Show)
fetchSectionStmt :: Query
fetchSectionStmt = [sql|SELECT * FROM section|]
fetchSections :: Connection -> IO [IxValue Section]
fetchSections conn = undefined
instance FromRow Section where
fromRow = undefined
-- okay, we can get sections previously stored. Fetch them and populate a
-- memoizing table with them.
-- Now, from an article, extract its sections. That's easy enough.
-- Now we put that all together and populate the section table with new
-- section information
storeSections :: Connection -> [IxValue (DatedArticle a)] -> IO ()
storeSections conn arts = undefined
insertSectionStmt :: Query
insertSectionStmt = [sql|INSERT INTO section (section) VALUES (?) returning id|]
insertSections :: Connection -> [Section] -> IO [Index]
insertSections conn sects = undefined
insertArtSectPivotStmt :: Query
insertArtSectPivotStmt =
[sql|INSERT INTO article_section (article_id,section_id) VALUES (?,?)|]
-- hint: use Pivots module for pivot inserts
instance ToRow Section where
toRow sect = undefined
-- with storeSections defined, define a new storeAncilliary to extract and
-- store values for keywords, authors and sections.
storeAncilliary :: Connection -> [IxValue (DatedArticle Authors)] -> IO ()
storeAncilliary conn ixarts = undefined
-- and apply this storeAncilliary to the etl function, and you've captured
-- the information we're interested in with the articles sampled.
-- Hint: use pa to process the articles
{-- BONUS -----------------------------------------------------------------
Keywords, Authors, and sections. All three follow the same pattern:
* fetch previously stored values
* memoize
* materials values from article set, see which values are new
* store new values, relate all values.
If we are following the same pattern, is there a generalization of the
functions for all of this, so we can have one function that does the work
for any memoize-y type? What would this function look like?
--}
memoizeStore :: ToRow a => Connection -> [IxValue (DatedArticle Authors)]
-> (IxValue (DatedArticle Authors) -> a)
-> MemoizingS IO Integer b ()
memoizeStore conn ixarts getter = undefined
-- something like this? Or something different?
|
geophf/1HaskellADay
|
exercises/HAD/Y2018/M01/D08/Exercise.hs
|
mit
| 3,600
| 0
| 13
| 562
| 459
| 278
| 181
| 42
| 1
|
{-# LANGUAGE OverlappingInstances, IncoherentInstances, UndecidableInstances,
PatternGuards, TupleSections #-}
module HeredNormal where
import Prelude hiding (pi,abs,mapM)
import Control.Applicative
import Control.Monad ((<=<))
import Control.Monad.Except hiding (mapM)
import Control.Monad.Reader hiding (mapM)
import Control.Monad.State hiding (mapM)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Traversable
import qualified Abstract as A
import Context
import Signature
import TypeCheck hiding (app)
import Util hiding (lookupSafe)
import Value
import MapEnv as M
import PrettyM
import Data.Char
import HeredNormVal
-- * Evaluation monad
type EvalM = Reader (MapSig NVal)
instance PrettyM EvalM NVal where
prettyM = prettyM <=< reify
-- * Context monad
data Context = Context
{ level :: Int
, tyEnv :: Env'
, valEnv :: Env'
}
emptyContext :: Context
emptyContext = Context (-1) M.empty M.empty
type ContextM = Reader Context
instance MonadCxt NVal Env' ContextM where
addLocal n@(A.Name x _) t cont = do
l <- asks level
let xv = NVar (n { A.uid = l }) t []
local (\ (Context l gamma rho) ->
Context (l - 1) (Map.insert x t gamma) (Map.insert x xv rho))
(cont xv)
lookupLocal x = do
gamma <- asks tyEnv
return $ lookupSafe (A.uid x) gamma
getEnv = asks valEnv
-- * Type checking monad
data SigCxt = SigCxt { globals :: MapSig NVal, locals :: Context }
type Err = Either String
type CheckExprM = ReaderT SigCxt Err
instance MonadCxt NVal Env' CheckExprM where
addLocal n@(A.Name x _) t cont = do
Context l gamma rho <- asks locals
let xv = NVar (n { A.uid = l }) t []
let cxt = Context (l - 1) (Map.insert x t gamma) (Map.insert x xv rho)
local (\ sc -> sc { locals = cxt }) $ cont xv
lookupLocal n@(A.Name x _) = do
gamma <- asks $ tyEnv . locals
return $ lookupSafe x gamma
getEnv = asks $ valEnv . locals
instance MonadCheckExpr NVal Env' EvalM CheckExprM where
doEval comp = runReader comp <$> asks globals
-- TODO ?
typeError err = failDoc $ prettyM err
newError err k = k `catchError` (const $ typeError err)
typeTrace tr = (enterDoc $ prettyM tr)
lookupGlobal x = symbType . sigLookup' (A.uid x) <$> asks globals
instance PrettyM CheckExprM NVal where
prettyM = doEval . prettyM
checkTySig :: A.Expr -> A.Type -> CheckExprM ()
checkTySig e t = do
-- checkType t
t <- eval t
check e t
runCheck :: A.Expr -> A.Type -> Err ()
runCheck e t = runReaderT (checkTySig e t) $ SigCxt M.empty emptyContext
-- * Declarations
type CheckDeclM = StateT (MapSig NVal) (ExceptT String IO)
instance MonadCheckDecl NVal Env' EvalM CheckExprM CheckDeclM where
doCheckExpr cont = either throwError return . runReaderT cont . sigCxt =<< get where
sigCxt sig = SigCxt sig emptyContext
instance PrettyM CheckDeclM NVal where
prettyM = doCheckExpr . prettyM
checkDeclaration :: A.Declaration -> CheckDeclM ()
checkDeclaration d = do
liftIO . putStrLn =<< showM d
checkDecl d
checkDeclarations :: A.Declarations -> CheckDeclM ()
checkDeclarations = mapM_ checkDeclaration . A.declarations
runCheckDecls :: A.Declarations -> IO (Err ())
runCheckDecls ds = runExceptT $ evalStateT (checkDeclarations ds) Map.empty
-- * Testing
-- polymorphic identity
hashString = fromIntegral . foldr f 0
where f c m = ord c + (m * 128) `rem` 1500007
hash :: String -> A.Name
hash s = A.Name (hashString s) s
var' x = A.Ident $ A.Var $ hash x
abs x e = A.Lam (hash x) Nothing e
app = A.App
ty = A.Typ
pi x = A.Pi (Just $ hash x)
eid = abs "A" $ abs "x" $ var' "x"
tid = pi "A" ty $ pi "x" (var' "A") $ var' "A"
arrow a b = A.Pi Nothing a b
tnat = pi "A" ty $
pi "zero" (var' "A") $
pi "suc" (var' "A" `arrow` var' "A") $
var' "A"
ezero = abs "A" $ abs "zero" $ abs "suc" $ var' "zero"
-- problem: esuc is not a nf
esuc n = abs "A" $ abs "zero" $ abs "suc" $ var' "suc" `app`
(n `app` var' "A" `app` var' "zero" `app` var' "suc")
enat e = abs "A" $ abs "zero" $ abs "suc" $ e
enats = map enat $ iterate (app (var' "suc")) (var' "zero")
e2 = enats !! 2
rid = runCheck eid tid
success = [(eid,tid),(ezero,tnat),(e2,tnat)] -- ,(Sort Type,Sort Kind)]
failure = [(tid,tid)]
runsuccs = map (uncurry runCheck) success
runtests = map (uncurry runCheck) (success ++ failure)
|
andreasabel/helf
|
src/HeredNormal.hs
|
mit
| 4,403
| 116
| 17
| 988
| 1,696
| 900
| 796
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad
import Data.Attoparsec
import Data.Attoparsec.Char8 as A
import Data.ByteString.Char8
data Action
= Success
| KeepAlive
| NoResource
| Hangup
| NewLeader
| Election
deriving Show
type Sender = ByteString
type Payload = ByteString
data Message = Message
{ action :: Action
, sender :: Sender
, payload :: Payload
} deriving Show
pprotocol :: Parser Message
pprotocol = do
act <- paction
send <- A.takeTill (== '.')
body <- A.takeTill (A.isSpace)
endOfLine
return $ Message act send body
paction :: Parser Action
paction = do
c <- anyWord8
case c of
1 -> return Success
2 -> return KeepAlive
3 -> return NoResource
4 -> return Hangup
5 -> return NewLeader
6 -> return Election
_ -> mzero
main :: IO ()
main = do
let msgtext = "\x01\x6c\x61\x70\x74\x6f\x70\x2e\x33\x2e\x31\x34\x31\x35\x39\x32\x36\x35\x33\x35\x0A"
let msg = parseOnly pprotocol msgtext
print msg
|
riwsky/wiwinwlh
|
src/attoparsec.hs
|
mit
| 1,001
| 11
| 10
| 228
| 316
| 154
| 162
| 43
| 7
|
import Data.List
layout :: [String] -> IO ()
layout = putStr
. unlines
. zipWith (\n l -> show n ++ ") " ++ l) [1..]
appString :: String -> String -> String
appString l r = "(" ++ l ++ "++" ++ r ++ ")"
split :: [a] -> [([a],[a])]
split [] = []
split [_] = []
split (x:xs) = ([x],xs) : [(x:ls,rs) | (ls,rs) <- split xs]
data Tree = Leaf String | Node Tree Tree
deriving Show
stringToTree :: String -> [Tree]
stringToTree x = case split x of
[] -> [Leaf x]
otherwise -> [Node l r | y <- split x, l <- (stringToTree (fst y)), r <- (stringToTree (snd y))]
treeToAppString :: Tree -> String
treeToAppString (Leaf x) = x
treeToAppString (Node x y) = appString (treeToAppString x) (treeToAppString y)
allWays :: String -> [String]
allWays x = x : (map treeToAppString (stringToTree x))
noParens :: String -> [String]
noParens xs = nub (map (filter (not . (`elem` "()"))) ((allWays xs)++(otherOnes (split xs))))
otherOnes :: [(String,String)] -> [String]
otherOnes [] = []
otherOnes (x:xs) = (appString (fst x) (snd x)) : (otherOnes xs)
|
craynafinal/cs557_functional_languages
|
hw3/q2.hs
|
mit
| 1,049
| 3
| 14
| 210
| 590
| 312
| 278
| 27
| 2
|
{- Copyright © 2012, Vincent Elisha Lee Frey. All rights reserved.
- This is open source software distributed under a MIT license.
- See the file 'LICENSE' for further information.
-}
module System.Console.CmdTheLine.Common where
import Data.Function ( on )
import Text.PrettyPrint ( Doc, text )
import Control.Applicative ( Applicative(..) )
import qualified Data.Map as M
import Control.Monad.Trans.Error
data Absence = Absent
| Present String
deriving ( Eq )
data OptKind = FlagKind
| OptKind
| OptVal String
deriving ( Eq )
data PosKind = PosAny
| PosN Bool Int
| PosL Bool Int
| PosR Bool Int
deriving ( Eq, Ord )
data ArgInfo = ArgInfo
{ absence :: Absence
, argDoc :: String
, argName :: String
, argSec :: String
, posKind :: PosKind
, optKind :: OptKind
, optNames :: [String]
, repeatable :: Bool
}
instance Eq ArgInfo where
ai == ai'
| isPos ai && isPos ai' = ((==) `on` posKind) ai ai'
| isOpt ai && isOpt ai' = ((==) `on` optNames) ai ai'
| otherwise = False
-- This Ord instance works for placing in 'Data.Map's, but not much else.
instance Ord ArgInfo where
compare ai ai'
| isPos ai && isPos ai' = (compare `on` posKind) ai ai'
| isOpt ai && isOpt ai' = (compare `on` optNames) ai ai'
| isOpt ai && isPos ai' = LT
| otherwise = GT
data Arg = Opt [( Int -- The position were the argument was found.
, String -- The name by which the argument was supplied.
, Maybe String -- If present, a value assigned to the argument.
)]
| Pos [String] -- A list of positional arguments
type CmdLine = M.Map ArgInfo Arg
isOpt, isPos :: ArgInfo -> Bool
isOpt ai = optNames ai /= []
isPos ai = optNames ai == []
{- |
Any 'String' argument to a 'ManBlock' constructor may contain the
following significant forms for a limited kind of meta-programing.
* $(i,text): italicizes @text@.
* $(b,text): bolds @text@.
* $(mname): evaluates to the name of the default term if there are choices
of commands, or the only term otherwise.
* $(tname): evaluates to the name of the currently evaluating term.
Additionally, text inside the content portion of an 'I' constructor may
contain one of the following significant forms.
* $(argName): evaluates to the name of the argument being documented.
-}
data ManBlock = S String -- ^ A section title.
| P String -- ^ A paragraph.
| I String String -- ^ A label-content pair. As in an argument
-- definition and its accompanying
-- documentation.
| NoBlank -- ^ Suppress the normal blank line following
-- a 'P' or an 'I'.
deriving ( Eq )
type Title = ( String, Int, String, String, String )
type Page = ( Title, [ManBlock] )
-- | Information about a 'Term'. It is recommended that 'TermInfo's be
-- created by customizing 'defTI', as in
--
-- > termInfo = defTI
-- > { termName = "caroline-no"
-- > , termDoc = "carry a line off"
-- > }
data TermInfo = TermInfo
{
-- | The name of the command or program represented by the term. Defaults to
-- @\"\"@.
termName :: String
-- | Documentation for the term. Defaults to @\"\"@.
, termDoc :: String
-- | The section under which to place the terms documentation.
-- Defaults to @\"COMMANDS\"@.
, termSec :: String
-- | The section under which to place a term's argument's
-- documentation by default. Defaults to @\"OPTIONS\"@.
, stdOptSec :: String
-- | A version string. Must be left blank for commands. Defaults to @\"\"@.
, version :: String
-- | A list of 'ManBlock's to append to the default @[ManBlock]@. Defaults
-- to @[]@.
, man :: [ManBlock]
} deriving ( Eq )
-- | A default 'TermInfo'.
defTI :: TermInfo
defTI = TermInfo
{ termName = ""
, version = ""
, termDoc = ""
, termSec = "COMMANDS"
, stdOptSec = "OPTIONS"
, man = []
}
type Command = ( TermInfo, [ArgInfo] )
data EvalInfo = EvalInfo
{ term :: Command -- The chosen term for this run.
, main :: Command -- The default term.
, choices :: [Command] -- A list of command-terms.
}
-- | The format to print help in.
data HelpFormat = Pager | Plain | Groff deriving ( Eq )
data Fail = MsgFail Doc
| UsageFail Doc
| HelpFail HelpFormat (Maybe String)
instance Error Fail where
strMsg = MsgFail . text
-- | A monad for values in the context of possibly failing with a helpful
-- message.
type Err = ErrorT Fail IO
type Yield a = EvalInfo -> CmdLine -> Err a
-- | The underlying Applicative of the library. A @Term@ represents a value
-- in the context of being computed from the command line arguments.
data Term a = Term [ArgInfo] (Yield a)
instance Functor Term where
fmap = yield . result . result . fmap
where
yield f (Term ais y) = Term ais (f y)
result = (.)
instance Applicative Term where
pure v = Term [] (\ _ _ -> return v)
(Term args f) <*> (Term args' v) = Term (args ++ args') wrapped
where
wrapped ei cl = f ei cl <*> v ei cl
data EvalKind = Simple -- The program has no commands.
| Main -- The default program is running.
| Choice -- A command has been chosen.
evalKind :: EvalInfo -> EvalKind
evalKind ei
| choices ei == [] = Simple
| fst (term ei) == fst (main ei) = Main
| otherwise = Choice
descCompare :: Ord a => a -> a -> Ordering
descCompare = flip compare
splitOn :: Eq a => a -> [a] -> ( [a], [a] )
splitOn sep xs = ( left, rest' )
where
rest' = if rest == [] then rest else tail rest -- Skip the 'sep'.
( left, rest ) = span (/= sep) xs
select :: a -> [( Bool, a )] -> a
select baseCase = foldr (uncurry (?)) baseCase
where
(?) True = const
(?) False = flip const
|
glutamate/cmdtheline
|
src/System/Console/CmdTheLine/Common.hs
|
mit
| 6,129
| 1
| 12
| 1,828
| 1,328
| 747
| 581
| 109
| 2
|
{-|
Module : TestPrint.Problen.ProblemExpr
Description : The ProblemExpr type Printer tests
Copyright : (c) Andrew Burnett 2014-2015
Maintainer : andyburnett88@gmail.com
Stability : experimental
Portability : Unknown
The Test Tree Node for the ProblemExpr type's Printer Tests
-}
module TestPrint.Problem.ProblemExpr (
printer, -- :: TestTree
problemExprs -- :: [ProblemExpr]
) where
import HSat.Problem.ProblemExpr.Class
import TestPrint
name :: String
name = "ProblemExpr"
printer :: TestTree
printer =
testGroup name [
printProblemExpr
]
printProblemExpr :: TestTree
printProblemExpr =
printList "ProblemExpr CNF" problemExprs
problemExprs :: [ProblemExpr]
problemExprs = []
|
aburnett88/HSat
|
tests-src/TestPrint/Problem/ProblemExpr.hs
|
mit
| 738
| 0
| 6
| 145
| 86
| 53
| 33
| 16
| 1
|
{-# LANGUAGE TupleSections #-}
------------------------------------------------------------------------------
module Snap.Snaplet.Rest.Resource.Builder
( addMedia
, setCreate
, setRead
, setUpdate
, setDelete
, setToDiff
, setFromParams
, setPutAction
) where
------------------------------------------------------------------------------
import Control.Monad
import Data.Maybe
------------------------------------------------------------------------------
import Snap.Core (Params)
------------------------------------------------------------------------------
import Snap.Snaplet.Rest.Resource.Internal
import Snap.Snaplet.Rest.Resource.Media (Media (..))
------------------------------------------------------------------------------
type ResourceBuilder res m id diff
= Resource res m id diff -> Resource res m id diff
------------------------------------------------------------------------------
-- | Add a media representation for rendering and parsing.
addMedia :: Monad m => Media res m diff int -> ResourceBuilder res m id diff
addMedia media res = res
{ renderers = renderers res ++ renderers'
, parsers = parsers res ++ parsers'
, diffParsers = diffParsers res ++ diffParsers'
, listRenderers = listRenderers res ++ listRenderers'
, listParsers = listParsers res ++ listParsers'
}
where
renderers' = fromMaybe [] $ do
fromResource' <- _fromResource media
(mts, render) <- responseMedia media
return $ map (, fromResource' >=> render) mts
parsers' = fromMaybe [] $ do
toResource' <- _toResource media
(mts, parse) <- requestMedia media
return $ map (, parse >=> maybe (return Nothing) toResource') mts
diffParsers' = fromMaybe [] $ do
toDiff' <- _toDiff media
(mts, parse) <- requestMedia media
return $ map (, parse >=> maybe (return Nothing) toDiff') mts
listRenderers' = fromMaybe [] $ do
fromResourceList' <- _fromResourceList media
(mts, render) <- responseMedia media
return $ map (, fromResourceList' >=> render) mts
listParsers' = fromMaybe [] $ do
toResourceList' <- _toResourceList media
(mts, parse) <- requestMedia media
return $ map (, parse >=> maybe (return Nothing) toResourceList') mts
------------------------------------------------------------------------------
-- | Set the create method for the resource.
setCreate :: (res -> m ()) -> ResourceBuilder res m id diff
setCreate f res = res { create = Just f }
------------------------------------------------------------------------------
-- | Set the read method for the resource.
setRead :: (id -> m [res]) -> ResourceBuilder res m id diff
setRead f res = res { retrieve = Just f }
------------------------------------------------------------------------------
-- | Set the update method for the resource. The method must return
-- a boolean, indicating whether anything was updated.
setUpdate :: (id -> diff -> m Bool) -> ResourceBuilder res m id diff
setUpdate f res = res { update = Just f }
------------------------------------------------------------------------------
-- | Set the delete method for the resource. The method must return a
-- boolean, indicating whether anything was deleted.
setDelete :: (id -> m Bool) -> ResourceBuilder res m id diff
setDelete f res = res { delete = Just f }
------------------------------------------------------------------------------
-- | Sets the conversion function from resource to diff value.
setToDiff :: (res -> diff) -> ResourceBuilder res m id diff
setToDiff f res = res { toDiff = Just f }
------------------------------------------------------------------------------
-- | Sets the URL query string parser.
setFromParams :: (Params -> Maybe id) -> ResourceBuilder res m id diff
setFromParams f res = res { fromParams = Just f }
------------------------------------------------------------------------------
-- | Sets a specific action to take when a PUT method is received. If not
-- set, this defaults to trying to update and then creating if that fails.
setPutAction :: PutAction -> ResourceBuilder res m id diff
setPutAction a res = res { putAction = Just a }
|
zmthy/snaplet-rest
|
src/Snap/Snaplet/Rest/Resource/Builder.hs
|
mit
| 4,249
| 0
| 16
| 777
| 922
| 489
| 433
| 58
| 1
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Views.Components.MainFooter (mainFooterView) where
import BasicPrelude
import Text.Blaze.Html5 (Html, (!))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
mainFooterView :: Html
mainFooterView =
H.footer $ H.div ! A.class_ "container" $ H.div ! A.class_ "row" $ do
H.div ! A.class_ "col-md-6" $
H.a
! A.href "http://marvel.com"
! A.target "_blank"
$ "Data provided by Marvel. © 2016 MARVEL"
H.div ! A.class_ "col-md-6" $
H.a
! A.href "https://github.com/nicolashery/example-marvel-haskell"
! A.target "_blank"
$ "View on GitHub"
|
nicolashery/example-marvel-haskell
|
Views/Components/MainFooter.hs
|
mit
| 722
| 0
| 14
| 156
| 182
| 99
| 83
| 20
| 1
|
import System.Environment (getArgs)
import qualified Data.ByteString.Lazy as B
copyFile :: FilePath -> FilePath -> IO ()
copyFile source dest = do
contents <- B.readFile source
B.writeFile dest contents
main = do
(fileName1:fileName2:_) <- getArgs
copyFile fileName1 fileName2
|
topliceanu/learn
|
haskell/bytestr.hs
|
mit
| 296
| 0
| 10
| 56
| 101
| 51
| 50
| 9
| 1
|
{-# LANGUAGE BangPatterns, RankNTypes #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
{-# OPTIONS_GHC -fspec-constr #-}
{-# OPTIONS_GHC -fdicts-cheap #-}
module Main where
import Criterion.Main as C
import HERMIT.Optimization.StreamFusion.List
f :: Int -> Int
f n = foldl (+) 0 (concatMap (\x -> enumFromTo 1 x) (enumFromTo 1 n))
{-# NOINLINE f #-}
g :: Int -> Int
g n = foldl (+) 0 (flatten mk step (enumFromTo 1 n))
where
mk x = (1,x)
{-# INLINE mk #-}
step (i,max)
| i<=max = Yield i (i+1,max)
| otherwise = Done
{-# INLINE step #-}
{-# NOINLINE g #-}
main = do
print $ f 1000
print $ g 1000
defaultMain
[ bgroup "concat tests / 100"
[ bench "f" $ whnf f 100
, bench "g" $ whnf g 100
]
, bgroup "concat tests / 1000"
[ bench "f" $ whnf f 1000
, bench "g" $ whnf g 1000
]
]
|
ku-fpg/hermit-streamfusion
|
Intuition.hs
|
mit
| 905
| 0
| 12
| 282
| 296
| 155
| 141
| 29
| 1
|
str = "sinus aestuum"
ns = [7,6..1]
chunks n xs
| n <= length xs = fst (splitAt n xs) : chunks n (tail xs)
| otherwise = []
chks = [chunks x str | x <- ns]
main = do
putStrLn "str = "
print str
putStrLn "chks = "
mapM_ (putStrLn . show) chks
|
jsavatgy/dit-doo
|
code/chunks.hs
|
gpl-2.0
| 265
| 0
| 9
| 79
| 138
| 65
| 73
| 11
| 1
|
import Functions
import Data.Bool
import SearchMonad
import Data.Maybe
type N = Integer
type Baire = N -> N
data T = Fork [(N,T)]
-- Programming exercises.
cantorTree :: T
cantorTree = Fork [(0, cantorTree), (1, cantorTree)]
unboundedBreadthTree :: N -> T
unboundedBreadthTree n = Fork [(i, unboundedBreadthTree(n+1)) | i <- [0..n]]
-- Q2 (a):
findT :: T -> (Baire -> Bool) -> Baire
existsT :: T -> (Baire -> Bool) -> Bool
existsT t p = p(findT t p)
shiftPredicate :: (Baire->Bool)-> N -> (Baire -> Bool)
shiftPredicate p x = \sequence -> p (\n -> if n == 0 then x else sequence (n-1))
findT (Fork ((i, tree) : [])) p = \n -> if n == 0 then i else findT tree (shiftPredicate p i) (n-1)
findT (Fork ((i, tree) : xs)) p = let solution = findT (Fork ((i, tree) : [])) p
in \n -> if p solution then solution n
else findT (Fork xs) p n
pr :: ( Baire -> Bool)
pr b = b 12 == 1
myTree :: N -> T
myTree n = Fork [(n,myTree (n+1))]
mt = myTree 0
-- Example.
a = findT cantorTree pr
-- Q2 (b):
(#) :: N -> Baire -> Baire
(n # a) 0 = n
(n # a) i = a (i-1)
findT' :: T -> (Baire -> Bool) -> Baire
existsT' :: T -> (Baire -> Bool) -> Bool
existsT' t p = p(findT' t p)
myMatch :: T -> N -> Maybe T
myMatch (Fork ((i, tree) : [])) n = if i == n then Just tree else Nothing
myMatch (Fork ((i, tree) : xs)) n = let t = myMatch (Fork ((i, tree) : [])) n in
if isJust t then t else myMatch (Fork xs) n
findBranch :: T -> (N -> Bool)-> N
findBranch (Fork ((i, tree) : [])) p = i
findBranch (Fork ((i, tree) : xs)) p = if p i then i else findBranch (Fork xs) p
findT' originalTree p = x # a
where x = findBranch originalTree (\x -> existsT' (fromJust $ myMatch originalTree x) (\a -> p (x # a)))
a = findT' (fromJust $ myMatch originalTree x) (\a -> p(x # a))
-- Examples.
b' = findT' cantorTree pr
b = findT' mt pr
-- Q2 (c):
findT'' :: T -> (Baire -> Bool) -> Baire
existsT'' :: T -> (Baire -> Bool) -> Bool
existsT'' t p = p(findT'' t p)
fork :: N -> Baire -> Baire -> Baire
fork x l r i | i == 0 = x
| odd i = l((i-1) `div` 2)
| otherwise = r((i-2) `div` 2)
findT'' originalTree p = fork x l r
where x = findBranch originalTree (\x -> let myTree = (fromJust $ myMatch originalTree x) in
existsT'' myTree (\l -> existsT'' myTree (\r -> p(fork x l r))))
tx = fromJust $ myMatch originalTree x
l = findT'' tx (\l -> existsT'' tx (\r -> p(fork x l r)))
r = findT'' tx (\r -> p(fork x l r))
-- Examples.
threetree = Fork [(0, threetree), (1, threetree), (2, threetree)]
c = findT'' cantorTree pr
c' = findT'' threetree (\b -> b 12 == 2)
|
KukovecJ/Nemogoci_Funkcionali
|
Exercises.hs
|
gpl-2.0
| 2,812
| 1
| 20
| 835
| 1,448
| 773
| 675
| 60
| 3
|
module Controllers.Game.Model.ServerGame (ServerGame,
makeServerGame,
gameId,
game,
playing,
broadcastChannel,
numConnections,
increaseConnectionsByOne,
decreaseConnectionsByOne,
getServerPlayer) where
import Prelude
import Wordify.Rules.Game
import Controllers.Game.Model.ServerPlayer
import Controllers.Game.Api
import Control.Concurrent.STM.TChan
import qualified Data.List.Safe as SL
import Control.Concurrent.STM.TVar
import Control.Monad.STM
import Data.Text
data ServerGame = ServerGame {
gameId :: Text,
game :: TVar Game,
playing :: [ServerPlayer],
broadcastChannel :: (TChan GameMessage),
numConnections :: TVar Int
}
makeServerGame :: Text -> TVar Game -> [ServerPlayer] -> (TChan GameMessage) -> STM ServerGame
makeServerGame gameId game players messageChannel = do
connections <- newTVar 0
return (ServerGame gameId game players messageChannel connections)
getServerPlayer :: ServerGame -> Int -> Maybe ServerPlayer
getServerPlayer serverGame playerNumber = playing serverGame SL.!! (playerNumber - 1)
increaseConnectionsByOne :: ServerGame -> STM ()
increaseConnectionsByOne serverGame = modifyTVar (numConnections serverGame) succ
decreaseConnectionsByOne :: ServerGame -> STM ()
decreaseConnectionsByOne serverGame = modifyTVar (numConnections serverGame) decreaseByOne
where
decreaseByOne i = i - 1
|
Happy0/liscrabble
|
src/Controllers/Game/Model/ServerGame.hs
|
gpl-2.0
| 1,951
| 0
| 10
| 776
| 352
| 196
| 156
| 36
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
module ADC.Types.Locale ( Locale(..) )
where
import Prelude hiding (Applicative(..), print)
import Text.Syntax
import Text.Syntax.Parser.Naive
import Text.Syntax.Printer.Naive
import qualified Data.Aeson.Types as AT ( Parser )
import Data.Aeson
import qualified Data.Text.Lazy as TL
import qualified Control.Applicative as CA ( empty, pure )
import Data.Maybe (fromJust)
data Locale = DE_DE
| EN_GB
| ES_ES
| FR_FR
| IT_IT
| PT_PT
| RU_RU
| KO_KR
| ZH_TW
| EN_US
| PT_BR
| ES_MX deriving (Eq, Ord)
pLocale :: Syntax f => f Locale
pLocale = pure DE_DE <* text "de_DE"
<|> pure EN_GB <* text "en_GB"
<|> pure ES_ES <* text "es_ES"
<|> pure FR_FR <* text "fr_FR"
<|> pure IT_IT <* text "it_IT"
<|> pure PT_PT <* text "pt_PT"
<|> pure RU_RU <* text "ru_RU"
<|> pure KO_KR <* text "ko_KR"
<|> pure ZH_TW <* text "zh_TW"
<|> pure EN_US <* text "en_US"
<|> pure PT_BR <* text "pt_BR"
<|> pure ES_MX <* text "es_MX"
runParser :: Parser t -> String -> [(t, String)]
runParser (Parser p) = p
instance Read Locale where readsPrec _ = runParser pLocale
instance Show Locale where show = fromJust . print pLocale
instance FromJSON Locale where
parseJSON (String t) = fromString (TL.unpack (TL.fromStrict t))
where fromString :: String -> AT.Parser Locale
fromString s = CA.pure (read s :: Locale)
parseJSON _ = CA.empty
|
gore-v/AuctionParser
|
src/ADC/Types/Locale.hs
|
gpl-3.0
| 1,640
| 0
| 28
| 469
| 510
| 271
| 239
| 47
| 1
|
module Utils
( module Utils.Debug
, module Utils
)
where
import Text.Parsec (choice, try)
import Text.Parsec.String (GenParser)
import Text.Regex.TDFA ((=~))
import Import
import Utils.Debug
-- strings
trim :: String -> String
trim s | l <= limit = s
| otherwise = take limit s ++ suffix
where
limit = 500
l = length s
suffix = printf "...(%d more)" (l-limit)
strip,lstrip,rstrip,dropws :: String -> String
strip = lstrip . rstrip
lstrip = dropws
rstrip = reverse . dropws . reverse
dropws = dropWhile (`elem` " \t")
-- | Test if a string contains a regular expression. A malformed regexp
-- (or a regexp larger than 300 characters, to avoid a regex-tdfa memory leak)
-- will cause a runtime error. This version uses regex-tdfa and no regexp
-- options.
containsRegex :: String -> String -> Bool
containsRegex s "" = containsRegex s "^"
containsRegex s r
| length r <= 300 = s =~ r
| otherwise = error "please avoid regexps larger than 300 characters, they are currently problematic"
-- parsing
choice' :: [GenParser tok st a] -> GenParser tok st a
choice' = choice . map try
-- system
-- toExitCode :: Int -> ExitCode
-- toExitCode 0 = ExitSuccess
-- toExitCode n = ExitFailure n
fromExitCode :: ExitCode -> Int
fromExitCode ExitSuccess = 0
fromExitCode (ExitFailure n) = n
-- misc
-- | Replace occurrences of old list with new list within a larger list.
replace::(Eq a) => [a] -> [a] -> [a] -> [a]
replace [] _ = id
replace old new = replace'
where
replace' [] = []
replace' l@(h:ts) = if old `isPrefixOf` l
then new ++ replace' (drop len l)
else h : replace' ts
len = length old
-- | Show a message, usage string, and terminate with exit status 1.
warn :: String -> IO ()
warn s = putStrLn s >> exitWith (ExitFailure 1)
|
simonmichael/shelltestrunner
|
src/Utils.hs
|
gpl-3.0
| 1,864
| 0
| 11
| 455
| 517
| 283
| 234
| 39
| 3
|
module RenderToHtml where
import System.IO
import Control.Monad.Trans (liftIO)
import CursesWrap
import Interface
import Data.Array
import BasicTypes
import CommonTypes
prelude = "<html><head><style>td {border: none; width: 1em; min-width: 1em; max-width: 1em}</style><title>htmlshot</title></head><body><table border=\"0\" cellspacing=\"0\" style=\"border: 0 0 0 0; margin: 0 0 0 0; \">"
postlude = "</table></body></html>"
color True name =
case name of
Black -> "808080"
Red -> "0000ff"
Green -> "00ff00"
Yellow -> "ffff00"
Blue -> "ff0000"
Purple -> "ff00ff"
Cyan -> "00ffff"
Grey -> "ffffff"
color False name =
case name of
Black -> "000000"
Red -> "000088"
Green -> "008800"
Yellow -> "888800"
Blue -> "880000"
Purple -> "880088"
Cyan -> "008888"
Grey -> "c0c0c0"
renderCharToHtml (StyledChar (Style bright brightBg fgColor bgColor) c) =
"<td style=\"color: #" ++
color bright fgColor ++
"; background-color: #" ++
color brightBg bgColor ++
";\">" ++ [c] ++ "</td>"
renderCharToHtml (StyleAnimatedChar ((Style bright brightBg fgColor bgColor):_) c) =
"<td style=\"color: #" ++
color bright fgColor ++
"; background-color: #" ++
color brightBg bgColor ++
";\">" ++ [c] ++ "</td>"
renderLevelToHtml level outputHandle = do
(Coord bx by, Coord ex ey) <- bounds `fmap` gsLevel level world_
liftIO $ hPutStr outputHandle prelude
flip mapM_ [by..ey] $ \line -> do
-- liftIO $ print [OnMap level (Coord x line) | x <- [bx..ex]]
chars <- mapM (renderPos True) $ [Coord x line | x <- [bx..ex]]
liftIO $ hPutStr outputHandle ("<tr>" ++ concatMap renderCharToHtml chars ++ "</tr>")
liftIO $ hPutStr outputHandle postlude
|
arirahikkala/straylight-divergence
|
src/RenderToHtml.hs
|
gpl-3.0
| 1,790
| 0
| 16
| 412
| 468
| 237
| 231
| 49
| 15
|
{-# LANGUAGE NoImplicitPrelude #-}
module TickerApp (main) where
import Prelude
import FFI
import JSAPI
import Ticker
main :: Fay ()
main =
addWindowEventListener "load" handleLoad
handleLoad :: Event -> Fay Bool
handleLoad _ = do
tickerInit "canvas"
return False
|
SneakingCat/fay-ticker
|
examples/TickerApp.hs
|
gpl-3.0
| 276
| 0
| 7
| 51
| 74
| 39
| 35
| 13
| 1
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module UseGHCTypeLitsNats where
import GHC.TypeLits
-- import Data.Proxy
data Proxy (t::Nat) = Proxy
----------------------------------------------------------------
-- Stuff that works.
class Compose (n::Nat) b b' t t' where
compose :: Proxy n -> (b -> b') -> t -> t'
instance Compose 0 b b' b b' where
compose _ f x = f x
instance (Compose n b b' t t' , sn ~ (1 + n)) => Compose sn b b' (a -> t) (a -> t') where
compose _ g f x = compose (Proxy::Proxy n) g (f x)
----------------------------------------------------------------
-- Stuff that does not work.
-- Complement a binary relation.
compBinRel , compBinRel' :: (a -> a -> Bool) -> (a -> a -> Bool)
compBinRel = compose (Proxy::Proxy 2) not
{-
Couldn't match type `1 + (1 + n)' with `2'
The type variable `n' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
In the expression: compose (Proxy :: Proxy 2) not
In an equation for `compBinRel':
compBinRel = compose (Proxy :: Proxy 2) not
-}
{-
No instance for (Compose n Bool Bool Bool Bool)
arising from a use of `compose'
The type variable `n' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there is a potential instance available:
instance Compose 0 b b' b b'
-}
compBinRel' = compose (Proxy::Proxy (1+(1+0))) not
{-
Couldn't match type `1 + (1 + 0)' with `1 + (1 + n)'
NB: `+' is a type function, and may not be injective
The type variable `n' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Expected type: Proxy (1 + (1 + 0))
Actual type: Proxy (1 + (1 + n))
In the first argument of `compose', namely
`(Proxy :: Proxy (1 + (1 + 0)))'
-}
|
ntc2/haskell-call-trace
|
experiments/composition/type-lits.hs
|
mpl-2.0
| 2,032
| 3
| 13
| 442
| 307
| 172
| 135
| 20
| 1
|
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
record :: Record
record = Record
{ rProperties =
[ "foo" .= "bar"
, "foo" .= "bar"
, "foo" .= "bar"
, "foo" .= "bar"
, "foo" .= "bar"
, "foo" .= "bar"
, "foo" .= "bar"
, "foo" .= "bar"
]
}
|
lspitzner/brittany
|
data/Test540.hs
|
agpl-3.0
| 343
| 0
| 8
| 94
| 76
| 44
| 32
| 11
| 1
|
module P9x.Util(
doExpectEqual, expectEqual, expectEqual_, testList
) where
import Test.HUnit
doExpectEqual :: (Eq a, Show a) => String -> a -> a -> IO Counts
doExpectEqual desc expected actual = runTestTT (expectEqual desc expected actual)
expectEqual_ :: (Eq a, Show a) => a -> a -> Test
expectEqual_ = expectEqual ""
expectEqual :: (Eq a, Show a) => String -> a -> a -> Test
expectEqual desc expected actual = TestCase (assertEqual desc expected actual)
testList :: String -> [Test] -> Test
testList description tests = TestLabel description (TestList tests)
|
dkandalov/katas
|
haskell/p99/src/p9x/Util.hs
|
unlicense
| 570
| 0
| 9
| 98
| 215
| 113
| 102
| 11
| 1
|
{-# OPTIONS_GHC -Wall -Werror #-}
module FAst (
FExpr(..),
FStmt(..),
frender
) where
-- The functional AST
import Text.PrettyPrint
type Ident = String
data FExpr = FInt Int
| FIdent Ident
| FCall Ident [FExpr]
| FFilter FExpr Ident FExpr
data FStmt = FAssign Ident FExpr
| FIf FExpr [FStmt]
class Pretty e where
pp :: e -> Doc
bracing :: Pretty a => Doc -> [a] -> Doc
doc `bracing` xs = doc <+> lbrace $+$ (nest 2 $ vcat $ map pp xs) $+$ rbrace
instance Pretty FStmt where
pp (FAssign ident expr) = text ident <+> char '=' <+> pp expr
pp (FIf expr stmts) = (text "if" <+> pp expr) `bracing` stmts
instance Pretty FExpr where
pp (FInt n) = int n
pp (FIdent ident) = text ident
pp (FCall ident exprs) = text ident <> lparen <>
(hsep $ punctuate comma $ map pp exprs) <> rparen
pp (FFilter lst ident filterFn) = lparen <> text ident <+> text "<*" <+> pp lst <+>
char '|' $+$ nest 2 (pp filterFn) $+$ rparen
frender :: [FStmt] -> Doc
frender stmts = vcat (map pp stmts)
|
hyPiRion/hs-playground
|
fun-to-imp/src/FAst.hs
|
unlicense
| 1,109
| 0
| 12
| 332
| 439
| 226
| 213
| 29
| 1
|
import AdventOfCode (readInputFile)
import Data.List (isInfixOf, tails)
nice1 :: String -> Bool
nice1 s = count (`elem` "aeiou") s >= 3 && not (any bad pairs) && any (uncurry (==)) pairs
where bad ('a', 'b') = True
bad ('c', 'd') = True
bad ('p', 'q') = True
bad ('x', 'y') = True
bad _ = False
pairs = zip s (drop 1 s)
nice2 :: String -> Bool
nice2 s = aba && any pairRepeats (tails s)
where aba = any (uncurry (==)) (zip s (drop 2 s))
pairRepeats (a:b:xs) = [a, b] `isInfixOf` xs
pairRepeats _ = False
count :: (a -> Bool) -> [a] -> Int
count f = length . filter f
main :: IO ()
main = do
s <- readInputFile
let l = lines s
print (count nice1 l)
print (count nice2 l)
|
petertseng/adventofcode-hs
|
bin/05_nice_strings.hs
|
apache-2.0
| 752
| 0
| 11
| 220
| 377
| 198
| 179
| 23
| 5
|
data Offer a = Present a
| PercentDiscount Float
| AbsoluteDiscount Float
| Restrict [a] (Offer a)
| From Integer (Offer a)
| Until Integer (Offer a)
| Extend Integer (Offer a)
| Both (Offer a) (Offer a)
| BetterOf (Offer a) (Offer a)
| If (Expr a) (Offer a) (Offer a)
deriving (Show)
data Expr a = AmountOf a | PriceOf a
| TotalNumberProducts | TotalPrice
| IVal Integer | FVal Float
| (Expr a) :+: (Expr a)
| (Expr a) :*: (Expr a)
| (Expr a) :<: (Expr a)
| (Expr a) :<=: (Expr a)
| (Expr a) :>: (Expr a)
| (Expr a) :>=: (Expr a)
| (Expr a) :&&: (Expr a)
| (Expr a) :||: (Expr a)
| Not (Expr a)
deriving (Show)
noOffer :: Offer a
noOffer = AbsoluteDiscount 0
v :: Offer String
v = Until 30 $ BetterOf (AbsoluteDiscount 10.0)
(Both (Present "ballon")
(If (TotalPrice :>: IVal 100) (PercentDiscount 5.0)
noOffer))
period :: Integer -> Integer -> Offer a -> Offer a
period f d o = From d (Until (f+d) o)
allOf :: [a] -> Offer a
allOf os = Restrict os noOffer
v1 = period 3 5 (Both (Both (Present "ballon") (Present "choco muffin")) (PercentDiscount 10.0))
-- oops, illegal expression, but it still type checks
incorrectExpression :: Expr Char
incorrectExpression = TotalPrice :||: (TotalNumberProducts :<: PriceOf 'a')
data Expr1 a r where
|
egaburov/funstuff
|
Haskell/dsl_fold/offer.hs
|
apache-2.0
| 1,625
| 0
| 13
| 618
| 599
| 316
| 283
| -1
| -1
|
-- Copyright (C) 2013-2014 Fraser Tweedale
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE OverloadedStrings #-}
module Types where
import Data.Aeson
import qualified Data.ByteString as BS
import Data.List.NonEmpty
import Network.URI (parseURI)
import Test.Hspec
import Crypto.JOSE.Types
spec :: Spec
spec = do
base64OctetsSpec
uriSpec
base64IntegerSpec
sizedBase64IntegerSpec
base64X509Spec
base64OctetsSpec :: Spec
base64OctetsSpec = describe "Base64Octets" $
it "can be read from JSON" $ do
eitherDecode "[\"AxY8DCtDaGlsbGljb3RoZQ\"]" `shouldBe` Right [Base64Octets iv]
eitherDecode "[\"9hH0vgRfYgPnAHOd8stkvw\"]" `shouldBe` Right [Base64Octets tag]
where
iv = BS.pack [3, 22, 60, 12, 43, 67, 104, 105, 108, 108, 105, 99, 111, 116, 104, 101]
tag = BS.pack [246, 17, 244, 190, 4, 95, 98, 3, 231, 0, 115, 157, 242, 203, 100, 191]
uriSpec :: Spec
uriSpec = describe "URI typeclasses" $ do
it "gets parsed from JSON correctly" $ do
decode "[\"http://example.com\"]" `shouldBe`
fmap (fmap (:[])) parseURI "http://example.com"
decode "[\"foo\"]" `shouldBe` (Nothing :: Maybe [URI])
it "gets formatted to JSON correctly" $
fmap toJSON (Network.URI.parseURI "http://example.com")
`shouldBe` Just (String "http://example.com")
base64IntegerSpec :: Spec
base64IntegerSpec = describe "Base64Integer" $ do
it "parses from JSON correctly" $ do
decode "[\"AQAC\"]" `shouldBe` Just [Base64Integer 65538]
decode "[\"????\"]" `shouldBe` (Nothing :: Maybe [Base64Integer])
it "formats to JSON correctly" $
toJSON (Base64Integer 65538) `shouldBe` "AQAC"
it "rejects empty string" $
decode "[\"\"]" `shouldBe` (Nothing :: Maybe [Base64Integer])
it "rejects leading zero" $
decode "[\"AD8\"]" `shouldBe` (Nothing :: Maybe [Base64Integer])
it "decodes AA as zero" $
decode "[\"AA\"]" `shouldBe` Just [Base64Integer 0]
it "encodes zero as AA" $
toJSON (Base64Integer 0) `shouldBe` "AA"
sizedBase64IntegerSpec :: Spec
sizedBase64IntegerSpec = describe "SizedBase64Integer" $ do
it "parses from JSON correctly" $ do
decode "[\"AQAC\"]" `shouldBe` Just [SizedBase64Integer 3 65538]
decode "[\"????\"]" `shouldBe` (Nothing :: Maybe [SizedBase64Integer])
it "formats to JSON correctly" $
toJSON (SizedBase64Integer 4 1) `shouldBe` "AAAAAQ"
-- JWS Appending B. "x5c" (X.509 Certificate Chain) Examples
--
base64X509Spec :: Spec
base64X509Spec = describe "Base64X509" $
it "parses from JSON correctly and encodes to input string" $
let decoded = decode x5cExample :: Maybe (NonEmpty Base64X509)
in fmap encode decoded `shouldBe` Just x5cExample
where
x5cExample = "[\"\
\MIIE3jCCA8agAwIBAgICAwEwDQYJKoZIhvcNAQEFBQAwYzELMAkGA1UEBhMCVVM\
\xITAfBgNVBAoTGFRoZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR2\
\8gRGFkZHkgQ2xhc3MgMiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjExM\
\TYwMTU0MzdaFw0yNjExMTYwMTU0MzdaMIHKMQswCQYDVQQGEwJVUzEQMA4GA1UE\
\CBMHQXJpem9uYTETMBEGA1UEBxMKU2NvdHRzZGFsZTEaMBgGA1UEChMRR29EYWR\
\keS5jb20sIEluYy4xMzAxBgNVBAsTKmh0dHA6Ly9jZXJ0aWZpY2F0ZXMuZ29kYW\
\RkeS5jb20vcmVwb3NpdG9yeTEwMC4GA1UEAxMnR28gRGFkZHkgU2VjdXJlIENlc\
\nRpZmljYXRpb24gQXV0aG9yaXR5MREwDwYDVQQFEwgwNzk2OTI4NzCCASIwDQYJ\
\KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMQt1RWMnCZM7DI161+4WQFapmGBWTt\
\wY6vj3D3HKrjJM9N55DrtPDAjhI6zMBS2sofDPZVUBJ7fmd0LJR4h3mUpfjWoqV\
\Tr9vcyOdQmVZWt7/v+WIbXnvQAjYwqDL1CBM6nPwT27oDyqu9SoWlm2r4arV3aL\
\GbqGmu75RpRSgAvSMeYddi5Kcju+GZtCpyz8/x4fKL4o/K1w/O5epHBp+YlLpyo\
\7RJlbmr2EkRTcDCVw5wrWCs9CHRK8r5RsL+H0EwnWGu1NcWdrxcx+AuP7q2BNgW\
\JCJjPOq8lh8BJ6qf9Z/dFjpfMFDniNoW1fho3/Rb2cRGadDAW/hOUoz+EDU8CAw\
\EAAaOCATIwggEuMB0GA1UdDgQWBBT9rGEyk2xF1uLuhV+auud2mWjM5zAfBgNVH\
\SMEGDAWgBTSxLDSkdRMEXGzYcs9of7dqGrU4zASBgNVHRMBAf8ECDAGAQH/AgEA\
\MDMGCCsGAQUFBwEBBCcwJTAjBggrBgEFBQcwAYYXaHR0cDovL29jc3AuZ29kYWR\
\keS5jb20wRgYDVR0fBD8wPTA7oDmgN4Y1aHR0cDovL2NlcnRpZmljYXRlcy5nb2\
\RhZGR5LmNvbS9yZXBvc2l0b3J5L2dkcm9vdC5jcmwwSwYDVR0gBEQwQjBABgRVH\
\SAAMDgwNgYIKwYBBQUHAgEWKmh0dHA6Ly9jZXJ0aWZpY2F0ZXMuZ29kYWRkeS5j\
\b20vcmVwb3NpdG9yeTAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQEFBQADggE\
\BANKGwOy9+aG2Z+5mC6IGOgRQjhVyrEp0lVPLN8tESe8HkGsz2ZbwlFalEzAFPI\
\UyIXvJxwqoJKSQ3kbTJSMUA2fCENZvD117esyfxVgqwcSeIaha86ykRvOe5GPLL\
\5CkKSkB2XIsKd83ASe8T+5o0yGPwLPk9Qnt0hCqU7S+8MxZC9Y7lhyVJEnfzuz9\
\p0iRFEUOOjZv2kWzRaJBydTXRE4+uXR21aITVSzGh6O1mawGhId/dQb8vxRMDsx\
\uxN89txJx9OjxUUAiKEngHUuHqDTMBqLdElrRhjZkAzVvb3du6/KFUJheqwNTrZ\
\EjYx8WnM25sgVjOuH0aBsXBTWVU+4=\",\"\
\MIIE+zCCBGSgAwIBAgICAQ0wDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1Z\
\hbGlDZXJ0IFZhbGlkYXRpb24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIE\
\luYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENsYXNzIDIgUG9saWN5IFZhbGlkYXRpb\
\24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0LmNvbS8x\
\IDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTA0MDYyOTE3MDY\
\yMFoXDTI0MDYyOTE3MDYyMFowYzELMAkGA1UEBhMCVVMxITAfBgNVBAoTGFRoZS\
\BHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28gRGFkZHkgQ2xhc3MgM\
\iBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQADggEN\
\ADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XC\
\APVYYYwhv2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux\
\6wwdhFJ2+qN1j3hybX2C32qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLO\
\tXiEqITLdiOr18SPaAIBQi2XKVlOARFmR6jYGB0xUGlcmIbYsUfb18aQr4CUWWo\
\riMYavx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmYvLEHZ6IVDd2gWMZ\
\Eewo+YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjggHhMIIB3TAdBgNVHQ\
\4EFgQU0sSw0pHUTBFxs2HLPaH+3ahq1OMwgdIGA1UdIwSByjCBx6GBwaSBvjCBu\
\zEkMCIGA1UEBxMbVmFsaUNlcnQgVmFsaWRhdGlvbiBOZXR3b3JrMRcwFQYDVQQK\
\Ew5WYWxpQ2VydCwgSW5jLjE1MDMGA1UECxMsVmFsaUNlcnQgQ2xhc3MgMiBQb2x\
\pY3kgVmFsaWRhdGlvbiBBdXRob3JpdHkxITAfBgNVBAMTGGh0dHA6Ly93d3cudm\
\FsaWNlcnQuY29tLzEgMB4GCSqGSIb3DQEJARYRaW5mb0B2YWxpY2VydC5jb22CA\
\QEwDwYDVR0TAQH/BAUwAwEB/zAzBggrBgEFBQcBAQQnMCUwIwYIKwYBBQUHMAGG\
\F2h0dHA6Ly9vY3NwLmdvZGFkZHkuY29tMEQGA1UdHwQ9MDswOaA3oDWGM2h0dHA\
\6Ly9jZXJ0aWZpY2F0ZXMuZ29kYWRkeS5jb20vcmVwb3NpdG9yeS9yb290LmNybD\
\BLBgNVHSAERDBCMEAGBFUdIAAwODA2BggrBgEFBQcCARYqaHR0cDovL2NlcnRpZ\
\mljYXRlcy5nb2RhZGR5LmNvbS9yZXBvc2l0b3J5MA4GA1UdDwEB/wQEAwIBBjAN\
\BgkqhkiG9w0BAQUFAAOBgQC1QPmnHfbq/qQaQlpE9xXUhUaJwL6e4+PrxeNYiY+\
\Sn1eocSxI0YGyeR+sBjUZsE4OWBsUs5iB0QQeyAfJg594RAoYC5jcdnplDQ1tgM\
\QLARzLrUc+cb53S8wGd9D0VmsfSxOaFIqII6hR8INMqzW/Rn453HWkrugp++85j\
\09VZw==\",\"\
\MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ\
\0IFZhbGlkYXRpb24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNT\
\AzBgNVBAsTLFZhbGlDZXJ0IENsYXNzIDIgUG9saWN5IFZhbGlkYXRpb24gQXV0a\
\G9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkq\
\hkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNjAwMTk1NFoXDTE\
\5MDYyNjAwMTk1NFowgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTm\
\V0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZ\
\XJ0IENsYXNzIDIgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQD\
\ExhodHRwOi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9\
\AdmFsaWNlcnQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDOOnHK5a\
\vIWZJV16vYdA757tn2VUdZZUcOBVXc65g2PFxTXdMwzzjsvUGJ7SVCCSRrCl6zf\
\N1SLUzm1NZ9WlmpZdRJEy0kTRxQb7XBhVQ7/nHk01xC+YDgkRoKWzk2Z/M/VXwb\
\P7RfZHM047QSv4dk+NoS/zcnwbNDu+97bi5p9wIDAQABMA0GCSqGSIb3DQEBBQU\
\AA4GBADt/UG9vUJSZSWI4OB9L+KXIPqeCgfYrx+jFzug6EILLGACOTb2oWH+heQ\
\C1u+mNr0HZDzTuIYEZoDJJKPTEjlbVUjP9UNV+mWwD5MlM/Mtsq2azSiGM5bUMM\
\j4QssxsodyamEwCW/POuZ6lcg5Ktz885hZo+L7tdEy8W9ViH0Pd\"]"
|
frasertweedale/hs-jose
|
test/Types.hs
|
apache-2.0
| 8,097
| 0
| 16
| 931
| 774
| 414
| 360
| 59
| 1
|
module Database.VCache.PVar
( PVar
, newPVar
, newPVars
, newPVarIO
, newPVarsIO
, loadRootPVar
, loadRootPVarIO
, readPVar
, readPVarIO
, writePVar
, modifyPVar
, modifyPVar'
, swapPVar
, pvar_space
, unsafePVarAddr
, unsafePVarRefct
) where
import Control.Concurrent.STM
import Database.VCache.Types
import Database.VCache.Alloc ( newPVar, newPVars, newPVarIO, newPVarsIO
, loadRootPVar, loadRootPVarIO)
import Database.VCache.Read (readRefctIO)
-- | Read a PVar as part of a transaction.
readPVar :: PVar a -> VTx a
readPVar pvar =
getVTxSpace >>= \ space ->
if space /= pvar_space pvar then fail eBadSpace else
liftSTM $ readTVar (pvar_data pvar) >>= \case { (RDV v) -> return v }
{-# INLINABLE readPVar #-}
-- Note that readPVar and readPVarIO must be strict in RDV in order to force
-- the initial, lazy read from the database. This is the only reason for RDV.
-- Without forcing here, a lazy read might return a value from an update.
-- | Read a PVar in the IO monad.
--
-- This is more efficient than a full transaction. It simply peeks at
-- the underlying TVar with readTVarIO. Durability of the value read
-- is not guaranteed.
readPVarIO :: PVar a -> IO a
readPVarIO pv =
readTVarIO (pvar_data pv) >>= \case { (RDV v) -> return v }
{-# INLINE readPVarIO #-}
eBadSpace :: String
eBadSpace = "VTx: mismatch between VTx VSpace and PVar VSpace"
-- | Write a PVar as part of a transaction.
writePVar :: PVar a -> a -> VTx ()
writePVar pvar v =
getVTxSpace >>= \ space ->
if space /= pvar_space pvar then fail eBadSpace else
markForWrite pvar v >>
liftSTM (writeTVar (pvar_data pvar) (RDV v))
{-# INLINABLE writePVar #-}
-- | Modify a PVar.
modifyPVar :: PVar a -> (a -> a) -> VTx ()
modifyPVar var f = do
x <- readPVar var
writePVar var (f x)
{-# INLINE modifyPVar #-}
-- | Modify a PVar, strictly.
modifyPVar' :: PVar a -> (a -> a) -> VTx ()
modifyPVar' var f = do
x <- readPVar var
writePVar var $! f x
{-# INLINE modifyPVar' #-}
-- | Swap contents of a PVar for a new value.
swapPVar :: PVar a -> a -> VTx a
swapPVar var new = do
old <- readPVar var
writePVar var new
return old
{-# INLINE swapPVar #-}
-- | Each PVar has a stable address in the VCache. This address will
-- be very stable, but is not deterministic and isn't really something
-- you should treat as meaningful information about the PVar. Mostly,
-- this function exists to support hashtables or memoization with
-- PVar keys.
--
-- The Show instance for PVars will also show the address.
unsafePVarAddr :: PVar a -> Address
unsafePVarAddr = pvar_addr
{-# INLINE unsafePVarAddr #-}
-- | This function allows developers to access the reference count
-- for the PVar that is currently recorded in the database. This may
-- be useful for heuristic purposes. However, caveats are needed:
--
-- First, because the VCache writer operates in a background thread,
-- the reference count returned here may be slightly out of date.
--
-- Second, it is possible that VCache will eventually use some other
-- form of garbage collection than reference counting. This function
-- should be considered an unstable element of the API.
--
-- Root PVars start with one root reference.
unsafePVarRefct :: PVar a -> IO Int
unsafePVarRefct var = readRefctIO (pvar_space var) (pvar_addr var)
|
dmbarbour/haskell-vcache
|
hsrc_lib/Database/VCache/PVar.hs
|
bsd-2-clause
| 3,417
| 0
| 13
| 744
| 619
| 337
| 282
| -1
| -1
|
module Bankotrav.Compression where
import Data.List (foldl', elemIndex)
import Data.Maybe (fromMaybe)
import Bankotrav.Types
import Bankotrav.Base
import Bankotrav.Counting
compressBoard :: Board -> Int
compressBoard board = fst $ foldl' step (0, emptyBoard) boardIndices
where step (acc, bi) i =
let cell = getCell board i
choices = validCells bi i
choice_i = fromMaybe (error "impossible") $ elemIndex cell choices
bi' = setCell bi i cell
acc' = acc + sum (map (nPossibleBoards . setCell bi i) (take choice_i choices))
in (acc', bi')
decompressBoard :: Int -> Board
decompressBoard idx = completeBoard $ snd $ foldl' step (idx, emptyBoard) boardIndices
where step (acc, bi) i =
let choices = validCells bi i
(choice, prev_sum) = findChoice 0 choices
acc' = acc - prev_sum
bi' = setCell bi i choice
in (acc', bi')
where findChoice cur (choice : choices) =
let new = nPossibleBoards $ setCell bi i choice
cur' = cur + new
in if cur' > acc
then (choice, cur)
else findChoice cur' choices
findChoice _ [] = error "impossible"
|
Athas/banko
|
bankotrav/src/Bankotrav/Compression.hs
|
bsd-2-clause
| 1,298
| 0
| 17
| 442
| 407
| 214
| 193
| 30
| 3
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Controller
( withYwitter
) where
import Ywitter
import Settings
import Yesod.Helpers.Static
import Yesod.Helpers.Auth
import Database.Persist.GenericSql
import Data.ByteString (ByteString)
-- Import all relevant handler modules here.
import Handler.Root
import Handler.Setting
import Handler.User
import Handler.Status
-- This line actually creates our YesodSite instance. It is the second half
-- of the call to mkYesodData which occurs in Ywitter.hs. Please see
-- the comments there for more details.
mkYesodDispatch "Ywitter" resourcesYwitter
-- Some default handlers that ship with the Yesod site template. You will
-- very rarely need to modify this.
getFaviconR :: Handler ()
getFaviconR = sendFile "image/x-icon" "favicon.ico"
getRobotsR :: Handler RepPlain
getRobotsR = return $ RepPlain $ toContent ("User-agent: *" :: ByteString)
-- 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.
withYwitter :: (Application -> IO a) -> IO a
withYwitter f = Settings.withConnectionPool $ \p -> do
runConnectionPool (runMigration migrateAll) p
let h = Ywitter s p
toWaiApp h >>= f
where
s = static Settings.staticdir
|
tanakh/Ywitter
|
Controller.hs
|
bsd-2-clause
| 1,493
| 0
| 12
| 236
| 226
| 126
| 100
| 27
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module MainTest where
import Data.Text (Text)
import qualified Data.Text as T
import qualified FastTags
import FastTags hiding (process)
import qualified Lexer
import Token
import Test.Tasty
import Test.Tasty.HUnit
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "tests"
[ testTokenize
, testTokenizeWithNewlines
, testStripComments
, testBreakBlocks
, testProcessAll
, testProcess
, testStripCpp
]
test :: (Show a, Eq b, Show b) => (a -> b) -> a -> b -> TestTree
test f x expected = testCase (take 70 $ show x) $ f x @?= expected
testTokenize :: TestTree
testTokenize = testGroup "tokenize"
[ "xyz -- abc" ==> [T "xyz", Newline 0]
, "xyz --- abc" ==> [T "xyz", Newline 0]
, " {- foo -}" ==> [Newline 0]
, " {- foo \n\
\\n\
\-}" ==> [Newline 0]
, " {- foo {- bar-} -}" ==> [Newline 0]
, " {-# INLINE #-}" ==> [Newline 0]
, "a::b->c" ==> [T "a", DoubleColon, T "b", Arrow, T "c", Newline 0]
, "a∷b→c" ==> [T "a", DoubleColon, T "b", Arrow, T "c", Newline 0]
, "x{-\n bc#-}\n" ==> [T "x", Newline 0]
, "X.Y" ==> [T "X.Y", Newline 0]
, "a=>b" ==> [T "a", Implies, T "b", Newline 0]
, "a ⇒ b" ==> [T "a", Implies, T "b", Newline 0]
, "x9" ==> [T "x9", Newline 0]
-- , "9x" ==> ["nl 0", "9", "x"]
, "x :+: y" ==> [T "x", T ":+:", T "y", Newline 0]
, "(#$)" ==> [LParen, T "#$", RParen, Newline 0]
, "Data.Map.map" ==> [T "Data.Map.map", Newline 0]
, "Map.map" ==> [T "Map.map", Newline 0]
, "forall a. f a" ==> [KWForall, T "a", Dot, T "f", T "a", Newline 0]
, "forall a . Foo" ==> [KWForall, T "a", Dot, T "Foo", Newline 0]
, "forall a. Foo" ==> [KWForall, T "a", Dot, T "Foo", Newline 0]
, "forall a .Foo" ==> [KWForall, T "a", Dot, T "Foo", Newline 0]
, "forall a.Foo" ==> [KWForall, T "a", Dot, T "Foo", Newline 0]
, "$#-- hi" ==> [T "$#--", T "hi", Newline 0]
, "(*), (-)" ==> [LParen, T "*", RParen, Comma, LParen, T "-", RParen, Newline 0]
, "(.::)" ==> [LParen, T ".::", RParen, Newline 0]
-- we rely on this behavior
, "data (:+) a b" ==> [KWData, LParen, T ":+", RParen, T "a", T "b", Newline 0]
, "data (.::+::) a b" ==> [KWData, LParen, T ".::+::", RParen, T "a", T "b", Newline 0]
-- string tokenization
, "foo \"bar\" baz" ==> [T "foo", String, T "baz", Newline 0]
-- multiline string
, "foo \"bar\\\n\
\ \\bar\" baz" ==> [T "foo", String, T "baz", Newline 0]
, "(\\err -> case err of Foo -> True; _ -> False)" ==>
[LParen, T "\\", T "err", Arrow, KWCase, T "err", KWOf, T "Foo", Arrow, T "True", T "_", Arrow, T "False", RParen, Newline 0]
, "foo = \"foo\\n\\\n\
\ \\\" bar" ==>
[T "foo", Equals, String, T "bar", Newline 0]
, "foo = \"foo\\n\\\n\
\ \\x\" bar" ==>
[T "foo", Equals, String, T "bar", Newline 0]
, tokenizeSplices
]
where
(==>) = test f
f :: Text -> [TokenVal]
f = tail . map valOf . unstrippedTokensOf . tokenize
tokenizeSplices = testGroup "tokenize splices"
[ "$(foo)" ==> [SpliceStart, T "foo", RParen, Newline 0]
, "$(foo [| baz |])" ==> [SpliceStart, T "foo", QuasiquoterStart, QuasiquoterEnd, RParen, Newline 0]
, "$(foo [bar| baz |])" ==> [SpliceStart, T "foo", QuasiquoterStart, QuasiquoterEnd, RParen, Newline 0]
, "$(foo [bar| bar!\nbaz!\n $(baz) |])" ==>
[SpliceStart, T "foo", QuasiquoterStart, SpliceStart, T "baz", RParen, QuasiquoterEnd, RParen, Newline 0]
]
testTokenizeWithNewlines :: TestTree
testTokenizeWithNewlines = testGroup "tokenize with newlines"
[ "1\n2\n" ==> [Newline 0, T "1", Newline 0, T "2", Newline 0]
, " 11\n 11\n" ==> [Newline 1, T "11", Newline 1, T "11", Newline 0]
]
where
(==>) = test f
f = map valOf . unstrippedTokensOf . tokenize
testStripComments :: TestTree
testStripComments = testGroup "stripComments"
[ "hello -- there" ==> ["nl 0", "hello", "nl 0"]
, "hello --there" ==> ["nl 0", "hello", "nl 0"]
, "hello {- there -} fred" ==> ["nl 0", "hello", "fred", "nl 0"]
, "hello -- {- there -}\nfred" ==> ["nl 0", "hello", "nl 0", "fred", "nl 0"]
, "{-# LANG #-} hello {- there {- nested -} comment -} fred" ==> ["nl 0", "hello", "fred", "nl 0"]
, "hello {-\nthere\n------}\n fred" ==> ["nl 0", "hello", "nl 1", "fred", "nl 0"]
, "hello {- \nthere\n ------} \n fred" ==> ["nl 0", "hello", "nl 1", "fred", "nl 0"]
, "hello {-\nthere\n-----}\n fred" ==> ["nl 0", "hello", "nl 1", "fred", "nl 0"]
, "hello {- \nthere\n -----} \n fred" ==> ["nl 0", "hello", "nl 1", "fred", "nl 0"]
, "hello {-\n-- there -}" ==> ["nl 0", "hello", "nl 0"]
, "foo --- my comment\n--- my other comment\nbar" ==> ["nl 0", "foo", "nl 0", "nl 0", "bar", "nl 0"]
]
where
(==>) = test f
f = extractTokens . tokenize
testBreakBlocks :: TestTree
testBreakBlocks = testGroup "breakBlocks"
[ "1\n2\n" ==> [["1"], ["2"]]
, "1\n 1\n2\n" ==> [["1", "1"], ["2"]]
, "1\n 1\n 1\n2\n" ==> [["1", "1", "1"], ["2"]]
-- intervening blank lines are ignored
, "1\n 1\n\n 1\n2\n" ==> [["1", "1", "1"], ["2"]]
, "1\n\n\n 1\n2\n" ==> [["1", "1"], ["2"]]
, "1\n 11\n 11\n" ==> [["1", "11", "11"]]
, " 11\n 11\n" ==> [["11"], ["11"]]
]
where
(==>) = test f
f = map (extractTokens . UnstrippedTokens . FastTags.stripNewlines)
. FastTags.breakBlocks . tokenize
testProcessAll :: TestTree
testProcessAll = testGroup "processAll"
[ ["data X", "module X"] ==> ["fn0:1 X Type", "fn1:1 X Module"]
-- Type goes ahead of Module.
, ["module X\n\
\data X"] ==> ["fn0:2 X Type", "fn0:1 X Module"]
-- Extra X was filtered.
, ["module X\n\
\data X = X\n"] ==> ["fn0:2 X Type", "fn0:2 X Constructor", "fn0:1 X Module"]
, ["module X\n\
\data X a =\n\
\ X a\n"] ==> ["fn0:2 X Type", "fn0:3 X Constructor", "fn0:1 X Module"]
, ["newtype A f a b = A\n\
\ { unA :: f (a -> b) }"]
==> ["fn0:1 A Type", "fn0:1 A Constructor", "fn0:2 unA Function"]
]
where
(==>) = test f
f = map showTag
. FastTags.processAll
. map (\(i, t) -> fst $ FastTags.process ("fn" ++ show i) False t)
. zip [0..]
showTag (Pos p (TagVal text typ)) =
unwords [show p, T.unpack text, show typ]
testProcess :: TestTree
testProcess = testGroup "process"
[ testPrefixes
, testData
, testGADT
, testFamilies
, testFunctions
, testClass
, testInstance
, testLiterate
, testPatterns
, testFFI
]
testPrefixes :: TestTree
testPrefixes = testGroup "prefix tracking"
[ "module Bar.Foo where\n"
==>
[Pos (SrcPos fn 1 "module Bar.Foo") (TagVal "Foo" Module)]
, "newtype Foo a b =\n\
\\tBar x y z\n"
==>
[ Pos (SrcPos fn 2 "\tBar") (TagVal "Bar" Constructor)
, Pos (SrcPos fn 1 "newtype Foo") (TagVal "Foo" Type)
]
, "f :: A -> B\n\
\g :: C -> D\n\
\data D = C {\n\
\\tf :: A\n\
\\t}\n"
==>
[ Pos (SrcPos fn 3 "data D = C") (TagVal "C" Constructor)
, Pos (SrcPos fn 3 "data D") (TagVal "D" Type)
, Pos (SrcPos fn 4 "\tf") (TagVal "f" Function)
, Pos (SrcPos fn 1 "f") (TagVal "f" Function)
, Pos (SrcPos fn 2 "g") (TagVal "g" Function)
]
]
where
(==>) = test f
f = fst . FastTags.process fn True
fn = "fn.hs"
testData :: TestTree
testData = testGroup "data"
[ "data X\n" ==> ["X"]
, "data X = X Int\n" ==> ["X", "X"]
, "data Foo = Bar | Baz" ==> ["Bar", "Baz", "Foo"]
, "data Foo =\n\tBar\n\t| Baz" ==> ["Bar", "Baz", "Foo"]
-- Records.
, "data Foo a = Bar { field :: Field }" ==> ["Bar", "Foo", "field"]
, "data R = R { a::X, b::Y }" ==> ["R", "R", "a", "b"]
, "data R = R { a∷X, b∷Y }" ==> ["R", "R", "a", "b"]
, "data R = R {\n\ta::X\n\t, b::Y\n\t}" ==> ["R", "R", "a", "b"]
, "data R = R {\n\ta,b::X\n\t}" ==> ["R", "R", "a", "b"]
, "data R = R {\n\
\ a :: !RealTime\n\
\ , b :: !RealTime\n\
\}"
==>
["R", "R", "a", "b"]
, "data Rec = Rec {\n\
\ a :: Int\n\
\, b :: !Double\n\
\, c :: Maybe Rec\
\\n\
\}"
==>
["Rec", "Rec", "a", "b", "c"]
, "data X = X !Int" ==> ["X", "X"]
, "data X = Y !Int !X | Z" ==> ["X", "Y", "Z"]
, "data X = Y :+: !Z | !X `Mult` X" ==> [":+:", "Mult", "X"]
, "data X = !Y `Add` !Z" ==> ["Add", "X"]
, "data X = forall a. Y a" ==> ["X", "Y"]
, "data X = forall a . Y a" ==> ["X", "Y"]
, "data X = forall a .Y a" ==> ["X", "Y"]
, "data X = forall a.Y a" ==> ["X", "Y"]
, "data X = forall a. Eq a => Y a" ==> ["X", "Y"]
, "data X = forall a. (Eq a) => Y a" ==> ["X", "Y"]
, "data X = forall (a :: Nat). (Eq' a) => Y a" ==> ["X", "Y"]
, "data X = forall a. (Eq a, Ord a) => Y a" ==> ["X", "Y"]
-- "data X = forall a. Ref :<: a => Y a" ==> ["X", "Y"]
-- "data X = forall a. (:<:) Ref a => Y a" ==> ["X", "Y"]
, "data X = forall a. ((:<:) Ref a) => Y a" ==> ["X", "Y"]
, "data X = forall a. Y !a" ==> ["X", "Y"]
, "data X = forall a. (Eq a, Ord a) => Y !a" ==> ["X", "Y"]
, "data Foo a = \n\
\ Plain Int\n\
\ | forall a. Bar a Int\n\
\ | forall a b. Baz b a\n\
\ | forall a . Quux a \
\ | forall a .Quuz a"
==>
["Bar", "Baz", "Foo", "Plain", "Quux", "Quuz"]
, "data X a = Add a " ==> ["Add", "X"]
, "data Eq a => X a = Add a" ==> ["Add", "X"]
, "data (Eq a) => X a = Add a" ==> ["Add", "X"]
, "data (Eq a, Ord a) => X a = Add a" ==> ["Add", "X"]
, "data (Eq (a), Ord (a)) => X a = Add a" ==> ["Add", "X"]
-- These are hard-to-deal-with uses of contexts, which are probably not that
-- common and therefoce can be ignored.
-- "data Ref :<: f => X f = RRef f" ==> ["X", "RRef"]
-- "data a :<: b => X a b = Add a" ==> ["X", "Add"]
, "data (a :<: b) => X a b = Add a" ==> ["Add", "X"]
, "data a :><: b = a :>|<: b" ==> [":><:", ":>|<:"]
, "data (:><:) a b = (:>|<:) a b" ==> [":><:", ":>|<:"]
, "data (:><:) a b = Foo b | (:>|<:) a b" ==> [":><:", ":>|<:", "Foo"]
, "data (:><:) a b = Foo b | forall c. (:>|<:) a c" ==> [":><:", ":>|<:", "Foo"]
, "data (:><:) a b = Foo b | forall c. (Eq c) => (:>|<:) a c" ==> [":><:", ":>|<:", "Foo"]
, "data (:><:) a b = Foo b | forall c. Eq c => (:>|<:) a c" ==> [":><:", ":>|<:", "Foo"]
, "newtype Eq a => X a = Add a" ==> ["Add", "X"]
, "newtype (Eq a) => X a = Add a" ==> ["Add", "X"]
, "newtype (Eq a, Ord a) => X a = Add a" ==> ["Add", "X"]
, "newtype (u :*: v) z = X" ==> [":*:", "X"]
, "data (u :*: v) z = X" ==> [":*:", "X"]
, "type (u :*: v) z = (u, v, z)" ==> [":*:"]
, "newtype ((u :: (* -> *) -> *) :*: v) z = X" ==> [":*:", "X"]
, "data ((u :: (* -> *) -> *) :*: v) z = X" ==> [":*:", "X"]
, "type ((u :: (* -> *) -> *) :*: v) z = (u, v, z)" ==> [":*:"]
, "newtype (Eq (v z)) => ((u :: (* -> *) -> *) :*: v) z = X" ==> [":*:", "X"]
, "data (Eq (v z)) => ((u :: (* -> *) -> *) :*: v) z = X" ==> [":*:", "X"]
, "type (Eq (v z)) => ((u :: (* -> *) -> *) :*: v) z = (u, v, z)" ==> [":*:"]
, "newtype Eq (v z) => ((u :: (* -> *) -> *) :*: v) z = X" ==> [":*:", "X"]
, "data Eq (v z) => ((u :: (* -> *) -> *) :*: v) z = X" ==> [":*:", "X"]
, "type Eq (v z) => ((u :: (* -> *) -> *) :*: v) z = (u, v, z)" ==> [":*:"]
, "newtype (Eq (v z)) => ((u :: (* -> *) -> *) `Foo` v) z = X" ==> ["Foo", "X"]
, "data (Eq (v z)) => ((u :: (* -> *) -> *) `Foo` v) z = X" ==> ["Foo", "X"]
, "type (Eq (v z)) => ((u :: (* -> *) -> *) `Foo` v) z = (u, v, z)" ==> ["Foo"]
, "type (Eq (v z)) => ((u ∷ (* -> *) -> *) `Foo` v) z = (u, v, z)" ==> ["Foo"]
, "newtype Eq (v z) => ((u :: (* -> *) -> *) `Foo` v) z = X" ==> ["Foo", "X"]
, "data Eq (v z) => ((u :: (* -> *) -> *) `Foo` v) z = X" ==> ["Foo", "X"]
, "type Eq (v z) => ((u :: (* -> *) -> *) `Foo` v) z = (u, v, z)" ==> ["Foo"]
, "type Eq (v z) ⇒ ((u ∷ (* → *) → *) `Foo` v) z = (u, v, z)" ==> ["Foo"]
, "data (:*:) u v z = X" ==> [":*:", "X"]
, "data (Eq (u v), Ord (z)) => (:*:) u v z = X" ==> [":*:", "X"]
, "data (u `W` v) z = X" ==> ["W", "X"]
, "data (Eq (u v), Ord (z)) => (u `W` v) z = X" ==> ["W", "X"]
, "newtype X a = Z {\n\
\ -- TODO blah\n\
\ foo :: [a] }"
==>
["X", "Z", "foo"]
, "newtype (u :*: v) z = X {\n\
\ -- my insightful comment\n\
\ extract :: (u (v z)) }"
==>
[":*:", "X", "extract"]
, "data Hadron a b = Science { f :: a, g :: a, h :: b }"
==>
["Hadron", "Science", "f", "g", "h"]
, "data Hadron a b = Science { f :: a, g :: (a, b), h :: b }"
==>
["Hadron", "Science", "f", "g", "h"]
, "data Hadron a b = forall x. Science { f :: x, h :: b }"
==>
["Hadron", "Science", "f", "h"]
, "data Hadron a b = forall x. Science { f :: [x], h :: b }"
==>
["Hadron", "Science", "f", "h"]
, "data Hadron a b = forall x y. Science { f :: (x, y), h :: b }"
==>
["Hadron", "Science", "f", "h"]
, "data Hadron a b = forall x y. Science { f :: [(x, y)], h :: b }"
==>
["Hadron", "Science", "f", "h"]
, "data Hadron a b = forall x y. Science { f :: [(Box x, Map x y)], h :: b }"
==>
["Hadron", "Science", "f", "h"]
, "data Hadron a b = forall x y. Science { f ∷ [(Box x, Map x y)], h ∷ b }"
==>
["Hadron", "Science", "f", "h"]
, "data Hadron a b = forall x y z. Science\n\
\ { f :: x\n\
\ , g :: [(Box x, Map x y, z)] \
\ }"
==>
["Hadron", "Science", "f", "g"]
, "data Hadron a b = forall x y z. Science\n\
\ { f :: x\n\
\ , g :: [(Box x, Map x y, z)] \
\ , h :: b\n\
\ }"
==>
["Hadron", "Science", "f", "g", "h"]
, "data Hadron a b = Science { h :: b }"
==>
["Hadron", "Science", "h"]
, "data Test a b =\n\
\ Foo a\n\
\ | Bar [(Maybe a, Map a b, b)]"
==>
["Bar", "Foo", "Test"]
, "data Test a b =\n\
\ Foo a\n\
\ | [(Maybe b, Map b a, a)] `Bar` [(Maybe a, Map a b, b)]"
==>
["Bar", "Foo", "Test"]
]
where
(==>) = test process
testGADT :: TestTree
testGADT = testGroup "gadt"
[ "data X where A :: X\n" ==> ["A", "X"]
, "data X where\n\tA :: X\n" ==> ["A", "X"]
, "data X where\n\tA :: X\n\tB :: X\n" ==> ["A", "B", "X"]
, "data X where\n\tA, B :: X\n" ==> ["A", "B", "X"]
, "data X :: * -> * -> * where\n\
\ A, B :: Int -> Int -> X\n"
==>
["A", "B", "X"]
, "data X ∷ * → * → * where\n\
\ A, B ∷ Int → Int → X\n"
==>
["A", "B", "X"]
, "data Vec ix where\n\
\ Nil :: Int -> Foo Int\n\
\ (:::) :: Int -> Vec Int -> Vec Int\n\
\ (.+.) :: Int -> Int -> Vec Int -> Vec Int\n"
==>
[".+.", ":::", "Nil", "Vec"]
, "data Vec ix where\n\
\ Nil :: Int -> Foo Int\n\
\ -- foo\n\
\ (:::) :: Int -> Vec Int -> Vec Int\n\
\-- bar\n\
\ (.+.) :: Int -> \n\
\ -- ^ baz\n\
\ Int -> \n\
\ Vec Int -> \n\
\Vec Int\n"
==>
[".+.", ":::", "Nil", "Vec"]
, "data NatSing (n :: Nat) where\n ZeroSing :: 'Zero\n SuccSing :: NatSing n -> NatSing ('Succ n)\n"
==>
["NatSing", "SuccSing", "ZeroSing"]
]
where
(==>) = test process
testFamilies :: TestTree
testFamilies = testGroup "families"
[ "type family X :: *\n" ==> ["X"]
, "data family X :: * -> *\n" ==> ["X"]
, "data family a ** b" ==> ["**"]
, "type family a :<: b\n" ==> [":<:"]
, "type family (a :: Nat) :<: (b :: Nat) :: Nat\n" ==> [":<:"]
, "type family (a :: Nat) `Family` (b :: Nat) :: Nat\n" ==> ["Family"]
, "type family (m :: Nat) <=? (n :: Nat) :: Bool" ==> ["<=?"]
, "type family (m ∷ Nat) <=? (n ∷ Nat) ∷ Bool" ==> ["<=?"]
, "data instance X a b = Y a | Z { unZ :: b }" ==> ["Y", "Z", "unZ"]
, "data instance (Eq a, Eq b) => X a b = Y a | Z { unZ :: b }" ==> ["Y", "Z", "unZ"]
, "data instance XList Char = XCons !Char !(XList Char) | XNil" ==> ["XCons", "XNil"]
, "newtype instance Cxt x => T [x] = A (B x) deriving (Z,W)" ==> ["A"]
, "type instance Cxt x => T [x] = A (B x)" ==> []
, "data instance G [a] b where\n\
\ G1 :: c -> G [Int] b\n\
\ G2 :: G [a] Bool"
==>
["G1", "G2"]
, "class C where\n\ttype X y :: *\n" ==> ["C", "X"]
, "class C where\n\tdata X y :: *\n" ==> ["C", "X"]
, "class C where\n\ttype X y ∷ *\n" ==> ["C", "X"]
, "class C where\n\tdata X y ∷ *\n" ==> ["C", "X"]
]
where
(==>) = test process
testFunctions :: TestTree
testFunctions = testGroup "functions"
[
-- Multiple declarations.
"a,b::X" ==> ["a", "b"]
-- With an operator.
, "(+), a :: X" ==> ["+", "a"]
-- Don't get fooled by literals.
, "1 :: Int" ==> []
-- plain functions and operators
, "(.::) :: X -> Y" ==> [".::"]
, "(:::) :: X -> Y" ==> [":::"]
, "(->:) :: X -> Y" ==> ["->:"]
, "(--+) :: X -> Y" ==> ["--+"]
, "(=>>) :: X -> Y" ==> ["=>>"]
, "_g :: X -> Y" ==> ["_g"]
, toplevelFunctionsWithoutSignatures
]
where
(==>) = test process
toplevelFunctionsWithoutSignatures =
testGroup "toplevel functions without signatures"
[ "infix 5 |+|" ==> []
, "infixl 5 |+|" ==> []
, "infixr 5 |+|" ==> []
, "f = g" ==> ["f"]
, "f :: a -> b -> a\n\
\f x y = x"
==>
["f"]
, "f x y = x" ==> ["f"]
, "f (x :+: y) z = x" ==> ["f"]
, "(x :+: y) `f` z = x" ==> ["f"]
, "(x :+: y) :*: z = x" ==> [":*:"]
, "((:+:) x y) :*: z = x" ==> [":*:"]
, "(:*:) (x :+: y) z = x" ==> [":*:"]
, "(:*:) ((:+:) x y) z = x" ==> [":*:"]
, strictMatchTests
, lazyMatchTests
, atPatternsTests
, "f x Nothing = x\n\
\f x (Just y) = y"
==>
["f"]
, "f x y = g x\n\
\ where\n\
\ g _ = y"
==>
["f"]
, "x `f` y = x" ==> ["f"]
, "(|+|) x y = x" ==> ["|+|"]
, "x |+| y = x" ==> ["|+|"]
, "(!) x y = x" ==> ["!"]
, "--- my comment" ==> []
, "foo :: Rec -> Bar\n\
\foo Rec{..} = Bar (recField + 1)" ==>
["foo"]
, "foo :: Rec -> Bar\n\
\foo Rec { bar = Baz {..}} = Bar (recField + 1)" ==>
["foo"]
]
strictMatchTests = testGroup "strict match (!)"
[ "f !x y = x" ==> ["f"]
, "f x !y = x" ==> ["f"]
, "f !x !y = x" ==> ["f"]
, "f ! x y = x" ==> ["f"]
-- this one is a bit controversial but it seems to be the way ghc parses it
, "f ! x = x" ==> ["f"]
, "(:*:) !(x :+: y) z = x" ==> [":*:"]
, "(:*:) !(!x :+: !y) !z = x" ==> [":*:"]
, "(:*:) !((:+:) x y) z = x" ==> [":*:"]
, "(:*:) !((:+:) !x !y) !z = x" ==> [":*:"]
, "(!) :: a -> b -> a\n\
\(!) x y = x"
==>
["!"]
-- this is a degenerate case since even ghc treats ! here as
-- a BangPatterns instead of operator
, "x ! y = x" ==> ["x"]
]
lazyMatchTests = testGroup "lazy match (~)"
[ "f ~x y = x" ==> ["f"]
, "f x ~y = x" ==> ["f"]
, "f ~x ~y = x" ==> ["f"]
, "f ~ x y = x" ==> ["f"]
-- this one is a bit controversial but it seems to be the way ghc parses it
, "f ~ x = x" ==> ["f"]
, "(:*:) ~(x :+: y) z = x" ==> [":*:"]
, "(:*:) ~(~x :+: ~y) ~z = x" ==> [":*:"]
, "(:*:) ~((:+:) x y) z = x" ==> [":*:"]
, "(:*:) ~((:+:) ~x ~y) ~z = x" ==> [":*:"]
, "(~) :: a -> b -> a\n\
\(~) x y = x"
==>
["~"]
-- this is a degenerate case since even ghc treats ~ here as
-- a BangPatterns instead of operator
, "x ~ y = x" ==> ["x"]
]
atPatternsTests = testGroup "at patterns (@)"
[ "f z@x y = z" ==> ["f"]
, "f x z'@y = z'" ==> ["f"]
, "f z@x z'@y = z" ==> ["f"]
, "f z@(Foo _) z'@y = z" ==> ["f"]
, "f z@(Foo _) z'@(Bar _) = z" ==> ["f"]
, "f z @ x y = z" ==> ["f"]
, "f z @ (x : xs) = z: [x: xs]" ==> ["f"]
, "f z @ (x : zs @ xs) = z: [x: zs]" ==> ["f"]
, "f z @ (zz @x : zs @ xs) = z: [zz: zs]" ==> ["f"]
, "(:*:) zzz@(x :+: y) z = x" ==> [":*:"]
, "(:*:) zzz@(zx@x :+: zy@y) zz@z = x" ==> [":*:"]
, "(:*:) zzz@((:+:) x y) z = x" ==> [":*:"]
, "(:*:) zzz@((:+:) zs@x zs@y) zz@z = x" ==> [":*:"]
, "f z@(!x) ~y = x" ==> ["f"]
]
testClass :: TestTree
testClass = testGroup "class"
[ "class (X x) => C a b where\n\tm :: a->b\n\tn :: c\n" ==> ["C", "m", "n"]
, "class (X x) ⇒ C a b where\n\tm ∷ a→b\n\tn ∷ c\n" ==> ["C", "m", "n"]
, "class (X x) => C a b | a -> b where\n\tm :: a->b\n\tn :: c\n" ==> ["C", "m", "n"]
, "class (X x) ⇒ C a b | a → b where\n\tm ∷ a→b\n\tn ∷ c\n" ==> ["C", "m", "n"]
, "class A a where f :: X\n" ==> ["A", "f"]
-- indented inside where
, "class X where\n\ta, (+) :: X\n" ==> ["+", "X", "a"]
, "class X where\n\ta :: X\n\tb, c :: Y" ==> ["X", "a", "b", "c"]
, "class X\n\twhere\n\ta :: X\n\tb, c :: Y" ==> ["X", "a", "b", "c"]
, "class X\n\twhere\n\ta ::\n\t\tX\n\tb :: Y" ==> ["X", "a", "b"]
, "class a :<: b where\n f :: a -> b" ==> [":<:", "f"]
, "class (:<:) a b where\n f :: a -> b" ==> [":<:", "f"]
, "class Eq a => a :<: b where\n f :: a -> b" ==> [":<:", "f"]
, "class a ~ 'Foo => a :<: b where\n f :: a -> b" ==> [":<:", "f"]
, "class 'Foo ~ a => a :<: b where\n f :: a -> b" ==> [":<:", "f"]
, "class (Eq a) => a :<: b where\n f :: a -> b" ==> [":<:", "f"]
, "class (a ~ 'Foo) => a :<: b where\n f :: a -> b" ==> [":<:", "f"]
, "class ('Foo ~ a) => a :<: b where\n f :: a -> b" ==> [":<:", "f"]
-- , "class a :<<<: b => a :<: b where\n f :: a -> b"
-- ==>
-- [":<:", "f"]
, "class (a :<<<: b) => a :<: b where\n f :: a -> b" ==> [":<:", "f"]
, "class (a :<<<: b) ⇒ a :<: b where\n f ∷ a → b" ==> [":<:", "f"]
, "class (Eq a, Ord b) => a :<: b where\n f :: a -> b" ==> [":<:", "f"]
, "class (Eq a, Ord b) => (a :: (* -> *) -> *) :<: b where\n f :: a -> b"
==>
[":<:", "f"]
-- this is bizzarre
, "class (Eq (a), Ord (f a [a])) => f `Z` a" ==> ["Z"]
, "class A f where\n data F f :: *\n g :: a -> f a\n h :: f a -> a"
==>
["A", "F", "g", "h"]
, "class A f where\n data F f :: *\n mkF :: f -> F f\n getF :: F f -> f"
==>
["A", "F", "getF", "mkF"]
, "class A f where\n\
\ data F f :: * -- foo\n\
\ -- bar\n\
\ -- baz\n\
\ mkF :: f -> F f\n\
\ getF :: F f -> f"
==>
["A", "F", "getF", "mkF"]
-- Not confused by a class context on a method.
, "class X a where\n\tfoo :: Eq a => a -> a\n" ==> ["X", "foo"]
, "class Category cat where\n\
\ -- | the identity morphism\n\
\ id :: cat a a\n\
\ \n\
\ -- | morphism composition\n\
\ (.) :: cat b c -> cat a b -> cat a c" ==> [".", "Category", "id"]
]
where
(==>) = test process
testInstance :: TestTree
testInstance = testGroup "instance"
[ "instance Foo Quux where\n\
\ data Bar Quux a = QBar { frob :: a }\n\
\ | QBaz { fizz :: String }\n\
\ deriving (Show)"
==>
["QBar", "QBaz", "fizz", "frob"]
, "instance Foo Quux where\n\
\ data Bar Quux a = QBar a | QBaz String deriving (Show)"
==>
["QBar", "QBaz"]
, "instance Foo Quux where\n\
\ data Bar Quux a = QBar { frob :: a }\n\
\ | QBaz { fizz :: String }\n\
\ deriving (Show)\n\
\ data IMRuunningOutOfNamesHere Quux = Whatever"
==>
["QBar", "QBaz", "Whatever", "fizz", "frob"]
-- in this test foo function should not affect tags found
, "instance Foo Quux where\n\
\ data Bar Quux a = QBar { frob :: a }\n\
\ | QBaz { fizz :: String }\n\
\ deriving (Show)\n\
\\n\
\ foo _ = QBaz \"hey there\""
==>
["QBar", "QBaz", "fizz", "frob"]
, "instance Foo Int where foo _ = 1"
==>
[]
, "instance Foo Quux where\n\
\ newtype Bar Quux a = QBar a \n\
\ deriving (Show)\n\
\\n\
\ foo _ = QBaz \"hey there\""
==>
["QBar"]
, "instance Foo Quux where\n\
\ newtype Bar Quux a = QBar { frob :: a }"
==>
["QBar", "frob"]
, "instance (Monoid w,MonadBaseControl b m) => MonadBaseControl b (JournalT w m) where\n\
\ newtype StM (JournalT w m) a =\n\
\ StMJournal { unStMJournal :: ComposeSt (JournalT w) m a }\n\
\ liftBaseWith = defaultLiftBaseWith StMJournal\n\
\ restoreM = defaultRestoreM unStMJournal\n\
\ {-# INLINE liftBaseWith #-}\n\
\ {-# INLINE restoreM #-}\n\
\"
==>
["StMJournal", "unStMJournal"]
]
where
(==>) = test process
testLiterate :: TestTree
testLiterate = testGroup "literate"
[ "> class (X x) => C a b where\n>\tm :: a->b\n>\tn :: c\n"
==>
["C", "m", "n"]
, "Test\n\\begin{code}\nclass (X x) => C a b where\n\tm :: a->b\n\tn :: c\n\\end{code}"
==>
["C", "m", "n"]
]
where
(==>) = test f
f = map untag . fst . FastTags.process "fn.lhs" False
testPatterns :: TestTree
testPatterns = testGroup "patterns"
[ "pattern Arrow a b = ConsT \"->\" [a, b]"
==>
["Arrow"]
, "pattern Arrow a b = ConsT \"->\" [a, b]\n\
\pattern Pair a b = [a, b]"
==>
["Arrow", "Pair"]
, "pattern Sub a b = Op '-' [a, b]\n\
\pattern Pair a b = [a, b]"
==>
["Pair", "Sub"]
]
where
(==>) = test process
testFFI :: TestTree
testFFI = testGroup "ffi"
[ "foreign import ccall foo :: Double -> IO Double" ==> ["foo"]
, "foreign import unsafe java foo :: Double -> IO Double" ==> ["foo"]
, "foreign import safe stdcall foo :: Double -> IO Double" ==> ["foo"]
]
where
(==>) = test process
testStripCpp :: TestTree
testStripCpp = testGroup "strip cpp"
[ "foo\n\
\#if 0\n\
\bar\n\
\baz\n\
\#endif\n\
\quux" ==> "foo\n\nbar\nbaz\n\nquux"
, "foo\n\
\#if 0\n\
\bar\n\
\#else\n\
\baz\n\
\#endif\n\
\quux" ==> "foo\n\nbar\n\nbaz\n\nquux"
, "foo\n\
\#let alignment t = \"%lu\", (unsigned long)offsetof(struct {char x__; t (y__); }, y__)\n\
\bar" ==> "foo\n\nbar"
, "foo\n\
\#let x = y\\\n\
\ z\\\n\
\ w\n\
\bar" ==> "foo\n\n\n\nbar"
]
where
(==>) = test stripCpp
process :: Text -> [String]
process = map untag . fst . FastTags.process "fn.hs" False
untag :: Pos TagVal -> String
untag (Pos _ (TagVal name _)) = T.unpack name
tokenize :: Text -> UnstrippedTokens
tokenize =
either error UnstrippedTokens . Lexer.tokenize filename trackPrefixes . FastTags.stripCpp
where
filename = "fn"
trackPrefixes = False
extractTokens :: UnstrippedTokens -> [Text]
extractTokens = map (\token -> case FastTags.valOf token of
T name -> name
Newline n -> T.pack ("nl " ++ show n)
t -> T.pack $ show t) . FastTags.unstrippedTokensOf
|
osa1/fast-tags
|
tests/MainTest.hs
|
bsd-3-clause
| 28,118
| 0
| 16
| 9,268
| 5,865
| 3,434
| 2,431
| 533
| 3
|
{-# LANGUAGE OverloadedStrings #-}
module Document where
import Control.Applicative
import Data.Attoparsec.Text
import Data.Monoid
import Data.Text
import qualified Data.Text as Text
import Test.Tasty
import Test.Tasty.HUnit
import Data.OrgMode.Parse.Types
import Data.OrgMode.Parse.Attoparsec.Document
import Util
parserSmallDocumentTests :: TestTree
parserSmallDocumentTests = testGroup "Attoparsec Small Document"
[ testCase "Parse Empty Document" $ testDocS "" (Document "" [])
, testCase "Parse No Headlines" $ testDocS pText (Document pText [])
, testCase "Parse Heading Sample A" $ testDocS sampleAText sampleAParse
, testCase "Parse Heading no \n" $
testDocS "* T" (Document "" [emptyHeading {title="T"}])
]
where testDocS s r = expectParse (parseDocument kw) s (Right r)
testDocF s = expectParse (parseDocument kw) s (Left "Some failure")
kw = ["TODO", "CANCELED", "DONE"]
pText = "Paragraph text\n.No headline here.\n##--------\n"
sampleAText :: Text
sampleAText = Text.concat [sampleParagraph,"* Test1", spaces 20,":Hi there:\n"
,"*\n"
," *\n"
,"* Test2 :Two:Tags:\n"
]
sampleAParse :: Document
sampleAParse = Document
sampleParagraph
[emptyHeading {title="Test1", tags=["Hi there"]}
,emptyHeading {section=emptySection{sectionParagraph=" *\n"}}
,emptyHeading {title="Test2", tags=["Two","Tags"]}
]
emptyHeading :: Heading
emptyHeading = Heading {level = 1
,keyword = Nothing
,priority = Nothing
,title = ""
,stats = Nothing
,tags = []
,section = emptySection
,subHeadings = []
}
sampleParagraph :: Text
sampleParagraph = "This is some sample text in a paragraph which may contain * , : , and other special characters.\n\n"
spaces :: Int -> Text
spaces = flip Text.replicate " "
emptySection :: Section
emptySection = Section (Plns mempty) mempty mempty mempty
|
imalsogreg/orgmode-parse
|
test/Document.hs
|
bsd-3-clause
| 2,248
| 0
| 13
| 707
| 490
| 282
| 208
| 49
| 1
|
module LiquidHaskell.Plugin (
module Language.Haskell.Liquid.Plugin
) where
import Language.Haskell.Liquid.Plugin
|
spinda/liquidhaskell
|
src/LiquidHaskell/Plugin.hs
|
bsd-3-clause
| 122
| 0
| 5
| 17
| 23
| 16
| 7
| 3
| 0
|
{-# LANGUAGE OverloadedStrings, TupleSections #-}
module Shell where
import System.Posix.Types
import System.Posix.ByteString.FilePath
import System.Posix.Process.ByteString
import System.Posix.Directory.ByteString
import System.Posix.IO
import System.IO
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Text (Text)
import qualified Data.ByteString.Char8 as B
import Data.ByteString.Char8 (ByteString)
import Control.Applicative
import Control.Monad.IO.Class
import ShellParser
import InternalCommands
import Command
import Types
import Run
data ShellState = ShSt
{ shStCwd :: RawFilePath
} deriving (Read, Show, Eq)
|
firefrorefiddle/hssh
|
src/Shell.hs
|
bsd-3-clause
| 695
| 0
| 8
| 110
| 147
| 98
| 49
| 23
| 0
|
{-# LANGUAGE QuasiQuotes #-}
module Test12 () where
import LiquidHaskell
data L a = N | C a (L a)
[lq| measure len :: L a -> Int |]
len N = 0
len (C x xs) = 1 + len xs
[lq| three :: { v:(L Int) | len v = 3 } |]
three = C 1 (C 2 (C 3 N))
|
spinda/liquidhaskell
|
benchmarks/gsoc15/pos/test12.hs
|
bsd-3-clause
| 250
| 0
| 9
| 77
| 103
| 58
| 45
| 9
| 1
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
module Hexploration.Emulator.Internal where
import Hexploration.Byte
import Control.Applicative
import Control.Lens
import Control.Monad.Reader
import Control.Monad.Trans.Either
import Data.Binary
import Data.Bits
import Data.Word.Odd
import Data.Vector.Binary ()
import Data.Vector.Unboxed (Vector)
import Data.Vector.Unboxed.Mutable (IOVector)
import qualified Data.Vector.Unboxed.Mutable as Vector
import qualified Data.Vector.Generic as Generic.Vector
import qualified Data.Vector.Unboxed as Unboxed.Vector
-- | An address has 64 bits.
type Address = BytesX4
-- | Registers are indexed by the number of their least significant byte (from 0 to 255)
-- and their size (1 Byte, 2 Bytes, 4 Bytes, 8 Bytes or 16 Bytes).
data RegisterIndex = RegisterIndex
{ registerNumber :: Int
, registerSize :: Int }
type RegisterContent = Vector Byte
-- | A register index for registers with special size (from 1 Byte to 16 Bytes).
newtype SpecialRegisterIndex = SpecialRegisterIndex { specialRegisterIndex :: RegisterIndex }
type Registers = IOVector Byte
type Memory = IOVector Byte
-- | The Processor consists of the registers and the random access memory.
data Processor = Processor
{ _registers :: Registers
, _memory :: Memory }
makeLenses ''Processor
-- | There are various errors that can happen during the operation of the Processor.
data OperationError = UnknownInstructionCode
| UnsupportedInstruction
| NonExistentMemory
| NonExistentRegister
| WrongRegisterSize
-- | The Operation Monad describes the operation of the Processor.
newtype Operation a = Operation { operation :: EitherT OperationError (ReaderT Processor IO) a } deriving (Functor, Applicative, Monad)
-- | Throw an 'OperationError' in the 'Operation' monad.
throwError :: OperationError -> Operation a
throwError = Operation . left
-- | Create a well-formed 'RegisterIndex'.
-- Return 'Just' the 'RegisterIndex' or 'Nothing' if it cannot be generated
-- (not even by possibly adjusting the register number to the register size).
createRegisterIndex :: Word8 -> Word4 -> Either OperationError RegisterIndex
createRegisterIndex n s
| s' `elem` [1, 2, 4, 8, 16] = Right $ RegisterIndex (n' - n' `rem` s') s'
| otherwise = Left WrongRegisterSize
where s' = fromIntegral s + 1
n' = fromIntegral n
-- | Check whether the given index is well-formed.
-- Return 'True' if it is or 'False' otherwise.
checkRegisterIndex :: RegisterIndex -> Bool
checkRegisterIndex i = registerSize i `elem` [1, 2, 4, 8, 16]
&& registerNumber i >= 0 && registerNumber i < 256
&& registerNumber i `rem` registerSize i == 0
-- | Parse a 'RegisterIndex' in the 'Operation' monad.
parseRegisterIndex :: Word2 -> Word8 -> Operation RegisterIndex
parseRegisterIndex size number = Operation $ hoistEither $ createRegisterIndex number' size' where
number' | size == 3 = shift number 1
| otherwise = number
size' | size == 3 && number >= 0x80 = 0xF
| otherwise = (2 ^ size) - 1
-- | Create a well-formed 'SpecialRegisterIndex'.
-- Return 'Just' the 'SpecialRegisterIndex' or 'Nothing' if it cannot be generated with the given arguments.
createSpecialRegisterIndex :: Word8 -> Word4 -> Either OperationError SpecialRegisterIndex
createSpecialRegisterIndex n s
| s' + n' >= 256 = Left NonExistentRegister
| s' `notElem` [1 .. 16] = Left WrongRegisterSize
| otherwise = Right $ SpecialRegisterIndex $ RegisterIndex n' s'
where n' = fromIntegral n
s' = fromIntegral s + 1
-- | Check whether the given special index is well-formed.
-- Return 'True' if it is or 'False' otherwise.
checkSpecialRegisterIndex :: SpecialRegisterIndex -> Bool
checkSpecialRegisterIndex i = registerNumber i' + registerSize i' < 256 && registerSize i' `elem` [1 .. 16]
where i' = specialRegisterIndex i
-- | Parse a 'SpecialRegisterIndex' in the 'Operation' monad.
parseSpecialRegisterIndex :: Word4 -> Word8 -> Operation SpecialRegisterIndex
parseSpecialRegisterIndex size number = Operation $ hoistEither $ createSpecialRegisterIndex number size
-- | The index of the instruction pointer.
-- This index can be used, but checking whether it is well-formed will return false.
instructionPointer :: RegisterIndex
instructionPointer = RegisterIndex 256 4
-- | Get the size of the useable memory.
memorySize :: Integral a => Operation a
memorySize = fromIntegral <$> Operation (view $ memory . to Vector.length)
-- | An isomorphism between the content of a register and an 'Integral' of the right size.
#if MIN_VERSION_base(4,7,0)
#define BITS FiniteBits
#define bitSIZE finiteBitSize
#else
#define BITS Bits
#define bitSIZE bitSize
#endif
registerContent :: (BITS a, Integral a) => Iso' a RegisterContent
registerContent = iso toRegisterContent fromRegisterContent
where fromRegisterContent = flip Generic.Vector.ifoldl' 0 $ \ x i y -> x + shiftL (fromIntegral y) (16 * i)
toRegisterContent x = Generic.Vector.generate (size x) $ \ i -> fromIntegral $ shiftR x (16 * i) .&. 0xFFFF
size x = case bitSIZE x `divMod` 16 of
(n, 0) -> n
(n, _) -> n + 1
-- | Run the processor operation on the given memory.
-- All registers will be filled with zeros and the instruction pointer points to 0.
runProcessor :: Memory -> Operation a -> IO (Either OperationError a)
runProcessor m o = do
rs <- Vector.replicate 260 0
runReaderT (runEitherT $ operation o) $ Processor rs m
-- | Get an 'Operation' which reads the specified register.
--
-- Warning: The 'RegisterIndex' must be well-formed.
readRegister :: RegisterIndex -> Operation RegisterContent
readRegister i = Operation $ view registers >>= lift . lift . Generic.Vector.freeze . Vector.slice (registerNumber i) (registerSize i)
-- | Get an 'Operation' which writes the 'RegisterContent' to the specified register.
--
-- Warning: The 'RegisterIndex' must be well-formed and the 'RegisterContent' must have the specified size.
writeRegister :: RegisterIndex -> RegisterContent -> Operation ()
writeRegister i x = Operation $ view registers >>= lift . lift . flip Generic.Vector.copy x . Vector.slice (registerNumber i) (registerSize i)
-- | Get an 'Operation' which modifies the specified register with the specified function.
--
-- Warning: The 'RegisterIndex' must be well-formed and the function must work on the specified size.
modifyRegister :: RegisterIndex -> (RegisterContent -> RegisterContent) -> Operation ()
modifyRegister i f = writeRegister i =<< f <$> readRegister i
-- | Get an 'Operation' which loads the content at the specified address into the specified register.
--
-- Warning: The 'SpecialRegisterIndex' must be well-formed and the address must be in the bounds of the memory.
loadFromMemory :: Address -> SpecialRegisterIndex -> Operation ()
loadFromMemory a i = Operation $ do
register <- Vector.slice (registerNumber i') (registerSize i') <$> view registers
lift . lift . Vector.unsafeCopy register =<< Vector.slice (fromIntegral a) (registerSize i') <$> view memory
where i' = specialRegisterIndex i
-- | Get an 'Operation' which stores the content of the specified register at the specified address.
--
-- Warning: The 'SpecialRegisterIndex' must be well-formed and the address must be in the bounds of the memory.
storeInMemory :: Address -> SpecialRegisterIndex -> Operation ()
storeInMemory a i = Operation $ do
register <- Vector.slice (registerNumber i') (registerSize i') <$> view registers
lift . lift . flip Vector.unsafeCopy register =<< Vector.slice (fromIntegral a) (registerSize i') <$> view memory
where i' = specialRegisterIndex i
-- | Get an 'Operation' which reads the specified file to the addresses starting at the specified address.
--
-- Warning: The 'FilePath' must be well-formed and the memory must be large enough.
readMemoryFile :: FilePath -> Address -> Operation ()
readMemoryFile path a = Operation $ do
content <- lift . lift $ decodeFile path
lift . lift . flip Generic.Vector.unsafeCopy content =<< Vector.slice (fromIntegral a) (Unboxed.Vector.length content) <$> view memory
-- | Get an 'Operation' which writes the specified number of bytes
-- from the memory starting at the specified address to the specified file.
--
-- Warning: The 'FilePath' must be well-formed and there must be enough memory to write.
writeMemoryFile :: FilePath -> Address -> Int -> Operation ()
writeMemoryFile path a n = Operation $ do
content <- lift . lift . Generic.Vector.freeze . Vector.slice (fromIntegral a) n =<< view memory
lift . lift $ encodeFile path (content :: Vector Byte)
-- | Get the next byte of processor instruction code.
-- This operation also increments the instruction pointer by one.
instructionCode :: Operation Byte
instructionCode = Operation $ do
address <- view (from registerContent) <$> operation (readRegister instructionPointer)
operation $ writeRegister instructionPointer $ view registerContent $ address + 1
view memory >>= lift . lift . flip Vector.read address
|
chaosmasttter/hexploration
|
source/Hexploration/Emulator/Internal.hs
|
bsd-3-clause
| 9,429
| 0
| 13
| 1,876
| 1,928
| 1,015
| 913
| 111
| 2
|
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2015 Dimitri Sabadie
-- License : BSD3
--
-- Maintainer : Dimitri Sabadie <dimitri.sabadie@gmail.com>
-- Stability : experimental
-- Portability : portable
-----------------------------------------------------------------------------
module Graphics.UI.AGUI.Core.Renderer (
-- * Renderer
Renderer
) where
type Renderer a = a -> IO ()
|
phaazon/agui
|
src/Graphics/UI/AGUI/Core/Renderer.hs
|
bsd-3-clause
| 457
| 0
| 7
| 68
| 40
| 29
| 11
| 3
| 0
|
module RW.Chap6.TCs (
BasicEq
) where
class BasicEq a where
isEqual :: a -> a -> Bool
unEqual :: a -> a -> Bool
a `unEqual` b = not (isEqual a b)
instance BasicEq Bool where
isEqual True True = True
isEqual False False = True
isEqual _ _ = False
data Color =
Red
| Blue
| Green
| Yellow
instance BasicEq Color where
isEqual Red Red = True
isEqual Yellow Yellow = True
isEqual Blue Blue = True
isEqual Green Green = True
isEqual _ _ = False
instance Show Color where
show Red = "Red"
show Yellow = "Yellow"
show Blue = "Blue"
show Green = "Green"
instance Read Color where
readsPrec _ value =
tryParse [("Red", Red), ("Blue", Blue), ("Green", Green), ("Yellow", Yellow)]
where
tryParse [] = []
tryParse ((str, val):rest)
| take (length str) value == str = [(val, drop (length str) value)]
| otherwise = tryParse rest
|
ChrisCoffey/rwh
|
src/RW/Chap6/Typeclasses.hs
|
bsd-3-clause
| 985
| 0
| 14
| 322
| 368
| 194
| 174
| 33
| 0
|
{-# LANGUAGE ScopedTypeVariables #-}
module Database.Sqroll.Table.Field.Unique
( Unique (..)
) where
import Control.Applicative ((<$>))
import Database.Sqroll.Table.Field
newtype Unique a = Unique {unUnique :: a}
deriving (Eq, Ord, Show)
instance forall a. Field a => Field (Unique a) where
fieldTypes _ = fieldTypes (undefined :: a)
fieldIndexes _ = IndexUnique : fieldIndexes (undefined :: a)
fieldDefault = Unique fieldDefault
fieldPoke stmt n (Unique x) = fieldPoke stmt n x
fieldPeek stmt n = Unique <$> fieldPeek stmt n
|
pacak/sqroll
|
src/Database/Sqroll/Table/Field/Unique.hs
|
bsd-3-clause
| 578
| 0
| 8
| 129
| 183
| 103
| 80
| 13
| 0
|
{-# LANGUAGE ScopedTypeVariables #-}
-- |An efficient implementation of 'Data.Graph.Inductive.Graph.Graph'
-- using big-endian patricia tree (i.e. "Data.IntMap").
--
-- This module provides the following specialised functions to gain
-- more performance, using GHC's RULES pragma:
--
-- * 'Data.Graph.Inductive.Graph.insNode'
--
-- * 'Data.Graph.Inductive.Graph.insEdge'
--
-- * 'Data.Graph.Inductive.Graph.gmap'
--
-- * 'Data.Graph.Inductive.Graph.nmap'
--
-- * 'Data.Graph.Inductive.Graph.emap'
module Data.Graph.Inductive.PatriciaTree
( Gr
, UGr
)
where
import Data.Graph.Inductive.Graph
import Data.IntMap (IntMap)
import qualified Data.IntMap as IM
import Data.List
import Data.Maybe
import Control.Arrow(second)
newtype Gr a b = Gr (GraphRep a b)
type GraphRep a b = IntMap (Context' a b)
type Context' a b = (IntMap [b], a, IntMap [b])
type UGr = Gr () ()
instance Graph Gr where
-- required members
empty = Gr IM.empty
isEmpty (Gr g) = IM.null g
match = matchGr
mkGraph vs es = (insEdges' . insNodes vs) empty
where
insEdges' g = foldl' (flip insEdge) g es
labNodes (Gr g) = [ (node, label)
| (node, (_, label, _)) <- IM.toList g ]
-- overriding members for efficiency
noNodes (Gr g) = IM.size g
nodeRange (Gr g)
| IM.null g = (0, 0)
| otherwise = (ix (IM.minViewWithKey g), ix (IM.maxViewWithKey g))
where
ix = fst . fst . fromJust
labEdges (Gr g) = do (node, (_, _, s)) <- IM.toList g
(next, labels) <- IM.toList s
label <- labels
return (node, next, label)
instance DynGraph Gr where
(p, v, l, s) & (Gr g)
= let !g1 = IM.insert v (fromAdj p, l, fromAdj s) g
!g2 = addSucc g1 v p
!g3 = addPred g2 v s
in
Gr g3
matchGr :: Node -> Gr a b -> Decomp Gr a b
matchGr node (Gr g)
= case IM.lookup node g of
Nothing
-> (Nothing, Gr g)
Just (p, label, s)
-> let !g1 = IM.delete node g
!p' = IM.delete node p
!s' = IM.delete node s
!g2 = clearPred g1 node (IM.keys s')
!g3 = clearSucc g2 node (IM.keys p')
in
(Just (toAdj p', node, label, toAdj s), Gr g3)
{-# RULES
"insNode/Data.Graph.Inductive.PatriciaTree" insNode = fastInsNode
#-}
fastInsNode :: LNode a -> Gr a b -> Gr a b
fastInsNode (v, l) (Gr g) = g' `seq` Gr g'
where
g' = IM.insert v (IM.empty, l, IM.empty) g
{-# RULES
"insEdge/Data.Graph.Inductive.PatriciaTree" insEdge = fastInsEdge
#-}
fastInsEdge :: LEdge b -> Gr a b -> Gr a b
fastInsEdge (v, w, l) (Gr g) = g2 `seq` Gr g2
where
g1 = IM.adjust addSucc' v g
g2 = IM.adjust addPred' w g1
addSucc' (ps, l', ss) = (ps, l', IM.insertWith addLists w [l] ss)
addPred' (ps, l', ss) = (IM.insertWith addLists v [l] ps, l', ss)
{-# RULES
"gmap/Data.Graph.Inductive.PatriciaTree" gmap = fastGMap
#-}
fastGMap :: forall a b c d. (Context a b -> Context c d) -> Gr a b -> Gr c d
fastGMap f (Gr g) = Gr (IM.mapWithKey f' g)
where
f' :: Node -> Context' a b -> Context' c d
f' = ((fromContext . f) .) . toContext
{-# RULES
"nmap/Data.Graph.Inductive.PatriciaTree" nmap = fastNMap
#-}
fastNMap :: forall a b c. (a -> c) -> Gr a b -> Gr c b
fastNMap f (Gr g) = Gr (IM.map f' g)
where
f' :: Context' a b -> Context' c b
f' (ps, a, ss) = (ps, f a, ss)
{-# RULES
"emap/Data.Graph.Inductive.PatriciaTree" emap = fastEMap
#-}
fastEMap :: forall a b c. (b -> c) -> Gr a b -> Gr a c
fastEMap f (Gr g) = Gr (IM.map f' g)
where
f' :: Context' a b -> Context' a c
f' (ps, a, ss) = (IM.map (map f) ps, a, IM.map (map f) ss)
toAdj :: IntMap [b] -> Adj b
toAdj = concatMap expand . IM.toList
where
expand (n,ls) = map (flip (,) n) ls
fromAdj :: Adj b -> IntMap [b]
fromAdj = IM.fromListWith addLists . map (second return . swap)
toContext :: Node -> Context' a b -> Context a b
toContext v (ps, a, ss)
= (toAdj ps, v, a, toAdj ss)
fromContext :: Context a b -> Context' a b
fromContext (ps, _, a, ss)
= (fromAdj ps, a, fromAdj ss)
swap :: (a, b) -> (b, a)
swap (a, b) = (b, a)
-- A version of @++@ where order isn't important, so @xs ++ [x]@
-- becomes @x:xs@. Used when we have to have a function of type @[a]
-- -> [a] -> [a]@ but one of the lists is just going to be a single
-- element (and it isn't possible to tell which).
addLists :: [a] -> [a] -> [a]
addLists [a] as = a : as
addLists as [a] = a : as
addLists xs ys = xs ++ ys
addSucc :: GraphRep a b -> Node -> [(b, Node)] -> GraphRep a b
addSucc g _ [] = g
addSucc g v ((l, p) : rest) = addSucc g' v rest
where
g' = IM.adjust f p g
f (ps, l', ss) = (ps, l', IM.insertWith addLists v [l] ss)
addPred :: GraphRep a b -> Node -> [(b, Node)] -> GraphRep a b
addPred g _ [] = g
addPred g v ((l, s) : rest) = addPred g' v rest
where
g' = IM.adjust f s g
f (ps, l', ss) = (IM.insertWith addLists v [l] ps, l', ss)
clearSucc :: GraphRep a b -> Node -> [Node] -> GraphRep a b
clearSucc g _ [] = g
clearSucc g v (p:rest) = clearSucc g' v rest
where
g' = IM.adjust f p g
f (ps, l, ss) = (ps, l, IM.delete v ss)
clearPred :: GraphRep a b -> Node -> [Node] -> GraphRep a b
clearPred g _ [] = g
clearPred g v (s:rest) = clearPred g' v rest
where
g' = IM.adjust f s g
f (ps, l, ss) = (IM.delete v ps, l, ss)
|
jsa/fgl
|
Data/Graph/Inductive/PatriciaTree.hs
|
bsd-3-clause
| 5,774
| 0
| 15
| 1,812
| 2,284
| 1,212
| 1,072
| -1
| -1
|
-----------------------------------------------------------------------------
-- |
-- Module : System.Taffybar.Hooks.PagerHints
-- Copyright : (c) José A. Romero L.
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : José A. Romero L. <escherdragon@gmail.com>
-- Stability : unstable
-- Portability : unportable
--
-- Complements the "XMonad.Hooks.EwmhDesktops" with two additional hints
-- not contemplated by the EWMH standard:
--
-- [@_XMONAD_CURRENT_LAYOUT@] Contains a UTF-8 string with the name of the
-- windows layout currently used in the active workspace.
--
-- [@_XMONAD_VISIBLE_WORKSPACES@] Contains a list of UTF-8 strings with the
-- names of all the workspaces that are currently showed in a secondary
-- display, or an empty list if in the current installation there's only
-- one monitor.
--
-- The first hint can be set directly on the root window of the default
-- display, or indirectly via X11 events with an atom of the same
-- name. This allows both to track any changes that occur in the layout of
-- the current workspace, as well as to have it changed automatically by
-- just sending a custom event to the hook.
--
-- The second one should be considered read-only, and is set every time
-- XMonad calls its log hooks.
--
-----------------------------------------------------------------------------
module System.Taffybar.Hooks.PagerHints (
-- * Usage
-- $usage
pagerHints
) where
import Codec.Binary.UTF8.String (encode)
import Control.Monad
import Data.Monoid
import Foreign.C.Types (CInt)
import XMonad
import qualified XMonad.StackSet as W
-- $usage
--
-- You can use this module with the following in your @xmonad.hs@ file:
--
-- > import System.Taffybar.Hooks.PagerHints (pagerHints)
-- >
-- > main = xmonad $ ewmh $ pagerHints $ defaultConfig
-- > ...
-- | The \"Current Layout\" custom hint.
xLayoutProp :: X Atom
xLayoutProp = return =<< getAtom "_XMONAD_CURRENT_LAYOUT"
-- | The \"Visible Workspaces\" custom hint.
xVisibleProp :: X Atom
xVisibleProp = return =<< getAtom "_XMONAD_VISIBLE_WORKSPACES"
-- | Add support for the \"Current Layout\" and \"Visible Workspaces\" custom
-- hints to the given config.
pagerHints :: XConfig a -> XConfig a
pagerHints c = c { handleEventHook = handleEventHook c +++ pagerHintsEventHook
, logHook = logHook c +++ pagerHintsLogHook }
where x +++ y = x `mappend` y
-- | Update the current values of both custom hints.
pagerHintsLogHook :: X ()
pagerHintsLogHook = do
withWindowSet
(setCurrentLayout . description . W.layout . W.workspace . W.current)
withWindowSet
(setVisibleWorkspaces . map (W.tag . W.workspace) . W.visible)
-- | Set the value of the \"Current Layout\" custom hint to the one given.
setCurrentLayout :: String -> X ()
setCurrentLayout l = withDisplay $ \dpy -> do
r <- asks theRoot
a <- xLayoutProp
c <- getAtom "UTF8_STRING"
let l' = map fromIntegral (encode l)
io $ changeProperty8 dpy r a c propModeReplace l'
-- | Set the value of the \"Visible Workspaces\" hint to the one given.
setVisibleWorkspaces :: [String] -> X ()
setVisibleWorkspaces vis = withDisplay $ \dpy -> do
r <- asks theRoot
a <- xVisibleProp
c <- getAtom "UTF8_STRING"
let vis' = map fromIntegral $ concatMap ((++[0]) . encode) vis
io $ changeProperty8 dpy r a c propModeReplace vis'
-- | Handle all \"Current Layout\" events received from pager widgets, and
-- set the current layout accordingly.
pagerHintsEventHook :: Event -> X All
pagerHintsEventHook (ClientMessageEvent {
ev_message_type = mt,
ev_data = d
}) = withWindowSet $ \_ -> do
a <- xLayoutProp
when (mt == a) $ sendLayoutMessage d
return (All True)
pagerHintsEventHook _ = return (All True)
-- | Request a change in the current layout by sending an internal message
-- to XMonad.
sendLayoutMessage :: [CInt] -> X ()
sendLayoutMessage evData = case evData of
[] -> return ()
x:_ -> if x < 0
then sendMessage FirstLayout
else sendMessage NextLayout
|
Undeterminant/taffybar
|
src/System/Taffybar/Hooks/PagerHints.hs
|
bsd-3-clause
| 4,010
| 0
| 17
| 736
| 685
| 372
| 313
| 51
| 3
|
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Program.Db
-- Copyright : Isaac Jones 2006, Duncan Coutts 2007-2009
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This provides a 'ProgramDb' type which holds configured and not-yet
-- configured programs. It is the parameter to lots of actions elsewhere in
-- Cabal that need to look up and run programs. If we had a Cabal monad,
-- the 'ProgramDb' would probably be a reader or state component of it.
--
-- One nice thing about using it is that any program that is
-- registered with Cabal will get some \"configure\" and \".cabal\"
-- helpers like --with-foo-args --foo-path= and extra-foo-args.
--
-- There's also a hook for adding programs in a Setup.lhs script. See
-- hookedPrograms in 'Distribution.Simple.UserHooks'. This gives a
-- hook user the ability to get the above flags and such so that they
-- don't have to write all the PATH logic inside Setup.lhs.
module Distribution.Simple.Program.Db (
-- * The collection of configured programs we can run
ProgramDb,
emptyProgramDb,
defaultProgramDb,
restoreProgramDb,
-- ** Query and manipulate the program db
addKnownProgram,
addKnownPrograms,
lookupKnownProgram,
knownPrograms,
getProgramSearchPath,
setProgramSearchPath,
modifyProgramSearchPath,
userSpecifyPath,
userSpecifyPaths,
userMaybeSpecifyPath,
userSpecifyArgs,
userSpecifyArgss,
userSpecifiedArgs,
lookupProgram,
updateProgram,
configuredPrograms,
-- ** Query and manipulate the program db
configureProgram,
configureAllKnownPrograms,
lookupProgramVersion,
reconfigurePrograms,
requireProgram,
requireProgramVersion,
) where
import Prelude ()
import Distribution.Compat.Prelude
import Distribution.Simple.Program.Types
import Distribution.Simple.Program.Find
import Distribution.Simple.Program.Builtin
import Distribution.Simple.Utils
import Distribution.Version
import Distribution.Text
import Distribution.Verbosity
import Control.Monad (join)
import Data.Tuple (swap)
import qualified Data.Map as Map
-- ------------------------------------------------------------
-- * Programs database
-- ------------------------------------------------------------
-- | The configuration is a collection of information about programs. It
-- contains information both about configured programs and also about programs
-- that we are yet to configure.
--
-- The idea is that we start from a collection of unconfigured programs and one
-- by one we try to configure them at which point we move them into the
-- configured collection. For unconfigured programs we record not just the
-- 'Program' but also any user-provided arguments and location for the program.
data ProgramDb = ProgramDb {
unconfiguredProgs :: UnconfiguredProgs,
progSearchPath :: ProgramSearchPath,
configuredProgs :: ConfiguredProgs
}
type UnconfiguredProgram = (Program, Maybe FilePath, [ProgArg])
type UnconfiguredProgs = Map.Map String UnconfiguredProgram
type ConfiguredProgs = Map.Map String ConfiguredProgram
emptyProgramDb :: ProgramDb
emptyProgramDb = ProgramDb Map.empty defaultProgramSearchPath Map.empty
defaultProgramDb :: ProgramDb
defaultProgramDb = restoreProgramDb builtinPrograms emptyProgramDb
-- internal helpers:
updateUnconfiguredProgs :: (UnconfiguredProgs -> UnconfiguredProgs)
-> ProgramDb -> ProgramDb
updateUnconfiguredProgs update progdb =
progdb { unconfiguredProgs = update (unconfiguredProgs progdb) }
updateConfiguredProgs :: (ConfiguredProgs -> ConfiguredProgs)
-> ProgramDb -> ProgramDb
updateConfiguredProgs update progdb =
progdb { configuredProgs = update (configuredProgs progdb) }
-- Read & Show instances are based on listToFM
-- | Note that this instance does not preserve the known 'Program's.
-- See 'restoreProgramDb' for details.
--
instance Show ProgramDb where
show = show . Map.toAscList . configuredProgs
-- | Note that this instance does not preserve the known 'Program's.
-- See 'restoreProgramDb' for details.
--
instance Read ProgramDb where
readsPrec p s =
[ (emptyProgramDb { configuredProgs = Map.fromList s' }, r)
| (s', r) <- readsPrec p s ]
-- | Note that this instance does not preserve the known 'Program's.
-- See 'restoreProgramDb' for details.
--
instance Binary ProgramDb where
put db = do
put (progSearchPath db)
put (configuredProgs db)
get = do
searchpath <- get
progs <- get
return $! emptyProgramDb {
progSearchPath = searchpath,
configuredProgs = progs
}
-- | The 'Read'\/'Show' and 'Binary' instances do not preserve all the
-- unconfigured 'Programs' because 'Program' is not in 'Read'\/'Show' because
-- it contains functions. So to fully restore a deserialised 'ProgramDb' use
-- this function to add back all the known 'Program's.
--
-- * It does not add the default programs, but you probably want them, use
-- 'builtinPrograms' in addition to any extra you might need.
--
restoreProgramDb :: [Program] -> ProgramDb -> ProgramDb
restoreProgramDb = addKnownPrograms
-- -------------------------------
-- Managing unconfigured programs
-- | Add a known program that we may configure later
--
addKnownProgram :: Program -> ProgramDb -> ProgramDb
addKnownProgram prog = updateUnconfiguredProgs $
Map.insertWith combine (programName prog) (prog, Nothing, [])
where combine _ (_, path, args) = (prog, path, args)
addKnownPrograms :: [Program] -> ProgramDb -> ProgramDb
addKnownPrograms progs progdb = foldl' (flip addKnownProgram) progdb progs
lookupKnownProgram :: String -> ProgramDb -> Maybe Program
lookupKnownProgram name =
fmap (\(p,_,_)->p) . Map.lookup name . unconfiguredProgs
knownPrograms :: ProgramDb -> [(Program, Maybe ConfiguredProgram)]
knownPrograms progdb =
[ (p,p') | (p,_,_) <- Map.elems (unconfiguredProgs progdb)
, let p' = Map.lookup (programName p) (configuredProgs progdb) ]
-- | Get the current 'ProgramSearchPath' used by the 'ProgramDb'.
-- This is the default list of locations where programs are looked for when
-- configuring them. This can be overridden for specific programs (with
-- 'userSpecifyPath'), and specific known programs can modify or ignore this
-- search path in their own configuration code.
--
getProgramSearchPath :: ProgramDb -> ProgramSearchPath
getProgramSearchPath = progSearchPath
-- | Change the current 'ProgramSearchPath' used by the 'ProgramDb'.
-- This will affect programs that are configured from here on, so you
-- should usually set it before configuring any programs.
--
setProgramSearchPath :: ProgramSearchPath -> ProgramDb -> ProgramDb
setProgramSearchPath searchpath db = db { progSearchPath = searchpath }
-- | Modify the current 'ProgramSearchPath' used by the 'ProgramDb'.
-- This will affect programs that are configured from here on, so you
-- should usually modify it before configuring any programs.
--
modifyProgramSearchPath :: (ProgramSearchPath -> ProgramSearchPath)
-> ProgramDb
-> ProgramDb
modifyProgramSearchPath f db =
setProgramSearchPath (f $ getProgramSearchPath db) db
-- |User-specify this path. Basically override any path information
-- for this program in the configuration. If it's not a known
-- program ignore it.
--
userSpecifyPath :: String -- ^Program name
-> FilePath -- ^user-specified path to the program
-> ProgramDb -> ProgramDb
userSpecifyPath name path = updateUnconfiguredProgs $
flip Map.update name $ \(prog, _, args) -> Just (prog, Just path, args)
userMaybeSpecifyPath :: String -> Maybe FilePath
-> ProgramDb -> ProgramDb
userMaybeSpecifyPath _ Nothing progdb = progdb
userMaybeSpecifyPath name (Just path) progdb = userSpecifyPath name path progdb
-- |User-specify the arguments for this program. Basically override
-- any args information for this program in the configuration. If it's
-- not a known program, ignore it..
userSpecifyArgs :: String -- ^Program name
-> [ProgArg] -- ^user-specified args
-> ProgramDb
-> ProgramDb
userSpecifyArgs name args' =
updateUnconfiguredProgs
(flip Map.update name $
\(prog, path, args) -> Just (prog, path, args ++ args'))
. updateConfiguredProgs
(flip Map.update name $
\prog -> Just prog { programOverrideArgs = programOverrideArgs prog
++ args' })
-- | Like 'userSpecifyPath' but for a list of progs and their paths.
--
userSpecifyPaths :: [(String, FilePath)]
-> ProgramDb
-> ProgramDb
userSpecifyPaths paths progdb =
foldl' (\progdb' (prog, path) -> userSpecifyPath prog path progdb') progdb paths
-- | Like 'userSpecifyPath' but for a list of progs and their args.
--
userSpecifyArgss :: [(String, [ProgArg])]
-> ProgramDb
-> ProgramDb
userSpecifyArgss argss progdb =
foldl' (\progdb' (prog, args) -> userSpecifyArgs prog args progdb') progdb argss
-- | Get the path that has been previously specified for a program, if any.
--
userSpecifiedPath :: Program -> ProgramDb -> Maybe FilePath
userSpecifiedPath prog =
join . fmap (\(_,p,_)->p) . Map.lookup (programName prog) . unconfiguredProgs
-- | Get any extra args that have been previously specified for a program.
--
userSpecifiedArgs :: Program -> ProgramDb -> [ProgArg]
userSpecifiedArgs prog =
maybe [] (\(_,_,as)->as) . Map.lookup (programName prog) . unconfiguredProgs
-- -----------------------------
-- Managing configured programs
-- | Try to find a configured program
lookupProgram :: Program -> ProgramDb -> Maybe ConfiguredProgram
lookupProgram prog = Map.lookup (programName prog) . configuredProgs
-- | Update a configured program in the database.
updateProgram :: ConfiguredProgram -> ProgramDb
-> ProgramDb
updateProgram prog = updateConfiguredProgs $
Map.insert (programId prog) prog
-- | List all configured programs.
configuredPrograms :: ProgramDb -> [ConfiguredProgram]
configuredPrograms = Map.elems . configuredProgs
-- ---------------------------
-- Configuring known programs
-- | Try to configure a specific program. If the program is already included in
-- the collection of unconfigured programs then we use any user-supplied
-- location and arguments. If the program gets configured successfully it gets
-- added to the configured collection.
--
-- Note that it is not a failure if the program cannot be configured. It's only
-- a failure if the user supplied a location and the program could not be found
-- at that location.
--
-- The reason for it not being a failure at this stage is that we don't know up
-- front all the programs we will need, so we try to configure them all.
-- To verify that a program was actually successfully configured use
-- 'requireProgram'.
--
configureProgram :: Verbosity
-> Program
-> ProgramDb
-> IO ProgramDb
configureProgram verbosity prog progdb = do
let name = programName prog
maybeLocation <- case userSpecifiedPath prog progdb of
Nothing ->
programFindLocation prog verbosity (progSearchPath progdb)
>>= return . fmap (swap . fmap FoundOnSystem . swap)
Just path -> do
absolute <- doesExecutableExist path
if absolute
then return (Just (UserSpecified path, []))
else findProgramOnSearchPath verbosity (progSearchPath progdb) path
>>= maybe (die notFound)
(return . Just . swap . fmap UserSpecified . swap)
where notFound = "Cannot find the program '" ++ name
++ "'. User-specified path '"
++ path ++ "' does not refer to an executable and "
++ "the program is not on the system path."
case maybeLocation of
Nothing -> return progdb
Just (location, triedLocations) -> do
version <- programFindVersion prog verbosity (locationPath location)
newPath <- programSearchPathAsPATHVar (progSearchPath progdb)
let configuredProg = ConfiguredProgram {
programId = name,
programVersion = version,
programDefaultArgs = [],
programOverrideArgs = userSpecifiedArgs prog progdb,
programOverrideEnv = [("PATH", Just newPath)],
programProperties = Map.empty,
programLocation = location,
programMonitorFiles = triedLocations
}
configuredProg' <- programPostConf prog verbosity configuredProg
return (updateConfiguredProgs (Map.insert name configuredProg') progdb)
-- | Configure a bunch of programs using 'configureProgram'. Just a 'foldM'.
--
configurePrograms :: Verbosity
-> [Program]
-> ProgramDb
-> IO ProgramDb
configurePrograms verbosity progs progdb =
foldM (flip (configureProgram verbosity)) progdb progs
-- | Try to configure all the known programs that have not yet been configured.
--
configureAllKnownPrograms :: Verbosity
-> ProgramDb
-> IO ProgramDb
configureAllKnownPrograms verbosity progdb =
configurePrograms verbosity
[ prog | (prog,_,_) <- Map.elems notYetConfigured ] progdb
where
notYetConfigured = unconfiguredProgs progdb
`Map.difference` configuredProgs progdb
-- | reconfigure a bunch of programs given new user-specified args. It takes
-- the same inputs as 'userSpecifyPath' and 'userSpecifyArgs' and for all progs
-- with a new path it calls 'configureProgram'.
--
reconfigurePrograms :: Verbosity
-> [(String, FilePath)]
-> [(String, [ProgArg])]
-> ProgramDb
-> IO ProgramDb
reconfigurePrograms verbosity paths argss progdb = do
configurePrograms verbosity progs
. userSpecifyPaths paths
. userSpecifyArgss argss
$ progdb
where
progs = catMaybes [ lookupKnownProgram name progdb | (name,_) <- paths ]
-- | Check that a program is configured and available to be run.
--
-- It raises an exception if the program could not be configured, otherwise
-- it returns the configured program.
--
requireProgram :: Verbosity -> Program -> ProgramDb
-> IO (ConfiguredProgram, ProgramDb)
requireProgram verbosity prog progdb = do
-- If it's not already been configured, try to configure it now
progdb' <- case lookupProgram prog progdb of
Nothing -> configureProgram verbosity prog progdb
Just _ -> return progdb
case lookupProgram prog progdb' of
Nothing -> die notFound
Just configuredProg -> return (configuredProg, progdb')
where notFound = "The program '" ++ programName prog
++ "' is required but it could not be found."
-- | Check that a program is configured and available to be run.
--
-- Additionally check that the program version number is suitable and return
-- it. For example you could require 'AnyVersion' or @'orLaterVersion'
-- ('Version' [1,0] [])@
--
-- It returns the configured program, its version number and a possibly updated
-- 'ProgramDb'. If the program could not be configured or the version is
-- unsuitable, it returns an error value.
--
lookupProgramVersion
:: Verbosity -> Program -> VersionRange -> ProgramDb
-> IO (Either String (ConfiguredProgram, Version, ProgramDb))
lookupProgramVersion verbosity prog range programDb = do
-- If it's not already been configured, try to configure it now
programDb' <- case lookupProgram prog programDb of
Nothing -> configureProgram verbosity prog programDb
Just _ -> return programDb
case lookupProgram prog programDb' of
Nothing -> return $! Left notFound
Just configuredProg@ConfiguredProgram { programLocation = location } ->
case programVersion configuredProg of
Just version
| withinRange version range ->
return $! Right (configuredProg, version ,programDb')
| otherwise ->
return $! Left (badVersion version location)
Nothing ->
return $! Left (unknownVersion location)
where notFound = "The program '"
++ programName prog ++ "'" ++ versionRequirement
++ " is required but it could not be found."
badVersion v l = "The program '"
++ programName prog ++ "'" ++ versionRequirement
++ " is required but the version found at "
++ locationPath l ++ " is version " ++ display v
unknownVersion l = "The program '"
++ programName prog ++ "'" ++ versionRequirement
++ " is required but the version of "
++ locationPath l ++ " could not be determined."
versionRequirement
| isAnyVersion range = ""
| otherwise = " version " ++ display range
-- | Like 'lookupProgramVersion', but raises an exception in case of error
-- instead of returning 'Left errMsg'.
--
requireProgramVersion :: Verbosity -> Program -> VersionRange
-> ProgramDb
-> IO (ConfiguredProgram, Version, ProgramDb)
requireProgramVersion verbosity prog range programDb =
join $ either die return `fmap`
lookupProgramVersion verbosity prog range programDb
|
sopvop/cabal
|
Cabal/Distribution/Simple/Program/Db.hs
|
bsd-3-clause
| 17,744
| 4
| 21
| 4,119
| 2,915
| 1,591
| 1,324
| 254
| 4
|
{-# LANGUAGE UnicodeSyntax #-}
module Main where
import Arith.Parser (parseString)
import Arith.Semantics (eval)
import Control.Monad.Loops (whileM_)
import System.IO (getLine, hFlush, hIsEOF, putStr, stdin,
stdout)
main ∷ IO ()
main = do
putStr "λ "
hFlush stdout
whileM_ (fmap not $ hIsEOF stdin) $ do
hFlush stdout
input ← getLine
case parseString input of
Left e → putStrLn . show $ e
Right t → putStrLn . show . eval $ t
putStr "λ "
hFlush stdout
putStrLn "Bye."
|
ayberkt/TAPL
|
src/Arith/Main.hs
|
bsd-3-clause
| 625
| 0
| 15
| 225
| 190
| 94
| 96
| 20
| 2
|
module Main(main) where
import PolyPaver.Invocation
import Data.Ratio ((%))
main =
defaultMain Problem
{
box = [(0,(24083420467200 % 34059099853079,9007199254749184 % 6369051672525773)),(1,(1 % 2,2 % 1))]
,theorem = thm
}
thm =
Implies (Geq (Var 0) (Over (Over (Lit (1099511627775 % 1)) (Lit (1099511627776 % 1))) (Sqrt (Var 1)))) (Implies (Leq (Var 0) (Over (Over (Lit (1099511627777 % 1)) (Lit (1099511627776 % 1))) (Sqrt (Var 1)))) (Implies (Geq (Var 1) (Neg (Lit (340282000000000000000000000000000000000 % 1)))) (Implies (Geq (Var 1) (Over (Lit (1 % 1)) (Lit (2 % 1)))) (Implies (Leq (Var 1) (Lit (2 % 1))) (Implies (Geq (Var 0) (Neg (Lit (340282000000000000000000000000000000000 % 1)))) (Implies (Leq (Var 0) (Lit (340282000000000000000000000000000000000 % 1))) (And (Geq (FTimes (Var 1) (Var 0)) (Neg (Lit (340282000000000000000000000000000000000 % 1)))) (Leq (FTimes (Var 1) (Var 0)) (Lit (340282000000000000000000000000000000000 % 1))))))))))
|
michalkonecny/polypaver
|
examples/old/their_sqrt/their_sqrt_27.hs
|
bsd-3-clause
| 998
| 0
| 27
| 180
| 552
| 293
| 259
| 9
| 1
|
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Actions.PerWindowKeys
-- Description : Define key-bindings on a per-window basis.
-- Copyright : (c) Wilson Sales, 2019
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Wilson Sales <spoonm@spoonm.org>
-- Stability : unstable
-- Portability : unportable
--
-- Define key-bindings on a per-window basis.
--
-----------------------------------------------------------------------------
module XMonad.Actions.PerWindowKeys (
-- * Usage
-- $usage
bindAll,
bindFirst
) where
import XMonad
-- $usage
--
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Actions.PerWindowKeys
--
-- > ,((0, xK_F2), bindFirst [(className =? "firefox", spawn "dmenu"), (isFloat, withFocused $ windows . W.sink)])
--
-- > ,((0, xK_F3), bindAll [(isDialog, kill), (pure True, doSomething)])
--
-- If you want an action that will always run, but also want to do something for
-- other queries, you can use @'bindAll' [(query1, action1), ..., (pure True,
-- alwaysDoThisAction)]@.
--
-- Similarly, if you want a default action to be run if all the others failed,
-- you can use @'bindFirst' [(query1, action1), ..., (pure True,
-- doThisIfTheOthersFail)]@.
--
-- For detailed instructions on editing your key bindings, see
-- "XMonad.Doc.Extending#Editing_key_bindings".
-- | Run an action if a Query holds true. Doesn't stop at the first one that
-- does, however, and could potentially run all actions.
bindAll :: [(Query Bool, X ())] -> X ()
bindAll = mapM_ choose where
choose (mh,action) = withFocused $ \w -> whenX (runQuery mh w) action
-- | Run the action paired with the first Query that holds true.
bindFirst :: [(Query Bool, X ())] -> X ()
bindFirst = withFocused . chooseOne
chooseOne :: [(Query Bool, X ())] -> Window -> X ()
chooseOne [] _ = return ()
chooseOne ((mh,a):bs) w = do
c <- runQuery mh w
if c then a
else chooseOne bs w
|
xmonad/xmonad-contrib
|
XMonad/Actions/PerWindowKeys.hs
|
bsd-3-clause
| 2,201
| 0
| 11
| 528
| 277
| 164
| 113
| 15
| 2
|
module Expression
( Expr
, ExprBase(..)
, printExpr
, eval
, variables
, genExprList
) where
import Data.Bits as Bit
import Data.ByteString.Builder
import Data.Word
import Numeric
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Data.Set as Set
import Test.QuickCheck
-- |Base types for expressions
class Show a => ExprBase a where
printType :: a -> Builder -- ^ Print corresponding C data type
printConst :: a -> Builder -- ^ Print value as constant in C syntax
amounts :: a -> [a] -- ^ Shift amounts
immediates :: a -> [a] -- ^ Selected immediate values
instance ExprBase Word64 where
printType _ = string8 "unsigned long long"
printConst i = string8 "0x" <> word64Hex i <> string8 "ULL"
amounts _ = [ 1,6..63 ]
immediates _ = [ Bit.bit i | i <- [0..63]] ++ [ Bit.bit i - 1 | i <- [1..63]]
instance ExprBase Word32 where
printType _ = string8 "unsigned int"
printConst i = string8 "0x" <> word32Hex i <> string8 "U"
amounts _ = [ 1,4..31 ]
immediates _ = [ Bit.bit i | i <- [0..31]] ++ [ Bit.bit i - 1 | i <- [1..31]]
instance ExprBase Word16 where
printType _ = string8 "unsigned short"
printConst i = string8 "0x" <> word16Hex i <> string8 "U"
amounts _ = [ 1,4..16 ]
immediates _ = [ Bit.bit i | i <- [0..15]] ++ [ Bit.bit i - 1 | i <- [1..15]]
instance ExprBase Word8 where
printType _ = string8 "unsigned char"
printConst i = string8 "0x" <> word8Hex i <> string8 "U"
amounts _ = [ 1..7 ]
immediates _ = [ Bit.bit i | i <- [0..7]] ++ [ Bit.bit i - 1 | i <- [1..7]]
-- |Unary operations for expressions
data UnOp = Negate | Complement deriving Eq
instance Show UnOp where
show o = case o of
Negate -> " - "
Complement -> " ~ "
unop :: (Integral a, Bits a) => UnOp -> a -> a
unop o = case o of
Negate -> negate
Complement -> complement
-- |Binary operations for expressions
data BinOp = Add | Sub | Mul | Div | Mod | Shl | Shr | And | Or | Xor deriving Eq
instance Show BinOp where
show o = case o of
Add -> " + "
Sub -> " - "
Mul -> " * "
Div -> " / "
Mod -> " % "
Shl -> " << "
Shr -> " >> "
And -> " & "
Or -> " | "
Xor -> " ^ "
binop :: (Integral a, Bits a) => BinOp -> a -> a -> a
binop o =
case o of
Add -> (+)
Sub -> (-)
Mul -> (*)
Div -> quot
Mod -> rem
Shl -> wrap shiftL
Shr -> wrap shiftR
And -> (Bit..&.)
Or -> (Bit..|.)
Xor -> xor
where
wrap f x i = f x (fromIntegral i)
-- |Conditions for expressions
data Condition = Equal | NotEqual | LessThan | GreaterThan | LessOrEqual | GreaterOrEqual deriving Eq
instance Show Condition where
show o = case o of
Equal -> " == "
NotEqual -> " != "
LessThan -> " < "
GreaterThan -> " > "
LessOrEqual -> " <= "
GreaterOrEqual -> " >= "
condop :: (Integral a, Bits a) => Condition -> a -> a -> Bool
condop o = case o of
Equal -> (==)
NotEqual -> (/=)
LessThan -> (<)
GreaterThan -> (>)
LessOrEqual -> (<=)
GreaterOrEqual -> (>=)
if' :: Bool -> a -> a -> a
if' True x _ = x
if' False _ y = y
-- |Expressions
data Expr a
= UnExpr UnOp (Expr a)
| BinExpr BinOp (Expr a) (Expr a)
| CondExpr Condition (Expr a) (Expr a) (Expr a) (Expr a)
| Value a
| Variable String a
deriving Eq
-- |Show instance for messages of QuickCheck
instance (Integral a, Bits a, ExprBase a) => Show (Expr a) where
show = L.unpack . toLazyByteString . printExpr
-- |Builder for bytestream of an expression in C syntax
printExpr :: (Integral a, ExprBase a) => Expr a -> Builder
printExpr = pe 0
where
pe :: (Integral a, ExprBase a) => a -> Expr a -> Builder
pe v expr = case expr of
UnExpr o e -> char8 '(' <> printType v <> string8 ")(" <> string8 (show o) <> pse e <> char8 ')'
BinExpr o e1 e2 -> char8 '(' <> printType v <> string8 ")(" <> pse e1 <> string8 (show o) <> pse e2 <> char8 ')'
CondExpr o e1 e2 e3 e4 -> pse e1 <> string8 (show o) <> pse e2 <> string8 " ? " <> pse e3 <> string8 " : " <> pse e4
Value i -> printConst i
Variable n _ -> string8 n
pse (Value i) = printConst i
pse x = char8 '(' <> pe 0 x <> char8 ')'
-- |Evaluate an expression
eval :: (Integral a, Bits a) => Expr a -> Maybe a
eval expr = case expr of
UnExpr o e -> unop o <$> eval e
BinExpr o e1 e2 -> binop o <$> eval e1 <*> (eval e2 >>= catchErr o)
CondExpr o e1 e2 e3 e4 -> if' <$> (condop o <$> eval e1 <*> eval e2) <*> eval e3 <*> eval e4
Value i -> Just i
Variable _ i -> Just i
where
catchErr Div 0 = Nothing
catchErr Mod 0 = Nothing
catchErr _ n = Just n
-- |Extract variable name/value pairs used in an expression
variables :: (Eq a, Ord a) => Expr a -> [(String, a)]
variables = Set.toAscList . go Set.empty
where
go s expr = case expr of
UnExpr _ e -> go s e
BinExpr _ e1 e2 -> foldl go s [e1, e2]
CondExpr _ e1 e2 e3 e4 -> foldl go s [e1, e2, e3, e4]
Variable n i -> Set.insert (n, i) s
_ -> s
-- |Random expressions for QuickCheck
instance (Integral a, Bits a, ExprBase a) => Arbitrary (Expr a) where
-- |Generator for random expressions
arbitrary = sized expr
where
expr :: (Integral a, Bits a, ExprBase a) => Int -> Gen (Expr a)
expr n
| n == 0 = oneof [immAmount, mkVar <$> immAmount, immAny, mkVar <$> immAny]
| n > 0 = oneof [unaryExpr, arithExpr1, arithExpr2, shiftExpr, bitExpr, condExpr]
| otherwise = undefined
where
-- immediate constants/variable from range suitable as shift amount
immAmount = Value <$> elements (amounts 0)
-- immediate constants/variable from full range of data type
immAny = Value <$> elements (immediates 0)
-- convert immediate values into variables
mkVar (Value i) = Variable ("v_" ++ showHex i "") i
mkVar _ = undefined
-- generators for all expression forms
unaryExpr = UnExpr
<$> elements [Complement, Negate]
<*> expr (n-1)
arithExpr1 = BinExpr
<$> elements [Add, Sub, Mul]
<*> expr (n `div` 2)
<*> expr (n `div` 2)
arithExpr2 = BinExpr
<$> elements [Div, Mod]
<*> expr (n `div` 2)
<*> expr (n `div` 2) `suchThat` ((/= Just 0) . eval)
shiftExpr = BinExpr
<$> elements [Shl, Shr]
<*> expr (n `div` 2)
<*> oneof [immAmount, mkVar <$> immAmount]
bitExpr = BinExpr
<$> elements [And, Or, Xor]
<*> expr (n `div` 2)
<*> expr (n `div` 2)
condExpr = CondExpr
<$> elements [Equal, NotEqual, LessThan, GreaterThan, LessOrEqual, GreaterOrEqual]
<*> expr (n `div` 3)
<*> expr (n `div` 3)
<*> expr (n-1)
<*> expr (n-1)
-- |Shrink an expression into smaller expressions
shrink expr = filter ((/= Nothing) . eval) $ case expr of
UnExpr o e -> e : [UnExpr o e' | e' <- shrink e]
BinExpr o e1 e2 -> [e1, e2] ++ [BinExpr o e1' e2' | (e1', e2') <- shrink (e1, e2)]
CondExpr o e1 e2 e3 e4 -> [e1, e2, e3, e4] ++ [CondExpr o e1' e2' e3' e4' | (e1', e2', e3', e4') <- shrink (e1, e2, e3, e4)]
_ -> []
-- |Generator for a list of expressions. The list has a fixed length `len' and each expression is sized up to `complexity'
genExprList :: (Integral a, Bits a, ExprBase a) => Int -> Int -> Gen [Expr a]
genExprList len complexity = vectorOf len $ resize complexity arbitrary
|
m-schmidt/fuzzer
|
src/Expression.hs
|
bsd-3-clause
| 7,854
| 0
| 18
| 2,511
| 2,941
| 1,533
| 1,408
| 176
| 10
|
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.ShadowAmbient
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.ShadowAmbient (
-- * Extension Support
glGetARBShadowAmbient,
gl_ARB_shadow_ambient,
-- * Enums
pattern GL_TEXTURE_COMPARE_FAIL_VALUE_ARB
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/ARB/ShadowAmbient.hs
|
bsd-3-clause
| 664
| 0
| 5
| 91
| 47
| 36
| 11
| 7
| 0
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# OPTIONS_GHC -Wall -Werror #-}
{- |
Module : $Header$
Description : Compiling Lobster policies to information flow graphs
Copyright : (c) Galois, Inc.
License : see the file LICENSE
Maintainer : Joe Hurd
Stability : provisional
Portability : portable
Compiles the Lobster high-level policy language to an information flow graph.
-}
module Lobster.SELinux.SELinux
( SELinux(..)
, compileDomain
, toSELinux
, prettyPrintSELinux
, renderTypeEnforcement
, renderFileContext
, typeClassPermissionPort
)
where
import qualified Data.Char as Char
import Data.NonEmptyList(singleton)
import qualified SCD.SELinux.Syntax as SS
import qualified SCD.M4.Syntax as M4
import qualified SCD.M4.PrettyPrint()
import Text.PrettyPrint.HughesPJ(Doc, render, text)
import qualified Text.PrettyPrint.Pp as Pp
import Text.Regex.Posix((=~))
import Lobster.Monad
import qualified Lobster.Abs as Abs
import Lobster.Abs (
Connection(..),
PortId,
Position(..))
import qualified Lobster.Syntax as Syntax
import qualified Lobster.Domain as Domain
import Lobster.Domain(
DomainId,
DomainPort)
import qualified Lobster.Policy as Policy
import Lobster.Policy(
ContextClass(..),
Domain(..),
Value(..))
--------------------------------------------------------------------------------
-- SELinux classes.
--------------------------------------------------------------------------------
fileContextClass :: ContextClass
fileContextClass = Policy.mkContextClass Syntax.fileClass
dirContextClass :: ContextClass
dirContextClass = Policy.mkContextClass Syntax.dirClass
typeContextClass :: ContextClass
typeContextClass = Policy.mkContextClass Syntax.typeClass
toSELinuxContextClass :: ContextClass -> P String
toSELinuxContextClass (ccl @ (ContextClass ctxt cl)) =
if Policy.nullContext ctxt
then return (map Char.toLower (Syntax.idString cl))
else throwError $ "bad primitive class " ++ show ccl ++ "\n" ++
"primitive classes must be declared at the top level"
--------------------------------------------------------------------------------
-- Policy values.
--------------------------------------------------------------------------------
data SELinux =
SELinux
{ typeEnforcement :: M4.Implementation
, fileContext :: [M4.FileContext]
}
deriving (Eq, Show)
toSELinux :: String -> Domain -> P SELinux
toSELinux pref obj = do
te <- Policy.foldMSubDomain addTypeDeclaration [] obj
te' <- Policy.foldMConnectionsDomain addTypeEnforcement te obj
let imp = M4.Implementation
(SS.mkId pref)
(M4.Version "1.0")
(reverse te')
fc <- Policy.foldMSubDomain addFileContext [] obj
return SELinux
{typeEnforcement = imp,
fileContext = fc}
where
domainToType o = Policy.nameDomain o ++ "_t"
domainToClass :: Domain -> P String
domainToClass o =
let (ccl,_) = Policy.provenanceDomain o in
toSELinuxContextClass ccl
portToSubDomain :: DomainPort -> P Domain
portToSubDomain p = case Domain.domainDomainPort p of
Just i -> Policy.getSubDomain obj i
Nothing -> throwError "connection to System port"
portToType p = domainToType `fmap` portToSubDomain p
portToClass :: DomainPort -> P String
portToClass p = domainToClass =<< portToSubDomain p
portToPermission p = Syntax.idString (Domain.portDomainPort p)
addTypeDeclaration :: DomainId -> Domain -> M4.Stmts -> P M4.Stmts
addTypeDeclaration _ o tes =
let (ccl,vs) = Policy.provenanceDomain o in
if ccl == typeContextClass
then case vs of
[StringValue t] ->
return (M4.Require
(singleton (M4.RequireType
(singleton (SS.mkId t)))) : tes )
_ -> throwError $ "Bad arguments to "++
Syntax.idString Syntax.typeClass++
": "++show vs
else return (M4.Type (SS.mkId (domainToType o)) [] [] : tes)
addTypeEnforcement ::
DomainPort -> Connection -> DomainPort -> M4.Stmts -> P M4.Stmts
addTypeEnforcement p1 _ p2 tes =
do pt1 <- Policy.getPortTypeDomain obj p1
pt2 <- Policy.getPortTypeDomain obj p2
let pos1 = case Policy.positionPortType pt2 of
Just pos2 -> Just (Policy.invertPosition pos2)
Nothing -> Policy.positionPortType pt1
case pos1 of
Just SubjectPosition -> addTE p1 p2 tes
Just ObjectPosition -> addTE p2 p1 tes
Nothing -> throwError
("couldn't establish subject/object " ++
"relationship:\n " ++
Policy.prettyPrintDomainPort obj p1 ++ " : " ++
Policy.prettyPrintPortType pt1 ++ "\n " ++
Policy.prettyPrintDomainPort obj p2 ++ " : " ++
Policy.prettyPrintPortType pt2)
addTE :: DomainPort -> DomainPort -> M4.Stmts -> P M4.Stmts
addTE ps po tes =
do ns <- portToType ps
no <- portToType po
nc <- portToClass po
od <- portToSubDomain po
sd <- portToSubDomain ps
let np = portToPermission po
(odccl,vs) = Policy.provenanceDomain od
o = portTypeTypeClass (odccl,vs) no
s = portTypeTypeClass (Policy.provenanceDomain sd) ns
if odccl == typeTransitionContextClass
then case vs of
{-
[DomainValue ti, DomainValue ni] -> do
t <- domainToType `fmap` getSubDomain obj ti
n <- domainToType `fmap` getSubDomain obj ni
-}
-- Beware: Worst. Hack. Ever.
[StringValue ti, StringValue ni] -> do
let p = Syntax.idString (Domain.portDomainPort po)
me = reverse (drop 3 (reverse no))
return (mkTypeTransitionRule s (me++ti) (me++ni) p :
mkRoleRule defaultRole (me++ni) : tes)
_ -> throwError $
"Bad arguments to "++
Syntax.idString typeTransitionClass++
": "++show vs
else do
let (c,p) = case port2PermissionClass np of
Just cp -> cp
Nothing -> (nc,np)
return (mkAllowRule s o c p : tes)
addFileContext _ o fc =
let (ccl,vs) = Policy.provenanceDomain o in
if ccl == fileContextClass || ccl == dirContextClass then
case vs of
[StringValue s] ->
return $ M4.FileContext (M4.Path (M4.RegexpPath s)) Nothing
(Just (M4.GenContext fc_user fc_role
(SS.mkId (domainToType o))
fc_mlsRange)) : fc
_ -> throwError "bad File arguments"
else return fc
typeTransitionContextClass :: Policy.ContextClass
typeTransitionContextClass = Policy.mkContextClass typeTransitionClass
typeTransitionClass :: Abs.ClassId
typeTransitionClass = Syntax.mkId "TypeTransition"
portTypeTypeClass :: (ContextClass, [Value]) -> String -> String
portTypeTypeClass (ccl,[StringValue s]) _ | ccl == typeContextClass = s
portTypeTypeClass _ no = no
mkAllowRule :: String -> String -> String -> String -> M4.Stmt
mkAllowRule ns no nc np =
M4.TeAvTab SS.Allow
(SS.SourceTarget
{ SS.sourceTypes = singleton (SS.SignedId SS.Positive (SS.mkId ns))
, SS.targetTypes = singleton (SS.SignedId SS.Positive (SS.NotSelf
(SS.mkId no)))
, SS.targetClasses = singleton (SS.mkId nc)})
(SS.Permissions (singleton (SS.mkId np)))
mkTypeTransitionRule :: String -> String -> String -> String -> M4.Stmt
mkTypeTransitionRule ns t n p =
M4.Transition SS.TypeTransition
(SS.SourceTarget
{ SS.sourceTypes = singleton (SS.SignedId SS.Positive (SS.mkId ns))
, SS.targetTypes = singleton (SS.SignedId SS.Positive (SS.mkId t))
, SS.targetClasses = singleton (SS.mkId p) })
(SS.mkId n)
mkRoleRule :: SS.RoleId -> String -> M4.Stmt
mkRoleRule r t = M4.Role r [SS.SignedId SS.Positive (SS.mkId t)]
-- Default values to use for file contexts (hard-wired for now)
fc_user :: SS.UserId
fc_user = SS.mkId "system_u"
fc_role :: SS.RoleId
fc_role = SS.mkId "object_r"
fc_mlsRange :: M4.MlsRange
fc_mlsRange = M4.MlsRange s0 s0 where s0 = SS.mkId "s0"
-- Default role for role transition
defaultRole :: SS.RoleId
defaultRole = SS.mkId "unconfined_r"
prettyPrintSELinux :: SELinux -> String
prettyPrintSELinux selinux = render $ Pp.above $
[ text "--- Type enforcement (.te) file ---"
, ppTypeEnforcement selinux
, text "--- File context (.fc) file ---"
]
++
ppFileContext selinux
ppTypeEnforcement :: SELinux -> Doc
ppTypeEnforcement = Pp.pp . typeEnforcement
ppFileContext :: SELinux -> [Doc]
ppFileContext = map Pp.pp . fileContext
renderTypeEnforcement :: SELinux -> String
renderTypeEnforcement selinux = (render . ppTypeEnforcement) selinux
++ "\n" -- Files in POSIX end in newline
renderFileContext :: SELinux -> String
renderFileContext selinux = (render . Pp.above . ppFileContext) selinux
++ "\n" -- Files in POSIX end in newline
-- | Construct magic Type ports from class-permission map
typeClassPermissionPort :: SS.ClassId -> SS.PermissionId -> PortId
typeClassPermissionPort c p = Syntax.mkId (SS.idString c ++
typeClassPermissionSeparator ++
SS.idString p)
-- | Deconstruct magic Type port into class and permission
port2PermissionClass :: String -> Maybe (String, String)
port2PermissionClass s | m == "" = Nothing
| otherwise = Just (b,a)
where (b,m,a) = s =~ typeClassPermissionSeparator
typeClassPermissionSeparator :: String
typeClassPermissionSeparator = "__"
flattenDomain :: Domain -> Domain
flattenDomain domain =
case runP (Policy.flattenDomain domain) of
Left err ->
error ("ERROR: couldn't flatten the Lobster policy file:\n" ++ err)
Right domain' -> domain'
compileDomain :: String -> Domain -> SELinux
compileDomain output domain =
let domain' = flattenDomain domain in
domainToSELinux output domain'
domainToSELinux :: String -> Domain -> SELinux
domainToSELinux moduleName domain =
case runP (toSELinux moduleName domain) of
Left err ->
error ("ERROR: couldn't generate native SELinux from the " ++
"Lobster policy file:\n" ++ err)
Right selinux -> selinux
|
GaloisInc/sk-dev-platform
|
libs/lobster-selinux/src/Lobster/SELinux/SELinux.hs
|
bsd-3-clause
| 11,246
| 1
| 25
| 3,401
| 2,714
| 1,397
| 1,317
| 223
| 12
|
module QuoteUtilsTests
( main
) where
import Control.Concurrent
import Bridgewalker
import CommonTypes
import Config
import FormatUtils
import QuoteUtils
main :: IO ()
main = do
bwHandles <- initBridgewalker
threadDelay $ 5 * 1000 * 1000
testQuote bwHandles $ AmountBasedOnBTC 1000000
testQuote bwHandles $ AmountBasedOnUSDBeforeFees 10000000
testQuote bwHandles $ AmountBasedOnUSDAfterFees 10000000
testQuote bwHandles $ AmountBasedOnBTC 100000
testQuote bwHandles $ AmountBasedOnUSDBeforeFees 100000
testQuote bwHandles $ AmountBasedOnUSDAfterFees 100000
testQuote :: BridgewalkerHandles -> AmountType -> IO ()
testQuote bwHandles amount = do
let account = BridgewalkerAccount 2
qc <- compileQuote bwHandles account amount
putStrLn $ "Quote for: " ++ show amount
case qc of
SuccessfulQuote quote -> do
putStrLn $ "BTC: " ++ formatBTCAmount (qdBTC quote)
putStrLn $ "USD (Recipient): "
++ formatUSDAmount (qdUSDRecipient quote)
putStrLn $ "USD (Account): " ++ formatUSDAmount (qdUSDAccount quote)
putStrLn $ "Sufficient balance: " ++ show (qdSufficientBalance quote)
putStrLn $ "Needs small tx fund: " ++ show (qdNeedsSmallTxFund quote)
QuoteCompilationError errMsg -> print errMsg
putStrLn ""
|
javgh/bridgewalker
|
src/QuoteUtilsTests.hs
|
bsd-3-clause
| 1,360
| 0
| 15
| 322
| 346
| 157
| 189
| 33
| 2
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MonadComprehensions #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RebindableSyntax #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ViewPatterns #-}
-- TPC-H Q11
module Queries.TPCH.Standard.Q11
( q11
, q11Default
) where
import Database.DSH
import Schema.TPCH
fst3 :: (QA a, QA b, QA c) => Q (a, b ,c) -> Q a
fst3 (view -> (a, _, _)) = a
nationPartsValues :: Text -> Q [(Integer, Decimal, Integer)]
nationPartsValues nationName =
[ tup3 (ps_partkeyQ ps)
(ps_supplycostQ ps)
(ps_availqtyQ ps)
| ps <- partsupps
, s <- suppliers
, n <- nations
, ps_suppkeyQ ps == s_suppkeyQ s
, s_nationkeyQ s == n_nationkeyQ n
, n_nameQ n == toQ nationName
]
totalValue :: Decimal -> Q Decimal
totalValue fraction =
toQ fraction * sum [ ps_supplycostQ ps * integerToDecimal (ps_availqtyQ ps)
| ps <- partsupps
, s <- suppliers
, n <- nations
, ps_suppkeyQ ps == s_suppkeyQ s
, s_nationkeyQ s == n_nationkeyQ n
, n_nameQ n == "GERMANY"
]
partValue :: Q [(Integer, Decimal, Integer)] -> Q Decimal
partValue g = sum [ supplycost * integerToDecimal availqty
| (view -> (_, supplycost, availqty)) <- g
]
-- | TPC-H Query Q11 with standard validation parameters
q11Default :: Q [(Integer, Decimal)]
q11Default = q11 "GERMANY" 0.0001
-- | TPC-H Query Q11
q11 :: Text -> Decimal -> Q [(Integer, Decimal)]
q11 nationName fraction =
sortWith ((* (-1)) . snd)
[ pair k (partValue g)
| (view -> (k, g)) <- groupWithKey fst3 (nationPartsValues nationName)
, partValue g > (totalValue fraction)
]
|
ulricha/dsh-example-queries
|
Queries/TPCH/Standard/Q11.hs
|
bsd-3-clause
| 1,962
| 0
| 11
| 580
| 564
| 299
| 265
| 48
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Turtle
import Prelude hiding (FilePath, log, putStrLn)
import Filesystem.Path.CurrentOS (fromText)
import Data.Text (pack)
import Data.Maybe
import qualified System.IO as SysIO (hFlush, stdout)
defaultSleepSeconds = 120
main :: IO ()
main = do
(repoPath, maybeSecs) <- options "Runs a `git fetch` continuously for a given repository" parser
let secs = fromMaybe defaultSleepSeconds $ fmap realToFrac maybeSecs
fetch repoPath secs
parser :: Parser (FilePath, Maybe Int)
parser = (,) <$> argPath "repo" "The path to a git repository"
<*> optional (argInt "sleepSeconds" "The number of seconds to sleep between fetches.")
fetch :: FilePath -> NominalDiffTime -> IO ()
fetch repoDir sleepSeconds = do
cd repoDir
dir <- pwd
fetchOne dir .||. die (format ("Error fetching in "%fp%". Is this a git repository?") dir)
log $ format ("Fetching every "%s%" in " %fp% "") (pack $ show sleepSeconds) dir
fetchEvery dir sleepSeconds
fetchOne :: FilePath -> IO ExitCode
fetchOne dir = do
log $ format ("Running a git fetch in " %fp) dir
(exitCode, out) <- shellStrict "git fetch" empty
log $ format ("Done running a git fetch in " %fp% " - "%s%s) dir (pack $ show exitCode) out
return exitCode
fetchEvery :: FilePath -> NominalDiffTime -> IO ()
fetchEvery dir sleepSeconds = do
sleep sleepSeconds
fetchOne dir
fetchEvery dir sleepSeconds
log :: Text -> IO ()
log msg = do
now <- dateString
echo $ format (s%" "%s) now msg
SysIO.hFlush SysIO.stdout
dateString :: IO Text
dateString = do
d <- date
return $ pack $ show d
|
apauley/git-fetch-daemon
|
app/Main.hs
|
bsd-3-clause
| 1,630
| 0
| 13
| 321
| 559
| 277
| 282
| 44
| 1
|
module Plunge.Types.PreprocessorOutput
( Section(..)
, LineRange(..)
, LineAssociation(..)
, LineNumber
, FromLine
, ToLine
, CLine
, CppLine
, CppDirective(..)
, DirectiveFlag(..)
) where
type LineNumber = Int
type FromLine = Int
type ToLine = Int
type CLine = String
type CppLine = String
data DirectiveFlag = EnterFile | ReturnFile | SystemHeader | ExternC
deriving (Show, Ord, Eq)
data CppDirective = CppDirective LineNumber FilePath [DirectiveFlag]
deriving (Show)
data LineRange = LineRange { fromLine :: FromLine
, toLine :: ToLine
} deriving (Show)
data Section
= Block
{ blockLines :: [String]
, startLine :: LineNumber
, lineRange :: LineRange
}
| MiscDirective
{ directive :: CppDirective
, lineRange :: LineRange
}
| Expansion
{ enterDirective :: CppDirective
, returnDirective :: CppDirective
, startLine :: LineNumber
, sections :: [Section]
, lineRange :: LineRange
}
deriving (Show)
data LineAssociation = LineAssociation { cRange :: Maybe LineRange
, cppRange :: Maybe LineRange
} deriving (Show)
|
sw17ch/plunge
|
src/Plunge/Types/PreprocessorOutput.hs
|
bsd-3-clause
| 1,290
| 0
| 9
| 428
| 297
| 187
| 110
| 41
| 0
|
{-# LANGUAGE OverloadedStrings #-}
module Network.Anonymous.I2PSpec where
import Control.Concurrent.MVar
import Control.Concurrent (forkIO,
threadDelay,
killThread)
import qualified Network.Socket.ByteString as Network
import Data.Maybe (isJust, isNothing)
import Network.Anonymous.I2P
import qualified Network.Anonymous.I2P.Types.Socket as S
import Test.Hspec
spec :: Spec
spec = do
describe "when serving VirtualStream connections" $ do
it "source destination should match accepted destination" $
let storeDestination pubDestValidate' (_, dest) =
putMVar pubDestValidate' dest
in do
(privDest0, pubDest0) <- createDestination defaultEndPoint Nothing
(privDest1, pubDest1) <- createDestination defaultEndPoint Nothing
pubDestValidate0' <- newEmptyMVar
pubDestValidate1' <- newEmptyMVar
threadId <- forkIO $ withSession' defaultEndPoint S.VirtualStream (privDest0, pubDest0) (\ctx -> serveStream ctx (storeDestination pubDestValidate1'))
threadDelay 30000000
withSession' defaultEndPoint S.VirtualStream (privDest1, pubDest1) (\ctx -> connectStream ctx pubDest0 (storeDestination pubDestValidate0'))
pubDestValidate0 <- takeMVar pubDestValidate0'
pubDestValidate1 <- takeMVar pubDestValidate1'
pubDestValidate0 `shouldBe` pubDest0
pubDestValidate1 `shouldBe` pubDest1
killThread threadId
it "sockets should be able to communicate" $
let sendResponse (sock, _) = do
putStrLn "Now sending data.."
Network.sendAll sock "Hello, world!"
putStrLn "Sent data!"
readResponse response' (sock, _) = do
putStrLn "Now calling recv()"
buf <- Network.recv sock 64
putStrLn ("Received: " ++ show buf)
putMVar response' buf
in do
(privDest0, pubDest0) <- createDestination defaultEndPoint Nothing
response' <- newEmptyMVar
threadId <- forkIO $ withSession' defaultEndPoint S.VirtualStream (privDest0, pubDest0) (\ctx -> serveStream ctx sendResponse)
threadDelay 30000000
withSession defaultEndPoint S.VirtualStream (\ctx -> connectStream ctx pubDest0 (readResponse response'))
response <- takeMVar response'
response `shouldBe` "Hello, world!"
killThread threadId
describe "when serving datagrams connections" $ do
it "messages are received along with their reply address or not" $
let socketTypes = [ S.DatagramAnonymous
, S.DatagramRepliable]
receiveMessage msg' pubDest' (msg, pubDest) = do
putStrLn ("received message: " ++ show msg)
putMVar msg' msg
putMVar pubDest' pubDest
putStrLn ("stored mvars")
sendMessage ctx dest msg = do
threadDelay 30000000
putStrLn ("sending message: " ++ show msg)
sendDatagram ctx dest msg
performTest socketType = do
(privDest0, pubDest0) <- createDestination defaultEndPoint Nothing
msg' <- newEmptyMVar
sessionReady' <- newEmptyMVar
pubDest1' <- newEmptyMVar
finished' <- newEmptyMVar
threadId1 <- forkIO $ withSession' defaultEndPoint socketType (privDest0, pubDest0) (\ctx -> do
_ <- putMVar sessionReady' True
serveDatagram ctx (receiveMessage msg' pubDest1'))
_ <- takeMVar sessionReady'
threadId2 <- forkIO $ withSession defaultEndPoint socketType (\ctx -> do
sendMessage ctx pubDest0 "Hello, world!\n"
-- This blocks until the test is finished
_ <- readMVar finished'
return ())
msg <- readMVar msg'
pubDest1 <- readMVar pubDest1'
putMVar finished' True
putStrLn("got mvars: msg=" ++ show msg ++ ", pubDest1=" ++ show pubDest1)
msg `shouldBe` "Hello, world!\n"
case socketType of
S.DatagramAnonymous -> pubDest1 `shouldSatisfy` isNothing
S.DatagramRepliable -> pubDest1 `shouldSatisfy` isJust
return ()
in mapM performTest socketTypes >> return ()
|
bitemyapp/haskell-network-anonymous-i2p
|
test/Network/Anonymous/I2PSpec.hs
|
mit
| 4,839
| 0
| 26
| 1,779
| 1,007
| 485
| 522
| 86
| 2
|
{-# LANGUAGE RecordWildCards #-}
module Pos.Chain.Update.BlockVersionData
( BlockVersionData (..)
, isBootstrapEraBVD
, ObftConsensusStrictness (..)
, ConsensusEra (..)
, consensusEraBVD
, obftEraFlagValue
) where
import Universum
import Control.Monad.Except (MonadError)
import qualified Data.Aeson.Options as S (defaultOptions)
import Data.Aeson.TH (deriveJSON)
import Data.SafeCopy (base, deriveSafeCopySimple)
import Data.Time.Units (Millisecond)
import Formatting (bprint, build, int, (%))
import qualified Formatting.Buildable as Buildable
import Serokell.Data.Memory.Units (Byte, memory)
import Text.JSON.Canonical (FromJSON (..), ToJSON (..), fromJSField,
mkObject)
import Pos.Binary.Class (Cons (..), Field (..), deriveSimpleBi)
import Pos.Chain.Update.SoftforkRule
import Pos.Core.Binary ()
import Pos.Core.Common (CoinPortion, ScriptVersion, TxFeePolicy)
import Pos.Core.Slotting (EpochIndex (..), FlatSlotId, isBootstrapEra)
import Pos.Util.Json.Canonical (SchemaError)
import Pos.Util.Orphans ()
-- | Data which is associated with 'BlockVersion'.
data BlockVersionData = BlockVersionData
{ bvdScriptVersion :: !ScriptVersion
, bvdSlotDuration :: !Millisecond
, bvdMaxBlockSize :: !Byte
, bvdMaxHeaderSize :: !Byte
, bvdMaxTxSize :: !Byte
, bvdMaxProposalSize :: !Byte
, bvdMpcThd :: !CoinPortion
, bvdHeavyDelThd :: !CoinPortion
, bvdUpdateVoteThd :: !CoinPortion
, bvdUpdateProposalThd :: !CoinPortion
, bvdUpdateImplicit :: !FlatSlotId
, bvdSoftforkRule :: !SoftforkRule
, bvdTxFeePolicy :: !TxFeePolicy
, bvdUnlockStakeEpoch :: !EpochIndex
} deriving (Show, Eq, Ord, Generic, Typeable)
instance NFData BlockVersionData where
instance Buildable BlockVersionData where
build BlockVersionData {..} =
bprint ("{ script version: "%build%
", slot duration: "%int%" mcs"%
", block size limit: "%memory%
", header size limit: "%memory%
", tx size limit: "%memory%
", proposal size limit: "%memory%
", mpc threshold: "%build%
", heavyweight delegation threshold: "%build%
", update vote threshold: "%build%
", update proposal threshold: "%build%
", update implicit period: "%int%" slots"%
", softfork rule: "%build%
", tx fee policy: "%build%
", unlock stake epoch: "%build%
" }")
bvdScriptVersion
bvdSlotDuration
bvdMaxBlockSize
bvdMaxHeaderSize
bvdMaxTxSize
bvdMaxProposalSize
bvdMpcThd
bvdHeavyDelThd
bvdUpdateVoteThd
bvdUpdateProposalThd
bvdUpdateImplicit
bvdSoftforkRule
bvdTxFeePolicy
bvdUnlockStakeEpoch
instance Monad m => ToJSON m BlockVersionData where
toJSON (BlockVersionData scriptVersion slotDuration maxBlockSize maxHeaderSize maxTxSize maxProposalSize mpcThd heavyDelThd updateVoteThd updateProposalThd updateImplicit softforkRule txFeePolicy unlockStakeEpoch) =
mkObject
[ ("scriptVersion", toJSON scriptVersion)
, ("slotDuration", toJSON slotDuration)
, ("maxBlockSize", toJSON maxBlockSize)
, ("maxHeaderSize", toJSON maxHeaderSize)
, ("maxTxSize", toJSON maxTxSize)
, ("maxProposalSize", toJSON maxProposalSize)
, ("mpcThd", toJSON mpcThd)
, ("heavyDelThd", toJSON heavyDelThd)
, ("updateVoteThd", toJSON updateVoteThd)
, ("updateProposalThd", toJSON updateProposalThd)
, ("updateImplicit", toJSON updateImplicit)
, ("softforkRule", toJSON softforkRule)
, ("txFeePolicy", toJSON txFeePolicy)
, ("unlockStakeEpoch", toJSON unlockStakeEpoch)
]
instance MonadError SchemaError m => FromJSON m BlockVersionData where
fromJSON obj = do
bvdScriptVersion <- fromJSField obj "scriptVersion"
bvdSlotDuration <- fromJSField obj "slotDuration"
bvdMaxBlockSize <- fromJSField obj "maxBlockSize"
bvdMaxHeaderSize <- fromJSField obj "maxHeaderSize"
bvdMaxTxSize <- fromJSField obj "maxTxSize"
bvdMaxProposalSize <- fromJSField obj "maxProposalSize"
bvdMpcThd <- fromJSField obj "mpcThd"
bvdHeavyDelThd <- fromJSField obj "heavyDelThd"
bvdUpdateVoteThd <- fromJSField obj "updateVoteThd"
bvdUpdateProposalThd <- fromJSField obj "updateProposalThd"
bvdUpdateImplicit <- fromJSField obj "updateImplicit"
bvdSoftforkRule <- fromJSField obj "softforkRule"
bvdTxFeePolicy <- fromJSField obj "txFeePolicy"
bvdUnlockStakeEpoch <- fromJSField obj "unlockStakeEpoch"
return BlockVersionData {..}
deriveJSON S.defaultOptions ''BlockVersionData
-- | Version of 'isBootstrapEra' which takes 'BlockVersionData'
-- instead of unlock stake epoch.
isBootstrapEraBVD :: BlockVersionData -> EpochIndex -> Bool
isBootstrapEraBVD adoptedBVD = isBootstrapEra (bvdUnlockStakeEpoch adoptedBVD)
-- | This is a magic value which signifies that we are in the OBFT era.
-- Since we are no longer decentralizing this codebase, we can repurpose
-- this field to signify the shift to OBFT.
obftEraFlagValue :: EpochIndex
obftEraFlagValue = EpochIndex 9999999999999999999
data ObftConsensusStrictness = ObftStrict | ObftLenient
deriving (Eq, Show, Generic)
instance NFData ObftConsensusStrictness
data ConsensusEra = Original | OBFT ObftConsensusStrictness
deriving (Eq, Show, Generic)
instance NFData ConsensusEra
-- | This function uses the repurposed field `bvdUnlockStakeEpoch` to
-- tell us whether we are in the Original or OBFT consensus eras.
consensusEraBVD :: BlockVersionData -> ConsensusEra
consensusEraBVD bvd = if obftEraFlagValue == bvdUnlockStakeEpoch bvd
then OBFT ObftLenient
else Original
deriveSimpleBi ''BlockVersionData [
Cons 'BlockVersionData [
Field [| bvdScriptVersion :: ScriptVersion |],
Field [| bvdSlotDuration :: Millisecond |],
Field [| bvdMaxBlockSize :: Byte |],
Field [| bvdMaxHeaderSize :: Byte |],
Field [| bvdMaxTxSize :: Byte |],
Field [| bvdMaxProposalSize :: Byte |],
Field [| bvdMpcThd :: CoinPortion |],
Field [| bvdHeavyDelThd :: CoinPortion |],
Field [| bvdUpdateVoteThd :: CoinPortion |],
Field [| bvdUpdateProposalThd :: CoinPortion |],
Field [| bvdUpdateImplicit :: FlatSlotId |],
Field [| bvdSoftforkRule :: SoftforkRule |],
Field [| bvdTxFeePolicy :: TxFeePolicy |],
Field [| bvdUnlockStakeEpoch :: EpochIndex |]
]]
deriveSafeCopySimple 0 'base ''BlockVersionData
|
input-output-hk/pos-haskell-prototype
|
chain/src/Pos/Chain/Update/BlockVersionData.hs
|
mit
| 7,189
| 0
| 37
| 1,968
| 1,344
| 752
| 592
| -1
| -1
|
{-# LANGUAGE NPlusKPatterns #-}
module Ch6examp where
-- ghci -XNPlusKPatterns
-- : set expandtab ts=4 ruler number spell
-- U case over N+K ?
-- ? Bart's Blog Post on Pattern Matching over enumerables
import qualified Data.List as D
-- 6.1 -- 02:00
factorial :: Int -> Int
factorial n = product(take n [1..n])
f2ctorial :: Integral a => a -> a
f2ctorial n = product(D.genericTake n [1..n])
fact4rial :: Int -> Int
fact4rial 0 = 1
fact4rial (n + 1) = (n + 1) * factorial n
f2ct4rial :: Integral a => a -> a
f2ct4rial 0 = 1
f2ct4rial (n + 1) = (n + 1) * f2ctorial n
{-
factoriaL :: Int -> Int
factoriaL [] = []
factoriaL [0] = [1]
factoriaL (n + 1) = (n + 1) * factorial n
f2ctoriaL :: Integral a => a -> a
f2ctoriaL 0 = 1
f2ctoriaL (n + 1) = (n + 1) * f2ctorial n
-}
factoriaL n = [product(take n [1..n])|n<-[1..n]]
f2ctoriaL n = [product(D.genericTake n [1..n])|n<-[1..n]]
cmpairfact n = zip (factoriaL n) (f2ctoriaL n)
--(*) -- going to have to settle for just two args here
mult :: Integer->Integer->Integer
m `mult` 0 = 0
m `mult`(n+1) = m+(m`mult`n)
-- 6.2 -- 05:00 -- 15:00 --
--
pr4duct :: [Integer] -> Integer
pr4duct [] = 1 -- multiplication by 1 is the same as identity
pr4duct (x:xs) = x * (pr4duct xs)
l2ngth :: [a] -> Integer
l2ngth [] = 0
l2ngth (_:xs) = 1 + l2ngth xs
r2verse :: [a]->[a]
r2verse [] = []
r2verse (x:xs) = r2verse xs ++ [x]
-- (++)
join :: [a]->[a]->[a]
[] `join` ys = ys
(x:xs) `join` ys = x:(join xs ys)
{- > join [1,2,3] [4,5,6]
[1,2,3,4,5,6]
-}
ins2rt :: Ord a => a->[a]->[a]
ins2rt x [] = [x]
ins2rt x (y:ys) |x<=y = x:y:ys
|otherwise = y:ins2rt x ys
is4rt :: Ord a=>[a]->[a]
is4rt [] = []
is4rt (x:xs) = ins2rt x (is4rt xs)
-- 6.3 -- Multi args
z3p :: [a]->[b]->[(a,b)]
z3p [] _ = []
z3p _ [] = []
z3p (x:xs) (y:ys) = (x,y):z3p xs ys
dr4p :: Integer -> [a]->[a]
dr4p 0 xs = xs
dr4p (n+1) [] = []
dr4p (n+1) (_:xs) = dr4p n xs
-- > dr4p 5 [1..11]
-- [6,7,8,9,10,11]
-- 6.4 -- Multiple recursion
fibonacc3 :: Integer -> Integer
fibonacc3 0 = 0
fibonacc3 1 = 1
fibonacc3 (n+2) = fibonacc3 n + fibonacc3 (n+1)
-- compare to first meeting
qsort :: Ord a => [a]->[a]
qsort [] = []
qsort (x:xs) = qsort smaller ++ [x] ++ larger
where
smaller = [a|a<-xs,a<=x]
larger = [b|b<-xs,b>x]
-- 6.5 -- mutual recursion
ev2n :: Integer -> Bool
ev2n 0 = True
ev2n (n+1) = odd n
oDD :: Integer -> Bool
oDD 0 = False
oDD (n+1) = ev2n n
-- ev2n 5
-- False
-- ev2n 6
-- True
-- oDD 0
-- False
-- this uses position not value; evens [0..n] will return evens
-- return the opposite [1..n] will not.
evens :: [a] -> [a]
evens [] = []
evens (x:xs) = x:odds xs
odds :: [a] -> [a]
odds [] = []
odds (_:xs) = evens xs
-- 6.6 --
-- 6.8.1 --
-- do the (^) operator like we did for (*)
{-
mult :: Integer->Integer->Integer
m `mult` 0 = 0
m `mult`(n+1) = m+(m`mult`n)
our type def.
(^) :: (Num a, Integral b) => a -> b -> a -- Defined in `GHC.Real'
-}
eXpo :: (Integral a, Num a1) => a1 -> a -> a1
m `eXpo` 0 = 1
m `eXpo` (n+1) = m * m `eXpo` n
-- > 2 `eXpo` 3
-- 8
{-
2 `eXpo` 3
= {applying `eXpo` }
2 * (2 `eXpo` 2)
= {applying `eXpo` }
2*(2*(2 `eXpo` 1))
= {applying `eXpo` }
2*(2*(2*(2 `eXpo` 0)))
= {applying `eXpo` }
2*(2*(2*1))
= {applying * }
8
-- proof
*Ch6examp> 2 `eXpo` 3 == 2 * (2 `eXpo` 2)
True
*Ch6examp> 2 * (2 `eXpo` 2)==2*(2*(2 `eXpo` 1))
True
*Ch6examp> 2*(2*(2 `eXpo` 1))==2*(2*(2*(2 `eXpo` 0)))
True
*Ch6examp> 2*(2*(2*(2 `eXpo` 0)))== 2*(2*(2*1))
True
*Ch6examp> 2*(2*(2*1))== 8
True
-}
{- 6.8.2.1 --
length [1,2,3]
= {applying length}
1+ length [2,3]
= {applying length}
1+(1 + length [3])
= {applying length}
1 +(1+(1 + 0))
= {applying +}
3
-- proofs
*Ch7ex> length [1,2,3] == 1+ length [2,3]
True
*Ch7ex> 1+ length [2,3] == 1+(1 + length [3])
True
*Ch7ex> 1+(1 + length [3]) == 1 +(1+(1 + 0))
True
*Ch7ex> 1 +(1+(1 + 0)) == 3
True
-}
{- 6.8.2.2 --
drop 3 [1,2,3,4,5]
= {applying drop}
drop 2 [2,3,4,5]
= {applying drop}
drop 1 [3,4,5]
= {applying drop}
drop 0 [4,5]
= {applying drop}
[4,5]
-}
prf_drop = ((drop 3 [1,2,3,4,5]) == (drop 2 [2,3,4,5])) == ((drop 1 [3,4,5]== drop 0 [4,5])) -- trying to just tack on [4,8] didn't work because the to get a boolean back the == we had to follow an recursive like pattern.
-- *Ch6examp> prf_drop
-- True
-- *Ch6examp> drop 0 [4,5] == [4,5]
-- True
-- NOTE!! we had to balance the proof
prf_drop2 = (drop 0 [4,5]== [4,5]) == ((drop 3 [1,2,3,4,5] == drop 2 [2,3,4,5]) == (drop 1 [3,4,5]== drop 0 [4,5]))
-- *Ch6examp> prf_drop2
-- True
-- *Ch6examp> prf_drop == prf_drop2
-- True
{-
init [1,2,3]
= {applying init}
1:init [2,3]
= {applying init}
1:2:init [3]
= {applying init}
1:2:[]
= { list notation}
[1,2]
-- proof
*Ch6examp> init [1,2,3] == 1:init [2,3]
True
*Ch6examp> 1:init [2,3]==1:2:init [3]
True
*Ch6examp> 1:2:init [3] == 1:2:[]
True
*Ch6examp> 1:2:[] == [1,2]
True
-}
-- 6.8.3 --
-- and :: [Bool] -> Bool -- Defined in `GHC.List'
aNd [] = True
aNd (b:bs) = b && aNd bs
c4ncat [] = []
c4ncat (xs:xss) = xs ++ c4ncat xss
-- r2plicate :: Int -> a -> [a] -- Defined in `GHC.List'
r2plicate 0 _ = []
r2plicate (n+1) x = x:r2plicate n x
-- (x:_)!!0 = x
-- (_:xs)!!(n+1) = xs!!n
el2m :: Eq a => a -> [a] -> Bool
el2m x [] = False
el2m x (y:ys) | x==y = True
|otherwise = el2m x ys
-- 6.8.4 --
merge :: Ord a => [a] -> [a] -> [a]
merge [] ys = ys
merge xs [] = xs
merge (x:xs) (y:ys) = if x <= y then
x:merge xs (y:ys)
else
y:merge (x:xs) ys
-- 6.8.5 --
halve xs = splitAt (length xs `div` 2) xs
msort [] = []
msort [x] = [x]
msort xs = merge(msort ys) (msort zs)
where (ys, zs) = halve xs
{- 6.8.6.1 --
1. define type
s5m :: [Int] -> Int
2. enumerate the cases
sum [] =
sum (x:xs) =
3. define the simple case
sum [] = 0
sum(x:xs) =
4. define other cases
sum [] = 0
sum (x:xs) = x + sum xs
5. generalise and simplify
sum :: Num a => [a] -> a
sum = foldr (+) 0
-- 6.8.6.2 --
1. define type
take :: Int -> [a] -> [a]
2. enumerate the cases
take 0 [] =
take 0 (x:xs) =
take (n+1) [] =
take (n+1) (x:xs) =
3. define simple cases
take 0 [] = []
take 0 (x:xs) = []
take (n+1) [] = []
take (n+1) (x:xs) =
4. define the other cases
take 0 [] = []
take 0 (x:xs) = []
take (n+1) [] = []
take (n+1) (x:xs) = x:take n xs
5. generalise and simplify
take :: Int -> [a] -> [a]
take 0 _ = []
take (n+1) [] = []
take (n+1) (x:xs) = x:take n xs
-- 6.8.6.3 --
1. define type
last :: [a] -> [a]
2. enumerate the cases
last (x:xs) =
3. define simple cases
last (x:xs) =
take (x:xs) | null xs = x
| otherwise =
4. define the other cases
last (x:xs) =
take (x:xs) | null xs = x
| otherwise = last xs
5. generalise and simplify
last :: [a] -> [a]
last [x] = x
last (_:xs) = x
-}
|
HaskellForCats/HaskellForCats
|
MenaBeginning/Ch006/ch6ex2+.hs
|
mit
| 8,041
| 110
| 11
| 2,865
| 2,041
| 1,109
| 932
| 93
| 2
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.OpsWorks.SetLoadBasedAutoScaling
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Specify the load-based auto scaling configuration for a specified layer. For
-- more information, see <http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-autoscaling.html Managing Load with Time-based and Load-based Instances>.
--
-- To use load-based auto scaling, you must create a set of load-based auto
-- scaling instances. Load-based auto scaling operates only on the instances
-- from that set, so you must ensure that you have created enough instances to
-- handle the maximum anticipated load.
--
-- Required Permissions: To use this action, an IAM user must have a Manage
-- permissions level for the stack, or an attached policy that explicitly grants
-- permissions. For more information on user permissions, see <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing UserPermissions>.
--
-- <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_SetLoadBasedAutoScaling.html>
module Network.AWS.OpsWorks.SetLoadBasedAutoScaling
(
-- * Request
SetLoadBasedAutoScaling
-- ** Request constructor
, setLoadBasedAutoScaling
-- ** Request lenses
, slbasDownScaling
, slbasEnable
, slbasLayerId
, slbasUpScaling
-- * Response
, SetLoadBasedAutoScalingResponse
-- ** Response constructor
, setLoadBasedAutoScalingResponse
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.OpsWorks.Types
import qualified GHC.Exts
data SetLoadBasedAutoScaling = SetLoadBasedAutoScaling
{ _slbasDownScaling :: Maybe AutoScalingThresholds
, _slbasEnable :: Maybe Bool
, _slbasLayerId :: Text
, _slbasUpScaling :: Maybe AutoScalingThresholds
} deriving (Eq, Read, Show)
-- | 'SetLoadBasedAutoScaling' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'slbasDownScaling' @::@ 'Maybe' 'AutoScalingThresholds'
--
-- * 'slbasEnable' @::@ 'Maybe' 'Bool'
--
-- * 'slbasLayerId' @::@ 'Text'
--
-- * 'slbasUpScaling' @::@ 'Maybe' 'AutoScalingThresholds'
--
setLoadBasedAutoScaling :: Text -- ^ 'slbasLayerId'
-> SetLoadBasedAutoScaling
setLoadBasedAutoScaling p1 = SetLoadBasedAutoScaling
{ _slbasLayerId = p1
, _slbasEnable = Nothing
, _slbasUpScaling = Nothing
, _slbasDownScaling = Nothing
}
-- | An 'AutoScalingThresholds' object with the downscaling threshold configuration.
-- If the load falls below these thresholds for a specified amount of time, AWS
-- OpsWorks stops a specified number of instances.
slbasDownScaling :: Lens' SetLoadBasedAutoScaling (Maybe AutoScalingThresholds)
slbasDownScaling = lens _slbasDownScaling (\s a -> s { _slbasDownScaling = a })
-- | Enables load-based auto scaling for the layer.
slbasEnable :: Lens' SetLoadBasedAutoScaling (Maybe Bool)
slbasEnable = lens _slbasEnable (\s a -> s { _slbasEnable = a })
-- | The layer ID.
slbasLayerId :: Lens' SetLoadBasedAutoScaling Text
slbasLayerId = lens _slbasLayerId (\s a -> s { _slbasLayerId = a })
-- | An 'AutoScalingThresholds' object with the upscaling threshold configuration.
-- If the load exceeds these thresholds for a specified amount of time, AWS
-- OpsWorks starts a specified number of instances.
slbasUpScaling :: Lens' SetLoadBasedAutoScaling (Maybe AutoScalingThresholds)
slbasUpScaling = lens _slbasUpScaling (\s a -> s { _slbasUpScaling = a })
data SetLoadBasedAutoScalingResponse = SetLoadBasedAutoScalingResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'SetLoadBasedAutoScalingResponse' constructor.
setLoadBasedAutoScalingResponse :: SetLoadBasedAutoScalingResponse
setLoadBasedAutoScalingResponse = SetLoadBasedAutoScalingResponse
instance ToPath SetLoadBasedAutoScaling where
toPath = const "/"
instance ToQuery SetLoadBasedAutoScaling where
toQuery = const mempty
instance ToHeaders SetLoadBasedAutoScaling
instance ToJSON SetLoadBasedAutoScaling where
toJSON SetLoadBasedAutoScaling{..} = object
[ "LayerId" .= _slbasLayerId
, "Enable" .= _slbasEnable
, "UpScaling" .= _slbasUpScaling
, "DownScaling" .= _slbasDownScaling
]
instance AWSRequest SetLoadBasedAutoScaling where
type Sv SetLoadBasedAutoScaling = OpsWorks
type Rs SetLoadBasedAutoScaling = SetLoadBasedAutoScalingResponse
request = post "SetLoadBasedAutoScaling"
response = nullResponse SetLoadBasedAutoScalingResponse
|
romanb/amazonka
|
amazonka-opsworks/gen/Network/AWS/OpsWorks/SetLoadBasedAutoScaling.hs
|
mpl-2.0
| 5,533
| 0
| 9
| 1,037
| 576
| 351
| 225
| 66
| 1
|
{-
Copyright 2013 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Plush.Run.Script (
parse,
parseInput,
runCommand,
runScript,
runFile,
)
where
import Control.Applicative ((<$>))
import Control.Monad (when)
import Control.Monad.Exception (catchIOError)
import Plush.Parser
import Plush.Pretty
import {-# SOURCE #-} Plush.Run.Execute -- see Execute.hs-boot
import Plush.Run.Posix
import Plush.Run.Posix.Return
import Plush.Run.Posix.Utilities
import Plush.Run.ShellExec
import Plush.Run.Types
import qualified Plush.Run.ShellFlags as F
-- | Parse a command, in the state of the shell. Extracts the aliases from
-- the shell state to give to the parser. This action should have no side
-- effects, and the transformed shell state from this action can be safely
-- ignored.
parse :: (PosixLike m) => String -> ShellExec m ParseCommandResult
parse s = getAliases >>= return . flip parseCommand s
-- | Like 'parse', but the string is considered "shell input", and so is
-- subject the @verbose (@-v@) and @parseout@ (@-P@) shell flags. Therefore,
-- this operation can have output other potential side effects.
parseInput :: (PosixLike m) => String -> ShellExec m ParseCommandResult
parseInput s = do
flags <- getFlags
when (F.verbose flags) $ errStrLn s
pcr <- parse s
when (F.parseout flags) $ case pcr of
Right (cl, _) -> errStrLn $ pp cl
_ -> return ()
return pcr
-- | Run a single command, parsed out of a string.
runCommand :: (PosixLike m) => String -> ShellExec m (ShellStatus, Maybe String)
runCommand cmds = do
pcr <- parseInput cmds
case pcr of
Left errs -> shellError 125 errs >>= return . (\st -> (st, Nothing))
Right (cl, rest) -> execute cl >>= return . (\st -> (st, Just rest))
-- | Run all the commands, parsed from a string
runScript :: (PosixLike m) => String -> ShellExec m ShellStatus
runScript cmds0 = rc (StStatus ExitSuccess, Just cmds0)
where
rc (StStatus _, Just cmds) | not (null cmds) = runCommand cmds >>= rc
rc (st, _) = return st
-- | Run all commands from a file.
runFile :: (PosixLike m) => FilePath -> ShellExec m ShellStatus
runFile fp = do
mscript <- (Just <$> readAllFile fp) `catchIOError` (\_ -> return Nothing)
case mscript of
Nothing -> shellError 127 $ "file couldn't be read: " ++ fp
Just script -> runScript script
|
mzero/plush
|
src/Plush/Run/Script.hs
|
apache-2.0
| 2,907
| 0
| 14
| 584
| 646
| 344
| 302
| 45
| 2
|
--
-- 6.DateAndTime.hs
-- R_Functional_Programming
--
-- Created by RocKK on 2/13/14.
-- Copyright (c) 2014 RocKK.
-- All rights reserved.
--
-- Redistribution and use in source and binary forms are permitted
-- provided that the above copyright notice and this paragraph are
-- duplicated in all such forms and that any documentation,
-- advertising materials, and other materials related to such
-- distribution and use acknowledge that the software was developed
-- by the RocKK. The name of the
-- RocKK may not be used to endorse or promote products derived
-- from this software without specific prior written permission.
-- THIS SOFTWARE IS PROVIDED ''AS IS'' AND WITHOUT ANY EXPRESS OR
-- IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
import Data.Time
main = do
getCurrentTime >>= print
|
RocKK-MD/R_Functional_Programming
|
Sources/6.DateAndTime.hs
|
bsd-2-clause
| 903
| 0
| 7
| 160
| 37
| 28
| 9
| 3
| 1
|
{- ------------------------------------------------------------------------
(c) The GHC Team, 1992-2012
DeriveConstants is a program that extracts information from the C
declarations in the header files (primarily struct field offsets)
and generates various files, such as a header file that can be #included
into non-C source containing this information.
We want to get information about code generated by the C compiler,
such as the sizes of types, and offsets of struct fields. We need
this because the layout of certain runtime objects is defined in C
headers (e.g. includes/rts/storage/Closures.h), but we need access to
the layout of these structures from a Haskell program (GHC).
One way to do this is to compile and run a C program that includes the
header files and prints out the sizes and offsets. However, when we
are cross-compiling, we can't run a C program compiled for the target
platform.
So, this program works as follows: we generate a C program that when
compiled to an object file, has the information we need encoded as
symbol sizes. This means that we can extract the information without
needing to run the program, by inspecting the object file using 'nm'.
------------------------------------------------------------------------ -}
import Control.Monad (when, unless)
import Data.Bits (shiftL)
import Data.Char (toLower)
import Data.List (stripPrefix)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (catMaybes)
import Numeric (readHex)
import System.Environment (getArgs)
import System.Exit (ExitCode(ExitSuccess), exitFailure)
import System.FilePath ((</>))
import System.IO (stderr, hPutStrLn)
import System.Process (showCommandForUser, readProcess, rawSystem)
main :: IO ()
main = do opts <- parseArgs
let getOption descr opt = case opt opts of
Just x -> return x
Nothing -> die ("No " ++ descr ++ " given")
mode <- getOption "mode" o_mode
fn <- getOption "output filename" o_outputFilename
os <- getOption "target os" o_targetOS
let haskellWanteds = [ what | (wh, what) <- wanteds os
, wh `elem` [Haskell, Both] ]
case mode of
Gen_Haskell_Type -> writeHaskellType fn haskellWanteds
Gen_Haskell_Wrappers -> writeHaskellWrappers fn haskellWanteds
Gen_Haskell_Exports -> writeHaskellExports fn haskellWanteds
Gen_Computed cm ->
do tmpdir <- getOption "tmpdir" o_tmpdir
gccProg <- getOption "gcc program" o_gccProg
nmProg <- getOption "nm program" o_nmProg
let verbose = o_verbose opts
gccFlags = o_gccFlags opts
rs <- getWanted verbose os tmpdir gccProg gccFlags nmProg
(o_objdumpProg opts)
let haskellRs = [ what
| (wh, what) <- rs
, wh `elem` [Haskell, Both] ]
cRs = [ what
| (wh, what) <- rs
, wh `elem` [C, Both] ]
case cm of
ComputeHaskell -> writeHaskellValue fn haskellRs
ComputeHeader -> writeHeader fn cRs
data Options = Options {
o_verbose :: Bool,
o_mode :: Maybe Mode,
o_tmpdir :: Maybe FilePath,
o_outputFilename :: Maybe FilePath,
o_gccProg :: Maybe FilePath,
o_gccFlags :: [String],
o_nmProg :: Maybe FilePath,
o_objdumpProg :: Maybe FilePath,
o_targetOS :: Maybe String
}
parseArgs :: IO Options
parseArgs = do args <- getArgs
opts <- f emptyOptions args
return (opts {o_gccFlags = reverse (o_gccFlags opts)})
where emptyOptions = Options {
o_verbose = False,
o_mode = Nothing,
o_tmpdir = Nothing,
o_outputFilename = Nothing,
o_gccProg = Nothing,
o_gccFlags = [],
o_nmProg = Nothing,
o_objdumpProg = Nothing,
o_targetOS = Nothing
}
f opts [] = return opts
f opts ("-v" : args')
= f (opts {o_verbose = True}) args'
f opts ("--gen-haskell-type" : args')
= f (opts {o_mode = Just Gen_Haskell_Type}) args'
f opts ("--gen-haskell-value" : args')
= f (opts {o_mode = Just (Gen_Computed ComputeHaskell)}) args'
f opts ("--gen-haskell-wrappers" : args')
= f (opts {o_mode = Just Gen_Haskell_Wrappers}) args'
f opts ("--gen-haskell-exports" : args')
= f (opts {o_mode = Just Gen_Haskell_Exports}) args'
f opts ("--gen-header" : args')
= f (opts {o_mode = Just (Gen_Computed ComputeHeader)}) args'
f opts ("--tmpdir" : dir : args')
= f (opts {o_tmpdir = Just dir}) args'
f opts ("-o" : fn : args')
= f (opts {o_outputFilename = Just fn}) args'
f opts ("--gcc-program" : prog : args')
= f (opts {o_gccProg = Just prog}) args'
f opts ("--gcc-flag" : flag : args')
= f (opts {o_gccFlags = flag : o_gccFlags opts}) args'
f opts ("--nm-program" : prog : args')
= f (opts {o_nmProg = Just prog}) args'
f opts ("--objdump-program" : prog : args')
= f (opts {o_objdumpProg = Just prog}) args'
f opts ("--target-os" : os : args')
= f (opts {o_targetOS = Just os}) args'
f _ (flag : _) = die ("Unrecognised flag: " ++ show flag)
data Mode = Gen_Haskell_Type
| Gen_Haskell_Wrappers
| Gen_Haskell_Exports
| Gen_Computed ComputeMode
data ComputeMode = ComputeHaskell | ComputeHeader
type Wanteds = [(Where, What Fst)]
type Results = [(Where, What Snd)]
type Name = String
newtype CExpr = CExpr String
newtype CPPExpr = CPPExpr String
data What f = GetFieldType Name (f CExpr Integer)
| GetClosureSize Name (f CExpr Integer)
| GetWord Name (f CExpr Integer)
| GetInt Name (f CExpr Integer)
| GetNatural Name (f CExpr Integer)
| GetBool Name (f CPPExpr Bool)
| StructFieldMacro Name
| ClosureFieldMacro Name
| ClosurePayloadMacro Name
| FieldTypeGcptrMacro Name
data Fst a b = Fst a
data Snd a b = Snd b
data Where = C | Haskell | Both
deriving Eq
constantInt :: Where -> Name -> String -> Wanteds
constantInt w name expr = [(w, GetInt name (Fst (CExpr expr)))]
constantWord :: Where -> Name -> String -> Wanteds
constantWord w name expr = [(w, GetWord name (Fst (CExpr expr)))]
constantNatural :: Where -> Name -> String -> Wanteds
constantNatural w name expr = [(w, GetNatural name (Fst (CExpr expr)))]
constantBool :: Where -> Name -> String -> Wanteds
constantBool w name expr = [(w, GetBool name (Fst (CPPExpr expr)))]
fieldOffset :: Where -> String -> String -> Wanteds
fieldOffset w theType theField = fieldOffset_ w nameBase theType theField
where nameBase = theType ++ "_" ++ theField
fieldOffset_ :: Where -> Name -> String -> String -> Wanteds
fieldOffset_ w nameBase theType theField = [(w, GetWord name (Fst (CExpr expr)))]
where name = "OFFSET_" ++ nameBase
expr = "offsetof(" ++ theType ++ ", " ++ theField ++ ")"
-- FieldType is for defining REP_x to be b32 etc
-- These are both the C-- types used in a load
-- e.g. b32[addr]
-- and the names of the CmmTypes in the compiler
-- b32 :: CmmType
fieldType' :: Where -> String -> String -> Wanteds
fieldType' w theType theField
= fieldType_' w nameBase theType theField
where nameBase = theType ++ "_" ++ theField
fieldType_' :: Where -> Name -> String -> String -> Wanteds
fieldType_' w nameBase theType theField
= [(w, GetFieldType name (Fst (CExpr expr)))]
where name = "REP_" ++ nameBase
expr = "FIELD_SIZE(" ++ theType ++ ", " ++ theField ++ ")"
structField :: Where -> String -> String -> Wanteds
structField = structFieldHelper C
structFieldH :: Where -> String -> String -> Wanteds
structFieldH w = structFieldHelper w w
structField_ :: Where -> Name -> String -> String -> Wanteds
structField_ w nameBase theType theField
= fieldOffset_ w nameBase theType theField
++ fieldType_' C nameBase theType theField
++ structFieldMacro nameBase
structFieldMacro :: Name -> Wanteds
structFieldMacro nameBase = [(C, StructFieldMacro nameBase)]
-- Outputs the byte offset and MachRep for a field
structFieldHelper :: Where -> Where -> String -> String -> Wanteds
structFieldHelper wFT w theType theField = fieldOffset w theType theField
++ fieldType' wFT theType theField
++ structFieldMacro nameBase
where nameBase = theType ++ "_" ++ theField
closureFieldMacro :: Name -> Wanteds
closureFieldMacro nameBase = [(C, ClosureFieldMacro nameBase)]
closurePayload :: Where -> String -> String -> Wanteds
closurePayload w theType theField
= closureFieldOffset_ w nameBase theType theField
++ closurePayloadMacro nameBase
where nameBase = theType ++ "_" ++ theField
closurePayloadMacro :: Name -> Wanteds
closurePayloadMacro nameBase = [(C, ClosurePayloadMacro nameBase)]
-- Byte offset and MachRep for a closure field, minus the header
closureField_ :: Where -> Name -> String -> String -> Wanteds
closureField_ w nameBase theType theField
= closureFieldOffset_ w nameBase theType theField
++ fieldType_' C nameBase theType theField
++ closureFieldMacro nameBase
closureField :: Where -> String -> String -> Wanteds
closureField w theType theField = closureField_ w nameBase theType theField
where nameBase = theType ++ "_" ++ theField
closureFieldOffset_ :: Where -> Name -> String -> String -> Wanteds
closureFieldOffset_ w nameBase theType theField
= defOffset w nameBase (CExpr ("offsetof(" ++ theType ++ ", " ++ theField ++ ") - TYPE_SIZE(StgHeader)"))
-- Size of a closure type, minus the header, named SIZEOF_<type>_NoHdr
-- Also, we #define SIZEOF_<type> to be the size of the whole closure for .cmm.
closureSize :: Where -> String -> Wanteds
closureSize w theType = defSize w (theType ++ "_NoHdr") (CExpr expr)
++ defClosureSize C theType (CExpr expr)
where expr = "TYPE_SIZE(" ++ theType ++ ") - TYPE_SIZE(StgHeader)"
-- Byte offset and MachRep for a closure field, minus the header
closureFieldGcptr :: Where -> String -> String -> Wanteds
closureFieldGcptr w theType theField
= closureFieldOffset_ w nameBase theType theField
++ fieldTypeGcptr nameBase
++ closureFieldMacro nameBase
where nameBase = theType ++ "_" ++ theField
fieldTypeGcptr :: Name -> Wanteds
fieldTypeGcptr nameBase = [(C, FieldTypeGcptrMacro nameBase)]
closureFieldOffset :: Where -> String -> String -> Wanteds
closureFieldOffset w theType theField
= defOffset w nameBase (CExpr expr)
where nameBase = theType ++ "_" ++ theField
expr = "offsetof(" ++ theType ++ ", " ++ theField ++ ") - TYPE_SIZE(StgHeader)"
thunkSize :: Where -> String -> Wanteds
thunkSize w theType
= defSize w (theType ++ "_NoThunkHdr") (CExpr expr)
++ closureSize w theType
where expr = "TYPE_SIZE(" ++ theType ++ ") - TYPE_SIZE(StgThunkHeader)"
defIntOffset :: Where -> Name -> String -> Wanteds
defIntOffset w nameBase cExpr = [(w, GetInt ("OFFSET_" ++ nameBase) (Fst (CExpr cExpr)))]
defOffset :: Where -> Name -> CExpr -> Wanteds
defOffset w nameBase cExpr = [(w, GetWord ("OFFSET_" ++ nameBase) (Fst cExpr))]
structSize :: Where -> String -> Wanteds
structSize w theType = defSize w theType (CExpr ("TYPE_SIZE(" ++ theType ++ ")"))
defSize :: Where -> Name -> CExpr -> Wanteds
defSize w nameBase cExpr = [(w, GetWord ("SIZEOF_" ++ nameBase) (Fst cExpr))]
defClosureSize :: Where -> Name -> CExpr -> Wanteds
defClosureSize w nameBase cExpr = [(w, GetClosureSize ("SIZEOF_" ++ nameBase) (Fst cExpr))]
haskellise :: Name -> Name
haskellise (c : cs) = toLower c : cs
haskellise "" = ""
wanteds :: String -> Wanteds
wanteds os = concat
[-- Control group constant for integrity check; this
-- round-tripped constant is used for testing that
-- derivedConstant works as expected
constantWord Both "CONTROL_GROUP_CONST_291" "0x123"
-- Closure header sizes.
,constantWord Both "STD_HDR_SIZE"
-- grrr.. PROFILING is on so we need to
-- subtract sizeofW(StgProfHeader)
"sizeofW(StgHeader) - sizeofW(StgProfHeader)"
,constantWord Both "PROF_HDR_SIZE" "sizeofW(StgProfHeader)"
-- Size of a storage manager block (in bytes).
,constantWord Both "BLOCK_SIZE" "BLOCK_SIZE"
,constantWord C "MBLOCK_SIZE" "MBLOCK_SIZE"
-- blocks that fit in an MBlock, leaving space for the block
-- descriptors
,constantWord Both "BLOCKS_PER_MBLOCK" "BLOCKS_PER_MBLOCK"
-- could be derived, but better to save doing the calculation twice
,constantWord Both "TICKY_BIN_COUNT" "TICKY_BIN_COUNT"
-- number of bins for histograms used in ticky code
,fieldOffset Both "StgRegTable" "rR1"
,fieldOffset Both "StgRegTable" "rR2"
,fieldOffset Both "StgRegTable" "rR3"
,fieldOffset Both "StgRegTable" "rR4"
,fieldOffset Both "StgRegTable" "rR5"
,fieldOffset Both "StgRegTable" "rR6"
,fieldOffset Both "StgRegTable" "rR7"
,fieldOffset Both "StgRegTable" "rR8"
,fieldOffset Both "StgRegTable" "rR9"
,fieldOffset Both "StgRegTable" "rR10"
,fieldOffset Both "StgRegTable" "rF1"
,fieldOffset Both "StgRegTable" "rF2"
,fieldOffset Both "StgRegTable" "rF3"
,fieldOffset Both "StgRegTable" "rF4"
,fieldOffset Both "StgRegTable" "rF5"
,fieldOffset Both "StgRegTable" "rF6"
,fieldOffset Both "StgRegTable" "rD1"
,fieldOffset Both "StgRegTable" "rD2"
,fieldOffset Both "StgRegTable" "rD3"
,fieldOffset Both "StgRegTable" "rD4"
,fieldOffset Both "StgRegTable" "rD5"
,fieldOffset Both "StgRegTable" "rD6"
,fieldOffset Both "StgRegTable" "rXMM1"
,fieldOffset Both "StgRegTable" "rXMM2"
,fieldOffset Both "StgRegTable" "rXMM3"
,fieldOffset Both "StgRegTable" "rXMM4"
,fieldOffset Both "StgRegTable" "rXMM5"
,fieldOffset Both "StgRegTable" "rXMM6"
,fieldOffset Both "StgRegTable" "rYMM1"
,fieldOffset Both "StgRegTable" "rYMM2"
,fieldOffset Both "StgRegTable" "rYMM3"
,fieldOffset Both "StgRegTable" "rYMM4"
,fieldOffset Both "StgRegTable" "rYMM5"
,fieldOffset Both "StgRegTable" "rYMM6"
,fieldOffset Both "StgRegTable" "rZMM1"
,fieldOffset Both "StgRegTable" "rZMM2"
,fieldOffset Both "StgRegTable" "rZMM3"
,fieldOffset Both "StgRegTable" "rZMM4"
,fieldOffset Both "StgRegTable" "rZMM5"
,fieldOffset Both "StgRegTable" "rZMM6"
,fieldOffset Both "StgRegTable" "rL1"
,fieldOffset Both "StgRegTable" "rSp"
,fieldOffset Both "StgRegTable" "rSpLim"
,fieldOffset Both "StgRegTable" "rHp"
,fieldOffset Both "StgRegTable" "rHpLim"
,fieldOffset Both "StgRegTable" "rCCCS"
,fieldOffset Both "StgRegTable" "rCurrentTSO"
,fieldOffset Both "StgRegTable" "rCurrentNursery"
,fieldOffset Both "StgRegTable" "rHpAlloc"
,structField C "StgRegTable" "rRet"
,structField C "StgRegTable" "rNursery"
,defIntOffset Both "stgEagerBlackholeInfo"
"FUN_OFFSET(stgEagerBlackholeInfo)"
,defIntOffset Both "stgGCEnter1" "FUN_OFFSET(stgGCEnter1)"
,defIntOffset Both "stgGCFun" "FUN_OFFSET(stgGCFun)"
,fieldOffset Both "Capability" "r"
,fieldOffset C "Capability" "lock"
,structField C "Capability" "no"
,structField C "Capability" "mut_lists"
,structField C "Capability" "context_switch"
,structField C "Capability" "interrupt"
,structField C "Capability" "sparks"
,structField C "Capability" "total_allocated"
,structField C "Capability" "weak_ptr_list_hd"
,structField C "Capability" "weak_ptr_list_tl"
,structField Both "bdescr" "start"
,structField Both "bdescr" "free"
,structField Both "bdescr" "blocks"
,structField C "bdescr" "gen_no"
,structField C "bdescr" "link"
,structField Both "bdescr" "flags"
,structSize C "generation"
,structField C "generation" "n_new_large_words"
,structField C "generation" "weak_ptr_list"
,structSize Both "CostCentreStack"
,structField C "CostCentreStack" "ccsID"
,structFieldH Both "CostCentreStack" "mem_alloc"
,structFieldH Both "CostCentreStack" "scc_count"
,structField C "CostCentreStack" "prevStack"
,structField C "CostCentre" "ccID"
,structField C "CostCentre" "link"
,structField C "StgHeader" "info"
,structField_ Both "StgHeader_ccs" "StgHeader" "prof.ccs"
,structField_ Both "StgHeader_ldvw" "StgHeader" "prof.hp.ldvw"
,structSize Both "StgSMPThunkHeader"
,closurePayload C "StgClosure" "payload"
,structFieldH Both "StgEntCounter" "allocs"
,structFieldH Both "StgEntCounter" "allocd"
,structField Both "StgEntCounter" "registeredp"
,structField Both "StgEntCounter" "link"
,structField Both "StgEntCounter" "entry_count"
,closureSize Both "StgUpdateFrame"
,closureSize C "StgCatchFrame"
,closureSize C "StgStopFrame"
,closureSize Both "StgMutArrPtrs"
,closureField Both "StgMutArrPtrs" "ptrs"
,closureField Both "StgMutArrPtrs" "size"
,closureSize Both "StgSmallMutArrPtrs"
,closureField Both "StgSmallMutArrPtrs" "ptrs"
,closureSize Both "StgArrBytes"
,closureField Both "StgArrBytes" "bytes"
,closurePayload C "StgArrBytes" "payload"
,closureField C "StgTSO" "_link"
,closureField C "StgTSO" "global_link"
,closureField C "StgTSO" "what_next"
,closureField C "StgTSO" "why_blocked"
,closureField C "StgTSO" "block_info"
,closureField C "StgTSO" "blocked_exceptions"
,closureField C "StgTSO" "id"
,closureField C "StgTSO" "cap"
,closureField C "StgTSO" "saved_errno"
,closureField C "StgTSO" "trec"
,closureField C "StgTSO" "flags"
,closureField C "StgTSO" "dirty"
,closureField C "StgTSO" "bq"
,closureField Both "StgTSO" "alloc_limit"
,closureField_ Both "StgTSO_cccs" "StgTSO" "prof.cccs"
,closureField Both "StgTSO" "stackobj"
,closureField Both "StgStack" "sp"
,closureFieldOffset Both "StgStack" "stack"
,closureField C "StgStack" "stack_size"
,closureField C "StgStack" "dirty"
,structSize C "StgTSOProfInfo"
,closureField Both "StgUpdateFrame" "updatee"
,closureField C "StgCatchFrame" "handler"
,closureField C "StgCatchFrame" "exceptions_blocked"
,closureSize C "StgPAP"
,closureField C "StgPAP" "n_args"
,closureFieldGcptr C "StgPAP" "fun"
,closureField C "StgPAP" "arity"
,closurePayload C "StgPAP" "payload"
,thunkSize C "StgAP"
,closureField C "StgAP" "n_args"
,closureFieldGcptr C "StgAP" "fun"
,closurePayload C "StgAP" "payload"
,thunkSize C "StgAP_STACK"
,closureField C "StgAP_STACK" "size"
,closureFieldGcptr C "StgAP_STACK" "fun"
,closurePayload C "StgAP_STACK" "payload"
,thunkSize C "StgSelector"
,closureFieldGcptr C "StgInd" "indirectee"
,closureSize C "StgMutVar"
,closureField C "StgMutVar" "var"
,closureSize C "StgAtomicallyFrame"
,closureField C "StgAtomicallyFrame" "code"
,closureField C "StgAtomicallyFrame" "next_invariant_to_check"
,closureField C "StgAtomicallyFrame" "result"
,closureField C "StgInvariantCheckQueue" "invariant"
,closureField C "StgInvariantCheckQueue" "my_execution"
,closureField C "StgInvariantCheckQueue" "next_queue_entry"
,closureField C "StgAtomicInvariant" "code"
,closureField C "StgTRecHeader" "enclosing_trec"
,closureSize C "StgCatchSTMFrame"
,closureField C "StgCatchSTMFrame" "handler"
,closureField C "StgCatchSTMFrame" "code"
,closureSize C "StgCatchRetryFrame"
,closureField C "StgCatchRetryFrame" "running_alt_code"
,closureField C "StgCatchRetryFrame" "first_code"
,closureField C "StgCatchRetryFrame" "alt_code"
,closureField C "StgTVarWatchQueue" "closure"
,closureField C "StgTVarWatchQueue" "next_queue_entry"
,closureField C "StgTVarWatchQueue" "prev_queue_entry"
,closureSize C "StgTVar"
,closureField C "StgTVar" "current_value"
,closureField C "StgTVar" "first_watch_queue_entry"
,closureField C "StgTVar" "num_updates"
,closureSize C "StgWeak"
,closureField C "StgWeak" "link"
,closureField C "StgWeak" "key"
,closureField C "StgWeak" "value"
,closureField C "StgWeak" "finalizer"
,closureField C "StgWeak" "cfinalizers"
,closureSize C "StgCFinalizerList"
,closureField C "StgCFinalizerList" "link"
,closureField C "StgCFinalizerList" "fptr"
,closureField C "StgCFinalizerList" "ptr"
,closureField C "StgCFinalizerList" "eptr"
,closureField C "StgCFinalizerList" "flag"
,closureSize C "StgMVar"
,closureField C "StgMVar" "head"
,closureField C "StgMVar" "tail"
,closureField C "StgMVar" "value"
,closureSize C "StgMVarTSOQueue"
,closureField C "StgMVarTSOQueue" "link"
,closureField C "StgMVarTSOQueue" "tso"
,closureSize C "StgBCO"
,closureField C "StgBCO" "instrs"
,closureField C "StgBCO" "literals"
,closureField C "StgBCO" "ptrs"
,closureField C "StgBCO" "arity"
,closureField C "StgBCO" "size"
,closurePayload C "StgBCO" "bitmap"
,closureSize C "StgStableName"
,closureField C "StgStableName" "sn"
,closureSize C "StgBlockingQueue"
,closureField C "StgBlockingQueue" "bh"
,closureField C "StgBlockingQueue" "owner"
,closureField C "StgBlockingQueue" "queue"
,closureField C "StgBlockingQueue" "link"
,closureSize C "MessageBlackHole"
,closureField C "MessageBlackHole" "link"
,closureField C "MessageBlackHole" "tso"
,closureField C "MessageBlackHole" "bh"
,closureSize C "StgCompactNFData"
,closureField C "StgCompactNFData" "totalW"
,closureField C "StgCompactNFData" "autoBlockW"
,closureField C "StgCompactNFData" "nursery"
,closureField C "StgCompactNFData" "last"
,closureField C "StgCompactNFData" "hp"
,closureField C "StgCompactNFData" "hpLim"
,closureField C "StgCompactNFData" "hash"
,closureField C "StgCompactNFData" "result"
,structSize C "StgCompactNFDataBlock"
,structField C "StgCompactNFDataBlock" "self"
,structField C "StgCompactNFDataBlock" "owner"
,structField C "StgCompactNFDataBlock" "next"
,structField_ C "RtsFlags_ProfFlags_showCCSOnException"
"RTS_FLAGS" "ProfFlags.showCCSOnException"
,structField_ C "RtsFlags_DebugFlags_apply"
"RTS_FLAGS" "DebugFlags.apply"
,structField_ C "RtsFlags_DebugFlags_sanity"
"RTS_FLAGS" "DebugFlags.sanity"
,structField_ C "RtsFlags_DebugFlags_weak"
"RTS_FLAGS" "DebugFlags.weak"
,structField_ C "RtsFlags_GcFlags_initialStkSize"
"RTS_FLAGS" "GcFlags.initialStkSize"
,structField_ C "RtsFlags_MiscFlags_tickInterval"
"RTS_FLAGS" "MiscFlags.tickInterval"
,structSize C "StgFunInfoExtraFwd"
,structField C "StgFunInfoExtraFwd" "slow_apply"
,structField C "StgFunInfoExtraFwd" "fun_type"
,structFieldH Both "StgFunInfoExtraFwd" "arity"
,structField_ C "StgFunInfoExtraFwd_bitmap" "StgFunInfoExtraFwd" "b.bitmap"
,structSize Both "StgFunInfoExtraRev"
,structField C "StgFunInfoExtraRev" "slow_apply_offset"
,structField C "StgFunInfoExtraRev" "fun_type"
,structFieldH Both "StgFunInfoExtraRev" "arity"
,structField_ C "StgFunInfoExtraRev_bitmap" "StgFunInfoExtraRev" "b.bitmap"
,structField_ C "StgFunInfoExtraRev_bitmap_offset" "StgFunInfoExtraRev" "b.bitmap_offset"
,structField C "StgLargeBitmap" "size"
,fieldOffset C "StgLargeBitmap" "bitmap"
,structSize C "snEntry"
,structField C "snEntry" "sn_obj"
,structField C "snEntry" "addr"
,structSize C "spEntry"
,structField C "spEntry" "addr"
-- Note that this conditional part only affects the C headers.
-- That's important, as it means we get the same PlatformConstants
-- type on all platforms.
,if os == "mingw32"
then concat [structSize C "StgAsyncIOResult"
,structField C "StgAsyncIOResult" "reqID"
,structField C "StgAsyncIOResult" "len"
,structField C "StgAsyncIOResult" "errCode"]
else []
-- pre-compiled thunk types
,constantWord Haskell "MAX_SPEC_SELECTEE_SIZE" "MAX_SPEC_SELECTEE_SIZE"
,constantWord Haskell "MAX_SPEC_AP_SIZE" "MAX_SPEC_AP_SIZE"
-- closure sizes: these do NOT include the header (see below for
-- header sizes)
,constantWord Haskell "MIN_PAYLOAD_SIZE" "MIN_PAYLOAD_SIZE"
,constantInt Haskell "MIN_INTLIKE" "MIN_INTLIKE"
,constantWord Haskell "MAX_INTLIKE" "MAX_INTLIKE"
,constantWord Haskell "MIN_CHARLIKE" "MIN_CHARLIKE"
,constantWord Haskell "MAX_CHARLIKE" "MAX_CHARLIKE"
,constantWord Haskell "MUT_ARR_PTRS_CARD_BITS" "MUT_ARR_PTRS_CARD_BITS"
-- A section of code-generator-related MAGIC CONSTANTS.
,constantWord Haskell "MAX_Vanilla_REG" "MAX_VANILLA_REG"
,constantWord Haskell "MAX_Float_REG" "MAX_FLOAT_REG"
,constantWord Haskell "MAX_Double_REG" "MAX_DOUBLE_REG"
,constantWord Haskell "MAX_Long_REG" "MAX_LONG_REG"
,constantWord Haskell "MAX_XMM_REG" "MAX_XMM_REG"
,constantWord Haskell "MAX_Real_Vanilla_REG" "MAX_REAL_VANILLA_REG"
,constantWord Haskell "MAX_Real_Float_REG" "MAX_REAL_FLOAT_REG"
,constantWord Haskell "MAX_Real_Double_REG" "MAX_REAL_DOUBLE_REG"
,constantWord Haskell "MAX_Real_XMM_REG" "MAX_REAL_XMM_REG"
,constantWord Haskell "MAX_Real_Long_REG" "MAX_REAL_LONG_REG"
-- This tells the native code generator the size of the spill
-- area is has available.
,constantWord Haskell "RESERVED_C_STACK_BYTES" "RESERVED_C_STACK_BYTES"
-- The amount of (Haskell) stack to leave free for saving
-- registers when returning to the scheduler.
,constantWord Haskell "RESERVED_STACK_WORDS" "RESERVED_STACK_WORDS"
-- Continuations that need more than this amount of stack
-- should do their own stack check (see bug #1466).
,constantWord Haskell "AP_STACK_SPLIM" "AP_STACK_SPLIM"
-- Size of a word, in bytes
,constantWord Haskell "WORD_SIZE" "SIZEOF_HSWORD"
-- Size of a double in StgWords.
,constantWord Haskell "DOUBLE_SIZE" "SIZEOF_DOUBLE"
-- Size of a C int, in bytes. May be smaller than wORD_SIZE.
,constantWord Haskell "CINT_SIZE" "SIZEOF_INT"
,constantWord Haskell "CLONG_SIZE" "SIZEOF_LONG"
,constantWord Haskell "CLONG_LONG_SIZE" "SIZEOF_LONG_LONG"
-- Number of bits to shift a bitfield left by in an info table.
,constantWord Haskell "BITMAP_BITS_SHIFT" "BITMAP_BITS_SHIFT"
-- Amount of pointer bits used for semi-tagging constructor closures
,constantWord Haskell "TAG_BITS" "TAG_BITS"
,constantBool Haskell "WORDS_BIGENDIAN" "defined(WORDS_BIGENDIAN)"
,constantBool Haskell "DYNAMIC_BY_DEFAULT" "defined(DYNAMIC_BY_DEFAULT)"
,constantWord Haskell "LDV_SHIFT" "LDV_SHIFT"
,constantNatural Haskell "ILDV_CREATE_MASK" "LDV_CREATE_MASK"
,constantNatural Haskell "ILDV_STATE_CREATE" "LDV_STATE_CREATE"
,constantNatural Haskell "ILDV_STATE_USE" "LDV_STATE_USE"
]
getWanted :: Bool -> String -> FilePath -> FilePath -> [String] -> FilePath -> Maybe FilePath
-> IO Results
getWanted verbose os tmpdir gccProgram gccFlags nmProgram mobjdumpProgram
= do let cStuff = unlines (headers ++ concatMap (doWanted . snd) (wanteds os))
cFile = tmpdir </> "tmp.c"
oFile = tmpdir </> "tmp.o"
writeFile cFile cStuff
execute verbose gccProgram (gccFlags ++ ["-c", cFile, "-o", oFile])
xs <- case os of
"openbsd" -> readProcess objdumpProgam ["--syms", oFile] ""
"aix" -> readProcess objdumpProgam ["--syms", oFile] ""
_ -> readProcess nmProgram ["-P", oFile] ""
let ls = lines xs
m = Map.fromList $ case os of
"aix" -> parseAixObjdump ls
_ -> catMaybes $ map parseNmLine ls
case Map.lookup "CONTROL_GROUP_CONST_291" m of
Just 292 -> return () -- OK
Nothing -> die "CONTROL_GROUP_CONST_291 missing!"
Just 0x292 -> die $ "broken 'nm' detected, see https://ghc.haskell.org/ticket/11744.\n"
++ "\n"
++ "Workaround: You may want to pass\n"
++ " --with-nm=$(xcrun --find nm-classic)\n"
++ "to 'configure'.\n"
Just x -> die ("unexpected value round-tripped for CONTROL_GROUP_CONST_291: " ++ show x)
rs <- mapM (lookupResult m) (wanteds os)
return rs
where headers = ["#define IN_STG_CODE 0",
"",
"/*",
" * We need offsets of profiled things...",
" * better be careful that this doesn't",
" * affect the offsets of anything else.",
" */",
"",
"#define PROFILING",
"#define THREADED_RTS",
"",
"#include \"PosixSource.h\"",
"#include \"Rts.h\"",
"#include \"Stable.h\"",
"#include \"Capability.h\"",
"",
"#include <inttypes.h>",
"#include <stddef.h>",
"#include <stdio.h>",
"#include <string.h>",
"",
"#define FIELD_SIZE(s_type, field) ((size_t)sizeof(((s_type*)0)->field))",
"#define TYPE_SIZE(type) (sizeof(type))",
"#define FUN_OFFSET(sym) (offsetof(Capability,f.sym) - offsetof(Capability,r))",
"",
"#pragma GCC poison sizeof"
]
objdumpProgam = maybe (error "no objdump program given") id mobjdumpProgram
prefix = "derivedConstant"
mkFullName name = prefix ++ name
-- We add 1 to the value, as some platforms will make a symbol
-- of size 1 when for
-- char foo[0];
-- We then subtract 1 again when parsing.
doWanted (GetFieldType name (Fst (CExpr cExpr)))
= ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"]
doWanted (GetClosureSize name (Fst (CExpr cExpr)))
= ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"]
doWanted (GetWord name (Fst (CExpr cExpr)))
= ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"]
doWanted (GetInt name (Fst (CExpr cExpr)))
= ["char " ++ mkFullName name ++ "Mag[1 + ((intptr_t)(" ++ cExpr ++ ") >= 0 ? (" ++ cExpr ++ ") : -(" ++ cExpr ++ "))];",
"char " ++ mkFullName name ++ "Sig[(intptr_t)(" ++ cExpr ++ ") >= 0 ? 3 : 1];"]
doWanted (GetNatural name (Fst (CExpr cExpr)))
= -- These casts fix "right shift count >= width of type"
-- warnings
let cExpr' = "(uint64_t)(size_t)(" ++ cExpr ++ ")"
in ["char " ++ mkFullName name ++ "0[1 + ((" ++ cExpr' ++ ") & 0xFFFF)];",
"char " ++ mkFullName name ++ "1[1 + (((" ++ cExpr' ++ ") >> 16) & 0xFFFF)];",
"char " ++ mkFullName name ++ "2[1 + (((" ++ cExpr' ++ ") >> 32) & 0xFFFF)];",
"char " ++ mkFullName name ++ "3[1 + (((" ++ cExpr' ++ ") >> 48) & 0xFFFF)];"]
doWanted (GetBool name (Fst (CPPExpr cppExpr)))
= ["#if " ++ cppExpr,
"char " ++ mkFullName name ++ "[1];",
"#else",
"char " ++ mkFullName name ++ "[2];",
"#endif"]
doWanted (StructFieldMacro {}) = []
doWanted (ClosureFieldMacro {}) = []
doWanted (ClosurePayloadMacro {}) = []
doWanted (FieldTypeGcptrMacro {}) = []
-- parseNmLine parses "nm -P" output that looks like
-- "derivedConstantMAX_Vanilla_REG C 0000000b 0000000b" (GNU nm)
-- "_derivedConstantMAX_Vanilla_REG C b 0" (Mac OS X)
-- "_derivedConstantMAX_Vanilla_REG C 000000b" (MinGW)
-- "derivedConstantMAX_Vanilla_REG D 1 b" (Solaris)
-- and returns ("MAX_Vanilla_REG", 11)
parseNmLine line
= case words line of
('_' : n) : "C" : s : _ -> mkP n s
n : "C" : s : _ -> mkP n s
[n, "D", _, s] -> mkP n s
[s, "O", "*COM*", _, n] -> mkP n s
_ -> Nothing
where mkP r s = case (stripPrefix prefix r, readHex s) of
(Just name, [(size, "")]) -> Just (name, size)
_ -> Nothing
-- On AIX, `nm` isn't able to tell us the symbol size, so we
-- need to use `objdump --syms`. However, unlike on OpenBSD,
-- `objdump --syms` outputs entries spanning two lines, e.g.
--
-- [ 50](sec 3)(fl 0x00)(ty 0)(scl 2) (nx 1) 0x00000318 derivedConstantBLOCK_SIZE
-- AUX val 4097 prmhsh 0 snhsh 0 typ 3 algn 3 clss 5 stb 0 snstb 0
--
parseAixObjdump :: [String] -> [(String,Integer)]
parseAixObjdump = catMaybes . goAix
where
goAix (l1@('[':_):l2@('A':'U':'X':_):ls')
= parseObjDumpEntry l1 l2 : goAix ls'
goAix (_:ls') = goAix ls'
goAix [] = []
parseObjDumpEntry l1 l2
| ["val",n] <- take 2 (tail $ words l2)
, Just sym <- stripPrefix prefix sym0 = Just (sym, read n)
| otherwise = Nothing
where
[sym0, _] = take 2 (reverse $ words l1)
-- If an Int value is larger than 2^28 or smaller
-- than -2^28, then fail.
-- This test is a bit conservative, but if any
-- constants are roughly maxBound or minBound then
-- we probably need them to be Integer rather than
-- Int so that -- cross-compiling between 32bit and
-- 64bit platforms works.
lookupSmall :: Map String Integer -> Name -> IO Integer
lookupSmall m name
= case Map.lookup name m of
Just v
| v > 2^(28 :: Int) ||
v < -(2^(28 :: Int)) ->
die ("Value too large for GetWord: " ++ show v)
| otherwise -> return v
Nothing -> die ("Can't find " ++ show name)
lookupResult :: Map String Integer -> (Where, What Fst)
-> IO (Where, What Snd)
lookupResult m (w, GetWord name _)
= do v <- lookupSmall m name
return (w, GetWord name (Snd (v - 1)))
lookupResult m (w, GetInt name _)
= do mag <- lookupSmall m (name ++ "Mag")
sig <- lookupSmall m (name ++ "Sig")
return (w, GetWord name (Snd ((mag - 1) * (sig - 2))))
lookupResult m (w, GetNatural name _)
= do v0 <- lookupSmall m (name ++ "0")
v1 <- lookupSmall m (name ++ "1")
v2 <- lookupSmall m (name ++ "2")
v3 <- lookupSmall m (name ++ "3")
let v = (v0 - 1)
+ shiftL (v1 - 1) 16
+ shiftL (v2 - 1) 32
+ shiftL (v3 - 1) 48
return (w, GetWord name (Snd v))
lookupResult m (w, GetBool name _)
= do v <- lookupSmall m name
case v of
1 -> return (w, GetBool name (Snd True))
2 -> return (w, GetBool name (Snd False))
_ -> die ("Bad boolean: " ++ show v)
lookupResult m (w, GetFieldType name _)
= do v <- lookupSmall m name
return (w, GetFieldType name (Snd (v - 1)))
lookupResult m (w, GetClosureSize name _)
= do v <- lookupSmall m name
return (w, GetClosureSize name (Snd (v - 1)))
lookupResult _ (w, StructFieldMacro name)
= return (w, StructFieldMacro name)
lookupResult _ (w, ClosureFieldMacro name)
= return (w, ClosureFieldMacro name)
lookupResult _ (w, ClosurePayloadMacro name)
= return (w, ClosurePayloadMacro name)
lookupResult _ (w, FieldTypeGcptrMacro name)
= return (w, FieldTypeGcptrMacro name)
writeHaskellType :: FilePath -> [What Fst] -> IO ()
writeHaskellType fn ws = writeFile fn xs
where xs = unlines (headers ++ body ++ footers)
headers = ["data PlatformConstants = PlatformConstants {"
-- Now a kludge that allows the real entries to
-- all start with a comma, which makes life a
-- little easier
," pc_platformConstants :: ()"]
footers = [" } deriving Read"]
body = concatMap doWhat ws
doWhat (GetClosureSize name _) = [" , pc_" ++ name ++ " :: Int"]
doWhat (GetFieldType name _) = [" , pc_" ++ name ++ " :: Int"]
doWhat (GetWord name _) = [" , pc_" ++ name ++ " :: Int"]
doWhat (GetInt name _) = [" , pc_" ++ name ++ " :: Int"]
doWhat (GetNatural name _) = [" , pc_" ++ name ++ " :: Integer"]
doWhat (GetBool name _) = [" , pc_" ++ name ++ " :: Bool"]
doWhat (StructFieldMacro {}) = []
doWhat (ClosureFieldMacro {}) = []
doWhat (ClosurePayloadMacro {}) = []
doWhat (FieldTypeGcptrMacro {}) = []
writeHaskellValue :: FilePath -> [What Snd] -> IO ()
writeHaskellValue fn rs = writeFile fn xs
where xs = unlines (headers ++ body ++ footers)
headers = ["PlatformConstants {"
," pc_platformConstants = ()"]
footers = [" }"]
body = concatMap doWhat rs
doWhat (GetClosureSize name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetFieldType name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetWord name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetInt name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetNatural name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetBool name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (StructFieldMacro {}) = []
doWhat (ClosureFieldMacro {}) = []
doWhat (ClosurePayloadMacro {}) = []
doWhat (FieldTypeGcptrMacro {}) = []
writeHaskellWrappers :: FilePath -> [What Fst] -> IO ()
writeHaskellWrappers fn ws = writeFile fn xs
where xs = unlines body
body = concatMap doWhat ws
doWhat (GetFieldType {}) = []
doWhat (GetClosureSize {}) = []
doWhat (GetWord name _) = [haskellise name ++ " :: DynFlags -> Int",
haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"]
doWhat (GetInt name _) = [haskellise name ++ " :: DynFlags -> Int",
haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"]
doWhat (GetNatural name _) = [haskellise name ++ " :: DynFlags -> Integer",
haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"]
doWhat (GetBool name _) = [haskellise name ++ " :: DynFlags -> Bool",
haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"]
doWhat (StructFieldMacro {}) = []
doWhat (ClosureFieldMacro {}) = []
doWhat (ClosurePayloadMacro {}) = []
doWhat (FieldTypeGcptrMacro {}) = []
writeHaskellExports :: FilePath -> [What Fst] -> IO ()
writeHaskellExports fn ws = writeFile fn xs
where xs = unlines body
body = concatMap doWhat ws
doWhat (GetFieldType {}) = []
doWhat (GetClosureSize {}) = []
doWhat (GetWord name _) = [" " ++ haskellise name ++ ","]
doWhat (GetInt name _) = [" " ++ haskellise name ++ ","]
doWhat (GetNatural name _) = [" " ++ haskellise name ++ ","]
doWhat (GetBool name _) = [" " ++ haskellise name ++ ","]
doWhat (StructFieldMacro {}) = []
doWhat (ClosureFieldMacro {}) = []
doWhat (ClosurePayloadMacro {}) = []
doWhat (FieldTypeGcptrMacro {}) = []
writeHeader :: FilePath -> [What Snd] -> IO ()
writeHeader fn rs = writeFile fn xs
where xs = unlines (headers ++ body)
headers = ["/* This file is created automatically. Do not edit by hand.*/", ""]
body = concatMap doWhat rs
doWhat (GetFieldType name (Snd v)) = ["#define " ++ name ++ " b" ++ show (v * 8)]
doWhat (GetClosureSize name (Snd v)) = ["#define " ++ name ++ " (SIZEOF_StgHeader+" ++ show v ++ ")"]
doWhat (GetWord name (Snd v)) = ["#define " ++ name ++ " " ++ show v]
doWhat (GetInt name (Snd v)) = ["#define " ++ name ++ " " ++ show v]
doWhat (GetNatural name (Snd v)) = ["#define " ++ name ++ " " ++ show v]
doWhat (GetBool name (Snd v)) = ["#define " ++ name ++ " " ++ show (fromEnum v)]
doWhat (StructFieldMacro nameBase) =
["#define " ++ nameBase ++ "(__ptr__) REP_" ++ nameBase ++ "[__ptr__+OFFSET_" ++ nameBase ++ "]"]
doWhat (ClosureFieldMacro nameBase) =
["#define " ++ nameBase ++ "(__ptr__) REP_" ++ nameBase ++ "[__ptr__+SIZEOF_StgHeader+OFFSET_" ++ nameBase ++ "]"]
doWhat (ClosurePayloadMacro nameBase) =
["#define " ++ nameBase ++ "(__ptr__,__ix__) W_[__ptr__+SIZEOF_StgHeader+OFFSET_" ++ nameBase ++ " + WDS(__ix__)]"]
doWhat (FieldTypeGcptrMacro nameBase) =
["#define REP_" ++ nameBase ++ " gcptr"]
die :: String -> IO a
die err = do hPutStrLn stderr err
exitFailure
execute :: Bool -> FilePath -> [String] -> IO ()
execute verbose prog args
= do when verbose $ putStrLn $ showCommandForUser prog args
ec <- rawSystem prog args
unless (ec == ExitSuccess) $
die ("Executing " ++ show prog ++ " failed")
|
olsner/ghc
|
utils/deriveConstants/Main.hs
|
bsd-3-clause
| 46,059
| 203
| 19
| 14,963
| 10,343
| 5,358
| 4,985
| 757
| 35
|
module BrownPLT.JavaScript.Contracts.Template
( JavaScriptTemplate
, exprTemplate
, stmtTemplate
, substVar
, substVarList
, substIdList
, substFieldList
, expandCall
, templateExpression
, noPos
, thunkExpr
, renderTemplate
, renameVar
, templateStatements
) where
import Data.Data
import Data.Generics
import Text.ParserCombinators.Parsec (parse, many1)
import Text.ParserCombinators.Parsec.Pos (initialPos, SourcePos)
import Text.PrettyPrint.HughesPJ (render)
import BrownPLT.JavaScript.PrettyPrint (renderExpression, renderStatements)
import BrownPLT.JavaScript.Parser
import BrownPLT.JavaScript.Syntax
import BrownPLT.JavaScript.Instances()
import BrownPLT.JavaScript.Crawl() -- hack for instance
noPos :: SourcePos
noPos = initialPos "template"
thunkExpr :: ParsedExpression -> ParsedExpression
thunkExpr expr = FuncExpr noPos [] (ReturnStmt noPos (Just expr))
-- We may extend this later so that template definitions explicitly
-- state their free identifiers
data JavaScriptTemplate
= ExpressionTemplate ParsedExpression
| StatementTemplate [ParsedStatement]
exprTemplate :: String -> JavaScriptTemplate
exprTemplate str = case parse assignExpr "expression template" str of
Left err -> error ("Error parsing template: " ++ show err ++
"; template:\n\n" ++ str)
Right expr -> ExpressionTemplate expr
stmtTemplate :: String -> JavaScriptTemplate
stmtTemplate str = case parse (many1 parseStatement) "statement template" str of
Left err -> error ("Error parsing template: " ++ show err ++
"; template:\n\n" ++ str)
Right stmts -> StatementTemplate stmts
renderTemplate :: JavaScriptTemplate -> String
renderTemplate (ExpressionTemplate expr) = renderExpression expr
renderTemplate (StatementTemplate stmts) = renderStatements stmts
templateExpression :: JavaScriptTemplate -> ParsedExpression
templateExpression (ExpressionTemplate expr) = expr
templateStatements :: JavaScriptTemplate -> [ParsedStatement]
templateStatements (StatementTemplate stmts) = stmts
expandCall :: String -- ^function name to expand
-> ([ParsedExpression] -> [ParsedExpression]) -- ^argument expander
-> JavaScriptTemplate
-> JavaScriptTemplate
expandCall functionId expander (StatementTemplate body) =
StatementTemplate (everywhere (mkT subst) body) where
subst (CallExpr p1 fn@(VarRef p2 (Id p3 id')) args)
| id' == functionId = CallExpr p1 fn (expander args)
subst expr = expr
renameVar :: String -- ^original id
-> String -- ^new id
-> JavaScriptTemplate
-> JavaScriptTemplate
renameVar idOld idNew body =
let -- explicit signatures needed for generics
substExpr :: ParsedExpression -> ParsedExpression
substExpr (VarRef p1 (Id p2 thisId))
| thisId == idOld = VarRef p1 (Id p2 idNew)
substExpr v = v
substDecl :: VarDecl SourcePos -> VarDecl SourcePos
substDecl (VarDecl p1 (Id p2 thisId) val)
| thisId == idOld = VarDecl p1 (Id p2 idNew) val
substDecl v = v
in case body of
ExpressionTemplate body -> ExpressionTemplate $
everywhere ((mkT substDecl) . (mkT substExpr)) body
StatementTemplate stmts -> StatementTemplate $
everywhere (mkT substDecl . mkT substExpr) stmts
substVar :: String -- ^free identifier
-> ParsedExpression -- ^expression to substitute
-> JavaScriptTemplate
-> JavaScriptTemplate
substVar id expr body =
let subst (VarRef _ (Id _ id')) | id' == id = expr
subst expr = expr
in case body of
ExpressionTemplate body ->
ExpressionTemplate (everywhere (mkT subst) body)
StatementTemplate stmts ->
StatementTemplate (everywhere (mkT subst) stmts)
substVarList :: String -- ^identifier in a list
-> [ParsedExpression] -- ^list of expressions to substitute
-> JavaScriptTemplate
-> JavaScriptTemplate
substVarList id exprs (ExpressionTemplate body) =
ExpressionTemplate (everywhere (mkT subst) body) where
subst [VarRef _ (Id _ id')] | id' == id = exprs
subst lst = lst
substIdList :: String -- ^identifier in a list
-> [String] -- ^list of identifiers to substitute
-> JavaScriptTemplate
-> JavaScriptTemplate
substIdList id ids (ExpressionTemplate body) =
ExpressionTemplate (everywhere (mkT subst) body) where
subst [Id _ id'] | id' == id = map (Id noPos) ids
subst lst = lst
substFieldList :: String -- ^ placeholder field name
-> [(String,ParsedExpression)] -- ^list of fields
-> JavaScriptTemplate
-> JavaScriptTemplate
substFieldList fieldId fields (ExpressionTemplate body) =
ExpressionTemplate (everywhere (mkT subst) body) where
fields' = map (\(name,expr) -> (PropId noPos (Id noPos name),expr)) fields
subst [(PropId _ (Id _ id'), _)] | id' == fieldId = fields'
subst lst = lst
|
brownplt/javascript-contracts
|
src/BrownPLT/JavaScript/Contracts/Template.hs
|
bsd-3-clause
| 5,018
| 0
| 15
| 1,123
| 1,338
| 693
| 645
| 114
| 4
|
{-# LANGUAGE Haskell98, BangPatterns #-}
{-# LINE 1 "Data/ByteString/Search/Substitution.hs" #-}
-- |
-- Module : Data.ByteString.Search.Substitution
-- Copyright : Daniel Fischer
-- Licence : BSD3
-- Maintainer : Daniel Fischer <daniel.is.fischer@googlemail.com>
-- Stability : Provisional
-- Portability : portable
--
-- Class for values to be substituted into strict and lazy 'S.ByteString's
-- by the @replace@ functions defined in this package.
--
module Data.ByteString.Search.Substitution ( Substitution(..)) where
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Internal as LI
-- | Type class of meaningful substitutions for replace functions
-- on ByteStrings. Instances for strict and lazy ByteStrings are
-- provided here.
class Substitution a where
-- | @'substitution'@ transforms a value to a substitution function.
substitution :: a -> ([S.ByteString] -> [S.ByteString])
-- | @'prependCycle' sub lazyBS@ shall prepend infinitely many copies
-- of @sub@ to @lazyBS@ without entering an infinite loop in case
-- of an empty @sub@, so e.g.
--
-- @
-- 'prependCycle' \"\" \"ab\" == \"ab\"
-- @
--
-- shall (quickly) evaluate to 'True'.
-- For non-empty @sub@, the cycle shall be constructed efficiently.
prependCycle :: a -> (L.ByteString -> L.ByteString)
instance Substitution S.ByteString where
{-# INLINE substitution #-}
substitution sub = if S.null sub then id else (sub :)
{-# INLINE prependCycle #-}
prependCycle sub
| S.null sub = id
| otherwise = let c = LI.Chunk sub c in const c
instance Substitution L.ByteString where
{-# INLINE substitution #-}
substitution LI.Empty = id
substitution (LI.Chunk c t) = (c :) . flip (LI.foldrChunks (:)) t
{-# INLINE prependCycle #-}
prependCycle sub
| L.null sub = id
prependCycle sub = let cyc = LI.foldrChunks LI.Chunk cyc sub in const cyc
|
phischu/fragnix
|
tests/packages/scotty/Data.ByteString.Search.Substitution.hs
|
bsd-3-clause
| 2,043
| 0
| 12
| 452
| 327
| 189
| 138
| 24
| 0
|
{- |
Module : $Header$
Description : Utilities for CspCASLProver related to Isabelle
Copyright : (c) Liam O'Reilly and Markus Roggenbach,
Swansea University 2009
License : GPLv2 or higher, see LICENSE.txt
Maintainer : csliam@swansea.ac.uk
Stability : provisional
Portability : portable
Utilities for CspCASLProver related to Isabelle. The functions here
typically manipulate Isabelle signatures.
-}
module CspCASLProver.IsabelleUtils
( addConst
, addDef
, addInstanceOf
, addLemmasCollection
, addPrimRec
, addTheoremWithProof
, updateDomainTab
, writeIsaTheory
) where
import Common.AS_Annotation (makeNamed, Named, SenAttr (..))
import Common.ProofUtils (prepareSenNames)
import Comorphisms.CFOL2IsabelleHOL (IsaTheory)
-- import CspCASLProver.Consts
import qualified Data.Map as Map
import Isabelle.IsaParse (parseTheory)
import Isabelle.IsaPrint (getAxioms, printIsaTheory)
import Isabelle.IsaSign (DomainEntry, IsaProof (..), mkCond, mkSen
, Sentence (..), Sign (..), Sort
, Term (..), Typ (..))
import Isabelle.IsaConsts (mkVName)
import Isabelle.Translate (transString)
import Logic.Prover (Theory (..), toNamedList)
import Text.ParserCombinators.Parsec (parse)
-- | Add a single constant to the signature of an Isabelle theory
addConst :: String -> Typ -> IsaTheory -> IsaTheory
addConst cName cType isaTh =
let isaTh_sign = fst isaTh
isaTh_sen = snd isaTh
isaTh_sign_ConstTab = constTab isaTh_sign
isaTh_sign_ConstTabUpdated =
Map.insert (mkVName cName) cType isaTh_sign_ConstTab
isaTh_sign_updated = isaTh_sign {
constTab = isaTh_sign_ConstTabUpdated
}
in (isaTh_sign_updated, isaTh_sen)
-- | Function to add a def command to an Isabelle theory
addDef :: String -> Term -> Term -> IsaTheory -> IsaTheory
addDef name lhs rhs isaTh =
let isaTh_sign = fst isaTh
isaTh_sen = snd isaTh
sen = ConstDef (IsaEq lhs rhs)
namedSen = makeNamed name sen
in (isaTh_sign, isaTh_sen ++ [namedSen])
{- | Function to add an instance of command to an Isabelle theory. The
sort parameters here are basically strings. -}
addInstanceOf :: String -> [Sort] -> Sort -> [(String, Term)] -> IsaProof ->
IsaTheory -> IsaTheory
addInstanceOf name args res defs prf isaTh =
let isaTh_sign = fst isaTh
isaTh_sen = snd isaTh
sen = Instance name args res defs prf
namedSen = makeNamed name sen
in (isaTh_sign, isaTh_sen ++ [namedSen])
{- | Add a lemmas sentence (definition) that allow us to group large collections
of lemmas in to a single lemma. This cuts down on the repreated addition of
lemmas in the proofs. -}
addLemmasCollection :: String -> [String] -> IsaTheory -> IsaTheory
addLemmasCollection lemmaname lemmas isaTh =
if null lemmas
then isaTh
else let isaTh_sign = fst isaTh
isaTh_sen = snd isaTh
-- Make a named lemmas sentence
namedSen = (makeNamed lemmaname (Lemmas lemmaname lemmas))
{isAxiom = False}
in (isaTh_sign, isaTh_sen ++ [namedSen])
{- | Add a constant with a primrec defintion to the sentences of an Isabelle
theory. Parameters: constant name, type, primrec defintions and isabelle
theory to be added to. -}
addPrimRec :: String -> Typ -> [Term] -> IsaTheory -> IsaTheory
addPrimRec cName cType terms isaTh =
let isaTh_sign = fst isaTh
isaTh_sen = snd isaTh
primRecDef = RecDef {
keyword = Nothing, constName = mkVName cName,
constType = Just cType, primRecSenTerms = terms}
namedPrimRecDef = (makeNamed "BUG_what_does_this_word_do?" primRecDef) {
isAxiom = False,
isDef = True}
in (isaTh_sign, isaTh_sen ++ [namedPrimRecDef])
-- | Add a theorem with proof to an Isabelle theory
addTheoremWithProof :: String -> [Term] -> Term -> IsaProof -> IsaTheory ->
IsaTheory
addTheoremWithProof name conds concl proof' isaTh =
let isaTh_sign = fst isaTh
isaTh_sen = snd isaTh
sen = if null conds
then ((mkSen concl) {thmProof = Just proof'})
else ((mkCond conds concl) {thmProof = Just proof'})
namedSen = (makeNamed name sen) {isAxiom = False}
in (isaTh_sign, isaTh_sen ++ [namedSen])
{- | Prepare a theory for writing it out to a file. This function is based off
the function Isabelle.IsaProve.prepareTheory. The difference being that
this function does not mark axioms nor theorms as to be added to the
simplifier in Isabelle. -}
prepareTheory :: Theory Sign Sentence ()
-> (Sign, [Named Sentence], [Named Sentence], Map.Map String String)
prepareTheory (Theory sig nSens) = let
oSens = toNamedList nSens
nSens' = prepareSenNames transString oSens
(disAxs, disGoals) = getAxioms nSens'
in (sig, disAxs, disGoals,
Map.fromList $ zip (map senAttr nSens') $ map senAttr oSens)
-- | Add a DomainEntry to the domain tab of an Isabelle signature.
updateDomainTab :: DomainEntry -> IsaTheory -> IsaTheory
updateDomainTab domEnt (isaSign, isaSens) =
let oldDomTab = domainTab isaSign
isaSignUpdated = isaSign {domainTab = oldDomTab ++ [[domEnt]]}
in (isaSignUpdated, isaSens)
{- | Write out an Isabelle Theory. The theory should just run through
in Isabelle without any user interactions. This is based heavily
off Isabelle.IsaProve.isaProve -}
writeIsaTheory :: String -> Theory Sign Sentence () -> IO ()
writeIsaTheory thName th = do
let (sig, axs, ths, _) = prepareTheory th
-- thms = map senAttr ths
thBaseName = reverse . takeWhile (/= '/') $ reverse thName
{- useaxs = filter (\ s ->
sentence s /= mkSen true && (isDef s ||
isSuffixOf "def" (senAttr s))) axs
defaultProof = Just $ IsaProof
(if null useaxs then [] else [Using $ map senAttr useaxs])
By Auto -}
thy = shows (printIsaTheory thBaseName sig $ axs ++ ths) "\n"
thyFile = thBaseName ++ ".thy"
-- Check if the Isabelle theory is a valid Isabelle theory
case parse parseTheory thyFile thy of
Right _ -> do
{- prepareThyFiles (ho, bo) thyFile thy
removeDepFiles thBaseName thms
isabelle <- getEnvDef "HETS_ISABELLE" "Isabelle"
callSystem $ isabelle ++ " " ++ thyFile
ok <- checkFinalThyFile (ho, bo) thyFile
if ok then getAllProofDeps m thBaseName thms
else return [] -}
writeFile thyFile thy
return ()
{- The Isabelle theory is not a valid theory (according to Hets)
as it cannot be parsed. -}
Left err -> do
print err
putStrLn $ "Sorry, a generated theory cannot be parsed, see: "
++ thyFile
writeFile thyFile thy
putStrLn "Aborting Isabelle proof attempt"
return ()
|
keithodulaigh/Hets
|
CspCASLProver/IsabelleUtils.hs
|
gpl-2.0
| 6,924
| 0
| 14
| 1,731
| 1,359
| 740
| 619
| 107
| 2
|
{- |
Module : $Id$
Description : various encodings
Copyright : (c) Uni Bremen 2005-2007
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : non-portable (existential types)
This folder contains various comorphisms (implemented using
the type class 'Logic.Comorphism.Comorphism'), which are then
collected to a logic graph in "Comorphisms.LogicGraph".
The latter is based on the list of logics collected in
"Comorphisms.LogicList".
The individual comorphisms are on the one hand trivial embeddings:
"Comorphisms.CASL2CoCASL"
"Comorphisms.CASL2CspCASL"
"Comorphisms.CASL2HasCASL"
"Comorphisms.CASL2Modal"
"Comorphisms.Prop2CASL"
On the other hand, there are a number of real encodings:
"Comorphisms.CASL2PCFOL", "Comorphisms.CASL2TopSort" encodings of subsorting
"Comorphisms.CASL2SubCFOL" encoding of partiality
"Comorphisms.Sule2SoftFOL" translating a CASL subset to SoftFOL
"Comorphisms.Modal2CASL" encoding of Kripke worlds
"Comorphisms.HasCASL2Haskell"
translation of executable HasCASL subset to Haskell
"Comorphisms.CspCASL2Modal"
unfinished coding of CSP-CASL LTS semantics as Kripke models
"Comorphisms.CspCASL2IsabelleHOL"
unfinished coding of CSP-CASL in IsabelleHOL
"Comorphisms.HasCASL2HasCASL"
unfinished mapping of HasCASL subset to HasCASL program blocks
Finally, encodings to the theorem prover Isabelle:
"Comorphisms.CFOL2IsabelleHOL"
"Comorphisms.CoCFOL2IsabelleHOL"
"Comorphisms.PCoClTyCons2IsabelleHOL"
unfinished translation of HasCASL subset to Isabelle
"Comorphisms.Haskell2IsabelleHOLCF"
-}
module Comorphisms where
|
mariefarrell/Hets
|
Comorphisms.hs
|
gpl-2.0
| 1,663
| 0
| 2
| 227
| 5
| 4
| 1
| 1
| 0
|
{-# LANGUAGE OverloadedStrings #-}
module Clay.Color where
import Data.Char (isHexDigit)
import Data.Monoid
import Data.String
import Data.Text (Text)
import Text.Printf
import qualified Data.Text as Text
import Data.Text.Read as Text
import Clay.Property
import Clay.Common
-- * Color datatype.
data Color
= Rgba Integer Integer Integer Integer
| Hsla Integer Float Float Integer
| Other Value
deriving Show
-- * Color constructors.
rgba :: Integer -> Integer -> Integer -> Integer -> Color
rgba = Rgba
rgb :: Integer -> Integer -> Integer -> Color
rgb r g b = rgba r g b 255
hsla :: Integer -> Float -> Float -> Integer -> Color
hsla = Hsla
hsl :: Integer -> Float -> Float -> Color
hsl r g b = hsla r g b 255
grayish :: Integer -> Color
grayish g = rgb g g g
transparent :: Color
transparent = rgba 0 0 0 0
-- * Setting individual color components.
setR :: Integer -> Color -> Color
setR r (Rgba _ g b a) = Rgba r g b a
setR _ o = o
setG :: Integer -> Color -> Color
setG g (Rgba r _ b a) = Rgba r g b a
setG _ o = o
setB :: Integer -> Color -> Color
setB b (Rgba r g _ a) = Rgba r g b a
setB _ o = o
setA :: Integer -> Color -> Color
setA a (Rgba r g b _) = Rgba r g b a
setA a (Hsla r g b _) = Hsla r g b a
setA _ o = o
-- * Computing with colors.
(*.) :: Color -> Integer -> Color
(*.) (Rgba r g b a) i = Rgba (clamp (r * i)) (clamp (g * i)) (clamp (b * i)) a
(*.) o _ = o
(+.) :: Color -> Integer -> Color
(+.) (Rgba r g b a) i = Rgba (clamp (r + i)) (clamp (g + i)) (clamp (b + i)) a
(+.) o _ = o
(-.) :: Color -> Integer -> Color
(-.) (Rgba r g b a) i = Rgba (clamp (r - i)) (clamp (g - i)) (clamp (b - i)) a
(-.) o _ = o
clamp :: Integer -> Integer
clamp i = max (min i 255) 0
-------------------------------------------------------------------------------
instance Val Color where
value clr =
case clr of
Rgba r g b 255 -> Value $mconcat ["#", p' r, p' g, p' b]
Rgba r g b a -> Value $mconcat ["rgba(", p r, ",", p g, ",", p b, ",", ah a, ")"]
Hsla h s l 255 -> Value $mconcat ["hsl(", p h, ",", f s, ",", f l, ")"]
Hsla h s l a -> Value $mconcat ["hsla(", p h, ",", f s, ",", f l, ",", ah a, ")"]
Other o -> o
where p = fromString . show
p' = fromString . printf "%02x"
f = fromString . printf "%.4f%%"
ah = fromString . printf "%.4f" . (/ (256 :: Double)) . fromIntegral
instance None Color where none = Other "none"
instance Auto Color where auto = Other "auto"
instance Inherit Color where inherit = Other "inherit"
instance Other Color where other = Other
instance IsString Color where
fromString = parse . fromString
parse :: Text -> Color
parse t =
case Text.uncons t of
Just ('#', cs) | Text.all isHexDigit cs ->
case Text.unpack cs of
[a, b, c, d, e, f, g, h] -> rgba (hex a b) (hex c d) (hex e f) (hex g h)
[a, b, c, d, e, f ] -> rgb (hex a b) (hex c d) (hex e f)
[a, b, c, d ] -> rgba (hex a a) (hex b b) (hex c c) (hex d d)
[a, b, c ] -> rgb (hex a a) (hex b b) (hex c c)
_ -> err
_ -> err
where
hex a b = either err fst (Text.hexadecimal (Text.singleton a <> Text.singleton b))
err = error "Invalid color string"
-------------------------------------------------------------------------------
-- * List of color values by name.
aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black,
blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse,
chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue,
darkcyan, darkgoldenrod, darkgray, darkgreen, darkgrey, darkkhaki,
darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon,
darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise,
darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod,
gray, green, greenyellow, grey, honeydew, hotpink, indianred, indigo, ivory,
khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue,
lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgreen,
lightgrey, lightpink, lightsalmon, lightseagreen, lightskyblue,
lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid,
mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose,
moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip,
peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue,
saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue,
slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal,
thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow,
yellowgreen :: Color
aliceblue = rgb 240 248 255
antiquewhite = rgb 250 235 215
aqua = rgb 0 255 255
aquamarine = rgb 127 255 212
azure = rgb 240 255 255
beige = rgb 245 245 220
bisque = rgb 255 228 196
black = rgb 0 0 0
blanchedalmond = rgb 255 235 205
blue = rgb 0 0 255
blueviolet = rgb 138 43 226
brown = rgb 165 42 42
burlywood = rgb 222 184 135
cadetblue = rgb 95 158 160
chartreuse = rgb 127 255 0
chocolate = rgb 210 105 30
coral = rgb 255 127 80
cornflowerblue = rgb 100 149 237
cornsilk = rgb 255 248 220
crimson = rgb 220 20 60
cyan = rgb 0 255 255
darkblue = rgb 0 0 139
darkcyan = rgb 0 139 139
darkgoldenrod = rgb 184 134 11
darkgray = rgb 169 169 169
darkgreen = rgb 0 100 0
darkgrey = rgb 169 169 169
darkkhaki = rgb 189 183 107
darkmagenta = rgb 139 0 139
darkolivegreen = rgb 85 107 47
darkorange = rgb 255 140 0
darkorchid = rgb 153 50 204
darkred = rgb 139 0 0
darksalmon = rgb 233 150 122
darkseagreen = rgb 143 188 143
darkslateblue = rgb 72 61 139
darkslategray = rgb 47 79 79
darkslategrey = rgb 47 79 79
darkturquoise = rgb 0 206 209
darkviolet = rgb 148 0 211
deeppink = rgb 255 20 147
deepskyblue = rgb 0 191 255
dimgray = rgb 105 105 105
dimgrey = rgb 105 105 105
dodgerblue = rgb 30 144 255
firebrick = rgb 178 34 34
floralwhite = rgb 255 250 240
forestgreen = rgb 34 139 34
fuchsia = rgb 255 0 255
gainsboro = rgb 220 220 220
ghostwhite = rgb 248 248 255
gold = rgb 255 215 0
goldenrod = rgb 218 165 32
gray = rgb 128 128 128
green = rgb 0 128 0
greenyellow = rgb 173 255 47
grey = rgb 128 128 128
honeydew = rgb 240 255 240
hotpink = rgb 255 105 180
indianred = rgb 205 92 92
indigo = rgb 75 0 130
ivory = rgb 255 255 240
khaki = rgb 240 230 140
lavender = rgb 230 230 250
lavenderblush = rgb 255 240 245
lawngreen = rgb 124 252 0
lemonchiffon = rgb 255 250 205
lightblue = rgb 173 216 230
lightcoral = rgb 240 128 128
lightcyan = rgb 224 255 255
lightgoldenrodyellow = rgb 250 250 210
lightgray = rgb 211 211 211
lightgreen = rgb 144 238 144
lightgrey = rgb 211 211 211
lightpink = rgb 255 182 193
lightsalmon = rgb 255 160 122
lightseagreen = rgb 32 178 170
lightskyblue = rgb 135 206 250
lightslategray = rgb 119 136 153
lightslategrey = rgb 119 136 153
lightsteelblue = rgb 176 196 222
lightyellow = rgb 255 255 224
lime = rgb 0 255 0
limegreen = rgb 50 205 50
linen = rgb 250 240 230
magenta = rgb 255 0 255
maroon = rgb 128 0 0
mediumaquamarine = rgb 102 205 170
mediumblue = rgb 0 0 205
mediumorchid = rgb 186 85 211
mediumpurple = rgb 147 112 219
mediumseagreen = rgb 60 179 113
mediumslateblue = rgb 123 104 238
mediumspringgreen = rgb 0 250 154
mediumturquoise = rgb 72 209 204
mediumvioletred = rgb 199 21 133
midnightblue = rgb 25 25 112
mintcream = rgb 245 255 250
mistyrose = rgb 255 228 225
moccasin = rgb 255 228 181
navajowhite = rgb 255 222 173
navy = rgb 0 0 128
oldlace = rgb 253 245 230
olive = rgb 128 128 0
olivedrab = rgb 107 142 35
orange = rgb 255 165 0
orangered = rgb 255 69 0
orchid = rgb 218 112 214
palegoldenrod = rgb 238 232 170
palegreen = rgb 152 251 152
paleturquoise = rgb 175 238 238
palevioletred = rgb 219 112 147
papayawhip = rgb 255 239 213
peachpuff = rgb 255 218 185
peru = rgb 205 133 63
pink = rgb 255 192 203
plum = rgb 221 160 221
powderblue = rgb 176 224 230
purple = rgb 128 0 128
red = rgb 255 0 0
rosybrown = rgb 188 143 143
royalblue = rgb 65 105 225
saddlebrown = rgb 139 69 19
salmon = rgb 250 128 114
sandybrown = rgb 244 164 96
seagreen = rgb 46 139 87
seashell = rgb 255 245 238
sienna = rgb 160 82 45
silver = rgb 192 192 192
skyblue = rgb 135 206 235
slateblue = rgb 106 90 205
slategray = rgb 112 128 144
slategrey = rgb 112 128 144
snow = rgb 255 250 250
springgreen = rgb 0 255 127
steelblue = rgb 70 130 180
tan = rgb 210 180 140
teal = rgb 0 128 128
thistle = rgb 216 191 216
tomato = rgb 255 99 71
turquoise = rgb 64 224 208
violet = rgb 238 130 238
wheat = rgb 245 222 179
white = rgb 255 255 255
whitesmoke = rgb 245 245 245
yellow = rgb 255 255 0
yellowgreen = rgb 154 205 50
|
damianfral/clay
|
src/Clay/Color.hs
|
bsd-3-clause
| 10,938
| 0
| 14
| 3,931
| 3,658
| 2,017
| 1,641
| 253
| 6
|
pass :: [Inst] -> [Inst]
pass = peep1 . peep2 . peep3 . removeUnused
peep3 (x1:x2:x3:xs) = case (x1, x2, x3) of
(InstMove a b, InstMove c d, InstMove _ f) | (b == c) && (b == f) -> peep3 $ (InstMove a d):x3:xs
(InstMove a b, InstMove c d, InstUn _ _ f) | (b == c) && (b == f) -> peep3 $ (InstMove a d):x3:xs
(InstMove a b, InstMove c d, InstBin _ _ _ f) | (b == c) && (b == f) -> peep3 $ (InstMove a d):x3:xs
(InstMove a b, InstUn _ c d, InstMove _ f) | (b == c) && (b == f) -> peep3 $ (InstMove a d):x3:xs
(InstMove a b, InstUn _ c d, InstUn op _ f) | (b == c) && (b == f) -> peep3 $ (InstMove a d):x3:xs
(InstMove a b, InstUn _ c d, InstBin _ _ _ f) | (b == c) && (b == f) -> peep3 $ (InstMove a d):x3:xs
(InstMove a b, InstMove _ _, InstMove e g) | (b == g) && (b == e) -> peep3 $ x2:(InstMove a g):x3:xs
(InstMove a b, InstMove _ _, InstUn op e g) | (b == g) && (b == e) -> peep3 $ x2:(InstUn op a g):x3:xs
(InstMove a b, InstMove _ _, InstBin op e g f) | (b == g) && (b == e) && (b /= f) -> peep3 $ x2:(InstBin op a f g):xs
(InstMove a b, InstMove _ _, InstBin op e g f) | (b == g) && (b /= e) && (b == f) -> peep3 $ x2:(InstBin op e a g):xs
(InstMove a b, InstMove _ _, InstBin op e g f) | (b == g) && (b == e) && (b == f) -> peep3 $ x2:(InstBin op a a g):xs
(InstMove a b, InstBin op c d e, InstMove _ f) | (b == d) && (b /= c) && (b == f) -> peep3 $ (InstBin op c a e):x3:xs
(InstMove a b, InstBin op c d e, InstUn _ _ f) | (b == d) && (b /= c) && (b == f) -> peep3 $ (InstBin op c a e):x3:xs
(InstMove a b, InstBin op c d e, InstBin _ _ _ f) | (b == d) && (b /= c) && (b == f) -> peep3 $ (InstBin op c a e):x3:xs
(InstMove a b, InstBin op c d e, InstMove _ f) | (b /= d) && (b == c) && (b == f) -> peep3 $ (InstBin op c d e):x3:xs
(InstMove a b, InstBin op c d e, InstUn _ _ f) | (b /= d) && (b == c) && (b == f) -> peep3 $ (InstBin op c d e):x3:xs
(InstMove a b, InstBin op c d e, InstBin _ _ _ f) | (b /= d) && (b == c) && (b == f) -> peep3 $ (InstBin op c d e):x3:xs
(InstMove a b, InstBin op c d e, InstMove _ f) | (b == d) && (b == c) && (b == f) -> peep3 $ (InstBin op a a e):x3:xs
(InstMove a b, InstBin op c d e, InstUn _ _ f) | (b == d) && (b == c) && (b == f) -> peep3 $ (InstBin op a a e):x3:xs
(InstMove a b, InstBin op c d e, InstBin _ _ _ f) | (b == d) && (b == c) && (b == f) -> peep3 $ (InstBin op a a e):x3:xs
_ -> x1:(peep3 $ x2:x3:xs)
peep3 (x:xs) = x:(peep3 xs)
peep3 [] = []
peep2 (x1:x2:xs) = case x1 of
InstMove a b -> case x2 of
InstMove c d | (a == d) && (b == c) -> peep2 $ x1:xs
InstMove c d | (b == c) -> peep2 $ renameRegsMove a c d xs
InstUn op c d | (b == d) && (b == c) -> peep2 $ (InstUn op a b ):xs
InstBin op c d e | (b == e) && ((c == b) && (d /= b)) -> peep2 $ (InstBin op a d e):xs
InstBin op c d e | (b == e) && ((c /= b) && (d == b)) -> peep2 $ (InstBin op c a e):xs
InstBin op c d e | (b == e) && ((c == b) && (d == b)) -> peep2 $ (InstBin op a a e):xs
_ -> x1:(peep2 $ x2:xs)
InstUn op a b -> case x2 of
InstMove c d | (b == c) -> peep2 $ renameRegsUn op a c d xs
_ -> x1:(peep2 $ x2:xs)
InstBin op a b c -> case x2 of
InstMove d e | (c == d) -> peep2 $ renameRegsBin op a b d e xs
_ -> x1:(peep2 $ x2:xs)
peep2 (x:xs) = x:(peep2 xs)
peep2 [] = []
peep1 (x1:xs) = case x1 of
InstMove a b | a == b -> peep1 xs
| otherwise -> if doRename
then x1:(renameRegs src dst xs)
else x1:(peep1 xs)
where (doRename, src, dst) = chooseReg a b
rename reg = if reg == src
then dst
else reg
_ -> x1:(peep1 xs)
|
akrzemi1/Mach7
|
code/msvc/Versity/test/peep-v2.hs
|
bsd-3-clause
| 4,399
| 0
| 18
| 1,830
| 2,637
| 1,327
| 1,310
| 53
| 21
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE DataKinds #-}
module T15549b where
import Data.Kind (Type)
newtype Identity a = Identity a
newtype Par1 a = Par1 a
data family Sing :: forall k. k -> Type
data instance Sing :: forall k. k -> Type
type family Rep1 (f :: Type -> Type) :: Type -> Type
type instance Rep1 Identity = Par1
type family From1 (z :: f a) :: Rep1 f a
type instance From1 ('Identity x) = 'Par1 x
und :: a
und = und
f :: forall (a :: Type) (x :: Identity a). Sing x
f = g
where g :: forall (a :: Type) (f :: Type -> Type) (x :: f a). Sing x
g = seq (und :: Sing (From1 x)) und
|
sdiehl/ghc
|
testsuite/tests/typecheck/should_compile/T15549b.hs
|
bsd-3-clause
| 703
| 0
| 11
| 164
| 260
| 155
| 105
| -1
| -1
|
{-# LANGUAGE PartialTypeSignatures #-}
module AddAndOr6 where
addAndOr6 :: (Int, _) -> (Bool, _) -> (_ Int Bool)
addAndOr6 (a, b) (c, d) = (a `plus` d, b || c)
where plus :: Int -> Int -> Int
x `plus` y = x + y
|
urbanslug/ghc
|
testsuite/tests/partial-sigs/should_compile/AddAndOr6.hs
|
bsd-3-clause
| 222
| 0
| 8
| 56
| 108
| 63
| 45
| 6
| 1
|
{-# LANGUAGE CPP #-}
#include "stack001.hs"
|
forked-upstream-packages-for-ghcjs/ghc
|
testsuite/tests/rts/stack002.hs
|
bsd-3-clause
| 44
| 0
| 2
| 6
| 4
| 3
| 1
| 1
| 0
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Type inference of @loop@. This is complicated because of the
-- uniqueness and size inference, so the implementation is separate
-- from the main type checker.
module Language.Futhark.TypeChecker.Terms.DoLoop
( UncheckedLoop,
CheckedLoop,
checkDoLoop,
)
where
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.State
import Data.Bifunctor
import Data.Bitraversable
import qualified Data.Map.Strict as M
import Data.Maybe
import qualified Data.Set as S
import Futhark.Util (nubOrd)
import Futhark.Util.Pretty hiding (bool, group, space)
import Language.Futhark
import Language.Futhark.TypeChecker.Monad hiding (BoundV)
import Language.Futhark.TypeChecker.Terms.Monad hiding (consumed)
import Language.Futhark.TypeChecker.Terms.Pat
import Language.Futhark.TypeChecker.Types
import Language.Futhark.TypeChecker.Unify
import Prelude hiding (mod)
-- | Replace specified sizes with distinct fresh size variables.
someDimsFreshInType ::
SrcLoc ->
Rigidity ->
Name ->
S.Set VName ->
TypeBase (DimDecl VName) als ->
TermTypeM (TypeBase (DimDecl VName) als)
someDimsFreshInType loc r desc sizes = bitraverse onDim pure
where
onDim (NamedDim d)
| qualLeaf d `S.member` sizes = do
v <- newDimVar loc r desc
pure $ NamedDim $ qualName v
onDim d = pure d
-- | Replace the specified sizes with fresh size variables of the
-- specified ridigity. Returns the new fresh size variables.
freshDimsInType ::
SrcLoc ->
Rigidity ->
Name ->
S.Set VName ->
TypeBase (DimDecl VName) als ->
TermTypeM (TypeBase (DimDecl VName) als, [VName])
freshDimsInType loc r desc sizes t =
second M.elems <$> runStateT (bitraverse onDim pure t) mempty
where
onDim (NamedDim d)
| qualLeaf d `S.member` sizes = do
prev_subst <- gets $ M.lookup $ qualLeaf d
case prev_subst of
Just d' -> pure $ NamedDim $ qualName d'
Nothing -> do
v <- lift $ newDimVar loc r desc
modify $ M.insert (qualLeaf d) v
pure $ NamedDim $ qualName v
onDim d = pure d
-- | Mark bindings of names in "consumed" as Unique.
uniquePat :: Names -> Pat -> Pat
uniquePat consumed = recurse
where
recurse (Wildcard (Info t) wloc) =
Wildcard (Info $ t `setUniqueness` Nonunique) wloc
recurse (PatParens p ploc) =
PatParens (recurse p) ploc
recurse (PatAttr attr p ploc) =
PatAttr attr (recurse p) ploc
recurse (Id name (Info t) iloc)
| name `S.member` consumed =
let t' = t `setUniqueness` Unique `setAliases` mempty
in Id name (Info t') iloc
| otherwise =
let t' = t `setUniqueness` Nonunique
in Id name (Info t') iloc
recurse (TuplePat pats ploc) =
TuplePat (map recurse pats) ploc
recurse (RecordPat fs ploc) =
RecordPat (map (fmap recurse) fs) ploc
recurse (PatAscription p t ploc) =
PatAscription p t ploc
recurse p@PatLit {} = p
recurse (PatConstr n t ps ploc) =
PatConstr n t (map recurse ps) ploc
convergePat :: SrcLoc -> Pat -> Names -> PatType -> Usage -> TermTypeM Pat
convergePat loop_loc pat body_cons body_t body_loc = do
let -- Make the pattern unique where needed.
pat' = uniquePat (patNames pat `S.intersection` body_cons) pat
pat_t <- normTypeFully $ patternType pat'
unless (toStructural body_t `subtypeOf` toStructural pat_t) $
unexpectedType (srclocOf body_loc) (toStruct body_t) [toStruct pat_t]
-- Check that the new values of consumed merge parameters do not
-- alias something bound outside the loop, AND that anything
-- returned for a unique merge parameter does not alias anything
-- else returned. We also update the aliases for the pattern.
bound_outside <- asks $ S.fromList . M.keys . scopeVtable . termScope
let combAliases t1 t2 =
case t1 of
Scalar Record {} -> t1
_ -> t1 `addAliases` (<> aliases t2)
checkMergeReturn (Id pat_v (Info pat_v_t) patloc) t
| unique pat_v_t,
v : _ <-
S.toList $
S.map aliasVar (aliases t) `S.intersection` bound_outside =
lift . typeError loop_loc mempty $
"Return value for loop parameter"
<+> pquote (pprName pat_v)
<+> "aliases"
<+> pprName v <> "."
| otherwise = do
(cons, obs) <- get
unless (S.null $ aliases t `S.intersection` cons) $
lift . typeError loop_loc mempty $
"Return value for loop parameter"
<+> pquote (pprName pat_v)
<+> "aliases other consumed loop parameter."
when
( unique pat_v_t
&& not (S.null (aliases t `S.intersection` (cons <> obs)))
)
$ lift . typeError loop_loc mempty $
"Return value for consuming loop parameter"
<+> pquote (pprName pat_v)
<+> "aliases previously returned value."
if unique pat_v_t
then put (cons <> aliases t, obs)
else put (cons, obs <> aliases t)
pure $ Id pat_v (Info (combAliases pat_v_t t)) patloc
checkMergeReturn (Wildcard (Info pat_v_t) patloc) t =
pure $ Wildcard (Info (combAliases pat_v_t t)) patloc
checkMergeReturn (PatParens p _) t =
checkMergeReturn p t
checkMergeReturn (PatAscription p _ _) t =
checkMergeReturn p t
checkMergeReturn (RecordPat pfs patloc) (Scalar (Record tfs)) =
RecordPat . M.toList <$> sequence pfs' <*> pure patloc
where
pfs' = M.intersectionWith checkMergeReturn (M.fromList pfs) tfs
checkMergeReturn (TuplePat pats patloc) t
| Just ts <- isTupleRecord t =
TuplePat <$> zipWithM checkMergeReturn pats ts <*> pure patloc
checkMergeReturn p _ =
pure p
(pat'', (pat_cons, _)) <-
runStateT (checkMergeReturn pat' body_t) (mempty, mempty)
let body_cons' = body_cons <> S.map aliasVar pat_cons
if body_cons' == body_cons && patternType pat'' == patternType pat
then pure pat'
else convergePat loop_loc pat'' body_cons' body_t body_loc
data ArgSource = Initial | BodyResult
wellTypedLoopArg :: ArgSource -> [VName] -> Pat -> Exp -> TermTypeM ()
wellTypedLoopArg src sparams pat arg = do
(merge_t, _) <-
freshDimsInType (srclocOf arg) Nonrigid "loop" (S.fromList sparams) $
toStruct $ patternType pat
arg_t <- toStruct <$> expTypeFully arg
onFailure (checking merge_t arg_t) $
unify
(mkUsage (srclocOf arg) desc)
merge_t
arg_t
where
(checking, desc) =
case src of
Initial -> (CheckingLoopInitial, "matching initial loop values to pattern")
BodyResult -> (CheckingLoopBody, "matching loop body to pattern")
-- | An un-checked loop.
type UncheckedLoop =
(UncheckedPat, UncheckedExp, LoopFormBase NoInfo Name, UncheckedExp)
-- | A loop that has been type-checked.
type CheckedLoop =
([VName], Pat, Exp, LoopFormBase Info VName, Exp)
-- | Type-check a @loop@ expression, passing in a function for
-- type-checking subexpressions.
checkDoLoop ::
(UncheckedExp -> TermTypeM Exp) ->
UncheckedLoop ->
SrcLoc ->
TermTypeM (CheckedLoop, AppRes)
checkDoLoop checkExp (mergepat, mergeexp, form, loopbody) loc =
sequentially (checkExp mergeexp) $ \mergeexp' _ -> do
zeroOrderType
(mkUsage (srclocOf mergeexp) "use as loop variable")
"type used as loop variable"
=<< expTypeFully mergeexp'
-- The handling of dimension sizes is a bit intricate, but very
-- similar to checking a function, followed by checking a call to
-- it. The overall procedure is as follows:
--
-- (1) All empty dimensions in the merge pattern are instantiated
-- with nonrigid size variables. All explicitly specified
-- dimensions are preserved.
--
-- (2) The body of the loop is type-checked. The result type is
-- combined with the merge pattern type to determine which sizes are
-- variant, and these are turned into size parameters for the merge
-- pattern.
--
-- (3) We now conceptually have a function parameter type and
-- return type. We check that it can be called with the body type
-- as argument.
--
-- (4) Similarly to (3), we check that the "function" can be
-- called with the initial merge values as argument. The result
-- of this is the type of the loop as a whole.
--
-- (There is also a convergence loop for inferring uniqueness, but
-- that's orthogonal to the size handling.)
(merge_t, new_dims_to_initial_dim) <-
-- dim handling (1)
allDimsFreshInType loc Nonrigid "loop" =<< expTypeFully mergeexp'
let new_dims = M.keys new_dims_to_initial_dim
-- dim handling (2)
let checkLoopReturnSize mergepat' loopbody' = do
loopbody_t <- expTypeFully loopbody'
pat_t <-
someDimsFreshInType loc Nonrigid "loop" (S.fromList new_dims)
=<< normTypeFully (patternType mergepat')
-- We are ignoring the dimensions here, because any mismatches
-- should be turned into fresh size variables.
onFailure (CheckingLoopBody (toStruct pat_t) (toStruct loopbody_t)) $
unify
(mkUsage (srclocOf loopbody) "matching loop body to loop pattern")
(toStruct pat_t)
(toStruct loopbody_t)
-- Figure out which of the 'new_dims' dimensions are variant.
-- This works because we know that each dimension from
-- new_dims in the pattern is unique and distinct.
let onDims _ x y
| x == y = pure x
onDims _ (NamedDim v) d
| qualLeaf v `elem` new_dims = do
case M.lookup (qualLeaf v) new_dims_to_initial_dim of
Just d'
| d' == d ->
modify $ first $ M.insert (qualLeaf v) (SizeSubst d)
_ ->
modify $ second (qualLeaf v :)
pure $ NamedDim v
onDims _ x _ = pure x
loopbody_t' <- normTypeFully loopbody_t
merge_t' <- normTypeFully merge_t
let (init_substs, sparams) =
execState (matchDims onDims merge_t' loopbody_t') mempty
-- Make sure that any of new_dims that are invariant will be
-- replaced with the invariant size in the loop body. Failure
-- to do this can cause type annotations to still refer to
-- new_dims.
let dimToInit (v, SizeSubst d) =
constrain v $ Size (Just d) (mkUsage loc "size of loop parameter")
dimToInit _ =
pure ()
mapM_ dimToInit $ M.toList init_substs
mergepat'' <- applySubst (`M.lookup` init_substs) <$> updateTypes mergepat'
-- Eliminate those new_dims that turned into sparams so it won't
-- look like we have ambiguous sizes lying around.
modifyConstraints $ M.filterWithKey $ \k _ -> k `notElem` sparams
-- dim handling (3)
--
-- The only trick here is that we have to turn any instances
-- of loop parameters in the type of loopbody' rigid,
-- because we are no longer in a position to change them,
-- really.
wellTypedLoopArg BodyResult sparams mergepat'' loopbody'
pure (nubOrd sparams, mergepat'')
-- First we do a basic check of the loop body to figure out which of
-- the merge parameters are being consumed. For this, we first need
-- to check the merge pattern, which requires the (initial) merge
-- expression.
--
-- Play a little with occurences to ensure it does not look like
-- none of the merge variables are being used.
((sparams, mergepat', form', loopbody'), bodyflow) <-
case form of
For i uboundexp -> do
uboundexp' <-
require "being the bound in a 'for' loop" anySignedType
=<< checkExp uboundexp
bound_t <- expTypeFully uboundexp'
bindingIdent i bound_t $ \i' ->
noUnique . bindingPat [] mergepat (Ascribed merge_t) $
\mergepat' -> onlySelfAliasing . tapOccurrences $ do
loopbody' <- noSizeEscape $ checkExp loopbody
(sparams, mergepat'') <- checkLoopReturnSize mergepat' loopbody'
return
( sparams,
mergepat'',
For i' uboundexp',
loopbody'
)
ForIn xpat e -> do
(arr_t, _) <- newArrayType (srclocOf e) "e" 1
e' <- unifies "being iterated in a 'for-in' loop" arr_t =<< checkExp e
t <- expTypeFully e'
case t of
_
| Just t' <- peelArray 1 t ->
bindingPat [] xpat (Ascribed t') $ \xpat' ->
noUnique . bindingPat [] mergepat (Ascribed merge_t) $
\mergepat' -> onlySelfAliasing . tapOccurrences $ do
loopbody' <- noSizeEscape $ checkExp loopbody
(sparams, mergepat'') <- checkLoopReturnSize mergepat' loopbody'
return
( sparams,
mergepat'',
ForIn xpat' e',
loopbody'
)
| otherwise ->
typeError (srclocOf e) mempty $
"Iteratee of a for-in loop must be an array, but expression has type"
<+> ppr t
While cond ->
noUnique . bindingPat [] mergepat (Ascribed merge_t) $ \mergepat' ->
onlySelfAliasing . tapOccurrences
. sequentially
( checkExp cond
>>= unifies "being the condition of a 'while' loop" (Scalar $ Prim Bool)
)
$ \cond' _ -> do
loopbody' <- noSizeEscape $ checkExp loopbody
(sparams, mergepat'') <- checkLoopReturnSize mergepat' loopbody'
return
( sparams,
mergepat'',
While cond',
loopbody'
)
mergepat'' <- do
loopbody_t <- expTypeFully loopbody'
convergePat loc mergepat' (allConsumed bodyflow) loopbody_t $
mkUsage (srclocOf loopbody') "being (part of) the result of the loop body"
let consumeMerge (Id _ (Info pt) ploc) mt
| unique pt = consume ploc $ aliases mt
consumeMerge (TuplePat pats _) t
| Just ts <- isTupleRecord t =
zipWithM_ consumeMerge pats ts
consumeMerge (PatParens pat _) t =
consumeMerge pat t
consumeMerge (PatAscription pat _ _) t =
consumeMerge pat t
consumeMerge _ _ =
pure ()
consumeMerge mergepat'' =<< expTypeFully mergeexp'
-- dim handling (4)
wellTypedLoopArg Initial sparams mergepat'' mergeexp'
(loopt, retext) <-
freshDimsInType loc (Rigid RigidLoop) "loop" (S.fromList sparams) $
patternType mergepat''
-- We set all of the uniqueness to be unique. This is intentional,
-- and matches what happens for function calls. Those arrays that
-- really *cannot* be consumed will alias something unconsumable,
-- and will be caught that way.
let bound_here = patNames mergepat'' <> S.fromList sparams <> form_bound
form_bound =
case form' of
For v _ -> S.singleton $ identName v
ForIn forpat _ -> patNames forpat
While {} -> mempty
loopt' =
second (`S.difference` S.map AliasBound bound_here) $
loopt `setUniqueness` Unique
pure ((sparams, mergepat'', mergeexp', form', loopbody'), AppRes loopt' retext)
|
diku-dk/futhark
|
src/Language/Futhark/TypeChecker/Terms/DoLoop.hs
|
isc
| 16,043
| 0
| 28
| 4,956
| 3,782
| 1,897
| 1,885
| 291
| 13
|
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.ByteLengthQueuingStrategy
(newByteLengthQueuingStrategy, size, size_,
ByteLengthQueuingStrategy(..), gTypeByteLengthQueuingStrategy)
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/ByteLengthQueuingStrategy Mozilla ByteLengthQueuingStrategy documentation>
newByteLengthQueuingStrategy ::
(MonadDOM m) => m ByteLengthQueuingStrategy
newByteLengthQueuingStrategy
= liftDOM
(ByteLengthQueuingStrategy <$>
new (jsg "ByteLengthQueuingStrategy") ())
-- | <https://developer.mozilla.org/en-US/docs/Web/API/ByteLengthQueuingStrategy.size Mozilla ByteLengthQueuingStrategy.size documentation>
size :: (MonadDOM m) => ByteLengthQueuingStrategy -> m Double
size self = liftDOM ((self ^. jsf "size" ()) >>= valToNumber)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/ByteLengthQueuingStrategy.size Mozilla ByteLengthQueuingStrategy.size documentation>
size_ :: (MonadDOM m) => ByteLengthQueuingStrategy -> m ()
size_ self = liftDOM (void (self ^. jsf "size" ()))
|
ghcjs/jsaddle-dom
|
src/JSDOM/Generated/ByteLengthQueuingStrategy.hs
|
mit
| 1,983
| 0
| 11
| 251
| 456
| 282
| 174
| 29
| 1
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGTextPathElement
(pattern TEXTPATH_METHODTYPE_UNKNOWN,
pattern TEXTPATH_METHODTYPE_ALIGN,
pattern TEXTPATH_METHODTYPE_STRETCH,
pattern TEXTPATH_SPACINGTYPE_UNKNOWN,
pattern TEXTPATH_SPACINGTYPE_AUTO,
pattern TEXTPATH_SPACINGTYPE_EXACT, js_getStartOffset,
getStartOffset, js_getMethod, getMethod, js_getSpacing, getSpacing,
SVGTextPathElement, castToSVGTextPathElement,
gTypeSVGTextPathElement)
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 (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
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.Enums
pattern TEXTPATH_METHODTYPE_UNKNOWN = 0
pattern TEXTPATH_METHODTYPE_ALIGN = 1
pattern TEXTPATH_METHODTYPE_STRETCH = 2
pattern TEXTPATH_SPACINGTYPE_UNKNOWN = 0
pattern TEXTPATH_SPACINGTYPE_AUTO = 1
pattern TEXTPATH_SPACINGTYPE_EXACT = 2
foreign import javascript unsafe "$1[\"startOffset\"]"
js_getStartOffset ::
JSRef SVGTextPathElement -> IO (JSRef SVGAnimatedLength)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGTextPathElement.startOffset Mozilla SVGTextPathElement.startOffset documentation>
getStartOffset ::
(MonadIO m) => SVGTextPathElement -> m (Maybe SVGAnimatedLength)
getStartOffset self
= liftIO
((js_getStartOffset (unSVGTextPathElement self)) >>= fromJSRef)
foreign import javascript unsafe "$1[\"method\"]" js_getMethod ::
JSRef SVGTextPathElement -> IO (JSRef SVGAnimatedEnumeration)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGTextPathElement.method Mozilla SVGTextPathElement.method documentation>
getMethod ::
(MonadIO m) =>
SVGTextPathElement -> m (Maybe SVGAnimatedEnumeration)
getMethod self
= liftIO ((js_getMethod (unSVGTextPathElement self)) >>= fromJSRef)
foreign import javascript unsafe "$1[\"spacing\"]" js_getSpacing ::
JSRef SVGTextPathElement -> IO (JSRef SVGAnimatedEnumeration)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGTextPathElement.spacing Mozilla SVGTextPathElement.spacing documentation>
getSpacing ::
(MonadIO m) =>
SVGTextPathElement -> m (Maybe SVGAnimatedEnumeration)
getSpacing self
= liftIO
((js_getSpacing (unSVGTextPathElement self)) >>= fromJSRef)
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/JSFFI/Generated/SVGTextPathElement.hs
|
mit
| 2,990
| 18
| 11
| 437
| 643
| 378
| 265
| 54
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__ < 710
{-# LANGUAGE OverlappingInstances #-}
#endif
module Text.Blaze.JSON.Class where
import Prelude hiding(null)
import Text.Blaze.JSON.Internal
import qualified Data.Text as T
import qualified Data.Text.Lazy as L
import Data.Monoid
import Data.Int
import Data.Word
import qualified Data.Foldable as F
import qualified Data.Map as Map
import qualified Data.IntMap as IntMap
import qualified Data.Set as Set
import qualified Data.IntSet as IntSet
import qualified Data.Tree as Tree
class ToJSON a where
toJSON :: a -> JSON
instance ToJSON a => ToJSON (Maybe a) where
toJSON = maybe null toJSON
{-# INLINE toJSON #-}
instance (ToJSON a, ToJSON b) => ToJSON (Either a b) where
toJSON = object' id id . either left right
where
left l = [("Left", toJSON l)]
right r = [("Right", toJSON r)]
{-# INLINE toJSON #-}
instance ToJSON Bool where
toJSON = bool
{-# INLINE toJSON #-}
instance ToJSON () where
toJSON _ = array' id []
{-# INLINE toJSON #-}
instance ToJSON [Char] where
toJSON = text . T.pack
{-# INLINE toJSON #-}
instance ToJSON Char where
toJSON = text . T.singleton
{-# INLINE toJSON #-}
instance ToJSON Double where
toJSON = double
{-# INLINE toJSON #-}
instance ToJSON Float where
toJSON = float
{-# INLINE toJSON #-}
instance ToJSON Int where
toJSON = integral
{-# INLINE toJSON #-}
instance ToJSON Integer where
toJSON = integral
{-# INLINE toJSON #-}
instance ToJSON Int8 where
toJSON = integral
{-# INLINE toJSON #-}
instance ToJSON Int16 where
toJSON = integral
{-# INLINE toJSON #-}
instance ToJSON Int32 where
toJSON = integral
{-# INLINE toJSON #-}
instance ToJSON Int64 where
toJSON = integral
{-# INLINE toJSON #-}
instance ToJSON Word where
toJSON = integral
{-# INLINE toJSON #-}
instance ToJSON Word8 where
toJSON = integral
{-# INLINE toJSON #-}
instance ToJSON Word16 where
toJSON = integral
{-# INLINE toJSON #-}
instance ToJSON Word32 where
toJSON = integral
{-# INLINE toJSON #-}
instance ToJSON Word64 where
toJSON = integral
{-# INLINE toJSON #-}
instance ToJSON T.Text where
toJSON = text
{-# INLINE toJSON #-}
instance ToJSON L.Text where
toJSON = lazyText
{-# INLINE toJSON #-}
#if __GLASGOW_HASKELL__ >= 710
instance {-# OVERLAPPABLE #-} (F.Foldable f, ToJSON a) => ToJSON (f a) where
#else
instance (F.Foldable f, ToJSON a) => ToJSON (f a) where
#endif
toJSON = array' toJSON
{-# INLINE toJSON #-}
instance ToJSON a => ToJSON (Set.Set a) where
toJSON = toJSON . Set.toList
{-# INLINE toJSON #-}
instance ToJSON IntSet.IntSet where
toJSON = toJSON . IntSet.toList
{-# INLINE toJSON #-}
instance ToJSON a => ToJSON (IntMap.IntMap a) where
toJSON = toJSON . IntMap.toList
{-# INLINE toJSON #-}
instance ToJSON v => ToJSON (Map.Map T.Text v) where
toJSON = unsafeObject' id toJSON . Map.toList
{-# INLINE toJSON #-}
instance ToJSON v => ToJSON (Map.Map L.Text v) where
toJSON = unsafeObject' L.toStrict toJSON . Map.toList
{-# INLINE toJSON #-}
instance ToJSON v => ToJSON (Map.Map String v) where
toJSON = unsafeObject' T.pack toJSON . Map.toList
{-# INLINE toJSON #-}
instance ToJSON a => ToJSON (Tree.Tree a) where
toJSON (Tree.Node r b) = toJSON (r,b)
{-# INLINE toJSON #-}
instance ToJSON JSON where
toJSON = id
{-# INLINE toJSON #-}
instance (ToJSON a, ToJSON b) => ToJSON (a, b) where
toJSON (a,b) = array' id [toJSON a, toJSON b]
{-# INLINE toJSON #-}
instance (ToJSON a, ToJSON b, ToJSON c) => ToJSON (a, b, c) where
toJSON (a,b,c) = array' id [toJSON a, toJSON b, toJSON c]
{-# INLINE toJSON #-}
instance (ToJSON a, ToJSON b, ToJSON c, ToJSON d) => ToJSON (a, b, c, d) where
toJSON (a,b,c,d) = array' id [toJSON a, toJSON b, toJSON c, toJSON d]
{-# INLINE toJSON #-}
instance (ToJSON a, ToJSON b, ToJSON c, ToJSON d, ToJSON e) => ToJSON (a, b, c, d, e) where
toJSON (a,b,c,d,e) = array' id [toJSON a, toJSON b, toJSON c, toJSON d, toJSON e]
{-# INLINE toJSON #-}
instance (ToJSON a, ToJSON b, ToJSON c, ToJSON d, ToJSON e, ToJSON f) => ToJSON (a, b, c, d, e, f) where
toJSON (a,b,c,d,e,f) = array' id [toJSON a, toJSON b, toJSON c, toJSON d, toJSON e, toJSON f]
{-# INLINE toJSON #-}
instance ToJSON a => ToJSON (Dual a) where
toJSON = toJSON . getDual
{-# INLINE toJSON #-}
instance ToJSON a => ToJSON (First a) where
toJSON = toJSON . getFirst
{-# INLINE toJSON #-}
instance ToJSON a => ToJSON (Last a) where
toJSON = toJSON . getLast
{-# INLINE toJSON #-}
|
philopon/blaze-json
|
src/Text/Blaze/JSON/Class.hs
|
mit
| 4,790
| 0
| 10
| 1,122
| 1,463
| 809
| 654
| 136
| 0
|
{-# LANGUAGE RecordWildCards #-}
import Data.Foldable (for_)
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
import ArmstrongNumbers (armstrong)
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = describe "armstrong" $ for_ cases test
where
test Case{..} = it description assertion
where
assertion = armstrong input `shouldBe` expected
data Case = Case { description :: String
, input :: Int
, expected :: Bool
}
cases :: [Case]
cases = [ Case { description = "Zero is an Armstrong numbers"
, input = 0
, expected = True
}
, Case { description = "Single digit numbers are Armstrong numbers"
, input = 5
, expected = True
}
, Case { description = "There are no 2 digit Armstrong numbers"
, input = 10
, expected = False
}
, Case { description = "Three digit number that is an Armstrong number"
, input = 153
, expected = True
}
, Case { description = "Three digit number that is not an Armstrong number"
, input = 100
, expected = False
}
, Case { description = "Four digit number that is an Armstrong number"
, input = 9474
, expected = True
}
, Case { description = "Four digit number that is not an Armstrong number"
, input = 9475
, expected = False
}
, Case { description = "Seven digit number that is an Armstrong number"
, input = 9926315
, expected = True
}
, Case { description = "Seven digit number that is not an Armstrong number"
, input = 9926314
, expected = False
}
]
-- 234df17e8e4a0b126bb3c5cdd81f8e6965d8182e
|
exercism/xhaskell
|
exercises/practice/armstrong-numbers/test/Tests.hs
|
mit
| 2,199
| 0
| 10
| 936
| 391
| 241
| 150
| 42
| 1
|
module Q41 where
import Q39
import Q40
import AvlSet
goldbachList :: Int -> Int -> [(Int, Int)]
goldbachList x y = case (tryGoldbachList x y) of Left result -> result
Right message -> error message
tryGoldbachList :: Int -> Int -> Either [(Int, Int)] String
tryGoldbachList x y =
let
check :: Int -> Int -> Either [(Int, Int)] String
check x y
| x <= 2 = Right "x <= 2 is not supported"
| x > y = Right "x > y is not supported"
| otherwise = Left (tryGoldbachList' x y)
tryGoldbachList' :: Int -> Int -> [(Int, Int)]
tryGoldbachList' x y =
let
lower input = 2 * (quot input 2)
upper input = 2 * (quot (input+1) 2)
p = upper x
q = lower y
r = [p,p+2..q]
primesList = primesR 2 q
primesTree = foldr (flip insert) empty primesList
in
map (\s -> goldbachInternal s primesList primesTree) r
in
check x y
|
cshung/MiscLab
|
Haskell99/q41.hs
|
mit
| 1,043
| 0
| 17
| 403
| 378
| 193
| 185
| 27
| 2
|
import Graphics.UI.GLUT hiding (Point)
import Data.IORef
import Game.DeltaClock
import Game.Game (game)
import Game.Callbacks
import Game.Keyboard (initKeyboard)
main :: IO ()
main = do
_ <- getArgsAndInitialize
_ <- createWindow "Hello, World!"
clockRef <- initClock >>= newIORef
gameRef <- newIORef game
kbRef <- newIORef initKeyboard
let refs = (clockRef, kbRef, gameRef)
keyboardMouseCallback $= Just (handleKeyboard refs)
displayCallback $= display refs
mainLoop
|
sgrif/haskell-game
|
Main.hs
|
mit
| 492
| 0
| 10
| 84
| 158
| 79
| 79
| 17
| 1
|
-- Problems/Problem022Spec.hs
module Problems.Problem022Spec (main, spec) where
import Test.Hspec
import Problems.Problem022
main :: IO()
main = hspec spec
spec :: Spec
spec = describe "Problem 22" $
it "Should evaluate to 871198282" $
p22 `shouldBe` 871198282
|
Sgoettschkes/learning
|
haskell/ProjectEuler/tests/Problems/Problem022Spec.hs
|
mit
| 276
| 0
| 8
| 51
| 73
| 41
| 32
| 9
| 1
|
module Game.Mahjong.Test.Static.Examples ( tests ) where
import Game.Mahjong.Meld
import Game.Mahjong.Static.Tiles
import Game.Mahjong.Static.Melds
import Game.Mahjong.Static.Examples
import Test.Tasty
import Test.Tasty.HUnit
tests :: TestTree
tests = testGroup "Game.Mahjong.Static.Examples Tests" [constructionTests]
-- | Construction tests
constructionTests :: TestTree
constructionTests = testGroup "Construction tests" [
mkSequenceTests
, mkTripletTests
, mkQuartetTests
, mkPairTests
]
mkSequenceTests :: TestTree
mkSequenceTests = testGroup "Sequence creation tests" [
testCase "mkSequence' fails with Promote status" $
mkSequence' Promoted c1 @?= Nothing
, testCase "mkSequence' fails with bonus tile" $
mkSequence' Revealed f1 @?= Nothing
, testCase "mkSequence' fails with honor tile" $
mkSequence' Revealed ww @?= Nothing
, testCase "mkSequence' passes" $
mkSequence' Revealed c1 @?= Just c123
]
mkTripletTests :: TestTree
mkTripletTests = testGroup "Triplet creation tests" [
testCase "mkTriplet' fails with Promote status" $
mkTriplet' Promoted c1 @?= Nothing
, testCase "mkTriplet' fails with bonus tile" $
mkTriplet' Revealed s1 @?= Nothing
, testCase "mkTriplet' succeeds" $
mkTriplet' Revealed c1 @?= Just c111
, testCase "mkTriplet' succeeds" $
mkTriplet' Revealed wn @?= Just wnnn
]
mkQuartetTests :: TestTree
mkQuartetTests = testGroup "Quartet creation tests" [
testCase "mkQuartet' passes with Promote status" $
mkQuartet' Promoted c1 @?= promoteTriplet c111 c1
, testCase "mkQuartet' fails with bonus tile" $
mkQuartet' Revealed f1 @?= Nothing
, testCase "mkQuartet' succeeds" $
mkQuartet' Revealed c1 @?= Just c1111
, testCase "mkQuartet' succeeds" $
mkQuartet' Revealed wn @?= Just wnnnn
]
mkPairTests :: TestTree
mkPairTests = testGroup "Pair creation tests" [
testCase "mkPair' fails with Promote status" $
mkPair' Promoted c1 @?= Nothing
, testCase "mkPair' fails with bonus tile" $
mkPair' Revealed s1 @?= Nothing
, testCase "mkPair' succeeds" $
mkPair' Revealed c1 @?= Just c11
, testCase "mkPair' succeeds" $
mkPair' Revealed dr @?= Just drr
]
|
gspindles/mj-score-eval
|
test/Game/Mahjong/Test/Static/Examples.hs
|
mit
| 2,314
| 0
| 9
| 523
| 488
| 248
| 240
| 55
| 1
|
import System.Environment
import System.IO
import System.Exit
import Control.Exception
import Assembler
main :: IO ()
main = do
args <- getArgs
catch ( if length args /= 1
then error "number of arguments must be 1\nUsage: hass-assembler <program>"
else createMifFile $ head args
) err
where
err e = do
hPutStrLn stderr ("Error: " ++ show (e :: SomeException))
exitFailure
|
yu-i9/HaSS
|
src-assembler/Main.hs
|
mit
| 433
| 0
| 13
| 120
| 119
| 60
| 59
| 15
| 2
|
module GraphDB.Util.TH where
import GraphDB.Util.Prelude
import Language.Haskell.TH
import qualified GraphDB.Util.TH.Parsers as P
caseLambda :: [Match] -> Exp
caseLambda matches = LamE [VarP argName] (CaseE (VarE argName) matches)
where
argName = mkName "_0"
caseFunDec :: Name -> [Match] -> Dec
caseFunDec name matches =
FunD name [Clause [VarP argName] (NormalB (CaseE (VarE argName) matches)) []]
where
argName = mkName "_0"
reifyLocalInstances :: Q [(Name, [Type])]
reifyLocalInstances = do
loc <- location
text <- runIO $ readFile $ loc_filename loc
P.runParse text P.instances
|
nikita-volkov/graph-db
|
library/GraphDB/Util/TH.hs
|
mit
| 610
| 0
| 13
| 108
| 225
| 120
| 105
| 16
| 1
|
-- | Stability: provisional
module Test.Hspec.Core.Hooks (
before
, before_
, beforeWith
, beforeAll
, beforeAll_
, after
, after_
, afterAll
, afterAll_
, around
, around_
, aroundWith
) where
import Control.Exception (SomeException, finally, throwIO, try)
import Control.Concurrent.MVar
import Test.Hspec.Core.Spec
-- | Run a custom action before every spec item.
before :: IO a -> SpecWith a -> Spec
before action = around (action >>=)
-- | Run a custom action before every spec item.
before_ :: IO () -> SpecWith a -> SpecWith a
before_ action = around_ (action >>)
-- | Run a custom action before every spec item.
beforeWith :: (b -> IO a) -> SpecWith a -> SpecWith b
beforeWith action = aroundWith $ \e x -> action x >>= e
-- | Run a custom action before the first spec item.
beforeAll :: IO a -> SpecWith a -> Spec
beforeAll action spec = do
mvar <- runIO (newMVar Empty)
before (memoize mvar action) spec
-- | Run a custom action before the first spec item.
beforeAll_ :: IO () -> SpecWith a -> SpecWith a
beforeAll_ action spec = do
mvar <- runIO (newMVar Empty)
before_ (memoize mvar action) spec
data Memoized a =
Empty
| Memoized a
| Failed SomeException
memoize :: MVar (Memoized a) -> IO a -> IO a
memoize mvar action = do
result <- modifyMVar mvar $ \ma -> case ma of
Empty -> do
a <- try action
return (either Failed Memoized a, a)
Memoized a -> return (ma, Right a)
Failed _ -> throwIO (Pending (Just "exception in beforeAll-hook (see previous failure)"))
either throwIO return result
-- | Run a custom action after every spec item.
after :: ActionWith a -> SpecWith a -> SpecWith a
after action = aroundWith $ \e x -> e x `finally` action x
-- | Run a custom action after every spec item.
after_ :: IO () -> SpecWith a -> SpecWith a
after_ action = after $ \_ -> action
-- | Run a custom action before and/or after every spec item.
around :: (ActionWith a -> IO ()) -> SpecWith a -> Spec
around action = aroundWith $ \e () -> action e
-- | Run a custom action after the last spec item.
afterAll :: ActionWith a -> SpecWith a -> SpecWith a
afterAll action spec = runIO (runSpecM spec) >>= fromSpecList . return . NodeWithCleanup action
-- | Run a custom action after the last spec item.
afterAll_ :: IO () -> SpecWith a -> SpecWith a
afterAll_ action = afterAll (\_ -> action)
-- | Run a custom action before and/or after every spec item.
around_ :: (IO () -> IO ()) -> SpecWith a -> SpecWith a
around_ action = aroundWith $ \e a -> action (e a)
-- | Run a custom action before and/or after every spec item.
aroundWith :: (ActionWith a -> ActionWith b) -> SpecWith a -> SpecWith b
aroundWith action = mapAround (. action)
mapAround :: ((ActionWith b -> IO ()) -> ActionWith a -> IO ()) -> SpecWith a -> SpecWith b
mapAround f = mapSpecItem (untangle f) $ \i@Item{itemExample = e} -> i{itemExample = (. f) . e}
untangle :: ((ActionWith b -> IO ()) -> ActionWith a -> IO ()) -> ActionWith a -> ActionWith b
untangle f g = \b -> f ($ b) g
|
beni55/hspec
|
hspec-core/src/Test/Hspec/Core/Hooks.hs
|
mit
| 3,048
| 0
| 17
| 656
| 1,058
| 534
| 524
| 61
| 3
|
-- file Spec.hs
import Test.Hspec
import Test.QuickCheck
import Addition
main :: IO ()
main = hspec $ do
describe "Addition.add" $ do
it "returns the sum of two Integers" $ do
add 10 20 `shouldBe` (30 :: Integer)
|
laser/haste-experiment
|
demos/testing/AdditionSpec.hs
|
mit
| 226
| 0
| 15
| 51
| 74
| 38
| 36
| 8
| 1
|
{-# LANGUAGE RecordWildCards #-}
module OpenGLApp
(
openGLMain
, GLApp(..)
) where
import Graphics.UI.GLUT
data GLApp =
GLApp
{ title :: String
, display :: DisplayCallback
, special :: SpecialCallback
, keyboard :: KeyboardCallback
}
openGLMain :: GLApp -> IO ()
openGLMain GLApp{..} = do
_ <- getArgsAndInitialize
initialDisplayMode $= [DoubleBuffered, RGBMode, WithDepthBuffer]
window <- createWindow title
windowSize $= Size 540 400
clearColor $= Color4 0.05 0.05 0.05 0.0
clearDepth $= 1
shadeModel $= Smooth
depthFunc $= Just Less
hint PerspectiveCorrection $= Nicest
reshapeCallback $= Just reshape
specialCallback $= Just special
keyboardCallback $= Just keyboard
displayCallback $= wrapDisplay display window
mainLoop
reshape :: ReshapeCallback
reshape s@(Size width height) = do
viewport $= (Position 0 0, s)
matrixMode $= Projection
loadIdentity
perspective 45 (fromIntegral width / fromIntegral height) 2.01 4
matrixMode $= Modelview 0
wrapDisplay :: DisplayCallback -> Window -> DisplayCallback
wrapDisplay display window = do
clear [ColorBuffer, DepthBuffer]
loadIdentity
display
flush
swapBuffers
postRedisplay (Just window)
|
j-rock/tutte-your-stuff
|
src/OpenGLApp.hs
|
mit
| 1,281
| 0
| 10
| 296
| 370
| 179
| 191
| 43
| 1
|
import Control.Applicative
import qualified Data.ByteString.Char8 as BS
import Data.Maybe
solve :: (Ord a1, Ord a, Num a) => [a1] -> [(a1, a)] -> a -> a
solve [] _ ans = ans
solve (x:xs) [] ans = solve xs [(x,0)] ans
solve (x:xs) ((p,q):ss) ans
| x > p = solve xs ((x, 1):(p,q):ss) (max ans 1)
| otherwise =
let
pr = maximum $ map snd (takeWhile (\ (m, _) -> m >= x) ((p,q):ss))
nstack = dropWhile (\ (m, _) -> m >= x) ((p,q):ss)
in if null nstack
then solve xs [(x, 0)] ans
else solve xs ((x, pr + 1):nstack) (max ans (pr + 1))
readInt' :: BS.ByteString -> Int
readInt' = fst . fromJust . BS.readInt
main :: IO ()
main = do
_ <- BS.getLine
content <- BS.words <$> BS.getLine
let arr = map readInt' content
print $ solve arr [] 0
|
m00nlight/hackerrank
|
algorithm/contests/Counter-Code-2015/D.hs
|
gpl-2.0
| 836
| 0
| 16
| 254
| 471
| 253
| 218
| 23
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module Module.Scheme.Env
( current
, removeLastScope
, consNewScope
, genScope
, newFunction
, newSymbol
, pop, pop'
, push
, withEnv
, withGlobal
, withScope
, withNScope
, findSymbol
, findFunc
) where
import Control.Monad.State
import Control.Monad.Except
import qualified Data.Text as T
import Module.Scheme.Types
safeHead :: [Scope st] -> Scope st
safeHead [] = emptyScope
safeHead (x:_) = x
safeIndex :: Int -> [Scope st] -> Scope st
safeIndex i scopes
| length scopes >= i = scopes !! i
| otherwise = emptyScope
current :: Env st -> Scope st
current = safeHead . context
removeLastScope :: Env st -> Env st
removeLastScope env = env { context = drop 1 (context env) }
consNewScope :: Scope st -> Env st -> Env st
consNewScope scope env = env { context = scope : context env }
replaceScope :: Int -> Scope st -> Env st -> Env st
replaceScope i scope env = env { context = replace i scope (context env) }
where
replace n item ls = a ++ (item:b) where (a, _:b) = splitAt n ls
genScope :: [(Symbol, Expr)] -> Scope st
genScope = foldl gen emptyScope
where
gen scope (s, e) = newSymbol s e scope
newSymbol :: Symbol -> Expr -> Scope st -> Scope st
newSymbol symbol expr scope = scope { symbols = (symbol, expr) : symbols scope }
newFunction :: Symbol -> Call st -> Scope st -> Scope st
newFunction symbol call scope = scope { symbols = (symbol, SFunction symbol) : symbols scope
, functs = (symbol, call) : functs scope }
getAllSymbols :: [Scope st] -> [(Symbol, Expr)]
getAllSymbols = foldr ((++) . symbols) []
getAllFuncts :: [Scope st] -> [(Symbol, Call st)]
getAllFuncts = foldr ((++) . functs) []
push :: (WithScheme st) => Scope st -> Scheme st ()
push scope = withEnv (return . consNewScope scope)
pop :: (WithScheme st) => Scheme st ()
pop = withEnv (return . removeLastScope)
pop' :: (WithScheme st) => Scheme st (Scope st)
pop' = do
env <- lift getEnv
lift $ putEnv $ removeLastScope env
return $ current env
withEnv :: (WithScheme st) => (Env st -> Scheme st (Env st)) -> Scheme st ()
withEnv f = lift . putEnv =<< f =<< lift getEnv
withScope :: (WithScheme st) => (Scope st -> Scheme st (Scope st)) -> Scheme st ()
withScope f = withEnv $ \env -> do
new <- f $ current env
return $ consNewScope new $ removeLastScope env
withNScope :: (WithScheme st) => Int -> (Scope st -> Scheme st (Scope st)) -> Scheme st ()
withNScope n f = withEnv $ \env -> do
new <- f $ safeIndex n (context env)
return $ replaceScope n new env
withGlobal :: (WithScheme st) => (Scope st -> Scheme st (Scope st)) -> Scheme st ()
withGlobal f = withEnv $ \env -> do
new <- f $ global env
return $ env { global = new }
findSymbol :: (WithScheme st) => Symbol -> Scheme st Expr
findSymbol symbol = do
env <- lift getEnv
case lookup symbol (table env) of
Nothing -> throwError $ "Could not find symbol " `T.append` symbol
Just x -> return x
where
table env = getAllSymbols (context env ++ [global env])
findFunc :: (WithScheme st) => Symbol -> Scheme st (Call st)
findFunc symbol = do
ctx <- lift getEnv
case lookup symbol (table ctx) of
Nothing -> throwError $ "Could not find function " `T.append` symbol
Just x -> return x
where
table env = getAllFuncts (context env ++ [global env])
|
felixsch/ircbot
|
src/Module/Scheme/Env.hs
|
gpl-2.0
| 3,471
| 0
| 13
| 866
| 1,439
| 734
| 705
| 85
| 2
|
{-
Haskell implementation of sort tool.
http://linux.die.net/man/1/sort
-}
module Main where
import Data.List(sort)
main:: IO ()
main = getContents >>= putStrLn.unlines.sort.lines
|
huseyinyilmaz/hs-gnu-core-utils
|
src/sort.hs
|
gpl-2.0
| 185
| 0
| 8
| 26
| 40
| 23
| 17
| 4
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.