code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Main where import System.Environment import Text.ParserCombinators.Parsec hiding (spaces) import Control.Monad import Control.Monad.Error data LispVal = Atom String | List [LispVal] | DottedList [LispVal] LispVal | Number Integer | String String | Bool Bool data LispError = NumArgs Integer [LispVal] | TypeMismatch String LispVal | Parser ParseError | BadSpecialForm String LispVal | NotFunction String String | UnboundVar String String | Default String showError :: LispError -> String showError (UnboundVar message varname) = concat [message, ": ", varname] showError (BadSpecialForm message form) = concat [message, ": ", show form] showError (NotFunction message func) = concat [message, ": ", show func] showError (NumArgs expected found) = concat ["Expected ", show expected, " args: found values ", unwordsList found] showError (TypeMismatch expected found) = concat ["Invalid type: expected ", expected, ", found ", show found] showError (Parser parseErr) = concat ["Parse error at ", show parseErr] instance Show LispError where show = showError type ThrowsError = Either LispError instance Error LispError where noMsg = Default "An error has occurred" strMsg = Default trapError :: ThrowsError String -> ThrowsError String trapError action = catchError action (return . show) extractError :: ThrowsError a -> a extractError (Right val) = val symbol :: Parser Char symbol = oneOf "!$%&|*+-/:<=?>@^_~#" spaces :: Parser () spaces = skipMany1 space parseString :: Parser LispVal parseString = do char '"' x <- many (noneOf "\"") char '"' return $ String x parseAtom :: Parser LispVal parseAtom = do first <- letter <|> symbol rest <- many (letter <|> symbol <|> digit) let atom = first : rest return $ case atom of "#t" -> Bool True "#f" -> Bool False _ -> Atom atom parseNumber :: Parser LispVal parseNumber = liftM (Number . read) $ many1 digit parseList :: Parser LispVal parseList = liftM List . sepBy parseExpr $ spaces parseDottedList :: Parser LispVal parseDottedList = do init <- endBy parseExpr spaces char '.' spaces last <- parseExpr return $ DottedList init last parseQuoted :: Parser LispVal parseQuoted = do char '\'' e <- parseExpr return $ List [Atom "quote", e] parseExpr :: Parser LispVal parseExpr = parseAtom <|> parseString <|> parseNumber <|> parseQuoted <|> do char '(' x <- (try parseList) <|> parseDottedList char ')' return x showVal :: LispVal -> String showVal (Atom atom) = atom showVal (Number n) = show n showVal (String contents) = concat ["\"", contents, "\""] showVal (Bool True) = "#t" showVal (Bool False) = "#f" showVal (List list) = concat ["(", unwordsList list, ")"] showVal (DottedList init last) = concat ["(", unwordsList init, " . ", showVal last, ")"] unwordsList :: [LispVal] -> String unwordsList = unwords . map showVal instance Show LispVal where show = showVal unpackNum :: LispVal -> ThrowsError Integer unpackNum (Number n) = return n unpackNum (String s) = let parsed = reads s in if null parsed then throwError $ TypeMismatch "number" $ String s else return . fst . head $ parsed unpackNum (List [x]) = unpackNum x unpackNum notNum = throwError . TypeMismatch "number" $ notNum numericBinOp :: (Integer -> Integer -> Integer) -> [LispVal] -> ThrowsError LispVal numericBinOp op singleVal@[_] = throwError $ NumArgs 2 singleVal numericBinOp op params = mapM unpackNum params >>= return . Number . foldl1 op boolBinOp :: (LispVal -> ThrowsError a) -> (a -> a -> Bool) -> [LispVal] -> ThrowsError LispVal boolBinOp unpacker op args = if length args /= 2 then throwError . NumArgs 2 $ args else do left <- unpacker $ args !! 0 right <- unpacker $ args !! 1 return $ Bool (op left right) unpackStr :: LispVal -> ThrowsError String unpackStr (String s) = return s unpackStr (Number n) = return . show $ n unpackStr (Bool b) = return . show $ b unpackStr notString = throwError $ TypeMismatch "string" notString unpackBool :: LispVal -> ThrowsError Bool unpackBool (Bool b) = return b unpackBool notBool = throwError $ TypeMismatch "boolean" notBool strBoolBinop = boolBinOp unpackStr numBoolBinOp = boolBinOp unpackNum boolBoolBinOp = boolBinOp unpackBool primitives :: [(String, [LispVal] -> ThrowsError LispVal)] primitives = [("+", numericBinOp (+)), ("-", numericBinOp (-)), ("*", numericBinOp (*)), ("/", numericBinOp div), ("mod", numericBinOp mod), ("quotient", numericBinOp quot), ("remainder", numericBinOp rem), ("=", numBoolBinOp (==)), ("<", numBoolBinOp (<)), (">", numBoolBinOp (>)), ("/=", numBoolBinOp (/=)), (">=", numBoolBinOp (>=)), ("<=", numBoolBinOp (<=)), ("&&", boolBoolBinOp (&&)), ("||", boolBoolBinOp (||)), ("string=?", strBoolBinop (==)), ("string<?", strBoolBinop (<)), ("string<=?", strBoolBinop (<=)), ("string>=?", strBoolBinop (>=)) ] apply :: String -> [LispVal] -> ThrowsError LispVal apply func args = maybe (throwError $ NotFunction "Unrecognized primitive function args" func) ($ args) $ lookup func primitives eval :: LispVal -> ThrowsError LispVal eval val@(String _) = return val eval val@(Number _) = return val eval val@(Bool _) = return val eval (List [Atom "quote", val]) = return val eval (List [Atom "if", pred, conseq, alt]) = do b <- eval pred case b of Bool False -> eval alt otherwise -> eval conseq eval (List (Atom func : args)) = mapM eval args >>= apply func eval badForm = throwError $ BadSpecialForm "Unrecognized special form" badForm readExpr :: String -> ThrowsError LispVal readExpr input = case parse parseExpr "lisp" input of Left err -> throwError . Parser $ err Right val -> return val main :: IO () main = do args <- getArgs evaled <- return . liftM show $ readExpr (args !! 0) >>= eval putStrLn . extractError . trapError $ evaled
lifengsun/haskell-exercise
scheme/05/conditionalparser.hs
gpl-3.0
6,880
0
12
2,111
2,227
1,146
1,081
174
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.ProximityBeacon.Beacons.Update -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates the information about the specified beacon. **Any field that you -- do not populate in the submitted beacon will be permanently erased**, so -- you should follow the \"read, modify, write\" pattern to avoid -- inadvertently destroying data. Changes to the beacon status via this -- method will be silently ignored. To update beacon status, use the -- separate methods on this API for activation, deactivation, and -- decommissioning. Authenticate using an [OAuth access -- token](https:\/\/developers.google.com\/identity\/protocols\/OAuth2) -- from a signed-in user with **Is owner** or **Can edit** permissions in -- the Google Developers Console project. -- -- /See:/ <https://developers.google.com/beacons/proximity/ Proximity Beacon API Reference> for @proximitybeacon.beacons.update@. module Network.Google.Resource.ProximityBeacon.Beacons.Update ( -- * REST Resource BeaconsUpdateResource -- * Creating a Request , beaconsUpdate , BeaconsUpdate -- * Request Lenses , buXgafv , buUploadProtocol , buAccessToken , buBeaconName , buUploadType , buPayload , buProjectId , buCallback ) where import Network.Google.Prelude import Network.Google.ProximityBeacon.Types -- | A resource alias for @proximitybeacon.beacons.update@ method which the -- 'BeaconsUpdate' request conforms to. type BeaconsUpdateResource = "v1beta1" :> Capture "beaconName" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "projectId" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Beacon :> Put '[JSON] Beacon -- | Updates the information about the specified beacon. **Any field that you -- do not populate in the submitted beacon will be permanently erased**, so -- you should follow the \"read, modify, write\" pattern to avoid -- inadvertently destroying data. Changes to the beacon status via this -- method will be silently ignored. To update beacon status, use the -- separate methods on this API for activation, deactivation, and -- decommissioning. Authenticate using an [OAuth access -- token](https:\/\/developers.google.com\/identity\/protocols\/OAuth2) -- from a signed-in user with **Is owner** or **Can edit** permissions in -- the Google Developers Console project. -- -- /See:/ 'beaconsUpdate' smart constructor. data BeaconsUpdate = BeaconsUpdate' { _buXgafv :: !(Maybe Xgafv) , _buUploadProtocol :: !(Maybe Text) , _buAccessToken :: !(Maybe Text) , _buBeaconName :: !Text , _buUploadType :: !(Maybe Text) , _buPayload :: !Beacon , _buProjectId :: !(Maybe Text) , _buCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BeaconsUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'buXgafv' -- -- * 'buUploadProtocol' -- -- * 'buAccessToken' -- -- * 'buBeaconName' -- -- * 'buUploadType' -- -- * 'buPayload' -- -- * 'buProjectId' -- -- * 'buCallback' beaconsUpdate :: Text -- ^ 'buBeaconName' -> Beacon -- ^ 'buPayload' -> BeaconsUpdate beaconsUpdate pBuBeaconName_ pBuPayload_ = BeaconsUpdate' { _buXgafv = Nothing , _buUploadProtocol = Nothing , _buAccessToken = Nothing , _buBeaconName = pBuBeaconName_ , _buUploadType = Nothing , _buPayload = pBuPayload_ , _buProjectId = Nothing , _buCallback = Nothing } -- | V1 error format. buXgafv :: Lens' BeaconsUpdate (Maybe Xgafv) buXgafv = lens _buXgafv (\ s a -> s{_buXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). buUploadProtocol :: Lens' BeaconsUpdate (Maybe Text) buUploadProtocol = lens _buUploadProtocol (\ s a -> s{_buUploadProtocol = a}) -- | OAuth access token. buAccessToken :: Lens' BeaconsUpdate (Maybe Text) buAccessToken = lens _buAccessToken (\ s a -> s{_buAccessToken = a}) -- | Resource name of this beacon. A beacon name has the format -- \"beacons\/N!beaconId\" where the beaconId is the base16 ID broadcast by -- the beacon and N is a code for the beacon\'s type. Possible values are -- \`3\` for Eddystone, \`1\` for iBeacon, or \`5\` for AltBeacon. This -- field must be left empty when registering. After reading a beacon, -- clients can use the name for future operations. buBeaconName :: Lens' BeaconsUpdate Text buBeaconName = lens _buBeaconName (\ s a -> s{_buBeaconName = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). buUploadType :: Lens' BeaconsUpdate (Maybe Text) buUploadType = lens _buUploadType (\ s a -> s{_buUploadType = a}) -- | Multipart request metadata. buPayload :: Lens' BeaconsUpdate Beacon buPayload = lens _buPayload (\ s a -> s{_buPayload = a}) -- | The project id of the beacon to update. If the project id is not -- specified then the project making the request is used. The project id -- must match the project that owns the beacon. Optional. buProjectId :: Lens' BeaconsUpdate (Maybe Text) buProjectId = lens _buProjectId (\ s a -> s{_buProjectId = a}) -- | JSONP buCallback :: Lens' BeaconsUpdate (Maybe Text) buCallback = lens _buCallback (\ s a -> s{_buCallback = a}) instance GoogleRequest BeaconsUpdate where type Rs BeaconsUpdate = Beacon type Scopes BeaconsUpdate = '["https://www.googleapis.com/auth/userlocation.beacon.registry"] requestClient BeaconsUpdate'{..} = go _buBeaconName _buXgafv _buUploadProtocol _buAccessToken _buUploadType _buProjectId _buCallback (Just AltJSON) _buPayload proximityBeaconService where go = buildClient (Proxy :: Proxy BeaconsUpdateResource) mempty
brendanhay/gogol
gogol-proximitybeacon/gen/Network/Google/Resource/ProximityBeacon/Beacons/Update.hs
mpl-2.0
6,826
0
17
1,470
879
521
358
120
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.Disks.AggregatedList -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves an aggregated list of persistent disks. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.disks.aggregatedList@. module Network.Google.Resource.Compute.Disks.AggregatedList ( -- * REST Resource DisksAggregatedListResource -- * Creating a Request , disksAggregatedList , DisksAggregatedList -- * Request Lenses , dalIncludeAllScopes , dalReturnPartialSuccess , dalOrderBy , dalProject , dalFilter , dalPageToken , dalMaxResults ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.disks.aggregatedList@ method which the -- 'DisksAggregatedList' request conforms to. type DisksAggregatedListResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "aggregated" :> "disks" :> QueryParam "includeAllScopes" Bool :> QueryParam "returnPartialSuccess" Bool :> QueryParam "orderBy" Text :> QueryParam "filter" Text :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] DiskAggregatedList -- | Retrieves an aggregated list of persistent disks. -- -- /See:/ 'disksAggregatedList' smart constructor. data DisksAggregatedList = DisksAggregatedList' { _dalIncludeAllScopes :: !(Maybe Bool) , _dalReturnPartialSuccess :: !(Maybe Bool) , _dalOrderBy :: !(Maybe Text) , _dalProject :: !Text , _dalFilter :: !(Maybe Text) , _dalPageToken :: !(Maybe Text) , _dalMaxResults :: !(Textual Word32) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DisksAggregatedList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dalIncludeAllScopes' -- -- * 'dalReturnPartialSuccess' -- -- * 'dalOrderBy' -- -- * 'dalProject' -- -- * 'dalFilter' -- -- * 'dalPageToken' -- -- * 'dalMaxResults' disksAggregatedList :: Text -- ^ 'dalProject' -> DisksAggregatedList disksAggregatedList pDalProject_ = DisksAggregatedList' { _dalIncludeAllScopes = Nothing , _dalReturnPartialSuccess = Nothing , _dalOrderBy = Nothing , _dalProject = pDalProject_ , _dalFilter = Nothing , _dalPageToken = Nothing , _dalMaxResults = 500 } -- | Indicates whether every visible scope for each scope type (zone, region, -- global) should be included in the response. For new resource types added -- after this field, the flag has no effect as new resource types will -- always include every visible scope for each scope type in response. For -- resource types which predate this field, if this flag is omitted or -- false, only scopes of the scope types where the resource type is -- expected to be found will be included. dalIncludeAllScopes :: Lens' DisksAggregatedList (Maybe Bool) dalIncludeAllScopes = lens _dalIncludeAllScopes (\ s a -> s{_dalIncludeAllScopes = a}) -- | Opt-in for partial success behavior which provides partial results in -- case of failure. The default value is false. dalReturnPartialSuccess :: Lens' DisksAggregatedList (Maybe Bool) dalReturnPartialSuccess = lens _dalReturnPartialSuccess (\ s a -> s{_dalReturnPartialSuccess = a}) -- | Sorts list results by a certain order. By default, results are returned -- in alphanumerical order based on the resource name. You can also sort -- results in descending order based on the creation timestamp using -- \`orderBy=\"creationTimestamp desc\"\`. This sorts results based on the -- \`creationTimestamp\` field in reverse chronological order (newest -- result first). Use this to sort resources like operations so that the -- newest operation is returned first. Currently, only sorting by \`name\` -- or \`creationTimestamp desc\` is supported. dalOrderBy :: Lens' DisksAggregatedList (Maybe Text) dalOrderBy = lens _dalOrderBy (\ s a -> s{_dalOrderBy = a}) -- | Project ID for this request. dalProject :: Lens' DisksAggregatedList Text dalProject = lens _dalProject (\ s a -> s{_dalProject = a}) -- | A filter expression that filters resources listed in the response. The -- expression must specify the field name, a comparison operator, and the -- value that you want to use for filtering. The value must be a string, a -- number, or a boolean. The comparison operator must be either \`=\`, -- \`!=\`, \`>\`, or \`\<\`. For example, if you are filtering Compute -- Engine instances, you can exclude instances named \`example-instance\` -- by specifying \`name != example-instance\`. You can also filter nested -- fields. For example, you could specify \`scheduling.automaticRestart = -- false\` to include instances only if they are not scheduled for -- automatic restarts. You can use filtering on nested fields to filter -- based on resource labels. To filter on multiple expressions, provide -- each separate expression within parentheses. For example: \`\`\` -- (scheduling.automaticRestart = true) (cpuPlatform = \"Intel Skylake\") -- \`\`\` By default, each expression is an \`AND\` expression. However, -- you can include \`AND\` and \`OR\` expressions explicitly. For example: -- \`\`\` (cpuPlatform = \"Intel Skylake\") OR (cpuPlatform = \"Intel -- Broadwell\") AND (scheduling.automaticRestart = true) \`\`\` dalFilter :: Lens' DisksAggregatedList (Maybe Text) dalFilter = lens _dalFilter (\ s a -> s{_dalFilter = a}) -- | Specifies a page token to use. Set \`pageToken\` to the -- \`nextPageToken\` returned by a previous list request to get the next -- page of results. dalPageToken :: Lens' DisksAggregatedList (Maybe Text) dalPageToken = lens _dalPageToken (\ s a -> s{_dalPageToken = a}) -- | The maximum number of results per page that should be returned. If the -- number of available results is larger than \`maxResults\`, Compute -- Engine returns a \`nextPageToken\` that can be used to get the next page -- of results in subsequent list requests. Acceptable values are \`0\` to -- \`500\`, inclusive. (Default: \`500\`) dalMaxResults :: Lens' DisksAggregatedList Word32 dalMaxResults = lens _dalMaxResults (\ s a -> s{_dalMaxResults = a}) . _Coerce instance GoogleRequest DisksAggregatedList where type Rs DisksAggregatedList = DiskAggregatedList type Scopes DisksAggregatedList = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient DisksAggregatedList'{..} = go _dalProject _dalIncludeAllScopes _dalReturnPartialSuccess _dalOrderBy _dalFilter _dalPageToken (Just _dalMaxResults) (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy DisksAggregatedListResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/Disks/AggregatedList.hs
mpl-2.0
8,021
0
20
1,744
842
503
339
121
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Plus.People.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- List all of the people in the specified collection. -- -- /See:/ <https://developers.google.com/+/api/ Google+ API Reference> for @plus.people.list@. module Network.Google.Resource.Plus.People.List ( -- * REST Resource PeopleListResource -- * Creating a Request , peopleList , PeopleList -- * Request Lenses , plOrderBy , plCollection , plUserId , plPageToken , plMaxResults ) where import Network.Google.Plus.Types import Network.Google.Prelude -- | A resource alias for @plus.people.list@ method which the -- 'PeopleList' request conforms to. type PeopleListResource = "plus" :> "v1" :> "people" :> Capture "userId" Text :> "people" :> Capture "collection" PeopleListCollection :> QueryParam "orderBy" PeopleListOrderBy :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] PeopleFeed -- | List all of the people in the specified collection. -- -- /See:/ 'peopleList' smart constructor. data PeopleList = PeopleList' { _plOrderBy :: !(Maybe PeopleListOrderBy) , _plCollection :: !PeopleListCollection , _plUserId :: !Text , _plPageToken :: !(Maybe Text) , _plMaxResults :: !(Textual Word32) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PeopleList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plOrderBy' -- -- * 'plCollection' -- -- * 'plUserId' -- -- * 'plPageToken' -- -- * 'plMaxResults' peopleList :: PeopleListCollection -- ^ 'plCollection' -> Text -- ^ 'plUserId' -> PeopleList peopleList pPlCollection_ pPlUserId_ = PeopleList' { _plOrderBy = Nothing , _plCollection = pPlCollection_ , _plUserId = pPlUserId_ , _plPageToken = Nothing , _plMaxResults = 100 } -- | The order to return people in. plOrderBy :: Lens' PeopleList (Maybe PeopleListOrderBy) plOrderBy = lens _plOrderBy (\ s a -> s{_plOrderBy = a}) -- | The collection of people to list. plCollection :: Lens' PeopleList PeopleListCollection plCollection = lens _plCollection (\ s a -> s{_plCollection = a}) -- | Get the collection of people for the person identified. Use \"me\" to -- indicate the authenticated user. plUserId :: Lens' PeopleList Text plUserId = lens _plUserId (\ s a -> s{_plUserId = a}) -- | The continuation token, which is used to page through large result sets. -- To get the next page of results, set this parameter to the value of -- \"nextPageToken\" from the previous response. plPageToken :: Lens' PeopleList (Maybe Text) plPageToken = lens _plPageToken (\ s a -> s{_plPageToken = a}) -- | The maximum number of people to include in the response, which is used -- for paging. For any response, the actual number returned might be less -- than the specified maxResults. plMaxResults :: Lens' PeopleList Word32 plMaxResults = lens _plMaxResults (\ s a -> s{_plMaxResults = a}) . _Coerce instance GoogleRequest PeopleList where type Rs PeopleList = PeopleFeed type Scopes PeopleList = '["https://www.googleapis.com/auth/plus.login", "https://www.googleapis.com/auth/plus.me"] requestClient PeopleList'{..} = go _plUserId _plCollection _plOrderBy _plPageToken (Just _plMaxResults) (Just AltJSON) plusService where go = buildClient (Proxy :: Proxy PeopleListResource) mempty
brendanhay/gogol
gogol-plus/gen/Network/Google/Resource/Plus/People/List.hs
mpl-2.0
4,452
0
17
1,057
639
376
263
92
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.TargetPools.SetBackup -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Changes a backup target pool\'s configurations. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.targetPools.setBackup@. module Network.Google.Resource.Compute.TargetPools.SetBackup ( -- * REST Resource TargetPoolsSetBackupResource -- * Creating a Request , targetPoolsSetBackup , TargetPoolsSetBackup -- * Request Lenses , tpsbRequestId , tpsbProject , tpsbTargetPool , tpsbPayload , tpsbFailoverRatio , tpsbRegion ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.targetPools.setBackup@ method which the -- 'TargetPoolsSetBackup' request conforms to. type TargetPoolsSetBackupResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "regions" :> Capture "region" Text :> "targetPools" :> Capture "targetPool" Text :> "setBackup" :> QueryParam "requestId" Text :> QueryParam "failoverRatio" (Textual Double) :> QueryParam "alt" AltJSON :> ReqBody '[JSON] TargetReference :> Post '[JSON] Operation -- | Changes a backup target pool\'s configurations. -- -- /See:/ 'targetPoolsSetBackup' smart constructor. data TargetPoolsSetBackup = TargetPoolsSetBackup' { _tpsbRequestId :: !(Maybe Text) , _tpsbProject :: !Text , _tpsbTargetPool :: !Text , _tpsbPayload :: !TargetReference , _tpsbFailoverRatio :: !(Maybe (Textual Double)) , _tpsbRegion :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TargetPoolsSetBackup' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tpsbRequestId' -- -- * 'tpsbProject' -- -- * 'tpsbTargetPool' -- -- * 'tpsbPayload' -- -- * 'tpsbFailoverRatio' -- -- * 'tpsbRegion' targetPoolsSetBackup :: Text -- ^ 'tpsbProject' -> Text -- ^ 'tpsbTargetPool' -> TargetReference -- ^ 'tpsbPayload' -> Text -- ^ 'tpsbRegion' -> TargetPoolsSetBackup targetPoolsSetBackup pTpsbProject_ pTpsbTargetPool_ pTpsbPayload_ pTpsbRegion_ = TargetPoolsSetBackup' { _tpsbRequestId = Nothing , _tpsbProject = pTpsbProject_ , _tpsbTargetPool = pTpsbTargetPool_ , _tpsbPayload = pTpsbPayload_ , _tpsbFailoverRatio = Nothing , _tpsbRegion = pTpsbRegion_ } -- | An optional request ID to identify requests. Specify a unique request ID -- so that if you must retry your request, the server will know to ignore -- the request if it has already been completed. For example, consider a -- situation where you make an initial request and the request times out. -- If you make the request again with the same request ID, the server can -- check if original operation with the same request ID was received, and -- if so, will ignore the second request. This prevents clients from -- accidentally creating duplicate commitments. The request ID must be a -- valid UUID with the exception that zero UUID is not supported -- (00000000-0000-0000-0000-000000000000). tpsbRequestId :: Lens' TargetPoolsSetBackup (Maybe Text) tpsbRequestId = lens _tpsbRequestId (\ s a -> s{_tpsbRequestId = a}) -- | Project ID for this request. tpsbProject :: Lens' TargetPoolsSetBackup Text tpsbProject = lens _tpsbProject (\ s a -> s{_tpsbProject = a}) -- | Name of the TargetPool resource to set a backup pool for. tpsbTargetPool :: Lens' TargetPoolsSetBackup Text tpsbTargetPool = lens _tpsbTargetPool (\ s a -> s{_tpsbTargetPool = a}) -- | Multipart request metadata. tpsbPayload :: Lens' TargetPoolsSetBackup TargetReference tpsbPayload = lens _tpsbPayload (\ s a -> s{_tpsbPayload = a}) -- | New failoverRatio value for the target pool. tpsbFailoverRatio :: Lens' TargetPoolsSetBackup (Maybe Double) tpsbFailoverRatio = lens _tpsbFailoverRatio (\ s a -> s{_tpsbFailoverRatio = a}) . mapping _Coerce -- | Name of the region scoping this request. tpsbRegion :: Lens' TargetPoolsSetBackup Text tpsbRegion = lens _tpsbRegion (\ s a -> s{_tpsbRegion = a}) instance GoogleRequest TargetPoolsSetBackup where type Rs TargetPoolsSetBackup = Operation type Scopes TargetPoolsSetBackup = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient TargetPoolsSetBackup'{..} = go _tpsbProject _tpsbRegion _tpsbTargetPool _tpsbRequestId _tpsbFailoverRatio (Just AltJSON) _tpsbPayload computeService where go = buildClient (Proxy :: Proxy TargetPoolsSetBackupResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/TargetPools/SetBackup.hs
mpl-2.0
5,765
0
20
1,368
735
432
303
113
1
-- -- Copyright 2017-2018 Azad Bolour -- Licensed under GNU Affero General Public License v3.0 - -- https://github.com/azadbolour/boardgame/blob/master/LICENSE.md -- module Bolour.Util.HttpUtil ( mkHttpHeader , defaultOptionsHeaders ) where import qualified Data.CaseInsensitive as CI import qualified Data.ByteString.Char8 as BC import Network.HTTP.Types.Header (Header, ResponseHeaders) -- | Headers for response to options request. defaultOptionsHeaders :: ResponseHeaders defaultOptionsHeaders = mkHttpResponseHeaders [ ("Access-Control-Allow-Origin", "*") , ("Access-Control-Allow-Headers", "authorization") , ("Access-Control-Allow-Headers", "credentials") , ("Access-Control-Allow-Headers", "mode") , ("Access-Control-Allow-Headers", "accept") , ("Access-Control-Allow-Headers", "content-type") ] -- | Convert headers represented as string name-value pairs to header data structures. mkHttpResponseHeaders :: [(String, String)] -> ResponseHeaders mkHttpResponseHeaders stringHeaderList = mkHttpHeader <$> stringHeaderList -- | Convert a header represented as a string name-value pair to a header data structure. mkHttpHeader :: (String, String) -> Header mkHttpHeader (name, value) = (CI.mk $ BC.pack name, BC.pack value)
azadbolour/boardgame
haskell-server/src/Bolour/Util/HttpUtil.hs
agpl-3.0
1,274
0
8
176
203
129
74
18
1
-- Copyright 2011 The Text.XHtml Authors. -- -- 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. -- -- Contributors: -- Ian Lynagh <[email protected]> -- | Table combinators for XHTML. module Text.XHtml.Table (HtmlTable, HTMLTABLE(..), (</>), above, (<->), beside, aboves, besides, simpleTable) where import Text.XHtml.Internals import Text.XHtml.Strict.Elements import Text.XHtml.Strict.Attributes import qualified Text.XHtml.BlockTable as BT infixr 3 </> -- combining table cells infixr 4 <-> -- combining table cells -- -- * Tables -- class HTMLTABLE ht where cell :: ht -> HtmlTable instance HTMLTABLE HtmlTable where cell = id instance HTMLTABLE Html where cell h = let cellFn x y = h ! (add x colspan $ add y rowspan $ []) add 1 _ rest = rest add n fn rest = fn n : rest r = BT.single cellFn in mkHtmlTable r -- | We internally represent the Cell inside a Table with an -- object of the type -- -- > Int -> Int -> Html -- -- When we render it later, we find out how many columns -- or rows this cell will span over, and can -- include the correct colspan\/rowspan command. newtype HtmlTable = HtmlTable (BT.BlockTable (Int -> Int -> Html)) mkHtmlTable :: BT.BlockTable (Int -> Int -> Html) -> HtmlTable mkHtmlTable r = HtmlTable r -- We give both infix and nonfix, take your pick. -- Notice that there is no concept of a row/column -- of zero items. (</>),above,(<->),beside :: (HTMLTABLE ht1,HTMLTABLE ht2) => ht1 -> ht2 -> HtmlTable above a b = combine BT.above (cell a) (cell b) (</>) = above beside a b = combine BT.beside (cell a) (cell b) (<->) = beside combine :: (BT.BlockTable (Int -> Int -> Html) -> BT.BlockTable (Int -> Int -> Html) -> BT.BlockTable (Int -> Int -> Html)) -> HtmlTable -> HtmlTable -> HtmlTable combine fn (HtmlTable a) (HtmlTable b) = mkHtmlTable (a `fn` b) -- Both aboves and besides presume a non-empty list. -- here is no concept of a empty row or column in these -- table combinators. aboves :: (HTMLTABLE ht) => [ht] -> HtmlTable aboves [] = error "aboves []" aboves xs = foldr1 (</>) (map cell xs) besides :: (HTMLTABLE ht) => [ht] -> HtmlTable besides [] = error "besides []" besides xs = foldr1 (<->) (map cell xs) -- | renderTable takes the HtmlTable, and renders it back into -- and Html object. renderTable :: BT.BlockTable (Int -> Int -> Html) -> Html renderTable theTable = concatHtml [tr << [theCell x y | (theCell,(x,y)) <- theRow ] | theRow <- BT.getMatrix theTable] instance HTML HtmlTable where toHtml (HtmlTable tab) = renderTable tab instance Show HtmlTable where showsPrec _ (HtmlTable tab) = shows (renderTable tab) -- | If you can't be bothered with the above, then you -- can build simple tables with simpleTable. -- Just provide the attributes for the whole table, -- attributes for the cells (same for every cell), -- and a list of lists of cell contents, -- and this function will build the table for you. -- It does presume that all the lists are non-empty, -- and there is at least one list. -- -- Different length lists means that the last cell -- gets padded. If you want more power, then -- use the system above, or build tables explicitly. simpleTable :: [HtmlAttr] -> [HtmlAttr] -> [[Html]] -> Html simpleTable attr cellAttr lst = table ! attr << (aboves . map (besides . map ((td ! cellAttr) . toHtml)) ) lst
robinbb/hs-text-xhtml
Text/XHtml/Table.hs
apache-2.0
4,193
0
16
1,077
898
507
391
60
1
pot x y = if y > 0 then x * ( pot x (y-1) ) else 1
WillianLauber/haskell
pot.hs
apache-2.0
54
4
10
21
46
24
22
2
2
module Lab4 where import SetOrd import Data.List import System.Random import Test.Hspec import Test.QuickCheck -- run all using runAll = do runallTestEx4 runallTestEx5 main runallTestEx7 {- Ex.3 - Random set generation (0.5 hour) -} getRandomSet :: IO () getRandomSet = do gen <- newStdGen print $ getRndSet 100 1000 gen getRndSet :: Int -> Int -> StdGen -> Set Int getRndSet n r g = list2set $ getRndList n r g -- this function is also used in Ex.7 getRndList :: Int -> Int -> StdGen -> [Int] getRndList n r g = take n (randomRs (0, r) g :: [Int]) qcEqualSets = ((\s -> list2set s == list2set s) :: [Int] -> Bool) qcUniqueElems = ((\s -> uniqueList $ list2set s):: [Int] -> Bool) uniqueList :: Eq a => Set a -> Bool uniqueList (Set []) = True uniqueList (Set xs) = length (nub xs) == length xs --quickCheck qcEqualSets --> 100 tests passed! --quickCheck qcUniqueElems --> 100 tests passed! {- Ex.4 Set operations (2 hours) -} test1 = Set [1,2,3,4,5,6,7,8] test2 = Set [6,7,8,9,10,11] -- please use this to check all set operations runallTestEx4 = do print "run test intersect" quickCheck qcIntersectSet print "run test difference" quickCheck qcDiffSet print "run test union already defined" quickCheck qcUnionSet quickCheck qcDuplicates print "run test union us" quickCheck qcUnionSetUs quickCheck qcDuplicatesUs {- =================================================== intersection of set1 and set2: all elements in set1 that are contained in set2 -} intersectSet :: (Ord a, Eq a) => Set a -> Set a -> Set a intersectSet (Set []) _ = emptySet intersectSet (Set (x:xs)) set2 = if inSet x set2 then insertSet x (intersectSet (Set xs) set2) else intersectSet (Set xs) set2 --intersection test --quickCheck qcIntersectSet --> 100 tests passed! qcIntersectSet = ((\s t -> isIntersection (list2set s) (list2set t)) :: [Int] -> [Int] -> Bool) isIntersection :: (Ord a, Eq a) => Set a -> Set a -> Bool isIntersection set1 set2 = (subSet s3 set1) && (subSet s3 set2) && (matchElems set1 set2 s3) where s3 = intersectSet set1 set2 matchElems :: (Ord a, Eq a) => Set a -> Set a -> Set a -> Bool matchElems _ _ (Set []) = True matchElems (Set [x]) set2 iSet = if (inSet x set2) then (inSet x iSet) else True matchElems (Set (x:xs)) set2 iSet = if (inSet x set2) then (inSet x iSet) && (matchElems (Set xs) set2 iSet) else matchElems (Set xs) set2 iSet {- =================================================== difference of set1 and set2: set1 - (set1 intersect set2) -} diffSet :: (Ord a, Eq a) => Set a -> Set a -> Set a diffSet (Set []) _ = emptySet diffSet set1 (Set []) = set1 diffSet set1 set2 = removeSet (intersectSet set1 set2) set1 --remove elements contained in set1 from set2 removeSet :: (Ord a, Eq a) => Set a -> Set a -> Set a removeSet (Set []) set2 = set2 removeSet (Set (x:xs)) set2 = removeSet (Set xs) ( deleteSet x set2) -- difference test -- quickCheck qcDiffSet --> 100 tests passed! qcDiffSet = ((\s t -> isDifferent (diffSet (list2set s) (list2set t)) (list2set t)) :: [Int] -> [Int] -> Bool) isDifferent :: (Ord a, Eq a) => Set a -> Set a -> Bool isDifferent (Set []) set2 = True isDifferent (Set (x:xs)) set2 = (not (inSet x set2)) && ( isDifferent (Set xs) set2) {- unionSet is already defined in the SetOrd, so we skipped the implementation. We have implemented the following QuickCheck test when checking manually though, it failed at [(0,1),(0,0)] so we have implemented a new version SetOrd.unionSet appears not to work on the following: >> let a = [(0,1), (0,0)] >> unionSet (Set a) (Set a) << {(0,0),(0,1),(0,0)} -} qcUnionSet = (\s t -> (and [((inSet x (Set s)) && (inSet x (Set t)) && (inSet x (unionSet (Set s) (Set t)))) || not ((inSet x (Set s)) && (inSet x (Set t))) | x <- s, y <- t ]) ) :: [Int] -> [Int] -> Bool qcDuplicates = (\s t -> checkDuplicate (unionSet (list2set s) (list2set t))) :: [Int] -> [Int] -> Bool qcUnionSetUs = (\s t -> (and [((inSet x (Set s)) && (inSet x (Set t)) && (inSet x (setUnion (Set s) (Set t)))) || not ((inSet x (Set s)) && (inSet x (Set t))) | x <- s, y <- t ]) ) :: [Int] -> [Int] -> Bool qcDuplicatesUs = (\s t -> checkDuplicate (setUnion (list2set s) (list2set t))) :: [Int] -> [Int] -> Bool checkDuplicate (Set []) = True checkDuplicate (Set (x:xs)) = not (elem x xs) && checkDuplicate (Set xs) setUnion (Set s) (Set t) = joinSets (Set (nub s)) (Set (nub t)) emptySet -- helper union joinSets (Set []) (Set []) u = u joinSets (Set (s:ss)) (Set []) u = joinSets (Set ss) emptySet (insertSet s u) joinSets s all@(Set (t:ts)) u = joinSets s (Set ts) (insertSet t u) {- Ex.5 Relations (1.5 hour) -} type Rel a = [(a,a)] infixr 5 @@ (@@) :: Eq a => Rel a -> Rel a -> Rel a r @@ s = nub [(x,z) | (x,y) <- r, (w,z) <- s, y == w] trClos :: Ord a => Rel a -> Rel a trClos r = transClosure r r -- uses the property that the union of all the (ra @@ sa) should give a transitive closure, and that the transitive closure has been reached -- when no other element is added to the relation transClosure :: Ord a => Rel a -> Rel a -> Rel a transClosure _ [] = [] transClosure [] _ = [] transClosure ra sa = if diffSet (Set t) (setUnion (Set sa) (Set ra) ) == emptySet then t else transClosure ra t where r' = ra @@ sa Set t = (setUnion (Set ra) (Set r')) toRel :: Set (a, a) -> [(a, a)] toRel (Set xs) = xs --sort relations by first element srtRel :: Ord a => Rel a -> Rel a srtRel r = sortBy (\x y -> compare (fst x) (fst y)) r test3 = [(1,2),(2,3),(3,4)] runallTestEx5 = do print "Transitive closure of [(1,2),(2,3),(3,4)]" print $ trClos test3 -- trClos test3 : [(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)] {- Ex.6 Hspec specification (0.5 hour) -} main :: IO () main = hspec $ do describe "Lab4.trClos" $ do it "returns a list with the given relation when given a list with one relation" $ trClos [(0,1)] `shouldBe` [(0,1)] it "returns a relation that is transitive" $ do let r = trClos [(1,2),(2,3),(3,4)] isTransitive (trClos r) it "returns the transitive closure on the given list of binary relations" $ trClos [(1,2),(2,3),(3,4)] `shouldBe` [(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)] --it "returns a empty list when given an empty list" {- Ex.7 Testing trClos (1.5 hours) -} -- run with this runallTestEx7 = do print "using quickcheck" quickCheck qcTrClos print "using own random generator" testTrClos -- for each pair in r, check if it is transitive with any other pair it should be transitive with isTransitive :: Ord a => Rel a -> Bool isTransitive [] = True isTransitive r = and [ hasTrans (t,s) r | (t,s) <- r ] -- for (x,y) in r match on (u,v) in r so that y == u, then look for an (x,v) hasTrans :: Ord a => (a,a) -> Rel a -> Bool hasTrans (x,y) r = and [ elem (x,v) r | (u,v) <- r, y == u] -- check if R is subset of trClos of R subRel :: Ord a => Rel a -> Rel a -> Bool subRel set1 set2 = and [ elem (x,y) set2 | (x,y) <- set1 ] -- main test function testClosureTr :: Ord a => Rel a -> Bool testClosureTr r = isTransitive r' && subRel r r' where r' = trClos r -- own implementation: random relations testTrClos :: IO() testTrClos = do gen <- newStdGen print $ testClosureTr $ getRandomR gen getRandomR :: StdGen -> [(Int, Int)] getRandomR g = zip (getRndList 100 100 g) (getRndList 100 100 g) --quickCheck function qcTrClos = ((\z -> testClosureTr z) :: [(Int, Int)] -> Bool ) ---- BONUS (5 min) {- if we define the value that we put in as v then we can see that the formula is (x+v/x)/2. When x=sqrt(v) then v/x=x, so in that case the output is (x+x)/2=x, which makes the if statement get into the if clause instead of the else clause and the program terminates. As written earlier, in this case x=sqrt(v). -}
bartolkaruza/software-testing-2014-group-W1
week4/week4-exercises.hs
apache-2.0
8,226
24
19
2,073
3,099
1,616
1,483
131
3
module Valuable where import Prelude data Value = Min | Value Integer | Max deriving (Show, Ord, Eq) class Valuable a where value :: a -> Value
MichaelBaker/haskell-tictactoe
src/Valuable.hs
bsd-2-clause
149
0
7
32
55
31
24
5
0
-- | Program to replace HTML tags by whitespace -- -- This program was originally contributed by Petr Prokhorenkov. -- -- Tested in this benchmark: -- -- * Reading the file -- -- * Replacing text between HTML tags (<>) with whitespace -- -- * Writing back to a handle -- {-# OPTIONS_GHC -fspec-constr-count=5 #-} module Benchmarks.Programs.StripTags ( benchmark ) where import Criterion (Benchmark, bgroup, bench, whnfIO) import Data.List (mapAccumL) import System.IO (Handle, hPutStr) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.IO as T benchmark :: FilePath -> Handle -> Benchmark benchmark i o = bgroup "StripTags" [ bench "String" $ whnfIO $ readFile i >>= hPutStr o . string , bench "ByteString" $ whnfIO $ B.readFile i >>= B.hPutStr o . byteString , bench "Text" $ whnfIO $ T.readFile i >>= T.hPutStr o . text , bench "TextByteString" $ whnfIO $ B.readFile i >>= B.hPutStr o . T.encodeUtf8 . text . T.decodeUtf8 ] string :: String -> String string = snd . mapAccumL step 0 text :: T.Text -> T.Text text = snd . T.mapAccumL step 0 byteString :: B.ByteString -> B.ByteString byteString = snd . BC.mapAccumL step 0 step :: Int -> Char -> (Int, Char) step d c | d > 0 || d' > 0 = (d', ' ') | otherwise = (d', c) where d' = d + depth c depth '>' = 1 depth '<' = -1 depth _ = 0
bgamari/text
benchmarks/haskell/Benchmarks/Programs/StripTags.hs
bsd-2-clause
1,493
0
13
328
461
255
206
32
3
{-# LANGUAGE ScopedTypeVariables #-} module Main where import Control.Applicative hiding (Alternative(..), many) import Control.Monad.State.Strict import Control.Exception hiding (try) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe import Data.List import Data.Int import Data.Word import Data.Char import Text.ParserCombinators.Parsec import System.IO import System.Posix.DynamicLinker import Foreign.C.Types import Foreign.Ptr import Foreign.LibFFI import Prelude hiding (catch) pRead :: Read a => CharParser st a pRead = do s <- getInput case reads s of [] -> fail "no reads result" [(a, s')] -> setInput s' >> return a _ -> fail "ambiguous reads result" data Val = I CInt | IL CLong | I8 Int8 | I16 Int16 | I32 Int32 | I64 Int64 | U CUInt | UL CULong | U8 Word8 | U16 Word16 | U32 Word32 | U64 Word64 | Z CSize | F CFloat | D CDouble | P (Ptr ()) | S String deriving (Eq, Show) valToArg val = case val of I x -> argCInt x IL x -> argCLong x I8 x -> argInt8 x I16 x -> argInt16 x I32 x -> argInt32 x I64 x -> argInt64 x U x -> argCUInt x UL x -> argCULong x U8 x -> argWord8 x U16 x -> argWord16 x U32 x -> argWord32 x U64 x -> argWord64 x Z x -> argCSize x F x -> argCFloat x D x -> argCDouble x P x -> argPtr x S x -> argString x pIdent :: CharParser st String pIdent = liftM2 (:) (char '_' <|> letter) (many $ char '_' <|> alphaNum) <?> "identifier" pArg :: CharParser (Map String Val) Val pArg = liftM S pRead <|> do i <- pRead :: CharParser st Integer t <- many alphaNum case t of "" -> return $ I $ fromIntegral i "i" -> return $ I $ fromIntegral i "l" -> return $ IL $ fromIntegral i "i8" -> return $ I8 $ fromIntegral i "i16" -> return $ I16 $ fromIntegral i "i32" -> return $ I32 $ fromIntegral i "i64" -> return $ I64 $ fromIntegral i "u" -> return $ U $ fromIntegral i "ul" -> return $ UL $ fromIntegral i "u8" -> return $ U8 $ fromIntegral i "u16" -> return $ U16 $ fromIntegral i "u32" -> return $ U32 $ fromIntegral i "u64" -> return $ U64 $ fromIntegral i "p" -> return $ P $ plusPtr nullPtr $ fromIntegral i "z" -> return $ Z $ fromIntegral i _ -> fail "invalid type" <|> do x <- pRead :: CharParser st Double t <- many alphaNum case t of "" -> return $ D $ realToFrac x "s" -> return $ F $ realToFrac x _ -> fail "invalid type" <|> do ident <- pIdent env <- getState case Map.lookup ident env of Nothing -> fail "no such identifier" Just v -> return v pRet :: CharParser st (Maybe (RetType Val)) pRet = do t <- many1 alphaNum case t of "v" -> return Nothing "i" -> return $ Just $ fmap I retCInt "l" -> return $ Just $ fmap IL retCLong "i8" -> return $ Just $ fmap I8 retInt8 "i16" -> return $ Just $ fmap I16 retInt16 "i32" -> return $ Just $ fmap I32 retInt32 "i64" -> return $ Just $ fmap I64 retInt64 "u" -> return $ Just $ fmap U retCUInt "ul" -> return $ Just $ fmap UL retCULong "u8" -> return $ Just $ fmap U8 retWord8 "u16" -> return $ Just $ fmap U16 retWord16 "u32" -> return $ Just $ fmap U32 retWord32 "u64" -> return $ Just $ fmap U64 retWord64 "p" -> return $ Just $ fmap P (retPtr retVoid) "z" -> return $ Just $ fmap Z retCSize "f" -> return $ Just $ fmap F retCFloat "d" -> return $ Just $ fmap D retCDouble "s" -> return $ Just $ fmap S retString _ -> fail "invalid type" pCall :: CharParser (Map String Val) ((String -> IO (FunPtr a)) -> IO (Maybe (String, Val))) pCall = do mbAssign <- optionMaybe $ try $ pIdent <* (spaces >> char '=' >> spaces) mbRet <- pRet space sym <- pIdent vals <- many (space >> pArg) let call f retType = return $ \load -> load sym >>= \fp -> f <$> callFFI fp retType (map valToArg vals) case (mbAssign, mbRet) of (Just ident, Just retType) -> call (Just . (,) ident) retType (Nothing , Just retType) -> call (Just . (,) "it" ) retType (Nothing , Nothing ) -> call id (const Nothing <$> retVoid) (Just ident, Nothing) -> fail "cannot assign void" repl env = do putStr "> " hFlush stdout s <- getLine `catch` (\(e :: IOException) -> return ":q") case s of ":q" -> return () ":l" -> do forM_ (Map.toList env) $ \(ident, val) -> putStrLn $ ident ++ " = " ++ show val repl env _ -> do case words s of [ident] -> do case Map.lookup ident env of Nothing -> putStrLn ("No such identifier: " ++ show ident) Just val -> print val repl env _ -> case runParser pCall env "repl" s of Left err -> print err >> repl env Right call -> do mbAssign <- call (dlsym Default) `catch` (\(e :: IOException) -> print e >> return Nothing) repl $ maybe id (uncurry Map.insert) mbAssign env main = repl Map.empty
remiturk/libffi
examples/CCall.hs
bsd-2-clause
6,166
0
25
2,584
2,082
1,013
1,069
158
19
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1998 \section[PatSyn]{@PatSyn@: Pattern synonyms} -} {-# LANGUAGE CPP #-} module PatSyn ( -- * Main data types PatSyn, mkPatSyn, -- ** Type deconstruction patSynName, patSynArity, patSynIsInfix, patSynArgs, patSynMatcher, patSynBuilder, patSynUnivTyVarBinders, patSynExTyVars, patSynExTyVarBinders, patSynSig, patSynInstArgTys, patSynInstResTy, patSynFieldLabels, patSynFieldType, updatePatSynIds, pprPatSynType ) where #include "HsVersions.h" import GhcPrelude import Type import TyCoPpr import Name import Outputable import Unique import Util import BasicTypes import Var import FieldLabel import qualified Data.Data as Data import Data.Function import Data.List {- ************************************************************************ * * \subsection{Pattern synonyms} * * ************************************************************************ -} -- | Pattern Synonym -- -- See Note [Pattern synonym representation] -- See Note [Pattern synonym signature contexts] data PatSyn = MkPatSyn { psName :: Name, psUnique :: Unique, -- Cached from Name psArgs :: [Type], psArity :: Arity, -- == length psArgs psInfix :: Bool, -- True <=> declared infix psFieldLabels :: [FieldLabel], -- List of fields for a -- record pattern synonym -- INVARIANT: either empty if no -- record pat syn or same length as -- psArgs -- Universally-quantified type variables psUnivTyVars :: [TyVarBinder], -- Required dictionaries (may mention psUnivTyVars) psReqTheta :: ThetaType, -- Existentially-quantified type vars psExTyVars :: [TyVarBinder], -- Provided dictionaries (may mention psUnivTyVars or psExTyVars) psProvTheta :: ThetaType, -- Result type psResultTy :: Type, -- Mentions only psUnivTyVars -- See Note [Pattern synonym result type] -- See Note [Matchers and builders for pattern synonyms] psMatcher :: (Id, Bool), -- Matcher function. -- If Bool is True then prov_theta and arg_tys are empty -- and type is -- forall (p :: RuntimeRep) (r :: TYPE p) univ_tvs. -- req_theta -- => res_ty -- -> (forall ex_tvs. Void# -> r) -- -> (Void# -> r) -- -> r -- -- Otherwise type is -- forall (p :: RuntimeRep) (r :: TYPE r) univ_tvs. -- req_theta -- => res_ty -- -> (forall ex_tvs. prov_theta => arg_tys -> r) -- -> (Void# -> r) -- -> r psBuilder :: Maybe (Id, Bool) -- Nothing => uni-directional pattern synonym -- Just (builder, is_unlifted) => bi-directional -- Builder function, of type -- forall univ_tvs, ex_tvs. (req_theta, prov_theta) -- => arg_tys -> res_ty -- See Note [Builder for pattern synonyms with unboxed type] } {- Note [Pattern synonym signature contexts] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In a pattern synonym signature we write pattern P :: req => prov => t1 -> ... tn -> res_ty Note that the "required" context comes first, then the "provided" context. Moreover, the "required" context must not mention existentially-bound type variables; that is, ones not mentioned in res_ty. See lots of discussion in #10928. If there is no "provided" context, you can omit it; but you can't omit the "required" part (unless you omit both). Example 1: pattern P1 :: (Num a, Eq a) => b -> Maybe (a,b) pattern P1 x = Just (3,x) We require (Num a, Eq a) to match the 3; there is no provided context. Example 2: data T2 where MkT2 :: (Num a, Eq a) => a -> a -> T2 pattern P2 :: () => (Num a, Eq a) => a -> T2 pattern P2 x = MkT2 3 x When we match against P2 we get a Num dictionary provided. We can use that to check the match against 3. Example 3: pattern P3 :: Eq a => a -> b -> T3 b This signature is illegal because the (Eq a) is a required constraint, but it mentions the existentially-bound variable 'a'. You can see it's existential because it doesn't appear in the result type (T3 b). Note [Pattern synonym result type] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data T a b = MkT b a pattern P :: a -> T [a] Bool pattern P x = MkT True [x] P's psResultTy is (T a Bool), and it really only matches values of type (T [a] Bool). For example, this is ill-typed f :: T p q -> String f (P x) = "urk" This is different to the situation with GADTs: data S a where MkS :: Int -> S Bool Now MkS (and pattern synonyms coming from MkS) can match a value of type (S a), not just (S Bool); we get type refinement. That in turn means that if you have a pattern P x :: T [ty] Bool it's not entirely straightforward to work out the instantiation of P's universal tyvars. You have to /match/ the type of the pattern, (T [ty] Bool) against the psResultTy for the pattern synonym, T [a] Bool to get the instantiation a := ty. This is very unlike DataCons, where univ tyvars match 1-1 the arguments of the TyCon. Side note: I (SG) get the impression that instantiated return types should generate a *required* constraint for pattern synonyms, rather than a *provided* constraint like it's the case for GADTs. For example, I'd expect these declarations to have identical semantics: pattern Just42 :: Maybe Int pattern Just42 = Just 42 pattern Just'42 :: (a ~ Int) => Maybe a pattern Just'42 = Just 42 The latter generates the proper required constraint, the former does not. Also rather different to GADTs is the fact that Just42 doesn't have any universally quantified type variables, whereas Just'42 or MkS above has. Note [Pattern synonym representation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider the following pattern synonym declaration pattern P x = MkT [x] (Just 42) where data T a where MkT :: (Show a, Ord b) => [b] -> a -> T a so pattern P has type b -> T (Maybe t) with the following typeclass constraints: requires: (Eq t, Num t) provides: (Show (Maybe t), Ord b) In this case, the fields of MkPatSyn will be set as follows: psArgs = [b] psArity = 1 psInfix = False psUnivTyVars = [t] psExTyVars = [b] psProvTheta = (Show (Maybe t), Ord b) psReqTheta = (Eq t, Num t) psResultTy = T (Maybe t) Note [Matchers and builders for pattern synonyms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For each pattern synonym P, we generate * a "matcher" function, used to desugar uses of P in patterns, which implements pattern matching * A "builder" function (for bidirectional pattern synonyms only), used to desugar uses of P in expressions, which constructs P-values. For the above example, the matcher function has type: $mP :: forall (r :: ?) t. (Eq t, Num t) => T (Maybe t) -> (forall b. (Show (Maybe t), Ord b) => b -> r) -> (Void# -> r) -> r with the following implementation: $mP @r @t $dEq $dNum scrut cont fail = case scrut of MkT @b $dShow $dOrd [x] (Just 42) -> cont @b $dShow $dOrd x _ -> fail Void# Notice that the return type 'r' has an open kind, so that it can be instantiated by an unboxed type; for example where we see f (P x) = 3# The extra Void# argument for the failure continuation is needed so that it is lazy even when the result type is unboxed. For the same reason, if the pattern has no arguments, an extra Void# argument is added to the success continuation as well. For *bidirectional* pattern synonyms, we also generate a "builder" function which implements the pattern synonym in an expression context. For our running example, it will be: $bP :: forall t b. (Eq t, Num t, Show (Maybe t), Ord b) => b -> T (Maybe t) $bP x = MkT [x] (Just 42) NB: the existential/universal and required/provided split does not apply to the builder since you are only putting stuff in, not getting stuff out. Injectivity of bidirectional pattern synonyms is checked in tcPatToExpr which walks the pattern and returns its corresponding expression when available. Note [Builder for pattern synonyms with unboxed type] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For bidirectional pattern synonyms that have no arguments and have an unboxed type, we add an extra Void# argument to the builder, else it would be a top-level declaration with an unboxed type. pattern P = 0# $bP :: Void# -> Int# $bP _ = 0# This means that when typechecking an occurrence of P in an expression, we must remember that the builder has this void argument. This is done by TcPatSyn.patSynBuilderOcc. Note [Pattern synonyms and the data type Type] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The type of a pattern synonym is of the form (See Note [Pattern synonym signatures] in TcSigs): forall univ_tvs. req => forall ex_tvs. prov => ... We cannot in general represent this by a value of type Type: - if ex_tvs is empty, then req and prov cannot be distinguished from each other - if req is empty, then univ_tvs and ex_tvs cannot be distinguished from each other, and moreover, prov is seen as the "required" context (as it is the only context) ************************************************************************ * * \subsection{Instances} * * ************************************************************************ -} instance Eq PatSyn where (==) = (==) `on` getUnique (/=) = (/=) `on` getUnique instance Uniquable PatSyn where getUnique = psUnique instance NamedThing PatSyn where getName = patSynName instance Outputable PatSyn where ppr = ppr . getName instance OutputableBndr PatSyn where pprInfixOcc = pprInfixName . getName pprPrefixOcc = pprPrefixName . getName instance Data.Data PatSyn where -- don't traverse? toConstr _ = abstractConstr "PatSyn" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "PatSyn" {- ************************************************************************ * * \subsection{Construction} * * ************************************************************************ -} -- | Build a new pattern synonym mkPatSyn :: Name -> Bool -- ^ Is the pattern synonym declared infix? -> ([TyVarBinder], ThetaType) -- ^ Universially-quantified type -- variables and required dicts -> ([TyVarBinder], ThetaType) -- ^ Existentially-quantified type -- variables and provided dicts -> [Type] -- ^ Original arguments -> Type -- ^ Original result type -> (Id, Bool) -- ^ Name of matcher -> Maybe (Id, Bool) -- ^ Name of builder -> [FieldLabel] -- ^ Names of fields for -- a record pattern synonym -> PatSyn -- NB: The univ and ex vars are both in TyBinder form and TyVar form for -- convenience. All the TyBinders should be Named! mkPatSyn name declared_infix (univ_tvs, req_theta) (ex_tvs, prov_theta) orig_args orig_res_ty matcher builder field_labels = MkPatSyn {psName = name, psUnique = getUnique name, psUnivTyVars = univ_tvs, psExTyVars = ex_tvs, psProvTheta = prov_theta, psReqTheta = req_theta, psInfix = declared_infix, psArgs = orig_args, psArity = length orig_args, psResultTy = orig_res_ty, psMatcher = matcher, psBuilder = builder, psFieldLabels = field_labels } -- | The 'Name' of the 'PatSyn', giving it a unique, rooted identification patSynName :: PatSyn -> Name patSynName = psName -- | Should the 'PatSyn' be presented infix? patSynIsInfix :: PatSyn -> Bool patSynIsInfix = psInfix -- | Arity of the pattern synonym patSynArity :: PatSyn -> Arity patSynArity = psArity patSynArgs :: PatSyn -> [Type] patSynArgs = psArgs patSynFieldLabels :: PatSyn -> [FieldLabel] patSynFieldLabels = psFieldLabels -- | Extract the type for any given labelled field of the 'DataCon' patSynFieldType :: PatSyn -> FieldLabelString -> Type patSynFieldType ps label = case find ((== label) . flLabel . fst) (psFieldLabels ps `zip` psArgs ps) of Just (_, ty) -> ty Nothing -> pprPanic "dataConFieldType" (ppr ps <+> ppr label) patSynUnivTyVarBinders :: PatSyn -> [TyVarBinder] patSynUnivTyVarBinders = psUnivTyVars patSynExTyVars :: PatSyn -> [TyVar] patSynExTyVars ps = binderVars (psExTyVars ps) patSynExTyVarBinders :: PatSyn -> [TyVarBinder] patSynExTyVarBinders = psExTyVars patSynSig :: PatSyn -> ([TyVar], ThetaType, [TyVar], ThetaType, [Type], Type) patSynSig (MkPatSyn { psUnivTyVars = univ_tvs, psExTyVars = ex_tvs , psProvTheta = prov, psReqTheta = req , psArgs = arg_tys, psResultTy = res_ty }) = (binderVars univ_tvs, req, binderVars ex_tvs, prov, arg_tys, res_ty) patSynMatcher :: PatSyn -> (Id,Bool) patSynMatcher = psMatcher patSynBuilder :: PatSyn -> Maybe (Id, Bool) patSynBuilder = psBuilder updatePatSynIds :: (Id -> Id) -> PatSyn -> PatSyn updatePatSynIds tidy_fn ps@(MkPatSyn { psMatcher = matcher, psBuilder = builder }) = ps { psMatcher = tidy_pr matcher, psBuilder = fmap tidy_pr builder } where tidy_pr (id, dummy) = (tidy_fn id, dummy) patSynInstArgTys :: PatSyn -> [Type] -> [Type] -- Return the types of the argument patterns -- e.g. data D a = forall b. MkD a b (b->a) -- pattern P f x y = MkD (x,True) y f -- D :: forall a. forall b. a -> b -> (b->a) -> D a -- P :: forall c. forall b. (b->(c,Bool)) -> c -> b -> P c -- patSynInstArgTys P [Int,bb] = [bb->(Int,Bool), Int, bb] -- NB: the inst_tys should be both universal and existential patSynInstArgTys (MkPatSyn { psName = name, psUnivTyVars = univ_tvs , psExTyVars = ex_tvs, psArgs = arg_tys }) inst_tys = ASSERT2( tyvars `equalLength` inst_tys , text "patSynInstArgTys" <+> ppr name $$ ppr tyvars $$ ppr inst_tys ) map (substTyWith tyvars inst_tys) arg_tys where tyvars = binderVars (univ_tvs ++ ex_tvs) patSynInstResTy :: PatSyn -> [Type] -> Type -- Return the type of whole pattern -- E.g. pattern P x y = Just (x,x,y) -- P :: a -> b -> Just (a,a,b) -- (patSynInstResTy P [Int,Bool] = Maybe (Int,Int,Bool) -- NB: unlike patSynInstArgTys, the inst_tys should be just the *universal* tyvars patSynInstResTy (MkPatSyn { psName = name, psUnivTyVars = univ_tvs , psResultTy = res_ty }) inst_tys = ASSERT2( univ_tvs `equalLength` inst_tys , text "patSynInstResTy" <+> ppr name $$ ppr univ_tvs $$ ppr inst_tys ) substTyWith (binderVars univ_tvs) inst_tys res_ty -- | Print the type of a pattern synonym. The foralls are printed explicitly pprPatSynType :: PatSyn -> SDoc pprPatSynType (MkPatSyn { psUnivTyVars = univ_tvs, psReqTheta = req_theta , psExTyVars = ex_tvs, psProvTheta = prov_theta , psArgs = orig_args, psResultTy = orig_res_ty }) = sep [ pprForAll univ_tvs , pprThetaArrowTy req_theta , ppWhen insert_empty_ctxt $ parens empty <+> darrow , pprType sigma_ty ] where sigma_ty = mkForAllTys ex_tvs $ mkInvisFunTys prov_theta $ mkVisFunTys orig_args orig_res_ty insert_empty_ctxt = null req_theta && not (null prov_theta && null ex_tvs)
sdiehl/ghc
compiler/basicTypes/PatSyn.hs
bsd-3-clause
17,020
0
14
5,156
1,533
917
616
142
2
module Control.Concurrent.Latch where import Control.Concurrent.MVar import Control.Monad newtype Latch = Latch (MVar ()) newLatch :: IO Latch newLatch = do mvar <- newEmptyMVar return $ Latch mvar tripLatch :: Latch -> IO () tripLatch (Latch mvar) = void $ tryPutMVar mvar () awaitLatch :: Latch -> IO () awaitLatch (Latch mvar) = readMVar mvar
derekjw/haskell-future
test/Control/Concurrent/Latch.hs
bsd-3-clause
359
0
8
67
134
69
65
12
1
-- | This module contains the abstract syntax tree for the MiniJava language -- used in the compiler module Espresso.AST where newtype MJIdentifier = MJIdentifier String deriving (Show, Eq) data MJStatement = MJStatement deriving (Show, Eq) -- | The datatype for an expression in MiniJava data MJExpression = MJMainClass MJIdentifier MJIdentifier [MJStatement] deriving (Show, Eq)
helino/espresso
src/Espresso/AST.hs
bsd-3-clause
447
0
7
121
73
43
30
7
0
module Main where import Foreign import Foreign.C.Types import Foreign.C.String foreign import ccall "SSLeay_version" ssleay_version :: Int -> CString main = do str <- peekCString(ssleay_version(0)) putStrLn str
Chilledheart/ch_utils
utils/ssleay/haskell/ssleay_test.hs
bsd-3-clause
227
0
11
41
65
36
29
8
1
module Main where import Tutorial.Chapter10.Martian (run) import ALife.Creatur.Daemon (CreaturDaemon(..), Job(..), simpleDaemon, launch) import ALife.Creatur.Universe (mkSimpleUniverse) import ALife.Creatur.Task (simpleJob, runInteractingAgents, doNothing) import System.Directory (canonicalizePath) main :: IO () main = do dir <- canonicalizePath "chapter10" -- Required for daemon let u = mkSimpleUniverse "Chapter10" dir let j = simpleJob { task=runInteractingAgents run doNothing doNothing, sleepTime=0 } launch $ CreaturDaemon (simpleDaemon j u) j
mhwombat/creatur-examples
src/Tutorial/Chapter10/Daemon.hs
bsd-3-clause
586
0
12
95
171
97
74
16
1
-- This is a cut-down version of GHC's Exception module -- -- The main difference is that Hugs does not throw asynchronous -- exceptions, in particular heap and stack overflow and ctrl-C. -- Indeed, it is not entirely clear what to do in response to ctrl-C. module Hugs.Exception( SomeException(..), IOException(..), ArithException(..), ArrayException(..), catchException, -- :: IO a -> (Exception -> IO a) -> IO a throwIO, -- :: Exception -> IO a throw, -- :: Exception -> a evaluate, -- :: a -> IO a ) where import Hugs.Prelude ---------------------------------------------------------------- -- Primitive throw and catch ---------------------------------------------------------------- throwIO :: SomeException -> IO a throwIO exn = IO (\ s -> throw exn) evaluate :: a -> IO a evaluate x = IO (\ s -> x `seq` s x) ---------------------------------------------------------------- -- End ----------------------------------------------------------------
FranklinChen/Hugs
libraries/hugsbase/Hugs/Exception.hs
bsd-3-clause
983
14
9
161
157
97
60
14
1
{-# LANGUAGE OverloadedStrings #-} module SHA ( tests -- :: Int -> Tests ) where import Data.ByteString (ByteString) import qualified Data.ByteString as S import Data.ByteString.Base16 import Crypto.Hash.SHA import Test.QuickCheck import Util -------------------------------------------------------------------------------- -- Hashing pure256 :: ByteString -> Bool pure256 xs = sha256 xs == sha256 xs pure512 :: ByteString -> Bool pure512 xs = sha512 xs == sha512 xs length256 :: ByteString -> Bool length256 xs = S.length (sha256 xs) == 32 length512 :: ByteString -> Bool length512 xs = S.length (sha512 xs) == 64 vector256 :: Bool vector256 = sha256 plainText == expectation where plainText = "So you think that money is the root of all evil. Have you ever asked \ \what is the root of all money?" expectation = (fst . decode) "a27a1a1812b848461d6784e23f4d5ea6dfd2af17a106cd58a98f83bb24077da8" vector512 :: Bool vector512 = sha512 plainText == expectation where plainText = "You can ignore reality, but you can not ignore the consequences of \ \ignoring reality." expectation = (fst . decode) "84167c8baf28fd5d092b264c94bb490723df71ce2dd17fece09f63704be4c5df\ \2f880282b57f2655932af89d23a3d3c993c64539b7c7f231c12844b1dc895748" tests :: Int -> Tests tests ntests = [ ("sha256 purity", wrapArg pure256) , ("sha256 length", wrapArg length256) , ("sha256 vector", wrap vector256) , ("sha512 purity", wrapArg pure512) , ("sha512 length", wrapArg length512) , ("sha512 vector", wrap vector512) ] where wrap, wrapArg :: Testable prop => prop -> IO (Bool, Int) wrap = mkTest wrapArg = mkArgTest ntests
thoughtpolice/hs-nacl
tests/SHA.hs
bsd-3-clause
1,781
0
10
404
378
209
169
40
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveAnyClass #-} module Afftrack.API.Brand.Offers ( Offer(..) , addBrowserLanguageBlocked , addOfferBlacklist , addOfferBrowserLanguageAllowed , addOfferCategory , addOfferCountry , addOfferCustomAffiliateCap , addOfferCustomAffiliatePayout , addOfferDeviceType , addOfferOptimization , addOfferPrivate , addOfferState , addOfferTrafficType , createBannerCreative , createOffer , createOfferSchedule , createOfferScheduleDaily , createOfferScheduleRate , createTextCreative , getConvertsOn , getBrowserLanguages , getCreativeCounts , getCreatives , getOffer , getOfferBlacklist , getOfferState , getOfferStatus , getOfferBrowserLanguageAllowed , getOfferBrowserLanguageBlocked , getOfferCategories , getOfferCategory , getOfferCount , getOfferCountry , getOfferCustomAffiliateCap , getOfferCustomAffiliatePayout , getOfferDeviceType , getOfferPrivate , getOfferSchedule , getOfferTargeting , getOfferTrafficType , getOfferTypes , getPixelTypes , getTestLink , getTrackingTypes , getTrafficTypes , removeOfferBlacklist , removeOfferBrowserLanguageAllowed , removeOfferBrowserLanguageBlocked , removeOfferCountry , removeOfferCustomAffiliateCap , removeOfferCustomAffiliatePayout , removeOfferDeviceType , removeOfferOptimization , removeOfferPrivate , removeOfferSchedule , removeOfferScheduleRate , removeOfferState , removeOfferTrafficType , updateOffer , updateOfferSchedule , updateTrackingLink )where import GHC.Generics import Data.Aeson import Control.Applicative import Network.HTTP.Client import qualified Data.ByteString.Char8 as BS import Data.Text import Afftrack.API.Common import Afftrack.API.Types -------------------------------------------------------------------------------- addBrowserLanguageBlocked :: [Text] -> Call addBrowserLanguageBlocked params = Call "offer_offer" "addBrowserLanguageBlocked" "POST" [ Param "language" True (getValue params 0) -- Required , Param "offer_id" True (getValue params 1) -- Required ] addOfferBlacklist :: [Text] -> Call addOfferBlacklist params = Call "offer_offer" "addOfferBlacklist" "POST" [ Param "affiliate_id" True (getValue params 0) -- Required , Param "offer_id" True (getValue params 1) -- Required , Param "reason" False (getValue params 2) ] addOfferBrowserLanguageAllowed :: [Text] -> Call addOfferBrowserLanguageAllowed params = Call "offer_offer" "addOfferBrowserLanguageAllowed" "POST" [ Param "language" True (getValue params 0) -- Required , Param "offer_id" True (getValue params 1) -- Required ] addOfferCategory :: [Text] -> Call addOfferCategory params = Call "offer_offer" "addOfferCategory" "POST" [ Param "category_id" True (getValue params 0) -- Required , Param "offer_id" True (getValue params 1) -- Required ] addOfferCountry :: [Text] -> Call addOfferCountry params = Call "offer_offer" "addOfferCountry" "POST" [ Param "country" True (getValue params 0) -- Required , Param "offer_id" True (getValue params 1) -- Required , Param "enforce" False (getValue params 2) ] addOfferCustomAffiliateCap :: [Text] -> Call addOfferCustomAffiliateCap params = Call "offer_offer" "addOfferCustomAffiliateCap" "POST" [ Param "affiliate_id" True (getValue params 0) -- Required , Param "offer_id" True (getValue params 1) -- Required , Param "type" True (getValue params 2) -- Required , Param "day" False (getValue params 3) , Param "month" False (getValue params 4) , Param "total" False (getValue params 5) , Param "week" False (getValue params 6) ] addOfferCustomAffiliatePayout :: [Text] -> Call addOfferCustomAffiliatePayout params = Call "offer_offer" "addOfferCustomAffiliatePayout" "POST" [ Param "affiliate_id" True (getValue params 0) -- Required , Param "affiliate_payout" True (getValue params 1) -- Required , Param "offer_id" True (getValue params 2) -- Required , Param "merchant_payout" False (getValue params 3) ] addOfferDeviceType :: [Text] -> Call addOfferDeviceType params = Call "offer_offer" "addOfferDeviceType" "POST" [ Param "device_id" True (getValue params 0) -- Required , Param "offer_id" True (getValue params 1) -- Required ] addOfferOptimization :: [Text] -> Call addOfferOptimization params = Call "offer_offer" "addOfferOptimization" "POST" [ Param "affiliate_id" True (getValue params 0) -- Required , Param "offer_id" True (getValue params 1) -- Required , Param "percent" True (getValue params 2) -- Required ] addOfferPrivate :: [Text] -> Call addOfferPrivate params = Call "offer_offer" "addOfferPrivate" "POST" [ Param "affiliate_id" True (getValue params 0) -- Required , Param "offer_id" True (getValue params 1) -- Required ] addOfferState :: [Text] -> Call addOfferState params = Call "offer_offer" "addOfferState" "POST" [ Param "offer_id" True (getValue params 0) -- Required , Param "state" True (getValue params 1) -- Required ] addOfferTrafficType :: [Text] -> Call addOfferTrafficType params = Call "offer_offer" "addOfferTrafficType" "POST" [ Param "banner" True (getValue params 0) -- Required , Param "offer_id" True (getValue params 1) -- Required , Param "url" False (getValue params 2) ] createBannerCreative :: [Text] -> Call createBannerCreative params = Call "offer_offer" "createBannerCreative" "POST" [ Param "offer_id" True (getValue params 0) -- Required , Param "traffic_type_id" True (getValue params 1) -- Required ] createOffer :: [Text] -> Call createOffer params = Call "offer_offer" "createOffer" "POST" [ Param "admin_id" True (getValue params 0) -- Required , Param "category" True (getValue params 1) -- Required , Param "converts_at" True (getValue params 2) -- Required , Param "lead_rate" True (getValue params 3) -- Required , Param "merchant_id" True (getValue params 4) -- Required , Param "merchant_paying" True (getValue params 5) -- Required , Param "name" False (getValue params 6) , Param "name_private" False (getValue params 7) , Param "note" False (getValue params 8) , Param "preview" False (getValue params 9) , Param "requirements" False (getValue params 10) ] createOfferSchedule :: [Text] -> Call createOfferSchedule params = Call "offer_offer" "createOfferSchedule" "POST" [ Param "offer_id" True (getValue params 0) -- Required , Param "schedule_start" True (getValue params 1) -- Required , Param "type" True (getValue params 2) -- Required , Param "admin_id" False (getValue params 3) ] createOfferScheduleDaily :: [Text] -> Call createOfferScheduleDaily params = Call "offer_offer" "createOfferScheduleDaily" "POST" [ Param "daily_end_time" True (getValue params 0) -- Required , Param "daily_start_time" True (getValue params 1) -- Required , Param "offer_id" True (getValue params 2) -- Required , Param "schedule_end" True (getValue params 3) -- Required , Param "schedule_start" True (getValue params 4) -- Required , Param "admin_id" False (getValue params 5) ] createOfferScheduleRate :: [Text] -> Call createOfferScheduleRate params = Call "offer_offer" "createOfferScheduleRate" "POST" [ Param "affiliate_payout" True (getValue params 0) -- Required , Param "merchant_payout" True (getValue params 1) -- Required , Param "offer_id" True (getValue params 2) -- Required , Param "schedule_start" True (getValue params 3) -- Required , Param "admin_id" False (getValue params 4) ] createTextCreative :: [Text] -> Call createTextCreative params = Call "offer_offer" "createTextCreative" "POST" [ Param "offer_id" True (getValue params 0) -- Required , Param "url" True (getValue params 1) -- Required , Param "text" False (getValue params 2) ] getBrowserLanguages :: [Text] -> Call getBrowserLanguages params = Call "offer_offer" "getBrowserLanguages" "GET" [] getConvertsOn :: [Text] -> Call getConvertsOn params = Call "offer_offer" "getConvertsOn" "GET" [] getCreativeCounts :: [Text] -> Call getCreativeCounts params = Call "offer_offer" "getCreativeCounts" "GET" [ Param "offer_id" True (getValue params 0)] -- Required getCreatives :: [Text] -> Call getCreatives params = Call "offer_offer" "getCreatives" "GET" [ Param "offer_id" True (getValue params 0)] -- Required getDeviceTypes :: [Text] -> Call getDeviceTypes params = Call "offer_offer" "getDeviceTypes" "GET" [] getOffer :: [Text] -> Call getOffer params = Call "offer_offer" "getOffer" "GET" [ Param "category" False (getValue params 0) , Param "converts_on" False (getValue params 1) , Param "device_type" False (getValue params 2) , Param "limit" False (getValue params 3) , Param "merchant_id" False (getValue params 4) -- empty , Param "name" False (getValue params 5) , Param "offer_id" False (getValue params 6) , Param "offer_type" False (getValue params 7) , Param "orderby" False (getValue params 8) , Param "page" False (getValue params 9) , Param "sort" False (getValue params 10) , Param "status" False (getValue params 11) -- 107 active , Param "tracking_type" False (getValue params 12) , Param "traffic_type" False (getValue params 13) ] -- | Returns all blacklisted affiliates for the offer ID provided. -- getOfferBlacklist :: [Text] -> Call getOfferBlacklist params = Call "offer_offer" "getOfferBlacklist" "GET" [Param "offer_id" True (getValue params 0)] -- Required getOfferBrowserLanguageAllowed :: [Text] -> Call getOfferBrowserLanguageAllowed params = Call "offer_offer" "getOfferBrowserLanguageAllowed" "GET" [ Param "offer_id" True (getValue params 0)] -- Required getOfferBrowserLanguageBlocked :: [Text] -> Call getOfferBrowserLanguageBlocked params = Call "offer_offer" "getOfferBrowserLanguageBlocked" "GET" [ Param "offer_id" True (getValue params 0)] -- Required -- | All offer categories returned. -- getOfferCategories :: [Text] -> Call getOfferCategories params = Call "offer_offer" "getOfferCategories" "GET" [] -- | Returns all categories listed for the offer ID provided. -- getOfferCategory :: [Text] -> Call getOfferCategory params = Call "offer_offer" "getOfferCategory" "GET" [ Param "offer_id" True (getValue params 0)] -- Required -- | Return Int -- getOfferCount :: [Text] -> Call getOfferCount params = Call "offer_offer" "getOfferCount" "GET" [ Param "category" False (getValue params 0) , Param "converts_on" False (getValue params 1) , Param "device" False (getValue params 2) , Param "merchant_id" False (getValue params 3) , Param "name" False (getValue params 4) , Param "offer_type" False (getValue params 5) , Param "status" False (getValue params 6) , Param "tracking_type" False (getValue params 7) , Param "traffic_type" False (getValue params 8) ] getOfferCountry :: [Text] -> Call getOfferCountry params = Call "offer_offer" "getOfferCountry" "GET" [ Param "offer_id" True (getValue params 0)] -- Required getOfferCustomAffiliateCap :: [Text] -> Call getOfferCustomAffiliateCap params = Call "offer_offer" "getOfferCustomAffiliateCap" "GET" [ Param "offer_id" True (getValue params 0)] -- Required getOfferCustomAffiliatePayout :: [Text] -> Call getOfferCustomAffiliatePayout params = Call "offer_offer" "getOfferCustomAffiliatePayout" "GET" [ Param "offer_id" True (getValue params 0)] getOfferDeviceType :: [Text] -> Call getOfferDeviceType params = Call "offer_offer" "getOfferDeviceType" "GET" [ Param "offer_id" True (getValue params 0)] getOfferOptimization :: [Text] -> Call getOfferOptimization params = Call "offer_offer" "getOfferOptimization" "GET" [ Param "offer_id" True (getValue params 0)] getOfferPrivate :: [Text] -> Call getOfferPrivate params = Call "offer_offer" "getOfferPrivate" "GET" [ Param "offer_id" True (getValue params 0)] getOfferSchedule :: [Text] -> Call getOfferSchedule params = Call "offer_offer" "getOfferSchedule" "GET" [ Param "offer_id" True (getValue params 0)] -- | Returns array of all states targeted for the offer_id provided. -- getOfferState :: [Text] -> Call getOfferState params = Call "offer_offer" "getOfferState" "GET" [ Param "offer_id" True (getValue params 0)] -- Required getOfferStatus :: [Text] -> Call getOfferStatus params = Call "offer_offer" "getOfferStatus" "GET" [] getOfferTargeting :: [Text] -> Call getOfferTargeting params = Call "offer_offer" "getOfferTargeting" "GET" [] getOfferTrafficType :: [Text] -> Call getOfferTrafficType params = Call "offer_offer" "getOfferTrafficType" "GET" [ Param "offer_id" True (getValue params 0)] -- Required getOfferTypes :: [Text] -> Call getOfferTypes params = Call "offer_offer" "getOfferTypes" "GET" [] getPixelTypes :: [Text] -> Call getPixelTypes params = Call "offer_offer" "getPixelTypes" "GET" [] getTestLink:: [Text] -> Call getTestLink params = Call "offer_offer" "getTestLink" "GET" [ Param "offer_id" True (getValue params 0)] -- Required -- NB: API states that admin_id, required, but this is probably a typo getTrackingTypes :: [Text] -> Call getTrackingTypes params = Call "offer_offer" "getTrackingTypes" "GET" [] getTrafficTypes :: [Text] -> Call getTrafficTypes params = Call "offer_offer" "getTrafficTypes" "GET" [] removeOfferBlacklist :: [Text] -> Call removeOfferBlacklist params = Call "offer_offer" "removeOfferBlacklist" "POST" [ Param "affiliate_id" True (getValue params 0)] removeOfferBrowserLanguageAllowed :: [Text] -> Call removeOfferBrowserLanguageAllowed params = Call "offer_offer" "removeOfferBrowserLanguageAllowed" "POST" [ Param "offer_id" True (getValue params 0)] -- Required removeOfferBrowserLanguageBlocked :: [Text] -> Call removeOfferBrowserLanguageBlocked params = Call "offer_offer" "removeOfferBrowserLanguageBlocked" "POST" [] removeOfferCountry :: [Text] -> Call removeOfferCountry params = Call "offer_offer" "removeOfferCountry" "POST" [ Param "offer_id" True (getValue params 0)] -- Required removeOfferCustomAffiliateCap :: [Text] -> Call removeOfferCustomAffiliateCap params = Call "offer_offer" "removeOfferCountry" "POST" [ Param "offer_id" True (getValue params 0)] -- Required removeOfferCustomAffiliatePayout :: [Text] -> Call removeOfferCustomAffiliatePayout params = Call "offer_offer" "removeOfferCountry" "POST" [ Param "offer_id" True (getValue params 0)] -- Required removeOfferDeviceType :: [Text] -> Call removeOfferDeviceType params = Call "offer_offer" "removeOfferDeviceType" "POST" [ Param "device_id" True (getValue params 0)] -- Required removeOfferOptimization :: [Text] -> Call removeOfferOptimization params = Call "offer_offer" "removeOfferOptimization" "POST" [ Param "offer_id" True (getValue params 0) -- Required , Param "affiliate_id" False (getValue params 1) ] removeOfferPrivate :: [Text] -> Call removeOfferPrivate params = Call "offer_offer" "removeOfferPrivate" "POST" [ Param "offer_id" True (getValue params 0) -- Required , Param "affiliate_id" False (getValue params 1) ] removeOfferSchedule :: [Text] -> Call removeOfferSchedule params = Call "offer_offer" "removeOfferSchedule" "POST" [ Param "offer_id" True (getValue params 0) -- Required , Param "schedule_id" False (getValue params 1) ] removeOfferScheduleRate :: [Text] -> Call removeOfferScheduleRate params = Call "offer_offer" "removeOfferScheduleRate" "POST" [ Param "offer_id" True (getValue params 0) -- Required , Param "schedule_id" False (getValue params 1) ] removeOfferState :: [Text] -> Call removeOfferState params = Call "offer_offer" "removeOfferState" "POST" [ Param "offer_id" True (getValue params 0) -- Required , Param "state" False (getValue params 1) ] removeOfferTrafficType :: [Text] -> Call removeOfferTrafficType params = Call "offer_offer" "removeOfferTrafficType" "POST" [ Param "offer_id" True (getValue params 0) -- Required , Param "traffic_type_id" False (getValue params 1) ] updateOffer :: [Text] -> Call updateOffer params = Call "offer_offer" "updateOffer" "POST" [ Param "offer_id" True (getValue params 0) -- Required , Param "basic_proxy_filter" False (getValue params 1) , Param "block_ip" False (getValue params 2) , Param "break_frame" False (getValue params 3) , Param "captcha" False (getValue params 4) , Param "cap_redirect" False (getValue params 5) , Param "category" False (getValue params 6) , Param "click_frequency" False (getValue params 7) , Param "click_frequency_subnet" False (getValue params 8) , Param "click_frequency_unit" False (getValue params 9) , Param "converts_at" False (getValue params 10) , Param "cookie_life" False (getValue params 11) , Param "daily_aff_cap" False (getValue params 12) , Param "daily_cap" False (getValue params 13) , Param "geo_redirect" False (getValue params 14) , Param "hide_lead_rate" False (getValue params 15) , Param "hourly_cap" False (getValue params 16) , Param "intense_proxy_filter" False (getValue params 17) , Param "lead_rate" False (getValue params 18) , Param "maxmind" False (getValue params 19) , Param "merchant_id" False (getValue params 20) , Param "merchant_paying" False (getValue params 21) , Param "monthly_aff_cap" False (getValue params 22) , Param "monthly_cap" False (getValue params 23) , Param "name" False (getValue params 24) , Param "name_private" False (getValue params 25) , Param "pixel_type" False (getValue params 26) , Param "preview" True (getValue params 26) , Param "private" True (getValue params 27) , Param "redirect" True (getValue params 28) , Param "reject_info" True (getValue params 29) , Param "requirements" True (getValue params 30) , Param "select" True (getValue params 31) , Param "select_by" True (getValue params 32) , Param "select_who" True (getValue params 33) , Param "status" True (getValue params 34) , Param "subnet" True (getValue params 35) , Param "time_zone" True (getValue params 36) , Param "total_aff_cap" True (getValue params 37) , Param "total_cap" True (getValue params 38) , Param "tracking_type" True (getValue params 39) , Param "type" True (getValue params 40) , Param "weekly_aff_cap" True (getValue params 41) , Param "weekly_cap" True (getValue params 42) ] updateOfferSchedule :: [Text] -> Call updateOfferSchedule params = Call "offer_offer" "updateOfferSchedule" "POST" [ Param "datetime_start" True (getValue params 0) -- Required , Param "offer_id" True (getValue params 1) -- Required , Param "datetime_end" False (getValue params 2) , Param "new_rate" False (getValue params 3) , Param "status" False (getValue params 4) ] updateTrackingLink :: [Text] -> Call updateTrackingLink params = Call "offer_offer" "updateOfferSchedule" "POST" [ Param "offer_id" True (getValue params 0) -- Required , Param "tracking_url" True (getValue params 1) -- Required ]
kelecorix/api-afftrack
src/Afftrack/API/Brand/Offers.hs
bsd-3-clause
22,798
0
9
6,870
5,290
2,764
2,526
569
1
module Network.API.TLDR.Types ( Domain(..), Creator(..), Language(..), Editor(..), TLDR(..), Category(..), User(..), Gravatar(..), Time(..), LastActive(..), CreatedAt(..) ) where import Network.API.TLDR.Types.TLDR import Network.API.TLDR.Types.Category import Network.API.TLDR.Types.User import Network.API.TLDR.Types.Time
joshrotenberg/tldrio-hs
Network/API/TLDR/Types.hs
bsd-3-clause
677
0
5
378
119
86
33
16
0
{-| Module: SmartConstructor Copyright: (c) 2015 Frerich Raabe License: BSD3 Maintainer: [email protected] Stability: experimental This module exposes a 'makeSmartCtor' function which automatically creates smart constructors for custom newtype'd Haskell types. See <http://wiki.haskell.org/Smart_constructors> for a more in-depth discussion of smart constructors in Haskell. Smart constructors are useful for imposing additional checks on values; given e.g. > {-# LANGUAGE TemplateHaskell #-} > > import SmartConstructor > > newtype Positive = Positive Int > newtype NonEmptyList a = NonEmptyList [a] > newtype Interval = Interval (Integer, Integer) You can use 'makeSmartCtor' to generate smart constructors as follows: > -- Defines 'makePositive :: Int -> Maybe Positive' > makeSmartCtor defaultOptions ''Positive [|(> 0)|] > > -- Defines 'makeNonEmptyList :: [a] -> Maybe (NonEmptyList a) > makeSmartCtor defaultOptions ''NonEmptyList [|not . null|] Notice how the third argument defines a predicate; the generated functions apply this predicate to the given value: if it yields true, the smart constructor call evaluates to a 'Just' value. If the predicate yields false, the smart constructor evaluates to 'Nothing'. By default, the name for the smart constructor is derived from the type name. A custom name can be specified by modifying the 'ctorName' field of the defaultOptions: > -- Defines 'createIV :: (Integer, Integer) -> Maybe Interval > makeSmartCtor defaultOptions{ ctorName = "createIV" } ''Interval [|uncurry (<=)|] -} {-# LANGUAGE LambdaCase #-} module SmartConstructor ( SmartCtorOptions(..) , defaultOptions , makeSmartCtor ) where import Language.Haskell.TH import Language.Haskell.TH.Syntax (trueName, nothingName, justName, mkNameG, NameSpace(TcClsName)) {-| Values of the 'SmartCtorOptions' type can be passed to 'makeSmartCtor' in order to customize the generated constructor functions. At this point, only the name of the function can be changed. -} data SmartCtorOptions = SmartCtorOptions { {-| The desired name for the smart constructor function. An empty string will make 'makeSmartCtor' derive the function name from the type by prepending 'make' to the type name. -} ctorName :: String } {-| The default smart constructor generation options; the smart constructor function will be named after the type, e.g. > makeSmartCtor defaultOptions ''Foo [|const True|] defines a function 'makeFoo'. -} defaultOptions :: SmartCtorOptions defaultOptions = SmartCtorOptions "" -- Alas, not available in Language.Haskell.TH.Syntax maybeName :: Name maybeName = mkNameG TcClsName "base" "Data.Maybe" "Maybe" makeFuncT :: Type -> Type -> Type makeFuncT a = AppT (AppT ArrowT a) typeConType :: Name -> [Name] -> Type typeConType typeName typeVars = foldl AppT (ConT typeName) (map VarT typeVars) tyVarName :: TyVarBndr -> Name tyVarName (PlainTV n) = n tyVarName (KindedTV n _) = n conName :: Con -> Name conName (NormalC n _) = n conName (RecC n _) = n conName (InfixC _ n _) = n conName (ForallC _ _ c) = conName c -- |The 'makeSmartCtor' function creates a smart constructor for the given type, using the given predicate. makeSmartCtor :: SmartCtorOptions -- Options to customize the smart constructor function; the name of the defined function can be changed. -> Name -- The type to generate a smart constructor function for. -> Q Exp -- A predicate which is applied to the smart constructor argument to decide whether a Just value or Nothing is returned. -> Q [Dec] makeSmartCtor opts typeName predicate = do predExp <- predicate (dataCtor, tyVarBndrs) <- reify typeName >>= \case TyConI (NewtypeD _ _ tyVarBndrs ctor _) -> return (ctor, tyVarBndrs) _ -> fail "smartCtor: Expected name of newtype'd type constructor" sequence [ctorSignature tyVarBndrs dataCtor, ctorDefinition predExp dataCtor] where ctorSignature :: [TyVarBndr] -> Con -> Q Dec ctorSignature tyVarBndrs con = do let tyVarNames = map tyVarName tyVarBndrs let resultType = AppT (ConT maybeName) (typeConType typeName tyVarNames) return (SigD ctorName_ (ForallT tyVarBndrs [] (makeFuncT (innerType con) resultType))) where innerType (NormalC _ [(_, t)]) = t innerType (RecC _ [(_, _, t)]) = t innerType _ = undefined ctorDefinition :: Exp -> Con -> Q Dec ctorDefinition predExp con = return (FunD ctorName_ [Clause [VarP argName] ctorBody []]) where ctorBody = GuardedB [ (NormalG (AppE predExp (VarE argName)), AppE (ConE justName) (AppE (ConE (conName con)) (VarE argName))) , (NormalG (ConE trueName), ConE nothingName) ] argName = mkName "x" ctorName_ :: Name ctorName_ = mkName $ if null (ctorName opts) then "make" ++ nameBase typeName else ctorName opts
frerich/smartconstructor
src/SmartConstructor.hs
bsd-3-clause
5,152
0
18
1,189
812
424
388
54
5
{-#LANGUAGE BangPatterns, RankNTypes #-} module Control.FoldM ( -- * Fold Types Fold(..) , FoldM(..) -- * Folding , fold , foldM , scan -- * Stock Pure Folds , Control.FoldM.mconcat , Control.FoldM.foldMap , head , last , lastDef , lastN , null , length , and , or , any , all , sum , product , maximum , minimum , maximumBy , minimumBy , elem , notElem , find , index , elemIndex , findIndex -- , count -- * Stock Impure Folds , random , randomN , Control.Foldl.mapM_ , sink -- * Generic Folds , genericLength , genericIndex -- * Container folds , list , revList -- , nub -- , eqNub -- , set , vector -- * Utilities -- $utilities -- , purely -- , purely_ , impurely , impurely_ -- , generalize -- , simplify , hoists -- , duplicateM , premap -- , premapM , HandlerM , handles -- , handlesM , folded -- * IO fripperies , toHandle , stdout , stderr , toHandleLn , stdoutLn , stderrLn -- * Re-exports -- $reexports , module Control.Monad.Primitive , module Data.Foldable , module Data.Vector.Generic ) where import Control.Foldl (FoldM(..),Fold(..), HandlerM , foldM, sink, mapM_, vector, impurely , impurely_, hoists, random, randomN , folded) import qualified Control.Foldl as L import Data.Foldable (Foldable) import Control.Monad.Primitive (PrimMonad, RealWorld) import Data.Vector.Generic (Vector, Mutable) import Data.Functor.Identity (Identity(..)) import Prelude hiding ( head, last, null, length, any, all, and, or, maximum, minimum, elem, notElem, sum, product, mapM_) import qualified Data.Foldable as F import qualified Data.IOData as IOData import Control.Monad.IO.Class import qualified System.IO as IO import Data.Monoid (Monoid(..)) fold :: (Foldable f) => FoldM Identity a b -> f a -> b fold f = runIdentity . L.foldM f {-#INLINE fold #-} -- | Convert a pure strict left 'Fold' into a scan scan :: FoldM Identity a b -> [a] -> [b] scan f = L.scan (L.simplify f) {-# INLINE scan #-} -- | Fold all values within a container using 'mappend' and 'mempty' mconcat :: (Monad m, Monoid a) => FoldM m a a mconcat = L.generalize L.mconcat {-# INLINE mconcat #-} -- | Convert a \"@foldMap@\" to a 'Fold' foldMap :: (Monad m, Monoid w) => (a -> w) -> (w -> b) -> FoldM m a b foldMap to done = L.generalize (L.foldMap to done) -- | Fold all values into a list list :: Monad m => FoldM m a [a] list = L.generalize L.list {-# INLINE list #-} {-| Get the first character of a text stream or return 'Nothing' if the stream is empty -} head :: Monad m => FoldM m a (Maybe a) head = L.generalize L.head {-# INLINE head #-} {-| Get the last character of a text stream or return 'Nothing' if the text stream is empty -} last :: Monad m => FoldM m a (Maybe a) last = L.generalize L.last {-# INLINE last #-} {-| Get the last element of a container or return a default value if the container is empty -} lastDef :: Monad m => a -> FoldM m a a lastDef a = L.generalize (L.lastDef a) {-# INLINE lastDef #-} {-| Return the last N elements -} lastN :: Monad m => Int -> FoldM m a [a] lastN n = L.generalize (L.lastN n) {-# INLINE lastN #-} -- | Returns 'True' if the text stream is empty, 'False' otherwise null :: Monad m => FoldM m a Bool null = L.generalize L.null {-# INLINE null #-} -- | Return the length of the text stream in characters length :: (Monad m) => FoldM m a Int length = L.generalize L.length {-# INLINE length #-} {-| @(all predicate)@ returns 'True' if all characters satisfy the predicate, 'False' otherwise -} all :: Monad m => (a -> Bool) -> FoldM m a Bool all thus = L.generalize (L.all thus) {-| @(any predicate)@ returns 'True' if any character satisfies the predicate, 'False' otherwise -} any :: Monad m => (a -> Bool) -> FoldM m a Bool any thus = L.generalize (L.any thus) {-# INLINE any #-} -- | Returns 'True' if all elements are 'True', 'False' otherwise and :: Monad m => FoldM m Bool Bool and = L.generalize L.and {-# INLINE and #-} -- | Returns 'True' if any element is 'True', 'False' otherwise or :: Monad m => FoldM m Bool Bool or = L.generalize L.or {-# INLINE or #-} -- | Calculate the sum of all the elements sum :: (Monad m, Num n) => FoldM m n n sum = L.generalize L.sum {-#INLINE sum #-} -- | Calculate the product of all the elements product :: (Monad m, Num n) => FoldM m n n product = L.generalize L.product {-#INLINE product #-} -- | Computes the maximum character maximum :: (Monad m, Ord a) => FoldM m a (Maybe a) maximum = L.generalize L.maximum {-# INLINE maximum #-} {-| Computes the maximum element with respect to the given comparison function -} maximumBy :: Monad m => (a -> a -> Ordering) -> FoldM m a (Maybe a) maximumBy cmp = L.generalize (L.maximumBy cmp) {-# INLINABLE maximumBy #-} -- | Computes the minimum minimum :: (Monad m, Ord a) => FoldM m a (Maybe a) minimum = L.generalize L.minimum {-# INLINE minimum #-} {-| Computes the minimum element with respect to the given comparison function -} minimumBy :: Monad m => (a -> a -> Ordering) -> FoldM m a (Maybe a) minimumBy = L.generalize . L.minimumBy {-# INLINE minimumBy #-} {-| @(elem c)@ returns 'True' if the text stream has a character equal to @c@, 'False' otherwise -} elem :: (Monad m, Eq a) => a -> FoldM m a Bool elem = L.generalize . L.elem {-# INLINE elem #-} {-| @(notElem c)@ returns 'False' if the text stream has a character equal to @c@, 'True' otherwise -} notElem :: (Monad m, Eq a) => a -> FoldM m a Bool notElem = L.generalize . L.notElem {-# INLINABLE notElem #-} {-| @(find predicate)@ returns the first character that satisfies the predicate or 'Nothing' if no character satisfies the predicate -} find :: Monad m => (a -> Bool) -> FoldM m a (Maybe a) find thus = L.generalize (L.find thus) {-# INLINABLE find #-} {-| @(index n)@ returns the @n@th character of the text stream, or 'Nothing' if the stream has an insufficient number of characters -} index :: Monad m => Int -> FoldM m a (Maybe a) index = L.generalize . L.index {-#INLINE index #-} {-| @(elemIndex c)@ returns the index of the first character that equals @c@, or 'Nothing' if no character matches -} elemIndex :: (Monad m, Eq a) => a -> FoldM m a (Maybe Int) elemIndex c = L.generalize (L.elemIndex c) {-# INLINE elemIndex #-} {-| @(findIndex predicate)@ returns the index of the first character that satisfies the predicate, or 'Nothing' if no character satisfies the predicate -} findIndex :: Monad m => (a -> Bool) -> FoldM m a (Maybe Int) findIndex thus = L.generalize (L.findIndex thus) {-# INLINE findIndex #-} -- -- | @(count c)@ returns the number of times @c@ appears -- count :: (Monad m, Eq a) => a -> FoldM m a Int -- count = L.generalize . L.count -- {-# INLINE count #-} -- | Like 'length', except with a more general 'Num' return value genericLength :: (Monad m, Num b) => FoldM m a b genericLength = L.generalize L.genericLength {-# INLINE genericLength #-} -- | Like 'index', except with a more general 'Integral' argument genericIndex :: (Monad m, Integral i) => i -> FoldM m a (Maybe a) genericIndex = L.generalize . L.genericIndex {-# INLINE genericIndex #-} premap :: (a -> b) -> FoldM m b r -> FoldM m a r premap = L.premapM {-#INLINE premap #-} revList :: Monad m => FoldM m a [a] revList = L.generalize L.revList handles :: Monad m => HandlerM m a b -> FoldM m b r -> FoldM m a r handles = L.handlesM {-#INLINE handles #-} -- simplified IO nonsense toHandle :: (IOData.IOData a, MonadIO m) => IO.Handle -> FoldM m a () toHandle h = FoldM (\() bs -> IOData.hPut h bs) (return ()) return {-#INLINE toHandle #-} stdout :: (IOData.IOData a, MonadIO m) => FoldM m a () stdout = toHandle IO.stdout {-#INLINE stdout #-} stderr :: (IOData.IOData a, MonadIO m) => FoldM m a () stderr = toHandle IO.stderr {-#INLINE stderr #-} toHandleLn :: (IOData.IOData a, MonadIO m) => IO.Handle -> FoldM m a () toHandleLn h = FoldM (\() bs -> IOData.hPutStrLn h bs) (return ()) return {-#INLINE toHandleLn #-} stdoutLn :: (IOData.IOData a, MonadIO m) => FoldM m a () stdoutLn = toHandleLn IO.stdout {-#INLINE stdoutLn #-} stderrLn :: (IOData.IOData a, MonadIO m) => FoldM m a () stderrLn = toHandleLn IO.stderr {-#INLINE stderrLn #-}
michaelt/foldm
src/Control/FoldM.hs
bsd-3-clause
8,542
0
9
1,983
2,254
1,247
1,007
182
1
module Data.OrdPSQ.Tests ( tests ) where import Prelude hiding (lookup) import Data.List (isInfixOf) import Test.Framework (Test) import Test.Framework.Providers.HUnit (testCase) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.HUnit (Assertion, assert) import Test.QuickCheck (NonNegative(NonNegative)) import Data.OrdPSQ.Internal import Data.PSQ.Class.Gen () import Data.PSQ.Class.Util -------------------------------------------------------------------------------- -- Index of tests -------------------------------------------------------------------------------- tests :: [Test] tests = [ testCase "showElem" test_showElem , testCase "showLTree" test_showLTree , testCase "invalidLTree" test_invalidLTree , testCase "balanceErrors" test_balanceErrors , testProperty "toAscList" prop_toAscList , testProperty "takeMin_length" prop_takeMin_length , testProperty "takeMin_increasing" prop_takeMin_increasing , testProperty "insertWith_const" prop_insertWith_const , testProperty "insertWith_flipconst" prop_insertWith_flipconst ] -------------------------------------------------------------------------------- -- Tests the result of 'moduleError' for internal issues -------------------------------------------------------------------------------- assertModuleError :: String -> String -> a -> Assertion assertModuleError fun msg = assertErrorCall $ \e -> do assert $ fun `isInfixOf` e assert $ msg `isInfixOf` e -------------------------------------------------------------------------------- -- HUnit tests -------------------------------------------------------------------------------- test_showElem :: Assertion test_showElem = assert $ length (coverShowInstance (E 0 0 'A' :: Elem Int Int Char)) > 0 test_showLTree :: Assertion test_showLTree = do assert $ length (coverShowInstance t1) > 0 assert $ length (coverShowInstance t2) > 0 assert $ length (coverShowInstance t3) > 0 where t1, t2, t3 :: LTree Int Int Char t1 = Start t2 = LLoser 1 e Start 0 Start t3 = RLoser 1 e Start 0 Start e = E 0 0 'A' test_invalidLTree :: Assertion test_invalidLTree = do assertModuleError "left" "empty" (left (Start :: LTree Int Int Char)) assertModuleError "right" "empty" (right (Start :: LTree Int Int Char)) assertModuleError "maxKey" "empty" (maxKey (empty :: OrdPSQ Int Int Char)) test_balanceErrors :: Assertion test_balanceErrors = do assertModuleError "lsingleLeft" msg (lsingleLeft 0 0 'A' nil 0 nil) assertModuleError "rsingleLeft" msg (rsingleLeft 0 0 'A' nil 0 nil) assertModuleError "lsingleRight" msg (lsingleRight 0 0 'A' nil 0 nil) assertModuleError "rsingleRight" msg (rsingleRight 0 0 'A' nil 0 nil) assertModuleError "ldoubleLeft" msg (ldoubleLeft 0 0 'A' nil 0 nil) assertModuleError "rdoubleLeft" msg (rdoubleLeft 0 0 'A' nil 0 nil) assertModuleError "ldoubleRight" msg (ldoubleRight 0 0 'A' nil 0 nil) assertModuleError "rdoubleRight" msg (rdoubleRight 0 0 'A' nil 0 nil) where nil = Start :: LTree Int Int Char msg = "malformed" -------------------------------------------------------------------------------- -- QuickCheck properties -------------------------------------------------------------------------------- prop_toAscList :: OrdPSQ Int Int Char -> Bool prop_toAscList t = isUniqueSorted [k | (k, _, _) <- toAscList t] where isUniqueSorted (x : y : zs) = x < y && isUniqueSorted (y : zs) isUniqueSorted [_] = True isUniqueSorted [] = True prop_takeMin_length :: NonNegative Int -> OrdPSQ Int Int Char -> Bool prop_takeMin_length (NonNegative n) t = length (takeMin n t) <= n prop_takeMin_increasing :: NonNegative Int -> OrdPSQ Int Int Char -> Bool prop_takeMin_increasing (NonNegative n) t = isSorted [p | (_, p, _) <- takeMin n t] where isSorted (x : y : zs) = x <= y && isSorted (y : zs) isSorted [_] = True isSorted [] = True prop_insertWith_const :: (Int,Int,Char) -> OrdPSQ Int Int Char -> Bool prop_insertWith_const (k,p,v) t = lookup k (i1 . i2 $ t) == Just (p + 1,succ v) where i1 = insertWith (const const) k (p + 1) (succ v) i2 = insert k p v prop_insertWith_flipconst :: (Int,Int,Char) -> OrdPSQ Int Int Char -> Bool prop_insertWith_flipconst (k,p,v) t = lookup k (i1 . i2 $ t) == Just (p,v) where i1 = insertWith (const $ flip const) k (p + 1) (succ v) i2 = insert k p v
ariep/psqueues
tests/Data/OrdPSQ/Tests.hs
bsd-3-clause
4,787
0
11
1,108
1,345
704
641
77
3
{-# LANGUAGE ScopedTypeVariables #-} module Main where import Flat import Flat.Repr import Flat.Decoder import Data.List (foldl') import qualified Data.ByteString as B import qualified ListT as L -- Big is a type that has a small encoded representation but a very large in-memory footprint. -- It is a very large bytestring whose bytes are all set to 0 newtype Big = Big B.ByteString newBig :: Int -> Big newBig giga = Big $ B.replicate (giga*1000000000) 0 -- length of Big in gigas gigas :: Big -> Int gigas (Big b) = B.length b `div` 1000000000 instance Show Big where show b = "Big of " ++ show (gigas b) ++ "Gbytes" instance Flat Big where -- The encoded form is just the number of giga elements size big = size (gigas big) encode big = encode (gigas big) -- The decoded form is massive decode = newBig <$> decode -- Run this as: cabal run FlatRepr -- +RTS -M2g main :: IO () main = do let numOfBigs = 5 -- A serialised list of Big values let bigsFile = flat $ replicate numOfBigs $ newBig 1 tstListT bigsFile tstRepr bigsFile tstBig bigsFile -- If we unserialise a list of Bigs and then process them (e.g. print them out) we end up in trouble, too much memory. tstBig :: B.ByteString -> IO () tstBig bigsFile = do print "Decode to [Big]:" let Right (bs :: [Big]) = unflat bigsFile mapM_ print bs -- So we unserialise instead them to a list of their flat representation, to be unflatted on demand later on tstRepr :: B.ByteString -> IO () tstRepr bigsFile = do print "Decode to [FlatRepl Big]:" let Right (bsR :: [Repr Big]) = unflat bigsFile let bs = map unrepr bsR mapM_ print bs -- Or: we extract one element at the time via a ListT -- See http://hackage.haskell.org/package/list-t-1.0.4/docs/ListT.html tstListT :: B.ByteString -> IO () tstListT bigsFile = do print "Decode to ListT IO Big:" stream :: L.ListT IO Big <- listTDecoder decode bigsFile L.traverse_ print stream
tittoassini/flat
test/FlatRepr.hs
bsd-3-clause
1,986
0
14
441
489
244
245
41
1
{-# LANGUAGE DeriveGeneric #-} module Message where ------------------------------------------------------------------------------ import qualified Data.Aeson as A import GHC.Generics ------------------------------------------------------------------------------ import Model import BrowserProfile import EntityID import Job import WorkerProfile ------------------------------------------------------------------------------ -- | 'BrowserMessage's go between browser and CBaaS server data BrowserMessage = WorkerJoined (EntityID WorkerProfile) WorkerProfile -- ^ Informing the browser that a worker has joined | WorkerLeft (EntityID WorkerProfile) -- ^ Informing the browser that a worker has left | JobFinished (EntityID Job) -- ^ Informing the browser of job completion - usually -- for jobs that this browser requested | JobStatusUpdate (EntityID Job, JobResult) -- ^ Informing the browser of a status-update on a -- job | SetBrowserID (BrowserProfileId) -- ^ Inform the browser of its ID number -- TODO: should this be asynchronous information? -- TODO: Does it need to be validated or enforced -- somehow? deriving (Eq, Show, Generic) instance A.ToJSON BrowserMessage instance A.FromJSON BrowserMessage ------------------------------------------------------------------------------ -- | 'WorkerMessage's go between CBaaS server and online workers data WorkerMessage = JobRequested (EntityID Job, Job) -- ^ Informs a worker that a user has requested a job. -- CBaaS server is -- responsible for ensuring that job requests are -- filtered by function name, argument type, -- and the worker's willingness to do jobs for -- various sorts of users based on group membership | WorkerStatusUpdate (EntityID Job, JobResult) -- ^ Informs the server that partial progress has been -- made on a job. -- TODO: Can/should we enforce the type -- of incremental results? | WorkerFinished (EntityID Job, JobResult) -- ^ Informs the server that the worker has finished, -- including the 'JobResult' data | WorkerSetID (EntityID WorkerProfile) deriving (Eq, Show, Generic) instance A.ToJSON WorkerMessage instance A.FromJSON WorkerMessage
CBMM/CBaaS
cbaas-lib/src/Message.hs
bsd-3-clause
2,911
0
8
1,063
245
149
96
27
0
module Msum1 ( msum1 ) where import Control.Monad msum1 :: MonadPlus m => [m a] -> m a msum1 = foldl1 mplus
YoshikuniJujo/papillon
test/monadPlus/Msum1.hs
bsd-3-clause
111
2
8
25
49
26
23
5
1
module Language.JavaScript.Parser ( PA.parse , PA.readJs , PA.parseFile , PA.showStripped , PA.showStrippedMaybe , JSNode(..) , SrcSpan(..) , AlexSpan(..) , Node(..) , ParseError(..) -- Source locations , AlexPosn(..) -- ParserMonad , P , ParseState (..) ) where import Language.JavaScript.Parser.AST import Language.JavaScript.Parser.ParseError import qualified Language.JavaScript.Parser.Parser as PA import Language.JavaScript.Parser.ParserMonad import Language.JavaScript.Parser.SrcLocation -- EOF
thdtjsdn/language-javascript
src/Language/JavaScript/Parser.hs
bsd-3-clause
628
0
5
177
127
89
38
20
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE MultiWayIf #-} module QCommon.MSG where import Control.Lens (ASetter', Traversal', Lens', (.=), use, (^.), (+=), (%=)) import Control.Monad (when, liftM, unless) import Data.Bits ((.&.), shiftR, shiftL, (.|.)) import Data.Int (Int8, Int16, Int32) import Data.Monoid (mempty, mappend) import Data.Word (Word8, Word16, Word32) import Linear (V3(..), _x, _y, _z, dot) import qualified Data.ByteString as B import qualified Data.ByteString.Builder as BB import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Lazy as BL import qualified Data.Vector as V import qualified Data.Vector.Unboxed as UV import Client.ClientStateT import Client.ClientStaticT import Game.EntityStateT import QCommon.SizeBufT import Types import Game.UserCmdT import QuakeState import qualified Constants import {-# SOURCE #-} qualified QCommon.Com as Com import qualified QCommon.SZ as SZ import qualified Util.Math3D as Math3D -- IMPROVE: use binary package for conversion to ByteString? writeCharI :: Traversal' QuakeState SizeBufT -> Int -> Quake () writeCharI = writeByteI writeCharF :: Traversal' QuakeState SizeBufT -> Float -> Quake () writeCharF = writeByteF writeByteI :: Traversal' QuakeState SizeBufT -> Int -> Quake () writeByteI sizeBufLens c = do --io (print "WRITE BYTE") let c' :: Word8 = fromIntegral (c .&. 0xFF) SZ.write sizeBufLens (B.pack [c']) 1 writeByteF :: Traversal' QuakeState SizeBufT -> Float -> Quake () writeByteF sizeBufLens c = do writeByteI sizeBufLens (truncate c) writeShort :: Traversal' QuakeState SizeBufT -> Int -> Quake () writeShort sizeBufLens c = do let c' :: Word32 = fromIntegral c a :: Word8 = fromIntegral (c' .&. 0xFF) b :: Word8 = fromIntegral ((c' `shiftR` 8) .&. 0xFF) SZ.write sizeBufLens (B.pack [a, b]) 2 writeInt :: Traversal' QuakeState SizeBufT -> Int -> Quake () writeInt sizeBufLens v = do let v' :: Word32 = fromIntegral v a :: Word8 = fromIntegral (v' .&. 0xFF) b :: Word8 = fromIntegral ((v' `shiftR` 8) .&. 0xFF) c :: Word8 = fromIntegral ((v' `shiftR` 16) .&. 0xFF) d :: Word8 = fromIntegral ((v' `shiftR` 24) .&. 0xFF) SZ.write sizeBufLens (B.pack [a, b, c, d]) 4 writeLong :: Traversal' QuakeState SizeBufT -> Int -> Quake () writeLong sizeBufLens v = writeInt sizeBufLens v writeFloat :: ASetter' QuakeState SizeBufT -> Float -> Quake () writeFloat _ _ = io (putStrLn "MSG.writeFloat") >> undefined -- TODO writeString :: Traversal' QuakeState SizeBufT -> B.ByteString -> Quake () writeString sizeBufLens s = do SZ.write sizeBufLens s (B.length s) writeByteI sizeBufLens 0 writeCoord :: Traversal' QuakeState SizeBufT -> Float -> Quake () writeCoord sizeBufLens f = writeShort sizeBufLens (truncate $ f * 8) writePos :: Traversal' QuakeState SizeBufT -> V3 Float -> Quake () writePos sizeBufLens pos = do writeShort sizeBufLens (truncate ((pos^._x) * 8)) writeShort sizeBufLens (truncate ((pos^._y) * 8)) writeShort sizeBufLens (truncate ((pos^._z) * 8)) writeDir :: Traversal' QuakeState SizeBufT -> V3 Float -> Quake () writeDir sizeBufLens dir = do -- do we need this? {- if (dir == null) { WriteByte(sb, 0); return; } -} let best = calcBest 0 0 0 Constants.numVertexNormals writeByteI sizeBufLens (fromIntegral best) where calcBest :: Float -> Int -> Int -> Int -> Int calcBest bestd best idx maxIdx | idx >= maxIdx = best | otherwise = let d = dot dir (Constants.byteDirs V.! idx) in if d > bestd then calcBest d idx (idx + 1) maxIdx else calcBest bestd best (idx + 1) maxIdx writeAngle :: Traversal' QuakeState SizeBufT -> Float -> Quake () writeAngle sizeBufLens f = writeByteI sizeBufLens ((truncate $ f * 256 / 360) .&. 255) writeAngle16 :: Traversal' QuakeState SizeBufT -> Float -> Quake () writeAngle16 sizeBufLens f = writeShort sizeBufLens (fromIntegral $ Math3D.angleToShort f) writeDeltaUserCmd :: Traversal' QuakeState SizeBufT -> UserCmdT -> UserCmdT -> Quake () writeDeltaUserCmd sizeBufLens from cmd = do -- send the movement message let a = if (cmd^.ucAngles._x) /= (from^.ucAngles._x) then Constants.cmAngle1 else 0 b = if (cmd^.ucAngles._y) /= (from^.ucAngles._y) then Constants.cmAngle2 else 0 c = if (cmd^.ucAngles._z) /= (from^.ucAngles._z) then Constants.cmAngle3 else 0 d = if (cmd^.ucForwardMove) /= (from^.ucForwardMove) then Constants.cmForward else 0 e = if (cmd^.ucSideMove) /= (from^.ucSideMove) then Constants.cmSide else 0 f = if (cmd^.ucUpMove) /= (from^.ucUpMove) then Constants.cmUp else 0 g = if (cmd^.ucButtons) /= (from^.ucButtons) then Constants.cmButtons else 0 h = if (cmd^.ucImpulse) /= (from^.ucImpulse) then Constants.cmImpulse else 0 bits = a .|. b .|. c .|. d .|. e .|. f .|. g .|. h writeByteI sizeBufLens (fromIntegral bits) when (bits .&. Constants.cmAngle1 /= 0) $ writeShort sizeBufLens (fromIntegral $ cmd^.ucAngles._x) when (bits .&. Constants.cmAngle2 /= 0) $ writeShort sizeBufLens (fromIntegral $ cmd^.ucAngles._y) when (bits .&. Constants.cmAngle3 /= 0) $ writeShort sizeBufLens (fromIntegral $ cmd^.ucAngles._z) when (bits .&. Constants.cmForward /= 0) $ writeShort sizeBufLens (fromIntegral $ cmd^.ucForwardMove) when (bits .&. Constants.cmSide /= 0) $ writeShort sizeBufLens (fromIntegral $ cmd^.ucSideMove) when (bits .&. Constants.cmUp /= 0) $ writeShort sizeBufLens (fromIntegral $ cmd^.ucUpMove) when (bits .&. Constants.cmButtons /= 0) $ writeByteI sizeBufLens (fromIntegral $ cmd^.ucButtons) when (bits .&. Constants.cmImpulse /= 0) $ writeByteI sizeBufLens (fromIntegral $ cmd^.ucImpulse) writeByteI sizeBufLens (fromIntegral $ cmd^.ucMsec) writeByteI sizeBufLens (fromIntegral $ cmd^.ucLightLevel) {- - ================== WriteDeltaEntity ================== - - Writes part of a packetentities message. Can delta from either a baseline - or a previous packet_entity -} writeDeltaEntity :: EntityStateT -> EntityStateT -> Traversal' QuakeState SizeBufT -> Bool -> Bool -> Quake () writeDeltaEntity from to sizeBufLens force newEntity = do when ((to^.esNumber) == 0) $ Com.comError Constants.errFatal "Unset entity number" when ((to^.esNumber) >= Constants.maxEdicts) $ Com.comError Constants.errFatal "Entity number >= MAX_EDICTS" -- io (print $ "from origin = " ++ show (from^.esOrigin)) -- io (print $ "to origin = " ++ show (to^.esOrigin)) -- send an update let a = if (to^.esNumber) >= 256 then Constants.uNumber16 else 0 -- number8 is implicit otherwise b = if (to^.esOrigin._x) /= (from^.esOrigin._x) then Constants.uOrigin1 else 0 c = if (to^.esOrigin._y) /= (from^.esOrigin._y) then Constants.uOrigin2 else 0 d = if (to^.esOrigin._z) /= (from^.esOrigin._z) then Constants.uOrigin3 else 0 e = if (to^.esAngles._x) /= (from^.esAngles._x) then Constants.uAngle1 else 0 f = if (to^.esAngles._y) /= (from^.esAngles._y) then Constants.uAngle2 else 0 g = if (to^.esAngles._z) /= (from^.esAngles._z) then Constants.uAngle3 else 0 h = if (to^.esSkinNum) /= (from^.esSkinNum) then if | (to^.esSkinNum) < 256 -> Constants.uSkin8 | (to^.esSkinNum) < 0x10000 -> Constants.uSkin16 | otherwise -> Constants.uSkin8 .|. Constants.uSkin16 else 0 i = if (to^.esFrame) /= (from^.esFrame) then if (to^.esFrame) < 256 then Constants.uFrame8 else Constants.uFrame16 else 0 j = if (to^.esEffects) /= (from^.esEffects) then if | (to^.esEffects) < 256 -> Constants.uEffects8 | (to^.esEffects) < 0x8000 -> Constants.uEffects16 | otherwise -> Constants.uEffects8 .|. Constants.uEffects16 else 0 k = if (to^.esRenderFx) /= (from^.esRenderFx) then if | (to^.esRenderFx) < 256 -> Constants.uRenderFx8 | (to^.esRenderFx) < 0x8000 -> Constants.uRenderFx16 | otherwise -> Constants.uRenderFx8 .|. Constants.uRenderFx16 else 0 l = if (to^.esSolid) /= (from^.esSolid) then Constants.uSolid else 0 -- event is not delta compressed, just 0 compressed m = if (to^.esEvent) /= 0 then Constants.uEvent else 0 n = if (to^.esModelIndex) /= (from^.esModelIndex) then Constants.uModel else 0 o = if (to^.esModelIndex2) /= (from^.esModelIndex2) then Constants.uModel2 else 0 p = if (to^.esModelIndex3) /= (from^.esModelIndex3) then Constants.uModel3 else 0 q = if (to^.esModelIndex4) /= (from^.esModelIndex4) then Constants.uModel4 else 0 r = if (to^.esSound) /= (from^.esSound) then Constants.uSound else 0 s = if newEntity || (to^.esRenderFx) .&. Constants.rfBeam /= 0 then Constants.uOldOrigin else 0 bits = a .|. b .|. c .|. d .|. e .|. f .|. g .|. h .|. i .|. j .|. k .|. l .|. m .|. n .|. o .|. p .|. q .|. r .|. s -- io (print $ "bits = " ++ show bits) -- write the message unless (bits == 0 && not force) $ do let finalBits = if | bits .&. 0xFF000000 /= 0 -> bits .|. Constants.uMoreBits3 .|. Constants.uMoreBits2 .|. Constants.uMoreBits1 | bits .&. 0x00FF0000 /= 0 -> bits .|. Constants.uMoreBits2 .|. Constants.uMoreBits1 | bits .&. 0x0000FF00 /= 0 -> bits .|. Constants.uMoreBits1 | otherwise -> bits -- io (print $ "finalBits = " ++ show finalBits) writeByteI sizeBufLens (finalBits .&. 255) --io (print "writeDelta ENTITYENTITY") --io (print "FROM") --io (print (from^.esNumber)) --io (print (from^.esModelIndex)) --io (print "TO") --io (print (to^.esNumber)) --io (print (to^.esModelIndex)) if | finalBits .&. 0xFF000000 /= 0 -> do writeByteI sizeBufLens ((finalBits `shiftR` 8) .&. 0xFF) writeByteI sizeBufLens ((finalBits `shiftR` 16) .&. 0xFF) writeByteI sizeBufLens ((finalBits `shiftR` 24) .&. 0xFF) | finalBits .&. 0x00FF0000 /= 0 -> do writeByteI sizeBufLens ((finalBits `shiftR` 8) .&. 0xFF) writeByteI sizeBufLens ((finalBits `shiftR` 16) .&. 0xFF) | finalBits .&. 0x0000FF00 /= 0 -> do writeByteI sizeBufLens ((finalBits `shiftR` 8) .&. 0xFF) | otherwise -> return () if finalBits .&. Constants.uNumber16 /= 0 then writeShort sizeBufLens (to^.esNumber) else writeByteI sizeBufLens (to^.esNumber) when (finalBits .&. Constants.uModel /= 0) $ writeByteI sizeBufLens (to^.esModelIndex) when (finalBits .&. Constants.uModel2 /= 0) $ writeByteI sizeBufLens (to^.esModelIndex2) when (finalBits .&. Constants.uModel3 /= 0) $ writeByteI sizeBufLens (to^.esModelIndex3) when (finalBits .&. Constants.uModel4 /= 0) $ writeByteI sizeBufLens (to^.esModelIndex4) when (finalBits .&. Constants.uFrame8 /= 0) $ writeByteI sizeBufLens (to^.esFrame) when (finalBits .&. Constants.uFrame16 /= 0) $ writeShort sizeBufLens (to^.esFrame) if | finalBits .&. Constants.uSkin8 /= 0 && finalBits .&. Constants.uSkin16 /= 0 -> -- used for laser colors writeInt sizeBufLens (to^.esSkinNum) | finalBits .&. Constants.uSkin8 /= 0 -> writeByteI sizeBufLens (to^.esSkinNum) | finalBits .&. Constants.uSkin16 /= 0 -> writeShort sizeBufLens (to^.esSkinNum) | otherwise -> return () if | finalBits .&. (Constants.uEffects8 .|. Constants.uEffects16) == (Constants.uEffects8 .|. Constants.uEffects16) -> writeInt sizeBufLens (to^.esEffects) | finalBits .&. Constants.uEffects8 /= 0 -> writeByteI sizeBufLens (to^.esEffects) | finalBits .&. Constants.uEffects16 /= 0 -> writeShort sizeBufLens (to^.esEffects) | otherwise -> return () if | finalBits .&. (Constants.uRenderFx8 .|. Constants.uRenderFx16) == (Constants.uRenderFx8 .|. Constants.uRenderFx16) -> writeInt sizeBufLens (to^.esRenderFx) | finalBits .&. Constants.uRenderFx8 /= 0 -> writeByteI sizeBufLens (to^.esRenderFx) | finalBits .&. Constants.uRenderFx16 /= 0 -> writeShort sizeBufLens (to^.esRenderFx) | otherwise -> return () when (finalBits .&. Constants.uOrigin1 /= 0) $ writeCoord sizeBufLens (to^.esOrigin._x) when (finalBits .&. Constants.uOrigin2 /= 0) $ writeCoord sizeBufLens (to^.esOrigin._y) when (finalBits .&. Constants.uOrigin3 /= 0) $ writeCoord sizeBufLens (to^.esOrigin._z) when (finalBits .&. Constants.uAngle1 /= 0) $ writeAngle sizeBufLens (to^.esAngles._x) when (finalBits .&. Constants.uAngle2 /= 0) $ writeAngle sizeBufLens (to^.esAngles._y) when (finalBits .&. Constants.uAngle3 /= 0) $ writeAngle sizeBufLens (to^.esAngles._z) when (finalBits .&. Constants.uOldOrigin /= 0) $ do writeCoord sizeBufLens (to^.esOldOrigin._x) writeCoord sizeBufLens (to^.esOldOrigin._y) writeCoord sizeBufLens (to^.esOldOrigin._z) when (finalBits .&. Constants.uSound /= 0) $ writeByteI sizeBufLens (to^.esSound) when (finalBits .&. Constants.uEvent /= 0) $ writeByteI sizeBufLens (to^.esEvent) when (finalBits .&. Constants.uSolid /= 0) $ writeShort sizeBufLens (to^.esSolid) -- -- reading functions -- beginReading :: Lens' QuakeState SizeBufT -> Quake () beginReading sizeBufLens = sizeBufLens.sbReadCount .= 0 -- IMPROVE: convert bytestring to int using binary package? readLong :: Lens' QuakeState SizeBufT -> Quake Int readLong sizeBufLens = do sizeBuf <- use $ sizeBufLens if (sizeBuf^.sbReadCount) + 4 > (sizeBuf^.sbCurSize) then do Com.printf "buffer underrun in ReadLong!" return (-1) else do let buf = sizeBuf^.sbData readCount = sizeBuf^.sbReadCount a :: Word32 = fromIntegral $ B.index buf readCount b :: Word32 = fromIntegral $ B.index buf (readCount + 1) c :: Word32 = fromIntegral $ B.index buf (readCount + 2) d :: Word32 = fromIntegral $ B.index buf (readCount + 3) result :: Int32 = fromIntegral $ a .|. (b `shiftL` 8) .|. (c `shiftL` 16) .|. (d `shiftL` 24) sizeBufLens.sbReadCount += 4 return $ fromIntegral result readByte :: Lens' QuakeState SizeBufT -> Quake Int readByte sizeBufLens = do sizeBuf <- use sizeBufLens let c = if (sizeBuf^.sbReadCount) + 1 > (sizeBuf^.sbCurSize) then (-1) else fromIntegral $ (sizeBuf^.sbData) `B.index` (sizeBuf^.sbReadCount) sizeBufLens.sbReadCount += 1 -- io (print "READ BYTE") -- io (print c) return c readShort :: Lens' QuakeState SizeBufT -> Quake Int readShort sizeBufLens = do sizeBuf <- use sizeBufLens if (sizeBuf^.sbReadCount) + 2 > (sizeBuf^.sbCurSize) then do Com.printf "buffer underrun in ReadLong!" return (-1) else do let buf = sizeBuf^.sbData readCount = sizeBuf^.sbReadCount a :: Word8 = B.index buf readCount b :: Word8 = B.index buf (readCount + 1) b' :: Word16 = (fromIntegral b) `shiftL` 8 result :: Int16 = fromIntegral $ (fromIntegral a) .|. b' -- io (print "READ SHORT") -- io (print result) sizeBufLens.sbReadCount += 2 return (fromIntegral result) readChar :: Lens' QuakeState SizeBufT -> Quake Int8 readChar sizeBufLens = do msgRead <- use sizeBufLens let c = if (msgRead^.sbReadCount) + 1 > (msgRead^.sbCurSize) then (-1) else fromIntegral $ B.index (msgRead^.sbData) (msgRead^.sbReadCount) sizeBufLens.sbReadCount += 1 return c readStringLine :: Lens' QuakeState SizeBufT -> Quake B.ByteString readStringLine sizeBufLens = do ret <- readStr 0 mempty let trimmedRet = B.reverse . BC.dropWhile (<= ' ') . B.reverse $ ret Com.dprintf $ "MSG.ReadStringLine:[" `B.append` trimmedRet `B.append` "]\n" return trimmedRet where readStr :: Int -> BB.Builder -> Quake B.ByteString readStr idx acc | idx >= 2047 = return (BL.toStrict $ BB.toLazyByteString acc) | otherwise = do c <- readChar sizeBufLens if c == -1 || c == 0 || c == 0x0A then return (BL.toStrict $ BB.toLazyByteString acc) else readStr (idx + 1) (acc `mappend` BB.int8 c) readString :: Lens' QuakeState SizeBufT -> Quake B.ByteString readString sizeBufLens = do buildString 0 mempty where buildString :: Int -> BB.Builder -> Quake B.ByteString buildString len acc | len >= 2047 = return (BL.toStrict $ BB.toLazyByteString acc) | otherwise = do c <- readByte sizeBufLens if c == -1 || c == 0 then return (BL.toStrict $ BB.toLazyByteString acc) else buildString (len + 1) (acc `mappend` (BB.word8 $ fromIntegral c)) readDeltaUserCmd :: Lens' QuakeState SizeBufT -> UserCmdT -> Quake UserCmdT readDeltaUserCmd sizeBufLens from = do let move = from bits <- liftM fromIntegral $ readByte sizeBufLens -- read current angles a1 <- if bits .&. Constants.cmAngle1 /= 0 then liftM fromIntegral (readShort sizeBufLens) else return (from^.ucAngles._x) a2 <- if bits .&. Constants.cmAngle2 /= 0 then liftM fromIntegral (readShort sizeBufLens) else return (from^.ucAngles._y) a3 <- if bits .&. Constants.cmAngle3 /= 0 then liftM fromIntegral (readShort sizeBufLens) else return (from^.ucAngles._z) -- read movement forward <- if bits .&. Constants.cmForward /= 0 then liftM fromIntegral (readShort sizeBufLens) else return (from^.ucForwardMove) side <- if bits .&. Constants.cmSide /= 0 then liftM fromIntegral (readShort sizeBufLens) else return (from^.ucSideMove) up <- if bits .&. Constants.cmUp /= 0 then liftM fromIntegral (readShort sizeBufLens) else return (from^.ucUpMove) -- read buttons buttons <- if bits .&. Constants.cmButtons /= 0 then liftM fromIntegral (readByte sizeBufLens) else return (from^.ucButtons) impulse <- if bits .&. Constants.cmImpulse /= 0 then liftM fromIntegral (readByte sizeBufLens) else return (from^.ucImpulse) -- read time to run command msec <- readByte sizeBufLens -- read the light level lightLevel <- readByte sizeBufLens return move { _ucAngles = V3 a1 a2 a3 , _ucForwardMove = forward , _ucSideMove = side , _ucUpMove = up , _ucButtons = buttons , _ucImpulse = impulse , _ucMsec = fromIntegral msec , _ucLightLevel = fromIntegral lightLevel } readCoord :: Lens' QuakeState SizeBufT -> Quake Float readCoord sizeBufLens = liftM ((* (1.0 / 8.0)) . fromIntegral) (readShort sizeBufLens) readAngle :: Lens' QuakeState SizeBufT -> Quake Float readAngle sizeBufLens = liftM ((* (360.0 / 256)) . fromIntegral) (readChar sizeBufLens) readAngle16 :: Lens' QuakeState SizeBufT -> Quake Float readAngle16 sizeBufLens = do v <- readShort sizeBufLens return (Math3D.shortToAngle v) readPos :: Lens' QuakeState SizeBufT -> Quake (V3 Float) readPos sizeBufLens = do a <- readCoord sizeBufLens b <- readCoord sizeBufLens c <- readCoord sizeBufLens return (V3 a b c) readData :: Lens' QuakeState SizeBufT -> Lens' QuakeState (UV.Vector Word8) -> Int -> Quake () readData sizeBufLens bufLens len = do updates <- collectUpdates 0 [] bufLens %= (UV.// updates) where collectUpdates :: Int -> [(Int, Word8)] -> Quake [(Int, Word8)] collectUpdates idx acc | idx >= len = return acc | otherwise = do w <- readByte sizeBufLens collectUpdates (idx + 1) ((idx, fromIntegral w) : acc) readDir :: Lens' QuakeState SizeBufT -> Quake (V3 Float) readDir sizeBufLens = do b <- readByte sizeBufLens when (b >= Constants.numVertexNormals) $ Com.comError Constants.errDrop "MSG_ReadDir: out of range" return (Constants.byteDirs V.! b)
ksaveljev/hake-2
src/QCommon/MSG.hs
bsd-3-clause
20,775
0
27
5,235
6,831
3,500
3,331
-1
-1
module AERN2.Linear.Vector.Type where import Control.Monad.ST import Data.STRef import MixedTypesNumPrelude hiding (length) import qualified Data.Vector as V import qualified Data.Vector.Generic.Mutable as M import AERN2.MP.Precision import AERN2.MP.Ball import qualified Prelude as P type (Vector a) = V.Vector a (+++) :: Vector a -> Vector a -> Vector a (+++) = (V.++) drop :: Int -> Vector a -> Vector a drop = V.drop take :: Int -> Vector a -> Vector a take = V.take empty :: Vector a empty = V.empty singleton :: a -> Vector a singleton = V.singleton cons :: a -> Vector a -> Vector a cons = V.cons fromList :: [a] -> Vector a fromList = V.fromList map :: (a -> b) -> Vector a -> Vector b map = V.map imap :: (Integer -> a -> b) -> Vector a -> Vector b imap h = V.imap (\i x -> h (integer i) x) enumFromTo :: Enum a => a -> a -> Vector a enumFromTo = V.enumFromTo slice :: Integer -> Integer -> Vector a -> Vector a slice i j = V.slice (int i) (int j) foldl' :: (b -> a -> b) -> b -> Vector a -> b foldl' = V.foldl' zipWith :: (a -> b -> c) -> Vector a -> Vector b -> Vector c zipWith = V.zipWith (!) :: Vector a -> Integer -> a (!) v i = (V.!) v (int i) length :: Vector a -> Integer length = integer . V.length intLength :: Vector a -> Int intLength = V.length inftyNorm :: (HasIntegers a, CanMinMaxSameType a) => Vector a -> a inftyNorm (v :: Vector a) = V.foldl' max (convertExactly 0 :: a) v find :: (a -> Bool) -> Vector a -> Maybe a find = V.find elem :: P.Eq a => a -> Vector a -> Bool elem = V.elem toList :: Vector a -> [a] toList = V.toList zip :: Vector a -> Vector b -> Vector (a, b) zip = V.zip null :: Vector a -> Bool null = V.null instance (HasAccuracy a, HasPrecision a) => HasAccuracy (Vector a) where getAccuracy v = V.foldl' max NoInformation $ V.map getAccuracy v instance (HasPrecision a) => HasPrecision (Vector a) where getPrecision v = if V.null v then (prec 2) else getPrecision $ v ! 0 -- TODO: safe? Alternative: V.foldl' max (prec 2) $ V.map getPrecision v instance (CanSetPrecision a) => CanSetPrecision (Vector a) where setPrecision p = V.map (setPrecision p) instance (CanAddSameType a) => CanAddAsymmetric (Vector a) (Vector a) where type AddType (Vector a) (Vector a) = Vector a add v w = runST $ do mv <- M.new (intLength v) aux mv 0 V.freeze mv where lth = length v aux :: (V.MVector s a) -> Integer -> (ST s ()) aux mv k = if k == lth then return () else do M.write mv (int k) (v ! k + w ! k) aux mv (k + 1) instance (CanSubSameType a) => CanSub (Vector a) (Vector a) where type SubType (Vector a) (Vector a) = Vector a sub v w = runST $ do mv <- M.new (intLength v) aux mv 0 V.freeze mv where lth = length v aux :: (V.MVector s a) -> Integer -> (ST s ()) aux mv k = if k == lth then return () else do M.write mv (int k) (v ! k - w ! k) aux mv (k + 1) instance (CanAddSameType a, CanMulSameType a, HasIntegers a) => CanMulAsymmetric (Vector a) (Vector a) where type MulType (Vector a) (Vector a) = a mul v w = runST $ do sum <- newSTRef (convertExactly 0) aux sum 0 readSTRef sum where lth = length v aux :: (STRef s a) -> Integer -> (ST s ()) aux sum k = if k == lth then return () else do modifySTRef sum (\x -> x + (v ! k) * (w ! k)) aux sum (k + 1) instance CanMulAsymmetric (CN MPBall) (Vector (CN MPBall)) where type MulType (CN MPBall) (Vector (CN MPBall)) = Vector (CN MPBall) mul x v = V.map (\y -> x * y) v
michalkonecny/aern2
aern2-mfun/src/AERN2/Linear/Vector/Type.hs
bsd-3-clause
4,102
0
17
1,427
1,727
887
840
-1
-1
{-# LANGUAGE ScopedTypeVariables #-} module Api.Invoice.Comment (resource) where import Control.Concurrent.STM (atomically, modifyTVar', readTVar) import Control.Monad.Reader import Control.Monad.Trans.Error import Data.List import Data.Monoid import Data.Ord import Data.Time import qualified Data.HashMap.Strict as H import qualified Data.Set as Set import Rest import qualified Rest.Resource as R import Api.Invoice (WithInvoice, invoiceFromIdentifier) import ApiTypes import Type.Comment (Comment (Comment)) import Type.CustomerComment (CustomerComment (CustomerComment)) import qualified Type.Comment as Comment import qualified Type.Invoice as Invoice import qualified Type.Customer as Customer type Identifier = String type WithComment = ReaderT Identifier WithInvoice resource :: Resource WithInvoice WithComment Identifier () Void resource = mkResourceReader { R.name = "comment" , R.schema = withListing () $ named [("id", singleRead id)] , R.list = const list , R.create = Just create -- PUT /invoice to create a new Invoice. } list :: ListHandler WithInvoice list = mkListing xmlJsonO $ \r -> do invoiceId <- getInvoiceId `orThrow` NotFound comms <- liftIO . atomically . readTVar =<< (lift . lift) (asks comments) return . take (count r) . drop (offset r) . sortBy (flip $ comparing Comment.createdTime) . maybe [] Set.toList . H.lookup invoiceId $ comms create :: Handler WithInvoice create = mkInputHandler xmlJson $ \ucomm -> do invoiceId <- getInvoiceId `orThrow` NotFound comm <- liftIO $ customerCommentToComment ucomm comms <- lift . lift $ asks comments liftIO . atomically $ modifyTVar' comms (H.insertWith (<>) invoiceId (Set.singleton comm)) return comm getInvoiceId :: ErrorT (Reason ()) WithInvoice (Maybe Invoice.Id) getInvoiceId = do invoiceIdent <- ask return . fmap Invoice.id =<< liftIO . atomically . invoiceFromIdentifier invoiceIdent =<< (lift . lift) (asks invoices) customerCommentToComment :: CustomerComment -> IO Comment customerCommentToComment (CustomerComment u content) = do t <- getCurrentTime return $ Comment (Customer.name u) t content
tinkerthaler/basic-invoice-rest
example-api/Api/Invoice/Comment.hs
bsd-3-clause
2,196
0
17
389
669
361
308
54
1
import Foreign main = do print $ map f [0..255] test :: String test = unlines $ "case x of" : do i <- [0x00..0xff :: Word8] return $ show i ++ " -> " ++ show (show i) f :: Word8 -> String f x = case x of 0 -> "0" 1 -> "1" 2 -> "2" 3 -> "3" 4 -> "4" 5 -> "5" 6 -> "6" 7 -> "7" 8 -> "8" 9 -> "9" 10 -> "10" 11 -> "11" 12 -> "12" 13 -> "13" 14 -> "14" 15 -> "15" 16 -> "16" 17 -> "17" 18 -> "18" 19 -> "19" 20 -> "20" 21 -> "21" 22 -> "22" 23 -> "23" 24 -> "24" 25 -> "25" 26 -> "26" 27 -> "27" 28 -> "28" 29 -> "29" 30 -> "30" 31 -> "31" 32 -> "32" 33 -> "33" 34 -> "34" 35 -> "35" 36 -> "36" 37 -> "37" 38 -> "38" 39 -> "39" 40 -> "40" 41 -> "41" 42 -> "42" 43 -> "43" 44 -> "44" 45 -> "45" 46 -> "46" 47 -> "47" 48 -> "48" 49 -> "49" 50 -> "50" 51 -> "51" 52 -> "52" 53 -> "53" 54 -> "54" 55 -> "55" 56 -> "56" 57 -> "57" 58 -> "58" 59 -> "59" 60 -> "60" 61 -> "61" 62 -> "62" 63 -> "63" 64 -> "64" 65 -> "65" 66 -> "66" 67 -> "67" 68 -> "68" 69 -> "69" 70 -> "70" 71 -> "71" 72 -> "72" 73 -> "73" 74 -> "74" 75 -> "75" 76 -> "76" 77 -> "77" 78 -> "78" 79 -> "79" 80 -> "80" 81 -> "81" 82 -> "82" 83 -> "83" 84 -> "84" 85 -> "85" 86 -> "86" 87 -> "87" 88 -> "88" 89 -> "89" 90 -> "90" 91 -> "91" 92 -> "92" 93 -> "93" 94 -> "94" 95 -> "95" 96 -> "96" 97 -> "97" 98 -> "98" 99 -> "99" 100 -> "100" 101 -> "101" 102 -> "102" 103 -> "103" 104 -> "104" 105 -> "105" 106 -> "106" 107 -> "107" 108 -> "108" 109 -> "109" 110 -> "110" 111 -> "111" 112 -> "112" 113 -> "113" 114 -> "114" 115 -> "115" 116 -> "116" 117 -> "117" 118 -> "118" 119 -> "119" 120 -> "120" 121 -> "121" 122 -> "122" 123 -> "123" 124 -> "124" 125 -> "125" 126 -> "126" 127 -> "127" 128 -> "128" 129 -> "129" 130 -> "130" 131 -> "131" 132 -> "132" 133 -> "133" 134 -> "134" 135 -> "135" 136 -> "136" 137 -> "137" 138 -> "138" 139 -> "139" 140 -> "140" 141 -> "141" 142 -> "142" 143 -> "143" 144 -> "144" 145 -> "145" 146 -> "146" 147 -> "147" 148 -> "148" 149 -> "149" 150 -> "150" 151 -> "151" 152 -> "152" 153 -> "153" 154 -> "154" 155 -> "155" 156 -> "156" 157 -> "157" 158 -> "158" 159 -> "159" 160 -> "160" 161 -> "161" 162 -> "162" 163 -> "163" 164 -> "164" 165 -> "165" 166 -> "166" 167 -> "167" 168 -> "168" 169 -> "169" 170 -> "170" 171 -> "171" 172 -> "172" 173 -> "173" 174 -> "174" 175 -> "175" 176 -> "176" 177 -> "177" 178 -> "178" 179 -> "179" 180 -> "180" 181 -> "181" 182 -> "182" 183 -> "183" 184 -> "184" 185 -> "185" 186 -> "186" 187 -> "187" 188 -> "188" 189 -> "189" 190 -> "190" 191 -> "191" 192 -> "192" 193 -> "193" 194 -> "194" 195 -> "195" 196 -> "196" 197 -> "197" 198 -> "198" 199 -> "199" 200 -> "200" 201 -> "201" 202 -> "202" 203 -> "203" 204 -> "204" 205 -> "205" 206 -> "206" 207 -> "207" 208 -> "208" 209 -> "209" 210 -> "210" 211 -> "211" 212 -> "212" 213 -> "213" 214 -> "214" 215 -> "215" 216 -> "216" 217 -> "217" 218 -> "218" 219 -> "219" 220 -> "220" 221 -> "221" 222 -> "222" 223 -> "223" 224 -> "224" 225 -> "225" 226 -> "226" 227 -> "227" 228 -> "228" 229 -> "229" 230 -> "230" 231 -> "231" 232 -> "232" 233 -> "233" 234 -> "234" 235 -> "235" 236 -> "236" 237 -> "237" 238 -> "238" 239 -> "239" 240 -> "240" 241 -> "241" 242 -> "242" 243 -> "243" 244 -> "244" 245 -> "245" 246 -> "246" 247 -> "247" 248 -> "248" 249 -> "249" 250 -> "250" 251 -> "251" 252 -> "252" 253 -> "253" 254 -> "254" 255 -> "255" _ -> "impossible"
meiersi/blaze-binary
src/Codec/MsgPack/CaseDist.hs
bsd-3-clause
3,868
0
11
1,359
1,649
825
824
267
257
{-# LANGUAGE CPP #-} #if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703 {-# LANGUAGE Trustworthy #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Data.IntMap -- Copyright : (c) Daan Leijen 2002 -- (c) Andriy Palamarchuk 2008 -- License : BSD-style -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- An efficient implementation of maps from integer keys to values -- (dictionaries). -- -- This module re-exports the value lazy "Data.IntMap.Lazy" API, plus -- several deprecated value strict functions. Please note that these functions -- have different strictness properties than those in "Data.IntMap.Strict": -- they only evaluate the result of the combining function. For example, the -- default value to 'insertWith'' is only evaluated if the combining function -- is called and uses it. -- -- These modules are intended to be imported qualified, to avoid name -- clashes with Prelude functions, e.g. -- -- > import Data.IntMap (IntMap) -- > import qualified Data.IntMap as IntMap -- -- The implementation is based on /big-endian patricia trees/. This data -- structure performs especially well on binary operations like 'union' -- and 'intersection'. However, my benchmarks show that it is also -- (much) faster on insertions and deletions when compared to a generic -- size-balanced map implementation (see "Data.Map"). -- -- * Chris Okasaki and Andy Gill, \"/Fast Mergeable Integer Maps/\", -- Workshop on ML, September 1998, pages 77-86, -- <http://citeseer.ist.psu.edu/okasaki98fast.html> -- -- * D.R. Morrison, \"/PATRICIA -- Practical Algorithm To Retrieve -- Information Coded In Alphanumeric/\", Journal of the ACM, 15(4), -- October 1968, pages 514-534. -- -- Operation comments contain the operation time complexity in -- the Big-O notation <http://en.wikipedia.org/wiki/Big_O_notation>. -- Many operations have a worst-case complexity of /O(min(n,W))/. -- This means that the operation can become linear in the number of -- elements with a maximum of /W/ -- the number of bits in an 'Int' -- (32 or 64). ----------------------------------------------------------------------------- module Data.IntMap ( module Data.IntMap.Lazy , insertWith' , insertWithKey' , fold , foldWithKey ) where import Prelude hiding (lookup,map,filter,foldr,foldl,null) import Data.IntMap.Base (IntMap(..), join, nomatch, zero) import Data.IntMap.Lazy -- | /Deprecated./ As of version 0.5, replaced by -- 'Data.IntMap.Strict.insertWith'. -- -- /O(log n)/. Same as 'insertWith', but the result of the combining function -- is evaluated to WHNF before inserted to the map. In contrast to -- 'Data.IntMap.Strict.insertWith', the value argument is not evaluted when not -- needed by the combining function. insertWith' :: (a -> a -> a) -> Key -> a -> IntMap a -> IntMap a -- We do not reuse Data.IntMap.Strict.insertWith, because it is stricter -- it -- forces evaluation of the given value. insertWith' f k x t = insertWithKey' (\_ x' y' -> f x' y') k x t -- | /Deprecated./ As of version 0.5, replaced by -- 'Data.IntMap.Strict.insertWithKey'. -- -- /O(log n)/. Same as 'insertWithKey', but the result of the combining -- function is evaluated to WHNF before inserted to the map. In contrast to -- 'Data.IntMap.Strict.insertWithKey', the value argument is not evaluted when -- not needed by the combining function. insertWithKey' :: (Key -> a -> a -> a) -> Key -> a -> IntMap a -> IntMap a -- We do not reuse Data.IntMap.Strict.insertWithKey, because it is stricter -- it -- forces evaluation of the given value. insertWithKey' f k x t = k `seq` case t of Bin p m l r | nomatch k p m -> join k (Tip k x) p t | zero k m -> Bin p m (insertWithKey' f k x l) r | otherwise -> Bin p m l (insertWithKey' f k x r) Tip ky y | k==ky -> Tip k $! f k x y | otherwise -> join k (Tip k x) ky t Nil -> Tip k x -- | /Deprecated./ As of version 0.5, replaced by 'foldr'. -- -- /O(n)/. Fold the values in the map using the given -- right-associative binary operator. This function is an equivalent -- of 'foldr' and is present for compatibility only. fold :: (a -> b -> b) -> b -> IntMap a -> b fold = foldr {-# INLINE fold #-} -- | /Deprecated./ As of version 0.5, replaced by 'foldrWithKey'. -- -- /O(n)/. Fold the keys and values in the map using the given -- right-associative binary operator. This function is an equivalent -- of 'foldrWithKey' and is present for compatibility only. foldWithKey :: (Key -> a -> b -> b) -> b -> IntMap a -> b foldWithKey = foldrWithKey {-# INLINE foldWithKey #-}
ekmett/containers
Data/IntMap.hs
bsd-3-clause
4,742
0
12
914
564
330
234
30
3
-- negative number should be enclosed by parentheses (-3) for example elementAt :: (Num a, Ord a) => [t] -> a -> t elementAt (x:xs) 1 = x elementAt [] _ = error "Index out of range" elementAt (x:xs) k | k < 1 = error "Index out of range" | otherwise = elementAt xs (k - 1)
m00nlight/99-problems
haskell/p-03.hs
bsd-3-clause
281
0
8
66
116
58
58
6
1
{-# LANGUAGE OverloadedStrings #-} module Handler.GithubEvent where import Import import Data.Text (pack, append) import Data.Text.Encoding (decodeLatin1) import Data.Time (UTCTime) import Github.Data.Definitions ( Error(..) , PullRequestEvent(..) , PingEvent(..) , DetailedPullRequest(..) , PullRequestCommit(..) , GithubDate(..) , GithubOwner(..) , repoName , repoOwner , PullRequestEventType(..) ) import Github.Data() postGithubEventR :: Handler Text postGithubEventR = do maybeEventType <- lookupHeader "X-GitHub-Event" -- Dispatch to handlers depending on the event type case maybeEventType of -- By calling "parseEvent" with the expected concrete output type of the event data type, it forces the compiler -- to attempt to interpret the JSON according to that type definition. Just "pull_request" -> requireJsonBody >>= handlePullRequestEvent Just "ping" -> requireJsonBody >>= handlePingEvent Just et -> return $ "Unhandled event type " `append` (decodeLatin1 et) Nothing -> error "Required X-GitHub-Event header not found in request" raiseError :: Either Error b -> b raiseError = either (error . show) id handlePullRequestEvent :: PullRequestEvent -> Handler Text handlePullRequestEvent pev = do case pullRequestEventAction pev of PullRequestSynchronized -> handleUpdatedPullRequestEvent pev PullRequestOpened -> handleUpdatedPullRequestEvent pev a -> return $ pack $ "Unhandled pull request event " ++ (show a) handleUpdatedPullRequestEvent :: PullRequestEvent -> Handler Text handleUpdatedPullRequestEvent pev = do runDB $ insert $ pullRequestDiffHistoryFromEvent pev return "Detected pull request update" pullRequestDiffHistoryFromEvent :: PullRequestEvent -> PullRequestDiffHistory pullRequestDiffHistoryFromEvent pev = PullRequestDiffHistory (getPullRequestOwner pev) (getPullRequestRepoName pev) (getPullRequestNumber pev) (getBaseSha pev) (getHeadSha pev) (getUpdateTime pev) getPullRequestOwner :: PullRequestEvent -> Text getPullRequestOwner = pack . githubOwnerLogin . repoOwner . pullRequestRepository getPullRequestRepoName :: PullRequestEvent -> Text getPullRequestRepoName = pack . repoName . pullRequestRepository getPullRequestNumber :: PullRequestEvent -> Int getPullRequestNumber = detailedPullRequestNumber . pullRequestEventPullRequest getHeadSha :: PullRequestEvent -> Text getHeadSha = pack . pullRequestCommitSha . detailedPullRequestHead . pullRequestEventPullRequest getBaseSha :: PullRequestEvent -> Text getBaseSha = pack . pullRequestCommitSha . detailedPullRequestBase . pullRequestEventPullRequest getUpdateTime :: PullRequestEvent -> UTCTime getUpdateTime = fromGithubDate . detailedPullRequestUpdatedAt . pullRequestEventPullRequest handlePingEvent :: PingEvent -> Handler Text handlePingEvent _ = return "Alive and well!"
cpennington/reviewhub
Handler/GithubEvent.hs
bsd-3-clause
3,286
0
12
834
587
316
271
59
4
{-# LANGUAGE OverloadedStrings #-} module Editor (editor,ide,emptyIDE) where import Data.Monoid (mempty) import Text.Blaze.Html import Text.Blaze.Html5 ((!)) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import Network.HTTP.Base (urlEncode) import qualified System.FilePath as FP -- | Display an editor and the compiled result side-by-side. ide :: String -> FilePath -> String -> Html ide cols fileName code = ideBuilder cols ("Elm Editor: " ++ FP.takeBaseName fileName) fileName ("/compile?input=" ++ urlEncode code) -- | Display an editor and the compiled result side-by-side. emptyIDE :: Html emptyIDE = ideBuilder "50%,50%" "Try Elm" "Empty.elm" "/Try.elm" ideBuilder :: String -> String -> String -> String -> Html ideBuilder cols title input output = H.docTypeHtml $ do H.head $ do H.title . toHtml $ title preEscapedToMarkup $ concat [ "<frameset cols=\"" ++ cols ++ "\">\n" , " <frame name=\"input\" src=\"/code/", input, "\" />\n" , " <frame name=\"output\" src=\"", output, "\" />\n" , "</frameset>" ] -- | list of themes to use with CodeMirror themes = [ "ambiance", "blackboard", "cobalt", "eclipse" , "elegant", "erlang-dark", "lesser-dark", "monokai", "neat", "night" , "rubyblue", "solarized", "twilight", "vibrant-ink", "xq-dark" ] -- | Create an HTML document that allows you to edit and submit Elm code -- for compilation. editor :: FilePath -> String -> Html editor filePath code = H.html $ do H.head $ do H.title . toHtml $ "Elm Editor: " ++ FP.takeBaseName filePath H.link ! A.rel "stylesheet" ! A.href "/codemirror-3.x/lib/codemirror.css" H.script ! A.src "/codemirror-3.x/lib/codemirror.js" $ mempty H.script ! A.src "/codemirror-3.x/mode/elm/elm.js" $ mempty mapM_ (\theme -> H.link ! A.rel "stylesheet" ! A.href (toValue ("/codemirror-3.x/theme/" ++ theme ++ ".css" :: String))) themes H.link ! A.rel "stylesheet" ! A.type_ "text/css" ! A.href "/misc/editor.css" H.script ! A.type_ "text/javascript" ! A.src "/misc/showdown.js" $ mempty H.script ! A.type_ "text/javascript" ! A.src "/misc/editor.js?0.10" $ mempty H.body $ do H.form ! A.id "inputForm" ! A.action "/compile" ! A.method "post" ! A.target "output" $ do H.div ! A.id "editor_box" $ do H.textarea ! A.name "input" ! A.id "input" $ toHtml ('\n':code) H.div ! A.id "options" $ do bar "documentation" docs bar "editor_options" editorOptions bar "always_on" (buttons >> options) H.script ! A.type_ "text/javascript" $ "initEditor();" bar :: AttributeValue -> Html -> Html bar id body = H.div ! A.id id ! A.class_ "option" $ body buttons :: Html buttons = H.div ! A.class_ "valign_kids" ! A.style "float:right; padding-right: 6px;" $ "Auto-update:" >> autoBox >> hotSwapButton >> compileButton where hotSwapButton = H.input ! A.type_ "button" ! A.id "hot_swap_button" ! A.value "Hot Swap" ! A.onclick "hotSwap()" ! A.title "Ctrl-Shift-Enter" compileButton = H.input ! A.type_ "button" ! A.id "compile_button" ! A.value "Compile" ! A.onclick "compile()" ! A.title "Ctrl-Enter: change program behavior but keep the state" autoBox = H.input ! A.type_ "checkbox" ! A.id "auto_hot_swap_checkbox" ! A.onchange "setAutoHotSwap(this.checked)" ! A.style "margin-right:20px;" ! A.title "attempt to hot-swap automatically" options :: Html options = H.div ! A.class_ "valign_kids" ! A.style "float:left; padding-left:6px; padding-top:2px;" ! A.title "Show documentation and types." $ (docs >> opts) where docs = do H.span $ "Hints:" H.input ! A.type_ "checkbox" ! A.id "show_type_checkbox" ! A.onchange "showType(this.checked);" opts = do H.span ! A.style "padding-left: 12px;" $ "Options:" H.input ! A.type_ "checkbox" ! A.id "options_checkbox" ! A.onchange "showOptions(this.checked);" editorOptions :: Html editorOptions = theme >> zoom >> lineNumbers where optionFor :: String -> Html optionFor text = H.option ! A.value (toValue text) $ toHtml text theme = H.select ! A.id "editor_theme" ! A.onchange "setTheme(this.value)" $ mapM_ optionFor themes zoom = H.select ! A.id "editor_zoom" ! A.onchange "setZoom(this.options[this.selectedIndex].innerHTML)" $ mapM_ optionFor ["100%", "80%", "150%", "200%"] lineNumbers = do H.span ! A.style "padding-left: 16px;" $ "Line Numbers:" H.input ! A.type_ "checkbox" ! A.id "editor_lines" ! A.onchange "showLines(this.checked);" docs :: Html docs = tipe >> desc where tipe = H.div ! A.class_ "type" $ message >> more message = H.div ! A.style "position:absolute; left:4px; right:36px; overflow:hidden; text-overflow:ellipsis;" $ "" more = H.a ! A.id "toggle_link" ! A.style "display:none; float:right;" ! A.href "javascript:toggleVerbose();" ! A.title "Ctrl+H" $ "more" desc = H.div ! A.class_ "doc" ! A.style "display:none;" $ ""
thSoft/elm-lang.org
server/Editor.hs
bsd-3-clause
5,886
0
21
1,850
1,495
744
751
123
1
{-# LANGUAGE OverloadedStrings #-} module Lazyfoo.Lesson08 (main) where import Control.Applicative import Control.Monad import Data.Foldable (for_) import Foreign.C.Types import Linear import Linear.Affine import SDL (($=)) import qualified SDL screenWidth, screenHeight :: CInt (screenWidth, screenHeight) = (640, 480) main :: IO () main = do SDL.initialize [SDL.InitVideo] SDL.HintRenderScaleQuality $= SDL.ScaleLinear do renderQuality <- SDL.get SDL.HintRenderScaleQuality when (renderQuality /= SDL.ScaleLinear) $ putStrLn "Warning: Linear texture filtering not enabled!" window <- SDL.createWindow "SDL Tutorial" SDL.defaultWindow {SDL.windowInitialSize = V2 screenWidth screenHeight} SDL.showWindow window renderer <- SDL.createRenderer window (-1) (SDL.RendererConfig { SDL.rendererAccelerated = True , SDL.rendererSoftware = False , SDL.rendererTargetTexture = False , SDL.rendererPresentVSync = False }) SDL.renderDrawColor renderer $= V4 maxBound maxBound maxBound maxBound let loop = do let collectEvents = do e <- SDL.pollEvent case e of Nothing -> return [] Just e' -> (e' :) <$> collectEvents events <- collectEvents let quit = any (== SDL.QuitEvent) $ map SDL.eventPayload events SDL.renderDrawColor renderer $= V4 maxBound maxBound maxBound maxBound SDL.renderClear renderer SDL.renderDrawColor renderer $= V4 maxBound 0 0 maxBound SDL.renderFillRect renderer (Just $ SDL.Rectangle (P $ V2 (screenWidth `div` 4) (screenHeight `div` 4)) (V2 (screenWidth `div` 2) (screenHeight `div` 2))) SDL.renderDrawColor renderer $= V4 0 0 maxBound maxBound SDL.renderDrawRect renderer (Just (SDL.Rectangle (P $ V2 (screenWidth `div` 6) (screenHeight `div` 6)) (V2 (screenWidth * 2 `div` 3) (screenHeight * 2 `div` 3)))) SDL.renderDrawColor renderer $= V4 0 maxBound 0 maxBound SDL.renderDrawLine renderer (P (V2 0 (screenHeight `div` 2))) (P (V2 screenWidth (screenHeight `div` 2))) SDL.renderDrawColor renderer $= V4 maxBound maxBound maxBound maxBound for_ [0, 4 .. screenHeight] $ \i -> SDL.renderDrawPoint renderer (P (V2 (screenWidth `div` 2) i)) SDL.renderPresent renderer unless quit loop loop SDL.destroyRenderer renderer SDL.destroyWindow window SDL.quit
svenkeidel/sdl2
examples/lazyfoo/Lesson08.hs
bsd-3-clause
2,609
0
21
717
816
416
400
61
2
{-# LANGUAGE CPP #-} module Bead.Persistence.SQL.Comment where import Data.Maybe import Database.Persist.Sql import qualified Bead.Domain.Entities as Domain import qualified Bead.Domain.Relationships as Domain import qualified Bead.Domain.Shared.Evaluation as Domain import Bead.Persistence.SQL.Class import Bead.Persistence.SQL.Entities #ifdef TEST import qualified Data.Set as Set import Data.String (fromString) import Bead.Persistence.SQL.Assignment import Bead.Persistence.SQL.Course import Bead.Persistence.SQL.Submission import Bead.Persistence.SQL.User import Bead.Persistence.SQL.TestData import Test.Tasty.TestSet (ioTest, shrink, equals) #endif -- * Comment -- Saves the comment for the given submission saveComment :: Domain.SubmissionKey -> Domain.Comment -> Persist Domain.CommentKey saveComment submissionKey c = do key <- insert (fromDomainValue c) insert (CommentsOfSubmission (toEntityKey submissionKey) key) return $! toDomainKey key -- Loads the comment from the database loadComment :: Domain.CommentKey -> Persist Domain.Comment loadComment key = do c <- get (toEntityKey key) return $! maybe (persistError "loadComment" $ "The comment was not found: " ++ show key) toDomainValue c -- Returns the submission of the comment submissionOfComment :: Domain.CommentKey -> Persist Domain.SubmissionKey submissionOfComment key = do sbs <- selectList [ CommentsOfSubmissionComment ==. toEntityKey key ] [] return $! maybe (persistError "submissionOfComment" $ "The comment is not found: " ++ show key) (toDomainKey . commentsOfSubmissionSubmission . entityVal) (listToMaybe sbs) #ifdef TEST commentTests = do shrink "Comment end-to-end story." (do ioTest "Comment end-to-end test" $ runSql $ do initDB c <- saveCourse course ca <- saveCourseAssignment c asg saveUser user1 s <- saveSubmission ca user1name sbm cs <- commentsOfSubmission s equals (Set.fromList []) (Set.fromList cs) "Comments were for an empty submission." cm <- saveComment s cmt cs <- commentsOfSubmission s equals (Set.fromList [cm]) (Set.fromList cs) "Saved comment was not found for the submission." cmt' <- loadComment cm equals cmt cmt' "The comment was not saved and loaded correctly" sc <- submissionOfComment cm equals s sc "The submission of the comment was wrong" cm2 <- saveComment s cmt cs <- commentsOfSubmission s equals (Set.fromList [cm,cm2]) (Set.fromList cs) "Comments of the submission were wrong." return ()) (do return ()) return () #endif
pgj/bead
src/Bead/Persistence/SQL/Comment.hs
bsd-3-clause
2,928
0
17
797
672
342
330
28
1
{-# LANGUAGE FlexibleContexts #-} -- | -- Module: Data.JSON.Schema.Generator -- Copyright: (c) 2015 Shohei Murayama -- License: BSD3 -- Maintainer: Shohei Murayama <[email protected]> -- Stability: experimental -- -- A generator for JSON Schemas from ADT. -- module Data.JSON.Schema.Generator ( -- * How to use this library -- $use -- * Genenerating JSON Schema Options(..), FieldType(..), defaultOptions , generate, generate' -- * Type conversion , JSONSchemaGen(toSchema) , JSONSchemaPrim(toSchemaPrim) , convert -- * Generic Schema class , GJSONSchemaGen(gToSchema) , genericToSchema ) where import Data.ByteString.Lazy.Char8 (ByteString) import Data.JSON.Schema.Generator.Class (JSONSchemaGen(toSchema), JSONSchemaPrim(toSchemaPrim) , GJSONSchemaGen(gToSchema), Options(..), FieldType(..), defaultOptions, genericToSchema) import Data.JSON.Schema.Generator.Convert (convert) import Data.JSON.Schema.Generator.Generic () import Data.Proxy (Proxy) import qualified Data.Aeson as A import qualified Data.Aeson.Types as A -- | Generate a JSON Schema from a proxy value of a type. -- This uses the default options to generate schema in json format. -- generate :: JSONSchemaGen a => Proxy a -- ^ A proxy value of the type from which a schema will be generated. -> ByteString generate = A.encode . convert A.defaultOptions . toSchema defaultOptions -- | Generate a JSON Schema from a proxy vaulue of a type. -- This uses the specified options to generate schema in json format. -- generate' :: JSONSchemaGen a => Options -- ^ Schema generation 'Options'. -> A.Options -- ^ Encoding 'A.Options' of aeson. -> Proxy a -- ^ A proxy value of the type from which a schema will be generated. -> ByteString generate' opts aopts = A.encode . convert aopts . toSchema opts -- $use -- Example: -- -- > {-# LANGUAGE DeriveGeneric #-} -- > -- > import qualified Data.ByteString.Lazy.Char8 as BL -- > import Data.JSON.Schema.Generator -- > import Data.Proxy -- > import GHC.Generics -- > -- > data User = User -- > { name :: String -- > , age :: Int -- > , email :: Maybe String -- > } deriving Generic -- > -- > instance JSONSchemaGen User -- > -- > main :: IO () -- > main = BL.putStrLn $ generate (Proxy :: Proxy User) -- -- Let's run the above script, we can get on stdout (the following json is formatted with jq): -- -- @ -- { -- \"required\": [ -- \"name\", -- \"age\", -- \"email\" -- ], -- \"$schema\": \"http://json-schema.org\/draft-04\/schema#\", -- \"id\": \"Main.User\", -- \"title\": \"Main.User\", -- \"type\": \"object\", -- \"properties\": { -- \"email\": { -- \"type\": [ -- \"string\", -- \"null\" -- ] -- }, -- \"age\": { -- \"type\": \"integer\" -- }, -- \"name\": { -- \"type\": \"string\" -- } -- } -- } -- @
yuga/jsonschema-gen
src/Data/JSON/Schema/Generator.hs
bsd-3-clause
2,988
0
9
686
346
243
103
35
1
-- | This module provides an interface to \complexity pair combinators\. -- A complexity pair is a special subset of processors that return a complexity pair proof. -- A complexity pair combinator is a processor that takes a complexity pair as argument. module Tct.Trs.Data.ComplexityPair ( ComplexityPair (..) , ComplexityPairDeclaration (..) , IsComplexityPair (..) , ComplexityPairProof (..) , toComplexityPair , someComplexityPair ) where import qualified Tct.Core.Data as T import Tct.Trs.Data.Problem import Tct.Trs.Data.RuleSelector (ExpressionSelector) import Tct.Trs.Data.Rules (Rules) import Tct.Trs.Data.Symbol (F, V) data ComplexityPairProof = ComplexityPairProof { result :: T.ProofTree Trs , removableDPs :: Rules F V , removableTrs :: Rules F V } deriving Show -- MS: TODO: a complexity pair should just return a proof tree -- then lift it here -- | A 'ComplexityPair' provides a special solve method returning a 'ComplexityProof'. class IsComplexityPair p where solveComplexityPair :: p -> ExpressionSelector F V -> Problem F V -> T.TctM (Either String ComplexityPairProof) -- | A 'ComplexityPair' is a processor that can returns 'ComplexityPairProof'. data ComplexityPair where ComplexityPair :: (T.Processor p, IsComplexityPair p) => p -> ComplexityPair instance Show ComplexityPair where show (ComplexityPair p) = show p -- | Existential type for declarations specifying a Strategy. data ComplexityPairDeclaration where CD :: (Trs ~ prob, T.ParsableArgs args, T.ArgsInfo args) => T.Declaration (args T.:-> ComplexityPair) -> ComplexityPairDeclaration someComplexityPair :: (Trs ~ prob, T.ParsableArgs args, T.ArgsInfo args) => T.Declaration (args T.:-> ComplexityPair) -> ComplexityPairDeclaration someComplexityPair = CD toComplexityPair :: (T.Processor p, IsComplexityPair p) => p -> ComplexityPair toComplexityPair = ComplexityPair
ComputationWithBoundedResources/tct-trs
src/Tct/Trs/Data/ComplexityPair.hs
bsd-3-clause
1,973
0
12
365
396
229
167
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module Deviser.Evaluator ( eval , expand , primEnv ) where import Data.Monoid ((<>)) import Control.Monad.Except import Control.Monad.Reader import qualified Data.Map as Map import qualified Data.Text as T import Deviser.Types -- List Primitives cons :: MonadError LispError m => [LispVal] -> m LispVal cons [h, List []] = return (List [h]) cons [h, List xs] = return (List (h : xs)) cons [h, DottedList xs x] = return (DottedList (h : xs) x) cons [h, x] = return (DottedList [h] x) cons h = throwError (NumArgs 2 h) car :: MonadError LispError m => [LispVal] -> m LispVal car [List (x : _)] = return x car [DottedList (x : _) _] = return x car [x] = throwError (TypeMismatch "pair" x) car x = throwError (NumArgs 1 x) cdr :: MonadError LispError m => [LispVal] -> m LispVal cdr [List (_ : xs)] = return (List xs) cdr [DottedList (_ : s : xs) x] = return (DottedList (s : xs) x) cdr [DottedList [_] x] = return x cdr [x] = throwError (TypeMismatch "pair" x) cdr x = throwError (NumArgs 1 x) eqv :: (Applicative f, Eq a) => a -> a -> f LispVal eqv x y = Bool <$> pure (x == y) -- Unary Operations symbolp :: MonadError LispError m => LispVal -> m LispVal symbolp (Atom _) = return (Bool True) symbolp _ = return (Bool False) numberp :: MonadError LispError m => LispVal -> m LispVal numberp (Number _) = return (Bool True) numberp _ = return (Bool False) stringp :: MonadError LispError m => LispVal -> m LispVal stringp (String _) = return (Bool True) stringp _ = return (Bool False) boolp :: MonadError LispError m => LispVal -> m LispVal boolp (Bool _) = return (Bool True) boolp _ = return (Bool False) listp :: MonadError LispError m => LispVal -> m LispVal listp (List _) = return (Bool True) listp (DottedList _ _) = return (Bool True) listp _ = return (Bool False) symbolToString :: MonadError LispError m => LispVal -> m LispVal symbolToString (Atom s) = return (String s) symbolToString _ = return (String "") stringToSymbol :: MonadError LispError m => LispVal -> m LispVal stringToSymbol (String s) = return (Atom s) stringToSymbol _ = return (Atom "") -- Evaluator -- type UnaryOp = LispVal -> Eval LispVal -- type BinaryOp = LispVal -> LispVal -> Eval LispVal unaryOp :: MonadError LispError m => (LispVal -> m a) -> [LispVal] -> m a unaryOp op [x] = op x unaryOp _ xs = throwError (NumArgs 1 xs) binaryOp :: MonadError LispError m => (LispVal -> LispVal -> m a) -> [LispVal] -> m a binaryOp op [x, y] = op x y binaryOp _ xs = throwError (NumArgs 1 xs) binaryOpFold :: MonadError LispError m => (LispVal -> LispVal -> m LispVal) -> LispVal -> [LispVal] -> m LispVal binaryOpFold op _ [a,b] = op a b binaryOpFold _ _ args@[] = throwError (NumArgs 2 args) binaryOpFold op farg args = foldM op farg args numericBinOp :: MonadError LispError m => (Integer -> Integer -> Integer) -> LispVal -> LispVal -> m LispVal numericBinOp op (Number x) (Number y) = return (Number (op x y)) numericBinOp _ Nil (Number y) = return (Number y) numericBinOp _ (Number x) Nil = return (Number x) numericBinOp _ x (Number _) = throwError (TypeMismatch "number" x) numericBinOp _ (Number _) y = throwError (TypeMismatch "number" y) numericBinOp _ x _ = throwError (TypeMismatch "number" x) numBoolBinOp :: MonadError LispError m => (Integer -> Integer -> Bool) -> LispVal -> LispVal -> m LispVal numBoolBinOp op (Number x) (Number y) = return (Bool (op x y)) numBoolBinOp _ x (Number _) = throwError (TypeMismatch "number" x) numBoolBinOp _ (Number _) y = throwError (TypeMismatch "number" y) numBoolBinOp _ x _ = throwError (TypeMismatch "number" x) eqOp :: MonadError LispError m => (Bool -> Bool -> Bool) -> LispVal -> LispVal -> m LispVal eqOp op (Bool x) (Bool y) = return (Bool (op x y)) eqOp _ x (Bool _) = throwError (TypeMismatch "bool" x) eqOp _ (Bool _) y = throwError (TypeMismatch "bool" y) eqOp _ x _ = throwError (TypeMismatch "bool" x) primEnv :: EnvCtx primEnv = Map.fromList [ ("cons", PrimOp cons) , ("car", PrimOp car) , ("cdr", PrimOp cdr) , ("eq?", PrimOp (binaryOp eqv)) , ("+", PrimOp (binaryOpFold (numericBinOp (+)) (Number 0))) , ("*", PrimOp (binaryOpFold (numericBinOp (*)) (Number 1))) , ("-", PrimOp (binaryOp (numericBinOp (-)))) , ("/", PrimOp (binaryOp (numericBinOp div))) , ("mod", PrimOp (binaryOp (numericBinOp mod))) , ("quotient", PrimOp (binaryOp (numericBinOp quot))) , ("remainder", PrimOp (binaryOp (numericBinOp rem))) , ("symbol?", PrimOp (unaryOp symbolp)) , ("number?", PrimOp (unaryOp numberp)) , ("string?", PrimOp (unaryOp stringp)) , ("bool?", PrimOp (unaryOp boolp)) , ("list?", PrimOp (unaryOp listp)) , ("symbol->string", PrimOp (unaryOp symbolToString)) , ("string->symbol", PrimOp (unaryOp stringToSymbol)) , ("=", PrimOp (binaryOp (numBoolBinOp (==)))) , ("<", PrimOp (binaryOp (numBoolBinOp (<)))) , (">", PrimOp (binaryOp (numBoolBinOp (>)))) , ("/=", PrimOp (binaryOp (numBoolBinOp (/=)))) , (">=", PrimOp (binaryOp (numBoolBinOp (>=)))) , ("<=", PrimOp (binaryOp (numBoolBinOp (<=)))) , ("&&", PrimOp (binaryOpFold (eqOp (&&)) (Bool True))) , ("||", PrimOp (binaryOpFold (eqOp (||)) (Bool False))) ] getVar :: (MonadReader EnvCtx m, MonadError LispError m) => LispVal -> m LispVal getVar (Atom atom) = do env <- ask case Map.lookup atom env of Just x -> return x Nothing -> throwError (UnboundVar atom) getVar n = throwError (TypeMismatch "atom" n) ifExpr :: (MonadError LispError m, MonadReader EnvCtx m) => LispVal -> LispVal -> LispVal -> m LispVal ifExpr predicate consequent alternate = do ifResult <- eval predicate case ifResult of (Bool True) -> eval consequent (Bool False) -> eval alternate x -> throwError (TypeMismatch "bool" x) condExp :: (MonadError LispError m, MonadReader EnvCtx m) => [LispVal] -> m LispVal condExp [List [Atom "else", consequent]] = eval consequent condExp (List [predicate, consequent] : xs) = do predResult <- eval predicate case predResult of (Bool True) -> eval consequent (Bool False) -> condExp xs x -> throwError (TypeMismatch "bool" x) condExp x = throwError (NumArgs 1 x) eqf :: MonadError LispError m => LispVal -> LispVal -> m Bool eqf x y = do res <- eqv y x case res of Bool b -> return b _ -> throwError (TypeMismatch "bool" x) caseExpr :: (MonadError LispError m, MonadReader EnvCtx m) => LispVal -> [LispVal] -> m LispVal caseExpr _ x@[] = throwError (NumArgs 1 x) caseExpr _ (List (Atom "else" : thenBody) : _) = last <$> mapM eval thenBody caseExpr valExpr (List (List datums : thenBody) : clauses) = do result <- eval valExpr foundMatch <- or <$> traverse (eqf result) datums if foundMatch then last <$> mapM eval thenBody else caseExpr valExpr clauses caseExpr valExpr clauses = throwError (BadSpecialForm "Ill-constructed case expression" (List (Atom "case" : valExpr : clauses))) letBindingsAreValid :: [LispVal] -> Bool letBindingsAreValid = all folder where folder (List [Atom _, _]) = True folder _ = False collectLetBindings :: [LispVal] -> Map.Map T.Text LispVal collectLetBindings = foldl folder (Map.fromList []) where folder acc (List [Atom var, expr]) = Map.insert var expr acc folder _ _ = Map.fromList [] letExpr :: (MonadError LispError m, MonadReader EnvCtx m) => [LispVal] -> [LispVal] -> m LispVal letExpr pairs exprs = if letBindingsAreValid pairs then do bindings <- traverse eval (collectLetBindings pairs) local (mappend bindings) (beginExpr exprs) else throwError (BadSpecialForm "Ill-formed let-expression" (List pairs)) ensureAtom :: MonadError LispError m => LispVal -> m LispVal ensureAtom n@(Atom _) = return n ensureAtom n = throwError (TypeMismatch "atom" n) extractVar :: MonadError LispError m => LispVal -> m T.Text extractVar (Atom atom) = return atom extractVar n = throwError (TypeMismatch "atom" n) defExpr :: (MonadError LispError m, MonadReader EnvCtx m) => LispVal -> LispVal -> m LispVal defExpr var expr = do evaledExpr <- eval expr extractedVar <- extractVar <$> ensureAtom var insertMe <- extractedVar local (Map.insert insertMe evaledExpr) (return var) beginExpr :: (MonadError LispError m, MonadReader EnvCtx m) => [LispVal] -> m LispVal beginExpr [List (Atom "define" : [Atom var, expr]), rest] = do evaledExpr <- eval expr local (Map.insert var evaledExpr) (eval rest) beginExpr (List (Atom "define" : [Atom var, expr]) : rest) = do evaledExpr <- eval expr local (Map.insert var evaledExpr) (beginExpr rest) beginExpr [x] = eval x beginExpr (x:xs) = eval x >> beginExpr xs beginExpr [] = return Nil lambdaExpr :: (MonadReader EnvCtx m, MonadError LispError m) => [LispVal] -> LispVal -> m LispVal lambdaExpr params expr = do env <- ask unwrappedParams <- mapM extractVar params return (Lambda unwrappedParams Nothing expr env) lambdaExprVarargs :: (MonadReader EnvCtx m, MonadError LispError m) => LispVal -> LispVal -> m LispVal lambdaExprVarargs (Atom p) expr = do env <- ask return (Lambda [] (Just p) expr env) lambdaExprVarargs _ _ = throwError (BadSpecialForm "vararg" Nil) apply :: (MonadError LispError m, MonadReader EnvCtx m) => LispVal -> [LispVal] -> m LispVal apply f args = do funVar <- eval f evaledArgs <- mapM eval args case funVar of (PrimOp internalFn) -> either throwError pure (internalFn evaledArgs) (Lambda params Nothing body boundEnv) -> local (mappend (Map.fromList (zip params evaledArgs) <> boundEnv)) (eval body) (Lambda [] (Just vp) body boundEnv) -> local (mappend (Map.insert vp (List evaledArgs) boundEnv)) (eval body) _ -> throwError (NotFunction funVar) evalExpr :: (MonadError LispError m, MonadReader EnvCtx m) => LispVal -> m LispVal evalExpr expr = do e <- eval expr case e of v@(List _) -> eval v _ -> return e eval :: (MonadError LispError m, MonadReader EnvCtx m) => LispVal -> m LispVal eval v@(String _) = return v eval v@(Number _) = return v eval v@(Bool _) = return v eval (List (Atom "list" : xs)) = List <$> pure xs eval (List [Atom "quote", value]) = return value eval (List []) = return Nil eval Nil = return Nil eval v@(Atom _) = getVar v eval (List [Atom "if", predicate, conseq, alt]) = ifExpr predicate conseq alt eval (List (Atom "cond" : clauses)) = condExp clauses eval (List (Atom "case" : key : clauses)) = caseExpr key clauses eval (List (Atom "let" : List pairs : exprs)) = letExpr pairs exprs eval (List (Atom "begin" : rest)) = beginExpr rest eval (List [Atom "define", varExpr, expr]) = defExpr varExpr expr eval (List [Atom "lambda", List params, expr]) = lambdaExpr params expr eval (List [Atom "lambda", vs@(Atom _), expr]) = lambdaExprVarargs vs expr eval (List [Atom "eval", value]) = evalExpr value eval (List (f : args)) = apply f args eval badForm = throwError (BadSpecialForm "Unrecognized special form" badForm) expandAndSplice :: (MonadError LispError m, MonadReader EnvCtx m) => LispVal -> m LispVal -> m LispVal expandAndSplice (List [Atom "unquote-splicing", xs@(List _)]) acc = do b <- acc a <- eval xs case (a, b) of (List as, List bs) -> List <$> pure (as ++ bs) (h, t) -> cons [h, t] expandAndSplice a acc = do t <- acc h <- expandQuasiquoted a cons [h, t] expandQuasiquoted :: (MonadError LispError m, MonadReader EnvCtx m) => LispVal -> m LispVal expandQuasiquoted (List [Atom "unquote", x@(Atom _)]) = getVar x *> pure x expandQuasiquoted (List [Atom "unquote", xs@(List _)]) = eval xs expandQuasiquoted (List xs) = foldr expandAndSplice (pure (List [])) xs expandQuasiquoted x = pure x quote :: LispVal -> LispVal quote x = List [Atom "quote", x] expand :: (MonadReader EnvCtx m, MonadError LispError m) => LispVal -> m LispVal expand (List [Atom "quasiquote", value]) = quote <$> expandQuasiquoted value expand (List xs) = List <$> traverse expand xs expand x = pure x
henrytill/deviser
src/Deviser/Evaluator.hs
bsd-3-clause
13,427
0
17
3,767
5,378
2,695
2,683
295
4
{-# LANGUAGE GeneralizedNewtypeDeriving , DeriveFunctor , DeriveFoldable , DeriveTraversable , DeriveGeneric , DeriveDataTypeable , MultiParamTypeClasses , FlexibleInstances , FlexibleContexts , UndecidableInstances , TypeFamilies , TupleSections #-} module Data.Trie.HashMap where import Data.Trie.Class (Trie (..)) import Data.Semigroup (Semigroup) import Data.Monoid (First (..), Last (..), (<>)) import Data.Hashable (Hashable) import Data.Maybe (fromMaybe, fromJust) import qualified Data.Foldable as F import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.List.NonEmpty as NE import qualified Data.HashMap.Lazy as HM import qualified Data.Key as K import Control.Monad (replicateM) import Data.Data (Data, Typeable) import GHC.Generics (Generic) import Control.DeepSeq (NFData) import Prelude hiding (lookup, null) import Test.QuickCheck (Arbitrary (..), resize, choose, sized, scale) import Test.QuickCheck.Instances () -- * One Step data HashMapChildren c p a = HashMapChildren { hashMapNode :: !(Maybe a) , hashMapChildren :: !(Maybe (c p a)) } deriving (Show, Eq, Functor, Foldable, Traversable, Generic, Data, Typeable) instance ( NFData (c p a) , NFData p , NFData a ) => NFData (HashMapChildren c p a) instance ( Arbitrary a , Arbitrary p , Arbitrary (c p a) ) => Arbitrary (HashMapChildren c p a) where arbitrary = HashMapChildren <$> arbitrary <*> scale (`div` 2) arbitrary instance ( Semigroup (c p a) ) => Semigroup (HashMapChildren c p a) where (HashMapChildren mx mxs) <> (HashMapChildren my mys) = HashMapChildren (getLast (Last mx <> Last my)) (mxs <> mys) instance ( Monoid (c p a) ) => Monoid (HashMapChildren c p a) where mempty = HashMapChildren Nothing Nothing newtype HashMapStep c p a = HashMapStep { unHashMapStep :: HM.HashMap p (HashMapChildren c p a) } deriving (Show, Eq, Functor, Foldable, Traversable, Generic, Data, Typeable) instance ( NFData (c p a) , NFData p , NFData a ) => NFData (HashMapStep c p a) instance ( Arbitrary a , Arbitrary p , Arbitrary (c p a) , Hashable p , Eq p ) => Arbitrary (HashMapStep c p a) where arbitrary = sized go where go n = do i <- choose (0,n) xs <- replicateM i $ (,) <$> arbitrary <*> resize (n `div` 2) arbitrary pure (HashMapStep (HM.fromList xs)) instance ( Hashable p , Eq p , Trie NonEmpty p c ) => Trie NonEmpty p (HashMapStep c) where lookup (p:|ps) (HashMapStep xs) | F.null ps = hashMapNode =<< HM.lookup p xs | otherwise = lookup (NE.fromList ps) =<< hashMapChildren =<< HM.lookup p xs delete (p:|ps) (HashMapStep xs) | F.null ps = let mxs = hashMapChildren =<< HM.lookup p xs in HashMapStep (HM.insert p (HashMapChildren Nothing mxs) xs) | otherwise = let (HashMapChildren mx mxs) = fromMaybe (HashMapChildren Nothing Nothing) (HM.lookup p xs) in HashMapStep (HM.insert p (HashMapChildren mx (delete (NE.fromList ps) <$> mxs)) xs) insert :: ( Hashable p , Eq p , Trie NonEmpty p c , Monoid (c p a) ) => NonEmpty p -> a -> HashMapStep c p a -> HashMapStep c p a insert (p:|ps) x (HashMapStep xs) | F.null ps = let mxs = hashMapChildren =<< HM.lookup p xs in HashMapStep (HM.insert p (HashMapChildren (Just x) $! mxs) xs) | otherwise = let mx = hashMapNode =<< HM.lookup p xs xs' = fromMaybe mempty (hashMapChildren =<< HM.lookup p xs) in HashMapStep (HM.insert p (HashMapChildren mx (Just (Data.Trie.Class.insert (NE.fromList ps) x xs'))) xs) {-# INLINEABLE insert #-} instance ( Hashable p , Eq p , Semigroup (c p a) ) => Semigroup (HashMapStep c p a) where (HashMapStep xs) <> (HashMapStep ys) = HashMapStep (HM.unionWith (<>) xs ys) instance ( Hashable p , Eq p , Monoid (c p a) ) => Monoid (HashMapStep c p a) where mempty = empty empty :: HashMapStep c p a empty = HashMapStep HM.empty singleton :: Hashable p => p -> a -> HashMapStep c p a singleton p x = HashMapStep (HM.singleton p (HashMapChildren (Just x) Nothing)) {-# INLINEABLE singleton #-} -- * Fixpoint of Steps newtype HashMapTrie p a = HashMapTrie { unHashMapTrie :: HashMapStep HashMapTrie p a } deriving (Show, Eq, Functor, Foldable, Traversable, Semigroup, Monoid, Arbitrary) instance (Hashable p, Eq p) => Trie NonEmpty p HashMapTrie where lookup ts (HashMapTrie xs) = lookup ts xs delete ts (HashMapTrie xs) = HashMapTrie (delete ts xs) insert ts x (HashMapTrie xs) = HashMapTrie (Data.Trie.HashMap.insert ts x xs) type instance K.Key (HashMapTrie p) = NonEmpty p instance ( Hashable p , Eq p ) => K.Lookup (HashMapTrie p) where lookup = lookup -- * Conversion keys :: ( Hashable p , Eq p ) => HashMapTrie p a -> [NonEmpty p] keys (HashMapTrie (HashMapStep xs)) = let ks = HM.keys xs in F.concatMap go ks where go k = let (HashMapChildren _ mxs) = fromJust (HM.lookup k xs) in case mxs of Nothing -> [] Just xs' -> NE.cons k <$> keys xs' {-# INLINEABLE keys #-} elems :: HashMapTrie p a -> [a] elems = F.toList -- * Query subtrie :: ( Hashable p , Eq p ) => NonEmpty p -> HashMapTrie p a -> Maybe (HashMapTrie p a) subtrie (p:|ps) (HashMapTrie (HashMapStep xs)) | F.null ps = hashMapChildren =<< HM.lookup p xs | otherwise = subtrie (NE.fromList ps) =<< hashMapChildren =<< HM.lookup p xs {-# INLINEABLE subtrie #-} -- lookupNearest ~ match match :: ( Hashable p , Eq p ) => NonEmpty p -> HashMapTrie p a -> Maybe (NonEmpty p, a, [p]) match (p:|ps) (HashMapTrie (HashMapStep xs)) = do (HashMapChildren mx mxs) <- HM.lookup p xs let mFoundHere = (p:|[],,ps) <$> mx if F.null ps then mFoundHere else getFirst $ First (do (pre,y,suff) <- match (NE.fromList ps) =<< mxs pure (NE.cons p pre, y, suff)) <> First mFoundHere {-# INLINEABLE match #-} -- | Returns a list of all the nodes along the path to the furthest point in the -- query, in order of the path walked from the root to the furthest point. matches :: ( Hashable p , Eq p ) => NonEmpty p -> HashMapTrie p a -> [(NonEmpty p, a, [p])] matches (p:|ps) (HashMapTrie (HashMapStep xs)) = let (HashMapChildren mx mxs) = fromMaybe mempty (HM.lookup p xs) foundHere = case mx of Nothing -> [] Just x -> [(p:|[],x,ps)] in if F.null ps then foundHere else let rs = case mxs of Nothing -> [] Just xs' -> matches (NE.fromList ps) xs' in foundHere ++ (prependAncestry <$> rs) where prependAncestry (pre,x,suff) = (NE.cons p pre,x,suff) {-# INLINEABLE matches #-}
athanclark/tries
src/Data/Trie/HashMap.hs
bsd-3-clause
7,405
0
19
2,275
2,642
1,368
1,274
180
4
{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleInstances #-} module Homework7.Sized where import Data.Monoid newtype Size = Size Int deriving (Eq, Ord, Show, Num) getSize :: Size -> Int getSize (Size i) = i class Sized a where size :: a -> Size instance Sized Size where size = id -- This instance means that things like -- (Foo, Size) -- (Foo, (Bar, Size)) -- ... -- are all instances of Sized. instance Sized b => Sized (a,b) where size = size . snd instance Monoid Size where mempty = Size 0 mappend = (+)
gabluc/CIS194-Solutions
src/Homework7/Sized.hs
bsd-3-clause
537
0
7
117
151
85
66
16
1
{-| Module : Client.Image.Layout Description : Layout code for the multi-window splits Copyright : (c) Eric Mertens, 2016 License : ISC Maintainer : [email protected] -} module Client.Image.Layout (scrollAmount, drawLayout) where import Control.Lens import Client.State import Client.State.Focus import Client.Configuration (LayoutMode(..)) import Client.Image.PackedImage (Image', unpackImage) import Client.Image.StatusLine (statusLineImage, minorStatusLineImage) import Client.Image.Textbox import Client.Image.LineWrap (lineWrap, terminate) import Client.Image.Palette import Client.View import Graphics.Vty.Image import Graphics.Vty.Attributes (defAttr) -- | Compute the combined image for all the visible message windows. drawLayout :: ClientState {- ^ client state -} -> (Int, Int, Int, Int, Image) {- ^ overscroll, cursor row, cursor col, next offset, final image -} drawLayout st = case view clientLayout st of TwoColumn | not (null extrafocus) -> drawLayoutTwo st extrafocus _ -> drawLayoutOne st extrafocus where extrafocus = clientExtraFocuses st -- | Layout algorithm for all windows in a single column. drawLayoutOne :: ClientState {- ^ client state -} -> [(Focus, Subfocus)] {- ^ extra windows -} -> (Int, Int, Int, Int, Image) {- ^ overscroll and final image -} drawLayoutOne st extrafocus = (overscroll, row, col, nextOffset, output) where w = view clientWidth st h:hs = splitHeights (rows - saveRows) (length extraLines) scroll = view clientScroll st (overscroll, row, col, nextOffset, main) = drawMain w (saveRows + h) scroll st output = vertCat $ reverse $ main : [ drawExtra st w h' foc subfoc imgs | (h', (foc, subfoc, imgs)) <- zip hs extraLines] rows = view clientHeight st -- don't count textbox or the main status line against the main window's height saveRows = 1 + imageHeight (statusLineImage w st) extraLines = [ (focus, subfocus, viewLines focus subfocus w st) | (focus, subfocus) <- extrafocus ] -- | Layout algorithm for all windows in a single column. drawLayoutTwo :: ClientState {- ^ client state -} -> [(Focus, Subfocus)] {- ^ extra windows -} -> (Int, Int, Int, Int, Image) {- ^ overscroll, cursor row, cursor col, offset, final image -} drawLayoutTwo st extrafocus = (overscroll, row, col, nextOffset, output) where [wl,wr] = divisions (view clientWidth st - 1) 2 hs = divisions (rows - length extraLines) (length extraLines) scroll = view clientScroll st output = main <|> divider <|> extraImgs extraImgs = vertCat $ reverse [ drawExtra st wr h' foc subfoc imgs | (h', (foc, subfoc, imgs)) <- zip hs extraLines] (overscroll, row, col, nextOffset, main) = drawMain wl rows scroll st pal = clientPalette st divider = charFill (view palWindowDivider pal) ' ' 1 rows rows = view clientHeight st extraLines = [ (focus, subfocus, viewLines focus subfocus wr st) | (focus, subfocus) <- extrafocus ] drawMain :: Int {- ^ draw width -} -> Int {- ^ draw height -} -> Int {- ^ scroll amount -} -> ClientState {- ^ client state -} -> (Int,Int,Int,Int,Image) drawMain w h scroll st = (overscroll, row, col, nextOffset, msgs <-> bottomImg) where focus = view clientFocus st subfocus = view clientSubfocus st msgLines = viewLines focus subfocus w st (overscroll, msgs) = messagePane w h' scroll msgLines h' = max 0 (h - imageHeight bottomImg) bottomImg = statusLineImage w st <-> tbImage (row, col, nextOffset, tbImage) = textboxImage 3 w st -- | Draw one of the extra windows from @/splits@ drawExtra :: ClientState {- ^ client state -} -> Int {- ^ draw width -} -> Int {- ^ draw height -} -> Focus {- ^ focus -} -> Subfocus {- ^ subfocus -} -> [Image'] {- ^ image lines -} -> Image {- ^ rendered window -} drawExtra st w h focus subfocus lineImages = msgImg <-> unpackImage (minorStatusLineImage focus subfocus w True st) where (_, msgImg) = messagePane w h 0 lineImages -- | Generate an image corresponding to the image lines of the given -- focus and subfocus. Returns the number of lines overscrolled to -- assist in clamping scroll to the lines available in the window. messagePane :: Int {- ^ client width -} -> Int {- ^ available rows -} -> Int {- ^ current scroll -} -> [Image'] {- ^ focused window -} -> (Int, Image) {- ^ overscroll, rendered messages -} messagePane w h scroll images = (overscroll, img) where vimg = assemble emptyImage images vimg1 = cropBottom h vimg img = charFill defAttr ' ' w (h - imageHeight vimg1) <-> vimg1 overscroll = vh - imageHeight vimg vh = h + scroll assemble acc _ | imageHeight acc >= vh = cropTop vh acc assemble acc [] = acc assemble acc (x:xs) = assemble (this <-> acc) xs where this = vertCat $ map (terminate w . unpackImage) $ lineWrap w x splitHeights :: Int {- ^ screen rows to fill -} -> Int {- ^ number of extra windows -} -> [Int] {- ^ list of heights for each division -} splitHeights h ex = divisions (h - ex) (1 + ex) -- | Constructs a list of numbers with the length of the divisor -- and that sums to the dividend. Each element will be within -- one of the quotient. divisions :: Int {- ^ dividend -} -> Int {- ^ divisor -} -> [Int] divisions x y | y <= 0 = [] | otherwise = replicate r (q+1) ++ replicate (y-r) q where (q,r) = quotRem (max 0 x) y -- | Compute the number of lines in a page at the current window size scrollAmount :: ClientState {- ^ client state -} -> Int {- ^ scroll amount -} scrollAmount st = case view clientLayout st of TwoColumn -> h OneColumn -> head (splitHeights h ex) -- extra will be equal to main or 1 smaller where layout = view clientLayout st h = view clientHeight st - bottomSize ex = length (clientExtraFocuses st) bottomSize = 1 -- textbox + imageHeight (statusLineImage mainWidth st) mainWidth = case layout of TwoColumn -> head (divisions (view clientWidth st - 1) 2) OneColumn -> view clientWidth st
glguy/irc-core
src/Client/Image/Layout.hs
isc
6,743
0
15
1,997
1,650
906
744
133
3
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE QuasiQuotes #-} module Tests.KFoldApproximation ( kApproximationTests ) where import qualified Data.Map as M import Data.Monoid import Data.Word import qualified Distribution.TestSuite as TS import Test.QuickCheck import Tests.OneApproximation hiding (testCombinator, prop_approx_match) import Tests.TestUtils import KMC.Determinization import qualified KMC.Kleenex.Approximation as A import KMC.Kleenex.ApproximationMetrics import KMC.Kleenex.Desugaring import KMC.Kleenex.Syntax import KMC.SymbolicFST.Transducer import KMC.SymbolicSST import KMC.Theories import KMC.RangeSet import KMC.Util.Heredoc kApproximationTests :: [TS.Test] kApproximationTests = testCombinatorFold [ ("testProg3", testProg3)] [ LCS, Hamming, Levenshtein] [ 1,2 ] prop_approx_fold :: RProgAct -> TestSST -> TestSST -> ApproxMetric -> Int -> Property prop_approx_fold p sst1 sst2 m k = forAll (generateString p m k) $ \s -> (validateMatch sst1 s) == (validateMatch sst2 s) testCombinatorFold :: [(String, RProgAct)] -> [ApproxMetric] -> [Int] -> [TS.Test] testCombinatorFold ps ms ks = concat $ map (\p -> concat ( map (\m -> map (\k -> qtest p m k) ks) ms)) ps where qtest p m k = simpleTest (desc p m k) $ quickTest rpp $ prop_approx_fold (snd p) (testSST (snd p) m k Matching) (testSSTFold (snd p) m k Matching) m k desc p m k = "ApproxQC: " ++ (fst p) ++ " " ++ (show m) ++ " " ++ show k rpp = 20 -- ^ Number of quickcheck runs pr program -- | Creates a SST from a RProg, an ErrorMetric and a approximation value k testSSTFold :: RProgAct -> ApproxMetric -> Int -> ApproxMode -> TestSST testSSTFold p m k mode = let aprog = A.approxProg p k 0 m mode ffst = constructTransducer aprog 0 in enumerateVariables $ enumerateStates $ sstFromFST ffst True
diku-kmc/repg
test/Tests/KFoldApproximation.hs
mit
2,140
0
17
601
584
321
263
41
1
module WeiXin.PublicPlatform.QRCode where -- {{{1 imports import ClassyPrelude import Network.Wreq import qualified Network.Wreq.Session as WS import Control.Lens hiding ((.=)) #if !MIN_VERSION_base(4, 13, 0) import Control.Monad.Reader (asks) #endif import Data.Aeson import Data.Aeson.Types (Pair) import WeiXin.PublicPlatform.Class import WeiXin.PublicPlatform.WS import Network.HTTP.Types (renderQueryText) import qualified Blaze.ByteString.Builder as BBB -- }}}1 -- | 创建永久场景二维码 wxppQrCodeCreatePersist :: (WxppApiMonad env m) => AccessToken -> WxppScene -> m WxppMakeSceneResult -- {{{1 wxppQrCodeCreatePersist atk scene = do wxppQrCodeCreateInternal [ "action_name" .= action ] atk scene where action = case scene of WxppSceneInt {} -> "QR_LIMIT_SCENE" :: Text WxppSceneStr {} -> "QR_LIMIT_STR_SCENE" -- }}}1 -- | 创建短期场景二维码 -- UPDATE: 现在看文档又说可以用字串形式的场景参数 wxppQrCodeCreateTransient :: (WxppApiMonad env m) => AccessToken -> Int -- ^ TTL in seconds -> WxppScene -> m WxppMakeSceneResult -- {{{1 wxppQrCodeCreateTransient atk ttl scene = wxppQrCodeCreateInternal [ "action_name" .= action , "expire_seconds" .= ttl ] atk scene where action = case scene of WxppSceneInt {} -> "QR_SCENE" :: Text WxppSceneStr {} -> "QR_STR_SCENE" -- }}}1 wxppQrCodeCreateInternal :: (WxppApiMonad env m) => [Pair] -> AccessToken -> WxppScene -> m WxppMakeSceneResult wxppQrCodeCreateInternal js_pairs (AccessToken { accessTokenData = atk }) scene = do (sess, url_conf) <- asks (getWreqSession &&& getWxppUrlConfig) let url = wxppUrlConfSecureApiBase url_conf ++ "/qrcode/create" opts = defaults & param "access_token" .~ [ atk ] liftIO (WS.postWith opts sess url $ toJSON $ object $ ( "action_info" .= object [ "scene" .= scene ] ) : js_pairs) >>= asWxppWsResponseNormal' -- | 可直接在网页上使用的显示二维码的URL wxppQrCodeUrlByTicket :: QRTicket -> UrlText wxppQrCodeUrlByTicket (QRTicket ticket) = UrlText $ "https://mp.weixin.qq.com/cgi-bin/showqrcode" <> decodeUtf8 (BBB.toByteString $ renderQueryText True [ ("ticket", Just ticket ) ] ) -- vim: set foldmethod=marker:
yoo-e/weixin-mp-sdk
WeiXin/PublicPlatform/QRCode.hs
mit
2,683
0
16
797
527
293
234
54
2
-- -- -- ------------------ -- Exercise 11.26. ------------------ -- -- -- module E'11'26 where -- Note: Use/See templates for proofs by extensionality. -- --------------- -- 1. Proposition: -- --------------- -- -- id . f = f -- -- -- Proof By Extensionality: -- ------------------------ -- -- (id . f) x -- = id (f x) -- = f x -- -- -- ■ (1. Proof)
pascal-knodel/haskell-craft
_/links/E'11'26.hs
mit
378
0
2
90
30
29
1
1
0
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, CPP, OverloadedStrings, GeneralizedNewtypeDeriving #-} {- Copyright (C) 2009-2014 John MacFarlane <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Templates Copyright : Copyright (C) 2009-2014 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <[email protected]> Stability : alpha Portability : portable A simple templating system with variable substitution and conditionals. The following program illustrates its use: > {-# LANGUAGE OverloadedStrings #-} > import Data.Text > import Data.Aeson > import Text.Pandoc.Templates > > data Employee = Employee { firstName :: String > , lastName :: String > , salary :: Maybe Int } > instance ToJSON Employee where > toJSON e = object [ "name" .= object [ "first" .= firstName e > , "last" .= lastName e ] > , "salary" .= salary e ] > > employees :: [Employee] > employees = [ Employee "John" "Doe" Nothing > , Employee "Omar" "Smith" (Just 30000) > , Employee "Sara" "Chen" (Just 60000) ] > > template :: Template > template = either error id $ compileTemplate > "$for(employee)$Hi, $employee.name.first$. $if(employee.salary)$You make $employee.salary$.$else$No salary data.$endif$$sep$\n$endfor$" > > main = putStrLn $ renderTemplate template $ object ["employee" .= employees ] A slot for an interpolated variable is a variable name surrounded by dollar signs. To include a literal @$@ in your template, use @$$@. Variable names must begin with a letter and can contain letters, numbers, @_@, @-@, and @.@. The values of variables are determined by a JSON object that is passed as a parameter to @renderTemplate@. So, for example, @title@ will return the value of the @title@ field, and @employee.salary@ will return the value of the @salary@ field of the object that is the value of the @employee@ field. The value of a variable will be indented to the same level as the variable. A conditional begins with @$if(variable_name)$@ and ends with @$endif$@. It may optionally contain an @$else$@ section. The if section is used if @variable_name@ has a non-null value, otherwise the else section is used. Conditional keywords should not be indented, or unexpected spacing problems may occur. The @$for$@ keyword can be used to iterate over an array. If the value of the associated variable is not an array, a single iteration will be performed on its value. You may optionally specify separators using @$sep$@, as in the example above. -} module Text.Pandoc.Templates ( renderTemplate , renderTemplate' , TemplateTarget(..) , varListToJSON , compileTemplate , Template , getDefaultTemplate ) where import Data.Char (isAlphaNum) import Control.Monad (guard, when) import Data.Aeson (ToJSON(..), Value(..)) import qualified Text.Parsec as P import Text.Parsec.Text (Parser) import Control.Applicative import qualified Data.Text as T import Data.Text (Text) import Data.Text.Encoding (encodeUtf8) import Text.Pandoc.Compat.Monoid ((<>), Monoid(..)) import Data.List (intersperse) import System.FilePath ((</>), (<.>)) import qualified Data.Map as M import qualified Data.HashMap.Strict as H import Data.Foldable (toList) import qualified Control.Exception.Extensible as E (try, IOException) #if MIN_VERSION_blaze_html(0,5,0) import Text.Blaze.Html (Html) import Text.Blaze.Internal (preEscapedText) #else import Text.Blaze (preEscapedText, Html) #endif import Data.ByteString.Lazy (ByteString, fromChunks) import Text.Pandoc.Shared (readDataFileUTF8, ordNub) import Data.Vector ((!?)) -- | Get default template for the specified writer. getDefaultTemplate :: (Maybe FilePath) -- ^ User data directory to search first -> String -- ^ Name of writer -> IO (Either E.IOException String) getDefaultTemplate user writer = do let format = takeWhile (`notElem` "+-") writer -- strip off extensions case format of "native" -> return $ Right "" "json" -> return $ Right "" "docx" -> return $ Right "" "odt" -> getDefaultTemplate user "opendocument" "markdown_strict" -> getDefaultTemplate user "markdown" "multimarkdown" -> getDefaultTemplate user "markdown" "markdown_github" -> getDefaultTemplate user "markdown" "markdown_mmd" -> getDefaultTemplate user "markdown" "markdown_phpextra" -> getDefaultTemplate user "markdown" _ -> let fname = "templates" </> "default" <.> format in E.try $ readDataFileUTF8 user fname newtype Template = Template { unTemplate :: Value -> Text } deriving Monoid type Variable = [Text] class TemplateTarget a where toTarget :: Text -> a instance TemplateTarget Text where toTarget = id instance TemplateTarget String where toTarget = T.unpack instance TemplateTarget ByteString where toTarget = fromChunks . (:[]) . encodeUtf8 instance TemplateTarget Html where toTarget = preEscapedText varListToJSON :: [(String, String)] -> Value varListToJSON assoc = toJSON $ M.fromList assoc' where assoc' = [(T.pack k, toVal [T.pack z | (y,z) <- assoc, not (null z), y == k]) | k <- ordNub $ map fst assoc ] toVal [x] = toJSON x toVal [] = Null toVal xs = toJSON xs renderTemplate :: (ToJSON a, TemplateTarget b) => Template -> a -> b renderTemplate (Template f) context = toTarget $ f $ toJSON context compileTemplate :: Text -> Either String Template compileTemplate template = case P.parse (pTemplate <* P.eof) "template" template of Left e -> Left (show e) Right x -> Right x -- | Like 'renderTemplate', but compiles the template first, -- raising an error if compilation fails. renderTemplate' :: (ToJSON a, TemplateTarget b) => String -> a -> b renderTemplate' template = renderTemplate (either error id $ compileTemplate $ T.pack template) var :: Variable -> Template var = Template . resolveVar resolveVar :: Variable -> Value -> Text resolveVar var' val = case multiLookup var' val of Just (Array vec) -> maybe mempty (resolveVar []) $ vec !? 0 Just (String t) -> T.stripEnd t Just (Number n) -> T.pack $ show n Just (Bool True) -> "true" Just (Object _) -> "true" Just _ -> mempty Nothing -> mempty multiLookup :: [Text] -> Value -> Maybe Value multiLookup [] x = Just x multiLookup (v:vs) (Object o) = H.lookup v o >>= multiLookup vs multiLookup _ _ = Nothing lit :: Text -> Template lit = Template . const cond :: Variable -> Template -> Template -> Template cond var' (Template ifyes) (Template ifno) = Template $ \val -> case resolveVar var' val of "" -> ifno val _ -> ifyes val iter :: Variable -> Template -> Template -> Template iter var' template sep = Template $ \val -> unTemplate (case multiLookup var' val of Just (Array vec) -> mconcat $ intersperse sep $ map (setVar template var') $ toList vec Just x -> cond var' (setVar template var' x) mempty Nothing -> mempty) val setVar :: Template -> Variable -> Value -> Template setVar (Template f) var' val = Template $ f . replaceVar var' val replaceVar :: Variable -> Value -> Value -> Value replaceVar [] new _ = new replaceVar (v:vs) new (Object o) = Object $ H.adjust (\x -> replaceVar vs new x) v o replaceVar _ _ old = old --- parsing pTemplate :: Parser Template pTemplate = do sp <- P.option mempty pInitialSpace rest <- mconcat <$> many (pConditional <|> pFor <|> pNewline <|> pVar <|> pLit <|> pEscapedDollar) return $ sp <> rest takeWhile1 :: (Char -> Bool) -> Parser Text takeWhile1 f = T.pack <$> P.many1 (P.satisfy f) pLit :: Parser Template pLit = lit <$> takeWhile1 (\x -> x /='$' && x /= '\n') pNewline :: Parser Template pNewline = do P.char '\n' sp <- P.option mempty pInitialSpace return $ lit "\n" <> sp pInitialSpace :: Parser Template pInitialSpace = do sps <- takeWhile1 (==' ') let indentVar = if T.null sps then id else indent (T.length sps) v <- P.option mempty $ indentVar <$> pVar return $ lit sps <> v pEscapedDollar :: Parser Template pEscapedDollar = lit "$" <$ P.try (P.string "$$") pVar :: Parser Template pVar = var <$> (P.try $ P.char '$' *> pIdent <* P.char '$') pIdent :: Parser [Text] pIdent = do first <- pIdentPart rest <- many (P.char '.' *> pIdentPart) return (first:rest) pIdentPart :: Parser Text pIdentPart = P.try $ do first <- P.letter rest <- T.pack <$> P.many (P.satisfy (\c -> isAlphaNum c || c == '_' || c == '-')) let id' = T.singleton first <> rest guard $ id' `notElem` reservedWords return id' reservedWords :: [Text] reservedWords = ["else","endif","for","endfor","sep"] skipEndline :: Parser () skipEndline = P.try $ P.skipMany (P.satisfy (`elem` " \t")) >> P.char '\n' >> return () pConditional :: Parser Template pConditional = do P.try $ P.string "$if(" id' <- pIdent P.string ")$" -- if newline after the "if", then a newline after "endif" will be swallowed multiline <- P.option False (True <$ skipEndline) ifContents <- pTemplate elseContents <- P.option mempty $ P.try $ do P.string "$else$" when multiline $ P.option () skipEndline pTemplate P.string "$endif$" when multiline $ P.option () skipEndline return $ cond id' ifContents elseContents pFor :: Parser Template pFor = do P.try $ P.string "$for(" id' <- pIdent P.string ")$" -- if newline after the "for", then a newline after "endfor" will be swallowed multiline <- P.option False $ skipEndline >> return True contents <- pTemplate sep <- P.option mempty $ do P.try $ P.string "$sep$" when multiline $ P.option () skipEndline pTemplate P.string "$endfor$" when multiline $ P.option () skipEndline return $ iter id' contents sep indent :: Int -> Template -> Template indent 0 x = x indent ind (Template f) = Template $ \val -> indent' (f val) where indent' t = T.concat $ intersperse ("\n" <> T.replicate ind " ") $ T.lines t
peter-fogg/pardoc
src/Text/Pandoc/Templates.hs
gpl-2.0
11,546
0
19
3,030
2,664
1,359
1,305
196
10
module Hilbert.Derivation ( Derivation , derive , example ) where import Hilbert.Env import Hilbert.Actions import Autolib.ToDoc import Autolib.Reader import Autolib.Reporter import Autolib.FiniteMap import Autolib.TES.Identifier import Autolib.TES import Autolib.Size import Data.Typeable data Derivation = Derivation { env :: Env Action , act :: Action } deriving Typeable example :: Derivation example = read $ unlines [ "let { Fx = sub H13 { A = x && y, B = x } " , " , Px = sub H4 { A = x, B = y } " , "} in mopo Px Fx" ] instance Size Derivation where size = size . env instance ToDoc Derivation where toDoc d = vcat [ text "let" <+> toDoc ( env d ) , text "in" <+> toDoc ( act d ) ] instance Reader Derivation where reader = do my_reserved "let" e <- reader my_reserved "in" r <- reader return $ Derivation { env = e, act = r } derive axioms d = do e <- foldM ( \ e ( k, ( name, action ) ) -> do inform $ text "Schritt" <+> toDoc k v <- nested 4 $ informed_value e action extend e ( name, v ) ) axioms ( zip [1 :: Int ..] $ contents $ env d ) v <- informed_value e $ act d return v
florianpilz/autotool
src/Hilbert/Derivation.hs
gpl-2.0
1,226
26
12
360
271
170
101
43
1
{- | Module : ./Temporal/ModalCaslToNuSmvLtl.hs Copyright : (c) Klaus Hartke, Uni Bremen 2008 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : experimental Portability : portable -} module ModalCaslToNuSmvLtl where import Control.Monad as Monad import Data.Maybe as Maybe import Text.ParserCombinators.Parsec hiding (State) import ModalCasl as Casl import NuSmvLtl as Ltl {- ---------------------------------------------------------------------------- Convert Modal CASL formulas to LTL formulas recognized by NuSMV ---------------------------------------------------------------------------- -} convert :: Casl.StateFormula a -> Maybe (Ltl.Formula a) convert (Casl.Var x) = Just (Ltl.Var x) convert (Casl.A phi) = convert' phi convert _ = Nothing convert' :: Casl.PathFormula a -> Maybe (Ltl.Formula a) convert' (Casl.Por (Casl.Pnot phi) psi) = liftM2 Ltl.Impl (convert' phi) (convert' psi) convert' (Casl.State (Casl.Var x)) = Just (Ltl.Var x) convert' (Casl.Pnot phi) = liftM Ltl.Not (convert' phi) convert' (Casl.Pand phi psi) = liftM2 Ltl.And (convert' phi) (convert' psi) convert' (Casl.Por phi psi) = liftM2 Ltl.Or (convert' phi) (convert' psi) convert' (Casl.X phi) = liftM Ltl.X (convert' phi) convert' (Casl.G phi) = liftM Ltl.G (convert' phi) convert' (Casl.F phi) = liftM Ltl.F (convert' phi) convert' (Casl.W phi psi) = convert' ((phi `Casl.Pand` psi) `Casl.B` (Casl.Pnot phi `Casl.Pand` psi)) convert' (Casl.U phi psi) = convert' (psi `Casl.B` (Casl.Pnot phi `Casl.Pand` Casl.Pnot psi)) convert' (Casl.B phi psi) = liftM2 Ltl.V (convert' phi) (convert' psi) convert' (Casl.W' phi psi) = convert' (Casl.Pnot psi `Casl.U'` (phi `Casl.Pand` psi)) convert' (Casl.U' phi psi) = liftM2 Ltl.U (convert' phi) (convert' psi) convert' (Casl.B' phi psi) = convert' (Casl.Pnot psi `Casl.U'` (phi `Casl.Pand` Casl.Pnot psi)) convert' (Casl.XPast phi) = liftM Ltl.Y (convert' phi) convert' (Casl.GPast phi) = liftM Ltl.H (convert' phi) convert' (Casl.FPast phi) = liftM Ltl.O (convert' phi) convert' (Casl.WPast phi psi) = convert' ((phi `Casl.Pand` psi) `Casl.BPast` (Casl.Pnot phi `Casl.Pand` psi)) convert' (Casl.UPast phi psi) = convert' (psi `Casl.BPast` (Casl.Pnot phi `Casl.Pand` Casl.Pnot psi)) convert' (Casl.BPast phi psi) = liftM2 Ltl.T (convert' phi) (convert' psi) convert' (Casl.WPast' phi psi) = convert' (Casl.Pnot psi `Casl.UPast'` (phi `Casl.Pand` psi)) convert' (Casl.UPast' phi psi) = liftM2 Ltl.S (convert' phi) (convert' psi) convert' (Casl.BPast' phi psi) = convert' (Casl.Pnot psi `Casl.UPast'` (phi `Casl.Pand` Casl.Pnot psi)) convert' (Casl.XPast' phi) = liftM Ltl.Z (convert' phi) convert' _ = Nothing -- ---------------------------------------------------------------------------- data Expr = Expr String instance Show Expr where show (Expr x) = x expr = liftM Expr (many1 (lower <|> char '=' <|> char '_' <|> char '.' <|> digit)) parseAndConvert :: String -> Formula Expr parseAndConvert text = let Right x = parse (Casl.parser expr) "<<input>>" text Just y = convert x in y -- ----------------------------------------------------------------------------
spechub/Hets
Temporal/ModalCaslToNuSmvLtl.hs
gpl-2.0
3,647
0
13
937
1,267
648
619
52
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.IAM.DeleteSigningCertificate -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes the specified signing certificate associated with the specified -- user. -- -- If you do not specify a user name, IAM determines the user name -- implicitly based on the AWS access key ID signing the request. Because -- this action works for access keys under the AWS account, you can use -- this action to manage root credentials even if the AWS account has no -- associated users. -- -- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteSigningCertificate.html AWS API Reference> for DeleteSigningCertificate. module Network.AWS.IAM.DeleteSigningCertificate ( -- * Creating a Request deleteSigningCertificate , DeleteSigningCertificate -- * Request Lenses , dscUserName , dscCertificateId -- * Destructuring the Response , deleteSigningCertificateResponse , DeleteSigningCertificateResponse ) where import Network.AWS.IAM.Types import Network.AWS.IAM.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'deleteSigningCertificate' smart constructor. data DeleteSigningCertificate = DeleteSigningCertificate' { _dscUserName :: !(Maybe Text) , _dscCertificateId :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteSigningCertificate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dscUserName' -- -- * 'dscCertificateId' deleteSigningCertificate :: Text -- ^ 'dscCertificateId' -> DeleteSigningCertificate deleteSigningCertificate pCertificateId_ = DeleteSigningCertificate' { _dscUserName = Nothing , _dscCertificateId = pCertificateId_ } -- | The name of the user the signing certificate belongs to. dscUserName :: Lens' DeleteSigningCertificate (Maybe Text) dscUserName = lens _dscUserName (\ s a -> s{_dscUserName = a}); -- | The ID of the signing certificate to delete. dscCertificateId :: Lens' DeleteSigningCertificate Text dscCertificateId = lens _dscCertificateId (\ s a -> s{_dscCertificateId = a}); instance AWSRequest DeleteSigningCertificate where type Rs DeleteSigningCertificate = DeleteSigningCertificateResponse request = postQuery iAM response = receiveNull DeleteSigningCertificateResponse' instance ToHeaders DeleteSigningCertificate where toHeaders = const mempty instance ToPath DeleteSigningCertificate where toPath = const "/" instance ToQuery DeleteSigningCertificate where toQuery DeleteSigningCertificate'{..} = mconcat ["Action" =: ("DeleteSigningCertificate" :: ByteString), "Version" =: ("2010-05-08" :: ByteString), "UserName" =: _dscUserName, "CertificateId" =: _dscCertificateId] -- | /See:/ 'deleteSigningCertificateResponse' smart constructor. data DeleteSigningCertificateResponse = DeleteSigningCertificateResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteSigningCertificateResponse' with the minimum fields required to make a request. -- deleteSigningCertificateResponse :: DeleteSigningCertificateResponse deleteSigningCertificateResponse = DeleteSigningCertificateResponse'
olorin/amazonka
amazonka-iam/gen/Network/AWS/IAM/DeleteSigningCertificate.hs
mpl-2.0
4,056
0
11
780
450
274
176
64
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.EC2.DescribeKeyPairs -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Describes one or more of your key pairs. -- -- For more information about key pairs, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html Key Pairs> in the /Amazon ElasticCompute Cloud User Guide for Linux/. -- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeKeyPairs.html> module Network.AWS.EC2.DescribeKeyPairs ( -- * Request DescribeKeyPairs -- ** Request constructor , describeKeyPairs -- ** Request lenses , dkp1DryRun , dkp1Filters , dkp1KeyNames -- * Response , DescribeKeyPairsResponse -- ** Response constructor , describeKeyPairsResponse -- ** Response lenses , dkprKeyPairs ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.EC2.Types import qualified GHC.Exts data DescribeKeyPairs = DescribeKeyPairs { _dkp1DryRun :: Maybe Bool , _dkp1Filters :: List "Filter" Filter , _dkp1KeyNames :: List "KeyName" Text } deriving (Eq, Read, Show) -- | 'DescribeKeyPairs' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dkp1DryRun' @::@ 'Maybe' 'Bool' -- -- * 'dkp1Filters' @::@ ['Filter'] -- -- * 'dkp1KeyNames' @::@ ['Text'] -- describeKeyPairs :: DescribeKeyPairs describeKeyPairs = DescribeKeyPairs { _dkp1DryRun = Nothing , _dkp1KeyNames = mempty , _dkp1Filters = mempty } dkp1DryRun :: Lens' DescribeKeyPairs (Maybe Bool) dkp1DryRun = lens _dkp1DryRun (\s a -> s { _dkp1DryRun = a }) -- | One or more filters. -- -- 'fingerprint' - The fingerprint of the key pair. -- -- 'key-name' - The name of the key pair. -- -- dkp1Filters :: Lens' DescribeKeyPairs [Filter] dkp1Filters = lens _dkp1Filters (\s a -> s { _dkp1Filters = a }) . _List -- | One or more key pair names. -- -- Default: Describes all your key pairs. dkp1KeyNames :: Lens' DescribeKeyPairs [Text] dkp1KeyNames = lens _dkp1KeyNames (\s a -> s { _dkp1KeyNames = a }) . _List newtype DescribeKeyPairsResponse = DescribeKeyPairsResponse { _dkprKeyPairs :: List "item" KeyPairInfo } deriving (Eq, Read, Show, Monoid, Semigroup) -- | 'DescribeKeyPairsResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dkprKeyPairs' @::@ ['KeyPairInfo'] -- describeKeyPairsResponse :: DescribeKeyPairsResponse describeKeyPairsResponse = DescribeKeyPairsResponse { _dkprKeyPairs = mempty } -- | Information about one or more key pairs. dkprKeyPairs :: Lens' DescribeKeyPairsResponse [KeyPairInfo] dkprKeyPairs = lens _dkprKeyPairs (\s a -> s { _dkprKeyPairs = a }) . _List instance ToPath DescribeKeyPairs where toPath = const "/" instance ToQuery DescribeKeyPairs where toQuery DescribeKeyPairs{..} = mconcat [ "DryRun" =? _dkp1DryRun , "Filter" `toQueryList` _dkp1Filters , "KeyName" `toQueryList` _dkp1KeyNames ] instance ToHeaders DescribeKeyPairs instance AWSRequest DescribeKeyPairs where type Sv DescribeKeyPairs = EC2 type Rs DescribeKeyPairs = DescribeKeyPairsResponse request = post "DescribeKeyPairs" response = xmlResponse instance FromXML DescribeKeyPairsResponse where parseXML x = DescribeKeyPairsResponse <$> x .@? "keySet" .!@ mempty
kim/amazonka
amazonka-ec2/gen/Network/AWS/EC2/DescribeKeyPairs.hs
mpl-2.0
4,315
0
10
903
582
356
226
64
1
{-| This module contains utilities related to the @Either@ type. -} module Language.K3.Utils.Either ( gatherParallelErrors ) where import Data.Either import Data.Monoid -- |Using @Either@ as a mechanism for error handling, perform numerous -- computations concurrently. Error terms must be monoidal and thus are -- concatenated if any errors occr. gatherParallelErrors :: (Monoid a) => [Either a b] -> Either a [b] gatherParallelErrors xs = let (errs,results) = partitionEithers xs in if null errs then Right results else Left $ mconcat errs
DaMSL/K3
src/Language/K3/Utils/Either.hs
apache-2.0
553
0
9
92
111
61
50
8
2
{-# OPTIONS_HADDOCK hide #-} module Main where import System.Exit import System.IO import System.Console.GetOpt import System.Environment import Network.SoundCloud (scResolve, scShowInfo) import qualified Network.SoundCloud.Track as Track data Options = Options { optTrackURL :: Maybe String , optOutput :: Maybe String , optInfo :: Maybe String , optResolve :: Maybe String } options :: [OptDescr (Options -> IO Options)] options = [ Option "t" ["track"] (ReqArg (\arg opt -> return opt { optTrackURL = return arg }) "URL") "Indicate the URL of the track to be downloaded." , Option "o" ["output"] (ReqArg (\arg opt -> return opt { optOutput = return arg }) "FILE") "Output File" , Option "i" ["info"] (ReqArg (\arg opt -> return opt { optInfo = return arg }) "URL") "Get info about the resource pointed by the URL" , Option "r" ["resolve"] (ReqArg (\arg opt -> return opt { optResolve = return arg }) "URL") "Resolve the SoundCloud's API URL for an arbitrary URL. Supports users, tracks, sets, groups and apps" , Option "h" ["help"] (NoArg (\_ -> exitHelp)) "Show usage info" ] defaultOptions :: Options defaultOptions = Options { optTrackURL = Nothing , optOutput = Nothing , optInfo = Nothing , optResolve = Nothing } processOpts :: (Maybe String, Maybe String, Maybe String, Maybe String) -> IO () processOpts opts = case opts of (Just a0, Just b0, Nothing, Nothing) -> Track.fetch a0 b0 (Just a0, Nothing, Nothing, Nothing) -> Track.fetch a0 "" (Nothing, Nothing, Just c0, Nothing) -> scShowInfo c0 (Nothing, Nothing, Nothing, Just d0) -> do uri <- scResolve d0 putStrLn uri (_, _, _, _) -> exitErrorHelp "" main :: IO () main = do args <- getArgs let (actions, _, _) = getOpt RequireOrder options args opts <- foldl (>>=) (return defaultOptions) actions let Options { optTrackURL = trackUrl , optOutput = output , optInfo = info , optResolve = resolve } = opts let optsTracker = (trackUrl, output, info, resolve) processOpts optsTracker exitErrorHelp :: String -> IO a exitErrorHelp msg = do hPutStrLn stderr msg hPutStrLn stderr "" showHelp exitFailure showHelp :: IO () showHelp = do prg <- getProgName hPutStrLn stderr (usageInfo prg options) hFlush stderr exitHelp :: IO a exitHelp = do showHelp exitSuccess
sebasmagri/HScD
src/hscd.hs
bsd-3-clause
2,897
0
14
1,041
802
426
376
79
5
{- (c) The University of Glasgow 2006 Functions for working with the typechecker environment (setters, getters...). -} {-# LANGUAGE CPP, ExplicitForAll, FlexibleInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Eta.TypeCheck.TcRnMonad( module Eta.TypeCheck.TcRnMonad, module Eta.TypeCheck.TcRnTypes, module Eta.Utils.IOEnv ) where import Eta.TypeCheck.TcRnTypes -- Re-export all import Eta.Utils.IOEnv -- Re-export all import Eta.TypeCheck.TcEvidence import {-# SOURCE #-} Eta.TypeCheck.TcSplice (runRemoteModFinalizers) import Eta.HsSyn.HsSyn hiding (LIE) import Eta.Main.HscTypes import Eta.BasicTypes.Module import Eta.BasicTypes.RdrName import Eta.BasicTypes.Name import Eta.Types.Type import Eta.TypeCheck.TcType import Eta.Types.InstEnv import Eta.Types.FamInstEnv import Eta.Prelude.PrelNames import Eta.Utils.Maybes import Eta.BasicTypes.Var import Eta.BasicTypes.Id import Eta.BasicTypes.VarSet import Eta.BasicTypes.VarEnv import Eta.Main.ErrUtils import Eta.BasicTypes.SrcLoc import Eta.BasicTypes.NameEnv import Eta.BasicTypes.NameSet import Eta.Utils.Bag import Eta.Utils.Outputable import qualified Eta.Utils.Outputable as Outputable import Eta.BasicTypes.UniqSupply import Eta.Utils.UniqFM import Eta.Main.DynFlags import Eta.Main.StaticFlags import Eta.Utils.FastString import Eta.Utils.Panic import Eta.Utils.Util import Eta.Main.Annotations import Eta.BasicTypes.BasicTypes( TopLevelFlag ) import Control.Exception import Data.IORef import qualified Data.Set as Set import Control.Monad import qualified Eta.LanguageExtensions as LangExt #ifdef ETA_REPL import qualified Data.Map as Map #endif {- ************************************************************************ * * initTc * * ************************************************************************ -} -- | Setup the initial typechecking environment initTc :: HscEnv -> HscSource -> Bool -- True <=> retain renamed syntax trees -> Module -> RealSrcSpan -> TcM r -> IO (Messages, Maybe r) -- Nothing => error thrown by the thing inside -- (error messages should have been printed already) initTc hsc_env hsc_src keep_rn_syntax mod loc do_this = do { errs_var <- newIORef (emptyBag, emptyBag) ; tvs_var <- newIORef emptyVarSet ; keep_var <- newIORef emptyNameSet ; used_rdr_var <- newIORef Set.empty ; th_var <- newIORef False ; th_splice_var<- newIORef False ; infer_var <- newIORef True ; lie_var <- newIORef emptyWC ; dfun_n_var <- newIORef emptyOccSet ; type_env_var <- case hsc_type_env_var hsc_env of { Just (_mod, te_var) -> return te_var ; Nothing -> newIORef emptyNameEnv } ; dependent_files_var <- newIORef [] ; static_wc_var <- newIORef emptyWC ; #ifdef ETA_REPL th_topdecls_var <- newIORef [] ; th_topnames_var <- newIORef emptyNameSet ; th_modfinalizers_var <- newIORef [] ; th_state_var <- newIORef Map.empty ; th_remote_state_var <- newIORef Nothing ; #endif /* ETA_REPL */ let { dflags = hsc_dflags hsc_env ; maybe_rn_syntax :: forall a. a -> Maybe a ; maybe_rn_syntax empty_val | keep_rn_syntax = Just empty_val | otherwise = Nothing ; gbl_env = TcGblEnv { #ifdef ETA_REPL tcg_th_topdecls = th_topdecls_var, tcg_th_topnames = th_topnames_var, tcg_th_modfinalizers = th_modfinalizers_var, tcg_th_state = th_state_var, tcg_th_remote_state = th_remote_state_var, #endif /* ETA_REPL */ tcg_mod = mod, tcg_semantic_mod = if thisPackage dflags == moduleUnitId mod then canonicalizeHomeModule dflags (moduleName mod) else mod, tcg_src = hsc_src, tcg_rdr_env = emptyGlobalRdrEnv, tcg_fix_env = emptyNameEnv, tcg_field_env = RecFields emptyNameEnv emptyNameSet, tcg_default = Nothing, tcg_type_env = emptyNameEnv, tcg_type_env_var = type_env_var, tcg_inst_env = emptyInstEnv, tcg_fam_inst_env = emptyFamInstEnv, tcg_ann_env = emptyAnnEnv, tcg_visible_orphan_mods = mkModuleSet [mod], tcg_th_used = th_var, tcg_th_splice_used = th_splice_var, tcg_exports = [], tcg_imports = emptyImportAvails, tcg_used_rdrnames = used_rdr_var, tcg_dus = emptyDUs, tcg_rn_imports = [], tcg_rn_exports = if hsc_src == HsigFile -- Always retain renamed syntax, so that we can give -- better errors. (TODO: how?) then Just [] else maybe_rn_syntax [], tcg_rn_decls = maybe_rn_syntax emptyRnGroup, tcg_binds = emptyLHsBinds, tcg_imp_specs = [], tcg_sigs = emptyNameSet, tcg_ev_binds = emptyBag, tcg_warns = NoWarnings, tcg_anns = [], tcg_tcs = [], tcg_insts = [], tcg_fam_insts = [], tcg_rules = [], tcg_fords = [], tcg_vects = [], tcg_patsyns = [], tcg_merged = [], tcg_dfun_n = dfun_n_var, tcg_keep = keep_var, tcg_doc_hdr = Nothing, tcg_hpc = False, tcg_main = Nothing, tcg_self_boot = NoSelfBoot, tcg_safeInfer = infer_var, tcg_dependent_files = dependent_files_var, tcg_tc_plugins = [], tcg_top_loc = loc, tcg_static_wc = static_wc_var } ; lcl_env = TcLclEnv { tcl_errs = errs_var, tcl_loc = loc, -- Should be over-ridden very soon! tcl_ctxt = [], tcl_rdr = emptyLocalRdrEnv, tcl_th_ctxt = topStage, tcl_th_bndrs = emptyNameEnv, tcl_arrow_ctxt = NoArrowCtxt, tcl_env = emptyNameEnv, tcl_bndrs = [], tcl_tidy = emptyTidyEnv, tcl_tyvars = tvs_var, tcl_lie = lie_var, tcl_tclvl = topTcLevel } ; } ; -- OK, here's the business end! maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $ do { r <- tryM do_this ; case r of Right res -> return (Just res) Left _ -> return Nothing } ; -- Check for unsolved constraints lie <- readIORef lie_var ; if isEmptyWC lie then return () else pprPanic "initTc: unsolved constraints" (ppr lie) ; -- Collect any error messages msgs <- readIORef errs_var ; let { final_res | errorsFound dflags msgs = Nothing | otherwise = maybe_res } ; return (msgs, final_res) } initTcInteractive :: HscEnv -> TcM a -> IO (Messages, Maybe a) -- Initialise the type checker monad for use in GHCi initTcInteractive hsc_env thing_inside = initTc hsc_env HsSrcFile False (icInteractiveModule (hsc_IC hsc_env)) (realSrcLocSpan interactive_src_loc) thing_inside where interactive_src_loc = mkRealSrcLoc (fsLit "<interactive>") 1 1 initTcForLookup :: HscEnv -> TcM a -> IO a -- The thing_inside is just going to look up something -- in the environment, so we don't need much setup initTcForLookup hsc_env thing_inside = do { (msgs, m) <- initTcInteractive hsc_env thing_inside ; case m of Nothing -> throwIO $ mkSrcErr $ snd msgs Just x -> return x } {- ************************************************************************ * * Initialisation * * ************************************************************************ -} initTcRnIf :: Char -- Tag for unique supply -> HscEnv -> gbl -> lcl -> TcRnIf gbl lcl a -> IO a initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside = do { us <- mkSplitUniqSupply uniq_tag ; ; us_var <- newIORef us ; ; let { env = Env { env_top = hsc_env, env_us = us_var, env_gbl = gbl_env, env_lcl = lcl_env} } ; runIOEnv env thing_inside } {- ************************************************************************ * * Simple accessors * * ************************************************************************ -} discardResult :: TcM a -> TcM () discardResult a = a >> return () getTopEnv :: TcRnIf gbl lcl HscEnv getTopEnv = do { env <- getEnv; return (env_top env) } updTopEnv :: (HscEnv -> HscEnv) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a updTopEnv upd = updEnv (\ env@(Env { env_top = top }) -> env { env_top = upd top }) getGblEnv :: TcRnIf gbl lcl gbl getGblEnv = do { Env {..} <- getEnv; return env_gbl } updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) -> env { env_gbl = upd gbl }) setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env }) getLclEnv :: TcRnIf gbl lcl lcl getLclEnv = do { Env {..} <- getEnv; return env_lcl } updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) -> env { env_lcl = upd lcl }) setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env }) getEnvs :: TcRnIf gbl lcl (gbl, lcl) getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) } setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env }) -- Command-line flags xoptM :: LangExt.Extension -> TcRnIf gbl lcl Bool xoptM flag = do { dflags <- getDynFlags; return (xopt flag dflags) } doptM :: DumpFlag -> TcRnIf gbl lcl Bool doptM flag = do { dflags <- getDynFlags; return (dopt flag dflags) } goptM :: GeneralFlag -> TcRnIf gbl lcl Bool goptM flag = do { dflags <- getDynFlags; return (gopt flag dflags) } woptM :: WarningFlag -> TcRnIf gbl lcl Bool woptM flag = do { dflags <- getDynFlags; return (wopt flag dflags) } setXOptM :: LangExt.Extension -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a setXOptM flag = updEnv (\ env@(Env { env_top = top }) -> env { env_top = top { hsc_dflags = xopt_set (hsc_dflags top) flag}} ) unsetGOptM :: GeneralFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a unsetGOptM flag = updEnv (\ env@(Env { env_top = top }) -> env { env_top = top { hsc_dflags = gopt_unset (hsc_dflags top) flag}} ) unsetWOptM :: WarningFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a unsetWOptM flag = updEnv (\ env@(Env { env_top = top }) -> env { env_top = top { hsc_dflags = wopt_unset (hsc_dflags top) flag}} ) -- | Do it flag is true whenDOptM :: DumpFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () whenDOptM flag thing_inside = do b <- doptM flag when b thing_inside whenGOptM :: GeneralFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () whenGOptM flag thing_inside = do b <- goptM flag when b thing_inside whenWOptM :: WarningFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () whenWOptM flag thing_inside = do b <- woptM flag when b thing_inside whenXOptM :: LangExt.Extension -> TcRnIf gbl lcl () -> TcRnIf gbl lcl () whenXOptM flag thing_inside = do b <- xoptM flag when b thing_inside getGhcMode :: TcRnIf gbl lcl GhcMode getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) } withDoDynamicToo :: TcRnIf gbl lcl a -> TcRnIf gbl lcl a withDoDynamicToo m = do env <- getEnv let dflags = extractDynFlags env dflags' = dynamicTooMkDynamicDynFlags dflags env' = replaceDynFlags env dflags' setEnv env' m getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState) getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) } getEps :: TcRnIf gbl lcl ExternalPackageState getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) } -- | Update the external package state. Returns the second result of the -- modifier function. -- -- This is an atomic operation and forces evaluation of the modified EPS in -- order to avoid space leaks. updateEps :: (ExternalPackageState -> (ExternalPackageState, a)) -> TcRnIf gbl lcl a updateEps upd_fn = do traceIf (text "updating EPS") eps_var <- getEpsVar atomicUpdMutVar' eps_var upd_fn -- | Update the external package state. -- -- This is an atomic operation and forces evaluation of the modified EPS in -- order to avoid space leaks. updateEps_ :: (ExternalPackageState -> ExternalPackageState) -> TcRnIf gbl lcl () updateEps_ upd_fn = do traceIf (text "updating EPS_") eps_var <- getEpsVar atomicUpdMutVar' eps_var (\eps -> (upd_fn eps, ())) getHpt :: TcRnIf gbl lcl HomePackageTable getHpt = do { env <- getTopEnv; return (hsc_HPT env) } getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable) getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env) ; return (eps, hsc_HPT env) } -- | A convenient wrapper for taking a @MaybeErr MsgDoc a@ and throwing -- an exception if it is an error. withException :: TcRnIf gbl lcl (MaybeErr MsgDoc a) -> TcRnIf gbl lcl a withException do_this = do r <- do_this dflags <- getDynFlags case r of Failed err -> liftIO $ throwGhcExceptionIO (ProgramError (showSDoc dflags err)) Succeeded result -> return result {- ************************************************************************ * * Arrow scopes * * ************************************************************************ -} newArrowScope :: TcM a -> TcM a newArrowScope = updLclEnv $ \env -> env { tcl_arrow_ctxt = ArrowCtxt (tcl_rdr env) (tcl_lie env) } -- Return to the stored environment (from the enclosing proc) escapeArrowScope :: TcM a -> TcM a escapeArrowScope = updLclEnv $ \ env -> case tcl_arrow_ctxt env of NoArrowCtxt -> env ArrowCtxt rdr_env lie -> env { tcl_arrow_ctxt = NoArrowCtxt , tcl_lie = lie , tcl_rdr = rdr_env } {- ************************************************************************ * * Unique supply * * ************************************************************************ -} newUnique :: TcRnIf gbl lcl Unique newUnique = do { env <- getEnv ; let { u_var = env_us env } ; us <- readMutVar u_var ; case takeUniqFromSupply us of { (uniq, us') -> do { writeMutVar u_var us' ; return $! uniq }}} -- NOTE 1: we strictly split the supply, to avoid the possibility of leaving -- a chain of unevaluated supplies behind. -- NOTE 2: we use the uniq in the supply from the MutVar directly, and -- throw away one half of the new split supply. This is safe because this -- is the only place we use that unique. Using the other half of the split -- supply is safer, but slower. newUniqueSupply :: TcRnIf gbl lcl UniqSupply newUniqueSupply = do { env <- getEnv ; let { u_var = env_us env } ; us <- readMutVar u_var ; case splitUniqSupply us of { (us1,us2) -> do { writeMutVar u_var us1 ; return us2 }}} newLocalName :: Name -> TcM Name newLocalName name = newName (nameOccName name) newName :: OccName -> TcM Name newName occ = do { uniq <- newUnique ; loc <- getSrcSpanM ; return (mkInternalName uniq occ loc) } newSysName :: OccName -> TcM Name newSysName occ = do { uniq <- newUnique ; return (mkSystemName uniq occ) } newSysLocalId :: FastString -> TcType -> TcRnIf gbl lcl TcId newSysLocalId fs ty = do { u <- newUnique ; return (mkSysLocal fs u ty) } newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId] newSysLocalIds fs tys = do { us <- newUniqueSupply ; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) } instance MonadUnique (IOEnv (Env gbl lcl)) where getUniqueM = newUnique getUniqueSupplyM = newUniqueSupply {- ************************************************************************ * * Debugging * * ************************************************************************ -} newTcRef :: a -> TcRnIf gbl lcl (TcRef a) newTcRef = newMutVar readTcRef :: TcRef a -> TcRnIf gbl lcl a readTcRef = readMutVar writeTcRef :: TcRef a -> a -> TcRnIf gbl lcl () writeTcRef = writeMutVar updTcRef :: TcRef a -> (a -> a) -> TcRnIf gbl lcl () -- Returns () updTcRef ref fn = liftIO $ do { old <- readIORef ref ; writeIORef ref (fn old) } updTcRefX :: TcRef a -> (a -> a) -> TcRnIf gbl lcl a -- Returns previous value updTcRefX ref fn = liftIO $ do { old <- readIORef ref ; writeIORef ref (fn old) ; return old } {- ************************************************************************ * * Debugging * * ************************************************************************ -} traceTc :: String -> SDoc -> TcRn () traceTc herald doc = traceTcN 1 (hang (text herald) 2 doc) -- | Typechecker trace traceTcN :: Int -> SDoc -> TcRn () traceTcN level doc = do dflags <- getDynFlags when (level <= traceLevel dflags && not opt_NoDebugOutput) $ traceOptTcRn Opt_D_dump_tc_trace doc -- Renamer Trace traceRn :: String -> SDoc -> TcRn () traceRn = labelledTraceOptTcRn Opt_D_dump_rn_trace -- | Trace when a certain flag is enabled. This is like `traceOptTcRn` -- but accepts a string as a label and formats the trace message uniformly. labelledTraceOptTcRn :: DumpFlag -> String -> SDoc -> TcRn () labelledTraceOptTcRn flag herald doc = do traceOptTcRn flag (formatTraceMsg herald doc) formatTraceMsg :: String -> SDoc -> SDoc formatTraceMsg herald doc = hang (text herald) 2 doc -- | Output a doc if the given 'DumpFlag' is set. -- -- By default this logs to stdout -- However, if the `-ddump-to-file` flag is set, -- then this will dump output to a file -- -- Just a wrapper for 'dumpSDoc' traceOptTcRn :: DumpFlag -> SDoc -> TcRn () traceOptTcRn flag doc = do { dflags <- getDynFlags ; when (dopt flag dflags) (traceTcRn flag doc) } traceTcRn :: DumpFlag -> SDoc -> TcRn () -- ^ Unconditionally dump some trace output -- -- The DumpFlag is used only to set the output filename -- for --dump-to-file, not to decide whether or not to output -- That part is done by the caller traceTcRn flag doc = do { real_doc <- prettyDoc doc ; dflags <- getDynFlags ; printer <- getPrintUnqualified dflags ; liftIO $ dumpSDoc dflags printer flag "" real_doc } where -- Add current location if opt_PprStyle_Debug prettyDoc :: SDoc -> TcRn SDoc prettyDoc doc = if opt_PprStyle_Debug then do { loc <- getSrcSpanM; return $ mkLocMessage SevOutput loc doc } else return doc -- The full location is usually way too much getPrintUnqualified :: DynFlags -> TcRn PrintUnqualified getPrintUnqualified dflags = do { rdr_env <- getGlobalRdrEnv ; return $ mkPrintUnqualified dflags rdr_env } -- | Like logInfoTcRn, but for user consumption printForUserTcRn :: SDoc -> TcRn () printForUserTcRn doc = do { dflags <- getDynFlags ; printer <- getPrintUnqualified dflags ; liftIO (printInfoForUser dflags printer doc) } -- | Typechecker debug debugDumpTcRn :: SDoc -> TcRn () debugDumpTcRn doc = unless opt_NoDebugOutput $ traceOptTcRn Opt_D_dump_tc doc {- traceIf and traceHiDiffs work in the TcRnIf monad, where no RdrEnv is available. Alas, they behave inconsistently with the other stuff; e.g. are unaffected by -dump-to-file. -} traceIf, traceHiDiffs :: SDoc -> TcRnIf m n () traceIf = traceOptIf Opt_D_dump_if_trace traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs traceOptIf :: DumpFlag -> SDoc -> TcRnIf m n () traceOptIf flag doc = whenDOptM flag $ -- No RdrEnv available, so qualify everything do { dflags <- getDynFlags ; liftIO (putMsg dflags doc) } {- ************************************************************************ * * Typechecker global environment * * ************************************************************************ -} -- -- setModule :: Module -> TcRn a -> TcRn a -- setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside getIsGHCi :: TcRn Bool getIsGHCi = do { mod <- getModule ; return (isInteractiveModule mod) } getGHCiMonad :: TcRn Name getGHCiMonad = do { hsc <- getTopEnv; return (ic_monad $ hsc_IC hsc) } getInteractivePrintName :: TcRn Name getInteractivePrintName = do { hsc <- getTopEnv; return (ic_int_print $ hsc_IC hsc) } getItName :: SrcSpan -> TcRn Name getItName loc = do hsc <- getTopEnv itNo <- icItCounterInc (hsc_IC hsc) uniq <- newUnique return $ itName (fromIntegral itNo) uniq loc tcIsHsBootOrSig :: TcRn Bool tcIsHsBootOrSig = do { env <- getGblEnv; return (isHsBootOrSig (tcg_src env)) } tcSelfBootInfo :: TcRn SelfBootInfo tcSelfBootInfo = do { env <- getGblEnv; return (tcg_self_boot env) } getGlobalRdrEnv :: TcRn GlobalRdrEnv getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) } getRdrEnvs :: TcRn (GlobalRdrEnv, LocalRdrEnv) getRdrEnvs = do { (gbl,lcl) <- getEnvs; return (tcg_rdr_env gbl, tcl_rdr lcl) } getImports :: TcRn ImportAvails getImports = do { env <- getGblEnv; return (tcg_imports env) } getFixityEnv :: TcRn FixityEnv getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) } extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a extendFixityEnv new_bit = updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) -> env {tcg_fix_env = extendNameEnvList old_fix_env new_bit}) getRecFieldEnv :: TcRn RecFieldEnv getRecFieldEnv = do { env <- getGblEnv; return (tcg_field_env env) } getDeclaredDefaultTys :: TcRn (Maybe [Type]) getDeclaredDefaultTys = do { env <- getGblEnv; return (tcg_default env) } addDependentFiles :: [FilePath] -> TcRn () addDependentFiles fs = do ref <- fmap tcg_dependent_files getGblEnv dep_files <- readTcRef ref writeTcRef ref (fs ++ dep_files) {- ************************************************************************ * * Error management * * ************************************************************************ -} getSrcSpanM :: TcRn SrcSpan -- Avoid clash with Name.getSrcLoc getSrcSpanM = do { env <- getLclEnv; return (RealSrcSpan (tcl_loc env)) } setSrcSpan :: SrcSpan -> TcRn a -> TcRn a setSrcSpan (RealSrcSpan real_loc) thing_inside = updLclEnv (\env -> env { tcl_loc = real_loc }) thing_inside -- Don't overwrite useful info with useless: setSrcSpan (UnhelpfulSpan _) thing_inside = thing_inside addLocM :: (a -> TcM b) -> Located a -> TcM b addLocM fn (L loc a) = setSrcSpan loc $ fn a wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b) wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b) wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c) wrapLocFstM fn (L loc a) = setSrcSpan loc $ do (b,c) <- fn a return (L loc b, c) wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c) wrapLocSndM fn (L loc a) = setSrcSpan loc $ do (b,c) <- fn a return (b, L loc c) -- Reporting errors getErrsVar :: TcRn (TcRef Messages) getErrsVar = do { env <- getLclEnv; return (tcl_errs env) } setErrsVar :: TcRef Messages -> TcRn a -> TcRn a setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v }) addErr :: MsgDoc -> TcRn () -- Ignores the context stack addErr msg = do { loc <- getSrcSpanM; addErrAt loc msg } failWith :: MsgDoc -> TcRn a failWith msg = addErr msg >> failM addErrAt :: SrcSpan -> MsgDoc -> TcRn () -- addErrAt is mainly (exclusively?) used by the renamer, where -- tidying is not an issue, but it's all lazy so the extra -- work doesn't matter addErrAt loc msg = do { ctxt <- getErrCtxt ; tidy_env <- tcInitTidyEnv ; err_info <- mkErrInfo tidy_env ctxt ; addLongErrAt loc msg err_info } addErrs :: [(SrcSpan,MsgDoc)] -> TcRn () addErrs msgs = mapM_ add msgs where add (loc,msg) = addErrAt loc msg checkErr :: Bool -> MsgDoc -> TcRn () -- Add the error if the bool is False checkErr ok msg = unless ok (addErr msg) -- | Display a warning if a condition is met, -- and the warning is enabled warnIfFlag :: WarningFlag -> Bool -> MsgDoc -> TcRn () warnIfFlag warn_flag is_bad msg = do { warn_on <- woptM warn_flag ; when (warn_on && is_bad) $ addWarn (Reason warn_flag) msg } -- | Display a warning if a condition is met. warnIf :: Bool -> MsgDoc -> TcRn () warnIf is_bad msg = when is_bad (addWarn NoReason msg) addMessages :: Messages -> TcRn () addMessages (m_warns, m_errs) = do { errs_var <- getErrsVar ; (warns, errs) <- readTcRef errs_var ; writeTcRef errs_var (warns `unionBags` m_warns, errs `unionBags` m_errs) } discardWarnings :: TcRn a -> TcRn a -- Ignore warnings inside the thing inside; -- used to ignore-unused-variable warnings inside derived code discardWarnings thing_inside = do { errs_var <- getErrsVar ; (old_warns, _) <- readTcRef errs_var ; ; result <- thing_inside -- Revert warnings to old_warns ; (_new_warns, new_errs) <- readTcRef errs_var ; writeTcRef errs_var (old_warns, new_errs) ; return result } {- ************************************************************************ * * Shared error message stuff: renamer and typechecker * * ************************************************************************ -} mkLongErrAt :: SrcSpan -> MsgDoc -> MsgDoc -> TcRn ErrMsg mkLongErrAt loc msg extra = do { dflags <- getDynFlags ; printer <- getPrintUnqualified dflags ; return $ mkLongErrMsg dflags loc printer msg extra } addLongErrAt :: SrcSpan -> MsgDoc -> MsgDoc -> TcRn () addLongErrAt loc msg extra = mkLongErrAt loc msg extra >>= reportError reportErrors :: [ErrMsg] -> TcM () reportErrors = mapM_ reportError reportError :: ErrMsg -> TcRn () reportError err = do { traceTc "Adding error:" (pprLocErrMsg err) ; errs_var <- getErrsVar ; (warns, errs) <- readTcRef errs_var ; writeTcRef errs_var (warns, errs `snocBag` err) } reportWarning :: ErrMsg -> TcRn () reportWarning warn = do { traceTc "Adding warning:" (pprLocErrMsg warn) ; errs_var <- getErrsVar ; (warns, errs) <- readTcRef errs_var ; writeTcRef errs_var (warns `snocBag` warn, errs) } try_m :: TcRn r -> TcRn (Either IOEnvFailure r) -- Does tryM, with a debug-trace on failure try_m thing = do { (mb_r, lie) <- tryCaptureConstraints thing ; emitConstraints lie -- Debug trace ; case mb_r of Left exn -> traceTc "tryTc/recoverM recovering from" $ text (showException exn) Right {} -> return () ; return mb_r } ----------------------- recoverM :: TcRn r -- Recovery action; do this if the main one fails -> TcRn r -- Main action: do this first -> TcRn r -- Errors in 'thing' are retained recoverM recover thing = do { mb_res <- try_m thing ; case mb_res of Left _ -> recover Right res -> return res } ----------------------- mapAndRecoverM :: (a -> TcRn b) -> [a] -> TcRn [b] -- Drop elements of the input that fail, so the result -- list can be shorter than the argument list mapAndRecoverM _ [] = return [] mapAndRecoverM f (x:xs) = do { mb_r <- try_m (f x) ; rs <- mapAndRecoverM f xs ; return (case mb_r of Left _ -> rs Right r -> r:rs) } -- | Succeeds if applying the argument to all members of the lists succeeds, -- but nevertheless runs it on all arguments, to collect all errors. mapAndReportM :: (a -> TcRn b) -> [a] -> TcRn [b] mapAndReportM f xs = checkNoErrs (mapAndRecoverM f xs) ----------------------- tryTc :: TcRn a -> TcRn (Messages, Maybe a) -- (tryTc m) executes m, and returns -- Just r, if m succeeds (returning r) -- Nothing, if m fails -- It also returns all the errors and warnings accumulated by m -- It always succeeds (never raises an exception) tryTc m = do { errs_var <- newTcRef emptyMessages ; res <- try_m (setErrsVar errs_var m) ; msgs <- readTcRef errs_var ; return (msgs, case res of Left _ -> Nothing Right val -> Just val) -- The exception is always the IOEnv built-in -- in exception; see IOEnv.failM } ----------------------- tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a) -- Run the thing, returning -- Just r, if m succceeds with no error messages -- Nothing, if m fails, or if it succeeds but has error messages -- Either way, the messages are returned; even in the Just case -- there might be warnings tryTcErrs thing = do { (msgs, res) <- tryTc thing ; dflags <- getDynFlags ; let errs_found = errorsFound dflags msgs ; return (msgs, case res of Nothing -> Nothing Just val | errs_found -> Nothing | otherwise -> Just val) } ----------------------- tryTcLIE :: TcM a -> TcM (Messages, Maybe a) -- Just like tryTcErrs, except that it ensures that the LIE -- for the thing is propagated only if there are no errors -- Hence it's restricted to the type-check monad tryTcLIE thing_inside = do { ((msgs, mb_res), lie) <- captureConstraints (tryTcErrs thing_inside) ; ; case mb_res of Nothing -> return (msgs, Nothing) Just val -> do { emitConstraints lie; return (msgs, Just val) } } ----------------------- tryTcLIE_ :: TcM r -> TcM r -> TcM r -- (tryTcLIE_ r m) tries m; -- if m succeeds with no error messages, it's the answer -- otherwise tryTcLIE_ drops everything from m and tries r instead. tryTcLIE_ recover main = do { (msgs, mb_res) <- tryTcLIE main ; case mb_res of Just val -> do { addMessages msgs -- There might be warnings ; return val } Nothing -> recover -- Discard all msgs } ----------------------- checkNoErrs :: TcM r -> TcM r -- (checkNoErrs m) succeeds iff m succeeds and generates no errors -- If m fails then (checkNoErrsTc m) fails. -- If m succeeds, it checks whether m generated any errors messages -- (it might have recovered internally) -- If so, it fails too. -- Regardless, any errors generated by m are propagated to the enclosing context. checkNoErrs main = do { (msgs, mb_res) <- tryTcLIE main ; addMessages msgs ; case mb_res of Nothing -> failM Just val -> return val } whenNoErrs :: TcM () -> TcM () whenNoErrs thing = ifErrsM (return ()) thing ifErrsM :: TcRn r -> TcRn r -> TcRn r -- ifErrsM bale_out normal -- does 'bale_out' if there are errors in errors collection -- otherwise does 'normal' ifErrsM bale_out normal = do { errs_var <- getErrsVar ; msgs <- readTcRef errs_var ; dflags <- getDynFlags ; if errorsFound dflags msgs then bale_out else normal } failIfErrsM :: TcRn () -- Useful to avoid error cascades failIfErrsM = ifErrsM failM (return ()) checkTH :: Outputable a => a -> String -> TcRn () #ifdef ETA_REPL checkTH _ _ = return () -- OK #else checkTH e what = failTH e what -- Raise an error in a stage-1 compiler #endif failTH :: Outputable a => a -> String -> TcRn x failTH e what -- Raise an error in a stage-1 compiler = failWithTc (vcat [ hang (char 'A' <+> text what <+> ptext (sLit "requires GHC with interpreter support:")) 2 (ppr e) , ptext (sLit "Perhaps you are using a stage-1 compiler?") ]) {- ************************************************************************ * * Context management for the type checker * * ************************************************************************ -} getErrCtxt :: TcM [ErrCtxt] getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) } setErrCtxt :: [ErrCtxt] -> TcM a -> TcM a setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt }) addErrCtxt :: MsgDoc -> TcM a -> TcM a addErrCtxt msg = addErrCtxtM (\env -> return (env, msg)) addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, MsgDoc)) -> TcM a -> TcM a addErrCtxtM ctxt = updCtxt (\ ctxts -> (False, ctxt) : ctxts) addLandmarkErrCtxt :: MsgDoc -> TcM a -> TcM a addLandmarkErrCtxt msg = updCtxt (\ctxts -> (True, \env -> return (env,msg)) : ctxts) -- Helper function for the above updCtxt :: ([ErrCtxt] -> [ErrCtxt]) -> TcM a -> TcM a updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) -> env { tcl_ctxt = upd ctxt }) popErrCtxt :: TcM a -> TcM a popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (_ : ms) -> ms }) getCtLoc :: CtOrigin -> TcM CtLoc getCtLoc origin = do { env <- getLclEnv ; return (CtLoc { ctl_origin = origin , ctl_env = env , ctl_depth = initialSubGoalDepth }) } setCtLoc :: CtLoc -> TcM a -> TcM a -- Set the SrcSpan and error context from the CtLoc setCtLoc (CtLoc { ctl_env = lcl }) thing_inside = updLclEnv (\env -> env { tcl_loc = tcl_loc lcl , tcl_bndrs = tcl_bndrs lcl , tcl_ctxt = tcl_ctxt lcl }) thing_inside {- ************************************************************************ * * Error message generation (type checker) * * ************************************************************************ The addErrTc functions add an error message, but do not cause failure. The 'M' variants pass a TidyEnv that has already been used to tidy up the message; we then use it to tidy the context messages -} addErrTc :: MsgDoc -> TcM () addErrTc err_msg = do { env0 <- tcInitTidyEnv ; addErrTcM (env0, err_msg) } addErrsTc :: [MsgDoc] -> TcM () addErrsTc err_msgs = mapM_ addErrTc err_msgs addErrTcM :: (TidyEnv, MsgDoc) -> TcM () addErrTcM (tidy_env, err_msg) = do { ctxt <- getErrCtxt ; loc <- getSrcSpanM ; add_err_tcm tidy_env err_msg loc ctxt } -- Return the error message, instead of reporting it straight away mkErrTcM :: (TidyEnv, MsgDoc) -> TcM ErrMsg mkErrTcM (tidy_env, err_msg) = do { ctxt <- getErrCtxt ; loc <- getSrcSpanM ; err_info <- mkErrInfo tidy_env ctxt ; mkLongErrAt loc err_msg err_info } -- The failWith functions add an error message and cause failure failWithTc :: MsgDoc -> TcM a -- Add an error message and fail failWithTc err_msg = addErrTc err_msg >> failM failWithTcM :: (TidyEnv, MsgDoc) -> TcM a -- Add an error message and fail failWithTcM local_and_msg = addErrTcM local_and_msg >> failM checkTc :: Bool -> MsgDoc -> TcM () -- Check that the boolean is true checkTc True _ = return () checkTc False err = failWithTc err -- Warnings have no 'M' variant, nor failure -- | Display a warning if a condition is met. warnTc :: WarnReason -> Bool -> MsgDoc -> TcM () warnTc reason warn_if_true warn_msg | warn_if_true = addWarnTc reason warn_msg | otherwise = return () addWarnTc :: WarnReason -> MsgDoc -> TcM () addWarnTc reason msg = do { env0 <- tcInitTidyEnv ; addWarnTcM reason (env0, msg) } addWarnTcM :: WarnReason -> (TidyEnv, MsgDoc) -> TcM () addWarnTcM reason (env0, msg) = do { ctxt <- getErrCtxt ; err_info <- mkErrInfo env0 ctxt ; add_warn reason msg err_info } addWarn :: WarnReason -> MsgDoc -> TcRn () addWarn reason msg = add_warn reason msg Outputable.empty addWarnAt :: WarnReason -> SrcSpan -> MsgDoc -> TcRn () addWarnAt reason loc msg = add_warn_at reason loc msg Outputable.empty add_warn :: WarnReason -> MsgDoc -> MsgDoc -> TcRn () add_warn reason msg extra_info = do { loc <- getSrcSpanM ; add_warn_at reason loc msg extra_info } add_warn_at :: WarnReason -> SrcSpan -> MsgDoc -> MsgDoc -> TcRn () add_warn_at reason loc msg extra_info = do { dflags <- getDynFlags ; printer <- getPrintUnqualified dflags ; let { warn = makeIntoWarning reason $ mkLongWarnMsg dflags loc printer msg extra_info } ; reportWarning warn } tcInitTidyEnv :: TcM TidyEnv tcInitTidyEnv = do { lcl_env <- getLclEnv ; return (tcl_tidy lcl_env) } {- ----------------------------------- Other helper functions -} add_err_tcm :: TidyEnv -> MsgDoc -> SrcSpan -> [ErrCtxt] -> TcM () add_err_tcm tidy_env err_msg loc ctxt = do { err_info <- mkErrInfo tidy_env ctxt ; addLongErrAt loc err_msg err_info } mkErrInfo :: TidyEnv -> [ErrCtxt] -> TcM SDoc -- Tidy the error info, trimming excessive contexts mkErrInfo env ctxts -- | opt_PprStyle_Debug -- In -dppr-debug style the output -- = return empty -- just becomes too voluminous | otherwise = go 0 env ctxts where go :: Int -> TidyEnv -> [ErrCtxt] -> TcM SDoc go _ _ [] = return Outputable.empty go n env ((is_landmark, ctxt) : ctxts) | is_landmark || n < mAX_CONTEXTS -- Too verbose || opt_PprStyle_Debug = do { (env', msg) <- ctxt env ; let n' = if is_landmark then n else n+1 ; rest <- go n' env' ctxts ; return (msg $$ rest) } | otherwise = go n env ctxts mAX_CONTEXTS :: Int -- No more than this number of non-landmark contexts mAX_CONTEXTS = 3 -- debugTc is useful for monadic debugging code debugTc :: TcM () -> TcM () debugTc thing | debugIsOn = thing | otherwise = return () {- ************************************************************************ * * Type constraints * * ************************************************************************ -} newTcEvBinds :: TcM EvBindsVar newTcEvBinds = do { ref <- newTcRef emptyEvBindMap ; uniq <- newUnique ; return (EvBindsVar ref uniq) } addTcEvBind :: EvBindsVar -> EvVar -> EvTerm -> TcM () -- Add a binding to the TcEvBinds by side effect addTcEvBind (EvBindsVar ev_ref _) ev_id ev_tm = do { traceTc "addTcEvBind" $ vcat [ text "ev_id =" <+> ppr ev_id , text "ev_tm =" <+> ppr ev_tm ] ; bnds <- readTcRef ev_ref ; writeTcRef ev_ref (extendEvBinds bnds ev_id ev_tm) } getTcEvBinds :: EvBindsVar -> TcM (Bag EvBind) getTcEvBinds (EvBindsVar ev_ref _) = do { bnds <- readTcRef ev_ref ; return (evBindMapBinds bnds) } chooseUniqueOccTc :: (OccSet -> OccName) -> TcM OccName chooseUniqueOccTc fn = do { env <- getGblEnv ; let dfun_n_var = tcg_dfun_n env ; set <- readTcRef dfun_n_var ; let occ = fn set ; writeTcRef dfun_n_var (extendOccSet set occ) ; return occ } getConstraintVar :: TcM (TcRef WantedConstraints) getConstraintVar = do { env <- getLclEnv; return (tcl_lie env) } setConstraintVar :: TcRef WantedConstraints -> TcM a -> TcM a setConstraintVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var }) emitConstraints :: WantedConstraints -> TcM () emitConstraints ct = do { lie_var <- getConstraintVar ; updTcRef lie_var (`andWC` ct) } emitSimple :: Ct -> TcM () emitSimple ct = do { lie_var <- getConstraintVar ; updTcRef lie_var (`addSimples` unitBag ct) } emitSimples :: Cts -> TcM () emitSimples cts = do { lie_var <- getConstraintVar ; updTcRef lie_var (`addSimples` cts) } emitImplication :: Implication -> TcM () emitImplication ct = do { lie_var <- getConstraintVar ; updTcRef lie_var (`addImplics` unitBag ct) } emitImplications :: Bag Implication -> TcM () emitImplications ct = do { lie_var <- getConstraintVar ; updTcRef lie_var (`addImplics` ct) } emitInsoluble :: Ct -> TcM () emitInsoluble ct = do { lie_var <- getConstraintVar ; updTcRef lie_var (`addInsols` unitBag ct) ; v <- readTcRef lie_var ; traceTc "emitInsoluble" (ppr v) } tryCaptureConstraints :: TcM a -> TcM (Either IOEnvFailure a, WantedConstraints) -- (captureConstraints_maybe m) runs m, -- and returns the type constraints it generates -- It never throws an exception; instead if thing_inside fails, -- it returns Left exn and the insoluble constraints tryCaptureConstraints thing_inside = do { lie_var <- newTcRef emptyWC ; mb_res <- tryM $ updLclEnv (\ env -> env { tcl_lie = lie_var }) $ thing_inside ; lie <- readTcRef lie_var -- See Note [Constraints and errors] ; let lie_to_keep = case mb_res of Left {} -> insolublesOnly lie Right {} -> lie ; return (mb_res, lie_to_keep) } captureConstraints :: TcM a -> TcM (a, WantedConstraints) -- (captureConstraints m) runs m, and returns the type constraints it generates captureConstraints thing_inside = do { (mb_res, lie) <- tryCaptureConstraints thing_inside -- See Note [Constraints and errors] -- If the thing_inside threw an exception, emit the insoluble -- constraints only (returned by tryCaptureConstraints) -- so that they are not lost ; case mb_res of Left _ -> do { emitConstraints lie; failM } Right res -> return (res, lie) } captureTcLevel :: TcM a -> TcM (a, TcLevel) captureTcLevel thing_inside = do { env <- getLclEnv ; let tclvl' = pushTcLevel (tcl_tclvl env) ; res <- setLclEnv (env { tcl_tclvl = tclvl' }) thing_inside ; return (res, tclvl') } -- | The name says it all. The returned TcLevel is the *inner* TcLevel. pushLevelAndCaptureConstraints :: TcM a -> TcM (a, TcLevel, WantedConstraints) pushLevelAndCaptureConstraints thing_inside = do { env <- getLclEnv ; let tclvl' = pushTcLevel (tcl_tclvl env) ; (res, lie) <- setLclEnv (env { tcl_tclvl = tclvl' }) $ captureConstraints thing_inside ; return (res, tclvl', lie) } pushTcLevelM :: TcM a -> TcM a pushTcLevelM thing_inside = do { env <- getLclEnv ; let tclvl' = pushTcLevel (tcl_tclvl env) ; setLclEnv (env { tcl_tclvl = tclvl' }) thing_inside } pushTcLevelM2 :: TcM a -> TcM (a, TcLevel) -- See Note [TcLevel assignment] in TcType pushTcLevelM2 thing_inside = do { env <- getLclEnv ; let tclvl' = pushTcLevel (tcl_tclvl env) ; res <- setLclEnv (env { tcl_tclvl = tclvl' }) thing_inside ; return (res, tclvl') } getTcLevel :: TcM TcLevel getTcLevel = do { env <- getLclEnv ; return (tcl_tclvl env) } setTcLevel :: TcLevel -> TcM a -> TcM a setTcLevel tclvl thing_inside = updLclEnv (\env -> env { tcl_tclvl = tclvl }) thing_inside isTouchableTcM :: TcTyVar -> TcM Bool isTouchableTcM tv = do { env <- getLclEnv ; return (isTouchableMetaTyVar (tcl_tclvl env) tv) } getLclTypeEnv :: TcM TcTypeEnv getLclTypeEnv = do { env <- getLclEnv; return (tcl_env env) } setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a -- Set the local type envt, but do *not* disturb other fields, -- notably the lie_var setLclTypeEnv lcl_env thing_inside = updLclEnv upd thing_inside where upd env = env { tcl_env = tcl_env lcl_env, tcl_tyvars = tcl_tyvars lcl_env } traceTcConstraints :: String -> TcM () traceTcConstraints msg = do { lie_var <- getConstraintVar ; lie <- readTcRef lie_var ; traceTc (msg ++ ": LIE:") (ppr lie) } emitWildcardHoleConstraints :: [(Name, TcTyVar)] -> TcM () emitWildcardHoleConstraints wcs = do { ctLoc <- getCtLoc HoleOrigin ; forM_ wcs $ \(name, tv) -> do { ; let real_span = case nameSrcSpan name of RealSrcSpan span -> span UnhelpfulSpan str -> pprPanic "emitWildcardHoleConstraints" (ppr name <+> quotes (ftext str)) -- Wildcards are defined locally, and so have RealSrcSpans ctLoc' = setCtLocSpan ctLoc real_span ty = mkTyVarTy tv ev = mkLocalId name ty can = CHoleCan { cc_ev = CtWanted ty ev ctLoc' , cc_occ = occName name , cc_hole = TypeHole } ; emitInsoluble can } } {- Note [Constraints and errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this (Trac #12124): foo :: Maybe Int foo = return (case Left 3 of Left -> 1 -- Hard error here! _ -> 0) The call to 'return' will generate a (Monad m) wanted constraint; but then there'll be "hard error" (i.e. an exception in the TcM monad), from the unsaturated Left constructor pattern. We'll recover in tcPolyBinds, using recoverM. But then the final tcSimplifyTop will see that (Monad m) constraint, with 'm' utterly un-filled-in, and will emit a misleading error message. The underlying problem is that an exception interrupts the constraint gathering process. Bottom line: if we have an exception, it's best simply to discard any gathered constraints. Hence in 'try_m' we capture the constraints in a fresh variable, and only emit them into the surrounding context if we exit normally. If an exception is raised, simply discard the collected constraints... we have a hard error to report. So this capture-the-emit dance isn't as stupid as it looks :-). However suppose we throw an exception inside an invocation of captureConstraints, and discard all the constraints. Some of those constraints might be "variable out of scope" Hole constraints, and that might have been the actual original cause of the exception! For example (Trac #12529): f = p @ Int Here 'p' is out of scope, so we get an insolube Hole constraint. But the visible type application fails in the monad (thows an exception). We must not discard the out-of-scope error. So we /retain the insoluble constraints/ if there is an exception. Hence: - insolublesOnly in tryCaptureConstraints - emitConstraints in the Left case of captureConstraints Hover note that fresly-generated constraints like (Int ~ Bool), or ((a -> b) ~ Int) are all CNonCanonical, and hence won't be flagged as insoluble. The constraint solver does that. So they'll be discarded. That's probably ok; but see th/5358 as a not-so-good example: t1 :: Int t1 x = x -- Manifestly wrong foo = $(...raises exception...) We report the exception, but not the bug in t1. Oh well. Possible solution: make TcUnify.uType spot manifestly-insoluble constraints. ************************************************************************ * * Template Haskell context * * ************************************************************************ -} recordThUse :: TcM () recordThUse = do { env <- getGblEnv; writeTcRef (tcg_th_used env) True } recordThSpliceUse :: TcM () recordThSpliceUse = do { env <- getGblEnv; writeTcRef (tcg_th_splice_used env) True } keepAlive :: Name -> TcRn () -- Record the name in the keep-alive set keepAlive name = do { env <- getGblEnv ; traceRn "keep alive" (ppr name) ; updTcRef (tcg_keep env) (`extendNameSet` name) } getStage :: TcM ThStage getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) } getStageAndBindLevel :: Name -> TcRn (Maybe (TopLevelFlag, ThLevel, ThStage)) getStageAndBindLevel name = do { env <- getLclEnv; ; case lookupNameEnv (tcl_th_bndrs env) name of Nothing -> return Nothing Just (top_lvl, bind_lvl) -> return (Just (top_lvl, bind_lvl, tcl_th_ctxt env)) } setStage :: ThStage -> TcM a -> TcRn a setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s }) -- | Adds the given modFinalizers to the global environment and set them to use -- the current local environment. addModFinalizersWithLclEnv :: ThModFinalizers -> TcM () addModFinalizersWithLclEnv mod_finalizers = do lcl_env <- getLclEnv th_modfinalizers_var <- fmap tcg_th_modfinalizers getGblEnv updTcRef th_modfinalizers_var $ \fins -> setLclEnv lcl_env (runRemoteModFinalizers mod_finalizers) : fins {- ************************************************************************ * * Safe Haskell context * * ************************************************************************ -} -- | Mark that safe inference has failed recordUnsafeInfer :: TcM () recordUnsafeInfer = getGblEnv >>= \env -> writeTcRef (tcg_safeInfer env) False -- | Figure out the final correct safe haskell mode finalSafeMode :: DynFlags -> TcGblEnv -> IO SafeHaskellMode finalSafeMode dflags tcg_env = do safeInf <- readIORef (tcg_safeInfer tcg_env) return $ case safeHaskell dflags of Sf_None | safeInferOn dflags && safeInf -> Sf_Safe | otherwise -> Sf_None s -> s {- ************************************************************************ * * Stuff for the renamer's local env * * ************************************************************************ -} getLocalRdrEnv :: RnM LocalRdrEnv getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) } setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a setLocalRdrEnv rdr_env thing_inside = updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside {- ************************************************************************ * * Stuff for interface decls * * ************************************************************************ -} mkIfLclEnv :: Module -> SDoc -> Bool -> IfLclEnv mkIfLclEnv mod loc boot = IfLclEnv { if_mod = mod, if_loc = loc, if_boot = boot, if_tv_env = emptyUFM, if_nsubst = Nothing, if_id_env = emptyUFM } -- | Run an 'IfG' (top-level interface monad) computation inside an existing -- 'TcRn' (typecheck-renaming monad) computation by initializing an 'IfGblEnv' -- based on 'TcGblEnv'. initIfaceTcRn :: IfG a -> TcRn a initIfaceTcRn thing_inside = do { tcg_env <- getGblEnv ; dflags <- getDynFlags ; let !mod = tcg_semantic_mod tcg_env -- When we are instantiating a signature, we DEFINITELY -- do not want to knot tie. is_instantiate = unitIdIsDefinite (thisPackage dflags) && not (null (thisUnitIdInsts dflags)) ; let { if_env = IfGblEnv { if_rec_types = if is_instantiate then Nothing else Just (mod, get_type_env) } ; get_type_env = readTcRef (tcg_type_env_var tcg_env) } ; setEnvs (if_env, ()) thing_inside } -- Used when sucking in a ModIface into a ModDetails to put in -- the HPT. Notably, unlike initIfaceCheck, this does NOT use -- hsc_type_env_var (since we're not actually going to typecheck, -- so this variable will never get updated!) initIfaceLoad :: HscEnv -> IfG a -> IO a initIfaceLoad hsc_env do_this = do let gbl_env = IfGblEnv { -- if_doc = text "initIfaceLoad", if_rec_types = Nothing } initTcRnIf 'i' hsc_env gbl_env () do_this initIfaceCheck :: HscEnv -> IfG a -> IO a -- Used when checking the up-to-date-ness of the old Iface -- Initialise the environment with no useful info at all initIfaceCheck hsc_env do_this = do let rec_types = case hsc_type_env_var hsc_env of Just (mod,var) -> Just (mod, readTcRef var) Nothing -> Nothing gbl_env = IfGblEnv { if_rec_types = rec_types } initTcRnIf 'i' hsc_env gbl_env () do_this initIfaceLcl :: Module -> SDoc -> Bool -> IfL a -> IfM lcl a initIfaceLcl mod loc_doc hi_boot_file thing_inside = setLclEnv (mkIfLclEnv mod loc_doc hi_boot_file) thing_inside -- | Initialize interface typechecking, but with a 'NameShape' -- to apply when typechecking top-level 'OccName's (see -- 'lookupIfaceTop') initIfaceLclWithSubst :: Module -> SDoc -> Bool -> NameShape -> IfL a -> IfM lcl a initIfaceLclWithSubst mod loc_doc hi_boot_file nsubst thing_inside = setLclEnv ((mkIfLclEnv mod loc_doc hi_boot_file) { if_nsubst = Just nsubst }) thing_inside getIfModule :: IfL Module getIfModule = do { env <- getLclEnv; return (if_mod env) } -------------------- failIfM :: MsgDoc -> IfL a -- The Iface monad doesn't have a place to accumulate errors, so we -- just fall over fast if one happens; it "shouldnt happen". -- We use IfL here so that we can get context info out of the local env failIfM msg = do { env <- getLclEnv ; let full_msg = (if_loc env <> colon) $$ nest 2 msg ; dflags <- getDynFlags ; liftIO (putLogMsg dflags NoReason SevFatal noSrcSpan (defaultErrStyle dflags) full_msg) ; failM } -------------------- forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a) -- Run thing_inside in an interleaved thread. -- It shares everything with the parent thread, so this is DANGEROUS. -- -- It returns Nothing if the computation fails -- -- It's used for lazily type-checking interface -- signatures, which is pretty benign forkM_maybe doc thing_inside -- NB: Don't share the mutable env_us with the interleaved thread since env_us -- does not get updated atomically (e.g. in newUnique and newUniqueSupply). = do { child_us <- newUniqueSupply ; child_env_us <- newMutVar child_us -- see Note [Masking exceptions in forkM_maybe] ; unsafeInterleaveM $ uninterruptibleMaskM_ $ updEnv (\env -> env { env_us = child_env_us }) $ do { traceIf (text "Starting fork {" <+> doc) ; mb_res <- tryM $ updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $ thing_inside ; case mb_res of Right r -> do { traceIf (text "} ending fork" <+> doc) ; return (Just r) } Left exn -> do { -- Bleat about errors in the forked thread, if -ddump-if-trace is on -- Otherwise we silently discard errors. Errors can legitimately -- happen when compiling interface signatures (see tcInterfaceSigs) whenDOptM Opt_D_dump_if_trace $ do dflags <- getDynFlags let msg = hang (text "forkM failed:" <+> doc) 2 (text (show exn)) liftIO $ putLogMsg dflags NoReason SevFatal noSrcSpan (defaultErrStyle dflags) msg ; traceIf (text "} ending fork (badly)" <+> doc) ; return Nothing } }} forkM :: SDoc -> IfL a -> IfL a forkM doc thing_inside = do { mb_res <- forkM_maybe doc thing_inside ; return (case mb_res of Nothing -> pgmError "Cannot continue after interface file error" -- pprPanic "forkM" doc Just r -> r) } {- Note [Masking exceptions in forkM_maybe] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When using GHC-as-API it must be possible to interrupt snippets of code executed using runStmt (#1381). Since commit 02c4ab04 this is almost possible by throwing an asynchronous interrupt to the GHC thread. However, there is a subtle problem: runStmt first typechecks the code before running it, and the exception might interrupt the type checker rather than the code. Moreover, the typechecker might be inside an unsafeInterleaveIO (through forkM_maybe), and more importantly might be inside an exception handler inside that unsafeInterleaveIO. If that is the case, the exception handler will rethrow the asynchronous exception as a synchronous exception, and the exception will end up as the value of the unsafeInterleaveIO thunk (see #8006 for a detailed discussion). We don't currently know a general solution to this problem, but we can use uninterruptibleMask_ to avoid the situation. -}
rahulmutt/ghcvm
compiler/Eta/TypeCheck/TcRnMonad.hs
bsd-3-clause
61,023
62
25
18,997
13,487
7,038
6,449
-1
-1
-- The intention is that this will be the new unit test framework. -- Please add any working tests here. This file should do nothing -- but import tests from other modules. -- -- Stephen Blackheath, 2009 module Main where import PackageTests.BenchmarkExeV10.Check import PackageTests.BenchmarkOptions.Check import PackageTests.BenchmarkStanza.Check -- import PackageTests.BuildDeps.GlobalBuildDepsNotAdditive1.Check -- import PackageTests.BuildDeps.GlobalBuildDepsNotAdditive2.Check import PackageTests.BuildDeps.InternalLibrary0.Check import PackageTests.BuildDeps.InternalLibrary1.Check import PackageTests.BuildDeps.InternalLibrary2.Check import PackageTests.BuildDeps.InternalLibrary3.Check import PackageTests.BuildDeps.InternalLibrary4.Check import PackageTests.BuildDeps.SameDepsAllRound.Check import PackageTests.BuildDeps.TargetSpecificDeps1.Check import PackageTests.BuildDeps.TargetSpecificDeps2.Check import PackageTests.BuildDeps.TargetSpecificDeps3.Check import PackageTests.BuildTestSuiteDetailedV09.Check import PackageTests.PackageTester (PackageSpec(..), SuiteConfig(..), compileSetup) import PackageTests.PathsModule.Executable.Check import PackageTests.PathsModule.Library.Check import PackageTests.PreProcess.Check import PackageTests.PreProcessExtraSources.Check import PackageTests.TemplateHaskell.Check import PackageTests.CMain.Check import PackageTests.DeterministicAr.Check import PackageTests.EmptyLib.Check import PackageTests.Haddock.Check import PackageTests.TestOptions.Check import PackageTests.TestStanza.Check import PackageTests.TestSuiteExeV10.Check import PackageTests.OrderFlags.Check import PackageTests.ReexportedModules.Check import Distribution.Simple.Configure ( ConfigStateFileError(..), findDistPrefOrDefault, getConfigStateFile ) import Distribution.Simple.LocalBuildInfo (LocalBuildInfo(..)) import Distribution.Simple.Program.Types (programPath) import Distribution.Simple.Program.Builtin ( ghcProgram, ghcPkgProgram, haddockProgram ) import Distribution.Simple.Program.Db (requireProgram) import Distribution.Simple.Setup (Flag(..)) import Distribution.Simple.Utils (cabalVersion) import Distribution.Text (display) import Distribution.Verbosity (normal) import Distribution.Version (Version(Version)) import Control.Exception (try, throw) import Distribution.Compat.Environment ( setEnv ) import System.Directory ( canonicalizePath, setCurrentDirectory ) import System.FilePath ((</>)) import Test.Tasty import Test.Tasty.HUnit tests :: SuiteConfig -> Version -> [TestTree] tests config version = [ testCase "BuildDeps/SameDepsAllRound" (PackageTests.BuildDeps.SameDepsAllRound.Check.suite config) -- The two following tests were disabled by Johan Tibell as -- they have been failing for a long time: -- , testCase "BuildDeps/GlobalBuildDepsNotAdditive1/" -- (PackageTests.BuildDeps.GlobalBuildDepsNotAdditive1.Check.suite ghcPath) -- , testCase "BuildDeps/GlobalBuildDepsNotAdditive2/" -- (PackageTests.BuildDeps.GlobalBuildDepsNotAdditive2.Check.suite ghcPath) , testCase "BuildDeps/InternalLibrary0" (PackageTests.BuildDeps.InternalLibrary0.Check.suite config version) , testCase "PreProcess" (PackageTests.PreProcess.Check.suite config) , testCase "PreProcessExtraSources" (PackageTests.PreProcessExtraSources.Check.suite config) , testCase "TestStanza" (PackageTests.TestStanza.Check.suite config) -- ^ The Test stanza test will eventually be required -- only for higher versions. , testGroup "TestSuiteExeV10" (PackageTests.TestSuiteExeV10.Check.checks config) , testCase "TestOptions" (PackageTests.TestOptions.Check.suite config) , testCase "BenchmarkStanza" (PackageTests.BenchmarkStanza.Check.suite config) -- ^ The benchmark stanza test will eventually be required -- only for higher versions. , testCase "BenchmarkExeV10/Test" (PackageTests.BenchmarkExeV10.Check.checkBenchmark config) , testCase "BenchmarkOptions" (PackageTests.BenchmarkOptions.Check.suite config) , testCase "TemplateHaskell/vanilla" (PackageTests.TemplateHaskell.Check.vanilla config) , testCase "TemplateHaskell/profiling" (PackageTests.TemplateHaskell.Check.profiling config) , testCase "PathsModule/Executable" (PackageTests.PathsModule.Executable.Check.suite config) , testCase "PathsModule/Library" (PackageTests.PathsModule.Library.Check.suite config) , testCase "DeterministicAr" (PackageTests.DeterministicAr.Check.suite config) , testCase "EmptyLib/emptyLib" (PackageTests.EmptyLib.Check.emptyLib config) , testCase "Haddock" (PackageTests.Haddock.Check.suite config) , testCase "BuildTestSuiteDetailedV09" (PackageTests.BuildTestSuiteDetailedV09.Check.suite config) , testCase "OrderFlags" (PackageTests.OrderFlags.Check.suite config) , testCase "TemplateHaskell/dynamic" (PackageTests.TemplateHaskell.Check.dynamic config) , testCase "ReexportedModules" (PackageTests.ReexportedModules.Check.suite config) ] ++ -- These tests are only required to pass on cabal version >= 1.7 (if version >= Version [1, 7] [] then [ testCase "BuildDeps/TargetSpecificDeps1" (PackageTests.BuildDeps.TargetSpecificDeps1.Check.suite config) , testCase "BuildDeps/TargetSpecificDeps2" (PackageTests.BuildDeps.TargetSpecificDeps2.Check.suite config) , testCase "BuildDeps/TargetSpecificDeps3" (PackageTests.BuildDeps.TargetSpecificDeps3.Check.suite config) , testCase "BuildDeps/InternalLibrary1" (PackageTests.BuildDeps.InternalLibrary1.Check.suite config) , testCase "BuildDeps/InternalLibrary2" (PackageTests.BuildDeps.InternalLibrary2.Check.suite config) , testCase "BuildDeps/InternalLibrary3" (PackageTests.BuildDeps.InternalLibrary3.Check.suite config) , testCase "BuildDeps/InternalLibrary4" (PackageTests.BuildDeps.InternalLibrary4.Check.suite config) , testCase "PackageTests/CMain" (PackageTests.CMain.Check.checkBuild config) ] else []) main :: IO () main = do -- Find the builddir used to build Cabal distPref_ <- findDistPrefOrDefault NoFlag >>= canonicalizePath -- Use the default builddir for all of the subsequent package tests setEnv "CABAL_BUILDDIR" "dist" lbi <- getPersistBuildConfig_ (distPref_ </> "setup-config") (ghc, _) <- requireProgram normal ghcProgram (withPrograms lbi) (ghcPkg, _) <- requireProgram normal ghcPkgProgram (withPrograms lbi) (haddock, _) <- requireProgram normal haddockProgram (withPrograms lbi) let haddockPath = programPath haddock dbFile = distPref_ </> "package.conf.inplace" config = SuiteConfig { cabalDistPref = distPref_ , ghcPath = programPath ghc , ghcPkgPath = programPath ghcPkg , inplaceSpec = PackageSpec { directory = [] , configOpts = [ "--package-db=" ++ dbFile , "--constraint=Cabal == " ++ display cabalVersion ] , distPref = Nothing } } putStrLn $ "Cabal test suite - testing cabal version " ++ display cabalVersion putStrLn $ "Using ghc: " ++ ghcPath config putStrLn $ "Using ghc-pkg: " ++ ghcPkgPath config putStrLn $ "Using haddock: " ++ haddockPath setCurrentDirectory "tests" -- Create a shared Setup executable to speed up Simple tests compileSetup config "." defaultMain $ testGroup "Package Tests" (tests config cabalVersion) -- Like Distribution.Simple.Configure.getPersistBuildConfig but -- doesn't check that the Cabal version matches, which it doesn't when -- we run Cabal's own test suite, due to bootstrapping issues. getPersistBuildConfig_ :: FilePath -> IO LocalBuildInfo getPersistBuildConfig_ filename = do eLBI <- try $ getConfigStateFile filename case eLBI of Left (ConfigStateFileBadVersion _ _ (Right lbi)) -> return lbi Left (ConfigStateFileBadVersion _ _ (Left err)) -> throw err Left err -> throw err Right lbi -> return lbi
rimmington/cabal
Cabal/tests/PackageTests.hs
bsd-3-clause
8,337
0
16
1,465
1,455
836
619
140
4
-- FIXME See how much of this module can be deleted. {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# OPTIONS -fno-warn-unused-do-bind #-} -- | Functions for the GHC package database. module Stack.GhcPkg (findGhcPkgId ,findGhcPkgKey ,getGlobalDB ,EnvOverride ,envHelper ,createDatabase ,unregisterGhcPkgId ,getCabalPkgVer ,findGhcPkgHaddockHtml ,findGhcPkgDepends ,findTransitiveGhcPkgDepends ,listGhcPkgDbs ,ghcPkgExeName ,mkGhcPackagePath) where import Control.Applicative import Control.Monad import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Trans.Control import qualified Data.ByteString.Char8 as S8 import Data.Either import Data.List import qualified Data.Map as Map import Data.Maybe import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import Path (Path, Abs, Dir, toFilePath, parent, parseAbsDir) import Path.IO (dirExists, createTree) import Prelude hiding (FilePath) import Stack.Constants import Stack.Types import System.Directory (canonicalizePath, doesDirectoryExist) import System.FilePath (FilePath, searchPathSeparator, dropTrailingPathSeparator) import System.Process.Read -- | Get the global package database getGlobalDB :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m) => EnvOverride -> WhichCompiler -> m (Path Abs Dir) getGlobalDB menv wc = do -- This seems like a strange way to get the global package database -- location, but I don't know of a better one bs <- ghcPkg menv wc [] ["list", "--global"] >>= either throwM return let fp = S8.unpack $ stripTrailingColon $ firstLine bs liftIO (canonicalizePath fp) >>= parseAbsDir where stripTrailingColon bs | S8.null bs = bs | S8.last bs == ':' = S8.init bs | otherwise = bs firstLine = S8.takeWhile (\c -> c /= '\r' && c /= '\n') -- | Run the ghc-pkg executable ghcPkg :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m) => EnvOverride -> WhichCompiler -> [Path Abs Dir] -> [String] -> m (Either ReadProcessException S8.ByteString) ghcPkg menv wc pkgDbs args = do eres <- go r <- case eres of Left _ -> do mapM_ (createDatabase menv wc) pkgDbs go Right _ -> return eres return r where go = tryProcessStdout Nothing menv (ghcPkgExeName wc) args' args' = packageDbFlags pkgDbs ++ args -- | Create a package database in the given directory, if it doesn't exist. createDatabase :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m) => EnvOverride -> WhichCompiler -> Path Abs Dir -> m () createDatabase menv wc db = do exists <- dirExists db unless exists $ do -- Creating the parent doesn't seem necessary, as ghc-pkg -- seems to be sufficiently smart. But I don't feel like -- finding out it isn't the hard way createTree (parent db) _ <- tryProcessStdout Nothing menv (ghcPkgExeName wc) ["init", toFilePath db] return () -- | Get the name to use for "ghc-pkg", given the compiler version. ghcPkgExeName :: WhichCompiler -> String ghcPkgExeName Ghc = "ghc-pkg" ghcPkgExeName Ghcjs = "ghcjs-pkg" -- | Get the necessary ghc-pkg flags for setting up the given package database packageDbFlags :: [Path Abs Dir] -> [String] packageDbFlags pkgDbs = "--no-user-package-db" : map (\x -> ("--package-db=" ++ toFilePath x)) pkgDbs -- | Get the value of a field of the package. findGhcPkgField :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m) => EnvOverride -> WhichCompiler -> [Path Abs Dir] -- ^ package databases -> String -- ^ package identifier, or GhcPkgId -> Text -> m (Maybe Text) findGhcPkgField menv wc pkgDbs name field = do result <- ghcPkg menv wc pkgDbs ["field", "--simple-output", name, T.unpack field] return $ case result of Left{} -> Nothing Right lbs -> fmap (stripCR . T.decodeUtf8) $ listToMaybe $ S8.lines lbs where stripCR t = fromMaybe t (T.stripSuffix "\r" t) -- | Get the id of the package e.g. @foo-0.0.0-9c293923c0685761dcff6f8c3ad8f8ec@. findGhcPkgId :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m) => EnvOverride -> WhichCompiler -> [Path Abs Dir] -- ^ package databases -> PackageName -> m (Maybe GhcPkgId) findGhcPkgId menv wc pkgDbs name = do mpid <- findGhcPkgField menv wc pkgDbs (packageNameString name) "id" case mpid of Just !pid -> return (parseGhcPkgId (T.encodeUtf8 pid)) _ -> return Nothing -- | Get the package key e.g. @foo_9bTCpMF7G4UFWJJvtDrIdB@. -- -- NOTE: GHC > 7.10 only! Will always yield 'Nothing' otherwise. findGhcPkgKey :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m) => EnvOverride -> WhichCompiler -> [Path Abs Dir] -- ^ package databases -> PackageName -> m (Maybe Text) findGhcPkgKey menv wc pkgDbs name = findGhcPkgField menv wc pkgDbs (packageNameString name) "key" -- | Get the version of the package findGhcPkgVersion :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m) => EnvOverride -> WhichCompiler -> [Path Abs Dir] -- ^ package databases -> PackageName -> m (Maybe Version) findGhcPkgVersion menv wc pkgDbs name = do mv <- findGhcPkgField menv wc pkgDbs (packageNameString name) "version" case mv of Just !v -> return (parseVersion (T.encodeUtf8 v)) _ -> return Nothing -- | Get the Haddock HTML documentation path of the package. findGhcPkgHaddockHtml :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m) => EnvOverride -> WhichCompiler -> [Path Abs Dir] -- ^ package databases -> String -- ^ PackageIdentifier or GhcPkgId -> m (Maybe (PackageIdentifier, Path Abs Dir)) findGhcPkgHaddockHtml menv wc pkgDbs ghcPkgId = do mpath <- findGhcPkgField menv wc pkgDbs ghcPkgId "haddock-html" mid <- findGhcPkgField menv wc pkgDbs ghcPkgId "id" mversion <- findGhcPkgField menv wc pkgDbs ghcPkgId "version" let mpkgId = PackageIdentifier <$> (mid >>= parsePackageName . T.encodeUtf8) <*> (mversion >>= parseVersion . T.encodeUtf8) case (,) <$> mpath <*> mpkgId of Just (path0, pkgId) -> do let path = T.unpack path0 exists <- liftIO $ doesDirectoryExist path path' <- if exists then liftIO $ canonicalizePath path else return path return $ fmap (pkgId,) (parseAbsDir path') _ -> return Nothing -- | Finds dependencies of package, and all their dependencies, etc. findTransitiveGhcPkgDepends :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m) => EnvOverride -> WhichCompiler -> [Path Abs Dir] -- ^ package databases -> PackageIdentifier -> m (Set PackageIdentifier) findTransitiveGhcPkgDepends menv wc pkgDbs pkgId0 = liftM (Set.fromList . Map.elems) (go (packageIdentifierString pkgId0) Map.empty) where go pkgId res = do deps <- findGhcPkgDepends menv wc pkgDbs pkgId loop deps res loop [] res = return res loop (dep:deps) res = do if Map.member dep res then loop deps res else do let pkgId = ghcPkgIdString dep mname <- findGhcPkgField menv wc pkgDbs pkgId "name" mversion <- findGhcPkgField menv wc pkgDbs pkgId "version" let mident = do name <- mname >>= parsePackageName . T.encodeUtf8 version <- mversion >>= parseVersion . T.encodeUtf8 Just $ PackageIdentifier name version res' = maybe id (Map.insert dep) mident res res'' <- go pkgId res' -- FIXME is the Map.union actually necessary? loop deps (Map.union res res'') -- | Get the dependencies of the package. findGhcPkgDepends :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m) => EnvOverride -> WhichCompiler -> [Path Abs Dir] -- ^ package databases -> String -- ^ package identifier or GhcPkgId -> m [GhcPkgId] findGhcPkgDepends menv wc pkgDbs pkgId = do mdeps <- findGhcPkgField menv wc pkgDbs pkgId "depends" case mdeps of Just !deps -> return (mapMaybe (parseGhcPkgId . T.encodeUtf8) (T.words deps)) _ -> return [] unregisterGhcPkgId :: (MonadIO m, MonadLogger m, MonadThrow m, MonadCatch m, MonadBaseControl IO m) => EnvOverride -> WhichCompiler -> CompilerVersion -> Path Abs Dir -- ^ package database -> GhcPkgId -> PackageIdentifier -> m () unregisterGhcPkgId menv wc cv pkgDb gid ident = do eres <- ghcPkg menv wc [pkgDb] args case eres of Left e -> $logWarn $ T.pack $ show e Right _ -> return () where -- TODO ideally we'd tell ghc-pkg a GhcPkgId instead args = "unregister" : "--user" : "--force" : (case cv of GhcVersion v | v < $(mkVersion "7.9") -> [packageIdentifierString ident] _ -> ["--ipid", ghcPkgIdString gid]) -- | Get the version of Cabal from the global package database. getCabalPkgVer :: (MonadThrow m, MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m) => EnvOverride -> WhichCompiler -> m Version getCabalPkgVer menv wc = findGhcPkgVersion menv wc [] -- global DB cabalPackageName >>= maybe (throwM $ Couldn'tFindPkgId cabalPackageName) return listGhcPkgDbs :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m) => EnvOverride -> WhichCompiler -> [Path Abs Dir] -> m [PackageIdentifier] listGhcPkgDbs menv wc pkgDbs = do result <- ghcPkg menv wc pkgDbs ["list", "--simple-output"] return $ case result of Left{} -> [] Right lbs -> mapMaybe parsePackageIdentifier (S8.words lbs) -- | Get the value for GHC_PACKAGE_PATH mkGhcPackagePath :: Bool -> Path Abs Dir -> Path Abs Dir -> Path Abs Dir -> Text mkGhcPackagePath locals localdb deps globaldb = T.pack $ intercalate [searchPathSeparator] $ concat [ [toFilePathNoTrailingSlash localdb | locals] , [toFilePathNoTrailingSlash deps] , [toFilePathNoTrailingSlash globaldb] ] -- TODO: dedupe with copy in Stack.Setup toFilePathNoTrailingSlash :: Path loc Dir -> FilePath toFilePathNoTrailingSlash = dropTrailingPathSeparator . toFilePath
kairuku/stack
src/Stack/GhcPkg.hs
bsd-3-clause
11,739
0
19
3,443
2,978
1,514
1,464
249
3
{-# LANGUAGE BangPatterns, ScopedTypeVariables #-} -- | -- Module : Data.Text.Lazy.Search -- Copyright : (c) 2009, 2010 Bryan O'Sullivan -- -- License : BSD-style -- Maintainer : [email protected], [email protected], -- [email protected] -- Stability : experimental -- Portability : GHC -- -- Fast substring search for lazy 'Text', based on work by Boyer, -- Moore, Horspool, Sunday, and Lundh. Adapted from the strict -- implementation. module Data.Text.Lazy.Search ( indices ) where import qualified Data.Text.Array as A import Data.Int (Int64) import Data.Word (Word16, Word64) import qualified Data.Text.Internal as T import Data.Text.Fusion.Internal (PairS(..)) import Data.Text.Lazy.Internal (Text(..), foldlChunks) import Data.Bits ((.|.), (.&.)) import Data.Text.UnsafeShift (shiftL) --LIQUID -- import qualified Data.Text -- import Data.Text.Array (Array(..), MArray(..)) -- import qualified Data.Text.Fusion.Internal -- import qualified Data.Text.Fusion.Size -- import qualified Data.Text.Internal -- import qualified Data.Text.Private -- import qualified Data.Text.Search -- import qualified Data.Text.Unsafe import Data.Text.Lazy.Internal (foldrChunks) -- import qualified Data.Word -- import Data.Int (Int32) import Language.Haskell.Liquid.Prelude import Language.Haskell.Liquid.Foreign -- | /O(n+m)/ Find the offsets of all non-overlapping indices of -- @needle@ within @haystack@. -- -- This function is strict in @needle@, and lazy (as far as possible) -- in the chunks of @haystack@. -- -- In (unlikely) bad cases, this algorithm's complexity degrades -- towards /O(n*m)/. {-@ type IdxList a N = [a]<{\ix iy -> (ix+N) <= iy}> @-} {-@ indices :: pat:Text -> src:Text -> IdxList {v:Nat64 | v <= ((ltlen src) - (ltlen pat))} (ltlen pat) @-} indices :: Text -- ^ Substring to search for (@needle@) -> Text -- ^ Text to search in (@haystack@) -> [Int64] indices needle@(Chunk n ns) _haystack@(Chunk k@(T.Text _ _ klen) ks) = if nlen <= 0 then [] else if nlen == 1 then indicesOne (nindex 0) _haystack Empty k ks 0 else advance needle _haystack Empty k ks 0 0 where -- advance x@(T.Text _ _ l) xs = scan -- where -- scan !g !i -- | i >= m = case xs of -- Empty -> [] -- Chunk y ys -> advance y ys g (i-m) -- | lackingHay (i + nlen) x xs = [] -- | c == z && candidateMatch 0 = g : scan (g+nlen) (i+nlen) -- | otherwise = scan (g+delta) (i+delta) -- where -- m = fromIntegral l -- c = hindex (i + nlast) -- delta | nextInPattern = nlen + 1 -- | c == z = skip + 1 -- | otherwise = 1 -- nextInPattern = mask .&. swizzle (hindex (i+nlen)) == 0 -- candidateMatch !j -- | j >= nlast = True -- | hindex (i+j) /= nindex j = False -- | otherwise = candidateMatch (j+1) -- hindex = index x xs nlen = wordLength needle nlast = nlen - 1 nindex = index n ns -- z = foldlChunks fin 0 needle -- --LIQUID fin param needs to be non-empty -- where fin _ (T.Text farr foff flen) = A.unsafeIndex farr (foff+flen-1) -- (mask :: Word64) :*: skip = buildTable n ns 0 0 0 (nlen-2) -- swizzle w = 1 `shiftL` (fromIntegral w .&. 0x3f) -- buildTable (T.Text xarr xoff xlen) xs = go -- where -- go !(g::Int64) !i !msk !skp -- | i >= xlast = case xs of -- Empty -> (msk .|. swizzle z) :*: skp -- Chunk y ys -> buildTable y ys g 0 msk' skp' -- | otherwise = go (g+1) (i+1) msk' skp' -- where c = A.unsafeIndex xarr (xoff+i) -- msk' = msk .|. swizzle c -- skp' | c == z = nlen - g - 2 -- | otherwise = skp -- xlast = xlen - 1 -- -- | Check whether an attempt to index into the haystack at the -- -- given offset would fail. -- lackingHay q = go 0 -- where -- go p (T.Text _ _ l) ps = p' < q && case ps of -- Empty -> True -- Chunk r rs -> go p' r rs -- where p' = p + fromIntegral l indices _ _ = [] {-@ advance :: pat:{v:Text | (ltlen v) > 1} -> src:LTextNE -> ts0:LTextLE src -> x:{v:TextNE | (tlen v) <= (ltlen src)} -> xs:{v:Text | (((ltlen v) + (tlen x)) = ((ltlen src) - (ltlen ts0)))} -> i:Nat64 -> g:{v:Int64 | (v - i) = (ltlen ts0)} -> IdxList {v:Int64 | (BtwnI (v) (g) ((ltlen src) - (ltlen pat)))} (ltlen pat) @-} advance :: Text -> Text -> Text -> T.Text -> Text -> Int64 -> Int64 -> [Int64] advance needle haystack ts0 x xs i g = advance_scan needle haystack ts0 x xs i g (wordLength haystack - g + 1) {-@ advance_scan :: pat:{v:Text | (ltlen v) > 1} -> src:LTextNE -> ts0:LTextLE src -> x:{v:TextNE | (tlen v) <= (ltlen src)} -> xs:{v:Text | (((ltlen v) + (tlen x)) = ((ltlen src) - (ltlen ts0)))} -> i:Nat64 -> g:{v:Int64 | (v - i) = (ltlen ts0)} -> {v:Int64 | v = ((ltlen src) - g) + 1} -> IdxList {v:Int64 | (BtwnI (v) (g) ((ltlen src) - (ltlen pat)))} (ltlen pat) @-} {-@ Decrease advance_scan 5 8 @-} advance_scan :: Text -> Text -> Text -> T.Text -> Text -> Int64 -> Int64 -> Int64 -> [Int64] advance_scan needle@(Chunk n ns) src ts0 x@(T.Text _ _ l) xs !i !g dec = if i >= m then case xs of Empty -> [] Chunk y ys -> advance_scan needle src (Chunk x ts0) y ys (i-m) g dec else if lackingHay (i + nlen) x xs then [] else let d = delta nlen skip c z nextInPattern c = index x xs (i + nlast) nextInPattern = mask .&. swizzle (index x xs (i+nlen)) == 0 candidateMatch (d :: Int64) !j = if j >= nlast then True else if index x xs (i+j) /= index n ns j then False else candidateMatch (d-1) (j+1) --LIQUID candidateMatch !j --LIQUID | j >= nlast = True --LIQUID | index x xs (i+j) /= index n ns j = False --LIQUID | otherwise = candidateMatch (j+1) in if c == z && candidateMatch nlast 0 then g : advance_scan needle src ts0 x xs (i+nlen) (g+nlen) (dec-nlen) else advance_scan needle src ts0 x xs (i+d) (g+d) (dec-d) where nlen = wordLength needle nlast = nlen - 1 (mask :: Word64) :*: skip = buildTable z nlen Empty n ns 0 0 0 (nlen-2) nlen z = foldlChunks fin 0 needle where fin _ (T.Text farr foff flen) = A.unsafeIndex farr (foff+flen-1) m = fromIntegral l -- | Check whether an attempt to index into the haystack at the -- given offset would fail. {-@ lackingHay :: q:Nat64 -> t:TextNE -> ts:Text -> {v:Bool | ((Prop v) <=> (q > ((tlen t) + (ltlen ts))))} @-} lackingHay :: Int64 -> T.Text -> Text -> Bool lackingHay q t ts = lackingHay_go q 0 t ts {-@ lackingHay_go :: q:Nat64 -> p:Nat64 -> t:TextNE -> ts:Text -> {v:Bool | ((Prop v) <=> (q > (p + (tlen t) + (ltlen ts))))} @-} {-@ Decrease lackingHay_go 4 @-} lackingHay_go :: Int64 -> Int64 -> T.Text -> Text -> Bool lackingHay_go q p (T.Text _ _ l) Empty = q > (p + fromIntegral l) lackingHay_go q p (T.Text _ _ l) (Chunk r rs) = let p' = p + fromIntegral l in q > p' && lackingHay_go q p' r rs {-@ delta :: nlen:{v:Int64 | v > 1} -> skip:{v:Nat64 | v <= nlen} -> Word16 -> Word16 -> Bool -> {v:Int64 | (BtwnI v 1 (nlen + 1))} @-} delta :: Int64 -> Int64 -> Word16 -> Word16 -> Bool -> Int64 delta nlen skip c z nextInPattern = if nextInPattern then nlen + 1 else if c == z then skip + 1 else 1 swizzle w = 1 `shiftL` (fromIntegral w .&. 0x3f) {-@ buildTable :: Word16 -> nlen:{v:Int64 | v > 1} -> ts0:{v:Text | (BtwnI (ltlen v) 0 nlen)} -> t:{v:T.Text | (BtwnEI (tlen v) 0 nlen)} -> ts:{v:Text | (((ltlen v) + (tlen t)) = (nlen - (ltlen ts0)))} -> i:TValidI t -> g:{v:Nat64 | v <= ((ltlen ts0) + i)} -> Word64 -> {v:Nat64 | v < nlen} -> d:{v:Nat64 | nlen = (i + v)} -> PairS Word64 {v:Nat64 | v < nlen} @-} {-@ Decrease buildTable 5 10 @-} buildTable :: Word16 -> Int64 -> Text -> T.Text -> Text -> Int -> Int64 -> Word64 -> Int64 -> Int64 -> PairS Word64 Int64 buildTable z nlen ts0 t@(T.Text xarr xoff xlen) xs !i !(g::Int64) !msk !skp (d :: Int64) = if i >= xlast then case xs of Empty -> (msk .|. swizzle z) :*: skp Chunk y ys -> let msk' = msk .|. swizzle c skp' = if c == z then nlen - g - 2 else skp --LIQUID skp' | c == z = nlen - g - 2 --LIQUID | otherwise = skp in buildTable z nlen (Chunk t ts0) y ys 0 g msk' skp' nlen else let msk' = msk .|. swizzle c skp' = if c == z then nlen - g - 2 else skp --LIQUID skp' | c == z = nlen - g - 2 --LIQUID | otherwise = skp in buildTable z nlen ts0 t xs (i+1) (g+1) msk' skp' (d-1) where c = A.unsafeIndex xarr (xoff+i) xlast = xlen - 1 -- | Fast index into a partly unpacked 'Text'. We take into account -- the possibility that the caller might try to access one element -- past the end. {-@ index :: t:TextNE -> ts:Text -> i:{v:Nat64 | v <= ((tlen t) + (ltlen ts))} -> Word16 @-} {-@ Decrease index 2 @-} index :: T.Text -> Text -> Int64 -> Word16 index (T.Text arr off len) xs !i = if j < len then A.unsafeIndex arr (off+j) else case xs of Empty -> -- out of bounds, but legal if j == len then 0 -- should never happen, due to lackingHay above else liquidError "index" Chunk c cs -> index c cs (i-fromIntegral len) where j = fromIntegral i -- | A variant of 'indices' that scans linearly for a single 'Word16'. {-@ indicesOne :: Word16 -> t0:Text -> ts0:LTextLE t0 -> t:TextNE -> ts:{v:Text | (((ltlen v) + (tlen t)) = ((ltlen t0) - (ltlen ts0)))} -> i:{v:Int64 | v = (ltlen ts0)} -> [{v:Int64 | (Btwn (v) (i) (ltlen t0))}]<{\ix iy -> ix < iy}> @-} indicesOne :: Word16 -> Text -> Text -> T.Text -> Text -> Int64 -> [Int64] --LIQUID indicesOne c = chunk --LIQUID where --LIQUID chunk !i (T.Text oarr ooff olen) os = go 0 --LIQUID where --LIQUID go h | h >= olen = case os of --LIQUID Empty -> [] --LIQUID Chunk y ys -> chunk (i+fromIntegral olen) y ys --LIQUID | on == c = i + fromIntegral h : go (h+1) --LIQUID | otherwise = go (h+1) --LIQUID where on = A.unsafeIndex oarr (ooff+h) indicesOne c t0 ts0 t@(T.Text _ _ l) os !i = indicesOne_go c t0 ts0 t os i 0 l {-@ Decrease indicesOne_go 5 8 @-} {-@ indicesOne_go :: Word16 -> t0:Text -> ts0:LTextLE t0 -> t:{v:TextNE | (tlen v) <= (ltlen t0)} -> ts:{v:Text | (((ltlen v) + (tlen t)) = ((ltlen t0) - (ltlen ts0)))} -> i:{v:Int64 | v = (ltlen ts0)} -> h:{v:Nat | v <= (tlen t)} -> {v:Int|v = ((tlen t) - h)} -> [{v:Int64 | (Btwn (v) (i+h) (ltlen t0))}]<{\ix iy -> ix < iy}> @-} indicesOne_go :: Word16 -> Text -> Text -> T.Text -> Text -> Int64 -> Int -> Int -> [Int64] indicesOne_go c t0 ts0 t@(T.Text oarr ooff olen) os !i h d = if h >= olen then case os of Empty -> [] Chunk y@(T.Text _ _ l) ys -> indicesOne_go c t0 (Chunk t ts0) y ys (i+fromIntegral olen) 0 l else let on = A.unsafeIndex oarr (ooff+h) in if on == c then i + fromIntegral h : indicesOne_go c t0 ts0 t os i (h+1) (d-1) else indicesOne_go c t0 ts0 t os i (h+1) (d-1) -- | The number of 'Word16' values in a 'Text'. {-@ wordLength :: t:Text -> {v:Nat64 | v = (ltlen t)} @-} wordLength :: Text -> Int64 --LIQUID wordLength = foldlChunks sumLength 0 --LIQUID where sumLength i (T.Text _ _ l) = i + fromIntegral l wordLength = foldrChunks sumLength 0 {-@ sumLength :: ts:Text -> t:T.Text -> i:Int64 -> {v:Int64 | v = ((tlen t) + i)} @-} sumLength :: Text -> T.Text -> Int64 -> Int64 sumLength _ (T.Text _ _ l) i = i + fromIntegral l --LIQUID emptyError :: String -> a --LIQUID emptyError fun = error ("Data.Text.Lazy.Search." ++ fun ++ ": empty input")
mightymoose/liquidhaskell
benchmarks/text-0.11.2.3/Data/Text/Lazy/Search.hs
bsd-3-clause
13,404
0
17
4,747
2,264
1,245
1,019
101
7
-- !!! ds029: pattern binding with guards (dubious but valid) -- module ShouldCompile where f x = y where (y,z) | y < z = (0,1) | y > z = (1,2) | True = (2,3)
snoyberg/ghc
testsuite/tests/deSugar/should_compile/ds029.hs
bsd-3-clause
210
0
10
87
78
43
35
5
1
module F8 where f8f b x y = let g = \z -> x+y+z in if b then y else g (x*x) f8 = f8f True 1 2
urbanslug/ghc
testsuite/tests/arityanal/f8.hs
bsd-3-clause
103
0
11
37
70
37
33
4
2
{-# LANGUAGE TypeFamilies #-} module ColInference where type family Elem c type instance Elem [e] = e class Col c where isEmpty :: c -> Bool add :: c -> Elem c -> c headTail :: c -> (Elem c,c) sawpOne c1 c2 = let (x,c1') = headTail c1 (y,c2') = headTail c2 in (add c1' y,add c1' x)
urbanslug/ghc
testsuite/tests/indexed-types/should_compile/ColInference4.hs
bsd-3-clause
320
3
10
97
139
75
64
12
1
{-# LANGUAGE BangPatterns #-} module PrimeFactors (primeFactors) where -- When in doubt, trial division primeFactors :: Integer -> [Integer] primeFactors n | n < 2 = [] | even n = 2 : primeFactors (n `div` 2) | otherwise = reverse $ go 3 n [] where go !k !m !fs | k > m = fs | k == m = k : fs | m `mod` k == 0 = go k (m `div` k) (k : fs) | otherwise = go (k + 2) m fs
genos/online_problems
exercism/haskell/prime-factors/src/PrimeFactors.hs
mit
476
0
11
197
202
101
101
10
1
number :: Integer number = 2 ^ 1000 sumDigits :: Integer -> Integer sumDigits n | n < 10 = n | otherwise = n `mod` 10 + sumDigits (n `div` 10) solution :: Integer solution = sumDigits number
DylanSp/Project-Euler-in-Haskell
prob16/solution.hs
mit
203
0
9
51
86
45
41
8
1
{-# LANGUAGE NoImplicitPrelude #-} module Advent.Day2Spec (main, spec) where import Advent.Day2 import BasePrelude import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = do describe "day2Part1" $ do it "calculates the correct total wrapping paper" $ do day2part1 "2x3x4" `shouldBe` 58 day2part1 "1x1x10" `shouldBe` 43 describe "day2Part2" $ do it "calculates the correct total ribbon" $ do day2part2 "2x3x4" `shouldBe` 34 day2part2 "1x1x10" `shouldBe` 14
jhenahan/adventofcode
test/Advent/Day2Spec.hs
mit
539
0
14
139
144
73
71
17
1
{-# LANGUAGE OverloadedStrings #-} module Libfuzzer ( storeTestCase ) where import Control.Monad (unless) import Crypto.Hash.SHA1 (hash) import Data.Byteable (toBytes) import System.Directory (createDirectoryIfMissing, doesFileExist) import System.IO (withFile, IOMode(..)) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as Char8 import qualified Data.ByteArray.Encoding as BA hashInHex :: String -> String hashInHex = hashInHexBS . Char8.pack hashInHexBS :: BS.ByteString -> String hashInHexBS = Char8.unpack . BA.convertToBase BA.Base16 . toBytes . hash storeTestCase :: String -> BS.ByteString -> IO () storeTestCase name content = -- Use first 60 bytes for generating directory name. This adds -- different variants of almost same exception into same directory let dir = "results/" ++ hashInHex (take 60 name) file = hashInHexBS content readme = dir ++ "/00README" in do createDirectoryIfMissing True dir hasReadme <- doesFileExist readme unless hasReadme ( withFile readme WriteMode $ \h -> BS.hPut h $ Char8.pack (name ++ "\n") ) withFile (dir ++ "/" ++ file) WriteMode $ \h -> BS.hPut h content
ouspg/libfuzzerfication
base/libfuzzer-base-haskell/hs-libfuzzer/src/Libfuzzer.hs
mit
1,212
0
16
236
328
179
149
29
1
-- | Rules for making lenses. module Rules ( noSigs , jsonOptions , slackOptions ) where import Control.Lens (LensRules, lensRules, generateSignatures, set) import Data.Aeson.TH (Options(..), SumEncoding(..), defaultOptions, defaultTaggedObject) import Data.Aeson.Types (camelTo2) import Data.Char (toLower) -- | Make lenses without signatures. -- -- Writing the signatures out manually allows attaching Haddocks to them. noSigs :: LensRules noSigs = set generateSignatures False lensRules -- | Converts @prefixedCamelCase@ to @camel-case@. modifier :: Char -> String -> String modifier sep = drop 1 . dropWhile (/= sep) . camelTo2 sep -- | Standard Aeson options for our configuration types. jsonOptions :: Options jsonOptions = defaultOptions { fieldLabelModifier = modifier '-' , constructorTagModifier = map toLower , sumEncoding = defaultTaggedObject { tagFieldName = "type" } } -- | Standard Aeson options for the Slack API types. slackOptions :: Options slackOptions = defaultOptions { fieldLabelModifier = modifier '_' , omitNothingFields = True }
fusionapp/catcher-in-the-rye
src/Rules.hs
mit
1,088
0
8
179
220
133
87
23
1
module PPOL.Permutation ( toPermutationIndex , fromPermutationIndex -- , fromList , toList -- , PPOL.Permutation.length ) where import qualified Data.List as List import qualified Data.Array as Array import qualified Data.Maybe as Maybe type Permutation = Array.Array Int Int type PermutationSize = Int type PermutationIndex = Int rank :: Permutation -> PermutationIndex rank p = 0 toPermutationIndex = rank unrank :: PermutationIndex -> PermutationSize -> Permutation fromPermutationIndex = unrank fromList :: [Int] -> Maybe.Maybe Permutation fromList xs = if List.sort xs == [1..n] then Just xs else Nothing where n = List.length xs toList :: Permutation -> [Int] toList = id length :: Permutation -> Int length = List.length elem :: Permutation -> Permutation -> Bool elem p p' = True
vialette/PPOL
src/PPOL/Permutation.hs
mit
813
2
8
144
237
138
99
27
2
{-# htermination maybe :: b -> (a -> b) -> Maybe a -> b #-} import Maybe
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Maybe_maybe_1.hs
mit
73
0
3
17
5
3
2
1
0
-------------------------------------------------------------------- -- | -- Module : Lexer -- Copyright : (c) Stephen Diehl 2013 -- License : MIT -- Maintainer: [email protected] -- Stability : experimental -- Portability: non-portable -- -------------------------------------------------------------------- module Lexer where import Text.Parsec.String (Parser) import Text.Parsec.Language (emptyDef) import Text.Parsec.Prim (many) import qualified Text.Parsec.Token as Tok lexer :: Tok.TokenParser () lexer = Tok.makeTokenParser style where ops = ["+","*","-","/",";","=",",","<",">","|",":"] names = ["dude check dat", "it wants the", "extern","if","i would totally","whatever ill just","in","for" ,"binary", "unary", "var", "." ] style = emptyDef { Tok.commentLine = "#" , Tok.reservedOpNames = ops , Tok.reservedNames = names } integer = Tok.integer lexer float = Tok.float lexer parens = Tok.parens lexer commaSep = Tok.commaSep lexer semiSep = Tok.semiSep lexer identifier = Tok.identifier lexer whitespace = Tok.whiteSpace lexer reserved = Tok.reserved lexer reservedOp = Tok.reservedOp lexer operator :: Parser String operator = do c <- Tok.opStart emptyDef cs <- many $ Tok.opLetter emptyDef return (c:cs)
thekafkaf/brolang
src/Lexer.hs
mit
1,357
0
10
281
334
194
140
28
1
{-# LANGUAGE OverloadedStrings #-} module PlaceTask ( placeTaskIntoCGroup ) where import Types import qualified Data.ByteString.Lazy as LB import qualified Codec.Binary.UTF8.String as U import Data.Aeson import Data.Aeson.Encode.Pretty (encodePretty) import System.FilePath.Posix ((</>)) import System.Directory (doesFileExist) import Control.Exception import qualified Data.Map.Lazy as M import Data.Char import System.Process import System.Exit import Network.FastCGI data AttachedTask = AttachedTask CGroupName TaskPID data NonAttachedTask = NonAttachedTask CGroupName TaskPID successfullyStatus :: String successfullyStatus = "successfully" failureStatus :: String failureStatus = "failure" -- Instances for JSON creation. instance ToJSON AttachedTask where toJSON (AttachedTask name aPID) = object [ "cgroup" .= name , "pid" .= aPID , "status" .= successfullyStatus ] instance ToJSON NonAttachedTask where toJSON (NonAttachedTask name aPID) = object [ "cgroup" .= name , "pid" .= aPID , "status" .= failureStatus ] -- Show list of tasks in particular cgroup. Based on content of /sys/fs/cgroup/NAME/tasks. placeTaskIntoCGroup :: SMap -> CGI CGIResult placeTaskIntoCGroup queryData = do setHeader "Content-type" "application/json" let taskPID = M.findWithDefault "" "task" queryData -- Make sure that taskPID is just a number... taskPIDIsANumber = all isDigit taskPID nameOfCGroup = M.findWithDefault "" "intogroup" queryData pathToTasksFile = "/sys/fs/cgroup" </> nameOfCGroup </> "tasks" attachTaskCommand = "echo " ++ taskPID ++ " >> " ++ pathToTasksFile -- Make sure that nameOfCGroup is correct name of cgroup-file... cGroupActuallyExists <- liftIO $ doesFileExist pathToTasksFile if taskPIDIsANumber && cGroupActuallyExists then do -- At this point we already know that attachTaskCommand is safe. resultCode <- liftIO $ system attachTaskCommand `catch` possibleErrors case resultCode of ExitSuccess -> itsDone nameOfCGroup taskPID ExitFailure _ -> failure nameOfCGroup taskPID else failure nameOfCGroup taskPID possibleErrors :: IOException -> IO ExitCode possibleErrors _ = return $ ExitFailure 1 itsDone :: CGroupName -> TaskPID -> CGI CGIResult itsDone nameOfCGroup taskPID = output . U.decode . LB.unpack . encodePretty $ AttachedTask nameOfCGroup taskPID failure :: CGroupName -> TaskPID -> CGI CGIResult failure nameOfCGroup taskPID = do setStatus 500 "Internal Server Error" output . U.decode . LB.unpack . encodePretty $ NonAttachedTask nameOfCGroup taskPID
denisshevchenko/control-groups
src/PlaceTask.hs
mit
3,152
0
13
995
575
307
268
55
3
{-# LANGUAGE Haskell2010 #-} {-# OPTIONS -Wall #-} -- | -- Module : Foreign.Java.JNI.%NAME% -- Copyright : (c) Julian Fleischer 2013 -- License : MIT (See LICENSE file in cabal package) -- -- Maintainer : [email protected] -- Stability : stable -- Portability : portable (Haskell2010) -- -- Low level interface to the Java Virtual Machine. -- This module is a very thin wrapper over the Java Native Interface. -- -- Note that all functions that return references (of type @Ptr JObjectRef@) -- return global references which you will need to free manually. -- -- This module contains %SAFETY% bindings, see also -- "Foreign.Java.JNI.%OPPOSITE%". -- -- Read the /The Java Native Interface - Programmer's Guide and Specification/ -- for further information on the Java Native Interface -- (available at <http://www.soi.city.ac.uk/~kloukin/IN2P3/material/jni.pdf>, -- and <http://192.9.162.55/docs/books/jni/>). module Foreign.Java.JNI.%NAME% ( -- * Controlling the virtual machine JVM, createVM, createVM', destroyVM, persistVM, -- * Discovering classes JClassRef, findClass, -- * Object creation JConstructorID, JObjectRef, getConstructorID, newObject, -- * Method access JStaticMethodID, JMethodID, getStaticMethodID, getMethodID, -- ** Static method invocation callStaticVoidMethod, callStaticBooleanMethod, callStaticCharMethod, callStaticByteMethod, callStaticShortMethod, callStaticIntMethod, callStaticLongMethod, callStaticFloatMethod, callStaticDoubleMethod, callStaticObjectMethod, callStaticStringMethod, -- ** Method invocation callVoidMethod, callBooleanMethod, callCharMethod, callByteMethod, callShortMethod, callIntMethod, callLongMethod, callFloatMethod, callDoubleMethod, callObjectMethod, callStringMethod, -- * Field access JFieldID, JStaticFieldID, getFieldID, getStaticFieldID, -- ** Static getters getStaticBooleanField, getStaticCharField, getStaticByteField, getStaticShortField, getStaticIntField, getStaticLongField, getStaticFloatField, getStaticDoubleField, getStaticObjectField, getStaticStringField, -- ** Static setters setStaticBooleanField, setStaticCharField, setStaticByteField, setStaticShortField, setStaticIntField, setStaticLongField, setStaticFloatField, setStaticDoubleField, setStaticObjectField, setStaticStringField, -- ** Member getters getBooleanField, getCharField, getByteField, getShortField, getIntField, getLongField, getFloatField, getDoubleField, getObjectField, getStringField, -- ** Member setters setBooleanField, setCharField, setByteField, setShortField, setIntField, setLongField, setFloatField, setDoubleField, setObjectField, setStringField, -- * Argument passing JValues, JArg (..), mkJValues, newJValues, setJValueByte, setJValueShort, setJValueInt, setJValueLong, setJValueFloat, setJValueDouble, setJValueObject, setJValueString, -- * Releasing resources releaseJObjectRef, releaseJClassRef, releaseJThrowableRef, release, -- * Special data types -- ** String handling JChars, JBytes, newJString, charsFromJString, bytesFromJString, releaseJChars, releaseJBytes, jStringToCString, -- ** Array handling getArrayLength, -- ** Reflection getObjectClass, isInstanceOf, -- ** Exception handling JThrowableRef, exceptionCheck, exceptionOccurred, exceptionOccurredClear, exceptionClear, exceptionDescribe, -- * Debugging getDebugStatus, setDebugStatus, -- * libjvm initialization getLibjvmPath, getCompiledLibjvmPath, setLibjvmPath, registerCallbacks, -- * Workarounds for certain platforms runCocoaMain ) where import Data.Int import Data.Word import Foreign import Foreign.C.Types import Foreign.C.String import Foreign.Java.JNI.Types -- | Create a JValues Array which can be used for argument -- passing to a multi parameter method. You need to free the -- Ptr object manually using 'free'. -- -- This method is implemented using @calloc@ internally. -- See the native implementation of @newJValues@. mkJValues :: Ptr JVM -> [JArg] -> IO (Ptr JValues) mkJValues vm args = do jvalues <- newJValues $ fromIntegral $ length args fillJValuesArray vm (0 :: CInt) args jvalues fillJValuesArray :: Ptr JVM -> CInt -> [JArg] -> Ptr JValues -> IO (Ptr JValues) fillJValuesArray _ _ [] jvalues = return jvalues fillJValuesArray vm ix (x:xs) jvalues = setValue >> fillJValuesArray vm (ix+1) xs jvalues where setValue = case x of (BooleanA v) -> setJValueBoolean jvalues ix v (CharA v) -> setJValueChar jvalues ix v (ByteA v) -> setJValueByte jvalues ix v (ShortA v) -> setJValueShort jvalues ix v (IntA v) -> setJValueInt jvalues ix v (LongA v) -> setJValueLong jvalues ix v (FloatA v) -> setJValueFloat jvalues ix $ realToFrac v (DoubleA v) -> setJValueDouble jvalues ix $ realToFrac v (ObjectA (Just v)) -> withForeignPtr (jobjectPtr v) $ \ptr -> setJValueObject jvalues ix ptr (ObjectA Nothing) -> setJValueObject jvalues ix nullPtr (ArrayA (Just v)) -> withForeignPtr (jarrayPtr v) $ \ptr -> setJValueObject jvalues ix ptr (ArrayA Nothing) -> setJValueObject jvalues ix nullPtr (StringA v) -> do cstring <- newCString v setJValueString vm jvalues ix cstring free cstring foreign import ccall %SAFETY% "ffijni.h createVM" createVM :: IO (Ptr JVM) foreign import ccall %SAFETY% "ffijni.h createVM2" createVM' :: Word32 -- ^ The number of arguments (like argc) -> Ptr CString -- ^ A @char**@ to the arguments (like argv) -> IO (Ptr JVM) -- ^ Returns a Ptr to the newly running JVM foreign import ccall %SAFETY% "ffijni.h destroyVM" destroyVM :: Ptr JVM -> IO () foreign import ccall %SAFETY% "ffijni.h persistVM" persistVM :: Ptr JVM -> IO () foreign import ccall %SAFETY% "ffijni.h findClass" findClass :: Ptr JVM -> CString -> IO (Ptr JClassRef) foreign import ccall %SAFETY% "ffijni.h newObject" newObject :: Ptr JVM -> Ptr JClassRef -> Ptr JConstructorID -> Ptr JValues -> IO (Ptr JObjectRef) foreign import ccall %SAFETY% "ffijni.h getConstructorID" getConstructorID :: Ptr JVM -> Ptr JClassRef -> CString -> IO (Ptr JConstructorID) foreign import ccall %SAFETY% "ffijni.h getStaticMethodID" getStaticMethodID :: Ptr JVM -> Ptr JClassRef -> CString -> CString -> IO (Ptr JStaticMethodID) foreign import ccall %SAFETY% "ffijni.h getMethodID" getMethodID :: Ptr JVM -> Ptr JClassRef -> CString -> CString -> IO (Ptr JMethodID) foreign import ccall %SAFETY% "ffijni.h getStaticFieldID" getStaticFieldID :: Ptr JVM -> Ptr JClassRef -> CString -> CString -> IO (Ptr JStaticFieldID) foreign import ccall %SAFETY% "ffijni.h getFieldID" getFieldID :: Ptr JVM -> Ptr JClassRef -> CString -> CString -> IO (Ptr JFieldID) foreign import ccall %SAFETY% "ffijni.h callStaticVoidMethod" callStaticVoidMethod :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticMethodID -> Ptr JValues -> IO () foreign import ccall %SAFETY% "ffijni.h callStaticIntMethod" callStaticIntMethod :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticMethodID -> Ptr JValues -> IO Int32 foreign import ccall %SAFETY% "ffijni.h callStaticLongMethod" callStaticLongMethod :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticMethodID -> Ptr JValues -> IO Int64 foreign import ccall %SAFETY% "ffijni.h callStaticShortMethod" callStaticShortMethod :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticMethodID -> Ptr JValues -> IO Int16 foreign import ccall %SAFETY% "ffijni.h callStaticByteMethod" callStaticByteMethod :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticMethodID -> Ptr JValues -> IO Int8 foreign import ccall %SAFETY% "ffijni.h callStaticFloatMethod" callStaticFloatMethod :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticMethodID -> Ptr JValues -> IO CFloat foreign import ccall %SAFETY% "ffijni.h callStaticDoubleMethod" callStaticDoubleMethod :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticMethodID -> Ptr JValues -> IO CDouble foreign import ccall %SAFETY% "ffijni.h callStaticBooleanMethod" callStaticBooleanMethod :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticMethodID -> Ptr JValues -> IO Bool foreign import ccall %SAFETY% "ffijni.h callStaticCharMethod" callStaticCharMethod :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticMethodID -> Ptr JValues -> IO Word16 foreign import ccall %SAFETY% "ffijni.h callStaticObjectMethod" callStaticObjectMethod :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticMethodID -> Ptr JValues -> IO (Ptr JObjectRef) foreign import ccall %SAFETY% "ffijni.h callStaticStringMethod" callStaticStringMethod :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticMethodID -> Ptr JValues -> IO CString foreign import ccall %SAFETY% "ffijni.h callVoidMethod" callVoidMethod :: Ptr JVM -> Ptr JObjectRef -> Ptr JMethodID -> Ptr JValues -> IO () foreign import ccall %SAFETY% "ffijni.h callLongMethod" callLongMethod :: Ptr JVM -> Ptr JObjectRef -> Ptr JMethodID -> Ptr JValues -> IO Int64 foreign import ccall %SAFETY% "ffijni.h callIntMethod" callIntMethod :: Ptr JVM -> Ptr JObjectRef -> Ptr JMethodID -> Ptr JValues -> IO Int32 foreign import ccall %SAFETY% "ffijni.h callShortMethod" callShortMethod :: Ptr JVM -> Ptr JObjectRef -> Ptr JMethodID -> Ptr JValues -> IO Int16 foreign import ccall %SAFETY% "ffijni.h callByteMethod" callByteMethod :: Ptr JVM -> Ptr JObjectRef -> Ptr JMethodID -> Ptr JValues -> IO Int8 foreign import ccall %SAFETY% "ffijni.h callFloatMethod" callFloatMethod :: Ptr JVM -> Ptr JObjectRef -> Ptr JMethodID -> Ptr JValues -> IO CFloat foreign import ccall %SAFETY% "ffijni.h callDoubleMethod" callDoubleMethod :: Ptr JVM -> Ptr JObjectRef -> Ptr JMethodID -> Ptr JValues -> IO CDouble foreign import ccall %SAFETY% "ffijni.h callBooleanMethod" callBooleanMethod :: Ptr JVM -> Ptr JObjectRef -> Ptr JMethodID -> Ptr JValues -> IO Bool foreign import ccall %SAFETY% "ffijni.h callCharMethod" callCharMethod :: Ptr JVM -> Ptr JObjectRef -> Ptr JMethodID -> Ptr JValues -> IO Word16 foreign import ccall %SAFETY% "ffijni.h callObjectMethod" callObjectMethod :: Ptr JVM -> Ptr JObjectRef -> Ptr JMethodID -> Ptr JValues -> IO (Ptr JObjectRef) foreign import ccall %SAFETY% "ffijni.h callStringMethod" callStringMethod :: Ptr JVM -> Ptr JObjectRef -> Ptr JMethodID -> Ptr JValues -> IO CString foreign import ccall %SAFETY% "ffijni.h getStaticLongField" getStaticLongField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> IO Int64 foreign import ccall %SAFETY% "ffijni.h getStaticIntField" getStaticIntField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> IO Int32 foreign import ccall %SAFETY% "ffijni.h getStaticShortField" getStaticShortField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> IO Int16 foreign import ccall %SAFETY% "ffijni.h getStaticByteField" getStaticByteField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> IO Int8 foreign import ccall %SAFETY% "ffijni.h getStaticFloatField" getStaticFloatField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> IO CFloat foreign import ccall %SAFETY% "ffijni.h getStaticDoubleField" getStaticDoubleField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> IO CDouble foreign import ccall %SAFETY% "ffijni.h getStaticBooleanField" getStaticBooleanField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> IO Bool foreign import ccall %SAFETY% "ffijni.h getStaticCharField" getStaticCharField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> IO Word16 foreign import ccall %SAFETY% "ffijni.h getStaticObjectField" getStaticObjectField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> IO (Ptr JObjectRef) foreign import ccall %SAFETY% "ffijni.h getStaticStringField" getStaticStringField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> IO CString foreign import ccall %SAFETY% "ffijni.h getLongField" getLongField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> IO Int64 foreign import ccall %SAFETY% "ffijni.h getIntField" getIntField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> IO Int32 foreign import ccall %SAFETY% "ffijni.h getShortField" getShortField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> IO Int16 foreign import ccall %SAFETY% "ffijni.h getByteField" getByteField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> IO Int8 foreign import ccall %SAFETY% "ffijni.h getFloatField" getFloatField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> IO CFloat foreign import ccall %SAFETY% "ffijni.h getDoubleField" getDoubleField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> IO CDouble foreign import ccall %SAFETY% "ffijni.h getBooleanField" getBooleanField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> IO Bool foreign import ccall %SAFETY% "ffijni.h getCharField" getCharField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> IO Word16 foreign import ccall %SAFETY% "ffijni.h getObjectField" getObjectField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> IO (Ptr JObjectRef) foreign import ccall %SAFETY% "ffijni.h getStringField" getStringField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> IO CString foreign import ccall %SAFETY% "ffijni.h setStaticLongField" setStaticLongField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> Int64 -> IO () foreign import ccall %SAFETY% "ffijni.h setStaticIntField" setStaticIntField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> Int32 -> IO () foreign import ccall %SAFETY% "ffijni.h setStaticShortField" setStaticShortField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> Int16 -> IO () foreign import ccall %SAFETY% "ffijni.h setStaticByteField" setStaticByteField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> Int8 -> IO () foreign import ccall %SAFETY% "ffijni.h setStaticFloatField" setStaticFloatField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> CFloat -> IO () foreign import ccall %SAFETY% "ffijni.h setStaticDoubleField" setStaticDoubleField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> CDouble -> IO () foreign import ccall %SAFETY% "ffijni.h setStaticBooleanField" setStaticBooleanField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> Bool -> IO () foreign import ccall %SAFETY% "ffijni.h setStaticCharField" setStaticCharField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> Word16 -> IO () foreign import ccall %SAFETY% "ffijni.h setStaticObjectField" setStaticObjectField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> Ptr JObjectRef -> IO () foreign import ccall %SAFETY% "ffijni.h setStaticStringField" setStaticStringField :: Ptr JVM -> Ptr JClassRef -> Ptr JStaticFieldID -> CString -> IO () foreign import ccall %SAFETY% "ffijni.h setLongField" setLongField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> Int64 -> IO () foreign import ccall %SAFETY% "ffijni.h setIntField" setIntField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> Int32 -> IO () foreign import ccall %SAFETY% "ffijni.h setShortField" setShortField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> Int16 -> IO () foreign import ccall %SAFETY% "ffijni.h setByteField" setByteField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> Int8 -> IO () foreign import ccall %SAFETY% "ffijni.h setFloatField" setFloatField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> CFloat -> IO () foreign import ccall %SAFETY% "ffijni.h setDoubleField" setDoubleField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> CDouble -> IO () foreign import ccall %SAFETY% "ffijni.h setBooleanField" setBooleanField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> Bool -> IO () foreign import ccall %SAFETY% "ffijni.h setCharField" setCharField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> Word16 -> IO () foreign import ccall %SAFETY% "ffijni.h setObjectField" setObjectField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> Ptr JObjectRef -> IO () foreign import ccall %SAFETY% "ffijni.h setStringField" setStringField :: Ptr JVM -> Ptr JObjectRef -> Ptr JFieldID -> CString -> IO () foreign import ccall %SAFETY% "ffijni.h newJValues" newJValues :: CInt -> IO (Ptr JValues) foreign import ccall %SAFETY% "ffijni.h setJValueLong" setJValueLong :: Ptr JValues -> CInt -> Int64 -> IO () foreign import ccall %SAFETY% "ffijni.h setJValueInt" setJValueInt :: Ptr JValues -> CInt -> Int32 -> IO () foreign import ccall %SAFETY% "ffijni.h setJValueShort" setJValueShort :: Ptr JValues -> CInt -> Int16 -> IO () foreign import ccall %SAFETY% "ffijni.h setJValueByte" setJValueByte :: Ptr JValues -> CInt -> Int8 -> IO () foreign import ccall %SAFETY% "ffijni.h setJValueFloat" setJValueFloat :: Ptr JValues -> CInt -> CFloat -> IO () foreign import ccall %SAFETY% "ffijni.h setJValueDouble" setJValueDouble :: Ptr JValues -> CInt -> CDouble -> IO () foreign import ccall %SAFETY% "ffijni.h setJValueBoolean" setJValueBoolean :: Ptr JValues -> CInt -> Bool -> IO () foreign import ccall %SAFETY% "ffijni.h setJValueChar" setJValueChar :: Ptr JValues -> CInt -> Word16 -> IO () foreign import ccall %SAFETY% "ffijni.h setJValueObject" setJValueObject :: Ptr JValues -> CInt -> Ptr JObjectRef -> IO () foreign import ccall %SAFETY% "ffijni.h setJValueString" setJValueString :: Ptr JVM -> Ptr JValues -> CInt -> CString -> IO () foreign import ccall %SAFETY% "ffijni.h newJString" newJString :: Ptr JVM -> CString -> IO (Ptr JObjectRef) foreign import ccall %SAFETY% "ffijni.h charsFromJString" charsFromJString :: Ptr JVM -> Ptr JObjectRef -> IO (Ptr JChars) foreign import ccall %SAFETY% "ffijni.h bytesFromJString" bytesFromJString :: Ptr JVM -> Ptr JObjectRef -> IO (Ptr JBytes) foreign import ccall %SAFETY% "ffijni.h releaseJChars" releaseJChars :: Ptr JVM -> Ptr JObjectRef -> CString -> IO () foreign import ccall %SAFETY% "ffijni.h releaseJBytes" releaseJBytes :: Ptr JVM -> Ptr JObjectRef -> CString -> IO () foreign import ccall %SAFETY% "ffijni.h jStringToCString" jStringToCString :: Ptr JVM -> Ptr JObjectRef -> CString -> IO () foreign import ccall %SAFETY% "ffijni.h getArrayLength" getArrayLength :: Ptr JVM -> Ptr JObjectRef -> IO Int32 foreign import ccall %SAFETY% "ffijni.h getObjectClass" getObjectClass :: Ptr JVM -> Ptr JObjectRef -> IO (Ptr JClassRef) foreign import ccall %SAFETY% "ffijni.h isInstanceOf" isInstanceOf :: Ptr JVM -> Ptr JObjectRef -> Ptr JClassRef -> IO Bool -- | Returns the path to libjvm that is used by this library. -- Note that this will return the @nullPtr@ if the library has not -- yet been initialized. The library is lazily initialized the first -- time that 'runJava'' is used. 'runJava' is implemented in terms of -- 'runJava', as is 'initJava'. -- -- You are not allowed to invoke 'free' on the returned cstring. foreign import ccall %SAFETY% "ffijni.h getLibjvmPath" getLibjvmPath :: IO CString -- | Returns the path to libjvm with which this library has been -- compiled. This is guaranteed to never return 'nullPtr'. -- -- You are not allowed to invoke 'free' on the returned cstring. foreign import ccall %SAFETY% "ffijni.h getCompiledLibjvmPath" getCompiledLibjvmPath :: IO CString -- | Sets the path to libjvm. Note that this will only have an -- effect if the library has not yet been initialized, that is -- before any of the following functions is used: 'runJava', -- 'runJava'', and 'initJava'. -- -- Do not invoke 'free' on the cstring passed to this function, -- as this function will not set a copy but the object given. -- It is only ever used once during the lifecycle of your -- application. foreign import ccall %SAFETY% "ffijni.h setLibjvmPath" setLibjvmPath :: CString -> IO () -- | Checks whether an exception has occured in the virtual -- machine or not. foreign import ccall %SAFETY% "ffijni.h exceptionCheck" exceptionCheck :: Ptr JVM -> IO Bool foreign import ccall %SAFETY% "ffijni.h exceptionClear" exceptionClear :: Ptr JVM -> IO () foreign import ccall %SAFETY% "ffijni.h exceptionDescribe" exceptionDescribe :: Ptr JVM -> IO () -- | Checks whether an exception occured and return that exception. -- If no exception occured, the returned pointer will be the 'nullPtr'. -- This method will return a local reference only, so beware that the -- obtained Ptr will not be valid for too long. foreign import ccall %SAFETY% "ffijni.h exceptionOccurred" exceptionOccurred :: Ptr JVM -> IO (Ptr JThrowableRef) -- | Checks whether an exception occured and return that exception. -- If no exception occured, the returned pointer will be the 'nullPtr'. -- This method will also call exceptionClear which means that it can -- not be called twice. This method will return a global reference -- - as opposed to 'exceptionOccurred', which will return a local -- reference only. foreign import ccall %SAFETY% "ffijni.h exceptionOccurredClear" exceptionOccurredClear :: Ptr JVM -> IO (Ptr JThrowableRef) foreign import ccall %SAFETY% "ffijni.h releaseJObjectRef" releaseJObjectRef :: Ptr JVM -> Ptr JObjectRef -> IO () foreign import ccall %SAFETY% "ffijni.h releaseJClassRef" releaseJClassRef :: Ptr JVM -> Ptr JClassRef -> IO () foreign import ccall %SAFETY% "ffijni.h releaseJThrowableRef" releaseJThrowableRef :: Ptr JVM -> Ptr JThrowableRef -> IO () foreign import ccall %SAFETY% "ffijni.h &release" release_ :: FunPtr (Ptr a -> IO ()) class ReleaseGlobalReference a where release :: FunPtr (Ptr a -> IO ()) -- ^ @release@ is a special function which can be used to create a -- 'ForeignPtr'. A ForeignPtr does not carry a reference to a virtual -- machine (no @Ptr JVM@), thus this function will lookup the current -- virtual machine or do nothing if it can not find one. It is -- realised as a 'FunPtr' as this is what 'newForeignPtr' expects. release = release_ instance ReleaseGlobalReference JObjectRef instance ReleaseGlobalReference JClassRef instance ReleaseGlobalReference JThrowableRef foreign import ccall %SAFETY% "ffijni.h registerCallbacks" registerCallbacks :: Ptr JVM -> Ptr JClassRef -> IO Bool foreign import ccall %SAFETY% "ffijni.h getDebugStatus" getDebugStatus :: IO Bool foreign import ccall %SAFETY% "ffijni.g setDebugStatus" setDebugStatus :: Bool -> IO () foreign import ccall %SAFETY% "ffijni.h runCocoaMain" runCocoaMain :: IO ()
fehu/haskell-java-bridge-fork
src/Foreign/Java/JNI/core.hs
mit
22,694
111
13
4,157
5,376
2,762
2,614
-1
-1
{-| Compiling regular expressions, the new way. -} module CompileRegExp where import RegExpOps import Data.Maybe(fromJust) import qualified Data.Map as Map --import Trace compile r = number (build Map.empty [r]) where build _ [] = [] build dfa (r:rs) = if Map.member r dfa then build dfa rs else (r,fs):build dfa' (frs++rs) where dfa' = Map.insert r fs dfa fs = factors r frs = map snd (snd fs) number states = map numb states where mapping = Map.fromList (zip (map fst states) [(1::Int) ..]) num = fromJust . flip Map.lookup mapping numb (r,(b,edges)) = (num r,(b,[(t,num r)|(t,r)<-edges]))
yav/haskell-lexer
generator/src/CompileRegExp.hs
mit
686
0
14
191
294
161
133
17
3
module Main where import Graphics.Svg ( loadSvgFile ) import Graphics.Rasterific.Svg ( loadCreateFontCache, renderSvgDocument ) import Codec.Picture import Codec.Picture.Types import Data.Vector.Storable.Mutable -- ( IOVector(..) ) import Data.Word ( Word8 ) import Data.Function ( fix ) import Data.Vector.Storable ( Vector(..) ) import qualified Data.Vector.Storable as V import qualified Data.Vector.Generic.Mutable as GM import Control.Monad as CM import SDL.Video.Renderer ( createRGBSurfaceFrom, PixelFormat(..), Surface() ) import SDL.Vect ( V2(..) ) import Foreign.C.Types ( CInt ) -- SDL dependency: sudo apt-get install libsdl2-dev main :: IO () main = do let filepath = "img/homer-simpson.svg" mimage <- loadSVGImage filepath case mimage of Nothing -> putStrLn "Image convertion failed." (Just image) -> do let surfaceSize :: V2 CInt surfaceSize = V2 1280 720 surface <- createSurfaceFromSVG image surfaceSize -- show the surface putStrLn "Hopefully showing the image." createSurfaceFromSVG :: Image PixelRGBA8 -> V2 CInt -> IO Surface createSurfaceFromSVG image surfaceSize = do let rawImageData :: Vector Word8 rawImageData = imageData image imWidth :: Int imWidth = imageWidth image pitch :: CInt pitch = fromIntegral imWidth mutableVector <- convertToMutableVector rawImageData createRGBSurfaceFrom mutableVector surfaceSize pitch RGBA8888 -- | as per https://github.com/haskell/vector/issues/175, there are some missing convertion functions -- so we have to create one by hand convertToMutableVector :: Vector Word8 -> IO (IOVector Word8) convertToMutableVector v = do let len = V.length v mv <- GM.new len CM.forM_ [0..(len - 1)] $ \i -> GM.write mv i (v V.! i) return mv loadSVGImage :: FilePath -> IO (Maybe (Image PixelRGBA8)) loadSVGImage filepath = do mdoc <- loadSvgFile filepath case mdoc of Nothing -> return Nothing Just doc -> do cache <- loadCreateFontCache "fonty-texture-cache" (finalImage, _) <- renderSvgDocument cache Nothing 96 doc return $ Just finalImage
cirquit/Personal-Repository
Haskell/svg-loading/app/Main.hs
mit
2,542
0
15
826
580
303
277
52
2
module Text.Greek.Phonology.Phoneme where import Text.Greek.Phonology.Consonants import Text.Greek.Phonology.Vowels data Phoneme = MkConsonant ConsonantPhoneme | MkVowel VowelPhoneme deriving (Eq, Ord, Show)
scott-fleischman/greek-grammar
haskell/greek-grammar/src/Text/Greek/Phonology/Phoneme.hs
mit
218
0
6
29
51
32
19
7
0
{-# language DeriveDataTypeable #-} {-# language TemplateHaskell #-} module Up.Iso where import Up.Store import Autolib.Reporter import Autolib.ToDoc import Autolib.Reader import Data.Typeable import qualified Data.Map as M import Control.Monad data Links = Links [ (Int, Int) ] deriving (Eq, Ord, Typeable) derives [makeReader, makeToDoc] [''Links] nicely (Links xs) = vcat $ flip map ( zip [1 :: Int ..] xs ) $ \ (i,(d,s)) -> hsep [ text "Frame" , toDoc i, text ":" , text "dynamischer Vorgänger", toDoc d, text "," , text "statischer Vorgänger", toDoc s, text ";" ] iso :: Links -> Store -> Reporter () iso (Links dss) t = forM_ (zip [1..] dss) $ \ (i,(d,s)) -> do case M.lookup i (store t) of Nothing -> reject $ text "es existiert kein Frame mit Nummer" <+> toDoc i Just f -> do when ( d /= dynamic_link f ) $ whine "dynamische" d f when ( s /= static_link f ) $ whine "statische" s f whine tag v f = reject $ vcat [ text "der" <+> text tag <+> text "Vorgänger" <+> text "soll" <+> toDoc v <+> text "sein:" , toDoc f ]
marcellussiegburg/autotool
collection/src/Up/Iso.hs
gpl-2.0
1,201
0
18
364
452
233
219
32
2
{-# LANGUAGE RankNTypes #-} module DarkPlaces.Text ( -- types DPTextToken(..), DecodeType(..), -- type synonyms DPTextOutput, DPTextFilter, -- newtypes BinDPText(..), DPText(..), -- functions parseDPText, stripColors, toUTF, toASCII, toText, -- convert funcs fromBinDPText, fromDPText, fromByteString, toBinDPText, toDPText, -- util funcs concatText, -- output funcs hOutputColors, outputColors, hOutputNoColors, outputNoColors, hOutputColorsLn, outputColorsLn, hOutputNoColorsLn, outputNoColorsLn, -- low level output hPutDPTextTokenPlain, hPutDPTextTokenANSI, -- low level funcs conduitDPText, minimizeColorsFrom, minimizeColors, simplifyColors, -- check colors hSupportColors, supportColors ) where import DarkPlaces.Text.Lexer import DarkPlaces.Text.Types import DarkPlaces.Text.Colors import DarkPlaces.Text.Chars import DarkPlaces.Text.Classes import qualified Data.ByteString as B import qualified Data.Text as T import System.Console.ANSI (hSupportsANSI, hSetSGR) import Data.Conduit import qualified Data.Conduit.List as CL import Data.Conduit.Attoparsec (conduitParser, PositionRange) import Control.Monad.Catch (MonadThrow) import Control.Monad (when, join, liftM) import Data.String import System.IO (Handle, stdout, hPutChar) import Control.Monad.IO.Class import qualified Data.ByteString.UTF8 as BU import Data.Monoid import Data.Semigroup import Data.Function (on) type DPTextOutput a m = (MonadIO m) => Consumer (DPTextToken a) m () type DPTextFilter a m b = (Monad m) => Conduit (DPTextToken a) m (DPTextToken b) newtype BinDPText = BinDPText [DPTextToken B.ByteString] deriving (Show) newtype DPText = DPText [DPTextToken T.Text] deriving (Show) instance Eq BinDPText where (==) = (==) `on` (\(BinDPText v) -> minimizeTextTockens v) instance IsString BinDPText where fromString s = BinDPText $ join $ stream $$ CL.consume where stream = fromByteString $ BU.fromString s instance Semigroup BinDPText where (BinDPText a) <> (BinDPText b) = BinDPText $ a <> b instance Monoid BinDPText where mempty = BinDPText [] instance Eq DPText where (==) = (==) `on` (\(DPText v) -> minimizeTextTockens v) instance IsString DPText where fromString s = DPText $ join $ stream $$ CL.consume where mapDecode = CL.map $ mapTextToken (decode Utf8Lenient) stream = fromByteString (BU.fromString s) =$= mapDecode instance Semigroup DPText where (DPText a) <> (DPText b) = DPText $ a <> b instance Monoid DPText where mempty = DPText [] conduitDPText :: (MonadThrow m) => Conduit B.ByteString m (PositionRange, Maybe BinDPTextToken) conduitDPText = conduitParser maybeDPTextToken parseDPText :: (MonadThrow m) => Conduit B.ByteString m (DPTextToken B.ByteString) parseDPText = conduitDPText =$= CL.mapMaybe snd fromBinDPText :: (Monad m) => BinDPText -> Producer m (DPTextToken B.ByteString) fromBinDPText (BinDPText lst) = CL.sourceList lst toBinDPText :: (Monad m) => Producer m (DPTextToken B.ByteString) -> m BinDPText toBinDPText stream = liftM BinDPText $ stream $$ CL.consume fromDPText :: (Monad m) => DPText -> Producer m (DPTextToken T.Text) fromDPText (DPText lst) = CL.sourceList lst toDPText :: (Monad m) => Producer m (DPTextToken T.Text) -> m DPText toDPText stream = liftM DPText $ stream $$ CL.consume fromByteString :: (MonadThrow m) => B.ByteString -> Producer m (DPTextToken B.ByteString) fromByteString bs = yield bs =$= parseDPText stripColors :: DPTextFilter a m a stripColors = CL.filter isTextData removeUnnecessaryColors :: DPTextFilter a m a removeUnnecessaryColors = do m1 <- await m2 <- await case (m1, m2) of (Just t1, Nothing) -> yield t1 (Just t1, Just t2) | isColor t1, isColor t2 -> do leftover t2 removeUnnecessaryColors (Just t1, Just t2) -> do yield t1 leftover t2 removeUnnecessaryColors _ -> return () minimizeColorsFrom :: (Eq a) => DPTextToken a -> DPTextFilter a m a minimizeColorsFrom sc = removeUnnecessaryColors =$= do mt <- await case mt of Nothing -> return () Just t -> do let (sc', r) = minimize sc t when r $ yield t minimizeColorsFrom sc' where resetColor = SimpleColor 0 minimize c x | isColor x && x == c = (c, False) | isColor x = (x, True) | isNewline x = (resetColor, True) | otherwise = (c, True) minimizeColors :: (Eq a) => DPTextFilter a m a minimizeColors = minimizeColorsFrom (SimpleColor 0) toText :: (IsString a, Monad m) => Conduit (DPTextToken a) m a toText = CL.map tokenToText concatText :: (Monoid a, Monad m) => Consumer a m a concatText = mconcat `fmap` CL.consume simplifyColors :: DPTextFilter a m a simplifyColors = CL.map convert where convert (HexColor h) = SimpleColor (simplifyColor h) convert x = x toUTF :: DecodeType -> DPTextFilter B.ByteString m T.Text toUTF dec_type = CL.map $ mapTextToken decodeFun where decodeFun = decodeQFontUTF (dec_type /= NexuizDecode) . decode dec_type toASCII :: DecodeType -> DPTextFilter B.ByteString m T.Text toASCII dec_type = CL.map $ mapTextToken decodeFun where decodeFun = decodeQFontASCII (dec_type /= NexuizDecode) . decode dec_type hPutDPTextTokenPlain :: (Printable a) => Handle -> DPTextToken a -> IO () hPutDPTextTokenPlain h t = case t of (DPString s) -> hPutPrintable h s DPNewline -> hPutChar h '\n' _ -> return () hPutDPTextTokenANSI :: (Printable a) => Handle -> DPTextToken a -> IO () hPutDPTextTokenANSI h t = case t of (SimpleColor c) -> hSetSGR h (getColor c) (DPString s) -> hPutPrintable h s DPNewline -> hPutChar h '\n' >> hReset h _ -> return () hOutputColors :: (Printable a, Eq a) => Handle -> DPTextOutput a m hOutputColors h = simplifyColors =$= minimizeColors =$= output where output = addCleanup (const $ liftIO $ hReset h) (CL.mapM_ $ liftIO . hPutDPTextTokenANSI h) outputColors :: (Printable a, Eq a) => DPTextOutput a m outputColors = hOutputColors stdout hOutputNoColors :: (Printable a) => Handle -> DPTextOutput a m hOutputNoColors h = stripColors =$= CL.mapM_ (liftIO . hPutDPTextTokenPlain h) outputNoColors :: (Printable a) => DPTextOutput a m outputNoColors = hOutputNoColors stdout hWithLn :: Handle -> DPTextOutput a m -> DPTextOutput a m hWithLn h consumer = addCleanup (const newline) consumer where newline = liftIO $ hPutChar h '\n' hOutputColorsLn :: (Printable a, Eq a) => Handle -> DPTextOutput a m hOutputColorsLn h = hWithLn h (hOutputColors h) outputColorsLn :: (Printable a, Eq a) => DPTextOutput a m outputColorsLn = hOutputColorsLn stdout hOutputNoColorsLn :: (Printable a) => Handle -> DPTextOutput a m hOutputNoColorsLn h = hWithLn h (hOutputNoColors h) outputNoColorsLn :: (Printable a) => DPTextOutput a m outputNoColorsLn = hOutputNoColorsLn stdout hSupportColors :: Handle -> IO Bool hSupportColors = hSupportsANSI supportColors :: IO Bool supportColors = hSupportColors stdout minimizeTextTockens :: (Monoid a) => [DPTextToken a] -> [DPTextToken a] minimizeTextTockens ts = case ts of (DPString f):(DPString s):xs -> DPString (f <> s) : minimizeTextTockens xs x:xs -> x : minimizeTextTockens xs [] -> []
bacher09/darkplaces-text
src/DarkPlaces/Text.hs
gpl-2.0
7,570
0
16
1,685
2,498
1,307
1,191
181
4
module Network.Gitit2.Handler.Edit ( getEditR, getRevertR, postUpdateR, postCreateR ) where import Control.Monad (when) import Data.ByteString.Lazy.UTF8 (toString) import Data.FileStore as FS import Data.Maybe (fromMaybe) import qualified Data.Text as T import Network.Gitit2.Cache import Network.Gitit2.Import import Yesod (Route) getEditR :: HasGitit master => Page -> GH master Html getEditR page = do requireUser fs <- filestore <$> getYesod path <- pathForPage page mbcont <- getRawContents path Nothing let contents = case mbcont of Nothing -> "" Just c -> toString c mbrev <- case mbcont of Nothing -> return Nothing Just _ -> pathForPage page >>= \f -> liftIO (Just <$> latest fs f) edit False contents mbrev page getRevertR :: HasGitit master => RevisionId -> Page -> GH master Html getRevertR rev page = do requireUser path <- pathForPage page mbcont <- getRawContents path (Just rev) case mbcont of Nothing -> notFound Just contents -> edit True (toString contents) (Just rev) page edit :: HasGitit master => Bool -- revert? -> String -- contents to put in text box -> Maybe RevisionId -- unless new page, Just id of old version -> Page -> GH master Html edit revert txt mbrevid page = do requireUser let contents = Textarea $ T.pack txt mr <- getMessageRender let comment = if revert then mr $ MsgReverted $ fromMaybe "" mbrevid else "" (form, enctype) <- lift $ generateFormPost $ editForm $ Just Edit{ editContents = contents , editComment = comment } toMaster <- getRouteToParent let route = toMaster $ case mbrevid of Just revid -> UpdateR revid page Nothing -> CreateR page showEditForm page route enctype $ do when revert $ toWidget [julius| $(document).ready(function (){ $('textarea').attr('readonly','readonly').attr('style','color: gray;'); }); |] form showEditForm :: HasGitit master => Page -> Route master -> Enctype -> WidgetT master IO () -> GH master Html showEditForm page route enctype form = makePage pageLayout{ pgName = Just page , pgTabs = [EditTab] , pgSelectedTab = EditTab } $ do toWidget [julius| function updatePreviewPane() { var url = location.pathname.replace(/_edit\//,"_preview/"); $.post( url, {"contents" : $("#editpane").attr("value")}, function(data) { $('#previewpane').html(data); // TODO: Process any mathematics (we only use mathjax as of 2015/04/07) }, "html"); }; |] [whamlet| <h1>#{page}</h1> <div #editform> <form method=post action=@{route} enctype=#{enctype}> ^{form} <input type=submit> <input type=button onclick="updatePreviewPane()" value="Preview"> <div #previewpane> |] postUpdateR :: HasGitit master => RevisionId -> Page -> GH master Html postUpdateR revid = update' (Just revid) postCreateR :: HasGitit master => Page -> GH master Html postCreateR = update' Nothing update' :: HasGitit master => Maybe RevisionId -> Page -> GH master Html update' mbrevid page = do user <- requireUser ((result, widget), enctype) <- lift $ runFormPost $ editForm Nothing fs <- filestore <$> getYesod toMaster <- getRouteToParent let route = toMaster $ case mbrevid of Just revid -> UpdateR revid page Nothing -> CreateR page case result of FormSuccess r -> do let auth = Author (gititUserName user) (gititUserEmail user) let comm = T.unpack $ editComment r let cont = filter (/='\r') $ T.unpack $ unTextarea $ editContents r path <- pathForPage page case mbrevid of Just revid -> do mres <- liftIO $ modify fs path revid auth comm cont case mres of Right () -> do expireCache path redirect $ ViewR page Left mergeinfo -> do setMessageI $ MsgMerged revid edit False (mergeText mergeinfo) (Just $ revId $ mergeRevision mergeinfo) page Nothing -> do expireCache path liftIO $ save fs path auth comm cont redirect $ ViewR page _ -> showEditForm page route enctype widget data Edit = Edit { editContents :: Textarea , editComment :: Text } deriving Show editForm :: HasGitit master => Maybe Edit -> Html -> MForm (HandlerT master IO) (FormResult Edit, WidgetT master IO ()) editForm mbedit = renderDivs $ Edit <$> areq textareaField (fieldSettingsLabel MsgPageSource) {fsId = Just "editpane"} (editContents <$> mbedit) <*> areq commentField (fieldSettingsLabel MsgChangeDescription) (editComment <$> mbedit) where commentField = check validateNonempty textField validateNonempty y | T.null y = Left MsgValueRequired | otherwise = Right y
thkoch2001/gitit2
Network/Gitit2/Handler/Edit.hs
gpl-2.0
5,569
0
25
1,936
1,387
675
712
-1
-1
module Control.Monad.Select ( Select , chance ) where import Control.Monad.Select.Internal
davidspies/regret-solver
select-game/src/Control/Monad/Select.hs
gpl-3.0
104
0
4
23
22
15
7
4
0
module Sound.Tidal.VolcaBeats where import Sound.Tidal.Stream (makeI, makeF) import Sound.Tidal.MIDI.Control import Control.Applicative beats :: ControllerShape beats = ControllerShape { params = [ mCC "lKick" 40, mCC "lSnare" 41, mCC "lLoTom" 42, mCC "lHiTom" 43, mCC "lClHat" 44, mCC "lOpHat" 45, mCC "lClap" 46, mCC "lClaves" 47, mCC "lAgogo" 48, mCC "lCrash" 49, mCC "sClap" 50, mCC "sClaves" 51, mCC "sAgogo" 52, mCC "sCrash" 53, mCC "stutterTime" 54, mCC "stutterDepth" 55, mCC "tomDecay" 56, mCC "clHatDecay" 57, mCC "opHatDecay" 58, mCC "hatGrain" 59 ], duration = ("dur", 0.05), velocity = ("vel", 0.5), latency = 0.1 } oscBeats = toOscShape beats drum = (makeI oscBeats "note") . (noteN <$>) lbd = makeF oscBeats "lKick" lsn = makeF oscBeats "lSnare" llt = makeF oscBeats "lLoTom" lht = makeF oscBeats "lHiTom" lch = makeF oscBeats "lClHat" loh = makeF oscBeats "lOpHat" lcp = makeF oscBeats "lClap" lcl = makeF oscBeats "lClaves" lag = makeF oscBeats "lAgogo" lcr = makeF oscBeats "lCrash" scp = makeF oscBeats "sClap" scl = makeF oscBeats "sClaves" sag = makeF oscBeats "sAgogo" scr = makeF oscBeats "sCrash" stt = makeF oscBeats "stutterTime" std = makeF oscBeats "stutterDepth" dt = makeF oscBeats "tomDecay" dch = makeF oscBeats "clHatDecay" doh = makeF oscBeats "opHatDecay" dhg = makeF oscBeats "hatGrain" noteN :: String -> Int noteN "bd" = 36 noteN "sn" = 38 noteN "lt" = 43 noteN "ht" = 50 noteN "ch" = 42 noteN "oh" = 46 noteN "cp" = 39 noteN "cl" = 75 noteN "ag" = 67 noteN "cr" = 49 noteN _ = 0
lennart/tidal-midi
Sound/Tidal/VolcaBeats.hs
gpl-3.0
2,219
0
8
956
567
298
269
63
1
module Console( consoleString ) where -- | This function is used to print erroneous strings provided by users of the server. -- For one, it is supposed to escape unprintable characters. -- Furthermore it trims the string if necessary so the console can't easily be flooded by single large malicious requests. consoleString :: String -> String consoleString string = let lengthLimit = 64 in show if length string > lengthLimit then take lengthLimit string ++ "..." else string
epicvrvs/Veles
Source/Veles/Console.hs
gpl-3.0
498
0
10
100
67
36
31
-1
-1
-- NOTE: if this is NOT strict, then memory builds up like HELL {-# LANGUAGE Strict #-} module SugarScape.Core.Init ( createSugarScape ) where import Control.Monad.Random import Control.Monad.STM import Data.Char import Data.List import SugarScape.Agent.Agent import SugarScape.Agent.Common import SugarScape.Agent.Interface import SugarScape.Core.Common import SugarScape.Core.Discrete import SugarScape.Core.Model import SugarScape.Core.Random import SugarScape.Core.Scenario createSugarScape :: RandomGen g => SugarScapeScenario -> RandT g STM ([(AgentId, SugAgentObservable, SugAgentMSF g)], SugEnvironment, SugarScapeScenario) createSugarScape params = do params' <- generateDiseaseMasterList params ras <- agentDistribution params' (sgAgentDistribution params') let as = map (\(ad, _) -> (adId ad, adInitObs ad, adSf ad)) ras occupations = map (\(ad, s) -> (sugAgCoord s, (adId ad, s))) ras sugarSpecs = envSpec spiceSpecs = map reverse envSpec sugSpiceSpecs = parseEnvSpec sugarSpecs spiceSpecs sugSpiceCoords = specToCoords sugSpiceSpecs sugarscapeDimensions sites = createSites params' sugSpiceCoords occupations env <- lift $ createDiscrete2d sugarscapeDimensions neumann WrapBoth sites return (as, env, params') generateDiseaseMasterList :: MonadRandom m => SugarScapeScenario -> m SugarScapeScenario generateDiseaseMasterList params = case spDiseasesEnabled params of Nothing -> return params Just (isl, dl, dc, ad, _) -> do ml <- mapM (\_ -> do rn <- getRandomR (1, dl) take rn <$> getRandoms) [1..dc] return params { spDiseasesEnabled = Just (isl, dl, dc, ad, ml)} agentDistribution :: (MonadRandom m, RandomGen g) => SugarScapeScenario -> AgentDistribution -> m [(SugAgentDef g, SugAgentState)] agentDistribution params CombatCorners = do let agentCount = sgAgentCount params halfCount = floor ((fromIntegral agentCount / 2) :: Double) aisTopRight = [1 .. halfCount] aisBotLeft = [halfCount + 1 .. agentCount] randCoordsTopRight <- randomCoords (30, 30) sugarscapeDimensions (length aisTopRight) rasTopRight <- mapM (\(aid, coord) -> randomAgent params (aid, coord) agentMsf (changeToRedTribe params)) (zip aisTopRight randCoordsTopRight) randCoordsBotLeft <- randomCoords (0,0) (20, 20) (length aisBotLeft) rasBotLeft <- mapM (\(aid, coord) -> randomAgent params (aid, coord) agentMsf (changeToBlueTribe params)) (zip aisBotLeft randCoordsBotLeft) return (rasBotLeft ++ rasTopRight) agentDistribution params dist = do let agentCount = sgAgentCount params ais = [1..agentCount] coordDims = case dist of Scatter -> sugarscapeDimensions (Corner dim) -> dim _ -> error "missing AgentDistribution case, programming fault, shouldn't happen!" randCoords <- randomCoords (0,0) coordDims agentCount mapM (\(aid, coord) -> randomAgent params (aid, coord) agentMsf id) (zip ais randCoords) specToCoords :: [[(Int, Int)]] -> Discrete2dCoord -> [(Discrete2dCoord, Int, Int)] specToCoords specs (dimX, dimY) | length specs /= dimY = error ("sugar row count does not match y-dimensions: " ++ show (length specs) ++ " not " ++ show dimY) | otherwise = specLines specs 0 [] where specLines :: [[(Int, Int)]] -> Int -> [(Discrete2dCoord, Int, Int)] -> [(Discrete2dCoord, Int, Int)] specLines [] _ acc = acc specLines (l : ls) y acc | length l /= dimX = error ("sugar spec line size does not match x-dimensions: " ++ show (length l) ++ " not " ++ show dimX) | otherwise = specLines ls (y + 1) acc' where acc' = specLineToCoords l 0 acc specLineToCoords :: [(Int, Int)] -> Int -> [(Discrete2dCoord, Int, Int)] -> [(Discrete2dCoord, Int, Int)] specLineToCoords [] _ accLine = accLine specLineToCoords ((su, sp) : ss) x accLine = specLineToCoords ss (x + 1) accLine' where accLine' = ((x, y), su, sp) : accLine parseEnvSpec :: [String] -> [String] -> [[(Int, Int)]] parseEnvSpec = zipWith parseEnvSpecLine where parseEnvSpecLine :: String -> String -> [(Int, Int)] parseEnvSpecLine sugLine spiceLine = reverse $ zipWith parseEnvSpecAux sugLine spiceLine where parseEnvSpecAux :: Char -> Char -> (Int, Int) parseEnvSpecAux su sp | isNumber su && isNumber sp = (digitToInt su, digitToInt sp) | otherwise = error "bad character in environment specification" createSites :: SugarScapeScenario -> [(Discrete2dCoord, Int, Int)] -> [(Discrete2dCoord, (AgentId, SugAgentState))] -> [(Discrete2dCoord, SugEnvSite)] createSites params siteSpecs occupations = map (initRandomSite params occupations) siteSpecs initRandomSite :: SugarScapeScenario -> [(Discrete2dCoord, (AgentId, SugAgentState))] -> (Discrete2dCoord, Int, Int) -> (Discrete2dCoord, SugEnvSite) initRandomSite params os (coord, sugar, spice) = (coord, c) where mayOccupier = Data.List.find ((==coord) . fst) os occ = maybe Nothing (\(_, (aid, s)) -> (Just $ occupier aid s)) mayOccupier spice' = if spSpiceEnabled params then spice else 0 c = SugEnvSite { sugEnvSiteSugarCapacity = fromIntegral sugar , sugEnvSiteSugarLevel = fromIntegral sugar , sugEnvSiteSpiceCapacity = fromIntegral spice' , sugEnvSiteSpiceLevel = fromIntegral spice' , sugEnvSiteOccupier = occ , sugEnvSitePolutionLevel = 0 } randomCoords :: MonadRandom m => Discrete2dDimension -> Discrete2dDimension -> Int -> m [Discrete2dCoord] randomCoords (minX, minY) (maxX, maxY) n | n > maxCoords = error "Logical error: can't draw more elements from a finite set than there are elements in the set" | otherwise = do let coords = [ (x, y) | x <- [minX..maxX-1], y <- [minY..maxY-1] ] shuffCoords <- fisherYatesShuffleM coords return $ take n shuffCoords where maxCoords = (maxX - minX) * (maxY - minY)
thalerjonathan/phd
public/towards/SugarScape/experimental/concurrent/src/SugarScape/Core/Init.hs
gpl-3.0
6,713
0
18
1,959
1,950
1,051
899
135
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.SQL.BackupRuns.Insert -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a new backup run on demand. -- -- /See:/ <https://developers.google.com/cloud-sql/ Cloud SQL Admin API Reference> for @sql.backupRuns.insert@. module Network.Google.Resource.SQL.BackupRuns.Insert ( -- * REST Resource BackupRunsInsertResource -- * Creating a Request , backupRunsInsert , BackupRunsInsert -- * Request Lenses , briXgafv , briUploadProtocol , briProject , briAccessToken , briUploadType , briPayload , briCallback , briInstance ) where import Network.Google.Prelude import Network.Google.SQLAdmin.Types -- | A resource alias for @sql.backupRuns.insert@ method which the -- 'BackupRunsInsert' request conforms to. type BackupRunsInsertResource = "v1" :> "projects" :> Capture "project" Text :> "instances" :> Capture "instance" Text :> "backupRuns" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] BackupRun :> Post '[JSON] Operation -- | Creates a new backup run on demand. -- -- /See:/ 'backupRunsInsert' smart constructor. data BackupRunsInsert = BackupRunsInsert' { _briXgafv :: !(Maybe Xgafv) , _briUploadProtocol :: !(Maybe Text) , _briProject :: !Text , _briAccessToken :: !(Maybe Text) , _briUploadType :: !(Maybe Text) , _briPayload :: !BackupRun , _briCallback :: !(Maybe Text) , _briInstance :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BackupRunsInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'briXgafv' -- -- * 'briUploadProtocol' -- -- * 'briProject' -- -- * 'briAccessToken' -- -- * 'briUploadType' -- -- * 'briPayload' -- -- * 'briCallback' -- -- * 'briInstance' backupRunsInsert :: Text -- ^ 'briProject' -> BackupRun -- ^ 'briPayload' -> Text -- ^ 'briInstance' -> BackupRunsInsert backupRunsInsert pBriProject_ pBriPayload_ pBriInstance_ = BackupRunsInsert' { _briXgafv = Nothing , _briUploadProtocol = Nothing , _briProject = pBriProject_ , _briAccessToken = Nothing , _briUploadType = Nothing , _briPayload = pBriPayload_ , _briCallback = Nothing , _briInstance = pBriInstance_ } -- | V1 error format. briXgafv :: Lens' BackupRunsInsert (Maybe Xgafv) briXgafv = lens _briXgafv (\ s a -> s{_briXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). briUploadProtocol :: Lens' BackupRunsInsert (Maybe Text) briUploadProtocol = lens _briUploadProtocol (\ s a -> s{_briUploadProtocol = a}) -- | Project ID of the project that contains the instance. briProject :: Lens' BackupRunsInsert Text briProject = lens _briProject (\ s a -> s{_briProject = a}) -- | OAuth access token. briAccessToken :: Lens' BackupRunsInsert (Maybe Text) briAccessToken = lens _briAccessToken (\ s a -> s{_briAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). briUploadType :: Lens' BackupRunsInsert (Maybe Text) briUploadType = lens _briUploadType (\ s a -> s{_briUploadType = a}) -- | Multipart request metadata. briPayload :: Lens' BackupRunsInsert BackupRun briPayload = lens _briPayload (\ s a -> s{_briPayload = a}) -- | JSONP briCallback :: Lens' BackupRunsInsert (Maybe Text) briCallback = lens _briCallback (\ s a -> s{_briCallback = a}) -- | Cloud SQL instance ID. This does not include the project ID. briInstance :: Lens' BackupRunsInsert Text briInstance = lens _briInstance (\ s a -> s{_briInstance = a}) instance GoogleRequest BackupRunsInsert where type Rs BackupRunsInsert = Operation type Scopes BackupRunsInsert = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/sqlservice.admin"] requestClient BackupRunsInsert'{..} = go _briProject _briInstance _briXgafv _briUploadProtocol _briAccessToken _briUploadType _briCallback (Just AltJSON) _briPayload sQLAdminService where go = buildClient (Proxy :: Proxy BackupRunsInsertResource) mempty
brendanhay/gogol
gogol-sqladmin/gen/Network/Google/Resource/SQL/BackupRuns/Insert.hs
mpl-2.0
5,384
0
20
1,345
864
502
362
127
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.EC2.CopySnapshot -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Copies a point-in-time snapshot of an EBS volume and stores it in Amazon S3. -- You can copy the snapshot within the same region or from one region to -- another. You can use the snapshot to create EBS volumes or Amazon Machine -- Images (AMIs). The snapshot is copied to the regional endpoint that you send -- the HTTP request to. -- -- Copies of encrypted EBS snapshots remain encrypted. Copies of unencrypted -- snapshots remain unencrypted. -- -- Copying snapshots that were encrypted with non-default AWS Key Management -- Service (KMS) master keys is not supported at this time. -- -- For more information, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-copy-snapshot.html Copying an Amazon EBS Snapshot> in the /AmazonElastic Compute Cloud User Guide/. -- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CopySnapshot.html> module Network.AWS.EC2.CopySnapshot ( -- * Request CopySnapshot -- ** Request constructor , copySnapshot -- ** Request lenses , csDescription , csDestinationRegion , csDryRun , csPresignedUrl , csSourceRegion , csSourceSnapshotId -- * Response , CopySnapshotResponse -- ** Response constructor , copySnapshotResponse -- ** Response lenses , csrSnapshotId ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.EC2.Types import qualified GHC.Exts data CopySnapshot = CopySnapshot { _csDescription :: Maybe Text , _csDestinationRegion :: Maybe Text , _csDryRun :: Maybe Bool , _csPresignedUrl :: Maybe Text , _csSourceRegion :: Text , _csSourceSnapshotId :: Text } deriving (Eq, Ord, Read, Show) -- | 'CopySnapshot' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'csDescription' @::@ 'Maybe' 'Text' -- -- * 'csDestinationRegion' @::@ 'Maybe' 'Text' -- -- * 'csDryRun' @::@ 'Maybe' 'Bool' -- -- * 'csPresignedUrl' @::@ 'Maybe' 'Text' -- -- * 'csSourceRegion' @::@ 'Text' -- -- * 'csSourceSnapshotId' @::@ 'Text' -- copySnapshot :: Text -- ^ 'csSourceRegion' -> Text -- ^ 'csSourceSnapshotId' -> CopySnapshot copySnapshot p1 p2 = CopySnapshot { _csSourceRegion = p1 , _csSourceSnapshotId = p2 , _csDryRun = Nothing , _csDescription = Nothing , _csDestinationRegion = Nothing , _csPresignedUrl = Nothing } -- | A description for the EBS snapshot. csDescription :: Lens' CopySnapshot (Maybe Text) csDescription = lens _csDescription (\s a -> s { _csDescription = a }) -- | The destination region to use in the 'PresignedUrl' parameter of a snapshot -- copy operation. This parameter is only valid for specifying the destination -- region in a 'PresignedUrl' parameter, where it is required. -- -- 'CopySnapshot' sends the snapshot copy to the regional endpoint that you send -- the HTTP request to, such as 'ec2.us-east-1.amazonaws.com' (in the AWS CLI, -- this is specified with the '--region' parameter or the default region in your -- AWS configuration file). -- -- csDestinationRegion :: Lens' CopySnapshot (Maybe Text) csDestinationRegion = lens _csDestinationRegion (\s a -> s { _csDestinationRegion = a }) -- | Checks whether you have the required permissions for the action, without -- actually making the request, and provides an error response. If you have the -- required permissions, the error response is 'DryRunOperation'. Otherwise, it is 'UnauthorizedOperation'. csDryRun :: Lens' CopySnapshot (Maybe Bool) csDryRun = lens _csDryRun (\s a -> s { _csDryRun = a }) -- | The pre-signed URL that facilitates copying an encrypted snapshot. This -- parameter is only required when copying an encrypted snapshot with the Amazon -- EC2 Query API; it is available as an optional parameter in all other cases. -- The 'PresignedUrl' should use the snapshot source endpoint, the 'CopySnapshot' -- action, and include the 'SourceRegion', 'SourceSnapshotId', and 'DestinationRegion' -- parameters. The 'PresignedUrl' must be signed using AWS Signature Version 4. -- Because EBS snapshots are stored in Amazon S3, the signing algorithm for this -- parameter uses the same logic that is described in <http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html Authenticating Requests byUsing Query Parameters (AWS Signature Version 4)> in the /Amazon Simple StorageService API Reference/. An invalid or improperly signed 'PresignedUrl' will -- cause the copy operation to fail asynchronously, and the snapshot will move -- to an 'error' state. csPresignedUrl :: Lens' CopySnapshot (Maybe Text) csPresignedUrl = lens _csPresignedUrl (\s a -> s { _csPresignedUrl = a }) -- | The ID of the region that contains the snapshot to be copied. csSourceRegion :: Lens' CopySnapshot Text csSourceRegion = lens _csSourceRegion (\s a -> s { _csSourceRegion = a }) -- | The ID of the EBS snapshot to copy. csSourceSnapshotId :: Lens' CopySnapshot Text csSourceSnapshotId = lens _csSourceSnapshotId (\s a -> s { _csSourceSnapshotId = a }) newtype CopySnapshotResponse = CopySnapshotResponse { _csrSnapshotId :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'CopySnapshotResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'csrSnapshotId' @::@ 'Maybe' 'Text' -- copySnapshotResponse :: CopySnapshotResponse copySnapshotResponse = CopySnapshotResponse { _csrSnapshotId = Nothing } -- | The ID of the new snapshot. csrSnapshotId :: Lens' CopySnapshotResponse (Maybe Text) csrSnapshotId = lens _csrSnapshotId (\s a -> s { _csrSnapshotId = a }) instance ToPath CopySnapshot where toPath = const "/" instance ToQuery CopySnapshot where toQuery CopySnapshot{..} = mconcat [ "Description" =? _csDescription , "DestinationRegion" =? _csDestinationRegion , "DryRun" =? _csDryRun , "PresignedUrl" =? _csPresignedUrl , "SourceRegion" =? _csSourceRegion , "SourceSnapshotId" =? _csSourceSnapshotId ] instance ToHeaders CopySnapshot instance AWSRequest CopySnapshot where type Sv CopySnapshot = EC2 type Rs CopySnapshot = CopySnapshotResponse request = post "CopySnapshot" response = xmlResponse instance FromXML CopySnapshotResponse where parseXML x = CopySnapshotResponse <$> x .@? "snapshotId"
romanb/amazonka
amazonka-ec2/gen/Network/AWS/EC2/CopySnapshot.hs
mpl-2.0
7,485
0
9
1,538
805
495
310
86
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AccessApproval.Projects.ApprovalRequests.Approve -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Approves a request and returns the updated ApprovalRequest. Returns -- NOT_FOUND if the request does not exist. Returns FAILED_PRECONDITION if -- the request exists but is not in a pending state. -- -- /See:/ <https://cloud.google.com/access-approval/docs Access Approval API Reference> for @accessapproval.projects.approvalRequests.approve@. module Network.Google.Resource.AccessApproval.Projects.ApprovalRequests.Approve ( -- * REST Resource ProjectsApprovalRequestsApproveResource -- * Creating a Request , projectsApprovalRequestsApprove , ProjectsApprovalRequestsApprove -- * Request Lenses , paraXgafv , paraUploadProtocol , paraAccessToken , paraUploadType , paraPayload , paraName , paraCallback ) where import Network.Google.AccessApproval.Types import Network.Google.Prelude -- | A resource alias for @accessapproval.projects.approvalRequests.approve@ method which the -- 'ProjectsApprovalRequestsApprove' request conforms to. type ProjectsApprovalRequestsApproveResource = "v1" :> CaptureMode "name" "approve" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] ApproveApprovalRequestMessage :> Post '[JSON] ApprovalRequest -- | Approves a request and returns the updated ApprovalRequest. Returns -- NOT_FOUND if the request does not exist. Returns FAILED_PRECONDITION if -- the request exists but is not in a pending state. -- -- /See:/ 'projectsApprovalRequestsApprove' smart constructor. data ProjectsApprovalRequestsApprove = ProjectsApprovalRequestsApprove' { _paraXgafv :: !(Maybe Xgafv) , _paraUploadProtocol :: !(Maybe Text) , _paraAccessToken :: !(Maybe Text) , _paraUploadType :: !(Maybe Text) , _paraPayload :: !ApproveApprovalRequestMessage , _paraName :: !Text , _paraCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsApprovalRequestsApprove' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'paraXgafv' -- -- * 'paraUploadProtocol' -- -- * 'paraAccessToken' -- -- * 'paraUploadType' -- -- * 'paraPayload' -- -- * 'paraName' -- -- * 'paraCallback' projectsApprovalRequestsApprove :: ApproveApprovalRequestMessage -- ^ 'paraPayload' -> Text -- ^ 'paraName' -> ProjectsApprovalRequestsApprove projectsApprovalRequestsApprove pParaPayload_ pParaName_ = ProjectsApprovalRequestsApprove' { _paraXgafv = Nothing , _paraUploadProtocol = Nothing , _paraAccessToken = Nothing , _paraUploadType = Nothing , _paraPayload = pParaPayload_ , _paraName = pParaName_ , _paraCallback = Nothing } -- | V1 error format. paraXgafv :: Lens' ProjectsApprovalRequestsApprove (Maybe Xgafv) paraXgafv = lens _paraXgafv (\ s a -> s{_paraXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). paraUploadProtocol :: Lens' ProjectsApprovalRequestsApprove (Maybe Text) paraUploadProtocol = lens _paraUploadProtocol (\ s a -> s{_paraUploadProtocol = a}) -- | OAuth access token. paraAccessToken :: Lens' ProjectsApprovalRequestsApprove (Maybe Text) paraAccessToken = lens _paraAccessToken (\ s a -> s{_paraAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). paraUploadType :: Lens' ProjectsApprovalRequestsApprove (Maybe Text) paraUploadType = lens _paraUploadType (\ s a -> s{_paraUploadType = a}) -- | Multipart request metadata. paraPayload :: Lens' ProjectsApprovalRequestsApprove ApproveApprovalRequestMessage paraPayload = lens _paraPayload (\ s a -> s{_paraPayload = a}) -- | Name of the approval request to approve. paraName :: Lens' ProjectsApprovalRequestsApprove Text paraName = lens _paraName (\ s a -> s{_paraName = a}) -- | JSONP paraCallback :: Lens' ProjectsApprovalRequestsApprove (Maybe Text) paraCallback = lens _paraCallback (\ s a -> s{_paraCallback = a}) instance GoogleRequest ProjectsApprovalRequestsApprove where type Rs ProjectsApprovalRequestsApprove = ApprovalRequest type Scopes ProjectsApprovalRequestsApprove = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsApprovalRequestsApprove'{..} = go _paraName _paraXgafv _paraUploadProtocol _paraAccessToken _paraUploadType _paraCallback (Just AltJSON) _paraPayload accessApprovalService where go = buildClient (Proxy :: Proxy ProjectsApprovalRequestsApproveResource) mempty
brendanhay/gogol
gogol-accessapproval/gen/Network/Google/Resource/AccessApproval/Projects/ApprovalRequests/Approve.hs
mpl-2.0
5,815
0
16
1,259
781
457
324
116
1
{-# LANGUAGE DeriveGeneric, LambdaCase #-} import GHC.Exts (Down(..)) import GHC.Generics (Generic) import Numeric (showFFloat) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8) import Data.ByteString as B (readFile) import Data.List (sort, sortBy, group, isSuffixOf) import Data.Char (isSpace, isLetter, isPunctuation) import Data.Ord (comparing) import Data.Either (partitionEithers) import Data.Binary import Control.Monad.IO.Class import Control.Monad ((>=>), when) import Control.Arrow ((&&&), second) import System.Directory import System.Console.Haskeline -- -- Types and static data -- type BigramFreq = ((Char, Char), Double) -- the langugage model consists of a name (ISO 639-1 code) -- and a vector of bigram frequencies data LanguageModel = LM !String ![BigramFreq] deriving Generic instance Binary LanguageModel -- custom Show instance for display in the REPL instance Show LanguageModel where show (LM name freqs) = unlines [ getExtendedModelName name ++ ", its 30 most common bigrams being:" , " " ++ (unwords . map (deTuple . fst) . take 30) freqs ] where deTuple (a, b) = [a, b] modelName (LM name _) = name -- similarity is more significant when the input data is -- by at least dDistanceThreshold more similar to the best -- fitting model than to the one next-to-best dDistanceThreshold = 0.01 :: Double absentBigramPenaltyFactor = 1.5 :: Double -- special char for intermediate representation of word boundaries wordBoundary = '#' :: Char -- -- Functions for bigram model creation, comparison and evaluation -- -- leaves only letters, special chars and the word boundary for bigram -- creation. bigrams containing a word boundary will be disregarded. prepare :: T.Text -> T.Text prepare = T.intercalate (T.singleton wordBoundary) . T.words . T.filter (\c -> isSpace c || isLetter c || retain c) . T.map punctuationToSpace where punctuationToSpace c = if isPunctuation c && (not . retain) c then ' ' else c retain = (`elem` "'") -- special chars to retain, e.g. apostrophe -- creates a list of bigram frequencies given some input data. -- only the 150 most frequent bigrams are retained to limit -- space usage; increasing that number should minimize fallout, -- and might need readjustment of the value for dDistanceThreshold. createFrequencies :: T.Text -> [BigramFreq] createFrequencies t = map (second (\c -> fromIntegral c / fromIntegral len)) . take 150 -- 150 bigrams ~4kB (on-disk) language model . sortBy (comparing (Down . snd)) . map (head &&& length) . group . sort $ bgs where bigrams a = T.zip a (T.tail a) len = length bgs bgs = filter (\(x, y) -> x /= wordBoundary && y /= wordBoundary) . bigrams . prepare $ t -- vector distance of bigram frequencies with respect to a language model -- is used as a similarity measure of some input data with that model vectorDistance :: LanguageModel -> [BigramFreq] -> Double vectorDistance (LM _ freqs) = sqrt . sum . map ((^ 2) . distance) where distance (bg, freq) = maybe (absentBigramPenaltyFactor * freq) -- penalty for bigrams absent from the model (subtract freq) (lookup bg freqs) -- evaluate bigram frequency similarity relative to some language models -- to utter a more or less precise guess makeGuess :: Bool -> [LanguageModel] -> [BigramFreq] -> InputT IO () makeGuess showDeltas models freqs | length models <= 1 = outputStrLn "I cant' really tell, need at least 2 language models" | otherwise = let dFreqs@(a:b:_) = sortBy (comparing fst) [(vectorDistance m freqs, name) | m@(LM name _) <- models] bestGuess = getExtendedModelName (snd a) in do when showDeltas $ mapM_ (\(dist, name) -> outputStrLn ("Δ" ++ name ++ " ≈ " ++ showFFloat (Just 6) dist "")) dFreqs outputStrLn $ if fst b - fst a >= dDistanceThreshold then "I'm quite sure this is: " ++ bestGuess else "I'd have to guess... " ++ bestGuess -- -- File handling -- -- loads all .lmod files in current directory -- exceptions are caught and wrapped up in the Either type loadModels :: InputT IO [Either String LanguageModel] loadModels = liftIO $ filesByExtension ".lmod" >>= mapM tryLoad where tryLoad fName = (Right `fmap` decodeFile fName) `catch` (\e -> return $ Left (fName ++ " -- " ++ show (e :: SomeException))) -- loads a text file and creates bigram frequency vector from it. -- can throw an exception loadAndCreateFrequencies :: FilePath -> IO [BigramFreq] loadAndCreateFrequencies = B.readFile >=> return . createFrequencies . decodeUtf8 -- returns a list of files with a given extension in the current directory filesByExtension :: String -> IO [FilePath] filesByExtension ext = getCurrentDirectory >>= (getDirectoryContents >=> return . filter (ext `isSuffixOf`)) -- write a model file for a given language code analyzing some file input writeModelFile :: FilePath -> String -> InputT IO () writeModelFile fp lcode = handle (\e -> outputStrLn $ fp ++ " -- " ++ show (e :: SomeException)) $ liftIO $ do freqs <- loadAndCreateFrequencies fp encodeFile fName (LM lcode freqs) putStrLn ("model file created: " ++ fName) where fName = lcode ++ ".lmod" -- -- the REPL -- eval :: [LanguageModel] -> String -> InputT IO () eval _ "h" = outputStrLn "e <file> - load a file, evaluate differences to loaded models and make a guess\n\ \i <text> - for some input, evaluate differences to loaded models and make a guess\n\ \t <file> - load a file, train a model from its data\n\ \r - rebuild models from <xy.txt> files, xy being a 2-letter language code\n\ \s - show models loaded in memory\n\ \q - quit" eval models "s" | null models = outputStrLn "no models loaded" | otherwise = mapM_ (outputStrLn . show) models eval _ ('t':' ':fp) = do ln <- getInputLine "2-letter language code? " let lcode = case ln of Just c@(a:b:[]) -> c _ -> "__" writeModelFile fp lcode eval _ "r" = do fps <- filter ((== 6) . length) `fmap` liftIO (filesByExtension ".txt") sequence_ [writeModelFile fp (take 2 fp) | fp <- fps] eval models ('e':' ':fp) = handle (\e -> outputStrLn $ show (e :: SomeException)) $ liftIO (loadAndCreateFrequencies fp) >>= makeGuess True models eval models ('i':' ':someInput) = makeGuess True models . createFrequencies . T.pack $ someInput eval _ _ = outputStrLn "unknown command" main = putStrLn "Guess the language !!1!\n\ \ (c) by M. G. Meier 2013" >> runInputT defaultSettings main' >> putStrLn "" main' = do (bads, goods) <- partitionEithers `fmap` loadModels mapM_ outputStrLn bads outputStrLn $ show (length goods) ++ " model(s) loaded" repl $ sortBy (comparing modelName) goods where repl models = getInputLine "(h for help) > " >>= maybe (outputStrLn "") (\case "q" -> return () xs@(x:_) | x `elem` "rt" -> eval models xs >> main' -- to reload models | otherwise -> eval models xs >> repl models _ -> repl models) -- -- some more static data; extend from here: -- http://meta.wikimedia.org/wiki/Template:List_of_language_names_ordered_by_code -- getExtendedModelName name = name ++ maybe "" (" -- " ++) (lookup name iso6391Codes) iso6391Codes = [ ("br", "Brezhoneg") , ("cy", "Cymraeg") , ("de", "Deutsch") , ("en", "English") , ("es", "Español") , ("et", "Eesti keel") , ("eu", "Euskara") , ("fi", "Suomi") , ("fr", "Français") , ("ka", "Kartuli ena") , ("pt", "Português") , ("sv", "Svenska") ]
mgmeier/LanguageClassifier
LangClass.hs
unlicense
8,524
0
19
2,504
2,054
1,102
952
-1
-1
{-# LANGUAGE FlexibleInstances #-} module FOLSpec where import qualified Data.Text as T import Test.QuickCheck import Control.Monad import Akarui.FOL.Formula import Akarui.FOL.FOL import Akarui.FOL.Symbols import Akarui.FOL.BinT import Akarui.Parser.FOL import PredicateSpec genAtom :: Gen FOL genAtom = do p <- genPredicate return $ Atom p -- Missing: existential and universal Quantifiers: instance Arbitrary FOL where arbitrary = sized fol' where fol' 0 = elements [top, bot] fol' n = oneof [ elements [top, bot] , genAtom , liftM Not sub , liftM2 (BinOp And) sub sub , liftM2 (BinOp Or) sub sub , liftM2 (BinOp Implies) sub sub , liftM2 (BinOp Xor) sub sub , liftM2 (BinOp Iff) sub sub] where sub = fol' (n `div` 2) instance Arbitrary Symbols where arbitrary = elements [long, shouting, symbolic, semisymbolic] -- Tests if printing a formula and parsing the result yields back the original formula. prop_parsing_back :: Symbols -> FOL -> Bool prop_parsing_back s f = case parseFOL (T.unpack $ prettyPrintFm s f) of Left _ -> False Right f' -> f == f' -- Make sure Ord and Eq fit together. prop_fol_ord :: FOL -> FOL -> Bool prop_fol_ord f0 f1 = case f0 `compare` f1 of EQ -> f0 == f1 _ -> f0 /= f1 -- Equal to self. prop_fol_self_eq :: FOL -> Bool prop_fol_self_eq f = f `compare` f == EQ && f == f
PhDP/Manticore
tests/FOLSpec.hs
apache-2.0
1,447
0
12
368
440
238
202
41
2
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} -- | Very simple scheduler and node monitor module Main where import System.Environment (getArgs) import Control.Applicative import Control.Monad import Control.Monad.Trans.Except import Control.Distributed.Process import Control.Distributed.Process.Closure import Control.Distributed.Process.Node (initRemoteTable) import Control.Distributed.Process.Backend.SimpleLocalnet import Control.Distributed.Process.Serializable (Serializable) import Control.Distributed.Process.Platform.ManagedProcess import Control.Distributed.Process.Platform.Async import Data.Binary import Data.Binary.Get import Data.Binary.Put import Data.Typeable import qualified Data.Set as Set import qualified Data.Map as Map import Data.Map (Map) import Data.Set (Set) import qualified Data.Vector.Storable as S import Text.Printf import GHC.Generics (Generic) ---------------------------------------------------------------- -- ---------------------------------------------------------------- -- | Representation of the DNA program -- -- data DNA a where DotProduct :: DNA (DVector Double) -> DNA (DVector Double) -> DNA Double ReadFile :: FilePath -> DNA (DVector Double) Generate :: DNA (DVector Double) deriving Typeable -- | Distributed vector data DVector a = DVector (S.Vector a) {- instance Binary a => Binary (DNA a) where get = do tag <- getWord8 case tag of put (DotProduct a b) = undefined -} ---------------------------------------------------------------- -- Interpretation of DNA program ---------------------------------------------------------------- controller :: ProcessDefinition () controller = defaultProcess { apiHandlers = [] } ---------------------------------------------------------------- -- Actors ---------------------------------------------------------------- -- | Single threaded interpretation of a program interpret :: DNA a -> Process a interpret (DotProduct a b) = do -- We create asyncA <- asyncLinkedSTM $ task $ interpret a asyncB <- asyncLinkedSTM $ task $ interpret b ra <- wait asyncA rb <- wait asyncB case (ra,rb) of (AsyncDone (DVector va), AsyncDone (DVector vb)) -> return $ S.sum $ S.zipWith (*) va vb interpret (ReadFile fname) = undefined interpret (Generate) = undefined
SKA-ScienceDataProcessor/RC
MS1/distributed-dot-product/managed.hs
apache-2.0
2,486
0
13
363
490
287
203
48
1
{-# LANGUAGE TupleSections #-} module DuckTest.Internal.State.Init where import DuckTest.Builtins import DuckTest.Internal.State import DuckTest.Types initState :: InternalState e initState = addVariableType "hasattr" (Functional [("", Any), ("", strType)] Any) $ addVariableType "print" (Functional [("", Any)] Void) $ addVariableType "len" (Functional [("", fromList Nothing $ map (,Any) ["__len__"])] Any) $ addVariableType "str" (Functional [("", fromList Nothing $ map (,Any) ["__str__"])] strType) $ addVariableType "int" (Functional [("", Any)] intType) $ addVariableType "set" (Functional [] setType) $ addVariableType "list" (Functional [] $ listType Any) emptyState
jrahm/DuckTest
src/DuckTest/Internal/State/Init.hs
bsd-2-clause
710
0
17
114
256
139
117
15
1
module Conf.ParseSpec (spec) where import Data.Version (makeVersion) import Distribution.Compiler (CompilerId(..), CompilerFlavor(..)) import Distribution.PackageDescription (FlagName(..)) import Distribution.System (OS(..), Arch(..)) import Test.Hspec import Conf.Parse (Conf(..)) import qualified Conf.Parse as Conf spec :: Spec spec = do describe "parse" $ do it "accepts empty sections" $ Conf.parse "" `shouldBe` Right (Conf.defaultConf) it "accepts OSes Cabal considers valid" $ Conf.parse "windows" `shouldBe` Right (Conf.defaultConf { os = Windows }) it "accepts arches Cabal considers valid" $ Conf.parse ";i386" `shouldBe` Right (Conf.defaultConf { arch = I386 }) it "accepts compilers Cabal considers valid" $ Conf.parse ";;yhc-1.0" `shouldBe` Right (Conf.defaultConf { impl = CompilerId YHC (makeVersion [1, 0]) }) it "accepts flags assignments" $ Conf.parse ";;;+foo,-bar,-baz" `shouldBe` Right (Conf.defaultConf { cflags = [enable "foo", disable "bar", disable "baz" ] }) it "acceots skipped sections" $ Conf.parse ";i386;;+foo,-bar,-baz" `shouldBe` Right (Conf.defaultConf { arch = I386, cflags = [enable "foo", disable "bar", disable "baz" ] }) it "accepts more skipped sections" $ Conf.parse "windows;;yhc-1.0;" `shouldBe` Right (Conf.defaultConf { os = Windows , impl = CompilerId YHC (makeVersion [1, 0]) }) it "flag assignments start with + or -" $ Conf.parse "windows;;yhc-1.0;*foo" `shouldSatisfy` isLeft enable, disable :: String -> (FlagName, Bool) enable n = (FlagName n, True) disable n = (FlagName n, False) isLeft :: Either e a -> Bool isLeft (Left _) = True isLeft (Right _) = False
supki/outdated
test/spec/Conf/ParseSpec.hs
bsd-2-clause
1,840
0
18
449
571
310
261
43
1
{-# LANGUAGE TypeOperators #-} {- API.hs , building blocks that needs to know about the program datastructure (a :-> b) Joel Svensson -} module Obsidian.ArrowObsidian.API ( (->-), pure, sync, two, ilv ) where import Data.Bits import Data.Word import Obsidian.ArrowObsidian.Arr import Obsidian.ArrowObsidian.Core import Obsidian.ArrowObsidian.Flatten import Obsidian.ArrowObsidian.Exp import Obsidian.ArrowObsidian.Bitwise import Obsidian.ArrowObsidian.PureAPI -------------------------------------------------------------------------------- pure = Pure (->-) :: (a :-> b) -> (b :-> c) -> (a :-> c) Pure f ->- Pure g = Pure (g . f) Pure f ->- Sync g h = Sync (g . f) h Sync f h1 ->- h2 = Sync f (h1 ->- h2) sync :: Flatten a => (Arr a :-> Arr a) sync = Sync (fmap toFData) (pure (fmap fromFData)) -------------------------------------------------------------------------------- ilv f = Pure riffle' ->- two f ->- Pure unriffle' -------------------------------------------------------------------------------- logInt n | n <= 1 = 0 logInt n = 1 + logInt (n `div` 2) -------------------------------------------------------------------------------- two :: (Arr a :-> Arr b) -> (Arr a :-> Arr b) two (Pure f) = Pure $ twoFF f two (Sync f g) = Sync (twoFF f) (two g) twoFF :: (Arr a -> Arr b) -> Arr a -> Arr b twoFF f arr = Arr (\i -> f ( Arr (\j -> arr ! ((sh bit bit2 (i .&. num2)) .|. j)) n2) ! (i .&. mask)) nl where n2 = (len arr) `div` 2 :: Int bit = logInt n2 bit2 = logInt nl2 num2 = fromIntegral $ 2^bit2 mask = complement num2 nl = 2 * nl2 nl2 = (len (f (Arr (\j -> arr ! variable "X") n2 ))) sh :: (Bits a) => Int -> Int -> a -> a sh b1 b2 a | b1 == b2 = a | b1 < b2 = a `shiftR` (b2 - b1) | b1 > b2 = a `shiftL` (b1 - b2) twoFF' :: (Arr a -> Arr b) -> Arr a -> Arr b twoFF' f arr = Arr (\i -> f ( Arr (\j -> arr ! (ifThenElse (top i) (j + fromIntegral m) j)) m) ! (bot i)) nl where m = len arr `div` 2 top i = i >=* (fromIntegral m) bot i = i `mod` (fromIntegral m) nl = len arr
svenssonjoel/ArrowObsidian
Obsidian/ArrowObsidian/API.hs
bsd-3-clause
2,370
0
20
755
911
476
435
52
1
module UtilSpec (main, spec) where import Model import Util import Data.AEq import Test.Hspec import Test.QuickCheck import Debug.Trace -- `main` is here so that this module can be run from GHCi on its own. It is -- not needed for automatic spec discovery. main :: IO () main = hspec spec spec :: Spec spec = do describe "Matrix" $ do it "implements equality" $ do m `shouldBe` m it "implements inequality" $ do m1 `shouldNotBe` m describe "addOne" $ do it "appends column of ones to left side of matrix" $ do addOnes s `shouldBe` sAddOnes
lobachevzky/deepnet
test/UtilSpec.hs
bsd-3-clause
581
0
14
137
148
77
71
19
1
{-# LANGUAGE CPP #-} {- | Module  : Control.Graph.Base Description : Base type class for graph indexed types. Copyright  : (c) Aaron Friel License  : BSD-3 Maintainer  : Aaron Friel <[email protected]> Stability  : unstable Portability : portable -} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeFamilies #-} module Control.Graphted.Class (Graphted (..), Constraint) where #if MIN_VERSION_GLASGOW_HASKELL(8,0,1,0) import Data.Kind (Constraint) #else import GHC.Exts (Constraint) #endif -- | Base class that all Graph-indexed types may implement. -- class Graphted (f :: p -> * -> *) where -- | The unit of our kind p. type Unit f :: p -- | An invariant on combining indexes. type family Inv f (i :: p) (j :: p) :: Constraint type instance Inv f i j = () -- | An elementary composition of indexes. -- -- N.B.: This may be nonsensical if and only if type classes override the -- default definitions of their own type families. -- -- This exists for convenience. type family Combine f (i :: p) (j :: p) :: p
AaronFriel/graphted
src/Control/Graphted/Class.hs
bsd-3-clause
1,143
0
9
274
137
95
42
11
0
module Ivory.Tower.Config.Parser ( ConfigParser() , runConfigParser , string , integer , double , bool , array , subsection , withDefault , (<|>) , (<?>) ) where import Prelude () import Prelude.Compat import qualified Data.Map as M import Text.TOML.Value import Data.Either (lefts, rights) import Data.List (intercalate) newtype ConfigParser a = ConfigParser { unConfigParser :: Value -> Either String a } instance Functor ConfigParser where fmap f c = ConfigParser $ \v -> fmap f (unConfigParser c v) instance Applicative ConfigParser where pure a = ConfigParser (const (pure a)) (ConfigParser f) <*> (ConfigParser a) = ConfigParser (\v -> (f v) <*> (a v)) instance Monad ConfigParser where return = pure (ConfigParser a) >>= f = ConfigParser (\v -> a v >>= \b -> unConfigParser (f b) v) fail e = ConfigParser (const (Left e)) runConfigParser :: ConfigParser a -> Value -> Either String a runConfigParser = unConfigParser configParser :: String -> (Value -> Maybe a) -> ConfigParser a configParser e p = ConfigParser $ \v -> case p v of Just a -> Right a Nothing -> Left ("expected " ++ e ++ ", got " ++ show v) string :: ConfigParser String string = configParser "string" $ \v -> case v of Right (VString a) -> Just a _ -> Nothing integer :: ConfigParser Integer integer = configParser "integer" $ \v -> case v of Right (VInteger a) -> Just a _ -> Nothing double :: ConfigParser Double double = configParser "double" $ \v -> case v of Right (VDouble a) -> Just a -- The Scientific type that attoparsec now uses will parse numbers -- like `1.0` as integers, so we account for that here. This means -- `1` will parse as a double, but this doesn't seem too harmful. Right (VInteger i) -> Just (fromIntegral i) _ -> Nothing bool :: ConfigParser Bool bool = configParser "bool" $ \v -> case v of Right (VBool a) -> Just a _ -> Nothing array :: ConfigParser a -> ConfigParser [a] array p = ConfigParser $ \v -> case v of Right (VArray as) -> let bs = map (\a -> unConfigParser p (Right a)) as in case lefts bs of [] -> Right (rights bs) es -> Left ("got following errors when parsing array elements: " ++ intercalate "; " es) _ -> Left ("expected array, got " ++ show v) subsection :: String -> ConfigParser a -> ConfigParser a subsection key vparser = ConfigParser $ \v -> case v of Left (TOML toml) -> case M.lookup key toml of Just v' -> unConfigParser vparser v' Nothing -> Left ("failed to find subsection named " ++ key ++ " in " ++ show toml) _ -> Left ("expected subsection, got " ++ show v) infixr 1 <|> (<|>) :: ConfigParser a -> ConfigParser a -> ConfigParser a (<|>) a b = ConfigParser $ \v -> case unConfigParser a v of Right r -> Right r Left _ -> unConfigParser b v infix 0 <?> (<?>) :: ConfigParser a -> String -> ConfigParser a (<?>) a lbl = a <|> fail lbl withDefault :: ConfigParser a -> a -> ConfigParser a withDefault a d = a <|> return d
GaloisInc/tower
tower-config/src/Ivory/Tower/Config/Parser.hs
bsd-3-clause
3,138
0
19
809
1,132
576
556
90
3
module Problem71 where main :: IO () main = print . fst . foldl1 (\(n, d) (n', d') -> if n' * d < n * d' -- n / d > n' / d' then (n, d) else (n', d') ) $ [ (floor (fromIntegral (3 * k) / 7.0) - 1, k) | k <- [1 .. 1000000] ]
adityagupta1089/Project-Euler-Haskell
src/problems/Problem71.hs
bsd-3-clause
309
0
14
146
136
78
58
10
2
-- | This module provides Hoca specific commands for the interactive mode. module Tct.Hoca.Interactive ( module M , loadML , listML , parseML ) where import Tct.Core.Interactive as M import Tct.Hoca.Processors as M import Tct.Hoca.Strategies as M import qualified Tct.Core as T import Tct.Hoca.Config (hocaConfig) import Tct.Hoca.Types (ML) loadML :: FilePath -> IO () loadML = load' hocaConfig -- | Parse 'ML strategy. Specialised version of 'parse'. parseML :: T.Declared ML ML => String -> T.Strategy ML ML parseML = parse (T.decls :: [T.StrategyDeclaration ML ML]) -- | List 'ML strategies. Specialised version of 'list'. listML :: T.Declared ML ML => IO () listML = list (T.decls :: [T.StrategyDeclaration ML ML])
ComputationWithBoundedResources/tct-hoca
src/Tct/Hoca/Interactive.hs
bsd-3-clause
812
0
9
204
201
118
83
-1
-1
{-# OPTIONS_GHC -fno-warn-type-defaults #-} module Util.AverageFileSize ( getAverageFileSize , calculateAverageFileSize ) where import Data.List (foldl') import qualified Data.Map.Strict as M import Request (FileID, FileRequest, FileSize, RequestType (..), forEachFileRequestIn) type FileStatistic = M.Map FileID FileSize getAverageFileSize :: String -> IO (Double, Int) getAverageFileSize logPath = calculateAverageFileSize `forEachFileRequestIn` logPath calculateAverageFileSize :: [FileRequest] -> (Double, Int) calculateAverageFileSize requests = let statistic = foldl' fileToStatistic M.empty requests sumOfAllSizes = fromIntegral $ foldl' (+) 0 statistic nrOfDifferentFiles = M.size statistic in (sumOfAllSizes / fromIntegral nrOfDifferentFiles, nrOfDifferentFiles) fileToStatistic :: FileStatistic -> FileRequest -> FileStatistic fileToStatistic statistic (Read, fileId, fileSize) = let combine oldValue _ = oldValue in M.insertWith combine fileId fileSize statistic fileToStatistic statistic _ = statistic
wochinge/CacheSimulator
src/Util/AverageFileSize.hs
bsd-3-clause
1,125
0
10
222
259
145
114
23
1
-------------------------------------------------------------------------------- module Copilot.Kind.CoreUtils.Expr where import Copilot.Core import Data.Monoid import Data.List (concatMap) -------------------------------------------------------------------------------- foldCExpr :: forall m a . (Monoid m) => (forall t . Expr t -> m) -> Expr a -> m foldCExpr f = fld where fld :: forall a . Expr a -> m fld e = f e <> case e of (Local _ _ _ ea eb) -> fld ea <> fld eb (ExternFun _ _ args _ _) -> foldl fldArgs mempty args (ExternArray _ _ _ _ ea _ _) -> fld ea (Op1 _ ea) -> fld ea (Op2 _ ea eb) -> fld ea <> fld eb (Op3 _ ea eb ec) -> fld ea <> fld eb <> fld ec _ -> mempty fldArgs :: m -> UExpr -> m fldArgs m (UExpr {uExprExpr}) = m <> fld uExprExpr -------------------------------------------------------------------------------- foldCSpecExprs :: forall m . (Monoid m) => (forall t . Expr t -> m) -> Spec -> m foldCSpecExprs f spec = mconcat $ map streamExpr (specStreams spec) ++ map observerExpr (specObservers spec) ++ map triggerExpr (specTriggers spec) ++ map propertyExpr (specProperties spec) where streamExpr (Stream {streamExpr}) = foldCExpr f streamExpr observerExpr (Observer {observerExpr}) = foldCExpr f observerExpr triggerExpr (Trigger {triggerGuard}) = foldCExpr f triggerGuard propertyExpr (Property {propertyExpr}) = foldCExpr f propertyExpr -------------------------------------------------------------------------------- addBoundCheckingProps :: Spec -> (Spec, [String]) addBoundCheckingProps spec = ( spec {specProperties = properties} , map propertyName properties ) where properties = foldCSpecExprs checkExpr spec checkExpr (ExternArray tind _ name size ind _ (Just tag)) = let propertyName = "_bounds_" ++ show name ++ "_" ++ show tag ++ "_" propertyExpr = Op2 And (Op2 (Le tind) (Const tind 0) ind) (Op2 (Lt tind) ind (Const tind (fromInteger . toInteger $ size))) in [Property propertyName propertyExpr] checkExpr _ = mempty --------------------------------------------------------------------------------
jonathan-laurent/copilot-kind
src/Copilot/Kind/CoreUtils/Expr.hs
bsd-3-clause
2,412
0
18
667
743
378
365
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LiberalTypeSynonyms #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} -- | Types used throughout the ManagedProcess framework module Control.Distributed.Process.ManagedProcess.Internal.Types ( -- * Exported data types InitResult(..) , GenProcess() , runProcess , lift , liftIO , ProcessState(..) , State , Queue , Limit , Condition(..) , ProcessAction(..) , ProcessReply(..) , Action , Reply , ActionHandler , CallHandler , CastHandler , StatelessHandler , DeferredCallHandler , StatelessCallHandler , InfoHandler , ChannelHandler , StatelessChannelHandler , InitHandler , ShutdownHandler , ExitState(..) , isCleanShutdown , exitState , TimeoutHandler , UnhandledMessagePolicy(..) , ProcessDefinition(..) , Priority(..) , DispatchPriority(..) , DispatchFilter(..) , Filter(..) -- , Check(..) , PrioritisedProcessDefinition(..) , RecvTimeoutPolicy(..) , ControlChannel(..) , newControlChan , ControlPort(..) , channelControlPort , Dispatcher(..) , ExternDispatcher(..) , DeferredDispatcher(..) , ExitSignalDispatcher(..) , MessageMatcher(..) , ExternMatcher(..) , Message(..) , CallResponse(..) , CallId , CallRef(..) , CallRejected(..) , makeRef , caller , rejectToCaller , recipient , tag , initCall , unsafeInitCall , waitResponse ) where import Control.Concurrent.STM (STM) import Control.Distributed.Process hiding (Message, mask, finally, liftIO) import qualified Control.Distributed.Process as P (Message, liftIO) import Control.Distributed.Process.Serializable import Control.Distributed.Process.Extras ( Recipient(..) , ExitReason(..) , Addressable , Resolvable(..) , Routable(..) , NFSerializable ) import Control.Distributed.Process.ManagedProcess.Internal.PriorityQueue ( PriorityQ ) import Control.Distributed.Process.Extras.Internal.Types ( resolveOrDie ) import Control.Distributed.Process.Extras.Time import Control.Distributed.Process.ManagedProcess.Timer (Timer, TimerKey) import Control.DeepSeq (NFData(..)) import Control.Monad.Fix (MonadFix) import Control.Monad.Catch ( catch , throwM , uninterruptibleMask , mask , finally , MonadThrow , MonadCatch , MonadMask(..) ) import qualified Control.Monad.Catch as Catch ( catch , throwM ) import Control.Monad.IO.Class (MonadIO) import qualified Control.Monad.State.Strict as ST ( MonadState , StateT , get , lift , runStateT ) import Data.Binary hiding (decode) import Data.Map.Strict (Map) import Data.Typeable (Typeable) import Data.IORef (IORef) import Prelude hiding (init) import GHC.Generics -------------------------------------------------------------------------------- -- API -- -------------------------------------------------------------------------------- -- | wrapper for a @MonitorRef@ type CallId = MonitorRef -- | Wraps a consumer of the call API newtype CallRef a = CallRef { unCaller :: (Recipient, CallId) } deriving (Eq, Show, Typeable, Generic) -- | Retrieve the @Recipient@ for a @CallRef@. recipient :: CallRef a -> Recipient recipient = fst . unCaller -- | Retrieve the @CallId@ for a @CallRef@. tag :: CallRef a -> CallId tag = snd . unCaller instance Binary (CallRef a) where instance NFData (CallRef a) where rnf (CallRef x) = rnf x `seq` () -- | Creates a @CallRef@ for the given @Recipient@ and @CallId@ makeRef :: Recipient -> CallId -> CallRef a makeRef r c = CallRef (r, c) -- | @Message@ type used internally by the call, cast, and rpcChan APIs. data Message a b = CastMessage a | CallMessage a (CallRef b) | ChanMessage a (SendPort b) deriving (Typeable, Generic) -- | Retrieve the @Recipient@ from a @Message@. If the supplied message is -- a /cast/ or /chan/ message will evaluate to @Nothing@, otherwise @Just ref@. caller :: forall a b . Message a b -> Maybe Recipient caller (CallMessage _ ref) = Just $ recipient ref caller _ = Nothing -- | Reject a /call/ message with the supplied string. Sends @CallRejected@ to -- the recipient if the input is a @CallMessage@, otherwise has no side effects. rejectToCaller :: forall a b . Message a b -> String -> Process () rejectToCaller (CallMessage _ ref) m = sendTo ref (CallRejected m (tag ref)) rejectToCaller _ _ = return () instance (Serializable a, Serializable b) => Binary (Message a b) where instance (NFSerializable a, NFSerializable b) => NFData (Message a b) where rnf (CastMessage a) = rnf a `seq` () rnf (CallMessage a b) = rnf a `seq` rnf b `seq` () rnf (ChanMessage a b) = rnf a `seq` rnf b `seq` () deriving instance (Eq a, Eq b) => Eq (Message a b) deriving instance (Show a, Show b) => Show (Message a b) -- | Response type for the call API data CallResponse a = CallResponse a CallId deriving (Typeable, Generic) instance Serializable a => Binary (CallResponse a) instance NFSerializable a => NFData (CallResponse a) where rnf (CallResponse a c) = rnf a `seq` rnf c `seq` () deriving instance Eq a => Eq (CallResponse a) deriving instance Show a => Show (CallResponse a) -- | Sent to a consumer of the /call/ API when a server filter expression -- explicitly rejects an incoming call message. data CallRejected = CallRejected String CallId deriving (Typeable, Generic, Show, Eq) instance Binary CallRejected where instance NFData CallRejected where instance Resolvable (CallRef a) where resolve (CallRef (r, _)) = resolve r instance Routable (CallRef a) where sendTo (CallRef (c, _)) = sendTo c unsafeSendTo (CallRef (c, _)) = unsafeSendTo c -- | Return type for and 'InitHandler' expression. data InitResult s = InitOk s Delay {- ^ a successful initialisation, initial state and timeout -} | InitStop String {- ^ failed initialisation and the reason, this will result in an error -} | InitIgnore {- ^ the process has decided not to continue starting - this is not an error -} deriving (Typeable) -- | Represent a max-backlog from RecvTimeoutPolicy type Limit = Maybe Int -- | Internal priority queue, used by prioritised processes. type Queue = PriorityQ Int P.Message -- | Map from @TimerKey@ to @(Timer, Message)@. type TimerMap = Map TimerKey (Timer, P.Message) -- | Internal state of a prioritised process loop. data ProcessState s = ProcessState { timeoutSpec :: RecvTimeoutPolicy , procDef :: ProcessDefinition s , procPrio :: [DispatchPriority s] , procFilters :: [DispatchFilter s] , usrTimeout :: Delay , sysTimeout :: Timer , usrTimers :: TimerMap , internalQ :: Queue , procState :: s } -- | Prioritised process state, held as an @IORef@. type State s = IORef (ProcessState s) -- | StateT based monad for prioritised process loops. newtype GenProcess s a = GenProcess { unManaged :: ST.StateT (State s) Process a } deriving ( Functor , Monad , ST.MonadState (State s) , MonadIO , MonadFix , Typeable , Applicative ) instance forall s . MonadThrow (GenProcess s) where throwM = lift . Catch.throwM instance forall s . MonadCatch (GenProcess s) where catch p h = do pSt <- ST.get -- we can throw away our state since it is always accessed via an IORef (a, _) <- lift $ Catch.catch (runProcess pSt p) (runProcess pSt . h) return a instance forall s . MonadMask (GenProcess s) where mask p = do pSt <- ST.get lift $ mask $ \restore -> do (a, _) <- runProcess pSt (p (liftRestore restore)) return a where liftRestore restoreP = \p2 -> do ourSTate <- ST.get (a', _) <- lift $ restoreP $ runProcess ourSTate p2 return a' uninterruptibleMask p = do pSt <- ST.get (a, _) <- lift $ uninterruptibleMask $ \restore -> runProcess pSt (p (liftRestore restore)) return a where liftRestore restoreP = \p2 -> do ourSTate <- ST.get (a', _) <- lift $ restoreP $ runProcess ourSTate p2 return a' #if MIN_VERSION_exceptions(0,10,0) generalBracket acquire release inner = GenProcess $ generalBracket (unManaged acquire) (\a e -> unManaged $ release a e) (unManaged . inner) #endif -- | Run an action in the @GenProcess@ monad. runProcess :: State s -> GenProcess s a -> Process (a, State s) runProcess state proc = ST.runStateT (unManaged proc) state -- | Lift an action in the @Process@ monad to @GenProcess@. lift :: Process a -> GenProcess s a lift p = GenProcess $ ST.lift p -- | Lift an IO action directly into @GenProcess@, @liftIO = lift . Process.LiftIO@. liftIO :: IO a -> GenProcess s a liftIO = lift . P.liftIO -- | The action taken by a process after a handler has run and its updated state. -- See "Control.Distributed.Process.ManagedProcess.Server.continue" -- "Control.Distributed.Process.ManagedProcess.Server.timeoutAfter" -- "Control.Distributed.Process.ManagedProcess.Server.hibernate" -- "Control.Distributed.Process.ManagedProcess.Server.stop" -- "Control.Distributed.Process.ManagedProcess.Server.stopWith" -- -- Also see "Control.Distributed.Process.Management.Priority.act" and -- "Control.Distributed.Process.ManagedProcess.Priority.runAfter". -- -- And other actions. This type should not be used directly. data ProcessAction s = ProcessSkip | ProcessActivity (GenProcess s ()) -- ^ run the given activity | ProcessExpression (GenProcess s (ProcessAction s)) -- ^ evaluate an expression | ProcessContinue s -- ^ continue with (possibly new) state | ProcessTimeout Delay s -- ^ timeout if no messages are received | ProcessHibernate TimeInterval s -- ^ hibernate for /delay/ | ProcessStop ExitReason -- ^ stop the process, giving @ExitReason@ | ProcessStopping s ExitReason -- ^ stop the process with @ExitReason@, with updated state | ProcessBecome (ProcessDefinition s) s -- ^ changes the current process definition -- | Returned from handlers for the synchronous 'call' protocol, encapsulates -- the reply data /and/ the action to take after sending the reply. A handler -- can return @NoReply@ if they wish to ignore the call. data ProcessReply r s = ProcessReply r (ProcessAction s) | ProcessReject String (ProcessAction s) -- TODO: can we use a functional dependency here? | NoReply (ProcessAction s) -- | Wraps a predicate that is used to determine whether or not a handler -- is valid based on some combination of the current process state, the -- type and/or value of the input message or both. data Condition s m = Condition (s -> m -> Bool) -- ^ predicated on the process state /and/ the message | State (s -> Bool) -- ^ predicated on the process state only | Input (m -> Bool) -- ^ predicated on the input message only {- class Check c s m | s m -> c where -- data Checker c :: * -> * -> * -- apply :: s -> m -> Checker c s m -> Bool apply :: s -> m -> c -> Bool instance Check (Condition s m) s m where -- data Checker (Condition s m) s m = CheckCond (Condition s m) apply s m (Condition f) = f s m apply s _ (State f) = f s apply _ m (Input f) = f m instance Check (s -> m -> Bool) s m where -- data Checker (s -> m -> Bool) s m = CheckF (s -> m -> Bool) apply s m f = f s m -} -- | Informs a /shutdown handler/ of whether it is running due to a clean -- shutdown, or in response to an unhandled exception. data ExitState s = CleanShutdown s -- ^ given when an ordered shutdown is underway | LastKnown s {- ^ given due to an unhandled exception, passing the last known state -} -- | @True@ if the @ExitState@ is @CleanShutdown@, otherwise @False@. isCleanShutdown :: ExitState s -> Bool isCleanShutdown (CleanShutdown _) = True isCleanShutdown _ = False -- | Evaluates to the @s@ state datum in the given @ExitState@. exitState :: ExitState s -> s exitState (CleanShutdown s) = s exitState (LastKnown s) = s -- | An action (server state transition) in the @Process@ monad type Action s = Process (ProcessAction s) -- | An action (server state transition) causing a reply to a caller, in the -- @Process@ monad type Reply b s = Process (ProcessReply b s) -- | An expression used to handle a message type ActionHandler s a = s -> a -> Action s -- | An expression used to handle a message and providing a reply type CallHandler s a b = s -> a -> Reply b s -- | An expression used to ignore server state during handling type StatelessHandler s a = a -> (s -> Action s) -- | An expression used to handle a /call/ message where the reply is deferred -- via the 'CallRef' type DeferredCallHandler s a b = CallRef b -> CallHandler s a b -- | An expression used to handle a /call/ message ignoring server state type StatelessCallHandler s a b = CallRef b -> a -> Reply b s -- | An expression used to handle a /cast/ message type CastHandler s a = ActionHandler s a -- | An expression used to handle an /info/ message type InfoHandler s a = ActionHandler s a -- | An expression used to handle a /channel/ message type ChannelHandler s a b = SendPort b -> ActionHandler s a -- | An expression used to handle a /channel/ message in a stateless process type StatelessChannelHandler s a b = SendPort b -> StatelessHandler s a -- | An expression used to initialise a process with its state type InitHandler a s = a -> Process (InitResult s) -- | An expression used to handle process termination type ShutdownHandler s = ExitState s -> ExitReason -> Process () -- | An expression used to handle process timeouts type TimeoutHandler s = ActionHandler s Delay -- dispatching to implementation callbacks -- | Provides a means for servers to listen on a separate, typed /control/ -- channel, thereby segregating the channel from their regular -- (and potentially busy) mailbox. newtype ControlChannel m = ControlChannel { unControl :: (SendPort (Message m ()), ReceivePort (Message m ())) } -- | Creates a new 'ControlChannel'. newControlChan :: (Serializable m) => Process (ControlChannel m) newControlChan = fmap ControlChannel newChan -- | The writable end of a 'ControlChannel'. -- newtype ControlPort m = ControlPort { unPort :: SendPort (Message m ()) } deriving (Show) deriving instance (Serializable m) => Binary (ControlPort m) instance Eq (ControlPort m) where a == b = unPort a == unPort b -- | Obtain an opaque expression for communicating with a 'ControlChannel'. -- channelControlPort :: ControlChannel m -> ControlPort m channelControlPort cc = ControlPort $ fst $ unControl cc -- | Given as the result of evaluating a "DispatchFilter". This type is intended -- for internal use. For an API for working with filters, -- see "Control.Distributed.Process.ManagedProcess.Priority". data Filter s = FilterOk s | FilterSafe s | forall m . (Show m) => FilterReject m s | FilterSkip s | FilterStop s ExitReason -- | Provides dispatch from a variety of inputs to a typed filter handler. data DispatchFilter s = forall a b . (Serializable a, Serializable b) => FilterApi { apiFilter :: s -> Message a b -> Process (Filter s) } | forall a . (Serializable a) => FilterAny { anyFilter :: s -> a -> Process (Filter s) } | FilterRaw { rawFilter :: s -> P.Message -> Process (Maybe (Filter s)) } | FilterState { stateFilter :: s -> Process (Maybe (Filter s)) } -- | Provides dispatch from cast and call messages to a typed handler. data Dispatcher s = forall a b . (Serializable a, Serializable b) => Dispatch { dispatch :: s -> Message a b -> Process (ProcessAction s) } | forall a b . (Serializable a, Serializable b) => DispatchIf { dispatch :: s -> Message a b -> Process (ProcessAction s) , dispatchIf :: s -> Message a b -> Bool } -- | Provides dispatch for channels and STM actions data ExternDispatcher s = forall a b . (Serializable a, Serializable b) => DispatchCC -- control channel dispatch { channel :: ReceivePort (Message a b) , dispatchChan :: s -> Message a b -> Process (ProcessAction s) } | forall a . (Serializable a) => DispatchSTM -- arbitrary STM actions { stmAction :: STM a , dispatchStm :: s -> a -> Process (ProcessAction s) , matchStm :: Match P.Message , matchAnyStm :: forall m . (P.Message -> m) -> Match m } -- | Provides dispatch for any input, returns 'Nothing' for unhandled messages. data DeferredDispatcher s = DeferredDispatcher { dispatchInfo :: s -> P.Message -> Process (Maybe (ProcessAction s)) } -- | Provides dispatch for any exit signal - returns 'Nothing' for unhandled exceptions data ExitSignalDispatcher s = ExitSignalDispatcher { dispatchExit :: s -> ProcessId -> P.Message -> Process (Maybe (ProcessAction s)) } -- | Defines the means of dispatching inbound messages to a handler class MessageMatcher d where matchDispatch :: UnhandledMessagePolicy -> s -> d s -> Match (ProcessAction s) instance MessageMatcher Dispatcher where matchDispatch _ s (Dispatch d) = match (d s) matchDispatch _ s (DispatchIf d cond) = matchIf (cond s) (d s) instance MessageMatcher ExternDispatcher where matchDispatch _ s (DispatchCC c d) = matchChan c (d s) matchDispatch _ s (DispatchSTM c d _ _) = matchSTM c (d s) -- | Defines the means of dispatching messages from external channels (e.g. -- those defined in terms of "ControlChannel", and STM actions) to a handler. class ExternMatcher d where matchExtern :: UnhandledMessagePolicy -> s -> d s -> Match P.Message matchMapExtern :: forall m s . UnhandledMessagePolicy -> s -> (P.Message -> m) -> d s -> Match m instance ExternMatcher ExternDispatcher where matchExtern _ _ (DispatchCC c _) = matchChan c (return . unsafeWrapMessage) matchExtern _ _ (DispatchSTM _ _ m _) = m matchMapExtern _ _ f (DispatchCC c _) = matchChan c (return . f . unsafeWrapMessage) matchMapExtern _ _ f (DispatchSTM _ _ _ p) = p f -- | Priority of a message, encoded as an @Int@ newtype Priority a = Priority { getPrio :: Int } -- | Dispatcher for prioritised handlers data DispatchPriority s = PrioritiseCall { prioritise :: s -> P.Message -> Process (Maybe (Int, P.Message)) } | PrioritiseCast { prioritise :: s -> P.Message -> Process (Maybe (Int, P.Message)) } | PrioritiseInfo { prioritise :: s -> P.Message -> Process (Maybe (Int, P.Message)) } -- | For a 'PrioritisedProcessDefinition', this policy determines for how long -- the /receive loop/ should continue draining the process' mailbox before -- processing its received mail (in priority order). -- -- If a prioritised /managed process/ is receiving a lot of messages (into its -- /real/ mailbox), the server might never get around to actually processing its -- inputs. This (mandatory) policy provides a guarantee that eventually (i.e., -- after a specified number of received messages or time interval), the server -- will stop removing messages from its mailbox and process those it has already -- received. -- data RecvTimeoutPolicy = RecvMaxBacklog Int | RecvTimer TimeInterval deriving (Typeable) -- | A @ProcessDefinition@ decorated with @DispatchPriority@ for certain -- input domains. data PrioritisedProcessDefinition s = PrioritisedProcessDefinition { processDef :: ProcessDefinition s , priorities :: [DispatchPriority s] , filters :: [DispatchFilter s] , recvTimeout :: RecvTimeoutPolicy } -- | Policy for handling unexpected messages, i.e., messages which are not -- sent using the 'call' or 'cast' APIs, and which are not handled by any of the -- 'handleInfo' handlers. data UnhandledMessagePolicy = Terminate -- ^ stop immediately, giving @ExitOther "UnhandledInput"@ as the reason | DeadLetter ProcessId -- ^ forward the message to the given recipient | Log -- ^ log messages, then behave identically to @Drop@ | Drop -- ^ dequeue and then drop/ignore the message deriving (Show, Eq) -- | Stores the functions that determine runtime behaviour in response to -- incoming messages and a policy for responding to unhandled messages. data ProcessDefinition s = ProcessDefinition { apiHandlers :: [Dispatcher s] -- ^ functions that handle call/cast messages , infoHandlers :: [DeferredDispatcher s] -- ^ functions that handle non call/cast messages , externHandlers :: [ExternDispatcher s] -- ^ functions that handle control channel and STM inputs , exitHandlers :: [ExitSignalDispatcher s] -- ^ functions that handle exit signals , timeoutHandler :: TimeoutHandler s -- ^ a function that handles timeouts , shutdownHandler :: ShutdownHandler s -- ^ a function that is run just before the process exits , unhandledMessagePolicy :: UnhandledMessagePolicy -- ^ how to deal with unhandled messages } -- note [rpc calls] -- One problem with using plain expect/receive primitives to perform a -- synchronous (round trip) call is that a reply matching the expected type -- could come from anywhere! The Call.hs module uses a unique integer tag to -- distinguish between inputs but this is easy to forge, and forces all callers -- to maintain a tag pool, which is quite onerous. -- -- Here, we use a private (internal) tag based on a 'MonitorRef', which is -- guaranteed to be unique per calling process (in the absence of mallicious -- peers). This is handled throughout the roundtrip, such that the reply will -- either contain the CallId (i.e., the ame 'MonitorRef' with which we're -- tracking the server process) or we'll see the server die. -- -- Of course, the downside to all this is that the monitoring and receiving -- clutters up your mailbox, and if your mailbox is extremely full, could -- incur delays in delivery. The callAsync function provides a neat -- work-around for that, relying on the insulation provided by Async. -- TODO: Generify this /call/ API and use it in Call.hs to avoid tagging -- TODO: the code below should be moved elsewhere. Maybe to Client.hs? -- | The send part of the /call/ client-server interaction. The resulting -- "CallRef" can be used to identify the corrolary response message (if one is -- sent by the server), and is unique to this /call-reply/ pair. initCall :: forall s a b . (Addressable s, Serializable a, Serializable b) => s -> a -> Process (CallRef b) initCall sid msg = do pid <- resolveOrDie sid "initCall: unresolveable address " mRef <- monitor pid self <- getSelfPid let cRef = makeRef (Pid self) mRef in do sendTo pid (CallMessage msg cRef :: Message a b) return cRef -- | Version of @initCall@ that utilises "unsafeSendTo". unsafeInitCall :: forall s a b . ( Addressable s , NFSerializable a , NFSerializable b ) => s -> a -> Process (CallRef b) unsafeInitCall sid msg = do pid <- resolveOrDie sid "unsafeInitCall: unresolveable address " mRef <- monitor pid self <- getSelfPid let cRef = makeRef (Pid self) mRef in do unsafeSendTo pid (CallMessage msg cRef :: Message a b) return cRef -- | Wait on the server's response after an "initCall" has been previously been sent. -- -- This function does /not/ trap asynchronous exceptions. waitResponse :: forall b. (Serializable b) => Maybe TimeInterval -> CallRef b -> Process (Maybe (Either ExitReason b)) waitResponse mTimeout cRef = let (_, mRef) = unCaller cRef matchers = [ matchIf (\((CallResponse _ ref) :: CallResponse b) -> ref == mRef) (\((CallResponse m _) :: CallResponse b) -> return (Right m)) , matchIf (\((CallRejected _ ref)) -> ref == mRef) (\(CallRejected s _) -> return (Left $ ExitOther $ s)) , matchIf (\(ProcessMonitorNotification ref _ _) -> ref == mRef) (\(ProcessMonitorNotification _ _ r) -> return (Left (err r))) ] err r = ExitOther $ show r in case mTimeout of (Just ti) -> finally (receiveTimeout (asTimeout ti) matchers) (unmonitor mRef) Nothing -> finally (fmap Just (receiveWait matchers)) (unmonitor mRef)
haskell-distributed/distributed-process-client-server
src/Control/Distributed/Process/ManagedProcess/Internal/Types.hs
bsd-3-clause
25,548
0
17
6,127
5,156
2,896
2,260
412
2
module Signal.Wavelet.List1 where import Signal.Wavelet.List.Common dwt :: [Double] -> [Double] -> [Double] dwt angles signal = dwtWorker latticeSeq csl angles signal idwt :: [Double] -> [Double] -> [Double] idwt angles signal = dwtWorker latticeSeq csr angles signal
jstolarek/lattice-structure-hs
src/Signal/Wavelet/List1.hs
bsd-3-clause
274
0
7
43
96
54
42
6
1
{-# LANGUAGE CPP #-} module Main where import TestsCommon import GalFld.Core import GalFld.Sandbox.FFSandbox (e2f2,e2e2f2,e4f2) import GalFld.Sandbox.PolySandbox -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- subroutineAdd list = do it "test * (x+0=x)" $ pMapM_ (\ x -> x + pKonst 0 `shouldBe` x) list it "test * (x-x=0)" $ pMapM_ (\ x -> x - x `shouldBe` pKonst 0) list -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- subroutineMult list = do it "test * (x*1=x)" $ pMapM_ (\ x -> x * pKonst 1 `shouldBe` x) list it "xy=yx" $ pMapM_ (\ (x,y) -> x * y == y * x `shouldBe` True) $ zip (take testSize list) (drop testSize list) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- subroutineDiv list = do it "test divP (x/x=1)" $ pMapM_ (\ x -> divPInv x x `shouldBe` (pKonst 1, nullP)) list it "test divP generally" $ pMapM_ (\ (x,y) -> unDivP (divPInv x y) x y `shouldBe` True) $ zip (take testSize list) (drop testSize list) #if 0 it "test divPHorner <-> divPInv" $ pMapM_ (\ (x,y) -> divPInv x y `shouldBe` divP x y) $ zip (take testSize list) (drop testSize list) #endif it "x/0 throws exception" $ pMapM_ (\x -> evaluate (divP x nullP) `shouldThrow` anyException) list it "test eekP" $ pMapM_ (\ (x, y) -> unEekP (eekP x y) x y `shouldBe` True) $ zip (take testSize list) (drop testSize list) where unDivP (q,r) a b = a == q * b + r unEekP (d,s,t) a b = d == s*a + t*b -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- subroutine list = do subroutineAdd list subroutineMult list subroutineDiv list -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- testSize = 3 main :: IO () main = do list <- rndSelect (getAllP (elems undefined ::[F5]) 10) (2*testSize) vList <- rndSelect (getAllP (elems e2f2) 10) (2*testSize) wList <- rndSelect (getAllP (elems e4f2) 10) (2*testSize) hspec $ do describe "GalFld.Core.Polynomials Basic" $ it "P[1] == P[1,0]" $ pList [1] `shouldBe` pList[1,0] describe "GalFld.Core.Polynomials @F5 (subset)" $ subroutine list describe "GalFld.Core.Polynomials @e2f2 (full)" $ subroutine (getAllP (elems e2f2) 4) --describe "GalFld.Core.Polynomials @e2e2f2" $ subroutine vList describe "GalFld.Core.Polynomials @e2f2 (subset)" $ subroutine vList {-describe "GalFld.Core.Polynomials @e4f2 (subset)" $-} {-subroutine wList-}
maximilianhuber/softwareProjekt
test/PolyTests.hs
bsd-3-clause
3,019
0
15
555
868
445
423
50
1