code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE 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.Gmail.Users.Settings.SendAs.Get
-- 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)
--
-- Gets the specified send-as alias. Fails with an HTTP 404 error if the
-- specified address is not a member of the collection.
--
-- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.settings.sendAs.get@.
module Network.Google.Resource.Gmail.Users.Settings.SendAs.Get
(
-- * REST Resource
UsersSettingsSendAsGetResource
-- * Creating a Request
, usersSettingsSendAsGet
, UsersSettingsSendAsGet
-- * Request Lenses
, ussagUserId
, ussagSendAsEmail
) where
import Network.Google.Gmail.Types
import Network.Google.Prelude
-- | A resource alias for @gmail.users.settings.sendAs.get@ method which the
-- 'UsersSettingsSendAsGet' request conforms to.
type UsersSettingsSendAsGetResource =
"gmail" :>
"v1" :>
"users" :>
Capture "userId" Text :>
"settings" :>
"sendAs" :>
Capture "sendAsEmail" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] SendAs
-- | Gets the specified send-as alias. Fails with an HTTP 404 error if the
-- specified address is not a member of the collection.
--
-- /See:/ 'usersSettingsSendAsGet' smart constructor.
data UsersSettingsSendAsGet = UsersSettingsSendAsGet'
{ _ussagUserId :: !Text
, _ussagSendAsEmail :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'UsersSettingsSendAsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ussagUserId'
--
-- * 'ussagSendAsEmail'
usersSettingsSendAsGet
:: Text -- ^ 'ussagSendAsEmail'
-> UsersSettingsSendAsGet
usersSettingsSendAsGet pUssagSendAsEmail_ =
UsersSettingsSendAsGet'
{ _ussagUserId = "me"
, _ussagSendAsEmail = pUssagSendAsEmail_
}
-- | User\'s email address. The special value \"me\" can be used to indicate
-- the authenticated user.
ussagUserId :: Lens' UsersSettingsSendAsGet Text
ussagUserId
= lens _ussagUserId (\ s a -> s{_ussagUserId = a})
-- | The send-as alias to be retrieved.
ussagSendAsEmail :: Lens' UsersSettingsSendAsGet Text
ussagSendAsEmail
= lens _ussagSendAsEmail
(\ s a -> s{_ussagSendAsEmail = a})
instance GoogleRequest UsersSettingsSendAsGet where
type Rs UsersSettingsSendAsGet = SendAs
type Scopes UsersSettingsSendAsGet =
'["https://mail.google.com/",
"https://www.googleapis.com/auth/gmail.modify",
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/gmail.settings.basic"]
requestClient UsersSettingsSendAsGet'{..}
= go _ussagUserId _ussagSendAsEmail (Just AltJSON)
gmailService
where go
= buildClient
(Proxy :: Proxy UsersSettingsSendAsGetResource)
mempty
|
rueshyna/gogol
|
gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Settings/SendAs/Get.hs
|
mpl-2.0
| 3,713 | 0 | 15 | 842 | 392 | 238 | 154 | 66 | 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.Vault.Matters.Exports.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)
--
-- Lists details about the exports in the specified matter.
--
-- /See:/ <https://developers.google.com/vault G Suite Vault API Reference> for @vault.matters.exports.list@.
module Network.Google.Resource.Vault.Matters.Exports.List
(
-- * REST Resource
MattersExportsListResource
-- * Creating a Request
, mattersExportsList
, MattersExportsList
-- * Request Lenses
, melXgafv
, melUploadProtocol
, melAccessToken
, melUploadType
, melMatterId
, melPageToken
, melPageSize
, melCallback
) where
import Network.Google.Prelude
import Network.Google.Vault.Types
-- | A resource alias for @vault.matters.exports.list@ method which the
-- 'MattersExportsList' request conforms to.
type MattersExportsListResource =
"v1" :>
"matters" :>
Capture "matterId" Text :>
"exports" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListExportsResponse
-- | Lists details about the exports in the specified matter.
--
-- /See:/ 'mattersExportsList' smart constructor.
data MattersExportsList =
MattersExportsList'
{ _melXgafv :: !(Maybe Xgafv)
, _melUploadProtocol :: !(Maybe Text)
, _melAccessToken :: !(Maybe Text)
, _melUploadType :: !(Maybe Text)
, _melMatterId :: !Text
, _melPageToken :: !(Maybe Text)
, _melPageSize :: !(Maybe (Textual Int32))
, _melCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'MattersExportsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'melXgafv'
--
-- * 'melUploadProtocol'
--
-- * 'melAccessToken'
--
-- * 'melUploadType'
--
-- * 'melMatterId'
--
-- * 'melPageToken'
--
-- * 'melPageSize'
--
-- * 'melCallback'
mattersExportsList
:: Text -- ^ 'melMatterId'
-> MattersExportsList
mattersExportsList pMelMatterId_ =
MattersExportsList'
{ _melXgafv = Nothing
, _melUploadProtocol = Nothing
, _melAccessToken = Nothing
, _melUploadType = Nothing
, _melMatterId = pMelMatterId_
, _melPageToken = Nothing
, _melPageSize = Nothing
, _melCallback = Nothing
}
-- | V1 error format.
melXgafv :: Lens' MattersExportsList (Maybe Xgafv)
melXgafv = lens _melXgafv (\ s a -> s{_melXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
melUploadProtocol :: Lens' MattersExportsList (Maybe Text)
melUploadProtocol
= lens _melUploadProtocol
(\ s a -> s{_melUploadProtocol = a})
-- | OAuth access token.
melAccessToken :: Lens' MattersExportsList (Maybe Text)
melAccessToken
= lens _melAccessToken
(\ s a -> s{_melAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
melUploadType :: Lens' MattersExportsList (Maybe Text)
melUploadType
= lens _melUploadType
(\ s a -> s{_melUploadType = a})
-- | The matter ID.
melMatterId :: Lens' MattersExportsList Text
melMatterId
= lens _melMatterId (\ s a -> s{_melMatterId = a})
-- | The pagination token as returned in the response.
melPageToken :: Lens' MattersExportsList (Maybe Text)
melPageToken
= lens _melPageToken (\ s a -> s{_melPageToken = a})
-- | The number of exports to return in the response.
melPageSize :: Lens' MattersExportsList (Maybe Int32)
melPageSize
= lens _melPageSize (\ s a -> s{_melPageSize = a}) .
mapping _Coerce
-- | JSONP
melCallback :: Lens' MattersExportsList (Maybe Text)
melCallback
= lens _melCallback (\ s a -> s{_melCallback = a})
instance GoogleRequest MattersExportsList where
type Rs MattersExportsList = ListExportsResponse
type Scopes MattersExportsList =
'["https://www.googleapis.com/auth/ediscovery",
"https://www.googleapis.com/auth/ediscovery.readonly"]
requestClient MattersExportsList'{..}
= go _melMatterId _melXgafv _melUploadProtocol
_melAccessToken
_melUploadType
_melPageToken
_melPageSize
_melCallback
(Just AltJSON)
vaultService
where go
= buildClient
(Proxy :: Proxy MattersExportsListResource)
mempty
|
brendanhay/gogol
|
gogol-vault/gen/Network/Google/Resource/Vault/Matters/Exports/List.hs
|
mpl-2.0
| 5,456 | 0 | 19 | 1,339 | 885 | 511 | 374 | 126 | 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.ServiceManagement.Services.Disable
-- 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)
--
-- Disables a service for a project, so it can no longer be be used for the
-- project. It prevents accidental usage that may cause unexpected billing
-- charges or security leaks. Operation
--
-- /See:/ <https://cloud.google.com/service-management/ Service Management API Reference> for @servicemanagement.services.disable@.
module Network.Google.Resource.ServiceManagement.Services.Disable
(
-- * REST Resource
ServicesDisableResource
-- * Creating a Request
, servicesDisable
, ServicesDisable
-- * Request Lenses
, sXgafv
, sUploadProtocol
, sAccessToken
, sUploadType
, sPayload
, sServiceName
, sCallback
) where
import Network.Google.Prelude
import Network.Google.ServiceManagement.Types
-- | A resource alias for @servicemanagement.services.disable@ method which the
-- 'ServicesDisable' request conforms to.
type ServicesDisableResource =
"v1" :>
"services" :>
CaptureMode "serviceName" "disable" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] DisableServiceRequest :>
Post '[JSON] Operation
-- | Disables a service for a project, so it can no longer be be used for the
-- project. It prevents accidental usage that may cause unexpected billing
-- charges or security leaks. Operation
--
-- /See:/ 'servicesDisable' smart constructor.
data ServicesDisable =
ServicesDisable'
{ _sXgafv :: !(Maybe Xgafv)
, _sUploadProtocol :: !(Maybe Text)
, _sAccessToken :: !(Maybe Text)
, _sUploadType :: !(Maybe Text)
, _sPayload :: !DisableServiceRequest
, _sServiceName :: !Text
, _sCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ServicesDisable' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sXgafv'
--
-- * 'sUploadProtocol'
--
-- * 'sAccessToken'
--
-- * 'sUploadType'
--
-- * 'sPayload'
--
-- * 'sServiceName'
--
-- * 'sCallback'
servicesDisable
:: DisableServiceRequest -- ^ 'sPayload'
-> Text -- ^ 'sServiceName'
-> ServicesDisable
servicesDisable pSPayload_ pSServiceName_ =
ServicesDisable'
{ _sXgafv = Nothing
, _sUploadProtocol = Nothing
, _sAccessToken = Nothing
, _sUploadType = Nothing
, _sPayload = pSPayload_
, _sServiceName = pSServiceName_
, _sCallback = Nothing
}
-- | V1 error format.
sXgafv :: Lens' ServicesDisable (Maybe Xgafv)
sXgafv = lens _sXgafv (\ s a -> s{_sXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
sUploadProtocol :: Lens' ServicesDisable (Maybe Text)
sUploadProtocol
= lens _sUploadProtocol
(\ s a -> s{_sUploadProtocol = a})
-- | OAuth access token.
sAccessToken :: Lens' ServicesDisable (Maybe Text)
sAccessToken
= lens _sAccessToken (\ s a -> s{_sAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
sUploadType :: Lens' ServicesDisable (Maybe Text)
sUploadType
= lens _sUploadType (\ s a -> s{_sUploadType = a})
-- | Multipart request metadata.
sPayload :: Lens' ServicesDisable DisableServiceRequest
sPayload = lens _sPayload (\ s a -> s{_sPayload = a})
-- | Name of the service to disable. Specifying an unknown service name will
-- cause the request to fail.
sServiceName :: Lens' ServicesDisable Text
sServiceName
= lens _sServiceName (\ s a -> s{_sServiceName = a})
-- | JSONP
sCallback :: Lens' ServicesDisable (Maybe Text)
sCallback
= lens _sCallback (\ s a -> s{_sCallback = a})
instance GoogleRequest ServicesDisable where
type Rs ServicesDisable = Operation
type Scopes ServicesDisable =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/service.management"]
requestClient ServicesDisable'{..}
= go _sServiceName _sXgafv _sUploadProtocol
_sAccessToken
_sUploadType
_sCallback
(Just AltJSON)
_sPayload
serviceManagementService
where go
= buildClient
(Proxy :: Proxy ServicesDisableResource)
mempty
|
brendanhay/gogol
|
gogol-servicemanagement/gen/Network/Google/Resource/ServiceManagement/Services/Disable.hs
|
mpl-2.0
| 5,340 | 0 | 17 | 1,297 | 788 | 461 | 327 | 112 | 1 |
module TranspilerTest where
import Transpiler (transpile)
import Test.Hspec
s =>> c = transpile s `shouldBe` Left c
gg s = transpile s `shouldBe` Right "Hugh?"
main :: IO ()
main = hspec $ do
describe "When there's no lambda" $ do
it "Should work when expressions are very simple" $ do
"call()" =>> "call()"
"callFunc(a)" =>> "callFunc(a)"
"callFunc(123)" =>> "callFunc(123)"
"func(jjfly)" =>> "func(jjfly)"
it "Should not parse wtf" $ do
gg "%^&*("
gg "x9x92xb29xub29bx120()!("
it "Should work when there're lots of spaces" $ do
"invoke ( a , b )" =>> "invoke(a,b)"
"gg ( a ) " =>> "gg(a)"
"shit ( ) " =>> "shit()"
it "Should work when there're multiple parameters" $ do
"invoke(a, b)" =>> "invoke(a,b)"
"invoke(a, 1, b, 2)" =>> "invoke(a,1,b,2)"
"invoke(a, 1,b, 2)" =>> "invoke(a,1,b,2)"
"i(123,abc,bsa,xsa)" =>> "i(123,abc,bsa,xsa)"
gg "f(a,)"
gg "f("
gg ")"
gg "f (,a)"
describe "When there're lambda expressions" $ do
it "Should work for simple tests" $ do
"call({})" =>> "call((){})"
"invoke({},{})" =>> "invoke((){},(){})"
"invoke({},{},{},{},{},{},{},{},{},{})" =>> "invoke((){},(){},(){},(){},(){},(){},(){},(){},(){},(){})"
gg "i(,{})"
it "Should work for lambdas with single paramter" $ do
"f({a->})" =>> "f((a){})"
"f({_->})" =>> "f((_){})"
"f({assWeCan->})" =>> "f((assWeCan){})"
gg "f({a->)"
gg "f(a->})"
gg "f({1a->a})"
it "Should work when lambda has an expression inside" $ do
"f({a->a})" =>> "f((a){a;})"
"f({jj->assWeCan})" =>> "f((jj){assWeCan;})"
gg "f(->)"
describe "When lambda expressions aren't inside brackets" $ do
it "Should work for empty lambdas" $ do
"call(\n){}" =>> "call((){})"
"call{}" =>> "call((){})"
"inv( a) { }" =>> "inv(a,(){})"
"invo(123, abc ) { } " =>> "invo(123,abc,(){})"
it "Should work when there're lots of spaces" $ do
"invoke ( a , b ) { } " =>> "invoke(a,b,(){})"
"gg ( a ) { } " =>> "gg(a,(){})"
"shit ( ) " =>> "shit()"
it "Should work when there're parameters" $ do
"f(x){a->}" =>> "f(x,(a){})"
"f{a->}" =>> "f((a){})"
"f(q){abc->}" =>> "f(q,(abc){})"
"f{a,b->}" =>> "f((a,b){})"
"f(){a,b->}" =>> "f((a,b){})"
"f(){a,b,c,d->}" =>> "f((a,b,c,d){})"
"f(x,y){a,b,c,d->}" =>> "f(x,y,(a,b,c,d){})"
gg "f(){->a}"
it "Should work when there's a statement inside lambda" $ do
"f(a,b){a->a}" =>> "f(a,b,(a){a;})"
"f(x,y){a,b->a \nb}" =>> "f(x,y,(a,b){a;b;})"
"f(abc,def){a,b,c,d,e->a\n b\n c\n d\n e}" =>> "f(abc,def,(a,b,c,d,e){a;b;c;d;e;})"
gg "run{->a}"
it "Should work when there're no parameters but statements" $ do
"run{a}" =>> "run((){a;})"
"run(a){ass}" =>> "run(a,(){ass;})"
"run(a){ass we can}" =>> "run(a,(){ass;we;can;})"
describe "When invoking a lambda directly" $ do
it "Should work when it's bare" $ do
"{}()" =>> "(){}()"
"{a}()" =>> "(){a;}()"
it "Should work when there're parameters" $ do
"{a->a}(233)" =>> "(a){a;}(233)"
"{a,b,c->a b c}(233,666,999)" =>> "(a,b,c){a;b;c;}(233,666,999)"
"{a,b,c->a b c } (233 , 666, 999)" =>> "(a,b,c){a;b;c;}(233,666,999)"
--
|
ice1000/OI-codes
|
codewars/authoring/haskell/TranspilerSpec.hs
|
agpl-3.0
| 3,451 | 0 | 14 | 937 | 646 | 273 | 373 | 82 | 1 |
module FixTheCode where
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.Class
import Control.Monad
import Control.Monad.IO.Class
isValid :: String -> Bool
isValid v = '!' `elem` v
maybeExcite :: MaybeT IO String
maybeExcite = do
v <- lift getLine
guard $ isValid v
return v
doExcite :: IO ()
doExcite = do
putStrLn "say something excite!"
excite <- runMaybeT maybeExcite
case excite of
Nothing -> putStrLn "MOAR EXCITE"
Just e -> putStrLn ("Good, was very excite: " ++ e)
|
thewoolleyman/haskellbook
|
26/14/maor/FixTheCode.hs
|
unlicense
| 508 | 0 | 12 | 98 | 160 | 82 | 78 | 19 | 2 |
module Ylang.Lexer where
import Text.Parsec.String (Parser)
import Text.Parsec.Language (emptyDef)
import qualified Text.Parsec.Token as Token
lexer :: Token.TokenParser ()
lexer = Token.makeTokenParser style
where
style = emptyDef {
Token.commentLine = commentLine
, Token.reservedOpNames = operators
, Token.reservedNames = keywords
}
commentLine = ";"
operators = ["+", "-", "*", "/", "=", "\\", "->", ",", ".", ":"]
keywords = ["dec", "def", "let", "var"]
integer :: Parser Integer
integer = Token.integer lexer
floating :: Parser Double
floating = Token.float lexer
strings :: Parser String
strings = Token.stringLiteral lexer
charLit :: Parser Char
charLit = Token.charLiteral lexer
parens :: Parser a -> Parser a
parens = Token.parens lexer
brackets :: Parser a -> Parser a
brackets = Token.brackets lexer
reserved :: String -> Parser ()
reserved = Token.reserved lexer
reservedOp :: String -> Parser ()
reservedOp = Token.reservedOp lexer
|
VoQn/ylang
|
Ylang/Lexer.hs
|
apache-2.0
| 1,011 | 0 | 8 | 198 | 319 | 177 | 142 | 29 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGraphicsItem.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:25
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QGraphicsItem (
QqGraphicsItem(..)
,QqGraphicsItem_nf(..)
,children
,qGraphicsItem_delete, qGraphicsItem_delete1
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QGraphicsItem
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
instance QuserMethod (QGraphicsItem ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsItem_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QGraphicsItem_userMethod" qtc_QGraphicsItem_userMethod :: Ptr (TQGraphicsItem a) -> CInt -> IO ()
instance QuserMethod (QGraphicsItemSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsItem_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QGraphicsItem ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QGraphicsItem_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QGraphicsItem_userMethodVariant" qtc_QGraphicsItem_userMethodVariant :: Ptr (TQGraphicsItem a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QGraphicsItemSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QGraphicsItem_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqGraphicsItem x1 where
qGraphicsItem :: x1 -> IO (QGraphicsItem ())
instance QqGraphicsItem (()) where
qGraphicsItem ()
= withQGraphicsItemResult $
qtc_QGraphicsItem
foreign import ccall "qtc_QGraphicsItem" qtc_QGraphicsItem :: IO (Ptr (TQGraphicsItem ()))
instance QqGraphicsItem ((QGraphicsItem t1)) where
qGraphicsItem (x1)
= withQGraphicsItemResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem1 cobj_x1
foreign import ccall "qtc_QGraphicsItem1" qtc_QGraphicsItem1 :: Ptr (TQGraphicsItem t1) -> IO (Ptr (TQGraphicsItem ()))
instance QqGraphicsItem ((QGraphicsTextItem t1)) where
qGraphicsItem (x1)
= withQGraphicsItemResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem1_graphicstextitem cobj_x1
foreign import ccall "qtc_QGraphicsItem1_graphicstextitem" qtc_QGraphicsItem1_graphicstextitem :: Ptr (TQGraphicsTextItem t1) -> IO (Ptr (TQGraphicsItem ()))
instance QqGraphicsItem ((QGraphicsItem t1, QGraphicsScene t2)) where
qGraphicsItem (x1, x2)
= withQGraphicsItemResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem2 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem2" qtc_QGraphicsItem2 :: Ptr (TQGraphicsItem t1) -> Ptr (TQGraphicsScene t2) -> IO (Ptr (TQGraphicsItem ()))
instance QqGraphicsItem ((QGraphicsTextItem t1, QGraphicsScene t2)) where
qGraphicsItem (x1, x2)
= withQGraphicsItemResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem2_graphicstextitem cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem2_graphicstextitem" qtc_QGraphicsItem2_graphicstextitem :: Ptr (TQGraphicsTextItem t1) -> Ptr (TQGraphicsScene t2) -> IO (Ptr (TQGraphicsItem ()))
class QqGraphicsItem_nf x1 where
qGraphicsItem_nf :: x1 -> IO (QGraphicsItem ())
instance QqGraphicsItem_nf (()) where
qGraphicsItem_nf ()
= withObjectRefResult $
qtc_QGraphicsItem
instance QqGraphicsItem_nf ((QGraphicsItem t1)) where
qGraphicsItem_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem1 cobj_x1
instance QqGraphicsItem_nf ((QGraphicsTextItem t1)) where
qGraphicsItem_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem1_graphicstextitem cobj_x1
instance QqGraphicsItem_nf ((QGraphicsItem t1, QGraphicsScene t2)) where
qGraphicsItem_nf (x1, x2)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem2 cobj_x1 cobj_x2
instance QqGraphicsItem_nf ((QGraphicsTextItem t1, QGraphicsScene t2)) where
qGraphicsItem_nf (x1, x2)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem2_graphicstextitem cobj_x1 cobj_x2
instance QacceptDrops (QGraphicsItem a) (()) where
acceptDrops x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_acceptDrops cobj_x0
foreign import ccall "qtc_QGraphicsItem_acceptDrops" qtc_QGraphicsItem_acceptDrops :: Ptr (TQGraphicsItem a) -> IO CBool
instance QacceptedMouseButtons (QGraphicsItem a) (()) where
acceptedMouseButtons x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_acceptedMouseButtons cobj_x0
foreign import ccall "qtc_QGraphicsItem_acceptedMouseButtons" qtc_QGraphicsItem_acceptedMouseButtons :: Ptr (TQGraphicsItem a) -> IO CLong
instance QacceptsHoverEvents (QGraphicsItem a) (()) where
acceptsHoverEvents x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_acceptsHoverEvents cobj_x0
foreign import ccall "qtc_QGraphicsItem_acceptsHoverEvents" qtc_QGraphicsItem_acceptsHoverEvents :: Ptr (TQGraphicsItem a) -> IO CBool
instance QaddToIndex (QGraphicsItem ()) (()) where
addToIndex x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_addToIndex cobj_x0
foreign import ccall "qtc_QGraphicsItem_addToIndex" qtc_QGraphicsItem_addToIndex :: Ptr (TQGraphicsItem a) -> IO ()
instance QaddToIndex (QGraphicsItemSc a) (()) where
addToIndex x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_addToIndex cobj_x0
instance Qadvance (QGraphicsItem ()) ((Int)) where
advance x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_advance_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGraphicsItem_advance_h" qtc_QGraphicsItem_advance_h :: Ptr (TQGraphicsItem a) -> CInt -> IO ()
instance Qadvance (QGraphicsItemSc a) ((Int)) where
advance x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_advance_h cobj_x0 (toCInt x1)
instance QqqboundingRect (QGraphicsItem ()) (()) (IO (QRectF ())) where
qqboundingRect x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_boundingRect_h cobj_x0
foreign import ccall "qtc_QGraphicsItem_boundingRect_h" qtc_QGraphicsItem_boundingRect_h :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQRectF ()))
instance QqqboundingRect (QGraphicsItemSc a) (()) (IO (QRectF ())) where
qqboundingRect x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_boundingRect_h cobj_x0
instance QqboundingRect (QGraphicsItem ()) (()) (IO (RectF)) where
qboundingRect x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_boundingRect_qth_h cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
foreign import ccall "qtc_QGraphicsItem_boundingRect_qth_h" qtc_QGraphicsItem_boundingRect_qth_h :: Ptr (TQGraphicsItem a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QqboundingRect (QGraphicsItemSc a) (()) (IO (RectF)) where
qboundingRect x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_boundingRect_qth_h cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
children :: QGraphicsItem a -> (()) -> IO ([QGraphicsItem ()])
children x0 ()
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_children cobj_x0 arr
foreign import ccall "qtc_QGraphicsItem_children" qtc_QGraphicsItem_children :: Ptr (TQGraphicsItem a) -> Ptr (Ptr (TQGraphicsItem ())) -> IO CInt
instance QqchildrenBoundingRect (QGraphicsItem a) (()) where
qchildrenBoundingRect x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_childrenBoundingRect cobj_x0
foreign import ccall "qtc_QGraphicsItem_childrenBoundingRect" qtc_QGraphicsItem_childrenBoundingRect :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQRectF ()))
instance QchildrenBoundingRect (QGraphicsItem a) (()) where
childrenBoundingRect x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_childrenBoundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
foreign import ccall "qtc_QGraphicsItem_childrenBoundingRect_qth" qtc_QGraphicsItem_childrenBoundingRect_qth :: Ptr (TQGraphicsItem a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QclearFocus (QGraphicsItem a) (()) where
clearFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_clearFocus cobj_x0
foreign import ccall "qtc_QGraphicsItem_clearFocus" qtc_QGraphicsItem_clearFocus :: Ptr (TQGraphicsItem a) -> IO ()
instance QcollidesWithItem (QGraphicsItem ()) ((QGraphicsItem t1)) where
collidesWithItem x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithItem_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_collidesWithItem_h" qtc_QGraphicsItem_collidesWithItem_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QcollidesWithItem (QGraphicsItemSc a) ((QGraphicsItem t1)) where
collidesWithItem x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithItem_h cobj_x0 cobj_x1
instance QcollidesWithItem (QGraphicsItem ()) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithItem1_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsItem_collidesWithItem1_h" qtc_QGraphicsItem_collidesWithItem1_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CLong -> IO CBool
instance QcollidesWithItem (QGraphicsItemSc a) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithItem1_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QcollidesWithItem (QGraphicsItem ()) ((QGraphicsTextItem t1)) where
collidesWithItem x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithItem_graphicstextitem_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_collidesWithItem_graphicstextitem_h" qtc_QGraphicsItem_collidesWithItem_graphicstextitem_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QcollidesWithItem (QGraphicsItemSc a) ((QGraphicsTextItem t1)) where
collidesWithItem x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithItem_graphicstextitem_h cobj_x0 cobj_x1
instance QcollidesWithItem (QGraphicsItem ()) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithItem1_graphicstextitem_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsItem_collidesWithItem1_graphicstextitem_h" qtc_QGraphicsItem_collidesWithItem1_graphicstextitem_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CLong -> IO CBool
instance QcollidesWithItem (QGraphicsItemSc a) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithItem1_graphicstextitem_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QcollidesWithPath (QGraphicsItem ()) ((QPainterPath t1)) where
collidesWithPath x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithPath_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_collidesWithPath_h" qtc_QGraphicsItem_collidesWithPath_h :: Ptr (TQGraphicsItem a) -> Ptr (TQPainterPath t1) -> IO CBool
instance QcollidesWithPath (QGraphicsItemSc a) ((QPainterPath t1)) where
collidesWithPath x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithPath_h cobj_x0 cobj_x1
instance QcollidesWithPath (QGraphicsItem ()) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithPath1_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsItem_collidesWithPath1_h" qtc_QGraphicsItem_collidesWithPath1_h :: Ptr (TQGraphicsItem a) -> Ptr (TQPainterPath t1) -> CLong -> IO CBool
instance QcollidesWithPath (QGraphicsItemSc a) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_collidesWithPath1_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QcollidingItems (QGraphicsItem a) (()) where
collidingItems x0 ()
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_collidingItems cobj_x0 arr
foreign import ccall "qtc_QGraphicsItem_collidingItems" qtc_QGraphicsItem_collidingItems :: Ptr (TQGraphicsItem a) -> Ptr (Ptr (TQGraphicsItem ())) -> IO CInt
instance QcollidingItems (QGraphicsItem a) ((ItemSelectionMode)) where
collidingItems x0 (x1)
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_collidingItems1 cobj_x0 (toCLong $ qEnum_toInt x1) arr
foreign import ccall "qtc_QGraphicsItem_collidingItems1" qtc_QGraphicsItem_collidingItems1 :: Ptr (TQGraphicsItem a) -> CLong -> Ptr (Ptr (TQGraphicsItem ())) -> IO CInt
instance Qqcontains (QGraphicsItem ()) ((PointF)) where
qcontains x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsItem_contains_qth_h cobj_x0 cpointf_x1_x cpointf_x1_y
foreign import ccall "qtc_QGraphicsItem_contains_qth_h" qtc_QGraphicsItem_contains_qth_h :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO CBool
instance Qqcontains (QGraphicsItemSc a) ((PointF)) where
qcontains x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsItem_contains_qth_h cobj_x0 cpointf_x1_x cpointf_x1_y
instance Qqqcontains (QGraphicsItem ()) ((QPointF t1)) where
qqcontains x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_contains_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_contains_h" qtc_QGraphicsItem_contains_h :: Ptr (TQGraphicsItem a) -> Ptr (TQPointF t1) -> IO CBool
instance Qqqcontains (QGraphicsItemSc a) ((QPointF t1)) where
qqcontains x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_contains_h cobj_x0 cobj_x1
instance QcontextMenuEvent (QGraphicsItem ()) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_contextMenuEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_contextMenuEvent_h" qtc_QGraphicsItem_contextMenuEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent (QGraphicsItemSc a) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_contextMenuEvent_h cobj_x0 cobj_x1
instance Qcursor (QGraphicsItem a) (()) where
cursor x0 ()
= withQCursorResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_cursor cobj_x0
foreign import ccall "qtc_QGraphicsItem_cursor" qtc_QGraphicsItem_cursor :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQCursor ()))
instance Qqdata (QGraphicsItem ()) ((Int)) (IO (QVariant ())) where
qdata x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_data cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGraphicsItem_data" qtc_QGraphicsItem_data :: Ptr (TQGraphicsItem a) -> CInt -> IO (Ptr (TQVariant ()))
instance Qqdata (QGraphicsItemSc a) ((Int)) (IO (QVariant ())) where
qdata x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_data cobj_x0 (toCInt x1)
instance Qqdata_nf (QGraphicsItem ()) ((Int)) (IO (QVariant ())) where
qdata_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_data cobj_x0 (toCInt x1)
instance Qqdata_nf (QGraphicsItemSc a) ((Int)) (IO (QVariant ())) where
qdata_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_data cobj_x0 (toCInt x1)
instance QdeviceTransform (QGraphicsItem a) ((QTransform t1)) where
deviceTransform x0 (x1)
= withQTransformResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_deviceTransform cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_deviceTransform" qtc_QGraphicsItem_deviceTransform :: Ptr (TQGraphicsItem a) -> Ptr (TQTransform t1) -> IO (Ptr (TQTransform ()))
instance QdragEnterEvent (QGraphicsItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_dragEnterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_dragEnterEvent_h" qtc_QGraphicsItem_dragEnterEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragEnterEvent (QGraphicsItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_dragEnterEvent_h cobj_x0 cobj_x1
instance QdragLeaveEvent (QGraphicsItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_dragLeaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_dragLeaveEvent_h" qtc_QGraphicsItem_dragLeaveEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragLeaveEvent (QGraphicsItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_dragLeaveEvent_h cobj_x0 cobj_x1
instance QdragMoveEvent (QGraphicsItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_dragMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_dragMoveEvent_h" qtc_QGraphicsItem_dragMoveEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragMoveEvent (QGraphicsItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_dragMoveEvent_h cobj_x0 cobj_x1
instance QdropEvent (QGraphicsItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_dropEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_dropEvent_h" qtc_QGraphicsItem_dropEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdropEvent (QGraphicsItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_dropEvent_h cobj_x0 cobj_x1
instance QensureVisible (QGraphicsItem a) (()) where
ensureVisible x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_ensureVisible cobj_x0
foreign import ccall "qtc_QGraphicsItem_ensureVisible" qtc_QGraphicsItem_ensureVisible :: Ptr (TQGraphicsItem a) -> IO ()
instance QensureVisible (QGraphicsItem a) ((Double, Double, Double, Double)) where
ensureVisible x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_ensureVisible4 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4)
foreign import ccall "qtc_QGraphicsItem_ensureVisible4" qtc_QGraphicsItem_ensureVisible4 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO ()
instance QensureVisible (QGraphicsItem a) ((Double, Double, Double, Double, Int)) where
ensureVisible x0 (x1, x2, x3, x4, x5)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_ensureVisible5 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4) (toCInt x5)
foreign import ccall "qtc_QGraphicsItem_ensureVisible5" qtc_QGraphicsItem_ensureVisible5 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> CInt -> IO ()
instance QensureVisible (QGraphicsItem a) ((Double, Double, Double, Double, Int, Int)) where
ensureVisible x0 (x1, x2, x3, x4, x5, x6)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_ensureVisible6 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4) (toCInt x5) (toCInt x6)
foreign import ccall "qtc_QGraphicsItem_ensureVisible6" qtc_QGraphicsItem_ensureVisible6 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> CInt -> CInt -> IO ()
instance QqensureVisible (QGraphicsItem a) ((QRectF t1)) where
qensureVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_ensureVisible1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_ensureVisible1" qtc_QGraphicsItem_ensureVisible1 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> IO ()
instance QqensureVisible (QGraphicsItem a) ((QRectF t1, Int)) where
qensureVisible x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_ensureVisible2 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QGraphicsItem_ensureVisible2" qtc_QGraphicsItem_ensureVisible2 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> CInt -> IO ()
instance QqensureVisible (QGraphicsItem a) ((QRectF t1, Int, Int)) where
qensureVisible x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_ensureVisible3 cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QGraphicsItem_ensureVisible3" qtc_QGraphicsItem_ensureVisible3 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> CInt -> CInt -> IO ()
instance QensureVisible (QGraphicsItem a) ((RectF)) where
ensureVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_ensureVisible1_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h
foreign import ccall "qtc_QGraphicsItem_ensureVisible1_qth" qtc_QGraphicsItem_ensureVisible1_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO ()
instance QensureVisible (QGraphicsItem a) ((RectF, Int)) where
ensureVisible x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_ensureVisible2_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h (toCInt x2)
foreign import ccall "qtc_QGraphicsItem_ensureVisible2_qth" qtc_QGraphicsItem_ensureVisible2_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> CInt -> IO ()
instance QensureVisible (QGraphicsItem a) ((RectF, Int, Int)) where
ensureVisible x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_ensureVisible3_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QGraphicsItem_ensureVisible3_qth" qtc_QGraphicsItem_ensureVisible3_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> CInt -> CInt -> IO ()
instance Qextension (QGraphicsItem ()) ((QVariant t1)) (IO (QVariant ())) where
extension x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_extension cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_extension" qtc_QGraphicsItem_extension :: Ptr (TQGraphicsItem a) -> Ptr (TQVariant t1) -> IO (Ptr (TQVariant ()))
instance Qextension (QGraphicsItemSc a) ((QVariant t1)) (IO (QVariant ())) where
extension x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_extension cobj_x0 cobj_x1
instance Qflags (QGraphicsItem a) (()) (IO (GraphicsItemFlags)) where
flags x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_flags cobj_x0
foreign import ccall "qtc_QGraphicsItem_flags" qtc_QGraphicsItem_flags :: Ptr (TQGraphicsItem a) -> IO CLong
instance QfocusInEvent (QGraphicsItem ()) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_focusInEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_focusInEvent_h" qtc_QGraphicsItem_focusInEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent (QGraphicsItemSc a) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_focusInEvent_h cobj_x0 cobj_x1
instance QfocusOutEvent (QGraphicsItem ()) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_focusOutEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_focusOutEvent_h" qtc_QGraphicsItem_focusOutEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent (QGraphicsItemSc a) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_focusOutEvent_h cobj_x0 cobj_x1
instance Qgroup (QGraphicsItem a) (()) (IO (QGraphicsItemGroup ())) where
group x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_group cobj_x0
foreign import ccall "qtc_QGraphicsItem_group" qtc_QGraphicsItem_group :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQGraphicsItemGroup ()))
instance QhandlesChildEvents (QGraphicsItem a) (()) where
handlesChildEvents x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_handlesChildEvents cobj_x0
foreign import ccall "qtc_QGraphicsItem_handlesChildEvents" qtc_QGraphicsItem_handlesChildEvents :: Ptr (TQGraphicsItem a) -> IO CBool
instance QhasCursor (QGraphicsItem a) (()) where
hasCursor x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_hasCursor cobj_x0
foreign import ccall "qtc_QGraphicsItem_hasCursor" qtc_QGraphicsItem_hasCursor :: Ptr (TQGraphicsItem a) -> IO CBool
instance QhasFocus (QGraphicsItem a) (()) where
hasFocus x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_hasFocus cobj_x0
foreign import ccall "qtc_QGraphicsItem_hasFocus" qtc_QGraphicsItem_hasFocus :: Ptr (TQGraphicsItem a) -> IO CBool
instance Qhide (QGraphicsItem a) (()) where
hide x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_hide cobj_x0
foreign import ccall "qtc_QGraphicsItem_hide" qtc_QGraphicsItem_hide :: Ptr (TQGraphicsItem a) -> IO ()
instance QhoverEnterEvent (QGraphicsItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_hoverEnterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_hoverEnterEvent_h" qtc_QGraphicsItem_hoverEnterEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverEnterEvent (QGraphicsItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_hoverEnterEvent_h cobj_x0 cobj_x1
instance QhoverLeaveEvent (QGraphicsItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_hoverLeaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_hoverLeaveEvent_h" qtc_QGraphicsItem_hoverLeaveEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverLeaveEvent (QGraphicsItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_hoverLeaveEvent_h cobj_x0 cobj_x1
instance QhoverMoveEvent (QGraphicsItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_hoverMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_hoverMoveEvent_h" qtc_QGraphicsItem_hoverMoveEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverMoveEvent (QGraphicsItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_hoverMoveEvent_h cobj_x0 cobj_x1
instance QinputMethodEvent (QGraphicsItem ()) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_inputMethodEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_inputMethodEvent_h" qtc_QGraphicsItem_inputMethodEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent (QGraphicsItemSc a) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_inputMethodEvent_h cobj_x0 cobj_x1
instance QinputMethodQuery (QGraphicsItem ()) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGraphicsItem_inputMethodQuery_h" qtc_QGraphicsItem_inputMethodQuery_h :: Ptr (TQGraphicsItem a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery (QGraphicsItemSc a) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
instance QinstallSceneEventFilter (QGraphicsItem a) ((QGraphicsItem t1)) where
installSceneEventFilter x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_installSceneEventFilter cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_installSceneEventFilter" qtc_QGraphicsItem_installSceneEventFilter :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> IO ()
instance QinstallSceneEventFilter (QGraphicsItem a) ((QGraphicsTextItem t1)) where
installSceneEventFilter x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_installSceneEventFilter_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_installSceneEventFilter_graphicstextitem" qtc_QGraphicsItem_installSceneEventFilter_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> IO ()
instance QisAncestorOf (QGraphicsItem a) ((QGraphicsItem t1)) where
isAncestorOf x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_isAncestorOf cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_isAncestorOf" qtc_QGraphicsItem_isAncestorOf :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QisAncestorOf (QGraphicsItem a) ((QGraphicsTextItem t1)) where
isAncestorOf x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_isAncestorOf_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_isAncestorOf_graphicstextitem" qtc_QGraphicsItem_isAncestorOf_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QisEnabled (QGraphicsItem a) (()) where
isEnabled x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_isEnabled cobj_x0
foreign import ccall "qtc_QGraphicsItem_isEnabled" qtc_QGraphicsItem_isEnabled :: Ptr (TQGraphicsItem a) -> IO CBool
instance QisObscured (QGraphicsItem a) (()) where
isObscured x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_isObscured cobj_x0
foreign import ccall "qtc_QGraphicsItem_isObscured" qtc_QGraphicsItem_isObscured :: Ptr (TQGraphicsItem a) -> IO CBool
instance QisObscured (QGraphicsItem a) ((Double, Double, Double, Double)) where
isObscured x0 (x1, x2, x3, x4)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_isObscured2 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4)
foreign import ccall "qtc_QGraphicsItem_isObscured2" qtc_QGraphicsItem_isObscured2 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO CBool
instance QqisObscured (QGraphicsItem a) ((QRectF t1)) where
qisObscured x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_isObscured1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_isObscured1" qtc_QGraphicsItem_isObscured1 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> IO CBool
instance QisObscured (QGraphicsItem a) ((RectF)) where
isObscured x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_isObscured1_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h
foreign import ccall "qtc_QGraphicsItem_isObscured1_qth" qtc_QGraphicsItem_isObscured1_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO CBool
instance QisObscuredBy (QGraphicsItem ()) ((QGraphicsItem t1)) where
isObscuredBy x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_isObscuredBy_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_isObscuredBy_h" qtc_QGraphicsItem_isObscuredBy_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QisObscuredBy (QGraphicsItemSc a) ((QGraphicsItem t1)) where
isObscuredBy x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_isObscuredBy_h cobj_x0 cobj_x1
instance QisObscuredBy (QGraphicsItem ()) ((QGraphicsTextItem t1)) where
isObscuredBy x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_isObscuredBy_graphicstextitem_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_isObscuredBy_graphicstextitem_h" qtc_QGraphicsItem_isObscuredBy_graphicstextitem_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QisObscuredBy (QGraphicsItemSc a) ((QGraphicsTextItem t1)) where
isObscuredBy x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_isObscuredBy_graphicstextitem_h cobj_x0 cobj_x1
instance QisSelected (QGraphicsItem a) (()) where
isSelected x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_isSelected cobj_x0
foreign import ccall "qtc_QGraphicsItem_isSelected" qtc_QGraphicsItem_isSelected :: Ptr (TQGraphicsItem a) -> IO CBool
instance QisVisible (QGraphicsItem a) (()) where
isVisible x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_isVisible cobj_x0
foreign import ccall "qtc_QGraphicsItem_isVisible" qtc_QGraphicsItem_isVisible :: Ptr (TQGraphicsItem a) -> IO CBool
instance QitemChange (QGraphicsItem ()) ((GraphicsItemChange, QVariant t2)) where
itemChange x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_itemChange_h cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
foreign import ccall "qtc_QGraphicsItem_itemChange_h" qtc_QGraphicsItem_itemChange_h :: Ptr (TQGraphicsItem a) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant ()))
instance QitemChange (QGraphicsItemSc a) ((GraphicsItemChange, QVariant t2)) where
itemChange x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_itemChange_h cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
instance QkeyPressEvent (QGraphicsItem ()) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_keyPressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_keyPressEvent_h" qtc_QGraphicsItem_keyPressEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent (QGraphicsItemSc a) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_keyPressEvent_h cobj_x0 cobj_x1
instance QkeyReleaseEvent (QGraphicsItem ()) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_keyReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_keyReleaseEvent_h" qtc_QGraphicsItem_keyReleaseEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent (QGraphicsItemSc a) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_keyReleaseEvent_h cobj_x0 cobj_x1
instance QmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, Double, Double)) (IO (PointF)) where
mapFromItem x0 (x1, x2, x3)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromItem4_qth cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3) cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapFromItem4_qth" qtc_QGraphicsItem_mapFromItem4_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, PointF)) (IO (PointF)) where
mapFromItem x0 (x1, x2)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCPointF x2 $ \cpointf_x2_x cpointf_x2_y ->
qtc_QGraphicsItem_mapFromItem2_qth cobj_x0 cobj_x1 cpointf_x2_x cpointf_x2_y cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapFromItem2_qth" qtc_QGraphicsItem_mapFromItem2_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, Double, Double)) (IO (PointF)) where
mapFromItem x0 (x1, x2, x3)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromItem4_graphicstextitem_qth cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3) cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapFromItem4_graphicstextitem_qth" qtc_QGraphicsItem_mapFromItem4_graphicstextitem_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, PointF)) (IO (PointF)) where
mapFromItem x0 (x1, x2)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCPointF x2 $ \cpointf_x2_x cpointf_x2_y ->
qtc_QGraphicsItem_mapFromItem2_graphicstextitem_qth cobj_x0 cobj_x1 cpointf_x2_x cpointf_x2_y cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapFromItem2_graphicstextitem_qth" qtc_QGraphicsItem_mapFromItem2_graphicstextitem_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, QPainterPath t2)) (IO (QPainterPath ())) where
mapFromItem x0 (x1, x2)
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapFromItem3 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapFromItem3" qtc_QGraphicsItem_mapFromItem3 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQPainterPath t2) -> IO (Ptr (TQPainterPath ()))
instance QmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, QPainterPath t2)) (IO (QPainterPath ())) where
mapFromItem x0 (x1, x2)
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapFromItem3_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapFromItem3_graphicstextitem" qtc_QGraphicsItem_mapFromItem3_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQPainterPath t2) -> IO (Ptr (TQPainterPath ()))
instance QqmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, Double, Double)) (IO (QPointF ())) where
qmapFromItem x0 (x1, x2, x3)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromItem4 cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3)
foreign import ccall "qtc_QGraphicsItem_mapFromItem4" qtc_QGraphicsItem_mapFromItem4 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> IO (Ptr (TQPointF ()))
instance QqmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, QPointF t2)) (IO (QPointF ())) where
qmapFromItem x0 (x1, x2)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapFromItem2 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapFromItem2" qtc_QGraphicsItem_mapFromItem2 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQPointF t2) -> IO (Ptr (TQPointF ()))
instance QqmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, Double, Double)) (IO (QPointF ())) where
qmapFromItem x0 (x1, x2, x3)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromItem4_graphicstextitem cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3)
foreign import ccall "qtc_QGraphicsItem_mapFromItem4_graphicstextitem" qtc_QGraphicsItem_mapFromItem4_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> IO (Ptr (TQPointF ()))
instance QqmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, QPointF t2)) (IO (QPointF ())) where
qmapFromItem x0 (x1, x2)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapFromItem2_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapFromItem2_graphicstextitem" qtc_QGraphicsItem_mapFromItem2_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQPointF t2) -> IO (Ptr (TQPointF ()))
instance QmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, Double, Double, Double, Double)) (IO (QPolygonF ())) where
mapFromItem x0 (x1, x2, x3, x4, x5)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromItem5 cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3) (toCDouble x4) (toCDouble x5)
foreign import ccall "qtc_QGraphicsItem_mapFromItem5" qtc_QGraphicsItem_mapFromItem5 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, QPolygonF t2)) (IO (QPolygonF ())) where
mapFromItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapFromItem1 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapFromItem1" qtc_QGraphicsItem_mapFromItem1 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQPolygonF t2) -> IO (Ptr (TQPolygonF ()))
instance QqmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, QRectF t2)) (IO (QPolygonF ())) where
qmapFromItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapFromItem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapFromItem" qtc_QGraphicsItem_mapFromItem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQRectF t2) -> IO (Ptr (TQPolygonF ()))
instance QmapFromItem (QGraphicsItem a) ((QGraphicsItem t1, RectF)) (IO (QPolygonF ())) where
mapFromItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCRectF x2 $ \crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h ->
qtc_QGraphicsItem_mapFromItem_qth cobj_x0 cobj_x1 crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h
foreign import ccall "qtc_QGraphicsItem_mapFromItem_qth" qtc_QGraphicsItem_mapFromItem_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, Double, Double, Double, Double)) (IO (QPolygonF ())) where
mapFromItem x0 (x1, x2, x3, x4, x5)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromItem5_graphicstextitem cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3) (toCDouble x4) (toCDouble x5)
foreign import ccall "qtc_QGraphicsItem_mapFromItem5_graphicstextitem" qtc_QGraphicsItem_mapFromItem5_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, QPolygonF t2)) (IO (QPolygonF ())) where
mapFromItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapFromItem1_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapFromItem1_graphicstextitem" qtc_QGraphicsItem_mapFromItem1_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQPolygonF t2) -> IO (Ptr (TQPolygonF ()))
instance QqmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, QRectF t2)) (IO (QPolygonF ())) where
qmapFromItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapFromItem_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapFromItem_graphicstextitem" qtc_QGraphicsItem_mapFromItem_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQRectF t2) -> IO (Ptr (TQPolygonF ()))
instance QmapFromItem (QGraphicsItem a) ((QGraphicsTextItem t1, RectF)) (IO (QPolygonF ())) where
mapFromItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCRectF x2 $ \crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h ->
qtc_QGraphicsItem_mapFromItem_graphicstextitem_qth cobj_x0 cobj_x1 crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h
foreign import ccall "qtc_QGraphicsItem_mapFromItem_graphicstextitem_qth" qtc_QGraphicsItem_mapFromItem_graphicstextitem_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapFromParent (QGraphicsItem a) ((Double, Double)) (IO (PointF)) where
mapFromParent x0 (x1, x2)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapFromParent4_qth cobj_x0 (toCDouble x1) (toCDouble x2) cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapFromParent4_qth" qtc_QGraphicsItem_mapFromParent4_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapFromParent (QGraphicsItem a) ((PointF)) (IO (PointF)) where
mapFromParent x0 (x1)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsItem_mapFromParent1_qth cobj_x0 cpointf_x1_x cpointf_x1_y cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapFromParent1_qth" qtc_QGraphicsItem_mapFromParent1_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapFromParent (QGraphicsItem a) ((QPainterPath t1)) (IO (QPainterPath ())) where
mapFromParent x0 (x1)
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromParent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapFromParent" qtc_QGraphicsItem_mapFromParent :: Ptr (TQGraphicsItem a) -> Ptr (TQPainterPath t1) -> IO (Ptr (TQPainterPath ()))
instance QqmapFromParent (QGraphicsItem a) ((Double, Double)) (IO (QPointF ())) where
qmapFromParent x0 (x1, x2)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapFromParent4 cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_mapFromParent4" qtc_QGraphicsItem_mapFromParent4 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO (Ptr (TQPointF ()))
instance QqmapFromParent (QGraphicsItem a) ((QPointF t1)) (IO (QPointF ())) where
qmapFromParent x0 (x1)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromParent1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapFromParent1" qtc_QGraphicsItem_mapFromParent1 :: Ptr (TQGraphicsItem a) -> Ptr (TQPointF t1) -> IO (Ptr (TQPointF ()))
instance QmapFromParent (QGraphicsItem a) ((Double, Double, Double, Double)) (IO (QPolygonF ())) where
mapFromParent x0 (x1, x2, x3, x4)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapFromParent5 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4)
foreign import ccall "qtc_QGraphicsItem_mapFromParent5" qtc_QGraphicsItem_mapFromParent5 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapFromParent (QGraphicsItem a) ((QPolygonF t1)) (IO (QPolygonF ())) where
mapFromParent x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromParent2 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapFromParent2" qtc_QGraphicsItem_mapFromParent2 :: Ptr (TQGraphicsItem a) -> Ptr (TQPolygonF t1) -> IO (Ptr (TQPolygonF ()))
instance QqmapFromParent (QGraphicsItem a) ((QRectF t1)) (IO (QPolygonF ())) where
qmapFromParent x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromParent3 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapFromParent3" qtc_QGraphicsItem_mapFromParent3 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> IO (Ptr (TQPolygonF ()))
instance QmapFromParent (QGraphicsItem a) ((RectF)) (IO (QPolygonF ())) where
mapFromParent x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_mapFromParent3_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h
foreign import ccall "qtc_QGraphicsItem_mapFromParent3_qth" qtc_QGraphicsItem_mapFromParent3_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapFromScene (QGraphicsItem a) ((Double, Double)) (IO (PointF)) where
mapFromScene x0 (x1, x2)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapFromScene4_qth cobj_x0 (toCDouble x1) (toCDouble x2) cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapFromScene4_qth" qtc_QGraphicsItem_mapFromScene4_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapFromScene (QGraphicsItem a) ((PointF)) (IO (PointF)) where
mapFromScene x0 (x1)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsItem_mapFromScene1_qth cobj_x0 cpointf_x1_x cpointf_x1_y cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapFromScene1_qth" qtc_QGraphicsItem_mapFromScene1_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapFromScene (QGraphicsItem a) ((QPainterPath t1)) (IO (QPainterPath ())) where
mapFromScene x0 (x1)
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromScene cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapFromScene" qtc_QGraphicsItem_mapFromScene :: Ptr (TQGraphicsItem a) -> Ptr (TQPainterPath t1) -> IO (Ptr (TQPainterPath ()))
instance QqmapFromScene (QGraphicsItem a) ((Double, Double)) (IO (QPointF ())) where
qmapFromScene x0 (x1, x2)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapFromScene4 cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_mapFromScene4" qtc_QGraphicsItem_mapFromScene4 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO (Ptr (TQPointF ()))
instance QqmapFromScene (QGraphicsItem a) ((QPointF t1)) (IO (QPointF ())) where
qmapFromScene x0 (x1)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromScene1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapFromScene1" qtc_QGraphicsItem_mapFromScene1 :: Ptr (TQGraphicsItem a) -> Ptr (TQPointF t1) -> IO (Ptr (TQPointF ()))
instance QmapFromScene (QGraphicsItem a) ((Double, Double, Double, Double)) (IO (QPolygonF ())) where
mapFromScene x0 (x1, x2, x3, x4)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapFromScene5 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4)
foreign import ccall "qtc_QGraphicsItem_mapFromScene5" qtc_QGraphicsItem_mapFromScene5 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapFromScene (QGraphicsItem a) ((QPolygonF t1)) (IO (QPolygonF ())) where
mapFromScene x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromScene2 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapFromScene2" qtc_QGraphicsItem_mapFromScene2 :: Ptr (TQGraphicsItem a) -> Ptr (TQPolygonF t1) -> IO (Ptr (TQPolygonF ()))
instance QqmapFromScene (QGraphicsItem a) ((QRectF t1)) (IO (QPolygonF ())) where
qmapFromScene x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapFromScene3 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapFromScene3" qtc_QGraphicsItem_mapFromScene3 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> IO (Ptr (TQPolygonF ()))
instance QmapFromScene (QGraphicsItem a) ((RectF)) (IO (QPolygonF ())) where
mapFromScene x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_mapFromScene3_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h
foreign import ccall "qtc_QGraphicsItem_mapFromScene3_qth" qtc_QGraphicsItem_mapFromScene3_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapToItem (QGraphicsItem a) ((QGraphicsItem t1, Double, Double)) (IO (PointF)) where
mapToItem x0 (x1, x2, x3)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToItem4_qth cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3) cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapToItem4_qth" qtc_QGraphicsItem_mapToItem4_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapToItem (QGraphicsItem a) ((QGraphicsItem t1, PointF)) (IO (PointF)) where
mapToItem x0 (x1, x2)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCPointF x2 $ \cpointf_x2_x cpointf_x2_y ->
qtc_QGraphicsItem_mapToItem1_qth cobj_x0 cobj_x1 cpointf_x2_x cpointf_x2_y cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapToItem1_qth" qtc_QGraphicsItem_mapToItem1_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, Double, Double)) (IO (PointF)) where
mapToItem x0 (x1, x2, x3)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToItem4_graphicstextitem_qth cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3) cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapToItem4_graphicstextitem_qth" qtc_QGraphicsItem_mapToItem4_graphicstextitem_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, PointF)) (IO (PointF)) where
mapToItem x0 (x1, x2)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCPointF x2 $ \cpointf_x2_x cpointf_x2_y ->
qtc_QGraphicsItem_mapToItem1_graphicstextitem_qth cobj_x0 cobj_x1 cpointf_x2_x cpointf_x2_y cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapToItem1_graphicstextitem_qth" qtc_QGraphicsItem_mapToItem1_graphicstextitem_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapToItem (QGraphicsItem a) ((QGraphicsItem t1, QPainterPath t2)) (IO (QPainterPath ())) where
mapToItem x0 (x1, x2)
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapToItem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapToItem" qtc_QGraphicsItem_mapToItem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQPainterPath t2) -> IO (Ptr (TQPainterPath ()))
instance QmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, QPainterPath t2)) (IO (QPainterPath ())) where
mapToItem x0 (x1, x2)
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapToItem_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapToItem_graphicstextitem" qtc_QGraphicsItem_mapToItem_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQPainterPath t2) -> IO (Ptr (TQPainterPath ()))
instance QqmapToItem (QGraphicsItem a) ((QGraphicsItem t1, Double, Double)) (IO (QPointF ())) where
qmapToItem x0 (x1, x2, x3)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToItem4 cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3)
foreign import ccall "qtc_QGraphicsItem_mapToItem4" qtc_QGraphicsItem_mapToItem4 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> IO (Ptr (TQPointF ()))
instance QqmapToItem (QGraphicsItem a) ((QGraphicsItem t1, QPointF t2)) (IO (QPointF ())) where
qmapToItem x0 (x1, x2)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapToItem1 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapToItem1" qtc_QGraphicsItem_mapToItem1 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQPointF t2) -> IO (Ptr (TQPointF ()))
instance QqmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, Double, Double)) (IO (QPointF ())) where
qmapToItem x0 (x1, x2, x3)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToItem4_graphicstextitem cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3)
foreign import ccall "qtc_QGraphicsItem_mapToItem4_graphicstextitem" qtc_QGraphicsItem_mapToItem4_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> IO (Ptr (TQPointF ()))
instance QqmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, QPointF t2)) (IO (QPointF ())) where
qmapToItem x0 (x1, x2)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapToItem1_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapToItem1_graphicstextitem" qtc_QGraphicsItem_mapToItem1_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQPointF t2) -> IO (Ptr (TQPointF ()))
instance QmapToItem (QGraphicsItem a) ((QGraphicsItem t1, Double, Double, Double, Double)) (IO (QPolygonF ())) where
mapToItem x0 (x1, x2, x3, x4, x5)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToItem5 cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3) (toCDouble x4) (toCDouble x5)
foreign import ccall "qtc_QGraphicsItem_mapToItem5" qtc_QGraphicsItem_mapToItem5 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapToItem (QGraphicsItem a) ((QGraphicsItem t1, QPolygonF t2)) (IO (QPolygonF ())) where
mapToItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapToItem2 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapToItem2" qtc_QGraphicsItem_mapToItem2 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQPolygonF t2) -> IO (Ptr (TQPolygonF ()))
instance QqmapToItem (QGraphicsItem a) ((QGraphicsItem t1, QRectF t2)) (IO (QPolygonF ())) where
qmapToItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapToItem3 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapToItem3" qtc_QGraphicsItem_mapToItem3 :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQRectF t2) -> IO (Ptr (TQPolygonF ()))
instance QmapToItem (QGraphicsItem a) ((QGraphicsItem t1, RectF)) (IO (QPolygonF ())) where
mapToItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCRectF x2 $ \crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h ->
qtc_QGraphicsItem_mapToItem3_qth cobj_x0 cobj_x1 crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h
foreign import ccall "qtc_QGraphicsItem_mapToItem3_qth" qtc_QGraphicsItem_mapToItem3_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, Double, Double, Double, Double)) (IO (QPolygonF ())) where
mapToItem x0 (x1, x2, x3, x4, x5)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToItem5_graphicstextitem cobj_x0 cobj_x1 (toCDouble x2) (toCDouble x3) (toCDouble x4) (toCDouble x5)
foreign import ccall "qtc_QGraphicsItem_mapToItem5_graphicstextitem" qtc_QGraphicsItem_mapToItem5_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, QPolygonF t2)) (IO (QPolygonF ())) where
mapToItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapToItem2_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapToItem2_graphicstextitem" qtc_QGraphicsItem_mapToItem2_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQPolygonF t2) -> IO (Ptr (TQPolygonF ()))
instance QqmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, QRectF t2)) (IO (QPolygonF ())) where
qmapToItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_mapToItem3_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_mapToItem3_graphicstextitem" qtc_QGraphicsItem_mapToItem3_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQRectF t2) -> IO (Ptr (TQPolygonF ()))
instance QmapToItem (QGraphicsItem a) ((QGraphicsTextItem t1, RectF)) (IO (QPolygonF ())) where
mapToItem x0 (x1, x2)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCRectF x2 $ \crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h ->
qtc_QGraphicsItem_mapToItem3_graphicstextitem_qth cobj_x0 cobj_x1 crectf_x2_x crectf_x2_y crectf_x2_w crectf_x2_h
foreign import ccall "qtc_QGraphicsItem_mapToItem3_graphicstextitem_qth" qtc_QGraphicsItem_mapToItem3_graphicstextitem_qth :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapToParent (QGraphicsItem a) ((Double, Double)) (IO (PointF)) where
mapToParent x0 (x1, x2)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapToParent4_qth cobj_x0 (toCDouble x1) (toCDouble x2) cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapToParent4_qth" qtc_QGraphicsItem_mapToParent4_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapToParent (QGraphicsItem a) ((PointF)) (IO (PointF)) where
mapToParent x0 (x1)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsItem_mapToParent1_qth cobj_x0 cpointf_x1_x cpointf_x1_y cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapToParent1_qth" qtc_QGraphicsItem_mapToParent1_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapToParent (QGraphicsItem a) ((QPainterPath t1)) (IO (QPainterPath ())) where
mapToParent x0 (x1)
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToParent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapToParent" qtc_QGraphicsItem_mapToParent :: Ptr (TQGraphicsItem a) -> Ptr (TQPainterPath t1) -> IO (Ptr (TQPainterPath ()))
instance QqmapToParent (QGraphicsItem a) ((Double, Double)) (IO (QPointF ())) where
qmapToParent x0 (x1, x2)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapToParent4 cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_mapToParent4" qtc_QGraphicsItem_mapToParent4 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO (Ptr (TQPointF ()))
instance QqmapToParent (QGraphicsItem a) ((QPointF t1)) (IO (QPointF ())) where
qmapToParent x0 (x1)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToParent1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapToParent1" qtc_QGraphicsItem_mapToParent1 :: Ptr (TQGraphicsItem a) -> Ptr (TQPointF t1) -> IO (Ptr (TQPointF ()))
instance QmapToParent (QGraphicsItem a) ((Double, Double, Double, Double)) (IO (QPolygonF ())) where
mapToParent x0 (x1, x2, x3, x4)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapToParent5 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4)
foreign import ccall "qtc_QGraphicsItem_mapToParent5" qtc_QGraphicsItem_mapToParent5 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapToParent (QGraphicsItem a) ((QPolygonF t1)) (IO (QPolygonF ())) where
mapToParent x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToParent2 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapToParent2" qtc_QGraphicsItem_mapToParent2 :: Ptr (TQGraphicsItem a) -> Ptr (TQPolygonF t1) -> IO (Ptr (TQPolygonF ()))
instance QqmapToParent (QGraphicsItem a) ((QRectF t1)) (IO (QPolygonF ())) where
qmapToParent x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToParent3 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapToParent3" qtc_QGraphicsItem_mapToParent3 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> IO (Ptr (TQPolygonF ()))
instance QmapToParent (QGraphicsItem a) ((RectF)) (IO (QPolygonF ())) where
mapToParent x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_mapToParent3_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h
foreign import ccall "qtc_QGraphicsItem_mapToParent3_qth" qtc_QGraphicsItem_mapToParent3_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapToScene (QGraphicsItem a) ((Double, Double)) (IO (PointF)) where
mapToScene x0 (x1, x2)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapToScene4_qth cobj_x0 (toCDouble x1) (toCDouble x2) cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapToScene4_qth" qtc_QGraphicsItem_mapToScene4_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapToScene (QGraphicsItem a) ((PointF)) (IO (PointF)) where
mapToScene x0 (x1)
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsItem_mapToScene1_qth cobj_x0 cpointf_x1_x cpointf_x1_y cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_mapToScene1_qth" qtc_QGraphicsItem_mapToScene1_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QmapToScene (QGraphicsItem a) ((QPainterPath t1)) (IO (QPainterPath ())) where
mapToScene x0 (x1)
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToScene cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapToScene" qtc_QGraphicsItem_mapToScene :: Ptr (TQGraphicsItem a) -> Ptr (TQPainterPath t1) -> IO (Ptr (TQPainterPath ()))
instance QqmapToScene (QGraphicsItem a) ((Double, Double)) (IO (QPointF ())) where
qmapToScene x0 (x1, x2)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapToScene4 cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_mapToScene4" qtc_QGraphicsItem_mapToScene4 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO (Ptr (TQPointF ()))
instance QqmapToScene (QGraphicsItem a) ((QPointF t1)) (IO (QPointF ())) where
qmapToScene x0 (x1)
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToScene1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapToScene1" qtc_QGraphicsItem_mapToScene1 :: Ptr (TQGraphicsItem a) -> Ptr (TQPointF t1) -> IO (Ptr (TQPointF ()))
instance QmapToScene (QGraphicsItem a) ((Double, Double, Double, Double)) (IO (QPolygonF ())) where
mapToScene x0 (x1, x2, x3, x4)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_mapToScene5 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4)
foreign import ccall "qtc_QGraphicsItem_mapToScene5" qtc_QGraphicsItem_mapToScene5 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance QmapToScene (QGraphicsItem a) ((QPolygonF t1)) (IO (QPolygonF ())) where
mapToScene x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToScene2 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapToScene2" qtc_QGraphicsItem_mapToScene2 :: Ptr (TQGraphicsItem a) -> Ptr (TQPolygonF t1) -> IO (Ptr (TQPolygonF ()))
instance QqmapToScene (QGraphicsItem a) ((QRectF t1)) (IO (QPolygonF ())) where
qmapToScene x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mapToScene3 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mapToScene3" qtc_QGraphicsItem_mapToScene3 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> IO (Ptr (TQPolygonF ()))
instance QmapToScene (QGraphicsItem a) ((RectF)) (IO (QPolygonF ())) where
mapToScene x0 (x1)
= withQPolygonFResult $
withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_mapToScene3_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h
foreign import ccall "qtc_QGraphicsItem_mapToScene3_qth" qtc_QGraphicsItem_mapToScene3_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO (Ptr (TQPolygonF ()))
instance Qmatrix (QGraphicsItem a) (()) where
matrix x0 ()
= withQMatrixResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_matrix cobj_x0
foreign import ccall "qtc_QGraphicsItem_matrix" qtc_QGraphicsItem_matrix :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQMatrix ()))
instance QmouseDoubleClickEvent (QGraphicsItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mouseDoubleClickEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mouseDoubleClickEvent_h" qtc_QGraphicsItem_mouseDoubleClickEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent (QGraphicsItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mouseDoubleClickEvent_h cobj_x0 cobj_x1
instance QmouseMoveEvent (QGraphicsItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mouseMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mouseMoveEvent_h" qtc_QGraphicsItem_mouseMoveEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseMoveEvent (QGraphicsItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mouseMoveEvent_h cobj_x0 cobj_x1
instance QmousePressEvent (QGraphicsItem ()) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mousePressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mousePressEvent_h" qtc_QGraphicsItem_mousePressEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmousePressEvent (QGraphicsItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mousePressEvent_h cobj_x0 cobj_x1
instance QmouseReleaseEvent (QGraphicsItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mouseReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_mouseReleaseEvent_h" qtc_QGraphicsItem_mouseReleaseEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseReleaseEvent (QGraphicsItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_mouseReleaseEvent_h cobj_x0 cobj_x1
instance QmoveBy (QGraphicsItem a) ((Double, Double)) where
moveBy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_moveBy cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_moveBy" qtc_QGraphicsItem_moveBy :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO ()
instance QopaqueArea (QGraphicsItem ()) (()) where
opaqueArea x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_opaqueArea_h cobj_x0
foreign import ccall "qtc_QGraphicsItem_opaqueArea_h" qtc_QGraphicsItem_opaqueArea_h :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQPainterPath ()))
instance QopaqueArea (QGraphicsItemSc a) (()) where
opaqueArea x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_opaqueArea_h cobj_x0
instance Qpaint (QGraphicsItem ()) ((QPainter t1, QStyleOptionGraphicsItem t2)) where
paint x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_paint_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_paint_h" qtc_QGraphicsItem_paint_h :: Ptr (TQGraphicsItem a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionGraphicsItem t2) -> IO ()
instance Qpaint (QGraphicsItemSc a) ((QPainter t1, QStyleOptionGraphicsItem t2)) where
paint x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_paint_h cobj_x0 cobj_x1 cobj_x2
instance Qpaint (QGraphicsItem ()) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where
paint x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGraphicsItem_paint1_h cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QGraphicsItem_paint1_h" qtc_QGraphicsItem_paint1_h :: Ptr (TQGraphicsItem a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionGraphicsItem t2) -> Ptr (TQWidget t3) -> IO ()
instance Qpaint (QGraphicsItemSc a) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where
paint x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGraphicsItem_paint1_h cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance QparentItem (QGraphicsItem a) (()) where
parentItem x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_parentItem cobj_x0
foreign import ccall "qtc_QGraphicsItem_parentItem" qtc_QGraphicsItem_parentItem :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQGraphicsItem ()))
instance Qpos (QGraphicsItem a) (()) (IO (PointF)) where
pos x0 ()
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_pos_qth cobj_x0 cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_pos_qth" qtc_QGraphicsItem_pos_qth :: Ptr (TQGraphicsItem a) -> Ptr CDouble -> Ptr CDouble -> IO ()
instance Qqpos (QGraphicsItem a) (()) (IO (QPointF ())) where
qpos x0 ()
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_pos cobj_x0
foreign import ccall "qtc_QGraphicsItem_pos" qtc_QGraphicsItem_pos :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQPointF ()))
instance QprepareGeometryChange (QGraphicsItem ()) (()) where
prepareGeometryChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_prepareGeometryChange cobj_x0
foreign import ccall "qtc_QGraphicsItem_prepareGeometryChange" qtc_QGraphicsItem_prepareGeometryChange :: Ptr (TQGraphicsItem a) -> IO ()
instance QprepareGeometryChange (QGraphicsItemSc a) (()) where
prepareGeometryChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_prepareGeometryChange cobj_x0
instance QremoveFromIndex (QGraphicsItem ()) (()) where
removeFromIndex x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_removeFromIndex cobj_x0
foreign import ccall "qtc_QGraphicsItem_removeFromIndex" qtc_QGraphicsItem_removeFromIndex :: Ptr (TQGraphicsItem a) -> IO ()
instance QremoveFromIndex (QGraphicsItemSc a) (()) where
removeFromIndex x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_removeFromIndex cobj_x0
instance QremoveSceneEventFilter (QGraphicsItem a) ((QGraphicsItem t1)) where
removeSceneEventFilter x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_removeSceneEventFilter cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_removeSceneEventFilter" qtc_QGraphicsItem_removeSceneEventFilter :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> IO ()
instance QremoveSceneEventFilter (QGraphicsItem a) ((QGraphicsTextItem t1)) where
removeSceneEventFilter x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_removeSceneEventFilter_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_removeSceneEventFilter_graphicstextitem" qtc_QGraphicsItem_removeSceneEventFilter_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> IO ()
instance QresetMatrix (QGraphicsItem a) (()) where
resetMatrix x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_resetMatrix cobj_x0
foreign import ccall "qtc_QGraphicsItem_resetMatrix" qtc_QGraphicsItem_resetMatrix :: Ptr (TQGraphicsItem a) -> IO ()
instance QresetTransform (QGraphicsItem a) (()) where
resetTransform x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_resetTransform cobj_x0
foreign import ccall "qtc_QGraphicsItem_resetTransform" qtc_QGraphicsItem_resetTransform :: Ptr (TQGraphicsItem a) -> IO ()
instance Qrotate (QGraphicsItem a) ((Double)) where
rotate x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_rotate cobj_x0 (toCDouble x1)
foreign import ccall "qtc_QGraphicsItem_rotate" qtc_QGraphicsItem_rotate :: Ptr (TQGraphicsItem a) -> CDouble -> IO ()
instance Qqscale (QGraphicsItem a) ((Double, Double)) where
qscale x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_scale cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_scale" qtc_QGraphicsItem_scale :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO ()
instance Qscene (QGraphicsItem a) (()) where
scene x0 ()
= withQGraphicsSceneResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_scene cobj_x0
foreign import ccall "qtc_QGraphicsItem_scene" qtc_QGraphicsItem_scene :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQGraphicsScene ()))
instance QqsceneBoundingRect (QGraphicsItem a) (()) where
qsceneBoundingRect x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_sceneBoundingRect cobj_x0
foreign import ccall "qtc_QGraphicsItem_sceneBoundingRect" qtc_QGraphicsItem_sceneBoundingRect :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQRectF ()))
instance QsceneBoundingRect (QGraphicsItem a) (()) where
sceneBoundingRect x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_sceneBoundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
foreign import ccall "qtc_QGraphicsItem_sceneBoundingRect_qth" qtc_QGraphicsItem_sceneBoundingRect_qth :: Ptr (TQGraphicsItem a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QsceneEvent (QGraphicsItem ()) ((QEvent t1)) where
sceneEvent x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_sceneEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_sceneEvent_h" qtc_QGraphicsItem_sceneEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQEvent t1) -> IO CBool
instance QsceneEvent (QGraphicsItemSc a) ((QEvent t1)) where
sceneEvent x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_sceneEvent_h cobj_x0 cobj_x1
instance QsceneEventFilter (QGraphicsItem ()) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_sceneEventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_sceneEventFilter_h" qtc_QGraphicsItem_sceneEventFilter_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter (QGraphicsItemSc a) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_sceneEventFilter_h cobj_x0 cobj_x1 cobj_x2
instance QsceneEventFilter (QGraphicsItem ()) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_sceneEventFilter_graphicstextitem_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItem_sceneEventFilter_graphicstextitem_h" qtc_QGraphicsItem_sceneEventFilter_graphicstextitem_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter (QGraphicsItemSc a) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_sceneEventFilter_graphicstextitem_h cobj_x0 cobj_x1 cobj_x2
instance QsceneMatrix (QGraphicsItem a) (()) where
sceneMatrix x0 ()
= withQMatrixResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_sceneMatrix cobj_x0
foreign import ccall "qtc_QGraphicsItem_sceneMatrix" qtc_QGraphicsItem_sceneMatrix :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQMatrix ()))
instance QscenePos (QGraphicsItem a) (()) where
scenePos x0 ()
= withPointFResult $ \cpointf_ret_x cpointf_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_scenePos_qth cobj_x0 cpointf_ret_x cpointf_ret_y
foreign import ccall "qtc_QGraphicsItem_scenePos_qth" qtc_QGraphicsItem_scenePos_qth :: Ptr (TQGraphicsItem a) -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QqscenePos (QGraphicsItem a) (()) where
qscenePos x0 ()
= withQPointFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_scenePos cobj_x0
foreign import ccall "qtc_QGraphicsItem_scenePos" qtc_QGraphicsItem_scenePos :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQPointF ()))
instance QsceneTransform (QGraphicsItem a) (()) where
sceneTransform x0 ()
= withQTransformResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_sceneTransform cobj_x0
foreign import ccall "qtc_QGraphicsItem_sceneTransform" qtc_QGraphicsItem_sceneTransform :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQTransform ()))
instance QsetAcceptDrops (QGraphicsItem a) ((Bool)) where
setAcceptDrops x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setAcceptDrops cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGraphicsItem_setAcceptDrops" qtc_QGraphicsItem_setAcceptDrops :: Ptr (TQGraphicsItem a) -> CBool -> IO ()
instance QsetAcceptedMouseButtons (QGraphicsItem a) ((MouseButtons)) where
setAcceptedMouseButtons x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setAcceptedMouseButtons cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QGraphicsItem_setAcceptedMouseButtons" qtc_QGraphicsItem_setAcceptedMouseButtons :: Ptr (TQGraphicsItem a) -> CLong -> IO ()
instance QsetAcceptsHoverEvents (QGraphicsItem a) ((Bool)) where
setAcceptsHoverEvents x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setAcceptsHoverEvents cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGraphicsItem_setAcceptsHoverEvents" qtc_QGraphicsItem_setAcceptsHoverEvents :: Ptr (TQGraphicsItem a) -> CBool -> IO ()
instance QsetCursor (QGraphicsItem a) ((QCursor t1)) where
setCursor x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setCursor cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_setCursor" qtc_QGraphicsItem_setCursor :: Ptr (TQGraphicsItem a) -> Ptr (TQCursor t1) -> IO ()
instance QsetData (QGraphicsItem a) ((Int, QVariant t2)) (IO ()) where
setData x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_setData cobj_x0 (toCInt x1) cobj_x2
foreign import ccall "qtc_QGraphicsItem_setData" qtc_QGraphicsItem_setData :: Ptr (TQGraphicsItem a) -> CInt -> Ptr (TQVariant t2) -> IO ()
instance QsetEnabled (QGraphicsItem a) ((Bool)) where
setEnabled x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setEnabled cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGraphicsItem_setEnabled" qtc_QGraphicsItem_setEnabled :: Ptr (TQGraphicsItem a) -> CBool -> IO ()
instance QsetExtension (QGraphicsItem ()) ((QGraphicsItemExtension, QVariant t2)) where
setExtension x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_setExtension cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
foreign import ccall "qtc_QGraphicsItem_setExtension" qtc_QGraphicsItem_setExtension :: Ptr (TQGraphicsItem a) -> CLong -> Ptr (TQVariant t2) -> IO ()
instance QsetExtension (QGraphicsItemSc a) ((QGraphicsItemExtension, QVariant t2)) where
setExtension x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItem_setExtension cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
instance QsetFlag (QGraphicsItem a) ((GraphicsItemFlag)) where
setFlag x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setFlag cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGraphicsItem_setFlag" qtc_QGraphicsItem_setFlag :: Ptr (TQGraphicsItem a) -> CLong -> IO ()
instance QsetFlag (QGraphicsItem a) ((GraphicsItemFlag, Bool)) where
setFlag x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setFlag1 cobj_x0 (toCLong $ qEnum_toInt x1) (toCBool x2)
foreign import ccall "qtc_QGraphicsItem_setFlag1" qtc_QGraphicsItem_setFlag1 :: Ptr (TQGraphicsItem a) -> CLong -> CBool -> IO ()
instance QsetFlags (QGraphicsItem a) ((GraphicsItemFlags)) where
setFlags x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setFlags cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QGraphicsItem_setFlags" qtc_QGraphicsItem_setFlags :: Ptr (TQGraphicsItem a) -> CLong -> IO ()
instance QsetFocus (QGraphicsItem a) (()) where
setFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setFocus cobj_x0
foreign import ccall "qtc_QGraphicsItem_setFocus" qtc_QGraphicsItem_setFocus :: Ptr (TQGraphicsItem a) -> IO ()
instance QsetFocus (QGraphicsItem a) ((FocusReason)) where
setFocus x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setFocus1 cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGraphicsItem_setFocus1" qtc_QGraphicsItem_setFocus1 :: Ptr (TQGraphicsItem a) -> CLong -> IO ()
instance QsetGroup (QGraphicsItem a) ((QGraphicsItemGroup t1)) where
setGroup x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setGroup cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_setGroup" qtc_QGraphicsItem_setGroup :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItemGroup t1) -> IO ()
instance QsetHandlesChildEvents (QGraphicsItem a) ((Bool)) where
setHandlesChildEvents x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setHandlesChildEvents cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGraphicsItem_setHandlesChildEvents" qtc_QGraphicsItem_setHandlesChildEvents :: Ptr (TQGraphicsItem a) -> CBool -> IO ()
instance QsetMatrix (QGraphicsItem a) ((QMatrix t1)) where
setMatrix x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setMatrix cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_setMatrix" qtc_QGraphicsItem_setMatrix :: Ptr (TQGraphicsItem a) -> Ptr (TQMatrix t1) -> IO ()
instance QsetMatrix (QGraphicsItem a) ((QMatrix t1, Bool)) where
setMatrix x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setMatrix1 cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QGraphicsItem_setMatrix1" qtc_QGraphicsItem_setMatrix1 :: Ptr (TQGraphicsItem a) -> Ptr (TQMatrix t1) -> CBool -> IO ()
instance QsetParentItem (QGraphicsItem a) ((QGraphicsItem t1)) where
setParentItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setParentItem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_setParentItem" qtc_QGraphicsItem_setParentItem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsItem t1) -> IO ()
instance QsetParentItem (QGraphicsItem a) ((QGraphicsTextItem t1)) where
setParentItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setParentItem_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_setParentItem_graphicstextitem" qtc_QGraphicsItem_setParentItem_graphicstextitem :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsTextItem t1) -> IO ()
instance QsetPos (QGraphicsItem a) ((Double, Double)) where
setPos x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setPos1 cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_setPos1" qtc_QGraphicsItem_setPos1 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO ()
instance QsetPos (QGraphicsItem a) ((PointF)) where
setPos x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsItem_setPos_qth cobj_x0 cpointf_x1_x cpointf_x1_y
foreign import ccall "qtc_QGraphicsItem_setPos_qth" qtc_QGraphicsItem_setPos_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO ()
instance QqsetPos (QGraphicsItem a) ((QPointF t1)) where
qsetPos x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setPos cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_setPos" qtc_QGraphicsItem_setPos :: Ptr (TQGraphicsItem a) -> Ptr (TQPointF t1) -> IO ()
instance QsetSelected (QGraphicsItem a) ((Bool)) where
setSelected x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setSelected cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGraphicsItem_setSelected" qtc_QGraphicsItem_setSelected :: Ptr (TQGraphicsItem a) -> CBool -> IO ()
instance QsetToolTip (QGraphicsItem a) ((String)) where
setToolTip x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGraphicsItem_setToolTip cobj_x0 cstr_x1
foreign import ccall "qtc_QGraphicsItem_setToolTip" qtc_QGraphicsItem_setToolTip :: Ptr (TQGraphicsItem a) -> CWString -> IO ()
instance QsetTransform (QGraphicsItem a) ((QTransform t1)) where
setTransform x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setTransform cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_setTransform" qtc_QGraphicsItem_setTransform :: Ptr (TQGraphicsItem a) -> Ptr (TQTransform t1) -> IO ()
instance QsetTransform (QGraphicsItem a) ((QTransform t1, Bool)) where
setTransform x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_setTransform1 cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QGraphicsItem_setTransform1" qtc_QGraphicsItem_setTransform1 :: Ptr (TQGraphicsItem a) -> Ptr (TQTransform t1) -> CBool -> IO ()
instance QsetVisible (QGraphicsItem a) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGraphicsItem_setVisible" qtc_QGraphicsItem_setVisible :: Ptr (TQGraphicsItem a) -> CBool -> IO ()
instance QsetZValue (QGraphicsItem a) ((Double)) where
setZValue x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_setZValue cobj_x0 (toCDouble x1)
foreign import ccall "qtc_QGraphicsItem_setZValue" qtc_QGraphicsItem_setZValue :: Ptr (TQGraphicsItem a) -> CDouble -> IO ()
instance Qshape (QGraphicsItem ()) (()) (IO (QPainterPath ())) where
shape x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_shape_h cobj_x0
foreign import ccall "qtc_QGraphicsItem_shape_h" qtc_QGraphicsItem_shape_h :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQPainterPath ()))
instance Qshape (QGraphicsItemSc a) (()) (IO (QPainterPath ())) where
shape x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_shape_h cobj_x0
instance Qshear (QGraphicsItem a) ((Double, Double)) where
shear x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_shear cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_shear" qtc_QGraphicsItem_shear :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO ()
instance Qqshow (QGraphicsItem a) (()) where
qshow x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_show cobj_x0
foreign import ccall "qtc_QGraphicsItem_show" qtc_QGraphicsItem_show :: Ptr (TQGraphicsItem a) -> IO ()
instance QsupportsExtension (QGraphicsItem ()) ((QGraphicsItemExtension)) where
supportsExtension x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_supportsExtension cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGraphicsItem_supportsExtension" qtc_QGraphicsItem_supportsExtension :: Ptr (TQGraphicsItem a) -> CLong -> IO CBool
instance QsupportsExtension (QGraphicsItemSc a) ((QGraphicsItemExtension)) where
supportsExtension x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_supportsExtension cobj_x0 (toCLong $ qEnum_toInt x1)
instance QtoolTip (QGraphicsItem a) (()) where
toolTip x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_toolTip cobj_x0
foreign import ccall "qtc_QGraphicsItem_toolTip" qtc_QGraphicsItem_toolTip :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQString ()))
instance QtopLevelItem (QGraphicsItem a) (()) (IO (QGraphicsItem ())) where
topLevelItem x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_topLevelItem cobj_x0
foreign import ccall "qtc_QGraphicsItem_topLevelItem" qtc_QGraphicsItem_topLevelItem :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQGraphicsItem ()))
instance Qtransform (QGraphicsItem a) (()) where
transform x0 ()
= withQTransformResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_transform cobj_x0
foreign import ccall "qtc_QGraphicsItem_transform" qtc_QGraphicsItem_transform :: Ptr (TQGraphicsItem a) -> IO (Ptr (TQTransform ()))
instance Qqtranslate (QGraphicsItem a) ((Double, Double)) (IO ()) where
qtranslate x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_translate cobj_x0 (toCDouble x1) (toCDouble x2)
foreign import ccall "qtc_QGraphicsItem_translate" qtc_QGraphicsItem_translate :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> IO ()
instance Qqtype (QGraphicsItem ()) (()) (IO (Int)) where
qtype x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_type_h cobj_x0
foreign import ccall "qtc_QGraphicsItem_type_h" qtc_QGraphicsItem_type_h :: Ptr (TQGraphicsItem a) -> IO CInt
instance Qqtype (QGraphicsItemSc a) (()) (IO (Int)) where
qtype x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_type_h cobj_x0
instance QunsetCursor (QGraphicsItem a) (()) where
unsetCursor x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_unsetCursor cobj_x0
foreign import ccall "qtc_QGraphicsItem_unsetCursor" qtc_QGraphicsItem_unsetCursor :: Ptr (TQGraphicsItem a) -> IO ()
instance Qupdate (QGraphicsItem a) (()) where
update x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_update cobj_x0
foreign import ccall "qtc_QGraphicsItem_update" qtc_QGraphicsItem_update :: Ptr (TQGraphicsItem a) -> IO ()
instance Qupdate (QGraphicsItem a) ((Double, Double, Double, Double)) where
update x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_update2 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) (toCDouble x4)
foreign import ccall "qtc_QGraphicsItem_update2" qtc_QGraphicsItem_update2 :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO ()
instance Qqupdate (QGraphicsItem a) ((QRectF t1)) where
qupdate x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_update1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_update1" qtc_QGraphicsItem_update1 :: Ptr (TQGraphicsItem a) -> Ptr (TQRectF t1) -> IO ()
instance Qupdate (QGraphicsItem a) ((RectF)) where
update x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRectF x1 $ \crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h ->
qtc_QGraphicsItem_update1_qth cobj_x0 crectf_x1_x crectf_x1_y crectf_x1_w crectf_x1_h
foreign import ccall "qtc_QGraphicsItem_update1_qth" qtc_QGraphicsItem_update1_qth :: Ptr (TQGraphicsItem a) -> CDouble -> CDouble -> CDouble -> CDouble -> IO ()
instance QwheelEvent (QGraphicsItem ()) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_wheelEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItem_wheelEvent_h" qtc_QGraphicsItem_wheelEvent_h :: Ptr (TQGraphicsItem a) -> Ptr (TQGraphicsSceneWheelEvent t1) -> IO ()
instance QwheelEvent (QGraphicsItemSc a) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItem_wheelEvent_h cobj_x0 cobj_x1
instance Qqx (QGraphicsItem a) (()) (IO (Double)) where
qx x0 ()
= withDoubleResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_x cobj_x0
foreign import ccall "qtc_QGraphicsItem_x" qtc_QGraphicsItem_x :: Ptr (TQGraphicsItem a) -> IO CDouble
instance Qqy (QGraphicsItem a) (()) (IO (Double)) where
qy x0 ()
= withDoubleResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_y cobj_x0
foreign import ccall "qtc_QGraphicsItem_y" qtc_QGraphicsItem_y :: Ptr (TQGraphicsItem a) -> IO CDouble
instance QzValue (QGraphicsItem a) (()) where
zValue x0 ()
= withDoubleResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_zValue cobj_x0
foreign import ccall "qtc_QGraphicsItem_zValue" qtc_QGraphicsItem_zValue :: Ptr (TQGraphicsItem a) -> IO CDouble
qGraphicsItem_delete :: QGraphicsItem a -> IO ()
qGraphicsItem_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_delete cobj_x0
foreign import ccall "qtc_QGraphicsItem_delete" qtc_QGraphicsItem_delete :: Ptr (TQGraphicsItem a) -> IO ()
qGraphicsItem_delete1 :: QGraphicsItem a -> IO ()
qGraphicsItem_delete1 x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItem_delete1 cobj_x0
foreign import ccall "qtc_QGraphicsItem_delete1" qtc_QGraphicsItem_delete1 :: Ptr (TQGraphicsItem a) -> IO ()
|
uduki/hsQt
|
Qtc/Gui/QGraphicsItem.hs
|
bsd-2-clause
| 106,074 | 0 | 17 | 15,737 | 32,754 | 16,584 | 16,170 | -1 | -1 |
module Main where
import Crypto.Classes
import Crypto.Hash.Ed2k
import Crypto.Types (BitLength)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as L
import Data.Int (Int64)
import Data.Tagged
import Test.Framework (defaultMain, testGroup, Test)
import Test.Framework.Providers.HUnit
import Test.HUnit hiding (Test)
import Text.Printf (printf)
ed2kBlockLength :: Int64
ed2kBlockLength = let bits = untag (blockLength :: Tagged Ed2k BitLength) in fromIntegral $ bits `div` 8
toHex :: Ed2k -> String
toHex d = concatMap (printf "%02x") (B.unpack $ encode $ d)
main :: IO ()
main = defaultMain tests
tests :: [Test]
tests = [testGroup "Hashing tests" [
testCase "Block length" $
9728000 @=? ed2kBlockLength,
testCase "No data (lazy)" $
"31d6cfe0d16ae931b73c59d7e0c089c0" @=? (toHex $ hash L.empty),
testCase "No data (strict)" $
"31d6cfe0d16ae931b73c59d7e0c089c0" @=? (toHex $ hash' B.empty),
testCase "Short text (lazy)" $
"1bee69a46ba811185c194762abaeae90" @=? (toHex $ hash (L.pack "The quick brown fox jumps over the lazy dog")),
testCase "Short text (strict)" $
"1bee69a46ba811185c194762abaeae90" @=? (toHex $ hash' (B.pack "The quick brown fox jumps over the lazy dog")),
testCase "Single block, zeroes (lazy)" $
"d7def262a127cd79096a108e7a9fc138" @=? (toHex $ hash (L.replicate ed2kBlockLength '\0')),
testCase "Single block, zeroes (strict)" $
"d7def262a127cd79096a108e7a9fc138" @=? (toHex $ hash' (B.replicate (fromIntegral ed2kBlockLength) '\0')),
testCase "Two blocks, zeroes (lazy)" $
"194ee9e4fa79b2ee9f8829284c466051" @=? (toHex $ hash (L.replicate (2 * ed2kBlockLength) '\0')),
testCase "Two blocks, zeroes (strict)" $
"194ee9e4fa79b2ee9f8829284c466051" @=? (toHex $ hash' (B.replicate (2 * (fromIntegral ed2kBlockLength)) '\0'))]]
|
nullref/haskell-hash-ed2k
|
Test/Ed2k.hs
|
bsd-2-clause
| 1,991 | 0 | 17 | 431 | 520 | 281 | 239 | 38 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Game.GameChase where
import Control.Lens (use, (^.), (.=), zoom, ix, preuse, (%=), (&), (+~), (%~))
import Control.Monad (unless, liftM)
import Data.Bits ((.&.), complement)
import Linear (_x, _z, normalize)
import {-# SOURCE #-} Game.GameImportT
import Game.CVarT
import Game.GameLocalsT
import Game.PMoveT
import Game.EntityStateT
import Game.EdictT
import Game.PlayerStateT
import Game.GClientT
import Game.ClientRespawnT
import Types
import Game.PMoveStateT
import QuakeState
import QuakeRef
import CVarVariables
import qualified Util.Math3D as Math3D
getChaseTarget :: Ref EdictT -> Quake ()
getChaseTarget edictRef = do
maxClientsValue <- liftM (^.cvValue) maxClientsCVar
done <- findChaseTarget 1 (truncate maxClientsValue)
unless done $ do
centerPrintf <- use $ gameBaseGlobals.gbGameImport.giCenterPrintf
centerPrintf edictRef "No other players to chase."
where findChaseTarget :: Int -> Int -> Quake Bool
findChaseTarget idx maxIdx
| idx > maxIdx = return False
| otherwise = do
let otherRef = Ref idx
other <- readRef otherRef
let Just (Ref gClientIdx) = other^.eClient
Just gClient <- preuse $ gameBaseGlobals.gbGame.glClients.ix gClientIdx
if (other^.eInUse) && not (gClient^.gcResp.crSpectator)
then do
zoom (gameBaseGlobals.gbGame.glClients.ix gClientIdx) $ do
gcChaseTarget .= Just otherRef
gcUpdateChase .= True
updateChaseCam edictRef
return True
else
findChaseTarget (idx + 1) maxIdx
updateChaseCam :: Ref EdictT -> Quake ()
updateChaseCam edictRef = do
edict <- readRef edictRef
let Just gClientRef@(Ref gClientIdx) = edict^.eClient
-- is our chase target gone?
gone <- isChaseTargetGone gClientRef
unless gone $ do
Just gClient <- preuse $ gameBaseGlobals.gbGame.glClients.ix gClientIdx
let Just targRef = gClient^.gcChaseTarget
targ <- readRef targRef
let Just (Ref targClientIdx) = targ^.eClient
Just targClient <- preuse $ gameBaseGlobals.gbGame.glClients.ix targClientIdx
let ownerV = (targ^.eEntityState.esOrigin) & _z +~ fromIntegral (targ^.eViewHeight)
oldGoal = edict^.eEntityState.esOrigin
angles = (targClient^.gcVAngle) & _x %~ (\v -> if v > 56 then 56 else v) -- IMPROVE: use Constants.pitch instead of _x directly
(Just fwrd, Just right, _) = Math3D.angleVectors angles True True False
forward = normalize fwrd
o = ownerV + fmap (* (-30)) forward
io (putStrLn "GameChase.updateChaseCam") >> undefined -- TODO
where isChaseTargetGone :: Ref GClientT -> Quake Bool
isChaseTargetGone (Ref gClientIdx) = do
Just gClient <- preuse $ gameBaseGlobals.gbGame.glClients.ix gClientIdx
let Just chaseTargetRef = gClient^.gcChaseTarget
chaseTarget <- readRef chaseTargetRef
let Just (Ref chaseTargetClientIdx) = chaseTarget^.eClient
Just chaseTargetClient <- preuse $ gameBaseGlobals.gbGame.glClients.ix gClientIdx
if not (chaseTarget^.eInUse) || (chaseTargetClient^.gcResp.crSpectator)
then do
let oldRef = chaseTargetRef
chaseNext edictRef
Just gClient' <- preuse $ gameBaseGlobals.gbGame.glClients.ix gClientIdx
if (gClient'^.gcChaseTarget) == Just oldRef
then do
zoom (gameBaseGlobals.gbGame.glClients.ix gClientIdx) $ do
gcChaseTarget .= Nothing
gcPlayerState.psPMoveState.pmsPMFlags %= (.&. (complement pmfNoPrediction))
return True
else
return False
else
return False
chaseNext :: Ref EdictT -> Quake ()
chaseNext _ = do
io (putStrLn "GameChase.chaseNext") >> undefined -- TODO
|
ksaveljev/hake-2
|
src/Game/GameChase.hs
|
bsd-3-clause
| 4,042 | 0 | 21 | 1,111 | 1,150 | 570 | 580 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Actions.DynamicWorkspaces
-- Copyright : (c) David Roundy <[email protected]>
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : none
-- Stability : unstable
-- Portability : unportable
--
-- Provides bindings to add and delete workspaces.
--
-----------------------------------------------------------------------------
module XMonad.Actions.DynamicWorkspaces (
-- * Usage
-- $usage
addWorkspace, addWorkspacePrompt,
removeWorkspace,
removeEmptyWorkspace,
removeEmptyWorkspaceAfter,
removeEmptyWorkspaceAfterExcept,
addHiddenWorkspace,
withWorkspace,
selectWorkspace, renameWorkspace,
renameWorkspaceByName,
toNthWorkspace, withNthWorkspace
) where
import XMonad hiding (workspaces)
import XMonad.StackSet hiding (filter, modify, delete)
import XMonad.Prompt.Workspace ( Wor(Wor), workspacePrompt )
import XMonad.Prompt ( XPConfig, mkXPrompt )
import XMonad.Util.WorkspaceCompare ( getSortByIndex )
import Data.List (find)
import Data.Maybe (isNothing)
import Control.Monad (when)
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@ file:
--
-- > import XMonad.Actions.DynamicWorkspaces
-- > import XMonad.Actions.CopyWindow(copy)
--
-- Then add keybindings like the following:
--
-- > , ((modm .|. shiftMask, xK_BackSpace), removeWorkspace)
-- > , ((modm .|. shiftMask, xK_v ), selectWorkspace defaultXPConfig)
-- > , ((modm, xK_m ), withWorkspace defaultXPConfig (windows . W.shift))
-- > , ((modm .|. shiftMask, xK_m ), withWorkspace defaultXPConfig (windows . copy))
-- > , ((modm .|. shiftMask, xK_r ), renameWorkspace defaultXPConfig)
--
-- > -- mod-[1..9] %! Switch to workspace N
-- > -- mod-shift-[1..9] %! Move client to workspace N
-- > ++
-- > zip (zip (repeat (modm)) [xK_1..xK_9]) (map (withNthWorkspace W.greedyView) [0..])
-- > ++
-- > zip (zip (repeat (modm .|. shiftMask)) [xK_1..xK_9]) (map (withNthWorkspace W.shift) [0..])
--
-- For detailed instructions on editing your key bindings, see
-- "XMonad.Doc.Extending#Editing_key_bindings". See also the documentation for
-- "XMonad.Actions.CopyWindow", 'windows', 'shift', and 'defaultXPConfig'.
mkCompl :: [String] -> String -> IO [String]
mkCompl l s = return $ filter (\x -> take (length s) x == s) l
withWorkspace :: XPConfig -> (String -> X ()) -> X ()
withWorkspace c job = do ws <- gets (workspaces . windowset)
sort <- getSortByIndex
let ts = map tag $ sort ws
job' t | t `elem` ts = job t
| otherwise = addHiddenWorkspace t >> job t
mkXPrompt (Wor "") c (mkCompl ts) job'
renameWorkspace :: XPConfig -> X ()
renameWorkspace conf = workspacePrompt conf renameWorkspaceByName
renameWorkspaceByName :: String -> X ()
renameWorkspaceByName w = windows $ \s -> let sett wk = wk { tag = w }
setscr scr = scr { workspace = sett $ workspace scr }
sets q = q { current = setscr $ current q }
in sets $ removeWorkspace' w s
toNthWorkspace :: (String -> X ()) -> Int -> X ()
toNthWorkspace job wnum = do sort <- getSortByIndex
ws <- gets (map tag . sort . workspaces . windowset)
case drop wnum ws of
(w:_) -> job w
[] -> return ()
withNthWorkspace :: (String -> WindowSet -> WindowSet) -> Int -> X ()
withNthWorkspace job wnum = do sort <- getSortByIndex
ws <- gets (map tag . sort . workspaces . windowset)
case drop wnum ws of
(w:_) -> windows $ job w
[] -> return ()
selectWorkspace :: XPConfig -> X ()
selectWorkspace conf = workspacePrompt conf $ \w ->
do s <- gets windowset
if tagMember w s
then windows $ greedyView w
else addWorkspace w
-- | Add a new workspace with the given name, or do nothing if a
-- workspace with the given name already exists; then switch to the
-- newly created workspace.
addWorkspace :: String -> X ()
addWorkspace newtag = addHiddenWorkspace newtag >> windows (greedyView newtag)
-- | Prompt for the name of a new workspace, add it if it does not
-- already exist, and switch to it.
addWorkspacePrompt :: XPConfig -> X ()
addWorkspacePrompt conf = mkXPrompt (Wor "New workspace name: ") conf (const (return [])) addWorkspace
-- | Add a new hidden workspace with the given name, or do nothing if
-- a workspace with the given name already exists.
addHiddenWorkspace :: String -> X ()
addHiddenWorkspace newtag =
whenX (gets (not . tagMember newtag . windowset)) $ do
l <- asks (layoutHook . config)
windows (addHiddenWorkspace' newtag l)
-- | Remove the current workspace if it contains no windows.
removeEmptyWorkspace :: X ()
removeEmptyWorkspace = gets (currentTag . windowset) >>= removeEmptyWorkspaceByTag
-- | Remove the current workspace.
removeWorkspace :: X ()
removeWorkspace = gets (currentTag . windowset) >>= removeWorkspaceByTag
-- | Remove workspace with specific tag if it contains no windows. Only works
-- on the current or the last workspace.
removeEmptyWorkspaceByTag :: String -> X ()
removeEmptyWorkspaceByTag t = whenX (isEmpty t) $ removeWorkspaceByTag t
-- | Remove workspace with specific tag. Only works on the current or the last workspace.
removeWorkspaceByTag :: String -> X ()
removeWorkspaceByTag torem = do
s <- gets windowset
case s of
StackSet { current = Screen { workspace = cur }, hidden = (w:_) } -> do
when (torem==tag cur) $ windows $ view $ tag w
windows $ removeWorkspace' torem
_ -> return ()
-- | Remove the current workspace after an operation if it is empty and hidden.
-- Can be used to remove a workspace if it is empty when leaving it. The
-- operation may only change workspace once, otherwise the workspace will not
-- be removed.
removeEmptyWorkspaceAfter :: X () -> X ()
removeEmptyWorkspaceAfter = removeEmptyWorkspaceAfterExcept []
-- | Like 'removeEmptyWorkspaceAfter' but use a list of sticky workspaces,
-- whose entries will never be removed.
removeEmptyWorkspaceAfterExcept :: [String] -> X () -> X ()
removeEmptyWorkspaceAfterExcept sticky f = do
before <- gets (currentTag . windowset)
f
after <- gets (currentTag . windowset)
when (before/=after && before `notElem` sticky) $ removeEmptyWorkspaceByTag before
isEmpty :: String -> X Bool
isEmpty t = do wsl <- gets $ workspaces . windowset
let mws = find (\ws -> tag ws == t) wsl
return $ maybe True (isNothing . stack) mws
addHiddenWorkspace' :: i -> l -> StackSet i l a sid sd -> StackSet i l a sid sd
addHiddenWorkspace' newtag l s@(StackSet { hidden = ws }) = s { hidden = Workspace newtag l Nothing:ws }
removeWorkspace' :: (Eq i) => i -> StackSet i l a sid sd -> StackSet i l a sid sd
removeWorkspace' torem s@(StackSet { current = scr@(Screen { workspace = wc })
, hidden = (w:ws) })
| tag w == torem = s { current = scr { workspace = wc { stack = meld (stack w) (stack wc) } }
, hidden = ws }
where meld Nothing Nothing = Nothing
meld x Nothing = x
meld Nothing x = x
meld (Just x) (Just y) = differentiate (integrate x ++ integrate y)
removeWorkspace' _ s = s
|
markus1189/xmonad-contrib-710
|
XMonad/Actions/DynamicWorkspaces.hs
|
bsd-3-clause
| 8,317 | 0 | 18 | 2,587 | 1,788 | 930 | 858 | 100 | 4 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
#if __GLASGOW_HASKELL__ >= 800
{-# OPTIONS_GHC -Wno-redundant-constraints #-}
#endif
-- | Execute commands within the properly configured Stack
-- environment.
module Stack.Exec where
import Control.Monad.IO.Unlift
import Control.Monad.Logger
import Stack.Types.Config
import System.Process.Log
import Data.Streaming.Process (ProcessExitedUnsuccessfully(..))
import System.Exit
import System.Process.Run (callProcess, callProcessObserveStdout, Cmd(..))
#ifdef WINDOWS
import System.Process.Read (EnvOverride)
#else
import qualified System.Process.PID1 as PID1
import System.Process.Read (EnvOverride, envHelper, preProcess)
#endif
-- | Default @EnvSettings@ which includes locals and GHC_PACKAGE_PATH
defaultEnvSettings :: EnvSettings
defaultEnvSettings = EnvSettings
{ esIncludeLocals = True
, esIncludeGhcPackagePath = True
, esStackExe = True
, esLocaleUtf8 = False
}
-- | Environment settings which do not embellish the environment
plainEnvSettings :: EnvSettings
plainEnvSettings = EnvSettings
{ esIncludeLocals = False
, esIncludeGhcPackagePath = False
, esStackExe = False
, esLocaleUtf8 = False
}
-- | Execute a process within the Stack configured environment.
--
-- Execution will not return, because either:
--
-- 1) On non-windows, execution is taken over by execv of the
-- sub-process. This allows signals to be propagated (#527)
--
-- 2) On windows, an 'ExitCode' exception will be thrown.
exec :: (MonadUnliftIO m, MonadLogger m)
=> EnvOverride -> String -> [String] -> m b
#ifdef WINDOWS
exec = execSpawn
#else
exec menv cmd0 args = do
cmd <- preProcess Nothing menv cmd0
$withProcessTimeLog cmd args $
liftIO $ PID1.run cmd args (envHelper menv)
#endif
-- | Like 'exec', but does not use 'execv' on non-windows. This way, there
-- is a sub-process, which is helpful in some cases (#1306)
--
-- This function only exits by throwing 'ExitCode'.
execSpawn :: (MonadUnliftIO m, MonadLogger m)
=> EnvOverride -> String -> [String] -> m b
execSpawn menv cmd0 args = do
e <- $withProcessTimeLog cmd0 args $
try (callProcess (Cmd Nothing cmd0 menv args))
liftIO $ case e of
Left (ProcessExitedUnsuccessfully _ ec) -> exitWith ec
Right () -> exitSuccess
execObserve :: (MonadUnliftIO m, MonadLogger m)
=> EnvOverride -> String -> [String] -> m String
execObserve menv cmd0 args = do
e <- $withProcessTimeLog cmd0 args $
try (callProcessObserveStdout (Cmd Nothing cmd0 menv args))
case e of
Left (ProcessExitedUnsuccessfully _ ec) -> liftIO $ exitWith ec
Right s -> return s
|
martin-kolinek/stack
|
src/Stack/Exec.hs
|
bsd-3-clause
| 2,839 | 0 | 13 | 604 | 488 | 277 | 211 | 48 | 2 |
{-# language CPP #-}
-- | = Name
--
-- VK_EXT_global_priority - device extension
--
-- == VK_EXT_global_priority
--
-- [__Name String__]
-- @VK_EXT_global_priority@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
-- 175
--
-- [__Revision__]
-- 2
--
-- [__Extension and Version Dependencies__]
--
-- - Requires Vulkan 1.0
--
-- [__Deprecation state__]
--
-- - /Promoted/ to @VK_KHR_global_priority@ extension
--
-- [__Contact__]
--
-- - Andres Rodriguez
-- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_global_priority] @lostgoat%0A<<Here describe the issue or question you have about the VK_EXT_global_priority extension>> >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
-- 2017-10-06
--
-- [__IP Status__]
-- No known IP claims.
--
-- [__Contributors__]
--
-- - Andres Rodriguez, Valve
--
-- - Pierre-Loup Griffais, Valve
--
-- - Dan Ginsburg, Valve
--
-- - Mitch Singer, AMD
--
-- == Description
--
-- In Vulkan, users can specify device-scope queue priorities. In some
-- cases it may be useful to extend this concept to a system-wide scope.
-- This extension provides a mechanism for callers to set their system-wide
-- priority. The default queue priority is
-- 'Vulkan.Extensions.VK_KHR_global_priority.QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT'.
--
-- The driver implementation will attempt to skew hardware resource
-- allocation in favour of the higher-priority task. Therefore,
-- higher-priority work may retain similar latency and throughput
-- characteristics even if the system is congested with lower priority
-- work.
--
-- The global priority level of a queue shall take precedence over the
-- per-process queue priority
-- ('Vulkan.Core10.Device.DeviceQueueCreateInfo'::@pQueuePriorities@).
--
-- Abuse of this feature may result in starving the rest of the system from
-- hardware resources. Therefore, the driver implementation may deny
-- requests to acquire a priority above the default priority
-- ('Vulkan.Extensions.VK_KHR_global_priority.QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT')
-- if the caller does not have sufficient privileges. In this scenario
-- 'ERROR_NOT_PERMITTED_EXT' is returned.
--
-- The driver implementation may fail the queue allocation request if
-- resources required to complete the operation have been exhausted (either
-- by the same process or a different process). In this scenario
-- 'Vulkan.Core10.Enums.Result.ERROR_INITIALIZATION_FAILED' is returned.
--
-- == New Structures
--
-- - Extending 'Vulkan.Core10.Device.DeviceQueueCreateInfo':
--
-- - 'DeviceQueueGlobalPriorityCreateInfoEXT'
--
-- == New Enums
--
-- - 'QueueGlobalPriorityEXT'
--
-- == New Enum Constants
--
-- - 'EXT_GLOBAL_PRIORITY_EXTENSION_NAME'
--
-- - 'EXT_GLOBAL_PRIORITY_SPEC_VERSION'
--
-- - Extending 'Vulkan.Core10.Enums.Result.Result':
--
-- - 'ERROR_NOT_PERMITTED_EXT'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT'
--
-- == Version History
--
-- - Revision 2, 2017-11-03 (Andres Rodriguez)
--
-- - Fixed VkQueueGlobalPriorityEXT missing _EXT suffix
--
-- - Revision 1, 2017-10-06 (Andres Rodriguez)
--
-- - First version.
--
-- == See Also
--
-- 'DeviceQueueGlobalPriorityCreateInfoEXT', 'QueueGlobalPriorityEXT'
--
-- == Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_EXT_global_priority Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_EXT_global_priority ( pattern STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT
, pattern ERROR_NOT_PERMITTED_EXT
, QueueGlobalPriorityEXT
, DeviceQueueGlobalPriorityCreateInfoEXT
, EXT_GLOBAL_PRIORITY_SPEC_VERSION
, pattern EXT_GLOBAL_PRIORITY_SPEC_VERSION
, EXT_GLOBAL_PRIORITY_EXTENSION_NAME
, pattern EXT_GLOBAL_PRIORITY_EXTENSION_NAME
, DeviceQueueGlobalPriorityCreateInfoKHR(..)
, QueueGlobalPriorityKHR(..)
) where
import Data.String (IsString)
import Vulkan.Extensions.VK_KHR_global_priority (DeviceQueueGlobalPriorityCreateInfoKHR)
import Vulkan.Extensions.VK_KHR_global_priority (QueueGlobalPriorityKHR)
import Vulkan.Core10.Enums.Result (Result(ERROR_NOT_PERMITTED_KHR))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_KHR))
import Vulkan.Extensions.VK_KHR_global_priority (DeviceQueueGlobalPriorityCreateInfoKHR(..))
import Vulkan.Extensions.VK_KHR_global_priority (QueueGlobalPriorityKHR(..))
-- No documentation found for TopLevel "VK_STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT"
pattern STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT = STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_KHR
-- No documentation found for TopLevel "VK_ERROR_NOT_PERMITTED_EXT"
pattern ERROR_NOT_PERMITTED_EXT = ERROR_NOT_PERMITTED_KHR
-- No documentation found for TopLevel "VkQueueGlobalPriorityEXT"
type QueueGlobalPriorityEXT = QueueGlobalPriorityKHR
-- No documentation found for TopLevel "VkDeviceQueueGlobalPriorityCreateInfoEXT"
type DeviceQueueGlobalPriorityCreateInfoEXT = DeviceQueueGlobalPriorityCreateInfoKHR
type EXT_GLOBAL_PRIORITY_SPEC_VERSION = 2
-- No documentation found for TopLevel "VK_EXT_GLOBAL_PRIORITY_SPEC_VERSION"
pattern EXT_GLOBAL_PRIORITY_SPEC_VERSION :: forall a . Integral a => a
pattern EXT_GLOBAL_PRIORITY_SPEC_VERSION = 2
type EXT_GLOBAL_PRIORITY_EXTENSION_NAME = "VK_EXT_global_priority"
-- No documentation found for TopLevel "VK_EXT_GLOBAL_PRIORITY_EXTENSION_NAME"
pattern EXT_GLOBAL_PRIORITY_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern EXT_GLOBAL_PRIORITY_EXTENSION_NAME = "VK_EXT_global_priority"
|
expipiplus1/vulkan
|
src/Vulkan/Extensions/VK_EXT_global_priority.hs
|
bsd-3-clause
| 6,417 | 0 | 8 | 1,248 | 382 | 286 | 96 | -1 | -1 |
{-# LANGUAGE DeriveGeneric #-}
module Crawl.Stats.Shield where
import qualified Data.Csv as CSV
import GHC.Generics (Generic)
import qualified Data.Default as Default
import qualified Crawl.Stats.Named as Named
data Shield = Shield {
name :: String,
block :: Integer,
evPenalty :: Integer,
dexContrib :: Integer,
strContrib :: Integer
} deriving (Generic, Eq)
instance CSV.FromNamedRecord Shield
instance Named.Named Shield where
name = name
instance Default.Default Shield where
def = Shield "none" 0 0 0 0
|
jfrikker/crawlstats
|
src/Crawl/Stats/Shield.hs
|
bsd-3-clause
| 529 | 0 | 8 | 92 | 143 | 87 | 56 | 18 | 0 |
-- Config.hs
{-# OPTIONS_GHC -Wall #-}
module Lab2.Config( cL
, cN
, hilbertDim
, imageSize
) where
hilbertDim :: Int
hilbertDim = 16 -- for max value of 65535
cL, cN :: Int
cL = 3
cN = 4
imageSize :: Num a => a
imageSize = 500
|
ghorn/cs240h-class
|
Lab2/Config.hs
|
bsd-3-clause
| 305 | 0 | 6 | 125 | 67 | 42 | 25 | 12 | 1 |
module Data.Wavelets.ReconstructionSpec (main, spec) where
import Test.Hspec
import Data.Wavelets.Reconstruction
import Data.Wavelets
import System.IO
import qualified Data.Vector.Storable as V
{-| The test waveletData below was transformed into several of the result dataFiles |-}
-- 3 sinusoids added together to make an interesting data set that is easy to understand
testWaveletData :: [Double]
testWaveletData = [ ((sin (pi*t*2))+ (sin (pi * t * 2.1) + (sin (pi * t * 2.002))))* 12 | t <- [1 .. 1000] ]
impulse = replicate 499 1
++ replicate 1 100
++ replicate 500 1
impulseAvg = (1.3956047904191924)
waveletHaar_packer_separate_testStub :: IO [[Double]]
waveletHaar_packer_separate_testStub = do
(read `fmap` readFile "./test/Data/haar_separate.tst" )
testWaveletHaar_PackerSeparate = dwt 12 haar wp_separate impulse
compareWaveletHaarResults = do
let rslt = testWaveletHaar_PackerSeparate
ctrl <- waveletHaar_packer_separate_testStub
return $ (length rslt ) == (length ctrl)
testReconstructTimeSeries = reconstructTimeSeries (12-n) haar wp_separate $ drop n testWaveletHaar_PackerSeparate
where n = 3
main :: IO ()
main = do
haar_separate_test_data <- waveletHaar_packer_separate_testStub
hspec $ spec
-- | Have to bring in test data from a file to test this
spec :: Spec
spec = do
describe "reconstructTimeSeries" $ do
it "shouldReturn a scaled wavelet" $ do
let tstData = testWaveletData
tst <- compareWaveletHaarResults
tst `shouldBe` True
|
smurphy8/wavelets
|
test/Data/Wavelets/ReconstructionSpec.hs
|
bsd-3-clause
| 1,533 | 0 | 15 | 281 | 391 | 209 | 182 | 33 | 1 |
{-# LANGUAGE RankNTypes #-}
module Parser (parseTerm) where
import Syntax
import Text.Parsec hiding(State)
import Text.Parsec.String
import qualified Text.Parsec.Token as P
import Text.Parsec.Language
import Data.Char
import Control.Monad
import Control.Applicative((<*))
{- --------------------------------------------------------
インデックスを付けるための機構
-------------------------------------------------------- -}
data Context = Ctx {
depth :: Int,
binding :: [(Char, Int)],
tyDepth :: Int,
tyBinding :: [(Char, Int)]
}
updateCtx :: Context -> Char -> Context
updateCtx (Ctx d b tyD tyB) c = (Ctx (d+1) ((c, d):b) tyD tyB)
updateTyCtx :: Context -> Char -> Context
updateTyCtx (Ctx d b tyD tyB) c = (Ctx d b (tyD+1) ((c, tyD):tyB))
freeVar :: Char -> Int
freeVar c = (ord c) - (ord 'a')
freshTyVar :: Char -> Int
freshTyVar c = (ord c) - (ord 'A')
{- 外側から小さい値を使う de Bruijin レベルを使う.
束縛変数ならばそのまま値を返してよく,
自由変数ならば深さの分だけシフトしてインデックスとする.-}
index :: Context -> Char -> Int
index (Ctx depth bind _ _) v =
case lookup v bind of
Just d -> d
Nothing -> depth + freeVar v
tyIndex :: Context -> Char -> Int
tyIndex (Ctx _ _ depth bind) v =
case lookup v bind of
Just d -> d
Nothing -> depth + freshTyVar v
{- --------------------------------------------------------
パーサー
-------------------------------------------------------- -}
parseTerm :: String -> Check Term
parseTerm input =
case parse (term $ Ctx 0 [] 0 []) "" input of
Left er -> Left $ show er
Right r -> Right r
def :: LanguageDef st
def = emptyDef {
P.opLetter = oneOf "\\:->",
P.reservedOpNames = ["\\", ":", "->"],
P.reservedNames = ["if", "then", "else", "true", "false", "Bool"]
}
lexer :: P.TokenParser st
lexer = P.makeTokenParser def
operator :: Parser String
operator = P.operator lexer
identifier :: Parser String
identifier = P.identifier lexer
var :: Parser Char
var = do
i <- identifier
if length i == 1 && head i `elem` ['a'..'z']
then return $ head i
else fail "variable must be one lower character"
tyVar :: Parser Char
tyVar = do
i <- identifier
if length i == 1 && head i `elem` ['A'..'Z']
then return $ head i
else fail "variable must be one upper character"
reservedOp :: String -> Parser ()
reservedOp = P.reservedOp lexer
parens :: forall a. Parser a -> Parser a
parens = P.parens lexer
brackets :: forall a. Parser a -> Parser a
brackets = P.brackets lexer
braces :: forall a. Parser a -> Parser a
braces = P.braces lexer
whiteSpace :: Parser ()
whiteSpace = P.whiteSpace lexer
symbol :: String -> Parser String
symbol = P.symbol lexer
term :: Context -> Parser Term
term c = do
whiteSpace
t <- termBody c
eof >> (return t)
termBody :: Context -> Parser Term
termBody c = try (abst c)
<|> try (tyAbst c)
<|> try (generalApp c)
<|> termif c
generalApp :: Context -> Parser Term
generalApp c = unit c >>= appChain c
appChain :: Context -> Term -> Parser Term
appChain c t = try (do t' <- unit c
appChain c (TmApp t t'))
<|> try (do t' <- brackets (tyAnnot c)
appChain c (TmTyApp t t'))
<|> return t
abst :: Context -> Parser Term
abst c = do
a <- (reservedOp "\\") >> var
ty <- optionMaybe (reservedOp ":" >> tyAnnot c)
t <- termBody (updateCtx c a)
case ty of Just ty' -> return $ TmAbs a ty' t
Nothing -> fail "annotate type"
unit :: Context -> Parser Term
unit c = try (liftM2 (foldl TmProj) (unit_rec c) (many $ symbol "." >> identifier))
<|> unit_rec c
unit_rec :: Context -> Parser Term
unit_rec c = parens (termBody c)
<|> try (liftM TmRcd (braces $ record c `sepBy1` symbol ","))
<|> try (symbol "true" >> return TmTrue)
<|> try (symbol "false" >> return TmFalse)
<|> do a <- var
return $ TmVar (index c a) a
record :: Context -> Parser (String, Term)
record c = liftM2 (,) (identifier <* symbol "=") (termBody c)
termif :: Context -> Parser Term
termif c = do
p <- try (symbol "if") >> termBody c
t <- try (symbol "then") >> termBody c
f <- try (symbol "else") >> termBody c
return $ TmIf p t f
tyAnnot :: Context -> Parser TyTerm
tyAnnot c = tyunit c `chainl1` (reservedOp "->" >> return TyArr)
tyunit :: Context -> Parser TyTerm
tyunit c = try (symbol "Bool" >> return TyBool)
<|> try (symbol "Top" >> return TyTop)
<|> try (parens $ tyAnnot c)
<|> try (liftM TyRcd (braces $ tyRecord c `sepBy1` symbol ","))
<|> do v <- tyVar
return $ TyVar v (tyIndex c v)
tyRecord :: Context -> Parser (String, TyTerm)
tyRecord c = liftM2 (,) (identifier <* symbol ":") (tyAnnot c)
tyAbst :: Context -> Parser Term
tyAbst c = do
v <- (reservedOp "\\") >> tyVar
t <- termBody (updateTyCtx c v)
return $ TmTyAbs v t
|
yu-i9/SystemF
|
parser/Parser.hs
|
bsd-3-clause
| 5,199 | 0 | 15 | 1,352 | 1,958 | 979 | 979 | 132 | 2 |
module Tests.Regress
( testTree -- :: TestTree
) where
import Test.Tasty
import qualified Tests.Regress.Issue13 as Issue13
import qualified Tests.Regress.FlatTerm as FlatTerm
--------------------------------------------------------------------------------
-- Tests and properties
testTree :: TestTree
testTree = testGroup "Regression tests"
[ FlatTerm.testTree
, Issue13.testTree
]
|
arianvp/binary-serialise-cbor
|
tests/Tests/Regress.hs
|
bsd-3-clause
| 407 | 0 | 7 | 64 | 62 | 41 | 21 | 9 | 1 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
module Web.Zwaluw (
-- * Types
Router, (:-)(..), (<>), (.~)
-- * Running routers
, parse, unparse
, parse1, unparse1
-- * Router combinators
, pure, xmap, xmaph
, val, readshow, lit, push
, opt, duck, satisfy, rFilter, printAs
, manyr, somer, chainr, chainr1
, manyl, somel, chainl, chainl1
-- * Built-in routers
, int, integer, string, char, digit, hexDigit
, (/), part
, rNil, rCons, rList, rListSep
, rPair
, rLeft, rRight, rEither
, rNothing, rJust, rMaybe
, rTrue, rFalse
) where
import Prelude hiding ((.), id, (/))
import Control.Monad (guard)
import Control.Category
import Data.Monoid
import Data.Char (isDigit, isHexDigit, intToDigit, digitToInt)
import Web.Zwaluw.Core
import Web.Zwaluw.TH
infixr 8 <>
-- | Infix operator for 'mappend'.
(<>) :: Monoid m => m -> m -> m
(<>) = mappend
-- | Make a router optional.
opt :: Router r r -> Router r r
opt = (id <>)
-- | Repeat a router zero or more times, combining the results from left to right.
manyr :: Router r r -> Router r r
manyr = opt . somer
-- | Repeat a router one or more times, combining the results from left to right.
somer :: Router r r -> Router r r
somer p = p . manyr p
-- | @chainr p op@ repeats @p@ zero or more times, separated by @op@.
-- The result is a right associative fold of the results of @p@ with the results of @op@.
chainr :: Router r r -> Router r r -> Router r r
chainr p op = opt (manyr (p .~ op) . p)
-- | @chainr1 p op@ repeats @p@ one or more times, separated by @op@.
-- The result is a right associative fold of the results of @p@ with the results of @op@.
chainr1 :: Router r (a :- r) -> Router (a :- a :- r) (a :- r) -> Router r (a :- r)
chainr1 p op = manyr (duck1 p .~ op) . p
-- | Repeat a router zero or more times, combining the results from right to left.
manyl :: Router r r -> Router r r
manyl = opt . somel
-- | Repeat a router one or more times, combining the results from right to left.
somel :: Router r r -> Router r r
somel p = p .~ manyl p
-- | @chainl1 p op@ repeats @p@ zero or more times, separated by @op@.
-- The result is a left associative fold of the results of @p@ with the results of @op@.
chainl :: Router r r -> Router r r -> Router r r
chainl p op = opt (p .~ manyl (op . p))
-- | @chainl1 p op@ repeats @p@ one or more times, separated by @op@.
-- The result is a left associative fold of the results of @p@ with the results of @op@.
chainl1 :: Router r (a :- r) -> Router (a :- a :- r) (a :- r) -> Router r (a :- r)
chainl1 p op = p .~ manyl (op . duck p)
-- | Filtering on routers.
rFilter :: (a -> Bool) -> Router () (a :- ()) -> Router r (a :- r)
rFilter p r = val
(\s -> [ (a, s') | (f, s') <- prs r s, let a = hhead (f ()), p a ])
(\a -> [ f | p a, (f, _) <- ser r (a :- ()) ])
-- | Push a value on the stack (during parsing, pop it from the stack when serializing).
push :: Eq a => a -> Router r (a :- r)
push a = pure (a :-) (\(a' :- t) -> guard (a' == a) >> Just t)
-- | Routes any value that has a Show and Read instance.
readshow :: (Show a, Read a) => Router r (a :- r)
readshow = val reads (return . shows)
-- | Routes any @Int@.
int :: Router r (Int :- r)
int = readshow
-- | Routes any @Integer@.
integer :: Router r (Integer :- r)
integer = readshow
-- | Routes any string.
string :: Router r (String :- r)
string = val (\s -> [(s, "")]) (return . (++))
-- | Routes one character satisfying the given predicate.
satisfy :: (Char -> Bool) -> Router r (Char :- r)
satisfy p = val
(\s -> [ (c, cs) | c:cs <- [s], p c ])
(\c -> [ (c :) | p c ])
-- | Routes one character.
char :: Router r (Char :- r)
char = satisfy (const True)
-- | Routes one decimal digit.
digit :: Router r (Int :- r)
digit = xmaph digitToInt (\i -> guard (i >= 0 && i < 10) >> Just (intToDigit i)) (satisfy isDigit)
-- | Routes one hexadecimal digit.
hexDigit :: Router r (Int :- r)
hexDigit = xmaph digitToInt (\i -> guard (i >= 0 && i < 16) >> Just (intToDigit i)) (satisfy isHexDigit)
infixr 9 /
-- | @p \/ q@ is equivalent to @p . \"\/\" . q@.
(/) :: Router b c -> Router a b -> Router a c
(/) f g = f . lit "/" . g
-- | Routes part of a URL, i.e. a String not containing @\'\/\'@ or @\'\?\'@.
part :: Router r (String :- r)
part = rList (satisfy (\c -> c /= '/' && c /= '?'))
rNil :: Router r ([a] :- r)
rNil = pure ([] :-) $ \(xs :- t) -> do [] <- Just xs; Just t
rCons :: Router (a :- [a] :- r) ([a] :- r)
rCons = pure (arg (arg (:-)) (:)) $ \(xs :- t) -> do a:as <- Just xs; Just (a :- as :- t)
-- | Converts a router for a value @a@ to a router for a list of @a@.
rList :: Router r (a :- r) -> Router r ([a] :- r)
rList r = manyr (rCons . duck1 r) . rNil
-- | Converts a router for a value @a@ to a router for a list of @a@, with a separator.
rListSep :: Router r (a :- r) -> Router ([a] :- r) ([a] :- r) -> Router r ([a] :- r)
rListSep r sep = chainr (rCons . duck1 r) sep . rNil
rPair :: Router (f :- s :- r) ((f, s) :- r)
rPair = pure (arg (arg (:-)) (,)) $ \(ab :- t) -> do (a,b) <- Just ab; Just (a :- b :- t)
$(deriveRouters ''Either)
rLeft :: Router (a :- r) (Either a b :- r)
rRight :: Router (b :- r) (Either a b :- r)
-- | Combines a router for a value @a@ and a router for a value @b@ into a router for @Either a b@.
rEither :: Router r (a :- r) -> Router r (b :- r) -> Router r (Either a b :- r)
rEither l r = rLeft . l <> rRight . r
$(deriveRouters ''Maybe)
rNothing :: Router r (Maybe a :- r)
rJust :: Router (a :- r) (Maybe a :- r)
-- | Converts a router for a value @a@ to a router for a @Maybe a@.
rMaybe :: Router r (a :- r) -> Router r (Maybe a :- r)
rMaybe r = rJust . r <> rNothing
$(deriveRouters ''Bool)
rTrue :: Router r (Bool :- r)
rFalse :: Router r (Bool :- r)
|
MedeaMelana/Zwaluw
|
Web/Zwaluw.hs
|
bsd-3-clause
| 5,875 | 0 | 16 | 1,402 | 2,283 | 1,239 | 1,044 | 100 | 1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1998
\section[DataCon]{@DataCon@: Data Constructors}
-}
{-# LANGUAGE CPP, DeriveDataTypeable #-}
module DataCon (
-- * Main data types
DataCon, DataConRep(..),
SrcStrictness(..), SrcUnpackedness(..),
HsSrcBang(..), HsImplBang(..),
StrictnessMark(..),
ConTag,
-- ** Equality specs
EqSpec, mkEqSpec, eqSpecTyVar, eqSpecType,
eqSpecPair, eqSpecPreds,
substEqSpec, filterEqSpec,
-- ** Field labels
FieldLbl(..), FieldLabel, FieldLabelString,
-- ** Type construction
mkDataCon, buildAlgTyCon, fIRST_TAG,
-- ** Type deconstruction
dataConRepType, dataConSig, dataConInstSig, dataConFullSig,
dataConName, dataConIdentity, dataConTag, dataConTyCon,
dataConOrigTyCon, dataConUserType,
dataConUnivTyVars, dataConUnivTyBinders,
dataConExTyVars, dataConExTyBinders,
dataConAllTyVars,
dataConEqSpec, dataConTheta,
dataConStupidTheta,
dataConInstArgTys, dataConOrigArgTys, dataConOrigResTy,
dataConInstOrigArgTys, dataConRepArgTys,
dataConFieldLabels, dataConFieldType,
dataConSrcBangs,
dataConSourceArity, dataConRepArity, dataConRepRepArity,
dataConIsInfix,
dataConWorkId, dataConWrapId, dataConWrapId_maybe,
dataConImplicitTyThings,
dataConRepStrictness, dataConImplBangs, dataConBoxer,
splitDataProductType_maybe,
-- ** Predicates on DataCons
isNullarySrcDataCon, isNullaryRepDataCon, isTupleDataCon, isUnboxedTupleCon,
isVanillaDataCon, classDataCon, dataConCannotMatch,
isBanged, isMarkedStrict, eqHsBang, isSrcStrict, isSrcUnpacked,
specialPromotedDc, isLegacyPromotableDataCon, isLegacyPromotableTyCon,
-- ** Promotion related functions
promoteDataCon
) where
#include "HsVersions.h"
import {-# SOURCE #-} MkId( DataConBoxer )
import Type
import ForeignCall ( CType )
import Coercion
import Unify
import TyCon
import FieldLabel
import Class
import Name
import PrelNames
import Var
import Outputable
import ListSetOps
import Util
import BasicTypes
import FastString
import Module
import Binary
import UniqFM
import qualified Data.Data as Data
import Data.Char
import Data.Word
import Data.List( mapAccumL, find )
{-
Data constructor representation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following Haskell data type declaration
data T = T !Int ![Int]
Using the strictness annotations, GHC will represent this as
data T = T Int# [Int]
That is, the Int has been unboxed. Furthermore, the Haskell source construction
T e1 e2
is translated to
case e1 of { I# x ->
case e2 of { r ->
T x r }}
That is, the first argument is unboxed, and the second is evaluated. Finally,
pattern matching is translated too:
case e of { T a b -> ... }
becomes
case e of { T a' b -> let a = I# a' in ... }
To keep ourselves sane, we name the different versions of the data constructor
differently, as follows.
Note [Data Constructor Naming]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Each data constructor C has two, and possibly up to four, Names associated with it:
OccName Name space Name of Notes
---------------------------------------------------------------------------
The "data con itself" C DataName DataCon In dom( GlobalRdrEnv )
The "worker data con" C VarName Id The worker
The "wrapper data con" $WC VarName Id The wrapper
The "newtype coercion" :CoT TcClsName TyCon
EVERY data constructor (incl for newtypes) has the former two (the
data con itself, and its worker. But only some data constructors have a
wrapper (see Note [The need for a wrapper]).
Each of these three has a distinct Unique. The "data con itself" name
appears in the output of the renamer, and names the Haskell-source
data constructor. The type checker translates it into either the wrapper Id
(if it exists) or worker Id (otherwise).
The data con has one or two Ids associated with it:
The "worker Id", is the actual data constructor.
* Every data constructor (newtype or data type) has a worker
* The worker is very like a primop, in that it has no binding.
* For a *data* type, the worker *is* the data constructor;
it has no unfolding
* For a *newtype*, the worker has a compulsory unfolding which
does a cast, e.g.
newtype T = MkT Int
The worker for MkT has unfolding
\\(x:Int). x `cast` sym CoT
Here CoT is the type constructor, witnessing the FC axiom
axiom CoT : T = Int
The "wrapper Id", \$WC, goes as follows
* Its type is exactly what it looks like in the source program.
* It is an ordinary function, and it gets a top-level binding
like any other function.
* The wrapper Id isn't generated for a data type if there is
nothing for the wrapper to do. That is, if its defn would be
\$wC = C
Note [The need for a wrapper]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Why might the wrapper have anything to do? Two reasons:
* Unboxing strict fields (with -funbox-strict-fields)
data T = MkT !(Int,Int)
\$wMkT :: (Int,Int) -> T
\$wMkT (x,y) = MkT x y
Notice that the worker has two fields where the wapper has
just one. That is, the worker has type
MkT :: Int -> Int -> T
* Equality constraints for GADTs
data T a where { MkT :: a -> T [a] }
The worker gets a type with explicit equality
constraints, thus:
MkT :: forall a b. (a=[b]) => b -> T a
The wrapper has the programmer-specified type:
\$wMkT :: a -> T [a]
\$wMkT a x = MkT [a] a [a] x
The third argument is a coercion
[a] :: [a]~[a]
INVARIANT: the dictionary constructor for a class
never has a wrapper.
A note about the stupid context
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Data types can have a context:
data (Eq a, Ord b) => T a b = T1 a b | T2 a
and that makes the constructors have a context too
(notice that T2's context is "thinned"):
T1 :: (Eq a, Ord b) => a -> b -> T a b
T2 :: (Eq a) => a -> T a b
Furthermore, this context pops up when pattern matching
(though GHC hasn't implemented this, but it is in H98, and
I've fixed GHC so that it now does):
f (T2 x) = x
gets inferred type
f :: Eq a => T a b -> a
I say the context is "stupid" because the dictionaries passed
are immediately discarded -- they do nothing and have no benefit.
It's a flaw in the language.
Up to now [March 2002] I have put this stupid context into the
type of the "wrapper" constructors functions, T1 and T2, but
that turned out to be jolly inconvenient for generics, and
record update, and other functions that build values of type T
(because they don't have suitable dictionaries available).
So now I've taken the stupid context out. I simply deal with
it separately in the type checker on occurrences of a
constructor, either in an expression or in a pattern.
[May 2003: actually I think this decision could evasily be
reversed now, and probably should be. Generics could be
disabled for types with a stupid context; record updates now
(H98) needs the context too; etc. It's an unforced change, so
I'm leaving it for now --- but it does seem odd that the
wrapper doesn't include the stupid context.]
[July 04] With the advent of generalised data types, it's less obvious
what the "stupid context" is. Consider
C :: forall a. Ord a => a -> a -> T (Foo a)
Does the C constructor in Core contain the Ord dictionary? Yes, it must:
f :: T b -> Ordering
f = /\b. \x:T b.
case x of
C a (d:Ord a) (p:a) (q:a) -> compare d p q
Note that (Foo a) might not be an instance of Ord.
************************************************************************
* *
\subsection{Data constructors}
* *
************************************************************************
-}
-- | A data constructor
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose','ApiAnnotation.AnnComma'
-- For details on above see note [Api annotations] in ApiAnnotation
data DataCon
= MkData {
dcName :: Name, -- This is the name of the *source data con*
-- (see "Note [Data Constructor Naming]" above)
dcUnique :: Unique, -- Cached from Name
dcTag :: ConTag, -- ^ Tag, used for ordering 'DataCon's
-- Running example:
--
-- *** As declared by the user
-- data T a where
-- MkT :: forall x y. (x~y,Ord x) => x -> y -> T (x,y)
-- *** As represented internally
-- data T a where
-- MkT :: forall a. forall x y. (a~(x,y),x~y,Ord x) => x -> y -> T a
--
-- The next six fields express the type of the constructor, in pieces
-- e.g.
--
-- dcUnivTyVars = [a]
-- dcExTyVars = [x,y]
-- dcEqSpec = [a~(x,y)]
-- dcOtherTheta = [x~y, Ord x]
-- dcOrigArgTys = [x,y]
-- dcRepTyCon = T
-- In general, the dcUnivTyVars are NOT NECESSARILY THE SAME AS THE TYVARS
-- FOR THE PARENT TyCon. (This is a change (Oct05): previously, vanilla
-- datacons guaranteed to have the same type variables as their parent TyCon,
-- but that seems ugly.)
dcVanilla :: Bool, -- True <=> This is a vanilla Haskell 98 data constructor
-- Its type is of form
-- forall a1..an . t1 -> ... tm -> T a1..an
-- No existentials, no coercions, nothing.
-- That is: dcExTyVars = dcEqSpec = dcOtherTheta = []
-- NB 1: newtypes always have a vanilla data con
-- NB 2: a vanilla constructor can still be declared in GADT-style
-- syntax, provided its type looks like the above.
-- The declaration format is held in the TyCon (algTcGadtSyntax)
-- Universally-quantified type vars [a,b,c]
-- INVARIANT: length matches arity of the dcRepTyCon
-- INVARIANT: result type of data con worker is exactly (T a b c)
dcUnivTyVars :: [TyVar], -- Two linked fields
dcUnivTyBinders :: [TyBinder], -- see Note [TyBinders in DataCons]
-- Existentially-quantified type vars [x,y]
dcExTyVars :: [TyVar], -- Two linked fields
dcExTyBinders :: [TyBinder], -- see Note [TyBinders in DataCons]
-- INVARIANT: the UnivTyVars and ExTyVars all have distinct OccNames
-- Reason: less confusing, and easier to generate IfaceSyn
dcEqSpec :: [EqSpec], -- Equalities derived from the result type,
-- _as written by the programmer_
-- This field allows us to move conveniently between the two ways
-- of representing a GADT constructor's type:
-- MkT :: forall a b. (a ~ [b]) => b -> T a
-- MkT :: forall b. b -> T [b]
-- Each equality is of the form (a ~ ty), where 'a' is one of
-- the universally quantified type variables
-- The next two fields give the type context of the data constructor
-- (aside from the GADT constraints,
-- which are given by the dcExpSpec)
-- In GADT form, this is *exactly* what the programmer writes, even if
-- the context constrains only universally quantified variables
-- MkT :: forall a b. (a ~ b, Ord b) => a -> T a b
dcOtherTheta :: ThetaType, -- The other constraints in the data con's type
-- other than those in the dcEqSpec
dcStupidTheta :: ThetaType, -- The context of the data type declaration
-- data Eq a => T a = ...
-- or, rather, a "thinned" version thereof
-- "Thinned", because the Report says
-- to eliminate any constraints that don't mention
-- tyvars free in the arg types for this constructor
--
-- INVARIANT: the free tyvars of dcStupidTheta are a subset of dcUnivTyVars
-- Reason: dcStupidTeta is gotten by thinning the stupid theta from the tycon
--
-- "Stupid", because the dictionaries aren't used for anything.
-- Indeed, [as of March 02] they are no longer in the type of
-- the wrapper Id, because that makes it harder to use the wrap-id
-- to rebuild values after record selection or in generics.
dcOrigArgTys :: [Type], -- Original argument types
-- (before unboxing and flattening of strict fields)
dcOrigResTy :: Type, -- Original result type, as seen by the user
-- NB: for a data instance, the original user result type may
-- differ from the DataCon's representation TyCon. Example
-- data instance T [a] where MkT :: a -> T [a]
-- The OrigResTy is T [a], but the dcRepTyCon might be :T123
-- Now the strictness annotations and field labels of the constructor
dcSrcBangs :: [HsSrcBang],
-- See Note [Bangs on data constructor arguments]
--
-- The [HsSrcBang] as written by the programmer.
--
-- Matches 1-1 with dcOrigArgTys
-- Hence length = dataConSourceArity dataCon
dcFields :: [FieldLabel],
-- Field labels for this constructor, in the
-- same order as the dcOrigArgTys;
-- length = 0 (if not a record) or dataConSourceArity.
-- The curried worker function that corresponds to the constructor:
-- It doesn't have an unfolding; the code generator saturates these Ids
-- and allocates a real constructor when it finds one.
dcWorkId :: Id,
-- Constructor representation
dcRep :: DataConRep,
-- Cached
-- dcRepArity == length dataConRepArgTys
dcRepArity :: Arity,
-- dcSourceArity == length dcOrigArgTys
dcSourceArity :: Arity,
-- Result type of constructor is T t1..tn
dcRepTyCon :: TyCon, -- Result tycon, T
dcRepType :: Type, -- Type of the constructor
-- forall a x y. (a~(x,y), x~y, Ord x) =>
-- x -> y -> T a
-- (this is *not* of the constructor wrapper Id:
-- see Note [Data con representation] below)
-- Notice that the existential type parameters come *second*.
-- Reason: in a case expression we may find:
-- case (e :: T t) of
-- MkT x y co1 co2 (d:Ord x) (v:r) (w:F s) -> ...
-- It's convenient to apply the rep-type of MkT to 't', to get
-- forall x y. (t~(x,y), x~y, Ord x) => x -> y -> T t
-- and use that to check the pattern. Mind you, this is really only
-- used in CoreLint.
dcInfix :: Bool, -- True <=> declared infix
-- Used for Template Haskell and 'deriving' only
-- The actual fixity is stored elsewhere
dcPromoted :: TyCon -- The promoted TyCon
-- See Note [Promoted data constructors] in TyCon
}
{- Note [TyBinders in DataCons]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DataCons and PatSyns store their universal and existential type
variables in a pair of fields, e.g.
dcUnivTyVars :: [TyVar],
dcUnivTyBinders :: [TyBinder],
and similarly dcExTyVars/dcExTyVarBinders
Of these, the former is always redundant:
dcUnivTyVars = [ tv | Named tv _ <- dcUnivTyBinders ]
Specifically:
* The two fields correspond 1-1
* Each TyBinder a Named (no Anons)
* The TyVar in each TyBinder is the same as the TyVar in
the corresponding tyvar in the TyVars list.
* Each Visibilty flag (va, vb, etc) is Invisible or Specified.
None are Visible. (A DataCon is a term-level function; see
Note [No Visible TyBinder in terms] in TyCoRep.)
Why store these fields redundantly? Purely convenience. In most
places in GHC, it's just the TyVars that are needed, so that's what's
returned from, say, dataConFullSig.
Why do we need the TyBinders? So that we can construct the right
type for the DataCon with its foralls attributed the correce visiblity.
That in turn governs whether you can use visible type application
at a call of the data constructor.
-}
data DataConRep
= NoDataConRep -- No wrapper
| DCR { dcr_wrap_id :: Id -- Takes src args, unboxes/flattens,
-- and constructs the representation
, dcr_boxer :: DataConBoxer
, dcr_arg_tys :: [Type] -- Final, representation argument types,
-- after unboxing and flattening,
-- and *including* all evidence args
, dcr_stricts :: [StrictnessMark] -- 1-1 with dcr_arg_tys
-- See also Note [Data-con worker strictness] in MkId.hs
, dcr_bangs :: [HsImplBang] -- The actual decisions made (including failures)
-- about the original arguments; 1-1 with orig_arg_tys
-- See Note [Bangs on data constructor arguments]
}
-- Algebraic data types always have a worker, and
-- may or may not have a wrapper, depending on whether
-- the wrapper does anything.
--
-- Data types have a worker with no unfolding
-- Newtypes just have a worker, which has a compulsory unfolding (just a cast)
-- _Neither_ the worker _nor_ the wrapper take the dcStupidTheta dicts as arguments
-- The wrapper (if it exists) takes dcOrigArgTys as its arguments
-- The worker takes dataConRepArgTys as its arguments
-- If the worker is absent, dataConRepArgTys is the same as dcOrigArgTys
-- The 'NoDataConRep' case is important
-- Not only is this efficient,
-- but it also ensures that the wrapper is replaced
-- by the worker (because it *is* the worker)
-- even when there are no args. E.g. in
-- f (:) x
-- the (:) *is* the worker.
-- This is really important in rule matching,
-- (We could match on the wrappers,
-- but that makes it less likely that rules will match
-- when we bring bits of unfoldings together.)
-------------------------
-- | Bangs on data constructor arguments as the user wrote them in the
-- source code.
--
-- (HsSrcBang _ SrcUnpack SrcLazy) and
-- (HsSrcBang _ SrcUnpack NoSrcStrict) (without StrictData) makes no sense, we
-- emit a warning (in checkValidDataCon) and treat it like
-- (HsSrcBang _ NoSrcUnpack SrcLazy)
data HsSrcBang =
HsSrcBang (Maybe SourceText) -- Note [Pragma source text] in BasicTypes
SrcUnpackedness
SrcStrictness
deriving Data.Data
-- | Bangs of data constructor arguments as generated by the compiler
-- after consulting HsSrcBang, flags, etc.
data HsImplBang
= HsLazy -- ^ Lazy field
| HsStrict -- ^ Strict but not unpacked field
| HsUnpack (Maybe Coercion)
-- ^ Strict and unpacked field
-- co :: arg-ty ~ product-ty HsBang
deriving Data.Data
-- | What strictness annotation the user wrote
data SrcStrictness = SrcLazy -- ^ Lazy, ie '~'
| SrcStrict -- ^ Strict, ie '!'
| NoSrcStrict -- ^ no strictness annotation
deriving (Eq, Data.Data)
-- | What unpackedness the user requested
data SrcUnpackedness = SrcUnpack -- ^ {-# UNPACK #-} specified
| SrcNoUnpack -- ^ {-# NOUNPACK #-} specified
| NoSrcUnpack -- ^ no unpack pragma
deriving (Eq, Data.Data)
-------------------------
-- StrictnessMark is internal only, used to indicate strictness
-- of the DataCon *worker* fields
data StrictnessMark = MarkedStrict | NotMarkedStrict
-- | An 'EqSpec' is a tyvar/type pair representing an equality made in
-- rejigging a GADT constructor
data EqSpec = EqSpec TyVar
Type
-- | Make an 'EqSpec'
mkEqSpec :: TyVar -> Type -> EqSpec
mkEqSpec tv ty = EqSpec tv ty
eqSpecTyVar :: EqSpec -> TyVar
eqSpecTyVar (EqSpec tv _) = tv
eqSpecType :: EqSpec -> Type
eqSpecType (EqSpec _ ty) = ty
eqSpecPair :: EqSpec -> (TyVar, Type)
eqSpecPair (EqSpec tv ty) = (tv, ty)
eqSpecPreds :: [EqSpec] -> ThetaType
eqSpecPreds spec = [ mkPrimEqPred (mkTyVarTy tv) ty
| EqSpec tv ty <- spec ]
-- | Substitute in an 'EqSpec'. Precondition: if the LHS of the EqSpec
-- is mapped in the substitution, it is mapped to a type variable, not
-- a full type.
substEqSpec :: TCvSubst -> EqSpec -> EqSpec
substEqSpec subst (EqSpec tv ty)
= EqSpec tv' (substTy subst ty)
where
tv' = getTyVar "substEqSpec" (substTyVar subst tv)
-- | Filter out any TyBinders mentioned in an EqSpec
filterEqSpec :: [EqSpec] -> [TyBinder] -> [TyBinder]
filterEqSpec eq_spec
= filter not_in_eq_spec
where
not_in_eq_spec bndr = let var = binderVar "filterEqSpec" bndr in
all (not . (== var) . eqSpecTyVar) eq_spec
instance Outputable EqSpec where
ppr (EqSpec tv ty) = ppr (tv, ty)
{- Note [Bangs on data constructor arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data T = MkT !Int {-# UNPACK #-} !Int Bool
When compiling the module, GHC will decide how to represent
MkT, depending on the optimisation level, and settings of
flags like -funbox-small-strict-fields.
Terminology:
* HsSrcBang: What the user wrote
Constructors: HsSrcBang
* HsImplBang: What GHC decided
Constructors: HsLazy, HsStrict, HsUnpack
* If T was defined in this module, MkT's dcSrcBangs field
records the [HsSrcBang] of what the user wrote; in the example
[ HsSrcBang _ NoSrcUnpack SrcStrict
, HsSrcBang _ SrcUnpack SrcStrict
, HsSrcBang _ NoSrcUnpack NoSrcStrictness]
* However, if T was defined in an imported module, the importing module
must follow the decisions made in the original module, regardless of
the flag settings in the importing module.
Also see Note [Bangs on imported data constructors] in MkId
* The dcr_bangs field of the dcRep field records the [HsImplBang]
If T was defined in this module, Without -O the dcr_bangs might be
[HsStrict, HsStrict, HsLazy]
With -O it might be
[HsStrict, HsUnpack _, HsLazy]
With -funbox-small-strict-fields it might be
[HsUnpack, HsUnpack _, HsLazy]
With -XStrictData it might be
[HsStrict, HsUnpack _, HsStrict]
Note [Data con representation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The dcRepType field contains the type of the representation of a contructor
This may differ from the type of the constructor *Id* (built
by MkId.mkDataConId) for two reasons:
a) the constructor Id may be overloaded, but the dictionary isn't stored
e.g. data Eq a => T a = MkT a a
b) the constructor may store an unboxed version of a strict field.
Here's an example illustrating both:
data Ord a => T a = MkT Int! a
Here
T :: Ord a => Int -> a -> T a
but the rep type is
Trep :: Int# -> a -> T a
Actually, the unboxed part isn't implemented yet!
************************************************************************
* *
\subsection{Instances}
* *
************************************************************************
-}
instance Eq DataCon where
a == b = getUnique a == getUnique b
a /= b = getUnique a /= getUnique b
instance Ord DataCon where
a <= b = getUnique a <= getUnique b
a < b = getUnique a < getUnique b
a >= b = getUnique a >= getUnique b
a > b = getUnique a > getUnique b
compare a b = getUnique a `compare` getUnique b
instance Uniquable DataCon where
getUnique = dcUnique
instance NamedThing DataCon where
getName = dcName
instance Outputable DataCon where
ppr con = ppr (dataConName con)
instance OutputableBndr DataCon where
pprInfixOcc con = pprInfixName (dataConName con)
pprPrefixOcc con = pprPrefixName (dataConName con)
instance Data.Data DataCon where
-- don't traverse?
toConstr _ = abstractConstr "DataCon"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "DataCon"
instance Outputable HsSrcBang where
ppr (HsSrcBang _ prag mark) = ppr prag <+> ppr mark
instance Outputable HsImplBang where
ppr HsLazy = text "Lazy"
ppr (HsUnpack Nothing) = text "Unpacked"
ppr (HsUnpack (Just co)) = text "Unpacked" <> parens (ppr co)
ppr HsStrict = text "StrictNotUnpacked"
instance Outputable SrcStrictness where
ppr SrcLazy = char '~'
ppr SrcStrict = char '!'
ppr NoSrcStrict = empty
instance Outputable SrcUnpackedness where
ppr SrcUnpack = text "{-# UNPACK #-}"
ppr SrcNoUnpack = text "{-# NOUNPACK #-}"
ppr NoSrcUnpack = empty
instance Outputable StrictnessMark where
ppr MarkedStrict = text "!"
ppr NotMarkedStrict = empty
instance Binary SrcStrictness where
put_ bh SrcLazy = putByte bh 0
put_ bh SrcStrict = putByte bh 1
put_ bh NoSrcStrict = putByte bh 2
get bh =
do h <- getByte bh
case h of
0 -> return SrcLazy
1 -> return SrcLazy
_ -> return NoSrcStrict
instance Binary SrcUnpackedness where
put_ bh SrcNoUnpack = putByte bh 0
put_ bh SrcUnpack = putByte bh 1
put_ bh NoSrcUnpack = putByte bh 2
get bh =
do h <- getByte bh
case h of
0 -> return SrcNoUnpack
1 -> return SrcUnpack
_ -> return NoSrcUnpack
-- | Compare strictness annotations
eqHsBang :: HsImplBang -> HsImplBang -> Bool
eqHsBang HsLazy HsLazy = True
eqHsBang HsStrict HsStrict = True
eqHsBang (HsUnpack Nothing) (HsUnpack Nothing) = True
eqHsBang (HsUnpack (Just c1)) (HsUnpack (Just c2))
= eqType (coercionType c1) (coercionType c2)
eqHsBang _ _ = False
isBanged :: HsImplBang -> Bool
isBanged (HsUnpack {}) = True
isBanged (HsStrict {}) = True
isBanged HsLazy = False
isSrcStrict :: SrcStrictness -> Bool
isSrcStrict SrcStrict = True
isSrcStrict _ = False
isSrcUnpacked :: SrcUnpackedness -> Bool
isSrcUnpacked SrcUnpack = True
isSrcUnpacked _ = False
isMarkedStrict :: StrictnessMark -> Bool
isMarkedStrict NotMarkedStrict = False
isMarkedStrict _ = True -- All others are strict
{- *********************************************************************
* *
\subsection{Construction}
* *
********************************************************************* -}
-- | Build a new data constructor
mkDataCon :: Name
-> Bool -- ^ Is the constructor declared infix?
-> TyConRepName -- ^ TyConRepName for the promoted TyCon
-> [HsSrcBang] -- ^ Strictness/unpack annotations, from user
-> [FieldLabel] -- ^ Field labels for the constructor,
-- if it is a record, otherwise empty
-> [TyVar] -> [TyBinder] -- ^ Universals. See Note [TyBinders in DataCons]
-> [TyVar] -> [TyBinder] -- ^ Existentials.
-- (These last two must be Named and Invisible/Specified)
-> [EqSpec] -- ^ GADT equalities
-> ThetaType -- ^ Theta-type occuring before the arguments proper
-> [Type] -- ^ Original argument types
-> Type -- ^ Original result type
-> RuntimeRepInfo -- ^ See comments on 'TyCon.RuntimeRepInfo'
-> TyCon -- ^ Representation type constructor
-> ThetaType -- ^ The "stupid theta", context of the data
-- declaration e.g. @data Eq a => T a ...@
-> Id -- ^ Worker Id
-> DataConRep -- ^ Representation
-> DataCon
-- Can get the tag from the TyCon
mkDataCon name declared_infix prom_info
arg_stricts -- Must match orig_arg_tys 1-1
fields
univ_tvs univ_bndrs ex_tvs ex_bndrs
eq_spec theta
orig_arg_tys orig_res_ty rep_info rep_tycon
stupid_theta work_id rep
-- Warning: mkDataCon is not a good place to check invariants.
-- If the programmer writes the wrong result type in the decl, thus:
-- data T a where { MkT :: S }
-- then it's possible that the univ_tvs may hit an assertion failure
-- if you pull on univ_tvs. This case is checked by checkValidDataCon,
-- so the error is detected properly... it's just that asaertions here
-- are a little dodgy.
= con
where
is_vanilla = null ex_tvs && null eq_spec && null theta
con = MkData {dcName = name, dcUnique = nameUnique name,
dcVanilla = is_vanilla, dcInfix = declared_infix,
dcUnivTyVars = univ_tvs, dcUnivTyBinders = univ_bndrs,
dcExTyVars = ex_tvs, dcExTyBinders = ex_bndrs,
dcEqSpec = eq_spec,
dcOtherTheta = theta,
dcStupidTheta = stupid_theta,
dcOrigArgTys = orig_arg_tys, dcOrigResTy = orig_res_ty,
dcRepTyCon = rep_tycon,
dcSrcBangs = arg_stricts,
dcFields = fields, dcTag = tag, dcRepType = rep_ty,
dcWorkId = work_id,
dcRep = rep,
dcSourceArity = length orig_arg_tys,
dcRepArity = length rep_arg_tys,
dcPromoted = promoted }
-- The 'arg_stricts' passed to mkDataCon are simply those for the
-- source-language arguments. We add extra ones for the
-- dictionary arguments right here.
tag = assoc "mkDataCon" (tyConDataCons rep_tycon `zip` [fIRST_TAG..]) con
rep_arg_tys = dataConRepArgTys con
rep_ty = mkForAllTys univ_bndrs $ mkForAllTys ex_bndrs $
mkFunTys rep_arg_tys $
mkTyConApp rep_tycon (mkTyVarTys univ_tvs)
-- See Note [Promoted data constructors] in TyCon
prom_binders = filterEqSpec eq_spec univ_bndrs ++
ex_bndrs ++
map mkAnonBinder theta ++
map mkAnonBinder orig_arg_tys
prom_res_kind = orig_res_ty
promoted
= mkPromotedDataCon con name prom_info prom_binders prom_res_kind roles rep_info
roles = map (const Nominal) (univ_tvs ++ ex_tvs) ++
map (const Representational) orig_arg_tys
-- | The 'Name' of the 'DataCon', giving it a unique, rooted identification
dataConName :: DataCon -> Name
dataConName = dcName
-- | The tag used for ordering 'DataCon's
dataConTag :: DataCon -> ConTag
dataConTag = dcTag
-- | The type constructor that we are building via this data constructor
dataConTyCon :: DataCon -> TyCon
dataConTyCon = dcRepTyCon
-- | The original type constructor used in the definition of this data
-- constructor. In case of a data family instance, that will be the family
-- type constructor.
dataConOrigTyCon :: DataCon -> TyCon
dataConOrigTyCon dc
| Just (tc, _) <- tyConFamInst_maybe (dcRepTyCon dc) = tc
| otherwise = dcRepTyCon dc
-- | The representation type of the data constructor, i.e. the sort
-- type that will represent values of this type at runtime
dataConRepType :: DataCon -> Type
dataConRepType = dcRepType
-- | Should the 'DataCon' be presented infix?
dataConIsInfix :: DataCon -> Bool
dataConIsInfix = dcInfix
-- | The universally-quantified type variables of the constructor
dataConUnivTyVars :: DataCon -> [TyVar]
dataConUnivTyVars = dcUnivTyVars
-- | 'TyBinder's for the universally-quantified type variables
dataConUnivTyBinders :: DataCon -> [TyBinder]
dataConUnivTyBinders = dcUnivTyBinders
-- | The existentially-quantified type variables of the constructor
dataConExTyVars :: DataCon -> [TyVar]
dataConExTyVars = dcExTyVars
-- | 'TyBinder's for the existentially-quantified type variables
dataConExTyBinders :: DataCon -> [TyBinder]
dataConExTyBinders = dcExTyBinders
-- | Both the universal and existentiatial type variables of the constructor
dataConAllTyVars :: DataCon -> [TyVar]
dataConAllTyVars (MkData { dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs })
= univ_tvs ++ ex_tvs
-- | Equalities derived from the result type of the data constructor, as written
-- by the programmer in any GADT declaration. This includes *all* GADT-like
-- equalities, including those written in by hand by the programmer.
dataConEqSpec :: DataCon -> [EqSpec]
dataConEqSpec (MkData { dcEqSpec = eq_spec, dcOtherTheta = theta })
= eq_spec ++
[ spec -- heterogeneous equality
| Just (tc, [_k1, _k2, ty1, ty2]) <- map splitTyConApp_maybe theta
, tc `hasKey` heqTyConKey
, spec <- case (getTyVar_maybe ty1, getTyVar_maybe ty2) of
(Just tv1, _) -> [mkEqSpec tv1 ty2]
(_, Just tv2) -> [mkEqSpec tv2 ty1]
_ -> []
] ++
[ spec -- homogeneous equality
| Just (tc, [_k, ty1, ty2]) <- map splitTyConApp_maybe theta
, tc `hasKey` eqTyConKey
, spec <- case (getTyVar_maybe ty1, getTyVar_maybe ty2) of
(Just tv1, _) -> [mkEqSpec tv1 ty2]
(_, Just tv2) -> [mkEqSpec tv2 ty1]
_ -> []
]
-- | The *full* constraints on the constructor type.
dataConTheta :: DataCon -> ThetaType
dataConTheta (MkData { dcEqSpec = eq_spec, dcOtherTheta = theta })
= eqSpecPreds eq_spec ++ theta
-- | Get the Id of the 'DataCon' worker: a function that is the "actual"
-- constructor and has no top level binding in the program. The type may
-- be different from the obvious one written in the source program. Panics
-- if there is no such 'Id' for this 'DataCon'
dataConWorkId :: DataCon -> Id
dataConWorkId dc = dcWorkId dc
-- | Get the Id of the 'DataCon' wrapper: a function that wraps the "actual"
-- constructor so it has the type visible in the source program: c.f. 'dataConWorkId'.
-- Returns Nothing if there is no wrapper, which occurs for an algebraic data constructor
-- and also for a newtype (whose constructor is inlined compulsorily)
dataConWrapId_maybe :: DataCon -> Maybe Id
dataConWrapId_maybe dc = case dcRep dc of
NoDataConRep -> Nothing
DCR { dcr_wrap_id = wrap_id } -> Just wrap_id
-- | Returns an Id which looks like the Haskell-source constructor by using
-- the wrapper if it exists (see 'dataConWrapId_maybe') and failing over to
-- the worker (see 'dataConWorkId')
dataConWrapId :: DataCon -> Id
dataConWrapId dc = case dcRep dc of
NoDataConRep-> dcWorkId dc -- worker=wrapper
DCR { dcr_wrap_id = wrap_id } -> wrap_id
-- | Find all the 'Id's implicitly brought into scope by the data constructor. Currently,
-- the union of the 'dataConWorkId' and the 'dataConWrapId'
dataConImplicitTyThings :: DataCon -> [TyThing]
dataConImplicitTyThings (MkData { dcWorkId = work, dcRep = rep })
= [AnId work] ++ wrap_ids
where
wrap_ids = case rep of
NoDataConRep -> []
DCR { dcr_wrap_id = wrap } -> [AnId wrap]
-- | The labels for the fields of this particular 'DataCon'
dataConFieldLabels :: DataCon -> [FieldLabel]
dataConFieldLabels = dcFields
-- | Extract the type for any given labelled field of the 'DataCon'
dataConFieldType :: DataCon -> FieldLabelString -> Type
dataConFieldType con label
= case find ((== label) . flLabel . fst) (dcFields con `zip` dcOrigArgTys con) of
Just (_, ty) -> ty
Nothing -> pprPanic "dataConFieldType" (ppr con <+> ppr label)
-- | Strictness/unpack annotations, from user; or, for imported
-- DataCons, from the interface file
-- The list is in one-to-one correspondence with the arity of the 'DataCon'
dataConSrcBangs :: DataCon -> [HsSrcBang]
dataConSrcBangs = dcSrcBangs
-- | Source-level arity of the data constructor
dataConSourceArity :: DataCon -> Arity
dataConSourceArity (MkData { dcSourceArity = arity }) = arity
-- | Gives the number of actual fields in the /representation/ of the
-- data constructor. This may be more than appear in the source code;
-- the extra ones are the existentially quantified dictionaries
dataConRepArity :: DataCon -> Arity
dataConRepArity (MkData { dcRepArity = arity }) = arity
-- | The number of fields in the /representation/ of the constructor
-- AFTER taking into account the unpacking of any unboxed tuple fields
dataConRepRepArity :: DataCon -> RepArity
dataConRepRepArity dc = typeRepArity (dataConRepArity dc) (dataConRepType dc)
-- | Return whether there are any argument types for this 'DataCon's original source type
isNullarySrcDataCon :: DataCon -> Bool
isNullarySrcDataCon dc = null (dcOrigArgTys dc)
-- | Return whether there are any argument types for this 'DataCon's runtime representation type
isNullaryRepDataCon :: DataCon -> Bool
isNullaryRepDataCon dc = dataConRepArity dc == 0
dataConRepStrictness :: DataCon -> [StrictnessMark]
-- ^ Give the demands on the arguments of a
-- Core constructor application (Con dc args)
dataConRepStrictness dc = case dcRep dc of
NoDataConRep -> [NotMarkedStrict | _ <- dataConRepArgTys dc]
DCR { dcr_stricts = strs } -> strs
dataConImplBangs :: DataCon -> [HsImplBang]
-- The implementation decisions about the strictness/unpack of each
-- source program argument to the data constructor
dataConImplBangs dc
= case dcRep dc of
NoDataConRep -> replicate (dcSourceArity dc) HsLazy
DCR { dcr_bangs = bangs } -> bangs
dataConBoxer :: DataCon -> Maybe DataConBoxer
dataConBoxer (MkData { dcRep = DCR { dcr_boxer = boxer } }) = Just boxer
dataConBoxer _ = Nothing
-- | The \"signature\" of the 'DataCon' returns, in order:
--
-- 1) The result of 'dataConAllTyVars',
--
-- 2) All the 'ThetaType's relating to the 'DataCon' (coercion, dictionary, implicit
-- parameter - whatever)
--
-- 3) The type arguments to the constructor
--
-- 4) The /original/ result type of the 'DataCon'
dataConSig :: DataCon -> ([TyVar], ThetaType, [Type], Type)
dataConSig con@(MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs,
dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
= (univ_tvs ++ ex_tvs, dataConTheta con, arg_tys, res_ty)
dataConInstSig
:: DataCon
-> [Type] -- Instantiate the *universal* tyvars with these types
-> ([TyVar], ThetaType, [Type]) -- Return instantiated existentials
-- theta and arg tys
-- ^ Instantantiate the universal tyvars of a data con,
-- returning the instantiated existentials, constraints, and args
dataConInstSig (MkData { dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs
, dcEqSpec = eq_spec, dcOtherTheta = theta
, dcOrigArgTys = arg_tys })
univ_tys
= (ex_tvs'
, substTheta subst (eqSpecPreds eq_spec ++ theta)
, substTys subst arg_tys)
where
univ_subst = zipTvSubst univ_tvs univ_tys
(subst, ex_tvs') = mapAccumL Type.substTyVarBndr univ_subst ex_tvs
-- | The \"full signature\" of the 'DataCon' returns, in order:
--
-- 1) The result of 'dataConUnivTyVars'
--
-- 2) The result of 'dataConExTyVars'
--
-- 3) The GADT equalities
--
-- 4) The result of 'dataConDictTheta'
--
-- 5) The original argument types to the 'DataCon' (i.e. before
-- any change of the representation of the type)
--
-- 6) The original result type of the 'DataCon'
dataConFullSig :: DataCon
-> ([TyVar], [TyVar], [EqSpec], ThetaType, [Type], Type)
dataConFullSig (MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs,
dcEqSpec = eq_spec, dcOtherTheta = theta,
dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
= (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, res_ty)
dataConOrigResTy :: DataCon -> Type
dataConOrigResTy dc = dcOrigResTy dc
-- | The \"stupid theta\" of the 'DataCon', such as @data Eq a@ in:
--
-- > data Eq a => T a = ...
dataConStupidTheta :: DataCon -> ThetaType
dataConStupidTheta dc = dcStupidTheta dc
dataConUserType :: DataCon -> Type
-- ^ The user-declared type of the data constructor
-- in the nice-to-read form:
--
-- > T :: forall a b. a -> b -> T [a]
--
-- rather than:
--
-- > T :: forall a c. forall b. (c~[a]) => a -> b -> T c
--
-- NB: If the constructor is part of a data instance, the result type
-- mentions the family tycon, not the internal one.
dataConUserType (MkData { dcUnivTyBinders = univ_bndrs,
dcExTyBinders = ex_bndrs, dcEqSpec = eq_spec,
dcOtherTheta = theta, dcOrigArgTys = arg_tys,
dcOrigResTy = res_ty })
= mkForAllTys (filterEqSpec eq_spec univ_bndrs) $
mkForAllTys ex_bndrs $
mkFunTys theta $
mkFunTys arg_tys $
res_ty
where
-- | Finds the instantiated types of the arguments required to construct a 'DataCon' representation
-- NB: these INCLUDE any dictionary args
-- but EXCLUDE the data-declaration context, which is discarded
-- It's all post-flattening etc; this is a representation type
dataConInstArgTys :: DataCon -- ^ A datacon with no existentials or equality constraints
-- However, it can have a dcTheta (notably it can be a
-- class dictionary, with superclasses)
-> [Type] -- ^ Instantiated at these types
-> [Type]
dataConInstArgTys dc@(MkData {dcUnivTyVars = univ_tvs,
dcExTyVars = ex_tvs}) inst_tys
= ASSERT2( length univ_tvs == length inst_tys
, text "dataConInstArgTys" <+> ppr dc $$ ppr univ_tvs $$ ppr inst_tys)
ASSERT2( null ex_tvs, ppr dc )
map (substTyWith univ_tvs inst_tys) (dataConRepArgTys dc)
-- | Returns just the instantiated /value/ argument types of a 'DataCon',
-- (excluding dictionary args)
dataConInstOrigArgTys
:: DataCon -- Works for any DataCon
-> [Type] -- Includes existential tyvar args, but NOT
-- equality constraints or dicts
-> [Type]
-- For vanilla datacons, it's all quite straightforward
-- But for the call in MatchCon, we really do want just the value args
dataConInstOrigArgTys dc@(MkData {dcOrigArgTys = arg_tys,
dcUnivTyVars = univ_tvs,
dcExTyVars = ex_tvs}) inst_tys
= ASSERT2( length tyvars == length inst_tys
, text "dataConInstOrigArgTys" <+> ppr dc $$ ppr tyvars $$ ppr inst_tys )
map (substTyWith tyvars inst_tys) arg_tys
where
tyvars = univ_tvs ++ ex_tvs
-- | Returns the argument types of the wrapper, excluding all dictionary arguments
-- and without substituting for any type variables
dataConOrigArgTys :: DataCon -> [Type]
dataConOrigArgTys dc = dcOrigArgTys dc
-- | Returns the arg types of the worker, including *all*
-- evidence, after any flattening has been done and without substituting for
-- any type variables
dataConRepArgTys :: DataCon -> [Type]
dataConRepArgTys (MkData { dcRep = rep
, dcEqSpec = eq_spec
, dcOtherTheta = theta
, dcOrigArgTys = orig_arg_tys })
= case rep of
NoDataConRep -> ASSERT( null eq_spec ) theta ++ orig_arg_tys
DCR { dcr_arg_tys = arg_tys } -> arg_tys
-- | The string @package:module.name@ identifying a constructor, which is attached
-- to its info table and used by the GHCi debugger and the heap profiler
dataConIdentity :: DataCon -> [Word8]
-- We want this string to be UTF-8, so we get the bytes directly from the FastStrings.
dataConIdentity dc = bytesFS (unitIdFS (moduleUnitId mod)) ++
fromIntegral (ord ':') : bytesFS (moduleNameFS (moduleName mod)) ++
fromIntegral (ord '.') : bytesFS (occNameFS (nameOccName name))
where name = dataConName dc
mod = ASSERT( isExternalName name ) nameModule name
isTupleDataCon :: DataCon -> Bool
isTupleDataCon (MkData {dcRepTyCon = tc}) = isTupleTyCon tc
isUnboxedTupleCon :: DataCon -> Bool
isUnboxedTupleCon (MkData {dcRepTyCon = tc}) = isUnboxedTupleTyCon tc
-- | Vanilla 'DataCon's are those that are nice boring Haskell 98 constructors
isVanillaDataCon :: DataCon -> Bool
isVanillaDataCon dc = dcVanilla dc
-- | Should this DataCon be allowed in a type even without -XDataKinds?
-- Currently, only Lifted & Unlifted
specialPromotedDc :: DataCon -> Bool
specialPromotedDc = isKindTyCon . dataConTyCon
-- | Was this datacon promotable before GHC 8.0? That is, is it promotable
-- without -XTypeInType
isLegacyPromotableDataCon :: DataCon -> Bool
isLegacyPromotableDataCon dc
= null (dataConEqSpec dc) -- no GADTs
&& null (dataConTheta dc) -- no context
&& not (isFamInstTyCon (dataConTyCon dc)) -- no data instance constructors
&& allUFM isLegacyPromotableTyCon (tyConsOfType (dataConUserType dc))
-- | Was this tycon promotable before GHC 8.0? That is, is it promotable
-- without -XTypeInType
isLegacyPromotableTyCon :: TyCon -> Bool
isLegacyPromotableTyCon tc
= isVanillaAlgTyCon tc ||
-- This returns True more often than it should, but it's quite painful
-- to make this fully accurate. And no harm is caused; we just don't
-- require -XTypeInType every time we need to. (We'll always require
-- -XDataKinds, though, so there's no standards-compliance issue.)
isFunTyCon tc || isKindTyCon tc
classDataCon :: Class -> DataCon
classDataCon clas = case tyConDataCons (classTyCon clas) of
(dict_constr:no_more) -> ASSERT( null no_more ) dict_constr
[] -> panic "classDataCon"
dataConCannotMatch :: [Type] -> DataCon -> Bool
-- Returns True iff the data con *definitely cannot* match a
-- scrutinee of type (T tys)
-- where T is the dcRepTyCon for the data con
dataConCannotMatch tys con
| null inst_theta = False -- Common
| all isTyVarTy tys = False -- Also common
| otherwise = typesCantMatch (concatMap predEqs inst_theta)
where
(_, inst_theta, _) = dataConInstSig con tys
-- TODO: could gather equalities from superclasses too
predEqs pred = case classifyPredType pred of
EqPred NomEq ty1 ty2 -> [(ty1, ty2)]
ClassPred eq [_, ty1, ty2]
| eq `hasKey` eqTyConKey -> [(ty1, ty2)]
_ -> []
{-
%************************************************************************
%* *
Promoting of data types to the kind level
* *
************************************************************************
-}
promoteDataCon :: DataCon -> TyCon
promoteDataCon (MkData { dcPromoted = tc }) = tc
{-
************************************************************************
* *
\subsection{Splitting products}
* *
************************************************************************
-}
-- | Extract the type constructor, type argument, data constructor and it's
-- /representation/ argument types from a type if it is a product type.
--
-- Precisely, we return @Just@ for any type that is all of:
--
-- * Concrete (i.e. constructors visible)
--
-- * Single-constructor
--
-- * Not existentially quantified
--
-- Whether the type is a @data@ type or a @newtype@
splitDataProductType_maybe
:: Type -- ^ A product type, perhaps
-> Maybe (TyCon, -- The type constructor
[Type], -- Type args of the tycon
DataCon, -- The data constructor
[Type]) -- Its /representation/ arg types
-- Rejecting existentials is conservative. Maybe some things
-- could be made to work with them, but I'm not going to sweat
-- it through till someone finds it's important.
splitDataProductType_maybe ty
| Just (tycon, ty_args) <- splitTyConApp_maybe ty
, Just con <- isDataProductTyCon_maybe tycon
= Just (tycon, ty_args, con, dataConInstArgTys con ty_args)
| otherwise
= Nothing
{-
************************************************************************
* *
Building an algebraic data type
* *
************************************************************************
buildAlgTyCon is here because it is called from TysWiredIn, which can
depend on this module, but not on BuildTyCl.
-}
buildAlgTyCon :: Name
-> [TyVar] -- ^ Kind variables and type variables
-> [Role]
-> Maybe CType
-> ThetaType -- ^ Stupid theta
-> AlgTyConRhs
-> RecFlag
-> Bool -- ^ True <=> was declared in GADT syntax
-> AlgTyConFlav
-> TyCon
buildAlgTyCon tc_name ktvs roles cType stupid_theta rhs
is_rec gadt_syn parent
= mkAlgTyCon tc_name binders liftedTypeKind ktvs roles cType stupid_theta
rhs parent is_rec gadt_syn
where
binders = mkTyBindersPreferAnon ktvs liftedTypeKind
|
vikraman/ghc
|
compiler/basicTypes/DataCon.hs
|
bsd-3-clause
| 50,860 | 0 | 22 | 14,673 | 5,794 | 3,302 | 2,492 | 497 | 5 |
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1994-1998
Desugaring foreign calls
-}
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
module DsCCall
( dsCCall
, mkFCall
, unboxArg
, boxResult
, resultWrapper
) where
#include "HsVersions.h"
import GhcPrelude
import CoreSyn
import DsMonad
import CoreUtils
import MkCore
import MkId
import ForeignCall
import DataCon
import DsUtils
import TcType
import Type
import Id ( Id )
import Coercion
import PrimOp
import TysPrim
import TyCon
import TysWiredIn
import BasicTypes
import Literal
import PrelNames
import DynFlags
import Outputable
import Util
import Data.Maybe
{-
Desugaring of @ccall@s consists of adding some state manipulation,
unboxing any boxed primitive arguments and boxing the result if
desired.
The state stuff just consists of adding in
@PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
The unboxing is straightforward, as all information needed to unbox is
available from the type. For each boxed-primitive argument, we
transform:
\begin{verbatim}
_ccall_ foo [ r, t1, ... tm ] e1 ... em
|
|
V
case e1 of { T1# x1# ->
...
case em of { Tm# xm# -> xm#
ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
} ... }
\end{verbatim}
The reboxing of a @_ccall_@ result is a bit tricker: the types don't
contain information about the state-pairing functions so we have to
keep a list of \tr{(type, s-p-function)} pairs. We transform as
follows:
\begin{verbatim}
ccall# foo [ r, t1#, ... tm# ] e1# ... em#
|
|
V
\ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
(StateAnd<r># result# state#) -> (R# result#, realWorld#)
\end{verbatim}
-}
dsCCall :: CLabelString -- C routine to invoke
-> [CoreExpr] -- Arguments (desugared)
-- Precondition: none have levity-polymorphic types
-> Safety -- Safety of the call
-> Type -- Type of the result: IO t
-> DsM CoreExpr -- Result, of type ???
dsCCall lbl args may_gc result_ty
= do (unboxed_args, arg_wrappers) <- mapAndUnzipM unboxArg args
(ccall_result_ty, res_wrapper) <- boxResult result_ty
uniq <- newUnique
dflags <- getDynFlags
let
target = StaticTarget NoSourceText lbl Nothing True
the_fcall = CCall (CCallSpec target CCallConv may_gc)
the_prim_app = mkFCall dflags uniq the_fcall unboxed_args ccall_result_ty
return (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
mkFCall :: DynFlags -> Unique -> ForeignCall
-> [CoreExpr] -- Args
-> Type -- Result type
-> CoreExpr
-- Construct the ccall. The only tricky bit is that the ccall Id should have
-- no free vars, so if any of the arg tys do we must give it a polymorphic type.
-- [I forget *why* it should have no free vars!]
-- For example:
-- mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
--
-- Here we build a ccall thus
-- (ccallid::(forall a b. StablePtr (a -> b) -> Addr -> Char -> IO Addr))
-- a b s x c
mkFCall dflags uniq the_fcall val_args res_ty
= ASSERT( all isTyVar tyvars ) -- this must be true because the type is top-level
mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
where
arg_tys = map exprType val_args
body_ty = (mkVisFunTys arg_tys res_ty)
tyvars = tyCoVarsOfTypeWellScoped body_ty
ty = mkInvForAllTys tyvars body_ty
the_fcall_id = mkFCallId dflags uniq the_fcall ty
unboxArg :: CoreExpr -- The supplied argument, not levity-polymorphic
-> DsM (CoreExpr, -- To pass as the actual argument
CoreExpr -> CoreExpr -- Wrapper to unbox the arg
)
-- Example: if the arg is e::Int, unboxArg will return
-- (x#::Int#, \W. case x of I# x# -> W)
-- where W is a CoreExpr that probably mentions x#
-- always returns a non-levity-polymorphic expression
unboxArg arg
-- Primitive types: nothing to unbox
| isPrimitiveType arg_ty
= return (arg, \body -> body)
-- Recursive newtypes
| Just(co, _rep_ty) <- topNormaliseNewType_maybe arg_ty
= unboxArg (mkCastDs arg co)
-- Booleans
| Just tc <- tyConAppTyCon_maybe arg_ty,
tc `hasKey` boolTyConKey
= do dflags <- getDynFlags
prim_arg <- newSysLocalDs intPrimTy
return (Var prim_arg,
\ body -> Case (mkWildCase arg arg_ty intPrimTy
[(DataAlt falseDataCon,[],mkIntLit dflags 0),
(DataAlt trueDataCon, [],mkIntLit dflags 1)])
-- In increasing tag order!
prim_arg
(exprType body)
[(DEFAULT,[],body)])
-- Data types with a single constructor, which has a single, primitive-typed arg
-- This deals with Int, Float etc; also Ptr, ForeignPtr
| is_product_type && data_con_arity == 1
= ASSERT2(isUnliftedType data_con_arg_ty1, pprType arg_ty)
-- Typechecker ensures this
do case_bndr <- newSysLocalDs arg_ty
prim_arg <- newSysLocalDs data_con_arg_ty1
return (Var prim_arg,
\ body -> Case arg case_bndr (exprType body) [(DataAlt data_con,[prim_arg],body)]
)
-- Byte-arrays, both mutable and otherwise; hack warning
-- We're looking for values of type ByteArray, MutableByteArray
-- data ByteArray ix = ByteArray ix ix ByteArray#
-- data MutableByteArray s ix = MutableByteArray ix ix (MutableByteArray# s)
| is_product_type &&
data_con_arity == 3 &&
isJust maybe_arg3_tycon &&
(arg3_tycon == byteArrayPrimTyCon ||
arg3_tycon == mutableByteArrayPrimTyCon)
= do case_bndr <- newSysLocalDs arg_ty
vars@[_l_var, _r_var, arr_cts_var] <- newSysLocalsDs data_con_arg_tys
return (Var arr_cts_var,
\ body -> Case arg case_bndr (exprType body) [(DataAlt data_con,vars,body)]
)
| otherwise
= do l <- getSrcSpanDs
pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
where
arg_ty = exprType arg
maybe_product_type = splitDataProductType_maybe arg_ty
is_product_type = isJust maybe_product_type
Just (_, _, data_con, data_con_arg_tys) = maybe_product_type
data_con_arity = dataConSourceArity data_con
(data_con_arg_ty1 : _) = data_con_arg_tys
(_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
maybe_arg3_tycon = tyConAppTyCon_maybe data_con_arg_ty3
Just arg3_tycon = maybe_arg3_tycon
boxResult :: Type
-> DsM (Type, CoreExpr -> CoreExpr)
-- Takes the result of the user-level ccall:
-- either (IO t),
-- or maybe just t for a side-effect-free call
-- Returns a wrapper for the primitive ccall itself, along with the
-- type of the result of the primitive ccall. This result type
-- will be of the form
-- State# RealWorld -> (# State# RealWorld, t' #)
-- where t' is the unwrapped form of t. If t is simply (), then
-- the result type will be
-- State# RealWorld -> (# State# RealWorld #)
boxResult result_ty
| Just (io_tycon, io_res_ty) <- tcSplitIOType_maybe result_ty
-- isIOType_maybe handles the case where the type is a
-- simple wrapping of IO. E.g.
-- newtype Wrap a = W (IO a)
-- No coercion necessary because its a non-recursive newtype
-- (If we wanted to handle a *recursive* newtype too, we'd need
-- another case, and a coercion.)
-- The result is IO t, so wrap the result in an IO constructor
= do { res <- resultWrapper io_res_ty
; let extra_result_tys
= case res of
(Just ty,_)
| isUnboxedTupleType ty
-> let Just ls = tyConAppArgs_maybe ty in tail ls
_ -> []
return_result state anss
= mkCoreUbxTup
(realWorldStatePrimTy : io_res_ty : extra_result_tys)
(state : anss)
; (ccall_res_ty, the_alt) <- mk_alt return_result res
; state_id <- newSysLocalDs realWorldStatePrimTy
; let io_data_con = head (tyConDataCons io_tycon)
toIOCon = dataConWrapId io_data_con
wrap the_call =
mkApps (Var toIOCon)
[ Type io_res_ty,
Lam state_id $
mkWildCase (App the_call (Var state_id))
ccall_res_ty
(coreAltType the_alt)
[the_alt]
]
; return (realWorldStatePrimTy `mkVisFunTy` ccall_res_ty, wrap) }
boxResult result_ty
= do -- It isn't IO, so do unsafePerformIO
-- It's not conveniently available, so we inline it
res <- resultWrapper result_ty
(ccall_res_ty, the_alt) <- mk_alt return_result res
let
wrap = \ the_call -> mkWildCase (App the_call (Var realWorldPrimId))
ccall_res_ty
(coreAltType the_alt)
[the_alt]
return (realWorldStatePrimTy `mkVisFunTy` ccall_res_ty, wrap)
where
return_result _ [ans] = ans
return_result _ _ = panic "return_result: expected single result"
mk_alt :: (Expr Var -> [Expr Var] -> Expr Var)
-> (Maybe Type, Expr Var -> Expr Var)
-> DsM (Type, (AltCon, [Id], Expr Var))
mk_alt return_result (Nothing, wrap_result)
= do -- The ccall returns ()
state_id <- newSysLocalDs realWorldStatePrimTy
let
the_rhs = return_result (Var state_id)
[wrap_result (panic "boxResult")]
ccall_res_ty = mkTupleTy Unboxed [realWorldStatePrimTy]
the_alt = (DataAlt (tupleDataCon Unboxed 1), [state_id], the_rhs)
return (ccall_res_ty, the_alt)
mk_alt return_result (Just prim_res_ty, wrap_result)
= -- The ccall returns a non-() value
ASSERT2( isPrimitiveType prim_res_ty, ppr prim_res_ty )
-- True because resultWrapper ensures it is so
do { result_id <- newSysLocalDs prim_res_ty
; state_id <- newSysLocalDs realWorldStatePrimTy
; let the_rhs = return_result (Var state_id)
[wrap_result (Var result_id)]
ccall_res_ty = mkTupleTy Unboxed [realWorldStatePrimTy, prim_res_ty]
the_alt = (DataAlt (tupleDataCon Unboxed 2), [state_id, result_id], the_rhs)
; return (ccall_res_ty, the_alt) }
resultWrapper :: Type
-> DsM (Maybe Type, -- Type of the expected result, if any
CoreExpr -> CoreExpr) -- Wrapper for the result
-- resultWrapper deals with the result *value*
-- E.g. foreign import foo :: Int -> IO T
-- Then resultWrapper deals with marshalling the 'T' part
-- So if resultWrapper ty = (Just ty_rep, marshal)
-- then marshal (e :: ty_rep) :: ty
-- That is, 'marshal' wrape the result returned by the foreign call,
-- of type ty_rep, into the value Haskell expected, of type 'ty'
--
-- Invariant: ty_rep is always a primitive type
-- i.e. (isPrimitiveType ty_rep) is True
resultWrapper result_ty
-- Base case 1: primitive types
| isPrimitiveType result_ty
= return (Just result_ty, \e -> e)
-- Base case 2: the unit type ()
| Just (tc,_) <- maybe_tc_app
, tc `hasKey` unitTyConKey
= return (Nothing, \_ -> Var unitDataConId)
-- Base case 3: the boolean type
| Just (tc,_) <- maybe_tc_app
, tc `hasKey` boolTyConKey
= do { dflags <- getDynFlags
; let marshal_bool e
= mkWildCase e intPrimTy boolTy
[ (DEFAULT ,[],Var trueDataConId )
, (LitAlt (mkLitInt dflags 0),[],Var falseDataConId)]
; return (Just intPrimTy, marshal_bool) }
-- Newtypes
| Just (co, rep_ty) <- topNormaliseNewType_maybe result_ty
= do { (maybe_ty, wrapper) <- resultWrapper rep_ty
; return (maybe_ty, \e -> mkCastDs (wrapper e) (mkSymCo co)) }
-- The type might contain foralls (eg. for dummy type arguments,
-- referring to 'Ptr a' is legal).
| Just (tyvar, rest) <- splitForAllTy_maybe result_ty
= do { (maybe_ty, wrapper) <- resultWrapper rest
; return (maybe_ty, \e -> Lam tyvar (wrapper e)) }
-- Data types with a single constructor, which has a single arg
-- This includes types like Ptr and ForeignPtr
| Just (tycon, tycon_arg_tys) <- maybe_tc_app
, Just data_con <- isDataProductTyCon_maybe tycon -- One constructor, no existentials
, [unwrapped_res_ty] <- dataConInstOrigArgTys data_con tycon_arg_tys -- One argument
= do { dflags <- getDynFlags
; (maybe_ty, wrapper) <- resultWrapper unwrapped_res_ty
; let narrow_wrapper = maybeNarrow dflags tycon
marshal_con e = Var (dataConWrapId data_con)
`mkTyApps` tycon_arg_tys
`App` wrapper (narrow_wrapper e)
; return (maybe_ty, marshal_con) }
| otherwise
= pprPanic "resultWrapper" (ppr result_ty)
where
maybe_tc_app = splitTyConApp_maybe result_ty
-- When the result of a foreign call is smaller than the word size, we
-- need to sign- or zero-extend the result up to the word size. The C
-- standard appears to say that this is the responsibility of the
-- caller, not the callee.
maybeNarrow :: DynFlags -> TyCon -> (CoreExpr -> CoreExpr)
maybeNarrow dflags tycon
| tycon `hasKey` int8TyConKey = \e -> App (Var (mkPrimOpId Narrow8IntOp)) e
| tycon `hasKey` int16TyConKey = \e -> App (Var (mkPrimOpId Narrow16IntOp)) e
| tycon `hasKey` int32TyConKey
&& wORD_SIZE dflags > 4 = \e -> App (Var (mkPrimOpId Narrow32IntOp)) e
| tycon `hasKey` word8TyConKey = \e -> App (Var (mkPrimOpId Narrow8WordOp)) e
| tycon `hasKey` word16TyConKey = \e -> App (Var (mkPrimOpId Narrow16WordOp)) e
| tycon `hasKey` word32TyConKey
&& wORD_SIZE dflags > 4 = \e -> App (Var (mkPrimOpId Narrow32WordOp)) e
| otherwise = id
|
sdiehl/ghc
|
compiler/deSugar/DsCCall.hs
|
bsd-3-clause
| 14,632 | 0 | 19 | 4,478 | 2,714 | 1,428 | 1,286 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
#if __GLASGOW_HASKELL__ >= 707
{-# LANGUAGE RoleAnnotations #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Control.Lens.Internal.Context
-- Copyright : (C) 2012-2016 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
----------------------------------------------------------------------------
module Control.Lens.Internal.Context
( IndexedFunctor(..)
, IndexedComonad(..)
, IndexedComonadStore(..)
, Sellable(..)
, Context(..), Context'
, Pretext(..), Pretext'
, PretextT(..), PretextT'
) where
import Prelude ()
import Control.Arrow
import qualified Control.Category as C
import Control.Comonad
import Control.Comonad.Store.Class
import Control.Lens.Internal.Indexed
import Control.Lens.Internal.Prelude
import Data.Profunctor.Rep
import Prelude hiding ((.),id)
------------------------------------------------------------------------------
-- IndexedFunctor
------------------------------------------------------------------------------
-- | This is a Bob Atkey -style 2-argument indexed functor.
--
-- It exists as a superclass for 'IndexedComonad' and expresses the functoriality
-- of an 'IndexedComonad' in its third argument.
class IndexedFunctor w where
ifmap :: (s -> t) -> w a b s -> w a b t
------------------------------------------------------------------------------
-- IndexedComonad
------------------------------------------------------------------------------
-- | This is a Bob Atkey -style 2-argument indexed comonad.
--
-- It exists as a superclass for 'IndexedComonad' and expresses the functoriality
-- of an 'IndexedComonad' in its third argument.
--
-- The notion of indexed monads is covered in more depth in Bob Atkey's
-- "Parameterized Notions of Computation" <http://bentnib.org/paramnotions-jfp.pdf>
-- and that construction is dualized here.
class IndexedFunctor w => IndexedComonad w where
#if __GLASGOW_HASKELL__ >= 708
{-# MINIMAL iextract, (iduplicate | iextend) #-}
#endif
-- | extract from an indexed comonadic value when the indices match.
iextract :: w a a t -> t
-- | duplicate an indexed comonadic value splitting the index.
iduplicate :: w a c t -> w a b (w b c t)
iduplicate = iextend id
{-# INLINE iduplicate #-}
-- | extend a indexed comonadic computation splitting the index.
iextend :: (w b c t -> r) -> w a c t -> w a b r
iextend f = ifmap f . iduplicate
{-# INLINE iextend #-}
------------------------------------------------------------------------------
-- IndexedComonadStore
------------------------------------------------------------------------------
-- | This is an indexed analogue to 'ComonadStore' for when you are working with an
-- 'IndexedComonad'.
class IndexedComonad w => IndexedComonadStore w where
-- | This is the generalization of 'pos' to an indexed comonad store.
ipos :: w a c t -> a
-- | This is the generalization of 'peek' to an indexed comonad store.
ipeek :: c -> w a c t -> t
ipeek c = iextract . iseek c
{-# INLINE ipeek #-}
-- | This is the generalization of 'peeks' to an indexed comonad store.
ipeeks :: (a -> c) -> w a c t -> t
ipeeks f = iextract . iseeks f
{-# INLINE ipeeks #-}
-- | This is the generalization of 'seek' to an indexed comonad store.
iseek :: b -> w a c t -> w b c t
-- | This is the generalization of 'seeks' to an indexed comonad store.
iseeks :: (a -> b) -> w a c t -> w b c t
-- | This is the generalization of 'experiment' to an indexed comonad store.
iexperiment :: Functor f => (b -> f c) -> w b c t -> f t
iexperiment bfc wbct = (`ipeek` wbct) <$> bfc (ipos wbct)
{-# INLINE iexperiment #-}
-- | We can always forget the rest of the structure of 'w' and obtain a simpler
-- indexed comonad store model called 'Context'.
context :: w a b t -> Context a b t
context wabt = Context (`ipeek` wabt) (ipos wabt)
{-# INLINE context #-}
------------------------------------------------------------------------------
-- Sellable
------------------------------------------------------------------------------
-- | This is used internally to construct a 'Control.Lens.Internal.Bazaar.Bazaar', 'Context' or 'Pretext'
-- from a singleton value.
class Corepresentable p => Sellable p w | w -> p where
sell :: p a (w a b b)
------------------------------------------------------------------------------
-- Context
------------------------------------------------------------------------------
-- | The indexed store can be used to characterize a 'Control.Lens.Lens.Lens'
-- and is used by 'Control.Lens.Lens.cloneLens'.
--
-- @'Context' a b t@ is isomorphic to
-- @newtype 'Context' a b t = 'Context' { runContext :: forall f. 'Functor' f => (a -> f b) -> f t }@,
-- and to @exists s. (s, 'Control.Lens.Lens.Lens' s t a b)@.
--
-- A 'Context' is like a 'Control.Lens.Lens.Lens' that has already been applied to a some structure.
data Context a b t = Context (b -> t) a
-- type role Context representational representational representational
instance IndexedFunctor Context where
ifmap f (Context g t) = Context (f . g) t
{-# INLINE ifmap #-}
instance IndexedComonad Context where
iextract (Context f a) = f a
{-# INLINE iextract #-}
iduplicate (Context f a) = Context (Context f) a
{-# INLINE iduplicate #-}
iextend g (Context f a) = Context (g . Context f) a
{-# INLINE iextend #-}
instance IndexedComonadStore Context where
ipos (Context _ a) = a
{-# INLINE ipos #-}
ipeek b (Context g _) = g b
{-# INLINE ipeek #-}
ipeeks f (Context g a) = g (f a)
{-# INLINE ipeeks #-}
iseek a (Context g _) = Context g a
{-# INLINE iseek #-}
iseeks f (Context g a) = Context g (f a)
{-# INLINE iseeks #-}
iexperiment f (Context g a) = g <$> f a
{-# INLINE iexperiment #-}
context = id
{-# INLINE context #-}
instance Functor (Context a b) where
fmap f (Context g t) = Context (f . g) t
{-# INLINE fmap #-}
instance a ~ b => Comonad (Context a b) where
extract (Context f a) = f a
{-# INLINE extract #-}
duplicate (Context f a) = Context (Context f) a
{-# INLINE duplicate #-}
extend g (Context f a) = Context (g . Context f) a
{-# INLINE extend #-}
instance a ~ b => ComonadStore a (Context a b) where
pos = ipos
{-# INLINE pos #-}
peek = ipeek
{-# INLINE peek #-}
peeks = ipeeks
{-# INLINE peeks #-}
seek = iseek
{-# INLINE seek #-}
seeks = iseeks
{-# INLINE seeks #-}
experiment = iexperiment
{-# INLINE experiment #-}
instance Sellable (->) Context where
sell = Context id
{-# INLINE sell #-}
-- | @type 'Context'' a s = 'Context' a a s@
type Context' a = Context a a
------------------------------------------------------------------------------
-- Pretext
------------------------------------------------------------------------------
-- | This is a generalized form of 'Context' that can be repeatedly cloned with less
-- impact on its performance, and which permits the use of an arbitrary 'Conjoined'
-- 'Profunctor'
newtype Pretext p a b t = Pretext { runPretext :: forall f. Functor f => p a (f b) -> f t }
-- type role Pretext representational nominal nominal nominal
-- | @type 'Pretext'' p a s = 'Pretext' p a a s@
type Pretext' p a = Pretext p a a
instance IndexedFunctor (Pretext p) where
ifmap f (Pretext k) = Pretext (fmap f . k)
{-# INLINE ifmap #-}
instance Functor (Pretext p a b) where
fmap = ifmap
{-# INLINE fmap #-}
instance Conjoined p => IndexedComonad (Pretext p) where
iextract (Pretext m) = runIdentity $ m (arr Identity)
{-# INLINE iextract #-}
iduplicate (Pretext m) = getCompose $ m (Compose #. distrib sell C.. sell)
{-# INLINE iduplicate #-}
instance (a ~ b, Conjoined p) => Comonad (Pretext p a b) where
extract = iextract
{-# INLINE extract #-}
duplicate = iduplicate
{-# INLINE duplicate #-}
instance Conjoined p => IndexedComonadStore (Pretext p) where
ipos (Pretext m) = getConst $ coarr m $ arr Const
{-# INLINE ipos #-}
ipeek a (Pretext m) = runIdentity $ coarr m $ arr (\_ -> Identity a)
{-# INLINE ipeek #-}
ipeeks f (Pretext m) = runIdentity $ coarr m $ arr (Identity . f)
{-# INLINE ipeeks #-}
iseek a (Pretext m) = Pretext (lmap (lmap (const a)) m)
{-# INLINE iseek #-}
iseeks f (Pretext m) = Pretext (lmap (lmap f) m)
{-# INLINE iseeks #-}
iexperiment f (Pretext m) = coarr m (arr f)
{-# INLINE iexperiment #-}
context (Pretext m) = coarr m (arr sell)
{-# INLINE context #-}
instance (a ~ b, Conjoined p) => ComonadStore a (Pretext p a b) where
pos = ipos
{-# INLINE pos #-}
peek = ipeek
{-# INLINE peek #-}
peeks = ipeeks
{-# INLINE peeks #-}
seek = iseek
{-# INLINE seek #-}
seeks = iseeks
{-# INLINE seeks #-}
experiment = iexperiment
{-# INLINE experiment #-}
instance Corepresentable p => Sellable p (Pretext p) where
sell = cotabulate $ \ w -> Pretext (`cosieve` w)
{-# INLINE sell #-}
------------------------------------------------------------------------------
-- PretextT
------------------------------------------------------------------------------
-- | This is a generalized form of 'Context' that can be repeatedly cloned with less
-- impact on its performance, and which permits the use of an arbitrary 'Conjoined'
-- 'Profunctor'.
--
-- The extra phantom 'Functor' is used to let us lie and claim
-- 'Control.Lens.Getter.Getter'-compatibility under limited circumstances.
-- This is used internally to permit a number of combinators to gracefully
-- degrade when applied to a 'Control.Lens.Fold.Fold' or
-- 'Control.Lens.Getter.Getter'.
newtype PretextT p (g :: * -> *) a b t = PretextT { runPretextT :: forall f. Functor f => p a (f b) -> f t }
#if __GLASGOW_HASKELL__ >= 707
-- really we want PretextT p g a b t to permit the last 3 arguments to be representational iff p and f accept representational arguments
-- but that isn't currently an option in GHC
type role PretextT representational nominal nominal nominal nominal
#endif
-- | @type 'PretextT'' p g a s = 'PretextT' p g a a s@
type PretextT' p g a = PretextT p g a a
instance IndexedFunctor (PretextT p g) where
ifmap f (PretextT k) = PretextT (fmap f . k)
{-# INLINE ifmap #-}
instance Functor (PretextT p g a b) where
fmap = ifmap
{-# INLINE fmap #-}
instance Conjoined p => IndexedComonad (PretextT p g) where
iextract (PretextT m) = runIdentity $ m (arr Identity)
{-# INLINE iextract #-}
iduplicate (PretextT m) = getCompose $ m (Compose #. distrib sell C.. sell)
{-# INLINE iduplicate #-}
instance (a ~ b, Conjoined p) => Comonad (PretextT p g a b) where
extract = iextract
{-# INLINE extract #-}
duplicate = iduplicate
{-# INLINE duplicate #-}
instance Conjoined p => IndexedComonadStore (PretextT p g) where
ipos (PretextT m) = getConst $ coarr m $ arr Const
{-# INLINE ipos #-}
ipeek a (PretextT m) = runIdentity $ coarr m $ arr (\_ -> Identity a)
{-# INLINE ipeek #-}
ipeeks f (PretextT m) = runIdentity $ coarr m $ arr (Identity . f)
{-# INLINE ipeeks #-}
iseek a (PretextT m) = PretextT (lmap (lmap (const a)) m)
{-# INLINE iseek #-}
iseeks f (PretextT m) = PretextT (lmap (lmap f) m)
{-# INLINE iseeks #-}
iexperiment f (PretextT m) = coarr m (arr f)
{-# INLINE iexperiment #-}
context (PretextT m) = coarr m (arr sell)
{-# INLINE context #-}
instance (a ~ b, Conjoined p) => ComonadStore a (PretextT p g a b) where
pos = ipos
{-# INLINE pos #-}
peek = ipeek
{-# INLINE peek #-}
peeks = ipeeks
{-# INLINE peeks #-}
seek = iseek
{-# INLINE seek #-}
seeks = iseeks
{-# INLINE seeks #-}
experiment = iexperiment
{-# INLINE experiment #-}
instance Corepresentable p => Sellable p (PretextT p g) where
sell = cotabulate $ \ w -> PretextT (`cosieve` w)
{-# INLINE sell #-}
instance (Profunctor p, Contravariant g) => Contravariant (PretextT p g a b) where
contramap _ = (<$) (error "contramap: PretextT")
{-# INLINE contramap #-}
------------------------------------------------------------------------------
-- Utilities
------------------------------------------------------------------------------
-- | We can convert any 'Conjoined' 'Profunctor' to a function,
-- possibly losing information about an index in the process.
coarr :: (Representable q, Comonad (Rep q)) => q a b -> a -> b
coarr qab = extract . sieve qab
{-# INLINE coarr #-}
|
ddssff/lens
|
src/Control/Lens/Internal/Context.hs
|
bsd-3-clause
| 12,647 | 0 | 12 | 2,416 | 2,744 | 1,499 | 1,245 | -1 | -1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
module Analytics
( runAnalytics
, analyzeBoard
) where
import Data.Aeson (eitherDecode, FromJSON)
import Data.Either (rights, lefts)
import Data.Typeable
import Data.List
import Data.Maybe
import Text.Format
import Control.Monad.IO.Class (liftIO, MonadIO)
import Control.Monad.Catch
import Control.Monad.Logger
import Control.Monad.Reader
import Control.Applicative
import Control.Concurrent.ParallelIO
import Control.Concurrent (threadDelay)
import qualified Data.Text as T
import qualified Data.Text.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as C (pack)
import GHC.Generics
import Debug.Trace
import Network.HTTP (simpleHTTP, getRequest, getResponseBody)
import Hakyll.Web.Html (stripTags)
import qualified Post as P
import qualified Logging as Log
import Types
newtype Analytics a = Analytics { unAnalytics :: ReaderT Log.Config (LoggingT IO) a }
deriving (Functor, Applicative, Monad, MonadIO, MonadLogger, MonadReader Log.Config)
runAnalytics :: Analytics a -> IO a
runAnalytics a = runStdoutLoggingT $ runReaderT (unAnalytics a) (Log.mkConfig "Analytics")
bmemeCount :: Meme -> Board -> Int
bmemeCount meme board = sum $ map (memeCount meme) board
postCount :: Thread -> Int
postCount x = length $ posts x
memeCount :: Meme -> Thread -> Int
memeCount meme thread = sum $ (map wordCount (alias meme)) <*> (posts thread)
where wordCount meme post = T.count (T.toLower meme) (T.toLower (fromMaybe "" (P.com post)))
catToThreadNo :: Catalog -> [ThreadID]
catToThreadNo cat = map no (concatMap threads cat)
dubs :: Board -> [Int]
dubs b = filter isDubs $ map P.no (concatMap posts b)
where
isDubs :: Int -> Bool
isDubs x = case digs x of
x:y:xs -> x == y
x -> error $ "Chan.dubs malformed post number" ++ (show x )
-- convert number to list of digits
digs :: Integral x => x -> [x]
digs 0 = []
digs x = x `mod` 10 : digs (x `div` 10)
containsMeme :: T.Text -> P.Post -> Bool
containsMeme meme post
= case (P.com post) of
Nothing -> False
Just com -> T.isInfixOf (T.toLower meme) (T.toLower com)
isAnon :: P.Post -> Bool
isAnon p
= case (P.name p) of
Nothing -> False
Just n -> n == "Anonymous"
isTripcode :: P.Post -> Bool
isTripcode p
= case (P.name p) of
Nothing -> False
Just n -> T.isInfixOf " !!" n
displayPost :: P.Post -> (ThreadID, String)
displayPost post = (P.no post, stripTags $ T.unpack (fromMaybe "" (P.com post)))
analyzeBoard :: (MonadReader Log.Config m, MonadLogger m) => Board -> m ()
analyzeBoard board = do
recordMemes board
recordCount board
recordPosts board
recordDubs board
recordTripcodes board
recordMemes :: (MonadReader Log.Config m, MonadLogger m) => Board -> m ()
recordMemes board = do
Log.info "Top Memes:"
Log.info . show $ map (\x -> (x, bmemeCount x board)) memes
recordCount :: (MonadReader Log.Config m, MonadLogger m) => Board -> m ()
recordCount board = do
Log.info "Post Counts"
let pcs = map postCount board
Log.info $ show pcs
Log.info $ format "Average post count: {0}." [show (realToFrac (sum pcs) / (genericLength pcs))]
recordPosts :: (MonadReader Log.Config m, MonadLogger m) => Board -> m ()
recordPosts board = do
let haskellPosts = filter (containsMeme "haskell") (concatMap posts board)
Log.info $ format "Found {0} haskell posts:\n{1} " [show (length haskellPosts), concatMap (show . displayPost) haskellPosts]
recordDubs :: (MonadReader Log.Config m, MonadLogger m) => Board -> m ()
recordDubs board = do
let ds = map show (dubs board)
Log.info $ format "Found {0} dubs in {1} posts: " [(show (length ds)), show $ length (concatMap posts board)]
Log.info $ unwords ds
recordTripcodes :: (MonadReader Log.Config m, MonadLogger m) => Board -> m ()
recordTripcodes b = do
let ps = concatMap posts b
let anons = filter isAnon ps
let tripcodes = filter isTripcode ps
let tripcodePercent = ((fromIntegral $ length tripcodes) / (fromIntegral $length ps))
Log.info $ format "Found {0} Anonymous posts and {1} tripcode posts out of {2} total posts." [show $ length anons, show $ length tripcodes, show $ length ps]
Log.info $ format "That's {0}" [status tripcodePercent]
where
status :: (Real a, Fractional a)=> a -> String
status tripcodePercent
| tripcodePercent == 0 = "The Best Day Ever!"
| tripcodePercent > 0.1 = "Terrible."
| otherwise = "Same old, same old.."
showT :: Show a => a -> T.Text
showT = T.pack . show
|
k4smiley/Chan
|
src/Analytics.hs
|
bsd-3-clause
| 4,721 | 0 | 15 | 986 | 1,691 | 869 | 822 | 110 | 3 |
import Control.Monad (unless)
import qualified Data.ByteString as BS
import qualified Data.HashMap.Strict as HM
import qualified Data.Vector as V
import Data.Yaml
import System.Environment (getArgs)
import System.IO (stdout)
main :: IO ()
main = do
vs <- getArgs >>= decodeFiles
unless (null vs) $ do
let bs = encode $ foldr1 mergeObjects vs
BS.hPut stdout bs
decodeFiles :: [String] -> IO [Value]
decodeFiles = mapM $ \f -> do
e <- decodeFileEither f
case e of
Left ex -> error $ showParseException ex
Right v -> return v
mergeObjects :: Value -> Value -> Value
mergeObjects (Object o1) (Object o2) = Object $ HM.unionWith mergeObjects o1 o2
mergeObjects (Array a1) (Array a2) = Array $ (V.++) a1 a2
mergeObjects v1 v2 = error $ "Cannot merge " ++ show v1 ++ " with " ++ show v2
showParseException :: ParseException -> String
showParseException (InvalidYaml (Just ex)) = showYamlException ex
showParseException (AesonException s) = s
showParseException ex = show ex
showYamlException :: YamlException -> String
showYamlException (YamlException s) = show s
showYamlException (YamlParseException p c m) = p ++ " " ++ c ++ " at " ++ show m
|
djoyner/yamlmerge
|
Main.hs
|
bsd-3-clause
| 1,224 | 0 | 14 | 273 | 443 | 225 | 218 | 30 | 2 |
{- |
Copyright : Galois, Inc. 2012-2014
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable (language extensions)
-}
module Main where
import System.Environment (getArgs)
import Verifier.SAW
processFile :: FilePath -> IO ()
processFile file = do
sc <- mkSharedContext preludeModule
tm <- scReadExternal sc =<< readFile file
putStrLn $ "Shared size: " ++ show (scSharedSize tm)
putStrLn $ "Tree size: " ++ show (scTreeSize tm)
main :: IO ()
main = mapM_ processFile =<< getArgs
|
iblumenfeld/saw-core
|
tools/extcore-info.hs
|
bsd-3-clause
| 547 | 0 | 10 | 101 | 131 | 64 | 67 | 11 | 1 |
import Data.Pipe
import GHC.Event
|
YoshikuniJujo/xmpipe
|
test/testMergeChan.hs
|
bsd-3-clause
| 36 | 0 | 4 | 6 | 11 | 6 | 5 | 2 | 0 |
import Disorder.Core.Main
import qualified Test.Zodiac.HttpClient.Request
import qualified Test.Zodiac.HttpClient.TSRP
main :: IO ()
main =
disorderMain [
Test.Zodiac.HttpClient.Request.tests
, Test.Zodiac.HttpClient.TSRP.tests
]
|
ambiata/zodiac
|
zodiac-http-client/test/test.hs
|
bsd-3-clause
| 252 | 0 | 7 | 42 | 57 | 37 | 20 | 8 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
-- |
-- Module: $HEADER$
-- Description: TODO
-- Copyright: (c) 2016 Peter Trško
-- License: BSD3
--
-- Stability: experimental
-- Portability: GHC specific language extensions.
--
-- TODO
module Data.DHT.DKS.Type.Message.JoinDone
( JoinDone(..)
)
where
import Data.Eq (Eq)
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import Text.Show (Show)
import Data.Default.Class (Default(def))
import Data.OverloadedRecords.TH (overloadedRecord)
import Data.DHT.DKS.Type.Hash (DksHash)
data JoinDone = JoinDone
{ _requester :: !DksHash
, _successor :: !DksHash
, _predecessor :: !DksHash
}
deriving (Eq, Generic, Show, Typeable)
overloadedRecord def ''JoinDone
|
FPBrno/dht-dks
|
src/Data/DHT/DKS/Type/Message/JoinDone.hs
|
bsd-3-clause
| 988 | 0 | 9 | 167 | 175 | 113 | 62 | 29 | 0 |
{-# LANGUAGE CPP #-}
module TcInteract (
solveSimpleGivens, -- Solves [EvVar],GivenLoc
solveSimpleWanteds -- Solves Cts
) where
#include "HsVersions.h"
import BasicTypes ()
import TcCanonical
import TcFlatten
import VarSet
import Type
import Unify
import InstEnv( DFunInstType, lookupInstEnv, instanceDFunId )
import CoAxiom(sfInteractTop, sfInteractInert)
import Var
import TcType
import PrelNames (knownNatClassName, knownSymbolClassName, ipClassNameKey )
import Id( idType )
import Class
import TyCon
import FunDeps
import FamInst
import Inst( tyVarsOfCt )
import TcEvidence
import Outputable
import TcRnTypes
import TcErrors
import TcSMonad
import Bag
import Data.List( partition, foldl', deleteFirstsBy )
import VarEnv
import Control.Monad
import Maybes( isJust )
import Pair (Pair(..))
import Unique( hasKey )
import FastString ( sLit )
import DynFlags
import Util
{-
**********************************************************************
* *
* Main Interaction Solver *
* *
**********************************************************************
Note [Basic Simplifier Plan]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Pick an element from the WorkList if there exists one with depth
less than our context-stack depth.
2. Run it down the 'stage' pipeline. Stages are:
- canonicalization
- inert reactions
- spontaneous reactions
- top-level intreactions
Each stage returns a StopOrContinue and may have sideffected
the inerts or worklist.
The threading of the stages is as follows:
- If (Stop) is returned by a stage then we start again from Step 1.
- If (ContinueWith ct) is returned by a stage, we feed 'ct' on to
the next stage in the pipeline.
4. If the element has survived (i.e. ContinueWith x) the last stage
then we add him in the inerts and jump back to Step 1.
If in Step 1 no such element exists, we have exceeded our context-stack
depth and will simply fail.
Note [Unflatten after solving the simple wanteds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We unflatten after solving the wc_simples of an implication, and before attempting
to float. This means that
* The fsk/fmv flatten-skolems only survive during solveSimples. We don't
need to worry about then across successive passes over the constraint tree.
(E.g. we don't need the old ic_fsk field of an implication.
* When floating an equality outwards, we don't need to worry about floating its
associated flattening constraints.
* Another tricky case becomes easy: Trac #4935
type instance F True a b = a
type instance F False a b = b
[w] F c a b ~ gamma
(c ~ True) => a ~ gamma
(c ~ False) => b ~ gamma
Obviously this is soluble with gamma := F c a b, and unflattening
will do exactly that after solving the simple constraints and before
attempting the implications. Before, when we were not unflattening,
we had to push Wanted funeqs in as new givens. Yuk!
Another example that becomes easy: indexed_types/should_fail/T7786
[W] BuriedUnder sub k Empty ~ fsk
[W] Intersect fsk inv ~ s
[w] xxx[1] ~ s
[W] forall[2] . (xxx[1] ~ Empty)
=> Intersect (BuriedUnder sub k Empty) inv ~ Empty
Note [Running plugins on unflattened wanteds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There is an annoying mismatch between solveSimpleGivens and
solveSimpleWanteds, because the latter needs to fiddle with the inert
set, unflatten and and zonk the wanteds. It passes the zonked wanteds
to runTcPluginsWanteds, which produces a replacement set of wanteds,
some additional insolubles and a flag indicating whether to go round
the loop again. If so, prepareInertsForImplications is used to remove
the previous wanteds (which will still be in the inert set). Note
that prepareInertsForImplications will discard the insolubles, so we
must keep track of them separately.
-}
solveSimpleGivens :: CtLoc -> [EvVar] -> TcS ()
solveSimpleGivens loc givens
| null givens -- Shortcut for common case
= return ()
| otherwise
= go (map mk_given_ct givens)
where
mk_given_ct ev_id = mkNonCanonical (CtGiven { ctev_evtm = EvId ev_id
, ctev_pred = evVarPred ev_id
, ctev_loc = loc })
go givens = do { solveSimples (listToBag givens)
; new_givens <- runTcPluginsGiven
; when (notNull new_givens) (go new_givens)
}
solveSimpleWanteds :: Cts -> TcS WantedConstraints
solveSimpleWanteds = go emptyBag
where
go insols0 wanteds
= do { solveSimples wanteds
; (implics, tv_eqs, fun_eqs, insols, others) <- getUnsolvedInerts
; unflattened_eqs <- unflatten tv_eqs fun_eqs
-- See Note [Unflatten after solving the simple wanteds]
; zonked <- zonkSimples (others `andCts` unflattened_eqs)
-- Postcondition is that the wl_simples are zonked
; (wanteds', insols', rerun) <- runTcPluginsWanted zonked
-- See Note [Running plugins on unflattened wanteds]
; let all_insols = insols0 `unionBags` insols `unionBags` insols'
; if rerun then do { updInertTcS prepareInertsForImplications
; go all_insols wanteds' }
else return (WC { wc_simple = wanteds'
, wc_insol = all_insols
, wc_impl = implics }) }
-- The main solver loop implements Note [Basic Simplifier Plan]
---------------------------------------------------------------
solveSimples :: Cts -> TcS ()
-- Returns the final InertSet in TcS
-- Has no effect on work-list or residual-iplications
-- The constraints are initially examined in left-to-right order
solveSimples cts
= {-# SCC "solveSimples" #-}
do { dyn_flags <- getDynFlags
; updWorkListTcS (\wl -> foldrBag extendWorkListCt wl cts)
; solve_loop (maxSubGoalDepth dyn_flags) }
where
solve_loop max_depth
= {-# SCC "solve_loop" #-}
do { sel <- selectNextWorkItem max_depth
; case sel of
NoWorkRemaining -- Done, successfuly (modulo frozen)
-> return ()
MaxDepthExceeded cnt ct -- Failure, depth exceeded
-> wrapErrTcS $ solverDepthErrorTcS cnt (ctEvidence ct)
NextWorkItem ct -- More work, loop around!
-> do { runSolverPipeline thePipeline ct; solve_loop max_depth } }
-- | Extract the (inert) givens and invoke the plugins on them.
-- Remove solved givens from the inert set and emit insolubles, but
-- return new work produced so that 'solveSimpleGivens' can feed it back
-- into the main solver.
runTcPluginsGiven :: TcS [Ct]
runTcPluginsGiven = do
(givens,_,_) <- fmap splitInertCans getInertCans
if null givens
then return []
else do
p <- runTcPlugins (givens,[],[])
let (solved_givens, _, _) = pluginSolvedCts p
updInertCans (removeInertCts solved_givens)
mapM_ emitInsoluble (pluginBadCts p)
return (pluginNewCts p)
-- | Given a bag of (flattened, zonked) wanteds, invoke the plugins on
-- them and produce an updated bag of wanteds (possibly with some new
-- work) and a bag of insolubles. The boolean indicates whether
-- 'solveSimpleWanteds' should feed the updated wanteds back into the
-- main solver.
runTcPluginsWanted :: Cts -> TcS (Cts, Cts, Bool)
runTcPluginsWanted zonked_wanteds
| isEmptyBag zonked_wanteds = return (zonked_wanteds, emptyBag, False)
| otherwise = do
(given,derived,_) <- fmap splitInertCans getInertCans
p <- runTcPlugins (given, derived, bagToList zonked_wanteds)
let (solved_givens, solved_deriveds, solved_wanteds) = pluginSolvedCts p
(_, _, wanteds) = pluginInputCts p
updInertCans (removeInertCts $ solved_givens ++ solved_deriveds)
mapM_ setEv solved_wanteds
return ( listToBag $ pluginNewCts p ++ wanteds
, listToBag $ pluginBadCts p
, notNull (pluginNewCts p) )
where
setEv :: (EvTerm,Ct) -> TcS ()
setEv (ev,ct) = case ctEvidence ct of
CtWanted {ctev_evar = evar} -> setWantedEvBind evar ev
_ -> panic "runTcPluginsWanted.setEv: attempt to solve non-wanted!"
-- | A triple of (given, derived, wanted) constraints to pass to plugins
type SplitCts = ([Ct], [Ct], [Ct])
-- | A solved triple of constraints, with evidence for wanteds
type SolvedCts = ([Ct], [Ct], [(EvTerm,Ct)])
-- | Represents collections of constraints generated by typechecker
-- plugins
data TcPluginProgress = TcPluginProgress
{ pluginInputCts :: SplitCts
-- ^ Original inputs to the plugins with solved/bad constraints
-- removed, but otherwise unmodified
, pluginSolvedCts :: SolvedCts
-- ^ Constraints solved by plugins
, pluginBadCts :: [Ct]
-- ^ Constraints reported as insoluble by plugins
, pluginNewCts :: [Ct]
-- ^ New constraints emitted by plugins
}
-- | Starting from a triple of (given, derived, wanted) constraints,
-- invoke each of the typechecker plugins in turn and return
--
-- * the remaining unmodified constraints,
-- * constraints that have been solved,
-- * constraints that are insoluble, and
-- * new work.
--
-- Note that new work generated by one plugin will not be seen by
-- other plugins on this pass (but the main constraint solver will be
-- re-invoked and they will see it later). There is no check that new
-- work differs from the original constraints supplied to the plugin:
-- the plugin itself should perform this check if necessary.
runTcPlugins :: SplitCts -> TcS TcPluginProgress
runTcPlugins all_cts = do
gblEnv <- getGblEnv
foldM do_plugin initialProgress (tcg_tc_plugins gblEnv)
where
do_plugin :: TcPluginProgress -> TcPluginSolver -> TcS TcPluginProgress
do_plugin p solver = do
result <- runTcPluginTcS (uncurry3 solver (pluginInputCts p))
return $ progress p result
progress :: TcPluginProgress -> TcPluginResult -> TcPluginProgress
progress p (TcPluginContradiction bad_cts) =
p { pluginInputCts = discard bad_cts (pluginInputCts p)
, pluginBadCts = bad_cts ++ pluginBadCts p
}
progress p (TcPluginOk solved_cts new_cts) =
p { pluginInputCts = discard (map snd solved_cts) (pluginInputCts p)
, pluginSolvedCts = add solved_cts (pluginSolvedCts p)
, pluginNewCts = new_cts ++ pluginNewCts p
}
initialProgress = TcPluginProgress all_cts ([], [], []) [] []
discard :: [Ct] -> SplitCts -> SplitCts
discard cts (xs, ys, zs) =
(xs `without` cts, ys `without` cts, zs `without` cts)
without :: [Ct] -> [Ct] -> [Ct]
without = deleteFirstsBy eqCt
eqCt :: Ct -> Ct -> Bool
eqCt c c' = case (ctEvidence c, ctEvidence c') of
(CtGiven pred _ _, CtGiven pred' _ _) -> pred `eqType` pred'
(CtWanted pred _ _, CtWanted pred' _ _) -> pred `eqType` pred'
(CtDerived pred _ , CtDerived pred' _ ) -> pred `eqType` pred'
(_ , _ ) -> False
add :: [(EvTerm,Ct)] -> SolvedCts -> SolvedCts
add xs scs = foldl' addOne scs xs
addOne :: SolvedCts -> (EvTerm,Ct) -> SolvedCts
addOne (givens, deriveds, wanteds) (ev,ct) = case ctEvidence ct of
CtGiven {} -> (ct:givens, deriveds, wanteds)
CtDerived{} -> (givens, ct:deriveds, wanteds)
CtWanted {} -> (givens, deriveds, (ev,ct):wanteds)
type WorkItem = Ct
type SimplifierStage = WorkItem -> TcS (StopOrContinue Ct)
data SelectWorkItem
= NoWorkRemaining -- No more work left (effectively we're done!)
| MaxDepthExceeded SubGoalCounter Ct
-- More work left to do but this constraint has exceeded
-- the maximum depth for one of the subgoal counters and we
-- must stop
| NextWorkItem Ct -- More work left, here's the next item to look at
selectNextWorkItem :: SubGoalDepth -- Max depth allowed
-> TcS SelectWorkItem
selectNextWorkItem max_depth
= updWorkListTcS_return pick_next
where
pick_next :: WorkList -> (SelectWorkItem, WorkList)
pick_next wl
= case selectWorkItem wl of
(Nothing,_)
-> (NoWorkRemaining,wl) -- No more work
(Just ct, new_wl)
| Just cnt <- subGoalDepthExceeded max_depth (ctLocDepth (ctLoc ct)) -- Depth exceeded
-> (MaxDepthExceeded cnt ct,new_wl)
(Just ct, new_wl)
-> (NextWorkItem ct, new_wl) -- New workitem and worklist
runSolverPipeline :: [(String,SimplifierStage)] -- The pipeline
-> WorkItem -- The work item
-> TcS ()
-- Run this item down the pipeline, leaving behind new work and inerts
runSolverPipeline pipeline workItem
= do { initial_is <- getTcSInerts
; traceTcS "Start solver pipeline {" $
vcat [ ptext (sLit "work item = ") <+> ppr workItem
, ptext (sLit "inerts = ") <+> ppr initial_is]
; bumpStepCountTcS -- One step for each constraint processed
; final_res <- run_pipeline pipeline (ContinueWith workItem)
; final_is <- getTcSInerts
; case final_res of
Stop ev s -> do { traceFireTcS ev s
; traceTcS "End solver pipeline (discharged) }"
(ptext (sLit "inerts =") <+> ppr final_is)
; return () }
ContinueWith ct -> do { traceFireTcS (ctEvidence ct) (ptext (sLit "Kept as inert"))
; traceTcS "End solver pipeline (not discharged) }" $
vcat [ ptext (sLit "final_item =") <+> ppr ct
, pprTvBndrs (varSetElems $ tyVarsOfCt ct)
, ptext (sLit "inerts =") <+> ppr final_is]
; insertInertItemTcS ct }
}
where run_pipeline :: [(String,SimplifierStage)] -> StopOrContinue Ct
-> TcS (StopOrContinue Ct)
run_pipeline [] res = return res
run_pipeline _ (Stop ev s) = return (Stop ev s)
run_pipeline ((stg_name,stg):stgs) (ContinueWith ct)
= do { traceTcS ("runStage " ++ stg_name ++ " {")
(text "workitem = " <+> ppr ct)
; res <- stg ct
; traceTcS ("end stage " ++ stg_name ++ " }") empty
; run_pipeline stgs res }
{-
Example 1:
Inert: {c ~ d, F a ~ t, b ~ Int, a ~ ty} (all given)
Reagent: a ~ [b] (given)
React with (c~d) ==> IR (ContinueWith (a~[b])) True []
React with (F a ~ t) ==> IR (ContinueWith (a~[b])) False [F [b] ~ t]
React with (b ~ Int) ==> IR (ContinueWith (a~[Int]) True []
Example 2:
Inert: {c ~w d, F a ~g t, b ~w Int, a ~w ty}
Reagent: a ~w [b]
React with (c ~w d) ==> IR (ContinueWith (a~[b])) True []
React with (F a ~g t) ==> IR (ContinueWith (a~[b])) True [] (can't rewrite given with wanted!)
etc.
Example 3:
Inert: {a ~ Int, F Int ~ b} (given)
Reagent: F a ~ b (wanted)
React with (a ~ Int) ==> IR (ContinueWith (F Int ~ b)) True []
React with (F Int ~ b) ==> IR Stop True [] -- after substituting we re-canonicalize and get nothing
-}
thePipeline :: [(String,SimplifierStage)]
thePipeline = [ ("canonicalization", TcCanonical.canonicalize)
, ("interact with inerts", interactWithInertsStage)
, ("top-level reactions", topReactionsStage) ]
{-
*********************************************************************************
* *
The interact-with-inert Stage
* *
*********************************************************************************
Note [The Solver Invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
We always add Givens first. So you might think that the solver has
the invariant
If the work-item is Given,
then the inert item must Given
But this isn't quite true. Suppose we have,
c1: [W] beta ~ [alpha], c2 : [W] blah, c3 :[W] alpha ~ Int
After processing the first two, we get
c1: [G] beta ~ [alpha], c2 : [W] blah
Now, c3 does not interact with the the given c1, so when we spontaneously
solve c3, we must re-react it with the inert set. So we can attempt a
reaction between inert c2 [W] and work-item c3 [G].
It *is* true that [Solver Invariant]
If the work-item is Given,
AND there is a reaction
then the inert item must Given
or, equivalently,
If the work-item is Given,
and the inert item is Wanted/Derived
then there is no reaction
-}
-- Interaction result of WorkItem <~> Ct
type StopNowFlag = Bool -- True <=> stop after this interaction
interactWithInertsStage :: WorkItem -> TcS (StopOrContinue Ct)
-- Precondition: if the workitem is a CTyEqCan then it will not be able to
-- react with anything at this stage.
interactWithInertsStage wi
= do { inerts <- getTcSInerts
; let ics = inert_cans inerts
; case wi of
CTyEqCan {} -> interactTyVarEq ics wi
CFunEqCan {} -> interactFunEq ics wi
CIrredEvCan {} -> interactIrred ics wi
CDictCan {} -> interactDict ics wi
_ -> pprPanic "interactWithInerts" (ppr wi) }
-- CHoleCan are put straight into inert_frozen, so never get here
-- CNonCanonical have been canonicalised
data InteractResult
= IRKeep -- Keep the existing inert constraint in the inert set
| IRReplace -- Replace the existing inert constraint with the work item
| IRDelete -- Delete the existing inert constraint from the inert set
instance Outputable InteractResult where
ppr IRKeep = ptext (sLit "keep")
ppr IRReplace = ptext (sLit "replace")
ppr IRDelete = ptext (sLit "delete")
solveOneFromTheOther :: CtEvidence -- Inert
-> CtEvidence -- WorkItem
-> TcS (InteractResult, StopNowFlag)
-- Preconditions:
-- 1) inert and work item represent evidence for the /same/ predicate
-- 2) ip/class/irred evidence (no coercions) only
solveOneFromTheOther ev_i ev_w
| isDerived ev_w
= return (IRKeep, True)
| isDerived ev_i -- The inert item is Derived, we can just throw it away,
-- The ev_w is inert wrt earlier inert-set items,
-- so it's safe to continue on from this point
= return (IRDelete, False)
| CtWanted { ctev_evar = ev_id } <- ev_w
= do { setWantedEvBind ev_id (ctEvTerm ev_i)
; return (IRKeep, True) }
| CtWanted { ctev_evar = ev_id } <- ev_i
= do { setWantedEvBind ev_id (ctEvTerm ev_w)
; return (IRReplace, True) }
-- So they are both Given
-- See Note [Replacement vs keeping]
| lvl_i == lvl_w
= do { binds <- getTcEvBindsMap
; if has_binding binds ev_w && not (has_binding binds ev_i)
then return (IRReplace, True)
else return (IRKeep, True) }
| otherwise -- Both are Given
= return (if use_replacement then IRReplace else IRKeep, True)
where
pred = ctEvPred ev_i
loc_i = ctEvLoc ev_i
loc_w = ctEvLoc ev_w
lvl_i = ctLocLevel loc_i
lvl_w = ctLocLevel loc_w
has_binding binds ev
| EvId v <- ctEvTerm ev = isJust (lookupEvBind binds v)
| otherwise = True
use_replacement
| isIPPred pred = lvl_w > lvl_i
| otherwise = lvl_w < lvl_i
{-
Note [Replacement vs keeping]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we have two Given constraints both of type (C tys), say, which should
we keep?
* For implicit parameters we want to keep the innermost (deepest)
one, so that it overrides the outer one.
See Note [Shadowing of Implicit Parameters]
* For everything else, we want to keep the outermost one. Reason: that
makes it more likely that the inner one will turn out to be unused,
and can be reported as redundant. See Note [Tracking redundant constraints]
in TcSimplify.
It transpires that using the outermost one is reponsible for an
8% performance improvement in nofib cryptarithm2, compared to
just rolling the dice. I didn't investigate why.
* If there is no "outermost" one, we keep the one that has a non-trivial
evidence binding. Note [Tracking redundant constraints] again.
Example: f :: (Eq a, Ord a) => blah
then we may find [G] sc_sel (d1::Ord a) :: Eq a
[G] d2 :: Eq a
We want to discard d2 in favour of the superclass selection from
the Ord dictionary.
* Finally, when there is still a choice, use IRKeep rather than
IRReplace, to avoid unnecesary munging of the inert set.
Doing the depth-check for implicit parameters, rather than making the work item
always overrride, is important. Consider
data T a where { T1 :: (?x::Int) => T Int; T2 :: T a }
f :: (?x::a) => T a -> Int
f T1 = ?x
f T2 = 3
We have a [G] (?x::a) in the inert set, and at the pattern match on T1 we add
two new givens in the work-list: [G] (?x::Int)
[G] (a ~ Int)
Now consider these steps
- process a~Int, kicking out (?x::a)
- process (?x::Int), the inner given, adding to inert set
- process (?x::a), the outer given, overriding the inner given
Wrong! The depth-check ensures that the inner implicit parameter wins.
(Actually I think that the order in which the work-list is processed means
that this chain of events won't happen, but that's very fragile.)
*********************************************************************************
* *
interactIrred
* *
*********************************************************************************
-}
-- Two pieces of irreducible evidence: if their types are *exactly identical*
-- we can rewrite them. We can never improve using this:
-- if we want ty1 :: Constraint and have ty2 :: Constraint it clearly does not
-- mean that (ty1 ~ ty2)
interactIrred :: InertCans -> Ct -> TcS (StopOrContinue Ct)
interactIrred inerts workItem@(CIrredEvCan { cc_ev = ev_w })
| let pred = ctEvPred ev_w
(matching_irreds, others) = partitionBag (\ct -> ctPred ct `tcEqType` pred)
(inert_irreds inerts)
, (ct_i : rest) <- bagToList matching_irreds
, let ctev_i = ctEvidence ct_i
= ASSERT( null rest )
do { (inert_effect, stop_now) <- solveOneFromTheOther ctev_i ev_w
; case inert_effect of
IRKeep -> return ()
IRDelete -> updInertIrreds (\_ -> others)
IRReplace -> updInertIrreds (\_ -> others `snocCts` workItem)
-- These const upd's assume that solveOneFromTheOther
-- has no side effects on InertCans
; if stop_now then
return (Stop ev_w (ptext (sLit "Irred equal") <+> parens (ppr inert_effect)))
; else
continueWith workItem }
| otherwise
= continueWith workItem
interactIrred _ wi = pprPanic "interactIrred" (ppr wi)
{-
*********************************************************************************
* *
interactDict
* *
*********************************************************************************
-}
interactDict :: InertCans -> Ct -> TcS (StopOrContinue Ct)
interactDict inerts workItem@(CDictCan { cc_ev = ev_w, cc_class = cls, cc_tyargs = tys })
| Just ctev_i <- lookupInertDict inerts (ctEvLoc ev_w) cls tys
= do { (inert_effect, stop_now) <- solveOneFromTheOther ctev_i ev_w
; case inert_effect of
IRKeep -> return ()
IRDelete -> updInertDicts $ \ ds -> delDict ds cls tys
IRReplace -> updInertDicts $ \ ds -> addDict ds cls tys workItem
; if stop_now then
return (Stop ev_w (ptext (sLit "Dict equal") <+> parens (ppr inert_effect)))
else
continueWith workItem }
| cls `hasKey` ipClassNameKey
, isGiven ev_w
= interactGivenIP inerts workItem
| otherwise
= do { mapBagM_ (addFunDepWork workItem) (findDictsByClass (inert_dicts inerts) cls)
-- Standard thing: create derived fds and keep on going. Importantly we don't
-- throw workitem back in the worklist because this can cause loops (see #5236)
; continueWith workItem }
interactDict _ wi = pprPanic "interactDict" (ppr wi)
interactGivenIP :: InertCans -> Ct -> TcS (StopOrContinue Ct)
-- Work item is Given (?x:ty)
-- See Note [Shadowing of Implicit Parameters]
interactGivenIP inerts workItem@(CDictCan { cc_ev = ev, cc_class = cls
, cc_tyargs = tys@(ip_str:_) })
= do { updInertCans $ \cans -> cans { inert_dicts = addDict filtered_dicts cls tys workItem }
; stopWith ev "Given IP" }
where
dicts = inert_dicts inerts
ip_dicts = findDictsByClass dicts cls
other_ip_dicts = filterBag (not . is_this_ip) ip_dicts
filtered_dicts = addDictsByClass dicts cls other_ip_dicts
-- Pick out any Given constraints for the same implicit parameter
is_this_ip (CDictCan { cc_ev = ev, cc_tyargs = ip_str':_ })
= isGiven ev && ip_str `tcEqType` ip_str'
is_this_ip _ = False
interactGivenIP _ wi = pprPanic "interactGivenIP" (ppr wi)
addFunDepWork :: Ct -> Ct -> TcS ()
addFunDepWork work_ct inert_ct
= do { let fd_eqns :: [Equation CtLoc]
fd_eqns = [ eqn { fd_loc = derived_loc }
| eqn <- improveFromAnother inert_pred work_pred ]
; rewriteWithFunDeps fd_eqns
-- We don't really rewrite tys2, see below _rewritten_tys2, so that's ok
-- NB: We do create FDs for given to report insoluble equations that arise
-- from pairs of Givens, and also because of floating when we approximate
-- implications. The relevant test is: typecheck/should_fail/FDsFromGivens.hs
-- Also see Note [When improvement happens]
}
where
work_pred = ctPred work_ct
inert_pred = ctPred inert_ct
work_loc = ctLoc work_ct
inert_loc = ctLoc inert_ct
derived_loc = work_loc { ctl_origin = FunDepOrigin1 work_pred work_loc
inert_pred inert_loc }
{-
Note [Shadowing of Implicit Parameters]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following example:
f :: (?x :: Char) => Char
f = let ?x = 'a' in ?x
The "let ?x = ..." generates an implication constraint of the form:
?x :: Char => ?x :: Char
Furthermore, the signature for `f` also generates an implication
constraint, so we end up with the following nested implication:
?x :: Char => (?x :: Char => ?x :: Char)
Note that the wanted (?x :: Char) constraint may be solved in
two incompatible ways: either by using the parameter from the
signature, or by using the local definition. Our intention is
that the local definition should "shadow" the parameter of the
signature, and we implement this as follows: when we add a new
*given* implicit parameter to the inert set, it replaces any existing
givens for the same implicit parameter.
This works for the normal cases but it has an odd side effect
in some pathological programs like this:
-- This is accepted, the second parameter shadows
f1 :: (?x :: Int, ?x :: Char) => Char
f1 = ?x
-- This is rejected, the second parameter shadows
f2 :: (?x :: Int, ?x :: Char) => Int
f2 = ?x
Both of these are actually wrong: when we try to use either one,
we'll get two incompatible wnated constraints (?x :: Int, ?x :: Char),
which would lead to an error.
I can think of two ways to fix this:
1. Simply disallow multiple constratits for the same implicit
parameter---this is never useful, and it can be detected completely
syntactically.
2. Move the shadowing machinery to the location where we nest
implications, and add some code here that will produce an
error if we get multiple givens for the same implicit parameter.
*********************************************************************************
* *
interactFunEq
* *
*********************************************************************************
-}
interactFunEq :: InertCans -> Ct -> TcS (StopOrContinue Ct)
-- Try interacting the work item with the inert set
interactFunEq inerts workItem@(CFunEqCan { cc_ev = ev, cc_fun = tc
, cc_tyargs = args, cc_fsk = fsk })
| Just (CFunEqCan { cc_ev = ev_i, cc_fsk = fsk_i }) <- matching_inerts
= if ev_i `canRewriteOrSame` ev
then -- Rewrite work-item using inert
do { traceTcS "reactFunEq (discharge work item):" $
vcat [ text "workItem =" <+> ppr workItem
, text "inertItem=" <+> ppr ev_i ]
; reactFunEq ev_i fsk_i ev fsk
; stopWith ev "Inert rewrites work item" }
else -- Rewrite intert using work-item
do { traceTcS "reactFunEq (rewrite inert item):" $
vcat [ text "workItem =" <+> ppr workItem
, text "inertItem=" <+> ppr ev_i ]
; updInertFunEqs $ \ feqs -> insertFunEq feqs tc args workItem
-- Do the updInertFunEqs before the reactFunEq, so that
-- we don't kick out the inertItem as well as consuming it!
; reactFunEq ev fsk ev_i fsk_i
; stopWith ev "Work item rewrites inert" }
| Just ops <- isBuiltInSynFamTyCon_maybe tc
= do { let matching_funeqs = findFunEqsByTyCon funeqs tc
; let interact = sfInteractInert ops args (lookupFlattenTyVar eqs fsk)
do_one (CFunEqCan { cc_tyargs = iargs, cc_fsk = ifsk, cc_ev = iev })
= mapM_ (unifyDerived (ctEvLoc iev) Nominal)
(interact iargs (lookupFlattenTyVar eqs ifsk))
do_one ct = pprPanic "interactFunEq" (ppr ct)
; mapM_ do_one matching_funeqs
; traceTcS "builtInCandidates 1: " $ vcat [ ptext (sLit "Candidates:") <+> ppr matching_funeqs
, ptext (sLit "TvEqs:") <+> ppr eqs ]
; return (ContinueWith workItem) }
| otherwise
= return (ContinueWith workItem)
where
eqs = inert_eqs inerts
funeqs = inert_funeqs inerts
matching_inerts = findFunEqs funeqs tc args
interactFunEq _ wi = pprPanic "interactFunEq" (ppr wi)
lookupFlattenTyVar :: TyVarEnv EqualCtList -> TcTyVar -> TcType
-- ^ Look up a flatten-tyvar in the inert nominal TyVarEqs;
-- this is used only when dealing with a CFunEqCan
lookupFlattenTyVar inert_eqs ftv
= case lookupVarEnv inert_eqs ftv of
Just (CTyEqCan { cc_rhs = rhs, cc_eq_rel = NomEq } : _) -> rhs
_ -> mkTyVarTy ftv
reactFunEq :: CtEvidence -> TcTyVar -- From this :: F tys ~ fsk1
-> CtEvidence -> TcTyVar -- Solve this :: F tys ~ fsk2
-> TcS ()
reactFunEq from_this fsk1 (CtGiven { ctev_evtm = tm, ctev_loc = loc }) fsk2
= do { let fsk_eq_co = mkTcSymCo (evTermCoercion tm)
`mkTcTransCo` ctEvCoercion from_this
-- :: fsk2 ~ fsk1
fsk_eq_pred = mkTcEqPred (mkTyVarTy fsk2) (mkTyVarTy fsk1)
; new_ev <- newGivenEvVar loc (fsk_eq_pred, EvCoercion fsk_eq_co)
; emitWorkNC [new_ev] }
reactFunEq from_this fuv1 (CtWanted { ctev_evar = evar }) fuv2
= dischargeFmv evar fuv2 (ctEvCoercion from_this) (mkTyVarTy fuv1)
reactFunEq _ _ solve_this@(CtDerived {}) _
= pprPanic "reactFunEq" (ppr solve_this)
{-
Note [Cache-caused loops]
~~~~~~~~~~~~~~~~~~~~~~~~~
It is very dangerous to cache a rewritten wanted family equation as 'solved' in our
solved cache (which is the default behaviour or xCtEvidence), because the interaction
may not be contributing towards a solution. Here is an example:
Initial inert set:
[W] g1 : F a ~ beta1
Work item:
[W] g2 : F a ~ beta2
The work item will react with the inert yielding the _same_ inert set plus:
i) Will set g2 := g1 `cast` g3
ii) Will add to our solved cache that [S] g2 : F a ~ beta2
iii) Will emit [W] g3 : beta1 ~ beta2
Now, the g3 work item will be spontaneously solved to [G] g3 : beta1 ~ beta2
and then it will react the item in the inert ([W] g1 : F a ~ beta1). So it
will set
g1 := g ; sym g3
and what is g? Well it would ideally be a new goal of type (F a ~ beta2) but
remember that we have this in our solved cache, and it is ... g2! In short we
created the evidence loop:
g2 := g1 ; g3
g3 := refl
g1 := g2 ; sym g3
To avoid this situation we do not cache as solved any workitems (or inert)
which did not really made a 'step' towards proving some goal. Solved's are
just an optimization so we don't lose anything in terms of completeness of
solving.
Note [Efficient Orientation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we are interacting two FunEqCans with the same LHS:
(inert) ci :: (F ty ~ xi_i)
(work) cw :: (F ty ~ xi_w)
We prefer to keep the inert (else we pass the work item on down
the pipeline, which is a bit silly). If we keep the inert, we
will (a) discharge 'cw'
(b) produce a new equality work-item (xi_w ~ xi_i)
Notice the orientation (xi_w ~ xi_i) NOT (xi_i ~ xi_w):
new_work :: xi_w ~ xi_i
cw := ci ; sym new_work
Why? Consider the simplest case when xi1 is a type variable. If
we generate xi1~xi2, porcessing that constraint will kick out 'ci'.
If we generate xi2~xi1, there is less chance of that happening.
Of course it can and should still happen if xi1=a, xi1=Int, say.
But we want to avoid it happening needlessly.
Similarly, if we *can't* keep the inert item (because inert is Wanted,
and work is Given, say), we prefer to orient the new equality (xi_i ~
xi_w).
Note [Carefully solve the right CFunEqCan]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
---- OLD COMMENT, NOW NOT NEEDED
---- because we now allow multiple
---- wanted FunEqs with the same head
Consider the constraints
c1 :: F Int ~ a -- Arising from an application line 5
c2 :: F Int ~ Bool -- Arising from an application line 10
Suppose that 'a' is a unification variable, arising only from
flattening. So there is no error on line 5; it's just a flattening
variable. But there is (or might be) an error on line 10.
Two ways to combine them, leaving either (Plan A)
c1 :: F Int ~ a -- Arising from an application line 5
c3 :: a ~ Bool -- Arising from an application line 10
or (Plan B)
c2 :: F Int ~ Bool -- Arising from an application line 10
c4 :: a ~ Bool -- Arising from an application line 5
Plan A will unify c3, leaving c1 :: F Int ~ Bool as an error
on the *totally innocent* line 5. An example is test SimpleFail16
where the expected/actual message comes out backwards if we use
the wrong plan.
The second is the right thing to do. Hence the isMetaTyVarTy
test when solving pairwise CFunEqCan.
*********************************************************************************
* *
interactTyVarEq
* *
*********************************************************************************
-}
interactTyVarEq :: InertCans -> Ct -> TcS (StopOrContinue Ct)
-- CTyEqCans are always consumed, so always returns Stop
interactTyVarEq inerts workItem@(CTyEqCan { cc_tyvar = tv
, cc_rhs = rhs
, cc_ev = ev
, cc_eq_rel = eq_rel })
| (ev_i : _) <- [ ev_i | CTyEqCan { cc_ev = ev_i, cc_rhs = rhs_i }
<- findTyEqs inerts tv
, ev_i `canRewriteOrSame` ev
, rhs_i `tcEqType` rhs ]
= -- Inert: a ~ b
-- Work item: a ~ b
do { setEvBindIfWanted ev (ctEvTerm ev_i)
; stopWith ev "Solved from inert" }
| Just tv_rhs <- getTyVar_maybe rhs
, (ev_i : _) <- [ ev_i | CTyEqCan { cc_ev = ev_i, cc_rhs = rhs_i }
<- findTyEqs inerts tv_rhs
, ev_i `canRewriteOrSame` ev
, rhs_i `tcEqType` mkTyVarTy tv ]
= -- Inert: a ~ b
-- Work item: b ~ a
do { setEvBindIfWanted ev
(EvCoercion (mkTcSymCo (ctEvCoercion ev_i)))
; stopWith ev "Solved from inert (r)" }
| otherwise
= do { tclvl <- getTcLevel
; if canSolveByUnification tclvl ev eq_rel tv rhs
then do { solveByUnification ev tv rhs
; n_kicked <- kickOutRewritable Given NomEq tv
-- Given because the tv := xi is given
-- NomEq because only nom. equalities are solved
-- by unification
; return (Stop ev (ptext (sLit "Spontaneously solved") <+> ppr_kicked n_kicked)) }
else do { traceTcS "Can't solve tyvar equality"
(vcat [ text "LHS:" <+> ppr tv <+> dcolon <+> ppr (tyVarKind tv)
, ppWhen (isMetaTyVar tv) $
nest 4 (text "TcLevel of" <+> ppr tv
<+> text "is" <+> ppr (metaTyVarTcLevel tv))
, text "RHS:" <+> ppr rhs <+> dcolon <+> ppr (typeKind rhs)
, text "TcLevel =" <+> ppr tclvl ])
; n_kicked <- kickOutRewritable (ctEvFlavour ev)
(ctEvEqRel ev)
tv
; updInertCans (\ ics -> addInertCan ics workItem)
; return (Stop ev (ptext (sLit "Kept as inert") <+> ppr_kicked n_kicked)) } }
interactTyVarEq _ wi = pprPanic "interactTyVarEq" (ppr wi)
-- @trySpontaneousSolve wi@ solves equalities where one side is a
-- touchable unification variable.
-- Returns True <=> spontaneous solve happened
canSolveByUnification :: TcLevel -> CtEvidence -> EqRel
-> TcTyVar -> Xi -> Bool
canSolveByUnification tclvl gw eq_rel tv xi
| ReprEq <- eq_rel -- we never solve representational equalities this way.
= False
| isGiven gw -- See Note [Touchables and givens]
= False
| isTouchableMetaTyVar tclvl tv
= case metaTyVarInfo tv of
SigTv -> is_tyvar xi
_ -> True
| otherwise -- Untouchable
= False
where
is_tyvar xi
= case tcGetTyVar_maybe xi of
Nothing -> False
Just tv -> case tcTyVarDetails tv of
MetaTv { mtv_info = info }
-> case info of
SigTv -> True
_ -> False
SkolemTv {} -> True
FlatSkol {} -> False
RuntimeUnk -> True
solveByUnification :: CtEvidence -> TcTyVar -> Xi -> TcS ()
-- Solve with the identity coercion
-- Precondition: kind(xi) is a sub-kind of kind(tv)
-- Precondition: CtEvidence is Wanted or Derived
-- Precondition: CtEvidence is nominal
-- Returns: workItem where
-- workItem = the new Given constraint
--
-- NB: No need for an occurs check here, because solveByUnification always
-- arises from a CTyEqCan, a *canonical* constraint. Its invariants
-- say that in (a ~ xi), the type variable a does not appear in xi.
-- See TcRnTypes.Ct invariants.
--
-- Post: tv is unified (by side effect) with xi;
-- we often write tv := xi
solveByUnification wd tv xi
= do { let tv_ty = mkTyVarTy tv
; traceTcS "Sneaky unification:" $
vcat [text "Unifies:" <+> ppr tv <+> ptext (sLit ":=") <+> ppr xi,
text "Coercion:" <+> pprEq tv_ty xi,
text "Left Kind is:" <+> ppr (typeKind tv_ty),
text "Right Kind is:" <+> ppr (typeKind xi) ]
; let xi' = defaultKind xi
-- We only instantiate kind unification variables
-- with simple kinds like *, not OpenKind or ArgKind
-- cf TcUnify.uUnboundKVar
; setWantedTyBind tv xi'
; setEvBindIfWanted wd (EvCoercion (mkTcNomReflCo xi')) }
ppr_kicked :: Int -> SDoc
ppr_kicked 0 = empty
ppr_kicked n = parens (int n <+> ptext (sLit "kicked out"))
kickOutRewritable :: CtFlavour -- Flavour of the equality that is
-- being added to the inert set
-> EqRel -- of the new equality
-> TcTyVar -- The new equality is tv ~ ty
-> TcS Int
kickOutRewritable new_flavour new_eq_rel new_tv
| not ((new_flavour, new_eq_rel) `eqCanRewriteFR` (new_flavour, new_eq_rel))
= return 0 -- If new_flavour can't rewrite itself, it can't rewrite
-- anything else, so no need to kick out anything
-- This is a common case: wanteds can't rewrite wanteds
| otherwise
= do { ics <- getInertCans
; let (kicked_out, ics') = kick_out new_flavour new_eq_rel new_tv ics
; setInertCans ics'
; updWorkListTcS (appendWorkList kicked_out)
; unless (isEmptyWorkList kicked_out) $
csTraceTcS $
hang (ptext (sLit "Kick out, tv =") <+> ppr new_tv)
2 (vcat [ text "n-kicked =" <+> int (workListSize kicked_out)
, text "n-kept fun-eqs =" <+> int (sizeFunEqMap (inert_funeqs ics'))
, ppr kicked_out ])
; return (workListSize kicked_out) }
kick_out :: CtFlavour -> EqRel -> TcTyVar -> InertCans -> (WorkList, InertCans)
kick_out new_flavour new_eq_rel new_tv (IC { inert_eqs = tv_eqs
, inert_dicts = dictmap
, inert_funeqs = funeqmap
, inert_irreds = irreds
, inert_insols = insols })
= (kicked_out, inert_cans_in)
where
-- NB: Notice that don't rewrite
-- inert_solved_dicts, and inert_solved_funeqs
-- optimistically. But when we lookup we have to
-- take the substitution into account
inert_cans_in = IC { inert_eqs = tv_eqs_in
, inert_dicts = dicts_in
, inert_funeqs = feqs_in
, inert_irreds = irs_in
, inert_insols = insols_in }
kicked_out = WL { wl_eqs = tv_eqs_out
, wl_funeqs = feqs_out
, wl_rest = bagToList (dicts_out `andCts` irs_out
`andCts` insols_out)
, wl_implics = emptyBag }
(tv_eqs_out, tv_eqs_in) = foldVarEnv kick_out_eqs ([], emptyVarEnv) tv_eqs
(feqs_out, feqs_in) = partitionFunEqs kick_out_ct funeqmap
(dicts_out, dicts_in) = partitionDicts kick_out_ct dictmap
(irs_out, irs_in) = partitionBag kick_out_irred irreds
(insols_out, insols_in) = partitionBag kick_out_ct insols
-- Kick out even insolubles; see Note [Kick out insolubles]
can_rewrite :: CtEvidence -> Bool
can_rewrite = ((new_flavour, new_eq_rel) `eqCanRewriteFR`) . ctEvFlavourRole
kick_out_ct :: Ct -> Bool
kick_out_ct ct = kick_out_ctev (ctEvidence ct)
kick_out_ctev :: CtEvidence -> Bool
kick_out_ctev ev = can_rewrite ev
&& new_tv `elemVarSet` tyVarsOfType (ctEvPred ev)
-- See Note [Kicking out inert constraints]
kick_out_irred :: Ct -> Bool
kick_out_irred ct = can_rewrite (cc_ev ct)
&& new_tv `elemVarSet` closeOverKinds (tyVarsOfCt ct)
-- See Note [Kicking out Irreds]
kick_out_eqs :: EqualCtList -> ([Ct], TyVarEnv EqualCtList)
-> ([Ct], TyVarEnv EqualCtList)
kick_out_eqs eqs (acc_out, acc_in)
= (eqs_out ++ acc_out, case eqs_in of
[] -> acc_in
(eq1:_) -> extendVarEnv acc_in (cc_tyvar eq1) eqs_in)
where
(eqs_in, eqs_out) = partition keep_eq eqs
-- implements criteria K1-K3 in Note [The inert equalities] in TcFlatten
keep_eq (CTyEqCan { cc_tyvar = tv, cc_rhs = rhs_ty, cc_ev = ev
, cc_eq_rel = eq_rel })
| tv == new_tv
= not (can_rewrite ev) -- (K1)
| otherwise
= check_k2 && check_k3
where
check_k2 = not (ev `eqCanRewrite` ev)
|| not (can_rewrite ev)
|| not (new_tv `elemVarSet` tyVarsOfType rhs_ty)
check_k3
| can_rewrite ev
= case eq_rel of
NomEq -> not (rhs_ty `eqType` mkTyVarTy new_tv)
ReprEq -> isTyVarExposed new_tv rhs_ty
| otherwise
= True
keep_eq ct = pprPanic "keep_eq" (ppr ct)
{-
Note [Kicking out inert constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Given a new (a -> ty) inert, we want to kick out an existing inert
constraint if
a) the new constraint can rewrite the inert one
b) 'a' is free in the inert constraint (so that it *will*)
rewrite it if we kick it out.
For (b) we use tyVarsOfCt, which returns the type variables /and
the kind variables/ that are directly visible in the type. Hence we
will have exposed all the rewriting we care about to make the most
precise kinds visible for matching classes etc. No need to kick out
constraints that mention type variables whose kinds contain this
variable! (Except see Note [Kicking out Irreds].)
Note [Kicking out Irreds]
~~~~~~~~~~~~~~~~~~~~~~~~~
There is an awkward special case for Irreds. When we have a
kind-mis-matched equality constraint (a:k1) ~ (ty:k2), we turn it into
an Irred (see Note [Equalities with incompatible kinds] in
TcCanonical). So in this case the free kind variables of k1 and k2
are not visible. More precisely, the type looks like
(~) k1 (a:k1) (ty:k2)
because (~) has kind forall k. k -> k -> Constraint. So the constraint
itself is ill-kinded. We can "see" k1 but not k2. That's why we use
closeOverKinds to make sure we see k2.
This is not pretty. Maybe (~) should have kind
(~) :: forall k1 k1. k1 -> k2 -> Constraint
Note [Kick out insolubles]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have an insoluble alpha ~ [alpha], which is insoluble
because an occurs check. And then we unify alpha := [Int].
Then we really want to rewrite the insouluble to [Int] ~ [[Int]].
Now it can be decomposed. Otherwise we end up with a "Can't match
[Int] ~ [[Int]]" which is true, but a bit confusing because the
outer type constructors match.
Note [Avoid double unifications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The spontaneous solver has to return a given which mentions the unified unification
variable *on the left* of the equality. Here is what happens if not:
Original wanted: (a ~ alpha), (alpha ~ Int)
We spontaneously solve the first wanted, without changing the order!
given : a ~ alpha [having unified alpha := a]
Now the second wanted comes along, but he cannot rewrite the given, so we simply continue.
At the end we spontaneously solve that guy, *reunifying* [alpha := Int]
We avoid this problem by orienting the resulting given so that the unification
variable is on the left. [Note that alternatively we could attempt to
enforce this at canonicalization]
See also Note [No touchables as FunEq RHS] in TcSMonad; avoiding
double unifications is the main reason we disallow touchable
unification variables as RHS of type family equations: F xis ~ alpha.
************************************************************************
* *
* Functional dependencies, instantiation of equations
* *
************************************************************************
When we spot an equality arising from a functional dependency,
we now use that equality (a "wanted") to rewrite the work-item
constraint right away. This avoids two dangers
Danger 1: If we send the original constraint on down the pipeline
it may react with an instance declaration, and in delicate
situations (when a Given overlaps with an instance) that
may produce new insoluble goals: see Trac #4952
Danger 2: If we don't rewrite the constraint, it may re-react
with the same thing later, and produce the same equality
again --> termination worries.
To achieve this required some refactoring of FunDeps.lhs (nicer
now!).
-}
rewriteWithFunDeps :: [Equation CtLoc] -> TcS ()
-- NB: The returned constraints are all Derived
-- Post: returns no trivial equalities (identities) and all EvVars returned are fresh
rewriteWithFunDeps eqn_pred_locs
= mapM_ instFunDepEqn eqn_pred_locs
instFunDepEqn :: Equation CtLoc -> TcS ()
-- Post: Returns the position index as well as the corresponding FunDep equality
instFunDepEqn (FDEqn { fd_qtvs = tvs, fd_eqs = eqs, fd_loc = loc })
= do { (subst, _) <- instFlexiTcS tvs -- Takes account of kind substitution
; mapM_ (do_one subst) eqs }
where
do_one subst (FDEq { fd_ty_left = ty1, fd_ty_right = ty2 })
= unifyDerived loc Nominal $
Pair (Type.substTy subst ty1) (Type.substTy subst ty2)
{-
*********************************************************************************
* *
The top-reaction Stage
* *
*********************************************************************************
-}
topReactionsStage :: WorkItem -> TcS (StopOrContinue Ct)
topReactionsStage wi
= do { inerts <- getTcSInerts
; tir <- doTopReact inerts wi
; case tir of
ContinueWith wi -> return (ContinueWith wi)
Stop ev s -> return (Stop ev (ptext (sLit "Top react:") <+> s)) }
doTopReact :: InertSet -> WorkItem -> TcS (StopOrContinue Ct)
-- The work item does not react with the inert set, so try interaction with top-level
-- instances. Note:
--
-- (a) The place to add superclasses in not here in doTopReact stage.
-- Instead superclasses are added in the worklist as part of the
-- canonicalization process. See Note [Adding superclasses].
doTopReact inerts work_item
= do { traceTcS "doTopReact" (ppr work_item)
; case work_item of
CDictCan {} -> doTopReactDict inerts work_item
CFunEqCan {} -> doTopReactFunEq work_item
_ -> -- Any other work item does not react with any top-level equations
return (ContinueWith work_item) }
--------------------
doTopReactDict :: InertSet -> Ct -> TcS (StopOrContinue Ct)
-- Try to use type-class instance declarations to simplify the constraint
doTopReactDict inerts work_item@(CDictCan { cc_ev = fl, cc_class = cls
, cc_tyargs = xis })
| not (isWanted fl) -- Never use instances for Given or Derived constraints
= try_fundeps_and_return
| Just ev <- lookupSolvedDict inerts loc cls xis -- Cached
= do { setWantedEvBind dict_id (ctEvTerm ev);
; stopWith fl "Dict/Top (cached)" }
| otherwise -- Not cached
= do { lkup_inst_res <- matchClassInst inerts cls xis loc
; case lkup_inst_res of
GenInst wtvs ev_term -> do { addSolvedDict fl cls xis
; solve_from_instance wtvs ev_term }
NoInstance -> try_fundeps_and_return }
where
dict_id = ASSERT( isWanted fl ) ctEvId fl
pred = mkClassPred cls xis
loc = ctEvLoc fl
solve_from_instance :: [CtEvidence] -> EvTerm -> TcS (StopOrContinue Ct)
-- Precondition: evidence term matches the predicate workItem
solve_from_instance evs ev_term
| null evs
= do { traceTcS "doTopReact/found nullary instance for" $
ppr dict_id
; setWantedEvBind dict_id ev_term
; stopWith fl "Dict/Top (solved, no new work)" }
| otherwise
= do { traceTcS "doTopReact/found non-nullary instance for" $
ppr dict_id
; setWantedEvBind dict_id ev_term
; let mk_new_wanted ev
= mkNonCanonical (ev {ctev_loc = bumpCtLocDepth CountConstraints loc })
; updWorkListTcS (extendWorkListCts (map mk_new_wanted evs))
; stopWith fl "Dict/Top (solved, more work)" }
-- We didn't solve it; so try functional dependencies with
-- the instance environment, and return
-- NB: even if there *are* some functional dependencies against the
-- instance environment, there might be a unique match, and if
-- so we make sure we get on and solve it first. See Note [Weird fundeps]
try_fundeps_and_return
= do { instEnvs <- getInstEnvs
; let fd_eqns :: [Equation CtLoc]
fd_eqns = [ fd { fd_loc = loc { ctl_origin = FunDepOrigin2 pred (ctl_origin loc)
inst_pred inst_loc } }
| fd@(FDEqn { fd_loc = inst_loc, fd_pred1 = inst_pred })
<- improveFromInstEnv instEnvs pred ]
; rewriteWithFunDeps fd_eqns
; continueWith work_item }
doTopReactDict _ w = pprPanic "doTopReactDict" (ppr w)
--------------------
doTopReactFunEq :: Ct -> TcS (StopOrContinue Ct)
doTopReactFunEq work_item@(CFunEqCan { cc_ev = old_ev, cc_fun = fam_tc
, cc_tyargs = args , cc_fsk = fsk })
= ASSERT(isTypeFamilyTyCon fam_tc) -- No associated data families
-- have reached this far
ASSERT( not (isDerived old_ev) ) -- CFunEqCan is never Derived
-- Look up in top-level instances, or built-in axiom
do { match_res <- matchFam fam_tc args -- See Note [MATCHING-SYNONYMS]
; case match_res of {
Nothing -> do { try_improvement; continueWith work_item } ;
Just (ax_co, rhs_ty)
-- Found a top-level instance
| Just (tc, tc_args) <- tcSplitTyConApp_maybe rhs_ty
, isTypeFamilyTyCon tc
, tc_args `lengthIs` tyConArity tc -- Short-cut
-> shortCutReduction old_ev fsk ax_co tc tc_args
-- Try shortcut; see Note [Short cut for top-level reaction]
| isGiven old_ev -- Not shortcut
-> do { let final_co = mkTcSymCo (ctEvCoercion old_ev) `mkTcTransCo` ax_co
-- final_co :: fsk ~ rhs_ty
; new_ev <- newGivenEvVar deeper_loc (mkTcEqPred (mkTyVarTy fsk) rhs_ty,
EvCoercion final_co)
; emitWorkNC [new_ev] -- Non-cannonical; that will mean we flatten rhs_ty
; stopWith old_ev "Fun/Top (given)" }
| not (fsk `elemVarSet` tyVarsOfType rhs_ty)
-> do { dischargeFmv (ctEvId old_ev) fsk ax_co rhs_ty
; traceTcS "doTopReactFunEq" $
vcat [ text "old_ev:" <+> ppr old_ev
, nest 2 (text ":=") <+> ppr ax_co ]
; stopWith old_ev "Fun/Top (wanted)" }
| otherwise -- We must not assign ufsk := ...ufsk...!
-> do { alpha_ty <- newFlexiTcSTy (tyVarKind fsk)
; new_ev <- newWantedEvVarNC loc (mkTcEqPred alpha_ty rhs_ty)
; emitWorkNC [new_ev]
-- By emitting this as non-canonical, we deal with all
-- flattening, occurs-check, and ufsk := ufsk issues
; let final_co = ax_co `mkTcTransCo` mkTcSymCo (ctEvCoercion new_ev)
-- ax_co :: fam_tc args ~ rhs_ty
-- new_ev :: alpha ~ rhs_ty
-- ufsk := alpha
-- final_co :: fam_tc args ~ alpha
; dischargeFmv (ctEvId old_ev) fsk final_co alpha_ty
; traceTcS "doTopReactFunEq (occurs)" $
vcat [ text "old_ev:" <+> ppr old_ev
, nest 2 (text ":=") <+> ppr final_co
, text "new_ev:" <+> ppr new_ev ]
; stopWith old_ev "Fun/Top (wanted)" } } }
where
loc = ctEvLoc old_ev
deeper_loc = bumpCtLocDepth CountTyFunApps loc
try_improvement
| Just ops <- isBuiltInSynFamTyCon_maybe fam_tc
= do { inert_eqs <- getInertEqs
; let eqns = sfInteractTop ops args (lookupFlattenTyVar inert_eqs fsk)
; mapM_ (unifyDerived loc Nominal) eqns }
| otherwise
= return ()
doTopReactFunEq w = pprPanic "doTopReactFunEq" (ppr w)
shortCutReduction :: CtEvidence -> TcTyVar -> TcCoercion
-> TyCon -> [TcType] -> TcS (StopOrContinue Ct)
shortCutReduction old_ev fsk ax_co fam_tc tc_args
| isGiven old_ev
= ASSERT( ctEvEqRel old_ev == NomEq )
runFlatten $
do { (xis, cos) <- flattenManyNom old_ev tc_args
-- ax_co :: F args ~ G tc_args
-- cos :: xis ~ tc_args
-- old_ev :: F args ~ fsk
-- G cos ; sym ax_co ; old_ev :: G xis ~ fsk
; new_ev <- newGivenEvVar deeper_loc
( mkTcEqPred (mkTyConApp fam_tc xis) (mkTyVarTy fsk)
, EvCoercion (mkTcTyConAppCo Nominal fam_tc cos
`mkTcTransCo` mkTcSymCo ax_co
`mkTcTransCo` ctEvCoercion old_ev) )
; let new_ct = CFunEqCan { cc_ev = new_ev, cc_fun = fam_tc, cc_tyargs = xis, cc_fsk = fsk }
; emitFlatWork new_ct
; stopWith old_ev "Fun/Top (given, shortcut)" }
| otherwise
= ASSERT( not (isDerived old_ev) ) -- Caller ensures this
ASSERT( ctEvEqRel old_ev == NomEq )
do { (xis, cos) <- flattenManyNom old_ev tc_args
-- ax_co :: F args ~ G tc_args
-- cos :: xis ~ tc_args
-- G cos ; sym ax_co ; old_ev :: G xis ~ fsk
-- new_ev :: G xis ~ fsk
-- old_ev :: F args ~ fsk := ax_co ; sym (G cos) ; new_ev
; new_ev <- newWantedEvVarNC deeper_loc
(mkTcEqPred (mkTyConApp fam_tc xis) (mkTyVarTy fsk))
; setWantedEvBind (ctEvId old_ev)
(EvCoercion (ax_co `mkTcTransCo` mkTcSymCo (mkTcTyConAppCo Nominal fam_tc cos)
`mkTcTransCo` ctEvCoercion new_ev))
; let new_ct = CFunEqCan { cc_ev = new_ev, cc_fun = fam_tc, cc_tyargs = xis, cc_fsk = fsk }
; emitFlatWork new_ct
; stopWith old_ev "Fun/Top (wanted, shortcut)" }
where
loc = ctEvLoc old_ev
deeper_loc = bumpCtLocDepth CountTyFunApps loc
dischargeFmv :: EvVar -> TcTyVar -> TcCoercion -> TcType -> TcS ()
-- (dischargeFmv x fmv co ty)
-- [W] x :: F tys ~ fuv
-- co :: F tys ~ ty
-- Precondition: fuv is not filled, and fuv `notElem` ty
--
-- Then set fuv := ty,
-- set x := co
-- kick out any inert things that are now rewritable
dischargeFmv evar fmv co xi
= ASSERT2( not (fmv `elemVarSet` tyVarsOfType xi), ppr evar $$ ppr fmv $$ ppr xi )
do { setWantedTyBind fmv xi
; setWantedEvBind evar (EvCoercion co)
; n_kicked <- kickOutRewritable Given NomEq fmv
; traceTcS "dischargeFuv" (ppr fmv <+> equals <+> ppr xi $$ ppr_kicked n_kicked) }
{-
Note [Cached solved FunEqs]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
When trying to solve, say (FunExpensive big-type ~ ty), it's important
to see if we have reduced (FunExpensive big-type) before, lest we
simply repeat it. Hence the lookup in inert_solved_funeqs. Moreover
we must use `canRewriteOrSame` because both uses might (say) be Wanteds,
and we *still* want to save the re-computation.
Note [MATCHING-SYNONYMS]
~~~~~~~~~~~~~~~~~~~~~~~~
When trying to match a dictionary (D tau) to a top-level instance, or a
type family equation (F taus_1 ~ tau_2) to a top-level family instance,
we do *not* need to expand type synonyms because the matcher will do that for us.
Note [RHS-FAMILY-SYNONYMS]
~~~~~~~~~~~~~~~~~~~~~~~~~~
The RHS of a family instance is represented as yet another constructor which is
like a type synonym for the real RHS the programmer declared. Eg:
type instance F (a,a) = [a]
Becomes:
:R32 a = [a] -- internal type synonym introduced
F (a,a) ~ :R32 a -- instance
When we react a family instance with a type family equation in the work list
we keep the synonym-using RHS without expansion.
Note [FunDep and implicit parameter reactions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Currently, our story of interacting two dictionaries (or a dictionary
and top-level instances) for functional dependencies, and implicit
paramters, is that we simply produce new Derived equalities. So for example
class D a b | a -> b where ...
Inert:
d1 :g D Int Bool
WorkItem:
d2 :w D Int alpha
We generate the extra work item
cv :d alpha ~ Bool
where 'cv' is currently unused. However, this new item can perhaps be
spontaneously solved to become given and react with d2,
discharging it in favour of a new constraint d2' thus:
d2' :w D Int Bool
d2 := d2' |> D Int cv
Now d2' can be discharged from d1
We could be more aggressive and try to *immediately* solve the dictionary
using those extra equalities, but that requires those equalities to carry
evidence and derived do not carry evidence.
If that were the case with the same inert set and work item we might dischard
d2 directly:
cv :w alpha ~ Bool
d2 := d1 |> D Int cv
But in general it's a bit painful to figure out the necessary coercion,
so we just take the first approach. Here is a better example. Consider:
class C a b c | a -> b
And:
[Given] d1 : C T Int Char
[Wanted] d2 : C T beta Int
In this case, it's *not even possible* to solve the wanted immediately.
So we should simply output the functional dependency and add this guy
[but NOT its superclasses] back in the worklist. Even worse:
[Given] d1 : C T Int beta
[Wanted] d2: C T beta Int
Then it is solvable, but its very hard to detect this on the spot.
It's exactly the same with implicit parameters, except that the
"aggressive" approach would be much easier to implement.
Note [When improvement happens]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We fire an improvement rule when
* Two constraints match (modulo the fundep)
e.g. C t1 t2, C t1 t3 where C a b | a->b
The two match because the first arg is identical
Note that we *do* fire the improvement if one is Given and one is Derived (e.g. a
superclass of a Wanted goal) or if both are Given.
Example (tcfail138)
class L a b | a -> b
class (G a, L a b) => C a b
instance C a b' => G (Maybe a)
instance C a b => C (Maybe a) a
instance L (Maybe a) a
When solving the superclasses of the (C (Maybe a) a) instance, we get
Given: C a b ... and hance by superclasses, (G a, L a b)
Wanted: G (Maybe a)
Use the instance decl to get
Wanted: C a b'
The (C a b') is inert, so we generate its Derived superclasses (L a b'),
and now we need improvement between that derived superclass an the Given (L a b)
Test typecheck/should_fail/FDsFromGivens also shows why it's a good idea to
emit Derived FDs for givens as well.
Note [Weird fundeps]
~~~~~~~~~~~~~~~~~~~~
Consider class Het a b | a -> b where
het :: m (f c) -> a -> m b
class GHet (a :: * -> *) (b :: * -> *) | a -> b
instance GHet (K a) (K [a])
instance Het a b => GHet (K a) (K b)
The two instances don't actually conflict on their fundeps,
although it's pretty strange. So they are both accepted. Now
try [W] GHet (K Int) (K Bool)
This triggers fudeps from both instance decls; but it also
matches a *unique* instance decl, and we should go ahead and
pick that one right now. Otherwise, if we don't, it ends up
unsolved in the inert set and is reported as an error.
Trac #7875 is a case in point.
Note [Overriding implicit parameters]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f :: (?x::a) -> Bool -> a
g v = let ?x::Int = 3
in (f v, let ?x::Bool = True in f v)
This should probably be well typed, with
g :: Bool -> (Int, Bool)
So the inner binding for ?x::Bool *overrides* the outer one.
Hence a work-item Given overrides an inert-item Given.
-}
data LookupInstResult
= NoInstance
| GenInst [CtEvidence] EvTerm
instance Outputable LookupInstResult where
ppr NoInstance = text "NoInstance"
ppr (GenInst ev t) = text "GenInst" <+> ppr ev <+> ppr t
matchClassInst :: InertSet -> Class -> [Type] -> CtLoc -> TcS LookupInstResult
matchClassInst _ clas [ ty ] _
| className clas == knownNatClassName
, Just n <- isNumLitTy ty = makeDict (EvNum n)
| className clas == knownSymbolClassName
, Just s <- isStrLitTy ty = makeDict (EvStr s)
where
{- This adds a coercion that will convert the literal into a dictionary
of the appropriate type. See Note [KnownNat & KnownSymbol and EvLit]
in TcEvidence. The coercion happens in 2 steps:
Integer -> SNat n -- representation of literal to singleton
SNat n -> KnownNat n -- singleton to dictionary
The process is mirrored for Symbols:
String -> SSymbol n
SSymbol n -> KnownSymbol n
-}
makeDict evLit
| Just (_, co_dict) <- tcInstNewTyCon_maybe (classTyCon clas) [ty]
-- co_dict :: KnownNat n ~ SNat n
, [ meth ] <- classMethods clas
, Just tcRep <- tyConAppTyCon_maybe -- SNat
$ funResultTy -- SNat n
$ dropForAlls -- KnownNat n => SNat n
$ idType meth -- forall n. KnownNat n => SNat n
, Just (_, co_rep) <- tcInstNewTyCon_maybe tcRep [ty]
-- SNat n ~ Integer
= return (GenInst [] $ mkEvCast (EvLit evLit) (mkTcSymCo (mkTcTransCo co_dict co_rep)))
| otherwise
= panicTcS (text "Unexpected evidence for" <+> ppr (className clas)
$$ vcat (map (ppr . idType) (classMethods clas)))
matchClassInst inerts clas tys loc
= do { dflags <- getDynFlags
; tclvl <- getTcLevel
; traceTcS "matchClassInst" $ vcat [ text "pred =" <+> ppr pred
, text "inerts=" <+> ppr inerts
, text "untouchables=" <+> ppr tclvl ]
; instEnvs <- getInstEnvs
; case lookupInstEnv instEnvs clas tys of
([], _, _) -- Nothing matches
-> do { traceTcS "matchClass not matching" $
vcat [ text "dict" <+> ppr pred ]
; return NoInstance }
([(ispec, inst_tys)], [], _) -- A single match
| not (xopt Opt_IncoherentInstances dflags)
, given_overlap tclvl
-> -- See Note [Instance and Given overlap]
do { traceTcS "Delaying instance application" $
vcat [ text "Workitem=" <+> pprType (mkClassPred clas tys)
, text "Relevant given dictionaries=" <+> ppr givens_for_this_clas ]
; return NoInstance }
| otherwise
-> do { let dfun_id = instanceDFunId ispec
; traceTcS "matchClass success" $
vcat [text "dict" <+> ppr pred,
text "witness" <+> ppr dfun_id
<+> ppr (idType dfun_id) ]
-- Record that this dfun is needed
; match_one dfun_id inst_tys }
(matches, _, _) -- More than one matches
-- Defer any reactions of a multitude
-- until we learn more about the reagent
-> do { traceTcS "matchClass multiple matches, deferring choice" $
vcat [text "dict" <+> ppr pred,
text "matches" <+> ppr matches]
; return NoInstance } }
where
pred = mkClassPred clas tys
match_one :: DFunId -> [DFunInstType] -> TcS LookupInstResult
-- See Note [DFunInstType: instantiating types] in InstEnv
match_one dfun_id mb_inst_tys
= do { checkWellStagedDFun pred dfun_id loc
; (tys, theta) <- instDFunType dfun_id mb_inst_tys
; evc_vars <- mapM (newWantedEvVar loc) theta
; let new_ev_vars = freshGoals evc_vars
-- new_ev_vars are only the real new variables that can be emitted
dfun_app = EvDFunApp dfun_id tys (map (ctEvTerm . fst) evc_vars)
; return $ GenInst new_ev_vars dfun_app }
givens_for_this_clas :: Cts
givens_for_this_clas
= filterBag isGivenCt (findDictsByClass (inert_dicts $ inert_cans inerts) clas)
given_overlap :: TcLevel -> Bool
given_overlap tclvl = anyBag (matchable tclvl) givens_for_this_clas
matchable tclvl (CDictCan { cc_class = clas_g, cc_tyargs = sys
, cc_ev = fl })
| isGiven fl
= ASSERT( clas_g == clas )
case tcUnifyTys (\tv -> if isTouchableMetaTyVar tclvl tv &&
tv `elemVarSet` tyVarsOfTypes tys
then BindMe else Skolem) tys sys of
-- We can't learn anything more about any variable at this point, so the only
-- cause of overlap can be by an instantiation of a touchable unification
-- variable. Hence we only bind touchable unification variables. In addition,
-- we use tcUnifyTys instead of tcMatchTys to rule out cyclic substitutions.
Nothing -> False
Just _ -> True
| otherwise = False -- No overlap with a solved, already been taken care of
-- by the overlap check with the instance environment.
matchable _tys ct = pprPanic "Expecting dictionary!" (ppr ct)
{-
Note [Instance and Given overlap]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Example, from the OutsideIn(X) paper:
instance P x => Q [x]
instance (x ~ y) => R y [x]
wob :: forall a b. (Q [b], R b a) => a -> Int
g :: forall a. Q [a] => [a] -> Int
g x = wob x
This will generate the impliation constraint:
Q [a] => (Q [beta], R beta [a])
If we react (Q [beta]) with its top-level axiom, we end up with a
(P beta), which we have no way of discharging. On the other hand,
if we react R beta [a] with the top-level we get (beta ~ a), which
is solvable and can help us rewrite (Q [beta]) to (Q [a]) which is
now solvable by the given Q [a].
The solution is that:
In matchClassInst (and thus in topReact), we return a matching
instance only when there is no Given in the inerts which is
unifiable to this particular dictionary.
The end effect is that, much as we do for overlapping instances, we delay choosing a
class instance if there is a possibility of another instance OR a given to match our
constraint later on. This fixes bugs #4981 and #5002.
This is arguably not easy to appear in practice due to our aggressive prioritization
of equality solving over other constraints, but it is possible. I've added a test case
in typecheck/should-compile/GivenOverlapping.hs
We ignore the overlap problem if -XIncoherentInstances is in force: see
Trac #6002 for a worked-out example where this makes a difference.
Moreover notice that our goals here are different than the goals of the top-level
overlapping checks. There we are interested in validating the following principle:
If we inline a function f at a site where the same global instance environment
is available as the instance environment at the definition site of f then we
should get the same behaviour.
But for the Given Overlap check our goal is just related to completeness of
constraint solving.
-}
|
green-haskell/ghc
|
compiler/typecheck/TcInteract.hs
|
bsd-3-clause
| 73,245 | 38 | 23 | 21,971 | 10,656 | 5,547 | 5,109 | -1 | -1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.PixelRectangles.Rasterization
-- Copyright : (c) Sven Panne 2002-2005
-- License : BSD-style (see the file libraries/OpenGL/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- This module corresponds to a part of section 3.6.4 (Rasterization of Pixel
-- Rectangles) of the OpenGL 1.5 specs.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.PixelRectangles.Rasterization (
PixelData(..), PixelFormat(..), drawPixels, pixelZoom
) where
import Control.Monad ( liftM2 )
import Foreign.Ptr ( Ptr )
import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLenum, GLsizei, GLfloat )
import Graphics.Rendering.OpenGL.GL.CoordTrans ( Size(..) )
import Graphics.Rendering.OpenGL.GL.PixelData ( PixelData(..), withPixelData )
import Graphics.Rendering.OpenGL.GL.PixelFormat ( PixelFormat(..) )
import Graphics.Rendering.OpenGL.GL.QueryUtils (
GetPName(GetZoomX,GetZoomY), getFloat1 )
import Graphics.Rendering.OpenGL.GL.StateVar ( StateVar, makeStateVar )
--------------------------------------------------------------------------------
drawPixels :: Size -> PixelData a -> IO ()
drawPixels (Size w h) pd = withPixelData pd $ glDrawPixels w h
foreign import CALLCONV unsafe "glDrawPixels" glDrawPixels ::
GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ()
--------------------------------------------------------------------------------
pixelZoom :: StateVar (GLfloat, GLfloat)
pixelZoom =
makeStateVar
(liftM2 (,) (getFloat1 id GetZoomX) (getFloat1 id GetZoomY))
(uncurry glPixelZoom)
foreign import CALLCONV unsafe "glPixelZoom" glPixelZoom ::
GLfloat -> GLfloat -> IO ()
|
FranklinChen/hugs98-plus-Sep2006
|
packages/OpenGL/Graphics/Rendering/OpenGL/GL/PixelRectangles/Rasterization.hs
|
bsd-3-clause
| 1,872 | 7 | 10 | 242 | 356 | 219 | 137 | -1 | -1 |
----------------------------------------------------------------
-- Модуль приложения
-- Скрипты графического интерфейса (HScript)
-- Язык JavaScript
----------------------------------------------------------------
module WebUI.Scripts.JavaScript.HJavaScript
( module HJavaScriptBuilder
, module HJavaScriptTypes
, module HJavaScriptVars
, module HJavaScriptExps
, module HJavaScriptMath
, module HJavaScriptFunction
, module HJavaScriptElementDOM
, hjs
, ujs
, upjs
, hjsBR
, jsFinish
) where
-- Импорт модулей
import Prelude as PRL
import Data.Char (toLower)
import Data.String.Utils (strip)
import qualified Data.Text.Lazy as DTL
import Data.Int
import Control.Monad.RWS as ConMonRWS
import System.IO.Unsafe (unsafePerformIO)
import Text.Blaze.Html5
import Text.Hamlet
import Text.Lucius
import Text.Cassius
import Text.Julius
import WebUI.Scripts.HScript
import WebUI.Scripts.JavaScript.HJSUtils (smartTrim, ujs, upjs)
import WebUI.Scripts.JavaScript.HJSBuilder as HJavaScriptBuilder
import WebUI.Scripts.JavaScript.HJSTypes as HJavaScriptTypes
import WebUI.Scripts.JavaScript.HJSVars as HJavaScriptVars
import WebUI.Scripts.JavaScript.HJSExps as HJavaScriptExps
import WebUI.Scripts.JavaScript.HJSMath as HJavaScriptMath
import WebUI.Scripts.JavaScript.HJSFunction as HJavaScriptFunction
import WebUI.Scripts.JavaScript.HJSElementDOM as HJavaScriptElementDOM
-- | Подготовка JavaScript
prepareJS b = renderJavascriptUrl undefined b
-- | Виджет скрипта JS
hjs :: JavascriptUrl b
-> HSL HLangJS HLangJS
hjs js = do
hl <- return $ HL $ smartTrim $ do prepareJS js
modify (:> hl)
return hl
-- | Детектор WebGL
hjsBR :: HSL HLangJS HLangJS
hjsBR = do
c <- ask
hl <- return $ HL $ " " ++ (hbc_entryLine c)
modify (:> hl)
return hl
jsFinish :: HSL HLangJS HLFinish
jsFinish = do
return HLFinish
|
iqsf/HFitUI
|
src/WebUI/Scripts/JavaScript/HJavaScript.hs
|
bsd-3-clause
| 2,483 | 0 | 11 | 801 | 397 | 244 | 153 | 50 | 1 |
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
{- |
Module : $Header$
Description : Coding of a CASL sublogic to Propositional
Copyright : (c) Dominik Luecke and Uni Bremen 2007
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : non-portable (imports Logic.Logic)
A comorphism from CASL to Propositional. The CASL sublogic does not precisely
capture the valid domain of the translation. Sorts, ops and preds with
arguments will be ignored. The translation will fail for non-propositional
sentences.
-}
module Comorphisms.CASL2Prop (CASL2Prop (..)) where
import Common.ProofTree
import Logic.Logic
import Logic.Comorphism
-- Propositional
import qualified Propositional.Logic_Propositional as PLogic
import qualified Propositional.AS_BASIC_Propositional as PBasic
import qualified Propositional.Sublogic as PSL
import qualified Propositional.Sign as PSign
import qualified Propositional.Morphism as PMor
import qualified Propositional.Symbol as PSymbol
-- CASL
import CASL.Logic_CASL
import CASL.AS_Basic_CASL
import CASL.Sublogic
import CASL.Sign
import CASL.Morphism
import qualified Data.Set as Set
import qualified Data.Map as Map
import Common.AS_Annotation
import Common.Id
import Common.Result
import Common.DocUtils
import qualified Common.Lib.MapSet as MapSet
-- | lid of the morphism
data CASL2Prop = CASL2Prop deriving Show
instance Language CASL2Prop where
language_name CASL2Prop = "CASL2Propositional"
instance Comorphism CASL2Prop
CASL
CASL_Sublogics
CASLBasicSpec
CASLFORMULA
SYMB_ITEMS
SYMB_MAP_ITEMS
CASLSign
CASLMor
Symbol
RawSymbol
ProofTree
PLogic.Propositional
PSL.PropSL
PBasic.BASIC_SPEC
PBasic.FORMULA
PBasic.SYMB_ITEMS
PBasic.SYMB_MAP_ITEMS
PSign.Sign
PMor.Morphism
PSymbol.Symbol
PSymbol.Symbol
ProofTree
where
sourceLogic CASL2Prop = CASL
sourceSublogic CASL2Prop = sublogics_max need_fol need_pred
targetLogic CASL2Prop = PLogic.Propositional
mapSublogic CASL2Prop = Just . mapSub
map_theory CASL2Prop = mapTheory
is_model_transportable CASL2Prop = True
map_symbol CASL2Prop _ = mapSym
map_sentence CASL2Prop _ = trForm
map_morphism CASL2Prop = mapMor
has_model_expansion CASL2Prop = False
is_weakly_amalgamable CASL2Prop = True
isInclusionComorphism CASL2Prop = False
-- | Translation of the signature
mapSig :: CASLSign -> PSign.Sign
mapSig = PSign.Sign . MapSet.keysSet
. MapSet.filter (null . predArgs) . predMap
-- | Which is the target sublogic?
mapSub :: CASL_Sublogics -> PSL.PropSL
mapSub sl = if which_logic sl <= Horn then PSL.bottom else PSL.top
-- | Translation of morphisms
mapMor :: CASLMor -> Result PMor.Morphism
mapMor mor = return PMor.Morphism
{ PMor.source = mapSig (msource mor)
, PMor.target = mapSig (mtarget mor)
, PMor.propMap = Map.foldWithKey (\ (i, pt) j ->
if null (predArgs pt) then Map.insert i j else id) Map.empty
$ pred_map mor }
-- | Mapping of a theory
mapTheory :: (CASLSign, [Named CASLFORMULA])
-> Result (PSign.Sign, [Named PBasic.FORMULA])
mapTheory (sig, form) = do
sens <- mapM trNamedForm form
return (mapSig sig, sens)
-- | Translation of symbols
mapSym :: Symbol -> Set.Set PSymbol.Symbol
mapSym sym = case symbType sym of
PredAsItemType pt | null $ predArgs pt ->
Set.singleton (PSymbol.Symbol $ symName sym)
_ -> Set.empty
-- | Helper for map theory
trNamedForm :: Named CASLFORMULA -> Result (Named PBasic.FORMULA)
trNamedForm = mapNamedM trForm
-- | Helper for map sentence and map theory
trForm :: CASLFORMULA -> Result PBasic.FORMULA
trForm form = case form of
Negation fn rn -> do
t <- trForm fn
return $ PBasic.Negation t rn
Junction j fn rn -> do
ts <- mapM trForm fn
return $ (case j of
Con -> PBasic.Conjunction
Dis -> PBasic.Disjunction) ts rn
Relation f1 c f2 rn -> do
t1 <- trForm f1
t2 <- trForm f2
return $ (if c == Equivalence then PBasic.Equivalence else
PBasic.Implication) t1 t2 rn
Atom b rn -> return $ (if b then PBasic.True_atom else PBasic.False_atom) rn
Predication (Qual_pred_name pid (Pred_type [] _) _) [] _ ->
return . PBasic.Predication . mkSimpleId $ show pid
_ -> fail $ "not a propositional formula: " ++ showDoc form ""
|
keithodulaigh/Hets
|
Comorphisms/CASL2Prop.hs
|
gpl-2.0
| 4,439 | 17 | 15 | 874 | 1,051 | 559 | 492 | 104 | 9 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.SWF.Types.Product
-- 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)
--
module Network.AWS.SWF.Types.Product where
import Network.AWS.Prelude
import Network.AWS.SWF.Types.Sum
-- | Provides details of the 'ActivityTaskCancelRequested' event.
--
-- /See:/ 'activityTaskCancelRequestedEventAttributes' smart constructor.
data ActivityTaskCancelRequestedEventAttributes = ActivityTaskCancelRequestedEventAttributes'
{ _atcreaDecisionTaskCompletedEventId :: !Integer
, _atcreaActivityId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ActivityTaskCancelRequestedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'atcreaDecisionTaskCompletedEventId'
--
-- * 'atcreaActivityId'
activityTaskCancelRequestedEventAttributes
:: Integer -- ^ 'atcreaDecisionTaskCompletedEventId'
-> Text -- ^ 'atcreaActivityId'
-> ActivityTaskCancelRequestedEventAttributes
activityTaskCancelRequestedEventAttributes pDecisionTaskCompletedEventId_ pActivityId_ =
ActivityTaskCancelRequestedEventAttributes'
{ _atcreaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
, _atcreaActivityId = pActivityId_
}
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'RequestCancelActivityTask' decision
-- for this cancellation request. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
atcreaDecisionTaskCompletedEventId :: Lens' ActivityTaskCancelRequestedEventAttributes Integer
atcreaDecisionTaskCompletedEventId = lens _atcreaDecisionTaskCompletedEventId (\ s a -> s{_atcreaDecisionTaskCompletedEventId = a});
-- | The unique ID of the task.
atcreaActivityId :: Lens' ActivityTaskCancelRequestedEventAttributes Text
atcreaActivityId = lens _atcreaActivityId (\ s a -> s{_atcreaActivityId = a});
instance FromJSON
ActivityTaskCancelRequestedEventAttributes where
parseJSON
= withObject
"ActivityTaskCancelRequestedEventAttributes"
(\ x ->
ActivityTaskCancelRequestedEventAttributes' <$>
(x .: "decisionTaskCompletedEventId") <*>
(x .: "activityId"))
-- | Provides details of the 'ActivityTaskCanceled' event.
--
-- /See:/ 'activityTaskCanceledEventAttributes' smart constructor.
data ActivityTaskCanceledEventAttributes = ActivityTaskCanceledEventAttributes'
{ _aLatestCancelRequestedEventId :: !(Maybe Integer)
, _aDetails :: !(Maybe Text)
, _aScheduledEventId :: !Integer
, _aStartedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ActivityTaskCanceledEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aLatestCancelRequestedEventId'
--
-- * 'aDetails'
--
-- * 'aScheduledEventId'
--
-- * 'aStartedEventId'
activityTaskCanceledEventAttributes
:: Integer -- ^ 'aScheduledEventId'
-> Integer -- ^ 'aStartedEventId'
-> ActivityTaskCanceledEventAttributes
activityTaskCanceledEventAttributes pScheduledEventId_ pStartedEventId_ =
ActivityTaskCanceledEventAttributes'
{ _aLatestCancelRequestedEventId = Nothing
, _aDetails = Nothing
, _aScheduledEventId = pScheduledEventId_
, _aStartedEventId = pStartedEventId_
}
-- | If set, contains the ID of the last 'ActivityTaskCancelRequested' event
-- recorded for this activity task. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
aLatestCancelRequestedEventId :: Lens' ActivityTaskCanceledEventAttributes (Maybe Integer)
aLatestCancelRequestedEventId = lens _aLatestCancelRequestedEventId (\ s a -> s{_aLatestCancelRequestedEventId = a});
-- | Details of the cancellation (if any).
aDetails :: Lens' ActivityTaskCanceledEventAttributes (Maybe Text)
aDetails = lens _aDetails (\ s a -> s{_aDetails = a});
-- | The ID of the 'ActivityTaskScheduled' event that was recorded when this
-- activity task was scheduled. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
aScheduledEventId :: Lens' ActivityTaskCanceledEventAttributes Integer
aScheduledEventId = lens _aScheduledEventId (\ s a -> s{_aScheduledEventId = a});
-- | The ID of the 'ActivityTaskStarted' event recorded when this activity
-- task was started. This information can be useful for diagnosing problems
-- by tracing back the chain of events leading up to this event.
aStartedEventId :: Lens' ActivityTaskCanceledEventAttributes Integer
aStartedEventId = lens _aStartedEventId (\ s a -> s{_aStartedEventId = a});
instance FromJSON ActivityTaskCanceledEventAttributes
where
parseJSON
= withObject "ActivityTaskCanceledEventAttributes"
(\ x ->
ActivityTaskCanceledEventAttributes' <$>
(x .:? "latestCancelRequestedEventId") <*>
(x .:? "details")
<*> (x .: "scheduledEventId")
<*> (x .: "startedEventId"))
-- | Provides details of the 'ActivityTaskCompleted' event.
--
-- /See:/ 'activityTaskCompletedEventAttributes' smart constructor.
data ActivityTaskCompletedEventAttributes = ActivityTaskCompletedEventAttributes'
{ _atceaResult :: !(Maybe Text)
, _atceaScheduledEventId :: !Integer
, _atceaStartedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ActivityTaskCompletedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'atceaResult'
--
-- * 'atceaScheduledEventId'
--
-- * 'atceaStartedEventId'
activityTaskCompletedEventAttributes
:: Integer -- ^ 'atceaScheduledEventId'
-> Integer -- ^ 'atceaStartedEventId'
-> ActivityTaskCompletedEventAttributes
activityTaskCompletedEventAttributes pScheduledEventId_ pStartedEventId_ =
ActivityTaskCompletedEventAttributes'
{ _atceaResult = Nothing
, _atceaScheduledEventId = pScheduledEventId_
, _atceaStartedEventId = pStartedEventId_
}
-- | The results of the activity task (if any).
atceaResult :: Lens' ActivityTaskCompletedEventAttributes (Maybe Text)
atceaResult = lens _atceaResult (\ s a -> s{_atceaResult = a});
-- | The ID of the 'ActivityTaskScheduled' event that was recorded when this
-- activity task was scheduled. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
atceaScheduledEventId :: Lens' ActivityTaskCompletedEventAttributes Integer
atceaScheduledEventId = lens _atceaScheduledEventId (\ s a -> s{_atceaScheduledEventId = a});
-- | The ID of the 'ActivityTaskStarted' event recorded when this activity
-- task was started. This information can be useful for diagnosing problems
-- by tracing back the chain of events leading up to this event.
atceaStartedEventId :: Lens' ActivityTaskCompletedEventAttributes Integer
atceaStartedEventId = lens _atceaStartedEventId (\ s a -> s{_atceaStartedEventId = a});
instance FromJSON
ActivityTaskCompletedEventAttributes where
parseJSON
= withObject "ActivityTaskCompletedEventAttributes"
(\ x ->
ActivityTaskCompletedEventAttributes' <$>
(x .:? "result") <*> (x .: "scheduledEventId") <*>
(x .: "startedEventId"))
-- | Provides details of the 'ActivityTaskFailed' event.
--
-- /See:/ 'activityTaskFailedEventAttributes' smart constructor.
data ActivityTaskFailedEventAttributes = ActivityTaskFailedEventAttributes'
{ _atfeaReason :: !(Maybe Text)
, _atfeaDetails :: !(Maybe Text)
, _atfeaScheduledEventId :: !Integer
, _atfeaStartedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ActivityTaskFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'atfeaReason'
--
-- * 'atfeaDetails'
--
-- * 'atfeaScheduledEventId'
--
-- * 'atfeaStartedEventId'
activityTaskFailedEventAttributes
:: Integer -- ^ 'atfeaScheduledEventId'
-> Integer -- ^ 'atfeaStartedEventId'
-> ActivityTaskFailedEventAttributes
activityTaskFailedEventAttributes pScheduledEventId_ pStartedEventId_ =
ActivityTaskFailedEventAttributes'
{ _atfeaReason = Nothing
, _atfeaDetails = Nothing
, _atfeaScheduledEventId = pScheduledEventId_
, _atfeaStartedEventId = pStartedEventId_
}
-- | The reason provided for the failure (if any).
atfeaReason :: Lens' ActivityTaskFailedEventAttributes (Maybe Text)
atfeaReason = lens _atfeaReason (\ s a -> s{_atfeaReason = a});
-- | The details of the failure (if any).
atfeaDetails :: Lens' ActivityTaskFailedEventAttributes (Maybe Text)
atfeaDetails = lens _atfeaDetails (\ s a -> s{_atfeaDetails = a});
-- | The ID of the 'ActivityTaskScheduled' event that was recorded when this
-- activity task was scheduled. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
atfeaScheduledEventId :: Lens' ActivityTaskFailedEventAttributes Integer
atfeaScheduledEventId = lens _atfeaScheduledEventId (\ s a -> s{_atfeaScheduledEventId = a});
-- | The ID of the 'ActivityTaskStarted' event recorded when this activity
-- task was started. This information can be useful for diagnosing problems
-- by tracing back the chain of events leading up to this event.
atfeaStartedEventId :: Lens' ActivityTaskFailedEventAttributes Integer
atfeaStartedEventId = lens _atfeaStartedEventId (\ s a -> s{_atfeaStartedEventId = a});
instance FromJSON ActivityTaskFailedEventAttributes
where
parseJSON
= withObject "ActivityTaskFailedEventAttributes"
(\ x ->
ActivityTaskFailedEventAttributes' <$>
(x .:? "reason") <*> (x .:? "details") <*>
(x .: "scheduledEventId")
<*> (x .: "startedEventId"))
-- | Provides details of the 'ActivityTaskScheduled' event.
--
-- /See:/ 'activityTaskScheduledEventAttributes' smart constructor.
data ActivityTaskScheduledEventAttributes = ActivityTaskScheduledEventAttributes'
{ _atseaControl :: !(Maybe Text)
, _atseaHeartbeatTimeout :: !(Maybe Text)
, _atseaScheduleToCloseTimeout :: !(Maybe Text)
, _atseaInput :: !(Maybe Text)
, _atseaTaskPriority :: !(Maybe Text)
, _atseaScheduleToStartTimeout :: !(Maybe Text)
, _atseaStartToCloseTimeout :: !(Maybe Text)
, _atseaActivityType :: !ActivityType
, _atseaActivityId :: !Text
, _atseaTaskList :: !TaskList
, _atseaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ActivityTaskScheduledEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'atseaControl'
--
-- * 'atseaHeartbeatTimeout'
--
-- * 'atseaScheduleToCloseTimeout'
--
-- * 'atseaInput'
--
-- * 'atseaTaskPriority'
--
-- * 'atseaScheduleToStartTimeout'
--
-- * 'atseaStartToCloseTimeout'
--
-- * 'atseaActivityType'
--
-- * 'atseaActivityId'
--
-- * 'atseaTaskList'
--
-- * 'atseaDecisionTaskCompletedEventId'
activityTaskScheduledEventAttributes
:: ActivityType -- ^ 'atseaActivityType'
-> Text -- ^ 'atseaActivityId'
-> TaskList -- ^ 'atseaTaskList'
-> Integer -- ^ 'atseaDecisionTaskCompletedEventId'
-> ActivityTaskScheduledEventAttributes
activityTaskScheduledEventAttributes pActivityType_ pActivityId_ pTaskList_ pDecisionTaskCompletedEventId_ =
ActivityTaskScheduledEventAttributes'
{ _atseaControl = Nothing
, _atseaHeartbeatTimeout = Nothing
, _atseaScheduleToCloseTimeout = Nothing
, _atseaInput = Nothing
, _atseaTaskPriority = Nothing
, _atseaScheduleToStartTimeout = Nothing
, _atseaStartToCloseTimeout = Nothing
, _atseaActivityType = pActivityType_
, _atseaActivityId = pActivityId_
, _atseaTaskList = pTaskList_
, _atseaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | /Optional./ Data attached to the event that can be used by the decider
-- in subsequent workflow tasks. This data is not sent to the activity.
atseaControl :: Lens' ActivityTaskScheduledEventAttributes (Maybe Text)
atseaControl = lens _atseaControl (\ s a -> s{_atseaControl = a});
-- | The maximum time before which the worker processing this task must
-- report progress by calling RecordActivityTaskHeartbeat. If the timeout
-- is exceeded, the activity task is automatically timed out. If the worker
-- subsequently attempts to record a heartbeat or return a result, it will
-- be ignored.
atseaHeartbeatTimeout :: Lens' ActivityTaskScheduledEventAttributes (Maybe Text)
atseaHeartbeatTimeout = lens _atseaHeartbeatTimeout (\ s a -> s{_atseaHeartbeatTimeout = a});
-- | The maximum amount of time for this activity task.
atseaScheduleToCloseTimeout :: Lens' ActivityTaskScheduledEventAttributes (Maybe Text)
atseaScheduleToCloseTimeout = lens _atseaScheduleToCloseTimeout (\ s a -> s{_atseaScheduleToCloseTimeout = a});
-- | The input provided to the activity task.
atseaInput :: Lens' ActivityTaskScheduledEventAttributes (Maybe Text)
atseaInput = lens _atseaInput (\ s a -> s{_atseaInput = a});
-- | /Optional./ The priority to assign to the scheduled activity task. If
-- set, this will override any default priority value that was assigned
-- when the activity type was registered.
--
-- Valid values are integers that range from Java\'s 'Integer.MIN_VALUE'
-- (-2147483648) to 'Integer.MAX_VALUE' (2147483647). Higher numbers
-- indicate higher priority.
--
-- For more information about setting task priority, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/programming-priority.html Setting Task Priority>
-- in the /Amazon Simple Workflow Developer Guide/.
atseaTaskPriority :: Lens' ActivityTaskScheduledEventAttributes (Maybe Text)
atseaTaskPriority = lens _atseaTaskPriority (\ s a -> s{_atseaTaskPriority = a});
-- | The maximum amount of time the activity task can wait to be assigned to
-- a worker.
atseaScheduleToStartTimeout :: Lens' ActivityTaskScheduledEventAttributes (Maybe Text)
atseaScheduleToStartTimeout = lens _atseaScheduleToStartTimeout (\ s a -> s{_atseaScheduleToStartTimeout = a});
-- | The maximum amount of time a worker may take to process the activity
-- task.
atseaStartToCloseTimeout :: Lens' ActivityTaskScheduledEventAttributes (Maybe Text)
atseaStartToCloseTimeout = lens _atseaStartToCloseTimeout (\ s a -> s{_atseaStartToCloseTimeout = a});
-- | The type of the activity task.
atseaActivityType :: Lens' ActivityTaskScheduledEventAttributes ActivityType
atseaActivityType = lens _atseaActivityType (\ s a -> s{_atseaActivityType = a});
-- | The unique ID of the activity task.
atseaActivityId :: Lens' ActivityTaskScheduledEventAttributes Text
atseaActivityId = lens _atseaActivityId (\ s a -> s{_atseaActivityId = a});
-- | The task list in which the activity task has been scheduled.
atseaTaskList :: Lens' ActivityTaskScheduledEventAttributes TaskList
atseaTaskList = lens _atseaTaskList (\ s a -> s{_atseaTaskList = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision that resulted in the scheduling of this activity task. This
-- information can be useful for diagnosing problems by tracing back the
-- chain of events leading up to this event.
atseaDecisionTaskCompletedEventId :: Lens' ActivityTaskScheduledEventAttributes Integer
atseaDecisionTaskCompletedEventId = lens _atseaDecisionTaskCompletedEventId (\ s a -> s{_atseaDecisionTaskCompletedEventId = a});
instance FromJSON
ActivityTaskScheduledEventAttributes where
parseJSON
= withObject "ActivityTaskScheduledEventAttributes"
(\ x ->
ActivityTaskScheduledEventAttributes' <$>
(x .:? "control") <*> (x .:? "heartbeatTimeout") <*>
(x .:? "scheduleToCloseTimeout")
<*> (x .:? "input")
<*> (x .:? "taskPriority")
<*> (x .:? "scheduleToStartTimeout")
<*> (x .:? "startToCloseTimeout")
<*> (x .: "activityType")
<*> (x .: "activityId")
<*> (x .: "taskList")
<*> (x .: "decisionTaskCompletedEventId"))
-- | Provides details of the 'ActivityTaskStarted' event.
--
-- /See:/ 'activityTaskStartedEventAttributes' smart constructor.
data ActivityTaskStartedEventAttributes = ActivityTaskStartedEventAttributes'
{ _atseaIdentity :: !(Maybe Text)
, _atseaScheduledEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ActivityTaskStartedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'atseaIdentity'
--
-- * 'atseaScheduledEventId'
activityTaskStartedEventAttributes
:: Integer -- ^ 'atseaScheduledEventId'
-> ActivityTaskStartedEventAttributes
activityTaskStartedEventAttributes pScheduledEventId_ =
ActivityTaskStartedEventAttributes'
{ _atseaIdentity = Nothing
, _atseaScheduledEventId = pScheduledEventId_
}
-- | Identity of the worker that was assigned this task. This aids
-- diagnostics when problems arise. The form of this identity is user
-- defined.
atseaIdentity :: Lens' ActivityTaskStartedEventAttributes (Maybe Text)
atseaIdentity = lens _atseaIdentity (\ s a -> s{_atseaIdentity = a});
-- | The ID of the 'ActivityTaskScheduled' event that was recorded when this
-- activity task was scheduled. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
atseaScheduledEventId :: Lens' ActivityTaskStartedEventAttributes Integer
atseaScheduledEventId = lens _atseaScheduledEventId (\ s a -> s{_atseaScheduledEventId = a});
instance FromJSON ActivityTaskStartedEventAttributes
where
parseJSON
= withObject "ActivityTaskStartedEventAttributes"
(\ x ->
ActivityTaskStartedEventAttributes' <$>
(x .:? "identity") <*> (x .: "scheduledEventId"))
-- | Provides details of the 'ActivityTaskTimedOut' event.
--
-- /See:/ 'activityTaskTimedOutEventAttributes' smart constructor.
data ActivityTaskTimedOutEventAttributes = ActivityTaskTimedOutEventAttributes'
{ _attoeaDetails :: !(Maybe Text)
, _attoeaTimeoutType :: !ActivityTaskTimeoutType
, _attoeaScheduledEventId :: !Integer
, _attoeaStartedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ActivityTaskTimedOutEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'attoeaDetails'
--
-- * 'attoeaTimeoutType'
--
-- * 'attoeaScheduledEventId'
--
-- * 'attoeaStartedEventId'
activityTaskTimedOutEventAttributes
:: ActivityTaskTimeoutType -- ^ 'attoeaTimeoutType'
-> Integer -- ^ 'attoeaScheduledEventId'
-> Integer -- ^ 'attoeaStartedEventId'
-> ActivityTaskTimedOutEventAttributes
activityTaskTimedOutEventAttributes pTimeoutType_ pScheduledEventId_ pStartedEventId_ =
ActivityTaskTimedOutEventAttributes'
{ _attoeaDetails = Nothing
, _attoeaTimeoutType = pTimeoutType_
, _attoeaScheduledEventId = pScheduledEventId_
, _attoeaStartedEventId = pStartedEventId_
}
-- | Contains the content of the 'details' parameter for the last call made
-- by the activity to 'RecordActivityTaskHeartbeat'.
attoeaDetails :: Lens' ActivityTaskTimedOutEventAttributes (Maybe Text)
attoeaDetails = lens _attoeaDetails (\ s a -> s{_attoeaDetails = a});
-- | The type of the timeout that caused this event.
attoeaTimeoutType :: Lens' ActivityTaskTimedOutEventAttributes ActivityTaskTimeoutType
attoeaTimeoutType = lens _attoeaTimeoutType (\ s a -> s{_attoeaTimeoutType = a});
-- | The ID of the 'ActivityTaskScheduled' event that was recorded when this
-- activity task was scheduled. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
attoeaScheduledEventId :: Lens' ActivityTaskTimedOutEventAttributes Integer
attoeaScheduledEventId = lens _attoeaScheduledEventId (\ s a -> s{_attoeaScheduledEventId = a});
-- | The ID of the 'ActivityTaskStarted' event recorded when this activity
-- task was started. This information can be useful for diagnosing problems
-- by tracing back the chain of events leading up to this event.
attoeaStartedEventId :: Lens' ActivityTaskTimedOutEventAttributes Integer
attoeaStartedEventId = lens _attoeaStartedEventId (\ s a -> s{_attoeaStartedEventId = a});
instance FromJSON ActivityTaskTimedOutEventAttributes
where
parseJSON
= withObject "ActivityTaskTimedOutEventAttributes"
(\ x ->
ActivityTaskTimedOutEventAttributes' <$>
(x .:? "details") <*> (x .: "timeoutType") <*>
(x .: "scheduledEventId")
<*> (x .: "startedEventId"))
-- | Represents an activity type.
--
-- /See:/ 'activityType' smart constructor.
data ActivityType = ActivityType'
{ _atName :: !Text
, _atVersion :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ActivityType' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'atName'
--
-- * 'atVersion'
activityType
:: Text -- ^ 'atName'
-> Text -- ^ 'atVersion'
-> ActivityType
activityType pName_ pVersion_ =
ActivityType'
{ _atName = pName_
, _atVersion = pVersion_
}
-- | The name of this activity.
--
-- The combination of activity type name and version must be unique within
-- a domain.
atName :: Lens' ActivityType Text
atName = lens _atName (\ s a -> s{_atName = a});
-- | The version of this activity.
--
-- The combination of activity type name and version must be unique with in
-- a domain.
atVersion :: Lens' ActivityType Text
atVersion = lens _atVersion (\ s a -> s{_atVersion = a});
instance FromJSON ActivityType where
parseJSON
= withObject "ActivityType"
(\ x ->
ActivityType' <$> (x .: "name") <*> (x .: "version"))
instance ToJSON ActivityType where
toJSON ActivityType'{..}
= object
(catMaybes
[Just ("name" .= _atName),
Just ("version" .= _atVersion)])
-- | Configuration settings registered with the activity type.
--
-- /See:/ 'activityTypeConfiguration' smart constructor.
data ActivityTypeConfiguration = ActivityTypeConfiguration'
{ _atcDefaultTaskScheduleToStartTimeout :: !(Maybe Text)
, _atcDefaultTaskList :: !(Maybe TaskList)
, _atcDefaultTaskPriority :: !(Maybe Text)
, _atcDefaultTaskHeartbeatTimeout :: !(Maybe Text)
, _atcDefaultTaskScheduleToCloseTimeout :: !(Maybe Text)
, _atcDefaultTaskStartToCloseTimeout :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ActivityTypeConfiguration' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'atcDefaultTaskScheduleToStartTimeout'
--
-- * 'atcDefaultTaskList'
--
-- * 'atcDefaultTaskPriority'
--
-- * 'atcDefaultTaskHeartbeatTimeout'
--
-- * 'atcDefaultTaskScheduleToCloseTimeout'
--
-- * 'atcDefaultTaskStartToCloseTimeout'
activityTypeConfiguration
:: ActivityTypeConfiguration
activityTypeConfiguration =
ActivityTypeConfiguration'
{ _atcDefaultTaskScheduleToStartTimeout = Nothing
, _atcDefaultTaskList = Nothing
, _atcDefaultTaskPriority = Nothing
, _atcDefaultTaskHeartbeatTimeout = Nothing
, _atcDefaultTaskScheduleToCloseTimeout = Nothing
, _atcDefaultTaskStartToCloseTimeout = Nothing
}
-- | /Optional./ The default maximum duration, specified when registering the
-- activity type, that a task of an activity type can wait before being
-- assigned to a worker. You can override this default when scheduling a
-- task through the 'ScheduleActivityTask' decision.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
atcDefaultTaskScheduleToStartTimeout :: Lens' ActivityTypeConfiguration (Maybe Text)
atcDefaultTaskScheduleToStartTimeout = lens _atcDefaultTaskScheduleToStartTimeout (\ s a -> s{_atcDefaultTaskScheduleToStartTimeout = a});
-- | /Optional./ The default task list specified for this activity type at
-- registration. This default is used if a task list is not provided when a
-- task is scheduled through the 'ScheduleActivityTask' decision. You can
-- override the default registered task list when scheduling a task through
-- the 'ScheduleActivityTask' decision.
atcDefaultTaskList :: Lens' ActivityTypeConfiguration (Maybe TaskList)
atcDefaultTaskList = lens _atcDefaultTaskList (\ s a -> s{_atcDefaultTaskList = a});
-- | /Optional./ The default task priority for tasks of this activity type,
-- specified at registration. If not set, then \"0\" will be used as the
-- default priority. This default can be overridden when scheduling an
-- activity task.
--
-- Valid values are integers that range from Java\'s 'Integer.MIN_VALUE'
-- (-2147483648) to 'Integer.MAX_VALUE' (2147483647). Higher numbers
-- indicate higher priority.
--
-- For more information about setting task priority, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/programming-priority.html Setting Task Priority>
-- in the /Amazon Simple Workflow Developer Guide/.
atcDefaultTaskPriority :: Lens' ActivityTypeConfiguration (Maybe Text)
atcDefaultTaskPriority = lens _atcDefaultTaskPriority (\ s a -> s{_atcDefaultTaskPriority = a});
-- | /Optional./ The default maximum time, in seconds, before which a worker
-- processing a task must report progress by calling
-- RecordActivityTaskHeartbeat.
--
-- You can specify this value only when /registering/ an activity type. The
-- registered default value can be overridden when you schedule a task
-- through the 'ScheduleActivityTask' decision. If the activity worker
-- subsequently attempts to record a heartbeat or returns a result, the
-- activity worker receives an 'UnknownResource' fault. In this case,
-- Amazon SWF no longer considers the activity task to be valid; the
-- activity worker should clean up the activity task.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
atcDefaultTaskHeartbeatTimeout :: Lens' ActivityTypeConfiguration (Maybe Text)
atcDefaultTaskHeartbeatTimeout = lens _atcDefaultTaskHeartbeatTimeout (\ s a -> s{_atcDefaultTaskHeartbeatTimeout = a});
-- | /Optional./ The default maximum duration, specified when registering the
-- activity type, for tasks of this activity type. You can override this
-- default when scheduling a task through the 'ScheduleActivityTask'
-- decision.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
atcDefaultTaskScheduleToCloseTimeout :: Lens' ActivityTypeConfiguration (Maybe Text)
atcDefaultTaskScheduleToCloseTimeout = lens _atcDefaultTaskScheduleToCloseTimeout (\ s a -> s{_atcDefaultTaskScheduleToCloseTimeout = a});
-- | /Optional./ The default maximum duration for tasks of an activity type
-- specified when registering the activity type. You can override this
-- default when scheduling a task through the 'ScheduleActivityTask'
-- decision.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
atcDefaultTaskStartToCloseTimeout :: Lens' ActivityTypeConfiguration (Maybe Text)
atcDefaultTaskStartToCloseTimeout = lens _atcDefaultTaskStartToCloseTimeout (\ s a -> s{_atcDefaultTaskStartToCloseTimeout = a});
instance FromJSON ActivityTypeConfiguration where
parseJSON
= withObject "ActivityTypeConfiguration"
(\ x ->
ActivityTypeConfiguration' <$>
(x .:? "defaultTaskScheduleToStartTimeout") <*>
(x .:? "defaultTaskList")
<*> (x .:? "defaultTaskPriority")
<*> (x .:? "defaultTaskHeartbeatTimeout")
<*> (x .:? "defaultTaskScheduleToCloseTimeout")
<*> (x .:? "defaultTaskStartToCloseTimeout"))
-- | Detailed information about an activity type.
--
-- /See:/ 'activityTypeInfo' smart constructor.
data ActivityTypeInfo = ActivityTypeInfo'
{ _atiDeprecationDate :: !(Maybe POSIX)
, _atiDescription :: !(Maybe Text)
, _atiActivityType :: !ActivityType
, _atiStatus :: !RegistrationStatus
, _atiCreationDate :: !POSIX
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ActivityTypeInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'atiDeprecationDate'
--
-- * 'atiDescription'
--
-- * 'atiActivityType'
--
-- * 'atiStatus'
--
-- * 'atiCreationDate'
activityTypeInfo
:: ActivityType -- ^ 'atiActivityType'
-> RegistrationStatus -- ^ 'atiStatus'
-> UTCTime -- ^ 'atiCreationDate'
-> ActivityTypeInfo
activityTypeInfo pActivityType_ pStatus_ pCreationDate_ =
ActivityTypeInfo'
{ _atiDeprecationDate = Nothing
, _atiDescription = Nothing
, _atiActivityType = pActivityType_
, _atiStatus = pStatus_
, _atiCreationDate = _Time # pCreationDate_
}
-- | If DEPRECATED, the date and time DeprecateActivityType was called.
atiDeprecationDate :: Lens' ActivityTypeInfo (Maybe UTCTime)
atiDeprecationDate = lens _atiDeprecationDate (\ s a -> s{_atiDeprecationDate = a}) . mapping _Time;
-- | The description of the activity type provided in RegisterActivityType.
atiDescription :: Lens' ActivityTypeInfo (Maybe Text)
atiDescription = lens _atiDescription (\ s a -> s{_atiDescription = a});
-- | The ActivityType type structure representing the activity type.
atiActivityType :: Lens' ActivityTypeInfo ActivityType
atiActivityType = lens _atiActivityType (\ s a -> s{_atiActivityType = a});
-- | The current status of the activity type.
atiStatus :: Lens' ActivityTypeInfo RegistrationStatus
atiStatus = lens _atiStatus (\ s a -> s{_atiStatus = a});
-- | The date and time this activity type was created through
-- RegisterActivityType.
atiCreationDate :: Lens' ActivityTypeInfo UTCTime
atiCreationDate = lens _atiCreationDate (\ s a -> s{_atiCreationDate = a}) . _Time;
instance FromJSON ActivityTypeInfo where
parseJSON
= withObject "ActivityTypeInfo"
(\ x ->
ActivityTypeInfo' <$>
(x .:? "deprecationDate") <*> (x .:? "description")
<*> (x .: "activityType")
<*> (x .: "status")
<*> (x .: "creationDate"))
-- | Provides details of the 'CancelTimer' decision.
--
-- __Access Control__
--
-- You can use IAM policies to control this decision\'s access to Amazon
-- SWF resources as follows:
--
-- - Use a 'Resource' element with the domain name to limit the action to
-- only specified domains.
-- - Use an 'Action' element to allow or deny permission to call this
-- action.
-- - You cannot use an IAM policy to constrain this action\'s parameters.
--
-- If the caller does not have sufficient permissions to invoke the action,
-- or the parameter values fall outside the specified constraints, the
-- action fails. The associated event attribute\'s __cause__ parameter will
-- be set to OPERATION_NOT_PERMITTED. For details and example IAM policies,
-- see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- /See:/ 'cancelTimerDecisionAttributes' smart constructor.
newtype CancelTimerDecisionAttributes = CancelTimerDecisionAttributes'
{ _ctdaTimerId :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CancelTimerDecisionAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ctdaTimerId'
cancelTimerDecisionAttributes
:: Text -- ^ 'ctdaTimerId'
-> CancelTimerDecisionAttributes
cancelTimerDecisionAttributes pTimerId_ =
CancelTimerDecisionAttributes'
{ _ctdaTimerId = pTimerId_
}
-- | __Required.__ The unique ID of the timer to cancel.
ctdaTimerId :: Lens' CancelTimerDecisionAttributes Text
ctdaTimerId = lens _ctdaTimerId (\ s a -> s{_ctdaTimerId = a});
instance ToJSON CancelTimerDecisionAttributes where
toJSON CancelTimerDecisionAttributes'{..}
= object
(catMaybes [Just ("timerId" .= _ctdaTimerId)])
-- | Provides details of the 'CancelTimerFailed' event.
--
-- /See:/ 'cancelTimerFailedEventAttributes' smart constructor.
data CancelTimerFailedEventAttributes = CancelTimerFailedEventAttributes'
{ _ctfeaTimerId :: !Text
, _ctfeaCause :: !CancelTimerFailedCause
, _ctfeaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CancelTimerFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ctfeaTimerId'
--
-- * 'ctfeaCause'
--
-- * 'ctfeaDecisionTaskCompletedEventId'
cancelTimerFailedEventAttributes
:: Text -- ^ 'ctfeaTimerId'
-> CancelTimerFailedCause -- ^ 'ctfeaCause'
-> Integer -- ^ 'ctfeaDecisionTaskCompletedEventId'
-> CancelTimerFailedEventAttributes
cancelTimerFailedEventAttributes pTimerId_ pCause_ pDecisionTaskCompletedEventId_ =
CancelTimerFailedEventAttributes'
{ _ctfeaTimerId = pTimerId_
, _ctfeaCause = pCause_
, _ctfeaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | The timerId provided in the 'CancelTimer' decision that failed.
ctfeaTimerId :: Lens' CancelTimerFailedEventAttributes Text
ctfeaTimerId = lens _ctfeaTimerId (\ s a -> s{_ctfeaTimerId = a});
-- | The cause of the failure. This information is generated by the system
-- and can be useful for diagnostic purposes.
--
-- If __cause__ is set to OPERATION_NOT_PERMITTED, the decision failed
-- because it lacked sufficient permissions. For details and example IAM
-- policies, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
ctfeaCause :: Lens' CancelTimerFailedEventAttributes CancelTimerFailedCause
ctfeaCause = lens _ctfeaCause (\ s a -> s{_ctfeaCause = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'CancelTimer' decision to cancel this
-- timer. This information can be useful for diagnosing problems by tracing
-- back the chain of events leading up to this event.
ctfeaDecisionTaskCompletedEventId :: Lens' CancelTimerFailedEventAttributes Integer
ctfeaDecisionTaskCompletedEventId = lens _ctfeaDecisionTaskCompletedEventId (\ s a -> s{_ctfeaDecisionTaskCompletedEventId = a});
instance FromJSON CancelTimerFailedEventAttributes
where
parseJSON
= withObject "CancelTimerFailedEventAttributes"
(\ x ->
CancelTimerFailedEventAttributes' <$>
(x .: "timerId") <*> (x .: "cause") <*>
(x .: "decisionTaskCompletedEventId"))
-- | Provides details of the 'CancelWorkflowExecution' decision.
--
-- __Access Control__
--
-- You can use IAM policies to control this decision\'s access to Amazon
-- SWF resources as follows:
--
-- - Use a 'Resource' element with the domain name to limit the action to
-- only specified domains.
-- - Use an 'Action' element to allow or deny permission to call this
-- action.
-- - You cannot use an IAM policy to constrain this action\'s parameters.
--
-- If the caller does not have sufficient permissions to invoke the action,
-- or the parameter values fall outside the specified constraints, the
-- action fails. The associated event attribute\'s __cause__ parameter will
-- be set to OPERATION_NOT_PERMITTED. For details and example IAM policies,
-- see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- /See:/ 'cancelWorkflowExecutionDecisionAttributes' smart constructor.
newtype CancelWorkflowExecutionDecisionAttributes = CancelWorkflowExecutionDecisionAttributes'
{ _cwedaDetails :: Maybe Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CancelWorkflowExecutionDecisionAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cwedaDetails'
cancelWorkflowExecutionDecisionAttributes
:: CancelWorkflowExecutionDecisionAttributes
cancelWorkflowExecutionDecisionAttributes =
CancelWorkflowExecutionDecisionAttributes'
{ _cwedaDetails = Nothing
}
-- | /Optional./ details of the cancellation.
cwedaDetails :: Lens' CancelWorkflowExecutionDecisionAttributes (Maybe Text)
cwedaDetails = lens _cwedaDetails (\ s a -> s{_cwedaDetails = a});
instance ToJSON
CancelWorkflowExecutionDecisionAttributes where
toJSON CancelWorkflowExecutionDecisionAttributes'{..}
= object
(catMaybes [("details" .=) <$> _cwedaDetails])
-- | Provides details of the 'CancelWorkflowExecutionFailed' event.
--
-- /See:/ 'cancelWorkflowExecutionFailedEventAttributes' smart constructor.
data CancelWorkflowExecutionFailedEventAttributes = CancelWorkflowExecutionFailedEventAttributes'
{ _cCause :: !CancelWorkflowExecutionFailedCause
, _cDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CancelWorkflowExecutionFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cCause'
--
-- * 'cDecisionTaskCompletedEventId'
cancelWorkflowExecutionFailedEventAttributes
:: CancelWorkflowExecutionFailedCause -- ^ 'cCause'
-> Integer -- ^ 'cDecisionTaskCompletedEventId'
-> CancelWorkflowExecutionFailedEventAttributes
cancelWorkflowExecutionFailedEventAttributes pCause_ pDecisionTaskCompletedEventId_ =
CancelWorkflowExecutionFailedEventAttributes'
{ _cCause = pCause_
, _cDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | The cause of the failure. This information is generated by the system
-- and can be useful for diagnostic purposes.
--
-- If __cause__ is set to OPERATION_NOT_PERMITTED, the decision failed
-- because it lacked sufficient permissions. For details and example IAM
-- policies, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
cCause :: Lens' CancelWorkflowExecutionFailedEventAttributes CancelWorkflowExecutionFailedCause
cCause = lens _cCause (\ s a -> s{_cCause = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'CancelWorkflowExecution' decision
-- for this cancellation request. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
cDecisionTaskCompletedEventId :: Lens' CancelWorkflowExecutionFailedEventAttributes Integer
cDecisionTaskCompletedEventId = lens _cDecisionTaskCompletedEventId (\ s a -> s{_cDecisionTaskCompletedEventId = a});
instance FromJSON
CancelWorkflowExecutionFailedEventAttributes where
parseJSON
= withObject
"CancelWorkflowExecutionFailedEventAttributes"
(\ x ->
CancelWorkflowExecutionFailedEventAttributes' <$>
(x .: "cause") <*>
(x .: "decisionTaskCompletedEventId"))
-- | Provide details of the 'ChildWorkflowExecutionCanceled' event.
--
-- /See:/ 'childWorkflowExecutionCanceledEventAttributes' smart constructor.
data ChildWorkflowExecutionCanceledEventAttributes = ChildWorkflowExecutionCanceledEventAttributes'
{ _cDetails :: !(Maybe Text)
, _cWorkflowExecution :: !WorkflowExecution
, _cWorkflowType :: !WorkflowType
, _cInitiatedEventId :: !Integer
, _cStartedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ChildWorkflowExecutionCanceledEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cDetails'
--
-- * 'cWorkflowExecution'
--
-- * 'cWorkflowType'
--
-- * 'cInitiatedEventId'
--
-- * 'cStartedEventId'
childWorkflowExecutionCanceledEventAttributes
:: WorkflowExecution -- ^ 'cWorkflowExecution'
-> WorkflowType -- ^ 'cWorkflowType'
-> Integer -- ^ 'cInitiatedEventId'
-> Integer -- ^ 'cStartedEventId'
-> ChildWorkflowExecutionCanceledEventAttributes
childWorkflowExecutionCanceledEventAttributes pWorkflowExecution_ pWorkflowType_ pInitiatedEventId_ pStartedEventId_ =
ChildWorkflowExecutionCanceledEventAttributes'
{ _cDetails = Nothing
, _cWorkflowExecution = pWorkflowExecution_
, _cWorkflowType = pWorkflowType_
, _cInitiatedEventId = pInitiatedEventId_
, _cStartedEventId = pStartedEventId_
}
-- | Details of the cancellation (if provided).
cDetails :: Lens' ChildWorkflowExecutionCanceledEventAttributes (Maybe Text)
cDetails = lens _cDetails (\ s a -> s{_cDetails = a});
-- | The child workflow execution that was canceled.
cWorkflowExecution :: Lens' ChildWorkflowExecutionCanceledEventAttributes WorkflowExecution
cWorkflowExecution = lens _cWorkflowExecution (\ s a -> s{_cWorkflowExecution = a});
-- | The type of the child workflow execution.
cWorkflowType :: Lens' ChildWorkflowExecutionCanceledEventAttributes WorkflowType
cWorkflowType = lens _cWorkflowType (\ s a -> s{_cWorkflowType = a});
-- | The ID of the 'StartChildWorkflowExecutionInitiated' event corresponding
-- to the 'StartChildWorkflowExecution' decision to start this child
-- workflow execution. This information can be useful for diagnosing
-- problems by tracing back the chain of events leading up to this event.
cInitiatedEventId :: Lens' ChildWorkflowExecutionCanceledEventAttributes Integer
cInitiatedEventId = lens _cInitiatedEventId (\ s a -> s{_cInitiatedEventId = a});
-- | The ID of the 'ChildWorkflowExecutionStarted' event recorded when this
-- child workflow execution was started. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
cStartedEventId :: Lens' ChildWorkflowExecutionCanceledEventAttributes Integer
cStartedEventId = lens _cStartedEventId (\ s a -> s{_cStartedEventId = a});
instance FromJSON
ChildWorkflowExecutionCanceledEventAttributes where
parseJSON
= withObject
"ChildWorkflowExecutionCanceledEventAttributes"
(\ x ->
ChildWorkflowExecutionCanceledEventAttributes' <$>
(x .:? "details") <*> (x .: "workflowExecution") <*>
(x .: "workflowType")
<*> (x .: "initiatedEventId")
<*> (x .: "startedEventId"))
-- | Provides details of the 'ChildWorkflowExecutionCompleted' event.
--
-- /See:/ 'childWorkflowExecutionCompletedEventAttributes' smart constructor.
data ChildWorkflowExecutionCompletedEventAttributes = ChildWorkflowExecutionCompletedEventAttributes'
{ _cweceaResult :: !(Maybe Text)
, _cweceaWorkflowExecution :: !WorkflowExecution
, _cweceaWorkflowType :: !WorkflowType
, _cweceaInitiatedEventId :: !Integer
, _cweceaStartedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ChildWorkflowExecutionCompletedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cweceaResult'
--
-- * 'cweceaWorkflowExecution'
--
-- * 'cweceaWorkflowType'
--
-- * 'cweceaInitiatedEventId'
--
-- * 'cweceaStartedEventId'
childWorkflowExecutionCompletedEventAttributes
:: WorkflowExecution -- ^ 'cweceaWorkflowExecution'
-> WorkflowType -- ^ 'cweceaWorkflowType'
-> Integer -- ^ 'cweceaInitiatedEventId'
-> Integer -- ^ 'cweceaStartedEventId'
-> ChildWorkflowExecutionCompletedEventAttributes
childWorkflowExecutionCompletedEventAttributes pWorkflowExecution_ pWorkflowType_ pInitiatedEventId_ pStartedEventId_ =
ChildWorkflowExecutionCompletedEventAttributes'
{ _cweceaResult = Nothing
, _cweceaWorkflowExecution = pWorkflowExecution_
, _cweceaWorkflowType = pWorkflowType_
, _cweceaInitiatedEventId = pInitiatedEventId_
, _cweceaStartedEventId = pStartedEventId_
}
-- | The result of the child workflow execution (if any).
cweceaResult :: Lens' ChildWorkflowExecutionCompletedEventAttributes (Maybe Text)
cweceaResult = lens _cweceaResult (\ s a -> s{_cweceaResult = a});
-- | The child workflow execution that was completed.
cweceaWorkflowExecution :: Lens' ChildWorkflowExecutionCompletedEventAttributes WorkflowExecution
cweceaWorkflowExecution = lens _cweceaWorkflowExecution (\ s a -> s{_cweceaWorkflowExecution = a});
-- | The type of the child workflow execution.
cweceaWorkflowType :: Lens' ChildWorkflowExecutionCompletedEventAttributes WorkflowType
cweceaWorkflowType = lens _cweceaWorkflowType (\ s a -> s{_cweceaWorkflowType = a});
-- | The ID of the 'StartChildWorkflowExecutionInitiated' event corresponding
-- to the 'StartChildWorkflowExecution' decision to start this child
-- workflow execution. This information can be useful for diagnosing
-- problems by tracing back the chain of events leading up to this event.
cweceaInitiatedEventId :: Lens' ChildWorkflowExecutionCompletedEventAttributes Integer
cweceaInitiatedEventId = lens _cweceaInitiatedEventId (\ s a -> s{_cweceaInitiatedEventId = a});
-- | The ID of the 'ChildWorkflowExecutionStarted' event recorded when this
-- child workflow execution was started. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
cweceaStartedEventId :: Lens' ChildWorkflowExecutionCompletedEventAttributes Integer
cweceaStartedEventId = lens _cweceaStartedEventId (\ s a -> s{_cweceaStartedEventId = a});
instance FromJSON
ChildWorkflowExecutionCompletedEventAttributes where
parseJSON
= withObject
"ChildWorkflowExecutionCompletedEventAttributes"
(\ x ->
ChildWorkflowExecutionCompletedEventAttributes' <$>
(x .:? "result") <*> (x .: "workflowExecution") <*>
(x .: "workflowType")
<*> (x .: "initiatedEventId")
<*> (x .: "startedEventId"))
-- | Provides details of the 'ChildWorkflowExecutionFailed' event.
--
-- /See:/ 'childWorkflowExecutionFailedEventAttributes' smart constructor.
data ChildWorkflowExecutionFailedEventAttributes = ChildWorkflowExecutionFailedEventAttributes'
{ _cwefeaReason :: !(Maybe Text)
, _cwefeaDetails :: !(Maybe Text)
, _cwefeaWorkflowExecution :: !WorkflowExecution
, _cwefeaWorkflowType :: !WorkflowType
, _cwefeaInitiatedEventId :: !Integer
, _cwefeaStartedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ChildWorkflowExecutionFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cwefeaReason'
--
-- * 'cwefeaDetails'
--
-- * 'cwefeaWorkflowExecution'
--
-- * 'cwefeaWorkflowType'
--
-- * 'cwefeaInitiatedEventId'
--
-- * 'cwefeaStartedEventId'
childWorkflowExecutionFailedEventAttributes
:: WorkflowExecution -- ^ 'cwefeaWorkflowExecution'
-> WorkflowType -- ^ 'cwefeaWorkflowType'
-> Integer -- ^ 'cwefeaInitiatedEventId'
-> Integer -- ^ 'cwefeaStartedEventId'
-> ChildWorkflowExecutionFailedEventAttributes
childWorkflowExecutionFailedEventAttributes pWorkflowExecution_ pWorkflowType_ pInitiatedEventId_ pStartedEventId_ =
ChildWorkflowExecutionFailedEventAttributes'
{ _cwefeaReason = Nothing
, _cwefeaDetails = Nothing
, _cwefeaWorkflowExecution = pWorkflowExecution_
, _cwefeaWorkflowType = pWorkflowType_
, _cwefeaInitiatedEventId = pInitiatedEventId_
, _cwefeaStartedEventId = pStartedEventId_
}
-- | The reason for the failure (if provided).
cwefeaReason :: Lens' ChildWorkflowExecutionFailedEventAttributes (Maybe Text)
cwefeaReason = lens _cwefeaReason (\ s a -> s{_cwefeaReason = a});
-- | The details of the failure (if provided).
cwefeaDetails :: Lens' ChildWorkflowExecutionFailedEventAttributes (Maybe Text)
cwefeaDetails = lens _cwefeaDetails (\ s a -> s{_cwefeaDetails = a});
-- | The child workflow execution that failed.
cwefeaWorkflowExecution :: Lens' ChildWorkflowExecutionFailedEventAttributes WorkflowExecution
cwefeaWorkflowExecution = lens _cwefeaWorkflowExecution (\ s a -> s{_cwefeaWorkflowExecution = a});
-- | The type of the child workflow execution.
cwefeaWorkflowType :: Lens' ChildWorkflowExecutionFailedEventAttributes WorkflowType
cwefeaWorkflowType = lens _cwefeaWorkflowType (\ s a -> s{_cwefeaWorkflowType = a});
-- | The ID of the 'StartChildWorkflowExecutionInitiated' event corresponding
-- to the 'StartChildWorkflowExecution' decision to start this child
-- workflow execution. This information can be useful for diagnosing
-- problems by tracing back the chain of events leading up to this event.
cwefeaInitiatedEventId :: Lens' ChildWorkflowExecutionFailedEventAttributes Integer
cwefeaInitiatedEventId = lens _cwefeaInitiatedEventId (\ s a -> s{_cwefeaInitiatedEventId = a});
-- | The ID of the 'ChildWorkflowExecutionStarted' event recorded when this
-- child workflow execution was started. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
cwefeaStartedEventId :: Lens' ChildWorkflowExecutionFailedEventAttributes Integer
cwefeaStartedEventId = lens _cwefeaStartedEventId (\ s a -> s{_cwefeaStartedEventId = a});
instance FromJSON
ChildWorkflowExecutionFailedEventAttributes where
parseJSON
= withObject
"ChildWorkflowExecutionFailedEventAttributes"
(\ x ->
ChildWorkflowExecutionFailedEventAttributes' <$>
(x .:? "reason") <*> (x .:? "details") <*>
(x .: "workflowExecution")
<*> (x .: "workflowType")
<*> (x .: "initiatedEventId")
<*> (x .: "startedEventId"))
-- | Provides details of the 'ChildWorkflowExecutionStarted' event.
--
-- /See:/ 'childWorkflowExecutionStartedEventAttributes' smart constructor.
data ChildWorkflowExecutionStartedEventAttributes = ChildWorkflowExecutionStartedEventAttributes'
{ _cweseaWorkflowExecution :: !WorkflowExecution
, _cweseaWorkflowType :: !WorkflowType
, _cweseaInitiatedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ChildWorkflowExecutionStartedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cweseaWorkflowExecution'
--
-- * 'cweseaWorkflowType'
--
-- * 'cweseaInitiatedEventId'
childWorkflowExecutionStartedEventAttributes
:: WorkflowExecution -- ^ 'cweseaWorkflowExecution'
-> WorkflowType -- ^ 'cweseaWorkflowType'
-> Integer -- ^ 'cweseaInitiatedEventId'
-> ChildWorkflowExecutionStartedEventAttributes
childWorkflowExecutionStartedEventAttributes pWorkflowExecution_ pWorkflowType_ pInitiatedEventId_ =
ChildWorkflowExecutionStartedEventAttributes'
{ _cweseaWorkflowExecution = pWorkflowExecution_
, _cweseaWorkflowType = pWorkflowType_
, _cweseaInitiatedEventId = pInitiatedEventId_
}
-- | The child workflow execution that was started.
cweseaWorkflowExecution :: Lens' ChildWorkflowExecutionStartedEventAttributes WorkflowExecution
cweseaWorkflowExecution = lens _cweseaWorkflowExecution (\ s a -> s{_cweseaWorkflowExecution = a});
-- | The type of the child workflow execution.
cweseaWorkflowType :: Lens' ChildWorkflowExecutionStartedEventAttributes WorkflowType
cweseaWorkflowType = lens _cweseaWorkflowType (\ s a -> s{_cweseaWorkflowType = a});
-- | The ID of the 'StartChildWorkflowExecutionInitiated' event corresponding
-- to the 'StartChildWorkflowExecution' decision to start this child
-- workflow execution. This information can be useful for diagnosing
-- problems by tracing back the chain of events leading up to this event.
cweseaInitiatedEventId :: Lens' ChildWorkflowExecutionStartedEventAttributes Integer
cweseaInitiatedEventId = lens _cweseaInitiatedEventId (\ s a -> s{_cweseaInitiatedEventId = a});
instance FromJSON
ChildWorkflowExecutionStartedEventAttributes where
parseJSON
= withObject
"ChildWorkflowExecutionStartedEventAttributes"
(\ x ->
ChildWorkflowExecutionStartedEventAttributes' <$>
(x .: "workflowExecution") <*> (x .: "workflowType")
<*> (x .: "initiatedEventId"))
-- | Provides details of the 'ChildWorkflowExecutionTerminated' event.
--
-- /See:/ 'childWorkflowExecutionTerminatedEventAttributes' smart constructor.
data ChildWorkflowExecutionTerminatedEventAttributes = ChildWorkflowExecutionTerminatedEventAttributes'
{ _cweteaWorkflowExecution :: !WorkflowExecution
, _cweteaWorkflowType :: !WorkflowType
, _cweteaInitiatedEventId :: !Integer
, _cweteaStartedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ChildWorkflowExecutionTerminatedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cweteaWorkflowExecution'
--
-- * 'cweteaWorkflowType'
--
-- * 'cweteaInitiatedEventId'
--
-- * 'cweteaStartedEventId'
childWorkflowExecutionTerminatedEventAttributes
:: WorkflowExecution -- ^ 'cweteaWorkflowExecution'
-> WorkflowType -- ^ 'cweteaWorkflowType'
-> Integer -- ^ 'cweteaInitiatedEventId'
-> Integer -- ^ 'cweteaStartedEventId'
-> ChildWorkflowExecutionTerminatedEventAttributes
childWorkflowExecutionTerminatedEventAttributes pWorkflowExecution_ pWorkflowType_ pInitiatedEventId_ pStartedEventId_ =
ChildWorkflowExecutionTerminatedEventAttributes'
{ _cweteaWorkflowExecution = pWorkflowExecution_
, _cweteaWorkflowType = pWorkflowType_
, _cweteaInitiatedEventId = pInitiatedEventId_
, _cweteaStartedEventId = pStartedEventId_
}
-- | The child workflow execution that was terminated.
cweteaWorkflowExecution :: Lens' ChildWorkflowExecutionTerminatedEventAttributes WorkflowExecution
cweteaWorkflowExecution = lens _cweteaWorkflowExecution (\ s a -> s{_cweteaWorkflowExecution = a});
-- | The type of the child workflow execution.
cweteaWorkflowType :: Lens' ChildWorkflowExecutionTerminatedEventAttributes WorkflowType
cweteaWorkflowType = lens _cweteaWorkflowType (\ s a -> s{_cweteaWorkflowType = a});
-- | The ID of the 'StartChildWorkflowExecutionInitiated' event corresponding
-- to the 'StartChildWorkflowExecution' decision to start this child
-- workflow execution. This information can be useful for diagnosing
-- problems by tracing back the chain of events leading up to this event.
cweteaInitiatedEventId :: Lens' ChildWorkflowExecutionTerminatedEventAttributes Integer
cweteaInitiatedEventId = lens _cweteaInitiatedEventId (\ s a -> s{_cweteaInitiatedEventId = a});
-- | The ID of the 'ChildWorkflowExecutionStarted' event recorded when this
-- child workflow execution was started. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
cweteaStartedEventId :: Lens' ChildWorkflowExecutionTerminatedEventAttributes Integer
cweteaStartedEventId = lens _cweteaStartedEventId (\ s a -> s{_cweteaStartedEventId = a});
instance FromJSON
ChildWorkflowExecutionTerminatedEventAttributes where
parseJSON
= withObject
"ChildWorkflowExecutionTerminatedEventAttributes"
(\ x ->
ChildWorkflowExecutionTerminatedEventAttributes' <$>
(x .: "workflowExecution") <*> (x .: "workflowType")
<*> (x .: "initiatedEventId")
<*> (x .: "startedEventId"))
-- | Provides details of the 'ChildWorkflowExecutionTimedOut' event.
--
-- /See:/ 'childWorkflowExecutionTimedOutEventAttributes' smart constructor.
data ChildWorkflowExecutionTimedOutEventAttributes = ChildWorkflowExecutionTimedOutEventAttributes'
{ _cwetoeaWorkflowExecution :: !WorkflowExecution
, _cwetoeaWorkflowType :: !WorkflowType
, _cwetoeaTimeoutType :: !WorkflowExecutionTimeoutType
, _cwetoeaInitiatedEventId :: !Integer
, _cwetoeaStartedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ChildWorkflowExecutionTimedOutEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cwetoeaWorkflowExecution'
--
-- * 'cwetoeaWorkflowType'
--
-- * 'cwetoeaTimeoutType'
--
-- * 'cwetoeaInitiatedEventId'
--
-- * 'cwetoeaStartedEventId'
childWorkflowExecutionTimedOutEventAttributes
:: WorkflowExecution -- ^ 'cwetoeaWorkflowExecution'
-> WorkflowType -- ^ 'cwetoeaWorkflowType'
-> WorkflowExecutionTimeoutType -- ^ 'cwetoeaTimeoutType'
-> Integer -- ^ 'cwetoeaInitiatedEventId'
-> Integer -- ^ 'cwetoeaStartedEventId'
-> ChildWorkflowExecutionTimedOutEventAttributes
childWorkflowExecutionTimedOutEventAttributes pWorkflowExecution_ pWorkflowType_ pTimeoutType_ pInitiatedEventId_ pStartedEventId_ =
ChildWorkflowExecutionTimedOutEventAttributes'
{ _cwetoeaWorkflowExecution = pWorkflowExecution_
, _cwetoeaWorkflowType = pWorkflowType_
, _cwetoeaTimeoutType = pTimeoutType_
, _cwetoeaInitiatedEventId = pInitiatedEventId_
, _cwetoeaStartedEventId = pStartedEventId_
}
-- | The child workflow execution that timed out.
cwetoeaWorkflowExecution :: Lens' ChildWorkflowExecutionTimedOutEventAttributes WorkflowExecution
cwetoeaWorkflowExecution = lens _cwetoeaWorkflowExecution (\ s a -> s{_cwetoeaWorkflowExecution = a});
-- | The type of the child workflow execution.
cwetoeaWorkflowType :: Lens' ChildWorkflowExecutionTimedOutEventAttributes WorkflowType
cwetoeaWorkflowType = lens _cwetoeaWorkflowType (\ s a -> s{_cwetoeaWorkflowType = a});
-- | The type of the timeout that caused the child workflow execution to time
-- out.
cwetoeaTimeoutType :: Lens' ChildWorkflowExecutionTimedOutEventAttributes WorkflowExecutionTimeoutType
cwetoeaTimeoutType = lens _cwetoeaTimeoutType (\ s a -> s{_cwetoeaTimeoutType = a});
-- | The ID of the 'StartChildWorkflowExecutionInitiated' event corresponding
-- to the 'StartChildWorkflowExecution' decision to start this child
-- workflow execution. This information can be useful for diagnosing
-- problems by tracing back the chain of events leading up to this event.
cwetoeaInitiatedEventId :: Lens' ChildWorkflowExecutionTimedOutEventAttributes Integer
cwetoeaInitiatedEventId = lens _cwetoeaInitiatedEventId (\ s a -> s{_cwetoeaInitiatedEventId = a});
-- | The ID of the 'ChildWorkflowExecutionStarted' event recorded when this
-- child workflow execution was started. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
cwetoeaStartedEventId :: Lens' ChildWorkflowExecutionTimedOutEventAttributes Integer
cwetoeaStartedEventId = lens _cwetoeaStartedEventId (\ s a -> s{_cwetoeaStartedEventId = a});
instance FromJSON
ChildWorkflowExecutionTimedOutEventAttributes where
parseJSON
= withObject
"ChildWorkflowExecutionTimedOutEventAttributes"
(\ x ->
ChildWorkflowExecutionTimedOutEventAttributes' <$>
(x .: "workflowExecution") <*> (x .: "workflowType")
<*> (x .: "timeoutType")
<*> (x .: "initiatedEventId")
<*> (x .: "startedEventId"))
-- | Used to filter the closed workflow executions in visibility APIs by
-- their close status.
--
-- /See:/ 'closeStatusFilter' smart constructor.
newtype CloseStatusFilter = CloseStatusFilter'
{ _csfStatus :: CloseStatus
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CloseStatusFilter' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csfStatus'
closeStatusFilter
:: CloseStatus -- ^ 'csfStatus'
-> CloseStatusFilter
closeStatusFilter pStatus_ =
CloseStatusFilter'
{ _csfStatus = pStatus_
}
-- | __Required.__ The close status that must match the close status of an
-- execution for it to meet the criteria of this filter.
csfStatus :: Lens' CloseStatusFilter CloseStatus
csfStatus = lens _csfStatus (\ s a -> s{_csfStatus = a});
instance ToJSON CloseStatusFilter where
toJSON CloseStatusFilter'{..}
= object (catMaybes [Just ("status" .= _csfStatus)])
-- | Provides details of the 'CompleteWorkflowExecution' decision.
--
-- __Access Control__
--
-- You can use IAM policies to control this decision\'s access to Amazon
-- SWF resources as follows:
--
-- - Use a 'Resource' element with the domain name to limit the action to
-- only specified domains.
-- - Use an 'Action' element to allow or deny permission to call this
-- action.
-- - You cannot use an IAM policy to constrain this action\'s parameters.
--
-- If the caller does not have sufficient permissions to invoke the action,
-- or the parameter values fall outside the specified constraints, the
-- action fails. The associated event attribute\'s __cause__ parameter will
-- be set to OPERATION_NOT_PERMITTED. For details and example IAM policies,
-- see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- /See:/ 'completeWorkflowExecutionDecisionAttributes' smart constructor.
newtype CompleteWorkflowExecutionDecisionAttributes = CompleteWorkflowExecutionDecisionAttributes'
{ _cwedaResult :: Maybe Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CompleteWorkflowExecutionDecisionAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cwedaResult'
completeWorkflowExecutionDecisionAttributes
:: CompleteWorkflowExecutionDecisionAttributes
completeWorkflowExecutionDecisionAttributes =
CompleteWorkflowExecutionDecisionAttributes'
{ _cwedaResult = Nothing
}
-- | The result of the workflow execution. The form of the result is
-- implementation defined.
cwedaResult :: Lens' CompleteWorkflowExecutionDecisionAttributes (Maybe Text)
cwedaResult = lens _cwedaResult (\ s a -> s{_cwedaResult = a});
instance ToJSON
CompleteWorkflowExecutionDecisionAttributes where
toJSON
CompleteWorkflowExecutionDecisionAttributes'{..}
= object (catMaybes [("result" .=) <$> _cwedaResult])
-- | Provides details of the 'CompleteWorkflowExecutionFailed' event.
--
-- /See:/ 'completeWorkflowExecutionFailedEventAttributes' smart constructor.
data CompleteWorkflowExecutionFailedEventAttributes = CompleteWorkflowExecutionFailedEventAttributes'
{ _cwefeaCause :: !CompleteWorkflowExecutionFailedCause
, _cwefeaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CompleteWorkflowExecutionFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cwefeaCause'
--
-- * 'cwefeaDecisionTaskCompletedEventId'
completeWorkflowExecutionFailedEventAttributes
:: CompleteWorkflowExecutionFailedCause -- ^ 'cwefeaCause'
-> Integer -- ^ 'cwefeaDecisionTaskCompletedEventId'
-> CompleteWorkflowExecutionFailedEventAttributes
completeWorkflowExecutionFailedEventAttributes pCause_ pDecisionTaskCompletedEventId_ =
CompleteWorkflowExecutionFailedEventAttributes'
{ _cwefeaCause = pCause_
, _cwefeaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | The cause of the failure. This information is generated by the system
-- and can be useful for diagnostic purposes.
--
-- If __cause__ is set to OPERATION_NOT_PERMITTED, the decision failed
-- because it lacked sufficient permissions. For details and example IAM
-- policies, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
cwefeaCause :: Lens' CompleteWorkflowExecutionFailedEventAttributes CompleteWorkflowExecutionFailedCause
cwefeaCause = lens _cwefeaCause (\ s a -> s{_cwefeaCause = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'CompleteWorkflowExecution' decision
-- to complete this execution. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
cwefeaDecisionTaskCompletedEventId :: Lens' CompleteWorkflowExecutionFailedEventAttributes Integer
cwefeaDecisionTaskCompletedEventId = lens _cwefeaDecisionTaskCompletedEventId (\ s a -> s{_cwefeaDecisionTaskCompletedEventId = a});
instance FromJSON
CompleteWorkflowExecutionFailedEventAttributes where
parseJSON
= withObject
"CompleteWorkflowExecutionFailedEventAttributes"
(\ x ->
CompleteWorkflowExecutionFailedEventAttributes' <$>
(x .: "cause") <*>
(x .: "decisionTaskCompletedEventId"))
-- | Provides details of the 'ContinueAsNewWorkflowExecution' decision.
--
-- __Access Control__
--
-- You can use IAM policies to control this decision\'s access to Amazon
-- SWF resources as follows:
--
-- - Use a 'Resource' element with the domain name to limit the action to
-- only specified domains.
-- - Use an 'Action' element to allow or deny permission to call this
-- action.
-- - Constrain the following parameters by using a 'Condition' element
-- with the appropriate keys.
-- - 'tag': /Optional./. A tag used to identify the workflow
-- execution
-- - 'taskList': String constraint. The key is 'swf:taskList.name'.
-- - 'workflowType.version': String constraint. The key is
-- 'swf:workflowType.version'.
--
-- If the caller does not have sufficient permissions to invoke the action,
-- or the parameter values fall outside the specified constraints, the
-- action fails. The associated event attribute\'s __cause__ parameter will
-- be set to OPERATION_NOT_PERMITTED. For details and example IAM policies,
-- see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- /See:/ 'continueAsNewWorkflowExecutionDecisionAttributes' smart constructor.
data ContinueAsNewWorkflowExecutionDecisionAttributes = ContinueAsNewWorkflowExecutionDecisionAttributes'
{ _canwedaTagList :: !(Maybe [Text])
, _canwedaTaskStartToCloseTimeout :: !(Maybe Text)
, _canwedaLambdaRole :: !(Maybe Text)
, _canwedaInput :: !(Maybe Text)
, _canwedaWorkflowTypeVersion :: !(Maybe Text)
, _canwedaExecutionStartToCloseTimeout :: !(Maybe Text)
, _canwedaTaskList :: !(Maybe TaskList)
, _canwedaTaskPriority :: !(Maybe Text)
, _canwedaChildPolicy :: !(Maybe ChildPolicy)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ContinueAsNewWorkflowExecutionDecisionAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'canwedaTagList'
--
-- * 'canwedaTaskStartToCloseTimeout'
--
-- * 'canwedaLambdaRole'
--
-- * 'canwedaInput'
--
-- * 'canwedaWorkflowTypeVersion'
--
-- * 'canwedaExecutionStartToCloseTimeout'
--
-- * 'canwedaTaskList'
--
-- * 'canwedaTaskPriority'
--
-- * 'canwedaChildPolicy'
continueAsNewWorkflowExecutionDecisionAttributes
:: ContinueAsNewWorkflowExecutionDecisionAttributes
continueAsNewWorkflowExecutionDecisionAttributes =
ContinueAsNewWorkflowExecutionDecisionAttributes'
{ _canwedaTagList = Nothing
, _canwedaTaskStartToCloseTimeout = Nothing
, _canwedaLambdaRole = Nothing
, _canwedaInput = Nothing
, _canwedaWorkflowTypeVersion = Nothing
, _canwedaExecutionStartToCloseTimeout = Nothing
, _canwedaTaskList = Nothing
, _canwedaTaskPriority = Nothing
, _canwedaChildPolicy = Nothing
}
-- | The list of tags to associate with the new workflow execution. A maximum
-- of 5 tags can be specified. You can list workflow executions with a
-- specific tag by calling ListOpenWorkflowExecutions or
-- ListClosedWorkflowExecutions and specifying a TagFilter.
canwedaTagList :: Lens' ContinueAsNewWorkflowExecutionDecisionAttributes [Text]
canwedaTagList = lens _canwedaTagList (\ s a -> s{_canwedaTagList = a}) . _Default . _Coerce;
-- | Specifies the maximum duration of decision tasks for the new workflow
-- execution. This parameter overrides the 'defaultTaskStartToCloseTimout'
-- specified when registering the workflow type using RegisterWorkflowType.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
--
-- A task start-to-close timeout for the new workflow execution must be
-- specified either as a default for the workflow type or through this
-- parameter. If neither this parameter is set nor a default task
-- start-to-close timeout was specified at registration time then a fault
-- will be returned.
canwedaTaskStartToCloseTimeout :: Lens' ContinueAsNewWorkflowExecutionDecisionAttributes (Maybe Text)
canwedaTaskStartToCloseTimeout = lens _canwedaTaskStartToCloseTimeout (\ s a -> s{_canwedaTaskStartToCloseTimeout = a});
-- | The ARN of an IAM role that authorizes Amazon SWF to invoke AWS Lambda
-- functions.
--
-- In order for this workflow execution to invoke AWS Lambda functions, an
-- appropriate IAM role must be specified either as a default for the
-- workflow type or through this field.
canwedaLambdaRole :: Lens' ContinueAsNewWorkflowExecutionDecisionAttributes (Maybe Text)
canwedaLambdaRole = lens _canwedaLambdaRole (\ s a -> s{_canwedaLambdaRole = a});
-- | The input provided to the new workflow execution.
canwedaInput :: Lens' ContinueAsNewWorkflowExecutionDecisionAttributes (Maybe Text)
canwedaInput = lens _canwedaInput (\ s a -> s{_canwedaInput = a});
-- | Undocumented member.
canwedaWorkflowTypeVersion :: Lens' ContinueAsNewWorkflowExecutionDecisionAttributes (Maybe Text)
canwedaWorkflowTypeVersion = lens _canwedaWorkflowTypeVersion (\ s a -> s{_canwedaWorkflowTypeVersion = a});
-- | If set, specifies the total duration for this workflow execution. This
-- overrides the 'defaultExecutionStartToCloseTimeout' specified when
-- registering the workflow type.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
--
-- An execution start-to-close timeout for this workflow execution must be
-- specified either as a default for the workflow type or through this
-- field. If neither this field is set nor a default execution
-- start-to-close timeout was specified at registration time then a fault
-- will be returned.
canwedaExecutionStartToCloseTimeout :: Lens' ContinueAsNewWorkflowExecutionDecisionAttributes (Maybe Text)
canwedaExecutionStartToCloseTimeout = lens _canwedaExecutionStartToCloseTimeout (\ s a -> s{_canwedaExecutionStartToCloseTimeout = a});
-- | Undocumented member.
canwedaTaskList :: Lens' ContinueAsNewWorkflowExecutionDecisionAttributes (Maybe TaskList)
canwedaTaskList = lens _canwedaTaskList (\ s a -> s{_canwedaTaskList = a});
-- | /Optional./ The task priority that, if set, specifies the priority for
-- the decision tasks for this workflow execution. This overrides the
-- defaultTaskPriority specified when registering the workflow type. Valid
-- values are integers that range from Java\'s 'Integer.MIN_VALUE'
-- (-2147483648) to 'Integer.MAX_VALUE' (2147483647). Higher numbers
-- indicate higher priority.
--
-- For more information about setting task priority, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/programming-priority.html Setting Task Priority>
-- in the /Amazon Simple Workflow Developer Guide/.
canwedaTaskPriority :: Lens' ContinueAsNewWorkflowExecutionDecisionAttributes (Maybe Text)
canwedaTaskPriority = lens _canwedaTaskPriority (\ s a -> s{_canwedaTaskPriority = a});
-- | If set, specifies the policy to use for the child workflow executions of
-- the new execution if it is terminated by calling the
-- TerminateWorkflowExecution action explicitly or due to an expired
-- timeout. This policy overrides the default child policy specified when
-- registering the workflow type using RegisterWorkflowType.
--
-- The supported child policies are:
--
-- - __TERMINATE:__ the child executions will be terminated.
-- - __REQUEST_CANCEL:__ a request to cancel will be attempted for each
-- child execution by recording a 'WorkflowExecutionCancelRequested'
-- event in its history. It is up to the decider to take appropriate
-- actions when it receives an execution history with this event.
-- - __ABANDON:__ no action will be taken. The child executions will
-- continue to run.
--
-- A child policy for this workflow execution must be specified either as a
-- default for the workflow type or through this parameter. If neither this
-- parameter is set nor a default child policy was specified at
-- registration time then a fault will be returned.
canwedaChildPolicy :: Lens' ContinueAsNewWorkflowExecutionDecisionAttributes (Maybe ChildPolicy)
canwedaChildPolicy = lens _canwedaChildPolicy (\ s a -> s{_canwedaChildPolicy = a});
instance ToJSON
ContinueAsNewWorkflowExecutionDecisionAttributes
where
toJSON
ContinueAsNewWorkflowExecutionDecisionAttributes'{..}
= object
(catMaybes
[("tagList" .=) <$> _canwedaTagList,
("taskStartToCloseTimeout" .=) <$>
_canwedaTaskStartToCloseTimeout,
("lambdaRole" .=) <$> _canwedaLambdaRole,
("input" .=) <$> _canwedaInput,
("workflowTypeVersion" .=) <$>
_canwedaWorkflowTypeVersion,
("executionStartToCloseTimeout" .=) <$>
_canwedaExecutionStartToCloseTimeout,
("taskList" .=) <$> _canwedaTaskList,
("taskPriority" .=) <$> _canwedaTaskPriority,
("childPolicy" .=) <$> _canwedaChildPolicy])
-- | Provides details of the 'ContinueAsNewWorkflowExecutionFailed' event.
--
-- /See:/ 'continueAsNewWorkflowExecutionFailedEventAttributes' smart constructor.
data ContinueAsNewWorkflowExecutionFailedEventAttributes = ContinueAsNewWorkflowExecutionFailedEventAttributes'
{ _canwefeaCause :: !ContinueAsNewWorkflowExecutionFailedCause
, _canwefeaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ContinueAsNewWorkflowExecutionFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'canwefeaCause'
--
-- * 'canwefeaDecisionTaskCompletedEventId'
continueAsNewWorkflowExecutionFailedEventAttributes
:: ContinueAsNewWorkflowExecutionFailedCause -- ^ 'canwefeaCause'
-> Integer -- ^ 'canwefeaDecisionTaskCompletedEventId'
-> ContinueAsNewWorkflowExecutionFailedEventAttributes
continueAsNewWorkflowExecutionFailedEventAttributes pCause_ pDecisionTaskCompletedEventId_ =
ContinueAsNewWorkflowExecutionFailedEventAttributes'
{ _canwefeaCause = pCause_
, _canwefeaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | The cause of the failure. This information is generated by the system
-- and can be useful for diagnostic purposes.
--
-- If __cause__ is set to OPERATION_NOT_PERMITTED, the decision failed
-- because it lacked sufficient permissions. For details and example IAM
-- policies, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
canwefeaCause :: Lens' ContinueAsNewWorkflowExecutionFailedEventAttributes ContinueAsNewWorkflowExecutionFailedCause
canwefeaCause = lens _canwefeaCause (\ s a -> s{_canwefeaCause = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'ContinueAsNewWorkflowExecution'
-- decision that started this execution. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
canwefeaDecisionTaskCompletedEventId :: Lens' ContinueAsNewWorkflowExecutionFailedEventAttributes Integer
canwefeaDecisionTaskCompletedEventId = lens _canwefeaDecisionTaskCompletedEventId (\ s a -> s{_canwefeaDecisionTaskCompletedEventId = a});
instance FromJSON
ContinueAsNewWorkflowExecutionFailedEventAttributes
where
parseJSON
= withObject
"ContinueAsNewWorkflowExecutionFailedEventAttributes"
(\ x ->
ContinueAsNewWorkflowExecutionFailedEventAttributes'
<$>
(x .: "cause") <*>
(x .: "decisionTaskCompletedEventId"))
-- | Specifies a decision made by the decider. A decision can be one of these
-- types:
--
-- - __CancelTimer__: cancels a previously started timer and records a
-- 'TimerCanceled' event in the history.
-- - __CancelWorkflowExecution__: closes the workflow execution and
-- records a 'WorkflowExecutionCanceled' event in the history.
-- - __CompleteWorkflowExecution__: closes the workflow execution and
-- records a 'WorkflowExecutionCompleted' event in the history .
-- - __ContinueAsNewWorkflowExecution__: closes the workflow execution
-- and starts a new workflow execution of the same type using the same
-- workflow ID and a unique run ID. A 'WorkflowExecutionContinuedAsNew'
-- event is recorded in the history.
-- - __FailWorkflowExecution__: closes the workflow execution and records
-- a 'WorkflowExecutionFailed' event in the history.
-- - __RecordMarker__: records a 'MarkerRecorded' event in the history.
-- Markers can be used for adding custom information in the history for
-- instance to let deciders know that they do not need to look at the
-- history beyond the marker event.
-- - __RequestCancelActivityTask__: attempts to cancel a previously
-- scheduled activity task. If the activity task was scheduled but has
-- not been assigned to a worker, then it will be canceled. If the
-- activity task was already assigned to a worker, then the worker will
-- be informed that cancellation has been requested in the response to
-- RecordActivityTaskHeartbeat.
-- - __RequestCancelExternalWorkflowExecution__: requests that a request
-- be made to cancel the specified external workflow execution and
-- records a 'RequestCancelExternalWorkflowExecutionInitiated' event in
-- the history.
-- - __ScheduleActivityTask__: schedules an activity task.
-- - __ScheduleLambdaFunction__: schedules a AWS Lambda function.
-- - __SignalExternalWorkflowExecution__: requests a signal to be
-- delivered to the specified external workflow execution and records a
-- 'SignalExternalWorkflowExecutionInitiated' event in the history.
-- - __StartChildWorkflowExecution__: requests that a child workflow
-- execution be started and records a
-- 'StartChildWorkflowExecutionInitiated' event in the history. The
-- child workflow execution is a separate workflow execution with its
-- own history.
-- - __StartTimer__: starts a timer for this workflow execution and
-- records a 'TimerStarted' event in the history. This timer will fire
-- after the specified delay and record a 'TimerFired' event.
--
-- __Access Control__
--
-- If you grant permission to use 'RespondDecisionTaskCompleted', you can
-- use IAM policies to express permissions for the list of decisions
-- returned by this action as if they were members of the API. Treating
-- decisions as a pseudo API maintains a uniform conceptual model and helps
-- keep policies readable. For details and example IAM policies, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- __Decision Failure__
--
-- Decisions can fail for several reasons
--
-- - The ordering of decisions should follow a logical flow. Some
-- decisions might not make sense in the current context of the
-- workflow execution and will therefore fail.
-- - A limit on your account was reached.
-- - The decision lacks sufficient permissions.
--
-- One of the following events might be added to the history to indicate an
-- error. The event attribute\'s __cause__ parameter indicates the cause.
-- If __cause__ is set to OPERATION_NOT_PERMITTED, the decision failed
-- because it lacked sufficient permissions. For details and example IAM
-- policies, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- - __ScheduleActivityTaskFailed__: a ScheduleActivityTask decision
-- failed. This could happen if the activity type specified in the
-- decision is not registered, is in a deprecated state, or the
-- decision is not properly configured.
-- - __ScheduleLambdaFunctionFailed__: a ScheduleLambdaFunctionFailed
-- decision failed. This could happen if the AWS Lambda function
-- specified in the decision does not exist, or the AWS Lambda
-- service\'s limits are exceeded.
-- - __RequestCancelActivityTaskFailed__: a RequestCancelActivityTask
-- decision failed. This could happen if there is no open activity task
-- with the specified activityId.
-- - __StartTimerFailed__: a StartTimer decision failed. This could
-- happen if there is another open timer with the same timerId.
-- - __CancelTimerFailed__: a CancelTimer decision failed. This could
-- happen if there is no open timer with the specified timerId.
-- - __StartChildWorkflowExecutionFailed__: a StartChildWorkflowExecution
-- decision failed. This could happen if the workflow type specified is
-- not registered, is deprecated, or the decision is not properly
-- configured.
-- - __SignalExternalWorkflowExecutionFailed__: a
-- SignalExternalWorkflowExecution decision failed. This could happen
-- if the 'workflowID' specified in the decision was incorrect.
-- - __RequestCancelExternalWorkflowExecutionFailed__: a
-- RequestCancelExternalWorkflowExecution decision failed. This could
-- happen if the 'workflowID' specified in the decision was incorrect.
-- - __CancelWorkflowExecutionFailed__: a CancelWorkflowExecution
-- decision failed. This could happen if there is an unhandled decision
-- task pending in the workflow execution.
-- - __CompleteWorkflowExecutionFailed__: a CompleteWorkflowExecution
-- decision failed. This could happen if there is an unhandled decision
-- task pending in the workflow execution.
-- - __ContinueAsNewWorkflowExecutionFailed__: a
-- ContinueAsNewWorkflowExecution decision failed. This could happen if
-- there is an unhandled decision task pending in the workflow
-- execution or the ContinueAsNewWorkflowExecution decision was not
-- configured correctly.
-- - __FailWorkflowExecutionFailed__: a FailWorkflowExecution decision
-- failed. This could happen if there is an unhandled decision task
-- pending in the workflow execution.
--
-- The preceding error events might occur due to an error in the decider
-- logic, which might put the workflow execution in an unstable state The
-- cause field in the event structure for the error event indicates the
-- cause of the error.
--
-- A workflow execution may be closed by the decider by returning one of
-- the following decisions when completing a decision task:
-- 'CompleteWorkflowExecution', 'FailWorkflowExecution',
-- 'CancelWorkflowExecution' and 'ContinueAsNewWorkflowExecution'. An
-- UnhandledDecision fault will be returned if a workflow closing decision
-- is specified and a signal or activity event had been added to the
-- history while the decision task was being performed by the decider.
-- Unlike the above situations which are logic issues, this fault is always
-- possible because of race conditions in a distributed system. The right
-- action here is to call RespondDecisionTaskCompleted without any
-- decisions. This would result in another decision task with these new
-- events included in the history. The decider should handle the new events
-- and may decide to close the workflow execution.
--
-- __How to code a decision__
--
-- You code a decision by first setting the decision type field to one of
-- the above decision values, and then set the corresponding attributes
-- field shown below:
--
-- - ScheduleActivityTaskDecisionAttributes
-- - ScheduleLambdaFunctionDecisionAttributes
-- - RequestCancelActivityTaskDecisionAttributes
-- - CompleteWorkflowExecutionDecisionAttributes
-- - FailWorkflowExecutionDecisionAttributes
-- - CancelWorkflowExecutionDecisionAttributes
-- - ContinueAsNewWorkflowExecutionDecisionAttributes
-- - RecordMarkerDecisionAttributes
-- - StartTimerDecisionAttributes
-- - CancelTimerDecisionAttributes
-- - SignalExternalWorkflowExecutionDecisionAttributes
-- - RequestCancelExternalWorkflowExecutionDecisionAttributes
-- - StartChildWorkflowExecutionDecisionAttributes
--
-- /See:/ 'decision' smart constructor.
data Decision = Decision'
{ _dRequestCancelExternalWorkflowExecutionDecisionAttributes :: !(Maybe RequestCancelExternalWorkflowExecutionDecisionAttributes)
, _dScheduleActivityTaskDecisionAttributes :: !(Maybe ScheduleActivityTaskDecisionAttributes)
, _dSignalExternalWorkflowExecutionDecisionAttributes :: !(Maybe SignalExternalWorkflowExecutionDecisionAttributes)
, _dStartTimerDecisionAttributes :: !(Maybe StartTimerDecisionAttributes)
, _dRecordMarkerDecisionAttributes :: !(Maybe RecordMarkerDecisionAttributes)
, _dFailWorkflowExecutionDecisionAttributes :: !(Maybe FailWorkflowExecutionDecisionAttributes)
, _dStartChildWorkflowExecutionDecisionAttributes :: !(Maybe StartChildWorkflowExecutionDecisionAttributes)
, _dCompleteWorkflowExecutionDecisionAttributes :: !(Maybe CompleteWorkflowExecutionDecisionAttributes)
, _dScheduleLambdaFunctionDecisionAttributes :: !(Maybe ScheduleLambdaFunctionDecisionAttributes)
, _dRequestCancelActivityTaskDecisionAttributes :: !(Maybe RequestCancelActivityTaskDecisionAttributes)
, _dCancelWorkflowExecutionDecisionAttributes :: !(Maybe CancelWorkflowExecutionDecisionAttributes)
, _dCancelTimerDecisionAttributes :: !(Maybe CancelTimerDecisionAttributes)
, _dContinueAsNewWorkflowExecutionDecisionAttributes :: !(Maybe ContinueAsNewWorkflowExecutionDecisionAttributes)
, _dDecisionType :: !DecisionType
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'Decision' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dRequestCancelExternalWorkflowExecutionDecisionAttributes'
--
-- * 'dScheduleActivityTaskDecisionAttributes'
--
-- * 'dSignalExternalWorkflowExecutionDecisionAttributes'
--
-- * 'dStartTimerDecisionAttributes'
--
-- * 'dRecordMarkerDecisionAttributes'
--
-- * 'dFailWorkflowExecutionDecisionAttributes'
--
-- * 'dStartChildWorkflowExecutionDecisionAttributes'
--
-- * 'dCompleteWorkflowExecutionDecisionAttributes'
--
-- * 'dScheduleLambdaFunctionDecisionAttributes'
--
-- * 'dRequestCancelActivityTaskDecisionAttributes'
--
-- * 'dCancelWorkflowExecutionDecisionAttributes'
--
-- * 'dCancelTimerDecisionAttributes'
--
-- * 'dContinueAsNewWorkflowExecutionDecisionAttributes'
--
-- * 'dDecisionType'
decision
:: DecisionType -- ^ 'dDecisionType'
-> Decision
decision pDecisionType_ =
Decision'
{ _dRequestCancelExternalWorkflowExecutionDecisionAttributes = Nothing
, _dScheduleActivityTaskDecisionAttributes = Nothing
, _dSignalExternalWorkflowExecutionDecisionAttributes = Nothing
, _dStartTimerDecisionAttributes = Nothing
, _dRecordMarkerDecisionAttributes = Nothing
, _dFailWorkflowExecutionDecisionAttributes = Nothing
, _dStartChildWorkflowExecutionDecisionAttributes = Nothing
, _dCompleteWorkflowExecutionDecisionAttributes = Nothing
, _dScheduleLambdaFunctionDecisionAttributes = Nothing
, _dRequestCancelActivityTaskDecisionAttributes = Nothing
, _dCancelWorkflowExecutionDecisionAttributes = Nothing
, _dCancelTimerDecisionAttributes = Nothing
, _dContinueAsNewWorkflowExecutionDecisionAttributes = Nothing
, _dDecisionType = pDecisionType_
}
-- | Provides details of the 'RequestCancelExternalWorkflowExecution'
-- decision. It is not set for other decision types.
dRequestCancelExternalWorkflowExecutionDecisionAttributes :: Lens' Decision (Maybe RequestCancelExternalWorkflowExecutionDecisionAttributes)
dRequestCancelExternalWorkflowExecutionDecisionAttributes = lens _dRequestCancelExternalWorkflowExecutionDecisionAttributes (\ s a -> s{_dRequestCancelExternalWorkflowExecutionDecisionAttributes = a});
-- | Provides details of the 'ScheduleActivityTask' decision. It is not set
-- for other decision types.
dScheduleActivityTaskDecisionAttributes :: Lens' Decision (Maybe ScheduleActivityTaskDecisionAttributes)
dScheduleActivityTaskDecisionAttributes = lens _dScheduleActivityTaskDecisionAttributes (\ s a -> s{_dScheduleActivityTaskDecisionAttributes = a});
-- | Provides details of the 'SignalExternalWorkflowExecution' decision. It
-- is not set for other decision types.
dSignalExternalWorkflowExecutionDecisionAttributes :: Lens' Decision (Maybe SignalExternalWorkflowExecutionDecisionAttributes)
dSignalExternalWorkflowExecutionDecisionAttributes = lens _dSignalExternalWorkflowExecutionDecisionAttributes (\ s a -> s{_dSignalExternalWorkflowExecutionDecisionAttributes = a});
-- | Provides details of the 'StartTimer' decision. It is not set for other
-- decision types.
dStartTimerDecisionAttributes :: Lens' Decision (Maybe StartTimerDecisionAttributes)
dStartTimerDecisionAttributes = lens _dStartTimerDecisionAttributes (\ s a -> s{_dStartTimerDecisionAttributes = a});
-- | Provides details of the 'RecordMarker' decision. It is not set for other
-- decision types.
dRecordMarkerDecisionAttributes :: Lens' Decision (Maybe RecordMarkerDecisionAttributes)
dRecordMarkerDecisionAttributes = lens _dRecordMarkerDecisionAttributes (\ s a -> s{_dRecordMarkerDecisionAttributes = a});
-- | Provides details of the 'FailWorkflowExecution' decision. It is not set
-- for other decision types.
dFailWorkflowExecutionDecisionAttributes :: Lens' Decision (Maybe FailWorkflowExecutionDecisionAttributes)
dFailWorkflowExecutionDecisionAttributes = lens _dFailWorkflowExecutionDecisionAttributes (\ s a -> s{_dFailWorkflowExecutionDecisionAttributes = a});
-- | Provides details of the 'StartChildWorkflowExecution' decision. It is
-- not set for other decision types.
dStartChildWorkflowExecutionDecisionAttributes :: Lens' Decision (Maybe StartChildWorkflowExecutionDecisionAttributes)
dStartChildWorkflowExecutionDecisionAttributes = lens _dStartChildWorkflowExecutionDecisionAttributes (\ s a -> s{_dStartChildWorkflowExecutionDecisionAttributes = a});
-- | Provides details of the 'CompleteWorkflowExecution' decision. It is not
-- set for other decision types.
dCompleteWorkflowExecutionDecisionAttributes :: Lens' Decision (Maybe CompleteWorkflowExecutionDecisionAttributes)
dCompleteWorkflowExecutionDecisionAttributes = lens _dCompleteWorkflowExecutionDecisionAttributes (\ s a -> s{_dCompleteWorkflowExecutionDecisionAttributes = a});
-- | Undocumented member.
dScheduleLambdaFunctionDecisionAttributes :: Lens' Decision (Maybe ScheduleLambdaFunctionDecisionAttributes)
dScheduleLambdaFunctionDecisionAttributes = lens _dScheduleLambdaFunctionDecisionAttributes (\ s a -> s{_dScheduleLambdaFunctionDecisionAttributes = a});
-- | Provides details of the 'RequestCancelActivityTask' decision. It is not
-- set for other decision types.
dRequestCancelActivityTaskDecisionAttributes :: Lens' Decision (Maybe RequestCancelActivityTaskDecisionAttributes)
dRequestCancelActivityTaskDecisionAttributes = lens _dRequestCancelActivityTaskDecisionAttributes (\ s a -> s{_dRequestCancelActivityTaskDecisionAttributes = a});
-- | Provides details of the 'CancelWorkflowExecution' decision. It is not
-- set for other decision types.
dCancelWorkflowExecutionDecisionAttributes :: Lens' Decision (Maybe CancelWorkflowExecutionDecisionAttributes)
dCancelWorkflowExecutionDecisionAttributes = lens _dCancelWorkflowExecutionDecisionAttributes (\ s a -> s{_dCancelWorkflowExecutionDecisionAttributes = a});
-- | Provides details of the 'CancelTimer' decision. It is not set for other
-- decision types.
dCancelTimerDecisionAttributes :: Lens' Decision (Maybe CancelTimerDecisionAttributes)
dCancelTimerDecisionAttributes = lens _dCancelTimerDecisionAttributes (\ s a -> s{_dCancelTimerDecisionAttributes = a});
-- | Provides details of the 'ContinueAsNewWorkflowExecution' decision. It is
-- not set for other decision types.
dContinueAsNewWorkflowExecutionDecisionAttributes :: Lens' Decision (Maybe ContinueAsNewWorkflowExecutionDecisionAttributes)
dContinueAsNewWorkflowExecutionDecisionAttributes = lens _dContinueAsNewWorkflowExecutionDecisionAttributes (\ s a -> s{_dContinueAsNewWorkflowExecutionDecisionAttributes = a});
-- | Specifies the type of the decision.
dDecisionType :: Lens' Decision DecisionType
dDecisionType = lens _dDecisionType (\ s a -> s{_dDecisionType = a});
instance ToJSON Decision where
toJSON Decision'{..}
= object
(catMaybes
[("requestCancelExternalWorkflowExecutionDecisionAttributes"
.=)
<$>
_dRequestCancelExternalWorkflowExecutionDecisionAttributes,
("scheduleActivityTaskDecisionAttributes" .=) <$>
_dScheduleActivityTaskDecisionAttributes,
("signalExternalWorkflowExecutionDecisionAttributes"
.=)
<$>
_dSignalExternalWorkflowExecutionDecisionAttributes,
("startTimerDecisionAttributes" .=) <$>
_dStartTimerDecisionAttributes,
("recordMarkerDecisionAttributes" .=) <$>
_dRecordMarkerDecisionAttributes,
("failWorkflowExecutionDecisionAttributes" .=) <$>
_dFailWorkflowExecutionDecisionAttributes,
("startChildWorkflowExecutionDecisionAttributes" .=)
<$> _dStartChildWorkflowExecutionDecisionAttributes,
("completeWorkflowExecutionDecisionAttributes" .=)
<$> _dCompleteWorkflowExecutionDecisionAttributes,
("scheduleLambdaFunctionDecisionAttributes" .=) <$>
_dScheduleLambdaFunctionDecisionAttributes,
("requestCancelActivityTaskDecisionAttributes" .=)
<$> _dRequestCancelActivityTaskDecisionAttributes,
("cancelWorkflowExecutionDecisionAttributes" .=) <$>
_dCancelWorkflowExecutionDecisionAttributes,
("cancelTimerDecisionAttributes" .=) <$>
_dCancelTimerDecisionAttributes,
("continueAsNewWorkflowExecutionDecisionAttributes"
.=)
<$>
_dContinueAsNewWorkflowExecutionDecisionAttributes,
Just ("decisionType" .= _dDecisionType)])
-- | Provides details of the 'DecisionTaskCompleted' event.
--
-- /See:/ 'decisionTaskCompletedEventAttributes' smart constructor.
data DecisionTaskCompletedEventAttributes = DecisionTaskCompletedEventAttributes'
{ _dtceaExecutionContext :: !(Maybe Text)
, _dtceaScheduledEventId :: !Integer
, _dtceaStartedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DecisionTaskCompletedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dtceaExecutionContext'
--
-- * 'dtceaScheduledEventId'
--
-- * 'dtceaStartedEventId'
decisionTaskCompletedEventAttributes
:: Integer -- ^ 'dtceaScheduledEventId'
-> Integer -- ^ 'dtceaStartedEventId'
-> DecisionTaskCompletedEventAttributes
decisionTaskCompletedEventAttributes pScheduledEventId_ pStartedEventId_ =
DecisionTaskCompletedEventAttributes'
{ _dtceaExecutionContext = Nothing
, _dtceaScheduledEventId = pScheduledEventId_
, _dtceaStartedEventId = pStartedEventId_
}
-- | User defined context for the workflow execution.
dtceaExecutionContext :: Lens' DecisionTaskCompletedEventAttributes (Maybe Text)
dtceaExecutionContext = lens _dtceaExecutionContext (\ s a -> s{_dtceaExecutionContext = a});
-- | The ID of the 'DecisionTaskScheduled' event that was recorded when this
-- decision task was scheduled. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
dtceaScheduledEventId :: Lens' DecisionTaskCompletedEventAttributes Integer
dtceaScheduledEventId = lens _dtceaScheduledEventId (\ s a -> s{_dtceaScheduledEventId = a});
-- | The ID of the 'DecisionTaskStarted' event recorded when this decision
-- task was started. This information can be useful for diagnosing problems
-- by tracing back the chain of events leading up to this event.
dtceaStartedEventId :: Lens' DecisionTaskCompletedEventAttributes Integer
dtceaStartedEventId = lens _dtceaStartedEventId (\ s a -> s{_dtceaStartedEventId = a});
instance FromJSON
DecisionTaskCompletedEventAttributes where
parseJSON
= withObject "DecisionTaskCompletedEventAttributes"
(\ x ->
DecisionTaskCompletedEventAttributes' <$>
(x .:? "executionContext") <*>
(x .: "scheduledEventId")
<*> (x .: "startedEventId"))
-- | Provides details about the 'DecisionTaskScheduled' event.
--
-- /See:/ 'decisionTaskScheduledEventAttributes' smart constructor.
data DecisionTaskScheduledEventAttributes = DecisionTaskScheduledEventAttributes'
{ _dtseaTaskPriority :: !(Maybe Text)
, _dtseaStartToCloseTimeout :: !(Maybe Text)
, _dtseaTaskList :: !TaskList
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DecisionTaskScheduledEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dtseaTaskPriority'
--
-- * 'dtseaStartToCloseTimeout'
--
-- * 'dtseaTaskList'
decisionTaskScheduledEventAttributes
:: TaskList -- ^ 'dtseaTaskList'
-> DecisionTaskScheduledEventAttributes
decisionTaskScheduledEventAttributes pTaskList_ =
DecisionTaskScheduledEventAttributes'
{ _dtseaTaskPriority = Nothing
, _dtseaStartToCloseTimeout = Nothing
, _dtseaTaskList = pTaskList_
}
-- | /Optional./ A task priority that, if set, specifies the priority for
-- this decision task. Valid values are integers that range from Java\'s
-- 'Integer.MIN_VALUE' (-2147483648) to 'Integer.MAX_VALUE' (2147483647).
-- Higher numbers indicate higher priority.
--
-- For more information about setting task priority, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/programming-priority.html Setting Task Priority>
-- in the /Amazon Simple Workflow Developer Guide/.
dtseaTaskPriority :: Lens' DecisionTaskScheduledEventAttributes (Maybe Text)
dtseaTaskPriority = lens _dtseaTaskPriority (\ s a -> s{_dtseaTaskPriority = a});
-- | The maximum duration for this decision task. The task is considered
-- timed out if it does not completed within this duration.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
dtseaStartToCloseTimeout :: Lens' DecisionTaskScheduledEventAttributes (Maybe Text)
dtseaStartToCloseTimeout = lens _dtseaStartToCloseTimeout (\ s a -> s{_dtseaStartToCloseTimeout = a});
-- | The name of the task list in which the decision task was scheduled.
dtseaTaskList :: Lens' DecisionTaskScheduledEventAttributes TaskList
dtseaTaskList = lens _dtseaTaskList (\ s a -> s{_dtseaTaskList = a});
instance FromJSON
DecisionTaskScheduledEventAttributes where
parseJSON
= withObject "DecisionTaskScheduledEventAttributes"
(\ x ->
DecisionTaskScheduledEventAttributes' <$>
(x .:? "taskPriority") <*>
(x .:? "startToCloseTimeout")
<*> (x .: "taskList"))
-- | Provides details of the 'DecisionTaskStarted' event.
--
-- /See:/ 'decisionTaskStartedEventAttributes' smart constructor.
data DecisionTaskStartedEventAttributes = DecisionTaskStartedEventAttributes'
{ _dtseaIdentity :: !(Maybe Text)
, _dtseaScheduledEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DecisionTaskStartedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dtseaIdentity'
--
-- * 'dtseaScheduledEventId'
decisionTaskStartedEventAttributes
:: Integer -- ^ 'dtseaScheduledEventId'
-> DecisionTaskStartedEventAttributes
decisionTaskStartedEventAttributes pScheduledEventId_ =
DecisionTaskStartedEventAttributes'
{ _dtseaIdentity = Nothing
, _dtseaScheduledEventId = pScheduledEventId_
}
-- | Identity of the decider making the request. This enables diagnostic
-- tracing when problems arise. The form of this identity is user defined.
dtseaIdentity :: Lens' DecisionTaskStartedEventAttributes (Maybe Text)
dtseaIdentity = lens _dtseaIdentity (\ s a -> s{_dtseaIdentity = a});
-- | The ID of the 'DecisionTaskScheduled' event that was recorded when this
-- decision task was scheduled. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
dtseaScheduledEventId :: Lens' DecisionTaskStartedEventAttributes Integer
dtseaScheduledEventId = lens _dtseaScheduledEventId (\ s a -> s{_dtseaScheduledEventId = a});
instance FromJSON DecisionTaskStartedEventAttributes
where
parseJSON
= withObject "DecisionTaskStartedEventAttributes"
(\ x ->
DecisionTaskStartedEventAttributes' <$>
(x .:? "identity") <*> (x .: "scheduledEventId"))
-- | Provides details of the 'DecisionTaskTimedOut' event.
--
-- /See:/ 'decisionTaskTimedOutEventAttributes' smart constructor.
data DecisionTaskTimedOutEventAttributes = DecisionTaskTimedOutEventAttributes'
{ _dttoeaTimeoutType :: !DecisionTaskTimeoutType
, _dttoeaScheduledEventId :: !Integer
, _dttoeaStartedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DecisionTaskTimedOutEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dttoeaTimeoutType'
--
-- * 'dttoeaScheduledEventId'
--
-- * 'dttoeaStartedEventId'
decisionTaskTimedOutEventAttributes
:: DecisionTaskTimeoutType -- ^ 'dttoeaTimeoutType'
-> Integer -- ^ 'dttoeaScheduledEventId'
-> Integer -- ^ 'dttoeaStartedEventId'
-> DecisionTaskTimedOutEventAttributes
decisionTaskTimedOutEventAttributes pTimeoutType_ pScheduledEventId_ pStartedEventId_ =
DecisionTaskTimedOutEventAttributes'
{ _dttoeaTimeoutType = pTimeoutType_
, _dttoeaScheduledEventId = pScheduledEventId_
, _dttoeaStartedEventId = pStartedEventId_
}
-- | The type of timeout that expired before the decision task could be
-- completed.
dttoeaTimeoutType :: Lens' DecisionTaskTimedOutEventAttributes DecisionTaskTimeoutType
dttoeaTimeoutType = lens _dttoeaTimeoutType (\ s a -> s{_dttoeaTimeoutType = a});
-- | The ID of the 'DecisionTaskScheduled' event that was recorded when this
-- decision task was scheduled. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
dttoeaScheduledEventId :: Lens' DecisionTaskTimedOutEventAttributes Integer
dttoeaScheduledEventId = lens _dttoeaScheduledEventId (\ s a -> s{_dttoeaScheduledEventId = a});
-- | The ID of the 'DecisionTaskStarted' event recorded when this decision
-- task was started. This information can be useful for diagnosing problems
-- by tracing back the chain of events leading up to this event.
dttoeaStartedEventId :: Lens' DecisionTaskTimedOutEventAttributes Integer
dttoeaStartedEventId = lens _dttoeaStartedEventId (\ s a -> s{_dttoeaStartedEventId = a});
instance FromJSON DecisionTaskTimedOutEventAttributes
where
parseJSON
= withObject "DecisionTaskTimedOutEventAttributes"
(\ x ->
DecisionTaskTimedOutEventAttributes' <$>
(x .: "timeoutType") <*> (x .: "scheduledEventId")
<*> (x .: "startedEventId"))
-- | Contains the configuration settings of a domain.
--
-- /See:/ 'domainConfiguration' smart constructor.
newtype DomainConfiguration = DomainConfiguration'
{ _dcWorkflowExecutionRetentionPeriodInDays :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DomainConfiguration' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dcWorkflowExecutionRetentionPeriodInDays'
domainConfiguration
:: Text -- ^ 'dcWorkflowExecutionRetentionPeriodInDays'
-> DomainConfiguration
domainConfiguration pWorkflowExecutionRetentionPeriodInDays_ =
DomainConfiguration'
{ _dcWorkflowExecutionRetentionPeriodInDays = pWorkflowExecutionRetentionPeriodInDays_
}
-- | The retention period for workflow executions in this domain.
dcWorkflowExecutionRetentionPeriodInDays :: Lens' DomainConfiguration Text
dcWorkflowExecutionRetentionPeriodInDays = lens _dcWorkflowExecutionRetentionPeriodInDays (\ s a -> s{_dcWorkflowExecutionRetentionPeriodInDays = a});
instance FromJSON DomainConfiguration where
parseJSON
= withObject "DomainConfiguration"
(\ x ->
DomainConfiguration' <$>
(x .: "workflowExecutionRetentionPeriodInDays"))
-- | Contains general information about a domain.
--
-- /See:/ 'domainInfo' smart constructor.
data DomainInfo = DomainInfo'
{ _diDescription :: !(Maybe Text)
, _diName :: !Text
, _diStatus :: !RegistrationStatus
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DomainInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'diDescription'
--
-- * 'diName'
--
-- * 'diStatus'
domainInfo
:: Text -- ^ 'diName'
-> RegistrationStatus -- ^ 'diStatus'
-> DomainInfo
domainInfo pName_ pStatus_ =
DomainInfo'
{ _diDescription = Nothing
, _diName = pName_
, _diStatus = pStatus_
}
-- | The description of the domain provided through RegisterDomain.
diDescription :: Lens' DomainInfo (Maybe Text)
diDescription = lens _diDescription (\ s a -> s{_diDescription = a});
-- | The name of the domain. This name is unique within the account.
diName :: Lens' DomainInfo Text
diName = lens _diName (\ s a -> s{_diName = a});
-- | The status of the domain:
--
-- - __REGISTERED__: The domain is properly registered and available. You
-- can use this domain for registering types and creating new workflow
-- executions.
-- - __DEPRECATED__: The domain was deprecated using DeprecateDomain, but
-- is still in use. You should not create new workflow executions in
-- this domain.
diStatus :: Lens' DomainInfo RegistrationStatus
diStatus = lens _diStatus (\ s a -> s{_diStatus = a});
instance FromJSON DomainInfo where
parseJSON
= withObject "DomainInfo"
(\ x ->
DomainInfo' <$>
(x .:? "description") <*> (x .: "name") <*>
(x .: "status"))
-- | Used to filter the workflow executions in visibility APIs by various
-- time-based rules. Each parameter, if specified, defines a rule that must
-- be satisfied by each returned query result. The parameter values are in
-- the <https://en.wikipedia.org/wiki/Unix_time Unix Time format>. For
-- example: '\"oldestDate\": 1325376070.'
--
-- /See:/ 'executionTimeFilter' smart constructor.
data ExecutionTimeFilter = ExecutionTimeFilter'
{ _etfLatestDate :: !(Maybe POSIX)
, _etfOldestDate :: !POSIX
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ExecutionTimeFilter' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'etfLatestDate'
--
-- * 'etfOldestDate'
executionTimeFilter
:: UTCTime -- ^ 'etfOldestDate'
-> ExecutionTimeFilter
executionTimeFilter pOldestDate_ =
ExecutionTimeFilter'
{ _etfLatestDate = Nothing
, _etfOldestDate = _Time # pOldestDate_
}
-- | Specifies the latest start or close date and time to return.
etfLatestDate :: Lens' ExecutionTimeFilter (Maybe UTCTime)
etfLatestDate = lens _etfLatestDate (\ s a -> s{_etfLatestDate = a}) . mapping _Time;
-- | Specifies the oldest start or close date and time to return.
etfOldestDate :: Lens' ExecutionTimeFilter UTCTime
etfOldestDate = lens _etfOldestDate (\ s a -> s{_etfOldestDate = a}) . _Time;
instance ToJSON ExecutionTimeFilter where
toJSON ExecutionTimeFilter'{..}
= object
(catMaybes
[("latestDate" .=) <$> _etfLatestDate,
Just ("oldestDate" .= _etfOldestDate)])
-- | Provides details of the 'ExternalWorkflowExecutionCancelRequested'
-- event.
--
-- /See:/ 'externalWorkflowExecutionCancelRequestedEventAttributes' smart constructor.
data ExternalWorkflowExecutionCancelRequestedEventAttributes = ExternalWorkflowExecutionCancelRequestedEventAttributes'
{ _ewecreaWorkflowExecution :: !WorkflowExecution
, _ewecreaInitiatedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ExternalWorkflowExecutionCancelRequestedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ewecreaWorkflowExecution'
--
-- * 'ewecreaInitiatedEventId'
externalWorkflowExecutionCancelRequestedEventAttributes
:: WorkflowExecution -- ^ 'ewecreaWorkflowExecution'
-> Integer -- ^ 'ewecreaInitiatedEventId'
-> ExternalWorkflowExecutionCancelRequestedEventAttributes
externalWorkflowExecutionCancelRequestedEventAttributes pWorkflowExecution_ pInitiatedEventId_ =
ExternalWorkflowExecutionCancelRequestedEventAttributes'
{ _ewecreaWorkflowExecution = pWorkflowExecution_
, _ewecreaInitiatedEventId = pInitiatedEventId_
}
-- | The external workflow execution to which the cancellation request was
-- delivered.
ewecreaWorkflowExecution :: Lens' ExternalWorkflowExecutionCancelRequestedEventAttributes WorkflowExecution
ewecreaWorkflowExecution = lens _ewecreaWorkflowExecution (\ s a -> s{_ewecreaWorkflowExecution = a});
-- | The ID of the 'RequestCancelExternalWorkflowExecutionInitiated' event
-- corresponding to the 'RequestCancelExternalWorkflowExecution' decision
-- to cancel this external workflow execution. This information can be
-- useful for diagnosing problems by tracing back the chain of events
-- leading up to this event.
ewecreaInitiatedEventId :: Lens' ExternalWorkflowExecutionCancelRequestedEventAttributes Integer
ewecreaInitiatedEventId = lens _ewecreaInitiatedEventId (\ s a -> s{_ewecreaInitiatedEventId = a});
instance FromJSON
ExternalWorkflowExecutionCancelRequestedEventAttributes
where
parseJSON
= withObject
"ExternalWorkflowExecutionCancelRequestedEventAttributes"
(\ x ->
ExternalWorkflowExecutionCancelRequestedEventAttributes'
<$>
(x .: "workflowExecution") <*>
(x .: "initiatedEventId"))
-- | Provides details of the 'ExternalWorkflowExecutionSignaled' event.
--
-- /See:/ 'externalWorkflowExecutionSignaledEventAttributes' smart constructor.
data ExternalWorkflowExecutionSignaledEventAttributes = ExternalWorkflowExecutionSignaledEventAttributes'
{ _eweseaWorkflowExecution :: !WorkflowExecution
, _eweseaInitiatedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ExternalWorkflowExecutionSignaledEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'eweseaWorkflowExecution'
--
-- * 'eweseaInitiatedEventId'
externalWorkflowExecutionSignaledEventAttributes
:: WorkflowExecution -- ^ 'eweseaWorkflowExecution'
-> Integer -- ^ 'eweseaInitiatedEventId'
-> ExternalWorkflowExecutionSignaledEventAttributes
externalWorkflowExecutionSignaledEventAttributes pWorkflowExecution_ pInitiatedEventId_ =
ExternalWorkflowExecutionSignaledEventAttributes'
{ _eweseaWorkflowExecution = pWorkflowExecution_
, _eweseaInitiatedEventId = pInitiatedEventId_
}
-- | The external workflow execution that the signal was delivered to.
eweseaWorkflowExecution :: Lens' ExternalWorkflowExecutionSignaledEventAttributes WorkflowExecution
eweseaWorkflowExecution = lens _eweseaWorkflowExecution (\ s a -> s{_eweseaWorkflowExecution = a});
-- | The ID of the 'SignalExternalWorkflowExecutionInitiated' event
-- corresponding to the 'SignalExternalWorkflowExecution' decision to
-- request this signal. This information can be useful for diagnosing
-- problems by tracing back the chain of events leading up to this event.
eweseaInitiatedEventId :: Lens' ExternalWorkflowExecutionSignaledEventAttributes Integer
eweseaInitiatedEventId = lens _eweseaInitiatedEventId (\ s a -> s{_eweseaInitiatedEventId = a});
instance FromJSON
ExternalWorkflowExecutionSignaledEventAttributes
where
parseJSON
= withObject
"ExternalWorkflowExecutionSignaledEventAttributes"
(\ x ->
ExternalWorkflowExecutionSignaledEventAttributes' <$>
(x .: "workflowExecution") <*>
(x .: "initiatedEventId"))
-- | Provides details of the 'FailWorkflowExecution' decision.
--
-- __Access Control__
--
-- You can use IAM policies to control this decision\'s access to Amazon
-- SWF resources as follows:
--
-- - Use a 'Resource' element with the domain name to limit the action to
-- only specified domains.
-- - Use an 'Action' element to allow or deny permission to call this
-- action.
-- - You cannot use an IAM policy to constrain this action\'s parameters.
--
-- If the caller does not have sufficient permissions to invoke the action,
-- or the parameter values fall outside the specified constraints, the
-- action fails. The associated event attribute\'s __cause__ parameter will
-- be set to OPERATION_NOT_PERMITTED. For details and example IAM policies,
-- see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- /See:/ 'failWorkflowExecutionDecisionAttributes' smart constructor.
data FailWorkflowExecutionDecisionAttributes = FailWorkflowExecutionDecisionAttributes'
{ _fwedaReason :: !(Maybe Text)
, _fwedaDetails :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'FailWorkflowExecutionDecisionAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'fwedaReason'
--
-- * 'fwedaDetails'
failWorkflowExecutionDecisionAttributes
:: FailWorkflowExecutionDecisionAttributes
failWorkflowExecutionDecisionAttributes =
FailWorkflowExecutionDecisionAttributes'
{ _fwedaReason = Nothing
, _fwedaDetails = Nothing
}
-- | A descriptive reason for the failure that may help in diagnostics.
fwedaReason :: Lens' FailWorkflowExecutionDecisionAttributes (Maybe Text)
fwedaReason = lens _fwedaReason (\ s a -> s{_fwedaReason = a});
-- | /Optional./ Details of the failure.
fwedaDetails :: Lens' FailWorkflowExecutionDecisionAttributes (Maybe Text)
fwedaDetails = lens _fwedaDetails (\ s a -> s{_fwedaDetails = a});
instance ToJSON
FailWorkflowExecutionDecisionAttributes where
toJSON FailWorkflowExecutionDecisionAttributes'{..}
= object
(catMaybes
[("reason" .=) <$> _fwedaReason,
("details" .=) <$> _fwedaDetails])
-- | Provides details of the 'FailWorkflowExecutionFailed' event.
--
-- /See:/ 'failWorkflowExecutionFailedEventAttributes' smart constructor.
data FailWorkflowExecutionFailedEventAttributes = FailWorkflowExecutionFailedEventAttributes'
{ _fwefeaCause :: !FailWorkflowExecutionFailedCause
, _fwefeaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'FailWorkflowExecutionFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'fwefeaCause'
--
-- * 'fwefeaDecisionTaskCompletedEventId'
failWorkflowExecutionFailedEventAttributes
:: FailWorkflowExecutionFailedCause -- ^ 'fwefeaCause'
-> Integer -- ^ 'fwefeaDecisionTaskCompletedEventId'
-> FailWorkflowExecutionFailedEventAttributes
failWorkflowExecutionFailedEventAttributes pCause_ pDecisionTaskCompletedEventId_ =
FailWorkflowExecutionFailedEventAttributes'
{ _fwefeaCause = pCause_
, _fwefeaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | The cause of the failure. This information is generated by the system
-- and can be useful for diagnostic purposes.
--
-- If __cause__ is set to OPERATION_NOT_PERMITTED, the decision failed
-- because it lacked sufficient permissions. For details and example IAM
-- policies, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
fwefeaCause :: Lens' FailWorkflowExecutionFailedEventAttributes FailWorkflowExecutionFailedCause
fwefeaCause = lens _fwefeaCause (\ s a -> s{_fwefeaCause = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'FailWorkflowExecution' decision to
-- fail this execution. This information can be useful for diagnosing
-- problems by tracing back the chain of events leading up to this event.
fwefeaDecisionTaskCompletedEventId :: Lens' FailWorkflowExecutionFailedEventAttributes Integer
fwefeaDecisionTaskCompletedEventId = lens _fwefeaDecisionTaskCompletedEventId (\ s a -> s{_fwefeaDecisionTaskCompletedEventId = a});
instance FromJSON
FailWorkflowExecutionFailedEventAttributes where
parseJSON
= withObject
"FailWorkflowExecutionFailedEventAttributes"
(\ x ->
FailWorkflowExecutionFailedEventAttributes' <$>
(x .: "cause") <*>
(x .: "decisionTaskCompletedEventId"))
-- | Event within a workflow execution. A history event can be one of these
-- types:
--
-- - __WorkflowExecutionStarted__: The workflow execution was started.
-- - __WorkflowExecutionCompleted__: The workflow execution was closed
-- due to successful completion.
-- - __WorkflowExecutionFailed__: The workflow execution closed due to a
-- failure.
-- - __WorkflowExecutionTimedOut__: The workflow execution was closed
-- because a time out was exceeded.
-- - __WorkflowExecutionCanceled__: The workflow execution was
-- successfully canceled and closed.
-- - __WorkflowExecutionTerminated__: The workflow execution was
-- terminated.
-- - __WorkflowExecutionContinuedAsNew__: The workflow execution was
-- closed and a new execution of the same type was created with the
-- same workflowId.
-- - __WorkflowExecutionCancelRequested__: A request to cancel this
-- workflow execution was made.
-- - __DecisionTaskScheduled__: A decision task was scheduled for the
-- workflow execution.
-- - __DecisionTaskStarted__: The decision task was dispatched to a
-- decider.
-- - __DecisionTaskCompleted__: The decider successfully completed a
-- decision task by calling RespondDecisionTaskCompleted.
-- - __DecisionTaskTimedOut__: The decision task timed out.
-- - __ActivityTaskScheduled__: An activity task was scheduled for
-- execution.
-- - __ScheduleActivityTaskFailed__: Failed to process
-- ScheduleActivityTask decision. This happens when the decision is not
-- configured properly, for example the activity type specified is not
-- registered.
-- - __ActivityTaskStarted__: The scheduled activity task was dispatched
-- to a worker.
-- - __ActivityTaskCompleted__: An activity worker successfully completed
-- an activity task by calling RespondActivityTaskCompleted.
-- - __ActivityTaskFailed__: An activity worker failed an activity task
-- by calling RespondActivityTaskFailed.
-- - __ActivityTaskTimedOut__: The activity task timed out.
-- - __ActivityTaskCanceled__: The activity task was successfully
-- canceled.
-- - __ActivityTaskCancelRequested__: A 'RequestCancelActivityTask'
-- decision was received by the system.
-- - __RequestCancelActivityTaskFailed__: Failed to process
-- RequestCancelActivityTask decision. This happens when the decision
-- is not configured properly.
-- - __WorkflowExecutionSignaled__: An external signal was received for
-- the workflow execution.
-- - __MarkerRecorded__: A marker was recorded in the workflow history as
-- the result of a 'RecordMarker' decision.
-- - __TimerStarted__: A timer was started for the workflow execution due
-- to a 'StartTimer' decision.
-- - __StartTimerFailed__: Failed to process StartTimer decision. This
-- happens when the decision is not configured properly, for example a
-- timer already exists with the specified timer ID.
-- - __TimerFired__: A timer, previously started for this workflow
-- execution, fired.
-- - __TimerCanceled__: A timer, previously started for this workflow
-- execution, was successfully canceled.
-- - __CancelTimerFailed__: Failed to process CancelTimer decision. This
-- happens when the decision is not configured properly, for example no
-- timer exists with the specified timer ID.
-- - __StartChildWorkflowExecutionInitiated__: A request was made to
-- start a child workflow execution.
-- - __StartChildWorkflowExecutionFailed__: Failed to process
-- StartChildWorkflowExecution decision. This happens when the decision
-- is not configured properly, for example the workflow type specified
-- is not registered.
-- - __ChildWorkflowExecutionStarted__: A child workflow execution was
-- successfully started.
-- - __ChildWorkflowExecutionCompleted__: A child workflow execution,
-- started by this workflow execution, completed successfully and was
-- closed.
-- - __ChildWorkflowExecutionFailed__: A child workflow execution,
-- started by this workflow execution, failed to complete successfully
-- and was closed.
-- - __ChildWorkflowExecutionTimedOut__: A child workflow execution,
-- started by this workflow execution, timed out and was closed.
-- - __ChildWorkflowExecutionCanceled__: A child workflow execution,
-- started by this workflow execution, was canceled and closed.
-- - __ChildWorkflowExecutionTerminated__: A child workflow execution,
-- started by this workflow execution, was terminated.
-- - __SignalExternalWorkflowExecutionInitiated__: A request to signal an
-- external workflow was made.
-- - __ExternalWorkflowExecutionSignaled__: A signal, requested by this
-- workflow execution, was successfully delivered to the target
-- external workflow execution.
-- - __SignalExternalWorkflowExecutionFailed__: The request to signal an
-- external workflow execution failed.
-- - __RequestCancelExternalWorkflowExecutionInitiated__: A request was
-- made to request the cancellation of an external workflow execution.
-- - __ExternalWorkflowExecutionCancelRequested__: Request to cancel an
-- external workflow execution was successfully delivered to the target
-- execution.
-- - __RequestCancelExternalWorkflowExecutionFailed__: Request to cancel
-- an external workflow execution failed.
-- - __LambdaFunctionScheduled__: An AWS Lambda function was scheduled
-- for execution.
-- - __LambdaFunctionStarted__: The scheduled function was invoked in the
-- AWS Lambda service.
-- - __LambdaFunctionCompleted__: The AWS Lambda function successfully
-- completed.
-- - __LambdaFunctionFailed__: The AWS Lambda function execution failed.
-- - __LambdaFunctionTimedOut__: The AWS Lambda function execution timed
-- out.
-- - __ScheduleLambdaFunctionFailed__: Failed to process
-- ScheduleLambdaFunction decision. This happens when the workflow
-- execution does not have the proper IAM role attached to invoke AWS
-- Lambda functions.
-- - __StartLambdaFunctionFailed__: Failed to invoke the scheduled
-- function in the AWS Lambda service. This happens when the AWS Lambda
-- service is not available in the current region, or received too many
-- requests.
--
-- /See:/ 'historyEvent' smart constructor.
data HistoryEvent = HistoryEvent'
{ _heWorkflowExecutionCancelRequestedEventAttributes :: !(Maybe WorkflowExecutionCancelRequestedEventAttributes)
, _heRecordMarkerFailedEventAttributes :: !(Maybe RecordMarkerFailedEventAttributes)
, _heRequestCancelExternalWorkflowExecutionInitiatedEventAttributes :: !(Maybe RequestCancelExternalWorkflowExecutionInitiatedEventAttributes)
, _heLambdaFunctionStartedEventAttributes :: !(Maybe LambdaFunctionStartedEventAttributes)
, _heDecisionTaskScheduledEventAttributes :: !(Maybe DecisionTaskScheduledEventAttributes)
, _heWorkflowExecutionCompletedEventAttributes :: !(Maybe WorkflowExecutionCompletedEventAttributes)
, _heStartTimerFailedEventAttributes :: !(Maybe StartTimerFailedEventAttributes)
, _heActivityTaskScheduledEventAttributes :: !(Maybe ActivityTaskScheduledEventAttributes)
, _heScheduleActivityTaskFailedEventAttributes :: !(Maybe ScheduleActivityTaskFailedEventAttributes)
, _heChildWorkflowExecutionCompletedEventAttributes :: !(Maybe ChildWorkflowExecutionCompletedEventAttributes)
, _heMarkerRecordedEventAttributes :: !(Maybe MarkerRecordedEventAttributes)
, _heScheduleLambdaFunctionFailedEventAttributes :: !(Maybe ScheduleLambdaFunctionFailedEventAttributes)
, _heCompleteWorkflowExecutionFailedEventAttributes :: !(Maybe CompleteWorkflowExecutionFailedEventAttributes)
, _heLambdaFunctionCompletedEventAttributes :: !(Maybe LambdaFunctionCompletedEventAttributes)
, _heRequestCancelExternalWorkflowExecutionFailedEventAttributes :: !(Maybe RequestCancelExternalWorkflowExecutionFailedEventAttributes)
, _heTimerCanceledEventAttributes :: !(Maybe TimerCanceledEventAttributes)
, _heWorkflowExecutionStartedEventAttributes :: !(Maybe WorkflowExecutionStartedEventAttributes)
, _heActivityTaskCompletedEventAttributes :: !(Maybe ActivityTaskCompletedEventAttributes)
, _heDecisionTaskTimedOutEventAttributes :: !(Maybe DecisionTaskTimedOutEventAttributes)
, _heCancelTimerFailedEventAttributes :: !(Maybe CancelTimerFailedEventAttributes)
, _heChildWorkflowExecutionStartedEventAttributes :: !(Maybe ChildWorkflowExecutionStartedEventAttributes)
, _heActivityTaskCanceledEventAttributes :: !(Maybe ActivityTaskCanceledEventAttributes)
, _heActivityTaskTimedOutEventAttributes :: !(Maybe ActivityTaskTimedOutEventAttributes)
, _heDecisionTaskStartedEventAttributes :: !(Maybe DecisionTaskStartedEventAttributes)
, _heWorkflowExecutionTerminatedEventAttributes :: !(Maybe WorkflowExecutionTerminatedEventAttributes)
, _heChildWorkflowExecutionCanceledEventAttributes :: !(Maybe ChildWorkflowExecutionCanceledEventAttributes)
, _heRequestCancelActivityTaskFailedEventAttributes :: !(Maybe RequestCancelActivityTaskFailedEventAttributes)
, _heLambdaFunctionScheduledEventAttributes :: !(Maybe LambdaFunctionScheduledEventAttributes)
, _heChildWorkflowExecutionTimedOutEventAttributes :: !(Maybe ChildWorkflowExecutionTimedOutEventAttributes)
, _heCancelWorkflowExecutionFailedEventAttributes :: !(Maybe CancelWorkflowExecutionFailedEventAttributes)
, _heStartChildWorkflowExecutionInitiatedEventAttributes :: !(Maybe StartChildWorkflowExecutionInitiatedEventAttributes)
, _heSignalExternalWorkflowExecutionFailedEventAttributes :: !(Maybe SignalExternalWorkflowExecutionFailedEventAttributes)
, _heActivityTaskStartedEventAttributes :: !(Maybe ActivityTaskStartedEventAttributes)
, _heStartLambdaFunctionFailedEventAttributes :: !(Maybe StartLambdaFunctionFailedEventAttributes)
, _heChildWorkflowExecutionTerminatedEventAttributes :: !(Maybe ChildWorkflowExecutionTerminatedEventAttributes)
, _heLambdaFunctionFailedEventAttributes :: !(Maybe LambdaFunctionFailedEventAttributes)
, _heWorkflowExecutionCanceledEventAttributes :: !(Maybe WorkflowExecutionCanceledEventAttributes)
, _heTimerStartedEventAttributes :: !(Maybe TimerStartedEventAttributes)
, _heActivityTaskCancelRequestedEventAttributes :: !(Maybe ActivityTaskCancelRequestedEventAttributes)
, _heWorkflowExecutionTimedOutEventAttributes :: !(Maybe WorkflowExecutionTimedOutEventAttributes)
, _heWorkflowExecutionSignaledEventAttributes :: !(Maybe WorkflowExecutionSignaledEventAttributes)
, _heTimerFiredEventAttributes :: !(Maybe TimerFiredEventAttributes)
, _heActivityTaskFailedEventAttributes :: !(Maybe ActivityTaskFailedEventAttributes)
, _heExternalWorkflowExecutionSignaledEventAttributes :: !(Maybe ExternalWorkflowExecutionSignaledEventAttributes)
, _heDecisionTaskCompletedEventAttributes :: !(Maybe DecisionTaskCompletedEventAttributes)
, _heStartChildWorkflowExecutionFailedEventAttributes :: !(Maybe StartChildWorkflowExecutionFailedEventAttributes)
, _heChildWorkflowExecutionFailedEventAttributes :: !(Maybe ChildWorkflowExecutionFailedEventAttributes)
, _heFailWorkflowExecutionFailedEventAttributes :: !(Maybe FailWorkflowExecutionFailedEventAttributes)
, _heContinueAsNewWorkflowExecutionFailedEventAttributes :: !(Maybe ContinueAsNewWorkflowExecutionFailedEventAttributes)
, _heSignalExternalWorkflowExecutionInitiatedEventAttributes :: !(Maybe SignalExternalWorkflowExecutionInitiatedEventAttributes)
, _heLambdaFunctionTimedOutEventAttributes :: !(Maybe LambdaFunctionTimedOutEventAttributes)
, _heWorkflowExecutionFailedEventAttributes :: !(Maybe WorkflowExecutionFailedEventAttributes)
, _heWorkflowExecutionContinuedAsNewEventAttributes :: !(Maybe WorkflowExecutionContinuedAsNewEventAttributes)
, _heExternalWorkflowExecutionCancelRequestedEventAttributes :: !(Maybe ExternalWorkflowExecutionCancelRequestedEventAttributes)
, _heEventTimestamp :: !POSIX
, _heEventType :: !EventType
, _heEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'HistoryEvent' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'heWorkflowExecutionCancelRequestedEventAttributes'
--
-- * 'heRecordMarkerFailedEventAttributes'
--
-- * 'heRequestCancelExternalWorkflowExecutionInitiatedEventAttributes'
--
-- * 'heLambdaFunctionStartedEventAttributes'
--
-- * 'heDecisionTaskScheduledEventAttributes'
--
-- * 'heWorkflowExecutionCompletedEventAttributes'
--
-- * 'heStartTimerFailedEventAttributes'
--
-- * 'heActivityTaskScheduledEventAttributes'
--
-- * 'heScheduleActivityTaskFailedEventAttributes'
--
-- * 'heChildWorkflowExecutionCompletedEventAttributes'
--
-- * 'heMarkerRecordedEventAttributes'
--
-- * 'heScheduleLambdaFunctionFailedEventAttributes'
--
-- * 'heCompleteWorkflowExecutionFailedEventAttributes'
--
-- * 'heLambdaFunctionCompletedEventAttributes'
--
-- * 'heRequestCancelExternalWorkflowExecutionFailedEventAttributes'
--
-- * 'heTimerCanceledEventAttributes'
--
-- * 'heWorkflowExecutionStartedEventAttributes'
--
-- * 'heActivityTaskCompletedEventAttributes'
--
-- * 'heDecisionTaskTimedOutEventAttributes'
--
-- * 'heCancelTimerFailedEventAttributes'
--
-- * 'heChildWorkflowExecutionStartedEventAttributes'
--
-- * 'heActivityTaskCanceledEventAttributes'
--
-- * 'heActivityTaskTimedOutEventAttributes'
--
-- * 'heDecisionTaskStartedEventAttributes'
--
-- * 'heWorkflowExecutionTerminatedEventAttributes'
--
-- * 'heChildWorkflowExecutionCanceledEventAttributes'
--
-- * 'heRequestCancelActivityTaskFailedEventAttributes'
--
-- * 'heLambdaFunctionScheduledEventAttributes'
--
-- * 'heChildWorkflowExecutionTimedOutEventAttributes'
--
-- * 'heCancelWorkflowExecutionFailedEventAttributes'
--
-- * 'heStartChildWorkflowExecutionInitiatedEventAttributes'
--
-- * 'heSignalExternalWorkflowExecutionFailedEventAttributes'
--
-- * 'heActivityTaskStartedEventAttributes'
--
-- * 'heStartLambdaFunctionFailedEventAttributes'
--
-- * 'heChildWorkflowExecutionTerminatedEventAttributes'
--
-- * 'heLambdaFunctionFailedEventAttributes'
--
-- * 'heWorkflowExecutionCanceledEventAttributes'
--
-- * 'heTimerStartedEventAttributes'
--
-- * 'heActivityTaskCancelRequestedEventAttributes'
--
-- * 'heWorkflowExecutionTimedOutEventAttributes'
--
-- * 'heWorkflowExecutionSignaledEventAttributes'
--
-- * 'heTimerFiredEventAttributes'
--
-- * 'heActivityTaskFailedEventAttributes'
--
-- * 'heExternalWorkflowExecutionSignaledEventAttributes'
--
-- * 'heDecisionTaskCompletedEventAttributes'
--
-- * 'heStartChildWorkflowExecutionFailedEventAttributes'
--
-- * 'heChildWorkflowExecutionFailedEventAttributes'
--
-- * 'heFailWorkflowExecutionFailedEventAttributes'
--
-- * 'heContinueAsNewWorkflowExecutionFailedEventAttributes'
--
-- * 'heSignalExternalWorkflowExecutionInitiatedEventAttributes'
--
-- * 'heLambdaFunctionTimedOutEventAttributes'
--
-- * 'heWorkflowExecutionFailedEventAttributes'
--
-- * 'heWorkflowExecutionContinuedAsNewEventAttributes'
--
-- * 'heExternalWorkflowExecutionCancelRequestedEventAttributes'
--
-- * 'heEventTimestamp'
--
-- * 'heEventType'
--
-- * 'heEventId'
historyEvent
:: UTCTime -- ^ 'heEventTimestamp'
-> EventType -- ^ 'heEventType'
-> Integer -- ^ 'heEventId'
-> HistoryEvent
historyEvent pEventTimestamp_ pEventType_ pEventId_ =
HistoryEvent'
{ _heWorkflowExecutionCancelRequestedEventAttributes = Nothing
, _heRecordMarkerFailedEventAttributes = Nothing
, _heRequestCancelExternalWorkflowExecutionInitiatedEventAttributes = Nothing
, _heLambdaFunctionStartedEventAttributes = Nothing
, _heDecisionTaskScheduledEventAttributes = Nothing
, _heWorkflowExecutionCompletedEventAttributes = Nothing
, _heStartTimerFailedEventAttributes = Nothing
, _heActivityTaskScheduledEventAttributes = Nothing
, _heScheduleActivityTaskFailedEventAttributes = Nothing
, _heChildWorkflowExecutionCompletedEventAttributes = Nothing
, _heMarkerRecordedEventAttributes = Nothing
, _heScheduleLambdaFunctionFailedEventAttributes = Nothing
, _heCompleteWorkflowExecutionFailedEventAttributes = Nothing
, _heLambdaFunctionCompletedEventAttributes = Nothing
, _heRequestCancelExternalWorkflowExecutionFailedEventAttributes = Nothing
, _heTimerCanceledEventAttributes = Nothing
, _heWorkflowExecutionStartedEventAttributes = Nothing
, _heActivityTaskCompletedEventAttributes = Nothing
, _heDecisionTaskTimedOutEventAttributes = Nothing
, _heCancelTimerFailedEventAttributes = Nothing
, _heChildWorkflowExecutionStartedEventAttributes = Nothing
, _heActivityTaskCanceledEventAttributes = Nothing
, _heActivityTaskTimedOutEventAttributes = Nothing
, _heDecisionTaskStartedEventAttributes = Nothing
, _heWorkflowExecutionTerminatedEventAttributes = Nothing
, _heChildWorkflowExecutionCanceledEventAttributes = Nothing
, _heRequestCancelActivityTaskFailedEventAttributes = Nothing
, _heLambdaFunctionScheduledEventAttributes = Nothing
, _heChildWorkflowExecutionTimedOutEventAttributes = Nothing
, _heCancelWorkflowExecutionFailedEventAttributes = Nothing
, _heStartChildWorkflowExecutionInitiatedEventAttributes = Nothing
, _heSignalExternalWorkflowExecutionFailedEventAttributes = Nothing
, _heActivityTaskStartedEventAttributes = Nothing
, _heStartLambdaFunctionFailedEventAttributes = Nothing
, _heChildWorkflowExecutionTerminatedEventAttributes = Nothing
, _heLambdaFunctionFailedEventAttributes = Nothing
, _heWorkflowExecutionCanceledEventAttributes = Nothing
, _heTimerStartedEventAttributes = Nothing
, _heActivityTaskCancelRequestedEventAttributes = Nothing
, _heWorkflowExecutionTimedOutEventAttributes = Nothing
, _heWorkflowExecutionSignaledEventAttributes = Nothing
, _heTimerFiredEventAttributes = Nothing
, _heActivityTaskFailedEventAttributes = Nothing
, _heExternalWorkflowExecutionSignaledEventAttributes = Nothing
, _heDecisionTaskCompletedEventAttributes = Nothing
, _heStartChildWorkflowExecutionFailedEventAttributes = Nothing
, _heChildWorkflowExecutionFailedEventAttributes = Nothing
, _heFailWorkflowExecutionFailedEventAttributes = Nothing
, _heContinueAsNewWorkflowExecutionFailedEventAttributes = Nothing
, _heSignalExternalWorkflowExecutionInitiatedEventAttributes = Nothing
, _heLambdaFunctionTimedOutEventAttributes = Nothing
, _heWorkflowExecutionFailedEventAttributes = Nothing
, _heWorkflowExecutionContinuedAsNewEventAttributes = Nothing
, _heExternalWorkflowExecutionCancelRequestedEventAttributes = Nothing
, _heEventTimestamp = _Time # pEventTimestamp_
, _heEventType = pEventType_
, _heEventId = pEventId_
}
-- | If the event is of type 'WorkflowExecutionCancelRequested' then this
-- member is set and provides detailed information about the event. It is
-- not set for other event types.
heWorkflowExecutionCancelRequestedEventAttributes :: Lens' HistoryEvent (Maybe WorkflowExecutionCancelRequestedEventAttributes)
heWorkflowExecutionCancelRequestedEventAttributes = lens _heWorkflowExecutionCancelRequestedEventAttributes (\ s a -> s{_heWorkflowExecutionCancelRequestedEventAttributes = a});
-- | If the event is of type 'DecisionTaskFailed' then this member is set and
-- provides detailed information about the event. It is not set for other
-- event types.
heRecordMarkerFailedEventAttributes :: Lens' HistoryEvent (Maybe RecordMarkerFailedEventAttributes)
heRecordMarkerFailedEventAttributes = lens _heRecordMarkerFailedEventAttributes (\ s a -> s{_heRecordMarkerFailedEventAttributes = a});
-- | If the event is of type
-- 'RequestCancelExternalWorkflowExecutionInitiated' then this member is
-- set and provides detailed information about the event. It is not set for
-- other event types.
heRequestCancelExternalWorkflowExecutionInitiatedEventAttributes :: Lens' HistoryEvent (Maybe RequestCancelExternalWorkflowExecutionInitiatedEventAttributes)
heRequestCancelExternalWorkflowExecutionInitiatedEventAttributes = lens _heRequestCancelExternalWorkflowExecutionInitiatedEventAttributes (\ s a -> s{_heRequestCancelExternalWorkflowExecutionInitiatedEventAttributes = a});
-- | Undocumented member.
heLambdaFunctionStartedEventAttributes :: Lens' HistoryEvent (Maybe LambdaFunctionStartedEventAttributes)
heLambdaFunctionStartedEventAttributes = lens _heLambdaFunctionStartedEventAttributes (\ s a -> s{_heLambdaFunctionStartedEventAttributes = a});
-- | If the event is of type 'DecisionTaskScheduled' then this member is set
-- and provides detailed information about the event. It is not set for
-- other event types.
heDecisionTaskScheduledEventAttributes :: Lens' HistoryEvent (Maybe DecisionTaskScheduledEventAttributes)
heDecisionTaskScheduledEventAttributes = lens _heDecisionTaskScheduledEventAttributes (\ s a -> s{_heDecisionTaskScheduledEventAttributes = a});
-- | If the event is of type 'WorkflowExecutionCompleted' then this member is
-- set and provides detailed information about the event. It is not set for
-- other event types.
heWorkflowExecutionCompletedEventAttributes :: Lens' HistoryEvent (Maybe WorkflowExecutionCompletedEventAttributes)
heWorkflowExecutionCompletedEventAttributes = lens _heWorkflowExecutionCompletedEventAttributes (\ s a -> s{_heWorkflowExecutionCompletedEventAttributes = a});
-- | If the event is of type 'StartTimerFailed' then this member is set and
-- provides detailed information about the event. It is not set for other
-- event types.
heStartTimerFailedEventAttributes :: Lens' HistoryEvent (Maybe StartTimerFailedEventAttributes)
heStartTimerFailedEventAttributes = lens _heStartTimerFailedEventAttributes (\ s a -> s{_heStartTimerFailedEventAttributes = a});
-- | If the event is of type 'ActivityTaskScheduled' then this member is set
-- and provides detailed information about the event. It is not set for
-- other event types.
heActivityTaskScheduledEventAttributes :: Lens' HistoryEvent (Maybe ActivityTaskScheduledEventAttributes)
heActivityTaskScheduledEventAttributes = lens _heActivityTaskScheduledEventAttributes (\ s a -> s{_heActivityTaskScheduledEventAttributes = a});
-- | If the event is of type 'ScheduleActivityTaskFailed' then this member is
-- set and provides detailed information about the event. It is not set for
-- other event types.
heScheduleActivityTaskFailedEventAttributes :: Lens' HistoryEvent (Maybe ScheduleActivityTaskFailedEventAttributes)
heScheduleActivityTaskFailedEventAttributes = lens _heScheduleActivityTaskFailedEventAttributes (\ s a -> s{_heScheduleActivityTaskFailedEventAttributes = a});
-- | If the event is of type 'ChildWorkflowExecutionCompleted' then this
-- member is set and provides detailed information about the event. It is
-- not set for other event types.
heChildWorkflowExecutionCompletedEventAttributes :: Lens' HistoryEvent (Maybe ChildWorkflowExecutionCompletedEventAttributes)
heChildWorkflowExecutionCompletedEventAttributes = lens _heChildWorkflowExecutionCompletedEventAttributes (\ s a -> s{_heChildWorkflowExecutionCompletedEventAttributes = a});
-- | If the event is of type 'MarkerRecorded' then this member is set and
-- provides detailed information about the event. It is not set for other
-- event types.
heMarkerRecordedEventAttributes :: Lens' HistoryEvent (Maybe MarkerRecordedEventAttributes)
heMarkerRecordedEventAttributes = lens _heMarkerRecordedEventAttributes (\ s a -> s{_heMarkerRecordedEventAttributes = a});
-- | Undocumented member.
heScheduleLambdaFunctionFailedEventAttributes :: Lens' HistoryEvent (Maybe ScheduleLambdaFunctionFailedEventAttributes)
heScheduleLambdaFunctionFailedEventAttributes = lens _heScheduleLambdaFunctionFailedEventAttributes (\ s a -> s{_heScheduleLambdaFunctionFailedEventAttributes = a});
-- | If the event is of type 'CompleteWorkflowExecutionFailed' then this
-- member is set and provides detailed information about the event. It is
-- not set for other event types.
heCompleteWorkflowExecutionFailedEventAttributes :: Lens' HistoryEvent (Maybe CompleteWorkflowExecutionFailedEventAttributes)
heCompleteWorkflowExecutionFailedEventAttributes = lens _heCompleteWorkflowExecutionFailedEventAttributes (\ s a -> s{_heCompleteWorkflowExecutionFailedEventAttributes = a});
-- | Undocumented member.
heLambdaFunctionCompletedEventAttributes :: Lens' HistoryEvent (Maybe LambdaFunctionCompletedEventAttributes)
heLambdaFunctionCompletedEventAttributes = lens _heLambdaFunctionCompletedEventAttributes (\ s a -> s{_heLambdaFunctionCompletedEventAttributes = a});
-- | If the event is of type 'RequestCancelExternalWorkflowExecutionFailed'
-- then this member is set and provides detailed information about the
-- event. It is not set for other event types.
heRequestCancelExternalWorkflowExecutionFailedEventAttributes :: Lens' HistoryEvent (Maybe RequestCancelExternalWorkflowExecutionFailedEventAttributes)
heRequestCancelExternalWorkflowExecutionFailedEventAttributes = lens _heRequestCancelExternalWorkflowExecutionFailedEventAttributes (\ s a -> s{_heRequestCancelExternalWorkflowExecutionFailedEventAttributes = a});
-- | If the event is of type 'TimerCanceled' then this member is set and
-- provides detailed information about the event. It is not set for other
-- event types.
heTimerCanceledEventAttributes :: Lens' HistoryEvent (Maybe TimerCanceledEventAttributes)
heTimerCanceledEventAttributes = lens _heTimerCanceledEventAttributes (\ s a -> s{_heTimerCanceledEventAttributes = a});
-- | If the event is of type 'WorkflowExecutionStarted' then this member is
-- set and provides detailed information about the event. It is not set for
-- other event types.
heWorkflowExecutionStartedEventAttributes :: Lens' HistoryEvent (Maybe WorkflowExecutionStartedEventAttributes)
heWorkflowExecutionStartedEventAttributes = lens _heWorkflowExecutionStartedEventAttributes (\ s a -> s{_heWorkflowExecutionStartedEventAttributes = a});
-- | If the event is of type 'ActivityTaskCompleted' then this member is set
-- and provides detailed information about the event. It is not set for
-- other event types.
heActivityTaskCompletedEventAttributes :: Lens' HistoryEvent (Maybe ActivityTaskCompletedEventAttributes)
heActivityTaskCompletedEventAttributes = lens _heActivityTaskCompletedEventAttributes (\ s a -> s{_heActivityTaskCompletedEventAttributes = a});
-- | If the event is of type 'DecisionTaskTimedOut' then this member is set
-- and provides detailed information about the event. It is not set for
-- other event types.
heDecisionTaskTimedOutEventAttributes :: Lens' HistoryEvent (Maybe DecisionTaskTimedOutEventAttributes)
heDecisionTaskTimedOutEventAttributes = lens _heDecisionTaskTimedOutEventAttributes (\ s a -> s{_heDecisionTaskTimedOutEventAttributes = a});
-- | If the event is of type 'CancelTimerFailed' then this member is set and
-- provides detailed information about the event. It is not set for other
-- event types.
heCancelTimerFailedEventAttributes :: Lens' HistoryEvent (Maybe CancelTimerFailedEventAttributes)
heCancelTimerFailedEventAttributes = lens _heCancelTimerFailedEventAttributes (\ s a -> s{_heCancelTimerFailedEventAttributes = a});
-- | If the event is of type 'ChildWorkflowExecutionStarted' then this member
-- is set and provides detailed information about the event. It is not set
-- for other event types.
heChildWorkflowExecutionStartedEventAttributes :: Lens' HistoryEvent (Maybe ChildWorkflowExecutionStartedEventAttributes)
heChildWorkflowExecutionStartedEventAttributes = lens _heChildWorkflowExecutionStartedEventAttributes (\ s a -> s{_heChildWorkflowExecutionStartedEventAttributes = a});
-- | If the event is of type 'ActivityTaskCanceled' then this member is set
-- and provides detailed information about the event. It is not set for
-- other event types.
heActivityTaskCanceledEventAttributes :: Lens' HistoryEvent (Maybe ActivityTaskCanceledEventAttributes)
heActivityTaskCanceledEventAttributes = lens _heActivityTaskCanceledEventAttributes (\ s a -> s{_heActivityTaskCanceledEventAttributes = a});
-- | If the event is of type 'ActivityTaskTimedOut' then this member is set
-- and provides detailed information about the event. It is not set for
-- other event types.
heActivityTaskTimedOutEventAttributes :: Lens' HistoryEvent (Maybe ActivityTaskTimedOutEventAttributes)
heActivityTaskTimedOutEventAttributes = lens _heActivityTaskTimedOutEventAttributes (\ s a -> s{_heActivityTaskTimedOutEventAttributes = a});
-- | If the event is of type 'DecisionTaskStarted' then this member is set
-- and provides detailed information about the event. It is not set for
-- other event types.
heDecisionTaskStartedEventAttributes :: Lens' HistoryEvent (Maybe DecisionTaskStartedEventAttributes)
heDecisionTaskStartedEventAttributes = lens _heDecisionTaskStartedEventAttributes (\ s a -> s{_heDecisionTaskStartedEventAttributes = a});
-- | If the event is of type 'WorkflowExecutionTerminated' then this member
-- is set and provides detailed information about the event. It is not set
-- for other event types.
heWorkflowExecutionTerminatedEventAttributes :: Lens' HistoryEvent (Maybe WorkflowExecutionTerminatedEventAttributes)
heWorkflowExecutionTerminatedEventAttributes = lens _heWorkflowExecutionTerminatedEventAttributes (\ s a -> s{_heWorkflowExecutionTerminatedEventAttributes = a});
-- | If the event is of type 'ChildWorkflowExecutionCanceled' then this
-- member is set and provides detailed information about the event. It is
-- not set for other event types.
heChildWorkflowExecutionCanceledEventAttributes :: Lens' HistoryEvent (Maybe ChildWorkflowExecutionCanceledEventAttributes)
heChildWorkflowExecutionCanceledEventAttributes = lens _heChildWorkflowExecutionCanceledEventAttributes (\ s a -> s{_heChildWorkflowExecutionCanceledEventAttributes = a});
-- | If the event is of type 'RequestCancelActivityTaskFailed' then this
-- member is set and provides detailed information about the event. It is
-- not set for other event types.
heRequestCancelActivityTaskFailedEventAttributes :: Lens' HistoryEvent (Maybe RequestCancelActivityTaskFailedEventAttributes)
heRequestCancelActivityTaskFailedEventAttributes = lens _heRequestCancelActivityTaskFailedEventAttributes (\ s a -> s{_heRequestCancelActivityTaskFailedEventAttributes = a});
-- | Undocumented member.
heLambdaFunctionScheduledEventAttributes :: Lens' HistoryEvent (Maybe LambdaFunctionScheduledEventAttributes)
heLambdaFunctionScheduledEventAttributes = lens _heLambdaFunctionScheduledEventAttributes (\ s a -> s{_heLambdaFunctionScheduledEventAttributes = a});
-- | If the event is of type 'ChildWorkflowExecutionTimedOut' then this
-- member is set and provides detailed information about the event. It is
-- not set for other event types.
heChildWorkflowExecutionTimedOutEventAttributes :: Lens' HistoryEvent (Maybe ChildWorkflowExecutionTimedOutEventAttributes)
heChildWorkflowExecutionTimedOutEventAttributes = lens _heChildWorkflowExecutionTimedOutEventAttributes (\ s a -> s{_heChildWorkflowExecutionTimedOutEventAttributes = a});
-- | If the event is of type 'CancelWorkflowExecutionFailed' then this member
-- is set and provides detailed information about the event. It is not set
-- for other event types.
heCancelWorkflowExecutionFailedEventAttributes :: Lens' HistoryEvent (Maybe CancelWorkflowExecutionFailedEventAttributes)
heCancelWorkflowExecutionFailedEventAttributes = lens _heCancelWorkflowExecutionFailedEventAttributes (\ s a -> s{_heCancelWorkflowExecutionFailedEventAttributes = a});
-- | If the event is of type 'StartChildWorkflowExecutionInitiated' then this
-- member is set and provides detailed information about the event. It is
-- not set for other event types.
heStartChildWorkflowExecutionInitiatedEventAttributes :: Lens' HistoryEvent (Maybe StartChildWorkflowExecutionInitiatedEventAttributes)
heStartChildWorkflowExecutionInitiatedEventAttributes = lens _heStartChildWorkflowExecutionInitiatedEventAttributes (\ s a -> s{_heStartChildWorkflowExecutionInitiatedEventAttributes = a});
-- | If the event is of type 'SignalExternalWorkflowExecutionFailed' then
-- this member is set and provides detailed information about the event. It
-- is not set for other event types.
heSignalExternalWorkflowExecutionFailedEventAttributes :: Lens' HistoryEvent (Maybe SignalExternalWorkflowExecutionFailedEventAttributes)
heSignalExternalWorkflowExecutionFailedEventAttributes = lens _heSignalExternalWorkflowExecutionFailedEventAttributes (\ s a -> s{_heSignalExternalWorkflowExecutionFailedEventAttributes = a});
-- | If the event is of type 'ActivityTaskStarted' then this member is set
-- and provides detailed information about the event. It is not set for
-- other event types.
heActivityTaskStartedEventAttributes :: Lens' HistoryEvent (Maybe ActivityTaskStartedEventAttributes)
heActivityTaskStartedEventAttributes = lens _heActivityTaskStartedEventAttributes (\ s a -> s{_heActivityTaskStartedEventAttributes = a});
-- | Undocumented member.
heStartLambdaFunctionFailedEventAttributes :: Lens' HistoryEvent (Maybe StartLambdaFunctionFailedEventAttributes)
heStartLambdaFunctionFailedEventAttributes = lens _heStartLambdaFunctionFailedEventAttributes (\ s a -> s{_heStartLambdaFunctionFailedEventAttributes = a});
-- | If the event is of type 'ChildWorkflowExecutionTerminated' then this
-- member is set and provides detailed information about the event. It is
-- not set for other event types.
heChildWorkflowExecutionTerminatedEventAttributes :: Lens' HistoryEvent (Maybe ChildWorkflowExecutionTerminatedEventAttributes)
heChildWorkflowExecutionTerminatedEventAttributes = lens _heChildWorkflowExecutionTerminatedEventAttributes (\ s a -> s{_heChildWorkflowExecutionTerminatedEventAttributes = a});
-- | Undocumented member.
heLambdaFunctionFailedEventAttributes :: Lens' HistoryEvent (Maybe LambdaFunctionFailedEventAttributes)
heLambdaFunctionFailedEventAttributes = lens _heLambdaFunctionFailedEventAttributes (\ s a -> s{_heLambdaFunctionFailedEventAttributes = a});
-- | If the event is of type 'WorkflowExecutionCanceled' then this member is
-- set and provides detailed information about the event. It is not set for
-- other event types.
heWorkflowExecutionCanceledEventAttributes :: Lens' HistoryEvent (Maybe WorkflowExecutionCanceledEventAttributes)
heWorkflowExecutionCanceledEventAttributes = lens _heWorkflowExecutionCanceledEventAttributes (\ s a -> s{_heWorkflowExecutionCanceledEventAttributes = a});
-- | If the event is of type 'TimerStarted' then this member is set and
-- provides detailed information about the event. It is not set for other
-- event types.
heTimerStartedEventAttributes :: Lens' HistoryEvent (Maybe TimerStartedEventAttributes)
heTimerStartedEventAttributes = lens _heTimerStartedEventAttributes (\ s a -> s{_heTimerStartedEventAttributes = a});
-- | If the event is of type 'ActivityTaskcancelRequested' then this member
-- is set and provides detailed information about the event. It is not set
-- for other event types.
heActivityTaskCancelRequestedEventAttributes :: Lens' HistoryEvent (Maybe ActivityTaskCancelRequestedEventAttributes)
heActivityTaskCancelRequestedEventAttributes = lens _heActivityTaskCancelRequestedEventAttributes (\ s a -> s{_heActivityTaskCancelRequestedEventAttributes = a});
-- | If the event is of type 'WorkflowExecutionTimedOut' then this member is
-- set and provides detailed information about the event. It is not set for
-- other event types.
heWorkflowExecutionTimedOutEventAttributes :: Lens' HistoryEvent (Maybe WorkflowExecutionTimedOutEventAttributes)
heWorkflowExecutionTimedOutEventAttributes = lens _heWorkflowExecutionTimedOutEventAttributes (\ s a -> s{_heWorkflowExecutionTimedOutEventAttributes = a});
-- | If the event is of type 'WorkflowExecutionSignaled' then this member is
-- set and provides detailed information about the event. It is not set for
-- other event types.
heWorkflowExecutionSignaledEventAttributes :: Lens' HistoryEvent (Maybe WorkflowExecutionSignaledEventAttributes)
heWorkflowExecutionSignaledEventAttributes = lens _heWorkflowExecutionSignaledEventAttributes (\ s a -> s{_heWorkflowExecutionSignaledEventAttributes = a});
-- | If the event is of type 'TimerFired' then this member is set and
-- provides detailed information about the event. It is not set for other
-- event types.
heTimerFiredEventAttributes :: Lens' HistoryEvent (Maybe TimerFiredEventAttributes)
heTimerFiredEventAttributes = lens _heTimerFiredEventAttributes (\ s a -> s{_heTimerFiredEventAttributes = a});
-- | If the event is of type 'ActivityTaskFailed' then this member is set and
-- provides detailed information about the event. It is not set for other
-- event types.
heActivityTaskFailedEventAttributes :: Lens' HistoryEvent (Maybe ActivityTaskFailedEventAttributes)
heActivityTaskFailedEventAttributes = lens _heActivityTaskFailedEventAttributes (\ s a -> s{_heActivityTaskFailedEventAttributes = a});
-- | If the event is of type 'ExternalWorkflowExecutionSignaled' then this
-- member is set and provides detailed information about the event. It is
-- not set for other event types.
heExternalWorkflowExecutionSignaledEventAttributes :: Lens' HistoryEvent (Maybe ExternalWorkflowExecutionSignaledEventAttributes)
heExternalWorkflowExecutionSignaledEventAttributes = lens _heExternalWorkflowExecutionSignaledEventAttributes (\ s a -> s{_heExternalWorkflowExecutionSignaledEventAttributes = a});
-- | If the event is of type 'DecisionTaskCompleted' then this member is set
-- and provides detailed information about the event. It is not set for
-- other event types.
heDecisionTaskCompletedEventAttributes :: Lens' HistoryEvent (Maybe DecisionTaskCompletedEventAttributes)
heDecisionTaskCompletedEventAttributes = lens _heDecisionTaskCompletedEventAttributes (\ s a -> s{_heDecisionTaskCompletedEventAttributes = a});
-- | If the event is of type 'StartChildWorkflowExecutionFailed' then this
-- member is set and provides detailed information about the event. It is
-- not set for other event types.
heStartChildWorkflowExecutionFailedEventAttributes :: Lens' HistoryEvent (Maybe StartChildWorkflowExecutionFailedEventAttributes)
heStartChildWorkflowExecutionFailedEventAttributes = lens _heStartChildWorkflowExecutionFailedEventAttributes (\ s a -> s{_heStartChildWorkflowExecutionFailedEventAttributes = a});
-- | If the event is of type 'ChildWorkflowExecutionFailed' then this member
-- is set and provides detailed information about the event. It is not set
-- for other event types.
heChildWorkflowExecutionFailedEventAttributes :: Lens' HistoryEvent (Maybe ChildWorkflowExecutionFailedEventAttributes)
heChildWorkflowExecutionFailedEventAttributes = lens _heChildWorkflowExecutionFailedEventAttributes (\ s a -> s{_heChildWorkflowExecutionFailedEventAttributes = a});
-- | If the event is of type 'FailWorkflowExecutionFailed' then this member
-- is set and provides detailed information about the event. It is not set
-- for other event types.
heFailWorkflowExecutionFailedEventAttributes :: Lens' HistoryEvent (Maybe FailWorkflowExecutionFailedEventAttributes)
heFailWorkflowExecutionFailedEventAttributes = lens _heFailWorkflowExecutionFailedEventAttributes (\ s a -> s{_heFailWorkflowExecutionFailedEventAttributes = a});
-- | If the event is of type 'ContinueAsNewWorkflowExecutionFailed' then this
-- member is set and provides detailed information about the event. It is
-- not set for other event types.
heContinueAsNewWorkflowExecutionFailedEventAttributes :: Lens' HistoryEvent (Maybe ContinueAsNewWorkflowExecutionFailedEventAttributes)
heContinueAsNewWorkflowExecutionFailedEventAttributes = lens _heContinueAsNewWorkflowExecutionFailedEventAttributes (\ s a -> s{_heContinueAsNewWorkflowExecutionFailedEventAttributes = a});
-- | If the event is of type 'SignalExternalWorkflowExecutionInitiated' then
-- this member is set and provides detailed information about the event. It
-- is not set for other event types.
heSignalExternalWorkflowExecutionInitiatedEventAttributes :: Lens' HistoryEvent (Maybe SignalExternalWorkflowExecutionInitiatedEventAttributes)
heSignalExternalWorkflowExecutionInitiatedEventAttributes = lens _heSignalExternalWorkflowExecutionInitiatedEventAttributes (\ s a -> s{_heSignalExternalWorkflowExecutionInitiatedEventAttributes = a});
-- | Undocumented member.
heLambdaFunctionTimedOutEventAttributes :: Lens' HistoryEvent (Maybe LambdaFunctionTimedOutEventAttributes)
heLambdaFunctionTimedOutEventAttributes = lens _heLambdaFunctionTimedOutEventAttributes (\ s a -> s{_heLambdaFunctionTimedOutEventAttributes = a});
-- | If the event is of type 'WorkflowExecutionFailed' then this member is
-- set and provides detailed information about the event. It is not set for
-- other event types.
heWorkflowExecutionFailedEventAttributes :: Lens' HistoryEvent (Maybe WorkflowExecutionFailedEventAttributes)
heWorkflowExecutionFailedEventAttributes = lens _heWorkflowExecutionFailedEventAttributes (\ s a -> s{_heWorkflowExecutionFailedEventAttributes = a});
-- | If the event is of type 'WorkflowExecutionContinuedAsNew' then this
-- member is set and provides detailed information about the event. It is
-- not set for other event types.
heWorkflowExecutionContinuedAsNewEventAttributes :: Lens' HistoryEvent (Maybe WorkflowExecutionContinuedAsNewEventAttributes)
heWorkflowExecutionContinuedAsNewEventAttributes = lens _heWorkflowExecutionContinuedAsNewEventAttributes (\ s a -> s{_heWorkflowExecutionContinuedAsNewEventAttributes = a});
-- | If the event is of type 'ExternalWorkflowExecutionCancelRequested' then
-- this member is set and provides detailed information about the event. It
-- is not set for other event types.
heExternalWorkflowExecutionCancelRequestedEventAttributes :: Lens' HistoryEvent (Maybe ExternalWorkflowExecutionCancelRequestedEventAttributes)
heExternalWorkflowExecutionCancelRequestedEventAttributes = lens _heExternalWorkflowExecutionCancelRequestedEventAttributes (\ s a -> s{_heExternalWorkflowExecutionCancelRequestedEventAttributes = a});
-- | The date and time when the event occurred.
heEventTimestamp :: Lens' HistoryEvent UTCTime
heEventTimestamp = lens _heEventTimestamp (\ s a -> s{_heEventTimestamp = a}) . _Time;
-- | The type of the history event.
heEventType :: Lens' HistoryEvent EventType
heEventType = lens _heEventType (\ s a -> s{_heEventType = a});
-- | The system generated ID of the event. This ID uniquely identifies the
-- event with in the workflow execution history.
heEventId :: Lens' HistoryEvent Integer
heEventId = lens _heEventId (\ s a -> s{_heEventId = a});
instance FromJSON HistoryEvent where
parseJSON
= withObject "HistoryEvent"
(\ x ->
HistoryEvent' <$>
(x .:?
"workflowExecutionCancelRequestedEventAttributes")
<*> (x .:? "recordMarkerFailedEventAttributes")
<*>
(x .:?
"requestCancelExternalWorkflowExecutionInitiatedEventAttributes")
<*> (x .:? "lambdaFunctionStartedEventAttributes")
<*> (x .:? "decisionTaskScheduledEventAttributes")
<*>
(x .:? "workflowExecutionCompletedEventAttributes")
<*> (x .:? "startTimerFailedEventAttributes")
<*> (x .:? "activityTaskScheduledEventAttributes")
<*>
(x .:? "scheduleActivityTaskFailedEventAttributes")
<*>
(x .:?
"childWorkflowExecutionCompletedEventAttributes")
<*> (x .:? "markerRecordedEventAttributes")
<*>
(x .:? "scheduleLambdaFunctionFailedEventAttributes")
<*>
(x .:?
"completeWorkflowExecutionFailedEventAttributes")
<*> (x .:? "lambdaFunctionCompletedEventAttributes")
<*>
(x .:?
"requestCancelExternalWorkflowExecutionFailedEventAttributes")
<*> (x .:? "timerCanceledEventAttributes")
<*> (x .:? "workflowExecutionStartedEventAttributes")
<*> (x .:? "activityTaskCompletedEventAttributes")
<*> (x .:? "decisionTaskTimedOutEventAttributes")
<*> (x .:? "cancelTimerFailedEventAttributes")
<*>
(x .:?
"childWorkflowExecutionStartedEventAttributes")
<*> (x .:? "activityTaskCanceledEventAttributes")
<*> (x .:? "activityTaskTimedOutEventAttributes")
<*> (x .:? "decisionTaskStartedEventAttributes")
<*>
(x .:? "workflowExecutionTerminatedEventAttributes")
<*>
(x .:?
"childWorkflowExecutionCanceledEventAttributes")
<*>
(x .:?
"requestCancelActivityTaskFailedEventAttributes")
<*> (x .:? "lambdaFunctionScheduledEventAttributes")
<*>
(x .:?
"childWorkflowExecutionTimedOutEventAttributes")
<*>
(x .:?
"cancelWorkflowExecutionFailedEventAttributes")
<*>
(x .:?
"startChildWorkflowExecutionInitiatedEventAttributes")
<*>
(x .:?
"signalExternalWorkflowExecutionFailedEventAttributes")
<*> (x .:? "activityTaskStartedEventAttributes")
<*>
(x .:? "startLambdaFunctionFailedEventAttributes")
<*>
(x .:?
"childWorkflowExecutionTerminatedEventAttributes")
<*> (x .:? "lambdaFunctionFailedEventAttributes")
<*>
(x .:? "workflowExecutionCanceledEventAttributes")
<*> (x .:? "timerStartedEventAttributes")
<*>
(x .:? "activityTaskCancelRequestedEventAttributes")
<*>
(x .:? "workflowExecutionTimedOutEventAttributes")
<*>
(x .:? "workflowExecutionSignaledEventAttributes")
<*> (x .:? "timerFiredEventAttributes")
<*> (x .:? "activityTaskFailedEventAttributes")
<*>
(x .:?
"externalWorkflowExecutionSignaledEventAttributes")
<*> (x .:? "decisionTaskCompletedEventAttributes")
<*>
(x .:?
"startChildWorkflowExecutionFailedEventAttributes")
<*>
(x .:? "childWorkflowExecutionFailedEventAttributes")
<*>
(x .:? "failWorkflowExecutionFailedEventAttributes")
<*>
(x .:?
"continueAsNewWorkflowExecutionFailedEventAttributes")
<*>
(x .:?
"signalExternalWorkflowExecutionInitiatedEventAttributes")
<*> (x .:? "lambdaFunctionTimedOutEventAttributes")
<*> (x .:? "workflowExecutionFailedEventAttributes")
<*>
(x .:?
"workflowExecutionContinuedAsNewEventAttributes")
<*>
(x .:?
"externalWorkflowExecutionCancelRequestedEventAttributes")
<*> (x .: "eventTimestamp")
<*> (x .: "eventType")
<*> (x .: "eventId"))
-- | Provides details for the 'LambdaFunctionCompleted' event.
--
-- /See:/ 'lambdaFunctionCompletedEventAttributes' smart constructor.
data LambdaFunctionCompletedEventAttributes = LambdaFunctionCompletedEventAttributes'
{ _lfceaResult :: !(Maybe Text)
, _lfceaScheduledEventId :: !Integer
, _lfceaStartedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'LambdaFunctionCompletedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lfceaResult'
--
-- * 'lfceaScheduledEventId'
--
-- * 'lfceaStartedEventId'
lambdaFunctionCompletedEventAttributes
:: Integer -- ^ 'lfceaScheduledEventId'
-> Integer -- ^ 'lfceaStartedEventId'
-> LambdaFunctionCompletedEventAttributes
lambdaFunctionCompletedEventAttributes pScheduledEventId_ pStartedEventId_ =
LambdaFunctionCompletedEventAttributes'
{ _lfceaResult = Nothing
, _lfceaScheduledEventId = pScheduledEventId_
, _lfceaStartedEventId = pStartedEventId_
}
-- | The result of the function execution (if any).
lfceaResult :: Lens' LambdaFunctionCompletedEventAttributes (Maybe Text)
lfceaResult = lens _lfceaResult (\ s a -> s{_lfceaResult = a});
-- | The ID of the 'LambdaFunctionScheduled' event that was recorded when
-- this AWS Lambda function was scheduled. This information can be useful
-- for diagnosing problems by tracing back the chain of events leading up
-- to this event.
lfceaScheduledEventId :: Lens' LambdaFunctionCompletedEventAttributes Integer
lfceaScheduledEventId = lens _lfceaScheduledEventId (\ s a -> s{_lfceaScheduledEventId = a});
-- | The ID of the 'LambdaFunctionStarted' event recorded in the history.
lfceaStartedEventId :: Lens' LambdaFunctionCompletedEventAttributes Integer
lfceaStartedEventId = lens _lfceaStartedEventId (\ s a -> s{_lfceaStartedEventId = a});
instance FromJSON
LambdaFunctionCompletedEventAttributes where
parseJSON
= withObject "LambdaFunctionCompletedEventAttributes"
(\ x ->
LambdaFunctionCompletedEventAttributes' <$>
(x .:? "result") <*> (x .: "scheduledEventId") <*>
(x .: "startedEventId"))
-- | Provides details for the 'LambdaFunctionFailed' event.
--
-- /See:/ 'lambdaFunctionFailedEventAttributes' smart constructor.
data LambdaFunctionFailedEventAttributes = LambdaFunctionFailedEventAttributes'
{ _lffeaReason :: !(Maybe Text)
, _lffeaDetails :: !(Maybe Text)
, _lffeaScheduledEventId :: !Integer
, _lffeaStartedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'LambdaFunctionFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lffeaReason'
--
-- * 'lffeaDetails'
--
-- * 'lffeaScheduledEventId'
--
-- * 'lffeaStartedEventId'
lambdaFunctionFailedEventAttributes
:: Integer -- ^ 'lffeaScheduledEventId'
-> Integer -- ^ 'lffeaStartedEventId'
-> LambdaFunctionFailedEventAttributes
lambdaFunctionFailedEventAttributes pScheduledEventId_ pStartedEventId_ =
LambdaFunctionFailedEventAttributes'
{ _lffeaReason = Nothing
, _lffeaDetails = Nothing
, _lffeaScheduledEventId = pScheduledEventId_
, _lffeaStartedEventId = pStartedEventId_
}
-- | The reason provided for the failure (if any).
lffeaReason :: Lens' LambdaFunctionFailedEventAttributes (Maybe Text)
lffeaReason = lens _lffeaReason (\ s a -> s{_lffeaReason = a});
-- | The details of the failure (if any).
lffeaDetails :: Lens' LambdaFunctionFailedEventAttributes (Maybe Text)
lffeaDetails = lens _lffeaDetails (\ s a -> s{_lffeaDetails = a});
-- | The ID of the 'LambdaFunctionScheduled' event that was recorded when
-- this AWS Lambda function was scheduled. This information can be useful
-- for diagnosing problems by tracing back the chain of events leading up
-- to this event.
lffeaScheduledEventId :: Lens' LambdaFunctionFailedEventAttributes Integer
lffeaScheduledEventId = lens _lffeaScheduledEventId (\ s a -> s{_lffeaScheduledEventId = a});
-- | The ID of the 'LambdaFunctionStarted' event recorded in the history.
lffeaStartedEventId :: Lens' LambdaFunctionFailedEventAttributes Integer
lffeaStartedEventId = lens _lffeaStartedEventId (\ s a -> s{_lffeaStartedEventId = a});
instance FromJSON LambdaFunctionFailedEventAttributes
where
parseJSON
= withObject "LambdaFunctionFailedEventAttributes"
(\ x ->
LambdaFunctionFailedEventAttributes' <$>
(x .:? "reason") <*> (x .:? "details") <*>
(x .: "scheduledEventId")
<*> (x .: "startedEventId"))
-- | Provides details for the 'LambdaFunctionScheduled' event.
--
-- /See:/ 'lambdaFunctionScheduledEventAttributes' smart constructor.
data LambdaFunctionScheduledEventAttributes = LambdaFunctionScheduledEventAttributes'
{ _lfseaInput :: !(Maybe Text)
, _lfseaStartToCloseTimeout :: !(Maybe Text)
, _lfseaId :: !Text
, _lfseaName :: !Text
, _lfseaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'LambdaFunctionScheduledEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lfseaInput'
--
-- * 'lfseaStartToCloseTimeout'
--
-- * 'lfseaId'
--
-- * 'lfseaName'
--
-- * 'lfseaDecisionTaskCompletedEventId'
lambdaFunctionScheduledEventAttributes
:: Text -- ^ 'lfseaId'
-> Text -- ^ 'lfseaName'
-> Integer -- ^ 'lfseaDecisionTaskCompletedEventId'
-> LambdaFunctionScheduledEventAttributes
lambdaFunctionScheduledEventAttributes pId_ pName_ pDecisionTaskCompletedEventId_ =
LambdaFunctionScheduledEventAttributes'
{ _lfseaInput = Nothing
, _lfseaStartToCloseTimeout = Nothing
, _lfseaId = pId_
, _lfseaName = pName_
, _lfseaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | Input provided to the AWS Lambda function.
lfseaInput :: Lens' LambdaFunctionScheduledEventAttributes (Maybe Text)
lfseaInput = lens _lfseaInput (\ s a -> s{_lfseaInput = a});
-- | The maximum time, in seconds, that the AWS Lambda function can take to
-- execute from start to close before it is marked as failed.
lfseaStartToCloseTimeout :: Lens' LambdaFunctionScheduledEventAttributes (Maybe Text)
lfseaStartToCloseTimeout = lens _lfseaStartToCloseTimeout (\ s a -> s{_lfseaStartToCloseTimeout = a});
-- | The unique Amazon SWF ID for the AWS Lambda task.
lfseaId :: Lens' LambdaFunctionScheduledEventAttributes Text
lfseaId = lens _lfseaId (\ s a -> s{_lfseaId = a});
-- | The name of the scheduled AWS Lambda function.
lfseaName :: Lens' LambdaFunctionScheduledEventAttributes Text
lfseaName = lens _lfseaName (\ s a -> s{_lfseaName = a});
-- | The ID of the 'DecisionTaskCompleted' event for the decision that
-- resulted in the scheduling of this AWS Lambda function. This information
-- can be useful for diagnosing problems by tracing back the chain of
-- events leading up to this event.
lfseaDecisionTaskCompletedEventId :: Lens' LambdaFunctionScheduledEventAttributes Integer
lfseaDecisionTaskCompletedEventId = lens _lfseaDecisionTaskCompletedEventId (\ s a -> s{_lfseaDecisionTaskCompletedEventId = a});
instance FromJSON
LambdaFunctionScheduledEventAttributes where
parseJSON
= withObject "LambdaFunctionScheduledEventAttributes"
(\ x ->
LambdaFunctionScheduledEventAttributes' <$>
(x .:? "input") <*> (x .:? "startToCloseTimeout") <*>
(x .: "id")
<*> (x .: "name")
<*> (x .: "decisionTaskCompletedEventId"))
-- | Provides details for the 'LambdaFunctionStarted' event.
--
-- /See:/ 'lambdaFunctionStartedEventAttributes' smart constructor.
newtype LambdaFunctionStartedEventAttributes = LambdaFunctionStartedEventAttributes'
{ _lfseaScheduledEventId :: Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'LambdaFunctionStartedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lfseaScheduledEventId'
lambdaFunctionStartedEventAttributes
:: Integer -- ^ 'lfseaScheduledEventId'
-> LambdaFunctionStartedEventAttributes
lambdaFunctionStartedEventAttributes pScheduledEventId_ =
LambdaFunctionStartedEventAttributes'
{ _lfseaScheduledEventId = pScheduledEventId_
}
-- | The ID of the 'LambdaFunctionScheduled' event that was recorded when
-- this AWS Lambda function was scheduled. This information can be useful
-- for diagnosing problems by tracing back the chain of events leading up
-- to this event.
lfseaScheduledEventId :: Lens' LambdaFunctionStartedEventAttributes Integer
lfseaScheduledEventId = lens _lfseaScheduledEventId (\ s a -> s{_lfseaScheduledEventId = a});
instance FromJSON
LambdaFunctionStartedEventAttributes where
parseJSON
= withObject "LambdaFunctionStartedEventAttributes"
(\ x ->
LambdaFunctionStartedEventAttributes' <$>
(x .: "scheduledEventId"))
-- | Provides details for the 'LambdaFunctionTimedOut' event.
--
-- /See:/ 'lambdaFunctionTimedOutEventAttributes' smart constructor.
data LambdaFunctionTimedOutEventAttributes = LambdaFunctionTimedOutEventAttributes'
{ _lftoeaTimeoutType :: !(Maybe LambdaFunctionTimeoutType)
, _lftoeaScheduledEventId :: !Integer
, _lftoeaStartedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'LambdaFunctionTimedOutEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lftoeaTimeoutType'
--
-- * 'lftoeaScheduledEventId'
--
-- * 'lftoeaStartedEventId'
lambdaFunctionTimedOutEventAttributes
:: Integer -- ^ 'lftoeaScheduledEventId'
-> Integer -- ^ 'lftoeaStartedEventId'
-> LambdaFunctionTimedOutEventAttributes
lambdaFunctionTimedOutEventAttributes pScheduledEventId_ pStartedEventId_ =
LambdaFunctionTimedOutEventAttributes'
{ _lftoeaTimeoutType = Nothing
, _lftoeaScheduledEventId = pScheduledEventId_
, _lftoeaStartedEventId = pStartedEventId_
}
-- | The type of the timeout that caused this event.
lftoeaTimeoutType :: Lens' LambdaFunctionTimedOutEventAttributes (Maybe LambdaFunctionTimeoutType)
lftoeaTimeoutType = lens _lftoeaTimeoutType (\ s a -> s{_lftoeaTimeoutType = a});
-- | The ID of the 'LambdaFunctionScheduled' event that was recorded when
-- this AWS Lambda function was scheduled. This information can be useful
-- for diagnosing problems by tracing back the chain of events leading up
-- to this event.
lftoeaScheduledEventId :: Lens' LambdaFunctionTimedOutEventAttributes Integer
lftoeaScheduledEventId = lens _lftoeaScheduledEventId (\ s a -> s{_lftoeaScheduledEventId = a});
-- | The ID of the 'LambdaFunctionStarted' event recorded in the history.
lftoeaStartedEventId :: Lens' LambdaFunctionTimedOutEventAttributes Integer
lftoeaStartedEventId = lens _lftoeaStartedEventId (\ s a -> s{_lftoeaStartedEventId = a});
instance FromJSON
LambdaFunctionTimedOutEventAttributes where
parseJSON
= withObject "LambdaFunctionTimedOutEventAttributes"
(\ x ->
LambdaFunctionTimedOutEventAttributes' <$>
(x .:? "timeoutType") <*> (x .: "scheduledEventId")
<*> (x .: "startedEventId"))
-- | Provides details of the 'MarkerRecorded' event.
--
-- /See:/ 'markerRecordedEventAttributes' smart constructor.
data MarkerRecordedEventAttributes = MarkerRecordedEventAttributes'
{ _mreaDetails :: !(Maybe Text)
, _mreaMarkerName :: !Text
, _mreaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'MarkerRecordedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mreaDetails'
--
-- * 'mreaMarkerName'
--
-- * 'mreaDecisionTaskCompletedEventId'
markerRecordedEventAttributes
:: Text -- ^ 'mreaMarkerName'
-> Integer -- ^ 'mreaDecisionTaskCompletedEventId'
-> MarkerRecordedEventAttributes
markerRecordedEventAttributes pMarkerName_ pDecisionTaskCompletedEventId_ =
MarkerRecordedEventAttributes'
{ _mreaDetails = Nothing
, _mreaMarkerName = pMarkerName_
, _mreaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | Details of the marker (if any).
mreaDetails :: Lens' MarkerRecordedEventAttributes (Maybe Text)
mreaDetails = lens _mreaDetails (\ s a -> s{_mreaDetails = a});
-- | The name of the marker.
mreaMarkerName :: Lens' MarkerRecordedEventAttributes Text
mreaMarkerName = lens _mreaMarkerName (\ s a -> s{_mreaMarkerName = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'RecordMarker' decision that
-- requested this marker. This information can be useful for diagnosing
-- problems by tracing back the chain of events leading up to this event.
mreaDecisionTaskCompletedEventId :: Lens' MarkerRecordedEventAttributes Integer
mreaDecisionTaskCompletedEventId = lens _mreaDecisionTaskCompletedEventId (\ s a -> s{_mreaDecisionTaskCompletedEventId = a});
instance FromJSON MarkerRecordedEventAttributes where
parseJSON
= withObject "MarkerRecordedEventAttributes"
(\ x ->
MarkerRecordedEventAttributes' <$>
(x .:? "details") <*> (x .: "markerName") <*>
(x .: "decisionTaskCompletedEventId"))
-- | Contains the count of tasks in a task list.
--
-- /See:/ 'pendingTaskCount' smart constructor.
data PendingTaskCount = PendingTaskCount'
{ _ptcTruncated :: !(Maybe Bool)
, _ptcCount :: !Nat
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'PendingTaskCount' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ptcTruncated'
--
-- * 'ptcCount'
pendingTaskCount
:: Natural -- ^ 'ptcCount'
-> PendingTaskCount
pendingTaskCount pCount_ =
PendingTaskCount'
{ _ptcTruncated = Nothing
, _ptcCount = _Nat # pCount_
}
-- | If set to true, indicates that the actual count was more than the
-- maximum supported by this API and the count returned is the truncated
-- value.
ptcTruncated :: Lens' PendingTaskCount (Maybe Bool)
ptcTruncated = lens _ptcTruncated (\ s a -> s{_ptcTruncated = a});
-- | The number of tasks in the task list.
ptcCount :: Lens' PendingTaskCount Natural
ptcCount = lens _ptcCount (\ s a -> s{_ptcCount = a}) . _Nat;
instance FromJSON PendingTaskCount where
parseJSON
= withObject "PendingTaskCount"
(\ x ->
PendingTaskCount' <$>
(x .:? "truncated") <*> (x .: "count"))
-- | Provides details of the 'RecordMarker' decision.
--
-- __Access Control__
--
-- You can use IAM policies to control this decision\'s access to Amazon
-- SWF resources as follows:
--
-- - Use a 'Resource' element with the domain name to limit the action to
-- only specified domains.
-- - Use an 'Action' element to allow or deny permission to call this
-- action.
-- - You cannot use an IAM policy to constrain this action\'s parameters.
--
-- If the caller does not have sufficient permissions to invoke the action,
-- or the parameter values fall outside the specified constraints, the
-- action fails. The associated event attribute\'s __cause__ parameter will
-- be set to OPERATION_NOT_PERMITTED. For details and example IAM policies,
-- see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- /See:/ 'recordMarkerDecisionAttributes' smart constructor.
data RecordMarkerDecisionAttributes = RecordMarkerDecisionAttributes'
{ _rmdaDetails :: !(Maybe Text)
, _rmdaMarkerName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'RecordMarkerDecisionAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rmdaDetails'
--
-- * 'rmdaMarkerName'
recordMarkerDecisionAttributes
:: Text -- ^ 'rmdaMarkerName'
-> RecordMarkerDecisionAttributes
recordMarkerDecisionAttributes pMarkerName_ =
RecordMarkerDecisionAttributes'
{ _rmdaDetails = Nothing
, _rmdaMarkerName = pMarkerName_
}
-- | /Optional./ details of the marker.
rmdaDetails :: Lens' RecordMarkerDecisionAttributes (Maybe Text)
rmdaDetails = lens _rmdaDetails (\ s a -> s{_rmdaDetails = a});
-- | __Required.__ The name of the marker.
rmdaMarkerName :: Lens' RecordMarkerDecisionAttributes Text
rmdaMarkerName = lens _rmdaMarkerName (\ s a -> s{_rmdaMarkerName = a});
instance ToJSON RecordMarkerDecisionAttributes where
toJSON RecordMarkerDecisionAttributes'{..}
= object
(catMaybes
[("details" .=) <$> _rmdaDetails,
Just ("markerName" .= _rmdaMarkerName)])
-- | Provides details of the 'RecordMarkerFailed' event.
--
-- /See:/ 'recordMarkerFailedEventAttributes' smart constructor.
data RecordMarkerFailedEventAttributes = RecordMarkerFailedEventAttributes'
{ _rmfeaMarkerName :: !Text
, _rmfeaCause :: !RecordMarkerFailedCause
, _rmfeaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'RecordMarkerFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rmfeaMarkerName'
--
-- * 'rmfeaCause'
--
-- * 'rmfeaDecisionTaskCompletedEventId'
recordMarkerFailedEventAttributes
:: Text -- ^ 'rmfeaMarkerName'
-> RecordMarkerFailedCause -- ^ 'rmfeaCause'
-> Integer -- ^ 'rmfeaDecisionTaskCompletedEventId'
-> RecordMarkerFailedEventAttributes
recordMarkerFailedEventAttributes pMarkerName_ pCause_ pDecisionTaskCompletedEventId_ =
RecordMarkerFailedEventAttributes'
{ _rmfeaMarkerName = pMarkerName_
, _rmfeaCause = pCause_
, _rmfeaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | The marker\'s name.
rmfeaMarkerName :: Lens' RecordMarkerFailedEventAttributes Text
rmfeaMarkerName = lens _rmfeaMarkerName (\ s a -> s{_rmfeaMarkerName = a});
-- | The cause of the failure. This information is generated by the system
-- and can be useful for diagnostic purposes.
--
-- If __cause__ is set to OPERATION_NOT_PERMITTED, the decision failed
-- because it lacked sufficient permissions. For details and example IAM
-- policies, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
rmfeaCause :: Lens' RecordMarkerFailedEventAttributes RecordMarkerFailedCause
rmfeaCause = lens _rmfeaCause (\ s a -> s{_rmfeaCause = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'RecordMarkerFailed' decision for
-- this cancellation request. This information can be useful for diagnosing
-- problems by tracing back the chain of events leading up to this event.
rmfeaDecisionTaskCompletedEventId :: Lens' RecordMarkerFailedEventAttributes Integer
rmfeaDecisionTaskCompletedEventId = lens _rmfeaDecisionTaskCompletedEventId (\ s a -> s{_rmfeaDecisionTaskCompletedEventId = a});
instance FromJSON RecordMarkerFailedEventAttributes
where
parseJSON
= withObject "RecordMarkerFailedEventAttributes"
(\ x ->
RecordMarkerFailedEventAttributes' <$>
(x .: "markerName") <*> (x .: "cause") <*>
(x .: "decisionTaskCompletedEventId"))
-- | Provides details of the 'RequestCancelActivityTask' decision.
--
-- __Access Control__
--
-- You can use IAM policies to control this decision\'s access to Amazon
-- SWF resources as follows:
--
-- - Use a 'Resource' element with the domain name to limit the action to
-- only specified domains.
-- - Use an 'Action' element to allow or deny permission to call this
-- action.
-- - You cannot use an IAM policy to constrain this action\'s parameters.
--
-- If the caller does not have sufficient permissions to invoke the action,
-- or the parameter values fall outside the specified constraints, the
-- action fails. The associated event attribute\'s __cause__ parameter will
-- be set to OPERATION_NOT_PERMITTED. For details and example IAM policies,
-- see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- /See:/ 'requestCancelActivityTaskDecisionAttributes' smart constructor.
newtype RequestCancelActivityTaskDecisionAttributes = RequestCancelActivityTaskDecisionAttributes'
{ _rcatdaActivityId :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'RequestCancelActivityTaskDecisionAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rcatdaActivityId'
requestCancelActivityTaskDecisionAttributes
:: Text -- ^ 'rcatdaActivityId'
-> RequestCancelActivityTaskDecisionAttributes
requestCancelActivityTaskDecisionAttributes pActivityId_ =
RequestCancelActivityTaskDecisionAttributes'
{ _rcatdaActivityId = pActivityId_
}
-- | The 'activityId' of the activity task to be canceled.
rcatdaActivityId :: Lens' RequestCancelActivityTaskDecisionAttributes Text
rcatdaActivityId = lens _rcatdaActivityId (\ s a -> s{_rcatdaActivityId = a});
instance ToJSON
RequestCancelActivityTaskDecisionAttributes where
toJSON
RequestCancelActivityTaskDecisionAttributes'{..}
= object
(catMaybes
[Just ("activityId" .= _rcatdaActivityId)])
-- | Provides details of the 'RequestCancelActivityTaskFailed' event.
--
-- /See:/ 'requestCancelActivityTaskFailedEventAttributes' smart constructor.
data RequestCancelActivityTaskFailedEventAttributes = RequestCancelActivityTaskFailedEventAttributes'
{ _rcatfeaActivityId :: !Text
, _rcatfeaCause :: !RequestCancelActivityTaskFailedCause
, _rcatfeaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'RequestCancelActivityTaskFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rcatfeaActivityId'
--
-- * 'rcatfeaCause'
--
-- * 'rcatfeaDecisionTaskCompletedEventId'
requestCancelActivityTaskFailedEventAttributes
:: Text -- ^ 'rcatfeaActivityId'
-> RequestCancelActivityTaskFailedCause -- ^ 'rcatfeaCause'
-> Integer -- ^ 'rcatfeaDecisionTaskCompletedEventId'
-> RequestCancelActivityTaskFailedEventAttributes
requestCancelActivityTaskFailedEventAttributes pActivityId_ pCause_ pDecisionTaskCompletedEventId_ =
RequestCancelActivityTaskFailedEventAttributes'
{ _rcatfeaActivityId = pActivityId_
, _rcatfeaCause = pCause_
, _rcatfeaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | The activityId provided in the 'RequestCancelActivityTask' decision that
-- failed.
rcatfeaActivityId :: Lens' RequestCancelActivityTaskFailedEventAttributes Text
rcatfeaActivityId = lens _rcatfeaActivityId (\ s a -> s{_rcatfeaActivityId = a});
-- | The cause of the failure. This information is generated by the system
-- and can be useful for diagnostic purposes.
--
-- If __cause__ is set to OPERATION_NOT_PERMITTED, the decision failed
-- because it lacked sufficient permissions. For details and example IAM
-- policies, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
rcatfeaCause :: Lens' RequestCancelActivityTaskFailedEventAttributes RequestCancelActivityTaskFailedCause
rcatfeaCause = lens _rcatfeaCause (\ s a -> s{_rcatfeaCause = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'RequestCancelActivityTask' decision
-- for this cancellation request. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
rcatfeaDecisionTaskCompletedEventId :: Lens' RequestCancelActivityTaskFailedEventAttributes Integer
rcatfeaDecisionTaskCompletedEventId = lens _rcatfeaDecisionTaskCompletedEventId (\ s a -> s{_rcatfeaDecisionTaskCompletedEventId = a});
instance FromJSON
RequestCancelActivityTaskFailedEventAttributes where
parseJSON
= withObject
"RequestCancelActivityTaskFailedEventAttributes"
(\ x ->
RequestCancelActivityTaskFailedEventAttributes' <$>
(x .: "activityId") <*> (x .: "cause") <*>
(x .: "decisionTaskCompletedEventId"))
-- | Provides details of the 'RequestCancelExternalWorkflowExecution'
-- decision.
--
-- __Access Control__
--
-- You can use IAM policies to control this decision\'s access to Amazon
-- SWF resources as follows:
--
-- - Use a 'Resource' element with the domain name to limit the action to
-- only specified domains.
-- - Use an 'Action' element to allow or deny permission to call this
-- action.
-- - You cannot use an IAM policy to constrain this action\'s parameters.
--
-- If the caller does not have sufficient permissions to invoke the action,
-- or the parameter values fall outside the specified constraints, the
-- action fails. The associated event attribute\'s __cause__ parameter will
-- be set to OPERATION_NOT_PERMITTED. For details and example IAM policies,
-- see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- /See:/ 'requestCancelExternalWorkflowExecutionDecisionAttributes' smart constructor.
data RequestCancelExternalWorkflowExecutionDecisionAttributes = RequestCancelExternalWorkflowExecutionDecisionAttributes'
{ _rcewedaControl :: !(Maybe Text)
, _rcewedaRunId :: !(Maybe Text)
, _rcewedaWorkflowId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'RequestCancelExternalWorkflowExecutionDecisionAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rcewedaControl'
--
-- * 'rcewedaRunId'
--
-- * 'rcewedaWorkflowId'
requestCancelExternalWorkflowExecutionDecisionAttributes
:: Text -- ^ 'rcewedaWorkflowId'
-> RequestCancelExternalWorkflowExecutionDecisionAttributes
requestCancelExternalWorkflowExecutionDecisionAttributes pWorkflowId_ =
RequestCancelExternalWorkflowExecutionDecisionAttributes'
{ _rcewedaControl = Nothing
, _rcewedaRunId = Nothing
, _rcewedaWorkflowId = pWorkflowId_
}
-- | /Optional./ Data attached to the event that can be used by the decider
-- in subsequent workflow tasks.
rcewedaControl :: Lens' RequestCancelExternalWorkflowExecutionDecisionAttributes (Maybe Text)
rcewedaControl = lens _rcewedaControl (\ s a -> s{_rcewedaControl = a});
-- | The 'runId' of the external workflow execution to cancel.
rcewedaRunId :: Lens' RequestCancelExternalWorkflowExecutionDecisionAttributes (Maybe Text)
rcewedaRunId = lens _rcewedaRunId (\ s a -> s{_rcewedaRunId = a});
-- | __Required.__ The 'workflowId' of the external workflow execution to
-- cancel.
rcewedaWorkflowId :: Lens' RequestCancelExternalWorkflowExecutionDecisionAttributes Text
rcewedaWorkflowId = lens _rcewedaWorkflowId (\ s a -> s{_rcewedaWorkflowId = a});
instance ToJSON
RequestCancelExternalWorkflowExecutionDecisionAttributes
where
toJSON
RequestCancelExternalWorkflowExecutionDecisionAttributes'{..}
= object
(catMaybes
[("control" .=) <$> _rcewedaControl,
("runId" .=) <$> _rcewedaRunId,
Just ("workflowId" .= _rcewedaWorkflowId)])
-- | Provides details of the 'RequestCancelExternalWorkflowExecutionFailed'
-- event.
--
-- /See:/ 'requestCancelExternalWorkflowExecutionFailedEventAttributes' smart constructor.
data RequestCancelExternalWorkflowExecutionFailedEventAttributes = RequestCancelExternalWorkflowExecutionFailedEventAttributes'
{ _rcewefeaControl :: !(Maybe Text)
, _rcewefeaRunId :: !(Maybe Text)
, _rcewefeaWorkflowId :: !Text
, _rcewefeaCause :: !RequestCancelExternalWorkflowExecutionFailedCause
, _rcewefeaInitiatedEventId :: !Integer
, _rcewefeaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'RequestCancelExternalWorkflowExecutionFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rcewefeaControl'
--
-- * 'rcewefeaRunId'
--
-- * 'rcewefeaWorkflowId'
--
-- * 'rcewefeaCause'
--
-- * 'rcewefeaInitiatedEventId'
--
-- * 'rcewefeaDecisionTaskCompletedEventId'
requestCancelExternalWorkflowExecutionFailedEventAttributes
:: Text -- ^ 'rcewefeaWorkflowId'
-> RequestCancelExternalWorkflowExecutionFailedCause -- ^ 'rcewefeaCause'
-> Integer -- ^ 'rcewefeaInitiatedEventId'
-> Integer -- ^ 'rcewefeaDecisionTaskCompletedEventId'
-> RequestCancelExternalWorkflowExecutionFailedEventAttributes
requestCancelExternalWorkflowExecutionFailedEventAttributes pWorkflowId_ pCause_ pInitiatedEventId_ pDecisionTaskCompletedEventId_ =
RequestCancelExternalWorkflowExecutionFailedEventAttributes'
{ _rcewefeaControl = Nothing
, _rcewefeaRunId = Nothing
, _rcewefeaWorkflowId = pWorkflowId_
, _rcewefeaCause = pCause_
, _rcewefeaInitiatedEventId = pInitiatedEventId_
, _rcewefeaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | Undocumented member.
rcewefeaControl :: Lens' RequestCancelExternalWorkflowExecutionFailedEventAttributes (Maybe Text)
rcewefeaControl = lens _rcewefeaControl (\ s a -> s{_rcewefeaControl = a});
-- | The 'runId' of the external workflow execution.
rcewefeaRunId :: Lens' RequestCancelExternalWorkflowExecutionFailedEventAttributes (Maybe Text)
rcewefeaRunId = lens _rcewefeaRunId (\ s a -> s{_rcewefeaRunId = a});
-- | The 'workflowId' of the external workflow to which the cancel request
-- was to be delivered.
rcewefeaWorkflowId :: Lens' RequestCancelExternalWorkflowExecutionFailedEventAttributes Text
rcewefeaWorkflowId = lens _rcewefeaWorkflowId (\ s a -> s{_rcewefeaWorkflowId = a});
-- | The cause of the failure. This information is generated by the system
-- and can be useful for diagnostic purposes.
--
-- If __cause__ is set to OPERATION_NOT_PERMITTED, the decision failed
-- because it lacked sufficient permissions. For details and example IAM
-- policies, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
rcewefeaCause :: Lens' RequestCancelExternalWorkflowExecutionFailedEventAttributes RequestCancelExternalWorkflowExecutionFailedCause
rcewefeaCause = lens _rcewefeaCause (\ s a -> s{_rcewefeaCause = a});
-- | The ID of the 'RequestCancelExternalWorkflowExecutionInitiated' event
-- corresponding to the 'RequestCancelExternalWorkflowExecution' decision
-- to cancel this external workflow execution. This information can be
-- useful for diagnosing problems by tracing back the chain of events
-- leading up to this event.
rcewefeaInitiatedEventId :: Lens' RequestCancelExternalWorkflowExecutionFailedEventAttributes Integer
rcewefeaInitiatedEventId = lens _rcewefeaInitiatedEventId (\ s a -> s{_rcewefeaInitiatedEventId = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the
-- 'RequestCancelExternalWorkflowExecution' decision for this cancellation
-- request. This information can be useful for diagnosing problems by
-- tracing back the chain of events leading up to this event.
rcewefeaDecisionTaskCompletedEventId :: Lens' RequestCancelExternalWorkflowExecutionFailedEventAttributes Integer
rcewefeaDecisionTaskCompletedEventId = lens _rcewefeaDecisionTaskCompletedEventId (\ s a -> s{_rcewefeaDecisionTaskCompletedEventId = a});
instance FromJSON
RequestCancelExternalWorkflowExecutionFailedEventAttributes
where
parseJSON
= withObject
"RequestCancelExternalWorkflowExecutionFailedEventAttributes"
(\ x ->
RequestCancelExternalWorkflowExecutionFailedEventAttributes'
<$>
(x .:? "control") <*> (x .:? "runId") <*>
(x .: "workflowId")
<*> (x .: "cause")
<*> (x .: "initiatedEventId")
<*> (x .: "decisionTaskCompletedEventId"))
-- | Provides details of the
-- 'RequestCancelExternalWorkflowExecutionInitiated' event.
--
-- /See:/ 'requestCancelExternalWorkflowExecutionInitiatedEventAttributes' smart constructor.
data RequestCancelExternalWorkflowExecutionInitiatedEventAttributes = RequestCancelExternalWorkflowExecutionInitiatedEventAttributes'
{ _rceweieaControl :: !(Maybe Text)
, _rceweieaRunId :: !(Maybe Text)
, _rceweieaWorkflowId :: !Text
, _rceweieaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'RequestCancelExternalWorkflowExecutionInitiatedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rceweieaControl'
--
-- * 'rceweieaRunId'
--
-- * 'rceweieaWorkflowId'
--
-- * 'rceweieaDecisionTaskCompletedEventId'
requestCancelExternalWorkflowExecutionInitiatedEventAttributes
:: Text -- ^ 'rceweieaWorkflowId'
-> Integer -- ^ 'rceweieaDecisionTaskCompletedEventId'
-> RequestCancelExternalWorkflowExecutionInitiatedEventAttributes
requestCancelExternalWorkflowExecutionInitiatedEventAttributes pWorkflowId_ pDecisionTaskCompletedEventId_ =
RequestCancelExternalWorkflowExecutionInitiatedEventAttributes'
{ _rceweieaControl = Nothing
, _rceweieaRunId = Nothing
, _rceweieaWorkflowId = pWorkflowId_
, _rceweieaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | /Optional./ Data attached to the event that can be used by the decider
-- in subsequent workflow tasks.
rceweieaControl :: Lens' RequestCancelExternalWorkflowExecutionInitiatedEventAttributes (Maybe Text)
rceweieaControl = lens _rceweieaControl (\ s a -> s{_rceweieaControl = a});
-- | The 'runId' of the external workflow execution to be canceled.
rceweieaRunId :: Lens' RequestCancelExternalWorkflowExecutionInitiatedEventAttributes (Maybe Text)
rceweieaRunId = lens _rceweieaRunId (\ s a -> s{_rceweieaRunId = a});
-- | The 'workflowId' of the external workflow execution to be canceled.
rceweieaWorkflowId :: Lens' RequestCancelExternalWorkflowExecutionInitiatedEventAttributes Text
rceweieaWorkflowId = lens _rceweieaWorkflowId (\ s a -> s{_rceweieaWorkflowId = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the
-- 'RequestCancelExternalWorkflowExecution' decision for this cancellation
-- request. This information can be useful for diagnosing problems by
-- tracing back the chain of events leading up to this event.
rceweieaDecisionTaskCompletedEventId :: Lens' RequestCancelExternalWorkflowExecutionInitiatedEventAttributes Integer
rceweieaDecisionTaskCompletedEventId = lens _rceweieaDecisionTaskCompletedEventId (\ s a -> s{_rceweieaDecisionTaskCompletedEventId = a});
instance FromJSON
RequestCancelExternalWorkflowExecutionInitiatedEventAttributes
where
parseJSON
= withObject
"RequestCancelExternalWorkflowExecutionInitiatedEventAttributes"
(\ x ->
RequestCancelExternalWorkflowExecutionInitiatedEventAttributes'
<$>
(x .:? "control") <*> (x .:? "runId") <*>
(x .: "workflowId")
<*> (x .: "decisionTaskCompletedEventId"))
-- | Provides details of the 'ScheduleActivityTask' decision.
--
-- __Access Control__
--
-- You can use IAM policies to control this decision\'s access to Amazon
-- SWF resources as follows:
--
-- - Use a 'Resource' element with the domain name to limit the action to
-- only specified domains.
-- - Use an 'Action' element to allow or deny permission to call this
-- action.
-- - Constrain the following parameters by using a 'Condition' element
-- with the appropriate keys.
-- - 'activityType.name': String constraint. The key is
-- 'swf:activityType.name'.
-- - 'activityType.version': String constraint. The key is
-- 'swf:activityType.version'.
-- - 'taskList': String constraint. The key is 'swf:taskList.name'.
--
-- If the caller does not have sufficient permissions to invoke the action,
-- or the parameter values fall outside the specified constraints, the
-- action fails. The associated event attribute\'s __cause__ parameter will
-- be set to OPERATION_NOT_PERMITTED. For details and example IAM policies,
-- see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- /See:/ 'scheduleActivityTaskDecisionAttributes' smart constructor.
data ScheduleActivityTaskDecisionAttributes = ScheduleActivityTaskDecisionAttributes'
{ _satdaControl :: !(Maybe Text)
, _satdaHeartbeatTimeout :: !(Maybe Text)
, _satdaScheduleToCloseTimeout :: !(Maybe Text)
, _satdaInput :: !(Maybe Text)
, _satdaTaskList :: !(Maybe TaskList)
, _satdaTaskPriority :: !(Maybe Text)
, _satdaScheduleToStartTimeout :: !(Maybe Text)
, _satdaStartToCloseTimeout :: !(Maybe Text)
, _satdaActivityType :: !ActivityType
, _satdaActivityId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ScheduleActivityTaskDecisionAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'satdaControl'
--
-- * 'satdaHeartbeatTimeout'
--
-- * 'satdaScheduleToCloseTimeout'
--
-- * 'satdaInput'
--
-- * 'satdaTaskList'
--
-- * 'satdaTaskPriority'
--
-- * 'satdaScheduleToStartTimeout'
--
-- * 'satdaStartToCloseTimeout'
--
-- * 'satdaActivityType'
--
-- * 'satdaActivityId'
scheduleActivityTaskDecisionAttributes
:: ActivityType -- ^ 'satdaActivityType'
-> Text -- ^ 'satdaActivityId'
-> ScheduleActivityTaskDecisionAttributes
scheduleActivityTaskDecisionAttributes pActivityType_ pActivityId_ =
ScheduleActivityTaskDecisionAttributes'
{ _satdaControl = Nothing
, _satdaHeartbeatTimeout = Nothing
, _satdaScheduleToCloseTimeout = Nothing
, _satdaInput = Nothing
, _satdaTaskList = Nothing
, _satdaTaskPriority = Nothing
, _satdaScheduleToStartTimeout = Nothing
, _satdaStartToCloseTimeout = Nothing
, _satdaActivityType = pActivityType_
, _satdaActivityId = pActivityId_
}
-- | /Optional./ Data attached to the event that can be used by the decider
-- in subsequent workflow tasks. This data is not sent to the activity.
satdaControl :: Lens' ScheduleActivityTaskDecisionAttributes (Maybe Text)
satdaControl = lens _satdaControl (\ s a -> s{_satdaControl = a});
-- | If set, specifies the maximum time before which a worker processing a
-- task of this type must report progress by calling
-- RecordActivityTaskHeartbeat. If the timeout is exceeded, the activity
-- task is automatically timed out. If the worker subsequently attempts to
-- record a heartbeat or returns a result, it will be ignored. This
-- overrides the default heartbeat timeout specified when registering the
-- activity type using RegisterActivityType.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
satdaHeartbeatTimeout :: Lens' ScheduleActivityTaskDecisionAttributes (Maybe Text)
satdaHeartbeatTimeout = lens _satdaHeartbeatTimeout (\ s a -> s{_satdaHeartbeatTimeout = a});
-- | The maximum duration for this activity task.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
--
-- A schedule-to-close timeout for this activity task must be specified
-- either as a default for the activity type or through this field. If
-- neither this field is set nor a default schedule-to-close timeout was
-- specified at registration time then a fault will be returned.
satdaScheduleToCloseTimeout :: Lens' ScheduleActivityTaskDecisionAttributes (Maybe Text)
satdaScheduleToCloseTimeout = lens _satdaScheduleToCloseTimeout (\ s a -> s{_satdaScheduleToCloseTimeout = a});
-- | The input provided to the activity task.
satdaInput :: Lens' ScheduleActivityTaskDecisionAttributes (Maybe Text)
satdaInput = lens _satdaInput (\ s a -> s{_satdaInput = a});
-- | If set, specifies the name of the task list in which to schedule the
-- activity task. If not specified, the 'defaultTaskList' registered with
-- the activity type will be used.
--
-- A task list for this activity task must be specified either as a default
-- for the activity type or through this field. If neither this field is
-- set nor a default task list was specified at registration time then a
-- fault will be returned.
--
-- The specified string must not start or end with whitespace. It must not
-- contain a ':' (colon), '\/' (slash), '|' (vertical bar), or any control
-- characters (\\u0000-\\u001f | \\u007f - \\u009f). Also, it must not
-- contain the literal string quotarnquot.
satdaTaskList :: Lens' ScheduleActivityTaskDecisionAttributes (Maybe TaskList)
satdaTaskList = lens _satdaTaskList (\ s a -> s{_satdaTaskList = a});
-- | /Optional./ If set, specifies the priority with which the activity task
-- is to be assigned to a worker. This overrides the defaultTaskPriority
-- specified when registering the activity type using RegisterActivityType.
-- Valid values are integers that range from Java\'s 'Integer.MIN_VALUE'
-- (-2147483648) to 'Integer.MAX_VALUE' (2147483647). Higher numbers
-- indicate higher priority.
--
-- For more information about setting task priority, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/programming-priority.html Setting Task Priority>
-- in the /Amazon Simple Workflow Developer Guide/.
satdaTaskPriority :: Lens' ScheduleActivityTaskDecisionAttributes (Maybe Text)
satdaTaskPriority = lens _satdaTaskPriority (\ s a -> s{_satdaTaskPriority = a});
-- | /Optional./ If set, specifies the maximum duration the activity task can
-- wait to be assigned to a worker. This overrides the default
-- schedule-to-start timeout specified when registering the activity type
-- using RegisterActivityType.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
--
-- A schedule-to-start timeout for this activity task must be specified
-- either as a default for the activity type or through this field. If
-- neither this field is set nor a default schedule-to-start timeout was
-- specified at registration time then a fault will be returned.
satdaScheduleToStartTimeout :: Lens' ScheduleActivityTaskDecisionAttributes (Maybe Text)
satdaScheduleToStartTimeout = lens _satdaScheduleToStartTimeout (\ s a -> s{_satdaScheduleToStartTimeout = a});
-- | If set, specifies the maximum duration a worker may take to process this
-- activity task. This overrides the default start-to-close timeout
-- specified when registering the activity type using RegisterActivityType.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
--
-- A start-to-close timeout for this activity task must be specified either
-- as a default for the activity type or through this field. If neither
-- this field is set nor a default start-to-close timeout was specified at
-- registration time then a fault will be returned.
satdaStartToCloseTimeout :: Lens' ScheduleActivityTaskDecisionAttributes (Maybe Text)
satdaStartToCloseTimeout = lens _satdaStartToCloseTimeout (\ s a -> s{_satdaStartToCloseTimeout = a});
-- | __Required.__ The type of the activity task to schedule.
satdaActivityType :: Lens' ScheduleActivityTaskDecisionAttributes ActivityType
satdaActivityType = lens _satdaActivityType (\ s a -> s{_satdaActivityType = a});
-- | __Required.__ The 'activityId' of the activity task.
--
-- The specified string must not start or end with whitespace. It must not
-- contain a ':' (colon), '\/' (slash), '|' (vertical bar), or any control
-- characters (\\u0000-\\u001f | \\u007f - \\u009f). Also, it must not
-- contain the literal string quotarnquot.
satdaActivityId :: Lens' ScheduleActivityTaskDecisionAttributes Text
satdaActivityId = lens _satdaActivityId (\ s a -> s{_satdaActivityId = a});
instance ToJSON
ScheduleActivityTaskDecisionAttributes where
toJSON ScheduleActivityTaskDecisionAttributes'{..}
= object
(catMaybes
[("control" .=) <$> _satdaControl,
("heartbeatTimeout" .=) <$> _satdaHeartbeatTimeout,
("scheduleToCloseTimeout" .=) <$>
_satdaScheduleToCloseTimeout,
("input" .=) <$> _satdaInput,
("taskList" .=) <$> _satdaTaskList,
("taskPriority" .=) <$> _satdaTaskPriority,
("scheduleToStartTimeout" .=) <$>
_satdaScheduleToStartTimeout,
("startToCloseTimeout" .=) <$>
_satdaStartToCloseTimeout,
Just ("activityType" .= _satdaActivityType),
Just ("activityId" .= _satdaActivityId)])
-- | Provides details of the 'ScheduleActivityTaskFailed' event.
--
-- /See:/ 'scheduleActivityTaskFailedEventAttributes' smart constructor.
data ScheduleActivityTaskFailedEventAttributes = ScheduleActivityTaskFailedEventAttributes'
{ _satfeaActivityType :: !ActivityType
, _satfeaActivityId :: !Text
, _satfeaCause :: !ScheduleActivityTaskFailedCause
, _satfeaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ScheduleActivityTaskFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'satfeaActivityType'
--
-- * 'satfeaActivityId'
--
-- * 'satfeaCause'
--
-- * 'satfeaDecisionTaskCompletedEventId'
scheduleActivityTaskFailedEventAttributes
:: ActivityType -- ^ 'satfeaActivityType'
-> Text -- ^ 'satfeaActivityId'
-> ScheduleActivityTaskFailedCause -- ^ 'satfeaCause'
-> Integer -- ^ 'satfeaDecisionTaskCompletedEventId'
-> ScheduleActivityTaskFailedEventAttributes
scheduleActivityTaskFailedEventAttributes pActivityType_ pActivityId_ pCause_ pDecisionTaskCompletedEventId_ =
ScheduleActivityTaskFailedEventAttributes'
{ _satfeaActivityType = pActivityType_
, _satfeaActivityId = pActivityId_
, _satfeaCause = pCause_
, _satfeaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | The activity type provided in the 'ScheduleActivityTask' decision that
-- failed.
satfeaActivityType :: Lens' ScheduleActivityTaskFailedEventAttributes ActivityType
satfeaActivityType = lens _satfeaActivityType (\ s a -> s{_satfeaActivityType = a});
-- | The activityId provided in the 'ScheduleActivityTask' decision that
-- failed.
satfeaActivityId :: Lens' ScheduleActivityTaskFailedEventAttributes Text
satfeaActivityId = lens _satfeaActivityId (\ s a -> s{_satfeaActivityId = a});
-- | The cause of the failure. This information is generated by the system
-- and can be useful for diagnostic purposes.
--
-- If __cause__ is set to OPERATION_NOT_PERMITTED, the decision failed
-- because it lacked sufficient permissions. For details and example IAM
-- policies, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
satfeaCause :: Lens' ScheduleActivityTaskFailedEventAttributes ScheduleActivityTaskFailedCause
satfeaCause = lens _satfeaCause (\ s a -> s{_satfeaCause = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision that resulted in the scheduling of this activity task. This
-- information can be useful for diagnosing problems by tracing back the
-- chain of events leading up to this event.
satfeaDecisionTaskCompletedEventId :: Lens' ScheduleActivityTaskFailedEventAttributes Integer
satfeaDecisionTaskCompletedEventId = lens _satfeaDecisionTaskCompletedEventId (\ s a -> s{_satfeaDecisionTaskCompletedEventId = a});
instance FromJSON
ScheduleActivityTaskFailedEventAttributes where
parseJSON
= withObject
"ScheduleActivityTaskFailedEventAttributes"
(\ x ->
ScheduleActivityTaskFailedEventAttributes' <$>
(x .: "activityType") <*> (x .: "activityId") <*>
(x .: "cause")
<*> (x .: "decisionTaskCompletedEventId"))
-- | Provides details of the 'ScheduleLambdaFunction' decision.
--
-- __Access Control__
--
-- You can use IAM policies to control this decision\'s access to Amazon
-- SWF resources as follows:
--
-- - Use a 'Resource' element with the domain name to limit the action to
-- only specified domains.
-- - Use an 'Action' element to allow or deny permission to call this
-- action.
-- - Constrain the following parameters by using a 'Condition' element
-- with the appropriate keys.
-- - 'activityType.name': String constraint. The key is
-- 'swf:activityType.name'.
-- - 'activityType.version': String constraint. The key is
-- 'swf:activityType.version'.
-- - 'taskList': String constraint. The key is 'swf:taskList.name'.
--
-- If the caller does not have sufficient permissions to invoke the action,
-- or the parameter values fall outside the specified constraints, the
-- action fails. The associated event attribute\'s __cause__ parameter will
-- be set to OPERATION_NOT_PERMITTED. For details and example IAM policies,
-- see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- /See:/ 'scheduleLambdaFunctionDecisionAttributes' smart constructor.
data ScheduleLambdaFunctionDecisionAttributes = ScheduleLambdaFunctionDecisionAttributes'
{ _slfdaInput :: !(Maybe Text)
, _slfdaStartToCloseTimeout :: !(Maybe Text)
, _slfdaId :: !Text
, _slfdaName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ScheduleLambdaFunctionDecisionAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'slfdaInput'
--
-- * 'slfdaStartToCloseTimeout'
--
-- * 'slfdaId'
--
-- * 'slfdaName'
scheduleLambdaFunctionDecisionAttributes
:: Text -- ^ 'slfdaId'
-> Text -- ^ 'slfdaName'
-> ScheduleLambdaFunctionDecisionAttributes
scheduleLambdaFunctionDecisionAttributes pId_ pName_ =
ScheduleLambdaFunctionDecisionAttributes'
{ _slfdaInput = Nothing
, _slfdaStartToCloseTimeout = Nothing
, _slfdaId = pId_
, _slfdaName = pName_
}
-- | The input provided to the AWS Lambda function.
slfdaInput :: Lens' ScheduleLambdaFunctionDecisionAttributes (Maybe Text)
slfdaInput = lens _slfdaInput (\ s a -> s{_slfdaInput = a});
-- | If set, specifies the maximum duration the function may take to execute.
slfdaStartToCloseTimeout :: Lens' ScheduleLambdaFunctionDecisionAttributes (Maybe Text)
slfdaStartToCloseTimeout = lens _slfdaStartToCloseTimeout (\ s a -> s{_slfdaStartToCloseTimeout = a});
-- | __Required.__ The SWF 'id' of the AWS Lambda task.
--
-- The specified string must not start or end with whitespace. It must not
-- contain a ':' (colon), '\/' (slash), '|' (vertical bar), or any control
-- characters (\\u0000-\\u001f | \\u007f - \\u009f). Also, it must not
-- contain the literal string quotarnquot.
slfdaId :: Lens' ScheduleLambdaFunctionDecisionAttributes Text
slfdaId = lens _slfdaId (\ s a -> s{_slfdaId = a});
-- | __Required.__ The name of the AWS Lambda function to invoke.
slfdaName :: Lens' ScheduleLambdaFunctionDecisionAttributes Text
slfdaName = lens _slfdaName (\ s a -> s{_slfdaName = a});
instance ToJSON
ScheduleLambdaFunctionDecisionAttributes where
toJSON ScheduleLambdaFunctionDecisionAttributes'{..}
= object
(catMaybes
[("input" .=) <$> _slfdaInput,
("startToCloseTimeout" .=) <$>
_slfdaStartToCloseTimeout,
Just ("id" .= _slfdaId),
Just ("name" .= _slfdaName)])
-- | Provides details for the 'ScheduleLambdaFunctionFailed' event.
--
-- /See:/ 'scheduleLambdaFunctionFailedEventAttributes' smart constructor.
data ScheduleLambdaFunctionFailedEventAttributes = ScheduleLambdaFunctionFailedEventAttributes'
{ _slffeaId :: !Text
, _slffeaName :: !Text
, _slffeaCause :: !ScheduleLambdaFunctionFailedCause
, _slffeaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ScheduleLambdaFunctionFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'slffeaId'
--
-- * 'slffeaName'
--
-- * 'slffeaCause'
--
-- * 'slffeaDecisionTaskCompletedEventId'
scheduleLambdaFunctionFailedEventAttributes
:: Text -- ^ 'slffeaId'
-> Text -- ^ 'slffeaName'
-> ScheduleLambdaFunctionFailedCause -- ^ 'slffeaCause'
-> Integer -- ^ 'slffeaDecisionTaskCompletedEventId'
-> ScheduleLambdaFunctionFailedEventAttributes
scheduleLambdaFunctionFailedEventAttributes pId_ pName_ pCause_ pDecisionTaskCompletedEventId_ =
ScheduleLambdaFunctionFailedEventAttributes'
{ _slffeaId = pId_
, _slffeaName = pName_
, _slffeaCause = pCause_
, _slffeaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | The unique Amazon SWF ID of the AWS Lambda task.
slffeaId :: Lens' ScheduleLambdaFunctionFailedEventAttributes Text
slffeaId = lens _slffeaId (\ s a -> s{_slffeaId = a});
-- | The name of the scheduled AWS Lambda function.
slffeaName :: Lens' ScheduleLambdaFunctionFailedEventAttributes Text
slffeaName = lens _slffeaName (\ s a -> s{_slffeaName = a});
-- | The cause of the failure. This information is generated by the system
-- and can be useful for diagnostic purposes.
--
-- If __cause__ is set to OPERATION_NOT_PERMITTED, the decision failed
-- because it lacked sufficient permissions. For details and example IAM
-- policies, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
slffeaCause :: Lens' ScheduleLambdaFunctionFailedEventAttributes ScheduleLambdaFunctionFailedCause
slffeaCause = lens _slffeaCause (\ s a -> s{_slffeaCause = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision that resulted in the scheduling of this AWS Lambda function.
-- This information can be useful for diagnosing problems by tracing back
-- the chain of events leading up to this event.
slffeaDecisionTaskCompletedEventId :: Lens' ScheduleLambdaFunctionFailedEventAttributes Integer
slffeaDecisionTaskCompletedEventId = lens _slffeaDecisionTaskCompletedEventId (\ s a -> s{_slffeaDecisionTaskCompletedEventId = a});
instance FromJSON
ScheduleLambdaFunctionFailedEventAttributes where
parseJSON
= withObject
"ScheduleLambdaFunctionFailedEventAttributes"
(\ x ->
ScheduleLambdaFunctionFailedEventAttributes' <$>
(x .: "id") <*> (x .: "name") <*> (x .: "cause") <*>
(x .: "decisionTaskCompletedEventId"))
-- | Provides details of the 'SignalExternalWorkflowExecution' decision.
--
-- __Access Control__
--
-- You can use IAM policies to control this decision\'s access to Amazon
-- SWF resources as follows:
--
-- - Use a 'Resource' element with the domain name to limit the action to
-- only specified domains.
-- - Use an 'Action' element to allow or deny permission to call this
-- action.
-- - You cannot use an IAM policy to constrain this action\'s parameters.
--
-- If the caller does not have sufficient permissions to invoke the action,
-- or the parameter values fall outside the specified constraints, the
-- action fails. The associated event attribute\'s __cause__ parameter will
-- be set to OPERATION_NOT_PERMITTED. For details and example IAM policies,
-- see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- /See:/ 'signalExternalWorkflowExecutionDecisionAttributes' smart constructor.
data SignalExternalWorkflowExecutionDecisionAttributes = SignalExternalWorkflowExecutionDecisionAttributes'
{ _sewedaControl :: !(Maybe Text)
, _sewedaInput :: !(Maybe Text)
, _sewedaRunId :: !(Maybe Text)
, _sewedaWorkflowId :: !Text
, _sewedaSignalName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'SignalExternalWorkflowExecutionDecisionAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sewedaControl'
--
-- * 'sewedaInput'
--
-- * 'sewedaRunId'
--
-- * 'sewedaWorkflowId'
--
-- * 'sewedaSignalName'
signalExternalWorkflowExecutionDecisionAttributes
:: Text -- ^ 'sewedaWorkflowId'
-> Text -- ^ 'sewedaSignalName'
-> SignalExternalWorkflowExecutionDecisionAttributes
signalExternalWorkflowExecutionDecisionAttributes pWorkflowId_ pSignalName_ =
SignalExternalWorkflowExecutionDecisionAttributes'
{ _sewedaControl = Nothing
, _sewedaInput = Nothing
, _sewedaRunId = Nothing
, _sewedaWorkflowId = pWorkflowId_
, _sewedaSignalName = pSignalName_
}
-- | /Optional./ Data attached to the event that can be used by the decider
-- in subsequent decision tasks.
sewedaControl :: Lens' SignalExternalWorkflowExecutionDecisionAttributes (Maybe Text)
sewedaControl = lens _sewedaControl (\ s a -> s{_sewedaControl = a});
-- | /Optional./ Input data to be provided with the signal. The target
-- workflow execution will use the signal name and input data to process
-- the signal.
sewedaInput :: Lens' SignalExternalWorkflowExecutionDecisionAttributes (Maybe Text)
sewedaInput = lens _sewedaInput (\ s a -> s{_sewedaInput = a});
-- | The 'runId' of the workflow execution to be signaled.
sewedaRunId :: Lens' SignalExternalWorkflowExecutionDecisionAttributes (Maybe Text)
sewedaRunId = lens _sewedaRunId (\ s a -> s{_sewedaRunId = a});
-- | __Required.__ The 'workflowId' of the workflow execution to be signaled.
sewedaWorkflowId :: Lens' SignalExternalWorkflowExecutionDecisionAttributes Text
sewedaWorkflowId = lens _sewedaWorkflowId (\ s a -> s{_sewedaWorkflowId = a});
-- | __Required.__ The name of the signal.The target workflow execution will
-- use the signal name and input to process the signal.
sewedaSignalName :: Lens' SignalExternalWorkflowExecutionDecisionAttributes Text
sewedaSignalName = lens _sewedaSignalName (\ s a -> s{_sewedaSignalName = a});
instance ToJSON
SignalExternalWorkflowExecutionDecisionAttributes
where
toJSON
SignalExternalWorkflowExecutionDecisionAttributes'{..}
= object
(catMaybes
[("control" .=) <$> _sewedaControl,
("input" .=) <$> _sewedaInput,
("runId" .=) <$> _sewedaRunId,
Just ("workflowId" .= _sewedaWorkflowId),
Just ("signalName" .= _sewedaSignalName)])
-- | Provides details of the 'SignalExternalWorkflowExecutionFailed' event.
--
-- /See:/ 'signalExternalWorkflowExecutionFailedEventAttributes' smart constructor.
data SignalExternalWorkflowExecutionFailedEventAttributes = SignalExternalWorkflowExecutionFailedEventAttributes'
{ _sewefeaControl :: !(Maybe Text)
, _sewefeaRunId :: !(Maybe Text)
, _sewefeaWorkflowId :: !Text
, _sewefeaCause :: !SignalExternalWorkflowExecutionFailedCause
, _sewefeaInitiatedEventId :: !Integer
, _sewefeaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'SignalExternalWorkflowExecutionFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sewefeaControl'
--
-- * 'sewefeaRunId'
--
-- * 'sewefeaWorkflowId'
--
-- * 'sewefeaCause'
--
-- * 'sewefeaInitiatedEventId'
--
-- * 'sewefeaDecisionTaskCompletedEventId'
signalExternalWorkflowExecutionFailedEventAttributes
:: Text -- ^ 'sewefeaWorkflowId'
-> SignalExternalWorkflowExecutionFailedCause -- ^ 'sewefeaCause'
-> Integer -- ^ 'sewefeaInitiatedEventId'
-> Integer -- ^ 'sewefeaDecisionTaskCompletedEventId'
-> SignalExternalWorkflowExecutionFailedEventAttributes
signalExternalWorkflowExecutionFailedEventAttributes pWorkflowId_ pCause_ pInitiatedEventId_ pDecisionTaskCompletedEventId_ =
SignalExternalWorkflowExecutionFailedEventAttributes'
{ _sewefeaControl = Nothing
, _sewefeaRunId = Nothing
, _sewefeaWorkflowId = pWorkflowId_
, _sewefeaCause = pCause_
, _sewefeaInitiatedEventId = pInitiatedEventId_
, _sewefeaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | Undocumented member.
sewefeaControl :: Lens' SignalExternalWorkflowExecutionFailedEventAttributes (Maybe Text)
sewefeaControl = lens _sewefeaControl (\ s a -> s{_sewefeaControl = a});
-- | The 'runId' of the external workflow execution that the signal was being
-- delivered to.
sewefeaRunId :: Lens' SignalExternalWorkflowExecutionFailedEventAttributes (Maybe Text)
sewefeaRunId = lens _sewefeaRunId (\ s a -> s{_sewefeaRunId = a});
-- | The 'workflowId' of the external workflow execution that the signal was
-- being delivered to.
sewefeaWorkflowId :: Lens' SignalExternalWorkflowExecutionFailedEventAttributes Text
sewefeaWorkflowId = lens _sewefeaWorkflowId (\ s a -> s{_sewefeaWorkflowId = a});
-- | The cause of the failure. This information is generated by the system
-- and can be useful for diagnostic purposes.
--
-- If __cause__ is set to OPERATION_NOT_PERMITTED, the decision failed
-- because it lacked sufficient permissions. For details and example IAM
-- policies, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
sewefeaCause :: Lens' SignalExternalWorkflowExecutionFailedEventAttributes SignalExternalWorkflowExecutionFailedCause
sewefeaCause = lens _sewefeaCause (\ s a -> s{_sewefeaCause = a});
-- | The ID of the 'SignalExternalWorkflowExecutionInitiated' event
-- corresponding to the 'SignalExternalWorkflowExecution' decision to
-- request this signal. This information can be useful for diagnosing
-- problems by tracing back the chain of events leading up to this event.
sewefeaInitiatedEventId :: Lens' SignalExternalWorkflowExecutionFailedEventAttributes Integer
sewefeaInitiatedEventId = lens _sewefeaInitiatedEventId (\ s a -> s{_sewefeaInitiatedEventId = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'SignalExternalWorkflowExecution'
-- decision for this signal. This information can be useful for diagnosing
-- problems by tracing back the chain of events leading up to this event.
sewefeaDecisionTaskCompletedEventId :: Lens' SignalExternalWorkflowExecutionFailedEventAttributes Integer
sewefeaDecisionTaskCompletedEventId = lens _sewefeaDecisionTaskCompletedEventId (\ s a -> s{_sewefeaDecisionTaskCompletedEventId = a});
instance FromJSON
SignalExternalWorkflowExecutionFailedEventAttributes
where
parseJSON
= withObject
"SignalExternalWorkflowExecutionFailedEventAttributes"
(\ x ->
SignalExternalWorkflowExecutionFailedEventAttributes'
<$>
(x .:? "control") <*> (x .:? "runId") <*>
(x .: "workflowId")
<*> (x .: "cause")
<*> (x .: "initiatedEventId")
<*> (x .: "decisionTaskCompletedEventId"))
-- | Provides details of the 'SignalExternalWorkflowExecutionInitiated'
-- event.
--
-- /See:/ 'signalExternalWorkflowExecutionInitiatedEventAttributes' smart constructor.
data SignalExternalWorkflowExecutionInitiatedEventAttributes = SignalExternalWorkflowExecutionInitiatedEventAttributes'
{ _seweieaControl :: !(Maybe Text)
, _seweieaInput :: !(Maybe Text)
, _seweieaRunId :: !(Maybe Text)
, _seweieaWorkflowId :: !Text
, _seweieaSignalName :: !Text
, _seweieaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'SignalExternalWorkflowExecutionInitiatedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'seweieaControl'
--
-- * 'seweieaInput'
--
-- * 'seweieaRunId'
--
-- * 'seweieaWorkflowId'
--
-- * 'seweieaSignalName'
--
-- * 'seweieaDecisionTaskCompletedEventId'
signalExternalWorkflowExecutionInitiatedEventAttributes
:: Text -- ^ 'seweieaWorkflowId'
-> Text -- ^ 'seweieaSignalName'
-> Integer -- ^ 'seweieaDecisionTaskCompletedEventId'
-> SignalExternalWorkflowExecutionInitiatedEventAttributes
signalExternalWorkflowExecutionInitiatedEventAttributes pWorkflowId_ pSignalName_ pDecisionTaskCompletedEventId_ =
SignalExternalWorkflowExecutionInitiatedEventAttributes'
{ _seweieaControl = Nothing
, _seweieaInput = Nothing
, _seweieaRunId = Nothing
, _seweieaWorkflowId = pWorkflowId_
, _seweieaSignalName = pSignalName_
, _seweieaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | /Optional./ data attached to the event that can be used by the decider
-- in subsequent decision tasks.
seweieaControl :: Lens' SignalExternalWorkflowExecutionInitiatedEventAttributes (Maybe Text)
seweieaControl = lens _seweieaControl (\ s a -> s{_seweieaControl = a});
-- | Input provided to the signal (if any).
seweieaInput :: Lens' SignalExternalWorkflowExecutionInitiatedEventAttributes (Maybe Text)
seweieaInput = lens _seweieaInput (\ s a -> s{_seweieaInput = a});
-- | The 'runId' of the external workflow execution to send the signal to.
seweieaRunId :: Lens' SignalExternalWorkflowExecutionInitiatedEventAttributes (Maybe Text)
seweieaRunId = lens _seweieaRunId (\ s a -> s{_seweieaRunId = a});
-- | The 'workflowId' of the external workflow execution.
seweieaWorkflowId :: Lens' SignalExternalWorkflowExecutionInitiatedEventAttributes Text
seweieaWorkflowId = lens _seweieaWorkflowId (\ s a -> s{_seweieaWorkflowId = a});
-- | The name of the signal.
seweieaSignalName :: Lens' SignalExternalWorkflowExecutionInitiatedEventAttributes Text
seweieaSignalName = lens _seweieaSignalName (\ s a -> s{_seweieaSignalName = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'SignalExternalWorkflowExecution'
-- decision for this signal. This information can be useful for diagnosing
-- problems by tracing back the chain of events leading up to this event.
seweieaDecisionTaskCompletedEventId :: Lens' SignalExternalWorkflowExecutionInitiatedEventAttributes Integer
seweieaDecisionTaskCompletedEventId = lens _seweieaDecisionTaskCompletedEventId (\ s a -> s{_seweieaDecisionTaskCompletedEventId = a});
instance FromJSON
SignalExternalWorkflowExecutionInitiatedEventAttributes
where
parseJSON
= withObject
"SignalExternalWorkflowExecutionInitiatedEventAttributes"
(\ x ->
SignalExternalWorkflowExecutionInitiatedEventAttributes'
<$>
(x .:? "control") <*> (x .:? "input") <*>
(x .:? "runId")
<*> (x .: "workflowId")
<*> (x .: "signalName")
<*> (x .: "decisionTaskCompletedEventId"))
-- | Provides details of the 'StartChildWorkflowExecution' decision.
--
-- __Access Control__
--
-- You can use IAM policies to control this decision\'s access to Amazon
-- SWF resources as follows:
--
-- - Use a 'Resource' element with the domain name to limit the action to
-- only specified domains.
-- - Use an 'Action' element to allow or deny permission to call this
-- action.
-- - Constrain the following parameters by using a 'Condition' element
-- with the appropriate keys.
-- - 'tagList.member.N': The key is \"swf:tagList.N\" where N is the
-- tag number from 0 to 4, inclusive.
-- - 'taskList': String constraint. The key is 'swf:taskList.name'.
-- - 'workflowType.name': String constraint. The key is
-- 'swf:workflowType.name'.
-- - 'workflowType.version': String constraint. The key is
-- 'swf:workflowType.version'.
--
-- If the caller does not have sufficient permissions to invoke the action,
-- or the parameter values fall outside the specified constraints, the
-- action fails. The associated event attribute\'s __cause__ parameter will
-- be set to OPERATION_NOT_PERMITTED. For details and example IAM policies,
-- see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- /See:/ 'startChildWorkflowExecutionDecisionAttributes' smart constructor.
data StartChildWorkflowExecutionDecisionAttributes = StartChildWorkflowExecutionDecisionAttributes'
{ _scwedaControl :: !(Maybe Text)
, _scwedaTagList :: !(Maybe [Text])
, _scwedaTaskStartToCloseTimeout :: !(Maybe Text)
, _scwedaLambdaRole :: !(Maybe Text)
, _scwedaInput :: !(Maybe Text)
, _scwedaExecutionStartToCloseTimeout :: !(Maybe Text)
, _scwedaTaskList :: !(Maybe TaskList)
, _scwedaTaskPriority :: !(Maybe Text)
, _scwedaChildPolicy :: !(Maybe ChildPolicy)
, _scwedaWorkflowType :: !WorkflowType
, _scwedaWorkflowId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'StartChildWorkflowExecutionDecisionAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'scwedaControl'
--
-- * 'scwedaTagList'
--
-- * 'scwedaTaskStartToCloseTimeout'
--
-- * 'scwedaLambdaRole'
--
-- * 'scwedaInput'
--
-- * 'scwedaExecutionStartToCloseTimeout'
--
-- * 'scwedaTaskList'
--
-- * 'scwedaTaskPriority'
--
-- * 'scwedaChildPolicy'
--
-- * 'scwedaWorkflowType'
--
-- * 'scwedaWorkflowId'
startChildWorkflowExecutionDecisionAttributes
:: WorkflowType -- ^ 'scwedaWorkflowType'
-> Text -- ^ 'scwedaWorkflowId'
-> StartChildWorkflowExecutionDecisionAttributes
startChildWorkflowExecutionDecisionAttributes pWorkflowType_ pWorkflowId_ =
StartChildWorkflowExecutionDecisionAttributes'
{ _scwedaControl = Nothing
, _scwedaTagList = Nothing
, _scwedaTaskStartToCloseTimeout = Nothing
, _scwedaLambdaRole = Nothing
, _scwedaInput = Nothing
, _scwedaExecutionStartToCloseTimeout = Nothing
, _scwedaTaskList = Nothing
, _scwedaTaskPriority = Nothing
, _scwedaChildPolicy = Nothing
, _scwedaWorkflowType = pWorkflowType_
, _scwedaWorkflowId = pWorkflowId_
}
-- | /Optional./ Data attached to the event that can be used by the decider
-- in subsequent workflow tasks. This data is not sent to the child
-- workflow execution.
scwedaControl :: Lens' StartChildWorkflowExecutionDecisionAttributes (Maybe Text)
scwedaControl = lens _scwedaControl (\ s a -> s{_scwedaControl = a});
-- | The list of tags to associate with the child workflow execution. A
-- maximum of 5 tags can be specified. You can list workflow executions
-- with a specific tag by calling ListOpenWorkflowExecutions or
-- ListClosedWorkflowExecutions and specifying a TagFilter.
scwedaTagList :: Lens' StartChildWorkflowExecutionDecisionAttributes [Text]
scwedaTagList = lens _scwedaTagList (\ s a -> s{_scwedaTagList = a}) . _Default . _Coerce;
-- | Specifies the maximum duration of decision tasks for this workflow
-- execution. This parameter overrides the 'defaultTaskStartToCloseTimout'
-- specified when registering the workflow type using RegisterWorkflowType.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
--
-- A task start-to-close timeout for this workflow execution must be
-- specified either as a default for the workflow type or through this
-- parameter. If neither this parameter is set nor a default task
-- start-to-close timeout was specified at registration time then a fault
-- will be returned.
scwedaTaskStartToCloseTimeout :: Lens' StartChildWorkflowExecutionDecisionAttributes (Maybe Text)
scwedaTaskStartToCloseTimeout = lens _scwedaTaskStartToCloseTimeout (\ s a -> s{_scwedaTaskStartToCloseTimeout = a});
-- | The ARN of an IAM role that authorizes Amazon SWF to invoke AWS Lambda
-- functions.
--
-- In order for this workflow execution to invoke AWS Lambda functions, an
-- appropriate IAM role must be specified either as a default for the
-- workflow type or through this field.
scwedaLambdaRole :: Lens' StartChildWorkflowExecutionDecisionAttributes (Maybe Text)
scwedaLambdaRole = lens _scwedaLambdaRole (\ s a -> s{_scwedaLambdaRole = a});
-- | The input to be provided to the workflow execution.
scwedaInput :: Lens' StartChildWorkflowExecutionDecisionAttributes (Maybe Text)
scwedaInput = lens _scwedaInput (\ s a -> s{_scwedaInput = a});
-- | The total duration for this workflow execution. This overrides the
-- defaultExecutionStartToCloseTimeout specified when registering the
-- workflow type.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
--
-- An execution start-to-close timeout for this workflow execution must be
-- specified either as a default for the workflow type or through this
-- parameter. If neither this parameter is set nor a default execution
-- start-to-close timeout was specified at registration time then a fault
-- will be returned.
scwedaExecutionStartToCloseTimeout :: Lens' StartChildWorkflowExecutionDecisionAttributes (Maybe Text)
scwedaExecutionStartToCloseTimeout = lens _scwedaExecutionStartToCloseTimeout (\ s a -> s{_scwedaExecutionStartToCloseTimeout = a});
-- | The name of the task list to be used for decision tasks of the child
-- workflow execution.
--
-- A task list for this workflow execution must be specified either as a
-- default for the workflow type or through this parameter. If neither this
-- parameter is set nor a default task list was specified at registration
-- time then a fault will be returned.
--
-- The specified string must not start or end with whitespace. It must not
-- contain a ':' (colon), '\/' (slash), '|' (vertical bar), or any control
-- characters (\\u0000-\\u001f | \\u007f - \\u009f). Also, it must not
-- contain the literal string quotarnquot.
scwedaTaskList :: Lens' StartChildWorkflowExecutionDecisionAttributes (Maybe TaskList)
scwedaTaskList = lens _scwedaTaskList (\ s a -> s{_scwedaTaskList = a});
-- | /Optional./ A task priority that, if set, specifies the priority for a
-- decision task of this workflow execution. This overrides the
-- defaultTaskPriority specified when registering the workflow type. Valid
-- values are integers that range from Java\'s 'Integer.MIN_VALUE'
-- (-2147483648) to 'Integer.MAX_VALUE' (2147483647). Higher numbers
-- indicate higher priority.
--
-- For more information about setting task priority, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/programming-priority.html Setting Task Priority>
-- in the /Amazon Simple Workflow Developer Guide/.
scwedaTaskPriority :: Lens' StartChildWorkflowExecutionDecisionAttributes (Maybe Text)
scwedaTaskPriority = lens _scwedaTaskPriority (\ s a -> s{_scwedaTaskPriority = a});
-- | /Optional./ If set, specifies the policy to use for the child workflow
-- executions if the workflow execution being started is terminated by
-- calling the TerminateWorkflowExecution action explicitly or due to an
-- expired timeout. This policy overrides the default child policy
-- specified when registering the workflow type using RegisterWorkflowType.
--
-- The supported child policies are:
--
-- - __TERMINATE:__ the child executions will be terminated.
-- - __REQUEST_CANCEL:__ a request to cancel will be attempted for each
-- child execution by recording a 'WorkflowExecutionCancelRequested'
-- event in its history. It is up to the decider to take appropriate
-- actions when it receives an execution history with this event.
-- - __ABANDON:__ no action will be taken. The child executions will
-- continue to run.
--
-- A child policy for this workflow execution must be specified either as a
-- default for the workflow type or through this parameter. If neither this
-- parameter is set nor a default child policy was specified at
-- registration time then a fault will be returned.
scwedaChildPolicy :: Lens' StartChildWorkflowExecutionDecisionAttributes (Maybe ChildPolicy)
scwedaChildPolicy = lens _scwedaChildPolicy (\ s a -> s{_scwedaChildPolicy = a});
-- | __Required.__ The type of the workflow execution to be started.
scwedaWorkflowType :: Lens' StartChildWorkflowExecutionDecisionAttributes WorkflowType
scwedaWorkflowType = lens _scwedaWorkflowType (\ s a -> s{_scwedaWorkflowType = a});
-- | __Required.__ The 'workflowId' of the workflow execution.
--
-- The specified string must not start or end with whitespace. It must not
-- contain a ':' (colon), '\/' (slash), '|' (vertical bar), or any control
-- characters (\\u0000-\\u001f | \\u007f - \\u009f). Also, it must not
-- contain the literal string quotarnquot.
scwedaWorkflowId :: Lens' StartChildWorkflowExecutionDecisionAttributes Text
scwedaWorkflowId = lens _scwedaWorkflowId (\ s a -> s{_scwedaWorkflowId = a});
instance ToJSON
StartChildWorkflowExecutionDecisionAttributes where
toJSON
StartChildWorkflowExecutionDecisionAttributes'{..}
= object
(catMaybes
[("control" .=) <$> _scwedaControl,
("tagList" .=) <$> _scwedaTagList,
("taskStartToCloseTimeout" .=) <$>
_scwedaTaskStartToCloseTimeout,
("lambdaRole" .=) <$> _scwedaLambdaRole,
("input" .=) <$> _scwedaInput,
("executionStartToCloseTimeout" .=) <$>
_scwedaExecutionStartToCloseTimeout,
("taskList" .=) <$> _scwedaTaskList,
("taskPriority" .=) <$> _scwedaTaskPriority,
("childPolicy" .=) <$> _scwedaChildPolicy,
Just ("workflowType" .= _scwedaWorkflowType),
Just ("workflowId" .= _scwedaWorkflowId)])
-- | Provides details of the 'StartChildWorkflowExecutionFailed' event.
--
-- /See:/ 'startChildWorkflowExecutionFailedEventAttributes' smart constructor.
data StartChildWorkflowExecutionFailedEventAttributes = StartChildWorkflowExecutionFailedEventAttributes'
{ _scwefeaControl :: !(Maybe Text)
, _scwefeaWorkflowType :: !WorkflowType
, _scwefeaCause :: !StartChildWorkflowExecutionFailedCause
, _scwefeaWorkflowId :: !Text
, _scwefeaInitiatedEventId :: !Integer
, _scwefeaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'StartChildWorkflowExecutionFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'scwefeaControl'
--
-- * 'scwefeaWorkflowType'
--
-- * 'scwefeaCause'
--
-- * 'scwefeaWorkflowId'
--
-- * 'scwefeaInitiatedEventId'
--
-- * 'scwefeaDecisionTaskCompletedEventId'
startChildWorkflowExecutionFailedEventAttributes
:: WorkflowType -- ^ 'scwefeaWorkflowType'
-> StartChildWorkflowExecutionFailedCause -- ^ 'scwefeaCause'
-> Text -- ^ 'scwefeaWorkflowId'
-> Integer -- ^ 'scwefeaInitiatedEventId'
-> Integer -- ^ 'scwefeaDecisionTaskCompletedEventId'
-> StartChildWorkflowExecutionFailedEventAttributes
startChildWorkflowExecutionFailedEventAttributes pWorkflowType_ pCause_ pWorkflowId_ pInitiatedEventId_ pDecisionTaskCompletedEventId_ =
StartChildWorkflowExecutionFailedEventAttributes'
{ _scwefeaControl = Nothing
, _scwefeaWorkflowType = pWorkflowType_
, _scwefeaCause = pCause_
, _scwefeaWorkflowId = pWorkflowId_
, _scwefeaInitiatedEventId = pInitiatedEventId_
, _scwefeaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | Undocumented member.
scwefeaControl :: Lens' StartChildWorkflowExecutionFailedEventAttributes (Maybe Text)
scwefeaControl = lens _scwefeaControl (\ s a -> s{_scwefeaControl = a});
-- | The workflow type provided in the 'StartChildWorkflowExecution' decision
-- that failed.
scwefeaWorkflowType :: Lens' StartChildWorkflowExecutionFailedEventAttributes WorkflowType
scwefeaWorkflowType = lens _scwefeaWorkflowType (\ s a -> s{_scwefeaWorkflowType = a});
-- | The cause of the failure. This information is generated by the system
-- and can be useful for diagnostic purposes.
--
-- If __cause__ is set to OPERATION_NOT_PERMITTED, the decision failed
-- because it lacked sufficient permissions. For details and example IAM
-- policies, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
scwefeaCause :: Lens' StartChildWorkflowExecutionFailedEventAttributes StartChildWorkflowExecutionFailedCause
scwefeaCause = lens _scwefeaCause (\ s a -> s{_scwefeaCause = a});
-- | The 'workflowId' of the child workflow execution.
scwefeaWorkflowId :: Lens' StartChildWorkflowExecutionFailedEventAttributes Text
scwefeaWorkflowId = lens _scwefeaWorkflowId (\ s a -> s{_scwefeaWorkflowId = a});
-- | The ID of the 'StartChildWorkflowExecutionInitiated' event corresponding
-- to the 'StartChildWorkflowExecution' decision to start this child
-- workflow execution. This information can be useful for diagnosing
-- problems by tracing back the chain of events leading up to this event.
scwefeaInitiatedEventId :: Lens' StartChildWorkflowExecutionFailedEventAttributes Integer
scwefeaInitiatedEventId = lens _scwefeaInitiatedEventId (\ s a -> s{_scwefeaInitiatedEventId = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'StartChildWorkflowExecution'
-- decision to request this child workflow execution. This information can
-- be useful for diagnosing problems by tracing back the cause of events.
scwefeaDecisionTaskCompletedEventId :: Lens' StartChildWorkflowExecutionFailedEventAttributes Integer
scwefeaDecisionTaskCompletedEventId = lens _scwefeaDecisionTaskCompletedEventId (\ s a -> s{_scwefeaDecisionTaskCompletedEventId = a});
instance FromJSON
StartChildWorkflowExecutionFailedEventAttributes
where
parseJSON
= withObject
"StartChildWorkflowExecutionFailedEventAttributes"
(\ x ->
StartChildWorkflowExecutionFailedEventAttributes' <$>
(x .:? "control") <*> (x .: "workflowType") <*>
(x .: "cause")
<*> (x .: "workflowId")
<*> (x .: "initiatedEventId")
<*> (x .: "decisionTaskCompletedEventId"))
-- | Provides details of the 'StartChildWorkflowExecutionInitiated' event.
--
-- /See:/ 'startChildWorkflowExecutionInitiatedEventAttributes' smart constructor.
data StartChildWorkflowExecutionInitiatedEventAttributes = StartChildWorkflowExecutionInitiatedEventAttributes'
{ _scweieaControl :: !(Maybe Text)
, _scweieaTagList :: !(Maybe [Text])
, _scweieaTaskStartToCloseTimeout :: !(Maybe Text)
, _scweieaLambdaRole :: !(Maybe Text)
, _scweieaInput :: !(Maybe Text)
, _scweieaExecutionStartToCloseTimeout :: !(Maybe Text)
, _scweieaTaskPriority :: !(Maybe Text)
, _scweieaWorkflowId :: !Text
, _scweieaWorkflowType :: !WorkflowType
, _scweieaTaskList :: !TaskList
, _scweieaDecisionTaskCompletedEventId :: !Integer
, _scweieaChildPolicy :: !ChildPolicy
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'StartChildWorkflowExecutionInitiatedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'scweieaControl'
--
-- * 'scweieaTagList'
--
-- * 'scweieaTaskStartToCloseTimeout'
--
-- * 'scweieaLambdaRole'
--
-- * 'scweieaInput'
--
-- * 'scweieaExecutionStartToCloseTimeout'
--
-- * 'scweieaTaskPriority'
--
-- * 'scweieaWorkflowId'
--
-- * 'scweieaWorkflowType'
--
-- * 'scweieaTaskList'
--
-- * 'scweieaDecisionTaskCompletedEventId'
--
-- * 'scweieaChildPolicy'
startChildWorkflowExecutionInitiatedEventAttributes
:: Text -- ^ 'scweieaWorkflowId'
-> WorkflowType -- ^ 'scweieaWorkflowType'
-> TaskList -- ^ 'scweieaTaskList'
-> Integer -- ^ 'scweieaDecisionTaskCompletedEventId'
-> ChildPolicy -- ^ 'scweieaChildPolicy'
-> StartChildWorkflowExecutionInitiatedEventAttributes
startChildWorkflowExecutionInitiatedEventAttributes pWorkflowId_ pWorkflowType_ pTaskList_ pDecisionTaskCompletedEventId_ pChildPolicy_ =
StartChildWorkflowExecutionInitiatedEventAttributes'
{ _scweieaControl = Nothing
, _scweieaTagList = Nothing
, _scweieaTaskStartToCloseTimeout = Nothing
, _scweieaLambdaRole = Nothing
, _scweieaInput = Nothing
, _scweieaExecutionStartToCloseTimeout = Nothing
, _scweieaTaskPriority = Nothing
, _scweieaWorkflowId = pWorkflowId_
, _scweieaWorkflowType = pWorkflowType_
, _scweieaTaskList = pTaskList_
, _scweieaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
, _scweieaChildPolicy = pChildPolicy_
}
-- | /Optional./ Data attached to the event that can be used by the decider
-- in subsequent decision tasks. This data is not sent to the activity.
scweieaControl :: Lens' StartChildWorkflowExecutionInitiatedEventAttributes (Maybe Text)
scweieaControl = lens _scweieaControl (\ s a -> s{_scweieaControl = a});
-- | The list of tags to associated with the child workflow execution.
scweieaTagList :: Lens' StartChildWorkflowExecutionInitiatedEventAttributes [Text]
scweieaTagList = lens _scweieaTagList (\ s a -> s{_scweieaTagList = a}) . _Default . _Coerce;
-- | The maximum duration allowed for the decision tasks for this workflow
-- execution.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
scweieaTaskStartToCloseTimeout :: Lens' StartChildWorkflowExecutionInitiatedEventAttributes (Maybe Text)
scweieaTaskStartToCloseTimeout = lens _scweieaTaskStartToCloseTimeout (\ s a -> s{_scweieaTaskStartToCloseTimeout = a});
-- | The IAM role attached to this workflow execution to use when invoking
-- AWS Lambda functions.
scweieaLambdaRole :: Lens' StartChildWorkflowExecutionInitiatedEventAttributes (Maybe Text)
scweieaLambdaRole = lens _scweieaLambdaRole (\ s a -> s{_scweieaLambdaRole = a});
-- | The inputs provided to the child workflow execution (if any).
scweieaInput :: Lens' StartChildWorkflowExecutionInitiatedEventAttributes (Maybe Text)
scweieaInput = lens _scweieaInput (\ s a -> s{_scweieaInput = a});
-- | The maximum duration for the child workflow execution. If the workflow
-- execution is not closed within this duration, it will be timed out and
-- force terminated.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
scweieaExecutionStartToCloseTimeout :: Lens' StartChildWorkflowExecutionInitiatedEventAttributes (Maybe Text)
scweieaExecutionStartToCloseTimeout = lens _scweieaExecutionStartToCloseTimeout (\ s a -> s{_scweieaExecutionStartToCloseTimeout = a});
-- | /Optional./ The priority assigned for the decision tasks for this
-- workflow execution. Valid values are integers that range from Java\'s
-- 'Integer.MIN_VALUE' (-2147483648) to 'Integer.MAX_VALUE' (2147483647).
-- Higher numbers indicate higher priority.
--
-- For more information about setting task priority, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/programming-priority.html Setting Task Priority>
-- in the /Amazon Simple Workflow Developer Guide/.
scweieaTaskPriority :: Lens' StartChildWorkflowExecutionInitiatedEventAttributes (Maybe Text)
scweieaTaskPriority = lens _scweieaTaskPriority (\ s a -> s{_scweieaTaskPriority = a});
-- | The 'workflowId' of the child workflow execution.
scweieaWorkflowId :: Lens' StartChildWorkflowExecutionInitiatedEventAttributes Text
scweieaWorkflowId = lens _scweieaWorkflowId (\ s a -> s{_scweieaWorkflowId = a});
-- | The type of the child workflow execution.
scweieaWorkflowType :: Lens' StartChildWorkflowExecutionInitiatedEventAttributes WorkflowType
scweieaWorkflowType = lens _scweieaWorkflowType (\ s a -> s{_scweieaWorkflowType = a});
-- | The name of the task list used for the decision tasks of the child
-- workflow execution.
scweieaTaskList :: Lens' StartChildWorkflowExecutionInitiatedEventAttributes TaskList
scweieaTaskList = lens _scweieaTaskList (\ s a -> s{_scweieaTaskList = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'StartChildWorkflowExecution'
-- decision to request this child workflow execution. This information can
-- be useful for diagnosing problems by tracing back the cause of events.
scweieaDecisionTaskCompletedEventId :: Lens' StartChildWorkflowExecutionInitiatedEventAttributes Integer
scweieaDecisionTaskCompletedEventId = lens _scweieaDecisionTaskCompletedEventId (\ s a -> s{_scweieaDecisionTaskCompletedEventId = a});
-- | The policy to use for the child workflow executions if this execution
-- gets terminated by explicitly calling the TerminateWorkflowExecution
-- action or due to an expired timeout.
--
-- The supported child policies are:
--
-- - __TERMINATE:__ the child executions will be terminated.
-- - __REQUEST_CANCEL:__ a request to cancel will be attempted for each
-- child execution by recording a 'WorkflowExecutionCancelRequested'
-- event in its history. It is up to the decider to take appropriate
-- actions when it receives an execution history with this event.
-- - __ABANDON:__ no action will be taken. The child executions will
-- continue to run.
scweieaChildPolicy :: Lens' StartChildWorkflowExecutionInitiatedEventAttributes ChildPolicy
scweieaChildPolicy = lens _scweieaChildPolicy (\ s a -> s{_scweieaChildPolicy = a});
instance FromJSON
StartChildWorkflowExecutionInitiatedEventAttributes
where
parseJSON
= withObject
"StartChildWorkflowExecutionInitiatedEventAttributes"
(\ x ->
StartChildWorkflowExecutionInitiatedEventAttributes'
<$>
(x .:? "control") <*> (x .:? "tagList" .!= mempty)
<*> (x .:? "taskStartToCloseTimeout")
<*> (x .:? "lambdaRole")
<*> (x .:? "input")
<*> (x .:? "executionStartToCloseTimeout")
<*> (x .:? "taskPriority")
<*> (x .: "workflowId")
<*> (x .: "workflowType")
<*> (x .: "taskList")
<*> (x .: "decisionTaskCompletedEventId")
<*> (x .: "childPolicy"))
-- | Provides details for the 'StartLambdaFunctionFailed' event.
--
-- /See:/ 'startLambdaFunctionFailedEventAttributes' smart constructor.
data StartLambdaFunctionFailedEventAttributes = StartLambdaFunctionFailedEventAttributes'
{ _sScheduledEventId :: !(Maybe Integer)
, _sCause :: !(Maybe StartLambdaFunctionFailedCause)
, _sMessage :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'StartLambdaFunctionFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sScheduledEventId'
--
-- * 'sCause'
--
-- * 'sMessage'
startLambdaFunctionFailedEventAttributes
:: StartLambdaFunctionFailedEventAttributes
startLambdaFunctionFailedEventAttributes =
StartLambdaFunctionFailedEventAttributes'
{ _sScheduledEventId = Nothing
, _sCause = Nothing
, _sMessage = Nothing
}
-- | The ID of the 'LambdaFunctionScheduled' event that was recorded when
-- this AWS Lambda function was scheduled. This information can be useful
-- for diagnosing problems by tracing back the chain of events leading up
-- to this event.
sScheduledEventId :: Lens' StartLambdaFunctionFailedEventAttributes (Maybe Integer)
sScheduledEventId = lens _sScheduledEventId (\ s a -> s{_sScheduledEventId = a});
-- | The cause of the failure. This information is generated by the system
-- and can be useful for diagnostic purposes.
--
-- If __cause__ is set to OPERATION_NOT_PERMITTED, the decision failed
-- because it lacked sufficient permissions. For details and example IAM
-- policies, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
sCause :: Lens' StartLambdaFunctionFailedEventAttributes (Maybe StartLambdaFunctionFailedCause)
sCause = lens _sCause (\ s a -> s{_sCause = a});
-- | The error message (if any).
sMessage :: Lens' StartLambdaFunctionFailedEventAttributes (Maybe Text)
sMessage = lens _sMessage (\ s a -> s{_sMessage = a});
instance FromJSON
StartLambdaFunctionFailedEventAttributes where
parseJSON
= withObject
"StartLambdaFunctionFailedEventAttributes"
(\ x ->
StartLambdaFunctionFailedEventAttributes' <$>
(x .:? "scheduledEventId") <*> (x .:? "cause") <*>
(x .:? "message"))
-- | Provides details of the 'StartTimer' decision.
--
-- __Access Control__
--
-- You can use IAM policies to control this decision\'s access to Amazon
-- SWF resources as follows:
--
-- - Use a 'Resource' element with the domain name to limit the action to
-- only specified domains.
-- - Use an 'Action' element to allow or deny permission to call this
-- action.
-- - You cannot use an IAM policy to constrain this action\'s parameters.
--
-- If the caller does not have sufficient permissions to invoke the action,
-- or the parameter values fall outside the specified constraints, the
-- action fails. The associated event attribute\'s __cause__ parameter will
-- be set to OPERATION_NOT_PERMITTED. For details and example IAM policies,
-- see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- /See:/ 'startTimerDecisionAttributes' smart constructor.
data StartTimerDecisionAttributes = StartTimerDecisionAttributes'
{ _stdaControl :: !(Maybe Text)
, _stdaTimerId :: !Text
, _stdaStartToFireTimeout :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'StartTimerDecisionAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'stdaControl'
--
-- * 'stdaTimerId'
--
-- * 'stdaStartToFireTimeout'
startTimerDecisionAttributes
:: Text -- ^ 'stdaTimerId'
-> Text -- ^ 'stdaStartToFireTimeout'
-> StartTimerDecisionAttributes
startTimerDecisionAttributes pTimerId_ pStartToFireTimeout_ =
StartTimerDecisionAttributes'
{ _stdaControl = Nothing
, _stdaTimerId = pTimerId_
, _stdaStartToFireTimeout = pStartToFireTimeout_
}
-- | /Optional./ Data attached to the event that can be used by the decider
-- in subsequent workflow tasks.
stdaControl :: Lens' StartTimerDecisionAttributes (Maybe Text)
stdaControl = lens _stdaControl (\ s a -> s{_stdaControl = a});
-- | __Required.__ The unique ID of the timer.
--
-- The specified string must not start or end with whitespace. It must not
-- contain a ':' (colon), '\/' (slash), '|' (vertical bar), or any control
-- characters (\\u0000-\\u001f | \\u007f - \\u009f). Also, it must not
-- contain the literal string quotarnquot.
stdaTimerId :: Lens' StartTimerDecisionAttributes Text
stdaTimerId = lens _stdaTimerId (\ s a -> s{_stdaTimerId = a});
-- | __Required.__ The duration to wait before firing the timer.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0.
stdaStartToFireTimeout :: Lens' StartTimerDecisionAttributes Text
stdaStartToFireTimeout = lens _stdaStartToFireTimeout (\ s a -> s{_stdaStartToFireTimeout = a});
instance ToJSON StartTimerDecisionAttributes where
toJSON StartTimerDecisionAttributes'{..}
= object
(catMaybes
[("control" .=) <$> _stdaControl,
Just ("timerId" .= _stdaTimerId),
Just
("startToFireTimeout" .= _stdaStartToFireTimeout)])
-- | Provides details of the 'StartTimerFailed' event.
--
-- /See:/ 'startTimerFailedEventAttributes' smart constructor.
data StartTimerFailedEventAttributes = StartTimerFailedEventAttributes'
{ _stfeaTimerId :: !Text
, _stfeaCause :: !StartTimerFailedCause
, _stfeaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'StartTimerFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'stfeaTimerId'
--
-- * 'stfeaCause'
--
-- * 'stfeaDecisionTaskCompletedEventId'
startTimerFailedEventAttributes
:: Text -- ^ 'stfeaTimerId'
-> StartTimerFailedCause -- ^ 'stfeaCause'
-> Integer -- ^ 'stfeaDecisionTaskCompletedEventId'
-> StartTimerFailedEventAttributes
startTimerFailedEventAttributes pTimerId_ pCause_ pDecisionTaskCompletedEventId_ =
StartTimerFailedEventAttributes'
{ _stfeaTimerId = pTimerId_
, _stfeaCause = pCause_
, _stfeaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | The timerId provided in the 'StartTimer' decision that failed.
stfeaTimerId :: Lens' StartTimerFailedEventAttributes Text
stfeaTimerId = lens _stfeaTimerId (\ s a -> s{_stfeaTimerId = a});
-- | The cause of the failure. This information is generated by the system
-- and can be useful for diagnostic purposes.
--
-- If __cause__ is set to OPERATION_NOT_PERMITTED, the decision failed
-- because it lacked sufficient permissions. For details and example IAM
-- policies, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
stfeaCause :: Lens' StartTimerFailedEventAttributes StartTimerFailedCause
stfeaCause = lens _stfeaCause (\ s a -> s{_stfeaCause = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'StartTimer' decision for this
-- activity task. This information can be useful for diagnosing problems by
-- tracing back the chain of events leading up to this event.
stfeaDecisionTaskCompletedEventId :: Lens' StartTimerFailedEventAttributes Integer
stfeaDecisionTaskCompletedEventId = lens _stfeaDecisionTaskCompletedEventId (\ s a -> s{_stfeaDecisionTaskCompletedEventId = a});
instance FromJSON StartTimerFailedEventAttributes
where
parseJSON
= withObject "StartTimerFailedEventAttributes"
(\ x ->
StartTimerFailedEventAttributes' <$>
(x .: "timerId") <*> (x .: "cause") <*>
(x .: "decisionTaskCompletedEventId"))
-- | Used to filter the workflow executions in visibility APIs based on a
-- tag.
--
-- /See:/ 'tagFilter' smart constructor.
newtype TagFilter = TagFilter'
{ _tfTag :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'TagFilter' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tfTag'
tagFilter
:: Text -- ^ 'tfTag'
-> TagFilter
tagFilter pTag_ =
TagFilter'
{ _tfTag = pTag_
}
-- | __Required.__ Specifies the tag that must be associated with the
-- execution for it to meet the filter criteria.
tfTag :: Lens' TagFilter Text
tfTag = lens _tfTag (\ s a -> s{_tfTag = a});
instance ToJSON TagFilter where
toJSON TagFilter'{..}
= object (catMaybes [Just ("tag" .= _tfTag)])
-- | Represents a task list.
--
-- /See:/ 'taskList' smart constructor.
newtype TaskList = TaskList'
{ _tlName :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'TaskList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tlName'
taskList
:: Text -- ^ 'tlName'
-> TaskList
taskList pName_ =
TaskList'
{ _tlName = pName_
}
-- | The name of the task list.
tlName :: Lens' TaskList Text
tlName = lens _tlName (\ s a -> s{_tlName = a});
instance FromJSON TaskList where
parseJSON
= withObject "TaskList"
(\ x -> TaskList' <$> (x .: "name"))
instance ToJSON TaskList where
toJSON TaskList'{..}
= object (catMaybes [Just ("name" .= _tlName)])
-- | Provides details of the 'TimerCanceled' event.
--
-- /See:/ 'timerCanceledEventAttributes' smart constructor.
data TimerCanceledEventAttributes = TimerCanceledEventAttributes'
{ _tceaTimerId :: !Text
, _tceaStartedEventId :: !Integer
, _tceaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'TimerCanceledEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tceaTimerId'
--
-- * 'tceaStartedEventId'
--
-- * 'tceaDecisionTaskCompletedEventId'
timerCanceledEventAttributes
:: Text -- ^ 'tceaTimerId'
-> Integer -- ^ 'tceaStartedEventId'
-> Integer -- ^ 'tceaDecisionTaskCompletedEventId'
-> TimerCanceledEventAttributes
timerCanceledEventAttributes pTimerId_ pStartedEventId_ pDecisionTaskCompletedEventId_ =
TimerCanceledEventAttributes'
{ _tceaTimerId = pTimerId_
, _tceaStartedEventId = pStartedEventId_
, _tceaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | The unique ID of the timer that was canceled.
tceaTimerId :: Lens' TimerCanceledEventAttributes Text
tceaTimerId = lens _tceaTimerId (\ s a -> s{_tceaTimerId = a});
-- | The ID of the 'TimerStarted' event that was recorded when this timer was
-- started. This information can be useful for diagnosing problems by
-- tracing back the chain of events leading up to this event.
tceaStartedEventId :: Lens' TimerCanceledEventAttributes Integer
tceaStartedEventId = lens _tceaStartedEventId (\ s a -> s{_tceaStartedEventId = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'CancelTimer' decision to cancel this
-- timer. This information can be useful for diagnosing problems by tracing
-- back the chain of events leading up to this event.
tceaDecisionTaskCompletedEventId :: Lens' TimerCanceledEventAttributes Integer
tceaDecisionTaskCompletedEventId = lens _tceaDecisionTaskCompletedEventId (\ s a -> s{_tceaDecisionTaskCompletedEventId = a});
instance FromJSON TimerCanceledEventAttributes where
parseJSON
= withObject "TimerCanceledEventAttributes"
(\ x ->
TimerCanceledEventAttributes' <$>
(x .: "timerId") <*> (x .: "startedEventId") <*>
(x .: "decisionTaskCompletedEventId"))
-- | Provides details of the 'TimerFired' event.
--
-- /See:/ 'timerFiredEventAttributes' smart constructor.
data TimerFiredEventAttributes = TimerFiredEventAttributes'
{ _tfeaTimerId :: !Text
, _tfeaStartedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'TimerFiredEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tfeaTimerId'
--
-- * 'tfeaStartedEventId'
timerFiredEventAttributes
:: Text -- ^ 'tfeaTimerId'
-> Integer -- ^ 'tfeaStartedEventId'
-> TimerFiredEventAttributes
timerFiredEventAttributes pTimerId_ pStartedEventId_ =
TimerFiredEventAttributes'
{ _tfeaTimerId = pTimerId_
, _tfeaStartedEventId = pStartedEventId_
}
-- | The unique ID of the timer that fired.
tfeaTimerId :: Lens' TimerFiredEventAttributes Text
tfeaTimerId = lens _tfeaTimerId (\ s a -> s{_tfeaTimerId = a});
-- | The ID of the 'TimerStarted' event that was recorded when this timer was
-- started. This information can be useful for diagnosing problems by
-- tracing back the chain of events leading up to this event.
tfeaStartedEventId :: Lens' TimerFiredEventAttributes Integer
tfeaStartedEventId = lens _tfeaStartedEventId (\ s a -> s{_tfeaStartedEventId = a});
instance FromJSON TimerFiredEventAttributes where
parseJSON
= withObject "TimerFiredEventAttributes"
(\ x ->
TimerFiredEventAttributes' <$>
(x .: "timerId") <*> (x .: "startedEventId"))
-- | Provides details of the 'TimerStarted' event.
--
-- /See:/ 'timerStartedEventAttributes' smart constructor.
data TimerStartedEventAttributes = TimerStartedEventAttributes'
{ _tseaControl :: !(Maybe Text)
, _tseaTimerId :: !Text
, _tseaStartToFireTimeout :: !Text
, _tseaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'TimerStartedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tseaControl'
--
-- * 'tseaTimerId'
--
-- * 'tseaStartToFireTimeout'
--
-- * 'tseaDecisionTaskCompletedEventId'
timerStartedEventAttributes
:: Text -- ^ 'tseaTimerId'
-> Text -- ^ 'tseaStartToFireTimeout'
-> Integer -- ^ 'tseaDecisionTaskCompletedEventId'
-> TimerStartedEventAttributes
timerStartedEventAttributes pTimerId_ pStartToFireTimeout_ pDecisionTaskCompletedEventId_ =
TimerStartedEventAttributes'
{ _tseaControl = Nothing
, _tseaTimerId = pTimerId_
, _tseaStartToFireTimeout = pStartToFireTimeout_
, _tseaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | /Optional./ Data attached to the event that can be used by the decider
-- in subsequent workflow tasks.
tseaControl :: Lens' TimerStartedEventAttributes (Maybe Text)
tseaControl = lens _tseaControl (\ s a -> s{_tseaControl = a});
-- | The unique ID of the timer that was started.
tseaTimerId :: Lens' TimerStartedEventAttributes Text
tseaTimerId = lens _tseaTimerId (\ s a -> s{_tseaTimerId = a});
-- | The duration of time after which the timer will fire.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0.
tseaStartToFireTimeout :: Lens' TimerStartedEventAttributes Text
tseaStartToFireTimeout = lens _tseaStartToFireTimeout (\ s a -> s{_tseaStartToFireTimeout = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'StartTimer' decision for this
-- activity task. This information can be useful for diagnosing problems by
-- tracing back the chain of events leading up to this event.
tseaDecisionTaskCompletedEventId :: Lens' TimerStartedEventAttributes Integer
tseaDecisionTaskCompletedEventId = lens _tseaDecisionTaskCompletedEventId (\ s a -> s{_tseaDecisionTaskCompletedEventId = a});
instance FromJSON TimerStartedEventAttributes where
parseJSON
= withObject "TimerStartedEventAttributes"
(\ x ->
TimerStartedEventAttributes' <$>
(x .:? "control") <*> (x .: "timerId") <*>
(x .: "startToFireTimeout")
<*> (x .: "decisionTaskCompletedEventId"))
-- | Represents a workflow execution.
--
-- /See:/ 'workflowExecution' smart constructor.
data WorkflowExecution = WorkflowExecution'
{ _weWorkflowId :: !Text
, _weRunId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowExecution' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'weWorkflowId'
--
-- * 'weRunId'
workflowExecution
:: Text -- ^ 'weWorkflowId'
-> Text -- ^ 'weRunId'
-> WorkflowExecution
workflowExecution pWorkflowId_ pRunId_ =
WorkflowExecution'
{ _weWorkflowId = pWorkflowId_
, _weRunId = pRunId_
}
-- | The user defined identifier associated with the workflow execution.
weWorkflowId :: Lens' WorkflowExecution Text
weWorkflowId = lens _weWorkflowId (\ s a -> s{_weWorkflowId = a});
-- | A system-generated unique identifier for the workflow execution.
weRunId :: Lens' WorkflowExecution Text
weRunId = lens _weRunId (\ s a -> s{_weRunId = a});
instance FromJSON WorkflowExecution where
parseJSON
= withObject "WorkflowExecution"
(\ x ->
WorkflowExecution' <$>
(x .: "workflowId") <*> (x .: "runId"))
instance ToJSON WorkflowExecution where
toJSON WorkflowExecution'{..}
= object
(catMaybes
[Just ("workflowId" .= _weWorkflowId),
Just ("runId" .= _weRunId)])
-- | Provides details of the 'WorkflowExecutionCancelRequested' event.
--
-- /See:/ 'workflowExecutionCancelRequestedEventAttributes' smart constructor.
data WorkflowExecutionCancelRequestedEventAttributes = WorkflowExecutionCancelRequestedEventAttributes'
{ _wecreaExternalWorkflowExecution :: !(Maybe WorkflowExecution)
, _wecreaExternalInitiatedEventId :: !(Maybe Integer)
, _wecreaCause :: !(Maybe WorkflowExecutionCancelRequestedCause)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowExecutionCancelRequestedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wecreaExternalWorkflowExecution'
--
-- * 'wecreaExternalInitiatedEventId'
--
-- * 'wecreaCause'
workflowExecutionCancelRequestedEventAttributes
:: WorkflowExecutionCancelRequestedEventAttributes
workflowExecutionCancelRequestedEventAttributes =
WorkflowExecutionCancelRequestedEventAttributes'
{ _wecreaExternalWorkflowExecution = Nothing
, _wecreaExternalInitiatedEventId = Nothing
, _wecreaCause = Nothing
}
-- | The external workflow execution for which the cancellation was
-- requested.
wecreaExternalWorkflowExecution :: Lens' WorkflowExecutionCancelRequestedEventAttributes (Maybe WorkflowExecution)
wecreaExternalWorkflowExecution = lens _wecreaExternalWorkflowExecution (\ s a -> s{_wecreaExternalWorkflowExecution = a});
-- | The ID of the 'RequestCancelExternalWorkflowExecutionInitiated' event
-- corresponding to the 'RequestCancelExternalWorkflowExecution' decision
-- to cancel this workflow execution.The source event with this ID can be
-- found in the history of the source workflow execution. This information
-- can be useful for diagnosing problems by tracing back the chain of
-- events leading up to this event.
wecreaExternalInitiatedEventId :: Lens' WorkflowExecutionCancelRequestedEventAttributes (Maybe Integer)
wecreaExternalInitiatedEventId = lens _wecreaExternalInitiatedEventId (\ s a -> s{_wecreaExternalInitiatedEventId = a});
-- | If set, indicates that the request to cancel the workflow execution was
-- automatically generated, and specifies the cause. This happens if the
-- parent workflow execution times out or is terminated, and the child
-- policy is set to cancel child executions.
wecreaCause :: Lens' WorkflowExecutionCancelRequestedEventAttributes (Maybe WorkflowExecutionCancelRequestedCause)
wecreaCause = lens _wecreaCause (\ s a -> s{_wecreaCause = a});
instance FromJSON
WorkflowExecutionCancelRequestedEventAttributes where
parseJSON
= withObject
"WorkflowExecutionCancelRequestedEventAttributes"
(\ x ->
WorkflowExecutionCancelRequestedEventAttributes' <$>
(x .:? "externalWorkflowExecution") <*>
(x .:? "externalInitiatedEventId")
<*> (x .:? "cause"))
-- | Provides details of the 'WorkflowExecutionCanceled' event.
--
-- /See:/ 'workflowExecutionCanceledEventAttributes' smart constructor.
data WorkflowExecutionCanceledEventAttributes = WorkflowExecutionCanceledEventAttributes'
{ _wDetails :: !(Maybe Text)
, _wDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowExecutionCanceledEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wDetails'
--
-- * 'wDecisionTaskCompletedEventId'
workflowExecutionCanceledEventAttributes
:: Integer -- ^ 'wDecisionTaskCompletedEventId'
-> WorkflowExecutionCanceledEventAttributes
workflowExecutionCanceledEventAttributes pDecisionTaskCompletedEventId_ =
WorkflowExecutionCanceledEventAttributes'
{ _wDetails = Nothing
, _wDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | Details for the cancellation (if any).
wDetails :: Lens' WorkflowExecutionCanceledEventAttributes (Maybe Text)
wDetails = lens _wDetails (\ s a -> s{_wDetails = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'CancelWorkflowExecution' decision
-- for this cancellation request. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
wDecisionTaskCompletedEventId :: Lens' WorkflowExecutionCanceledEventAttributes Integer
wDecisionTaskCompletedEventId = lens _wDecisionTaskCompletedEventId (\ s a -> s{_wDecisionTaskCompletedEventId = a});
instance FromJSON
WorkflowExecutionCanceledEventAttributes where
parseJSON
= withObject
"WorkflowExecutionCanceledEventAttributes"
(\ x ->
WorkflowExecutionCanceledEventAttributes' <$>
(x .:? "details") <*>
(x .: "decisionTaskCompletedEventId"))
-- | Provides details of the 'WorkflowExecutionCompleted' event.
--
-- /See:/ 'workflowExecutionCompletedEventAttributes' smart constructor.
data WorkflowExecutionCompletedEventAttributes = WorkflowExecutionCompletedEventAttributes'
{ _weceaResult :: !(Maybe Text)
, _weceaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowExecutionCompletedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'weceaResult'
--
-- * 'weceaDecisionTaskCompletedEventId'
workflowExecutionCompletedEventAttributes
:: Integer -- ^ 'weceaDecisionTaskCompletedEventId'
-> WorkflowExecutionCompletedEventAttributes
workflowExecutionCompletedEventAttributes pDecisionTaskCompletedEventId_ =
WorkflowExecutionCompletedEventAttributes'
{ _weceaResult = Nothing
, _weceaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | The result produced by the workflow execution upon successful
-- completion.
weceaResult :: Lens' WorkflowExecutionCompletedEventAttributes (Maybe Text)
weceaResult = lens _weceaResult (\ s a -> s{_weceaResult = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'CompleteWorkflowExecution' decision
-- to complete this execution. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
weceaDecisionTaskCompletedEventId :: Lens' WorkflowExecutionCompletedEventAttributes Integer
weceaDecisionTaskCompletedEventId = lens _weceaDecisionTaskCompletedEventId (\ s a -> s{_weceaDecisionTaskCompletedEventId = a});
instance FromJSON
WorkflowExecutionCompletedEventAttributes where
parseJSON
= withObject
"WorkflowExecutionCompletedEventAttributes"
(\ x ->
WorkflowExecutionCompletedEventAttributes' <$>
(x .:? "result") <*>
(x .: "decisionTaskCompletedEventId"))
-- | The configuration settings for a workflow execution including timeout
-- values, tasklist etc. These configuration settings are determined from
-- the defaults specified when registering the workflow type and those
-- specified when starting the workflow execution.
--
-- /See:/ 'workflowExecutionConfiguration' smart constructor.
data WorkflowExecutionConfiguration = WorkflowExecutionConfiguration'
{ _wecLambdaRole :: !(Maybe Text)
, _wecTaskPriority :: !(Maybe Text)
, _wecTaskStartToCloseTimeout :: !Text
, _wecExecutionStartToCloseTimeout :: !Text
, _wecTaskList :: !TaskList
, _wecChildPolicy :: !ChildPolicy
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowExecutionConfiguration' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wecLambdaRole'
--
-- * 'wecTaskPriority'
--
-- * 'wecTaskStartToCloseTimeout'
--
-- * 'wecExecutionStartToCloseTimeout'
--
-- * 'wecTaskList'
--
-- * 'wecChildPolicy'
workflowExecutionConfiguration
:: Text -- ^ 'wecTaskStartToCloseTimeout'
-> Text -- ^ 'wecExecutionStartToCloseTimeout'
-> TaskList -- ^ 'wecTaskList'
-> ChildPolicy -- ^ 'wecChildPolicy'
-> WorkflowExecutionConfiguration
workflowExecutionConfiguration pTaskStartToCloseTimeout_ pExecutionStartToCloseTimeout_ pTaskList_ pChildPolicy_ =
WorkflowExecutionConfiguration'
{ _wecLambdaRole = Nothing
, _wecTaskPriority = Nothing
, _wecTaskStartToCloseTimeout = pTaskStartToCloseTimeout_
, _wecExecutionStartToCloseTimeout = pExecutionStartToCloseTimeout_
, _wecTaskList = pTaskList_
, _wecChildPolicy = pChildPolicy_
}
-- | The IAM role used by this workflow execution when invoking AWS Lambda
-- functions.
wecLambdaRole :: Lens' WorkflowExecutionConfiguration (Maybe Text)
wecLambdaRole = lens _wecLambdaRole (\ s a -> s{_wecLambdaRole = a});
-- | The priority assigned to decision tasks for this workflow execution.
-- Valid values are integers that range from Java\'s 'Integer.MIN_VALUE'
-- (-2147483648) to 'Integer.MAX_VALUE' (2147483647). Higher numbers
-- indicate higher priority.
--
-- For more information about setting task priority, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/programming-priority.html Setting Task Priority>
-- in the /Amazon Simple Workflow Developer Guide/.
wecTaskPriority :: Lens' WorkflowExecutionConfiguration (Maybe Text)
wecTaskPriority = lens _wecTaskPriority (\ s a -> s{_wecTaskPriority = a});
-- | The maximum duration allowed for decision tasks for this workflow
-- execution.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
wecTaskStartToCloseTimeout :: Lens' WorkflowExecutionConfiguration Text
wecTaskStartToCloseTimeout = lens _wecTaskStartToCloseTimeout (\ s a -> s{_wecTaskStartToCloseTimeout = a});
-- | The total duration for this workflow execution.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
wecExecutionStartToCloseTimeout :: Lens' WorkflowExecutionConfiguration Text
wecExecutionStartToCloseTimeout = lens _wecExecutionStartToCloseTimeout (\ s a -> s{_wecExecutionStartToCloseTimeout = a});
-- | The task list used for the decision tasks generated for this workflow
-- execution.
wecTaskList :: Lens' WorkflowExecutionConfiguration TaskList
wecTaskList = lens _wecTaskList (\ s a -> s{_wecTaskList = a});
-- | The policy to use for the child workflow executions if this workflow
-- execution is terminated, by calling the TerminateWorkflowExecution
-- action explicitly or due to an expired timeout.
--
-- The supported child policies are:
--
-- - __TERMINATE:__ the child executions will be terminated.
-- - __REQUEST_CANCEL:__ a request to cancel will be attempted for each
-- child execution by recording a 'WorkflowExecutionCancelRequested'
-- event in its history. It is up to the decider to take appropriate
-- actions when it receives an execution history with this event.
-- - __ABANDON:__ no action will be taken. The child executions will
-- continue to run.
wecChildPolicy :: Lens' WorkflowExecutionConfiguration ChildPolicy
wecChildPolicy = lens _wecChildPolicy (\ s a -> s{_wecChildPolicy = a});
instance FromJSON WorkflowExecutionConfiguration
where
parseJSON
= withObject "WorkflowExecutionConfiguration"
(\ x ->
WorkflowExecutionConfiguration' <$>
(x .:? "lambdaRole") <*> (x .:? "taskPriority") <*>
(x .: "taskStartToCloseTimeout")
<*> (x .: "executionStartToCloseTimeout")
<*> (x .: "taskList")
<*> (x .: "childPolicy"))
-- | Provides details of the 'WorkflowExecutionContinuedAsNew' event.
--
-- /See:/ 'workflowExecutionContinuedAsNewEventAttributes' smart constructor.
data WorkflowExecutionContinuedAsNewEventAttributes = WorkflowExecutionContinuedAsNewEventAttributes'
{ _wecaneaTagList :: !(Maybe [Text])
, _wecaneaTaskStartToCloseTimeout :: !(Maybe Text)
, _wecaneaLambdaRole :: !(Maybe Text)
, _wecaneaInput :: !(Maybe Text)
, _wecaneaExecutionStartToCloseTimeout :: !(Maybe Text)
, _wecaneaTaskPriority :: !(Maybe Text)
, _wecaneaDecisionTaskCompletedEventId :: !Integer
, _wecaneaNewExecutionRunId :: !Text
, _wecaneaTaskList :: !TaskList
, _wecaneaChildPolicy :: !ChildPolicy
, _wecaneaWorkflowType :: !WorkflowType
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowExecutionContinuedAsNewEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wecaneaTagList'
--
-- * 'wecaneaTaskStartToCloseTimeout'
--
-- * 'wecaneaLambdaRole'
--
-- * 'wecaneaInput'
--
-- * 'wecaneaExecutionStartToCloseTimeout'
--
-- * 'wecaneaTaskPriority'
--
-- * 'wecaneaDecisionTaskCompletedEventId'
--
-- * 'wecaneaNewExecutionRunId'
--
-- * 'wecaneaTaskList'
--
-- * 'wecaneaChildPolicy'
--
-- * 'wecaneaWorkflowType'
workflowExecutionContinuedAsNewEventAttributes
:: Integer -- ^ 'wecaneaDecisionTaskCompletedEventId'
-> Text -- ^ 'wecaneaNewExecutionRunId'
-> TaskList -- ^ 'wecaneaTaskList'
-> ChildPolicy -- ^ 'wecaneaChildPolicy'
-> WorkflowType -- ^ 'wecaneaWorkflowType'
-> WorkflowExecutionContinuedAsNewEventAttributes
workflowExecutionContinuedAsNewEventAttributes pDecisionTaskCompletedEventId_ pNewExecutionRunId_ pTaskList_ pChildPolicy_ pWorkflowType_ =
WorkflowExecutionContinuedAsNewEventAttributes'
{ _wecaneaTagList = Nothing
, _wecaneaTaskStartToCloseTimeout = Nothing
, _wecaneaLambdaRole = Nothing
, _wecaneaInput = Nothing
, _wecaneaExecutionStartToCloseTimeout = Nothing
, _wecaneaTaskPriority = Nothing
, _wecaneaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
, _wecaneaNewExecutionRunId = pNewExecutionRunId_
, _wecaneaTaskList = pTaskList_
, _wecaneaChildPolicy = pChildPolicy_
, _wecaneaWorkflowType = pWorkflowType_
}
-- | The list of tags associated with the new workflow execution.
wecaneaTagList :: Lens' WorkflowExecutionContinuedAsNewEventAttributes [Text]
wecaneaTagList = lens _wecaneaTagList (\ s a -> s{_wecaneaTagList = a}) . _Default . _Coerce;
-- | The maximum duration of decision tasks for the new workflow execution.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
wecaneaTaskStartToCloseTimeout :: Lens' WorkflowExecutionContinuedAsNewEventAttributes (Maybe Text)
wecaneaTaskStartToCloseTimeout = lens _wecaneaTaskStartToCloseTimeout (\ s a -> s{_wecaneaTaskStartToCloseTimeout = a});
-- | The IAM role attached to this workflow execution to use when invoking
-- AWS Lambda functions.
wecaneaLambdaRole :: Lens' WorkflowExecutionContinuedAsNewEventAttributes (Maybe Text)
wecaneaLambdaRole = lens _wecaneaLambdaRole (\ s a -> s{_wecaneaLambdaRole = a});
-- | The input provided to the new workflow execution.
wecaneaInput :: Lens' WorkflowExecutionContinuedAsNewEventAttributes (Maybe Text)
wecaneaInput = lens _wecaneaInput (\ s a -> s{_wecaneaInput = a});
-- | The total duration allowed for the new workflow execution.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
wecaneaExecutionStartToCloseTimeout :: Lens' WorkflowExecutionContinuedAsNewEventAttributes (Maybe Text)
wecaneaExecutionStartToCloseTimeout = lens _wecaneaExecutionStartToCloseTimeout (\ s a -> s{_wecaneaExecutionStartToCloseTimeout = a});
-- | Undocumented member.
wecaneaTaskPriority :: Lens' WorkflowExecutionContinuedAsNewEventAttributes (Maybe Text)
wecaneaTaskPriority = lens _wecaneaTaskPriority (\ s a -> s{_wecaneaTaskPriority = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'ContinueAsNewWorkflowExecution'
-- decision that started this execution. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
wecaneaDecisionTaskCompletedEventId :: Lens' WorkflowExecutionContinuedAsNewEventAttributes Integer
wecaneaDecisionTaskCompletedEventId = lens _wecaneaDecisionTaskCompletedEventId (\ s a -> s{_wecaneaDecisionTaskCompletedEventId = a});
-- | The 'runId' of the new workflow execution.
wecaneaNewExecutionRunId :: Lens' WorkflowExecutionContinuedAsNewEventAttributes Text
wecaneaNewExecutionRunId = lens _wecaneaNewExecutionRunId (\ s a -> s{_wecaneaNewExecutionRunId = a});
-- | Undocumented member.
wecaneaTaskList :: Lens' WorkflowExecutionContinuedAsNewEventAttributes TaskList
wecaneaTaskList = lens _wecaneaTaskList (\ s a -> s{_wecaneaTaskList = a});
-- | The policy to use for the child workflow executions of the new execution
-- if it is terminated by calling the TerminateWorkflowExecution action
-- explicitly or due to an expired timeout.
--
-- The supported child policies are:
--
-- - __TERMINATE:__ the child executions will be terminated.
-- - __REQUEST_CANCEL:__ a request to cancel will be attempted for each
-- child execution by recording a 'WorkflowExecutionCancelRequested'
-- event in its history. It is up to the decider to take appropriate
-- actions when it receives an execution history with this event.
-- - __ABANDON:__ no action will be taken. The child executions will
-- continue to run.
wecaneaChildPolicy :: Lens' WorkflowExecutionContinuedAsNewEventAttributes ChildPolicy
wecaneaChildPolicy = lens _wecaneaChildPolicy (\ s a -> s{_wecaneaChildPolicy = a});
-- | Undocumented member.
wecaneaWorkflowType :: Lens' WorkflowExecutionContinuedAsNewEventAttributes WorkflowType
wecaneaWorkflowType = lens _wecaneaWorkflowType (\ s a -> s{_wecaneaWorkflowType = a});
instance FromJSON
WorkflowExecutionContinuedAsNewEventAttributes where
parseJSON
= withObject
"WorkflowExecutionContinuedAsNewEventAttributes"
(\ x ->
WorkflowExecutionContinuedAsNewEventAttributes' <$>
(x .:? "tagList" .!= mempty) <*>
(x .:? "taskStartToCloseTimeout")
<*> (x .:? "lambdaRole")
<*> (x .:? "input")
<*> (x .:? "executionStartToCloseTimeout")
<*> (x .:? "taskPriority")
<*> (x .: "decisionTaskCompletedEventId")
<*> (x .: "newExecutionRunId")
<*> (x .: "taskList")
<*> (x .: "childPolicy")
<*> (x .: "workflowType"))
-- | Contains the count of workflow executions returned from
-- CountOpenWorkflowExecutions or CountClosedWorkflowExecutions
--
-- /See:/ 'workflowExecutionCount' smart constructor.
data WorkflowExecutionCount = WorkflowExecutionCount'
{ _wecTruncated :: !(Maybe Bool)
, _wecCount :: !Nat
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowExecutionCount' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wecTruncated'
--
-- * 'wecCount'
workflowExecutionCount
:: Natural -- ^ 'wecCount'
-> WorkflowExecutionCount
workflowExecutionCount pCount_ =
WorkflowExecutionCount'
{ _wecTruncated = Nothing
, _wecCount = _Nat # pCount_
}
-- | If set to true, indicates that the actual count was more than the
-- maximum supported by this API and the count returned is the truncated
-- value.
wecTruncated :: Lens' WorkflowExecutionCount (Maybe Bool)
wecTruncated = lens _wecTruncated (\ s a -> s{_wecTruncated = a});
-- | The number of workflow executions.
wecCount :: Lens' WorkflowExecutionCount Natural
wecCount = lens _wecCount (\ s a -> s{_wecCount = a}) . _Nat;
instance FromJSON WorkflowExecutionCount where
parseJSON
= withObject "WorkflowExecutionCount"
(\ x ->
WorkflowExecutionCount' <$>
(x .:? "truncated") <*> (x .: "count"))
-- | Provides details of the 'WorkflowExecutionFailed' event.
--
-- /See:/ 'workflowExecutionFailedEventAttributes' smart constructor.
data WorkflowExecutionFailedEventAttributes = WorkflowExecutionFailedEventAttributes'
{ _wefeaReason :: !(Maybe Text)
, _wefeaDetails :: !(Maybe Text)
, _wefeaDecisionTaskCompletedEventId :: !Integer
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowExecutionFailedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wefeaReason'
--
-- * 'wefeaDetails'
--
-- * 'wefeaDecisionTaskCompletedEventId'
workflowExecutionFailedEventAttributes
:: Integer -- ^ 'wefeaDecisionTaskCompletedEventId'
-> WorkflowExecutionFailedEventAttributes
workflowExecutionFailedEventAttributes pDecisionTaskCompletedEventId_ =
WorkflowExecutionFailedEventAttributes'
{ _wefeaReason = Nothing
, _wefeaDetails = Nothing
, _wefeaDecisionTaskCompletedEventId = pDecisionTaskCompletedEventId_
}
-- | The descriptive reason provided for the failure (if any).
wefeaReason :: Lens' WorkflowExecutionFailedEventAttributes (Maybe Text)
wefeaReason = lens _wefeaReason (\ s a -> s{_wefeaReason = a});
-- | The details of the failure (if any).
wefeaDetails :: Lens' WorkflowExecutionFailedEventAttributes (Maybe Text)
wefeaDetails = lens _wefeaDetails (\ s a -> s{_wefeaDetails = a});
-- | The ID of the 'DecisionTaskCompleted' event corresponding to the
-- decision task that resulted in the 'FailWorkflowExecution' decision to
-- fail this execution. This information can be useful for diagnosing
-- problems by tracing back the chain of events leading up to this event.
wefeaDecisionTaskCompletedEventId :: Lens' WorkflowExecutionFailedEventAttributes Integer
wefeaDecisionTaskCompletedEventId = lens _wefeaDecisionTaskCompletedEventId (\ s a -> s{_wefeaDecisionTaskCompletedEventId = a});
instance FromJSON
WorkflowExecutionFailedEventAttributes where
parseJSON
= withObject "WorkflowExecutionFailedEventAttributes"
(\ x ->
WorkflowExecutionFailedEventAttributes' <$>
(x .:? "reason") <*> (x .:? "details") <*>
(x .: "decisionTaskCompletedEventId"))
-- | Used to filter the workflow executions in visibility APIs by their
-- 'workflowId'.
--
-- /See:/ 'workflowExecutionFilter' smart constructor.
newtype WorkflowExecutionFilter = WorkflowExecutionFilter'
{ _wefWorkflowId :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowExecutionFilter' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wefWorkflowId'
workflowExecutionFilter
:: Text -- ^ 'wefWorkflowId'
-> WorkflowExecutionFilter
workflowExecutionFilter pWorkflowId_ =
WorkflowExecutionFilter'
{ _wefWorkflowId = pWorkflowId_
}
-- | The workflowId to pass of match the criteria of this filter.
wefWorkflowId :: Lens' WorkflowExecutionFilter Text
wefWorkflowId = lens _wefWorkflowId (\ s a -> s{_wefWorkflowId = a});
instance ToJSON WorkflowExecutionFilter where
toJSON WorkflowExecutionFilter'{..}
= object
(catMaybes [Just ("workflowId" .= _wefWorkflowId)])
-- | Contains information about a workflow execution.
--
-- /See:/ 'workflowExecutionInfo' smart constructor.
data WorkflowExecutionInfo = WorkflowExecutionInfo'
{ _weiParent :: !(Maybe WorkflowExecution)
, _weiTagList :: !(Maybe [Text])
, _weiCloseStatus :: !(Maybe CloseStatus)
, _weiCloseTimestamp :: !(Maybe POSIX)
, _weiCancelRequested :: !(Maybe Bool)
, _weiExecution :: !WorkflowExecution
, _weiWorkflowType :: !WorkflowType
, _weiStartTimestamp :: !POSIX
, _weiExecutionStatus :: !ExecutionStatus
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowExecutionInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'weiParent'
--
-- * 'weiTagList'
--
-- * 'weiCloseStatus'
--
-- * 'weiCloseTimestamp'
--
-- * 'weiCancelRequested'
--
-- * 'weiExecution'
--
-- * 'weiWorkflowType'
--
-- * 'weiStartTimestamp'
--
-- * 'weiExecutionStatus'
workflowExecutionInfo
:: WorkflowExecution -- ^ 'weiExecution'
-> WorkflowType -- ^ 'weiWorkflowType'
-> UTCTime -- ^ 'weiStartTimestamp'
-> ExecutionStatus -- ^ 'weiExecutionStatus'
-> WorkflowExecutionInfo
workflowExecutionInfo pExecution_ pWorkflowType_ pStartTimestamp_ pExecutionStatus_ =
WorkflowExecutionInfo'
{ _weiParent = Nothing
, _weiTagList = Nothing
, _weiCloseStatus = Nothing
, _weiCloseTimestamp = Nothing
, _weiCancelRequested = Nothing
, _weiExecution = pExecution_
, _weiWorkflowType = pWorkflowType_
, _weiStartTimestamp = _Time # pStartTimestamp_
, _weiExecutionStatus = pExecutionStatus_
}
-- | If this workflow execution is a child of another execution then contains
-- the workflow execution that started this execution.
weiParent :: Lens' WorkflowExecutionInfo (Maybe WorkflowExecution)
weiParent = lens _weiParent (\ s a -> s{_weiParent = a});
-- | The list of tags associated with the workflow execution. Tags can be
-- used to identify and list workflow executions of interest through the
-- visibility APIs. A workflow execution can have a maximum of 5 tags.
weiTagList :: Lens' WorkflowExecutionInfo [Text]
weiTagList = lens _weiTagList (\ s a -> s{_weiTagList = a}) . _Default . _Coerce;
-- | If the execution status is closed then this specifies how the execution
-- was closed:
--
-- - 'COMPLETED': the execution was successfully completed.
-- - 'CANCELED': the execution was canceled.Cancellation allows the
-- implementation to gracefully clean up before the execution is
-- closed.
-- - 'TERMINATED': the execution was force terminated.
-- - 'FAILED': the execution failed to complete.
-- - 'TIMED_OUT': the execution did not complete in the alloted time and
-- was automatically timed out.
-- - 'CONTINUED_AS_NEW': the execution is logically continued. This means
-- the current execution was completed and a new execution was started
-- to carry on the workflow.
weiCloseStatus :: Lens' WorkflowExecutionInfo (Maybe CloseStatus)
weiCloseStatus = lens _weiCloseStatus (\ s a -> s{_weiCloseStatus = a});
-- | The time when the workflow execution was closed. Set only if the
-- execution status is CLOSED.
weiCloseTimestamp :: Lens' WorkflowExecutionInfo (Maybe UTCTime)
weiCloseTimestamp = lens _weiCloseTimestamp (\ s a -> s{_weiCloseTimestamp = a}) . mapping _Time;
-- | Set to true if a cancellation is requested for this workflow execution.
weiCancelRequested :: Lens' WorkflowExecutionInfo (Maybe Bool)
weiCancelRequested = lens _weiCancelRequested (\ s a -> s{_weiCancelRequested = a});
-- | The workflow execution this information is about.
weiExecution :: Lens' WorkflowExecutionInfo WorkflowExecution
weiExecution = lens _weiExecution (\ s a -> s{_weiExecution = a});
-- | The type of the workflow execution.
weiWorkflowType :: Lens' WorkflowExecutionInfo WorkflowType
weiWorkflowType = lens _weiWorkflowType (\ s a -> s{_weiWorkflowType = a});
-- | The time when the execution was started.
weiStartTimestamp :: Lens' WorkflowExecutionInfo UTCTime
weiStartTimestamp = lens _weiStartTimestamp (\ s a -> s{_weiStartTimestamp = a}) . _Time;
-- | The current status of the execution.
weiExecutionStatus :: Lens' WorkflowExecutionInfo ExecutionStatus
weiExecutionStatus = lens _weiExecutionStatus (\ s a -> s{_weiExecutionStatus = a});
instance FromJSON WorkflowExecutionInfo where
parseJSON
= withObject "WorkflowExecutionInfo"
(\ x ->
WorkflowExecutionInfo' <$>
(x .:? "parent") <*> (x .:? "tagList" .!= mempty) <*>
(x .:? "closeStatus")
<*> (x .:? "closeTimestamp")
<*> (x .:? "cancelRequested")
<*> (x .: "execution")
<*> (x .: "workflowType")
<*> (x .: "startTimestamp")
<*> (x .: "executionStatus"))
-- | Contains a paginated list of information about workflow executions.
--
-- /See:/ 'workflowExecutionInfos' smart constructor.
data WorkflowExecutionInfos = WorkflowExecutionInfos'
{ _weiNextPageToken :: !(Maybe Text)
, _weiExecutionInfos :: ![WorkflowExecutionInfo]
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowExecutionInfos' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'weiNextPageToken'
--
-- * 'weiExecutionInfos'
workflowExecutionInfos
:: WorkflowExecutionInfos
workflowExecutionInfos =
WorkflowExecutionInfos'
{ _weiNextPageToken = Nothing
, _weiExecutionInfos = mempty
}
-- | If a 'NextPageToken' was returned by a previous call, there are more
-- results available. To retrieve the next page of results, make the call
-- again using the returned token in 'nextPageToken'. Keep all other
-- arguments unchanged.
--
-- The configured 'maximumPageSize' determines how many results can be
-- returned in a single call.
weiNextPageToken :: Lens' WorkflowExecutionInfos (Maybe Text)
weiNextPageToken = lens _weiNextPageToken (\ s a -> s{_weiNextPageToken = a});
-- | The list of workflow information structures.
weiExecutionInfos :: Lens' WorkflowExecutionInfos [WorkflowExecutionInfo]
weiExecutionInfos = lens _weiExecutionInfos (\ s a -> s{_weiExecutionInfos = a}) . _Coerce;
instance FromJSON WorkflowExecutionInfos where
parseJSON
= withObject "WorkflowExecutionInfos"
(\ x ->
WorkflowExecutionInfos' <$>
(x .:? "nextPageToken") <*>
(x .:? "executionInfos" .!= mempty))
-- | Contains the counts of open tasks, child workflow executions and timers
-- for a workflow execution.
--
-- /See:/ 'workflowExecutionOpenCounts' smart constructor.
data WorkflowExecutionOpenCounts = WorkflowExecutionOpenCounts'
{ _weocOpenLambdaFunctions :: !(Maybe Nat)
, _weocOpenActivityTasks :: !Nat
, _weocOpenDecisionTasks :: !Nat
, _weocOpenTimers :: !Nat
, _weocOpenChildWorkflowExecutions :: !Nat
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowExecutionOpenCounts' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'weocOpenLambdaFunctions'
--
-- * 'weocOpenActivityTasks'
--
-- * 'weocOpenDecisionTasks'
--
-- * 'weocOpenTimers'
--
-- * 'weocOpenChildWorkflowExecutions'
workflowExecutionOpenCounts
:: Natural -- ^ 'weocOpenActivityTasks'
-> Natural -- ^ 'weocOpenDecisionTasks'
-> Natural -- ^ 'weocOpenTimers'
-> Natural -- ^ 'weocOpenChildWorkflowExecutions'
-> WorkflowExecutionOpenCounts
workflowExecutionOpenCounts pOpenActivityTasks_ pOpenDecisionTasks_ pOpenTimers_ pOpenChildWorkflowExecutions_ =
WorkflowExecutionOpenCounts'
{ _weocOpenLambdaFunctions = Nothing
, _weocOpenActivityTasks = _Nat # pOpenActivityTasks_
, _weocOpenDecisionTasks = _Nat # pOpenDecisionTasks_
, _weocOpenTimers = _Nat # pOpenTimers_
, _weocOpenChildWorkflowExecutions = _Nat # pOpenChildWorkflowExecutions_
}
-- | The count of AWS Lambda functions that are currently executing.
weocOpenLambdaFunctions :: Lens' WorkflowExecutionOpenCounts (Maybe Natural)
weocOpenLambdaFunctions = lens _weocOpenLambdaFunctions (\ s a -> s{_weocOpenLambdaFunctions = a}) . mapping _Nat;
-- | The count of activity tasks whose status is OPEN.
weocOpenActivityTasks :: Lens' WorkflowExecutionOpenCounts Natural
weocOpenActivityTasks = lens _weocOpenActivityTasks (\ s a -> s{_weocOpenActivityTasks = a}) . _Nat;
-- | The count of decision tasks whose status is OPEN. A workflow execution
-- can have at most one open decision task.
weocOpenDecisionTasks :: Lens' WorkflowExecutionOpenCounts Natural
weocOpenDecisionTasks = lens _weocOpenDecisionTasks (\ s a -> s{_weocOpenDecisionTasks = a}) . _Nat;
-- | The count of timers started by this workflow execution that have not
-- fired yet.
weocOpenTimers :: Lens' WorkflowExecutionOpenCounts Natural
weocOpenTimers = lens _weocOpenTimers (\ s a -> s{_weocOpenTimers = a}) . _Nat;
-- | The count of child workflow executions whose status is OPEN.
weocOpenChildWorkflowExecutions :: Lens' WorkflowExecutionOpenCounts Natural
weocOpenChildWorkflowExecutions = lens _weocOpenChildWorkflowExecutions (\ s a -> s{_weocOpenChildWorkflowExecutions = a}) . _Nat;
instance FromJSON WorkflowExecutionOpenCounts where
parseJSON
= withObject "WorkflowExecutionOpenCounts"
(\ x ->
WorkflowExecutionOpenCounts' <$>
(x .:? "openLambdaFunctions") <*>
(x .: "openActivityTasks")
<*> (x .: "openDecisionTasks")
<*> (x .: "openTimers")
<*> (x .: "openChildWorkflowExecutions"))
-- | Provides details of the 'WorkflowExecutionSignaled' event.
--
-- /See:/ 'workflowExecutionSignaledEventAttributes' smart constructor.
data WorkflowExecutionSignaledEventAttributes = WorkflowExecutionSignaledEventAttributes'
{ _wExternalWorkflowExecution :: !(Maybe WorkflowExecution)
, _wExternalInitiatedEventId :: !(Maybe Integer)
, _wInput :: !(Maybe Text)
, _wSignalName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowExecutionSignaledEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wExternalWorkflowExecution'
--
-- * 'wExternalInitiatedEventId'
--
-- * 'wInput'
--
-- * 'wSignalName'
workflowExecutionSignaledEventAttributes
:: Text -- ^ 'wSignalName'
-> WorkflowExecutionSignaledEventAttributes
workflowExecutionSignaledEventAttributes pSignalName_ =
WorkflowExecutionSignaledEventAttributes'
{ _wExternalWorkflowExecution = Nothing
, _wExternalInitiatedEventId = Nothing
, _wInput = Nothing
, _wSignalName = pSignalName_
}
-- | The workflow execution that sent the signal. This is set only of the
-- signal was sent by another workflow execution.
wExternalWorkflowExecution :: Lens' WorkflowExecutionSignaledEventAttributes (Maybe WorkflowExecution)
wExternalWorkflowExecution = lens _wExternalWorkflowExecution (\ s a -> s{_wExternalWorkflowExecution = a});
-- | The ID of the 'SignalExternalWorkflowExecutionInitiated' event
-- corresponding to the 'SignalExternalWorkflow' decision to signal this
-- workflow execution.The source event with this ID can be found in the
-- history of the source workflow execution. This information can be useful
-- for diagnosing problems by tracing back the chain of events leading up
-- to this event. This field is set only if the signal was initiated by
-- another workflow execution.
wExternalInitiatedEventId :: Lens' WorkflowExecutionSignaledEventAttributes (Maybe Integer)
wExternalInitiatedEventId = lens _wExternalInitiatedEventId (\ s a -> s{_wExternalInitiatedEventId = a});
-- | Inputs provided with the signal (if any). The decider can use the signal
-- name and inputs to determine how to process the signal.
wInput :: Lens' WorkflowExecutionSignaledEventAttributes (Maybe Text)
wInput = lens _wInput (\ s a -> s{_wInput = a});
-- | The name of the signal received. The decider can use the signal name and
-- inputs to determine how to the process the signal.
wSignalName :: Lens' WorkflowExecutionSignaledEventAttributes Text
wSignalName = lens _wSignalName (\ s a -> s{_wSignalName = a});
instance FromJSON
WorkflowExecutionSignaledEventAttributes where
parseJSON
= withObject
"WorkflowExecutionSignaledEventAttributes"
(\ x ->
WorkflowExecutionSignaledEventAttributes' <$>
(x .:? "externalWorkflowExecution") <*>
(x .:? "externalInitiatedEventId")
<*> (x .:? "input")
<*> (x .: "signalName"))
-- | Provides details of 'WorkflowExecutionStarted' event.
--
-- /See:/ 'workflowExecutionStartedEventAttributes' smart constructor.
data WorkflowExecutionStartedEventAttributes = WorkflowExecutionStartedEventAttributes'
{ _weseaParentInitiatedEventId :: !(Maybe Integer)
, _weseaTagList :: !(Maybe [Text])
, _weseaTaskStartToCloseTimeout :: !(Maybe Text)
, _weseaLambdaRole :: !(Maybe Text)
, _weseaInput :: !(Maybe Text)
, _weseaExecutionStartToCloseTimeout :: !(Maybe Text)
, _weseaTaskPriority :: !(Maybe Text)
, _weseaParentWorkflowExecution :: !(Maybe WorkflowExecution)
, _weseaContinuedExecutionRunId :: !(Maybe Text)
, _weseaChildPolicy :: !ChildPolicy
, _weseaTaskList :: !TaskList
, _weseaWorkflowType :: !WorkflowType
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowExecutionStartedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'weseaParentInitiatedEventId'
--
-- * 'weseaTagList'
--
-- * 'weseaTaskStartToCloseTimeout'
--
-- * 'weseaLambdaRole'
--
-- * 'weseaInput'
--
-- * 'weseaExecutionStartToCloseTimeout'
--
-- * 'weseaTaskPriority'
--
-- * 'weseaParentWorkflowExecution'
--
-- * 'weseaContinuedExecutionRunId'
--
-- * 'weseaChildPolicy'
--
-- * 'weseaTaskList'
--
-- * 'weseaWorkflowType'
workflowExecutionStartedEventAttributes
:: ChildPolicy -- ^ 'weseaChildPolicy'
-> TaskList -- ^ 'weseaTaskList'
-> WorkflowType -- ^ 'weseaWorkflowType'
-> WorkflowExecutionStartedEventAttributes
workflowExecutionStartedEventAttributes pChildPolicy_ pTaskList_ pWorkflowType_ =
WorkflowExecutionStartedEventAttributes'
{ _weseaParentInitiatedEventId = Nothing
, _weseaTagList = Nothing
, _weseaTaskStartToCloseTimeout = Nothing
, _weseaLambdaRole = Nothing
, _weseaInput = Nothing
, _weseaExecutionStartToCloseTimeout = Nothing
, _weseaTaskPriority = Nothing
, _weseaParentWorkflowExecution = Nothing
, _weseaContinuedExecutionRunId = Nothing
, _weseaChildPolicy = pChildPolicy_
, _weseaTaskList = pTaskList_
, _weseaWorkflowType = pWorkflowType_
}
-- | The ID of the 'StartChildWorkflowExecutionInitiated' event corresponding
-- to the 'StartChildWorkflowExecution' decision to start this workflow
-- execution. The source event with this ID can be found in the history of
-- the source workflow execution. This information can be useful for
-- diagnosing problems by tracing back the chain of events leading up to
-- this event.
weseaParentInitiatedEventId :: Lens' WorkflowExecutionStartedEventAttributes (Maybe Integer)
weseaParentInitiatedEventId = lens _weseaParentInitiatedEventId (\ s a -> s{_weseaParentInitiatedEventId = a});
-- | The list of tags associated with this workflow execution. An execution
-- can have up to 5 tags.
weseaTagList :: Lens' WorkflowExecutionStartedEventAttributes [Text]
weseaTagList = lens _weseaTagList (\ s a -> s{_weseaTagList = a}) . _Default . _Coerce;
-- | The maximum duration of decision tasks for this workflow type.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
weseaTaskStartToCloseTimeout :: Lens' WorkflowExecutionStartedEventAttributes (Maybe Text)
weseaTaskStartToCloseTimeout = lens _weseaTaskStartToCloseTimeout (\ s a -> s{_weseaTaskStartToCloseTimeout = a});
-- | The IAM role attached to this workflow execution to use when invoking
-- AWS Lambda functions.
weseaLambdaRole :: Lens' WorkflowExecutionStartedEventAttributes (Maybe Text)
weseaLambdaRole = lens _weseaLambdaRole (\ s a -> s{_weseaLambdaRole = a});
-- | The input provided to the workflow execution (if any).
weseaInput :: Lens' WorkflowExecutionStartedEventAttributes (Maybe Text)
weseaInput = lens _weseaInput (\ s a -> s{_weseaInput = a});
-- | The maximum duration for this workflow execution.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
weseaExecutionStartToCloseTimeout :: Lens' WorkflowExecutionStartedEventAttributes (Maybe Text)
weseaExecutionStartToCloseTimeout = lens _weseaExecutionStartToCloseTimeout (\ s a -> s{_weseaExecutionStartToCloseTimeout = a});
-- | Undocumented member.
weseaTaskPriority :: Lens' WorkflowExecutionStartedEventAttributes (Maybe Text)
weseaTaskPriority = lens _weseaTaskPriority (\ s a -> s{_weseaTaskPriority = a});
-- | The source workflow execution that started this workflow execution. The
-- member is not set if the workflow execution was not started by a
-- workflow.
weseaParentWorkflowExecution :: Lens' WorkflowExecutionStartedEventAttributes (Maybe WorkflowExecution)
weseaParentWorkflowExecution = lens _weseaParentWorkflowExecution (\ s a -> s{_weseaParentWorkflowExecution = a});
-- | If this workflow execution was started due to a
-- 'ContinueAsNewWorkflowExecution' decision, then it contains the 'runId'
-- of the previous workflow execution that was closed and continued as this
-- execution.
weseaContinuedExecutionRunId :: Lens' WorkflowExecutionStartedEventAttributes (Maybe Text)
weseaContinuedExecutionRunId = lens _weseaContinuedExecutionRunId (\ s a -> s{_weseaContinuedExecutionRunId = a});
-- | The policy to use for the child workflow executions if this workflow
-- execution is terminated, by calling the TerminateWorkflowExecution
-- action explicitly or due to an expired timeout.
--
-- The supported child policies are:
--
-- - __TERMINATE:__ the child executions will be terminated.
-- - __REQUEST_CANCEL:__ a request to cancel will be attempted for each
-- child execution by recording a 'WorkflowExecutionCancelRequested'
-- event in its history. It is up to the decider to take appropriate
-- actions when it receives an execution history with this event.
-- - __ABANDON:__ no action will be taken. The child executions will
-- continue to run.
weseaChildPolicy :: Lens' WorkflowExecutionStartedEventAttributes ChildPolicy
weseaChildPolicy = lens _weseaChildPolicy (\ s a -> s{_weseaChildPolicy = a});
-- | The name of the task list for scheduling the decision tasks for this
-- workflow execution.
weseaTaskList :: Lens' WorkflowExecutionStartedEventAttributes TaskList
weseaTaskList = lens _weseaTaskList (\ s a -> s{_weseaTaskList = a});
-- | The workflow type of this execution.
weseaWorkflowType :: Lens' WorkflowExecutionStartedEventAttributes WorkflowType
weseaWorkflowType = lens _weseaWorkflowType (\ s a -> s{_weseaWorkflowType = a});
instance FromJSON
WorkflowExecutionStartedEventAttributes where
parseJSON
= withObject
"WorkflowExecutionStartedEventAttributes"
(\ x ->
WorkflowExecutionStartedEventAttributes' <$>
(x .:? "parentInitiatedEventId") <*>
(x .:? "tagList" .!= mempty)
<*> (x .:? "taskStartToCloseTimeout")
<*> (x .:? "lambdaRole")
<*> (x .:? "input")
<*> (x .:? "executionStartToCloseTimeout")
<*> (x .:? "taskPriority")
<*> (x .:? "parentWorkflowExecution")
<*> (x .:? "continuedExecutionRunId")
<*> (x .: "childPolicy")
<*> (x .: "taskList")
<*> (x .: "workflowType"))
-- | Provides details of the 'WorkflowExecutionTerminated' event.
--
-- /See:/ 'workflowExecutionTerminatedEventAttributes' smart constructor.
data WorkflowExecutionTerminatedEventAttributes = WorkflowExecutionTerminatedEventAttributes'
{ _weteaCause :: !(Maybe WorkflowExecutionTerminatedCause)
, _weteaReason :: !(Maybe Text)
, _weteaDetails :: !(Maybe Text)
, _weteaChildPolicy :: !ChildPolicy
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowExecutionTerminatedEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'weteaCause'
--
-- * 'weteaReason'
--
-- * 'weteaDetails'
--
-- * 'weteaChildPolicy'
workflowExecutionTerminatedEventAttributes
:: ChildPolicy -- ^ 'weteaChildPolicy'
-> WorkflowExecutionTerminatedEventAttributes
workflowExecutionTerminatedEventAttributes pChildPolicy_ =
WorkflowExecutionTerminatedEventAttributes'
{ _weteaCause = Nothing
, _weteaReason = Nothing
, _weteaDetails = Nothing
, _weteaChildPolicy = pChildPolicy_
}
-- | If set, indicates that the workflow execution was automatically
-- terminated, and specifies the cause. This happens if the parent workflow
-- execution times out or is terminated and the child policy is set to
-- terminate child executions.
weteaCause :: Lens' WorkflowExecutionTerminatedEventAttributes (Maybe WorkflowExecutionTerminatedCause)
weteaCause = lens _weteaCause (\ s a -> s{_weteaCause = a});
-- | The reason provided for the termination (if any).
weteaReason :: Lens' WorkflowExecutionTerminatedEventAttributes (Maybe Text)
weteaReason = lens _weteaReason (\ s a -> s{_weteaReason = a});
-- | The details provided for the termination (if any).
weteaDetails :: Lens' WorkflowExecutionTerminatedEventAttributes (Maybe Text)
weteaDetails = lens _weteaDetails (\ s a -> s{_weteaDetails = a});
-- | The policy used for the child workflow executions of this workflow
-- execution.
--
-- The supported child policies are:
--
-- - __TERMINATE:__ the child executions will be terminated.
-- - __REQUEST_CANCEL:__ a request to cancel will be attempted for each
-- child execution by recording a 'WorkflowExecutionCancelRequested'
-- event in its history. It is up to the decider to take appropriate
-- actions when it receives an execution history with this event.
-- - __ABANDON:__ no action will be taken. The child executions will
-- continue to run.
weteaChildPolicy :: Lens' WorkflowExecutionTerminatedEventAttributes ChildPolicy
weteaChildPolicy = lens _weteaChildPolicy (\ s a -> s{_weteaChildPolicy = a});
instance FromJSON
WorkflowExecutionTerminatedEventAttributes where
parseJSON
= withObject
"WorkflowExecutionTerminatedEventAttributes"
(\ x ->
WorkflowExecutionTerminatedEventAttributes' <$>
(x .:? "cause") <*> (x .:? "reason") <*>
(x .:? "details")
<*> (x .: "childPolicy"))
-- | Provides details of the 'WorkflowExecutionTimedOut' event.
--
-- /See:/ 'workflowExecutionTimedOutEventAttributes' smart constructor.
data WorkflowExecutionTimedOutEventAttributes = WorkflowExecutionTimedOutEventAttributes'
{ _wetoeaTimeoutType :: !WorkflowExecutionTimeoutType
, _wetoeaChildPolicy :: !ChildPolicy
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowExecutionTimedOutEventAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wetoeaTimeoutType'
--
-- * 'wetoeaChildPolicy'
workflowExecutionTimedOutEventAttributes
:: WorkflowExecutionTimeoutType -- ^ 'wetoeaTimeoutType'
-> ChildPolicy -- ^ 'wetoeaChildPolicy'
-> WorkflowExecutionTimedOutEventAttributes
workflowExecutionTimedOutEventAttributes pTimeoutType_ pChildPolicy_ =
WorkflowExecutionTimedOutEventAttributes'
{ _wetoeaTimeoutType = pTimeoutType_
, _wetoeaChildPolicy = pChildPolicy_
}
-- | The type of timeout that caused this event.
wetoeaTimeoutType :: Lens' WorkflowExecutionTimedOutEventAttributes WorkflowExecutionTimeoutType
wetoeaTimeoutType = lens _wetoeaTimeoutType (\ s a -> s{_wetoeaTimeoutType = a});
-- | The policy used for the child workflow executions of this workflow
-- execution.
--
-- The supported child policies are:
--
-- - __TERMINATE:__ the child executions will be terminated.
-- - __REQUEST_CANCEL:__ a request to cancel will be attempted for each
-- child execution by recording a 'WorkflowExecutionCancelRequested'
-- event in its history. It is up to the decider to take appropriate
-- actions when it receives an execution history with this event.
-- - __ABANDON:__ no action will be taken. The child executions will
-- continue to run.
wetoeaChildPolicy :: Lens' WorkflowExecutionTimedOutEventAttributes ChildPolicy
wetoeaChildPolicy = lens _wetoeaChildPolicy (\ s a -> s{_wetoeaChildPolicy = a});
instance FromJSON
WorkflowExecutionTimedOutEventAttributes where
parseJSON
= withObject
"WorkflowExecutionTimedOutEventAttributes"
(\ x ->
WorkflowExecutionTimedOutEventAttributes' <$>
(x .: "timeoutType") <*> (x .: "childPolicy"))
-- | Represents a workflow type.
--
-- /See:/ 'workflowType' smart constructor.
data WorkflowType = WorkflowType'
{ _wtName :: !Text
, _wtVersion :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowType' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wtName'
--
-- * 'wtVersion'
workflowType
:: Text -- ^ 'wtName'
-> Text -- ^ 'wtVersion'
-> WorkflowType
workflowType pName_ pVersion_ =
WorkflowType'
{ _wtName = pName_
, _wtVersion = pVersion_
}
-- | __Required.__ The name of the workflow type.
--
-- The combination of workflow type name and version must be unique with in
-- a domain.
wtName :: Lens' WorkflowType Text
wtName = lens _wtName (\ s a -> s{_wtName = a});
-- | __Required.__ The version of the workflow type.
--
-- The combination of workflow type name and version must be unique with in
-- a domain.
wtVersion :: Lens' WorkflowType Text
wtVersion = lens _wtVersion (\ s a -> s{_wtVersion = a});
instance FromJSON WorkflowType where
parseJSON
= withObject "WorkflowType"
(\ x ->
WorkflowType' <$> (x .: "name") <*> (x .: "version"))
instance ToJSON WorkflowType where
toJSON WorkflowType'{..}
= object
(catMaybes
[Just ("name" .= _wtName),
Just ("version" .= _wtVersion)])
-- | The configuration settings of a workflow type.
--
-- /See:/ 'workflowTypeConfiguration' smart constructor.
data WorkflowTypeConfiguration = WorkflowTypeConfiguration'
{ _wtcDefaultLambdaRole :: !(Maybe Text)
, _wtcDefaultChildPolicy :: !(Maybe ChildPolicy)
, _wtcDefaultTaskList :: !(Maybe TaskList)
, _wtcDefaultTaskPriority :: !(Maybe Text)
, _wtcDefaultExecutionStartToCloseTimeout :: !(Maybe Text)
, _wtcDefaultTaskStartToCloseTimeout :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowTypeConfiguration' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wtcDefaultLambdaRole'
--
-- * 'wtcDefaultChildPolicy'
--
-- * 'wtcDefaultTaskList'
--
-- * 'wtcDefaultTaskPriority'
--
-- * 'wtcDefaultExecutionStartToCloseTimeout'
--
-- * 'wtcDefaultTaskStartToCloseTimeout'
workflowTypeConfiguration
:: WorkflowTypeConfiguration
workflowTypeConfiguration =
WorkflowTypeConfiguration'
{ _wtcDefaultLambdaRole = Nothing
, _wtcDefaultChildPolicy = Nothing
, _wtcDefaultTaskList = Nothing
, _wtcDefaultTaskPriority = Nothing
, _wtcDefaultExecutionStartToCloseTimeout = Nothing
, _wtcDefaultTaskStartToCloseTimeout = Nothing
}
-- | The default IAM role to use when a workflow execution invokes a AWS
-- Lambda function.
wtcDefaultLambdaRole :: Lens' WorkflowTypeConfiguration (Maybe Text)
wtcDefaultLambdaRole = lens _wtcDefaultLambdaRole (\ s a -> s{_wtcDefaultLambdaRole = a});
-- | /Optional./ The default policy to use for the child workflow executions
-- when a workflow execution of this type is terminated, by calling the
-- TerminateWorkflowExecution action explicitly or due to an expired
-- timeout. This default can be overridden when starting a workflow
-- execution using the StartWorkflowExecution action or the
-- 'StartChildWorkflowExecution' decision.
--
-- The supported child policies are:
--
-- - __TERMINATE:__ the child executions will be terminated.
-- - __REQUEST_CANCEL:__ a request to cancel will be attempted for each
-- child execution by recording a 'WorkflowExecutionCancelRequested'
-- event in its history. It is up to the decider to take appropriate
-- actions when it receives an execution history with this event.
-- - __ABANDON:__ no action will be taken. The child executions will
-- continue to run.
wtcDefaultChildPolicy :: Lens' WorkflowTypeConfiguration (Maybe ChildPolicy)
wtcDefaultChildPolicy = lens _wtcDefaultChildPolicy (\ s a -> s{_wtcDefaultChildPolicy = a});
-- | /Optional./ The default task list, specified when registering the
-- workflow type, for decisions tasks scheduled for workflow executions of
-- this type. This default can be overridden when starting a workflow
-- execution using the StartWorkflowExecution action or the
-- 'StartChildWorkflowExecution' decision.
wtcDefaultTaskList :: Lens' WorkflowTypeConfiguration (Maybe TaskList)
wtcDefaultTaskList = lens _wtcDefaultTaskList (\ s a -> s{_wtcDefaultTaskList = a});
-- | /Optional./ The default task priority, specified when registering the
-- workflow type, for all decision tasks of this workflow type. This
-- default can be overridden when starting a workflow execution using the
-- StartWorkflowExecution action or the 'StartChildWorkflowExecution'
-- decision.
--
-- Valid values are integers that range from Java\'s 'Integer.MIN_VALUE'
-- (-2147483648) to 'Integer.MAX_VALUE' (2147483647). Higher numbers
-- indicate higher priority.
--
-- For more information about setting task priority, see
-- <http://docs.aws.amazon.com/amazonswf/latest/developerguide/programming-priority.html Setting Task Priority>
-- in the /Amazon Simple Workflow Developer Guide/.
wtcDefaultTaskPriority :: Lens' WorkflowTypeConfiguration (Maybe Text)
wtcDefaultTaskPriority = lens _wtcDefaultTaskPriority (\ s a -> s{_wtcDefaultTaskPriority = a});
-- | /Optional./ The default maximum duration, specified when registering the
-- workflow type, for executions of this workflow type. This default can be
-- overridden when starting a workflow execution using the
-- StartWorkflowExecution action or the 'StartChildWorkflowExecution'
-- decision.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
wtcDefaultExecutionStartToCloseTimeout :: Lens' WorkflowTypeConfiguration (Maybe Text)
wtcDefaultExecutionStartToCloseTimeout = lens _wtcDefaultExecutionStartToCloseTimeout (\ s a -> s{_wtcDefaultExecutionStartToCloseTimeout = a});
-- | /Optional./ The default maximum duration, specified when registering the
-- workflow type, that a decision task for executions of this workflow type
-- might take before returning completion or failure. If the task does not
-- close in the specified time then the task is automatically timed out and
-- rescheduled. If the decider eventually reports a completion or failure,
-- it is ignored. This default can be overridden when starting a workflow
-- execution using the StartWorkflowExecution action or the
-- 'StartChildWorkflowExecution' decision.
--
-- The duration is specified in seconds; an integer greater than or equal
-- to 0. The value \"NONE\" can be used to specify unlimited duration.
wtcDefaultTaskStartToCloseTimeout :: Lens' WorkflowTypeConfiguration (Maybe Text)
wtcDefaultTaskStartToCloseTimeout = lens _wtcDefaultTaskStartToCloseTimeout (\ s a -> s{_wtcDefaultTaskStartToCloseTimeout = a});
instance FromJSON WorkflowTypeConfiguration where
parseJSON
= withObject "WorkflowTypeConfiguration"
(\ x ->
WorkflowTypeConfiguration' <$>
(x .:? "defaultLambdaRole") <*>
(x .:? "defaultChildPolicy")
<*> (x .:? "defaultTaskList")
<*> (x .:? "defaultTaskPriority")
<*> (x .:? "defaultExecutionStartToCloseTimeout")
<*> (x .:? "defaultTaskStartToCloseTimeout"))
-- | Used to filter workflow execution query results by type. Each parameter,
-- if specified, defines a rule that must be satisfied by each returned
-- result.
--
-- /See:/ 'workflowTypeFilter' smart constructor.
data WorkflowTypeFilter = WorkflowTypeFilter'
{ _wtfVersion :: !(Maybe Text)
, _wtfName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowTypeFilter' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wtfVersion'
--
-- * 'wtfName'
workflowTypeFilter
:: Text -- ^ 'wtfName'
-> WorkflowTypeFilter
workflowTypeFilter pName_ =
WorkflowTypeFilter'
{ _wtfVersion = Nothing
, _wtfName = pName_
}
-- | Version of the workflow type.
wtfVersion :: Lens' WorkflowTypeFilter (Maybe Text)
wtfVersion = lens _wtfVersion (\ s a -> s{_wtfVersion = a});
-- | __Required.__ Name of the workflow type.
wtfName :: Lens' WorkflowTypeFilter Text
wtfName = lens _wtfName (\ s a -> s{_wtfName = a});
instance ToJSON WorkflowTypeFilter where
toJSON WorkflowTypeFilter'{..}
= object
(catMaybes
[("version" .=) <$> _wtfVersion,
Just ("name" .= _wtfName)])
-- | Contains information about a workflow type.
--
-- /See:/ 'workflowTypeInfo' smart constructor.
data WorkflowTypeInfo = WorkflowTypeInfo'
{ _wtiDeprecationDate :: !(Maybe POSIX)
, _wtiDescription :: !(Maybe Text)
, _wtiWorkflowType :: !WorkflowType
, _wtiStatus :: !RegistrationStatus
, _wtiCreationDate :: !POSIX
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'WorkflowTypeInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wtiDeprecationDate'
--
-- * 'wtiDescription'
--
-- * 'wtiWorkflowType'
--
-- * 'wtiStatus'
--
-- * 'wtiCreationDate'
workflowTypeInfo
:: WorkflowType -- ^ 'wtiWorkflowType'
-> RegistrationStatus -- ^ 'wtiStatus'
-> UTCTime -- ^ 'wtiCreationDate'
-> WorkflowTypeInfo
workflowTypeInfo pWorkflowType_ pStatus_ pCreationDate_ =
WorkflowTypeInfo'
{ _wtiDeprecationDate = Nothing
, _wtiDescription = Nothing
, _wtiWorkflowType = pWorkflowType_
, _wtiStatus = pStatus_
, _wtiCreationDate = _Time # pCreationDate_
}
-- | If the type is in deprecated state, then it is set to the date when the
-- type was deprecated.
wtiDeprecationDate :: Lens' WorkflowTypeInfo (Maybe UTCTime)
wtiDeprecationDate = lens _wtiDeprecationDate (\ s a -> s{_wtiDeprecationDate = a}) . mapping _Time;
-- | The description of the type registered through RegisterWorkflowType.
wtiDescription :: Lens' WorkflowTypeInfo (Maybe Text)
wtiDescription = lens _wtiDescription (\ s a -> s{_wtiDescription = a});
-- | The workflow type this information is about.
wtiWorkflowType :: Lens' WorkflowTypeInfo WorkflowType
wtiWorkflowType = lens _wtiWorkflowType (\ s a -> s{_wtiWorkflowType = a});
-- | The current status of the workflow type.
wtiStatus :: Lens' WorkflowTypeInfo RegistrationStatus
wtiStatus = lens _wtiStatus (\ s a -> s{_wtiStatus = a});
-- | The date when this type was registered.
wtiCreationDate :: Lens' WorkflowTypeInfo UTCTime
wtiCreationDate = lens _wtiCreationDate (\ s a -> s{_wtiCreationDate = a}) . _Time;
instance FromJSON WorkflowTypeInfo where
parseJSON
= withObject "WorkflowTypeInfo"
(\ x ->
WorkflowTypeInfo' <$>
(x .:? "deprecationDate") <*> (x .:? "description")
<*> (x .: "workflowType")
<*> (x .: "status")
<*> (x .: "creationDate"))
|
fmapfmapfmap/amazonka
|
amazonka-swf/gen/Network/AWS/SWF/Types/Product.hs
|
mpl-2.0
| 348,280 | 0 | 67 | 63,611 | 39,955 | 23,807 | 16,148 | 4,115 | 1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="pt-BR">
<title>Eventos Enviados pelo Servidor | Exstensão do ZAP</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Conteúdo</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Índice</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Busca</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favoritos</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/sse/src/main/javahelp/org/zaproxy/zap/extension/sse/resources/help_pt_BR/helpset_pt_BR.hs
|
apache-2.0
| 998 | 80 | 64 | 163 | 427 | 215 | 212 | -1 | -1 |
{-# LANGUAGE BangPatterns, DeriveDataTypeable #-}
module Eta.Profiling.CostCentre (
CostCentre(..), CcName, IsCafCC(..),
-- All abstract except to friend: ParseIface.y
CostCentreStack,
CollectedCCs,
noCCS, currentCCS, dontCareCCS,
noCCSAttached, isCurrentCCS,
maybeSingletonCCS,
mkUserCC, mkAutoCC, mkAllCafsCC,
mkSingletonCCS,
isCafCCS, isCafCC, isSccCountCC, sccAbleCC, ccFromThisModule,
pprCostCentreCore,
costCentreUserName, costCentreUserNameFS,
costCentreSrcSpan,
cmpCostCentre -- used for removing dups in a list
) where
import Eta.Utils.Binary
import Eta.BasicTypes.Var
import Eta.BasicTypes.Name
import Eta.BasicTypes.Module
import Eta.BasicTypes.Unique
import Eta.Utils.Outputable
import Eta.Utils.FastTypes
import Eta.BasicTypes.SrcLoc
import Eta.Utils.FastString
import Eta.Utils.Util
import Data.Data
-----------------------------------------------------------------------------
-- Cost Centres
-- | A Cost Centre is a single @{-# SCC #-}@ annotation.
data CostCentre
= NormalCC {
cc_key :: {-# UNPACK #-} !Int,
-- ^ Two cost centres may have the same name and
-- module but different SrcSpans, so we need a way to
-- distinguish them easily and give them different
-- object-code labels. So every CostCentre has a
-- Unique that is distinct from every other
-- CostCentre in the same module.
--
-- XXX: should really be using Unique here, but we
-- need to derive Data below and there's no Data
-- instance for Unique.
cc_name :: CcName, -- ^ Name of the cost centre itself
cc_mod :: Module, -- ^ Name of module defining this CC.
cc_loc :: SrcSpan,
cc_is_caf :: IsCafCC -- see below
}
| AllCafsCC {
cc_mod :: Module, -- Name of module defining this CC.
cc_loc :: SrcSpan
}
deriving (Data, Typeable)
type CcName = FastString
data IsCafCC = NotCafCC | CafCC
deriving (Eq, Ord, Data, Typeable)
instance Eq CostCentre where
c1 == c2 = case c1 `cmpCostCentre` c2 of { EQ -> True; _ -> False }
instance Ord CostCentre where
compare = cmpCostCentre
cmpCostCentre :: CostCentre -> CostCentre -> Ordering
cmpCostCentre (AllCafsCC {cc_mod = m1}) (AllCafsCC {cc_mod = m2})
= m1 `compare` m2
cmpCostCentre NormalCC {cc_key = n1, cc_mod = m1}
NormalCC {cc_key = n2, cc_mod = m2}
-- first key is module name, then the integer key
= (m1 `compare` m2) `thenCmp` (n1 `compare` n2)
cmpCostCentre other_1 other_2
= let
!tag1 = tag_CC other_1
!tag2 = tag_CC other_2
in
if tag1 <# tag2 then LT else GT
where
tag_CC (NormalCC {}) = _ILIT(0)
tag_CC (AllCafsCC {}) = _ILIT(1)
-----------------------------------------------------------------------------
-- Predicates on CostCentre
isCafCC :: CostCentre -> Bool
isCafCC (AllCafsCC {}) = True
isCafCC (NormalCC {cc_is_caf = CafCC}) = True
isCafCC _ = False
-- | Is this a cost-centre which records scc counts
isSccCountCC :: CostCentre -> Bool
isSccCountCC cc | isCafCC cc = False
| otherwise = True
-- | Is this a cost-centre which can be sccd ?
sccAbleCC :: CostCentre -> Bool
sccAbleCC cc | isCafCC cc = False
| otherwise = True
ccFromThisModule :: CostCentre -> Module -> Bool
ccFromThisModule cc m = cc_mod cc == m
-----------------------------------------------------------------------------
-- Building cost centres
mkUserCC :: FastString -> Module -> SrcSpan -> Unique -> CostCentre
mkUserCC cc_name mod loc key
= NormalCC { cc_key = getKey key, cc_name = cc_name, cc_mod = mod, cc_loc = loc,
cc_is_caf = NotCafCC {-might be changed-}
}
mkAutoCC :: Id -> Module -> IsCafCC -> CostCentre
mkAutoCC id mod is_caf
= NormalCC { cc_key = getKey (getUnique id),
cc_name = str, cc_mod = mod,
cc_loc = nameSrcSpan (getName id),
cc_is_caf = is_caf
}
where
name = getName id
-- beware: only external names are guaranteed to have unique
-- Occnames. If the name is not external, we must append its
-- Unique.
-- See bug #249, tests prof001, prof002, also #2411
str | isExternalName name = occNameFS (getOccName id)
| otherwise = occNameFS (getOccName id)
`appendFS`
mkFastString ('_' : show (getUnique name))
mkAllCafsCC :: Module -> SrcSpan -> CostCentre
mkAllCafsCC m loc = AllCafsCC { cc_mod = m, cc_loc = loc }
-----------------------------------------------------------------------------
-- Cost Centre Stacks
-- | A Cost Centre Stack is something that can be attached to a closure.
-- This is either:
--
-- * the current cost centre stack (CCCS)
-- * a pre-defined cost centre stack (there are several
-- pre-defined CCSs, see below).
data CostCentreStack
= NoCCS
| CurrentCCS -- Pinned on a let(rec)-bound
-- thunk/function/constructor, this says that the
-- cost centre to be attached to the object, when it
-- is allocated, is whatever is in the
-- current-cost-centre-stack register.
| DontCareCCS -- We need a CCS to stick in static closures
-- (for data), but we *don't* expect them to
-- accumulate any costs. But we still need
-- the placeholder. This CCS is it.
| SingletonCCS CostCentre
deriving (Eq, Ord) -- needed for Ord on CLabel
-- synonym for triple which describes the cost centre info in the generated
-- code for a module.
type CollectedCCs
= ( [CostCentre] -- local cost-centres that need to be decl'd
, [CostCentre] -- "extern" cost-centres
, [CostCentreStack] -- pre-defined "singleton" cost centre stacks
)
noCCS, currentCCS, dontCareCCS :: CostCentreStack
noCCS = NoCCS
currentCCS = CurrentCCS
dontCareCCS = DontCareCCS
-----------------------------------------------------------------------------
-- Predicates on Cost-Centre Stacks
noCCSAttached :: CostCentreStack -> Bool
noCCSAttached NoCCS = True
noCCSAttached _ = False
isCurrentCCS :: CostCentreStack -> Bool
isCurrentCCS CurrentCCS = True
isCurrentCCS _ = False
isCafCCS :: CostCentreStack -> Bool
isCafCCS (SingletonCCS cc) = isCafCC cc
isCafCCS _ = False
maybeSingletonCCS :: CostCentreStack -> Maybe CostCentre
maybeSingletonCCS (SingletonCCS cc) = Just cc
maybeSingletonCCS _ = Nothing
mkSingletonCCS :: CostCentre -> CostCentreStack
mkSingletonCCS cc = SingletonCCS cc
-----------------------------------------------------------------------------
-- Printing Cost Centre Stacks.
-- The outputable instance for CostCentreStack prints the CCS as a C
-- expression.
instance Outputable CostCentreStack where
ppr NoCCS = ptext (sLit "NO_CCS")
ppr CurrentCCS = ptext (sLit "CCCS")
ppr DontCareCCS = ptext (sLit "CCS_DONT_CARE")
ppr (SingletonCCS cc) = ppr cc <> ptext (sLit "_ccs")
-----------------------------------------------------------------------------
-- Printing Cost Centres
--
-- There are several different ways in which we might want to print a
-- cost centre:
--
-- - the name of the cost centre, for profiling output (a C string)
-- - the label, i.e. C label for cost centre in .hc file.
-- - the debugging name, for output in -ddump things
-- - the interface name, for printing in _scc_ exprs in iface files.
--
-- The last 3 are derived from costCentreStr below. The first is given
-- by costCentreName.
instance Outputable CostCentre where
ppr cc = getPprStyle $ \ sty ->
if codeStyle sty
then ppCostCentreLbl cc
else text (costCentreUserName cc)
-- Printing in Core
pprCostCentreCore :: CostCentre -> SDoc
pprCostCentreCore (AllCafsCC {cc_mod = m})
= text "__sccC" <+> braces (ppr m)
pprCostCentreCore (NormalCC {cc_key = key, cc_name = n, cc_mod = m, cc_loc = loc,
cc_is_caf = caf})
= text "__scc" <+> braces (hsep [
ppr m <> char '.' <> ftext n,
ifPprDebug (ppr key),
pp_caf caf,
ifPprDebug (ppr loc)
])
pp_caf :: IsCafCC -> SDoc
pp_caf CafCC = text "__C"
pp_caf _ = empty
-- Printing as a C label
ppCostCentreLbl :: CostCentre -> SDoc
ppCostCentreLbl (AllCafsCC {cc_mod = m}) = ppr m <> text "_CAFs_cc"
ppCostCentreLbl (NormalCC {cc_key = k, cc_name = n, cc_mod = m,
cc_is_caf = is_caf})
= ppr m <> char '_' <> ztext (zEncodeFS n) <> char '_' <>
case is_caf of { CafCC -> ptext (sLit "CAF"); _ -> ppr (mkUniqueGrimily k)} <> text "_cc"
-- This is the name to go in the user-displayed string,
-- recorded in the cost centre declaration
costCentreUserName :: CostCentre -> String
costCentreUserName = unpackFS . costCentreUserNameFS
costCentreUserNameFS :: CostCentre -> FastString
costCentreUserNameFS (AllCafsCC {}) = mkFastString "CAF"
costCentreUserNameFS (NormalCC {cc_name = name, cc_is_caf = is_caf})
= case is_caf of
CafCC -> mkFastString "CAF:" `appendFS` name
_ -> name
costCentreSrcSpan :: CostCentre -> SrcSpan
costCentreSrcSpan = cc_loc
instance Binary IsCafCC where
put_ bh CafCC = do
putByte bh 0
put_ bh NotCafCC = do
putByte bh 1
get bh = do
h <- getByte bh
case h of
0 -> do return CafCC
_ -> do return NotCafCC
instance Binary CostCentre where
put_ bh (NormalCC aa ab ac _ad ae) = do
putByte bh 0
put_ bh aa
put_ bh ab
put_ bh ac
put_ bh ae
put_ bh (AllCafsCC ae _af) = do
putByte bh 1
put_ bh ae
get bh = do
h <- getByte bh
case h of
0 -> do aa <- get bh
ab <- get bh
ac <- get bh
ae <- get bh
return (NormalCC aa ab ac noSrcSpan ae)
_ -> do ae <- get bh
return (AllCafsCC ae noSrcSpan)
-- We ignore the SrcSpans in CostCentres when we serialise them,
-- and set the SrcSpans to noSrcSpan when deserialising. This is
-- ok, because we only need the SrcSpan when declaring the
-- CostCentre in the original module, it is not used by importing
-- modules.
|
rahulmutt/ghcvm
|
compiler/Eta/Profiling/CostCentre.hs
|
bsd-3-clause
| 11,032 | 0 | 15 | 3,346 | 2,148 | 1,172 | 976 | 183 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module System.Mesos.Raw.FrameworkInfo where
import System.Mesos.Internal
import System.Mesos.Raw.FrameworkId
type FrameworkInfoPtr = Ptr FrameworkInfo
foreign import ccall "ext/types.h toFrameworkInfo" c_toFrameworkInfo
:: Ptr CChar
-> CInt
-> Ptr CChar
-> CInt
-> Ptr FrameworkIDPtr
-> Ptr CDouble
-> Ptr CBool
-> Ptr CChar
-> CInt
-> Ptr CChar
-> CInt
-> Ptr CChar
-> CInt
-> IO FrameworkInfoPtr
foreign import ccall "ext/types.h fromFrameworkInfo" c_fromFrameworkInfo
:: FrameworkInfoPtr
-> Ptr (Ptr CChar)
-> Ptr CInt
-> Ptr (Ptr CChar)
-> Ptr CInt
-> Ptr FrameworkIDPtr
-> Ptr CBool
-> Ptr CDouble
-> Ptr CBool
-> Ptr CBool
-> Ptr (Ptr CChar)
-> Ptr CInt
-> Ptr (Ptr CChar)
-> Ptr CInt
-> Ptr (Ptr CChar)
-> Ptr CInt
-> IO ()
foreign import ccall "ext/types.h destroyFrameworkInfo" c_destroyFrameworkInfo
:: FrameworkInfoPtr
-> IO ()
instance CPPValue FrameworkInfo where
marshal fi = do
(up, ul) <- cstring $ frameworkInfoUser fi
(np, nl) <- cstring $ frameworkInfoName fi
(rp, rl) <- maybeCString $ frameworkInfoRole fi
(hp, hl) <- maybeCString $ frameworkInfoHostname fi
(pp, pl) <- maybeCString $ frameworkInfoPrincipal fi
fp' <- allocMaybe $ fmap CDouble $ frameworkInfoFailoverTimeout fi
cp' <- allocMaybe $ fmap toCBool $ frameworkInfoCheckpoint fi
let fidFun f = case frameworkInfoId' fi of
Nothing -> f nullPtr
Just r -> do
p <- alloc
fidp <- cppValue r
poke p fidp
f p
fidFun $ \fidp -> liftIO $ c_toFrameworkInfo up
(fromIntegral ul)
np
(fromIntegral nl)
fidp
fp'
cp'
rp
(fromIntegral rl)
hp
(fromIntegral hl)
pp
(fromIntegral pl)
unmarshal fp = do
(up, ul) <- arrayPair
(np, nl) <- arrayPair
idp <- alloc
tps <- alloc
tp <- alloc
cps <- alloc
cp <- alloc
(rp, rl) <- arrayPair
(hp, hl) <- arrayPair
(pp, pl) <- arrayPair
poke up nullPtr
poke ul 0
poke np nullPtr
poke nl 0
poke idp nullPtr
poke rp nullPtr
poke rl 0
poke hp nullPtr
poke hl 0
poke pp nullPtr
poke pl 0
liftIO $ c_fromFrameworkInfo fp up ul np nl idp tps tp cps cp rp rl hp hl pp pl
ubs <- peekCString (up, ul)
nbs <- peekCString (np, nl)
mid <- do
midp <- peek idp
if midp == nullPtr
then return Nothing
else fmap Just $ unmarshal midp
mt <- fmap (fmap (\(CDouble d) -> d)) $ peekMaybePrim tp tps
mc <- fmap (fmap (== 1)) $ peekMaybePrim cp cps
mr <- peekMaybeBS rp rl
mh <- peekMaybeBS hp hl
mp <- peekMaybeBS pp pl
return $ FrameworkInfo ubs nbs mid mt mc mr mh mp
destroy = c_destroyFrameworkInfo
equalExceptDefaults (FrameworkInfo u n i ft cp r hn p) (FrameworkInfo u' n' i' ft' cp' r' hn' p') =
u == u' && n == n' && i == i' && defEq 0 ft ft' && defEq False cp cp' && defEq "*" r r' && hn == hn' && p == p'
|
Atidot/hs-mesos
|
src/System/Mesos/Raw/FrameworkInfo.hs
|
mit
| 3,065 | 0 | 23 | 906 | 1,163 | 547 | 616 | 109 | 0 |
-- Copyright (c) Microsoft. All rights reserved.
-- Licensed under the MIT license. See LICENSE file in the project root for full license information.
{-# LANGUAGE OverloadedStrings, RecordWildCards #-}
{-|
Copyright : (c) Microsoft
License : MIT
Maintainer : [email protected]
Stability : provisional
Portability : portable
This module defines abstractions for mapping from the Bond type system into the
type system of a target programming language.
-}
module Language.Bond.Codegen.TypeMapping
( -- * Mapping context
MappingContext(..)
, TypeMapping(..)
, TypeNameBuilder
-- * Type mappings
, idlTypeMapping
, cppTypeMapping
, cppCustomAllocTypeMapping
, cppExpandAliasesTypeMapping
, csTypeMapping
, csCollectionInterfacesTypeMapping
, javaTypeMapping
, javaBoxedTypeMapping
-- * Alias mapping
--
-- | <https://microsoft.github.io/bond/manual/compiler.html#type-aliases Type aliases>
-- defined in a schema can optionally be mapped to user specified types.
, AliasMapping(..)
, Fragment(..)
, parseAliasMapping
-- #namespace-mapping#
-- * Namespace mapping
--
-- | Schema namespaces can be mapped into languange-specific namespaces in the
-- generated code.
, NamespaceMapping(..)
, parseNamespaceMapping
-- * Name builders
, getTypeName
, getInstanceTypeName
, getElementTypeName
, getAnnotatedTypeName
, getDeclTypeName
, getQualifiedName
-- * Helper functions
, getNamespace
, getDeclNamespace
, customAliasMapping
-- * TypeMapping helper functions
, elementTypeName
, aliasTypeName
, getAliasDeclTypeName
, declTypeName
, declQualifiedTypeName
) where
import Data.List
import Data.Monoid
import Data.Maybe
import Control.Applicative
import Control.Monad.Reader
import Prelude
import qualified Data.Text.Lazy as L
import Data.Text.Lazy.Builder
import Text.Shakespeare.Text
import Language.Bond.Syntax.Types
import Language.Bond.Syntax.Util
import Language.Bond.Util
import Language.Bond.Codegen.CustomMapping
-- | The 'MappingContext' encapsulates information about mapping Bond types
-- into types in the target language. A context instance is passed to code
-- generation templates.
data MappingContext = MappingContext
{ typeMapping :: TypeMapping
, aliasMapping :: [AliasMapping]
, namespaceMapping :: [NamespaceMapping]
, namespaces :: [Namespace]
}
-- | A type representing a type mapping.
data TypeMapping = TypeMapping
{ language :: Maybe Language
, global :: Builder
, separator :: Builder
, mapType :: Type -> TypeNameBuilder
, fixSyntax :: Builder -> Builder
, instanceMapping :: TypeMapping
, elementMapping :: TypeMapping
, annotatedMapping :: TypeMapping
}
type TypeNameBuilder = Reader MappingContext Builder
-- | Returns the namespace for the 'MappingContext'. The namespace may be
-- different than specified in the schema definition file due to
-- <#namespace-mapping namespace mapping>.
getNamespace :: MappingContext -> QualifiedName
getNamespace c@MappingContext {..} = resolveNamespace c namespaces
-- | Returns the namespace for a 'Declaration' in the specified 'MappingContext'.
getDeclNamespace :: MappingContext -> Declaration -> QualifiedName
getDeclNamespace c = resolveNamespace c . declNamespaces
-- | Builds a qualified name in the specified 'MappingContext'.
getQualifiedName :: MappingContext -> QualifiedName -> Builder
getQualifiedName MappingContext { typeMapping = m } = (global m <>) . sepBy (separator m) toText
-- | Builds the qualified name for a 'Declaration' in the specified
-- 'MappingContext'.
getDeclTypeName :: MappingContext -> Declaration -> Builder
getDeclTypeName c = getQualifiedName c . declQualifiedName c
-- | Builds the name of a 'Type' in the specified 'MappingContext'.
getTypeName :: MappingContext -> Type -> Builder
getTypeName c t = fix' $ runReader (typeName t) c
where
fix' = fixSyntax $ typeMapping c
getAliasDeclTypeName :: MappingContext -> Declaration -> Builder
getAliasDeclTypeName c d = fix' $ runReader (aliasDeclTypeName d) c
where
fix' = fixSyntax $ typeMapping c
-- | Builds the name to be used when instantiating a 'Type'. The instance type
-- name may be different than the type name returned by 'getTypeName' when the
-- latter is an interface.
getInstanceTypeName :: MappingContext -> Type -> Builder
getInstanceTypeName c t = runReader (instanceTypeName t) c
-- | Builds the name to be used when instantiating an element 'Type'.
getElementTypeName :: MappingContext -> Type -> Builder
getElementTypeName c t = runReader (elementTypeName t) c
-- | Builds the annotated name of a 'Type'. The type annotations are used to
-- express type information about a Bond type that doesn't directly map to
-- the target language type system (e.g. distinction between a nullable and
-- non-nullable string in C# type system).
getAnnotatedTypeName :: MappingContext -> Type -> Builder
getAnnotatedTypeName c t = runReader (annotatedTypeName t) c
-- | Returns 'True' if the alias has a custom mapping in the given
-- 'MappingContext'.
customAliasMapping :: MappingContext -> Declaration -> Bool
customAliasMapping = (maybe False (const True) .) . findAliasMapping
-- | The Bond IDL type name mapping.
idlTypeMapping :: TypeMapping
idlTypeMapping = TypeMapping
Nothing
""
"."
idlType
id
idlTypeMapping
idlTypeMapping
idlTypeMapping
-- | The default C++ type name mapping.
cppTypeMapping :: TypeMapping
cppTypeMapping = TypeMapping
(Just Cpp)
"::"
"::"
cppType
cppSyntaxFix
cppTypeMapping
cppTypeMapping
cppTypeMapping
-- | C++ type name mapping using a custom allocator.
cppCustomAllocTypeMapping :: ToText a => Bool -> a -> TypeMapping
cppCustomAllocTypeMapping scoped alloc = TypeMapping
(Just Cpp)
"::"
"::"
(cppTypeCustomAlloc scoped $ toText alloc)
cppSyntaxFix
(cppCustomAllocTypeMapping scoped alloc)
(cppCustomAllocTypeMapping scoped alloc)
(cppCustomAllocTypeMapping scoped alloc)
cppExpandAliasesTypeMapping :: TypeMapping -> TypeMapping
cppExpandAliasesTypeMapping m = m
{ mapType = cppTypeExpandAliases $ mapType m
, instanceMapping = cppExpandAliasesTypeMapping $ instanceMapping m
, elementMapping = cppExpandAliasesTypeMapping $ elementMapping m
, annotatedMapping = cppExpandAliasesTypeMapping $ annotatedMapping m
}
-- | The default C# type name mapping.
csTypeMapping :: TypeMapping
csTypeMapping = TypeMapping
(Just Cs)
"global::"
"."
csType
id
csTypeMapping
csTypeMapping
csAnnotatedTypeMapping
-- | C# type name mapping using interfaces rather than concrete types to
-- represent collections.
csCollectionInterfacesTypeMapping :: TypeMapping
csCollectionInterfacesTypeMapping = TypeMapping
(Just Cs)
"global::"
"."
csInterfaceType
id
csCollectionInstancesTypeMapping
csCollectionInterfacesTypeMapping
csAnnotatedTypeMapping
csCollectionInstancesTypeMapping :: TypeMapping
csCollectionInstancesTypeMapping = csCollectionInterfacesTypeMapping {mapType = csType}
csAnnotatedTypeMapping :: TypeMapping
csAnnotatedTypeMapping = TypeMapping
(Just Cs)
"global::"
"."
(csTypeAnnotation csType)
id
csAnnotatedTypeMapping
csAnnotatedTypeMapping
csAnnotatedTypeMapping
-- | The default Java type name mapping.
javaTypeMapping :: TypeMapping
javaTypeMapping = TypeMapping
(Just Java)
""
"."
javaType
id
javaTypeMapping
javaBoxedTypeMapping
javaTypeMapping
-- | Java type mapping that boxes all primitives.
javaBoxedTypeMapping :: TypeMapping
javaBoxedTypeMapping = TypeMapping
(Just Java)
""
"."
javaBoxedType
id
javaTypeMapping
javaBoxedTypeMapping
javaTypeMapping
infixr 6 <<>>
(<<>>) :: (Monoid r, Monad m) => m r -> m r -> m r
(<<>>) = liftM2 (<>)
infixr 6 <>>
(<>>) :: (Monoid r, Monad m) => r -> m r -> m r
(<>>) x = liftM (x <>)
infixr 6 <<>
(<<>) :: (Monoid r, Monad m) => m r -> r -> m r
(<<>) x y = liftM (<> y) x
pureText :: ToText a => a -> TypeNameBuilder
pureText = pure . toText
commaSepTypeNames :: [Type] -> TypeNameBuilder
commaSepTypeNames [] = return mempty
commaSepTypeNames [x] = typeName x
commaSepTypeNames (x:xs) = typeName x <<>> ", " <>> commaSepTypeNames xs
typeName :: Type -> TypeNameBuilder
typeName t = do
m <- asks $ mapType . typeMapping
m t
localWith :: (TypeMapping -> TypeMapping) -> TypeNameBuilder -> TypeNameBuilder
localWith f = local $ \c -> c { typeMapping = f $ typeMapping c }
-- | Builder for nested element types (e.g. list elements) in context of 'TypeNameBuilder' monad.
-- Used to implement 'mapType' function of 'TypeMapping'.
elementTypeName :: Type -> TypeNameBuilder
elementTypeName = localWith elementMapping . typeName
instanceTypeName :: Type -> TypeNameBuilder
instanceTypeName = localWith instanceMapping . typeName
annotatedTypeName :: Type -> TypeNameBuilder
annotatedTypeName = localWith annotatedMapping . typeName
resolveNamespace :: MappingContext -> [Namespace] -> QualifiedName
resolveNamespace MappingContext {..} ns =
maybe namespaceName toNamespace $ find ((namespaceName ==) . fromNamespace) namespaceMapping
where
namespaceName = nsName . fromJust $ mappingNamespace <|> neutralNamespace <|> fallbackNamespace
mappingNamespace = find ((language typeMapping ==) . nsLanguage) ns
neutralNamespace = find (isNothing . nsLanguage) ns
fallbackNamespace = case (language typeMapping) of
Nothing -> Just $ last ns
Just l -> error $ "No namespace declared for " ++ show l
declQualifiedName :: MappingContext -> Declaration -> QualifiedName
declQualifiedName c decl = getDeclNamespace c decl ++ [declName decl]
-- | Builder for the qualified name for a 'Declaration' in context of 'TypeNameBuilder' monad.
-- Used to implement 'mapType' function of 'TypeMapping'.
declQualifiedTypeName :: Declaration -> TypeNameBuilder
declQualifiedTypeName decl = do
ctx <- ask
return $ getDeclTypeName ctx decl
-- | Builder for the name for a 'Declaration' in context of 'TypeNameBuilder' monad.
-- Used to implement 'mapType' function of 'TypeMapping'.
declTypeName :: Declaration -> TypeNameBuilder
declTypeName decl = do
ctx <- ask
if namespaces ctx == declNamespaces decl
then pureText $ declName decl
else declQualifiedTypeName decl
findAliasMapping :: MappingContext -> Declaration -> Maybe AliasMapping
findAliasMapping ctx a = find isSameAlias $ aliasMapping ctx
where
aliasDeclName = declQualifiedName ctx a
isSameNs = namespaces ctx == declNamespaces a
isSameAlias m = aliasDeclName == aliasName m || isSameNs && [declName a] == aliasName m
-- | Builder for the type alias name in context of 'TypeNameBuilder' monad.
-- Used to implement 'mapType' function of 'TypeMapping'.
aliasTypeName :: Declaration -> [Type] -> TypeNameBuilder
aliasTypeName a args = do
ctx <- ask
case findAliasMapping ctx a of
Just AliasMapping {..} -> foldr ((<<>>) . fragment) (pure mempty) aliasTemplate
Nothing -> typeName $ resolveAlias a args
where
fragment (Fragment s) = pureText s
fragment (Placeholder i) = typeName $ args !! i
aliasDeclTypeName :: Declaration -> TypeNameBuilder
aliasDeclTypeName a@Alias {..} = do
ctx <- ask
case findAliasMapping ctx a of
Just AliasMapping {..} -> foldr ((<<>>) . fragment) (pure mempty) aliasTemplate
Nothing -> typeName aliasType
where
fragment (Fragment s) = pureText s
fragment (Placeholder i) = pureText $ paramName $ declParams !! i
aliasDeclTypeName _ = error "aliasDeclTypeName: impossible happened."
-- | Builder for the type alias element name in context of 'TypeNameBuilder' monad.
aliasElementTypeName :: Declaration -> [Type] -> TypeNameBuilder
aliasElementTypeName a args = do
ctx <- ask
case findAliasMapping ctx a of
Just AliasMapping {..} -> foldr ((<<>>) . fragment) (pure mempty) aliasTemplate
Nothing -> elementTypeName $ resolveAlias a args
where
fragment (Fragment s) = pureText s
fragment (Placeholder i) = elementTypeName $ args !! i
-- IDL type mapping
idlType :: Type -> TypeNameBuilder
idlType BT_Int8 = pure "int8"
idlType BT_Int16 = pure "int16"
idlType BT_Int32 = pure "int32"
idlType BT_Int64 = pure "int64"
idlType BT_UInt8 = pure "uint8"
idlType BT_UInt16 = pure "uint16"
idlType BT_UInt32 = pure "uint32"
idlType BT_UInt64 = pure "uint64"
idlType BT_Float = pure "float"
idlType BT_Double = pure "double"
idlType BT_Bool = pure "bool"
idlType BT_String = pure "string"
idlType BT_WString = pure "wstring"
idlType BT_MetaName = pure "bond_meta::name"
idlType BT_MetaFullName = pure "bond_meta::full_name"
idlType BT_Blob = pure "blob"
idlType (BT_IntTypeArg x) = pureText x
idlType (BT_Maybe type_) = elementTypeName type_
idlType (BT_List element) = "list<" <>> elementTypeName element <<> ">"
idlType (BT_Nullable element) = "nullable<" <>> elementTypeName element <<> ">"
idlType (BT_Vector element) = "vector<" <>> elementTypeName element <<> ">"
idlType (BT_Set element) = "set<" <>> elementTypeName element <<> ">"
idlType (BT_Map key value) = "map<" <>> elementTypeName key <<>> ", " <>> elementTypeName value <<> ">"
idlType (BT_Bonded type_) = "bonded<" <>> elementTypeName type_ <<> ">"
idlType (BT_TypeParam param) = pureText $ paramName param
idlType (BT_UserDefined a@Alias {..} args) = aliasTypeName a args
idlType (BT_UserDefined decl args) = declQualifiedTypeName decl <<>> (angles <$> commaSepTypeNames args)
-- C++ type mapping
cppType :: Type -> TypeNameBuilder
cppType BT_Int8 = pure "int8_t"
cppType BT_Int16 = pure "int16_t"
cppType BT_Int32 = pure "int32_t"
cppType BT_Int64 = pure "int64_t"
cppType BT_UInt8 = pure "uint8_t"
cppType BT_UInt16 = pure "uint16_t"
cppType BT_UInt32 = pure "uint32_t"
cppType BT_UInt64 = pure "uint64_t"
cppType BT_Float = pure "float"
cppType BT_Double = pure "double"
cppType BT_Bool = pure "bool"
cppType BT_String = pure "std::string"
cppType BT_WString = pure "std::wstring"
cppType BT_MetaName = pure "std::string"
cppType BT_MetaFullName = pure "std::string"
cppType BT_Blob = pure "::bond::blob"
cppType (BT_IntTypeArg x) = pureText x
cppType (BT_Maybe type_) = "::bond::maybe<" <>> elementTypeName type_ <<> ">"
cppType (BT_List element) = "std::list<" <>> elementTypeName element <<> ">"
cppType (BT_Nullable element) = "::bond::nullable<" <>> elementTypeName element <<> ">"
cppType (BT_Vector element) = "std::vector<" <>> elementTypeName element <<> ">"
cppType (BT_Set element) = "std::set<" <>> elementTypeName element <<> ">"
cppType (BT_Map key value) = "std::map<" <>> elementTypeName key <<>> ", " <>> elementTypeName value <<> ">"
cppType (BT_Bonded type_) = "::bond::bonded<" <>> elementTypeName type_ <<> ">"
cppType (BT_TypeParam param) = pureText $ paramName param
cppType (BT_UserDefined decl args) = declQualifiedTypeName decl <<>> (angles <$> commaSepTypeNames args)
-- C++ type mapping with custom allocator
cppTypeCustomAlloc :: Bool -> Builder -> Type -> TypeNameBuilder
cppTypeCustomAlloc scoped alloc BT_String = "std::basic_string<char, std::char_traits<char>, " <>> rebindAllocator scoped alloc (pure "char") <<> " >"
cppTypeCustomAlloc scoped alloc BT_WString = "std::basic_string<wchar_t, std::char_traits<wchar_t>, " <>> rebindAllocator scoped alloc (pure "wchar_t") <<> " >"
cppTypeCustomAlloc scoped alloc BT_MetaName = cppTypeCustomAlloc scoped alloc BT_String
cppTypeCustomAlloc scoped alloc BT_MetaFullName = cppTypeCustomAlloc scoped alloc BT_String
cppTypeCustomAlloc scoped alloc (BT_List element) = "std::list<" <>> elementTypeName element <<>> ", " <>> allocator scoped alloc element <<> ">"
cppTypeCustomAlloc scoped alloc (BT_Vector element) = "std::vector<" <>> elementTypeName element <<>> ", " <>> allocator scoped alloc element <<> ">"
cppTypeCustomAlloc scoped alloc (BT_Set element) = "std::set<" <>> elementTypeName element <<>> comparer element <<>> allocator scoped alloc element <<> ">"
cppTypeCustomAlloc scoped alloc (BT_Map key value) = "std::map<" <>> elementTypeName key <<>> ", " <>> elementTypeName value <<>> comparer key <<>> pairAllocator scoped alloc key value <<> ">"
cppTypeCustomAlloc _ _ t = cppType t
cppTypeExpandAliases :: (Type -> TypeNameBuilder) -> Type -> TypeNameBuilder
cppTypeExpandAliases _ (BT_UserDefined a@Alias {..} args) = aliasTypeName a args
cppTypeExpandAliases m t = m t
comparer :: Type -> TypeNameBuilder
comparer t = ", std::less<" <>> elementTypeName t <<> ">, "
rebindAllocator :: Bool -> Builder -> TypeNameBuilder -> TypeNameBuilder
rebindAllocator False alloc element = "typename std::allocator_traits<" <>> alloc <>> ">::template rebind_alloc<" <>> element <<> ">"
rebindAllocator True alloc element = "std::scoped_allocator_adaptor<" <>> rebindAllocator False alloc element <<> " >"
allocator :: Bool -> Builder -> Type -> TypeNameBuilder
allocator scoped alloc element = rebindAllocator scoped alloc $ elementTypeName element
pairAllocator :: Bool -> Builder -> Type -> Type -> TypeNameBuilder
pairAllocator scoped alloc key value = rebindAllocator scoped alloc $ "std::pair<const " <>> elementTypeName key <<>> ", " <>> elementTypeName value <<> "> "
cppSyntaxFix :: Builder -> Builder
cppSyntaxFix = fromLazyText . snd . L.foldr fixInvalid (' ', mempty) . toLazyText
where
fixInvalid c r
-- C++98 requires space between consecutive angle brackets
| c == '>' && fst r == '>' = (c, L.cons c (L.cons ' ' $ snd r))
-- <: is digraph for [
| c == '<' && fst r == ':' = (c, L.cons c (L.cons ' ' $ snd r))
| otherwise = (c, L.cons c (snd r))
-- C# type mapping
csType :: Type -> TypeNameBuilder
csType BT_Int8 = pure "sbyte"
csType BT_Int16 = pure "short"
csType BT_Int32 = pure "int"
csType BT_Int64 = pure "long"
csType BT_UInt8 = pure "byte"
csType BT_UInt16 = pure "ushort"
csType BT_UInt32 = pure "uint"
csType BT_UInt64 = pure "ulong"
csType BT_Float = pure "float"
csType BT_Double = pure "double"
csType BT_Bool = pure "bool"
csType BT_String = pure "string"
csType BT_WString = pure "string"
csType BT_MetaName = pure "string"
csType BT_MetaFullName = pure "string"
csType BT_Blob = pure "System.ArraySegment<byte>"
csType (BT_IntTypeArg x) = pureText x
csType (BT_Maybe type_) = csType (BT_Nullable type_)
csType (BT_Nullable element) = typeName element <<> if isScalar element then "?" else mempty
csType (BT_List element) = "LinkedList<" <>> elementTypeName element <<> ">"
csType (BT_Vector element) = "List<" <>> elementTypeName element <<> ">"
csType (BT_Set element) = "HashSet<" <>> elementTypeName element <<> ">"
csType (BT_Map key value) = "Dictionary<" <>> elementTypeName key <<>> ", " <>> elementTypeName value <<> ">"
csType (BT_Bonded type_) = "global::Bond.IBonded<" <>> typeName type_ <<> ">"
csType (BT_TypeParam param) = pureText $ paramName param
csType (BT_UserDefined a@Alias {} args) = aliasTypeName a args
csType (BT_UserDefined decl args) = declTypeName decl <<>> (angles <$> localWith (const csTypeMapping) (commaSepTypeNames args))
-- C# type mapping with collection interfaces
csInterfaceType :: Type -> TypeNameBuilder
csInterfaceType (BT_List element) = "ICollection<" <>> elementTypeName element <<> ">"
csInterfaceType (BT_Vector element) = "IList<" <>> elementTypeName element <<> ">"
csInterfaceType (BT_Set element) = "ISet<" <>> elementTypeName element <<> ">"
csInterfaceType (BT_Map key value) = "IDictionary<" <>> elementTypeName key <<>> ", " <>> elementTypeName value <<> ">"
csInterfaceType t = csType t
-- C# type annotation mapping
csTypeAnnotation :: (Type -> TypeNameBuilder) -> Type -> TypeNameBuilder
csTypeAnnotation _ BT_WString = pure "global::Bond.Tag.wstring"
csTypeAnnotation _ (BT_Nullable element) = "global::Bond.Tag.nullable<" <>> typeName element <<> ">"
csTypeAnnotation _ (BT_Maybe a@(BT_UserDefined Alias{} _)) = typeName a
csTypeAnnotation _ (BT_TypeParam (TypeParam _ Nothing)) = pure "global::Bond.Tag.classT"
csTypeAnnotation _ (BT_TypeParam (TypeParam _ (Just Value))) = pure "global::Bond.Tag.structT"
csTypeAnnotation _ (BT_UserDefined Alias {aliasType = BT_Blob} _) = pure "global::Bond.Tag.blob"
csTypeAnnotation m t@(BT_UserDefined a@Alias {..} args)
| isContainer t = m t
| otherwise = typeName $ resolveAlias a args
csTypeAnnotation _ (BT_UserDefined decl args) = declTypeName decl <<>> (angles <$> commaSepTypeNames args)
csTypeAnnotation m t = m t
-- Java type mapping
javaType :: Type -> TypeNameBuilder
javaType BT_Int8 = pure "byte"
javaType BT_Int16 = pure "short"
javaType BT_Int32 = pure "int"
javaType BT_Int64 = pure "long"
javaType BT_UInt8 = pure "byte"
javaType BT_UInt16 = pure "short"
javaType BT_UInt32 = pure "int"
javaType BT_UInt64 = pure "long"
javaType BT_Float = pure "float"
javaType BT_Double = pure "double"
javaType BT_Bool = pure "boolean"
javaType BT_String = pure "java.lang.String"
javaType BT_WString = pure "java.lang.String"
javaType BT_MetaName = pure "java.lang.String"
javaType BT_MetaFullName = pure "java.lang.String"
javaType BT_Blob = pure "org.bondlib.Blob"
javaType (BT_IntTypeArg x) = pureText x
javaType (BT_Maybe BT_Int8) = pure "org.bondlib.SomethingByte"
javaType (BT_Maybe BT_Int16) = pure "org.bondlib.SomethingShort"
javaType (BT_Maybe BT_Int32) = pure "org.bondlib.SomethingInteger"
javaType (BT_Maybe BT_Int64) = pure "org.bondlib.SomethingLong"
javaType (BT_Maybe BT_UInt8) = pure "org.bondlib.SomethingByte"
javaType (BT_Maybe BT_UInt16) = pure "org.bondlib.SomethingShort"
javaType (BT_Maybe BT_UInt32) = pure "org.bondlib.SomethingInteger"
javaType (BT_Maybe BT_UInt64) = pure "org.bondlib.SomethingLong"
javaType (BT_Maybe BT_Float) = pure "org.bondlib.SomethingFloat"
javaType (BT_Maybe BT_Double) = pure "org.bondlib.SomethingDouble"
javaType (BT_Maybe BT_Bool) = pure "org.bondlib.SomethingBoolean"
javaType (BT_UserDefined a@Alias {} args) = javaType (resolveAlias a args)
javaType (BT_Maybe (BT_UserDefined a@Alias {} args)) = javaType (BT_Maybe (resolveAlias a args))
javaType (BT_Maybe fieldType) = "org.bondlib.SomethingObject<" <>> javaBoxedType fieldType <<> ">"
javaType (BT_Nullable elementType) = javaBoxedType elementType
javaType (BT_List elementType) = "java.util.List<" <>> elementTypeName elementType <<> ">"
javaType (BT_Vector elementType) = "java.util.List<" <>> elementTypeName elementType <<> ">"
javaType (BT_Set elementType) = "java.util.Set<" <>> elementTypeName elementType <<> ">"
javaType (BT_Map keyType valueType) = "java.util.Map<" <>> elementTypeName keyType <<>> ", " <>> elementTypeName valueType <<> ">"
javaType (BT_TypeParam param) = pureText $ paramName param
javaType (BT_Bonded structType) = "org.bondlib.Bonded<" <>> javaBoxedType structType <<> ">"
javaType (BT_UserDefined decl args) =
declQualifiedTypeName decl <<>> (angles <$> localWith (const javaBoxedTypeMapping) (commaSepTypeNames args))
-- Java type mapping to a reference type with primitive types boxed
javaBoxedType :: Type -> TypeNameBuilder
javaBoxedType BT_Int8 = pure "java.lang.Byte"
javaBoxedType BT_Int16 = pure "java.lang.Short"
javaBoxedType BT_Int32 = pure "java.lang.Integer"
javaBoxedType BT_Int64 = pure "java.lang.Long"
javaBoxedType BT_UInt8 = pure "java.lang.Byte"
javaBoxedType BT_UInt16 = pure "java.lang.Short"
javaBoxedType BT_UInt32 = pure "java.lang.Integer"
javaBoxedType BT_UInt64 = pure "java.lang.Long"
javaBoxedType BT_Float = pure "java.lang.Float"
javaBoxedType BT_Double = pure "java.lang.Double"
javaBoxedType BT_Bool = pure "java.lang.Boolean"
javaBoxedType (BT_UserDefined a@Alias {} args) = aliasElementTypeName a args
javaBoxedType t = javaType t
|
jdubrule/bond
|
compiler/src/Language/Bond/Codegen/TypeMapping.hs
|
mit
| 23,861 | 0 | 13 | 3,973 | 5,920 | 2,981 | 2,939 | 433 | 3 |
{-# LANGUAGE TypeFamilies #-}
module Data.Mutable.Deque
( Deque
, UDeque
, asUDeque
, SDeque
, asSDeque
, BDeque
, asBDeque
, module Data.Mutable.Class
) where
import Control.Exception (assert)
import Control.Monad (liftM)
import Data.Mutable.Class
import qualified Data.Vector.Generic.Mutable as V
import qualified Data.Vector.Mutable as B
import qualified Data.Vector.Storable.Mutable as S
import qualified Data.Vector.Unboxed.Mutable as U
data DequeState v s a = DequeState
(v s a)
{-# UNPACK #-} !Int -- start
{-# UNPACK #-} !Int -- size
-- | A double-ended queue supporting any underlying vector type and any monad.
--
-- This implements a circular double-ended queue with exponential growth.
--
-- Since 0.2.0
newtype Deque v s a = Deque (MutVar s (DequeState v s a))
-- | A 'Deque' specialized to unboxed vectors.
--
-- Since 0.2.0
type UDeque = Deque U.MVector
-- | A 'Deque' specialized to storable vectors.
--
-- Since 0.2.0
type SDeque = Deque S.MVector
-- | A 'Deque' specialized to boxed vectors.
--
-- Since 0.2.0
type BDeque = Deque B.MVector
-- |
-- Since 0.2.0
asUDeque :: UDeque s a -> UDeque s a
asUDeque = id
-- |
-- Since 0.2.0
asSDeque :: SDeque s a -> SDeque s a
asSDeque = id
-- |
-- Since 0.2.0
asBDeque :: BDeque s a -> BDeque s a
asBDeque = id
instance MutableContainer (Deque v s a) where
type MCState (Deque v s a) = s
instance V.MVector v a => MutableCollection (Deque v s a) where
type CollElement (Deque v s a) = a
newColl = do
v <- V.new baseSize
liftM Deque $ newRef (DequeState v 0 0)
where
baseSize = 32
{-# INLINE newColl #-}
instance V.MVector v a => MutablePopFront (Deque v s a) where
popFront (Deque var) = do
DequeState v start size <- readRef var
if size == 0
then return Nothing
else do
x <- V.unsafeRead v start
let start' = start + 1
start''
| start' >= V.length v = 0
| otherwise = start'
writeRef var $! DequeState v start'' (size - 1)
return $! Just x
{-# INLINE popFront #-}
instance V.MVector v a => MutablePopBack (Deque v s a) where
popBack (Deque var) = do
DequeState v start size <- readRef var
if size == 0
then return Nothing
else do
let size' = size - 1
end = start + size'
end'
| end >= V.length v = end - V.length v
| otherwise = end
x <- V.unsafeRead v end'
writeRef var $! DequeState v start size'
return $! Just x
{-# INLINE popBack #-}
instance V.MVector v a => MutablePushFront (Deque v s a) where
pushFront (Deque var) x = do
DequeState v start size <- readRef var
inner v start size
where
inner v start size = do
if size >= V.length v
then newVector v start size inner
else do
let size' = size + 1
start' = (start - 1) `rem` V.length v
start''
| start' < 0 = V.length v + start'
| otherwise = start'
V.unsafeWrite v start'' x
writeRef var $! DequeState v start'' size'
{-# INLINE pushFront #-}
instance V.MVector v a => MutablePushBack (Deque v s a) where
pushBack (Deque var) x = do
DequeState v start size <- readRef var
inner v start size
where
inner v start size = do
if size >= V.length v
then newVector v start size inner
else do
let end = start + size
end'
| end >= V.length v = end - V.length v
| otherwise = end
V.unsafeWrite v end' x
writeRef var $! DequeState v start (size + 1)
{-# INLINE pushBack #-}
newVector :: (PrimMonad m, V.MVector v a)
=> v (PrimState m) a
-> Int
-> Int
-> (v (PrimState m) a -> Int -> Int -> m b)
-> m b
newVector v size2 sizeOrig f = assert (sizeOrig == V.length v) $ do
v' <- V.unsafeNew (V.length v * 2)
let size1 = V.length v - size2
V.unsafeCopy
(V.unsafeTake size1 v')
(V.unsafeSlice size2 size1 v)
V.unsafeCopy
(V.unsafeSlice size1 size2 v')
(V.unsafeTake size2 v)
f v' 0 sizeOrig
{-# INLINE newVector #-}
|
bitemyapp/mutable-containers
|
Data/Mutable/Deque.hs
|
mit
| 4,740 | 0 | 21 | 1,806 | 1,419 | 715 | 704 | 117 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Data.Monoid
import Data.Prototype
import Lens.Micro.Platform ((.=))
import Yi.Config
import Yi.Config.Default (defaultConfig)
import Yi.Config.Default.HaskellMode (configureHaskellMode)
import Yi.Config.Default.JavaScriptMode (configureJavaScriptMode)
import Yi.Config.Default.MiscModes (configureMiscModes)
import Yi.Config.Default.Vim
import Yi.Config.Default.Vty
import Yi.Config.Simple hiding (super)
import qualified Yi.Keymap.Vim as V2
import qualified Yi.Keymap.Vim.Common as V2
import qualified Yi.Keymap.Vim.Utils as V2
import qualified Yi.Mode.Haskell as Haskell
import qualified Yi.Rope as R
main :: IO ()
main = configMain defaultConfig $ do
configureVty
myVimConfig
configureHaskellMode
configureJavaScriptMode
configureMiscModes
myVimConfig :: ConfigM ()
myVimConfig = do
configureVim
defaultKmA .= myKeymapSet
modeTableA .= myModes
configCheckExternalChangesObsessivelyA .= False
myKeymapSet :: KeymapSet
myKeymapSet = V2.mkKeymapSet $ V2.defVimConfig `override` \super this ->
let eval = V2.pureEval this
in super {
-- Here we can add custom bindings.
-- See Yi.Keymap.Vim.Common for datatypes and
-- Yi.Keymap.Vim.Utils for useful functions like mkStringBindingE
-- In case of conflict, that is if there exist multiple bindings
-- whose prereq function returns WholeMatch,
-- the first such binding is used.
-- So it's important to have custom bindings first.
V2.vimBindings = myBindings eval <> V2.vimBindings super
}
myBindings :: (V2.EventString -> EditorM ()) -> [V2.VimBinding]
myBindings eval =
let nmap x y = V2.mkStringBindingE V2.Normal V2.Drop (x, y, id)
imap x y = V2.VimBindingE (\evs state -> case V2.vsMode state of
V2.Insert _ ->
fmap (const (y >> return V2.Continue))
(evs `V2.matchesString` x)
_ -> V2.NoMatch)
in [ nmap "<C-h>" previousTabE
, nmap "<C-l>" nextTabE
-- Press space to clear incremental search highlight
, nmap " " (eval ":nohlsearch<CR>")
, nmap "<F3>" (withCurrentBuffer deleteTrailingSpaceB)
, nmap "<F4>" (withCurrentBuffer moveToSol)
, nmap "<F1>" (withCurrentBuffer readCurrentWordB >>= printMsg . R.toText)
, imap "<Home>" (withCurrentBuffer moveToSol)
, imap "<End>" (withCurrentBuffer moveToEol)
]
myModes :: [AnyMode]
myModes = [
AnyMode Haskell.fastMode {
-- Disable beautification
modePrettify = const $ return ()
}
]
|
siddhanathan/yi
|
example-configs/yi-vim-vty-dynamic/yi.hs
|
gpl-2.0
| 2,920 | 0 | 21 | 893 | 612 | 341 | 271 | 55 | 2 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ru-RU">
<title>Revisit | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
0xkasun/security-tools
|
src/org/zaproxy/zap/extension/revisit/resources/help_ru_RU/helpset_ru_RU.hs
|
apache-2.0
| 969 | 80 | 66 | 159 | 413 | 209 | 204 | -1 | -1 |
{-# LANGUAGE ViewPatterns #-}
module PrettyPrint (showExpr) where
import Data.List (intersperse)
import qualified Language.Java.Pretty (prettyPrint)
import Text.PrettyPrint.ANSI.Leijen (Doc, (<+>), (<>), text, dot, colon)
import qualified Text.PrettyPrint.ANSI.Leijen as PP
import Unbound.Generics.LocallyNameless
import qualified Src as S
import Syntax
class Pretty p where
ppr :: (Applicative m, LFresh m) => p -> m Doc
instance Pretty Expr where
ppr (Var x) = return . text . show $ x
ppr (App e es) = PP.parens <$> ((<+>) <$> ppr e <*> (ppr es))
ppr (Lam bnd) = lunbind bnd $ \(delta, b) -> do
delta' <- ppr delta
b' <- ppr b
return (PP.parens $ text "λ" <> delta' <+> dot <+> b')
ppr (Star) = return $ PP.char '★'
ppr (Pi bnd) = lunbind bnd $ \(delta, b) -> do
let Cons bb = delta
let ((x, Embed t), bb') = unrebind bb
b' <- ppr b
if (head (show x) == '_' && isEmpty bb')
then do
t' <- ppr t
return (PP.parens $ t' <+> text "→" <+> b')
else do
delta' <- ppr delta
return (PP.parens $ text "Π" <> delta' <+> dot <+> b')
ppr (Mu b) = lunbind b $ \((x, Embed t), e) -> do
t' <- ppr t
e' <- ppr e
return (PP.parens $ text "μ" <+> (text . show $ x) <+> colon <+> t' <+> dot <+> e')
ppr (F t e) = do
e' <- ppr e
t' <- ppr t
return (text "cast↑" <> PP.brackets t' <+> e')
ppr (U e) = (text "cast↓" <+>) <$> ppr e
ppr (Let bnd) = lunbind bnd $ \((x, Embed e1), e2) -> do
e1' <- ppr e1
e2' <- ppr e2
return (text "let" <+> (text . show $ x) <+> PP.equals <+> e1' PP.<$> text "in" PP.<$> e2')
ppr (LetRec bnd) = lunbind bnd $ \((unrec -> binds, body)) -> do
binds' <- mapM
(\(n, Embed t, Embed e) -> do
e' <- ppr e
t' <- ppr t
return (text (show n) <+> PP.colon <+> t' PP.<$> (PP.indent 2 (PP.equals <+> e'))))
binds
body' <- ppr body
return $ text "let" <+> text "rec" PP.<$>
PP.vcat (intersperse (text "and") (map (PP.indent 2) binds')) PP.<$>
text "in" PP.<$>
body'
ppr (If g e1 e2) = do
g' <- ppr g
e1' <- ppr e1
e2' <- ppr e2
return (text "if" <+> g' <+> text "then" <+> e1' <+> text "else" <+> e2')
ppr (Lit (S.Int n)) = return $ PP.integer n
ppr (Lit (S.String s)) = return $ PP.dquotes (PP.string s)
ppr (Lit (S.Bool b)) = return $ PP.bool b
ppr (Lit (S.Char c)) = return $ PP.char c
ppr (Lit (S.UnitLit)) = return $ text "()"
ppr (PrimOp op e1 e2) = do
e1' <- ppr e1
e2' <- ppr e2
return $ PP.parens (e1' <+> op' <+> e2')
where
op' = text (Language.Java.Pretty.prettyPrint java_op)
java_op =
case op of
S.Arith op' -> op'
S.Compare op' -> op'
S.Logic op' -> op'
ppr Unit = return $ text "Unit"
ppr (JClass "java.lang.Integer") = return $ text "Int"
ppr (JClass "java.lang.String") = return $ text "String"
ppr (JClass "java.lang.Boolean") = return $ text "Bool"
ppr (JClass "java.lang.Character") = return $ text "Char"
ppr (JClass c) = return $ text c
ppr (JNew c args) = do
args' <- mapM ppr args
return (text "new" <+> text c <> PP.parens (PP.cat $ PP.punctuate PP.comma args'))
ppr (JMethod rcv mname args _) = do
args' <- mapM ppr args
c <- case rcv of Left cn -> return $ text cn
Right e -> ppr e
return (c <> dot <> text mname <> PP.parens (PP.cat $ PP.punctuate PP.comma args'))
ppr (JField rcv fname _) = do
c <- case rcv of Left cn -> return $ text cn
Right e -> ppr e
return (c <> dot <> text fname)
ppr (Tuple t) = do
t' <- mapM ppr t
return $ PP.parens $ PP.cat $ PP.punctuate PP.comma t'
ppr (Proj i t) = do
t' <- ppr t
return $ t' <> dot <> text (show i)
ppr (Seq es) = do
es' <- mapM ppr es
return $ PP.vcat es'
ppr (Product ts) = do
ts' <- mapM ppr ts
return $ PP.parens $ PP.cat $ PP.punctuate PP.comma ts'
ppr (Sum bnd) = lunbind bnd $ \((x, Embed t), e) -> do
t' <- ppr t
e' <- ppr e
return (PP.parens $ text "Σ" <+> (text . show $ x) <+> colon <+> t' <+> dot <+> e')
ppr (Pack (e1, e2) t) = do
e1' <- ppr e1
e2' <- ppr e2
t' <- ppr t
return $ text "pack" <+> (PP.parens $ e1' <+> PP.comma <+> e2') <+> text "as" <+> t'
ppr (UnPack (e1, e2) e3 e4) = do
e1' <- ppr e1
e2' <- ppr e2
e3' <- ppr e3
e4' <- ppr e4
return $ text "unpack" <+>
(PP.parens e1' <+> PP.comma <+> e2') <+>
PP.equals <+>
e3' <+>
text "in" <+>
e4'
instance Pretty Tele where
ppr Empty = return PP.empty
ppr (Cons bnd) = do
t' <- ppr t
bnd' <- ppr b'
return ((PP.parens $ (text . show $ x) <+> colon <+> t') <> bnd')
where
((x, Embed t), b') = unrebind bnd
showExpr :: Expr -> String
showExpr = show . runLFreshM . ppr
isEmpty :: Tele -> Bool
isEmpty Empty = True
isEmpty _ = False
|
bixuanzju/fcore
|
lib/newlib/PrettyPrint.hs
|
bsd-2-clause
| 5,268 | 0 | 23 | 1,782 | 2,483 | 1,203 | 1,280 | 137 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Prelude.Compat
import Control.DeepSeq
import Control.Exception
import Control.Monad
import Data.Aeson
import Data.Aeson.Parser
import Data.Attoparsec
import Data.Time.Clock
import System.Environment (getArgs)
import System.IO
import qualified Data.ByteString as B
main = do
(cnt:args) <- getArgs
let count = read cnt :: Int
forM_ args $ \arg -> withFile arg ReadMode $ \h -> do
putStrLn $ arg ++ ":"
start <- getCurrentTime
let loop !n
| n >= count = return ()
| otherwise = do
let go = do
s <- B.hGet h 16384
if B.null s
then loop (n+1)
else go
go
loop 0
end <- getCurrentTime
putStrLn $ " " ++ show (diffUTCTime end start)
|
dmjio/aeson
|
benchmarks/bench/ReadFile.hs
|
bsd-3-clause
| 904 | 0 | 27 | 268 | 282 | 143 | 139 | 33 | 2 |
{--------------------------------------------------------------------------------
Test Grid.
--------------------------------------------------------------------------------}
module Main where
import Graphics.UI.WX
import Graphics.UI.WXCore hiding (Event)
main
= start gui
gui :: IO ()
gui
= do f <- frame [text := "Grid test", visible := False]
-- use text control as logger
textlog <- textCtrl f [wrap := WrapNone, enabled := False]
textCtrlMakeLogActiveTarget textlog
logMessage "logging enabled"
-- grids
g <- gridCtrl f []
gridSetGridLineColour g (colorSystem Color3DFace)
gridSetCellHighlightColour g black
appendColumns g (head names)
appendRows g (map show [1..length (tail names)])
mapM_ (setRow g) (zip [0..] (tail names))
gridAutoSize g
windowOnKeyDown g (onGridKeyDown g)
set g [on gridEvent := onGrid]
-- layout
set f [layout := column 5 [fill (dynamic (widget g))
,hfill $ minsize (sz 20 80) $ widget textlog]
]
focusOn g
set f [visible := True] -- reduce flicker at startup.
return ()
where
onGridKeyDown g (EventKey key mods pt)
= case key of
KeyReturn ->
do logMessage "keyEnter"
gridMoveNext g
_ -> propagateEvent
onGrid ev
= case ev of
GridCellChange row col veto
-> logMessage ("cell changed: " ++ show (row,col))
_ -> propagateEvent
names
= [["First Name", "Last Name"]
,["Daan","Leijen"],["Arjan","van IJzendoorn"]
,["Martijn","Schrage"],["Andres","Loh"]]
setRow g (row,values)
= mapM_ (\(col,value) -> gridSetCellValue g row col value) (zip [0..] values)
{--------------------------------------------------------------------------------
Library?
--------------------------------------------------------------------------------}
gridCtrl :: Window a -> [Prop (Grid ())] -> IO (Grid ())
gridCtrl parent props
= feed2 props 0 $
initialWindow $ \id rect -> \props flags ->
do g <- gridCreate parent id rect flags
gridCreateGrid g 0 0 0
set g props
return g
gridEvent :: Event (Grid a) (EventGrid -> IO ())
gridEvent
= newEvent "gridEvent" gridGetOnGridEvent gridOnGridEvent
gridMoveNext :: Grid a -> IO ()
gridMoveNext g
= do row <- gridGetGridCursorRow g
col <- gridGetGridCursorCol g
rowCount <- gridGetNumberRows g
colCount <- gridGetNumberCols g
let (r,c) = if (row+1 >= rowCount)
then if (col+1 >= colCount)
then (0,0)
else (0,col+1)
else (row+1,col)
gridSetGridCursor g r c
gridMakeCellVisible g r c
return ()
appendColumns :: Grid a -> [String] -> IO ()
appendColumns g []
= return ()
appendColumns g labels
= do n <- gridGetNumberCols g
gridAppendCols g (length labels) True
mapM_ (\(i,label) -> gridSetColLabelValue g i label) (zip [n..] labels)
appendRows :: Grid a -> [String] -> IO ()
appendRows g []
= return ()
appendRows g labels
= do n <- gridGetNumberRows g
gridAppendRows g (length labels) True
mapM_ (\(i,label) -> gridSetRowLabelValue g i label) (zip [n..] labels)
|
ekmett/wxHaskell
|
samples/wx/Grid.hs
|
lgpl-2.1
| 3,380 | 0 | 16 | 974 | 1,126 | 556 | 570 | 81 | 3 |
{-# LANGUAGE LambdaCase, RankNTypes, BangPatterns #-}
module Stream.Combinators where
import Stream.Types
import Control.Applicative
import Control.Monad hiding (foldM)
import Control.Monad.Trans
import Control.Monad.Morph
import Data.Functor.Identity
import qualified Control.Monad.Trans.Free as Free
import Control.Monad.Trans.Free ( FreeT(..), FreeF(Free) )
import qualified Control.Foldl as L
jfold op seed out = \(Folding phi) ->
do x <- phi (\(a :> mx) -> mx >>= \x -> return (op x a))
join
(\_ -> return seed)
return (out x)
jfoldM op seed out = \(Folding phi) ->
do x <- phi (\(a :> mx) -> mx >>= \x -> op x a)
join
(const seed)
out x
-- purely fold ((,) <$> L.product <*> L.sum )
fold op seed out ls = liftM out (loop seed ls) where
loop !x = \case Step (a :> as) -> loop (op x a) as
Delay mas -> mas >>= \as -> loop x as
Return r -> return x
{-# INLINE[0] fold #-}
-- impurely foldM (generalize $ (,) <$> L.product <*> L.sum )
foldM op seed out ls = seed >>= \y -> loop y ls >>= out where
loop !x = \case Step (a :> as) -> op x a >>= \y -> loop y as
Delay mas -> mas >>= \as -> loop x as
Return r -> return x
{-# INLINE[0] foldM #-}
{-# RULES
"fold/buildStream"
forall op seed out phi.
fold op seed out (buildStream phi) = jfold op seed out phi
#-}
{-# RULES
"foldLM/buildStream"
forall op seed out phi.
foldM op seed out (buildStream phi) = jfoldM op seed out phi
#-}
iterFolding_ :: (Monad m) => Folding_ f m a -> (f (m a) -> m a) -> m a
iterFolding_ phi alg = phi alg join return
iterFolding :: (Monad m) => Folding f m a -> (f (m a) -> m a) -> m a
iterFolding phi alg = getFolding phi alg join return
-- -------
-- unfolds
-- -------
unfold :: (Functor f)
=> (a -> Either r (f a)) -> a -> Stream f m r
unfold f = let go = either Return (Step . fmap go) . f in go
unfold_ :: (Functor f)
=> (a -> Either r (f a)) -> a -> Folding_ f m r
unfold_ f a = \construct wrap done ->
let loop = either done (construct . fmap loop) . f in loop a
unfoldM :: (Functor f, Monad m)
=> (a -> m (Either r (f a))) -> a -> Stream f m r
unfoldM f = let loop = Delay . liftM (either Return (Step . fmap loop)) . f
in loop
unfoldM_ :: (Functor f, Monad m)
=> (a -> m (Either r (f a))) -> a -> Folding_ f m r
unfoldM_ f a construct wrap done = loop a where
loop = wrap . liftM (either done (construct . fmap loop)) . f
-- -------------------
-- unfoldM uncons = id
-- -------------------
uncons :: (Monad m, Functor f)
=> Stream f m r -> m (Either r (f (Stream f m r)))
uncons = \case Delay m -> m >>= uncons
Step ff -> return (Right ff)
Return r -> return (Left r)
next :: (Monad m)
=> Stream (Of a) m r -> m (Either r (a, Stream (Of a) m r))
next = liftM (fmap (\(a:>b) -> (a,b))). uncons
-- --------------------
-- diverse combinators
-- --------------------
-- cp Atkey & co
effectfulFolding :: (Functor f, Monad m) =>
(m a -> a)
-> (r -> a)
-> (f a -> a)
-> Stream f m r
-> a
effectfulFolding malg nil falg = loop where
loop = \case Delay m -> malg (liftM loop m)
Step f -> falg (fmap loop f)
Return r -> nil r
efold :: (Functor f, Monad m)
=> (m b -> b) -> (Either a (f b) -> b) -> Stream f m a -> b
efold malg ealg = loop where
loop = \case Delay m -> malg (liftM loop m)
Step f -> ealg (Right (fmap loop f))
Return r -> ealg (Left r)
crush :: (Monad m, Functor f) => Stream f m r -> m (Stream f m r)
crush = \case Delay m -> m; a -> return a
pr :: Functor f => f r -> Folding_ f m r
pr fr = \construct wrap done -> construct (fmap done fr)
sing :: a -> Folding_ (Of a) m () --yield
sing a = \construct wrap done -> construct (a :> done ())
ret :: r -> Folding_ f m r
ret r = \construct wrap done -> done r
consFolding_ :: a -> Folding_ (Of a) m r -> Folding_ (Of a) m r
consFolding_ a phi construct = phi (construct . (a :>) . construct)
consFolding :: a -> Folding (Of a) m r -> Folding (Of a) m r
consFolding a = \(Folding phi) -> Folding (consFolding_ a phi)
consFB :: (Functor f) => f x -> Folding_ f m x -> Folding_ f m x
consFB fx phi construct wrap done = construct (fmap done fx)
consFB_ :: a -> Folding_ (Of a) m x -> Folding_ (Of a) m x
consFB_ a phi construct wrap done =
phi (\_Ofar -> construct (a :> construct _Ofar))
wrap
done
-- ---------
augmentFolding :: Folding (Of a) m () -> Folding (Of a) m r -> Folding (Of a) m r
augmentFolding phi psi = Folding (augmentFolding_ (getFolding phi) (getFolding psi))
augmentsFolding :: Folding f m r -> Folding f m s -> Folding f m (r,s)
augmentsFolding phi psi = Folding (augmentsFolding_ (getFolding phi) (getFolding psi))
augmentFolding_ ::
(forall r'. (f r' -> r') -> (m r' -> r') -> (() -> r') -> r')
-> (forall r'. (f r' -> r') -> (m r' -> r') -> (s -> r') -> r')
-> (forall r'. (f r' -> r') -> (m r' -> r') -> (s -> r') -> r')
augmentFolding_ = \phi psi construct wrap done ->
phi construct
wrap
(\() -> psi construct
wrap
done)
augmentsFolding_ ::
(forall r'. (f r' -> r') -> (m r' -> r') -> (r -> r') -> r')
-> (forall r'. (f r' -> r') -> (m r' -> r') -> (s -> r') -> r')
-> (forall r'. (f r' -> r') -> (m r' -> r') -> ((r,s) -> r') -> r')
augmentsFolding_ = \phi psi construct wrap done ->
phi construct
wrap
(\r -> psi construct
wrap
(\s -> done (r,s)))
-- ---------
maps :: (forall x . f x -> g x) -> Folding f m a -> Folding g m a
maps morph fold = Folding (maps_ morph (getFolding fold))
maps_ :: (forall x . f x -> g x) -> Folding_ f m a -> Folding_ g m a
maps_ morph phi = \construct wrap done ->
phi (construct . morph)
wrap
done
iterT2 :: (Monad m) => (f (m a) -> m a) -> Folding_ f m a -> m a
iterT2 phi fold = fold phi join return
--
-- folded'' :: (Functor f, Monad m) => (f (m a) -> m a) -> Stream f m a -> m a
-- folded'' phi ls = iterT2 phi (foldStreamx ls)
-- ---------------
-- ----------------------------------
-- ill-fated 'distribution' principles
-- ----------------------------------
-- | Distribute 'Proxy' over a monad transformer
-- distribute
-- :: ( Monad m , MonadTrans t , MFunctor t
-- , Monad (t m) , Monad (t (Proxy a' a b' b m)) )
-- => Proxy a' a b' b (t m) r
-- -> t (Proxy a' a b' b m) r
freeFoldingDist2
:: (MFunctor t, MonadTrans t, Functor f, Monad (t (FreeT f m)),
Monad (t m), Monad m) =>
FreeT f (t m) a -> t (FreeT f m) a
freeFoldingDist2 = freeFolding (join . lift . FreeT. return . Free . fmap return)
(join . hoist lift) return
where
freeFolding construct wrap done =
wrap
. liftM (\case Free.Pure r -> done r
Free free_ -> construct (fmap (freeFolding construct wrap done) free_))
. runFreeT
newtype D m f = D {unD :: m (f (D m f))}
dist22
:: (MFunctor t, Monad (t (Folding f m)), Monad m)
=> Folding f (t m) a
-> (f (t (Folding f m) a) -> t (Folding f m) a)
-> t (Folding f m) a
dist22 (Folding phi) construct = phi construct
(join . hoist lift)
return
dd (Folding phi) = phi join join (lift . return)
d3 (Folding phi) y x = phi y (join . hoist lift) x -- (lift . return)
|
haskell-streaming/streaming
|
benchmarks/old/Stream/Combinators.hs
|
bsd-3-clause
| 7,792 | 0 | 18 | 2,449 | 3,315 | 1,687 | 1,628 | 156 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : RefacFunDef
-- Copyright : (c) Christopher Brown 2005
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- This module contains a transformation for HaRe.
-- Function Definition folding.
-- Looks for duplicate code and replaces it with a call to the function.
-- e.g.
--
-- @ square x = x * x @
--
-- @ g x y = x * x + y * y @
--
-- will be refactored to:
--
-- @ square x = x * x @
--
-- @ g x y = square x + square y @
--
-----------------------------------------------------------------------------
module RefacFunDef (
-- ** Data types
Binding, Environment, NonSetEnv,
FunctionPats, WhereDecls,
-- * Function types
subFunctionDef, checkInWhere, checkInPat,
createFunc, createFunc', getEnvironment,
canAddBind, checkVal, rewritePatsInEnv,
doZip, zipHighlightedMatch, callZipHighlightedMatch,
zipHighlightedField, zipHighlightedStmt,
-- * Type signatures with argument docs
findDefNameAndExp
) where
import PrettyPrint
import PrettyPrint
import PosSyntax
import AbstractIO
import Data.Maybe
import TypedIds
import UniqueNames hiding (srcLoc)
import PNT
import TiPNT
import Data.List
import RefacUtils
import PFE0 (findFile)
import MUtils (( # ))
import RefacLocUtils
import RefacGenFold hiding (FunctionPats, WhereDecls, Er, Patt, Mat, findDefNameAndExp, PatFun)
-- | Binds an exp to another e.g. (HsID x, HsLit 5) says x is bound to 5.
-- and it continues until the next non-comment line
type Binding = (HsExpP, HsExpP)
-- | An environment is a *set* of bindings.
type Environment = [Binding]
{- | An environment that is not yet a set - should be processed into an
'Environment'. -}
type NonSetEnv = [Maybe Binding]
-- | An argument list for a function which of course is a list of paterns.
type FunctionPats = [HsPatP]
-- | A list of declarations used to represent a where or let clause.
type WhereDecls = [HsDeclP]
data PatFun = Mat | Patt | Er deriving (Eq, Show)
{- | Function Definition folding.
This folding takes a function definition, looks for duplicate code and
replaces it with a call to the function.
e.g.
@
square x = x * x
g x y = x * x + y * y
@
will be refactored to:
@
square x = x * x
g x y = square x + square y
@
-}
subFunctionDef args
= do let fileName = args!!0
beginRow = read (args!!1)::Int
beginCol = read (args!!2)::Int
endRow = read (args!!3)::Int
endCol = read (args!!4)::Int
AbstractIO.putStrLn "subFunctionDef"
(inscps, exps, mod, tokList) <- parseSourceFile fileName
-- Parse the input file.
-- (inscps, exps, mod, tokList) <- parseSourceFile fileName
-- Find the function that's been highlighted as the refactree
let (ty, pnt, pats, subExp, wh)
= findDefNameAndExp tokList
(beginRow, beginCol)
(endRow, endCol)
mod
let exp = locToExp (beginRow, beginCol)
(endRow, endCol)
tokList
mod
{-
- Do the refactoring! Returns modifications as below:
- mod' - the modified Abstract Syntax Tree
- tokList' - the modified Token Stream
- m - ???
-}
if ty == Mat
then do
(mod', ((tokList', m), _)) <- runStateT (doZip pnt wh pats subExp mod)
((tokList, False), (0,0))
-- Write out the refactoring
writeRefactoredFiles False [((fileName, m), (tokList', mod'))]
AbstractIO.putStrLn "Completed.\n"
else do
(mod', ((tokList', m) , _)) <- runStateT (doSubstitution pnt subExp mod) ((tokList,False),( 0, 0))
writeRefactoredFiles False [((fileName, m), (tokList', mod'))]
AbstractIO.putStrLn "Completed.\n"
doSubstitution p e
= applyTP (full_tdTP (idTP `adhocTP` inMod
`adhocTP` inMatch
`adhocTP` inPat ))
where
inMod (mod@(HsModule loc name exps imps ds):: HsModuleP)
| p `elem` (map declToPNT ds)
= do
ds' <- doZipModule ds
return (HsModule loc name exps imps ds')
where
doZipModule t
= applyTP (full_tdTP (idTP `adhocTP` inMatch2
`adhocTP` inPat2)) t
where
inMatch2 (match@(HsMatch loc name pats rhs ds)::HsMatchP)
= do
(_, declared) <- hsFreeAndDeclaredNames pats
(_, declared') <- hsFreeAndDeclaredNames match
(_, declared'') <- hsFreeAndDeclaredNames ds
if (pNTtoName p) `elem` (declared++(declared'++declared''))
then return match
else do e' <- doSubstitution' p e declared rhs
return (HsMatch loc name pats e' ds)
inPat2 (pat@(Dec (HsPatBind loc pa rhs ds))::HsDeclP)
= do
(_, declared) <- hsFreeAndDeclaredNames pat
(_, declared') <- hsFreeAndDeclaredNames ds
if (pNTtoName p) `elem` (declared++declared')
then return pat
else do e' <- doSubstitution' p e declared rhs
return (Dec (HsPatBind loc pa e' ds))
inPat2 x = return x
inMod x = return x
inMatch (match@(HsMatch loc name pats rhs ds)::HsMatchP)
| p `elem` (map declToPNT ds)
= do
(_, declared) <- hsFreeAndDeclaredNames pats
(_, declared') <- hsFreeAndDeclaredNames match
if (pNTtoName p) `elem` (declared++declared')
then return match
else do
e' <- doSubstitution' p e declared rhs
return (HsMatch loc name pats e' ds)
inMatch x = return x
inPat (pat@(Dec (HsPatBind loc pa rhs ds))::HsDeclP)
| p `elem` (map declToPNT ds)
= do
(_, declared) <- hsFreeAndDeclaredNames pat
if (pNTtoName p) `elem` declared
then return pat
else do e' <- doSubstitution' p e declared rhs
return (Dec (HsPatBind loc pa e' ds))
inPat x = return x
doSubstitution' p e declared t
= applyTP (stop_tdTP (failTP `adhocTP` subExp)) t
where
subExp exp@((Exp _)::HsExpP)
| sameOccurrence exp e == False
= if toRelativeLocs e == toRelativeLocs exp then update exp (createFunc p) exp
else mzero
| otherwise
= mzero
createFunc pat = (Exp (HsId (HsVar pat)))
{-|
Takes the position of the highlighted code and returns
the function name, the list of arguments, the expression that has been
highlighted by the user, and any where\/let clauses associated with the
function.
-}
findDefNameAndExp :: Term t => [PosToken] -- ^ The token stream for the
-- file to be
-- refactored.
-> (Int, Int) -- ^ The beginning position of the highlighting.
-> (Int, Int) -- ^ The end position of the highlighting.
-> t -- ^ The abstract syntax tree.
-> (PatFun, PNT, FunctionPats, HsExpP, WhereDecls) -- ^ A tuple of,
-- (the function name, the list of arguments,
-- the expression highlighted, any where\/let clauses
-- associated with the function).
findDefNameAndExp toks beginPos endPos t
= fromMaybe (Er, defaultPNT, [], defaultExp, [])
(applyTU (once_tdTU (failTU `adhocTU` inMatch `adhocTU` inPat)) t)
where
--The selected sub-expression is in the rhs of a match
inMatch (match@(HsMatch loc1 pnt pats rhs@(HsBody e) ds)::HsMatchP)
| locToExp beginPos endPos toks rhs /= defaultExp
= Just (Mat, pnt, pats, locToExp beginPos endPos toks rhs, ds)
inMatch (match@(HsMatch loc1 pnt pats rhs@(HsGuard e) ds)::HsMatchP)
| locToExp beginPos endPos toks rhs /= defaultExp
= Just (Mat, pnt, pats, rmGuard rhs, ds)
inMatch _ = Nothing
--The selected sub-expression is in the rhs of a pattern-binding
inPat (pat@(Dec (HsPatBind loc1 ps rhs@(HsBody e) ds))::HsDeclP)
| locToExp beginPos endPos toks rhs /= defaultExp
= Just (Patt, patToPNT ps, [], locToExp beginPos endPos toks rhs, ds)
--The selected sub-expression is in the rhs of a pattern-binding
inPat (pat@(Dec (HsPatBind loc1 ps rhs@(HsGuard es) ds))::HsDeclP)
| locToExp beginPos endPos toks rhs /= defaultExp
= Just (Patt, patToPNT ps, [], rmGuard rhs, ds)
inPat _ = Nothing
rmGuard ((HsGuard gs)::RhsP)
= let (_,e1,e2)=glast "guardToIfThenElse" gs
in if ((pNtoName.expToPN) e1)=="otherwise"
then (foldl mkIfThenElse e2 (tail(reverse gs)))
else (foldl mkIfThenElse defaultElse (reverse gs))
mkIfThenElse e (_,e1, e2)=(Exp (HsIf e1 e2 e))
defaultElse=(Exp (HsApp (Exp (HsId (HsVar (PNT (PN (UnQual "error") (G (PlainModule "Prelude") "error"
(N (Just loc0)))) Value (N (Just loc0)))))) (Exp (HsLit loc0 (HsString "UnMatched Pattern")))))
doZip :: (MonadPlus m, Term t, MonadState (([PosToken],Bool),(Int, Int)) m) =>
PNT -> WhereDecls -> FunctionPats -> HsExpP -> t
-> m t
doZip p w patsGlob e t
= applyTP (full_tdTP (idTP `adhocTP` inMod
`adhocTP` inMatch
`adhocTP` inPat )) t
where
inMod (mod@(HsModule loc name exps imps ds):: HsModuleP)
| p `elem` (map declToPNT ds)
= do
ds' <- doZipModule ds
return (HsModule loc name exps imps ds')
where
doZipModule t
= applyTP (full_tdTP (idTP `adhocTP` inMatch2
`adhocTP` inPat2)) t
where
inMatch2 (match@(HsMatch loc name pats rhs ds)::HsMatchP)
= do
(_, declared) <- hsFreeAndDeclaredNames pats
(_, declared') <- hsFreeAndDeclaredNames match
(_, declared'') <- hsFreeAndDeclaredNames ds
if (pNTtoName p) `elem` (declared++(declared'++declared''))
then return match
else do e' <- doZip' p w patsGlob e rhs
return (HsMatch loc name pats e' ds)
inPat2 (pat@(Dec (HsPatBind loc pa rhs ds))::HsDeclP)
= do
(_, declared) <- hsFreeAndDeclaredNames pat
(_, declared') <- hsFreeAndDeclaredNames ds
if (pNTtoName p) `elem` (declared++declared')
then return pat
else do e' <- doZip' p w patsGlob e rhs
return (Dec (HsPatBind loc pa e' ds))
inPat2 x = return x
inMod x = return x
inMatch (match@(HsMatch loc name pats rhs ds)::HsMatchP)
| p `elem` (map declToPNT ds)
= do
(_, declared) <- hsFreeAndDeclaredNames pats
(_, declared') <- hsFreeAndDeclaredNames match
if (pNTtoName p) `elem` (declared++declared')
then return match
else do e' <- doZip' p w patsGlob e rhs
return (HsMatch loc name pats e' ds)
inMatch x = return x
inPat (pat@(Dec (HsPatBind loc pa rhs ds))::HsDeclP)
| p `elem` (map declToPNT ds)
= do
(_, declared) <- hsFreeAndDeclaredNames pat
if (pNTtoName p) `elem` declared
then return pat
else do e' <- doZip' p w patsGlob e rhs
return (Dec (HsPatBind loc pa e' ds))
inPat x = return x
{-|
doZip uses Strafunski to traverse each node of the AST and
then performs the folding on each node.
-}
doZip' :: (MonadPlus m, Term t, MonadState (([PosToken],Bool),(Int, Int)) m) =>
PNT -> WhereDecls -> FunctionPats -> HsExpP -> t
-> m t
doZip' p w pats e t
= applyTP (stop_tdTP (failTP `adhocTP` (zipExpCheck p w pats e))) t
where
zipExpCheck p w pats (exp1::HsExpP) (exp2::HsExpP)
| sameOccurrence exp1 exp2 == False
= do
result <- (callZipHighlightedMatch pats w exp1 exp2)
let environment = getEnvironment result
if result == [Nothing] || environment == Nothing
then do fail ""
else do let Just env = environment
let result' = map (rewritePatsInEnv env) pats
update exp2 (createFunc p result') exp2
| otherwise
= return exp1
{-|
checkVal calls checkAddBind in succession to check that all the bindings
can be added to the environment or not.
-}
checkVal :: NonSetEnv -> Bool
checkVal xs
= checkValAux xs []
where
checkValAux :: NonSetEnv -> Environment -> Bool
checkValAux [] _ = True
checkValAux ((Just (x,y)) : xs) env
= canAddBind (x,y) env &&
checkValAux xs ((x,y):env)
checkValAux (Nothing:xs) env = checkValAux xs env
{-|
canAddBind takes a binding and some environments, and checks to see
whether the binding can be added to the environment or not.
The binding will not be added to the environment if that binding
already exists within the environment. canAddBind returns True
if the binding can be added, and False if it cannot.
-}
canAddBind :: Binding -> Environment -> Bool
canAddBind _ [] = True
canAddBind (x,y) ((x',y'):xs)
= (x1 == x1' && y1 == y1') ||
(x1 /= x1' && canAddBind (x,y) xs)
where
[x1,x1',y1,y1'] = map toRelativeLocs [x,x',y,y']
{-|
getEnvironment takes a list of bindings and removes
the duplicates within the bindings
-}
getEnvironment :: NonSetEnv -> Maybe Environment
getEnvironment [] = Just []
getEnvironment (Nothing: xs) = getEnvironment xs
getEnvironment (Just (x,y):xs)
= case subEnv of
Nothing -> Nothing
Just env -> if canAddBind (x,y) env
then Just ((x,y):env)
else Nothing
where
subEnv = getEnvironment xs
{-|
rewritePatsInEnv takes the Environment and a pattern belonging to the
argument list of the function the user is folding against.
rewritePatsInEnv then forms an expression based on this pattern
taking into consideration the environment. This is used when forming
the function call
e.g.
@
Environment = [("x", [1,2,3]), ("y", 1)]
pat = (x,y)
@
would return...
@
HsTuple ([1,2,3], 1)
@
-}
rewritePatsInEnv :: Environment -> HsPatP -> HsExpP
rewritePatsInEnv [] p = error "Empty Environment!"
rewritePatsInEnv env (pat1@(Pat (HsPRec x y)))
= Exp (HsRecConstr loc0 x (map (sortField env) y))
where
sortField :: Environment -> HsFieldI a HsPatP -> HsFieldI a HsExpP
sortField env (HsField i e) = (HsField i (rewritePatsInEnv env e))
rewritePatsInEnv env (pat1@(Pat (HsPLit x y)))
= Exp (HsLit x y)
rewritePatsInEnv env (pat1@(Pat (HsPAsPat i p1)))
= Exp (HsAsPat i (rewritePatsInEnv env p1))
rewritePatsInEnv env (pat1@(Pat (HsPIrrPat p1)))
= Exp (HsIrrPat (rewritePatsInEnv env p1))
rewritePatsInEnv env (pat1@(Pat (HsPWildCard)))
= nameToExp "undefined"
rewritePatsInEnv env (pat1@(Pat (HsPApp i p1)))
= createFunc i (map (rewritePatsInEnv env) p1)
rewritePatsInEnv env (pat1@(Pat (HsPList _ p1)))
= Exp (HsList (map (rewritePatsInEnv env) p1))
rewritePatsInEnv env (pat1@(Pat (HsPTuple _ p1)))
= Exp (HsTuple (map (rewritePatsInEnv env) p1))
rewritePatsInEnv env (pat1@(Pat (HsPInfixApp p1 x p2)))
= Exp (HsInfixApp (rewritePatsInEnv env p1)
(HsCon x)
(rewritePatsInEnv env p2))
rewritePatsInEnv env (pat@(Pat (HsPParen p1)))
= Exp (HsParen (rewritePatsInEnv env p1))
rewritePatsInEnv env (pat1@(Pat (HsPId (HsVar (PNT (PN (UnQual i) _) _ _)))))
= if findRewrites i == []
then nameToExp "undefined"
else snd (head (findRewrites i))
where
findRewrites i = filter (checkPat i) env
checkPat i (Exp (HsId (HsVar (PNT (PN (UnQual i2) _) _ _))), (Exp z))
= i == i2
checkPat i _ = False
{-|
callZipHighlightedMatch simply calls the function zipHighlightedMatch
and then returns the value wrapped in a monad
-}
callZipHighlightedMatch :: Monad m => FunctionPats -> WhereDecls
-> HsExpP -> HsExpP -> m NonSetEnv
callZipHighlightedMatch pats w (exp1::HsExpP) (exp2::HsExpP)
= do zippedE1 <- zipHighlightedMatch False pats w exp1 exp2
return zippedE1
{- |
zipHighlightedMatch takes a list of patterns (the list of arguments for the
function highlighted, the where clause associated with the function,
the expression that has been highlighted and the expression that we are trying
to fold against.
zipHighlightedMatch then checks to see if the the expressions can be paired.
The expressions will only be paired if:
both expressions have the ssame type
e.g.
refactoron -> [1,2,3,4]
refactorod -> [1,2,3,4] becomes ([1,2,3,4], [1,2,3,4])
or, the highlighted expression is an idenitfier, in which case a pair is
always created, unless the idenitifier does not appear in the argument list
(pats)
-}
zipHighlightedMatch :: Monad m => Bool -> FunctionPats -> WhereDecls
-> HsExpP -> HsExpP -> m NonSetEnv
zipHighlightedMatch b pats w (exp1@(Exp (HsId (HsCon i1)))::HsExpP)
(exp2@(Exp (HsId (HsCon i2)))::HsExpP)
| i1 == i2 = return [ Just (exp1, exp2) ]
| otherwise = return [ Nothing ]
zipHighlightedMatch b pats w (exp1@(Exp (HsId (HsCon i1)))::HsExpP)
(exp2::HsExpP)
= return [ Nothing ]
zipHighlightedMatch True pats w (exp1@(Exp (HsId i1))::HsExpP)
(exp2@(Exp (HsId i2))::HsExpP)
| not (checkDefs i1 i2) = fail "untouched"
| checkInPat pats exp2 = return [ Just (exp1, exp2) ]
-- | checkInPat pats exp1 = return [ Just (exp1, exp2) ]
| checkGlobal i1 i2 = return [ Just (exp1, exp2) ]
| not (checkInWhere w exp1) = return [Nothing]
| otherwise = fail "untouched"
where
checkGlobal (HsVar i1) (HsVar i2) = (pNTtoPN i1) == (pNTtoPN i2)
checkGlobal _ _ = False
zipHighlightedMatch False pats w (exp1@(Exp (HsId i1))::HsExpP)
(exp2@(Exp (HsId i2))::HsExpP)
| checkInPat pats exp1 = return [ Just (exp1, exp2) ]
| checkGlobal i1 i2 = return [ Just (exp1, exp2) ]
| not (checkInWhere w exp1) = return [Nothing]
| otherwise = fail "untouched"
where
checkGlobal (HsVar i1) (HsVar i2) = (pNTtoPN i1) == (pNTtoPN i2)
checkGlobal _ _ = False
zipHighlightedMatch b pats w (exp1@(Exp (HsId i))::HsExpP) (exp2::HsExpP)
| checkInPat pats exp1 == True &&
checkInWhere w exp1 /= True
= return [ Just (exp1, exp2) ]
| otherwise
= fail "untouched"
zipHighlightedMatch b pats w (exp1@(Exp (HsLit _ i1))::HsExpP)
(exp2@(Exp (HsLit _ i2))::HsExpP)
| i1 == i2 = return [ Just (exp1, exp2) ]
| otherwise = return [ Nothing ]
zipHighlightedMatch b pats w (exp1@(Exp (HsLit _ _))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsInfixApp e1 i e2))::HsExpP)
(exp2@(Exp (HsInfixApp e11 i2 e22))::HsExpP)
| i == i2 = do zippedE1 <- zipHighlightedMatch b pats w e1 e11
zippedE2 <- zipHighlightedMatch b pats w e2 e22
if zippedE1 == [ Nothing ] || zippedE2 == [ Nothing ]
then return [ Nothing ]
else return (zippedE1 ++ zippedE2)
| otherwise = return [ Nothing ]
zipHighlightedMatch b pats w (exp1@(Exp (HsInfixApp e1 i e2))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsApp e1 e2))::HsExpP)
(exp2@(Exp (HsApp e11 e22))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
zippedE2 <- zipHighlightedMatch b pats w e2 e22
if zippedE1 == [Nothing] || zippedE2 == [ Nothing ]
then return [Nothing]
else return (zippedE1 ++ zippedE2)
zipHighlightedMatch b pats w (exp1@(Exp (HsApp e1 e2))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsNegApp _ e1))::HsExpP)
(exp2@(Exp (HsNegApp _ e2))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e2
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsNegApp _ e1))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsLambda ps e1))::HsExpP)
(exp2@(Exp (HsLambda ps2 e11))::HsExpP)
| wildCardAllPNs ps == wildCardAllPNs ps2
= do zippedE1 <- zipHighlightedMatch b pats w e1 (localRewriteExp e11 (localRewritePats ps ps2))
return zippedE1
where
localRewritePats [] ps = []
localRewritePats ps [] = []
localRewritePats (p1:p1s) (p2:p2s)
= (rewritePat p2 p1) : (localRewritePats p1s p2s)
localRewriteExp e [] = e
localRewriteExp e (p1:p1s)
= let e1' = rewritePatsInExp p1 e in localRewriteExp e1' p1s
zipHighlightedMatch b pats w (exp1@(Exp (HsLet _ e1))::HsExpP)
(exp2@(Exp (HsLet _ e11))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
zipHighlightedMatch b pats w (exp@(Exp (HsLet _ e1))::HsExpP) (exp2::HsExpP)
= fail ""
zipHighlightedMatch b pats w (exp1@(Exp (HsLambda _ e1))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsIf e1 e2 e3))::HsExpP)
(exp2@(Exp (HsIf e11 e22 e33))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
zippedE2 <- zipHighlightedMatch b pats w e2 e22
zippedE3 <- zipHighlightedMatch b pats w e3 e33
return (zippedE1 ++ zippedE2 ++ zippedE3)
zipHighlightedMatch b pats w (exp1@(Exp (HsIf e1 e2 e3))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats
w
(exp1@(Exp (HsCase e1 (alt@(HsAlt _ p1 e2 ds1):alts1)))::HsExpP)
(exp2@(Exp
(HsCase e11
(alt2@(HsAlt _ p11 e22 ds11):alts2)
))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
res <- zippedAlts (alt:alts1) (alt2:alts2)
if res == [Nothing]
then return [Nothing]
else return (zippedE1 ++ res)
where
zippedAlts [] alts = return []
zippedAlts alts [] = return []
zippedAlts ((HsAlt _ p1 (HsBody exp1) ds1):alts1) ((HsAlt _ p11 (HsBody exp2) ds11):alts2)
| wildCardAllPNs p1 == wildCardAllPNs p11
= do
zippedE1 <- zipHighlightedMatch b pats w exp1 (rewritePatsInExp (rewritePat p11 p1) exp2)
if zippedE1 == [Nothing]
then return [Nothing]
else do res <- zippedAlts alts1 alts2
if res == [Nothing] then return [Nothing]
else return (zippedE1 ++ res)
| otherwise = return [Nothing]
zippedAlts ((HsAlt _ p1 (HsGuard g1) ds1):alts1) ((HsAlt _ p22 (HsGuard g2) ds11):alts2)
| wildCardAllPNs p1 == wildCardAllPNs p22
= do
zippedE1 <- zippedGuards g1 (rewritePatsInGuard (rewritePat p22 p1) g2)
-- error $ show zippedE1
if zippedE1 == [Nothing]
then return [Nothing]
else do
res <- zippedAlts alts1 alts2
if res == [Nothing] then return [Nothing]
else return (zippedE1 ++ res)
where
zippedGuards _ [] = return []
zippedGuards [] _ = return []
zippedGuards ((_, e1, e2):gs1) ((_, e3, e4):gs2)
= do
e1' <- zipHighlightedMatch True pats w e1 e3
e2' <- zipHighlightedMatch True pats w e2 e4
res <- zippedGuards gs1 gs2
return ((e1' ++ e2') ++ res)
zippedAlts _ _ = return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp
(HsCase e1
((HsAlt _ e2 p1 ds1):alts1)
))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsDo (stat1)))::HsExpP)
(exp2@(Exp (HsDo (stat2)))::HsExpP)
= do zippedE1 <- zipHighlightedStmt pats w stat1 stat2
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsDo (stat1)))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsTuple ([e1])))::HsExpP)
(exp2@(Exp (HsTuple ([e11])))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsTuple (e1:e1s)))::HsExpP)
(exp2@(Exp (HsTuple (e11:e11s)))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
result <- zippedE2 e1s e11s
if result == [Nothing] || zippedE1 == [Nothing]
then return [Nothing]
else return (zippedE1 ++ result)
where
zippedE2 [] [] = return []
zippedE2 _ [] = return [Nothing]
zippedE2 [] _ = return [Nothing]
zippedE2 (x:xs) (y:ys)
= do result1 <- zipHighlightedMatch b pats w x y
result2 <- zippedE2 xs ys
if result1 == [Nothing] || result2 == [Nothing]
then return [Nothing]
else return (result1 ++ result2)
zipHighlightedMatch b pats w (exp1@(Exp (HsTuple (e1:e1s)))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsList ([e1])))::HsExpP)
(exp2@(Exp (HsList ([e11])))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsList (e1:e1s)))::HsExpP)
(exp2@(Exp (HsList (e11:e11s)))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
result <- zippedE2 e1s e11s
-- error (show zippedE1 ++ " " ++ show result)
if result == [Nothing] || zippedE1 == [Nothing]
then return [Nothing]
else return (zippedE1 ++ result)
where
zippedE2 [] [] = return []
zippedE2 _ [] = return [Nothing]
zippedE2 [] _ = return [Nothing]
zippedE2 (x:xs) (y:ys) = do
result1 <- zipHighlightedMatch b pats w x y
result2 <- zippedE2 xs ys
if result1 == [Nothing] || result2 == [Nothing]
then return [Nothing]
else return (result1 ++ result2)
zipHighlightedMatch b pats w (exp1@(Exp (HsList (e1:e1s)))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsParen e1))::HsExpP)
(exp2@(Exp (HsParen e11))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsParen e1))::HsExpP) (exp2::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 exp2
return zippedE1
zipHighlightedMatch b pats w (exp1::HsExpP) (exp2@(Exp (HsParen e2))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w exp1 e2
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsLeftSection e1 i1))::HsExpP)
(exp2@(Exp (HsLeftSection e11 i2))::HsExpP)
| i1 == i2 = do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
| otherwise = return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsLeftSection e1 i1))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsRightSection i1 e1))::HsExpP)
(exp2@(Exp (HsRightSection i2 e11))::HsExpP)
| i1 == i2 = do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
| otherwise = return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsRightSection i1 e1))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsRecConstr _ i1 i2 ))::HsExpP)
(exp2@(Exp (HsRecConstr _ i11 i22 ))::HsExpP)
| i1 == i11 = do zippedE1 <- zipHighlightedField pats w i2 i22
return zippedE1
| otherwise = do return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsRecConstr _ i1 i2))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsRecUpdate _ e1 i1))::HsExpP)
(exp2@(Exp (HsRecUpdate _ e11 i11))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
zippedE2 <- zipHighlightedField pats w i1 i11
return (zippedE1 ++ zippedE2)
zipHighlightedMatch b pats w (exp1@(Exp (HsRecUpdate _ e1 i1))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsEnumFrom e1))::HsExpP)
(exp2@(Exp (HsEnumFrom e11))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsEnumFrom e1))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsEnumFromTo e1 e2))::HsExpP)
(exp2@(Exp (HsEnumFromTo e11 e22))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
zippedE2 <- zipHighlightedMatch b pats w e2 e22
return (zippedE1 ++ zippedE2)
zipHighlightedMatch b pats w (exp1@(Exp (HsEnumFromTo e1 e2))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsEnumFromThen e1 e2))::HsExpP)
(exp2@(Exp (HsEnumFromThen e11 e22))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
zippedE2 <- zipHighlightedMatch b pats w e2 e22
return (zippedE1 ++ zippedE2)
zipHighlightedMatch b pats w (exp1@(Exp (HsEnumFromThen e1 e2))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsEnumFromThenTo e1 e2 e3))::HsExpP)
(exp2@(Exp (HsEnumFromThenTo e11 e22 e33))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
zippedE2 <- zipHighlightedMatch b pats w e2 e22
zippedE3 <- zipHighlightedMatch b pats w e3 e33
return (zippedE1 ++ zippedE2 ++ zippedE3)
zipHighlightedMatch b pats w (exp1@(Exp (HsEnumFromThenTo e1 e2 e3))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsListComp (stat1)))::HsExpP)
(exp2@(Exp (HsListComp (stat2)))::HsExpP)
= do zippedE1 <- zipHighlightedStmt pats w stat1 stat2
return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsListComp (stat1)))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsExpTypeSig _ e1 c1 t1))::HsExpP)
(exp2@(Exp (HsExpTypeSig _ e2 c2 t2))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e2
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsExpTypeSig _ e1 c1 t1))::HsExpP)
(exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsAsPat i1 e1))::HsExpP)
(exp2@(Exp (HsAsPat i11 e11))::HsExpP)
| i1 == i11 = do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
| otherwise = return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsAsPat i1 e1))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1@(Exp (HsIrrPat e1))::HsExpP)
(exp2@(Exp (HsIrrPat e11))::HsExpP)
= do zippedE1 <- zipHighlightedMatch b pats w e1 e11
return zippedE1
zipHighlightedMatch b pats w (exp1@(Exp (HsIrrPat e1))::HsExpP) (exp2::HsExpP)
= return [Nothing]
zipHighlightedMatch b pats w (exp1::HsExpP) (exp2::HsExpP)
= return [Nothing]
{-|
zipHighlightedField takes the highlighted expression
, and takes the expression that we are folding against.
If they are both fields, it then calls zipHiglightedMatch to
pair up the expressions within the fields.
-}
zipHighlightedField :: Monad m => FunctionPats -> WhereDecls
-> HsFieldsI PNT (HsExpI PNT) -> HsFieldsI PNT (HsExpI PNT)
-> m NonSetEnv
zipHighlightedField pats w [] _
= return [Nothing]
zipHighlightedField pats w _ []
= return [Nothing]
zipHighlightedField pats w ((fiel1@(HsField i1 e1)):xs)
((fiel2@(HsField i11 e11)):ys)
= if i1 == i11
then do zippedE1 <- zipHighlightedMatch False pats w e1 e11
return zippedE1
else do
return [Nothing]
checkDefs (HsVar p1@(PNT (PN (UnQual i) (_) ) _ _ )) (HsVar p2@(PNT (PN (UnQual i2) (_) ) _ _ ))
= i == i2
checkDefs _ _ = False
{-|
checkInPat checks that the Expression (supplied as 2nd argument)
occurs within the Function Arugment List.
checkInPat needs to check for every case that expression could be
e.g. literals, lists, tuples and records.
if the expression occurs then the function returns True
otherwise returns False.
-}
checkInPat :: FunctionPats -> HsExpP -> Bool
checkInPat (pat1@(Pat (HsPRec x y)):pats) exp
| (checkField y) == False = (checkInPat pats exp)
| otherwise = True
where
checkField ((HsField i e):xs)
| (checkInPat [e] exp) == False = (checkField xs)
| otherwise = True
checkInPat (pat1@(Pat (HsPIrrPat p)):pats) exp
| (checkInPat [p] exp) == False = checkInPat pats exp
| otherwise = True
checkInPat (pat1@(Pat (HsPAsPat i p)):pats) exp
| (checkInPat [p] exp) == False = checkInPat pats exp
| otherwise = True
checkInPat (pat1@(Pat (HsPWildCard)):pats) exp
= checkInPat pats exp
checkInPat (pat1@(Pat (HsPId (HsVar (PNT p@(PN (UnQual i) (_) ) _ _ )))):pats)
(exp1@(Exp (HsId (HsVar (PNT p2@(PN (UnQual i2) (_) ) _ _ ))))::HsExpP)
= if p == p2 then True else checkInPat pats exp1
{- = if i == i2
then True
else checkInPat pats exp1 -}
checkInPat (pat1@(Pat (HsPParen pat)):pats) exp
| (checkInPat [pat] exp) == False = checkInPat pats exp
| otherwise = True
checkInPat (pat@(Pat (HsPInfixApp pat1 x pat2)):pats) exp
| (checkInPat [pat1] exp) == False &&
(checkInPat [pat2] exp) == False
= checkInPat pats exp
| otherwise = True
checkInPat (pat@(Pat (HsPTuple _ pat1)):pats) exp
| (checkInPat pat1 exp) == False = checkInPat pats exp
| otherwise = True
checkInPat (pat@(Pat (HsPList _ pat1)):pats) exp
| (checkInPat pat1 exp) == False = checkInPat pats exp
| otherwise = True
checkInPat (pat@(Pat (HsPApp i pat1)):pats) exp
| (checkInPat pat1 exp) == False = checkInPat pats exp
| otherwise = True
checkInPat ((Pat (HsPLit _ (HsInt x))):pats) exp1
= checkInPat pats exp1
checkInPat _ _ = False
{-|
checkInWhere checks that where clause of the function does not contain
the expressions (as second argument). If it does the function returns
True, otherwise returns False.
-}
checkInWhere :: [HsDeclP] -> HsExpP -> Bool
checkInWhere [] _ = False
checkInWhere (wh@(Dec
(HsPatBind _
(Pat
(HsPId
(HsVar
(PNT
(PN
(UnQual i)
_
)
_
_
)
)
)
)
_
rest)):ws)
(exp1@(Exp (HsId (HsVar (PNT (PN (UnQual i2) _ ) _ _ ))))::HsExpP)
= i == i2
-- extractHsBody simply extracts the expression within an HsBody
-- and returns that Expression.
extractHsBody (HsBody exp) = return exp
extractHsBody _ = error "Case must contain HsBody"
{-|
zipHighLightedStmt checks that two statements are identical,
if they are, zipHighLightedStmt returns the two statements paired together
-}
zipHighlightedStmt :: Monad m => FunctionPats -> WhereDecls
-> HsStmtP -> HsStmtP -> m NonSetEnv
zipHighlightedStmt pats w (exp1@(HsGenerator _ p1 e1 e1')::HsStmtP)
(exp2@(HsGenerator _ p2 e2 e2')::HsStmtP)
| wildCardAllPNs p1 == wildCardAllPNs p2
= do zippedE1 <- zipHighlightedMatch False pats w e1 e2
zippedE2 <- zipHighlightedStmt pats w e1' e2'
return (zippedE1 ++ zippedE2)
zipHighlightedStmt pats w (exp1@(HsQualifier e1 e1')::HsStmtP)
(exp2@(HsQualifier e2 e2')::HsStmtP)
= do zippedE1 <- zipHighlightedMatch False pats w e1 e2
zippedE2 <- zipHighlightedStmt pats w e1' e2'
return [Nothing]
zipHighlightedStmt pats w (exp1@(HsLetStmt ds1 e1)::HsStmtP)
(exp2@(HsLetStmt ds2 e2)::HsStmtP)
= do zippedE1 <- zipHighlightedStmt pats w e1 e2
return zippedE1
zipHighlightedStmt pats w (exp1@(HsLast e1)::HsStmtP)
(exp2@(HsLast e2)::HsStmtP)
= do zippedE1 <- zipHighlightedMatch False pats w e1 e2
return zippedE1
zipHighlightedStmt pats w (exp1::HsStmtP) (exp2::HsStmtP)
= return [Nothing]
|
kmate/HaRe
|
old/refactorer/RefacFunDef.hs
|
bsd-3-clause
| 39,473 | 0 | 26 | 13,060 | 12,761 | 6,555 | 6,206 | -1 | -1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, MagicHash, UnboxedTuples, AutoDeriveTypeable #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_HADDOCK not-home #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Conc.Windows
-- Copyright : (c) The University of Glasgow, 1994-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC extensions)
--
-- Windows I/O manager
--
-----------------------------------------------------------------------------
-- #not-home
module GHC.Conc.Windows
( ensureIOManagerIsRunning
-- * Waiting
, threadDelay
, registerDelay
-- * Miscellaneous
, asyncRead
, asyncWrite
, asyncDoProc
, asyncReadBA
, asyncWriteBA
, ConsoleEvent(..)
, win32ConsoleHandler
, toWin32ConsoleEvent
) where
import Control.Monad
import Data.Bits (shiftR)
import Data.Maybe (Maybe(..))
import Data.Typeable
import GHC.Base
import GHC.Conc.Sync
import GHC.Enum (Enum)
import GHC.IO (unsafePerformIO)
import GHC.IORef
import GHC.MVar
import GHC.Num (Num(..))
import GHC.Ptr
import GHC.Read (Read)
import GHC.Real (div, fromIntegral)
import GHC.Show (Show)
import GHC.Word (Word32, Word64)
import GHC.Windows
#ifdef mingw32_HOST_OS
# if defined(i386_HOST_ARCH)
# define WINDOWS_CCONV stdcall
# elif defined(x86_64_HOST_ARCH)
# define WINDOWS_CCONV ccall
# else
# error Unknown mingw32 arch
# endif
#endif
-- ----------------------------------------------------------------------------
-- Thread waiting
-- Note: threadWaitRead and threadWaitWrite aren't really functional
-- on Win32, but left in there because lib code (still) uses them (the manner
-- in which they're used doesn't cause problems on a Win32 platform though.)
asyncRead :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
asyncRead (I# fd) (I# isSock) (I# len) (Ptr buf) =
IO $ \s -> case asyncRead# fd isSock len buf s of
(# s', len#, err# #) -> (# s', (I# len#, I# err#) #)
asyncWrite :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
asyncWrite (I# fd) (I# isSock) (I# len) (Ptr buf) =
IO $ \s -> case asyncWrite# fd isSock len buf s of
(# s', len#, err# #) -> (# s', (I# len#, I# err#) #)
asyncDoProc :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
asyncDoProc (FunPtr proc) (Ptr param) =
-- the 'length' value is ignored; simplifies implementation of
-- the async*# primops to have them all return the same result.
IO $ \s -> case asyncDoProc# proc param s of
(# s', _len#, err# #) -> (# s', I# err# #)
-- to aid the use of these primops by the IO Handle implementation,
-- provide the following convenience funs:
-- this better be a pinned byte array!
asyncReadBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
asyncReadBA fd isSock len off bufB =
asyncRead fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
asyncWriteBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
asyncWriteBA fd isSock len off bufB =
asyncWrite fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
-- ----------------------------------------------------------------------------
-- Threaded RTS implementation of threadDelay
-- | Suspends the current thread for a given number of microseconds
-- (GHC only).
--
-- There is no guarantee that the thread will be rescheduled promptly
-- when the delay has expired, but the thread will never continue to
-- run /earlier/ than specified.
--
threadDelay :: Int -> IO ()
threadDelay time
| threaded = waitForDelayEvent time
| otherwise = IO $ \s ->
case time of { I# time# ->
case delay# time# s of { s' -> (# s', () #)
}}
-- | Set the value of returned TVar to True after a given number of
-- microseconds. The caveats associated with threadDelay also apply.
--
registerDelay :: Int -> IO (TVar Bool)
registerDelay usecs
| threaded = waitForDelayEventSTM usecs
| otherwise = error "registerDelay: requires -threaded"
foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
waitForDelayEvent :: Int -> IO ()
waitForDelayEvent usecs = do
m <- newEmptyMVar
target <- calculateTarget usecs
atomicModifyIORef pendingDelays (\xs -> (Delay target m : xs, ()))
prodServiceThread
takeMVar m
-- Delays for use in STM
waitForDelayEventSTM :: Int -> IO (TVar Bool)
waitForDelayEventSTM usecs = do
t <- atomically $ newTVar False
target <- calculateTarget usecs
atomicModifyIORef pendingDelays (\xs -> (DelaySTM target t : xs, ()))
prodServiceThread
return t
calculateTarget :: Int -> IO USecs
calculateTarget usecs = do
now <- getMonotonicUSec
return $ now + (fromIntegral usecs)
data DelayReq
= Delay {-# UNPACK #-} !USecs {-# UNPACK #-} !(MVar ())
| DelaySTM {-# UNPACK #-} !USecs {-# UNPACK #-} !(TVar Bool)
{-# NOINLINE pendingDelays #-}
pendingDelays :: IORef [DelayReq]
pendingDelays = unsafePerformIO $ do
m <- newIORef []
sharedCAF m getOrSetGHCConcWindowsPendingDelaysStore
foreign import ccall unsafe "getOrSetGHCConcWindowsPendingDelaysStore"
getOrSetGHCConcWindowsPendingDelaysStore :: Ptr a -> IO (Ptr a)
{-# NOINLINE ioManagerThread #-}
ioManagerThread :: MVar (Maybe ThreadId)
ioManagerThread = unsafePerformIO $ do
m <- newMVar Nothing
sharedCAF m getOrSetGHCConcWindowsIOManagerThreadStore
foreign import ccall unsafe "getOrSetGHCConcWindowsIOManagerThreadStore"
getOrSetGHCConcWindowsIOManagerThreadStore :: Ptr a -> IO (Ptr a)
ensureIOManagerIsRunning :: IO ()
ensureIOManagerIsRunning
| threaded = startIOManagerThread
| otherwise = return ()
startIOManagerThread :: IO ()
startIOManagerThread = do
modifyMVar_ ioManagerThread $ \old -> do
let create = do t <- forkIO ioManager; return (Just t)
case old of
Nothing -> create
Just t -> do
s <- threadStatus t
case s of
ThreadFinished -> create
ThreadDied -> create
_other -> return (Just t)
insertDelay :: DelayReq -> [DelayReq] -> [DelayReq]
insertDelay d [] = [d]
insertDelay d1 ds@(d2 : rest)
| delayTime d1 <= delayTime d2 = d1 : ds
| otherwise = d2 : insertDelay d1 rest
delayTime :: DelayReq -> USecs
delayTime (Delay t _) = t
delayTime (DelaySTM t _) = t
type USecs = Word64
type NSecs = Word64
foreign import ccall unsafe "getMonotonicNSec"
getMonotonicNSec :: IO NSecs
getMonotonicUSec :: IO USecs
getMonotonicUSec = fmap (`div` 1000) getMonotonicNSec
{-# NOINLINE prodding #-}
prodding :: IORef Bool
prodding = unsafePerformIO $ do
r <- newIORef False
sharedCAF r getOrSetGHCConcWindowsProddingStore
foreign import ccall unsafe "getOrSetGHCConcWindowsProddingStore"
getOrSetGHCConcWindowsProddingStore :: Ptr a -> IO (Ptr a)
prodServiceThread :: IO ()
prodServiceThread = do
-- NB. use atomicModifyIORef here, otherwise there are race
-- conditions in which prodding is left at True but the server is
-- blocked in select().
was_set <- atomicModifyIORef prodding $ \b -> (True,b)
unless was_set wakeupIOManager
-- ----------------------------------------------------------------------------
-- Windows IO manager thread
ioManager :: IO ()
ioManager = do
wakeup <- c_getIOManagerEvent
service_loop wakeup []
service_loop :: HANDLE -- read end of pipe
-> [DelayReq] -- current delay requests
-> IO ()
service_loop wakeup old_delays = do
-- pick up new delay requests
new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))
let delays = foldr insertDelay old_delays new_delays
now <- getMonotonicUSec
(delays', timeout) <- getDelay now delays
r <- c_WaitForSingleObject wakeup timeout
case r of
0xffffffff -> do throwGetLastError "service_loop"
0 -> do
r2 <- c_readIOManagerEvent
exit <-
case r2 of
_ | r2 == io_MANAGER_WAKEUP -> return False
_ | r2 == io_MANAGER_DIE -> return True
0 -> return False -- spurious wakeup
_ -> do start_console_handler (r2 `shiftR` 1); return False
unless exit $ service_cont wakeup delays'
_other -> service_cont wakeup delays' -- probably timeout
service_cont :: HANDLE -> [DelayReq] -> IO ()
service_cont wakeup delays = do
r <- atomicModifyIORef prodding (\_ -> (False,False))
r `seq` return () -- avoid space leak
service_loop wakeup delays
-- must agree with rts/win32/ThrIOManager.c
io_MANAGER_WAKEUP, io_MANAGER_DIE :: Word32
io_MANAGER_WAKEUP = 0xffffffff
io_MANAGER_DIE = 0xfffffffe
data ConsoleEvent
= ControlC
| Break
| Close
-- these are sent to Services only.
| Logoff
| Shutdown
deriving (Eq, Ord, Enum, Show, Read, Typeable)
start_console_handler :: Word32 -> IO ()
start_console_handler r =
case toWin32ConsoleEvent r of
Just x -> withMVar win32ConsoleHandler $ \handler -> do
_ <- forkIO (handler x)
return ()
Nothing -> return ()
toWin32ConsoleEvent :: (Eq a, Num a) => a -> Maybe ConsoleEvent
toWin32ConsoleEvent ev =
case ev of
0 {- CTRL_C_EVENT-} -> Just ControlC
1 {- CTRL_BREAK_EVENT-} -> Just Break
2 {- CTRL_CLOSE_EVENT-} -> Just Close
5 {- CTRL_LOGOFF_EVENT-} -> Just Logoff
6 {- CTRL_SHUTDOWN_EVENT-} -> Just Shutdown
_ -> Nothing
win32ConsoleHandler :: MVar (ConsoleEvent -> IO ())
win32ConsoleHandler = unsafePerformIO (newMVar (error "win32ConsoleHandler"))
wakeupIOManager :: IO ()
wakeupIOManager = c_sendIOManagerEvent io_MANAGER_WAKEUP
-- Walk the queue of pending delays, waking up any that have passed
-- and return the smallest delay to wait for. The queue of pending
-- delays is kept ordered.
getDelay :: USecs -> [DelayReq] -> IO ([DelayReq], DWORD)
getDelay _ [] = return ([], iNFINITE)
getDelay now all@(d : rest)
= case d of
Delay time m | now >= time -> do
putMVar m ()
getDelay now rest
DelaySTM time t | now >= time -> do
atomically $ writeTVar t True
getDelay now rest
_otherwise ->
-- delay is in millisecs for WaitForSingleObject
let micro_seconds = delayTime d - now
milli_seconds = (micro_seconds + 999) `div` 1000
in return (all, fromIntegral milli_seconds)
foreign import ccall unsafe "getIOManagerEvent" -- in the RTS (ThrIOManager.c)
c_getIOManagerEvent :: IO HANDLE
foreign import ccall unsafe "readIOManagerEvent" -- in the RTS (ThrIOManager.c)
c_readIOManagerEvent :: IO Word32
foreign import ccall unsafe "sendIOManagerEvent" -- in the RTS (ThrIOManager.c)
c_sendIOManagerEvent :: Word32 -> IO ()
foreign import WINDOWS_CCONV "WaitForSingleObject"
c_WaitForSingleObject :: HANDLE -> DWORD -> IO DWORD
|
frantisekfarka/ghc-dsi
|
libraries/base/GHC/Conc/Windows.hs
|
bsd-3-clause
| 11,013 | 4 | 22 | 2,374 | 2,758 | 1,429 | 1,329 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE ExistentialQuantification #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.StaticPtr
-- Copyright : (C) 2014 I/O Tweag
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- Symbolic references to values.
--
-- References to values are usually implemented with memory addresses, and this
-- is practical when communicating values between the different pieces of a
-- single process.
--
-- When values are communicated across different processes running in possibly
-- different machines, though, addresses are no longer useful since each
-- process may use different addresses to store a given value.
--
-- To solve such concern, the references provided by this module offer a key
-- that can be used to locate the values on each process. Each process maintains
-- a global table of references which can be looked up with a given key. This
-- table is known as the Static Pointer Table. The reference can then be
-- dereferenced to obtain the value.
--
-----------------------------------------------------------------------------
module GHC.StaticPtr
( StaticPtr
, deRefStaticPtr
, StaticKey
, staticKey
, unsafeLookupStaticPtr
, StaticPtrInfo(..)
, staticPtrInfo
, staticPtrKeys
) where
import Data.Typeable (Typeable)
import Foreign.C.Types (CInt(..))
import Foreign.Marshal (allocaArray, peekArray, withArray)
import Foreign.Ptr (castPtr)
import GHC.Exts (addrToAny#)
import GHC.Ptr (Ptr(..), nullPtr)
import GHC.Fingerprint (Fingerprint(..))
-- | A reference to a value of type 'a'.
data StaticPtr a = StaticPtr StaticKey StaticPtrInfo a
deriving Typeable
-- | Dereferences a static pointer.
deRefStaticPtr :: StaticPtr a -> a
deRefStaticPtr (StaticPtr _ _ v) = v
-- | A key for `StaticPtrs` that can be serialized and used with
-- 'unsafeLookupStaticPtr'.
type StaticKey = Fingerprint
-- | The 'StaticKey' that can be used to look up the given 'StaticPtr'.
staticKey :: StaticPtr a -> StaticKey
staticKey (StaticPtr k _ _) = k
-- | Looks up a 'StaticPtr' by its 'StaticKey'.
--
-- If the 'StaticPtr' is not found returns @Nothing@.
--
-- This function is unsafe because the program behavior is undefined if the type
-- of the returned 'StaticPtr' does not match the expected one.
--
unsafeLookupStaticPtr :: StaticKey -> IO (Maybe (StaticPtr a))
unsafeLookupStaticPtr (Fingerprint w1 w2) = do
ptr@(Ptr addr) <- withArray [w1,w2] (hs_spt_lookup . castPtr)
if (ptr == nullPtr)
then return Nothing
else case addrToAny# addr of
(# spe #) -> return (Just spe)
foreign import ccall unsafe hs_spt_lookup :: Ptr () -> IO (Ptr a)
-- | Miscelaneous information available for debugging purposes.
data StaticPtrInfo = StaticPtrInfo
{ -- | Package key of the package where the static pointer is defined
spInfoPackageKey :: String
-- | Name of the module where the static pointer is defined
, spInfoModuleName :: String
-- | An internal name that is distinct for every static pointer defined in
-- a given module.
, spInfoName :: String
-- | Source location of the definition of the static pointer as a
-- @(Line, Column)@ pair.
, spInfoSrcLoc :: (Int, Int)
}
deriving (Show, Typeable)
-- | 'StaticPtrInfo' of the given 'StaticPtr'.
staticPtrInfo :: StaticPtr a -> StaticPtrInfo
staticPtrInfo (StaticPtr _ n _) = n
-- | A list of all known keys.
staticPtrKeys :: IO [StaticKey]
staticPtrKeys = do
keyCount <- hs_spt_key_count
allocaArray (fromIntegral keyCount) $ \p -> do
count <- hs_spt_keys p keyCount
peekArray (fromIntegral count) p >>=
mapM (\pa -> peekArray 2 pa >>= \[w1, w2] -> return $ Fingerprint w1 w2)
{-# NOINLINE staticPtrKeys #-}
foreign import ccall unsafe hs_spt_key_count :: IO CInt
foreign import ccall unsafe hs_spt_keys :: Ptr a -> CInt -> IO CInt
|
beni55/haste-compiler
|
libraries/ghc-7.10/base/GHC/StaticPtr.hs
|
bsd-3-clause
| 4,186 | 0 | 18 | 864 | 648 | 377 | 271 | 53 | 2 |
module Where4 where
-- source functions
f1 :: [a] -> [a]
f1 l = ls
where
ls = take (rs - 1) l
rs = length l
f2 :: [a] -> Int
f2 l = rs - 1
where
rs = length l
|
mpickering/HaRe
|
old/testing/merging/Where4_TokOut.hs
|
bsd-3-clause
| 210 | 0 | 9 | 94 | 89 | 49 | 40 | 8 | 1 |
import Distribution.Simple
import Ros.Internal.SetupUtil
main = defaultMainWithHooks $
simpleUserHooks { confHook = rosConf }
|
bitemyapp/roshask
|
Examples/Turtle/Setup.hs
|
bsd-3-clause
| 134 | 0 | 7 | 22 | 29 | 17 | 12 | 4 | 1 |
-- | A collection of commonly-used combinators to build up larger
-- codecs.
module Data.Wheat.Combinators where
import Control.Applicative ((<$>))
import Control.Monad ((>=>))
import Data.Foldable (foldMap)
import Data.Functor.Contravariant.Divisible (divide)
import Data.Monoid (Monoid, (<>))
-- Local imports
import Data.Wheat.Types
-- | Sequential composition of codecs.
--
-- When encoding, the input value is encoded with both codecs and the
-- results are concatenated. When decoding, the remaining bytestring
-- from the first codec is used as input to the second.
(<:>) :: Monoid b => GCodec i b e d1 -> GCodec i b e d2 -> GCodec i b e (d1, d2)
c1 <:> c2 = Codec (encoderOf c1 <> encoderOf c2) decoder where
decoder = do
x <- decoderOf c1
y <- decoderOf c2
return (x, y)
-- | Sequential composition of codecs, combining the results of
-- decoding monoidally.
(<<:>>) :: (Monoid b, Monoid d) => GCodec i b e d -> GCodec i b e d -> GCodec i b e d
c1 <<:>> c2 = Codec (encoderOf cx) (uncurry (<>) <$> decoderOf cx) where
cx = c1 <:> c2
-- | Right-biased sequential composition of codecs.
--
-- Encoding behaviour is the same as '<:>', decoding throws away the
-- result of the first codec.
(<:>>) :: Monoid b => GCodec i b e d1 -> GCodec i b e d2 -> GCodec i b e d2
c1 <:>> c2 = Codec (encoderOf cx) (snd <$> decoderOf cx) where
cx = c1 <:> c2
-- | Left-biased sequential composition of codecs.
--
-- Encoding behaviour is the same as '<:>', decoding throws away the
-- result of the second codec.
(<<:>) :: Monoid b => GCodec i b e d1 -> GCodec i b e d2 -> GCodec i b e d1
c1 <<:> c2 = Codec (encoderOf cx) (fst <$> decoderOf cx) where
cx = c1 <:> c2
-- | Combine two codecs into a codec for tuples of those types, where
-- the encoded forms of each element are concatenated.
(<++>) :: Monoid b => GCodec i b e1 d1 -> GCodec i b e2 d2 -> GCodec i b (e1, e2) (d1, d2)
(<++>) = separate id id
-- | Lift a codec over a type to over a list of that type.
--
-- Encoded elements are concatenated. Decoding never fails, as an
-- empty list is acceptable.
elementwise :: Monoid b => GCodec i b e d -> GCodec i b [e] [d]
elementwise c = Codec encoder decoder where
encoder = toEncoder' go where
go = foldMap (runEncoder' $ encoderOf c)
decoder = toDecoder $ go [] where
go ds b = case runDecoder (decoderOf c) b of
Just (d, b') -> go (d:ds) b'
Nothing -> Just (reverse ds, b)
-- | Encode a value as a combination of header and encoded value. The
-- codec used for encoding/decoding the value itself receives the
-- (encoded/decoded) header as a parameter.
header :: Monoid b => (e -> h) -> GCodec i b h h -> (h -> GCodec i b e d) -> GCodec i b e d
header hf hc cf = Codec encoder decoder where
encoder = toEncoder' $ \e ->
let h = hf e
in runEncoder' (encoderOf hc) h <> runEncoder' (encoderOf $ cf h) e
decoder = decoderOf hc >>= decoderOf . cf
-- | Apply a divide-and-conquer approach: given a function to split up
-- the encoding into two smaller components, and a function to combine
-- the smaller components after decoding, construct a codec for the
-- more complex type.
separate :: Monoid b => (e -> (e1, e2)) -> ((d1, d2) -> d) -> GCodec i b e1 d1 -> GCodec i b e2 d2 -> GCodec i b e d
separate split merge c1 c2 = Codec encoder decoder where
encoder = divide split (encoderOf c1) (encoderOf c2)
decoder = do
x <- decoderOf c1
y <- decoderOf c2
return $ merge (x, y)
-- | Given functions to convert the types, wrap one codec inside another.
--
-- Encoding and decoding will fail if the function does, even if the
-- inner codec succeeds.
wrap :: (d' -> Maybe d) -> (e -> Maybe e') -> GCodec i b e' d' -> GCodec i b e d
wrap df ef c = Codec encoder decoder where
encoder = toEncoder $ ef >=> runEncoder (encoderOf c)
decoder = toDecoder $ \b -> case runDecoder (decoderOf c) b of
Just (d, b') -> (\d' -> (d',b')) <$> df d
Nothing -> Nothing
|
barrucadu/wheat
|
Data/Wheat/Combinators.hs
|
mit
| 3,946 | 0 | 15 | 859 | 1,255 | 654 | 601 | 51 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Haskbot.Internal.Request
( Params
, jsonContentType
, textContentType
, getPostParams
, headOnly
, getParamsMap
, optParam
, reqParam
) where
import Control.Monad.Error (liftIO, throwError)
import Data.ByteString.Lazy (fromStrict)
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8)
import Haskbot.Internal.Environment (HaskbotM)
import qualified Data.Map as M
import qualified Network.HTTP.Types as N
import qualified Network.Wai as W
type Params = M.Map Text Text
-- constants
jsonContentType :: N.Header
jsonContentType = (N.hContentType, "application/json")
textContentType :: N.Header
textContentType = (N.hContentType, "text/plain")
-- internal functions
headOnly :: N.Status -> W.Response
headOnly status = W.responseLBS status [] . fromStrict $ N.statusMessage status
getParamsMap :: W.Request -> IO Params
getParamsMap req = do
body <- W.requestBody req
return . M.fromList . map decode $ N.parseSimpleQuery body
where
decode (k,v) = (decodeUtf8 k, decodeUtf8 v)
getPostParams :: W.Request -> HaskbotM Params
getPostParams req
| isPost = liftIO $ getParamsMap req
| otherwise = throwError N.status403
where
isPost = W.requestMethod req == N.methodPost
optParam :: Params -> Text -> HaskbotM (Maybe Text)
optParam pMap key = return $ M.lookup key pMap
reqParam :: Params -> Text -> HaskbotM Text
reqParam pMap key =
case M.lookup key pMap of
Just p -> return p
_ -> throwError N.badRequest400
|
Jonplussed/haskbot-core
|
src/Haskbot/Internal/Request.hs
|
mit
| 1,512 | 0 | 10 | 256 | 471 | 254 | 217 | 42 | 2 |
{-# LANGUAGE ScopedTypeVariables
, ExistentialQuantification
, LambdaCase
, KindSignatures
#-}
module Document.VarScope where
-- Modules
import Document.Phase.Types
import Document.Scope
import Latex.Parser (uncurry3)
import Logic.Expr
import UnitB.Syntax
-- Libraries
import qualified Control.Invariant as I
import Control.Lens
import Control.Precondition
import Data.Existential
import Data.Hashable
import qualified Data.List.NonEmpty as NE
import Data.Map as M
import Data.Typeable
import GHC.Generics.Instances
import Test.QuickCheck
import Test.QuickCheck.Regression
import Test.QuickCheck.Report
import Test.QuickCheck.ZoomEq
import Text.Printf.TH
import Utilities.Syntactic
class (Typeable a,Scope a,PrettyPrintable a) => IsVarScope a where
toOldEventDecl :: Name -> a -> [Either Error (EventId,[EventP2Field])]
toNewEventDecl :: Name -> a -> [Either Error (EventId,[EventP2Field])]
toThyDecl :: Name -> a -> [Either Error TheoryP2Field]
toMchDecl :: Name -> a -> [Either Error (MachineP2'Field ae ce t)]
newtype VarScope = VarScope { _varScopeCell :: Cell IsVarScope }
deriving (Typeable,Generic)
makeFields ''VarScope
instance Show VarScope where
show = readCell' show
instance ZoomEq VarScope where
x .== y = read2CellsWith' (.==) (x I.=== y) x y
instance Scope VarScope where
keep_from s = traverseCell' (keep_from s)
make_inherited = traverseCell' make_inherited
merge_scopes' = -- fmap (runIdentity . fromJust) .
apply2Cells' merge_scopes' Nothing
error_item = readCell' error_item
rename_events' m = traverseCell' (rename_events' m)
kind = readCell' kind
instance IsVarScope VarScope where
toOldEventDecl s = readCell' $ toOldEventDecl s
toNewEventDecl s = readCell' $ toNewEventDecl s
toThyDecl s = readCell' $ toThyDecl s
toMchDecl s = readCell' $ toMchDecl s
instance PrettyPrintable VarScope where
pretty = readCell' pretty
data TheoryConst = TheoryConst
{ thCons :: Var
, _theoryConstDeclSource :: DeclSource
, _theoryConstLineInfo :: LineInfo }
deriving (Eq,Ord,Show,Typeable,Generic)
data TheoryDef = TheoryDef
{ thDef :: Def
, _theoryDefDeclSource :: DeclSource
, _theoryDefLineInfo :: LineInfo }
deriving (Eq,Ord,Show,Typeable,Generic)
data MachineVar =
MchVar
{ var :: Var
, _machineVarDeclSource :: DeclSource
, _machineVarLineInfo :: LineInfo }
| DelMchVar
{ mvar :: Maybe Var
, _machineVarDeclSource :: DeclSource
, _machineVarLineInfo :: LineInfo }
deriving (Eq,Ord,Show,Typeable,Generic)
data MachineDef = MchDef
{ _machineDefName :: Name
, _term :: StringLi
, _machineDefDeclSource :: DeclSource
, _machineDefLineInfo :: LineInfo }
deriving (Eq,Ord,Show,Typeable,Generic)
data EvtDecls = Evt (Map EventOrDummy EventDecl)
deriving (Eq,Ord,Show,Typeable,Generic)
-- -- in Evt, 'Nothing' stands for a dummy
data DummyDecl = DummyDecl
deriving (Eq,Ord,Show,Generic)
type EventOrDummy = Either DummyDecl EventId
data EventDecl = EventDecl
{ _scope :: EvtScope Var
, _source :: NonEmpty EventOrDummy
, _eventDeclDeclSource :: DeclSource
, _eventDeclLineInfo :: LineInfo
} deriving (Show,Eq,Ord,Generic)
data EvtScope a = Param a | Index (InhStatus a) | Promoted (Maybe a)
deriving (Eq,Ord,Generic,Functor,Show)
instance Eq VarScope where
(==) = cellEqual' (==)
instance Ord VarScope where
compare = cellCompare' compare
makeLenses ''EventDecl
makeFields ''EventDecl
makePrisms ''EvtScope
makeFields ''TheoryConst
makeFields ''TheoryDef
makeFields ''MachineVar
makeFields ''MachineDef
makeFields ''EvtDecls
varDecl :: Getter EventDecl (Maybe Var)
varDecl = scope.to declOf
declOf :: EvtScope var -> Maybe var
declOf (Index (InhAdd v)) = Just v
declOf (Index (InhDelete v)) = v
declOf (Param v) = Just v
declOf (Promoted v) = v
instance PrettyRecord TheoryConst where
instance PrettyPrintable TheoryConst where
pretty = prettyRecord
instance ZoomEq TheoryConst where
instance Scope TheoryConst where
kind _ = "constant"
rename_events' _ e = [e]
instance PrettyRecord TheoryDef where
instance PrettyPrintable TheoryDef where
pretty = prettyRecord
instance ZoomEq TheoryDef where
instance Scope TheoryDef where
kind _ = "constant"
rename_events' _ e = [e]
instance PrettyRecord MachineDef where
instance PrettyPrintable MachineDef where
pretty = prettyRecord
instance ZoomEq MachineDef where
instance Scope MachineDef where
kind _ = "definition"
rename_events' _ e = [e]
instance PrettyRecord MachineVar where
instance PrettyPrintable MachineVar where
pretty = prettyRecord
instance ZoomEq MachineVar where
instance Scope MachineVar where
merge_scopes' (DelMchVar Nothing s _) (MchVar v Inherited li) = Just $ DelMchVar (Just v) s li
merge_scopes' (MchVar v Inherited li) (DelMchVar Nothing s _) = Just $ DelMchVar (Just v) s li
merge_scopes' _ _ = Nothing
kind (DelMchVar _ _ _) = "deleted variable"
kind (MchVar _ _ _) = "state variable"
rename_events' _ e = [e]
instance PrettyRecord EventDecl where
instance PrettyPrintable EventDecl where
pretty = prettyRecord
instance ZoomEq DummyDecl where
(.==) = (I.===)
instance ZoomEq EventDecl where
instance Scope EventDecl where
kind x = case x^.scope of
Index _ -> "index"
Param _ -> "parameter"
Promoted _ -> "promoted parameter"
keep_from s x | s == (x^.declSource) = Just x
| otherwise = Nothing
make_inherited = Just . (declSource .~ Inherited)
merge_scopes' s0 s1 = case (s0^.scope,s1^.scope) of
(Index (InhAdd v),Index (InhDelete Nothing)) ->
Just $ s1
& scope .~ Index (InhDelete (Just v))
& source .~ s0^.source
-- & declSource %~ declUnion (s0^.declSource)
(Index (InhDelete Nothing),Index (InhAdd v)) ->
Just $ s0
& scope .~ Index (InhDelete (Just v))
& source .~ s1^.source
-- & declSource %~ declUnion (s1^.declSource)
(Param v,Promoted Nothing) -> Just $ s1
& scope .~ Promoted (Just v)
& source .~ s0^.source
(Promoted Nothing,Param v) -> Just $ s0
& scope .~ Promoted (Just v)
& source .~ s1^.source
_ -> Nothing
rename_events' _ e = [e]
instance PrettyPrintable a => PrettyPrintable (EvtScope a) where
pretty = show . fmap Pretty
instance PrettyPrintable DummyDecl where
pretty DummyDecl = "dummy declaration"
instance Hashable DummyDecl where
instance PrettyPrintable EvtDecls where
pretty (Evt e) = "Evt " ++ pretty e
instance ZoomEq EvtDecls where
instance Scope EvtDecls where
kind (Evt m) = show $ M.map (view scope) m
keep_from s (Evt m)
| M.null r = Nothing
| otherwise = Just $ Evt r
where
r = M.mapMaybe (keep_from s) m
-- f x
-- | s == (x^.declSource) = Just x
-- | otherwise = Nothing
make_inherited (Evt m) = fmap Evt $ f $ M.mapMaybe make_inherited m
where
f m | M.null m = Nothing
| otherwise = Just m
error_item (Evt m) = fromJust' $ NE.nonEmpty $ elems $ mapWithKey msg m
where
msg (Right k) x = ([s|%s (event '%s')|] (kind x) (pretty k), x^.lineInfo)
msg (Left DummyDecl) x = ("dummy", x^.lineInfo)
merge_scopes' (Evt m0) (Evt m1) = Evt <$> scopeUnion merge_scopes' m0 m1
rename_events' lookup (Evt vs) = Evt <$> concatMap f (toList vs)
where
f (Right eid,x) = [ singleton (Right e) $ setSource (Right eid) x | e <- lookup eid ]
f (Left DummyDecl,x) = [ singleton (Left DummyDecl) x ]
setSource eid = source .~ eid :| []
instance Arbitrary TheoryDef where
arbitrary = genericArbitrary
shrink = genericShrink
instance Arbitrary TheoryConst where
arbitrary = genericArbitrary
shrink = genericShrink
instance Arbitrary MachineVar where
arbitrary = genericArbitrary
shrink = genericShrink
instance Arbitrary MachineDef where
arbitrary = genericArbitrary
shrink = genericShrink
instance Arbitrary EventDecl where
arbitrary = genericArbitrary
shrink = genericShrink
instance Arbitrary DummyDecl where
arbitrary = return DummyDecl
instance Arbitrary EvtDecls where
arbitrary = Evt . fromList <$> arbitrary
shrink = genericShrink
instance ZoomEq a => ZoomEq (EvtScope a) where
instance Arbitrary a => Arbitrary (EvtScope a) where
arbitrary = genericArbitrary
shrink = genericShrink
prop_axiom_Scope_clashesOverMerge :: Property
prop_axiom_Scope_clashesOverMerge = regression (uncurry3 axiom_Scope_clashesOverMerge)
[ (x,y,z) ]
where
x = Evt (fromList [(Left DummyDecl,EventDecl {_scope = Param (Var (Name {_backslash = False, _base = 'a' :| "", _primes = 0, _suffix = ""}) (Gen (DefSort (Name {_backslash = False, _base = 'a' :| "", _primes = 0, _suffix = ""}) (InternalName "" (Name {_backslash = False, _base = 'a' :| "", _primes = 0, _suffix = ""}) "") [] (Gen (Sort (Name {_backslash = False, _base = 'a' :| "", _primes = 0, _suffix = ""}) (InternalName "" (Name {_backslash = False, _base = 'a' :| "", _primes = 0, _suffix = ""}) "") 0) [])) [])), _source = Right (EventId (Lbl "m")) :| [], _eventDeclDeclSource = Local, _eventDeclLineInfo = (LI "file" 0 0)})])
y = Evt (fromList [(Left DummyDecl,EventDecl {_scope = Promoted Nothing, _source = Right (EventId (Lbl "c")) :| [], _eventDeclDeclSource = Inherited, _eventDeclLineInfo = (LI "file" 0 0)})])
z = Evt (fromList [(Left DummyDecl,EventDecl {_scope = Index (InhDelete Nothing), _source = Right (EventId (Lbl "c")) :| [], _eventDeclDeclSource = Local, _eventDeclLineInfo = (LI "file" 0 10)})])
return []
run_tests :: (PropName -> Property -> IO (a, Result))
-> IO ([a], Bool)
run_tests = $forAllProperties'
|
literate-unitb/literate-unitb
|
src/Document/VarScope.hs
|
mit
| 10,411 | 0 | 30 | 2,660 | 3,284 | 1,734 | 1,550 | -1 | -1 |
module Main where
import Engine
import GLUI
import SimpleBots
main :: IO ()
main = runBattle openGLUI [
("bot1", runInCircle),
("bot2", fireBot)
]
|
andreyLevushkin/LambdaWars
|
src/Main.hs
|
mit
| 173 | 0 | 7 | 49 | 51 | 31 | 20 | 8 | 1 |
module Handler.CustomError where
import Assets (getAllExams)
import Import
import Widgets (titleWidget, iconWidget, publicExamWidget, privateExamWidget)
-- | Custom 404 page
getCustomErrorR :: Handler Html
getCustomErrorR = do
setUltDestCurrent
memail <- lookupSession "_ID"
(publicExams, privateExams) <- runDB $ getAllExams memail
let middleWidget = [whamlet| <p class=boldWhite>_{MsgGet404} |]
defaultLayout $(widgetFile "error")
|
cirquit/quizlearner
|
quizlearner/Handler/CustomError.hs
|
mit
| 454 | 0 | 10 | 69 | 107 | 58 | 49 | -1 | -1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Models where
import Control.Monad.Logger (runStderrLoggingT)
import Control.Monad.Reader
import Control.Monad.Trans.Control
import Data.Aeson
import Data.Aeson.TH
import Data.Char (toLower)
import Data.Text (Text ())
import Data.Time
import Database.Persist.Postgresql
import Database.Persist.TH
import GHC.Generics
import Web.Users.Persistent
import Web.Users.Types
import Config
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Liftsession json
text Text
date UTCTime
user LoginId
deriving Show
Profile json
user LoginId
deriving Show
|]
data Registration
= Registration
{ regName :: Text
, regEmail :: Text
, regPassword :: Text
, regConfirmation :: Text
} deriving (Eq, Show)
deriveJSON defaultOptions { fieldLabelModifier = map toLower . Prelude.drop 3, constructorTagModifier = map toLower } ''Registration
data Auth
= Auth
{ authEmail :: Text
, authPassword :: Text
} deriving (Eq, Show)
deriveJSON defaultOptions { fieldLabelModifier = map toLower . Prelude.drop 4, constructorTagModifier = map toLower } ''Auth
doMigrations :: ReaderT SqlBackend IO ()
doMigrations = runMigration migrateAll
runDb :: (MonadIO m, MonadReader Config m) => SqlPersistT IO b -> m b
runDb query = asks getPool >>= liftIO . runSqlPool query
db :: (MonadIO m, MonadBaseControl IO m) => SqlPersistM a -> m a
db query =
runStderrLoggingT .
withPostgresqlPool (connStr Development) 1 $
liftIO . runSqlPersistMPool query
data Person = Person
{ name :: Text
, email :: Text
, personId :: LoginId
} deriving (Eq, Show, Generic)
instance ToJSON Person
instance FromJSON Person
type QLUser = User UserDetails
type UserDetails = ()
userToPerson :: LoginId -> QLUser -> Person
userToPerson lid User {..} =
Person { name = u_name
, email = u_email
, personId = lid
}
convertRegistration :: Registration -> QLUser
convertRegistration Registration{..} =
User { u_name = regName
, u_email = regEmail
, u_password = makePassword . PasswordPlain $ regPassword
, u_more = ()
, u_active = True
}
data AuthResponse
= AuthResponse
{ sessionId :: SessionId
, person :: Person
} deriving (Eq, Show, Generic)
instance ToJSON AuthResponse
|
parsonsmatt/QuickLift
|
src/Models.hs
|
mit
| 3,145 | 0 | 10 | 947 | 664 | 375 | 289 | 79 | 1 |
-- Tiny lambda-Micro-Haskell program TPJ 2015
z = 10 ;
neg b = if b then False else True ;
mnsdbl m n = m - n - n ;
once f x = f x ;
twice f x = f (f x) ;
|
jaanos/TPJ-2015-16
|
lmh/tiny_lmh.hs
|
mit
| 157 | 0 | 7 | 46 | 78 | 42 | 36 | 5 | 2 |
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Compression.GZip as GZ
import Control.Monad (forM_, when)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as BL
import Data.Char (toLower)
import qualified Data.Text.Lazy.IO as TL
import Distribution.Compiler (CompilerId(..), CompilerFlavor(..))
import Distribution.Homebrew
import qualified Distribution.PackageDescription as PD
import Distribution.PackageDescription.Configuration (finalizePackageDescription)
import Distribution.PackageDescription.Parse (readPackageDescription)
import Distribution.System (Platform(..), Arch(..), OS(..))
import Distribution.Verbosity (silent)
import Distribution.Version (Version(..))
import Network.HTTP (simpleHTTP, defaultGETRequest_, getResponseBody)
import Network.URI (URI(..), parseURI)
import Prelude hiding (or)
import System.Directory
import System.FilePath ((</>),(<.>))
import Text.Printf (printf)
-- * Configuration
instantiatePackageDescription :: PD.GenericPackageDescription -> Maybe PD.PackageDescription
instantiatePackageDescription gpd = case finalize gpd of
Left _ -> Nothing
Right (pd, _) -> Just pd
where
flags = []
isokay = const True
platform = Platform I386 OSX
compiler = CompilerId GHC (Version [7,6,3] [])
miscDeps = []
finalize = finalizePackageDescription flags isokay platform compiler miscDeps
remoteIndex :: String
remoteIndex = "http://hackage.haskell.org/packages/index.tar.gz"
localIndex :: FilePath
localIndex = "index"
-- * Main script
main :: IO ()
main = do
--home <- getHomeDirectory
--let cache =
-- home </> "Library" </> "Haskell" </> "repo-cache" </> "hackage.haskell.org"
putStrLn "Downloading the latest package list from hackage.haskell.org"
case parseURI remoteIndex of
Nothing -> error $ "Invalid URI: " ++ remoteIndex
Just uri -> do
indexTarGz <- getRequest uri
let indexTar = GZ.decompress (BL.fromChunks ((:[]) indexTarGz))
BL.writeFile "index.tar" indexTar
createDirectoryIfMissing False localIndex
Tar.extract localIndex "index.tar"
removeFile "index.tar"
putStrLn "Analysing package list"
packages <- getDirectoryContents localIndex
forM_ packages $ \package -> do
let packagePath = localIndex </> package
packagePathExists <- doesDirectoryExist packagePath
when (packagePathExists && package `notElem` [".",".."]) $ do
versions <- getDirectoryContents packagePath
let latestVersion = maximum versions
let latestPath = packagePath </> latestVersion
let cabalFile = latestPath </> package <.> "cabal"
cabalFileExists <- doesFileExist cabalFile
when cabalFileExists $ do
gpd <- readPackageDescription silent cabalFile
case instantiatePackageDescription gpd of
Nothing -> return ()
Just pd -> do
maybeFormula <- fromPackageDescription pd
case maybeFormula of
Nothing -> return ()
Just formDesc -> do
formCode <- renderFormula formDesc
let formPath = map toLower package <.> "rb"
putStrLn (printf "Writing formula for %s-%s" package latestVersion)
TL.writeFile formPath formCode
removeDirectoryRecursive localIndex
putStrLn "Done"
getRequest :: URI -> IO ByteString
getRequest url = simpleHTTP (defaultGETRequest_ url) >>= getResponseBody
|
pepijnkokke/homebrew-hackage
|
Main.hs
|
mit
| 3,728 | 11 | 25 | 965 | 857 | 461 | 396 | 75 | 4 |
module Main where
import Popeye.CLI
main :: IO ()
main = run
|
codeclimate/popeye
|
app/Main.hs
|
mit
| 63 | 0 | 6 | 14 | 24 | 14 | 10 | 4 | 1 |
#!/usr/bin/env stack
-- stack --install-ghc runghc --package turtle
-- #!/bin/bash
{-# LANGUAGE OverloadedStrings #-} --
--
import Turtle
say = echo
main = say "Hello, world!"
|
capitanbatata/functional-systems-in-haskell
|
fsh-exercises/scripts/example1.hs
|
mit
| 260 | 0 | 5 | 110 | 23 | 15 | 8 | 4 | 1 |
-- The number, 197, is called a circular prime because
-- all rotations of the digits: 197, 971, and 719, are themselves prime.
-- There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
-- How many circular primes are there below one million?
module Euler35 where
import Data.Numbers.Primes
import Data.List
-- TODO copy paste from Euler 34 - refactor
digits :: Integer -> [Integer]
digits a = reverse (digitsInternal a)
digitsInternal a
| a < 10 = [a]
| otherwise = q : digitsInternal r
where (r, q) = quotRem a 10
combine :: [Integer] -> Integer
combine list = foldl (\a b -> a * 10 + b) 0 list
-- https://stackoverflow.com/questions/7631664/how-to-define-a-rotates-function
listRotations :: [a] -> [[a]]
listRotations l = init (zipWith (++) (tails l) (inits l))
-- TODO read about ad hoc polimorphism
rotations :: Integer -> [Integer]
rotations a = nub (map combine (listRotations (digits a)))
allAre :: (Integer -> Bool) -> [Integer] -> Bool
allAre func [] = True -- not logical?
allAre func (x:xs)
| func(x) == False = False
| otherwise = allAre func xs
circularPrime :: Integer -> Bool
circularPrime 1 = False
circularPrime a
| not (isPrime a) = False
| otherwise = allAre isPrime (rotations a)
result = length(filter circularPrime (takeWhile (<1000000) [1..]))
|
kirhgoff/haskell-sandbox
|
euler35/euler35.hs
|
mit
| 1,333 | 0 | 11 | 250 | 422 | 221 | 201 | 26 | 1 |
main :: IO ()
main = putStrLn $ show $ solve
solve :: Int
solve = sum [sumMultiplesToN 3 1000, sumMultiplesToN 5 1000, -sumMultiplesToN 15 1000]
sumMultiplesToN :: (Integral a) => a -> a -> a
sumMultiplesToN m n = m * (sumToN $ (n-1) `div` m)
sumToN :: (Integral a) => a -> a
sumToN n = n * (n+1) `div` 2
|
pshendry/project-euler-solutions
|
0001/solution.hs
|
mit
| 308 | 1 | 10 | 66 | 158 | 86 | 72 | 8 | 1 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-------------------------------------------------------------------------------
-- Module : Domain.Concrete.Transformers.Expression
-- Copyright : (c) 2017 Marcelo Sousa
--
-- Transformers for the concrete semantics.
-- Two main transformers for the types of edges in the CFG:
-- transformer_expr (for the expression)
-------------------------------------------------------------------------------
module Domain.Concrete.Transformers.Expression (transformer_expr) where
import Control.Monad.State.Lazy hiding (join)
import Data.List
import Data.Map (Map)
import Data.Maybe
import Domain.Action
import Domain.Concrete.API
import Domain.Concrete.State
import Domain.Concrete.Transformers.State
import Domain.Concrete.Transformers.Statement
import Domain.Concrete.Value
import Domain.Lattice
import Domain.MemAddr
import Domain.Util
import Language.C.Syntax.Constants
import Language.C.Syntax.Ops
import Language.SimpleC.AST hiding (Value)
import Language.SimpleC.Converter hiding (Scope(..))
import Language.SimpleC.Flow
import Language.SimpleC.Util
import Util.Generic hiding (safeLookup)
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Model.GCS as GCS
-- Given an initial state and an expression
-- return the updated state.
transformer_expr :: SExpression -> ConTOp ConAct
transformer_expr expr = mytrace False ("transformer_expr: " ++ show expr) $ do
s@ConTState{..} <- get
if cond
then mytrace False ("transformer_expr: conditional " ++ show expr) $ do
(val, act) <- bool_transformer_expr expr
s@ConTState{..} <- get
let res_st = case val of
ConVal (VBool True) -> st
_ -> bot
set_state res_st
mytrace False ("bool_transformer: result = " ++ show val) $ return act
else do
(vals,act) <- transformer expr
return act
-- eval logical expressions
bool_transformer_expr :: SExpression -> ConTOp (ConValue, ConAct)
bool_transformer_expr expr = mytrace False ("bool_transformer_expr: " ++ show expr) $
case expr of
Binary op lhs rhs -> apply_logic op lhs rhs
Unary CNegOp rhs -> do
(conValue, acts) <- bool_transformer_expr rhs
return (negate conValue, acts)
Const k -> return (ConVal $ toBoolVal $ toValue k, bot)
_ -> error $ "bool_transformer_expr: not supported " ++ show expr
apply_logic :: BinaryOp -> SExpression -> SExpression -> ConTOp (ConValue,ConAct)
apply_logic op lhs rhs = do
-- process the lhs (get the new state, values and actions)
(lhs_vals,lhs_acts) <- transformer lhs
-- process the rhs (get the new state, values and actions)
(rhs_vals,rhs_acts) <- transformer rhs
let res_acts = lhs_acts `join` rhs_acts
res_val = case op of
CLeOp -> le_conval lhs_vals rhs_vals
CGrOp -> gr_conval lhs_vals rhs_vals
CLeqOp -> leq_conval lhs_vals rhs_vals
CGeqOp -> geq_conval lhs_vals rhs_vals
CEqOp -> eq_conval lhs_vals rhs_vals
CNeqOp -> neq_conval lhs_vals rhs_vals
CLndOp -> land_conval lhs_vals rhs_vals
CLorOp -> lor_conval lhs_vals rhs_vals
mytrace False ("apply_logic: lhs = " ++ show lhs_vals ++ "\t rhs = " ++ show rhs_vals) $ return (res_val,res_acts)
|
marcelosousa/poet
|
src/Domain/Concrete/Transformers/Expression.hs
|
gpl-2.0
| 3,274 | 0 | 20 | 595 | 787 | 423 | 364 | 65 | 8 |
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DatatypeContexts #-}
{-# language DatatypeContexts #-}
{-# language TemplateHaskell #-}
{-# language DeriveDataTypeable #-}
{-# language ScopedTypeVariables #-}
{-# language DoAndIfThenElse #-}
module Rewriting.Termination.Interpretation where
import Rewriting.Termination.Semiring
import qualified Rewriting.Termination.Domains as D
import Rewriting.Termination.Multilinear
import qualified Rewriting.Termination.Polynomial as P
import qualified Polynomial.Type as P
import Rewriting.Termination.Matrix (contents, dim)
import Rewriting.TRS
import Autolib.Reader
import Autolib.ToDoc
import Autolib.Reporter
import Control.Lens
import Control.Monad ( when, forM )
import Control.Applicative ( (<$>) )
import Data.Typeable
import Data.List ( transpose )
import Autolib.FiniteMap
import qualified Data.Map as M
import qualified Data.Set as S
import Autolib.Size
data Domain = Natural | Arctic | Tropical | Fuzzy
deriving (Eq, Typeable)
derives [makeReader, makeToDoc] [''Domain]
type Inter c d = M.Map c d
data (Symbol c, Ord c) => Interpretation c
= Matrix_Interpretation_Natural (Inter c (Multilinear D.Natural))
| Matrix_Interpretation_Arctic (Inter c (Multilinear D.Arctic))
| Matrix_Interpretation_Tropical (Inter c (Multilinear D.Tropical))
| Matrix_Interpretation_Fuzzy (Inter c (Multilinear D.Fuzzy))
| Polynomial_Interpretation (Inter c (P.Poly Integer P.X))
deriving (Eq, Typeable)
instance Symbol c => Size (Interpretation c) where
size i = case i of
Matrix_Interpretation_Natural m -> nonzeroes m
Matrix_Interpretation_Arctic m -> nonzeroes m
Matrix_Interpretation_Tropical m -> nonzeroes m
Matrix_Interpretation_Fuzzy m -> nonzeroes m
Polynomial_Interpretation m -> sum $ do
(c,p) <- M.toList m ; return $ P.nterms p
nonzeroes m = sum $ do
(k,v) <- M.toList m
a <- absolute v : coefficients v
x <- concat $ contents a
return $ if is_zero x then 0 else 1
derives [makeToDoc] [''Interpretation]
instance (Ord c, Symbol c, Reader c) => Reader (Interpretation c) where
reader =
do my_reserved "Matrix_Interpretation_Natural"
Matrix_Interpretation_Natural <$> reader
<|> do my_reserved "Matrix_Interpretation_Arctic"
Matrix_Interpretation_Arctic <$> reader
<|> do my_reserved "Matrix_Interpretation_Tropical"
Matrix_Interpretation_Tropical <$> reader
<|> do my_reserved "Matrix_Interpretation_Fuzzy"
Matrix_Interpretation_Fuzzy <$> reader
<|> do my_reserved "Polynomial_Interpretation"
Polynomial_Interpretation <$> reader
data Comparison = Greater | Greater_Equal | Other
deriving (Eq, Typeable )
derives [makeReader, makeToDoc] [''Comparison]
-- | applied to a term where variables are renamed to [1,2..from]
inter :: (Symbol c, Ord c, Semiring d, ToDoc d)
=> Inter c (Multilinear d) -> Int -> Int
-> Term Int c -> Reporter (Multilinear d)
inter int from dim t = explained t $ case t of
Var to -> return $ projection from to dim
Node f args -> case M.lookup f int of
Nothing -> reject $ vcat
[ text "missing interpretation for symbol" <+> toDoc f
]
Just fun -> do
let syn = length args
sem = length (coefficients fun)
when ( syn /= sem ) $ reject $ vcat
[ text "arity mismatch for symbol" <+> toDoc f
, text "arity of symbol is" <+> toDoc syn
, text "arity of interpretation of symbol is" <+> toDoc sem
]
gs <- forM args $ inter int from dim
return $ substitute fun gs
-- | applied to a term where variables are renamed to [1,2..from]
inter_poly :: (Symbol c, Ord c)
=> Inter c (P.Poly Integer P.X)
-> Term Int c -> Reporter (P.Poly Integer P.X)
inter_poly int t = explained t $ case t of
Var to -> return $ P.variable $ P.X to
Node f args -> case M.lookup f int of
Nothing -> reject $ vcat
[ text "missing interpretation for symbol" <+> toDoc f
]
Just fun -> do
let syn = length args
void $ sequence $ do
(c,m) <- P.terms fun ; f <- P.factors m ; let P.X i = f ^. P.var
return $ when ( i < 1 || i > syn ) $ reject $ vcat
[ text "interpretation of symbol" <+> toDoc f
, text "uses non-existing argument" <+> toDoc (P.X i)
, toDoc fun
]
P.must_be_monotone f syn fun
gs <- forM args $ inter_poly int
return $ P.substitute fun gs
explained t action = do
inform $ text "compute interpretation of" <+> toDoc t
i <- nested 4 action
inform $ vcat
[ text "interpretation of" <+> toDoc t <+> text "is"
, toDoc i
]
return i
check_monotone i = case i of
Matrix_Interpretation_Natural i -> must_be_monotone i
Matrix_Interpretation_Arctic i -> must_be_monotone i
Matrix_Interpretation_Tropical i -> must_be_monotone i
Matrix_Interpretation_Fuzzy i -> must_be_monotone i
Polynomial_Interpretation i -> return () -- do this in different place
must_be_monotone (int :: Inter c (Multilinear d)) = forM_ (M.toList int) $ \ (f, m) -> do
inform $ vcat [ text "check monotonicity for"
, text "symbol" <+> toDoc f
, text "interpreted by" <+> toDoc m
]
forM (coefficients m) $ \ c ->
when (not $ positive c) $ reject $ vcat
[ text "is not monotone since coefficient"
, toDoc c
, text "is not positive"
]
when (not (strict_addition ( undefined :: d))) $ do
when (not (null $ coefficients m) && not (is_zero $ absolute m)) $ reject $ vcat
[ text "interpretation is not monotone"
, text "since semiring addition is not monotone"
, text "and absolute part is non-zero"
, text "and function has at least one argument"
]
when (length ( coefficients m ) > 1) $ reject $ vcat
[ text "interpretation is not monotone"
, text "since semiring addition is not monotone"
, text "and function has more than one argument"
]
compute_order i = case i of
Matrix_Interpretation_Natural i -> order i
Matrix_Interpretation_Arctic i -> order i
Matrix_Interpretation_Tropical i -> order i
Matrix_Interpretation_Fuzzy i -> order i
Polynomial_Interpretation i -> order_poly i
order_poly :: (Symbol c, Ord v )
=> Inter c (P.Poly Integer P.X) -> Int
-> Rule (Term v c) -> Reporter Comparison
order_poly (int :: Inter c (P.Poly Integer P.X)) dim u = do
let l = lhs u ; r = rhs u
vs = S.union (vars l) (vars r)
m = M.fromList $ zip ( S.toList vs) [1..]
from = M.size m
rename = vmap (m M.!)
ml <- inter_poly int $ rename l
mr <- inter_poly int $ rename r
if P.weakly_greater ml mr
then if P.strictly_greater ml mr
then return Greater
else return Greater_Equal
else return Other
order :: (Symbol c, Ord v, Semiring d, ToDoc d )
=> Inter c (Multilinear d) -> Int
-> Rule (Term v c) -> Reporter Comparison
order (int :: Inter c (Multilinear d)) dim u = do
let l = lhs u ; r = rhs u
vs = S.union (vars l) (vars r)
m = M.fromList $ zip ( S.toList vs) [1..]
from = M.size m
rename = vmap (m M.!)
ml <- inter int from dim $ rename l
mr <- inter int from dim $ rename r
if and $ zipWith weakly_greater
(absolute ml : coefficients ml)
(absolute mr : coefficients mr)
then if ( if strict_addition (undefined :: d)
then strictly_greater (absolute ml) (absolute mr)
else and $ zipWith strictly_greater
(absolute ml : coefficients ml)
(absolute mr : coefficients mr)
)
then return Greater
else return Greater_Equal
else return Other
check_dimension sig dim i = case i of
Matrix_Interpretation_Natural i -> check_arity_dimension sig dim i
Matrix_Interpretation_Arctic i -> check_arity_dimension sig dim i
Matrix_Interpretation_Tropical i -> check_arity_dimension sig dim i
Matrix_Interpretation_Fuzzy i -> check_arity_dimension sig dim i
Polynomial_Interpretation {} -> return ()
check_arity_dimension sig dim i = do
check_arities sig i
must_be_dimension dim i
must_be_dimension d m = forM_ (M.toList m) $ \ (k,v) -> do
let check msg want m = when (want /= dim m) $ reject $ vcat
[ text "interpretation of symbol" <+> toDoc k
, text msg <+> toDoc m
, text "must have dimension" <+> toDoc want
]
check "absolute part" (d,1) $ absolute v
forM_ (coefficients v) $ check "coefficient" (d,d)
check_arities sig m = forM_ (S.toList sig) $ \ k ->
case M.lookup k m of
Nothing -> reject $ text "symbol" <+> toDoc k <+> text "is missing from interpretation"
Just v -> do
let ar = length $ coefficients v
when (arity k /= ar ) $ reject $ vcat
[ text "symbol" <+> toDoc k
, text "has arity" <+> toDoc (arity k)
, text "but its interpretation has arity" <+> toDoc ar
]
|
marcellussiegburg/autotool
|
collection/src/Rewriting/Termination/Interpretation.hs
|
gpl-2.0
| 9,614 | 0 | 24 | 2,902 | 3,039 | 1,477 | 1,562 | 204 | 5 |
{-# OPTIONS -Wall #-}
-- | Reexport module
module HsTri(
module Blender,
module ClosedOrCensus6,
module Codec.Rga.Parser,
module Codec.Rga.Writer,
module ConcreteNormal,
module ConcreteNormal.PreRenderable,
module Data.AscTuples,
module Data.FormalOps,
module Data.Vector,
module DisjointUnion,
module DotUtil,
module EdgeCentered,
module EqvGraphs,
module ExampleTriangulations,
module FaceLattice,
module HomogenousTuples,
module HsTri.Console,
module Numeric.AD.Vector,
module PreRenderable,
module PrettyUtil,
module QuadCoordinates,
module QuadCoordinates.CanonExt,
module QuadCoordinates.Dense,
module QuadCoordinates.MatchingEquations,
module QuadCoordinates.SolSetConversion,
module R3Immersions,
module Simplicial.SimplicialComplex,
module StandardCoordinates,
module StandardCoordinates.Dense,
module StandardCoordinates.MatchingEquations,
module StandardCoordinates.SurfaceQueries,
module THUtil,
module Tetrahedron.INormalDisc,
module Tetrahedron.NormalConstants,
module Tetrahedron.NormalDisc,
module Tikz.Gen,
module Tikz.Preview,
module TriArcGraph,
module Triangulation.Class,
module Triangulation.FacetGluing,
module Triangulation.Random,
module Triangulation.Transformations,
module Triangulation.VertexLink,
module TriangulationCxtObject,
module VerboseDD,
module Latexable.DD
) where
import Blender
import ClosedOrCensus6
import Codec.Rga.Parser
import Codec.Rga.Writer
import ConcreteNormal
import ConcreteNormal.PreRenderable
import Data.AscTuples
import Data.FormalOps
import Data.Vector(Vector)
import DisjointUnion
import DotUtil(viewDot,PrintDot)
import EdgeCentered
import EqvGraphs
import ExampleTriangulations
import FaceLattice
import HomogenousTuples
import HsTri.Console
import Numeric.AD.Vector
import PreRenderable
import PrettyUtil
import QuadCoordinates
import QuadCoordinates.CanonExt
import QuadCoordinates.Dense
import QuadCoordinates.MatchingEquations
import QuadCoordinates.SolSetConversion
import R3Immersions
import Simplicial.SimplicialComplex
import StandardCoordinates
import StandardCoordinates.Dense
import StandardCoordinates.MatchingEquations
import StandardCoordinates.SurfaceQueries
import THUtil
import Tetrahedron.INormalDisc
import Tetrahedron.NormalConstants
import Tetrahedron.NormalDisc
import Tikz.Gen
import Tikz.Preview
import TriArcGraph
import Triangulation.Class
import Triangulation.FacetGluing
import Triangulation.Random
import Triangulation.Transformations
import Triangulation.VertexLink
import TriangulationCxtObject
import VerboseDD
import Latexable.DD
|
DanielSchuessler/hstri
|
HsTri.hs
|
gpl-3.0
| 2,716 | 0 | 5 | 388 | 457 | 304 | 153 | 94 | 0 |
{-# LANGUAGE RecordWildCards #-}
module DFA where
import Control.Monad
import qualified Data.PQueue.Min as PQ
import qualified Data.Set as S
import qualified Data.List as L
import Data.List (sort)
import NFA
import Regex
data DFA s a = DFA { states :: [s]
, delta :: s -> a -> s
, start :: s
, accept :: [s]
}
class Alphabet a where
alphabet :: [a]
instance Alphabet Char where
alphabet = enumFromTo '!' (toEnum 126)
determinise :: (Alphabet a, Ord s) => NFA s a -> DFA [s] a
determinise NFA {..} = DFA { states = states'
, delta = delta'
, start = [start]
, accept = filter (\s -> not . S.null $ S.fromList s `S.intersection` S.fromList accept) states'
}
where
delta' sz a = S.toList $ S.fromList (sz >>= \s -> delta s a)
states' = closure (\s -> map (delta' s) alphabet) (S.singleton [start])
powerset [] = [[]]
powerset (x:xs) = let rs = powerset xs in map (x:) rs ++ rs
toDFA :: (Alphabet a, Eq a) => Regex a -> DFA [Int] a
toDFA = determinise . deEpsilon . toNFAe
symmetricDiff :: (Eq s1, Eq s2) => DFA s1 a -> DFA s2 a -> DFA (s1,s2) a
symmetricDiff DFA {states = s1, delta = d1, start = q1, accept = a1}
DFA {states = s2, delta = d2, start = q2, accept = a2} =
DFA { states = liftM2 (,) s1 s2
, delta = \(x1,x2) a -> (d1 x1 a, d2 x2 a)
, start = (q1,q2)
, accept = [(x,y) | x <- s1, y <- s2, not (x `elem` a1 && y `elem` a2), (x `elem` a1 || y `elem` a2)]
}
shortestWord :: (Alphabet a, Ord a, Ord s) => DFA s a -> Maybe [a]
shortestWord DFA {..} = shortestPath (PQ.singleton (0,start,[])) S.empty delta accept
shortestPath :: (Alphabet a, Ord s, Ord a) => PQ.MinQueue (Int, s, [a]) -> S.Set s -> (s -> a -> s) -> [s] -> Maybe [a]
shortestPath pq vis d target = case PQ.minView pq of
Nothing -> Nothing
Just ((l, s, w), pq') ->
if s `elem` target then
Just $ reverse w
else
shortestPath (pq' `PQ.union` PQ.fromList unvisitedNeighbours) (S.insert s vis) d target
where
unvisitedNeighbours = filter (not . flip S.member vis . second) potential
second (_,x,_) = x
potential = map (\a -> (l+1, d s a, a:w)) alphabet
|
TeofilC/regeq
|
src/DFA.hs
|
gpl-3.0
| 2,638 | 0 | 15 | 1,021 | 1,070 | 592 | 478 | 47 | 3 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TypeOperators #-}
{- |
Module : Tct.Method.Poly.NaturalPI
Copyright : (c) Martin Avanzini <[email protected]>,
Georg Moser <[email protected]>,
Andreas Schnabl <[email protected]>
License : LGPL (see COPYING)
Maintainer : Andreas Schnabl <[email protected]>
Stability : unstable
Portability : unportable
This module defines the processor for matrix.
-}
module Tct.Method.Matrix.NaturalMI where
import Control.Monad (liftM)
import Data.Typeable
import Prelude hiding ((&&),(||),not)
import Text.PrettyPrint.HughesPJ
import qualified Data.Map as Map
import qualified Data.Set as Set
import Qlogic.MiniSat (MiniSatLiteral, MiniSatSolver)
import Qlogic.Boolean
import Qlogic.Diophantine
import Qlogic.Formula (Formula(..))
import qualified Qlogic.MemoizedFormula as MForm
import Qlogic.PropositionalFormula
import Qlogic.Semiring
import qualified Qlogic.Assign as A
import qualified Qlogic.NatSat as N
import qualified Qlogic.SatSolver as SatSolver
import qualified Qlogic.Semiring as SR
import Termlib.Utils
import Termlib.Term (Term)
import qualified Tct.Utils.Xml as Xml
import qualified Termlib.FunctionSymbol as F
import qualified Termlib.Problem as Prob
import qualified Termlib.Rule as R
import qualified Termlib.Trs as Trs
import qualified Termlib.Variable as V
import qualified Termlib.ArgumentFiltering as AF
import qualified Tct.Method.RuleSelector as RS
import Tct.Certificate (poly, expo, certified, unknown)
import Tct.Encoding.AbstractInterpretation
import Tct.Encoding.Matrix hiding (maxMatrix)
import Tct.Encoding.Natring ()
import Tct.Encoding.UsablePositions hiding (empty)
import Tct.Method.Matrix.MatrixInterpretation as MI
import Tct.Processor.Args
import qualified Tct.Encoding.UsableRules as UREnc
import qualified Tct.Encoding.ArgumentFiltering as AFEnc
import qualified Tct.Processor.Args as A
import Tct.Processor.Args.Instances
import Tct.Processor.Args.Instances ()
import Tct.Processor.Orderings
import Tct.Utils.PPrint (indent)
import qualified Tct.Processor as P
import Tct.Processor (Answer(..), ComplexityProof(..))
import qualified Tct.Processor.Standard as S
-- | This parameter defines the shape of the matrix interpretations,
-- and how the induced complexity is computed.
data NaturalMIKind = Algebraic -- ^ Count number of ones in diagonal to compute induced complexity function.
| Automaton -- ^ Use automaton-techniques to compute induced complexity function.
| Triangular -- ^ Use triangular matrices only.
| Unrestricted -- ^ Put no further restrictions on the interpretation.
deriving (Typeable, Bounded, Enum, Eq)
instance Show NaturalMIKind where
show Algebraic = "algebraic"
show Triangular = "triangular"
show Automaton = "automaton"
show Unrestricted = "nothing"
data MatrixOrder = MatrixOrder { ordInter :: MatrixInter Int
, param :: MatrixKind
, miKind :: NaturalMIKind
, uargs :: UsablePositions
, input :: Prob.Problem
, argFilter :: Maybe AF.ArgumentFiltering
, usymbols :: [F.Symbol]
} deriving Show
data NaturalMI = NaturalMI deriving (Typeable, Show)
instance PrettyPrintable (MatrixOrder, Trs.Trs, V.Variables) where
pprint (order, trs, var) = pprintProof order P.ProofOutput $+$ pptrs
where sig = signature $ ordInter order
pptrs = text "Interpretations of rules:" $+$ vcat (map pprule $ Trs.rules trs)
pprule r = (text "Rule" <+> pprint (r, sig, var) <+> char ':') $+$ ppterm (R.lhs r) $+$ ppterm (R.rhs r)
ppterm t = pprint (t, sig, var) <+> char '=' <+> pprint ((interpretTerm (ordInter order) t), var)
instance ComplexityProof MatrixOrder where
pprintProof order _ = (if uargs order == fullWithSignature (signature $ ordInter order)
then empty
else paragraph "The following argument positions are usable:"
$+$ indent (pprint (uargs order, sig))
$+$ text "")
$+$ paragraph ("TcT has computed the following " ++ ppknd (param order))
$+$ text ""
$+$ indent (pprint inter)
$+$ text ""
$+$ paragraph "The order satisfies the following ordering constraints:"
$+$ text ""
$+$ indent (pprintOrientRules inter sig vars rs)
where ppknd UnrestrictedMatrix = "unrestricted matrix interpretation."
ppknd (TriangularMatrix Nothing) = "triangular matrix interpretation."
ppknd (TriangularMatrix (Just n)) = "triangular matrix interpretation. Note that "
++ "the diagonal of the component-wise maxima of interpretation-entries contains no more than "
++ show n ++ " non-zero entries."
ppknd (ConstructorBased _ Nothing) = "constructor-restricted matrix interpretation."
ppknd (ConstructorBased _ (Just n)) = "constructor-restricted matrix interpretation. Note that "
++ "the diagonal of the component-wise maxima of interpretation-entries (of constructors) contains no more than "
++ show n ++ " non-zero entries."
ppknd (EdaMatrix Nothing) = "matrix interpretation satisfying not(EDA)."
ppknd (EdaMatrix (Just n)) = "matrix interpretation satisfying not(EDA) and not(IDA(" ++ show n ++ "))."
ppknd (ConstructorEda _ Nothing) = "constructor-based matrix interpretation satisfying not(EDA)."
ppknd (ConstructorEda _ (Just n)) = "constructor-based matrix interpretation satisfying not(EDA) and not(IDA(" ++ show n ++ "))."
inter = ordInter order
prob = input order
sig = Prob.signature prob
vars = Prob.variables prob
rs = Trs.rules $ Prob.allComponents prob
answer order = CertAnswer $ certified (unknown, ub)
where m = ordInter order
countDiagonal | miKind order == Triangular = const $ dimension m
| otherwise = diagonalNonZeroes
ub = case param order of
UnrestrictedMatrix {} -> expo (Just 1)
TriangularMatrix {} -> poly $ Just $ countDiagonal $ maxNonIdMatrix m
where
ConstructorBased cs _ -> poly $ Just $ countDiagonal $ maxNonIdMatrix m'
where m' = m{interpretations = filterCs $ interpretations m}
filterCs = Map.filterWithKey (\f _ -> f `Set.member` cs)
EdaMatrix Nothing -> poly $ Just $ dimension m
EdaMatrix (Just n) -> poly $ Just n
ConstructorEda _ Nothing -> poly $ Just $ dimension m
ConstructorEda _ (Just n) -> poly $ Just $ n
-- TODO: include argfilter
toXml (MatrixOrder ord knd _ uarg _ _ _) =
Xml.elt "interpretation" [] (MI.toXml ord knd uarg)
type MatrixOptions = Arg (EnumOf NaturalMIKind) :+: Arg (Maybe Nat) :+: Arg Nat :+: Arg Nat :+: Arg (Maybe Nat) :+: Arg (Maybe Nat) :+: Arg Bool :+: Arg Bool
matrixOptions :: MatrixOptions
matrixOptions =
opt { A.name = "cert"
, A.description = unwords [ "This argument specifies restrictions on the matrix interpretation which induce polynomial growth of"
, "the interpretation of the considered starting terms relative to their size."
, "Here 'algebraic' refers to simple algebraic restrictions on matrices (in the current implementation,"
, "they are simply restricted to triangular shape, i.e. matrices where coefficients in the lower-left"
, "half below the diagonal are zero. Such matrix interpretations induce polynomial derivational-complexity."
, "If 'automaton' is given as argument, then criteria from the theory of weighted automata are used instead"
, "(in the current implementation, the negations of the criteria EDA, and possibly IDA(n), in the case that"
, "the flag 'degree' is set, are used)."
, "If 'nothing' is given, then matrix interpretations of all function symbols are unrestricted."
, "Note that matrix interpretations produced with this option do not induce polynomial complexities in general."
, "The default value is 'automaton'."
]
, A.defaultValue = Automaton}
:+:
opt { A.name = "degree"
, A.description = unwords [ "This argument ensures that the complexity induced by the searched matrix interpretation is bounded by a"
, "polynomial of the given degree. Its internal effect is dictated by the value the argument 'cert' is set to."
, "If it is set to 'algebraic', this restricts the number of non-zero entries in the diagonals of the matrices."
, "If it is set to 'automaton', this set the paramter 'n' in the criterion 'not IDA(n)'."
, "Finally, if it is set to 'unrestricted', the effect of setting the 'degree' argument is unspecified."
]
, A.defaultValue = Nothing}
:+:
opt { A.name = "dim"
, A.description = unwords [ "This argument specifies the dimension of the vectors and square-matrices appearing"
, " in the matrix interpretation."]
, A.defaultValue = Nat 2 }
:+:
opt { A.name = "bound"
, A.description = unwords [ "This argument specifies an upper-bound on coefficients appearing in the interpretation."
, "Such an upper-bound is necessary as we employ bit-blasting to SAT internally"
, "when searching for compatible matrix interpretations."]
, A.defaultValue = Nat 3 }
:+:
opt { A.name = "bits"
, A.description = unwords [ "This argument plays the same role as 'bound',"
, "but instead of an upper-bound the number of bits is specified."
, "This argument overrides the argument 'bound'."]
, A.defaultValue = Nothing }
:+:
opt { A.name = "cbits"
, A.description = unwords [ "This argument specifies the number of bits used for intermediate results, "
, "as for instance coefficients of matrices obtained by interpreting"
, "left- and right-hand sides."]
, A.defaultValue = Nothing }
:+:
opt { A.name = "uargs"
, A.description = unwords [ "This argument specifies whether usable arguments are computed (if applicable)"
, "in order to relax the monotonicity constraints on the interpretation."]
, A.defaultValue = True }
:+:
opt { A.name = "urules"
, A.description = unwords [ "This argument specifies whether usable rules modulo argument filtering is applied"
, "in order to decreas the number of rules to orient. "]
, A.defaultValue = True }
instance S.Processor NaturalMI where
name NaturalMI = "matrix"
description NaturalMI = [ "This processor orients the problem using matrix interpretation over natural numbers." ]
type ArgumentsOf NaturalMI = MatrixOptions
arguments NaturalMI = matrixOptions
instanceName inst = "matrix interpretation of dimension " ++ show (dim $ S.processorArgs inst)
type ProofOf NaturalMI = OrientationProof MatrixOrder
solve inst prob = orient rs prob (S.processorArgs inst)
where rs = RS.rsSelect (RS.selAllOf RS.selStricts) prob
solvePartial inst rs prob = mkProof `liftM` orient rs prob (S.processorArgs inst)
where mkProof res@(Order ord) =
P.PartialProof { P.ppInputProblem = prob
, P.ppResult = res
, P.ppRemovableDPs = Trs.toRules $ strictRules mi $ Prob.dpComponents prob
, P.ppRemovableTrs = Trs.toRules $ strictRules mi $ Prob.trsComponents prob }
where mi = ordInter ord
mkProof res =
P.PartialProof { P.ppInputProblem = prob
, P.ppResult = res
, P.ppRemovableDPs = []
, P.ppRemovableTrs = [] }
matrixProcessor :: S.StdProcessor NaturalMI
matrixProcessor = S.StdProcessor NaturalMI
-- | This processor implements matrix interpretations.
matrix :: S.ProcessorInstance NaturalMI
matrix = S.StdProcessor NaturalMI `S.withArgs` (Automaton :+: Nothing :+: nat 2 :+: nat 2 :+: Nothing :+: Just (nat 3) :+: True :+: True)
-- argument accessors
kind :: Domains (S.ArgumentsOf NaturalMI) -> Prob.StartTerms -> MatrixKind
kind (Unrestricted :+: _ :+: _ :+: _ :+: _ :+: _ :+: _ :+: _) _ = UnrestrictedMatrix
kind (Algebraic :+: d :+: _ :+: _ :+: _ :+: _ :+: _ :+: _) (Prob.BasicTerms _ cs) = ConstructorBased cs (fmap (\ (Nat n) -> n) d)
kind (Algebraic :+: d :+: _ :+: _ :+: _ :+: _ :+: _ :+: _) Prob.TermAlgebra {} = TriangularMatrix (fmap (\ (Nat n) -> n) d)
kind (Triangular :+: d :+: _ :+: _ :+: _ :+: _ :+: _ :+: _) (Prob.BasicTerms _ cs) = ConstructorBased cs (fmap (\ (Nat n) -> n) d)
kind (Triangular :+: d :+: _ :+: _ :+: _ :+: _ :+: _ :+: _) Prob.TermAlgebra {} = TriangularMatrix (fmap (\ (Nat n) -> n) d)
kind (Automaton :+: d :+: _ :+: _ :+: _ :+: _ :+: _ :+: _) (Prob.BasicTerms _ cs) = ConstructorEda cs (fmap (\ (Nat n) -> max 1 n) d)
kind (Automaton :+: d :+: _ :+: _ :+: _ :+: _ :+: _ :+: _) Prob.TermAlgebra {} = EdaMatrix (fmap (\ (Nat n) -> max 1 n) d)
mikind :: Domains (S.ArgumentsOf NaturalMI) -> NaturalMIKind
mikind (k :+: _ :+: _ :+: _ :+: _ :+: _ :+: _ :+: _) = k
bound :: Domains (S.ArgumentsOf NaturalMI) -> N.Size
bound (_ :+: _ :+: _ :+: Nat bnd :+: mbits :+: _ :+: _ :+: _ ) = case mbits of
Just (Nat b) -> N.Bits b
Nothing -> N.Bound bnd
cbits :: Domains (S.ArgumentsOf NaturalMI) -> Maybe N.Size
cbits (_ :+: _ :+: _ :+: _ :+: _ :+: b :+: _ :+: _) = do Nat n <- b
return $ N.Bits n
dim :: Domains (S.ArgumentsOf NaturalMI) -> Int
dim (_ :+: _ :+: Nat d :+: _ :+: _ :+: _ :+: _ :+: _) = d
isUargsOn :: Domains (S.ArgumentsOf NaturalMI) -> Bool
isUargsOn (_ :+: _ :+: _ :+: _ :+: _ :+: _ :+: ua :+: _) = ua
isUrulesOn :: Domains (S.ArgumentsOf NaturalMI) -> Bool
isUrulesOn (_ :+: _ :+: _ :+: _ :+: _ :+: _ :+: _ :+: ur) = ur
data MatrixDP = MWithDP | MNoDP deriving (Show,Eq)
kindConstraints :: Eq l => MatrixKind -> MatrixInter (DioPoly DioVar Int) -> DioFormula l DioVar Int
kindConstraints UnrestrictedMatrix _ = top
kindConstraints (TriangularMatrix Nothing) _ = top
kindConstraints (TriangularMatrix (Just deg)) absmi = diagOnesConstraints deg absmi
kindConstraints (ConstructorBased _ Nothing) _ = top
kindConstraints (ConstructorBased cs (Just deg)) absmi = diagOnesConstraints deg absmi'
where absmi' = absmi{interpretations = filterCs $ interpretations absmi}
filterCs = Map.filterWithKey (\f _ -> f `Set.member` cs)
kindConstraints (EdaMatrix Nothing) absmi = edaConstraints absmi
kindConstraints (EdaMatrix (Just deg)) absmi = idaConstraints deg absmi
kindConstraints (ConstructorEda cs mdeg) absmi =
rcConstraints (absmi' ds)
&& maybe (edaConstraints (absmi' cs)) (\ deg -> idaConstraints deg (absmi' cs)) mdeg
where ds = F.symbols (signature absmi) Set.\\ cs
absmi' fs = absmi{interpretations = filterFs fs $ interpretations absmi}
filterFs fs = Map.filterWithKey (\f _ -> f `Set.member` fs)
solveConstraint :: P.SolverM m =>
Prob.Problem
-> UsablePositions
-> MatrixKind
-> F.Signature
-> Domains (S.ArgumentsOf NaturalMI)
-> DioFormula MiniSatLiteral DioVar Int
-> m (OrientationProof MatrixOrder)
solveConstraint prob ua mk sig mp constraints =
catchException $
do let fml = toFormula (N.bound `liftM` cbits mp) (N.bound $ bound mp) constraints >>= SatSolver.addFormula
mi = abstractInterpretation mk (dim mp) sig :: MatrixInter (N.Size -> Int)
theMI <- P.minisatValue fml mi
return $ case theMI of
Nothing -> Incompatible
Just mv -> Order $ MatrixOrder (fmap (\x -> x $ bound mp) mv) mk (mikind mp) ua prob Nothing $ Set.toList $ Trs.definedSymbols $ Prob.trsComponents prob
-- formula :: DioFormula MiniSatLiteral DioVar Int -> IO (Either SatSolver.SatError (PropFormula MiniSatLiteral))
-- formula fml = run $ toFormula Nothing 3 fml
-- where run :: MiniSat r -> IO (Either SatSolver.SatError r)
-- run = SatSolver.runSolver
-- gt :: MatrixInter (DioPoly DioVar Int) -> Term -> Term -> DioFormula MiniSatLiteral DioVar Int
-- gt mi l r = interpretTerm mi l .>. interpretTerm mi r
solveConstraint' :: P.SolverM m =>
Prob.Problem
-> UsablePositions
-> MatrixKind
-> F.Signature
-> Domains (S.ArgumentsOf NaturalMI)
-> MatrixDP
-> Bool
-> Bool
-> MForm.MemoFormula arg MiniSatSolver MiniSatLiteral
-> DioFormula MiniSatLiteral DioVar Int
-> m (OrientationProof MatrixOrder)
solveConstraint' prob ua mk sig mp mdp allowAF allowUR mform dform = case mdp of
MWithDP -> solve initial mkOrder mform dform
where
mkOrder (mv SatSolver.:&: af SatSolver.:&: us) =
MatrixOrder { ordInter = fmap (\x -> x $ bound mp) mv
, param = mk
, miKind = mikind mp
, uargs = ua
, input = prob
, argFilter = if allowAF then Just af else Nothing
, usymbols = if allowUR then us else defaultUsymbols
}
initial = absmi SatSolver.:&: AFEnc.initial sig SatSolver.:&: UREnc.initialUsables prob
MNoDP -> solve initial mkOrder mform dform
where
mkOrder (mv) =
MatrixOrder { ordInter = fmap (\x -> x $ bound mp) mv
, param = mk
, miKind = mikind mp
, uargs = ua
, input = prob
, argFilter = Nothing
, usymbols = defaultUsymbols
}
initial = absmi
where
defaultUsymbols = Set.toList $ Trs.definedSymbols $ Prob.trsComponents prob
absmi = abstractInterpretation mk (dim mp) sig :: MatrixInter (N.Size -> Int)
solve :: SatSolver.Decoder e a => P.SolverM m => e -> ( e -> MatrixOrder) -> MForm.MemoFormula arg MiniSatSolver MiniSatLiteral -> DioFormula MiniSatLiteral DioVar Int -> m (OrientationProof MatrixOrder)
solve initial mkOrder memform dioform =
catchException $ do
let pform = do
pform1 <- MForm.toFormula memform
pform2 <- toFormula (N.bound `liftM` cbits mp) (N.bound $ bound mp) dioform
SatSolver.addFormula (pform1 && pform2)
mi <- P.minisatValue (pform) initial
return $ case mi of
Nothing -> Incompatible
Just o -> Order $ mkOrder o
orient :: P.SolverM m => P.SelectorExpression -> Prob.Problem -> Domains (S.ArgumentsOf NaturalMI) -> m (S.ProofOf NaturalMI)
orient rs prob mp = do
solveConstraint' prob ua mk sig mp mdp allowAF allowUR mform dform
where ua = usableArgsWhereApplicable (mdp == MWithDP) sig st uaOn strat allrules
mk = kind mp st
uaOn = isUargsOn mp
allowUR = isUrulesOn mp && Prob.isDPProblem prob
allowAF = mdp == MWithDP && allowUR
-- TODO: applicable together with urArgs?
d = dim mp
mdp = if Trs.isEmpty (Prob.strictTrs prob) && Prob.isDPProblem prob
then MWithDP
else MNoDP
sig = Prob.signature prob
st = Prob.startTerms prob
strat = Prob.strategy prob
trsrules = Prob.trsComponents prob
dprules = Prob.dpComponents prob
allrules = Prob.allComponents prob
absmi = abstractInterpretation mk d sig :: MatrixInter (DioPoly DioVar Int)
usable = if allowUR then UREnc.usable prob else const top
orientationConstraints =
bigAnd [usable (r) --> interpretTerm absmi (R.lhs r) .>=. (modify r $ interpretTerm absmi (R.rhs r)) | r <- Trs.rules trsrules]
&& bigAnd [interpretTerm absmi (R.lhs r) .>=. (modify r $ interpretTerm absmi (R.rhs r)) | r <- Trs.rules dprules]
&& RS.onSelectedRequire rs (\ _ r -> strictVar r .>. SR.zero)
where modify r inter = inter { constant = case constant inter of
Vector [] -> error "NaturalMI: zero-length vector in modify"
Vector (v:vs) -> Vector (v `SR.plus` strictVar r : vs)}
strictVar = restrictvar . Strict
dpChoice MWithDP _ u = safeRedpairConstraints sig ua u absmi
dpChoice MNoDP Prob.TermAlgebra {} _ = monotoneConstraints absmi
dpChoice MNoDP Prob.BasicTerms {} True = uargMonotoneConstraints ua absmi
dpChoice MNoDP Prob.BasicTerms {} False = monotoneConstraints absmi
validUsableRules :: MForm.MemoFormula MatArg MiniSatSolver MiniSatLiteral
validUsableRules = MForm.liftSat $ MForm.toFormula $ UREnc.validUsableRulesEncoding prob isUnfiltered
where isUnfiltered f i | allowAF = AFEnc.isInFilter f i
| otherwise = top
mform = validUsableRules
dform = (kindConstraint && dpConstraint && orientationConstraint && filteringConstraint)
where
kindConstraint = kindConstraints mk absmi
dpConstraint = dpChoice mdp st uaOn
orientationConstraint = orientationConstraints
filteringConstraint = filteringConstraints allowAF prob absmi
data Strict = Strict R.Rule deriving (Eq, Ord, Show, Typeable)
instance PropAtom Strict
data MatArg = Gt Term Term
| Gsq Term Term
| Eq Term Term
deriving (Eq, Ord, Show)
filteringConstraints :: (Eq l, Ord l, Show a) => AbstrOrdSemiring a (DioFormula l DioVar Int) => Bool -> Prob.Problem -> MatrixInter a -> DioFormula l DioVar Int
filteringConstraints allowAF prob absmi =
if allowAF then bigAnd $ constraint allargs else top
where
argsOf = concatMap (\f -> zip (cycle [f]) [1..F.arity (Prob.signature prob) f])
allfs = Set.toList $ Trs.functionSymbols $ Prob.allComponents prob
allargs = argsOf allfs
isNotZeroMatrix f i mi = fml
where
mxM = Map.lookup f (interpretations mi) >>= \l -> Map.lookup (V.Canon i) (coefficients l)
fml = case mxM of
Nothing -> error "Tct.Method.Matrix.NaturalMi.isInFilter: Undefined function index"
Just mx -> let entries = (\(n,m) -> [(k,l) | k <- [1 .. n], l <- [1 .. m]]) $ mdim mx in
notZero mx entries
notZero mx es = bigOr $ map (\(k,l) -> entry k l mx .>. SR.zero) es
constraint args = map (\(f,i) -> (atom (AFEnc.InFilter f i) <-> isNotZeroMatrix f i absmi)) args
uargMonotoneConstraints :: AbstrOrdSemiring a b => UsablePositions -> MatrixInter a -> b
uargMonotoneConstraints uarg = bigAnd . Map.mapWithKey funConstraint . interpretations
where funConstraint f = bigAnd . Map.map ((.>=. SR.one) . entry 1 1) . filterUargs f . coefficients
filterUargs f = Map.filterWithKey $ fun f
fun f (V.Canon i) _ = isUsable f i uarg
fun _ (V.User _) _ = error "Tct.Method.Matrix.NaturalMI.uargMonotoneConstraints: User variable in abstract interpretation"
monotoneConstraints :: AbstrOrdSemiring a b => MatrixInter a -> b
monotoneConstraints = bigAnd . Map.map (bigAnd . Map.map ((.>=. SR.one) . entry 1 1) . coefficients) . interpretations
safeRedpairConstraints :: AbstrOrdSemiring a b => F.Signature -> UsablePositions -> Bool -> MatrixInter a -> b
safeRedpairConstraints sig uarg uaOn = bigAnd . Map.mapWithKey funConstraint . compInterpretations
where compInterpretations = Map.filterWithKey isCompound . interpretations
isCompound f _ = F.isCompound sig f
funConstraint f = bigAnd . Map.map ((.>=. SR.one) . entry 1 1) . filterUargs f . coefficients
filterUargs f xs = if uaOn then Map.filterWithKey (fun f) xs else xs
fun f (V.Canon i) _ = isUsable f i uarg
fun _ (V.User _) _ = error "Tct.Method.Matrix.NaturalMI.safeRedPairConstraints: User variable in abstract interpretation"
slmiSafeRedpairConstraints :: (MIEntry a, AbstrOrdSemiring a b) => F.Signature -> UsablePositions -> MatrixInter a -> b
slmiSafeRedpairConstraints sig uarg mi = bigAnd $ Map.mapWithKey funConstraint $ compInterpretations mi
where compInterpretations = Map.filterWithKey isCompound . interpretations
isCompound f _ = F.isCompound sig f
d = dimension mi
funConstraint f = bigAnd . Map.map (.==. unit d) . filterUargs f . coefficients
filterUargs f = Map.filterWithKey $ fun f
fun f (V.Canon i) _ = isUsable f i uarg
fun _ (V.User _) _ = error "Tct.Method.Matrix.NaturalMI.slmiSafeRedPairConstraints: User variable in abstract interpretation"
positiveConstraints :: AbstrOrdSemiring a b => MatrixInter a -> b
positiveConstraints mi = positiveMatrices mi && positiveVectors mi
positiveMatrices :: AbstrOrdSemiring a b => MatrixInter a -> b
positiveMatrices = bigAnd . Map.map (bigAnd . Map.map (liftMatrix (bigAnd . map (liftVector bigAnd)) . fmap (.>=. SR.zero)) . coefficients) . interpretations
positiveVectors :: AbstrOrdSemiring a b => MatrixInter a -> b
positiveVectors = bigAnd . Map.map (liftVector bigAnd . fmap (.>=. SR.zero) . constant) . interpretations
checkDirect :: MatrixInter Int -> Trs.Trs -> Bool
checkDirect mi trs = strictTrsConstraints mi trs && monotoneConstraints mi
strictRules :: MatrixInter Int -> Trs.Trs -> Trs.Trs
strictRules mi = Trs.filterRules $ strictRuleConstraints mi
applyAss :: (Ord l, Eq l) => MatrixInter (N.NatFormula l) -> A.Assign l -> MatrixInter Int
applyAss mi ass = fmap (flip N.eval ass) mi
-- Fixing the number of ones in diagonals
data DiagOnesVar = DiagOnesVar Int
deriving (Eq, Ord, Show, Typeable)
instance PropAtom DiagOnesVar
diagOnesConstraints :: Eq l => Int -> MatrixInter (DioPoly DioVar Int) -> DioFormula l DioVar Int
diagOnesConstraints deg mi = diagOnesVars && maxDegree
where d = dimension mi
toD = [1..d]
diagOnesVars = bigAnd [ ((restrictvar $ DiagOnesVar x) .==. (SR.one :: DioPoly DioVar Int)) <-> f x | x <- toD ]
f x = bigOr $ map (bigOr . map (\ m -> entry x x m .>=. SR.one) . Map.elems . coefficients) $ Map.elems $ interpretations mi
maxDegree = (constToPoly deg :: DioPoly DioVar Int) .>=. SR.bigPlus [ restrictvar $ DiagOnesVar x | x <- toD ]
-- Automaton Stuff
-- Notation follows the 5-author CAI paper
data XdaVar = Gtwo Int Int Int Int
| R Int Int
| Done Int Int Int
| Dtwo Int Int Int
| Gthree Int Int Int Int Int Int
| T Int Int Int
| I Int Int
| J Int Int
| H Int Int -- first Argument: actual argument of h in the paper; second argument: height
deriving (Eq, Ord, Show, Typeable)
instance PropAtom XdaVar
dioAtom :: (PropAtom a, Eq l) => a -> DioFormula l DioVar Int
dioAtom = A . PAtom . PA . toDioVar
edaConstraints :: Eq l => MatrixInter (DioPoly DioVar Int) -> DioFormula l DioVar Int
edaConstraints mi = rConstraints mi && dConstraints mi && gtwoConstraints mi -- && goneConstraints mi
idaConstraints :: Eq l => Int -> MatrixInter (DioPoly DioVar Int) -> DioFormula l DioVar Int
idaConstraints deg mi = rConstraints mi && tConstraints mi && iConstraints mi && jConstraints mi && hConstraints deg mi && gThreeConstraints mi -- && edaConstraints mi
rcConstraints :: Eq l => MatrixInter (DioPoly DioVar Int) -> DioFormula l DioVar Int
rcConstraints mi = bigAnd [ ggeq mi 1 x --> dioAtom (R 1 x) | x <- toD ]
where d = dimension mi
toD = [1..d]
gtwoConstraints :: Eq l => MatrixInter (DioPoly DioVar Int) -> DioFormula l DioVar Int
gtwoConstraints mi = bigAnd [ f i j k l | i <- toD, j <- toD, k <- toD, l <- toD ]
where d = dimension mi
toD = [1..d]
f i j k l = (dioAtom $ Gtwo i j k l) <-> bigOr (map (bigOr . map (g i j k l) . Map.elems . coefficients) $ Map.elems $ interpretations mi)
g i j k l m = (entry i k m .>=. SR.one) && (entry j l m .>=. SR.one)
ggeq :: Eq l => MatrixInter (DioPoly DioVar Int) -> Int -> Int -> DioFormula l DioVar Int
ggeq mi i j = bigOr (map (bigOr . map (\ m -> entry i j m .>=. SR.one) . Map.elems . coefficients) $ Map.elems $ interpretations mi)
ggrt :: Eq l => MatrixInter (DioPoly DioVar Int) -> Int -> Int -> DioFormula l DioVar Int
ggrt mi i j = bigOr (map (bigOr . map (\ m -> entry i j m .>. SR.one) . Map.elems . coefficients) $ Map.elems $ interpretations mi)
gtwo :: Eq l => MatrixInter (DioPoly DioVar Int) -> Int -> Int -> Int -> Int -> DioFormula l DioVar Int
gtwo mi i j k l = bigOr (map (bigOr . map g . Map.elems . coefficients) $ Map.elems $ interpretations mi)
where g m = (entry i k m .>=. SR.one) && (entry j l m .>=. SR.one)
rConstraints :: Eq l => MatrixInter (DioPoly DioVar Int) -> DioFormula l DioVar Int
rConstraints mi = reflexivity && transitivity && compatibility && nocycle
where d = dimension mi
toD = [1..d]
reflexivity = bigAnd $ map (\ x -> dioAtom (R x x)) toD
transitivity = bigAnd [ (dioAtom (R x y) && dioAtom (R y z)) --> dioAtom (R x z) | x <- toD, y <- toD, z <- toD ]
compatibility = bigAnd [ ggeq mi x y --> dioAtom (R x y) | x <- toD, y <- toD ]
nocycle = bigAnd [ (dioAtom (R 1 y) && ggrt mi x y) --> not (dioAtom (R y x)) | x <- toD, y <- toD ]
dConstraints :: Eq l => MatrixInter (DioPoly DioVar Int) -> DioFormula l DioVar Int
dConstraints mi = foreapprox && forecompat && backapprox && backcompat && exactness
where d = dimension mi
toD = [1..d]
foreapprox = bigAnd [ dioAtom (R 1 x) --> dioAtom (Done x x x) | x <- toD ]
forecompat = bigAnd [ (dioAtom (Done i x y) && dioAtom (Gtwo x y z u)) --> dioAtom (Done i z u) | i <- toD, x <- toD, y <- toD, z <- toD, u <- toD ]
backapprox = bigAnd [ dioAtom (R 1 x) --> dioAtom (Dtwo x x x) | x <- toD ]
backcompat = bigAnd [ (dioAtom (Dtwo i x y) && dioAtom (Gtwo z u x y)) --> dioAtom (Dtwo i z u) | i <- toD, x <- toD, y <- toD, z <- toD, u <- toD ]
exactness = bigAnd [ if x == y then top else not (dioAtom (Done i x y) && dioAtom (Dtwo i x y)) | i <- toD, x <- toD, y <- toD ]
gThreeConstraints :: Eq l => MatrixInter (DioPoly DioVar Int) -> DioFormula l DioVar Int
gThreeConstraints mi = bigAnd [ f i j k x y z | i <- toD, j <- toD, k <- toD, x <- toD, y <- toD, z <- toD ]
where d = dimension mi
toD = [1..d]
f i j k x y z = (dioAtom $ Gthree i j k x y z) <-> bigOr (map (bigOr . map (g i j k x y z) . Map.elems . coefficients) $ Map.elems $ interpretations mi)
g i j k x y z m = (entry i x m .>=. SR.one) && (entry j y m .>=. SR.one) && (entry k z m .>=. SR.one)
gthree :: Eq l => MatrixInter (DioPoly DioVar Int) -> Int -> Int -> Int -> Int -> Int -> Int -> DioFormula l DioVar Int
gthree mi i j k x y z = bigOr (map (bigOr . map g . Map.elems . coefficients) $ Map.elems $ interpretations mi)
where g m = (entry i x m .>=. SR.one) && (entry j y m .>=. SR.one) && (entry k z m .>=. SR.one)
tConstraints :: Eq l => MatrixInter (DioPoly DioVar Int) -> DioFormula l DioVar Int
tConstraints mi = initial && gThreeStep
where d = dimension mi
toD = [1..d]
initial = bigAnd [ if x == y then top else (dioAtom (R 1 x) && dioAtom (R 1 y)) --> dioAtom (T x x y) | x <- toD, y <- toD ]
gThreeStep = bigAnd [ (dioAtom (T x y z) && dioAtom (Gthree x y z u v w)) --> dioAtom (T u v w) | x <- toD, y <- toD, z <- toD, u <- toD, v <- toD, w <- toD ]
iConstraints :: Eq l => MatrixInter (DioPoly DioVar Int) -> DioFormula l DioVar Int
iConstraints mi = bigAnd [ if x == y then Top else dioAtom (T x y y) --> dioAtom (I x y) | x <- toD, y <- toD ]
where d = dimension mi
toD = [1..d]
jConstraints :: Eq l => MatrixInter (DioPoly DioVar Int) -> DioFormula l DioVar Int
jConstraints mi = bigAnd [ f i j | i <- toD, j <- toD ]
where d = dimension mi
toD = [1..d]
f i j = dioAtom (J i j) <-> bigOr (map (\ k -> dioAtom (I i k) && dioAtom (R k j)) toD)
hConstraints :: Eq l => Int -> MatrixInter (DioPoly DioVar Int) -> DioFormula l DioVar Int
hConstraints deg mi = unaryNotation && jDecrease
where d = dimension mi
toD = [1..d]
unaryNotation = bigAnd [ dioAtom (H x h) --> dioAtom (H x (h - 1)) | x <- toD, h <- [2..deg - 1] ]
jDecrease = bigAnd [ f i j | i <- toD, j <- toD ]
f i j = dioAtom (J i j) --> bigOr (map (\ h -> dioAtom (H i h) && not (dioAtom $ H j h)) [1..deg - 1])
-- Instance declarations
class MIEntry a
instance MIEntry Int
instance MIEntry (DioPoly DioVar Int)
instance MIEntry (DioFormula l DioVar Int)
instance MIEntry a => MIEntry (Vector a)
instance (AbstrEq a b, MIEntry a) => AbstrEq (Vector a) b where
(Vector vs) .==. (Vector ws) = bigAnd $ zipWith (.==.) vs ws
instance (AbstrOrd a b, MIEntry a) => AbstrOrd (Vector a) b where
(Vector []) .<. _ = bot
_ .<. (Vector []) = bot
(Vector (v:vs)) .<. (Vector (w:ws)) = (v .<. w) && (Vector vs .<=. Vector ws)
(Vector vs) .<=. (Vector ws) = bigAnd $ zipWith (.<=.) vs ws
instance (AbstrEq a b, MIEntry a) => AbstrEq (Matrix a) b where
(Matrix vs) .==. (Matrix ws) = (Vector vs) .==. (Vector ws)
instance (AbstrOrd a b, MIEntry a) => AbstrOrd (Matrix a) b where
(Matrix vs) .<. (Matrix ws) = (Vector vs) .<. (Vector ws)
(Matrix vs) .<=. (Matrix ws) = (Vector vs) .<=. (Vector ws)
instance (AbstrEq a b, MIEntry a) => AbstrEq (LInter a) b where
(LI lcoeffs lconst) .==. (LI rcoeffs rconst) = bigAnd (Map.elems zipmaps) && lconst .==. rconst
where zipmaps = Map.intersectionWith (.==.) lcoeffs rcoeffs
instance (AbstrOrd a b, MIEntry a) => AbstrOrd (LInter a) b where
(LI lcoeffs lconst) .<. (LI rcoeffs rconst) = bigAnd (Map.elems zipmaps) && lconst .<. rconst
where zipmaps = Map.intersectionWith (.<=.) lcoeffs rcoeffs
(LI lcoeffs lconst) .<=. (LI rcoeffs rconst) = bigAnd (Map.elems zipmaps) && lconst .<=. rconst
where zipmaps = Map.intersectionWith (.<=.) lcoeffs rcoeffs
instance (Ord l, SatSolver.Solver s l) => MSemiring s l (N.NatFormula l) DioVar Int where
plus = N.mAddNO
prod = N.mTimesNO
zero = N.natToFormula 0
one = N.natToFormula 1
geq = N.mGeq
grt = N.mGrt
equ = N.mEqu
constToFormula = N.natToFormula
formAtom = N.natAtomM . N.Bound
truncFormTo = N.mTruncTo
padFormTo n f = N.padBots (max n l - l) f
where l = length f
instance SatSolver.Decoder (MatrixInter (N.Size -> Int)) (N.PLVec DioVar) where
add (N.PLVec (DioVar y) k) mi = case cast y of
Nothing -> mi
Just x -> mi{interpretations = Map.adjust newli fun (interpretations mi)}
where newli li | pos == 0 = li{constant = adjustv newval i (constant li)}
newli li | otherwise = li{coefficients = newli' li}
newli' li = Map.adjust newm (V.Canon pos) (coefficients li)
newm = adjustm newval i j
newval old n = old n + (2 ^ ((if r then 1 else N.bits n) - k))
r = restrict x
fun = varfun x
pos = argpos x
i = varrow x
j = varcol x
|
mzini/TcT
|
source/Tct/Method/Matrix/NaturalMI.hs
|
gpl-3.0
| 38,635 | 1 | 23 | 12,257 | 11,625 | 5,942 | 5,683 | -1 | -1 |
import System.Environment
import Data.List (sort) -- using sort as the internal bucket sorting algorithm
flatten :: [[a]] -> [a]
flatten xs = (\z n -> foldr (\x y -> foldr z y x) n xs) (:) []
bucketSort :: (RealFrac a, Ord a) => [a] -> Integer -> [a]
bucketSort [] _ = []
bucketSort array bucketSize = flatten $ map sort buckets
where
buckets = [filter (\x -> (getBucketIdx x arMin bucketSize) == i) array | i <- [0..nBuckets]]
nBuckets = (floor (arMax - arMin)) `div` bucketSize + 1
arMax = maximum array
arMin = minimum array
getBucketIdx :: (RealFrac a) => a -> a -> Integer -> Integer
getBucketIdx _ _ 0 = error "num buckets is 0?!"
getBucketIdx num min bucketSize = (floor (num - min)) `div` bucketSize
main :: IO ()
main = getArgs >>= \args -> print $ bucketSort (map (\x-> read x :: Float) (tail args)) (read (head args) :: Integer)
|
Jecoms/cosmos
|
code/sorting/bucket_sort/bucket_sort.hs
|
gpl-3.0
| 1,013 | 0 | 13 | 330 | 395 | 212 | 183 | 16 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
module Coala
( Filename(Filename)
, coala
, coalaIO
, Result (..)
, Severity (..)
, Line (..)
, Column (..)
, Affect (..)
, CodeRef (line, column)
, codeRef
, codeRefLine
, codeRefInLine
, FileRef
, filename
, RefPoint
, (-->)
, (-+>)
) where
import Prelude hiding ( getContents, putStr )
import Data.ByteString.Lazy ( putStr, ByteString, getContents )
import Data.Text ( Text, empty )
import Data.Aeson ( ToJSON, toJSON, object, (.=), Value , encode )
import Data.Maybe ( fromJust )
import Data.Tuple ( swap )
newtype Filename = Filename String deriving ( Eq, Show )
coala :: String -> (ByteString -> Maybe a) -> (a -> [Result]) -> IO ()
coala bearname reader bear = do
c <- getContents
putStr $ encode $ encodeResults bearname $ bear $ fromJust $ reader c
coalaIO :: String -> (ByteString -> Maybe a) -> (a -> IO [Result]) -> IO ()
coalaIO bearname reader bear = do
c <- getContents
res <- bear $ fromJust $ reader c
putStr $ encode $ encodeResults bearname res
data Severity = Info | Normal | Major deriving ( Show, Eq, Ord )
severityToInt :: Severity -> Int
severityToInt s = case s of
Info -> 0
Normal -> 1
Major -> 2
newtype Line = Line Int deriving ( Show, Eq )
newtype Column = Column Int deriving ( Show, Eq )
data Affect = Affect { start :: CodeRef
, end :: CodeRef
} deriving ( Eq, Show )
data CodeRef = CodeRef { file :: Filename
, line :: Line
, column :: Maybe Column
} deriving (Eq, Show)
data Result = Result { severity :: Severity
, message :: String
, affected :: [Affect]
} deriving (Eq, Show)
codeRef fn (sl,sc) (el, ec) = Affect (CodeRef fn sl sc) (CodeRef fn el ec)
codeRefInLine :: Filename -> Line -> Maybe Column -> (Int -> Int) -> Affect
codeRefInLine fn sl sc f = Affect (CodeRef fn sl sc) (CodeRef fn sl (sc >>= \c -> Just $ columnMap f c))
codeRefLine fn sl = Affect (CodeRef fn sl Nothing) (CodeRef fn sl Nothing)
lineMap f (Line a) = Line $ f a
columnMap f (Column a) = Column $ f a
class RefPoint a where
(-->) :: a -> a -> (Filename -> Affect)
(-+>) :: a -> Int -> (Filename -> Affect)
instance RefPoint Line where
from --> to = \fn -> codeRef fn (from, Nothing) (to, Nothing)
from -+> to = \fn -> codeRef fn (from, Nothing) (lineMap (to +) from, Nothing)
instance RefPoint (Line, Column) where
from --> to = \fn -> codeRef fn (fst from, Just $ snd from) (fst to, Just $ snd to)
from -+> to = \fn -> codeRefInLine fn (fst from) (Just $ snd from) (to +)
instance RefPoint (Line, Maybe Column) where
from --> to = \fn -> codeRef fn from to
from -+> to = \fn -> uncurry (codeRefInLine fn) from (to +)
instance RefPoint (Column, Line) where
from --> to = swap from --> swap to
from -+> to = swap from -+> to
instance RefPoint (Maybe Column, Line) where
from --> to = swap from --> swap to
from -+> to = swap from -+> to
class FileRef a where
filename :: a -> Filename
instance FileRef CodeRef where
filename = file
instance ToJSON Severity where
toJSON sev = toJSON $ severityToInt sev
instance ToJSON Filename where
toJSON (Filename fn) = toJSON fn
instance ToJSON Line where
toJSON (Line l) = toJSON l
instance ToJSON Column where
toJSON (Column c) = toJSON c
instance ToJSON CodeRef where
toJSON ref = object [
"file" .= file ref
, "line" .= line ref
, "column" .= column ref
]
instance ToJSON Affect where
toJSON affect = let s = start affect
e = end affect
in object [
"file" .= if file s == file e
then file s
else Filename ""
, "start" .= s
, "end" .= e
]
encodeResult :: String -> Result -> Value
encodeResult bearname r = object [
"message" .= message r
, "origin" .= bearname
, "debug_msg" .= empty
, "additional_info" .= empty
, "severity" .= severity r
, "affected_code" .= affected r
]
encodeResults :: String -> [Result] -> Value
encodeResults bearname rs = object [
"results" .= map (encodeResult bearname) rs
]
|
maweki/coalaHs
|
src/Coala.hs
|
gpl-3.0
| 4,471 | 0 | 13 | 1,372 | 1,653 | 879 | 774 | 121 | 3 |
-- UUAGC 0.9.52.1 (Helium/Syntax/UHA_Syntax.ag)
module Helium.Syntax.UHA_Syntax where
-- Alternative -------------------------------------------------
data Alternative = Alternative_Hole (Range) (Integer)
| Alternative_Feedback (Range) (String) (Alternative)
| Alternative_Alternative (Range) (Pattern) (RightHandSide)
| Alternative_Empty (Range)
-- Alternatives ------------------------------------------------
type Alternatives = [Alternative]
-- AnnotatedType -----------------------------------------------
data AnnotatedType = AnnotatedType_AnnotatedType (Range) (Bool) (Type)
-- AnnotatedTypes ----------------------------------------------
type AnnotatedTypes = [AnnotatedType]
-- Body --------------------------------------------------------
data Body = Body_Hole (Range) (Integer)
| Body_Body (Range) (ImportDeclarations) (Declarations)
-- Constructor -------------------------------------------------
data Constructor = Constructor_Constructor (Range) (Name) (AnnotatedTypes)
| Constructor_Infix (Range) (AnnotatedType) (Name) (AnnotatedType)
| Constructor_Record (Range) (Name) (FieldDeclarations)
-- Constructors ------------------------------------------------
type Constructors = [Constructor]
-- ContextItem -------------------------------------------------
data ContextItem = ContextItem_ContextItem (Range) (Name) (Types)
-- ContextItems ------------------------------------------------
type ContextItems = [ContextItem]
-- Declaration -------------------------------------------------
data Declaration = Declaration_Hole (Range) (Integer)
| Declaration_Type (Range) (SimpleType) (Type)
| Declaration_Data (Range) (ContextItems) (SimpleType) (Constructors) (Names)
| Declaration_Newtype (Range) (ContextItems) (SimpleType) (Constructor) (Names)
| Declaration_Class (Range) (ContextItems) (SimpleType) (MaybeDeclarations)
| Declaration_Instance (Range) (ContextItems) (Name) (Types) (MaybeDeclarations)
| Declaration_Default (Range) (Types)
| Declaration_FunctionBindings (Range) (FunctionBindings)
| Declaration_PatternBinding (Range) (Pattern) (RightHandSide)
| Declaration_TypeSignature (Range) (Names) (Type)
| Declaration_Fixity (Range) (Fixity) (MaybeInt) (Names)
| Declaration_Empty (Range)
-- Declarations ------------------------------------------------
type Declarations = [Declaration]
-- Export ------------------------------------------------------
data Export = Export_Variable (Range) (Name)
| Export_TypeOrClass (Range) (Name) (MaybeNames)
| Export_TypeOrClassComplete (Range) (Name)
| Export_Module (Range) (Name)
-- Exports -----------------------------------------------------
type Exports = [Export]
-- Expression --------------------------------------------------
data Expression = Expression_Hole (Range) (Integer)
| Expression_Feedback (Range) (String) (Expression)
| Expression_MustUse (Range) (Expression)
| Expression_Literal (Range) (Literal)
| Expression_Variable (Range) (Name)
| Expression_Constructor (Range) (Name)
| Expression_Parenthesized (Range) (Expression)
| Expression_NormalApplication (Range) (Expression) (Expressions)
| Expression_InfixApplication (Range) (MaybeExpression) (Expression) (MaybeExpression)
| Expression_If (Range) (Expression) (Expression) (Expression)
| Expression_Lambda (Range) (Patterns) (Expression)
| Expression_Case (Range) (Expression) (Alternatives)
| Expression_Let (Range) (Declarations) (Expression)
| Expression_Do (Range) (Statements)
| Expression_List (Range) (Expressions)
| Expression_Tuple (Range) (Expressions)
| Expression_Comprehension (Range) (Expression) (Qualifiers)
| Expression_Typed (Range) (Expression) (Type)
| Expression_RecordConstruction (Range) (Name) (RecordExpressionBindings)
| Expression_RecordUpdate (Range) (Expression) (RecordExpressionBindings)
| Expression_Enum (Range) (Expression) (MaybeExpression) (MaybeExpression)
| Expression_Negate (Range) (Expression)
| Expression_NegateFloat (Range) (Expression)
-- Expressions -------------------------------------------------
type Expressions = [Expression]
-- FieldDeclaration --------------------------------------------
data FieldDeclaration = FieldDeclaration_FieldDeclaration (Range) (Names) (AnnotatedType)
-- FieldDeclarations -------------------------------------------
type FieldDeclarations = [FieldDeclaration]
-- Fixity ------------------------------------------------------
data Fixity = Fixity_Infixl (Range)
| Fixity_Infixr (Range)
| Fixity_Infix (Range)
-- FunctionBinding ---------------------------------------------
data FunctionBinding = FunctionBinding_Hole (Range) (Integer)
| FunctionBinding_Feedback (Range) (String) (FunctionBinding)
| FunctionBinding_FunctionBinding (Range) (LeftHandSide) (RightHandSide)
-- FunctionBindings --------------------------------------------
type FunctionBindings = [FunctionBinding]
-- GuardedExpression -------------------------------------------
data GuardedExpression = GuardedExpression_GuardedExpression (Range) (Expression) (Expression)
-- GuardedExpressions ------------------------------------------
type GuardedExpressions = [GuardedExpression]
-- Import ------------------------------------------------------
data Import = Import_Variable (Range) (Name)
| Import_TypeOrClass (Range) (Name) (MaybeNames)
| Import_TypeOrClassComplete (Range) (Name)
-- ImportDeclaration -------------------------------------------
data ImportDeclaration = ImportDeclaration_Import (Range) (Bool) (Name) (MaybeName) (MaybeImportSpecification)
| ImportDeclaration_Empty (Range)
-- ImportDeclarations ------------------------------------------
type ImportDeclarations = [ImportDeclaration]
-- ImportSpecification -----------------------------------------
data ImportSpecification = ImportSpecification_Import (Range) (Bool) (Imports)
-- Imports -----------------------------------------------------
type Imports = [Import]
-- LeftHandSide ------------------------------------------------
data LeftHandSide = LeftHandSide_Function (Range) (Name) (Patterns)
| LeftHandSide_Infix (Range) (Pattern) (Name) (Pattern)
| LeftHandSide_Parenthesized (Range) (LeftHandSide) (Patterns)
-- Literal -----------------------------------------------------
data Literal = Literal_Int (Range) (String)
| Literal_Char (Range) (String)
| Literal_Float (Range) (String)
| Literal_String (Range) (String)
-- MaybeDeclarations -------------------------------------------
data MaybeDeclarations = MaybeDeclarations_Nothing
| MaybeDeclarations_Just (Declarations)
-- MaybeExports ------------------------------------------------
data MaybeExports = MaybeExports_Nothing
| MaybeExports_Just (Exports)
-- MaybeExpression ---------------------------------------------
data MaybeExpression = MaybeExpression_Nothing
| MaybeExpression_Just (Expression)
-- MaybeImportSpecification ------------------------------------
data MaybeImportSpecification = MaybeImportSpecification_Nothing
| MaybeImportSpecification_Just (ImportSpecification)
-- MaybeInt ----------------------------------------------------
data MaybeInt = MaybeInt_Nothing
| MaybeInt_Just (Int)
-- MaybeName ---------------------------------------------------
data MaybeName = MaybeName_Nothing
| MaybeName_Just (Name)
-- MaybeNames --------------------------------------------------
data MaybeNames = MaybeNames_Nothing
| MaybeNames_Just (Names)
-- Module ------------------------------------------------------
data Module = Module_Module (Range) (MaybeName) (MaybeExports) (Body)
-- Name --------------------------------------------------------
data Name = Name_Identifier (Range) (Strings) (String)
| Name_Operator (Range) (Strings) (String)
| Name_Special (Range) (Strings) (String)
-- Names -------------------------------------------------------
type Names = [Name]
-- Pattern -----------------------------------------------------
data Pattern = Pattern_Hole (Range) (Integer)
| Pattern_Literal (Range) (Literal)
| Pattern_Variable (Range) (Name)
| Pattern_Constructor (Range) (Name) (Patterns)
| Pattern_Parenthesized (Range) (Pattern)
| Pattern_InfixConstructor (Range) (Pattern) (Name) (Pattern)
| Pattern_List (Range) (Patterns)
| Pattern_Tuple (Range) (Patterns)
| Pattern_Record (Range) (Name) (RecordPatternBindings)
| Pattern_Negate (Range) (Literal)
| Pattern_As (Range) (Name) (Pattern)
| Pattern_Wildcard (Range)
| Pattern_Irrefutable (Range) (Pattern)
| Pattern_Successor (Range) (Name) (Literal)
| Pattern_NegateFloat (Range) (Literal)
-- Patterns ----------------------------------------------------
type Patterns = [Pattern]
-- Position ----------------------------------------------------
data Position = Position_Position (String) (Int) (Int)
| Position_Unknown
-- Qualifier ---------------------------------------------------
data Qualifier = Qualifier_Guard (Range) (Expression)
| Qualifier_Let (Range) (Declarations)
| Qualifier_Generator (Range) (Pattern) (Expression)
| Qualifier_Empty (Range)
-- Qualifiers --------------------------------------------------
type Qualifiers = [Qualifier]
-- Range -------------------------------------------------------
data Range = Range_Range (Position) (Position)
-- RecordExpressionBinding -------------------------------------
data RecordExpressionBinding = RecordExpressionBinding_RecordExpressionBinding (Range) (Name) (Expression)
-- RecordExpressionBindings ------------------------------------
type RecordExpressionBindings = [RecordExpressionBinding]
-- RecordPatternBinding ----------------------------------------
data RecordPatternBinding = RecordPatternBinding_RecordPatternBinding (Range) (Name) (Pattern)
-- RecordPatternBindings ---------------------------------------
type RecordPatternBindings = [RecordPatternBinding]
-- RightHandSide -----------------------------------------------
data RightHandSide = RightHandSide_Expression (Range) (Expression) (MaybeDeclarations)
| RightHandSide_Guarded (Range) (GuardedExpressions) (MaybeDeclarations)
-- SimpleType --------------------------------------------------
data SimpleType = SimpleType_SimpleType (Range) (Name) (Names)
-- Statement ---------------------------------------------------
data Statement = Statement_Expression (Range) (Expression)
| Statement_Let (Range) (Declarations)
| Statement_Generator (Range) (Pattern) (Expression)
| Statement_Empty (Range)
-- Statements --------------------------------------------------
type Statements = [Statement]
-- Strings -----------------------------------------------------
type Strings = [(String)]
-- Type --------------------------------------------------------
data Type = Type_Application (Range) (Bool) (Type) (Types)
| Type_Variable (Range) (Name)
| Type_Constructor (Range) (Name)
| Type_Qualified (Range) (ContextItems) (Type)
| Type_Forall (Range) (Names) (Type)
| Type_Exists (Range) (Names) (Type)
| Type_Parenthesized (Range) (Type)
-- Types -------------------------------------------------------
type Types = [Type]
|
roberth/uu-helium
|
src/Helium/Syntax/UHA_Syntax.hs
|
gpl-3.0
| 12,231 | 0 | 7 | 2,260 | 2,272 | 1,410 | 862 | 148 | 0 |
module Surfaces where
import Data.List (foldl')
import Types
mixColors :: (Float -> Float -> Float) -> Color -> Color -> Color
mixColors f (Color r0 g0 b0) (Color r1 g1 b1) = Color (f r0 r1) (f g0 g1) (f b0 b1)
{-# INLINE mixColors #-}
scaleColor :: (Float -> Float) -> Color -> Color
scaleColor f (Color r g b) = Color (f r) (f g) (f b)
{-# INLINE scaleColor #-}
avgColors :: [Color] -> Color
avgColors cs = let mixed = foldl' (mixColors (+)) (Color 0 0 0) cs
in scaleColor (/ fromIntegral (length cs)) mixed
{-# INLINE avgColors #-}
{- smart constructor that applies e^-ln to the attenuation constants -}
makeMaterial :: Color -> Color -> Float -> Float -> Float -> Color -> Material
makeMaterial diffuse specular phong reflIx refrIx atten =
Material diffuse specular phong reflIx refrIx (scaleColor log atten)
|
jrraymond/ray-tracer
|
src/Surfaces.hs
|
gpl-3.0
| 837 | 0 | 11 | 170 | 319 | 166 | 153 | 16 | 1 |
oddOrEven :: [Num] -> String
oddOrEven xs = if odd $ sum xs then "odd" else "even"
|
yannxia-self/code-war-hasekell-training
|
odd_or_even.hs
|
gpl-3.0
| 82 | 0 | 7 | 16 | 36 | 19 | 17 | 2 | 2 |
elementAt :: [a] -> Int -> a
elementAt [] n = error "Empty list or n greater than the size of the list"
elementAt (x : xs) n = if n < 0
then error "The second argument must be positive or equal to zero"
else if n == 0 then x else elementAt xs (n - 1)
|
dannywillems/99-problems
|
haskell/p03.hs
|
gpl-3.0
| 298 | 0 | 9 | 105 | 88 | 46 | 42 | 5 | 3 |
-- Module to manipulate uploaded files.
module Upload
( MimeSortedFiles (..),
uploadDir,
mimeSort,
cacheFile,
uncacheFile,
)
where
import Control.Monad (foldM)
import Control.Monad.IO.Class (MonadIO (..))
import Data.Aeson (ToJSON (..), genericToEncoding, genericToJSON)
import Data.Default (Default (..))
import Data.HashSet (HashSet)
import qualified Data.HashSet as HS
import Data.List (isInfixOf)
import GHC.Generics (Generic)
import JSON (jsonOptions)
import System.Process (readProcess)
-- Uploaded files, sorted by types.
data MimeSortedFiles = MimeSortedFiles
{ pubImages :: HashSet FilePath,
pubExecutables :: HashSet FilePath,
pubVideos :: HashSet FilePath,
pubArchives :: HashSet FilePath,
pubAudios :: HashSet FilePath,
pubTexts :: HashSet FilePath,
pubPapers :: HashSet FilePath,
pubUnknown :: HashSet FilePath
}
deriving (Eq, Generic, Show)
instance Default MimeSortedFiles where
def = MimeSortedFiles HS.empty HS.empty HS.empty HS.empty HS.empty HS.empty HS.empty HS.empty
instance ToJSON MimeSortedFiles where
toEncoding = genericToEncoding jsonOptions
toJSON = genericToJSON jsonOptions
-- Directory in which to store uploaded files.
uploadDir :: FilePath
uploadDir = "media/uploads"
-- FIXME: see #6, which is a workaround
-- Returns the mime of the input file.
readMime :: (MonadIO m) => FilePath -> m String
readMime path = liftIO $ readProcess "file" ["--mime-type", "-b", "-h", path] ""
-- Sort a list of files by mime and store them in a `MimeSortedFiles` value.
mimeSort :: (MonadIO m) => [FilePath] -> m MimeSortedFiles
mimeSort = foldM (flip cacheFile) def
-- Cache a new file in the list of mime-sorted files.
cacheFile :: (MonadIO m) => FilePath -> MimeSortedFiles -> m MimeSortedFiles
cacheFile path sortedFiles = do
mime <- readMime path
pure $ mimeDispatch mime sortedFiles (HS.insert path)
-- Uncache a file from the list of mime-sorted files.
uncacheFile :: (MonadIO m) => FilePath -> MimeSortedFiles -> m MimeSortedFiles
uncacheFile path sortedFiles = do
mime <- readMime path
pure $ mimeDispatch mime sortedFiles (HS.delete path)
-- Dispatch a function based on the mime of an input file path.
mimeDispatch :: String -> MimeSortedFiles -> (HashSet FilePath -> HashSet FilePath) -> MimeSortedFiles
mimeDispatch mime sortedFiles f
| isImage mime = sortedFiles {pubImages = f (pubImages sortedFiles)}
| isExecutable mime = sortedFiles {pubExecutables = f (pubExecutables sortedFiles)}
| isVideo mime = sortedFiles {pubVideos = f (pubVideos sortedFiles)}
| isArchive mime = sortedFiles {pubArchives = f (pubArchives sortedFiles)}
| isAudio mime = sortedFiles {pubAudios = f (pubAudios sortedFiles)}
| isText mime = sortedFiles {pubTexts = f (pubTexts sortedFiles)}
| isPaper mime = sortedFiles {pubPapers = f (pubPapers sortedFiles)}
| otherwise = sortedFiles {pubUnknown = f (pubUnknown sortedFiles)}
where
isImage = isInfixOf "image"
isExecutable = isInfixOf "exec"
isVideo = isInfixOf "video"
isArchive = isInfixOf "zip"
isAudio m = isInfixOf "audio" m || isInfixOf "ogg" m || isInfixOf "octet-stream" m
isText = isInfixOf "text"
isPaper = isInfixOf "pdf"
|
phaazon/phaazon.net
|
backend/src/Upload.hs
|
gpl-3.0
| 3,214 | 0 | 11 | 557 | 902 | 477 | 425 | 62 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
module Sara.Z3.Verifier ( verify ) where
import Sara.Errors as E
import Sara.Ast.AstUtils
import Sara.Z3.AstWrapper
import Sara.Z3.SymbolicExecutor
import Control.Monad.Except
import Control.Monad.Writer
import qualified Sara.Z3.ProofPart as P
import Sara.Z3.Pretty ( prettyRender )
import Sara.Z3.CodeGenerator ( codegen )
import Sara.Ast.Meta
import Sara.Z3.Declarations
import Z3.Monad
generateProofParts :: MonadZ3 m => PureCheckerProgram -> m [P.ProofPart]
generateProofParts prog = do
execWriterT (mapMDeclarations_ symbolicExecuteDecl prog)
setParams :: MonadZ3 m => m ()
setParams = do
params <- mkParams
mbqi <- mkStringSymbol "mbqi"
paramsSetBool params mbqi False
solverSetParams params
s <- paramsToString params
liftIO $ putStrLn s
verify :: MonadZ3 m => PureCheckerProgram -> ExceptT Error m ()
verify prog = do
setParams
let contracts = translateContracts prog
proofParts <- generateProofParts prog
let proofParts' = map (P.substituteFuncs contracts) proofParts
let funcDefs = translateFuncDefs contracts prog
mapM_ (\funcDef -> liftIO $ putStrLn $ "funcDef:\n" ++ prettyRender funcDef) funcDefs
mapM_ (assert <=< codegen) funcDefs
mapM_ verifyProofPart proofParts'
verifyProofPart :: MonadZ3 m => P.ProofPart -> ExceptT Error m ()
verifyProofPart [email protected]{..} = local $ do
liftIO $ putStrLn $ "assumption:\n" ++ prettyRender (runAst assumption)
assert =<< codegen (runAst assumption)
liftIO $ putStrLn $ "proof obligation:\n" ++ prettyRender (runAst proofObligation)
assert =<< mkNot =<< codegen (runAst proofObligation)
so <- solverToString
liftIO $ putStrLn $ "solver:\n" ++ so
res <- lift $ withModel $ \model -> do
failure <- P.findFailure model p
m <- modelToString model
liftIO $ putStrLn $ "model:\n" ++ m
so <- solverToString
liftIO $ putStrLn $ "solver:\n" ++ so
return failure
case res of
(Sat, Just (Just e)) -> throwError e
(Sat, Just Nothing) -> error "There was a failure, but we were not able to find it in the model."
(Sat, Nothing) -> error "Satisfiable, but no model attached."
(Unsat, _) -> return ()
(Undef, _) -> unsolvableError startType startPos
|
Lykos/Sara
|
src/lib/Sara/Z3/Verifier.hs
|
gpl-3.0
| 2,280 | 0 | 15 | 423 | 709 | 350 | 359 | 57 | 5 |
module OutOfTheYards.Content.Normalize (normalizeUrls) where
import Hakyll
import qualified Network.URL as URL
import Text.XML.Light
import System.FilePath (dropFileName)
-- Map an attribute transformation function over all nodes in a document.
mapAttrs :: (QName -> Attr -> Attr) -> Content -> Content
mapAttrs f c = case c of
Elem e -> Elem $ Element
{ elName = elName e
, elAttribs = map (f $ elName e) (elAttribs e)
, elContent = map (mapAttrs f) $ elContent e
, elLine = elLine e
}
_ -> c
-- Transform a node's attribute based on the node's tag name
-- and the value of the attribute. This is applied to all
-- attributes / tags in the XML document.
normalizeImageSrc :: String -> QName -> Attr -> Attr
normalizeImageSrc prefix tagName attr =
if qName tagName == "img" && (qName . attrKey) attr == "src"
then
let isRelative :: String -> Bool
isRelative s = case URL.importURL s of
Nothing -> False
Just url -> case URL.url_type url of
URL.PathRelative -> True
_ -> False
srcUrl = attrVal attr
rootedUrl = if isRelative srcUrl
then "/" ++ prefix ++ srcUrl
else srcUrl
in Attr
{ attrKey = attrKey attr
, attrVal = rootedUrl
}
else attr
-- Transform all relative URLs to be absolute rooted URLs.
normalizeUrls :: Context String -> Item String -> Compiler (Item String)
normalizeUrls ctx item = do
maybeRoute <- getRoute (itemIdentifier item)
return $ case maybeRoute of
Nothing -> item
Just route ->
let prefix = dropFileName route
t = concatMap showContent
. map (mapAttrs $ normalizeImageSrc prefix)
. parseXML
in Item
{ itemBody = t $ itemBody item
, itemIdentifier = itemIdentifier item
}
|
justinmanley/outoftheyards
|
src/OutOfTheYards/Content/Normalize.hs
|
gpl-3.0
| 2,034 | 0 | 20 | 716 | 498 | 258 | 240 | 43 | 5 |
module Hadolint.Lint
( lintIO,
lint,
analyze,
LintOptions (..),
ErrorRule,
WarningRule,
InfoRule,
StyleRule,
IgnoreRule,
TrustedRegistry,
)
where
import qualified Control.Parallel.Strategies as Parallel
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Sequence as Seq
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Hadolint.Formatter.Format as Format
import qualified Hadolint.Process
import qualified Hadolint.Rule
import qualified Language.Docker as Docker
import Language.Docker.Parser (DockerfileError, Error)
import Language.Docker.Syntax (Dockerfile)
type ErrorRule = Hadolint.Rule.RuleCode
type WarningRule = Hadolint.Rule.RuleCode
type InfoRule = Hadolint.Rule.RuleCode
type StyleRule = Hadolint.Rule.RuleCode
type IgnoreRule = Hadolint.Rule.RuleCode
type TrustedRegistry = Text
data LintOptions = LintOptions
{ errorRules :: [ErrorRule],
warningRules :: [WarningRule],
infoRules :: [InfoRule],
styleRules :: [StyleRule],
ignoreRules :: [IgnoreRule],
rulesConfig :: Hadolint.Process.RulesConfig,
failThreshold :: Hadolint.Rule.DLSeverity
}
deriving (Show)
instance Semigroup LintOptions where
LintOptions a1 a2 a3 a4 a5 a6 a7 <> LintOptions b1 b2 b3 b4 b5 b6 b7 =
LintOptions
(a1 <> b1)
(a2 <> b2)
(a3 <> b3)
(a4 <> b4)
(a5 <> b5)
(a6 <> b6)
(a7 <> b7)
instance Monoid LintOptions where
mempty = LintOptions mempty mempty mempty mempty mempty mempty mempty
-- | Performs the process of parsing the dockerfile and analyzing it with all the applicable
-- rules, depending on the list of ignored rules.
lintIO :: LintOptions -> NonEmpty.NonEmpty FilePath -> IO (NonEmpty.NonEmpty (Format.Result Text DockerfileError))
lintIO options dFiles = do
parsedFiles <- mapM parseFile (NonEmpty.toList dFiles)
return $ NonEmpty.fromList (lint options parsedFiles)
where
parseFile :: String -> IO (Text, Either Error Dockerfile)
parseFile "-" = do
res <- Docker.parseStdin
return (Text.pack "-", res)
parseFile s = do
res <- Docker.parseFile s
return (Text.pack s, res)
lint ::
LintOptions ->
[(Text, Either Error Dockerfile)] ->
[Format.Result Text DockerfileError]
lint options parsedFiles = gather results `Parallel.using` parallelRun
where
gather = fmap (uncurry Format.toResult)
results =
[ ( name,
fmap (analyze options) parseResult
)
| (name, parseResult) <- parsedFiles
]
parallelRun = Parallel.parList Parallel.rseq
analyze :: LintOptions -> Dockerfile -> Seq.Seq Hadolint.Rule.CheckFailure
analyze options dockerfile = fixer process
where
fixer = fixSeverity options
process = Hadolint.Process.run (rulesConfig options) dockerfile
fixSeverity :: LintOptions -> Seq.Seq Hadolint.Rule.CheckFailure -> Seq.Seq Hadolint.Rule.CheckFailure
fixSeverity LintOptions {..} = Seq.filter ignoredRules . Seq.mapWithIndex (const correctSeverity)
where
correctSeverity =
makeSeverity Hadolint.Rule.DLErrorC errorRules
. makeSeverity Hadolint.Rule.DLWarningC warningRules
. makeSeverity Hadolint.Rule.DLInfoC infoRules
. makeSeverity Hadolint.Rule.DLStyleC styleRules
ignoredRules = ignoreFilter ignoreRules
makeSeverity s rules [email protected] {code} =
if code `elem` rules
then rule {Hadolint.Rule.severity = s}
else rule
ignoreFilter :: [IgnoreRule] -> Hadolint.Rule.CheckFailure -> Bool
ignoreFilter ignored Hadolint.Rule.CheckFailure {code, severity} =
code `notElem` ignored && severity /= Hadolint.Rule.DLIgnoreC
|
lukasmartinelli/hadolint
|
src/Hadolint/Lint.hs
|
gpl-3.0
| 3,701 | 0 | 12 | 736 | 1,018 | 568 | 450 | -1 | -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.Monitoring.Projects.AlertPolicies.Get
-- 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)
--
-- Gets a single alerting policy.
--
-- /See:/ <https://cloud.google.com/monitoring/api/ Cloud Monitoring API Reference> for @monitoring.projects.alertPolicies.get@.
module Network.Google.Resource.Monitoring.Projects.AlertPolicies.Get
(
-- * REST Resource
ProjectsAlertPoliciesGetResource
-- * Creating a Request
, projectsAlertPoliciesGet
, ProjectsAlertPoliciesGet
-- * Request Lenses
, papgXgafv
, papgUploadProtocol
, papgAccessToken
, papgUploadType
, papgName
, papgCallback
) where
import Network.Google.Monitoring.Types
import Network.Google.Prelude
-- | A resource alias for @monitoring.projects.alertPolicies.get@ method which the
-- 'ProjectsAlertPoliciesGet' request conforms to.
type ProjectsAlertPoliciesGetResource =
"v3" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] AlertPolicy
-- | Gets a single alerting policy.
--
-- /See:/ 'projectsAlertPoliciesGet' smart constructor.
data ProjectsAlertPoliciesGet =
ProjectsAlertPoliciesGet'
{ _papgXgafv :: !(Maybe Xgafv)
, _papgUploadProtocol :: !(Maybe Text)
, _papgAccessToken :: !(Maybe Text)
, _papgUploadType :: !(Maybe Text)
, _papgName :: !Text
, _papgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsAlertPoliciesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'papgXgafv'
--
-- * 'papgUploadProtocol'
--
-- * 'papgAccessToken'
--
-- * 'papgUploadType'
--
-- * 'papgName'
--
-- * 'papgCallback'
projectsAlertPoliciesGet
:: Text -- ^ 'papgName'
-> ProjectsAlertPoliciesGet
projectsAlertPoliciesGet pPapgName_ =
ProjectsAlertPoliciesGet'
{ _papgXgafv = Nothing
, _papgUploadProtocol = Nothing
, _papgAccessToken = Nothing
, _papgUploadType = Nothing
, _papgName = pPapgName_
, _papgCallback = Nothing
}
-- | V1 error format.
papgXgafv :: Lens' ProjectsAlertPoliciesGet (Maybe Xgafv)
papgXgafv
= lens _papgXgafv (\ s a -> s{_papgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
papgUploadProtocol :: Lens' ProjectsAlertPoliciesGet (Maybe Text)
papgUploadProtocol
= lens _papgUploadProtocol
(\ s a -> s{_papgUploadProtocol = a})
-- | OAuth access token.
papgAccessToken :: Lens' ProjectsAlertPoliciesGet (Maybe Text)
papgAccessToken
= lens _papgAccessToken
(\ s a -> s{_papgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
papgUploadType :: Lens' ProjectsAlertPoliciesGet (Maybe Text)
papgUploadType
= lens _papgUploadType
(\ s a -> s{_papgUploadType = a})
-- | Required. The alerting policy to retrieve. The format is:
-- projects\/[PROJECT_ID_OR_NUMBER]\/alertPolicies\/[ALERT_POLICY_ID]
papgName :: Lens' ProjectsAlertPoliciesGet Text
papgName = lens _papgName (\ s a -> s{_papgName = a})
-- | JSONP
papgCallback :: Lens' ProjectsAlertPoliciesGet (Maybe Text)
papgCallback
= lens _papgCallback (\ s a -> s{_papgCallback = a})
instance GoogleRequest ProjectsAlertPoliciesGet where
type Rs ProjectsAlertPoliciesGet = AlertPolicy
type Scopes ProjectsAlertPoliciesGet =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/monitoring",
"https://www.googleapis.com/auth/monitoring.read"]
requestClient ProjectsAlertPoliciesGet'{..}
= go _papgName _papgXgafv _papgUploadProtocol
_papgAccessToken
_papgUploadType
_papgCallback
(Just AltJSON)
monitoringService
where go
= buildClient
(Proxy :: Proxy ProjectsAlertPoliciesGetResource)
mempty
|
brendanhay/gogol
|
gogol-monitoring/gen/Network/Google/Resource/Monitoring/Projects/AlertPolicies/Get.hs
|
mpl-2.0
| 4,894 | 0 | 15 | 1,061 | 702 | 411 | 291 | 103 | 1 |
{-# Language InstanceSigs, DoAndIfThenElse #-}
module Observables where
import Prelude hiding (map, takeWhile)
import System.IO
import Data.Char
import System.Console.ANSI
import Control.Monad
import Control.Monad.Trans
import qualified Data.List
import Data.IORef
import Coroutine
(|>) :: a -> (a -> b) -> b
x |> f = f x
isLeft :: Either a b -> Bool
isLeft (Left _) = True
isLeft _ = False
isRight :: Either a b -> Bool
isRight (Right _) = True
isRight _ = False
data Observer a = Observer (a -> Trampoline IO ())
data Observable a = Observable (Observer a -> Trampoline IO ())
onNext :: a -> Observer a -> Trampoline IO ()
onNext x (Observer f) = f x
unit :: a -> Observable a
unit x = Observable (\o -> o |> onNext x)
subscribe :: Observer a -> Observable a -> Trampoline IO ()
subscribe f (Observable m) = m f
merge :: Observable (Observable a) -> Observable a
merge xss = Observable (\o -> xss |> subscribe (Observer (\xs -> xs |> subscribe o)))
instance Functor Observable where
fmap :: (a -> b) -> Observable a -> Observable b
fmap f m = Observable (\o -> m |> subscribe(Observer(\x -> o |> onNext (f x))))
instance Monad Observable where
(>>=) :: Observable a -> (a -> Observable b) -> Observable b
m >>= f = merge (fmap f m)
return :: a -> Observable a
return = unit
instance MonadPlus Observable where
mzero :: Observable a
mzero = Observable (\o -> return ())
mplus :: Observable a -> Observable a -> Observable a
mplus xs ys = Observable (\o -> sequence_ [xs |> subscribe (Observer (\x -> o |> onNext x)),
ys |> subscribe (Observer (\x -> o |> onNext x))])
filter :: (a -> Bool) -> Observable a -> Observable a
filter p xs = Observable (\o -> xs |> subscribe (Observer (\x -> if (p x) then
(o |> onNext x)
else pause)))
takeWhile :: (a -> Bool) -> Observable a -> Observable a
takeWhile p xs = do x <- xs;
guard (p x);
return x
skipWhile :: (a -> Bool) -> Observable a -> Observable a
skipWhile p xs = takeWhile (not . p) xs
combine :: Observable a -> Observable b -> Observable (Either a b)
combine xs ys = Observable (\o -> do interleave [xs |> subscribe(Observer (\x -> do o |> onNext (Left x)
pause)),
ys |> subscribe(Observer (\x -> do o |> onNext (Right x)
pause))]
return ())
takeUntil :: Observable b -> Observable a -> Observable a
takeUntil sig xs = Observable (\o -> do ref <- liftIO $ newIORef False
(combine sig xs) |> subscribe (obs ref o))
where obs ref o = Observer (\x -> do b <- liftIO $ readIORef ref
if (b) then return ()
else if (isLeft x) then liftIO $ writeIORef ref True
else let (Right v) = x in o|> onNext v)
skipUntil :: Observable b -> Observable a -> Observable a
skipUntil sig xs = Observable (\o -> do ref <- liftIO $ newIORef False
(combine sig xs) |> subscribe (obs ref o))
where obs ref o = Observer (\x -> do b <- liftIO $ readIORef ref
if (b) then let (Right v) = x in o|> onNext v
else if (isLeft x) then liftIO $ writeIORef ref True
else return())
-- Work in progress,,
window :: Observable a -> Observable b -> Observable (Observable b)
window cl xs = Observable (\o -> do o |> onNext (xs |> takeUntil cl)
o |> onNext (xs |> skipUntil cl))
toObservable :: [a] -> Observable a
toObservable xs = Observable (\o -> (mapM_ (\ x -> o |> onNext x) xs))
keys :: Observable Char
keys = Observable loop
where loop o = do x <- liftIO $ getChar;
o |> onNext x;
loop o
|
holoed/Rx.hs
|
Observables.hs
|
apache-2.0
| 4,421 | 0 | 23 | 1,753 | 1,652 | 824 | 828 | 83 | 3 |
module Inference
(
inferRules
) where
import Types
infer :: Relation -> Expr -> [Relation]
infer (premices `Imply` (lhs `And` rhs)) goal =
infer (premices `Imply` rhs) goal ++
infer (premices `Imply` lhs) goal
infer (premices `Imply` (lhs `Or` rhs)) goal =
infer ((premices `And` Not lhs) `Imply` rhs) goal ++
infer ((premices `And` Not rhs) `Imply` lhs) goal
infer (premices `Imply` (lhs `Xor` rhs)) goal =
infer (premices `Imply` ((lhs `Or` rhs) `And` Not (lhs `And` rhs))) goal
-- inference of not rules
infer (rhs `Imply` Not (Not lhs)) goal =
infer (rhs `Imply` lhs) goal
infer (premices `Imply` Not (lhs `And` rhs)) goal =
infer (premices `Imply` (Not lhs `Or` Not rhs)) goal
infer (premices `Imply` Not (lhs `Or` rhs)) goal =
infer (premices `Imply` (Not lhs `And` Not rhs)) goal
infer (premices `Imply` Not (lhs `Xor` rhs)) goal =
infer (premices `Imply` (Not (lhs `Or` rhs) `Or` (lhs `And` rhs))) goal
-- return the rule sent if the rhs is the fact we are looking for
infer r@(_ `Imply` fact) goal
| goal == fact = [r]
-- | Not goal == fact = [r]
| otherwise = []
--modus tollens or transposition
launchInferences ( lhs `Imply` rhs) goal =
infer ( lhs `Imply` rhs) goal ++ infer ( Not rhs `Imply` Not lhs) goal
-- distribution of Equivalence in implications
launchInferences (rhs `Eq` lhs) goal =
launchInferences (rhs `Imply` lhs) goal ++ launchInferences (lhs `Imply` rhs) goal
-- inferRules :: [Relation] -> Expr -> [Relation]
inferRules rules goal = foldr (\r -> (++) (launchInferences r goal)) [] rules
|
tmielcza/demiurge
|
src/Inference.hs
|
apache-2.0
| 1,568 | 0 | 12 | 313 | 681 | 392 | 289 | 29 | 1 |
-----------------------------------------------------------------------------
--
-- Module : Marshaller
-- Description :
-- Copyright : (c) Tobias Reinhardt, 2015 <[email protected]
-- License : Apache License, Version 2.0
--
-- Maintainer : Tobias Reinhardt <[email protected]>
-- Portability : tested only on linux
-- |
--
-----------------------------------------------------------------------------
module Marshaller (
Option (Short, Long, Both),
NeedForArgument (Optional, Compulsory, None),
MarshalledEntity (NonOptionArgument, OptionWithArgument, OnlyOption),
marshal,
marshalArguments
) where
import Data.List.Split (splitOn)
import System.Environment
data NeedForArgument = Optional String | Compulsory | None
deriving(Show)
data Option = Short Char |
Long String |
Both Char String
deriving(Show)
instance Eq Option where
Short c1 == Short c2 = c1 == c2
Long s1 == Long s2 = s1 == s2
Short c1 == Both c2 _ = c1 == c2
Long s1 == Both _ s2 = s1 == s2
Both c1 _ == Short c2 = c1 == c2
Both _ s1 == Long s2 = s1 == s2
_ == _ = False
data MarshalledEntity = NonOptionArgument String |
OptionWithArgument Option String |
OnlyOption Option
deriving(Show)
type CommandLineArgument = String
type OptionDefinition = (Option, NeedForArgument)
marshalArguments :: [OptionDefinition] -> IO [MarshalledEntity]
marshalArguments x = do args <- getArgs
return (marshal args x)
marshal :: [CommandLineArgument] -> [OptionDefinition] -> [MarshalledEntity]
marshal [] _ = []
marshal (('-':'-':x):xs) ys = parseLong x xs ys
marshal (('-':x:[]):xs) ys = parseShort x xs ys
marshal (('-':x):xs) ys = parseCluster x xs ys
marshal (x:xs) ys = NonOptionArgument x : marshal xs ys
parseShort :: Char -> [CommandLineArgument] -> [OptionDefinition] -> [MarshalledEntity]
parseShort z [] ys = qualifyArgumentForOption (Short z) [] ys : []
parseShort z xxs@(('-':_):_) ys = qualifyArgumentForOption (Short z) [] ys : marshal xxs ys
parseShort z xxs@(x:xs) ys = case (getNeedForArgument (Short z) ys) of
None -> OnlyOption (Short z) : marshal xxs ys
_ -> OptionWithArgument (Short z) x : marshal xs ys
parseLong :: String -> [CommandLineArgument] -> [OptionDefinition] -> [MarshalledEntity]
parseLong z xs ys = case splitOn "=" z of
(u:[]) -> qualifyArgumentForOption (Long u) [] ys : marshal xs ys
(u:(v:[])) -> qualifyArgumentForOption (Long u) v ys : marshal xs ys
(_) -> error "Too many arguments"
parseCluster :: String -> [CommandLineArgument] -> [OptionDefinition] -> [MarshalledEntity]
parseCluster [] xs ys = marshal xs ys
parseCluster (z:zs) xs ys = qualifyArgumentForOption (Short z) [] ys : parseCluster zs xs ys
getNeedForArgument :: Option -> [OptionDefinition] -> NeedForArgument
getNeedForArgument x xs = case lookup x xs of
Nothing -> error "Option not defined"
Just u -> u
qualifyArgumentForOption :: Option -> String -> [OptionDefinition] -> MarshalledEntity
qualifyArgumentForOption x y xs = case (getNeedForArgument x xs, y) of
(Compulsory, []) -> error "option needs an argument"
(None, _:_) -> error "option can't have an argument"
(Optional u, []) -> OptionWithArgument x u
(_, []) -> OnlyOption x
(_, _) -> OptionWithArgument x y
|
tobiasreinhardt/show
|
CLIArguments/src/Marshaller.hs
|
apache-2.0
| 3,915 | 0 | 12 | 1,235 | 1,165 | 611 | 554 | 68 | 5 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Seraph.Model
( Directive(..)
, Event(..)
, OracleM
, oracle
, oracleModel
, oracleDebug
) where
-------------------------------------------------------------------------------
import Control.Lens
import Control.Monad.State.Strict
import Control.Monad.Writer.Strict
import qualified Data.Map as M
import Data.Maybe (isJust, mapMaybe)
import Data.Set (Set, (\\))
import qualified Data.Set as S
import Debug.Trace
import MVC
-------------------------------------------------------------------------------
import Seraph.Types
-------------------------------------------------------------------------------
oracleModel :: Model Config Event (Directives, [String])
oracleModel = asPipe $ loop model
where
model = unwrapModel oracle
-- model = unwrapModel oracleDebug
-------------------------------------------------------------------------------
type OracleM a = WriterT [String] (State Config) a
-------------------------------------------------------------------------------
unwrapModel :: (Event -> OracleM a)
-> Event
-> ListT (State Config) (a, [String])
unwrapModel f e = lift $ runWriterT (f e)
-------------------------------------------------------------------------------
oracleDebug :: Event -> OracleM Directives
oracleDebug e = do
s <- get
res <- traceShow s $ oracle e
-- s' <- get
-- traceShow ("EVT", e, "BEFORE", s, "AFTER", s') $ return res
traceShow ("EVT", e, "RES", res) $ return res
-------------------------------------------------------------------------------
oracle :: Event -> OracleM Directives
oracle (ProcessDeath prid) = do
progLogger "Process died"
existing <- gets $ view $ running . at prid . to isJust
mainLogger $ if existing
then "Spawning " ++ prid ^. pidStr
else "Process " ++ prid ^. pidStr ++ " not configured for restart"
modify $ set (running . at prid) Nothing
progs <- gets $ toListOf $ configured . ix prid
return $ Directives $ if null progs
then []
else map SpawnProg progs
where
progLogger = ctxLogger (prid ^. pidStr)
oracle (ProgRunning prid) = do
modify $ \c -> c & running <>~ S.singleton prid
progLogger "Marked as running"
return $ Directives []
where
progLogger = ctxLogger (prid ^. pidStr)
oracle (NewConfig cfg) = do
mainLogger "New config"
oldCfg <- get
put cfg
let oldPids = configPids oldCfg
let newPids = configPids cfg
let currentlyRunning = oldCfg ^. running
let spawnPids = newPids \\ oldPids
let killPids = currentlyRunning \\ newPids
spawnProgs <- getProgs $ spawnPids ^. to S.toList
let spawns = map SpawnProg spawnProgs
let kills = map KillProg $ killPids ^. to S.toList
mainLogger $ "Spawning " ++ slen spawns ++ " programs and killing " ++ slen kills
return . Directives $ spawns ++ kills
oracle ShutdownRequested = do
mainLogger "Shutdown requested."
modify $ set configured mempty
killPids <- gets $ view (running . to S.toList)
return . FinalDirectives . map KillProg $ killPids
oracle (ProgNotStarted prid e) = do
spawnProgs <- getProgs [prid]
progLogger $ "Failed to start: " ++ show e ++ ", retrying."
return $ Directives $ map SpawnProg spawnProgs
where
progLogger = ctxLogger (prid ^. pidStr)
-------------------------------------------------------------------------------
getProgs :: [ProgramId] -> OracleM [Program]
getProgs spawnPids = do
cfg <- get
return $ mapMaybe (progForPid cfg) spawnPids
where
progForPid cfg prid = cfg ^. configured . at prid
-------------------------------------------------------------------------------
configPids :: Config -> Set ProgramId
configPids cfg = cfg ^. configured . to M.keys . to S.fromList
-------------------------------------------------------------------------------
mainLogger :: MonadWriter [String] m => String -> m ()
mainLogger = ctxLogger "seraph"
-------------------------------------------------------------------------------
ctxLogger :: MonadWriter [String] m => String -> String -> m ()
ctxLogger label s = tell [unwords [label, "-", s]]
-------------------------------------------------------------------------------
slen :: Show a => [a] -> String
slen = show . length
|
MichaelXavier/Seraph
|
src/Seraph/Model.hs
|
bsd-2-clause
| 4,483 | 0 | 13 | 931 | 1,169 | 591 | 578 | -1 | -1 |
-- 709
import Data.Function(on)
import Data.List(sortBy)
import Euler(splitOn)
parseBaseExp ws = [(a,b,n+1) | n <- [0..length ws-1],
let [a,b] = parseOne $ ws !! n]
where parseOne w = map read $ splitOn ',' w
findLargest ws = snd $ last $ sortBy (compare `on` fst) $
map logBaseExp $ parseBaseExp ws
where logBaseExp (a,b,n) = (b * log a, n)
main = do
ns <- readFile "../files/p099_base_exp.txt"
putStrLn $ show $ findLargest $ lines ns
|
higgsd/euler
|
hs/99.hs
|
bsd-2-clause
| 505 | 0 | 11 | 144 | 228 | 119 | 109 | 12 | 1 |
{-# LANGUAGE RankNTypes #-}
module Insomnia.Interp.PMonad (ProbabilityMonad(..)
, SupportMonad(..)
, ExpMonad(..)
, SamplingMonad(..)
, ContinuousProbabilityMonad(..)
, samples
, ConditioningMonad(..)
, Exp
, Support
, Sample
, probability
, certainty
, impossibility
, logOdds)
where
import Control.Applicative
import Control.Monad (liftM)
import System.Random (RandomGen(split), random, newStdGen)
import Data.Number.Erf (invnormcdf)
type Probability = Double -- number from 0 to 1
certainty, impossibility :: Probability
certainty = 1.0
impossibility = 0.0
probability :: ExpMonad m => (a -> Bool) -> m a -> Double
probability p = expectation (numOfBool . p)
where numOfBool True = certainty
numOfBool False = impossibility
logOdds :: ExpMonad m => (a -> Bool) -> m a -> Double
logOdds p dist =
10 * (logBase 10 (probability p dist) - logBase 10 (probability (not . p) dist))
class Monad m => ProbabilityMonad m where
choose :: Probability -> m a -> m a -> m a
class ProbabilityMonad m => SupportMonad m where
support :: m a -> [a]
-- support (return x) = [x]
-- support (d >>= k) =
-- concat [support (k x) | x <- support d]
-- support (choose p d d') =
-- support d ++ support d'
class ProbabilityMonad m => ExpMonad m where
expectation :: (a -> Double) -> m a -> Double
-- expectation h (return x) = h x
-- expectation h (d >>= k) = expectation g d
-- where g x = expectation h (k x)
-- expectation h (choose p d d') =
-- p * expectation h d +
-- (1-p) * expectation h d'
-- sample (return x) r = (x, r)
-- sample (d >>= k) r =
-- let (x, r') = sample d r in sample (k x) r'
-- sample (choose p d d') r =
-- if r < p then sample d (r/p)
-- else sample d' ((1-r)/(1-p))
class ProbabilityMonad m => SamplingMonad m where
sample :: RandomGen g => m a -> g -> (a, g)
-- sample (return x) g = (x, g)
-- sample (d >>= k) g =
-- let (x, g') = sample d g in sample (k x) g'
-- sample (choose p d d') g =
-- let (x, g') = random g in
-- sample (if x < p then d else d') g'
newtype Support a = Support [a]
instance Functor Support where
fmap f (Support l) = Support (fmap f l)
instance Applicative Support where
pure = return
(Support lf) <*> (Support lx) =
Support [f x | f <- lf , x <- lx]
instance Monad Support where
return x = Support [x]
(Support l) >>= k =
Support (concat [s | x <- l, let Support s = k x])
instance ProbabilityMonad Support where
choose _ (Support l) (Support l') = Support (l ++ l')
instance SupportMonad Support where
support (Support l) = l
newtype Exp a = Exp ((a -> Double) -> Double)
instance Functor Exp where
fmap f (Exp d) = Exp (\h -> d (h . f))
instance Applicative Exp where
pure = return
(Exp df) <*> (Exp dx) = Exp (\h -> df (\f -> dx (\x -> h (f x))))
instance Monad Exp where
return x = Exp (\h -> h x)
(Exp d) >>= k =
Exp (\h -> let apply (Exp f) arg = f arg
g x = apply (k x) h
in d g)
instance ProbabilityMonad Exp where
choose p (Exp d1) (Exp d2) =
Exp (\h -> p * d1 h + (1-p) * d2 h)
instance ExpMonad Exp where
expectation h (Exp d) = d h
newtype Sample a = Sample (forall g . RandomGen g => g -> (a, g))
instance Functor Sample where
fmap f (Sample s) = Sample (\g -> let (x, g') = s g
in (f x, g'))
instance Applicative Sample where
pure = return
(Sample sf) <*> (Sample sx) =
Sample (\g -> let
(g1, g2) = split g
(f, _) = sf g1
(x, g'') = sx g2
in (f x, g''))
instance Monad Sample where
return x = Sample (\ g -> (x, g))
(Sample s) >>= k =
Sample (\ g -> let (a, g') = s g
Sample s' = k a
in s' g')
instance ProbabilityMonad Sample where
choose p (Sample s1) (Sample s2) =
Sample (\g -> let (x, g') = random g
in (if x < p then s1 else s2) g')
instance SamplingMonad Sample where
sample (Sample s) g = s g
class ProbabilityMonad m => ContinuousProbabilityMonad m where
u :: m Probability -- uniform over the unit interval
gauss :: m Double
gauss = liftM invnormcdf u
{-# MINIMAL u #-}
instance ContinuousProbabilityMonad Sample where
u = Sample random
samples :: SamplingMonad m => m a -> IO [a]
samples m =
do gen <- newStdGen
return $ run gen
where run g = let (a, g') = sample m g in a : run g'
class ProbabilityMonad m => ConditioningMonad m where
pfilter :: (a -> Bool) -> m a -> m a
instance ConditioningMonad Sample where
-- conditioning implemented by rejection sampling
pfilter p (Sample s) = Sample s'
where s' g = let (a, g') = s g
in if p a then (a, g')
else s' g'
instance ConditioningMonad Exp where
pfilter p (Exp integrate) = Exp integrate'
where integrate' f = integrate (\a -> if p a then f a else 0) /
integrate (\a -> if p a then 1 else 0)
instance ConditioningMonad Support where
pfilter p (Support as) = Support (filter p as)
|
lambdageek/insomnia
|
src/Insomnia/Interp/PMonad.hs
|
bsd-3-clause
| 5,536 | 0 | 17 | 1,872 | 1,876 | 973 | 903 | 119 | 2 |
module Settings.Flavours.Quickest (quickestFlavour) where
import Expression
import Flavour
import {-# SOURCE #-} Settings.Default
-- Please update doc/flavours.md when changing this file.
quickestFlavour :: Flavour
quickestFlavour = defaultFlavour
{ name = "quickest"
, args = defaultBuilderArgs <> quickestArgs <> defaultPackageArgs
, libraryWays = pure [vanilla]
, rtsWays = quickestRtsWays }
quickestArgs :: Args
quickestArgs = sourceArgs SourceArgs
{ hsDefault = pure ["-O0", "-H64m"]
, hsLibrary = mempty
, hsCompiler = stage0 ? arg "-O"
, hsGhc = stage0 ? arg "-O" }
quickestRtsWays :: Ways
quickestRtsWays = pure [vanilla, threaded]
|
ezyang/ghc
|
hadrian/src/Settings/Flavours/Quickest.hs
|
bsd-3-clause
| 701 | 0 | 9 | 150 | 156 | 93 | 63 | 18 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Utils where
import Kerchief.Prelude
import Prelude hiding (foldl, getLine, putStr, putStrLn)
import Control.Exception (SomeException, catch)
import Control.Monad.Trans (MonadIO)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Foldable (Foldable, foldl)
import System.Directory (getDirectoryContents)
askYesNo :: MonadIO m => String -> m a -> m a -> m a
askYesNo s yes no = io (prompt s) >>= \s -> case s of
"y" -> yes
"Y" -> yes
"yes" -> yes
"n" -> no
"N" -> no
"no" -> no
_ -> putStrLn "Please input \"y\" or \"n\"." >> askYesNo s yes no
catchNothing :: IO (Maybe a) -> IO (Maybe a)
catchNothing = (`catch` (\(_ :: SomeException) -> return Nothing))
catchVoid :: IO () -> IO ()
catchVoid = (`catch` (\(_ :: SomeException) -> return ()))
eitherToMaybe :: Either a b -> Maybe b
eitherToMaybe = either (const Nothing) Just
getDirectoryContents' :: FilePath -> IO [FilePath]
getDirectoryContents' = fmap (filter (\a -> a /= "." && a/= "..")) . getDirectoryContents
ifM :: Monad m => m Bool -> m a -> m a -> m a
ifM mb t f = mb >>= \b -> if b then t else f
-- | maybeThen a f m performs action |a| unconditionally, possibly preceded by
-- action |f b| if |m| is Just b.
maybeThen :: Monad m => m a -> (b -> m c) -> Maybe b -> m a
maybeThen thn _ Nothing = thn
maybeThen thn f (Just b) = f b >> thn
partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a], [a])
partitionM p = foldM (select p) ([],[])
where
select :: Monad m => (a -> m Bool) -> ([a],[a]) -> a -> m ([a],[a])
select q (ts,fs) x =
ifM (q x)
(return (x:ts,fs))
(return (ts,x:fs))
-- | Print each element of a Foldable, prepended by a number (starting at 1).
printNumbered :: (Show a, Foldable t) => t a -> IO ()
printNumbered = printNumberedWith show
printNumberedWith :: (MonadIO m, Foldable t) => (a -> String) -> t a -> m ()
printNumberedWith f = mapM_ putStrLn . showNumberedWith f
prompt :: MonadIO m => String -> m String
prompt s = putStr s >> getLine
showNumbered :: (Show a, Foldable t) => t a -> [String]
showNumbered = showNumberedWith show
showNumberedWith :: forall a t. Foldable t => (a -> String) -> t a -> [String]
showNumberedWith f = snd . foldl g (1,[])
where
g :: (Int,[String]) -> a -> (Int,[String])
g (n,ss) a = (n+1, ss ++ [show n ++ ". " ++ f a])
reads' :: Read a => String -> Maybe a
reads' s = case reads s of
[(a,"")] -> Just a
_ -> Nothing
unless' :: Monad m => m () -> Bool -> m ()
unless' = flip unless
whenJust :: (Functor m, Monad m) => (a -> m b) -> Maybe a -> m ()
whenJust _ Nothing = return ()
whenJust f (Just a) = void (f a)
safeReadFile :: FilePath -> IO (Maybe ByteString)
safeReadFile path = catchNothing (Just <$> BS.readFile path)
|
mitchellwrosen/kerchief
|
src/Utils.hs
|
bsd-3-clause
| 2,909 | 0 | 13 | 714 | 1,299 | 679 | 620 | 62 | 7 |
module HQuestions where
import Control.Arrow ((&&&))
import System.Random
import Data.List
import Data.Maybe
import Data.Function (on)
import Control.Monad (replicateM)
h1 :: [a] -> a
h1 = last
h2 :: [a] -> a
h2 = last . init
h3 :: [a] -> Int -> a
h3 xs n = xs !! (n-1)
h4 :: [a] -> Int
h4 = foldr (const (+1)) 0
h5 :: [a] -> [a]
h5 = foldl (\acc x -> x : acc) []
h6 :: Eq a => [a] -> Bool
h6 xs = xs == h5 xs
data NestedList a = Elem a | List [NestedList a]
h7 :: NestedList a -> [a]
h7 (Elem a) = [a]
h7 (List as) = concatMap h7 $ as
h8 :: Eq a => [a] -> [a]
h8 = fmap head . h9
h9 :: Eq a => [a] -> [[a]]
h9 = foldr f []
where f x [] = [[x]]
f x ((a:ac):acc) = if a == x then (x:a:ac):acc
else [x]:(a:ac):acc
h10 :: Eq a => [a] -> [(Int, a)]
h10 = fmap (length &&& head) . h9
data SingleOrMultiple a = Single a | Multiple Int a deriving (Show)
h11 :: Eq a => [a] -> [SingleOrMultiple a]
h11 = fmap check . h9
where check [x] = Single x
check xs@(x:_) = Multiple (length xs) x
h12 :: [SingleOrMultiple a] -> [a]
h12 = concatMap change
where change (Single x) = [x]
change (Multiple n x) = replicate n x
h13 :: Eq a => [a] -> [SingleOrMultiple a]
h13 = foldr change []
where change x [] = [Single x]
change x acc@((Single y):ac) = if x == y
then (Multiple 2 x):ac
else (Single x):acc
change x acc@((Multiple n y):ac) = if x == y
then (Multiple (n+1) y):ac
else (Single x):acc
h14 :: [a] -> [a]
h14 = concatMap (replicate 2)
h15 :: [a] -> Int -> [a]
h15 xs n = xs >>= replicate n
h16 :: [a] -> Int -> [a]
-- h16 xs n = fmap snd . filter ((/=0) . flip mod n . fst) . zip [1..] $ xs
h16 xs n = [c | (i, c) <- zip [1..] xs, mod i n /= 0]
h17 :: [a] -> Int -> ([a], [a])
-- h17 = flip splitAt
h17 [] _ = ([], [])
h17 li@(x:xs) n | n <= 0 = ([], li)
| otherwise = let (a, ac) = h17 xs (n-1)
in (x:a, ac)
h18 :: [a] -> Int -> Int -> [a]
h18 xs start stop = [xs !! (i-1) | i <- [start .. stop]]
h19 :: [a] -> Int -> [a]
h19 xs n = b ++ a
where (a, b) = h17 xs (if n > 0 then n else length xs + n)
h20 :: Int -> [a] -> (a, [a])
h20 n xs = (last a, init a ++ b)
where (a, b) = h17 xs (if n > 0 then n else length xs + n)
h21 :: a -> [a] -> Int -> [a]
h21 x xs n = r ++ (x:l)
where (r, l) = h17 xs (if n > 0 then n-1 else length xs + n - 1)
h22 :: Int -> Int -> [Int]
h22 start stop = [start .. stop]
h23 :: [a] -> Int -> IO [a]
h23 xs n = do
g <- getStdGen
let index = take n $ randomRs (0, length xs - 1) g
return [xs !! i | i <- index]
h24 :: Int -> Int -> IO [Int]
h24 num stop = do
g <- getStdGen
return . take num $ randomRs (1, stop) g
h25 :: Eq a => [a] -> IO [a]
-- h25 xs = do
-- g <- getStdGen
-- return . take (length xs) . nub $ [xs !! i | i <- randomRs (0, length xs - 1) g]
--too stupid
h25 [] = return []
h25 xs = do
ind <- randomRIO (0, length xs-1)
let (as, b:bs) = h17 xs ind
rest <- h25 (as++bs)
return (b : rest)
h26 :: Int -> [a] -> [[a]]
h26 0 _ = [[]]
h26 _ [] = [] -- very very important here
h26 n (x:xs) = ((x:) <$> h26 (n-1) xs) ++ (h26 n xs)
h27 :: [Int] -> [a] -> [[[a]]]
h27 [] _ = [[]]
h27 _ [] = []
h27 nl@(n:ns) xs =
[ (li:gs) | (li, ri) <- change n xs, gs <- h27 ns ri ]
where change :: Int -> [a] -> [([a], [a])]
change 0 xs = [([], xs)]
change _ [] = []
change m (y:ys) = ((\(z, zs) -> (y:z, zs)) <$> change (m-1) ys) ++
((\(z, zs) -> (z, y:zs)) <$> change m ys)
h28 :: [[a]] -> [[a]]
h28 = sortBy (compare `on` length)
h28' :: [[a]] -> [[a]]
h28' xs =
let table = map (head &&& length) . group . sort . map length $ xs
getFre x = case lookup (length x) table of
Just fre -> fre
Nothing -> error "This should not happen"
in sortBy (compare `on` getFre) xs
h31 :: Integer -> Bool
h31 n = n `elem` (takeWhile (<=n) primes)
where primes = 2 : 3 : 5 : (filter check [7,9..])
check m = all ((/=0) . mod m) (takeWhile (<= (round . sqrt . fromIntegral $ m)) primes)
h32 :: Integer -> Integer -> Integer
h32 a b = if b == 0
then abs a
else h32 b (mod a b)
h33 :: Integer -> Integer -> Bool
h33 a b = (gcd a b) == 1
h34 :: Integer -> Int
h34 n = length . filter (h33 n) $ [1..n-1]
h35 :: Integer -> [Integer]
h35 = helper
where primes = 2 : 3 : 5 : (filter check [7,9..])
check m = all ((/=0) . mod m) (takeWhile (<= (round . sqrt . fromIntegral $ m)) primes)
helper 1 = []
helper m =
let n':_ = dropWhile ((/=0) . mod m) primes
in n':(h35 (div m n'))
h36 :: Integer -> [(Integer, Int)]
h36 = map (head &&& length) . group . h35
h37 :: Integer -> Integer
h37 n = product [(p-1) * p^(m-1) | (p, m) <- (h36 n)] -- more effect
h39 :: Integer -> Integer -> [Integer]
h39 start stop = takeWhile (<= stop) (dropWhile (< start) primes)
where primes = 2 : 3 : 5 : (filter check [7,9..])
check m = all ((/=0) . mod m) (takeWhile (<= (round . sqrt . fromIntegral $ m)) primes)
h40 :: Integer -> (Integer, Integer)
h40 n = head [(m, k) | m <- thisprimes, let k = n - m, k `elem` thisprimes]
where primes = 2 : 3 : 5 : (filter check [7,9..])
check m = all ((/=0) . mod m) (takeWhile (<= (round . sqrt . fromIntegral $ m)) primes)
thisprimes = takeWhile (<=n) primes
h41 :: Integer -> Integer -> [(Integer, Integer)]
h41 start stop = [h40 k | k <- [start .. stop], even k]
h41' :: Integer -> Integer -> Integer -> [(Integer, Integer)]
h41' start stop limit = filter ((> limit) . fst) . map h40 . filter even $ [start .. stop]
not' :: Bool -> Bool
not' True = False
not' _ = True
and', or', nand',nor',equ',xor',impl' :: Bool -> Bool -> Bool
and' True True = True
and' _ _ = False
or' False False = False
or' _ _ = True
nand' a b = not' (and' a b)
nor' a b = not' (or' a b)
equ' True True = True
equ' False False = True
equ' _ _ = False
xor' a b = not' (equ' a b)
impl' a b = or' b (not' a)
h47 :: (Bool -> Bool -> Bool) -> IO ()
h47 f = mapM_ putStrLn $ [show a ++ " " ++ show b ++ " " ++ show (f a b) |
a <- [True, False],
b <- [True, False]]
infixl 4 `or'`
infixl 6 `and'`
infixl 3 `equ'`
h48 :: Int -> ([Bool] -> Bool) -> IO ()
h48 n f = mapM_ putStrLn [toStr args ++ " => " ++ show (f args)| args <- replicateM n [True, False]]
where toStr = unwords . map space
space True = "True "
space False = "False"
h49 :: Int -> [String]
h49 n = replicateM n "01" -- maybe wrong, if the order matters
h50 = undefined
-- prepare data constructure for tree
-- this shouldn't be visit outside this
data Tree a = Empty | Branch a (Tree a) (Tree a) deriving (Show, Eq)
tree1 = Branch 'a' (Branch 'b' (leaf 'd')
(leaf 'e'))
(Branch 'c' Empty
(Branch 'f' (leaf 'g')
Empty))
-- A binary tree consisting of a root node only
tree2 = Branch 'a' Empty Empty
-- An empty binary tree
tree3 = Empty
-- A tree of integers
tree4 = Branch 1 (Branch 2 Empty (Branch 4 Empty Empty))
(Branch 2 Empty Empty)
leaf :: a -> Tree a
leaf x = Branch x Empty Empty
height :: Tree a -> Int
height Empty = 0
height (Branch _ li ri) = 1 + max (height li) (height ri)
add :: a -> Tree a -> [Tree a]
add x Empty = [leaf x]
add x (Branch y li ri) =
if height li - height ri == 0
then map (\li' -> Branch y li' ri) (add x li) ++
map (Branch y li) (add x ri)
else if height li > height ri
then map (Branch y li) (add x ri)
else map (\li' -> Branch y li' ri) (add x li)
h55 :: Int -> [Tree Char]
h55 0 = [Empty]
h55 n = nub $ concatMap (add 'x') (h55 (n-1))
-- Too slow
h55' :: Int -> [Tree Char]
h55' 0 = [Empty]
h55' n =
let (q, r) = (n-1) `quotRem` 2
in [Branch 'x' left right | i <- [q .. q+r],
left <- h55' i,
right <- h55' (n-1-i)]
image :: Tree a -> Tree a
image Empty = Empty
image (Branch x li ri) = Branch x (image ri) (image li)
h56 :: Eq a => Tree a -> Bool
h56 Empty = True
h56 (Branch _ li ri) =
mirror li ri
where mirror Empty Empty = True
mirror (Branch _ l1 r1) (Branch _ l2 r2) = mirror l1 r2 && mirror l2 r1
mirror _ _ = False
insertTree :: Ord a => a -> Tree a -> Tree a
insertTree x Empty = leaf x
insertTree x al@(Branch y li ri) =
if x == y
then al
else if x > y
then Branch y li (insertTree x ri)
else Branch y (insertTree x li) ri
h57 :: Ord a => [a] -> Tree a
h57 = foldl (flip insertTree) Empty
h58 :: Int -> [Tree Char]
h58 n =
let (q, r) = n `quotRem` 2
in if r == 0
then [Branch 'x' li (image li) | li <- h58 q]
else []
h59 :: Int -> a -> [Tree a]
h59 0 _ = [Empty]
h59 1 x = [Branch x Empty Empty]
h59 n x =
[Branch x li ri | (ln, rn) <- [(n-1, n-2), (n-1, n-1), (n-2, n-1)],
li <- h59 ln x,
ri <- h59 rn x]
h90 :: [[Int]]
h90 = filter isAlone (permutations [1..8])
where isAlone li = and [ not (or (zipWith elem li diag)) |
ind <- [1..8],
let ded = fmap (+ (-ind)) [1..8],
let pos = li !! (ind - 1),
let diag = fmap (\b -> if b == 0 then [] else [pos+b, pos-b]) ded]
type KnightPath = [(Int, Int)]
h91 :: Int -> (Int, Int) -> [KnightPath]
h91 size (x, y) =
let from :: (Int, Int) -> KnightPath -> [(Int, Int)]
from (a, b) old = filter (`notElem` old) (jump (a, b))
next :: KnightPath -> (Int, Int) -> [KnightPath]
next old now = if length old == size^2 - 1
then (now : old):[]
else concatMap (next (now:old)) (from now old)
jump :: (Int, Int) -> [(Int, Int)]
jump (a, b) = [(col, row) | i <- [-2, -1, 1, 2],
j <- if abs i == 2 then [-1, 1] else [-2, 2],
let col = a + i,
let row = b + j,
col >= 1 && col <= size && row >= 1 && row <= size]
in next [] (x, y) -- too slow
-- just copy from the answers ORZ
h93 :: [Integer] -> IO ()
h93 = mapM_ putStrLn . puzzle
data Expr = Const Integer |
Binary Op Expr Expr deriving (Eq, Show)
data Op = Plus | Minus | Times | Divide deriving (Show, Enum, Eq, Bounded)
type Equation = (Expr, Expr)
type Value = Rational
puzzle :: [Integer] -> [String]
puzzle = map (flip showEquation "") . equations
equations :: [Integer] -> [Equation]
equations [] = error "no equations for empty list"
equations [_] = error "no equations for one element list"
equations xs = [ (e1, e2) |
(ns1, ns2) <- splits xs,
(e1, v1) <- exprs ns1,
(e2, v2) <- exprs ns2,
v1 == v2]
exprs :: [Integer] -> [(Expr, Value)]
exprs [n] = [(Const n, fromIntegral n)]
exprs xs = [ (Binary op e1 e2, v) |
(ns1, ns2) <- splits xs,
(e1, v1) <- exprs ns1,
(e2, v2) <- exprs ns2,
op <- [minBound .. maxBound],
v <- maybeToList (apply op v1 v2),
not (rightAssiable op e2)]
splits :: [a] -> [([a], [a])] -- split list into two non-empty list
splits xs = tail . init $ (zip (inits xs) (tails xs)) -- xs at least two element
apply :: Op -> Value -> Value -> Maybe Value
apply Plus v1 v2 = Just (v1 + v2)
apply Minus v1 v2 = Just (v1 - v2)
apply Times v1 v2 = Just (v1 * v2)
apply Divide _ 0 = Nothing
apply Divide v1 v2 = Just (v1 / v2)
rightAssiable :: Op -> Expr -> Bool
rightAssiable Plus (Binary Plus _ _) = True
rightAssiable Plus (Binary Minus _ _) = True
rightAssiable Times (Binary Times _ _) = True
rightAssiable Times (Binary Divide _ _) = True
rightAssiable _ _ = False
showEquation :: Equation -> ShowS
showEquation (l, r) = showEquPrec 0 l . showString "=" . showEquPrec 0 r
showEquPrec :: Int -> Expr -> ShowS
showEquPrec _ (Const n) = shows n
showEquPrec p (Binary op e1 e2) = showParen (p > op_pre) $
showEquPrec op_pre e1 . showString (name op) . showEquPrec (op_pre + 1) e2
where op_pre = precendence op
name :: Op -> String
name Plus = "+"
name Minus = "-"
name Times = "*"
name Divide = "/"
precendence :: Op -> Int
precendence Plus = 6
precendence Minus = 6
precendence Times = 7
precendence Divide = 7
|
niexshao/Exercises
|
src/HQuestions.hs
|
bsd-3-clause
| 12,574 | 0 | 18 | 3,970 | 6,550 | 3,482 | 3,068 | 327 | 5 |
module Example.Lens () where
|
smurphy8/refactor-patternmatch-with-lens
|
src/Example/Lens.hs
|
bsd-3-clause
| 30 | 0 | 3 | 5 | 9 | 6 | 3 | 1 | 0 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PostfixOperators #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
module Ion.Private.Types where
import Data.Char
import Data.List
import Data.Complex
import Data.Boolean
import Control.Monad.State
import Control.Monad.Free
{- Synonyms ---------------------------------------------------}
type Name = String
type ReturnType = String
type Stmt = Free Statement
type Ion = StateT Int Stmt
type LibName = String
{- Data Types -------------------------------------------------}
data Expr a where
-- Supported primitive types
B :: Bool -> Expr Bool
F :: Float -> Expr Float
C :: Char -> Expr Char
D :: Double -> Expr Double
I :: Int -> Expr Int
Cx :: Complex Float -> Expr (Complex Float)
-- Supported operations
And :: Expr a -> Expr a -> Expr a
Or :: Expr a -> Expr a -> Expr a
Not :: Expr a -> Expr a
Add :: Expr a -> Expr a -> Expr a
Mult :: Expr a -> Expr a -> Expr a
Sub :: Expr a -> Expr a -> Expr a
Var :: String -> Expr a
-- Conditional Logic
While :: Expr Bool -> Expr a -> Expr a
If :: Expr Bool -> Expr a -> Expr a -> Expr a
Set :: Expr a -> Expr a -> Expr a
data CFunc a = CFunc { name :: Name
, body :: Expr a
, loc :: LocationDecl
, inherit :: InheritDecl
, funcType :: FuncType
, numArgs :: Int
}
{-- Vector definitions ---------------------------------}
-- Phantoms
data Location = Host | Device
-- Inner type, not to be exposed
data Vector (l::Location) a = Vector { label :: String
, size :: Int
, elems :: [(Int, Expr a)]
}
deriving Show
data Iterator a = CountingIterator { ilabel :: String
, initval :: Expr a
}
data Random a = Random { rLabels :: [String]
, bounds :: (Int, Int)
}
data Statement next where
Decl :: Vector Host a -> next -> Statement next
DeclEmpty :: Vector Host a -> next -> Statement next
Trans :: CFunc a -> Vector Device a -> next -> Statement next
Cout :: Vector Host a -> next -> Statement next
Fold :: (Show a) => Name -> CFunc a -> Vector Device a -> Expr a -> next -> Statement next
Load :: Vector Device a -> next -> Statement next
Unload:: Vector Host a -> next -> Statement next
FoldD :: (Show a) => Name -> CFunc a -> CFunc a -> Vector Device a -> next -> Statement next
Sort :: Vector Device a -> next -> Statement next
AdjDiff :: Vector Device a -> next -> Statement next
IDecl :: Iterator a -> next -> Statement next
UpperBound :: Vector Device a -> Vector Device a -> Iterator a -> next -> Statement next
RandomGen :: Vector Host a -> Random a -> next -> Statement next
-- Declares whether a functor
-- is to be executed on the GPU or CPU
data LocationDecl = HostDecl | DeviceDecl | Both | Neither
data InheritDecl = None | BinaryFunc
data FuncType = Regular | StructBased
data ImportDecl = Stdlib | Thrust | Cuda | Iterator
{- Conversion Instances ------------------------------------------}
class ToExpr a where
toExpr :: a -> Expr a
class InitExpr a where
init :: Expr a
instance InitExpr Int where
init = I 0
instance InitExpr Bool where
init = B False
instance InitExpr Float where
init = F 0.0
instance InitExpr Double where
init = D 0.0
instance ToExpr Bool where
toExpr = B
instance ToExpr Int where
toExpr = I
instance ToExpr Float where
toExpr = F
instance ToExpr Double where
toExpr = D
instance ToExpr (Complex Float) where
toExpr = Cx
{- Show Instances -------------------------------------------------}
{- Used for emitting C++ code. Could perhaps be parameterized in
the future to output code in other languages such as Rust -}
instance Show (Expr a) where
show (Add e1 e2) = "(" ++ show e1 ++ " + " ++ show e2 ++ ")"
show (Sub e1 e2) = "(" ++ show e1 ++ " - " ++ show e2 ++ ")"
show (Mult e1 e2) = "(" ++ show e1 ++ " * " ++ show e2 ++ ")"
show (Or e1 e2) = "(" ++ show e1 ++ " || " ++ show e2 ++ ")"
show (And e1 e2) = "(" ++ show e1 ++ " && " ++ show e2 ++ ")"
show (Not e1) = "(!" ++ show e1 ++ ")"
show (Var s) = s
show (I n) = show n
show (B b) = map toLower $ show b
show (C c) = show c
show (F f) = show f
show (D d) = show d
show (Cx c) = "Complex("
++ (show $ realPart c) ++ ","
++ (show $ imagPart c) ++ ")"
show (If c a b) = "if(" ++ (show c) ++ "){\n"
++ show a ++ "}\n"
++ "else {\n"
++ show b ++ "}\n"
show (While c a) = "while(" ++ show c ++ "){\n"
++ show a ++ "}\n"
instance Show ImportDecl where
show Thrust = "thrust/"
show Stdlib = ""
show Cuda = ""
show Iterator = "iterator/"
-- TODO lookup thrust decl types
instance Show InheritDecl where
show l = case l of
BinaryFunc -> " : public thrust::binary_function"
None -> ""
instance Show LocationDecl where
show l = case l of
HostDecl -> "__host__ "
DeviceDecl -> "__device__ "
Both -> "__host__ __device__ \n"
Neither -> ""
instance Show (CFunc a) where
show func = preamble
++ "return " ++ (show $ body func) ++ ";"
++ closing
where preamble = case funcType func of
StructBased -> "struct "
++ (name func)
++ (case inherit func of
BinaryFunc -> show (inherit func) ++ "<const " ++ (retType $ body func) ++ "&"
++ ", const " ++ (retType $ body func) ++ "&"
++ ", " ++ (retType $ body func) ++ ">\n"
None -> "")
++ " {\n\t"
++ (show $ loc func)
++ (retType $ body func) ++ " operator()("
++ (case numArgs func of
1 -> args func
2 -> args2 func
3 -> args3 func)
++ ") const{\n\t\t"
Regular -> (retType $ body func)
++ "("
++ (case numArgs func of
1 -> args func
2 -> args2 func
3 -> args3 func)
++ ")"
++ " " ++ (name func) ++ "{\n\t"
closing = case funcType func of
StructBased -> "\n\t}\n};\n"
Regular -> "\n}\n"
iters :: String -> (String,String)
iters ident = (ident ++ ".begin()", ident ++ ".end()")
instance Show (Statement next) where
show (Decl (Vector ident sz elems) next) = "\tthrust::host_vector<"
++ (retType $ snd $ head elems)
++ "> "
++ ident
++ "(" ++ show sz ++ ")"
++ ";\n\t"
++ concatMap (\(ind, val) -> ident
++ "["
++ (show ind)
++ "] = "
++ (show val)
++ ";\n\t") elems
show (DeclEmpty (Vector ident sz elems) next) = "\tthrust::host_vector<"
++ (retType $ snd $ head elems)
++ "> "
++ ident
++ "(" ++ show sz ++ ")"
++ ";\n\t"
show (Load (Vector ident sz elems) next) = "\tthrust::device_vector<"
++ (retType $ snd $ head elems)
++ "> "
++ ident
++ " = v"
++ drop 1 ident
++ ";\n"
show (Unload (Vector ident sz elems) next) = "\tthrust::host_vector<"
++ (retType $ snd $ head elems)
++ "> "
++ ident
++ " = d"
++ drop 1 ident
++ ";\n"
show (Sort (Vector ident sz elems) next) = "\tthrust::sort("
++ (concat $ intersperse "," $
[ (fst $ iters ident),
(snd $ iters ident)])
++ ");"
show (AdjDiff (Vector ident sz elems) next) = "\tthrust::adjacent_difference("
++ (concat $ intersperse "," $
[ (fst $ iters ident),
(snd $ iters ident),
(fst $ iters ident)])
++ ");"
show (UpperBound (Vector ident1 sz1 elems1)
(Vector ident2 sz2 elems2)
(CountingIterator ident expr) next) = "\tthrust::upper_bound("
++ (concat $ intersperse "," $
[(fst $ iters ident1),
(snd $ iters ident1),
ident,
ident ++ " + " ++ show sz2,
(fst $ iters ident2)])
++ ");"
show (Trans fun (Vector ident _ _) next) = "\tthrust::transform("
++ (concat $ intersperse "," $
[ (fst $ iters ident),
(snd $ iters ident),
(fst $ iters ident)])
++ "," ++ (name fun)
++ "());"
show (Cout (Vector ident sz elems) next) = "\n\tfor (int i = 0; i < "
++ show sz
++ "; ++i){std::cout << "
++ ident
++ "[i] << \" \";}\n"
++ "\tstd::cout << std::endl;"
show (Fold to fun (Vector ident _ elems) init _) = "\t" ++ (retType init)
++ " "
++ to
++ " = "
++ "thrust::reduce("
++ (fst $ iters ident) ++ ", "
++ (snd $ iters ident) ++ ", "
++ (show init) ++ ", "
++ (name fun) ++ "());"
show (IDecl (CountingIterator ident expr) next) = "\tthrust::counting_iterator<"
++ retType expr
++ "> "
++ ident
++ "("
++ show expr
++ ");"
show (RandomGen (Vector id _ elems) (Random ident (a,b)) next) = "\tstatic thrust::default_random_engine "
++ ident !! 0
++ ";\n"
++ "\tstatic thrust::uniform_int_distribution<"
++ (retType $ snd $ head elems)
++ "> "
++ ident !! 1
++ "("
++ show a
++ ","
++ show b
++ ");\n"
++ "\tthrust::generate("
++ (fst $ iters id) ++ ", "
++ (snd $ iters id) ++ ", "
++ (ident !! 1) ++ "(" ++ ident !! 0 ++ "));\n"
{- Num, Ord, Frac Instances -------------------------------------}
{- This allows the Expr types to utilize regular arithmetic and
boolean operators for a more natural syntax -}
instance Num (Expr Int) where
fromInteger = I . fromIntegral
lhs + rhs = Add lhs rhs
lhs * rhs = Mult lhs rhs
lhs - rhs = Sub lhs rhs
signum (I v) = (I . signum) v
abs (I v) = (I . abs) v
instance Num (Expr Double) where
fromInteger = D . fromInteger
lhs + rhs = Add lhs rhs
lhs * rhs = Mult lhs rhs
lhs - rhs = Sub lhs rhs
signum (D v) = (D . signum) v
abs (D v) = (D . abs) v
instance Num (Expr Float) where
fromInteger = F . fromInteger
lhs + rhs = Add lhs rhs
lhs * rhs = Mult lhs rhs
lhs - rhs = Sub lhs rhs
signum (F v) = (F . signum) v
abs (F v) = (F . abs) v
instance Eq (Expr a) where
(Add a1 b1) == (Add a2 b2) = a1 == a2 && b1 == b2
(Sub a1 b1) == (Sub a2 b2) = a1 == a2 && b1 == b2
(I i1) == (I i2) = i1 == i2
(B b1) == (B b2) = b1 == b2
_ == _ = False
instance Ord (Expr Bool) where
(B b1) `compare` (B b2) = b1 `compare` b2
instance Ord (Expr Int) where
(I i1) `compare` (I i2) = i1 `compare` i2
instance Fractional (Expr Double) where
fromRational = D . realToFrac
recip = error "Undefined operation"
(/) = error "Undefined operation"
instance Fractional (Expr Float) where
fromRational = F . realToFrac
recip = error "Undefined operation"
(/) = error "Undefined operation"
instance Functor Statement where
fmap f (Decl vec next) = Decl vec (f next)
fmap f (DeclEmpty vec next) = DeclEmpty vec (f next)
fmap f (Load vec next) = Load vec (f next)
fmap f (Unload vec next) = Unload vec (f next)
fmap f (Trans cfunc vec next) = Trans cfunc vec (f next)
fmap f (Cout v next) = Cout v (f next)
fmap f (Fold to cfunc vec val next) = Fold to cfunc vec val (f next)
fmap f (Sort v next) = Sort v (f next)
fmap f (AdjDiff v next) = AdjDiff v (f next)
fmap f (IDecl iter next) = IDecl iter (f next)
fmap f (UpperBound v1 v2 i next) = UpperBound v1 v2 i (f next)
fmap f (RandomGen v rand next) = RandomGen v rand (f next)
{- Convenience operators for (Expr) bool's -}
instance Boolean (Expr Bool) where
b1 &&* b2 = And b1 b2
b1 ||* b2 = Or b1 b2
notB b1 = Not b1
true = B True
false = B False
{- Helper functions ---------------------------------------------}
{- Only for use in show instance, not to be exported It may be
better to work these into the type more naturally later on -}
retType :: (Expr a) -> String
retType (I _) = "int"
retType (F _) = "float"
retType (D _) = "double"
retType (C _) = "char"
retType (B _) = "bool"
retType (Cx _) = "complex<float> " -- Add space for C++98 compilers
retType (Add a b) = concat $ nub $ [retType a] ++ [retType b]
retType (Mult a b) = concat $ nub $ [retType a] ++ [retType b]
retType (Sub a b) = concat $ nub $ [retType a] ++ [retType b]
retType (And a b) = concat $ nub $ [retType a] ++ [retType b]
retType (Or a b) = concat $ nub $ [retType a] ++ [retType b]
retType (Not a) = concat $ nub $ [retType a]
retType (Var a) = ""
idents :: (Expr a) -> [String]
idents body = case body of
(Var a) -> [a]
(Add a b) -> idents a ++ idents b
(Or a b) -> idents a ++ idents b
(And a b) -> idents a ++ idents b
(Not a ) -> idents a
(Mult a b) -> idents a ++ idents b
(Sub a b) -> idents a ++ idents b
_ -> []
args :: (CFunc a) -> String
args fn = "const " ++ retType b ++ " " ++ (idents b !! 0)
where b = body fn
args2 :: (CFunc a) -> String
args2 fn = "const " ++ retType b ++ " " ++ (idents b !! 0) ++ ", "
++ "const " ++ retType b ++ " " ++ (idents b !! 1)
where b = body fn
args3 :: (CFunc a) -> String
args3 fn = "const " ++ retType b ++ " " ++ (idents b !! 0) ++ ", "
++ "const " ++ retType b ++ " " ++ (idents b !! 1) ++ ", "
++ "const " ++ retType b ++ " " ++ (idents b !! 2)
where b = body fn
|
ku-fpg/thrust-gen
|
src/Ion/Private/Types.hs
|
bsd-3-clause
| 18,582 | 0 | 33 | 9,157 | 5,242 | 2,633 | 2,609 | 355 | 8 |
{-# LANGUAGE FlexibleContexts #-}
{-|
Module : $Header$
CopyRight : (c) 8c6794b6, 2011-2013
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : portable
Synthesis methods
-}
module Spectrofy.Synth
( sinsyn
, fftsyn
) where
import Data.Complex (Complex(..), realPart)
import Data.Word (Word8)
import Data.List (foldl1')
import Data.Array.Repa
((:.)(..), Array, All(..), D, DIM2, DIM3, Source, U, Z(..))
import qualified Data.Array.Repa as R
import qualified Data.Array.Repa.FFTW as R
-- --------------------------------------------------------------------------
--
-- Manual sinusoids
--
-- | Sums up sinusoids manually.
--
-- Frequency is taken from y axis, time from x axis.
-- Amplitude for each frequency is result of luminated value in each pixel.
--
sinsyn ::
Source s (Word8, Word8, Word8)
=> Int -> Int -> Array s DIM2 (Word8, Word8, Word8) -> Array D DIM2 Double
sinsyn rate delta = squash . sumSins . toSins rate . to3D delta . rgbamp
{-# INLINE sinsyn #-}
rgbamp ::
Source s (Word8, Word8, Word8)
=> Array s DIM2 (Word8, Word8, Word8) -> Array D DIM2 Double
rgbamp arr = {-# SCC "rgbamp" #-} R.traverse arr f g where
f = id
g h ix = 10 ** ((red*0.21 + green*0.71 + blue*0.07) / (255*3)) - 1 where
(red', green', blue') = h ix
red = fromIntegral red'
green = fromIntegral green'
blue = fromIntegral blue'
{-# INLINE rgbamp #-}
to3D :: Source s Double => Int -> Array s DIM2 Double -> Array D DIM3 Double
to3D n = R.extend (Z:.All:.All:.n)
{-# INLINE to3D #-}
toSins :: Source s Double => Int -> Array s DIM3 Double -> Array D DIM3 Double
toSins rate arr = {-# SCC "toSins" #-} R.traverse arr id f where
_:.y:._:._ = R.extent arr
f g ix@(_:.i:._:.k)
| amp <= 0 = 0
| otherwise = amp * sin (frq * k' * 2 * pi / rate') / y'
where
amp = g ix
frq = (rate'/2) - (((y'-i'+1)/y') * (rate'/2))
rate' = fromIntegral rate
i' = fromIntegral i
y' = fromIntegral y
k' = fromIntegral k
{-# INLINE toSins #-}
sumSins :: (Source s Double) => Array s DIM3 Double -> Array U DIM2 Double
sumSins arr = {-# SCC "sumSins" #-} R.sumS (R.backpermute sh' f arr) where
f (_:.i:.j:.k) = Z:.k:.j:.i
sh' = Z:.z:.y:.x
(_:.x:.y:.z) = R.extent arr
{-# INLINE sumSins #-}
squash :: Source s Double => Array s DIM2 Double -> Array D DIM2 Double
squash arr = {-# SCC squash #-} R.backpermute sh' f arr where
f (_:._:.j) = Z:.j `mod` x:.j `div` x
(_:.x:.y) = R.extent arr
sh' = Z:.1:.(x*y)
{-# INLINE squash #-}
-- --------------------------------------------------------------------------
--
-- Inversed FFT
--
-- | Performs 1-dimensional inverse fft on each column, then concatenate results.
--
-- RGB values are used for initial phases and magnitude.
--
fftsyn :: Int -> Array D DIM2 (Word8, Word8, Word8) -> Array D DIM2 Double
fftsyn fsz img =
{-# SCC "fftsyn" #-}
foldl1' R.append $ map (fftslice fsz img') [0..n-1] where
img' = rgbamp img
_:._:.n = R.extent img
{-# INLINE fftsyn #-}
fftslice :: Int -> Array D DIM2 Double -> Int -> Array D DIM2 Double
fftslice wsize arr n =
{-# SCC "fs_reshape" #-}
R.reshape (Z :. 1 :. wsize :: DIM2) $
{-# SCC "fs_map" #-}
R.map realPart $
{-# SCC "fs_ifft" #-}
R.ifft $
{-# SCC "fs_computeS" #-}
R.computeS $
{-# SCC "fs_slice" #-}
R.slice (R.map (\x -> x :+ x) $ grow2d wsize (zpad arr)) (Z:.All:.n)
{-# INLINE fftslice #-}
grow2d :: Int -> Array D DIM2 Double -> Array D DIM2 Double
grow2d n arr = {-# SCC "grow2d" #-} R.traverse arr f g where
f _ = Z :. n :. y
_:.x:.y = R.extent arr
g h (_:.i:.j)
| i' >= 4 = k/4
| otherwise = h (Z:.i':.j)
where
k = h (Z:.i'-3:.j) + h (Z:.i'-2:.j) + h (Z:.i'-1:.j) + h (Z:.i':.j)
i' = fst $ properFraction $ (x' * fromIntegral i / n')
n' = fromIntegral n :: Double
x' = fromIntegral x
{-# INLINE grow2d #-}
zpad :: Array D DIM2 Double -> Array D DIM2 Double
zpad arr = {-# SCC "zpad" #-} R.reshape sh' arr' where
_:.x:.y = R.extent arr
len = x * y
zeros = R.fromFunction zsh (const 0)
zsh = Z :. len
sh' = Z :. (2*x) :. y
arr' = R.append (R.reshape zsh arr) zeros
{-# INLINE zpad #-}
|
8c6794b6/spectrofy
|
Spectrofy/Synth.hs
|
bsd-3-clause
| 4,204 | 0 | 16 | 957 | 1,662 | 880 | 782 | -1 | -1 |
module Paths_Demotivation (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
version :: Version
version = Version [0,1,0,0] []
bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/home/michael/CodeRepository/Demotivation/.stack-work/install/x86_64-linux/lts-3.13/7.10.2/bin"
libdir = "/home/michael/CodeRepository/Demotivation/.stack-work/install/x86_64-linux/lts-3.13/7.10.2/lib/x86_64-linux-ghc-7.10.2/Demotivation-0.1.0.0-LXV8E2iIDbJ2sYgWYZwx7a"
datadir = "/home/michael/CodeRepository/Demotivation/.stack-work/install/x86_64-linux/lts-3.13/7.10.2/share/x86_64-linux-ghc-7.10.2/Demotivation-0.1.0.0"
libexecdir = "/home/michael/CodeRepository/Demotivation/.stack-work/install/x86_64-linux/lts-3.13/7.10.2/libexec"
sysconfdir = "/home/michael/CodeRepository/Demotivation/.stack-work/install/x86_64-linux/lts-3.13/7.10.2/etc"
getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "Demotivation_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "Demotivation_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "Demotivation_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "Demotivation_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "Demotivation_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
|
Michaelt293/Demotivation
|
.stack-work/dist/x86_64-linux/Cabal-1.22.4.0/build/autogen/Paths_Demotivation.hs
|
bsd-3-clause
| 1,730 | 0 | 10 | 177 | 362 | 206 | 156 | 28 | 1 |
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE LambdaCase #-}
module Main where
import Hans
import Hans.Device
import Hans.IP4.Dhcp.Client (DhcpLease(..),defaultDhcpConfig,dhcpClient)
import Hans.IP4.Packet (pattern WildcardIP4)
import Hans.Socket
import System.IO
import Control.Concurrent (forkIO,threadDelay)
import Control.Exception
import Control.Monad (forever,void)
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy.Char8 as L8
import System.Environment (getArgs)
import System.Exit (exitFailure)
main :: IO ()
main =
getArgs >>= \case
[name] -> run (S8.pack name)
_ -> fail "Expected a device name (i.e. en0)"
run :: S8.ByteString -> IO ()
run name = do
ns <- newNetworkStack defaultConfig
dev <- addDevice ns name defaultDeviceConfig
_ <- forkIO (showExceptions "processPackets" (processPackets ns))
startDevice dev
mbLease <- dhcpClient ns defaultDhcpConfig dev
case mbLease of
Just lease ->
putStrLn ("Assigned IP: " ++ show (unpackIP4 (dhcpAddr lease)))
Nothing -> do
putStrLn "Dhcp failed"
exitFailure
sock <- sListen ns defaultSocketConfig WildcardIP4 8080 10
void . forkIO . forever $ do
putStrLn "Waiting for a client"
client <- sAccept (sock :: TcpListenSocket IP4)
putStrLn "Got a client"
void $ forkIO (handleClient client)
forever $ do
threadDelay (secs 10)
dumpStats (devStats dev)
secs :: Int -> Int
secs = (*1000000)
showExceptions :: String -> IO a -> IO a
showExceptions l m = m `catch` \ e ->
do print (l, e :: SomeException)
throwIO e
handleClient :: TcpSocket IP4 -> IO ()
handleClient sock = loop `finally` sClose sock
where
loop =
do str <- sRead sock 1024
if L8.null str
then hPutStrLn stderr "Closing client"
else do
_ <- sWrite sock str
loop
|
GaloisInc/HaNS
|
examples/echo-server/Main.hs
|
bsd-3-clause
| 2,193 | 0 | 17 | 670 | 608 | 310 | 298 | 60 | 2 |
module Sound.Player.Widgets (
songWidget,
playbackProgressBar
) where
import Brick.Types (Widget)
import Brick.Widgets.Core ((<+>), str, fill, vLimit, vBox)
import qualified Brick.Widgets.List as L
import qualified Brick.Widgets.ProgressBar as P
import qualified Data.Vector as Vec
import GHC.Float (double2Float)
import Lens.Micro ((^.))
import Sound.Player.Types (Song(Song), Status(Play, Pause), Playback(Playback))
-- | A song 'Widget', one of the items in the songs list.
songWidget :: Song -> Widget
songWidget (Song _ path status) =
vLimit 1 $ str (statusSymbol status) <+> str " " <+> str path <+> fill ' '
where
statusSymbol Play = "♫"
statusSymbol Pause = "•"
statusSymbol _ = " "
-- | A 'Widget' that shows two progress bars, the top bar shows the path of
-- the playing song, the bottom bar shows the playhead position, song duration
-- and playback percentage.
playbackProgressBar :: Maybe Playback -> L.List Song -> Widget
playbackProgressBar mPlayback l =
vBox [ titlePlaybackProgressBar mPlayback l
, infoPlaybackProgressBar mPlayback
]
-- | A 'Widget' that shows a progress bar with the path of the song.
titlePlaybackProgressBar :: Maybe Playback -> L.List Song -> Widget
titlePlaybackProgressBar Nothing _ = str " "
titlePlaybackProgressBar (Just pb@(Playback playPos _ _ _ _)) l =
P.progressBar (Just path) (playbackProgress pb)
where
songs = l ^. L.listElementsL
(Song _ path _) = songs Vec.! playPos
-- | A 'Widget' that shows a progress bar with the playhead position, song
-- duration and playback percentage.
infoPlaybackProgressBar :: Maybe Playback -> Widget
infoPlaybackProgressBar Nothing = str " "
infoPlaybackProgressBar (Just pb@(Playback _ _ ph d _)) =
P.progressBar (Just title) progress
where
progress = playbackProgress pb
percentage :: Integer
percentage = round (progress * 100)
title =
formatSeconds (d - ph) ++ " / " ++
formatSeconds d ++ " ~ " ++
show percentage ++ "%"
-- | A 'Float' number between 0 and 1 that is playing song's progress.
playbackProgress :: Playback -> Float
playbackProgress (Playback _ _ ph d _) = 1 - (double2Float ph / double2Float d)
-- | Returns a string that is a time formatted as /mm:ss/
formatSeconds :: Double -> String
formatSeconds s = pad (minutes s) ++ ":" ++ pad (seconds s)
where
seconds :: Double -> Int
seconds n = round n `mod` 60
minutes :: Double -> Int
minutes n = round n `div` 60
pad :: Int -> String
pad n
| length ns < 2 = "0" ++ ns
| otherwise = ns
where
ns = show n
|
potomak/haskell-player
|
src/Sound/Player/Widgets.hs
|
bsd-3-clause
| 2,622 | 0 | 14 | 569 | 733 | 392 | 341 | 51 | 3 |
{-# LANGUAGE NoImplicitPrelude #-}
module Stack.Options.ScriptParser where
import Options.Applicative
import Options.Applicative.Builder.Extra
import Stack.Options.Completion
import Stack.Prelude
data ScriptOpts = ScriptOpts
{ soPackages :: ![String]
, soFile :: !FilePath
, soArgs :: ![String]
, soCompile :: !ScriptExecute
, soGhcOptions :: ![String]
, soScriptExtraDeps :: ![PackageIdentifierRevision]
}
deriving Show
data ScriptExecute
= SEInterpret
| SECompile
| SEOptimize
deriving Show
scriptOptsParser :: Parser ScriptOpts
scriptOptsParser = ScriptOpts
<$> many (strOption
(long "package" <>
metavar "PACKAGE(S)" <>
help "Additional package(s) that must be installed"))
<*> strArgument (metavar "FILE" <> completer (fileExtCompleter [".hs", ".lhs"]))
<*> many (strArgument (metavar "-- ARGUMENT(S) (e.g. stack script X.hs -- argument(s) to program)"))
<*> (flag' SECompile
( long "compile"
<> help "Compile the script without optimization and run the executable"
) <|>
flag' SEOptimize
( long "optimize"
<> help "Compile the script with optimization and run the executable"
) <|>
pure SEInterpret)
<*> many (strOption
(long "ghc-options" <>
metavar "OPTIONS" <>
completer ghcOptsCompleter <>
help "Additional options passed to GHC"))
<*> many (option extraDepRead
(long "extra-dep" <>
metavar "PACKAGE-VERSION" <>
help "Extra dependencies to be added to the snapshot"))
where
extraDepRead = eitherReader $ mapLeft show . parsePackageIdentifierRevision . fromString
|
juhp/stack
|
src/Stack/Options/ScriptParser.hs
|
bsd-3-clause
| 1,773 | 0 | 17 | 489 | 361 | 187 | 174 | 58 | 1 |
module Statistics.Quantile.Bench.Accuracy where
import qualified Data.Vector as V
import Statistics.Quantile.Types
import Statistics.Quantile.Util
import Statistics.Sample
import System.IO
err :: Double
-> Double
-> Double
err true estimate =
let e = abs (true - estimate)
in e * e
selectorAccuracy :: Stream IO
-> Quantile
-> Double
-> Selector IO
-> IO Double
selectorAccuracy src q true (Selector select) =
err true <$> select q src
benchAccuracy :: Int
-> FilePath
-> Quantile
-> Double
-> Selector IO
-> IO Deviation
benchAccuracy n fp q true s = do
as <- V.replicateM n accuracy
pure $ Deviation (mean as) (stdDev as)
where accuracy = do
h <- openFile fp ReadMode
r <- selectorAccuracy (streamHandle h) q true s
hClose h
pure r
|
olorin/slides
|
2015-08-26-fp-syd-approx-quantiles/approx-quantile/src/Statistics/Quantile/Bench/Accuracy.hs
|
mit
| 940 | 0 | 12 | 327 | 286 | 142 | 144 | 33 | 1 |
import Geometry
import Drawing
main = drawPicture myPicture
myPicture points =
red ( drawCircle'' (a,b) ) &
blue ( drawCircle'' (c,d) ) &
drawAutoLabels (list ++ intersects) &
drawPoints intersects &
message "Circle-Circle Intersection"
where list = take 4 points
[a,b,c,d] = list
intersects = circle_circle (c,d) (a,b)
|
alphalambda/hsmath
|
src/Learn/Geometry/demo05circlecircle.hs
|
gpl-2.0
| 367 | 0 | 12 | 95 | 137 | 73 | 64 | 12 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
-- |
-- Copyright: © 2018 Herbert Valerio Riedel
-- SPDX-License-Identifier: GPL-3.0-or-later
--
module PlanJson
( PlanJson(..)
, PIType(..)
, PlanItem(..)
, CompName(..), parseCompName, dispCompName, strCompName
, CompInfo(..)
) where
import Prelude.Local
import Data.Aeson
import Data.Aeson.Types
import qualified Data.Map as M
import qualified Data.Set as S
import Data.Text (Text)
import qualified Data.Text as T
-- import Database.PostgreSQL.Simple.FromField
import Database.PostgreSQL.Simple.ToField
import PkgId
-- TODO: "bin-file", "dist-dir"
data PlanJson = PlanJson
{ pjCabalVersion :: Ver
, pjCabalLibVersion :: Ver
, pjCompilerId :: PkgId
, pjArch :: Text -- TODO
, pjOs :: Text -- TODO
, pjItems :: M.Map UnitID PlanItem
} deriving Show
data PIType = PIBuiltin
| PIGlobal
| PILocal
| PILocal2
deriving (Show,Eq,Ord)
data PlanItem = PlanItem
{ piId :: UnitID
, piPId :: PkgId
, piType :: PIType
, piFlags :: M.Map Text Bool
, piSha256 :: Maybe Text -- TODO
, piComps :: M.Map CompName CompInfo
} deriving Show
-- | Component of a package
--
-- NB: a similiar type exists in cabal's codebase
data CompName
= CompNameLib
| CompNameSubLib Text
| CompNameExe Text
| CompNameTest Text
| CompNameBench Text
| CompNameSetup
deriving (Show, Eq, Ord)
data CompInfo = CompInfo
{ ciLibDeps :: S.Set UnitID
, ciExeDeps :: S.Set UnitID
} deriving Show
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
instance ToField CompName where
toField = toField . dispCompName
instance FromJSON CompName where
parseJSON = withText "CompName" $
(maybe (fail "invalid CompName") pure . parseCompName)
instance ToJSON CompName where
toJSON = toJSON . dispCompName
toEncoding = toEncoding . dispCompName
instance FromJSONKey CompName where
fromJSONKey = FromJSONKeyTextParser
(maybe (fail "CompName") pure . parseCompName)
instance ToJSONKey CompName where
toJSONKey = toJSONKeyText dispCompName
instance FromJSON CompInfo where
parseJSON = withObject "CompInfo" $ \o ->
CompInfo <$> o .:?! "depends"
<*> o .:?! "exe-depends"
parseCompName :: Text -> Maybe CompName
parseCompName t0 = case T.splitOn ":" t0 of
["lib"] -> Just $ CompNameLib
["lib",n] -> Just $ CompNameSubLib n
["exe",n] -> Just $ CompNameExe n
["bench",n] -> Just $ CompNameBench n
["test",n] -> Just $ CompNameTest n
["setup"] -> Just $ CompNameSetup
_ -> Nothing
strCompName :: CompName -> Maybe Text
strCompName = \case
CompNameLib -> Nothing
CompNameSubLib n -> Just n
CompNameExe n -> Just n
CompNameBench n -> Just n
CompNameTest n -> Just n
CompNameSetup -> Nothing
dispCompName :: CompName -> Text
dispCompName = \case
CompNameLib -> "lib"
CompNameSubLib n -> "lib:" <> n
CompNameExe n -> "exe:" <> n
CompNameBench n -> "bench:" <> n
CompNameTest n -> "test:" <> n
CompNameSetup -> "setup"
instance FromJSON PlanJson where
parseJSON = withObject "PlanJson" $ \o ->
PlanJson <$> o .: "cabal-version"
<*> o .: "cabal-lib-version"
<*> o .: "compiler-id"
<*> o .: "arch"
<*> o .: "os"
<*> (toMap =<< o .: "install-plan")
where
toMap pil = do
let pim = M.fromList [ (piId pi',pi') | pi' <- pil ]
unless (M.size pim == length pil) $
fail "install-plan[] has duplicate ids"
pure pim
instance FromJSON PlanItem where
parseJSON = withObject "PlanItem" $ \o -> do
mcomponents <- o .:? "components"
mcomponentname <- o .:? "component-name"
ty <- o .: "type"
mstyle <- o .:? "style"
piId <- o .: "id"
piPId <- PkgId <$> o .: "pkg-name" <*> o .: "pkg-version"
piType <- case (ty :: Text, mstyle :: Maybe Text) of
("pre-existing",Nothing) -> pure PIBuiltin
("configured",Just "global") -> pure PIGlobal
("configured",Just "local") -> pure PILocal
("configured",Just "inplace") -> pure PILocal2
_ -> fail (show (ty,mstyle))
piFlags <- o .:?! "flags"
piSha256 <- o .:? "pkg-src-sha256"
piComps <- case (mcomponents, mcomponentname) of
(Just comps0, Nothing) ->
pure comps0
(Nothing, Just cname) ->
M.singleton cname <$> parseJSON (Object o)
(Nothing, Nothing) | piType == PIBuiltin ->
M.singleton CompNameLib <$> parseJSON (Object o)
_ -> fail (show o)
pure PlanItem{..}
instance ToField PIType where
toField = toField . go
where
go :: PIType -> Text
go = \case
PIGlobal -> "global"
PILocal -> "local"
PILocal2 -> "local2"
PIBuiltin -> "builtin"
-- toComp :: Text -> CompName
-- toComp = fromMaybe undefined . parseCompName
(.:?!) :: (FromJSON a, Monoid a) => Object -> Text -> Parser a
o .:?! fld = o .:? fld .!= mempty
|
Rizary/hackage-matrix-builder
|
src-lib/PlanJson.hs
|
gpl-3.0
| 6,178 | 0 | 18 | 2,139 | 1,477 | 788 | 689 | 144 | 7 |
-- | Unify support for type ASTs
{-# LANGUAGE NoImplicitPrelude #-}
module Lamdu.Infer.Internal.Unify
( unifyUnsafe
) where
import Control.Lens.Operators
import Control.Monad (when, unless)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.State (StateT, evalStateT)
import qualified Control.Monad.Trans.State as State
import qualified Data.Foldable as Foldable
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Lamdu.Calc.Type (Type)
import qualified Lamdu.Calc.Type as T
import Lamdu.Calc.Type.FlatComposite (FlatComposite(..))
import qualified Lamdu.Calc.Type.FlatComposite as FlatComposite
import qualified Lamdu.Calc.Type.Vars as TV
import qualified Lamdu.Infer.Error as Err
import Lamdu.Infer.Internal.Monad (Infer)
import qualified Lamdu.Infer.Internal.Monad as M
import Lamdu.Infer.Internal.Scope (SkolemScope(..))
import qualified Lamdu.Infer.Internal.Scope as Scope
import Lamdu.Infer.Internal.Subst (Subst, CanSubst)
import qualified Lamdu.Infer.Internal.Subst as Subst
import Text.PrettyPrint.HughesPJClass (Pretty(..))
import Prelude.Compat
{-# INLINE unifyUnsafe #-}
unifyUnsafe :: Type -> Type -> Infer ()
unifyUnsafe = unifyGeneric
-- These tvs appear in a context that only allows given skolems, so
-- narrow down the skolem scopes of these tvs
narrowSkolemScopesIn :: Monad m => SkolemScope -> TV.TypeVars -> M.InferCtx m ()
narrowSkolemScopesIn allowedSkolems (TV.TypeVars tvs rvs) =
narrow tvs >> narrow rvs
where
narrow nonSkolems =
Foldable.traverse_ (M.narrowTVScope allowedSkolems)
(Set.toList nonSkolems)
varBind :: (M.VarKind t, Pretty t) => T.Var t -> t -> Infer ()
varBind u t
| mtTv == Just u = pure ()
| otherwise =
do
allSkolems <- M.getSkolems
case (u `TV.member` allSkolems, mtTv) of
(False, _) ->
-- Binding a non-skolem(u) to a type(t)
do
uAllowedSkolems <- M.getSkolemsInScope u
let tSkolems = TV.intersection allSkolems tFree
-- u&t both not skolems. Narrow the skolem
-- scope of any free var in t
narrowSkolemScopesIn uAllowedSkolems
(tFree `TV.difference` tSkolems)
-- Next we check if the skolems in 't' escape
-- the scope of u (uAllowedSkolems)
let unallowedSkolems =
tSkolems `TV.difference`
(uAllowedSkolems ^. Scope.skolemScopeVars)
unless (TV.null unallowedSkolems) $
M.throwError $ Err.SkolemEscapesScope (pPrint u) (pPrint t) (pPrint unallowedSkolems)
-- Occurs check:
when (u `TV.member` tFree) $
M.throwError $ Err.OccursCheckFail (pPrint u) (pPrint t)
M.tellSubst u t
(True, Nothing) -> M.throwError $ Err.SkolemNotPolymorphic (pPrint u) (pPrint t)
(True, Just tTv)
| tTv `TV.member` allSkolems -> M.throwError $ Err.SkolemsUnified (pPrint u) (pPrint t)
| otherwise ->
-- Binding a skolem(u) to a non-skolem type-var
do
SkolemScope tvAllowedSkolems <- M.getSkolemsInScope tTv
unless (u `TV.member` tvAllowedSkolems) $
M.throwError $ Err.SkolemEscapesScope (pPrint u) (pPrint t) (pPrint u)
M.tellSubst tTv (TV.lift u)
where
tFree = TV.free t
mtTv = TV.unlift t
class CanSubst t => Unify t where
unifyGeneric :: t -> t -> Infer ()
closedRecord :: Map T.Tag Type -> T.Row
closedRecord fields = FlatComposite.toComposite (FlatComposite fields Nothing)
unifyFlatToPartial ::
Subst -> (Map T.Tag Type, T.RowVar) -> Map T.Tag Type ->
Infer ()
unifyFlatToPartial s (tfields, tname) ufields
| not (Map.null uniqueTFields) =
M.throwError $
Err.TypesDoNotUnity
(pPrint (FlatComposite.toComposite (FlatComposite tfields (Just tname))))
(pPrint (closedRecord ufields))
| otherwise =
varBind tname $
Subst.apply s $
FlatComposite.toComposite $ FlatComposite uniqueUFields Nothing
where
uniqueTFields = tfields `Map.difference` ufields
uniqueUFields = ufields `Map.difference` tfields
unifyFlatPartials ::
Subst ->
(Map T.Tag Type, T.RowVar) ->
(Map T.Tag Type, T.RowVar) ->
Infer ()
unifyFlatPartials s0 (tfields, tname) (ufields, uname) =
do
tScope <- M.getSkolemsInScope tname
uScope <- M.getSkolemsInScope uname
restTv <- M.freshInferredVar (tScope `Scope.skolemScopeIntersection` uScope) "r"
((), s1) <-
M.listenSubst $ varBind tname $
Subst.apply s0 $
Map.foldrWithKey T.RExtend restTv uniqueUFields
varBind uname $ Subst.apply (s0 <> s1) $
Map.foldrWithKey T.RExtend restTv uniqueTFields
where
uniqueTFields = tfields `Map.difference` ufields
uniqueUFields = ufields `Map.difference` tfields
unifyFlatFulls ::
Map T.Tag Type -> Map T.Tag Type -> Infer ()
unifyFlatFulls tfields ufields
| Map.keys tfields /= Map.keys ufields =
M.throwError $
Err.TypesDoNotUnity
(pPrint (closedRecord tfields))
(pPrint (closedRecord ufields))
| otherwise = pure mempty
unifyChild :: Unify t => t -> t -> StateT Subst Infer ()
unifyChild t u =
do
old <- State.get
((), s) <- lift $ M.listenSubst $ unifyGeneric (Subst.apply old t) (Subst.apply old u)
State.put (old <> s)
unifyIntersection :: (Unify a, Ord k) => Map k a -> Map k a -> Infer ()
unifyIntersection tfields ufields =
(`evalStateT` mempty) . Foldable.sequence_ $
Map.intersectionWith unifyChild tfields ufields
unifyFlattened :: FlatComposite -> FlatComposite -> Infer ()
unifyFlattened
(FlatComposite tfields tvar)
(FlatComposite ufields uvar) =
do
((), s) <- M.listenSubst $ unifyIntersection tfields ufields
case (tvar, uvar) of
(Nothing , Nothing ) -> unifyFlatFulls tfields ufields
(Just tname, Just uname) -> unifyFlatPartials s (tfields, tname) (ufields, uname)
(Just tname, Nothing ) -> unifyFlatToPartial s (tfields, tname) ufields
(Nothing , Just uname) -> unifyFlatToPartial s (ufields, uname) tfields
dontUnify :: Pretty t => t -> t -> Infer ()
dontUnify x y =
M.throwError $ Err.TypesDoNotUnity (pPrint x) (pPrint y)
instance Unify Type where
unifyGeneric (T.TFun l r) (T.TFun l' r') =
do
((), s1) <- M.listenSubst $ unifyGeneric l l'
unifyGeneric
(Subst.apply s1 r)
(Subst.apply s1 r')
unifyGeneric (T.TInst c0 p0) (T.TInst c1 p1)
| c0 == c1 && Map.keys p0 == Map.keys p1 = unifyIntersection p0 p1
unifyGeneric (T.TVar u) t = varBind u t
unifyGeneric t (T.TVar u) = varBind u t
unifyGeneric (T.TRecord x) (T.TRecord y) = unifyGeneric x y
unifyGeneric (T.TVariant x) (T.TVariant y) = unifyGeneric x y
unifyGeneric t1 t2 = dontUnify t1 t2
instance Unify T.Row where
unifyGeneric T.REmpty T.REmpty = pure ()
unifyGeneric (T.RVar u) t = varBind u t
unifyGeneric t (T.RVar u) = varBind u t
unifyGeneric
t@(T.RExtend f0 t0 r0)
u@(T.RExtend f1 t1 r1)
| f0 == f1 =
do
((), s) <- M.listenSubst $ unifyGeneric t0 t1
unifyGeneric (Subst.apply s r0) (Subst.apply s r1)
| otherwise =
unifyFlattened
(FlatComposite.fromComposite t)
(FlatComposite.fromComposite u)
unifyGeneric t1 t2 = dontUnify t1 t2
|
lamdu/Algorithm-W-Step-By-Step
|
src/Lamdu/Infer/Internal/Unify.hs
|
gpl-3.0
| 8,360 | 0 | 19 | 2,715 | 2,462 | 1,273 | 1,189 | 167 | 4 |
-----------------------------------------------------------------------------
-- |
-- Module : CK.Parsers.XML.XmlConfigurationParser
-- License : LGPL
--
-- Stability : under construction
-- Portability : unknown
--
-- An XML parser for the configuration knowledge.
-- This module does not yet use the asset-specific typed representation of CK.
--
-----------------------------------------------------------------------------
module CK.Parsers.XML.XmlConfigurationParser (parseXmlConfigurationKnowledge)
where
import BasicTypes
import Text.XML.HXT.Core
import Text.XML.HXT.RelaxNG
import System.Environment
import CK.Parsers.XML.XmlConfigurationKnowledge
-- |
-- XML parser for a configuration knowledge file.
-- It results either Success or Fail, if the file is
-- not valid.
--
parseXmlConfigurationKnowledge schema fileName =
do
errs <- checkConfigurationFile schema fileName
case errs of
[] -> do
configuration <- parseXmlConfigurationKnowledge' fileName
return $ configuration
otherwise -> do
let errs' = concat $ map show errs
return $ Fail errs'
checkConfigurationFile schema fileName =
do
errs <- runX ( errorMsgCollect
>>>
readDocument [ withValidate yes
, withRelaxNG (createURI schema)
, withErrors yes
] (createURI fileName)
>>>
getErrorMessages
) ;
return errs
parseXmlConfigurationKnowledge' fileName =
do
c <- runX ( xunpickleDocument xpConfigurationKnowledge [ withValidate yes
, withTrace 1
, withRemoveWS yes
, withPreserveComment yes
] (createURI fileName) )
case c of
[x] -> return $ Success x
otherwise -> return $ Fail "Unexpected error found when parsing the configuration knowledge."
--
-- The parser implementation using HXT library.
-- It requires several picklers.
--
instance XmlPickler XmlConfigurationKnowledge where
xpickle = xpConfigurationKnowledge
instance XmlPickler XmlConfiguration where
xpickle = xpConfiguration
instance XmlPickler XmlTransformation where
xpickle = xpTransformation
xpConfigurationKnowledge :: PU XmlConfigurationKnowledge
xpConfigurationKnowledge =
xpElem "configurationModel" $
xpWrap ( XmlConfigurationKnowledge, \ (XmlConfigurationKnowledge c) -> (c) ) $
(xpList xpConfiguration)
xpConfiguration :: PU XmlConfiguration
xpConfiguration =
xpElem "configuration" $
xpWrap ( uncurry4 XmlConfiguration, \ (XmlConfiguration e t r p) -> (e, t, r, p) ) $
xp4Tuple ( xpElem "expression" xpText )
( xpList xpTransformation )
( xpOption ( xpElem "required" xpText ) )
( xpOption ( xpElem "provided" xpText ) )
xpTransformation :: PU XmlTransformation
xpTransformation =
xpElem "transformation" $
xpWrap ( uncurry XmlTransformation, \ (XmlTransformation n a) -> (n, a) ) $
xpPair ( xpElem "name" xpText ) ( xpElem "args" xpText )
|
alessandroleite/hephaestus-pl
|
src/configuration-knowledge/src/CK/Parsers/XML/XmlConfigurationParser.hs
|
lgpl-3.0
| 3,335 | 26 | 16 | 999 | 628 | 331 | 297 | 61 | 2 |
module Main where
import Test.Tasty
-- import Test.Tasty.QuickCheck as QC
-- import Test.Tasty.HUnit as HU
-- import Test.Tasty.Golden as TG
import Test.Tasty.Hspec
specs :: Spec
specs = undefined
tests :: TestTree
tests = testGroup "main"
[ testCase "something" specs
]
main = defaultMain tests
|
erochest/life-cast
|
specs/Specs.hs
|
apache-2.0
| 313 | 0 | 7 | 61 | 59 | 35 | 24 | 9 | 1 |
{-# LANGUAGE CPP, DeriveDataTypeable, TupleSections #-}
{-# OPTIONS -Wall #-}
module Language.Paraiso.Optimization.DeadCodeElimination (
deadCodeElimination
) where
import Control.Applicative
import qualified Data.Graph.Inductive as FGL
import Data.Maybe
import qualified Data.Vector as V
import qualified Language.Paraiso.Annotation as Anot
import qualified Language.Paraiso.Annotation.Execution as Anot
import Language.Paraiso.Prelude
import Language.Paraiso.OM.Graph
import Language.Paraiso.Optimization.Graph
import Prelude hiding ((++))
-- | an optimization that changes nothing.
deadCodeElimination :: Optimization
deadCodeElimination = removeDead . markDead
markDead :: Optimization
markDead graph = imap update graph
where
update :: FGL.Node -> Anot.Annotation -> Anot.Annotation
update i a = Anot.set (Anot.Alive $ memoAlive V.! i) a
memoAlive :: V.Vector Bool
memoAlive = V.generate (FGL.noNodes graph) alive
alive i = case FGL.lab graph i of
Nothing -> error $ "node [" ++ show i ++ "] disappeared"
Just x -> case x of
NInst (Store _)_ -> True
NInst (Load _)_ -> True
_ -> or $ map (memoAlive V.!) $ FGL.suc graph i
removeDead :: Optimization
removeDead graph = graph2
where
graph2 = FGL.mkGraph newNodes newEdges
newNodes =
catMaybes $
fmap (\(idx, lab) -> (,lab) <$> renumber idx) $
FGL.labNodes graph
newEdges =
catMaybes $
fmap (\(iFrom, iTo, lab) -> (,,lab) <$> renumber iFrom <*> renumber iTo) $
FGL.labEdges graph
renumber :: Int -> Maybe Int
renumber = (oldToNew V.!)
oldToNew :: V.Vector (Maybe FGL.Node)
oldToNew =
V.update (V.replicate (FGL.noNodes graph) (Nothing)) $
V.imap (\newIdx oldIdx -> (oldIdx, Just newIdx)) $
newToOld
newToOld :: V.Vector FGL.Node
newToOld =
V.filter alive $ -- filter only alive nodes of
V.generate (FGL.noNodes graph) id -- all the node indices
alive :: FGL.Node -> Bool
alive i = case Anot.toMaybe $ getA $ fromJust $ FGL.lab graph i of
Just (Anot.Alive x) -> x
Nothing -> error $ "please markDead before removeDead"
|
nushio3/Paraiso
|
Language/Paraiso/Optimization/DeadCodeElimination.hs
|
bsd-3-clause
| 2,354 | 0 | 16 | 669 | 673 | 365 | 308 | 54 | 4 |
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1998
\section[TcForeign]{Typechecking \tr{foreign} declarations}
A foreign declaration is used to either give an externally
implemented function a Haskell type (and calling interface) or
give a Haskell function an external calling interface. Either way,
the range of argument and result types these functions can accommodate
is restricted to what the outside world understands (read C), and this
module checks to see if a foreign declaration has got a legal type.
-}
{-# LANGUAGE CPP #-}
module TcForeign
( tcForeignImports
, tcForeignExports
-- Low-level exports for hooks
, isForeignImport, isForeignExport
, tcFImport, tcFExport
, tcForeignImports'
, tcCheckFIType, checkCTarget, checkForeignArgs, checkForeignRes
, normaliseFfiType
, nonIOok, mustBeIO
, checkSafe, noCheckSafe
, tcForeignExports'
, tcCheckFEType
) where
#include "HsVersions.h"
import HsSyn
import TcRnMonad
import TcHsType
import TcExpr
import TcEnv
import FamInst
import FamInstEnv
import Coercion
import Type
import ForeignCall
import ErrUtils
import Id
import Name
import RdrName
import DataCon
import TyCon
import TcType
import PrelNames
import DynFlags
import Outputable
import Platform
import SrcLoc
import Bag
import Hooks
import qualified GHC.LanguageExtensions as LangExt
import Control.Monad
import Data.Maybe
-- Defines a binding
isForeignImport :: LForeignDecl name -> Bool
isForeignImport (L _ (ForeignImport {})) = True
isForeignImport _ = False
-- Exports a binding
isForeignExport :: LForeignDecl name -> Bool
isForeignExport (L _ (ForeignExport {})) = True
isForeignExport _ = False
{-
Note [Don't recur in normaliseFfiType']
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
normaliseFfiType' is the workhorse for normalising a type used in a foreign
declaration. If we have
newtype Age = MkAge Int
we want to see that Age -> IO () is the same as Int -> IO (). But, we don't
need to recur on any type parameters, because no paramaterized types (with
interesting parameters) are marshalable! The full list of marshalable types
is in the body of boxedMarshalableTyCon in TcType. The only members of that
list not at kind * are Ptr, FunPtr, and StablePtr, all of which get marshaled
the same way regardless of type parameter. So, no need to recur into
parameters.
Similarly, we don't need to look in AppTy's, because nothing headed by
an AppTy will be marshalable.
Note [FFI type roles]
~~~~~~~~~~~~~~~~~~~~~
The 'go' helper function within normaliseFfiType' always produces
representational coercions. But, in the "children_only" case, we need to
use these coercions in a TyConAppCo. Accordingly, the roles on the coercions
must be twiddled to match the expectation of the enclosing TyCon. However,
we cannot easily go from an R coercion to an N one, so we forbid N roles
on FFI type constructors. Currently, only two such type constructors exist:
IO and FunPtr. Thus, this is not an onerous burden.
If we ever want to lift this restriction, we would need to make 'go' take
the target role as a parameter. This wouldn't be hard, but it's a complication
not yet necessary and so is not yet implemented.
-}
-- normaliseFfiType takes the type from an FFI declaration, and
-- evaluates any type synonyms, type functions, and newtypes. However,
-- we are only allowed to look through newtypes if the constructor is
-- in scope. We return a bag of all the newtype constructors thus found.
-- Always returns a Representational coercion
normaliseFfiType :: Type -> TcM (Coercion, Type, Bag GlobalRdrElt)
normaliseFfiType ty
= do fam_envs <- tcGetFamInstEnvs
normaliseFfiType' fam_envs ty
normaliseFfiType' :: FamInstEnvs -> Type -> TcM (Coercion, Type, Bag GlobalRdrElt)
normaliseFfiType' env ty0 = go initRecTc ty0
where
go :: RecTcChecker -> Type -> TcM (Coercion, Type, Bag GlobalRdrElt)
go rec_nts ty
| Just ty' <- coreView ty -- Expand synonyms
= go rec_nts ty'
| Just (tc, tys) <- splitTyConApp_maybe ty
= go_tc_app rec_nts tc tys
| Just (bndr, inner_ty) <- splitPiTy_maybe ty
, Just tyvar <- binderVar_maybe bndr
= do (coi, nty1, gres1) <- go rec_nts inner_ty
return ( mkHomoForAllCos [tyvar] coi
, mkForAllTy bndr nty1, gres1 )
| otherwise -- see Note [Don't recur in normaliseFfiType']
= return (mkRepReflCo ty, ty, emptyBag)
go_tc_app :: RecTcChecker -> TyCon -> [Type]
-> TcM (Coercion, Type, Bag GlobalRdrElt)
go_tc_app rec_nts tc tys
-- We don't want to look through the IO newtype, even if it is
-- in scope, so we have a special case for it:
| tc_key `elem` [ioTyConKey, funPtrTyConKey, funTyConKey]
-- These *must not* have nominal roles on their parameters!
-- See Note [FFI type roles]
= children_only
| isNewTyCon tc -- Expand newtypes
, Just rec_nts' <- checkRecTc rec_nts tc
-- See Note [Expanding newtypes] in TyCon.hs
-- We can't just use isRecursiveTyCon; sometimes recursion is ok:
-- newtype T = T (Ptr T)
-- Here, we don't reject the type for being recursive.
-- If this is a recursive newtype then it will normally
-- be rejected later as not being a valid FFI type.
= do { rdr_env <- getGlobalRdrEnv
; case checkNewtypeFFI rdr_env tc of
Nothing -> nothing
Just gre -> do { (co', ty', gres) <- go rec_nts' nt_rhs
; return (mkTransCo nt_co co', ty', gre `consBag` gres) } }
| isFamilyTyCon tc -- Expand open tycons
, (co, ty) <- normaliseTcApp env Representational tc tys
, not (isReflexiveCo co)
= do (co', ty', gres) <- go rec_nts ty
return (mkTransCo co co', ty', gres)
| otherwise
= nothing -- see Note [Don't recur in normaliseFfiType']
where
tc_key = getUnique tc
children_only
= do xs <- mapM (go rec_nts) tys
let (cos, tys', gres) = unzip3 xs
-- the (repeat Representational) is because 'go' always
-- returns R coercions
cos' = zipWith3 downgradeRole (tyConRoles tc)
(repeat Representational) cos
return ( mkTyConAppCo Representational tc cos'
, mkTyConApp tc tys', unionManyBags gres)
nt_co = mkUnbranchedAxInstCo Representational (newTyConCo tc) tys []
nt_rhs = newTyConInstRhs tc tys
ty = mkTyConApp tc tys
nothing = return (mkRepReflCo ty, ty, emptyBag)
checkNewtypeFFI :: GlobalRdrEnv -> TyCon -> Maybe GlobalRdrElt
checkNewtypeFFI rdr_env tc
| Just con <- tyConSingleDataCon_maybe tc
, [gre] <- lookupGRE_Name rdr_env (dataConName con)
= Just gre -- See Note [Newtype constructor usage in foreign declarations]
| otherwise
= Nothing
{-
Note [Newtype constructor usage in foreign declarations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC automatically "unwraps" newtype constructors in foreign import/export
declarations. In effect that means that a newtype data constructor is
used even though it is not mentioned expclitly in the source, so we don't
want to report it as "defined but not used" or "imported but not used".
eg newtype D = MkD Int
foreign import foo :: D -> IO ()
Here 'MkD' us used. See Trac #7408.
GHC also expands type functions during this process, so it's not enough
just to look at the free variables of the declaration.
eg type instance F Bool = D
foreign import bar :: F Bool -> IO ()
Here again 'MkD' is used.
So we really have wait until the type checker to decide what is used.
That's why tcForeignImports and tecForeignExports return a (Bag GRE)
for the newtype constructors they see. Then TcRnDriver can add them
to the module's usages.
************************************************************************
* *
\subsection{Imports}
* *
************************************************************************
-}
tcForeignImports :: [LForeignDecl Name] -> TcM ([Id], [LForeignDecl Id], Bag GlobalRdrElt)
tcForeignImports decls
= getHooked tcForeignImportsHook tcForeignImports' >>= ($ decls)
tcForeignImports' :: [LForeignDecl Name] -> TcM ([Id], [LForeignDecl Id], Bag GlobalRdrElt)
-- For the (Bag GlobalRdrElt) result,
-- see Note [Newtype constructor usage in foreign declarations]
tcForeignImports' decls
= do { (ids, decls, gres) <- mapAndUnzip3M tcFImport $
filter isForeignImport decls
; return (ids, decls, unionManyBags gres) }
tcFImport :: LForeignDecl Name -> TcM (Id, LForeignDecl Id, Bag GlobalRdrElt)
tcFImport (L dloc fo@(ForeignImport { fd_name = L nloc nm, fd_sig_ty = hs_ty
, fd_fi = imp_decl }))
= setSrcSpan dloc $ addErrCtxt (foreignDeclCtxt fo) $
do { sig_ty <- solveEqualities $ tcHsSigType (ForSigCtxt nm) hs_ty
; (norm_co, norm_sig_ty, gres) <- normaliseFfiType sig_ty
; let
-- Drop the foralls before inspecting the
-- structure of the foreign type.
(bndrs, res_ty) = tcSplitPiTys norm_sig_ty
arg_tys = mapMaybe binderRelevantType_maybe bndrs
id = mkLocalId nm sig_ty
-- Use a LocalId to obey the invariant that locally-defined
-- things are LocalIds. However, it does not need zonking,
-- (so TcHsSyn.zonkForeignExports ignores it).
; imp_decl' <- tcCheckFIType arg_tys res_ty imp_decl
-- Can't use sig_ty here because sig_ty :: Type and
-- we need HsType Id hence the undefined
; let fi_decl = ForeignImport { fd_name = L nloc id
, fd_sig_ty = undefined
, fd_co = mkSymCo norm_co
, fd_fi = imp_decl' }
; return (id, L dloc fi_decl, gres) }
tcFImport d = pprPanic "tcFImport" (ppr d)
-- ------------ Checking types for foreign import ----------------------
tcCheckFIType :: [Type] -> Type -> ForeignImport -> TcM ForeignImport
tcCheckFIType arg_tys res_ty (CImport (L lc cconv) safety mh l@(CLabel _) src)
-- Foreign import label
= do checkCg checkCOrAsmOrLlvmOrInterp
-- NB check res_ty not sig_ty!
-- In case sig_ty is (forall a. ForeignPtr a)
check (isFFILabelTy (mkFunTys arg_tys res_ty)) (illegalForeignTyErr Outputable.empty)
cconv' <- checkCConv cconv
return (CImport (L lc cconv') safety mh l src)
tcCheckFIType arg_tys res_ty (CImport (L lc cconv) safety mh CWrapper src) = do
-- Foreign wrapper (former f.e.d.)
-- The type must be of the form ft -> IO (FunPtr ft), where ft is a valid
-- foreign type. For legacy reasons ft -> IO (Ptr ft) is accepted, too.
-- The use of the latter form is DEPRECATED, though.
checkCg checkCOrAsmOrLlvmOrInterp
cconv' <- checkCConv cconv
case arg_tys of
[arg1_ty] -> do checkForeignArgs isFFIExternalTy arg1_tys
checkForeignRes nonIOok checkSafe isFFIExportResultTy res1_ty
checkForeignRes mustBeIO checkSafe (isFFIDynTy arg1_ty) res_ty
where
(arg1_tys, res1_ty) = tcSplitFunTys arg1_ty
_ -> addErrTc (illegalForeignTyErr Outputable.empty (text "One argument expected"))
return (CImport (L lc cconv') safety mh CWrapper src)
tcCheckFIType arg_tys res_ty idecl@(CImport (L lc cconv) (L ls safety) mh
(CFunction target) src)
| isDynamicTarget target = do -- Foreign import dynamic
checkCg checkCOrAsmOrLlvmOrInterp
cconv' <- checkCConv cconv
case arg_tys of -- The first arg must be Ptr or FunPtr
[] ->
addErrTc (illegalForeignTyErr Outputable.empty (text "At least one argument expected"))
(arg1_ty:arg_tys) -> do
dflags <- getDynFlags
let curried_res_ty = mkFunTys arg_tys res_ty
check (isFFIDynTy curried_res_ty arg1_ty)
(illegalForeignTyErr argument)
checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys
checkForeignRes nonIOok checkSafe (isFFIImportResultTy dflags) res_ty
return $ CImport (L lc cconv') (L ls safety) mh (CFunction target) src
| cconv == PrimCallConv = do
dflags <- getDynFlags
checkTc (xopt LangExt.GHCForeignImportPrim dflags)
(text "Use GHCForeignImportPrim to allow `foreign import prim'.")
checkCg checkCOrAsmOrLlvmOrInterp
checkCTarget target
checkTc (playSafe safety)
(text "The safe/unsafe annotation should not be used with `foreign import prim'.")
checkForeignArgs (isFFIPrimArgumentTy dflags) arg_tys
-- prim import result is more liberal, allows (#,,#)
checkForeignRes nonIOok checkSafe (isFFIPrimResultTy dflags) res_ty
return idecl
| otherwise = do -- Normal foreign import
checkCg checkCOrAsmOrLlvmOrInterp
cconv' <- checkCConv cconv
checkCTarget target
dflags <- getDynFlags
checkForeignArgs (isFFIArgumentTy dflags safety) arg_tys
checkForeignRes nonIOok checkSafe (isFFIImportResultTy dflags) res_ty
checkMissingAmpersand dflags arg_tys res_ty
case target of
StaticTarget _ _ _ False
| not (null arg_tys) ->
addErrTc (text "`value' imports cannot have function types")
_ -> return ()
return $ CImport (L lc cconv') (L ls safety) mh (CFunction target) src
-- This makes a convenient place to check
-- that the C identifier is valid for C
checkCTarget :: CCallTarget -> TcM ()
checkCTarget (StaticTarget _ str _ _) = do
checkCg checkCOrAsmOrLlvmOrInterp
checkTc (isCLabelString str) (badCName str)
checkCTarget DynamicTarget = panic "checkCTarget DynamicTarget"
checkMissingAmpersand :: DynFlags -> [Type] -> Type -> TcM ()
checkMissingAmpersand dflags arg_tys res_ty
| null arg_tys && isFunPtrTy res_ty &&
wopt Opt_WarnDodgyForeignImports dflags
= addWarn (text "possible missing & in foreign import of FunPtr")
| otherwise
= return ()
{-
************************************************************************
* *
\subsection{Exports}
* *
************************************************************************
-}
tcForeignExports :: [LForeignDecl Name]
-> TcM (LHsBinds TcId, [LForeignDecl TcId], Bag GlobalRdrElt)
tcForeignExports decls =
getHooked tcForeignExportsHook tcForeignExports' >>= ($ decls)
tcForeignExports' :: [LForeignDecl Name]
-> TcM (LHsBinds TcId, [LForeignDecl TcId], Bag GlobalRdrElt)
-- For the (Bag GlobalRdrElt) result,
-- see Note [Newtype constructor usage in foreign declarations]
tcForeignExports' decls
= foldlM combine (emptyLHsBinds, [], emptyBag) (filter isForeignExport decls)
where
combine (binds, fs, gres1) (L loc fe) = do
(b, f, gres2) <- setSrcSpan loc (tcFExport fe)
return (b `consBag` binds, L loc f : fs, gres1 `unionBags` gres2)
tcFExport :: ForeignDecl Name -> TcM (LHsBind Id, ForeignDecl Id, Bag GlobalRdrElt)
tcFExport fo@(ForeignExport { fd_name = L loc nm, fd_sig_ty = hs_ty, fd_fe = spec })
= addErrCtxt (foreignDeclCtxt fo) $ do
sig_ty <- tcHsSigType (ForSigCtxt nm) hs_ty
rhs <- tcPolyExpr (nlHsVar nm) sig_ty
(norm_co, norm_sig_ty, gres) <- normaliseFfiType sig_ty
spec' <- tcCheckFEType norm_sig_ty spec
-- we're exporting a function, but at a type possibly more
-- constrained than its declared/inferred type. Hence the need
-- to create a local binding which will call the exported function
-- at a particular type (and, maybe, overloading).
-- We need to give a name to the new top-level binding that
-- is *stable* (i.e. the compiler won't change it later),
-- because this name will be referred to by the C code stub.
id <- mkStableIdFromName nm sig_ty loc mkForeignExportOcc
return ( mkVarBind id rhs
, ForeignExport { fd_name = L loc id
, fd_sig_ty = undefined
, fd_co = norm_co, fd_fe = spec' }
, gres)
tcFExport d = pprPanic "tcFExport" (ppr d)
-- ------------ Checking argument types for foreign export ----------------------
tcCheckFEType :: Type -> ForeignExport -> TcM ForeignExport
tcCheckFEType sig_ty (CExport (L l (CExportStatic esrc str cconv)) src) = do
checkCg checkCOrAsmOrLlvm
checkTc (isCLabelString str) (badCName str)
cconv' <- checkCConv cconv
checkForeignArgs isFFIExternalTy arg_tys
checkForeignRes nonIOok noCheckSafe isFFIExportResultTy res_ty
return (CExport (L l (CExportStatic esrc str cconv')) src)
where
-- Drop the foralls before inspecting n
-- the structure of the foreign type.
(bndrs, res_ty) = tcSplitPiTys sig_ty
arg_tys = mapMaybe binderRelevantType_maybe bndrs
{-
************************************************************************
* *
\subsection{Miscellaneous}
* *
************************************************************************
-}
------------ Checking argument types for foreign import ----------------------
checkForeignArgs :: (Type -> Validity) -> [Type] -> TcM ()
checkForeignArgs pred tys = mapM_ go tys
where
go ty = check (pred ty) (illegalForeignTyErr argument)
------------ Checking result types for foreign calls ----------------------
-- | Check that the type has the form
-- (IO t) or (t) , and that t satisfies the given predicate.
-- When calling this function, any newtype wrappers (should) have been
-- already dealt with by normaliseFfiType.
--
-- We also check that the Safe Haskell condition of FFI imports having
-- results in the IO monad holds.
--
checkForeignRes :: Bool -> Bool -> (Type -> Validity) -> Type -> TcM ()
checkForeignRes non_io_result_ok check_safe pred_res_ty ty
| Just (_, res_ty) <- tcSplitIOType_maybe ty
= -- Got an IO result type, that's always fine!
check (pred_res_ty res_ty) (illegalForeignTyErr result)
-- Case for non-IO result type with FFI Import
| not non_io_result_ok
= addErrTc $ illegalForeignTyErr result (text "IO result type expected")
| otherwise
= do { dflags <- getDynFlags
; case pred_res_ty ty of
-- Handle normal typecheck fail, we want to handle this first and
-- only report safe haskell errors if the normal type check is OK.
NotValid msg -> addErrTc $ illegalForeignTyErr result msg
-- handle safe infer fail
_ | check_safe && safeInferOn dflags
-> recordUnsafeInfer emptyBag
-- handle safe language typecheck fail
_ | check_safe && safeLanguageOn dflags
-> addErrTc (illegalForeignTyErr result safeHsErr)
-- success! non-IO return is fine
_ -> return () }
where
safeHsErr =
text "Safe Haskell is on, all FFI imports must be in the IO monad"
nonIOok, mustBeIO :: Bool
nonIOok = True
mustBeIO = False
checkSafe, noCheckSafe :: Bool
checkSafe = True
noCheckSafe = False
-- Checking a supported backend is in use
checkCOrAsmOrLlvm :: HscTarget -> Validity
checkCOrAsmOrLlvm HscC = IsValid
checkCOrAsmOrLlvm HscAsm = IsValid
checkCOrAsmOrLlvm HscLlvm = IsValid
checkCOrAsmOrLlvm _
= NotValid (text "requires unregisterised, llvm (-fllvm) or native code generation (-fasm)")
checkCOrAsmOrLlvmOrInterp :: HscTarget -> Validity
checkCOrAsmOrLlvmOrInterp HscC = IsValid
checkCOrAsmOrLlvmOrInterp HscAsm = IsValid
checkCOrAsmOrLlvmOrInterp HscLlvm = IsValid
checkCOrAsmOrLlvmOrInterp HscInterpreted = IsValid
checkCOrAsmOrLlvmOrInterp _
= NotValid (text "requires interpreted, unregisterised, llvm or native code generation")
checkCg :: (HscTarget -> Validity) -> TcM ()
checkCg check = do
dflags <- getDynFlags
let target = hscTarget dflags
case target of
HscNothing -> return ()
_ ->
case check target of
IsValid -> return ()
NotValid err -> addErrTc (text "Illegal foreign declaration:" <+> err)
-- Calling conventions
checkCConv :: CCallConv -> TcM CCallConv
checkCConv CCallConv = return CCallConv
checkCConv CApiConv = return CApiConv
checkCConv StdCallConv = do dflags <- getDynFlags
let platform = targetPlatform dflags
if platformArch platform == ArchX86
then return StdCallConv
else do -- This is a warning, not an error. see #3336
when (wopt Opt_WarnUnsupportedCallingConventions dflags) $
addWarnTc (text "the 'stdcall' calling convention is unsupported on this platform," $$ text "treating as ccall")
return CCallConv
checkCConv PrimCallConv = do addErrTc (text "The `prim' calling convention can only be used with `foreign import'")
return PrimCallConv
checkCConv JavaScriptCallConv = do dflags <- getDynFlags
if platformArch (targetPlatform dflags) == ArchJavaScript
then return JavaScriptCallConv
else do addErrTc (text "The `javascript' calling convention is unsupported on this platform")
return JavaScriptCallConv
-- Warnings
check :: Validity -> (MsgDoc -> MsgDoc) -> TcM ()
check IsValid _ = return ()
check (NotValid doc) err_fn = addErrTc (err_fn doc)
illegalForeignTyErr :: SDoc -> SDoc -> SDoc
illegalForeignTyErr arg_or_res extra
= hang msg 2 extra
where
msg = hsep [ text "Unacceptable", arg_or_res
, text "type in foreign declaration:"]
-- Used for 'arg_or_res' argument to illegalForeignTyErr
argument, result :: SDoc
argument = text "argument"
result = text "result"
badCName :: CLabelString -> MsgDoc
badCName target
= sep [quotes (ppr target) <+> text "is not a valid C identifier"]
foreignDeclCtxt :: ForeignDecl Name -> SDoc
foreignDeclCtxt fo
= hang (text "When checking declaration:")
2 (ppr fo)
|
nushio3/ghc
|
compiler/typecheck/TcForeign.hs
|
bsd-3-clause
| 23,241 | 62 | 18 | 6,385 | 4,117 | 2,107 | 2,010 | 317 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.