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.TagManager.Accounts.Containers.Workspaces.Templates.Create
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a GTM Custom Template.
--
-- /See:/ <https://developers.google.com/tag-manager Tag Manager API Reference> for @tagmanager.accounts.containers.workspaces.templates.create@.
module Network.Google.Resource.TagManager.Accounts.Containers.Workspaces.Templates.Create
(
-- * REST Resource
AccountsContainersWorkspacesTemplatesCreateResource
-- * Creating a Request
, accountsContainersWorkspacesTemplatesCreate
, AccountsContainersWorkspacesTemplatesCreate
-- * Request Lenses
, aParent
, aXgafv
, aUploadProtocol
, aAccessToken
, aUploadType
, aPayload
, aCallback
) where
import Network.Google.Prelude
import Network.Google.TagManager.Types
-- | A resource alias for @tagmanager.accounts.containers.workspaces.templates.create@ method which the
-- 'AccountsContainersWorkspacesTemplatesCreate' request conforms to.
type AccountsContainersWorkspacesTemplatesCreateResource
=
"tagmanager" :>
"v2" :>
Capture "parent" Text :>
"templates" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] CustomTemplate :>
Post '[JSON] CustomTemplate
-- | Creates a GTM Custom Template.
--
-- /See:/ 'accountsContainersWorkspacesTemplatesCreate' smart constructor.
data AccountsContainersWorkspacesTemplatesCreate =
AccountsContainersWorkspacesTemplatesCreate'
{ _aParent :: !Text
, _aXgafv :: !(Maybe Xgafv)
, _aUploadProtocol :: !(Maybe Text)
, _aAccessToken :: !(Maybe Text)
, _aUploadType :: !(Maybe Text)
, _aPayload :: !CustomTemplate
, _aCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountsContainersWorkspacesTemplatesCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aParent'
--
-- * 'aXgafv'
--
-- * 'aUploadProtocol'
--
-- * 'aAccessToken'
--
-- * 'aUploadType'
--
-- * 'aPayload'
--
-- * 'aCallback'
accountsContainersWorkspacesTemplatesCreate
:: Text -- ^ 'aParent'
-> CustomTemplate -- ^ 'aPayload'
-> AccountsContainersWorkspacesTemplatesCreate
accountsContainersWorkspacesTemplatesCreate pAParent_ pAPayload_ =
AccountsContainersWorkspacesTemplatesCreate'
{ _aParent = pAParent_
, _aXgafv = Nothing
, _aUploadProtocol = Nothing
, _aAccessToken = Nothing
, _aUploadType = Nothing
, _aPayload = pAPayload_
, _aCallback = Nothing
}
-- | GTM Workspace\'s API relative path. Example:
-- accounts\/{account_id}\/containers\/{container_id}\/workspaces\/{workspace_id}
aParent :: Lens' AccountsContainersWorkspacesTemplatesCreate Text
aParent = lens _aParent (\ s a -> s{_aParent = a})
-- | V1 error format.
aXgafv :: Lens' AccountsContainersWorkspacesTemplatesCreate (Maybe Xgafv)
aXgafv = lens _aXgafv (\ s a -> s{_aXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
aUploadProtocol :: Lens' AccountsContainersWorkspacesTemplatesCreate (Maybe Text)
aUploadProtocol
= lens _aUploadProtocol
(\ s a -> s{_aUploadProtocol = a})
-- | OAuth access token.
aAccessToken :: Lens' AccountsContainersWorkspacesTemplatesCreate (Maybe Text)
aAccessToken
= lens _aAccessToken (\ s a -> s{_aAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
aUploadType :: Lens' AccountsContainersWorkspacesTemplatesCreate (Maybe Text)
aUploadType
= lens _aUploadType (\ s a -> s{_aUploadType = a})
-- | Multipart request metadata.
aPayload :: Lens' AccountsContainersWorkspacesTemplatesCreate CustomTemplate
aPayload = lens _aPayload (\ s a -> s{_aPayload = a})
-- | JSONP
aCallback :: Lens' AccountsContainersWorkspacesTemplatesCreate (Maybe Text)
aCallback
= lens _aCallback (\ s a -> s{_aCallback = a})
instance GoogleRequest
AccountsContainersWorkspacesTemplatesCreate
where
type Rs AccountsContainersWorkspacesTemplatesCreate =
CustomTemplate
type Scopes
AccountsContainersWorkspacesTemplatesCreate
=
'["https://www.googleapis.com/auth/tagmanager.edit.containers"]
requestClient
AccountsContainersWorkspacesTemplatesCreate'{..}
= go _aParent _aXgafv _aUploadProtocol _aAccessToken
_aUploadType
_aCallback
(Just AltJSON)
_aPayload
tagManagerService
where go
= buildClient
(Proxy ::
Proxy
AccountsContainersWorkspacesTemplatesCreateResource)
mempty
| brendanhay/gogol | gogol-tagmanager/gen/Network/Google/Resource/TagManager/Accounts/Containers/Workspaces/Templates/Create.hs | mpl-2.0 | 5,773 | 0 | 18 | 1,303 | 786 | 459 | 327 | 116 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.Autoscalers.Update
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates an autoscaler in the specified project using the data included
-- in the request.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.autoscalers.update@.
module Network.Google.Resource.Compute.Autoscalers.Update
(
-- * REST Resource
AutoscalersUpdateResource
-- * Creating a Request
, autoscalersUpdate
, AutoscalersUpdate
-- * Request Lenses
, auProject
, auZone
, auPayload
, auAutoscaler
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.autoscalers.update@ method which the
-- 'AutoscalersUpdate' request conforms to.
type AutoscalersUpdateResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"zones" :>
Capture "zone" Text :>
"autoscalers" :>
QueryParam "autoscaler" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Autoscaler :> Put '[JSON] Operation
-- | Updates an autoscaler in the specified project using the data included
-- in the request.
--
-- /See:/ 'autoscalersUpdate' smart constructor.
data AutoscalersUpdate = AutoscalersUpdate'
{ _auProject :: !Text
, _auZone :: !Text
, _auPayload :: !Autoscaler
, _auAutoscaler :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'AutoscalersUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'auProject'
--
-- * 'auZone'
--
-- * 'auPayload'
--
-- * 'auAutoscaler'
autoscalersUpdate
:: Text -- ^ 'auProject'
-> Text -- ^ 'auZone'
-> Autoscaler -- ^ 'auPayload'
-> AutoscalersUpdate
autoscalersUpdate pAuProject_ pAuZone_ pAuPayload_ =
AutoscalersUpdate'
{ _auProject = pAuProject_
, _auZone = pAuZone_
, _auPayload = pAuPayload_
, _auAutoscaler = Nothing
}
-- | Project ID for this request.
auProject :: Lens' AutoscalersUpdate Text
auProject
= lens _auProject (\ s a -> s{_auProject = a})
-- | Name of the zone for this request.
auZone :: Lens' AutoscalersUpdate Text
auZone = lens _auZone (\ s a -> s{_auZone = a})
-- | Multipart request metadata.
auPayload :: Lens' AutoscalersUpdate Autoscaler
auPayload
= lens _auPayload (\ s a -> s{_auPayload = a})
-- | Name of the autoscaler to update.
auAutoscaler :: Lens' AutoscalersUpdate (Maybe Text)
auAutoscaler
= lens _auAutoscaler (\ s a -> s{_auAutoscaler = a})
instance GoogleRequest AutoscalersUpdate where
type Rs AutoscalersUpdate = Operation
type Scopes AutoscalersUpdate =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient AutoscalersUpdate'{..}
= go _auProject _auZone _auAutoscaler (Just AltJSON)
_auPayload
computeService
where go
= buildClient
(Proxy :: Proxy AutoscalersUpdateResource)
mempty
| rueshyna/gogol | gogol-compute/gen/Network/Google/Resource/Compute/Autoscalers/Update.hs | mpl-2.0 | 3,983 | 0 | 17 | 977 | 550 | 326 | 224 | 83 | 1 |
module AlecAirport.A281511Spec (main, spec) where
import Test.Hspec
import AlecAirport.A281511 (a281511)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A281511" $
it "correctly computes the first 20 elements" $
take 20 (map a281511 [1..]) `shouldBe` expectedValue where
expectedValue = [1,1,2,1,2,2,3,1,3,2,4,3,1,4,4,2,5,3,3,4]
| peterokagey/haskellOEIS | test/AlecAirport/A281511Spec.hs | apache-2.0 | 357 | 0 | 10 | 59 | 160 | 95 | 65 | 10 | 1 |
{-# LANGUAGE ForeignFunctionInterface, CPP #-}
module Format where
import Foreign
import Foreign.C
import Foreign.Marshal.Alloc
import qualified Data.ByteString as B
import qualified Data.ByteString.Unsafe as BU
import Data.Monoid
import System.Posix.Files
data Format = F {
formatName :: String,
formatEntry :: Int,
formatHeaderSize :: Int,
formatHeaderCons :: Int -> IO (Ptr CChar)
}
instance Show Format where
show = formatName
writeFormat fmt name dat = do
hp <- formatHeaderCons fmt (B.length dat)
h <- BU.unsafePackCStringLen (hp,formatHeaderSize fmt)
B.writeFile name (h <> dat)
stat <- getFileStatus name
let (+) = unionFileModes
setFileMode name (ownerExecuteMode + groupExecuteMode + otherExecuteMode + fileMode stat)
#define IMPORT_FUN(fun,t) foreign import ccall #fun fun :: t
#define IMPORT_FORMAT(fmt) IMPORT_FUN(fmt##_entry,Int) ; IMPORT_FUN(fmt##_headerSize,Int) ; IMPORT_FUN(fmt##_headerCons,Int -> IO (Ptr CChar)) ; fmt = F #fmt fmt##_entry fmt##_headerSize fmt##_headerCons
raw entry = F ("raw:"++show entry) entry 0 (const $ return nullPtr)
IMPORT_FORMAT(elf64) ; IMPORT_FORMAT(elf32) ; IMPORT_FORMAT(exe)
formats = [elf64,elf32,exe]
#if x86_64_HOST_ARCH
defaultFormat = elf64
#else
defaultFormat = raw 0
#endif
| lih/Alpha | src/Format.hs | bsd-2-clause | 1,277 | 0 | 12 | 201 | 313 | 171 | 142 | -1 | -1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QDial_h.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.QDial_h (
QsetNotchesVisible_h(..)
,QsetWrapping_h(..)
) where
import Foreign.C.Types
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QAbstractSlider
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QDial ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QDial_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QDial_unSetUserMethod" qtc_QDial_unSetUserMethod :: Ptr (TQDial a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QDialSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QDial_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QDial ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QDial_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QDialSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QDial_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QDial ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QDial_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QDialSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QDial_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QDial ()) (QDial x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QDial setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QDial_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QDial_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQDial x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QDial_setUserMethod" qtc_QDial_setUserMethod :: Ptr (TQDial a) -> CInt -> Ptr (Ptr (TQDial x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QDial :: (Ptr (TQDial x0) -> IO ()) -> IO (FunPtr (Ptr (TQDial x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QDial_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QDialSc a) (QDial x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QDial setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QDial_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QDial_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQDial x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QDial ()) (QDial x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QDial setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QDial_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QDial_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQDial x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QDial_setUserMethodVariant" qtc_QDial_setUserMethodVariant :: Ptr (TQDial a) -> CInt -> Ptr (Ptr (TQDial x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QDial :: (Ptr (TQDial x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQDial x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QDial_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QDialSc a) (QDial x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QDial setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QDial_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QDial_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQDial x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QDial ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QDial_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QDial_unSetHandler" qtc_QDial_unSetHandler :: Ptr (TQDial a) -> CWString -> IO (CBool)
instance QunSetHandler (QDialSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QDial_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QDial ()) (QDial x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qDialFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QDial_setHandler1" qtc_QDial_setHandler1 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QDial1 :: (Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QDial1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QDialSc a) (QDial x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qDialFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qevent_h (QDial ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_event cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_event" qtc_QDial_event :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QDialSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_event cobj_x0 cobj_x1
instance QsetHandler (QDial ()) (QDial x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qDialFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QDial_setHandler2" qtc_QDial_setHandler2 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QDial2 :: (Ptr (TQDial x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQDial x0) -> IO (Ptr (TQSize t0))))
foreign import ccall "wrapper" wrapSetHandler_QDial2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QDialSc a) (QDial x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qDialFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqminimumSizeHint_h (QDial ()) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_minimumSizeHint cobj_x0
foreign import ccall "qtc_QDial_minimumSizeHint" qtc_QDial_minimumSizeHint :: Ptr (TQDial a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint_h (QDialSc a) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_minimumSizeHint cobj_x0
instance QminimumSizeHint_h (QDial ()) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QDial_minimumSizeHint_qth" qtc_QDial_minimumSizeHint_qth :: Ptr (TQDial a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint_h (QDialSc a) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QsetHandler (QDial ()) (QDial x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qDialFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QDial_setHandler3" qtc_QDial_setHandler3 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QDial3 :: (Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QDial3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QDialSc a) (QDial x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qDialFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QmouseMoveEvent_h (QDial ()) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_mouseMoveEvent" qtc_QDial_mouseMoveEvent :: Ptr (TQDial a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QDialSc a) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QDial ()) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_mousePressEvent" qtc_QDial_mousePressEvent :: Ptr (TQDial a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QDialSc a) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QDial ()) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_mouseReleaseEvent" qtc_QDial_mouseReleaseEvent :: Ptr (TQDial a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QDialSc a) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_mouseReleaseEvent cobj_x0 cobj_x1
instance QpaintEvent_h (QDial ()) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_paintEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_paintEvent" qtc_QDial_paintEvent :: Ptr (TQDial a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent_h (QDialSc a) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_paintEvent cobj_x0 cobj_x1
instance QresizeEvent_h (QDial ()) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_resizeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_resizeEvent" qtc_QDial_resizeEvent :: Ptr (TQDial a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent_h (QDialSc a) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_resizeEvent cobj_x0 cobj_x1
instance QsetHandler (QDial ()) (QDial x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qDialFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QDial_setHandler4" qtc_QDial_setHandler4 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QDial4 :: (Ptr (TQDial x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQDial x0) -> CBool -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QDial4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QDialSc a) (QDial x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qDialFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
class QsetNotchesVisible_h x0 x1 where
setNotchesVisible_h :: x0 -> x1 -> IO ()
instance QsetNotchesVisible_h (QDial ()) ((Bool)) where
setNotchesVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setNotchesVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDial_setNotchesVisible" qtc_QDial_setNotchesVisible :: Ptr (TQDial a) -> CBool -> IO ()
instance QsetNotchesVisible_h (QDialSc a) ((Bool)) where
setNotchesVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setNotchesVisible cobj_x0 (toCBool x1)
class QsetWrapping_h x0 x1 where
setWrapping_h :: x0 -> x1 -> IO ()
instance QsetWrapping_h (QDial ()) ((Bool)) where
setWrapping_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setWrapping cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDial_setWrapping" qtc_QDial_setWrapping :: Ptr (TQDial a) -> CBool -> IO ()
instance QsetWrapping_h (QDialSc a) ((Bool)) where
setWrapping_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setWrapping cobj_x0 (toCBool x1)
instance QqsizeHint_h (QDial ()) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_sizeHint cobj_x0
foreign import ccall "qtc_QDial_sizeHint" qtc_QDial_sizeHint :: Ptr (TQDial a) -> IO (Ptr (TQSize ()))
instance QqsizeHint_h (QDialSc a) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_sizeHint cobj_x0
instance QsizeHint_h (QDial ()) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QDial_sizeHint_qth" qtc_QDial_sizeHint_qth :: Ptr (TQDial a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint_h (QDialSc a) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QsetHandler (QDial ()) (QDial x0 -> SliderChange -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> CLong -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qDialFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1enum
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QDial_setHandler5" qtc_QDial_setHandler5 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> CLong -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QDial5 :: (Ptr (TQDial x0) -> CLong -> IO ()) -> IO (FunPtr (Ptr (TQDial x0) -> CLong -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QDial5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QDialSc a) (QDial x0 -> SliderChange -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> CLong -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qDialFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1enum
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsliderChange_h (QDial ()) ((SliderChange)) where
sliderChange_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_sliderChange cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QDial_sliderChange" qtc_QDial_sliderChange :: Ptr (TQDial a) -> CLong -> IO ()
instance QsliderChange_h (QDialSc a) ((SliderChange)) where
sliderChange_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_sliderChange cobj_x0 (toCLong $ qEnum_toInt x1)
instance QchangeEvent_h (QDial ()) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_changeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_changeEvent" qtc_QDial_changeEvent :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent_h (QDialSc a) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_changeEvent cobj_x0 cobj_x1
instance QkeyPressEvent_h (QDial ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_keyPressEvent" qtc_QDial_keyPressEvent :: Ptr (TQDial a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QDialSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_keyPressEvent cobj_x0 cobj_x1
instance QwheelEvent_h (QDial ()) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_wheelEvent" qtc_QDial_wheelEvent :: Ptr (TQDial a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent_h (QDialSc a) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_wheelEvent cobj_x0 cobj_x1
instance QactionEvent_h (QDial ()) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_actionEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_actionEvent" qtc_QDial_actionEvent :: Ptr (TQDial a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent_h (QDialSc a) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_actionEvent cobj_x0 cobj_x1
instance QcloseEvent_h (QDial ()) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_closeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_closeEvent" qtc_QDial_closeEvent :: Ptr (TQDial a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent_h (QDialSc a) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_closeEvent cobj_x0 cobj_x1
instance QcontextMenuEvent_h (QDial ()) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_contextMenuEvent" qtc_QDial_contextMenuEvent :: Ptr (TQDial a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QDialSc a) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_contextMenuEvent cobj_x0 cobj_x1
instance QsetHandler (QDial ()) (QDial x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qDialFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QDial_setHandler6" qtc_QDial_setHandler6 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QDial6 :: (Ptr (TQDial x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQDial x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QDial6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QDialSc a) (QDial x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qDialFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdevType_h (QDial ()) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_devType cobj_x0
foreign import ccall "qtc_QDial_devType" qtc_QDial_devType :: Ptr (TQDial a) -> IO CInt
instance QdevType_h (QDialSc a) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_devType cobj_x0
instance QdragEnterEvent_h (QDial ()) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_dragEnterEvent" qtc_QDial_dragEnterEvent :: Ptr (TQDial a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent_h (QDialSc a) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QDial ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_dragLeaveEvent" qtc_QDial_dragLeaveEvent :: Ptr (TQDial a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent_h (QDialSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QDial ()) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_dragMoveEvent" qtc_QDial_dragMoveEvent :: Ptr (TQDial a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent_h (QDialSc a) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QDial ()) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_dropEvent" qtc_QDial_dropEvent :: Ptr (TQDial a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent_h (QDialSc a) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_dropEvent cobj_x0 cobj_x1
instance QenterEvent_h (QDial ()) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_enterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_enterEvent" qtc_QDial_enterEvent :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent_h (QDialSc a) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_enterEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QDial ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_focusInEvent" qtc_QDial_focusInEvent :: Ptr (TQDial a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QDialSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QDial ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_focusOutEvent" qtc_QDial_focusOutEvent :: Ptr (TQDial a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QDialSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_focusOutEvent cobj_x0 cobj_x1
instance QsetHandler (QDial ()) (QDial x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qDialFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QDial_setHandler7" qtc_QDial_setHandler7 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QDial7 :: (Ptr (TQDial x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQDial x0) -> CInt -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QDial7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QDialSc a) (QDial x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qDialFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QheightForWidth_h (QDial ()) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_heightForWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QDial_heightForWidth" qtc_QDial_heightForWidth :: Ptr (TQDial a) -> CInt -> IO CInt
instance QheightForWidth_h (QDialSc a) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_heightForWidth cobj_x0 (toCInt x1)
instance QhideEvent_h (QDial ()) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_hideEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_hideEvent" qtc_QDial_hideEvent :: Ptr (TQDial a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent_h (QDialSc a) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_hideEvent cobj_x0 cobj_x1
instance QsetHandler (QDial ()) (QDial x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qDialFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QDial_setHandler8" qtc_QDial_setHandler8 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QDial8 :: (Ptr (TQDial x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQDial x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QDial8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QDialSc a) (QDial x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qDialFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QinputMethodQuery_h (QDial ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QDial_inputMethodQuery" qtc_QDial_inputMethodQuery :: Ptr (TQDial a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QDialSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyReleaseEvent_h (QDial ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_keyReleaseEvent" qtc_QDial_keyReleaseEvent :: Ptr (TQDial a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QDialSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_keyReleaseEvent cobj_x0 cobj_x1
instance QleaveEvent_h (QDial ()) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_leaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_leaveEvent" qtc_QDial_leaveEvent :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent_h (QDialSc a) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_leaveEvent cobj_x0 cobj_x1
instance QmouseDoubleClickEvent_h (QDial ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_mouseDoubleClickEvent" qtc_QDial_mouseDoubleClickEvent :: Ptr (TQDial a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QDialSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmoveEvent_h (QDial ()) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_moveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_moveEvent" qtc_QDial_moveEvent :: Ptr (TQDial a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent_h (QDialSc a) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_moveEvent cobj_x0 cobj_x1
instance QsetHandler (QDial ()) (QDial x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qDialFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QDial_setHandler9" qtc_QDial_setHandler9 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QDial9 :: (Ptr (TQDial x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQDial x0) -> IO (Ptr (TQPaintEngine t0))))
foreign import ccall "wrapper" wrapSetHandler_QDial9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QDialSc a) (QDial x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qDialFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QpaintEngine_h (QDial ()) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_paintEngine cobj_x0
foreign import ccall "qtc_QDial_paintEngine" qtc_QDial_paintEngine :: Ptr (TQDial a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine_h (QDialSc a) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_paintEngine cobj_x0
instance QsetVisible_h (QDial ()) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDial_setVisible" qtc_QDial_setVisible :: Ptr (TQDial a) -> CBool -> IO ()
instance QsetVisible_h (QDialSc a) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setVisible cobj_x0 (toCBool x1)
instance QshowEvent_h (QDial ()) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_showEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_showEvent" qtc_QDial_showEvent :: Ptr (TQDial a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent_h (QDialSc a) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_showEvent cobj_x0 cobj_x1
instance QtabletEvent_h (QDial ()) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_tabletEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_tabletEvent" qtc_QDial_tabletEvent :: Ptr (TQDial a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent_h (QDialSc a) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_tabletEvent cobj_x0 cobj_x1
instance QsetHandler (QDial ()) (QDial x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qDialFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QDial_setHandler10" qtc_QDial_setHandler10 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QDial10 :: (Ptr (TQDial x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDial x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QDial10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QDialSc a) (QDial x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QDial10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QDial10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QDial_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQDial x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qDialFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QeventFilter_h (QDial ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QDial_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QDial_eventFilter" qtc_QDial_eventFilter :: Ptr (TQDial a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QDialSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QDial_eventFilter cobj_x0 cobj_x1 cobj_x2
| keera-studios/hsQt | Qtc/Gui/QDial_h.hs | bsd-2-clause | 58,905 | 0 | 18 | 13,243 | 20,387 | 9,841 | 10,546 | -1 | -1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
-- Create a source distribution tarball
module Stack.SDist
( getSDistTarball
) where
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
import qualified Codec.Compression.GZip as GZip
import Control.Applicative
import Control.Concurrent.Execute (ActionContext(..))
import Control.Monad (when, void)
import Control.Monad.Catch (MonadCatch, MonadMask)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (MonadReader, asks)
import Control.Monad.Trans.Control (liftBaseWith)
import Control.Monad.Trans.Resource
import qualified Data.ByteString.Lazy as L
import Data.Either (partitionEithers)
import Data.List
import qualified Data.Map.Strict as Map
import Data.Monoid ((<>))
import qualified Data.Set as Set
import qualified Data.Text as T
import Network.HTTP.Client.Conduit (HasHttpManager)
import Path
import Prelude -- Fix redundant import warnings
import Stack.Build (mkBaseConfigOpts)
import Stack.Build.Execute
import Stack.Build.Source (loadSourceMap, localFlags)
import Stack.Build.Target
import Stack.Constants
import Stack.Package
import Stack.Types
import Stack.Types.Internal
import qualified System.FilePath as FP
import System.IO.Temp (withSystemTempDirectory)
type M env m = (MonadIO m,MonadReader env m,HasHttpManager env,HasBuildConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,MonadMask m,HasLogLevel env,HasEnvConfig env,HasTerminal env)
-- | Given the path to a local package, creates its source
-- distribution tarball.
--
-- While this yields a 'FilePath', the name of the tarball, this
-- tarball is not written to the disk and instead yielded as a lazy
-- bytestring.
getSDistTarball :: M env m => Path Abs Dir -> m (FilePath, L.ByteString)
getSDistTarball pkgDir = do
let pkgFp = toFilePath pkgDir
lp <- readLocalPackage pkgDir
$logInfo $ "Getting file list for " <> T.pack pkgFp
fileList <- getSDistFileList lp
$logInfo $ "Building sdist tarball for " <> T.pack pkgFp
files <- normalizeTarballPaths (lines fileList)
liftIO $ do
-- NOTE: Could make this use lazy I/O to only read files as needed
-- for upload (both GZip.compress and Tar.write are lazy).
-- However, it seems less error prone and more predictable to read
-- everything in at once, so that's what we're doing for now:
let packWith f isDir fp =
f (pkgFp FP.</> fp)
(either error id (Tar.toTarPath isDir (pkgId FP.</> fp)))
tarName = pkgId FP.<.> "tar.gz"
pkgId = packageIdentifierString (packageIdentifier (lpPackage lp))
dirEntries <- mapM (packWith Tar.packDirectoryEntry True) (dirsFromFiles files)
fileEntries <- mapM (packWith Tar.packFileEntry False) files
return (tarName, GZip.compress (Tar.write (dirEntries ++ fileEntries)))
-- Read in a 'LocalPackage' config. This makes some default decisions
-- about 'LocalPackage' fields that might not be appropriate for other
-- usecases.
--
-- TODO: Dedupe with similar code in "Stack.Build.Source".
readLocalPackage :: M env m => Path Abs Dir -> m LocalPackage
readLocalPackage pkgDir = do
econfig <- asks getEnvConfig
bconfig <- asks getBuildConfig
cabalfp <- getCabalFileName pkgDir
name <- parsePackageNameFromFilePath cabalfp
let config = PackageConfig
{ packageConfigEnableTests = False
, packageConfigEnableBenchmarks = False
, packageConfigFlags = localFlags Map.empty bconfig name
, packageConfigCompilerVersion = envConfigCompilerVersion econfig
, packageConfigPlatform = configPlatform $ getConfig bconfig
}
package <- readPackage config cabalfp
return LocalPackage
{ lpPackage = package
, lpExeComponents = Nothing -- HACK: makes it so that sdist output goes to a log instead of a file.
, lpDir = pkgDir
, lpCabalFile = cabalfp
-- NOTE: these aren't the 'correct values, but aren't used in
-- the usage of this function in this module.
, lpTestDeps = Map.empty
, lpBenchDeps = Map.empty
, lpTestBench = Nothing
, lpDirtyFiles = True
, lpNewBuildCache = Map.empty
, lpFiles = Set.empty
, lpComponents = Set.empty
}
getSDistFileList :: M env m => LocalPackage -> m String
getSDistFileList lp =
withSystemTempDirectory (stackProgName <> "-sdist") $ \tmpdir -> do
menv <- getMinimalEnvOverride
let bopts = defaultBuildOpts
baseConfigOpts <- mkBaseConfigOpts bopts
(_, _mbp, locals, _extraToBuild, sourceMap) <- loadSourceMap NeedTargets bopts
runInBase <- liftBaseWith $ \run -> return (void . run)
withExecuteEnv menv bopts baseConfigOpts locals sourceMap $ \ee -> do
withSingleContext runInBase ac ee task Nothing (Just "sdist") $ \_package _cabalfp _pkgDir cabal _announce _console _mlogFile -> do
let outFile = tmpdir FP.</> "source-files-list"
cabal False ["sdist", "--list-sources", outFile]
liftIO (readFile outFile)
where
package = lpPackage lp
ac = ActionContext Set.empty
task = Task
{ taskProvides = PackageIdentifier (packageName package) (packageVersion package)
, taskType = TTLocal lp
, taskConfigOpts = TaskConfigOpts
{ tcoMissing = Set.empty
, tcoOpts = \_ -> ConfigureOpts [] []
}
, taskPresent = Map.empty
}
normalizeTarballPaths :: M env m => [FilePath] -> m [FilePath]
normalizeTarballPaths fps = do
--TODO: consider whether erroring out is better - otherwise the
--user might upload an incomplete tar?
when (not (null outsideDir)) $
$logWarn $ T.concat
[ "Warning: These files are outside of the package directory, and will be omitted from the tarball: "
, T.pack (show outsideDir)]
return files
where
(outsideDir, files) = partitionEithers (map pathToEither fps)
pathToEither fp = maybe (Left fp) Right (normalizePath fp)
normalizePath :: FilePath -> (Maybe FilePath)
normalizePath = fmap FP.joinPath . go . FP.splitDirectories . FP.normalise
where
go [] = Just []
go ("..":_) = Nothing
go (_:"..":xs) = go xs
go (x:xs) = (x :) <$> go xs
dirsFromFiles :: [FilePath] -> [FilePath]
dirsFromFiles dirs = Set.toAscList (Set.delete "." results)
where
results = foldl' (\s -> go s . FP.takeDirectory) Set.empty dirs
go s x
| Set.member x s = s
| otherwise = go (Set.insert x s) (FP.takeDirectory x)
| bixuanzju/stack | src/Stack/SDist.hs | bsd-3-clause | 7,020 | 0 | 20 | 1,779 | 1,653 | 891 | 762 | 124 | 4 |
{-# LANGUAGE DeriveDataTypeable, CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Xmobar
-- Copyright : (c) Andrea Rossato
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Jose A. Ortega Ruiz <jao@gnu.org>
-- Stability : unstable
-- Portability : unportable
--
-- A status bar for the Xmonad Window Manager
--
-----------------------------------------------------------------------------
module Xmobar
( -- * Main Stuff
-- $main
X , XConf (..), runX
, startLoop
-- * Program Execution
-- $command
, startCommand
-- * Window Management
-- $window
, createWin, updateWin
-- * Printing
-- $print
, drawInWin, printStrings
) where
import Prelude hiding (catch)
import Graphics.X11.Xlib hiding (textExtents, textWidth)
import Graphics.X11.Xlib.Extras
import Graphics.X11.Xinerama
import Graphics.X11.Xrandr
import Control.Arrow ((&&&))
import Control.Monad.Reader
import Control.Concurrent
import Control.Concurrent.STM
import Control.Exception (catch, SomeException(..))
import Data.Bits
import Config
import Parsers
import Commands
import Runnable
import Signal
import Window
import XUtil
#ifdef DBUS
import IPC.DBus
#endif
-- $main
--
-- The Xmobar data type and basic loops and functions.
-- | The X type is a ReaderT
type X = ReaderT XConf IO
-- | The ReaderT inner component
data XConf =
XConf { display :: Display
, rect :: Rectangle
, window :: Window
, fontS :: XFont
, config :: Config
}
-- | Runs the ReaderT
runX :: XConf -> X () -> IO ()
runX xc f = runReaderT f xc
-- | Starts the main event loop and threads
startLoop :: XConf -> TMVar SignalType -> [[(Maybe ThreadId, TVar String)]] -> IO ()
startLoop xcfg@(XConf _ _ w _ _) sig vs = do
tv <- atomically $ newTVar []
_ <- forkIO (checker tv [] vs sig `catch`
\(SomeException _) -> void (putStrLn "Thread checker failed"))
#ifdef THREADED_RUNTIME
_ <- forkOS (eventer sig `catch`
#else
_ <- forkIO (eventer sig `catch`
#endif
\(SomeException _) -> void (putStrLn "Thread eventer failed"))
#ifdef DBUS
runIPC sig
#endif
eventLoop tv xcfg sig
where
-- Reacts on events from X
eventer signal =
allocaXEvent $ \e -> do
dpy <- openDisplay ""
xrrSelectInput dpy (defaultRootWindow dpy) rrScreenChangeNotifyMask
selectInput dpy w (exposureMask .|. structureNotifyMask)
forever $ do
#ifdef THREADED_RUNTIME
nextEvent dpy e
#else
nextEvent' dpy e
#endif
ev <- getEvent e
case ev of
-- ConfigureEvent {} -> (atomically $ putTMVar signal Reposition)
ExposeEvent {} -> atomically $ putTMVar signal Wakeup
RRScreenChangeNotifyEvent {} -> atomically $ putTMVar signal Reposition
_ -> return ()
-- | Send signal to eventLoop every time a var is updated
checker :: TVar [String]
-> [String]
-> [[(Maybe ThreadId, TVar String)]]
-> TMVar SignalType
-> IO ()
checker tvar ov vs signal = do
nval <- atomically $ do
nv <- mapM concatV vs
guard (nv /= ov)
writeTVar tvar nv
return nv
atomically $ putTMVar signal Wakeup
checker tvar nval vs signal
where
concatV = fmap concat . mapM (readTVar . snd)
-- | Continuously wait for a signal from a thread or a interrupt handler
eventLoop :: TVar [String] -> XConf -> TMVar SignalType -> IO ()
eventLoop tv xc@(XConf d r w fs cfg) signal = do
typ <- atomically $ takeTMVar signal
case typ of
Wakeup -> do
runX xc (updateWin tv)
eventLoop tv xc signal
Reposition ->
reposWindow cfg
ChangeScreen -> do
ncfg <- updateConfigPosition cfg
reposWindow ncfg
Hide t -> hide (t*100*1000)
Reveal t -> reveal (t*100*1000)
Toggle t -> toggle t
TogglePersistent -> eventLoop
tv xc { config = cfg { persistent = not $ persistent cfg } } signal
where
isPersistent = not $ persistent cfg
hide t
| t == 0 =
when isPersistent (hideWindow d w) >> eventLoop tv xc signal
| otherwise = do
void $ forkIO
$ threadDelay t >> atomically (putTMVar signal $ Hide 0)
eventLoop tv xc signal
reveal t
| t == 0 = do
when isPersistent (showWindow r cfg d w)
eventLoop tv xc signal
| otherwise = do
void $ forkIO
$ threadDelay t >> atomically (putTMVar signal $ Reveal 0)
eventLoop tv xc signal
toggle t = do
ismapped <- isMapped d w
atomically (putTMVar signal $ if ismapped then Hide t else Reveal t)
eventLoop tv xc signal
reposWindow rcfg = do
r' <- repositionWin d w fs rcfg
eventLoop tv (XConf d r' w fs rcfg) signal
updateConfigPosition ocfg =
case position ocfg of
OnScreen n o -> do
srs <- getScreenInfo d
if n == length srs then
return (ocfg {position = OnScreen 1 o})
else
return (ocfg {position = OnScreen (n+1) o})
o ->
return (ocfg {position = OnScreen 1 o})
-- $command
-- | Runs a command as an independent thread and returns its thread id
-- and the TVar the command will be writing to.
startCommand :: TMVar SignalType
-> (Runnable,String,String)
-> IO (Maybe ThreadId, TVar String)
startCommand sig (com,s,ss)
| alias com == "" = do var <- atomically $ newTVar is
atomically $ writeTVar var (s ++ ss)
return (Nothing,var)
| otherwise = do var <- atomically $ newTVar is
let cb str = atomically $ writeTVar var (s ++ str ++ ss)
h <- forkIO $ start com cb
_ <- forkIO $ trigger com
$ maybe (return ()) (atomically . putTMVar sig)
return (Just h,var)
where is = s ++ "Updating..." ++ ss
updateWin :: TVar [String] -> X ()
updateWin v = do
xc <- ask
s <- io $ atomically $ readTVar v
let (conf,rec) = (config &&& rect) xc
l:c:r:_ = s ++ repeat ""
ps <- io $ mapM (parseString conf) [l, c, r]
drawInWin rec ps
-- $print
-- | Draws in and updates the window
drawInWin :: Rectangle -> [[(String, String)]] -> X ()
drawInWin (Rectangle _ _ wid ht) ~[left,center,right] = do
r <- ask
let (c,d ) = (config &&& display) r
(w,fs) = (window &&& fontS ) r
strLn = io . mapM (\(s,cl) -> textWidth d fs s >>= \tw -> return (s,cl,fi tw))
withColors d [bgColor c, borderColor c] $ \[bgcolor, bdcolor] -> do
gc <- io $ createGC d w
-- create a pixmap to write to and fill it with a rectangle
p <- io $ createPixmap d w wid ht
(defaultDepthOfScreen (defaultScreenOfDisplay d))
-- the fgcolor of the rectangle will be the bgcolor of the window
io $ setForeground d gc bgcolor
io $ fillRectangle d p gc 0 0 wid ht
-- write to the pixmap the new string
printStrings p gc fs 1 L =<< strLn left
printStrings p gc fs 1 R =<< strLn right
printStrings p gc fs 1 C =<< strLn center
-- draw 1 pixel border if requested
io $ drawBorder (border c) d p gc bdcolor wid ht
-- copy the pixmap with the new string to the window
io $ copyArea d p w gc 0 0 wid ht 0 0
-- free up everything (we do not want to leak memory!)
io $ freeGC d gc
io $ freePixmap d p
-- resync
io $ sync d True
-- | An easy way to print the stuff we need to print
printStrings :: Drawable -> GC -> XFont -> Position
-> Align -> [(String, String, Position)] -> X ()
printStrings _ _ _ _ _ [] = return ()
printStrings dr gc fontst offs a sl@((s,c,l):xs) = do
r <- ask
(as,ds) <- io $ textExtents fontst s
let (conf,d) = (config &&& display) r
Rectangle _ _ wid ht = rect r
totSLen = foldr (\(_,_,len) -> (+) len) 0 sl
valign = (fi ht `div` 2) + (fi (as + ds) `div` 3)
remWidth = fi wid - fi totSLen
offset = case a of
C -> (remWidth + offs) `div` 2
R -> remWidth
L -> offs
(fc,bc) = case break (==',') c of
(f,',':b) -> (f, b )
(f, _) -> (f, bgColor conf)
withColors d [bc] $ \[bc'] -> do
io $ setForeground d gc bc'
io $ fillRectangle d dr gc offset 0 (fi l) ht
io $ printString d dr fontst gc fc bc offset valign s
printStrings dr gc fontst (offs + l) a xs
| raboof/xmobar | src/Xmobar.hs | bsd-3-clause | 9,113 | 0 | 19 | 3,129 | 2,830 | 1,433 | 1,397 | 183 | 10 |
{-# language CPP #-}
-- | = Name
--
-- VK_EXT_hdr_metadata - device extension
--
-- == VK_EXT_hdr_metadata
--
-- [__Name String__]
-- @VK_EXT_hdr_metadata@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
-- 106
--
-- [__Revision__]
-- 2
--
-- [__Extension and Version Dependencies__]
--
-- - Requires Vulkan 1.0
--
-- - Requires @VK_KHR_swapchain@
--
-- [__Contact__]
--
-- - Courtney Goeltzenleuchter
-- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_hdr_metadata] @courtney-g%0A<<Here describe the issue or question you have about the VK_EXT_hdr_metadata extension>> >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
-- 2018-12-19
--
-- [__IP Status__]
-- No known IP claims.
--
-- [__Contributors__]
--
-- - Courtney Goeltzenleuchter, Google
--
-- == Description
--
-- This extension defines two new structures and a function to assign SMPTE
-- (the Society of Motion Picture and Television Engineers) 2086 metadata
-- and CTA (Consumer Technology Association) 861.3 metadata to a swapchain.
-- The metadata includes the color primaries, white point, and luminance
-- range of the reference monitor, which all together define the color
-- volume containing all the possible colors the reference monitor can
-- produce. The reference monitor is the display where creative work is
-- done and creative intent is established. To preserve such creative
-- intent as much as possible and achieve consistent color reproduction on
-- different viewing displays, it is useful for the display pipeline to
-- know the color volume of the original reference monitor where content
-- was created or tuned. This avoids performing unnecessary mapping of
-- colors that are not displayable on the original reference monitor. The
-- metadata also includes the @maxContentLightLevel@ and
-- @maxFrameAverageLightLevel@ as defined by CTA 861.3.
--
-- While the general purpose of the metadata is to assist in the
-- transformation between different color volumes of different displays and
-- help achieve better color reproduction, it is not in the scope of this
-- extension to define how exactly the metadata should be used in such a
-- process. It is up to the implementation to determine how to make use of
-- the metadata.
--
-- == New Commands
--
-- - 'setHdrMetadataEXT'
--
-- == New Structures
--
-- - 'HdrMetadataEXT'
--
-- - 'XYColorEXT'
--
-- == New Enum Constants
--
-- - 'EXT_HDR_METADATA_EXTENSION_NAME'
--
-- - 'EXT_HDR_METADATA_SPEC_VERSION'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_HDR_METADATA_EXT'
--
-- == Issues
--
-- 1) Do we need a query function?
--
-- __PROPOSED__: No, Vulkan does not provide queries for state that the
-- application can track on its own.
--
-- 2) Should we specify default if not specified by the application?
--
-- __PROPOSED__: No, that leaves the default up to the display.
--
-- == Version History
--
-- - Revision 1, 2016-12-27 (Courtney Goeltzenleuchter)
--
-- - Initial version
--
-- - Revision 2, 2018-12-19 (Courtney Goeltzenleuchter)
--
-- - Correct implicit validity for VkHdrMetadataEXT structure
--
-- == See Also
--
-- 'HdrMetadataEXT', 'XYColorEXT', 'setHdrMetadataEXT'
--
-- == Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_EXT_hdr_metadata 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_hdr_metadata ( setHdrMetadataEXT
, XYColorEXT(..)
, HdrMetadataEXT(..)
, EXT_HDR_METADATA_SPEC_VERSION
, pattern EXT_HDR_METADATA_SPEC_VERSION
, EXT_HDR_METADATA_EXTENSION_NAME
, pattern EXT_HDR_METADATA_EXTENSION_NAME
, SwapchainKHR(..)
) where
import Vulkan.Internal.Utils (traceAroundEvent)
import Control.Monad (unless)
import Control.Monad.IO.Class (liftIO)
import Foreign.Marshal.Alloc (allocaBytes)
import GHC.IO (throwIO)
import GHC.Ptr (nullFunPtr)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import Data.Coerce (coerce)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (evalContT)
import qualified Data.Vector (imapM_)
import qualified Data.Vector (length)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero(..))
import Control.Monad.IO.Class (MonadIO)
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.C.Types (CFloat)
import Foreign.C.Types (CFloat(..))
import Foreign.C.Types (CFloat(CFloat))
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import GHC.IO.Exception (IOErrorType(..))
import GHC.IO.Exception (IOException(..))
import Foreign.Ptr (FunPtr)
import Foreign.Ptr (Ptr)
import Data.Word (Word32)
import Data.Kind (Type)
import Control.Monad.Trans.Cont (ContT(..))
import Data.Vector (Vector)
import Vulkan.NamedType ((:::))
import Vulkan.Core10.Handles (Device)
import Vulkan.Core10.Handles (Device(..))
import Vulkan.Core10.Handles (Device(Device))
import Vulkan.Dynamic (DeviceCmds(pVkSetHdrMetadataEXT))
import Vulkan.Core10.Handles (Device_T)
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Extensions.Handles (SwapchainKHR)
import Vulkan.Extensions.Handles (SwapchainKHR(..))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_HDR_METADATA_EXT))
import Vulkan.Extensions.Handles (SwapchainKHR(..))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkSetHdrMetadataEXT
:: FunPtr (Ptr Device_T -> Word32 -> Ptr SwapchainKHR -> Ptr HdrMetadataEXT -> IO ()) -> Ptr Device_T -> Word32 -> Ptr SwapchainKHR -> Ptr HdrMetadataEXT -> IO ()
-- | vkSetHdrMetadataEXT - Set Hdr metadata
--
-- = Description
--
-- The metadata will be applied to the specified
-- 'Vulkan.Extensions.Handles.SwapchainKHR' objects at the next
-- 'Vulkan.Extensions.VK_KHR_swapchain.queuePresentKHR' call using that
-- 'Vulkan.Extensions.Handles.SwapchainKHR' object. The metadata will
-- persist until a subsequent 'setHdrMetadataEXT' changes it.
--
-- == Valid Usage (Implicit)
--
-- - #VUID-vkSetHdrMetadataEXT-device-parameter# @device@ /must/ be a
-- valid 'Vulkan.Core10.Handles.Device' handle
--
-- - #VUID-vkSetHdrMetadataEXT-pSwapchains-parameter# @pSwapchains@
-- /must/ be a valid pointer to an array of @swapchainCount@ valid
-- 'Vulkan.Extensions.Handles.SwapchainKHR' handles
--
-- - #VUID-vkSetHdrMetadataEXT-pMetadata-parameter# @pMetadata@ /must/ be
-- a valid pointer to an array of @swapchainCount@ valid
-- 'HdrMetadataEXT' structures
--
-- - #VUID-vkSetHdrMetadataEXT-swapchainCount-arraylength#
-- @swapchainCount@ /must/ be greater than @0@
--
-- - #VUID-vkSetHdrMetadataEXT-commonparent# Both of @device@, and the
-- elements of @pSwapchains@ /must/ have been created, allocated, or
-- retrieved from the same 'Vulkan.Core10.Handles.Instance'
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_hdr_metadata VK_EXT_hdr_metadata>,
-- 'Vulkan.Core10.Handles.Device', 'HdrMetadataEXT',
-- 'Vulkan.Extensions.Handles.SwapchainKHR'
setHdrMetadataEXT :: forall io
. (MonadIO io)
=> -- | @device@ is the logical device where the swapchain(s) were created.
Device
-> -- | @pSwapchains@ is a pointer to an array of @swapchainCount@
-- 'Vulkan.Extensions.Handles.SwapchainKHR' handles.
("swapchains" ::: Vector SwapchainKHR)
-> -- | @pMetadata@ is a pointer to an array of @swapchainCount@
-- 'HdrMetadataEXT' structures.
("metadata" ::: Vector HdrMetadataEXT)
-> io ()
setHdrMetadataEXT device swapchains metadata = liftIO . evalContT $ do
let vkSetHdrMetadataEXTPtr = pVkSetHdrMetadataEXT (case device of Device{deviceCmds} -> deviceCmds)
lift $ unless (vkSetHdrMetadataEXTPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkSetHdrMetadataEXT is null" Nothing Nothing
let vkSetHdrMetadataEXT' = mkVkSetHdrMetadataEXT vkSetHdrMetadataEXTPtr
let pSwapchainsLength = Data.Vector.length $ (swapchains)
lift $ unless ((Data.Vector.length $ (metadata)) == pSwapchainsLength) $
throwIO $ IOError Nothing InvalidArgument "" "pMetadata and pSwapchains must have the same length" Nothing Nothing
pPSwapchains <- ContT $ allocaBytes @SwapchainKHR ((Data.Vector.length (swapchains)) * 8)
lift $ Data.Vector.imapM_ (\i e -> poke (pPSwapchains `plusPtr` (8 * (i)) :: Ptr SwapchainKHR) (e)) (swapchains)
pPMetadata <- ContT $ allocaBytes @HdrMetadataEXT ((Data.Vector.length (metadata)) * 64)
lift $ Data.Vector.imapM_ (\i e -> poke (pPMetadata `plusPtr` (64 * (i)) :: Ptr HdrMetadataEXT) (e)) (metadata)
lift $ traceAroundEvent "vkSetHdrMetadataEXT" (vkSetHdrMetadataEXT' (deviceHandle (device)) ((fromIntegral pSwapchainsLength :: Word32)) (pPSwapchains) (pPMetadata))
pure $ ()
-- | VkXYColorEXT - Specify X,Y chromaticity coordinates
--
-- = Description
--
-- Chromaticity coordinates are as specified in CIE 15:2004 “Calculation of
-- chromaticity coordinates” (Section 7.3) and are limited to between 0 and
-- 1 for real colors for the reference monitor.
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_hdr_metadata VK_EXT_hdr_metadata>,
-- 'HdrMetadataEXT'
data XYColorEXT = XYColorEXT
{ -- | @x@ is the x chromaticity coordinate.
x :: Float
, -- | @y@ is the y chromaticity coordinate.
y :: Float
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (XYColorEXT)
#endif
deriving instance Show XYColorEXT
instance ToCStruct XYColorEXT where
withCStruct x f = allocaBytes 8 $ \p -> pokeCStruct p x (f p)
pokeCStruct p XYColorEXT{..} f = do
poke ((p `plusPtr` 0 :: Ptr CFloat)) (CFloat (x))
poke ((p `plusPtr` 4 :: Ptr CFloat)) (CFloat (y))
f
cStructSize = 8
cStructAlignment = 4
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 4 :: Ptr CFloat)) (CFloat (zero))
f
instance FromCStruct XYColorEXT where
peekCStruct p = do
x <- peek @CFloat ((p `plusPtr` 0 :: Ptr CFloat))
y <- peek @CFloat ((p `plusPtr` 4 :: Ptr CFloat))
pure $ XYColorEXT
(coerce @CFloat @Float x) (coerce @CFloat @Float y)
instance Storable XYColorEXT where
sizeOf ~_ = 8
alignment ~_ = 4
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero XYColorEXT where
zero = XYColorEXT
zero
zero
-- | VkHdrMetadataEXT - Specify Hdr metadata
--
-- == Valid Usage (Implicit)
--
-- Note
--
-- The validity and use of this data is outside the scope of Vulkan.
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_hdr_metadata VK_EXT_hdr_metadata>,
-- 'Vulkan.Core10.Enums.StructureType.StructureType', 'XYColorEXT',
-- 'setHdrMetadataEXT'
data HdrMetadataEXT = HdrMetadataEXT
{ -- | @displayPrimaryRed@ is a 'XYColorEXT' structure specifying the reference
-- monitor’s red primary in chromaticity coordinates
displayPrimaryRed :: XYColorEXT
, -- | @displayPrimaryGreen@ is a 'XYColorEXT' structure specifying the
-- reference monitor’s green primary in chromaticity coordinates
displayPrimaryGreen :: XYColorEXT
, -- | @displayPrimaryBlue@ is a 'XYColorEXT' structure specifying the
-- reference monitor’s blue primary in chromaticity coordinates
displayPrimaryBlue :: XYColorEXT
, -- | @whitePoint@ is a 'XYColorEXT' structure specifying the reference
-- monitor’s white-point in chromaticity coordinates
whitePoint :: XYColorEXT
, -- | @maxLuminance@ is the maximum luminance of the reference monitor in nits
maxLuminance :: Float
, -- | @minLuminance@ is the minimum luminance of the reference monitor in nits
minLuminance :: Float
, -- | @maxContentLightLevel@ is content’s maximum luminance in nits
maxContentLightLevel :: Float
, -- | @maxFrameAverageLightLevel@ is the maximum frame average light level in
-- nits
maxFrameAverageLightLevel :: Float
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (HdrMetadataEXT)
#endif
deriving instance Show HdrMetadataEXT
instance ToCStruct HdrMetadataEXT where
withCStruct x f = allocaBytes 64 $ \p -> pokeCStruct p x (f p)
pokeCStruct p HdrMetadataEXT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_HDR_METADATA_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr XYColorEXT)) (displayPrimaryRed)
poke ((p `plusPtr` 24 :: Ptr XYColorEXT)) (displayPrimaryGreen)
poke ((p `plusPtr` 32 :: Ptr XYColorEXT)) (displayPrimaryBlue)
poke ((p `plusPtr` 40 :: Ptr XYColorEXT)) (whitePoint)
poke ((p `plusPtr` 48 :: Ptr CFloat)) (CFloat (maxLuminance))
poke ((p `plusPtr` 52 :: Ptr CFloat)) (CFloat (minLuminance))
poke ((p `plusPtr` 56 :: Ptr CFloat)) (CFloat (maxContentLightLevel))
poke ((p `plusPtr` 60 :: Ptr CFloat)) (CFloat (maxFrameAverageLightLevel))
f
cStructSize = 64
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_HDR_METADATA_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr XYColorEXT)) (zero)
poke ((p `plusPtr` 24 :: Ptr XYColorEXT)) (zero)
poke ((p `plusPtr` 32 :: Ptr XYColorEXT)) (zero)
poke ((p `plusPtr` 40 :: Ptr XYColorEXT)) (zero)
poke ((p `plusPtr` 48 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 52 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 56 :: Ptr CFloat)) (CFloat (zero))
poke ((p `plusPtr` 60 :: Ptr CFloat)) (CFloat (zero))
f
instance FromCStruct HdrMetadataEXT where
peekCStruct p = do
displayPrimaryRed <- peekCStruct @XYColorEXT ((p `plusPtr` 16 :: Ptr XYColorEXT))
displayPrimaryGreen <- peekCStruct @XYColorEXT ((p `plusPtr` 24 :: Ptr XYColorEXT))
displayPrimaryBlue <- peekCStruct @XYColorEXT ((p `plusPtr` 32 :: Ptr XYColorEXT))
whitePoint <- peekCStruct @XYColorEXT ((p `plusPtr` 40 :: Ptr XYColorEXT))
maxLuminance <- peek @CFloat ((p `plusPtr` 48 :: Ptr CFloat))
minLuminance <- peek @CFloat ((p `plusPtr` 52 :: Ptr CFloat))
maxContentLightLevel <- peek @CFloat ((p `plusPtr` 56 :: Ptr CFloat))
maxFrameAverageLightLevel <- peek @CFloat ((p `plusPtr` 60 :: Ptr CFloat))
pure $ HdrMetadataEXT
displayPrimaryRed displayPrimaryGreen displayPrimaryBlue whitePoint (coerce @CFloat @Float maxLuminance) (coerce @CFloat @Float minLuminance) (coerce @CFloat @Float maxContentLightLevel) (coerce @CFloat @Float maxFrameAverageLightLevel)
instance Storable HdrMetadataEXT where
sizeOf ~_ = 64
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero HdrMetadataEXT where
zero = HdrMetadataEXT
zero
zero
zero
zero
zero
zero
zero
zero
type EXT_HDR_METADATA_SPEC_VERSION = 2
-- No documentation found for TopLevel "VK_EXT_HDR_METADATA_SPEC_VERSION"
pattern EXT_HDR_METADATA_SPEC_VERSION :: forall a . Integral a => a
pattern EXT_HDR_METADATA_SPEC_VERSION = 2
type EXT_HDR_METADATA_EXTENSION_NAME = "VK_EXT_hdr_metadata"
-- No documentation found for TopLevel "VK_EXT_HDR_METADATA_EXTENSION_NAME"
pattern EXT_HDR_METADATA_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern EXT_HDR_METADATA_EXTENSION_NAME = "VK_EXT_hdr_metadata"
| expipiplus1/vulkan | src/Vulkan/Extensions/VK_EXT_hdr_metadata.hs | bsd-3-clause | 16,530 | 0 | 17 | 3,155 | 3,202 | 1,858 | 1,344 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables, DeriveGeneric #-}
import qualified Data.ByteString.Lazy as BL
import Data.Csv
import qualified Data.Vector as V
import GHC.Generics
data Person = Person String Int deriving Generic
instance FromRecord Person
instance ToRecord Person
persons :: [Person]
persons = [Person "John" 50000, Person "Jane" 60000]
main :: IO ()
main = do
BL.writeFile "salaries.csv" $ encode (V.fromList persons)
csvData <- BL.readFile "salaries.csv"
case decode NoHeader csvData of
Left err -> putStrLn err
Right v -> V.forM_ v $ \ (Person name salary) ->
putStrLn $ name ++ " earns " ++ show salary ++ " dollars"
| mikeizbicki/cassava | examples/IndexBasedGeneric.hs | bsd-3-clause | 669 | 0 | 15 | 140 | 210 | 107 | 103 | 18 | 2 |
-- |Basic types and interfaces
module Data.Deciparsec.Parser ( -- * Types
Parser, Result, ParserT, IResult(..), TokenSeq
-- * Running Parsers
-- ** Resupplyable parsers
, runParserT, feedT, runParser, feed
-- ** Non-resupplyable parsers
, runParserT', evalParserT, execParserT, runParser', evalParser, execParser
-- * User State
, getUserState, putUserState, modifyUserState
-- * Source Position
, SourcePos, spName, spLine, spColumn, getSourcePos, putSourcePos, modifySourcePos
) where
import Data.Monoid
import Data.Functor.Identity
import Data.Deciparsec.Internal
import Data.Deciparsec.Internal.Types
import Data.Deciparsec.TokenSeq (TokenSeq)
-- |A Parser over the 'Identity' monad.
type Parser s u r = ParserT s u Identity r
-- |An 'IResult' in the 'Identity' monad.
type Result s u r = IResult s u Identity r
-- |The most general way to run a parser. A 'Partial' result can be resupplied with 'feedT'.
runParserT :: (Monad m, TokenSeq s t) =>
ParserT s u m a -- ^The parser
-> u -- ^The inital user state
-> String -- ^The name of the source \"file\"
-> s -- ^An inital token sequence. The rest can be supplied later
-> m (IResult s u m a)
runParserT p u src ts = runParserT_ p (ParserState (SourcePos src 1 1) u) (I ts) mempty Incomplete failK successK
-- |Run a parser that cannot be resupplied. This will return either an error, or the result of the parse and the
-- final user state.
runParserT' :: (Monad m, TokenSeq s t) =>
ParserT s u m a -- ^The parser
-> u -- ^The initial user state
-> String -- ^The name of the source \"file\"
-> s -- ^The entire token sequence to parse
-> m (Either ParseError (a, u))
runParserT' p u src ts = do
ir <- runParserT_ p (ParserState (SourcePos src 1 1) u) (I ts) mempty Complete failK successK
case ir of
Fail _ _ pe -> return $ Left pe
Done _ u' r -> return $ Right (r, u')
_ -> fail $ "runParserT': impossible error!"
-- |Run a parser that cannot be resupplied, and return either an error or the result of the parser. The
-- final user state will be discarded.
evalParserT :: (Monad m, TokenSeq s t) =>
ParserT s u m a -- ^The parser
-> u -- ^The initial user state
-> String -- ^The name of the source \"file\"
-> s -- ^The entire token sequence to parse
-> m (Either ParseError a)
evalParserT p u src ts = do
res <- runParserT' p u src ts
return $ either Left (Right . fst) res
-- either Left (Right . fst) <$> runParserT' p u src ts -- This requires :: Functor m
-- |Run a parser that cannot be resupplied, and return either an error or the final user state. The
-- result of the parser will be discarded.
execParserT :: (Monad m, TokenSeq s t) => ParserT s u m a -> u -> String -> s -> m (Either ParseError u)
execParserT p u src ts = do
res <- runParserT' p u src ts
return $ either Left (Right . snd) res
-- either Left (Right . snd) <$> runParserT' p u src ts -- This requires :: Functor m
-- |Run a parser in the 'Identity' monad. A 'Partial' result can be resupplied with 'feed'.
runParser :: TokenSeq s t =>
Parser s u a -- ^The parser
-> u -- ^The initial user state
-> String -- ^The name of the source \"file\"
-> s -- ^An initial token sequence. The rest can be supplied later
-> Result s u a
runParser p u src ts = runIdentity $ runParserT p u src ts
-- |Run a parser that cannot be resupplied in the 'Identity' monad.
runParser' :: TokenSeq s t =>
Parser s u a -- ^The parser
-> u -- ^The initial user state
-> String -- ^The name of the source \"file\"
-> s -- ^The entire token sequence to parse
-> Either ParseError (a, u)
runParser' p u src ts = runIdentity $ runParserT' p u src ts
-- |Run a parser that cannot be resupplied in the 'Identity' monad, and return either an error or the result of
-- the parser. The final user state will be discarded.
evalParser :: TokenSeq s t => Parser s u a -> u -> String -> s -> Either ParseError a
evalParser p u src ts = runIdentity $ evalParserT p u src ts
-- |Run a parser that cannot be resupplied in the 'Identity' monad, and return either an error or the final user
-- state. The result of the parser will be discarded.
execParser :: TokenSeq s t => Parser s u a -> u -> String -> s -> Either ParseError u
execParser p u src ts = runIdentity $ execParserT p u src ts
-- |Provide additional input to a 'Partial' result from 'runParserT'. Provide an
-- 'Data.Deciparsec.Internal.TokenSeq.empty' sequence to force the parser to \"finish\".
feedT :: (Monad m, TokenSeq s t) => IResult s u m a -> s -> m (IResult s u m a)
feedT f@(Fail {}) _ = return f
feedT (Partial k) ts = k ts
feedT (Done ts u r) ts' = return $ Done (ts <> ts') u r
-- |Provide additional input to a 'Partial' result from 'runParser'. Provide an
-- 'Data.Deciparsec.Internal.TokenSeq.empty' sequence to force the parser to \"finish\".
feed :: TokenSeq s t => Result s u a -> s -> Result s u a
feed = ((.).(.)) runIdentity feedT
failK :: Monad m => Failure s u m a
failK s0 i0 _a0 _m0 pe = return $ Fail (unI i0) (psState s0) pe
successK :: Monad m => Success s u a m a
successK s0 i0 _a0 _m0 a = return $ Done (unI i0) (psState s0) a
| d3tucker/deciparsec | src/Data/Deciparsec/Parser.hs | bsd-3-clause | 5,712 | 1 | 13 | 1,661 | 1,324 | 700 | 624 | 73 | 3 |
{-# LANGUAGE PatternGuards #-}
module Common.Draw
(drawLineU, drawLineA)
where
-- Repa
import Data.Array.Repa (Z (..), (:.) (..), U, DIM2, Array)
import qualified Data.Array.Repa as R
-- Acc
import Data.Array.Accelerate.IO
-- base
import Control.Monad
import Control.Monad.ST
import qualified Data.STRef
import qualified Data.Vector.Unboxed as UV
import qualified Data.Vector.Generic.Mutable as MV
import Common.World
-- | Draw a line onto the Repa array
drawLineU :: GlossCoord -> GlossCoord -> Cell -> Array U DIM2 Cell -> IO (Array U DIM2 Cell)
drawLineU (xa, ya) (xb, yb) new array
| sh@(Z :. _ :. width) <- R.extent array
, (x0, y0, x1, y1) <- ( round xa + resWidth, round ya + resHeight
, round xb + resWidth, round yb + resHeight )
, x0 < resX - 2, x1 < resX - 2, y0 < resY - 2, y1 < resY - 2, x0 > 2, y0 > 2, x1 > 2, y1 > 2
= do raw <- UV.unsafeThaw $ R.toUnboxed array
stToIO $ bresenham raw (\(x,y)-> y * width + x) new (x0, y0) (x1, y1)
raw' <- UV.unsafeFreeze raw
return $ R.fromUnboxed sh raw'
| otherwise = return array
-- | Draw a line onto the Repa array backed by Accelerate
drawLineA :: GlossCoord -> GlossCoord -> Cell -> Array A DIM2 Cell -> IO (Array A DIM2 Cell)
drawLineA (xa, ya) (xb, yb) new array
-- FIXME input check here as well, maybe faster
= R.copyP array >>= drawLineU (xa, ya) (xb, yb) new >>= R.copyP
-- Bresenham's line drawing, copypasted from
-- http://rosettacode.org/wiki/Bitmap/Bresenham's_line_algorithm
-- only destructively updating the array is fast enough
bresenham vec ix val (xa, ya) (xb, yb)
= do yV <- var y1
errorV <- var $ deltax `div` 2
forM_ [x1 .. x2] (\x -> do
y <- get yV
drawCirc $ if steep then (y, x) else (x, y)
mutate errorV $ subtract deltay
error <- get errorV
when (error < 0) (do
mutate yV (+ ystep)
mutate errorV (+ deltax)))
where steep = abs (yb - ya) > abs (xb - xa)
(xa', ya', xb', yb')
= if steep
then (ya, xa, yb, xb)
else (xa, ya, xb, yb)
(x1, y1, x2, y2)
= if xa' > xb'
then (xb', yb', xa', ya')
else (xa', ya', xb', yb')
deltax = x2 - x1
deltay = abs $ y2 - y1
ystep = if y1 < y2 then 1 else -1
var = Data.STRef.newSTRef
get = Data.STRef.readSTRef
mutate = Data.STRef.modifySTRef
drawCirc (x,y) = do MV.write vec (ix (x,y)) val -- me
MV.write vec (ix (x,y+1)) val -- top
MV.write vec (ix (x+1,y+1)) val -- top right
MV.write vec (ix (x+1,y)) val -- right
MV.write vec (ix (x+1,y-1)) val -- down right
MV.write vec (ix (x,y-1)) val -- down
MV.write vec (ix (x-1,y-1)) val -- down left
MV.write vec (ix (x-1,y)) val -- left
MV.write vec (ix (x-1,y+1)) val -- top left
MV.write vec (ix (x,y+2)) val -- top top
MV.write vec (ix (x+2,y)) val -- right right
MV.write vec (ix (x-2,y)) val -- left left
MV.write vec (ix (x,y-2)) val -- down down
| tranma/falling-turnip | common/Draw.hs | bsd-3-clause | 3,473 | 0 | 17 | 1,269 | 1,341 | 730 | 611 | 65 | 5 |
module Notate.Actions
( runInstall
, runNotebook
, runKernel
, runEval
) where
import Control.Monad (unless, forM_)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.State.Strict
import qualified Data.Aeson as A
import qualified Data.ByteString.Lazy as BL
import Data.List (findIndex)
import IHaskell.IPython.EasyKernel (easyKernel, KernelConfig(..))
import IHaskell.IPython.Types
import qualified Language.Haskell.Interpreter as HI
import Notate.Core
import System.Directory
import System.Environment (getEnv)
import System.FilePath ((</>))
import System.IO
import System.Process
runInstall :: Kernel -> NotateM ()
runInstall kernel = do
configDir <- gets nsConfigDir
exists <- liftIO $ doesDirectoryExist configDir
if exists
then fail ("Already exists: " ++ configDir)
else do
liftIO $ createDirectory configDir
let subConfigDir = configDir </> "config"
dataDir = configDir </> "data"
runtimeDir = configDir </> "runtime"
liftIO $ createDirectory subConfigDir
liftIO $ createDirectory dataDir
liftIO $ createDirectory runtimeDir
let kernelsDir = dataDir </> "kernels"
liftIO $ createDirectory kernelsDir
let thisKernelName = languageName (kernelLanguageInfo kernel)
thisKernelDir = kernelsDir </> thisKernelName
liftIO $ createDirectory thisKernelDir
kernelSpec <- liftIO $ writeKernelspec kernel thisKernelDir
let kernelFile = thisKernelDir </> "kernel.json"
liftIO $ BL.writeFile kernelFile (A.encode (A.toJSON kernelSpec))
runNotebook :: NotateM ()
runNotebook = do
configDir <- gets nsConfigDir
home <- liftIO $ getEnv "HOME"
let subConfigDir = configDir </> "config"
dataDir = configDir </> "data"
runtimeDir = configDir </> "runtime"
procDef = CreateProcess
{ cmdspec = ShellCommand ("jupyter notebook")
, cwd = Nothing
, env = Just
[ ("HOME", home)
, ("JUPYTER_CONFIG_DIR", subConfigDir)
, ("JUPYTER_PATH", dataDir)
, ("JUPYTER_RUNTIME_DIR", runtimeDir)
]
, std_in = Inherit
, std_out = Inherit
, std_err = Inherit
, close_fds = False
, create_group = False
, delegate_ctlc = True
, detach_console = False
, create_new_console = False
, new_session = False
, child_group = Nothing
, child_user = Nothing
}
(_, _, _, handle) <- liftIO $ createProcess procDef
exitCode <- liftIO $ waitForProcess handle
liftIO $ putStrLn ("jupyter exited with " ++ (show exitCode))
return ()
runKernel :: FilePath -> Kernel -> NotateM ()
runKernel profile kernel = do
liftIO $ putStrLn "starting notate kernel"
liftIO $ easyKernel profile kernel
liftIO $ putStrLn "finished notate kernel"
runEval :: NotateM ()
runEval = do
return ()
| ejconlon/notate | src/Notate/Actions.hs | bsd-3-clause | 2,885 | 0 | 16 | 692 | 771 | 414 | 357 | 80 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE UndecidableInstances #-}
#if __GLASGOW_HASKELL__ >= 800
{-# LANGUAGE UndecidableSuperClasses #-}
#endif
module WebApi.Internal where
import Data.Text.Encoding (encodeUtf8Builder)
import Control.Exception
import Control.Monad.Catch (MonadCatch)
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Trans.Resource (runResourceT,
withInternalState)
import Data.ByteString (ByteString)
import Data.ByteString.Builder (toLazyByteString, Builder)
import Data.ByteString.Lazy as LBS (toStrict)
import Data.List (find)
#if !(MIN_VERSION_base(4,8,0))
import Data.Monoid ((<>))
#endif
import Data.Maybe (fromMaybe)
import Data.Proxy
import qualified Data.Text as T (pack)
import Data.Typeable (Typeable)
import Network.HTTP.Media (MediaType, mapAcceptMedia,
matchAccept, matchContent
, mapAccept)
import Network.HTTP.Media.RenderHeader (renderHeader)
import Network.HTTP.Types hiding (Query)
import qualified Network.Wai as Wai
import qualified Network.Wai.Parse as Wai
import Web.Cookie
import WebApi.ContentTypes
import WebApi.Contract
import WebApi.Param
import WebApi.Util
import qualified Data.Text.Encoding as TE
import GHC.TypeLits
data RouteResult a = NotMatched | Matched a
type RoutingApplication = Wai.Request -> (RouteResult Wai.Response -> IO Wai.ResponseReceived) -> IO Wai.ResponseReceived
toApplication :: RoutingApplication -> Wai.Application
toApplication app request respond =
app request $ \routeResult -> case routeResult of
Matched result -> respond result
NotMatched -> respond (Wai.responseLBS notFound404 [] "")
type FromWaiRequestCtx m r =
( FromParam 'QueryParam (QueryParam m r)
, FromParam 'FormParam (FormParam m r)
, FromParam 'FileParam (FileParam m r)
, FromHeader (HeaderIn m r)
, FromParam 'Cookie (CookieIn m r)
, ToHListRecTuple (StripContents (RequestBody m r))
, PartDecodings (RequestBody m r)
, SingMethod m
, EncodingType m r (ContentTypes m r)
)
fromWaiRequest :: forall m r. FromWaiRequestCtx m r =>
Wai.Request
-> PathParam m r
-> (Request m r -> IO (Response m r))
-> IO (Validation [ParamErr] (Response m r))
fromWaiRequest waiReq pathPar handlerFn = do
let mContentTy = getContentType $ Wai.requestHeaders waiReq
case hasFormData mContentTy of
Just _ -> do
runResourceT $ withInternalState $ \internalState -> do
(formPar, filePar) <- Wai.parseRequestBody (Wai.tempFileBackEnd internalState) waiReq
let request = Request <$> pure pathPar
<*> (fromQueryParam $ Wai.queryString waiReq)
<*> (fromFormParam formPar)
<*> (fromFileParam (fmap fromWaiFile filePar))
<*> (fromHeader $ Wai.requestHeaders waiReq)
<*> (fromCookie $ maybe [] parseCookies (getCookie waiReq))
<*> (fromBody [])
handler' (acceptHeaderType accHdr <$> request)
Nothing -> do
bdy <- Wai.lazyRequestBody waiReq
let rBody = [(fromMaybe (renderHeader $ contentType (Proxy :: Proxy OctetStream)) mContentTy, bdy)]
let request = Request <$> pure pathPar
<*> (fromQueryParam $ Wai.queryString waiReq)
<*> (fromFormParam [])
<*> (fromFileParam [])
<*> (fromHeader $ Wai.requestHeaders waiReq)
<*> (fromCookie $ maybe [] parseCookies (getCookie waiReq))
<*> (fromBody rBody)
handler' (acceptHeaderType accHdr <$> request)
where
accHdr = getAcceptType (Wai.requestHeaders waiReq)
handler' (Validation (Right req)) = handlerFn req >>= \resp -> return $ Validation (Right resp)
handler' (Validation (Left parErr)) = return $ Validation (Left parErr)
hasFormData x = matchContent [contentType (Proxy :: Proxy MultipartFormData), contentType (Proxy :: Proxy UrlEncoded)] =<< x
acceptHeaderType :: Maybe ByteString -> Request m r -> Request m r
acceptHeaderType (Just x) r =
fromMaybe r $
(\(Encoding t _ _) -> setAcceptHeader t r) <$> matchAcceptHeaders x r
acceptHeaderType Nothing r = r
fromBody x = Validation $ either (\e -> Left [NotFound (bspack e)]) (Right . fromRecTuple (Proxy :: Proxy (StripContents (RequestBody m r)))) $ partDecodings (Proxy :: Proxy (RequestBody m r)) x
bspack = TE.encodeUtf8 . T.pack
fromWaiFile :: Wai.File FilePath -> (ByteString, FileInfo)
fromWaiFile (fname, waiFileInfo) = (fname, FileInfo
{ fileName = Wai.fileName waiFileInfo
, fileContentType = Wai.fileContentType waiFileInfo
, fileContent = Wai.fileContent waiFileInfo
})
toWaiResponse :: ( ToHeader (HeaderOut m r)
, ToParam 'Cookie (CookieOut m r)
, Encodings (ContentTypes m r) (ApiOut m r)
, Encodings (ContentTypes m r) (ApiErr m r)
) => Wai.Request -> Response m r -> Wai.Response
toWaiResponse wreq resp = case resp of
Success status out hdrs cookies -> case encode' resp out of
Just (ctype, o') -> let hds = (hContentType, renderHeader ctype) : handleHeaders' (toHeader hdrs) (toCookie cookies)
in Wai.responseBuilder status hds o'
Nothing -> Wai.responseBuilder notAcceptable406 [] "Matching content type not found"
Failure (Left (ApiError status errs hdrs cookies)) -> case encode' resp errs of
Just (ctype, errs') -> let hds = (hContentType, renderHeader ctype) : handleHeaders (toHeader <$> hdrs) (toCookie <$> cookies)
in Wai.responseBuilder status hds errs'
Nothing -> Wai.responseBuilder notAcceptable406 [] "Matching content type not found"
Failure (Right (OtherError ex)) -> Wai.responseBuilder internalServerError500 [] (encodeUtf8Builder (T.pack (displayException ex)))
where encode' :: ( Encodings (ContentTypes m r) a
) => apiRes m r -> a -> Maybe (MediaType, Builder)
encode' r o = case getAccept wreq of
Just acc -> let ecs = encodings (reproxy r) o
in (,) <$> matchAccept (map fst ecs) acc <*> mapAcceptMedia ecs acc
Nothing -> case encodings (reproxy r) o of
(x : _) -> Just x
_ -> Nothing
reproxy :: apiRes m r -> Proxy (ContentTypes m r)
reproxy = const Proxy
handleHeaders :: Maybe [Header] -> Maybe [(ByteString, CookieInfo ByteString)] -> [Header]
handleHeaders hds cks = handleHeaders' (maybe [] id hds) (maybe [] id cks)
handleHeaders' :: [Header] -> [(ByteString, CookieInfo ByteString)] -> [Header]
handleHeaders' hds cookies = let ckHs = map (\(ck, cv) -> (hSetCookie , renderSC ck cv)) cookies
in hds <> ckHs
renderSC k v = toStrict . toLazyByteString . renderSetCookie $ def
{ setCookieName = k
, setCookieValue = cookieValue v
, setCookiePath = cookiePath v
, setCookieExpires = cookieExpires v
, setCookieMaxAge = cookieMaxAge v
, setCookieDomain = cookieDomain v
, setCookieHttpOnly = fromMaybe False (cookieHttpOnly v)
, setCookieSecure = fromMaybe False (cookieSecure v)
}
-- | Describes the implementation of a single API end point corresponding to @ApiContract (ApiInterface p) m r@
class (ApiContract (ApiInterface p) m r) => ApiHandler (p :: *) (m :: *) (r :: *) where
-- | Handler for the API end point which returns a 'Response'.
--
-- TODO : 'query' type parameter is an experimental one used for trying out dependently typed params.
-- This parameter will let us refine the 'ApiOut' to the structure that is requested by the client.
-- for eg : graph.facebook.com/bgolub?fields=id,name,picture
--
-- This feature is not finalized and might get changed \/ removed.
-- Currently the return type of handler is equivalent to `Response m r`
--
handler :: (query ~ '[])
=> Tagged query p
-> Request m r
-> HandlerM p (Query (Response m r) query)
type family Query (t :: *) (query :: [*]) :: * where
Query t '[] = t
-- | Binds implementation to interface and provides a pluggable handler monad for the endpoint handler implementation.
class ( MonadCatch (HandlerM p)
, MonadIO (HandlerM p)
, WebApi (ApiInterface p)
) => WebApiServer (p :: *) where
-- | Type of the handler 'Monad'. It should implement 'MonadCatch' and 'MonadIO' classes. Defaults to 'IO'.
type HandlerM p :: * -> *
type ApiInterface p :: *
-- provides common defaulting information for api handlers
-- | Create a value of @IO a@ from @HandlerM p a@.
toIO :: p -> WebApiRequest -> HandlerM p a -> IO a
default toIO :: (HandlerM p ~ IO) => p -> WebApiRequest -> HandlerM p a -> IO a
toIO _ _ = id
type HandlerM p = IO
-- | Type of settings of the server.
data ServerSettings = ServerSettings
-- | Default server settings.
serverSettings :: ServerSettings
serverSettings = ServerSettings
newtype NestedApplication (apps :: [(Symbol, *)])
= NestedApplication [Wai.Application]
unconsNesApp :: NestedApplication (app ': apps) -> (Wai.Application, NestedApplication apps)
unconsNesApp (NestedApplication (app : apps)) = (app, NestedApplication apps)
unconsNesApp (NestedApplication []) = error "Panic: cannot happen by construction"
newtype ApiComponent c = ApiComponent Wai.Application
nestedApi :: NestedApplication '[]
nestedApi = NestedApplication []
data NestedR = NestedR
-- | Type of Exception raised in a handler.
data ApiException m r = ApiException { apiException :: ApiError m r }
instance Show (ApiException m r) where
show (ApiException _) = "ApiException"
instance (Typeable m, Typeable r) => Exception (ApiException m r) where
handleApiException :: (query ~ '[], Monad (HandlerM p)) => p -> ApiException m r -> (HandlerM p) (Query (Response m r) query)
handleApiException _ = return . Failure . Left . apiException
handleSomeException :: (query ~ '[], Monad (HandlerM p)) => p -> SomeException -> (HandlerM p) (Query (Response m r) query)
handleSomeException _ = return . Failure . Right . OtherError
getCookie :: Wai.Request -> Maybe ByteString
getCookie = fmap snd . find ((== hCookie) . fst) . Wai.requestHeaders
getAccept :: Wai.Request -> Maybe ByteString
getAccept = fmap snd . find ((== hAccept) . fst) . Wai.requestHeaders
hSetCookie :: HeaderName
hSetCookie = "Set-Cookie"
getContentType :: ResponseHeaders -> Maybe ByteString
getContentType = fmap snd . find ((== hContentType) . fst)
getAcceptType :: ResponseHeaders -> Maybe ByteString
getAcceptType = fmap snd . find ((== hAccept) . fst)
newtype Tagged (s :: [*]) b = Tagged { unTagged :: b }
toTagged :: Proxy s -> b -> Tagged s b
toTagged _ = Tagged
class EncodingType m r (ctypes :: [*]) where
getEncodingType :: Proxy ctypes -> [(MediaType, Encoding m r)]
instance ( Accept ctype
, Elem ctype (ContentTypes m r)
, EncodingType m r ctypes
) => EncodingType m r (ctype ': ctypes) where
getEncodingType _ =
(contentType (Proxy :: Proxy ctype), Encoding (Proxy :: Proxy ctype) Proxy Proxy) :
getEncodingType (Proxy :: Proxy ctypes)
instance EncodingType m r '[] where
getEncodingType _ = []
matchAcceptHeaders :: forall m r ctypes.
( EncodingType m r ctypes
, ctypes ~ ContentTypes m r
) => ByteString -> Request m r -> Maybe (Encoding m r)
matchAcceptHeaders b _ =
mapAccept (getEncodingType (Proxy :: Proxy ctypes)) b
data WebApiRequest = WebApiRequest { rawRequest :: Wai.Request }
| byteally/webapi | webapi/src/WebApi/Internal.hs | bsd-3-clause | 13,144 | 0 | 28 | 3,842 | 3,611 | 1,906 | 1,705 | 214 | 7 |
#!/usr/bin/env runhaskell
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
import Control.Monad
import Data.Maybe
import Narradar
import Narradar.Types.ArgumentFiltering (AF_, simpleHeu, bestHeu, innermost)
import Narradar.Types.Problem
import Narradar.Types.Problem.Rewriting
import Narradar.Types.Problem.NarrowingGen
import Narradar.Processor.RPO
import Narradar.Processor.FLOPS08
import Narradar.Processor.LOPSTR09
import Lattice
import Narradar.Interface.Cli
main = narradarMain listToMaybe
-- Missing dispatcher cases
instance (IsProblem typ, Pretty typ) => Dispatch (Problem typ trs) where
dispatch p = error ("missing dispatcher for problem of type " ++ show (pPrint $ getFramework p))
instance Dispatch thing where dispatch _ = error "missing dispatcher"
-- Prolog
instance Dispatch PrologProblem where
dispatch = apply SKTransform >=> dispatch
-- Rewriting
instance (Pretty (DPIdentifier a), Ord a, HasTrie a) => Dispatch (NProblem Rewriting (DPIdentifier a)) where
dispatch = ev >=> (inn .|. (dg >=> rpoPlusTransforms >=> final))
instance (Pretty (DPIdentifier a), Ord a, HasTrie a) => Dispatch (NProblem IRewriting (DPIdentifier a)) where
dispatch = sc >=> rpoPlusTransforms >=> final
-- Narrowing Goal
instance (id ~ DPIdentifier a, Ord a, Lattice (AF_ id), Pretty id, HasTrie a) =>
Dispatch (NProblem (InitialGoal (TermF (DPIdentifier a)) Narrowing) (DPIdentifier a)) where
dispatch = apply (ComputeSafeAF bestHeu) >=> dg >=>
apply (NarrowingGoalToRewriting bestHeu) >=>
dispatch
dg = apply DependencyGraphSCC{useInverse=True}
sc = apply SubtermCriterion
ev = apply ExtraVarsP
inn = apply ToInnermost >=> dispatch
rpoPlusTransforms
= repeatSolver 5 ( (sc .|. lpo .|. rpos .|. graphTransform) >=> dg)
where
lpo = apply (RPOProc LPOAF Needed SMTFFI)
lpos = apply (RPOProc LPOSAF Needed SMTFFI)
rpos = apply (RPOProc RPOSAF Needed SMTFFI)
graphTransform = apply NarrowingP .|. apply FInstantiation .|. apply Instantiation
| pepeiborra/narradar | strategies/FLOPS08-search.hs | bsd-3-clause | 2,230 | 0 | 13 | 356 | 615 | 329 | 286 | -1 | -1 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, DeriveDataTypeable, RecordWildCards#-}
module CommandLine(withArgs,OutputFormat(..)) where
import System.Console.CmdLib
import qualified Math.Statistics.WCC as T
data OutputFormat = PNG | RAW deriving (Eq,Data,Typeable,Show)
data Opts = Opts { windowIncrement :: Int
, windowSize :: Int
-- , maxLag :: Int
, lagSteps :: Int
, lagIncrement :: Int
, infile :: FilePath
, outfile :: FilePath
, outputFormat :: OutputFormat
, debug :: Bool
} deriving (Eq,Data,Typeable,Show)
instance Attributes Opts where
attributes _ = group "Options"
[ windowIncrement %> [Help "Window increment", ArgHelp "INT"]
, windowSize %> [Help "The window size", ArgHelp "SIZE"]
-- , maxLag %> [Help "The maximum lag, should be divisible by lagIncrement"]
, lagSteps %> [Help "Number of lag-steps"]
, lagIncrement %> [Help "lag increment"]
, outputFormat %> [Help "RAW will output the correlation matrix, PNG a png image", Default PNG, ArgHelp "RAW|PNG"]
, infile %> [Help "The input filename. Two columns of numbers (lines starting with '#' is ignored)"
,ArgHelp "FILE"]
, outfile %> [Help "The output filename", ArgHelp "FILE"]
, debug %> [Help "Print debug information", Default False]
]
readFlag _ = readCommon <+< (readOutputFormat)
where readOutputFormat "PNG" = PNG
readOutputFormat "RAW" = RAW
readOutputFormat x = error $ "unknown output format: " ++ x
instance RecordCommand Opts where
mode_summary _ = "Compute the windowed cross correlation."
run' _ = error "run' er undefined"
-- add this to remove the warning about uninitialized fields.
-- they isn't used though
-- defaultOpts = Opts { windowIncrement = ns "windowIncrement"
-- , windowSize = ns "windowSize"
-- , maxLag = ns "maxLag"
-- , lagIncrement = ns "lagIncrement"
-- , infile = ns "input filename"
-- , outfile = ns "output filename"
-- , outputFormat = ns "output format"
-- }
-- where ns x = error $ "no " ++x++ " specified"
--withArgs f = getArgs >>= executeR defaultOpts >>= return . parseOpts >>= \(i,o,out,p) -> f i o out p
withArgs :: (FilePath -> FilePath -> Bool -> OutputFormat -> T.WCCParams -> IO ()) -> IO ()
withArgs f = getArgs >>= executeR Opts {} >>= return . parseOpts >>= \(i,o,debug,out,p) -> f i o debug out p
--withArgs f = getArgs >>= dispatchR [] >>= f
parseOpts :: Opts -> (FilePath,FilePath,Bool,OutputFormat,T.WCCParams)
parseOpts (Opts {..}) | windowIncrement < 1 = bto "windowIncrement"
| windowSize < 1 = bto "windowSize"
-- | maxLag < 1 = bto "maxLag"
| lagSteps < 1 = bto "lagSteps"
| lagIncrement < 1 = bto "lagIncrement"
-- | lagErr /= 0 = error $ "maxLag not divisible by lagIncrement"
| infile == "" = nfg "in"
| outfile == "" = nfg "out"
| otherwise = (infile,outfile,debug,outputFormat,T.WCCParams {..})
where bto = error . (++" must be bigger than one.")
nfg x = error $ "no " ++ x ++ "file given."
-- (lagSteps,lagErr) = maxLag `divMod` lagIncrement | runebak/wcc | Source/CommandLine.hs | bsd-3-clause | 3,720 | 0 | 13 | 1,296 | 708 | 387 | 321 | 44 | 1 |
module Main (main) where
import Control.Concurrent (forkIO)
import Control.Concurrent.MVar (newEmptyMVar,
MVar,
takeMVar,
putMVar)
import Control.Concurrent.STM (TVar,
atomically,
writeTVar,
newTChan,
readTVar,
newTVarIO)
import Control.Monad (forever)
import System.Environment (getArgs)
import System.Exit (exitFailure,
exitSuccess)
import System.Posix.Signals (installHandler,
sigHUP,
sigTERM,
sigINT,
Handler(Catch))
import System.IO (hSetBuffering,
hPutStrLn,
BufferMode(LineBuffering),
stdout,
stderr)
import qualified Data.Map as M
import Angel.Log (logger)
import Angel.Config (monitorConfig)
import Angel.Data (GroupConfig(GroupConfig),
spec)
import Angel.Job (pollStale,
syncSupervisors)
import Angel.Files (startFileManager)
-- |Signal handler: when a HUP is trapped, write to the wakeSig Tvar
-- |to make the configuration monitor loop cycle/reload
handleHup :: TVar (Maybe Int) -> IO ()
handleHup wakeSig = atomically $ writeTVar wakeSig $ Just 1
handleExit :: MVar Bool -> IO ()
handleExit mv = putMVar mv True
main :: IO ()
main = handleArgs =<< getArgs
handleArgs :: [String] -> IO ()
handleArgs ["--help"] = printHelp
handleArgs ["-h"] = printHelp
handleArgs [] = printHelp
handleArgs [configPath] = runWithConfigPath configPath
handleArgs _ = errorExit "expected a single config file. Run with --help for usasge."
printHelp :: IO ()
printHelp = putStrLn "Usage: angel [--help] CONFIG_FILE" >> exitSuccess
runWithConfigPath :: FilePath -> IO ()
runWithConfigPath configPath = do
hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering
let logger' = logger "main"
logger' "Angel started"
logger' $ "Using config file: " ++ configPath
-- Create the TVar that represents the "global state" of running applications
-- and applications that _should_ be running
fileReqChan <- atomically newTChan
sharedGroupConfig <- newTVarIO $ GroupConfig M.empty M.empty fileReqChan
-- The wake signal, set by the HUP handler to wake the monitor loop
wakeSig <- newTVarIO Nothing
installHandler sigHUP (Catch $ handleHup wakeSig) Nothing
-- Handle dying
bye <- newEmptyMVar
installHandler sigTERM (Catch $ handleExit bye) Nothing
installHandler sigINT (Catch $ handleExit bye) Nothing
-- Fork off an ongoing state monitor to watch for inconsistent state
forkIO $ pollStale sharedGroupConfig
forkIO $ startFileManager fileReqChan
-- Finally, run the config load/monitor thread
forkIO $ forever $ monitorConfig configPath sharedGroupConfig wakeSig
_ <- takeMVar bye
logger' "INT | TERM received; initiating shutdown..."
logger' " 1. Clearing config"
atomically $ do
cfg <- readTVar sharedGroupConfig
writeTVar sharedGroupConfig cfg {spec = M.empty}
logger' " 2. Forcing sync to kill running processes"
syncSupervisors sharedGroupConfig
logger' "That's all folks!"
errorExit :: String -> IO ()
errorExit msg = hPutStrLn stderr msg >> exitFailure
| zalora/Angel | src/Angel/Main.hs | bsd-3-clause | 3,527 | 0 | 13 | 1,051 | 737 | 380 | 357 | 76 | 1 |
module Rash.Runtime.Interpreter where
import Control.Monad.IO.Class (liftIO)
import qualified Control.Monad.Trans.State as State
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
import qualified GHC.IO.Handle as Handle
import qualified System.IO as IO
import qualified System.Process as Proc
import qualified Rash.Debug as Debug
import Rash.IR.AST
import Rash.Runtime.Builtins as Builtins
import qualified Rash.Runtime.Process as Process
import qualified Rash.Runtime.Runtime as RT
import Rash.Runtime.Types
import qualified Rash.Util as Util
debug :: Show a => String -> a -> a
debug a b = Debug.traceTmpl "exe" a b
debugM :: (Show a, Monad f, Applicative f) => String -> a -> f ()
debugM a b = Debug.traceMTmpl "exe" a b
die :: Show a => String -> a -> t
die a b = Debug.die "exe" a b
interpret :: Program -> [String] -> IO Value
interpret (Program exprs) args = do
let st = Map.insert "sys.argv" (VArray (map VString args)) Map.empty
let ft = Builtins.builtins
let hs = Handles IO.stdin IO.stdout IO.stderr
let state = IState (Frame st hs) ft
(val, final) <- State.runStateT (evalExprs exprs) state
debugM "final state" final
return val
evalExprs :: [Expr] -> WithState Value
evalExprs es = do
debugM ("executing a list with " ++ (show (length es)) ++ " exprs") ()
evaled <- mapM evalExpr es
return (last evaled)
evalExpr :: Expr -> WithState Value
evalExpr e = do
_ <- debugM "executing" e
v <- evalExpr' e
_ <- debugM "returning" v
_ <- debugM " <- " e
return v
evalExpr' :: Expr -> WithState Value
evalExpr' Nop = return VNull
evalExpr' (FunctionDefinition fd@(FuncDef name _ _)) = do
RT.updateFuncTable $ Map.insert name (UserDefined fd)
return VNull
evalExpr' (If cond then' else') = do
condVal <- evalExpr cond
if Util.isTruthy condVal then evalExprs then' else evalExprs else'
evalExpr' (Binop l Equals r) = do
lval <- evalExpr l
rval <- evalExpr r
return $ VBool (lval == rval)
evalExpr' (Binop l And r) = do
lval <- evalExpr l
res <- if (Util.isTruthy lval) then
do rval <- evalExpr r
return $ Util.isTruthy rval
else return False
return $ VBool res
evalExpr' (Unop Not e) = do
res <- evalExpr e
return $ VBool $ not (Util.isTruthy res)
evalExpr' (Concat exprs) = do
vs <- mapM evalExpr exprs
return $ VString $ foldl (\a b -> a ++ (Util.asString b)) "" vs
evalExpr' (Variable name) = do
st <- RT.getSymTable
return $ fromMaybe VNull $ Map.lookup name st
evalExpr' ss@(Subscript (Variable name) e) = do
index <- evalExpr e
st <- RT.getSymTable
let var = Map.lookup name st
return $ case (var, index) of
(Just (VArray a), VInt i) -> Util.findWithDefault a i VNull
(Just (VHash h), VString s) -> Map.findWithDefault VNull s h
_ -> die "Can't do a subscript unless on array/int or hash/string" (ss, var, index)
evalExpr' (Assignment (LVar name) e) = do
result <- evalExpr e
RT.updateSymTable $ Map.insert name result
return result
------------------------------------------------
-- Function calls and pipes
------------------------------------------------
evalExpr' (Pipe (Stdin input) fns) = do
inputStr <- eval2Str input
(r,w) <- liftIO $ Proc.createPipe
liftIO $ IO.hPutStr w inputStr
result <- evalPipe fns r
liftIO $ IO.hClose r
return result
evalExpr' (Pipe NoStdin fns) = do
stdin <- RT.getStdin
evalPipe fns stdin
evalExpr' Null = return VNull
evalExpr' (Integer i) = return $ VInt i
evalExpr' (Str s) = return $ VString s
evalExpr' (Array es) = do
as <- mapM evalExpr es
return $ VArray as
evalExpr' e = do
die "an unsupported expression was found" e
eval2Str :: Expr -> WithState String
eval2Str e = do
expr <- evalExpr e
let (VString str) = Util.toString expr
return str
evalPipe :: [FunctionCall] -> Handle.Handle -> WithState Value
evalPipe fns stdin = do
commands <- mapM evalArgs fns
Process.evalPipe commands stdin evalExpr
where
evalArgs (Fn name args) = do
args2 <- mapM evalExpr args
return (name, args2)
evalArgs e = die "how do we invoke non-FunctionInvocations" e
| pbiggar/rash | src/Rash/Runtime/Interpreter.hs | bsd-3-clause | 4,274 | 0 | 14 | 1,002 | 1,626 | 794 | 832 | 113 | 5 |
{-# LANGUAGE FlexibleContexts #-}
module TypeCheck where
import Control.Monad.Except
import Control.Monad.Reader
import Data.List
import Text.Printf
type TypeVar = String
data Type = Type :->: Type
| TVar TypeVar
| ForAll TypeVar Type
deriving (Show)
infixr :->:
instance Eq Type where
(==) = go []
where
go :: [(TypeVar, TypeVar)] -> Type -> Type -> Bool
go ctx (ll :->: lr) (rl :->: rr) = (go ctx ll rl) && (go ctx lr rr)
go ctx (ForAll vl l) (ForAll vr r) = go ((vl, vr):ctx) l r
go ctx (TVar vl) (TVar vr) = let res = find (\(name, _) -> name == vl) ctx in
case res of Nothing -> vl == vr
Just (_, n) -> n == vr
go _ _ _ = False
type ExprVar = String
data Expr = EVar ExprVar
| Abs (ExprVar, Type) Expr
| TAbs TypeVar Expr
| Expr :@: Expr
| Expr :$: Type
deriving (Show, Eq)
infixl :@: -- Application term to term
infixl :$: -- Application type to term
data Assumption = EAs ExprVar Type
| TAs TypeVar
newtype Context = Context [Assumption]
getTypeFromContext :: ExprVar -> Context -> Maybe Type
getTypeFromContext varName (Context ctx) = go ctx
where
go :: [Assumption] -> Maybe Type
go [] = Nothing
go ((EAs varName' t):xs) | varName' == varName = Just t
go (_:xs) = go xs
addEAs :: ExprVar -> Type -> Context -> Context
addEAs varName varType (Context ctx) = Context $ (EAs varName varType):ctx
addTAs :: TypeVar -> Context -> Context
addTAs typeVarName (Context ctx) = Context $ (TAs typeVarName):ctx
emptyContext :: Context
emptyContext = Context []
fromListContext :: [Assumption] -> Context
fromListContext = Context
typeSubst :: TypeVar -> Type -> Type -> Type
typeSubst typeVarName concreteType = go
where
go (tl :->: tr) = go tl :->: go tr
go t@(TVar name) = if name == typeVarName then concreteType
else t
go t@(ForAll name st) = if name /= typeVarName then ForAll name $ go st
else t
typeCheck :: ( Monad m
, MonadReader Context m
, MonadError String m
) => Expr -> m Type
typeCheck (EVar varName) = do
t <- reader $ getTypeFromContext varName
case t of Nothing -> throwError $ printf "Unknown variable: %s" varName
Just t -> return t
typeCheck (Abs (varName, varType) e) = do
t <- local (addEAs varName varType) (typeCheck e)
return $ varType :->: t
typeCheck (TAbs typeVarName e) = do
t <- local (addTAs typeVarName) (typeCheck e)
return $ ForAll typeVarName t
typeCheck (el :@: er) = do
tl <- typeCheck el
tr <- typeCheck er
case tl of (argType :->: resultType) | argType == tr -> return resultType
_ -> throwError errorMsg
where
errorMsg = printf ("Term (%s) :: (%s)\n" ++
"is not applicable to\n" ++
"term (%s) :: (%s)")
(show er) (show tr) (show el) (show tl)
typeCheck (e :$: concreteType) = do
exprType <- typeCheck e
case exprType of (ForAll typeVarName t) -> return $ typeSubst typeVarName concreteType t
_ -> throwError errorMsg
where
errorMsg = printf ("Type (%s)\n" ++
"is not applicable to\n" ++
"term (%s) :: (%s)\n")
(show concreteType) (show e) (show exprType)
runTypeCheckInContext :: Context -> Expr -> Either String Type
runTypeCheckInContext ctx expr = runExcept $ runReaderT (typeCheck expr) ctx
runTypeCheck :: Expr -> Either String Type
runTypeCheck expr = runTypeCheckInContext emptyContext expr
| SergeevPavel/system-f-typecheck | src/TypeCheck.hs | bsd-3-clause | 4,261 | 0 | 15 | 1,678 | 1,297 | 666 | 631 | 89 | 5 |
{-# language CPP #-}
-- No documentation found for Chapter "BufferView"
module Vulkan.Core10.BufferView ( createBufferView
, withBufferView
, destroyBufferView
, BufferViewCreateInfo(..)
, BufferView(..)
, BufferViewCreateFlags(..)
) where
import Vulkan.Internal.Utils (traceAroundEvent)
import Control.Exception.Base (bracket)
import Control.Monad (unless)
import Control.Monad.IO.Class (liftIO)
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Marshal.Alloc (callocBytes)
import Foreign.Marshal.Alloc (free)
import GHC.Base (when)
import GHC.IO (throwIO)
import GHC.Ptr (nullFunPtr)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (evalContT)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero(..))
import Control.Monad.IO.Class (MonadIO)
import Data.Typeable (Typeable)
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import GHC.IO.Exception (IOErrorType(..))
import GHC.IO.Exception (IOException(..))
import Foreign.Ptr (FunPtr)
import Foreign.Ptr (Ptr)
import Data.Kind (Type)
import Control.Monad.Trans.Cont (ContT(..))
import Vulkan.NamedType ((:::))
import Vulkan.Core10.AllocationCallbacks (AllocationCallbacks)
import Vulkan.Core10.Handles (Buffer)
import Vulkan.Core10.Handles (BufferView)
import Vulkan.Core10.Handles (BufferView(..))
import Vulkan.Core10.Enums.BufferViewCreateFlags (BufferViewCreateFlags)
import Vulkan.Core10.Handles (Device)
import Vulkan.Core10.Handles (Device(..))
import Vulkan.Core10.Handles (Device(Device))
import Vulkan.Dynamic (DeviceCmds(pVkCreateBufferView))
import Vulkan.Dynamic (DeviceCmds(pVkDestroyBufferView))
import Vulkan.Core10.FundamentalTypes (DeviceSize)
import Vulkan.Core10.Handles (Device_T)
import Vulkan.Core10.Enums.Format (Format)
import Vulkan.Core10.Enums.Result (Result)
import Vulkan.Core10.Enums.Result (Result(..))
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Exception (VulkanException(..))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO))
import Vulkan.Core10.Enums.Result (Result(SUCCESS))
import Vulkan.Core10.Handles (BufferView(..))
import Vulkan.Core10.Enums.BufferViewCreateFlags (BufferViewCreateFlags(..))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkCreateBufferView
:: FunPtr (Ptr Device_T -> Ptr BufferViewCreateInfo -> Ptr AllocationCallbacks -> Ptr BufferView -> IO Result) -> Ptr Device_T -> Ptr BufferViewCreateInfo -> Ptr AllocationCallbacks -> Ptr BufferView -> IO Result
-- | vkCreateBufferView - Create a new buffer view object
--
-- == Valid Usage (Implicit)
--
-- - #VUID-vkCreateBufferView-device-parameter# @device@ /must/ be a
-- valid 'Vulkan.Core10.Handles.Device' handle
--
-- - #VUID-vkCreateBufferView-pCreateInfo-parameter# @pCreateInfo@ /must/
-- be a valid pointer to a valid 'BufferViewCreateInfo' structure
--
-- - #VUID-vkCreateBufferView-pAllocator-parameter# If @pAllocator@ is
-- not @NULL@, @pAllocator@ /must/ be a valid pointer to a valid
-- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' structure
--
-- - #VUID-vkCreateBufferView-pView-parameter# @pView@ /must/ be a valid
-- pointer to a 'Vulkan.Core10.Handles.BufferView' handle
--
-- == Return Codes
--
-- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>]
--
-- - 'Vulkan.Core10.Enums.Result.SUCCESS'
--
-- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
--
-- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY'
--
-- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY'
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>,
-- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks',
-- 'Vulkan.Core10.Handles.BufferView', 'BufferViewCreateInfo',
-- 'Vulkan.Core10.Handles.Device'
createBufferView :: forall io
. (MonadIO io)
=> -- | @device@ is the logical device that creates the buffer view.
Device
-> -- | @pCreateInfo@ is a pointer to a 'BufferViewCreateInfo' structure
-- containing parameters to be used to create the buffer view.
BufferViewCreateInfo
-> -- | @pAllocator@ controls host memory allocation as described in the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation Memory Allocation>
-- chapter.
("allocator" ::: Maybe AllocationCallbacks)
-> io (BufferView)
createBufferView device createInfo allocator = liftIO . evalContT $ do
let vkCreateBufferViewPtr = pVkCreateBufferView (case device of Device{deviceCmds} -> deviceCmds)
lift $ unless (vkCreateBufferViewPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCreateBufferView is null" Nothing Nothing
let vkCreateBufferView' = mkVkCreateBufferView vkCreateBufferViewPtr
pCreateInfo <- ContT $ withCStruct (createInfo)
pAllocator <- case (allocator) of
Nothing -> pure nullPtr
Just j -> ContT $ withCStruct (j)
pPView <- ContT $ bracket (callocBytes @BufferView 8) free
r <- lift $ traceAroundEvent "vkCreateBufferView" (vkCreateBufferView' (deviceHandle (device)) pCreateInfo pAllocator (pPView))
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
pView <- lift $ peek @BufferView pPView
pure $ (pView)
-- | A convenience wrapper to make a compatible pair of calls to
-- 'createBufferView' and 'destroyBufferView'
--
-- To ensure that 'destroyBufferView' is always called: pass
-- 'Control.Exception.bracket' (or the allocate function from your
-- favourite resource management library) as the last argument.
-- To just extract the pair pass '(,)' as the last argument.
--
withBufferView :: forall io r . MonadIO io => Device -> BufferViewCreateInfo -> Maybe AllocationCallbacks -> (io BufferView -> (BufferView -> io ()) -> r) -> r
withBufferView device pCreateInfo pAllocator b =
b (createBufferView device pCreateInfo pAllocator)
(\(o0) -> destroyBufferView device o0 pAllocator)
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkDestroyBufferView
:: FunPtr (Ptr Device_T -> BufferView -> Ptr AllocationCallbacks -> IO ()) -> Ptr Device_T -> BufferView -> Ptr AllocationCallbacks -> IO ()
-- | vkDestroyBufferView - Destroy a buffer view object
--
-- == Valid Usage
--
-- - #VUID-vkDestroyBufferView-bufferView-00936# All submitted commands
-- that refer to @bufferView@ /must/ have completed execution
--
-- - #VUID-vkDestroyBufferView-bufferView-00937# If
-- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' were
-- provided when @bufferView@ was created, a compatible set of
-- callbacks /must/ be provided here
--
-- - #VUID-vkDestroyBufferView-bufferView-00938# If no
-- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' were
-- provided when @bufferView@ was created, @pAllocator@ /must/ be
-- @NULL@
--
-- == Valid Usage (Implicit)
--
-- - #VUID-vkDestroyBufferView-device-parameter# @device@ /must/ be a
-- valid 'Vulkan.Core10.Handles.Device' handle
--
-- - #VUID-vkDestroyBufferView-bufferView-parameter# If @bufferView@ is
-- not 'Vulkan.Core10.APIConstants.NULL_HANDLE', @bufferView@ /must/ be
-- a valid 'Vulkan.Core10.Handles.BufferView' handle
--
-- - #VUID-vkDestroyBufferView-pAllocator-parameter# If @pAllocator@ is
-- not @NULL@, @pAllocator@ /must/ be a valid pointer to a valid
-- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks' structure
--
-- - #VUID-vkDestroyBufferView-bufferView-parent# If @bufferView@ is a
-- valid handle, it /must/ have been created, allocated, or retrieved
-- from @device@
--
-- == Host Synchronization
--
-- - Host access to @bufferView@ /must/ be externally synchronized
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>,
-- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks',
-- 'Vulkan.Core10.Handles.BufferView', 'Vulkan.Core10.Handles.Device'
destroyBufferView :: forall io
. (MonadIO io)
=> -- | @device@ is the logical device that destroys the buffer view.
Device
-> -- | @bufferView@ is the buffer view to destroy.
BufferView
-> -- | @pAllocator@ controls host memory allocation as described in the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation Memory Allocation>
-- chapter.
("allocator" ::: Maybe AllocationCallbacks)
-> io ()
destroyBufferView device bufferView allocator = liftIO . evalContT $ do
let vkDestroyBufferViewPtr = pVkDestroyBufferView (case device of Device{deviceCmds} -> deviceCmds)
lift $ unless (vkDestroyBufferViewPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkDestroyBufferView is null" Nothing Nothing
let vkDestroyBufferView' = mkVkDestroyBufferView vkDestroyBufferViewPtr
pAllocator <- case (allocator) of
Nothing -> pure nullPtr
Just j -> ContT $ withCStruct (j)
lift $ traceAroundEvent "vkDestroyBufferView" (vkDestroyBufferView' (deviceHandle (device)) (bufferView) pAllocator)
pure $ ()
-- | VkBufferViewCreateInfo - Structure specifying parameters of a newly
-- created buffer view
--
-- == Valid Usage
--
-- - #VUID-VkBufferViewCreateInfo-offset-00925# @offset@ /must/ be less
-- than the size of @buffer@
--
-- - #VUID-VkBufferViewCreateInfo-range-00928# If @range@ is not equal to
-- 'Vulkan.Core10.APIConstants.WHOLE_SIZE', @range@ /must/ be greater
-- than @0@
--
-- - #VUID-VkBufferViewCreateInfo-range-00929# If @range@ is not equal to
-- 'Vulkan.Core10.APIConstants.WHOLE_SIZE', @range@ /must/ be an
-- integer multiple of the texel block size of @format@
--
-- - #VUID-VkBufferViewCreateInfo-range-00930# If @range@ is not equal to
-- 'Vulkan.Core10.APIConstants.WHOLE_SIZE', the number of texel buffer
-- elements given by (⌊@range@ \/ (texel block size)⌋ × (texels per
-- block)) where texel block size and texels per block are as defined
-- in the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-compatibility Compatible Formats>
-- table for @format@, /must/ be less than or equal to
-- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxTexelBufferElements@
--
-- - #VUID-VkBufferViewCreateInfo-offset-00931# If @range@ is not equal
-- to 'Vulkan.Core10.APIConstants.WHOLE_SIZE', the sum of @offset@ and
-- @range@ /must/ be less than or equal to the size of @buffer@
--
-- - #VUID-VkBufferViewCreateInfo-range-04059# If @range@ is equal to
-- 'Vulkan.Core10.APIConstants.WHOLE_SIZE', the number of texel buffer
-- elements given by (⌊(size - @offset@) \/ (texel block size)⌋ ×
-- (texels per block)) where size is the size of @buffer@, and texel
-- block size and texels per block are as defined in the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#formats-compatibility Compatible Formats>
-- table for @format@, /must/ be less than or equal to
-- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxTexelBufferElements@
--
-- - #VUID-VkBufferViewCreateInfo-buffer-00932# @buffer@ /must/ have been
-- created with a @usage@ value containing at least one of
-- 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT'
-- or
-- 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT'
--
-- - #VUID-VkBufferViewCreateInfo-buffer-00933# If @buffer@ was created
-- with @usage@ containing
-- 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT',
-- @format@ /must/ be supported for uniform texel buffers, as specified
-- by the
-- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT'
-- flag in
-- 'Vulkan.Core10.DeviceInitialization.FormatProperties'::@bufferFeatures@
-- returned by
-- 'Vulkan.Core10.DeviceInitialization.getPhysicalDeviceFormatProperties'
--
-- - #VUID-VkBufferViewCreateInfo-buffer-00934# If @buffer@ was created
-- with @usage@ containing
-- 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT',
-- @format@ /must/ be supported for storage texel buffers, as specified
-- by the
-- 'Vulkan.Core10.Enums.FormatFeatureFlagBits.FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT'
-- flag in
-- 'Vulkan.Core10.DeviceInitialization.FormatProperties'::@bufferFeatures@
-- returned by
-- 'Vulkan.Core10.DeviceInitialization.getPhysicalDeviceFormatProperties'
--
-- - #VUID-VkBufferViewCreateInfo-buffer-00935# If @buffer@ is non-sparse
-- then it /must/ be bound completely and contiguously to a single
-- 'Vulkan.Core10.Handles.DeviceMemory' object
--
-- - #VUID-VkBufferViewCreateInfo-offset-02749# If the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-texelBufferAlignment texelBufferAlignment>
-- feature is not enabled, @offset@ /must/ be a multiple of
-- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@minTexelBufferOffsetAlignment@
--
-- - #VUID-VkBufferViewCreateInfo-buffer-02750# If the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-texelBufferAlignment texelBufferAlignment>
-- feature is enabled and if @buffer@ was created with @usage@
-- containing
-- 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT',
-- @offset@ /must/ be a multiple of the lesser of
-- 'Vulkan.Core13.Promoted_From_VK_EXT_texel_buffer_alignment.PhysicalDeviceTexelBufferAlignmentProperties'::@storageTexelBufferOffsetAlignmentBytes@
-- or, if
-- 'Vulkan.Core13.Promoted_From_VK_EXT_texel_buffer_alignment.PhysicalDeviceTexelBufferAlignmentProperties'::@storageTexelBufferOffsetSingleTexelAlignment@
-- is 'Vulkan.Core10.FundamentalTypes.TRUE', the size of a texel of the
-- requested @format@. If the size of a texel is a multiple of three
-- bytes, then the size of a single component of @format@ is used
-- instead
--
-- - #VUID-VkBufferViewCreateInfo-buffer-02751# If the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-texelBufferAlignment texelBufferAlignment>
-- feature is enabled and if @buffer@ was created with @usage@
-- containing
-- 'Vulkan.Core10.Enums.BufferUsageFlagBits.BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT',
-- @offset@ /must/ be a multiple of the lesser of
-- 'Vulkan.Core13.Promoted_From_VK_EXT_texel_buffer_alignment.PhysicalDeviceTexelBufferAlignmentProperties'::@uniformTexelBufferOffsetAlignmentBytes@
-- or, if
-- 'Vulkan.Core13.Promoted_From_VK_EXT_texel_buffer_alignment.PhysicalDeviceTexelBufferAlignmentProperties'::@uniformTexelBufferOffsetSingleTexelAlignment@
-- is 'Vulkan.Core10.FundamentalTypes.TRUE', the size of a texel of the
-- requested @format@. If the size of a texel is a multiple of three
-- bytes, then the size of a single component of @format@ is used
-- instead
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkBufferViewCreateInfo-sType-sType# @sType@ /must/ be
-- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO'
--
-- - #VUID-VkBufferViewCreateInfo-pNext-pNext# @pNext@ /must/ be @NULL@
--
-- - #VUID-VkBufferViewCreateInfo-flags-zerobitmask# @flags@ /must/ be
-- @0@
--
-- - #VUID-VkBufferViewCreateInfo-buffer-parameter# @buffer@ /must/ be a
-- valid 'Vulkan.Core10.Handles.Buffer' handle
--
-- - #VUID-VkBufferViewCreateInfo-format-parameter# @format@ /must/ be a
-- valid 'Vulkan.Core10.Enums.Format.Format' value
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>,
-- 'Vulkan.Core10.Handles.Buffer',
-- 'Vulkan.Core10.Enums.BufferViewCreateFlags.BufferViewCreateFlags',
-- 'Vulkan.Core10.FundamentalTypes.DeviceSize',
-- 'Vulkan.Core10.Enums.Format.Format',
-- 'Vulkan.Core10.Enums.StructureType.StructureType', 'createBufferView'
data BufferViewCreateInfo = BufferViewCreateInfo
{ -- | @flags@ is reserved for future use.
flags :: BufferViewCreateFlags
, -- | @buffer@ is a 'Vulkan.Core10.Handles.Buffer' on which the view will be
-- created.
buffer :: Buffer
, -- | @format@ is a 'Vulkan.Core10.Enums.Format.Format' describing the format
-- of the data elements in the buffer.
format :: Format
, -- | @offset@ is an offset in bytes from the base address of the buffer.
-- Accesses to the buffer view from shaders use addressing that is relative
-- to this starting offset.
offset :: DeviceSize
, -- | @range@ is a size in bytes of the buffer view. If @range@ is equal to
-- 'Vulkan.Core10.APIConstants.WHOLE_SIZE', the range from @offset@ to the
-- end of the buffer is used. If 'Vulkan.Core10.APIConstants.WHOLE_SIZE' is
-- used and the remaining size of the buffer is not a multiple of the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#texel-block-size texel block size>
-- of @format@, the nearest smaller multiple is used.
range :: DeviceSize
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (BufferViewCreateInfo)
#endif
deriving instance Show BufferViewCreateInfo
instance ToCStruct BufferViewCreateInfo where
withCStruct x f = allocaBytes 56 $ \p -> pokeCStruct p x (f p)
pokeCStruct p BufferViewCreateInfo{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr BufferViewCreateFlags)) (flags)
poke ((p `plusPtr` 24 :: Ptr Buffer)) (buffer)
poke ((p `plusPtr` 32 :: Ptr Format)) (format)
poke ((p `plusPtr` 40 :: Ptr DeviceSize)) (offset)
poke ((p `plusPtr` 48 :: Ptr DeviceSize)) (range)
f
cStructSize = 56
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 24 :: Ptr Buffer)) (zero)
poke ((p `plusPtr` 32 :: Ptr Format)) (zero)
poke ((p `plusPtr` 40 :: Ptr DeviceSize)) (zero)
poke ((p `plusPtr` 48 :: Ptr DeviceSize)) (zero)
f
instance FromCStruct BufferViewCreateInfo where
peekCStruct p = do
flags <- peek @BufferViewCreateFlags ((p `plusPtr` 16 :: Ptr BufferViewCreateFlags))
buffer <- peek @Buffer ((p `plusPtr` 24 :: Ptr Buffer))
format <- peek @Format ((p `plusPtr` 32 :: Ptr Format))
offset <- peek @DeviceSize ((p `plusPtr` 40 :: Ptr DeviceSize))
range <- peek @DeviceSize ((p `plusPtr` 48 :: Ptr DeviceSize))
pure $ BufferViewCreateInfo
flags buffer format offset range
instance Storable BufferViewCreateInfo where
sizeOf ~_ = 56
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero BufferViewCreateInfo where
zero = BufferViewCreateInfo
zero
zero
zero
zero
zero
| expipiplus1/vulkan | src/Vulkan/Core10/BufferView.hs | bsd-3-clause | 20,307 | 0 | 17 | 3,415 | 2,604 | 1,545 | 1,059 | -1 | -1 |
module BowlingKata.Day6Spec (spec) where
import Test.Hspec
import BowlingKata.Day6 (score)
spec :: Spec
spec = do
it "is a gutter game"
((score . replicate 20 $ 0) == 0)
it "rolls all ones"
((score . replicate 20 $ 1) == 20)
it "rolls one spare"
((score $ 5:5:3:(replicate 17 $ 0)) == 16)
it "rolls one strike"
((score $ 10:4:3:(replicate 16 $ 0)) == 24)
it "is a perfect game"
((score . replicate 12 $ 10) == 300)
| Alex-Diez/haskell-tdd-kata | old-katas/test/BowlingKata/Day6Spec.hs | bsd-3-clause | 537 | 0 | 14 | 199 | 211 | 108 | 103 | 15 | 1 |
{-# LANGUAGE BangPatterns #-}
module BinaryHeapSTMSpec where
import Control.Concurrent.STM
import Data.IORef (readIORef)
import Data.List (group, sort)
import Test.Hspec
import qualified BinaryHeapSTM as P
spec :: Spec
spec = do
describe "base priority queue" $ do
it "queues entries based on weight" $ do
q <- atomically $ P.new 100
e1 <- atomically $ P.newEntry 1 201
atomically $ P.enqueue e1 q
e2 <- atomically $ P.newEntry 3 101
atomically $ P.enqueue e2 q
e3 <- atomically $ P.newEntry 5 1
atomically $ P.enqueue e3 q
xs <- enqdeq q 1000
map length (group (sort xs)) `shouldBe` [664,333,3]
it "deletes properly" $ do
q <- atomically $ P.new 100
e1 <- atomically $ P.newEntry 1 201
e3 <- atomically $ P.newEntry 3 50
e5 <- atomically $ P.newEntry 5 5
e7 <- atomically $ P.newEntry 7 1
atomically $ P.enqueue e1 q
atomically $ P.enqueue e3 q
atomically $ P.enqueue e5 q
atomically $ P.enqueue e7 q
i1 <- atomically $ P.dequeue q
atomically (readTVar (P.item i1)) `shouldReturn` 1
atomically $ P.delete e5 q
i3 <- atomically $ P.dequeue q
atomically (readTVar (P.item i3)) `shouldReturn` 3
i7 <- atomically $ P.dequeue q
atomically (readTVar (P.item i7)) `shouldReturn` 7
enqdeq :: P.PriorityQueue Int -> Int -> IO [Int]
enqdeq pq num = loop pq num []
where
loop _ 0 vs = return vs
loop !q !n vs = do
ent <- atomically $ P.dequeue q
atomically $ P.enqueue ent q
v <- atomically . readTVar $ P.item ent
loop q (n - 1) (v:vs)
| kazu-yamamoto/http2 | bench-priority/test/BinaryHeapSTMSpec.hs | bsd-3-clause | 1,801 | 0 | 19 | 627 | 676 | 319 | 357 | 45 | 2 |
{-- snippet all --}
module PodParser where
import PodTypes
import Text.XML.HaXml
import Text.XML.HaXml.Parse
import Text.XML.HaXml.Html.Generate(showattr)
import Data.Char
import Data.List
data Item = Item {itemtitle :: String,
enclosureurl :: String
}
deriving (Eq, Show, Read)
data Feed = Feed {channeltitle :: String,
items :: [Item]}
deriving (Eq, Show, Read)
{- | Given a podcast and an Item, produce an Episode -}
item2ep :: Podcast -> Item -> Episode
item2ep pc item =
Episode {epId = 0,
epCast = pc,
epURL = enclosureurl item,
epDone = False}
{- | Parse the data from a given string, with the given name to use
in error messages. -}
parse :: String -> String -> Feed
parse content name =
Feed {channeltitle = getTitle doc,
items = getEnclosures doc}
where parseResult = xmlParse name (stripUnicodeBOM content)
doc = getContent parseResult
getContent :: Document -> Content
getContent (Document _ _ e _) = CElem e
{- | Some Unicode documents begin with a binary sequence;
strip it off before processing. -}
stripUnicodeBOM :: String -> String
stripUnicodeBOM ('\xef':'\xbb':'\xbf':x) = x
stripUnicodeBOM x = x
{- | Pull out the channel part of the document.
Note that HaXml defines CFilter as:
> type CFilter = Content -> [Content]
-}
channel :: CFilter
channel = tag "rss" /> tag "channel"
getTitle :: Content -> String
getTitle doc =
contentToStringDefault "Untitled Podcast"
(channel /> tag "title" /> txt $ doc)
getEnclosures :: Content -> [Item]
getEnclosures doc =
concatMap procItem $ getItems doc
where procItem :: Content -> [Item]
procItem item = concatMap (procEnclosure title) enclosure
where title = contentToStringDefault "Untitled Episode"
(keep /> tag "title" /> txt $ item)
enclosure = (keep /> tag "enclosure") item
getItems :: CFilter
getItems = channel /> tag "item"
procEnclosure :: String -> Content -> [Item]
procEnclosure title enclosure =
map makeItem (showattr "url" enclosure)
where makeItem :: Content -> Item
makeItem x = Item {itemtitle = title,
enclosureurl = contentToString [x]}
{- | Convert [Content] to a printable String, with a default if the
passed-in [Content] is [], signifying a lack of a match. -}
contentToStringDefault :: String -> [Content] -> String
contentToStringDefault msg [] = msg
contentToStringDefault _ x = contentToString x
{- | Convert [Content] to a printable string, taking care to unescape it.
An implementation without unescaping would simply be:
> contentToString = concatMap (show . content)
Because HaXml's unescaping only works on Elements, we must make sure that
whatever Content we have is wrapped in an Element, then use txt to
pull the insides back out. -}
contentToString :: [Content] -> String
contentToString =
concatMap procContent
where procContent x =
verbatim $ keep /> txt $ CElem (unesc (fakeElem x))
fakeElem :: Content -> Element
fakeElem x = Elem "fake" [] [x]
unesc :: Element -> Element
unesc = xmlUnEscape stdXmlEscaper
{-- /snippet all --}
| binesiyu/ifl | examples/ch23/PodParser.hs | mit | 3,472 | 0 | 14 | 1,009 | 721 | 391 | 330 | 64 | 2 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
-- Note: this file may contain spoilers
-- (although I would be really surprised if it did, I haven't seen the films)
module StarWars where
import GHC.Generics
import Data.Generics.Product
data Episode = NEWHOPE | EMPIRE | JEDI
deriving (Generic, Show, Eq)
data Character = Character
{ name :: String
, friends :: [Character]
, appearsIn :: [Episode]
} deriving (Generic, Show, Eq)
data Human = Human
{ name :: String
, friends :: [Character]
, appearsIn :: [Episode]
, homePlanet :: String
} deriving (Generic, Show)
data Droid = Droid
{ friends :: [Character]
, appearsIn :: [Episode]
, name :: String
, primaryFunction :: String
} deriving (Generic, Show)
luke :: Human
luke = Human
{ name = "Luke Skywalker"
, friends = []
, appearsIn = [NEWHOPE, EMPIRE, JEDI]
, homePlanet = "Saturn (?)"
}
r2d2 :: Droid
r2d2 = Droid
{ name = "R2-D2"
, friends = [upcast luke]
, appearsIn = [NEWHOPE, EMPIRE, JEDI]
, primaryFunction = "repair ships"
}
c3po :: Droid
c3po = Droid
{ name = "C3PO"
, friends = [upcast r2d2, upcast luke]
, appearsIn = [NEWHOPE, EMPIRE, JEDI]
, primaryFunction = "protocol and human relations"
}
getName :: HasField' "name" r a => r -> a
getName = getField @"name"
-- upcast :: Subtype a b => a -> b
characters :: [Character]
characters = [upcast r2d2, upcast luke, upcast c3po]
names :: [String]
names = map getName characters
-- => ["R2-D2","Luke Skywalker","C3PO"]
| kcsongor/generic-lens | generic-optics/examples/StarWars.hs | bsd-3-clause | 1,786 | 0 | 9 | 464 | 435 | 266 | 169 | 52 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TypeOperators #-}
module CommonServer where
import Data.Aeson
import GHC.Generics
------------------------------
-- File Structure
------------------------------
data File = File {
fileName :: FilePath,
fileContent :: String
} deriving (Eq, Show, Generic)
instance ToJSON File
instance FromJSON File
------------------------------
-- Server Identity
------------------------------
data Identity = Identity {
address :: String,
port :: String,
serverType :: ServerType
} deriving (Eq, Show, Generic)
instance ToJSON Identity
instance FromJSON Identity
------------------------------
-- Registered Server Types
------------------------------
data ServerType =
FileServer |
DirectoryServer |
ProxyServer |
SecurityServer |
TransactionServer |
IdentityServer |
ReplicationServer
deriving(Eq, Show, Generic)
instance ToJSON ServerType
instance FromJSON ServerType
------------------------------
-- Resources Directory
------------------------------
data Resources = Resources {
path :: String
} deriving (Eq, Show, Generic)
instance ToJSON Resources
instance FromJSON Resources
------------------------------
-- Client Data
------------------------------
data Client = Client {
username :: String,
password :: String
} deriving (Eq, Show, Generic)
instance ToJSON Client
instance FromJSON Client
------------------------------
-- Security Token
------------------------------
data Token = Token {
sessionId :: String,
sessionKey :: String,
ticket :: String,
client :: Identity
} deriving (Eq, Show, Generic)
instance ToJSON Token
instance FromJSON Token
------------------------------
-- Response Packet
------------------------------
data Response = Response {
code :: ResponseCode,
server :: Identity
} deriving (Eq, Show, Generic)
instance ToJSON Response
instance FromJSON Response
------------------------------
-- Response Codes
------------------------------
data ResponseCode =
FileUploadComplete |
FileUploadError |
HandshakeSuccessful |
HandshakeError |
IdentityFound |
IdentityNotFound |
IdentityReceived
deriving(Eq, Show, Generic)
instance ToJSON ResponseCode
instance FromJSON ResponseCode
| Coggroach/Gluon | .stack-work/intero/intero8374TU0.hs | bsd-3-clause | 2,366 | 0 | 8 | 420 | 462 | 267 | 195 | 67 | 0 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# OPTIONS_GHC -fno-warn-deprecations #-}
module Network.Wai.Handler.Warp.Request (
recvRequest
, headerLines
, pauseTimeoutKey
, getFileInfoKey
, getClientCertificateKey
, NoKeepAliveRequest (..)
) where
import qualified Control.Concurrent as Conc (yield)
import UnliftIO (throwIO, Exception)
import Data.Array ((!))
import qualified Data.ByteString as S
import qualified Data.ByteString.Unsafe as SU
import qualified Data.CaseInsensitive as CI
import qualified Data.IORef as I
import Data.Typeable (Typeable)
import qualified Data.Vault.Lazy as Vault
import Data.X509
import qualified Network.HTTP.Types as H
import Network.Socket (SockAddr)
import Network.Wai
import Network.Wai.Handler.Warp.Types
import Network.Wai.Internal
import Prelude hiding (lines)
import System.IO.Unsafe (unsafePerformIO)
import qualified System.TimeManager as Timeout
import Network.Wai.Handler.Warp.Conduit
import Network.Wai.Handler.Warp.FileInfoCache
import Network.Wai.Handler.Warp.Header
import Network.Wai.Handler.Warp.Imports hiding (readInt, lines)
import Network.Wai.Handler.Warp.ReadInt
import Network.Wai.Handler.Warp.RequestHeader
import Network.Wai.Handler.Warp.Settings (Settings, settingsNoParsePath, settingsMaxTotalHeaderLength)
----------------------------------------------------------------
-- | Receiving a HTTP request from 'Connection' and parsing its header
-- to create 'Request'.
recvRequest :: Bool -- ^ first request on this connection?
-> Settings
-> Connection
-> InternalInfo
-> Timeout.Handle
-> SockAddr -- ^ Peer's address.
-> Source -- ^ Where HTTP request comes from.
-> Transport
-> IO (Request
,Maybe (I.IORef Int)
,IndexedHeader
,IO ByteString) -- ^
-- 'Request' passed to 'Application',
-- how many bytes remain to be consumed, if known
-- 'IndexedHeader' of HTTP request for internal use,
-- Body producing action used for flushing the request body
recvRequest firstRequest settings conn ii th addr src transport = do
hdrlines <- headerLines (settingsMaxTotalHeaderLength settings) firstRequest src
(method, unparsedPath, path, query, httpversion, hdr) <- parseHeaderLines hdrlines
let idxhdr = indexRequestHeader hdr
expect = idxhdr ! fromEnum ReqExpect
cl = idxhdr ! fromEnum ReqContentLength
te = idxhdr ! fromEnum ReqTransferEncoding
handle100Continue = handleExpect conn httpversion expect
rawPath = if settingsNoParsePath settings then unparsedPath else path
vaultValue = Vault.insert pauseTimeoutKey (Timeout.pause th)
$ Vault.insert getFileInfoKey (getFileInfo ii)
$ Vault.insert getClientCertificateKey (getTransportClientCertificate transport)
Vault.empty
(rbody, remainingRef, bodyLength) <- bodyAndSource src cl te
-- body producing function which will produce '100-continue', if needed
rbody' <- timeoutBody remainingRef th rbody handle100Continue
-- body producing function which will never produce 100-continue
rbodyFlush <- timeoutBody remainingRef th rbody (return ())
let req = Request {
requestMethod = method
, httpVersion = httpversion
, pathInfo = H.decodePathSegments path
, rawPathInfo = rawPath
, rawQueryString = query
, queryString = H.parseQuery query
, requestHeaders = hdr
, isSecure = isTransportSecure transport
, remoteHost = addr
, requestBody = rbody'
, vault = vaultValue
, requestBodyLength = bodyLength
, requestHeaderHost = idxhdr ! fromEnum ReqHost
, requestHeaderRange = idxhdr ! fromEnum ReqRange
, requestHeaderReferer = idxhdr ! fromEnum ReqReferer
, requestHeaderUserAgent = idxhdr ! fromEnum ReqUserAgent
}
return (req, remainingRef, idxhdr, rbodyFlush)
----------------------------------------------------------------
headerLines :: Int -> Bool -> Source -> IO [ByteString]
headerLines maxTotalHeaderLength firstRequest src = do
bs <- readSource src
if S.null bs
-- When we're working on a keep-alive connection and trying to
-- get the second or later request, we don't want to treat the
-- lack of data as a real exception. See the http1 function in
-- the Run module for more details.
then if firstRequest then throwIO ConnectionClosedByPeer else throwIO NoKeepAliveRequest
else push maxTotalHeaderLength src (THStatus 0 0 id id) bs
data NoKeepAliveRequest = NoKeepAliveRequest
deriving (Show, Typeable)
instance Exception NoKeepAliveRequest
----------------------------------------------------------------
handleExpect :: Connection
-> H.HttpVersion
-> Maybe HeaderValue
-> IO ()
handleExpect conn ver (Just "100-continue") = do
connSendAll conn continue
Conc.yield
where
continue
| ver == H.http11 = "HTTP/1.1 100 Continue\r\n\r\n"
| otherwise = "HTTP/1.0 100 Continue\r\n\r\n"
handleExpect _ _ _ = return ()
----------------------------------------------------------------
bodyAndSource :: Source
-> Maybe HeaderValue -- ^ content length
-> Maybe HeaderValue -- ^ transfer-encoding
-> IO (IO ByteString
,Maybe (I.IORef Int)
,RequestBodyLength
)
bodyAndSource src cl te
| chunked = do
csrc <- mkCSource src
return (readCSource csrc, Nothing, ChunkedBody)
| otherwise = do
isrc@(ISource _ remaining) <- mkISource src len
return (readISource isrc, Just remaining, bodyLen)
where
len = toLength cl
bodyLen = KnownLength $ fromIntegral len
chunked = isChunked te
toLength :: Maybe HeaderValue -> Int
toLength Nothing = 0
toLength (Just bs) = readInt bs
isChunked :: Maybe HeaderValue -> Bool
isChunked (Just bs) = CI.foldCase bs == "chunked"
isChunked _ = False
----------------------------------------------------------------
timeoutBody :: Maybe (I.IORef Int) -- ^ remaining
-> Timeout.Handle
-> IO ByteString
-> IO ()
-> IO (IO ByteString)
timeoutBody remainingRef timeoutHandle rbody handle100Continue = do
isFirstRef <- I.newIORef True
let checkEmpty =
case remainingRef of
Nothing -> return . S.null
Just ref -> \bs -> if S.null bs
then return True
else do
x <- I.readIORef ref
return $! x <= 0
return $ do
isFirst <- I.readIORef isFirstRef
when isFirst $ do
-- Only check if we need to produce the 100 Continue status
-- when asking for the first chunk of the body
handle100Continue
-- Timeout handling was paused after receiving the full request
-- headers. Now we need to resume it to avoid a slowloris
-- attack during request body sending.
Timeout.resume timeoutHandle
I.writeIORef isFirstRef False
bs <- rbody
-- As soon as we finish receiving the request body, whether
-- because the application is not interested in more bytes, or
-- because there is no more data available, pause the timeout
-- handler again.
isEmpty <- checkEmpty bs
when isEmpty (Timeout.pause timeoutHandle)
return bs
----------------------------------------------------------------
type BSEndo = ByteString -> ByteString
type BSEndoList = [ByteString] -> [ByteString]
data THStatus = THStatus
!Int -- running total byte count (excluding current header chunk)
!Int -- current header chunk byte count
BSEndoList -- previously parsed lines
BSEndo -- bytestrings to be prepended
----------------------------------------------------------------
{- FIXME
close :: Sink ByteString IO a
close = throwIO IncompleteHeaders
-}
push :: Int -> Source -> THStatus -> ByteString -> IO [ByteString]
push maxTotalHeaderLength src (THStatus totalLen chunkLen lines prepend) bs'
-- Too many bytes
| currentTotal > maxTotalHeaderLength = throwIO OverLargeHeader
| otherwise = push' mNL
where
currentTotal = totalLen + chunkLen
-- bs: current header chunk, plus maybe (parts of) next header
bs = prepend bs'
bsLen = S.length bs
-- Maybe newline
-- Returns: Maybe
-- ( length of this chunk up to newline
-- , position of newline in relation to entire current header
-- , is this part of a multiline header
-- )
mNL = do
-- 10 is the code point for newline (\n)
chunkNL <- S.elemIndex 10 bs'
let headerNL = chunkNL + S.length (prepend "")
chunkNLlen = chunkNL + 1
-- check if there are two more bytes in the bs
-- if so, see if the second of those is a horizontal space
if bsLen > headerNL + 1 then
let c = S.index bs (headerNL + 1)
b = case headerNL of
0 -> True
1 -> S.index bs 0 == 13
_ -> False
isMultiline = not b && (c == 32 || c == 9)
in Just (chunkNLlen, headerNL, isMultiline)
else
Just (chunkNLlen, headerNL, False)
{-# INLINE push' #-}
push' :: Maybe (Int, Int, Bool) -> IO [ByteString]
-- No newline find in this chunk. Add it to the prepend,
-- update the length, and continue processing.
push' Nothing = do
bst <- readSource' src
when (S.null bst) $ throwIO IncompleteHeaders
push maxTotalHeaderLength src status bst
where
prepend' = S.append bs
thisChunkLen = S.length bs'
newChunkLen = chunkLen + thisChunkLen
status = THStatus totalLen newChunkLen lines prepend'
-- Found a newline, but next line continues as a multiline header
push' (Just (chunkNLlen, end, True)) =
push maxTotalHeaderLength src status rest
where
rest = S.drop (end + 1) bs
prepend' = S.append (SU.unsafeTake (checkCR bs end) bs)
-- If we'd just update the entire current chunk up to newline
-- we wouldn't count all the dropped newlines in between.
-- So update 'chunkLen' with current chunk up to newline
-- and use 'chunkLen' later on to add to 'totalLen'.
newChunkLen = chunkLen + chunkNLlen
status = THStatus totalLen newChunkLen lines prepend'
-- Found a newline at position end.
push' (Just (chunkNLlen, end, False))
-- leftover
| S.null line = do
when (start < bsLen) $ leftoverSource src (SU.unsafeDrop start bs)
return (lines [])
-- more headers
| otherwise = let lines' = lines . (line:)
newTotalLength = totalLen + chunkLen + chunkNLlen
status = THStatus newTotalLength 0 lines' id
in if start < bsLen then
-- more bytes in this chunk, push again
let bs'' = SU.unsafeDrop start bs
in push maxTotalHeaderLength src status bs''
else do
-- no more bytes in this chunk, ask for more
bst <- readSource' src
when (S.null bs) $ throwIO IncompleteHeaders
push maxTotalHeaderLength src status bst
where
start = end + 1 -- start of next chunk
line = SU.unsafeTake (checkCR bs end) bs
{-# INLINE checkCR #-}
checkCR :: ByteString -> Int -> Int
checkCR bs pos = if pos > 0 && 13 == S.index bs p then p else pos -- 13 is CR (\r)
where
!p = pos - 1
pauseTimeoutKey :: Vault.Key (IO ())
pauseTimeoutKey = unsafePerformIO Vault.newKey
{-# NOINLINE pauseTimeoutKey #-}
getFileInfoKey :: Vault.Key (FilePath -> IO FileInfo)
getFileInfoKey = unsafePerformIO Vault.newKey
{-# NOINLINE getFileInfoKey #-}
getClientCertificateKey :: Vault.Key (Maybe CertificateChain)
getClientCertificateKey = unsafePerformIO Vault.newKey
{-# NOINLINE getClientCertificateKey #-}
| kazu-yamamoto/wai | warp/Network/Wai/Handler/Warp/Request.hs | mit | 12,688 | 0 | 19 | 3,703 | 2,527 | 1,344 | 1,183 | 226 | 7 |
{-# LANGUAGE JavaScriptFFI, DeriveDataTypeable #-}
module InnerEar.WebSocket where
import Reflex
import qualified Reflex.Dom as R
import Text.JSON
import Text.JSON.Generic
import Data.Time.Clock
import Data.Time.Calendar (Day(ModifiedJulianDay))
import GHC.IORef
import qualified GHCJS.Prim as Prim
import qualified GHCJS.Types as T
import qualified GHCJS.Foreign as F
import qualified GHCJS.Marshal.Pure as P
import JavaScript.Object.Internal as O
import GHCJS.Foreign.Internal
import GHCJS.Marshal.Pure
import Control.Monad.IO.Class (liftIO)
import Data.Text
import InnerEar.Types.Request
import InnerEar.Types.Response
data WebSocket = WebSocket (Maybe T.JSVal)
webSocket :: IO WebSocket
webSocket = webSocket_ >>= return . WebSocket . Just
send :: WebSocket -> Request -> IO ()
send (WebSocket Nothing) _ = return ()
-- send (WebSocket (Just ws)) x = send_ ws $ Prim.toJSString $ encode $ toJSON x -- was just encode
send (WebSocket (Just ws)) x = send_ ws $ Prim.toJSString $ encodeJSON x
--send (WebSocket (Just ws)) x = do
-- let a = toJSON x :: JSValue
-- let b = encode a :: String
-- let c = pToJSVal b :: T.JSVal
-- send_ ws c
reflexWebSocket :: R.MonadWidget t m => Event t Request -> m (Event t [Response],Dynamic t String)
reflexWebSocket toSend = do
postBuild <- R.getPostBuild
newWs <- R.performEvent $ fmap (liftIO . (const webSocket)) postBuild
ws <- holdDyn (WebSocket Nothing) newWs
let wsAndToSend = attachDyn ws toSend
R.performEvent_ $ fmap (liftIO . (\(y,z) -> send y z)) wsAndToSend
let aLongTimeAgo = UTCTime (ModifiedJulianDay 0) (secondsToDiffTime 0)
ticks <- R.tickLossy (0.05::NominalDiffTime) aLongTimeAgo
let wsTick = tagDyn ws ticks
responses <- R.performEvent $ fmap (liftIO . getResponses) wsTick
let responses' = fmapMaybe id $ fmap (either (const Nothing) (Just)) responses
status <- R.performEvent $ fmap (liftIO . getStatus) wsTick
status' <- holdDyn "" status
return (responses',status')
getResponses :: WebSocket -> IO (Either String [Response])
getResponses (WebSocket (Just ws)) = do
rs <- getResponses_ ws :: IO T.JSVal
let a = Prim.fromJSString rs :: String
let c = decodeResponses a
-- let b = JSString (toJSString a) :: JSValue
-- let c = fromJSON b :: Result [Response]
return $ f c
where f (Ok xs) = Right xs
f (Error x) = Left $ "error trying to parse this in getResponses: " ++ x
getResponses (WebSocket Nothing) = return (Right [])
getStatus :: WebSocket -> IO String
getStatus (WebSocket (Just ws)) = Prim.fromJSString <$> getStatus_ ws
getStatus (WebSocket Nothing) = return ""
getHostName :: IO String
getHostName = Prim.fromJSString <$> getHostName_
getPort :: IO String
getPort = Prim.fromJSString <$> getPort_
-- Javascript FFI below this line:
foreign import javascript unsafe
"$r = new InnerEarWebSocket(4468)"
webSocket_ :: IO T.JSVal
foreign import javascript unsafe
"$1.send($2)"
send_ :: T.JSVal -> T.JSVal -> IO ()
foreign import javascript unsafe
"$1.setUrl($2)"
setUrl_ :: T.JSVal -> T.JSVal -> IO ()
foreign import javascript unsafe
"$r = location.hostname"
getHostName_ :: IO T.JSVal
foreign import javascript unsafe
"$r = location.port"
getPort_ :: IO T.JSVal
foreign import javascript unsafe
"$r = $1.getResponses()"
getResponses_ :: T.JSVal -> IO T.JSVal
foreign import javascript unsafe
"$r = $1.status"
getStatus_ :: T.JSVal -> IO T.JSVal
| d0kt0r0/InnerEar | src/InnerEar/WebSocket.hs | gpl-3.0 | 3,520 | 15 | 16 | 700 | 1,040 | 540 | 500 | 71 | 2 |
{-
(c) The GRASP/AQUA Project, Glasgow University, 1993-1998
\section[WwLib]{A library for the ``worker\/wrapper'' back-end to the strictness analyser}
-}
{-# LANGUAGE CPP #-}
module WwLib ( mkWwBodies, mkWWstr, mkWorkerArgs
, deepSplitProductType_maybe, findTypeShape
) where
#include "HsVersions.h"
import CoreSyn
import CoreUtils ( exprType, mkCast )
import Id
import IdInfo ( vanillaIdInfo )
import DataCon
import Demand
import MkCore ( mkRuntimeErrorApp, aBSENT_ERROR_ID, mkCoreUbxTup )
import MkId ( voidArgId, voidPrimId )
import TysPrim ( voidPrimTy )
import TysWiredIn ( tupleDataCon )
import Type
import Coercion
import FamInstEnv
import BasicTypes ( Boxity(..), OneShotInfo(..), worstOneShot )
import Literal ( absentLiteralOf )
import TyCon
import UniqSupply
import Unique
import Maybes
import Util
import Outputable
import DynFlags
import FastString
import ListSetOps
{-
************************************************************************
* *
\subsection[mkWrapperAndWorker]{@mkWrapperAndWorker@}
* *
************************************************************************
Here's an example. The original function is:
\begin{verbatim}
g :: forall a . Int -> [a] -> a
g = \/\ a -> \ x ys ->
case x of
0 -> head ys
_ -> head (tail ys)
\end{verbatim}
From this, we want to produce:
\begin{verbatim}
-- wrapper (an unfolding)
g :: forall a . Int -> [a] -> a
g = \/\ a -> \ x ys ->
case x of
I# x# -> $wg a x# ys
-- call the worker; don't forget the type args!
-- worker
$wg :: forall a . Int# -> [a] -> a
$wg = \/\ a -> \ x# ys ->
let
x = I# x#
in
case x of -- note: body of g moved intact
0 -> head ys
_ -> head (tail ys)
\end{verbatim}
Something we have to be careful about: Here's an example:
\begin{verbatim}
-- "f" strictness: U(P)U(P)
f (I# a) (I# b) = a +# b
g = f -- "g" strictness same as "f"
\end{verbatim}
\tr{f} will get a worker all nice and friendly-like; that's good.
{\em But we don't want a worker for \tr{g}}, even though it has the
same strictness as \tr{f}. Doing so could break laziness, at best.
Consequently, we insist that the number of strictness-info items is
exactly the same as the number of lambda-bound arguments. (This is
probably slightly paranoid, but OK in practice.) If it isn't the
same, we ``revise'' the strictness info, so that we won't propagate
the unusable strictness-info into the interfaces.
************************************************************************
* *
\subsection{The worker wrapper core}
* *
************************************************************************
@mkWwBodies@ is called when doing the worker\/wrapper split inside a module.
-}
mkWwBodies :: DynFlags
-> FamInstEnvs
-> Type -- Type of original function
-> [Demand] -- Strictness of original function
-> DmdResult -- Info about function result
-> [OneShotInfo] -- One-shot-ness of the function, value args only
-> UniqSM (Maybe ([Demand], -- Demands for worker (value) args
Id -> CoreExpr, -- Wrapper body, lacking only the worker Id
CoreExpr -> CoreExpr)) -- Worker body, lacking the original function rhs
-- wrap_fn_args E = \x y -> E
-- work_fn_args E = E x y
-- wrap_fn_str E = case x of { (a,b) ->
-- case a of { (a1,a2) ->
-- E a1 a2 b y }}
-- work_fn_str E = \a2 a2 b y ->
-- let a = (a1,a2) in
-- let x = (a,b) in
-- E
mkWwBodies dflags fam_envs fun_ty demands res_info one_shots
= do { let arg_info = demands `zip` (one_shots ++ repeat NoOneShotInfo)
all_one_shots = foldr (worstOneShot . snd) OneShotLam arg_info
; (wrap_args, wrap_fn_args, work_fn_args, res_ty) <- mkWWargs emptyTCvSubst fun_ty arg_info
; (useful1, work_args, wrap_fn_str, work_fn_str) <- mkWWstr dflags fam_envs wrap_args
-- Do CPR w/w. See Note [Always do CPR w/w]
; (useful2, wrap_fn_cpr, work_fn_cpr, cpr_res_ty)
<- mkWWcpr (gopt Opt_CprAnal dflags) fam_envs res_ty res_info
; let (work_lam_args, work_call_args) = mkWorkerArgs dflags work_args all_one_shots cpr_res_ty
worker_args_dmds = [idDemandInfo v | v <- work_call_args, isId v]
wrapper_body = wrap_fn_args . wrap_fn_cpr . wrap_fn_str . applyToVars work_call_args . Var
worker_body = mkLams work_lam_args. work_fn_str . work_fn_cpr . work_fn_args
; if useful1 && not (only_one_void_argument) || useful2
then return (Just (worker_args_dmds, wrapper_body, worker_body))
else return Nothing
}
-- We use an INLINE unconditionally, even if the wrapper turns out to be
-- something trivial like
-- fw = ...
-- f = __inline__ (coerce T fw)
-- The point is to propagate the coerce to f's call sites, so even though
-- f's RHS is now trivial (size 1) we still want the __inline__ to prevent
-- fw from being inlined into f's RHS
where
-- Note [Do not split void functions]
only_one_void_argument
| [d] <- demands
, Just (arg_ty1, _) <- splitFunTy_maybe fun_ty
, isAbsDmd d && isVoidTy arg_ty1
= True
| otherwise
= False
{-
Note [Always do CPR w/w]
~~~~~~~~~~~~~~~~~~~~~~~~
At one time we refrained from doing CPR w/w for thunks, on the grounds that
we might duplicate work. But that is already handled by the demand analyser,
which doesn't give the CPR proprety if w/w might waste work: see
Note [CPR for thunks] in DmdAnal.
And if something *has* been given the CPR property and we don't w/w, it's
a disaster, because then the enclosing function might say it has the CPR
property, but now doesn't and there a cascade of disaster. A good example
is Trac #5920.
************************************************************************
* *
\subsection{Making wrapper args}
* *
************************************************************************
During worker-wrapper stuff we may end up with an unlifted thing
which we want to let-bind without losing laziness. So we
add a void argument. E.g.
f = /\a -> \x y z -> E::Int# -- E does not mention x,y,z
==>
fw = /\ a -> \void -> E
f = /\ a -> \x y z -> fw realworld
We use the state-token type which generates no code.
-}
mkWorkerArgs :: DynFlags -> [Var]
-> OneShotInfo -- Whether all arguments are one-shot
-> Type -- Type of body
-> ([Var], -- Lambda bound args
[Var]) -- Args at call site
mkWorkerArgs dflags args all_one_shot res_ty
| any isId args || not needsAValueLambda
= (args, args)
| otherwise
= (args ++ [newArg], args ++ [voidPrimId])
where
needsAValueLambda =
isUnliftedType res_ty
|| not (gopt Opt_FunToThunk dflags)
-- see Note [Protecting the last value argument]
-- see Note [All One-Shot Arguments of a Worker]
newArg = setIdOneShotInfo voidArgId all_one_shot
{-
Note [Protecting the last value argument]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If the user writes (\_ -> E), they might be intentionally disallowing
the sharing of E. Since absence analysis and worker-wrapper are keen
to remove such unused arguments, we add in a void argument to prevent
the function from becoming a thunk.
The user can avoid adding the void argument with the -ffun-to-thunk
flag. However, this can create sharing, which may be bad in two ways. 1) It can
create a space leak. 2) It can prevent inlining *under a lambda*. If w/w
removes the last argument from a function f, then f now looks like a thunk, and
so f can't be inlined *under a lambda*.
Note [All One-Shot Arguments of a Worker]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sometimes, derived join-points are just lambda-lifted thunks, whose
only argument is of the unit type and is never used. This might
interfere with the absence analysis, basing on which results these
never-used arguments are eliminated in the worker. The additional
argument `all_one_shot` of `mkWorkerArgs` is to prevent this.
Example. Suppose we have
foo = \p(one-shot) q(one-shot). y + 3
Then we drop the unused args to give
foo = \pq. $wfoo void#
$wfoo = \void(one-shot). y + 3
But suppse foo didn't have all one-shot args:
foo = \p(not-one-shot) q(one-shot). expensive y + 3
Then we drop the unused args to give
foo = \pq. $wfoo void#
$wfoo = \void(not-one-shot). y + 3
If we made the void-arg one-shot we might inline an expensive
computation for y, which would be terrible!
************************************************************************
* *
\subsection{Coercion stuff}
* *
************************************************************************
We really want to "look through" coerces.
Reason: I've seen this situation:
let f = coerce T (\s -> E)
in \x -> case x of
p -> coerce T' f
q -> \s -> E2
r -> coerce T' f
If only we w/w'd f, we'd get
let f = coerce T (\s -> fw s)
fw = \s -> E
in ...
Now we'll inline f to get
let fw = \s -> E
in \x -> case x of
p -> fw
q -> \s -> E2
r -> fw
Now we'll see that fw has arity 1, and will arity expand
the \x to get what we want.
-}
-- mkWWargs just does eta expansion
-- is driven off the function type and arity.
-- It chomps bites off foralls, arrows, newtypes
-- and keeps repeating that until it's satisfied the supplied arity
mkWWargs :: TCvSubst -- Freshening substitution to apply to the type
-- See Note [Freshen type variables]
-> Type -- The type of the function
-> [(Demand,OneShotInfo)] -- Demands and one-shot info for value arguments
-> UniqSM ([Var], -- Wrapper args
CoreExpr -> CoreExpr, -- Wrapper fn
CoreExpr -> CoreExpr, -- Worker fn
Type) -- Type of wrapper body
mkWWargs subst fun_ty arg_info
| null arg_info
= return ([], id, id, substTy subst fun_ty)
| ((dmd,one_shot):arg_info') <- arg_info
, Just (arg_ty, fun_ty') <- splitFunTy_maybe fun_ty
= do { uniq <- getUniqueM
; let arg_ty' = substTy subst arg_ty
id = mk_wrap_arg uniq arg_ty' dmd one_shot
; (wrap_args, wrap_fn_args, work_fn_args, res_ty)
<- mkWWargs subst fun_ty' arg_info'
; return (id : wrap_args,
Lam id . wrap_fn_args,
work_fn_args . (`App` varToCoreExpr id),
res_ty) }
| Just (tv, fun_ty') <- splitForAllTy_maybe fun_ty
= do { let (subst', tv') = substTyVarBndr subst tv
-- This substTyVarBndr clones the type variable when necy
-- See Note [Freshen type variables]
; (wrap_args, wrap_fn_args, work_fn_args, res_ty)
<- mkWWargs subst' fun_ty' arg_info
; return (tv' : wrap_args,
Lam tv' . wrap_fn_args,
work_fn_args . (`mkTyApps` [mkTyVarTy tv']),
res_ty) }
| Just (co, rep_ty) <- topNormaliseNewType_maybe fun_ty
-- The newtype case is for when the function has
-- a newtype after the arrow (rare)
--
-- It's also important when we have a function returning (say) a pair
-- wrapped in a newtype, at least if CPR analysis can look
-- through such newtypes, which it probably can since they are
-- simply coerces.
= do { (wrap_args, wrap_fn_args, work_fn_args, res_ty)
<- mkWWargs subst rep_ty arg_info
; return (wrap_args,
\e -> Cast (wrap_fn_args e) (mkSymCo co),
\e -> work_fn_args (Cast e co),
res_ty) }
| otherwise
= WARN( True, ppr fun_ty ) -- Should not happen: if there is a demand
return ([], id, id, substTy subst fun_ty) -- then there should be a function arrow
applyToVars :: [Var] -> CoreExpr -> CoreExpr
applyToVars vars fn = mkVarApps fn vars
mk_wrap_arg :: Unique -> Type -> Demand -> OneShotInfo -> Id
mk_wrap_arg uniq ty dmd one_shot
= mkSysLocalOrCoVar (fsLit "w") uniq ty
`setIdDemandInfo` dmd
`setIdOneShotInfo` one_shot
{-
Note [Freshen type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Wen we do a worker/wrapper split, we must not use shadowed names,
else we'll get
f = /\ a /\a. fw a a
which is obviously wrong. Type variables can can in principle shadow,
within a type (e.g. forall a. a -> forall a. a->a). But type
variables *are* mentioned in <blah>, so we must substitute.
That's why we carry the TCvSubst through mkWWargs
************************************************************************
* *
\subsection{Strictness stuff}
* *
************************************************************************
-}
mkWWstr :: DynFlags
-> FamInstEnvs
-> [Var] -- Wrapper args; have their demand info on them
-- *Includes type variables*
-> UniqSM (Bool, -- Is this useful
[Var], -- Worker args
CoreExpr -> CoreExpr, -- Wrapper body, lacking the worker call
-- and without its lambdas
-- This fn adds the unboxing
CoreExpr -> CoreExpr) -- Worker body, lacking the original body of the function,
-- and lacking its lambdas.
-- This fn does the reboxing
mkWWstr _ _ []
= return (False, [], nop_fn, nop_fn)
mkWWstr dflags fam_envs (arg : args) = do
(useful1, args1, wrap_fn1, work_fn1) <- mkWWstr_one dflags fam_envs arg
(useful2, args2, wrap_fn2, work_fn2) <- mkWWstr dflags fam_envs args
return (useful1 || useful2, args1 ++ args2, wrap_fn1 . wrap_fn2, work_fn1 . work_fn2)
{-
Note [Unpacking arguments with product and polymorphic demands]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The argument is unpacked in a case if it has a product type and has a
strict *and* used demand put on it. I.e., arguments, with demands such
as the following ones:
<S,U(U, L)>
<S(L,S),U>
will be unpacked, but
<S,U> or <B,U>
will not, because the pieces aren't used. This is quite important otherwise
we end up unpacking massive tuples passed to the bottoming function. Example:
f :: ((Int,Int) -> String) -> (Int,Int) -> a
f g pr = error (g pr)
main = print (f fst (1, error "no"))
Does 'main' print "error 1" or "error no"? We don't really want 'f'
to unbox its second argument. This actually happened in GHC's onwn
source code, in Packages.applyPackageFlag, which ended up un-boxing
the enormous DynFlags tuple, and being strict in the
as-yet-un-filled-in pkgState files.
-}
----------------------
-- mkWWstr_one wrap_arg = (useful, work_args, wrap_fn, work_fn)
-- * wrap_fn assumes wrap_arg is in scope,
-- brings into scope work_args (via cases)
-- * work_fn assumes work_args are in scope, a
-- brings into scope wrap_arg (via lets)
mkWWstr_one :: DynFlags -> FamInstEnvs -> Var
-> UniqSM (Bool, [Var], CoreExpr -> CoreExpr, CoreExpr -> CoreExpr)
mkWWstr_one dflags fam_envs arg
| isTyVar arg
= return (False, [arg], nop_fn, nop_fn)
-- See Note [Worker-wrapper for bottoming functions]
| isAbsDmd dmd
, Just work_fn <- mk_absent_let dflags arg
-- Absent case. We can't always handle absence for arbitrary
-- unlifted types, so we need to choose just the cases we can
--- (that's what mk_absent_let does)
= return (True, [], nop_fn, work_fn)
-- See Note [Worthy functions for Worker-Wrapper split]
| isSeqDmd dmd -- `seq` demand; evaluate in wrapper in the hope
-- of dropping seqs in the worker
= let arg_w_unf = arg `setIdUnfolding` evaldUnfolding
-- Tell the worker arg that it's sure to be evaluated
-- so that internal seqs can be dropped
in return (True, [arg_w_unf], mk_seq_case arg, nop_fn)
-- Pass the arg, anyway, even if it is in theory discarded
-- Consider
-- f x y = x `seq` y
-- x gets a (Eval (Poly Abs)) demand, but if we fail to pass it to the worker
-- we ABSOLUTELY MUST record that x is evaluated in the wrapper.
-- Something like:
-- f x y = x `seq` fw y
-- fw y = let x{Evald} = error "oops" in (x `seq` y)
-- If we don't pin on the "Evald" flag, the seq doesn't disappear, and
-- we end up evaluating the absent thunk.
-- But the Evald flag is pretty weird, and I worry that it might disappear
-- during simplification, so for now I've just nuked this whole case
| isStrictDmd dmd
, Just cs <- splitProdDmd_maybe dmd
-- See Note [Unpacking arguments with product and polymorphic demands]
, Just (data_con, inst_tys, inst_con_arg_tys, co)
<- deepSplitProductType_maybe fam_envs (idType arg)
, cs `equalLength` inst_con_arg_tys
-- See Note [mkWWstr and unsafeCoerce]
= do { (uniq1:uniqs) <- getUniquesM
; let unpk_args = zipWith mk_ww_local uniqs inst_con_arg_tys
unpk_args_w_ds = zipWithEqual "mkWWstr" set_worker_arg_info unpk_args cs
unbox_fn = mkUnpackCase (Var arg) co uniq1
data_con unpk_args
rebox_fn = Let (NonRec arg con_app)
con_app = mkConApp2 data_con inst_tys unpk_args `mkCast` mkSymCo co
; (_, worker_args, wrap_fn, work_fn) <- mkWWstr dflags fam_envs unpk_args_w_ds
; return (True, worker_args, unbox_fn . wrap_fn, work_fn . rebox_fn) }
-- Don't pass the arg, rebox instead
| otherwise -- Other cases
= return (False, [arg], nop_fn, nop_fn)
where
dmd = idDemandInfo arg
one_shot = idOneShotInfo arg
-- If the wrapper argument is a one-shot lambda, then
-- so should (all) the corresponding worker arguments be
-- This bites when we do w/w on a case join point
set_worker_arg_info worker_arg demand
= worker_arg `setIdDemandInfo` demand
`setIdOneShotInfo` one_shot
----------------------
nop_fn :: CoreExpr -> CoreExpr
nop_fn body = body
{-
Note [mkWWstr and unsafeCoerce]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
By using unsafeCoerce, it is possible to make the number of demands fail to
match the number of constructor arguments; this happened in Trac #8037.
If so, the worker/wrapper split doesn't work right and we get a Core Lint
bug. The fix here is simply to decline to do w/w if that happens.
************************************************************************
* *
Type scrutiny that is specfic to demand analysis
* *
************************************************************************
Note [Do not unpack class dictionaries]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we have
f :: Ord a => [a] -> Int -> a
{-# INLINABLE f #-}
and we worker/wrapper f, we'll get a worker with an INLINALBE pragma
(see Note [Worker-wrapper for INLINABLE functions] in WorkWrap), which
can still be specialised by the type-class specialiser, something like
fw :: Ord a => [a] -> Int# -> a
BUT if f is strict in the Ord dictionary, we might unpack it, to get
fw :: (a->a->Bool) -> [a] -> Int# -> a
and the type-class specialiser can't specialise that. An example is
Trac #6056.
Moreover, dictinoaries can have a lot of fields, so unpacking them can
increase closure sizes.
Conclusion: don't unpack dictionaries.
-}
deepSplitProductType_maybe :: FamInstEnvs -> Type -> Maybe (DataCon, [Type], [Type], Coercion)
-- If deepSplitProductType_maybe ty = Just (dc, tys, arg_tys, co)
-- then dc @ tys (args::arg_tys) :: rep_ty
-- co :: ty ~ rep_ty
deepSplitProductType_maybe fam_envs ty
| let (co, ty1) = topNormaliseType_maybe fam_envs ty
`orElse` (mkRepReflCo ty, ty)
, Just (tc, tc_args) <- splitTyConApp_maybe ty1
, Just con <- isDataProductTyCon_maybe tc
, not (isClassTyCon tc) -- See Note [Do not unpack class dictionaries]
= Just (con, tc_args, dataConInstArgTys con tc_args, co)
deepSplitProductType_maybe _ _ = Nothing
deepSplitCprType_maybe :: FamInstEnvs -> ConTag -> Type -> Maybe (DataCon, [Type], [Type], Coercion)
-- If deepSplitCprType_maybe n ty = Just (dc, tys, arg_tys, co)
-- then dc @ tys (args::arg_tys) :: rep_ty
-- co :: ty ~ rep_ty
deepSplitCprType_maybe fam_envs con_tag ty
| let (co, ty1) = topNormaliseType_maybe fam_envs ty
`orElse` (mkRepReflCo ty, ty)
, Just (tc, tc_args) <- splitTyConApp_maybe ty1
, isDataTyCon tc
, let cons = tyConDataCons tc
, cons `lengthAtLeast` con_tag -- This might not be true if we import the
-- type constructor via a .hs-bool file (#8743)
, let con = cons `getNth` (con_tag - fIRST_TAG)
= Just (con, tc_args, dataConInstArgTys con tc_args, co)
deepSplitCprType_maybe _ _ _ = Nothing
findTypeShape :: FamInstEnvs -> Type -> TypeShape
-- Uncover the arrow and product shape of a type
-- The data type TypeShape is defined in Demand
-- See Note [Trimming a demand to a type] in Demand
findTypeShape fam_envs ty
| Just (tc, tc_args) <- splitTyConApp_maybe ty
, Just con <- isDataProductTyCon_maybe tc
= TsProd (map (findTypeShape fam_envs) $ dataConInstArgTys con tc_args)
| Just (_, res) <- splitFunTy_maybe ty
= TsFun (findTypeShape fam_envs res)
| Just (_, ty') <- splitForAllTy_maybe ty
= findTypeShape fam_envs ty'
| Just (_, ty') <- topNormaliseType_maybe fam_envs ty
= findTypeShape fam_envs ty'
| otherwise
= TsUnk
{-
************************************************************************
* *
\subsection{CPR stuff}
* *
************************************************************************
@mkWWcpr@ takes the worker/wrapper pair produced from the strictness
info and adds in the CPR transformation. The worker returns an
unboxed tuple containing non-CPR components. The wrapper takes this
tuple and re-produces the correct structured output.
The non-CPR results appear ordered in the unboxed tuple as if by a
left-to-right traversal of the result structure.
-}
mkWWcpr :: Bool
-> FamInstEnvs
-> Type -- function body type
-> DmdResult -- CPR analysis results
-> UniqSM (Bool, -- Is w/w'ing useful?
CoreExpr -> CoreExpr, -- New wrapper
CoreExpr -> CoreExpr, -- New worker
Type) -- Type of worker's body
mkWWcpr opt_CprAnal fam_envs body_ty res
-- CPR explicitly turned off (or in -O0)
| not opt_CprAnal = return (False, id, id, body_ty)
-- CPR is turned on by default for -O and O2
| otherwise
= case returnsCPR_maybe res of
Nothing -> return (False, id, id, body_ty) -- No CPR info
Just con_tag | Just stuff <- deepSplitCprType_maybe fam_envs con_tag body_ty
-> mkWWcpr_help stuff
| otherwise
-- See Note [non-algebraic or open body type warning]
-> WARN( True, text "mkWWcpr: non-algebraic or open body type" <+> ppr body_ty )
return (False, id, id, body_ty)
mkWWcpr_help :: (DataCon, [Type], [Type], Coercion)
-> UniqSM (Bool, CoreExpr -> CoreExpr, CoreExpr -> CoreExpr, Type)
mkWWcpr_help (data_con, inst_tys, arg_tys, co)
| [arg_ty1] <- arg_tys
, isUnliftedType arg_ty1
-- Special case when there is a single result of unlifted type
--
-- Wrapper: case (..call worker..) of x -> C x
-- Worker: case ( ..body.. ) of C x -> x
= do { (work_uniq : arg_uniq : _) <- getUniquesM
; let arg = mk_ww_local arg_uniq arg_ty1
con_app = mkConApp2 data_con inst_tys [arg] `mkCast` mkSymCo co
; return ( True
, \ wkr_call -> Case wkr_call arg (exprType con_app) [(DEFAULT, [], con_app)]
, \ body -> mkUnpackCase body co work_uniq data_con [arg] (varToCoreExpr arg)
-- varToCoreExpr important here: arg can be a coercion
-- Lacking this caused Trac #10658
, arg_ty1 ) }
| otherwise -- The general case
-- Wrapper: case (..call worker..) of (# a, b #) -> C a b
-- Worker: case ( ...body... ) of C a b -> (# a, b #)
= do { (work_uniq : uniqs) <- getUniquesM
; let (wrap_wild : args) = zipWith mk_ww_local uniqs (ubx_tup_ty : arg_tys)
ubx_tup_ty = exprType ubx_tup_app
ubx_tup_app = mkCoreUbxTup arg_tys (map varToCoreExpr args)
con_app = mkConApp2 data_con inst_tys args `mkCast` mkSymCo co
; return (True
, \ wkr_call -> Case wkr_call wrap_wild (exprType con_app) [(DataAlt (tupleDataCon Unboxed (length arg_tys)), args, con_app)]
, \ body -> mkUnpackCase body co work_uniq data_con args ubx_tup_app
, ubx_tup_ty ) }
mkUnpackCase :: CoreExpr -> Coercion -> Unique -> DataCon -> [Id] -> CoreExpr -> CoreExpr
-- (mkUnpackCase e co uniq Con args body)
-- returns
-- case e |> co of bndr { Con args -> body }
mkUnpackCase (Tick tickish e) co uniq con args body -- See Note [Profiling and unpacking]
= Tick tickish (mkUnpackCase e co uniq con args body)
mkUnpackCase scrut co uniq boxing_con unpk_args body
= Case casted_scrut bndr (exprType body)
[(DataAlt boxing_con, unpk_args, body)]
where
casted_scrut = scrut `mkCast` co
bndr = mk_ww_local uniq (exprType casted_scrut)
{-
Note [non-algebraic or open body type warning]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are a few cases where the W/W transformation is told that something
returns a constructor, but the type at hand doesn't really match this. One
real-world example involves unsafeCoerce:
foo = IO a
foo = unsafeCoerce c_exit
foreign import ccall "c_exit" c_exit :: IO ()
Here CPR will tell you that `foo` returns a () constructor for sure, but trying
to create a worker/wrapper for type `a` obviously fails.
(This was a real example until ee8e792 in libraries/base.)
It does not seem feasible to avoid all such cases already in the analyser (and
after all, the analysis is not really wrong), so we simply do nothing here in
mkWWcpr. But we still want to emit warning with -DDEBUG, to hopefully catch
other cases where something went avoidably wrong.
Note [Profiling and unpacking]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If the original function looked like
f = \ x -> {-# SCC "foo" #-} E
then we want the CPR'd worker to look like
\ x -> {-# SCC "foo" #-} (case E of I# x -> x)
and definitely not
\ x -> case ({-# SCC "foo" #-} E) of I# x -> x)
This transform doesn't move work or allocation
from one cost centre to another.
Later [SDM]: presumably this is because we want the simplifier to
eliminate the case, and the scc would get in the way? I'm ok with
including the case itself in the cost centre, since it is morally
part of the function (post transformation) anyway.
************************************************************************
* *
\subsection{Utilities}
* *
************************************************************************
Note [Absent errors]
~~~~~~~~~~~~~~~~~~~~
We make a new binding for Ids that are marked absent, thus
let x = absentError "x :: Int"
The idea is that this binding will never be used; but if it
buggily is used we'll get a runtime error message.
Coping with absence for *unlifted* types is important; see, for
example, Trac #4306. For these we find a suitable literal,
using Literal.absentLiteralOf. We don't have literals for
every primitive type, so the function is partial.
[I did try the experiment of using an error thunk for unlifted
things too, relying on the simplifier to drop it as dead code,
by making absentError
(a) *not* be a bottoming Id,
(b) be "ok for speculation"
But that relies on the simplifier finding that it really
is dead code, which is fragile, and indeed failed when
profiling is on, which disables various optimisations. So
using a literal will do.]
-}
mk_absent_let :: DynFlags -> Id -> Maybe (CoreExpr -> CoreExpr)
mk_absent_let dflags arg
| not (isUnliftedType arg_ty)
= Just (Let (NonRec arg abs_rhs))
| Just tc <- tyConAppTyCon_maybe arg_ty
, Just lit <- absentLiteralOf tc
= Just (Let (NonRec arg (Lit lit)))
| arg_ty `eqType` voidPrimTy
= Just (Let (NonRec arg (Var voidPrimId)))
| otherwise
= WARN( True, text "No absent value for" <+> ppr arg_ty )
Nothing
where
arg_ty = idType arg
abs_rhs = mkRuntimeErrorApp aBSENT_ERROR_ID arg_ty msg
msg = showSDoc dflags (ppr arg <+> ppr (idType arg))
mk_seq_case :: Id -> CoreExpr -> CoreExpr
mk_seq_case arg body = Case (Var arg) (sanitiseCaseBndr arg) (exprType body) [(DEFAULT, [], body)]
sanitiseCaseBndr :: Id -> Id
-- The argument we are scrutinising has the right type to be
-- a case binder, so it's convenient to re-use it for that purpose.
-- But we *must* throw away all its IdInfo. In particular, the argument
-- will have demand info on it, and that demand info may be incorrect for
-- the case binder. e.g. case ww_arg of ww_arg { I# x -> ... }
-- Quite likely ww_arg isn't used in '...'. The case may get discarded
-- if the case binder says "I'm demanded". This happened in a situation
-- like (x+y) `seq` ....
sanitiseCaseBndr id = id `setIdInfo` vanillaIdInfo
mk_ww_local :: Unique -> Type -> Id
mk_ww_local uniq ty = mkSysLocalOrCoVar (fsLit "ww") uniq ty
| nushio3/ghc | compiler/stranal/WwLib.hs | bsd-3-clause | 31,859 | 0 | 18 | 9,496 | 3,840 | 2,092 | 1,748 | 266 | 2 |
-- |Auxiliary functions to vectorise type abstractions.
module Vectorise.Utils.Poly
( polyAbstract
, polyApply
, polyVApply
, polyArity
)
where
import GhcPrelude
import Vectorise.Vect
import Vectorise.Monad
import Vectorise.Utils.PADict
import CoreSyn
import Type
import FastString
import Control.Monad
-- Vectorisation of type arguments -------------------------------------------------------------
-- |Vectorise under the 'PA' dictionary variables corresponding to a set of type arguments.
--
-- The dictionary variables are new local variables that are entered into the local vectorisation
-- map.
--
-- The purpose of this function is to introduce the additional 'PA' dictionary arguments that are
-- needed when vectorising type abstractions.
--
polyAbstract :: [TyVar] -> ([Var] -> VM a) -> VM a
polyAbstract tvs p
= localV
$ do { mdicts <- mapM mk_dict_var tvs
; zipWithM_ (\tv -> maybe (defLocalTyVar tv)
(defLocalTyVarWithPA tv . Var)) tvs mdicts
; p (mk_args mdicts)
}
where
mk_dict_var tv
= do { r <- paDictArgType tv
; case r of
Just ty -> liftM Just (newLocalVar (fsLit "dPA") ty)
Nothing -> return Nothing
}
mk_args mdicts = [dict | Just dict <- mdicts]
-- |Determine the number of 'PA' dictionary arguments required for a set of type variables (depends
-- on their kinds).
--
polyArity :: [TyVar] -> VM Int
polyArity tvs
= do { tys <- mapM paDictArgType tvs
; return $ length [() | Just _ <- tys]
}
-- |Apply a expression to its type arguments as well as 'PA' dictionaries for these type arguments.
--
polyApply :: CoreExpr -> [Type] -> VM CoreExpr
polyApply expr tys
= do { dicts <- mapM paDictOfType tys
; return $ expr `mkTyApps` tys `mkApps` dicts
}
-- |Apply a vectorised expression to a set of type arguments together with 'PA' dictionaries for
-- these type arguments.
--
polyVApply :: VExpr -> [Type] -> VM VExpr
polyVApply expr tys
= do { dicts <- mapM paDictOfType tys
; return $ mapVect (\e -> e `mkTyApps` tys `mkApps` dicts) expr
}
| ezyang/ghc | compiler/vectorise/Vectorise/Utils/Poly.hs | bsd-3-clause | 2,148 | 0 | 16 | 511 | 477 | 260 | 217 | 38 | 2 |
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
-----------------------------------------------------------------------------
-- |
-- Module : Hadron
-- Copyright : Soostone Inc
-- License : BSD3
--
-- Maintainer : Ozgun Ataman
-- Stability : experimental
--
-- Low level building blocks for working with Hadoop streaming.
--
-- We define all the base types for MapReduce and export map/reduce
-- maker functions that know how to deal with ByteString input and
-- output.
----------------------------------------------------------------------------
module Hadron.Basic
(
-- * Types
Key
, CompositeKey
, Mapper
, Reducer
-- * Hadoop Utilities
, emitCounter
, hsEmitCounter
, emitStatus
, getFileName
-- * MapReduce Construction
, mapReduceMain
, mapReduce
, MROptions (..)
, PartitionStrategy (..)
-- * Low-level Utilities
, mapper
, mapperWith
, combiner
, reducer
, setLineBuffering
-- * Data Serialization Utilities
, module Hadron.Protocol
) where
-------------------------------------------------------------------------------
import Blaze.ByteString.Builder
import Control.Applicative
import Control.Category
import Control.Lens
import Control.Monad
import Control.Monad.Base
import Control.Monad.Primitive
import Control.Monad.Trans
import Control.Monad.Trans.Resource
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as LB
import Data.Conduit
import Data.Conduit.Binary (sinkHandle, sourceHandle)
import Data.Conduit.Blaze
import qualified Data.Conduit.List as C
import Data.List
import Data.Monoid
import Options.Applicative
import Prelude hiding (id, (.))
import System.Environment
import System.IO
-------------------------------------------------------------------------------
import Hadron.Protocol
import Hadron.Run.Hadoop
import Hadron.Types
-------------------------------------------------------------------------------
showBS :: Show a => a -> B.ByteString
showBS = B.pack . show
-- | Emit a counter to be captured, added up and reported by Hadoop.
emitCounter
:: B.ByteString
-- ^ Group name
-> B.ByteString
-- ^ Counter name
-> Integer
-- ^ Increment
-> IO ()
emitCounter grp counter inc = LB.hPutStrLn stderr $ toLazyByteString txt
where
txt = mconcat $ map fromByteString
["reporter:counter:", grp, ",", counter, ",", showBS inc]
-- | Emit counter from this library's group
hsEmitCounter :: B.ByteString -> Integer -> IO ()
hsEmitCounter = emitCounter "Hadron"
-- | Emit a status line.
emitStatus :: B.ByteString -> IO ()
emitStatus msg = LB.hPutStrLn stderr $ toLazyByteString txt
where
txt = fromByteString "reporter:status:" <>
fromByteString msg
-- | Get the current filename from Hadoop ENV. Useful when writing
-- 'Mapper's and you would like to know what file you're currently
-- dealing with.
getFileName :: MonadIO m => m FilePath
getFileName = liftIO $ getEnv "mapreduce_map_input_file"
-------------------------------------------------------------------------------
mapper
:: Mapper B.ByteString CompositeKey B.ByteString
-- ^ A key/value producer - don't worry about putting any newline
-- endings yourself, we do that for you.
-> IO ()
mapper f = mapperWith id f
-- | Construct a mapper program using given serialization Prism.
mapperWith
:: Prism' B.ByteString t
-> Mapper B.ByteString CompositeKey t
-> IO ()
mapperWith p f = runResourceT $ do
setLineBuffering
sourceHandle stdin $=
f $=
encodeMapOutput p $$
sinkHandle stdout
-- -------------------------------------------------------------------------------
-- -- | Drop the key and simply output the value stream.
-- mapOnly
-- :: (InputStream B.ByteString -> OutputStream B.ByteString -> IO ())
-- -> IO ()
-- mapOnly f = do
-- setLineBuffering
-- f S.stdin S.stdout
-------------------------------------------------------------------------------
combiner
:: MROptions
-> Prism' B.ByteString b
-> Reducer CompositeKey b (CompositeKey, b)
-> IO ()
combiner mro mrInPrism f = runResourceT $ do
setLineBuffering
sourceHandle stdin =$=
decodeReducerInput mro mrInPrism =$=
f =$=
encodeMapOutput mrInPrism $$
sinkHandle stdout
-------------------------------------------------------------------------------
setLineBuffering :: MonadIO m => m ()
setLineBuffering = do
liftIO $ hSetBuffering stderr LineBuffering
liftIO $ hSetBuffering stdout LineBuffering
liftIO $ hSetBuffering stdin LineBuffering
-------------------------------------------------------------------------------
-- | Appropriately produce lines of mapper output in a way compliant
-- with Hadoop and 'decodeReducerInput'.
encodeMapOutput
:: (PrimMonad base, MonadBase base m)
=> Prism' B.ByteString b
-> Conduit (CompositeKey, b) m B.ByteString
encodeMapOutput mrInPrism = C.map conv $= builderToByteString
where
conv (k,v) = mconcat
[ mconcat (intersperse tab (map fromByteString k))
, tab
, fromByteString (review mrInPrism v)
, nl ]
tab = fromByteString "\t"
nl = fromByteString "\n"
-------------------------------------------------------------------------------
-- | Chunk 'stdin' into lines and try to decode the value using given 'Prism'.
decodeReducerInput
:: (MonadIO m, MonadThrow m)
=> MROptions
-> Prism' B.ByteString b
-> ConduitM a (CompositeKey, b) m ()
decodeReducerInput mro mrInPrism =
sourceHandle stdin =$=
lineC (numSegs (_mroPart mro)) =$=
C.mapMaybe (_2 (firstOf mrInPrism))
-------------------------------------------------------------------------------
reducerMain
:: MROptions
-> Prism' B.ByteString a
-> Reducer CompositeKey a B.ByteString
-> IO ()
reducerMain mro p f = do
setLineBuffering
runResourceT $ reducer mro p f $$ sinkHandle stdout
-- | Create a reducer program.
reducer
:: MROptions
-> Prism' B.ByteString a
-- ^ Input conversion function
-> Reducer CompositeKey a b
-- ^ A step function for any given key. Will be rerun from scratch
-- for each unique key based on MROptions.
-> Producer (ResourceT IO) b
reducer mro@MROptions{..} mrInPrism f = do
sourceHandle stdin =$=
decodeReducerInput mro mrInPrism =$=
go2
where
go2 = do
next <- await
case next of
Nothing -> return ()
Just x -> do
leftover x
block
go2
block = sameKey Nothing =$= f
sameKey cur = do
next <- await
case next of
Nothing -> return ()
Just x@(k,_) ->
case cur of
Just curKey -> do
let n = eqSegs _mroPart
case take n curKey == take n k of
True -> yield x >> sameKey cur
False -> leftover x
Nothing -> do
yield x
sameKey (Just k)
------------------
-- Main Program --
------------------
-------------------------------------------------------------------------------
mapReduce
:: MROptions
-> Prism' B.ByteString a
-- ^ Serialization for data between map and reduce stages
-> Mapper B.ByteString CompositeKey a
-> Reducer CompositeKey a B.ByteString
-> (IO (), IO ())
mapReduce mro mrInPrism f g = (mp, rd)
where
mp = mapperWith mrInPrism f
rd = reducerMain mro mrInPrism g
-- | A default main that will respond to 'map' and 'reduce' commands
-- to run the right phase appropriately.
--
-- This is the recommended 'main' entry point to a map-reduce program.
-- The resulting program will respond as:
--
-- > ./myProgram map
-- > ./myProgram reduce
mapReduceMain
:: MROptions
-> Prism' B.ByteString a
-- ^ Serialization function for the in-between data 'a'.
-> Mapper B.ByteString CompositeKey a
-> Reducer CompositeKey a B.ByteString
-- ^ Reducer for a stream of values belonging to the same key.
-> IO ()
mapReduceMain mro mrInPrism f g = liftIO (execParser opts) >>= run
where
(mp,rd) = mapReduce mro mrInPrism f g
run Map = mp
run Reduce = rd
opts = info (helper <*> commandParse)
( fullDesc
<> progDesc "This is a Hadron Map/Reduce binary. "
<> header "hadron - use Haskell for Hadron."
)
data Command = Map | Reduce
-------------------------------------------------------------------------------
commandParse :: Parser Command
commandParse = subparser
( command "map" (info (pure Map)
( progDesc "Run mapper." ))
<> command "reduce" (info (pure Reduce)
( progDesc "Run reducer" ))
)
| fpinsight/hadron | src/Hadron/Basic.hs | bsd-3-clause | 9,521 | 0 | 21 | 2,506 | 1,755 | 931 | 824 | 192 | 5 |
<?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="si-LK">
<title>Directory List v2.3</title>
<maps>
<homeID>directorylistv2_3</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> | thc202/zap-extensions | addOns/directorylistv2_3/src/main/javahelp/help_si_LK/helpset_si_LK.hs | apache-2.0 | 978 | 78 | 66 | 157 | 412 | 209 | 203 | -1 | -1 |
{-# LANGUAGE FlexibleContexts, BangPatterns #-}
import Data.Array.Repa
import Data.Array.Repa.IO.DevIL
import System.Environment
import Data.Array.Repa.Repr.ForeignPtr
import Data.Word
-- <<main
main :: IO ()
main = do
[n, f1,f2] <- getArgs
runIL $ do
(RGB v) <- readImage f1 -- <1>
rotated <- computeP $ rotate (read n) v :: IL (Array F DIM3 Word8) -- <2>
writeImage f2 (RGB rotated) -- <3>
-- >>
-- <<rotate
rotate :: Double -> Array F DIM3 Word8 -> Array D DIM3 Word8
rotate deg g = fromFunction (Z :. y :. x :. k) f -- <1>
where
sh@(Z :. y :. x :. k) = extent g
!theta = pi/180 * deg -- <2>
!st = sin theta -- <3>
!ct = cos theta
!cy = fromIntegral y / 2 :: Double -- <4>
!cx = fromIntegral x / 2 :: Double
f (Z :. i :. j :. k) -- <5>
| inShape sh old = g ! old -- <6>
| otherwise = 0 -- <7>
where
fi = fromIntegral i - cy -- <8>
fj = fromIntegral j - cx
i' = round (st * fj + ct * fi + cy) -- <9>
j' = round (ct * fj - st * fi + cx)
old = Z :. i' :. j' :. k -- <10>
-- >>
| lywaterman/parconc-examples | rotateimage.hs | bsd-3-clause | 1,427 | 0 | 14 | 668 | 456 | 237 | 219 | 29 | 1 |
module Way.Type where
import Data.IntSet (IntSet)
import qualified Data.IntSet as Set
import Data.List
import Data.Maybe
import Development.Shake.Classes
import Hadrian.Utilities
-- Note: order of constructors is important for compatibility with the old build
-- system, e.g. we want "thr_p", not "p_thr" (see instance Show Way).
-- | A 'WayUnit' is a single way of building source code, for example with
-- profiling enabled, or dynamically linked.
data WayUnit = Threaded
| Debug
| Profiling
| Logging
| Dynamic
deriving (Bounded, Enum, Eq, Ord)
-- TODO: get rid of non-derived Show instances
instance Show WayUnit where
show unit = case unit of
Threaded -> "thr"
Debug -> "debug"
Profiling -> "p"
Logging -> "l"
Dynamic -> "dyn"
instance Read WayUnit where
readsPrec _ s = [(unit, "") | unit <- [minBound ..], show unit == s]
-- | Collection of 'WayUnit's that stands for the different ways source code
-- is to be built.
newtype Way = Way IntSet
instance Binary Way where
put = put . show
get = fmap read get
instance Hashable Way where
hashWithSalt salt = hashWithSalt salt . show
instance NFData Way where
rnf (Way s) = s `seq` ()
-- | Construct a 'Way' from multiple 'WayUnit's. Inverse of 'wayToUnits'.
wayFromUnits :: [WayUnit] -> Way
wayFromUnits = Way . Set.fromList . map fromEnum
-- | Split a 'Way' into its 'WayUnit' building blocks.
-- Inverse of 'wayFromUnits'.
wayToUnits :: Way -> [WayUnit]
wayToUnits (Way set) = map toEnum . Set.elems $ set
-- | Check whether a 'Way' contains a certain 'WayUnit'.
wayUnit :: WayUnit -> Way -> Bool
wayUnit unit (Way set) = fromEnum unit `Set.member` set
-- | Add a 'WayUnit' to a 'Way'
addWayUnit :: WayUnit -> Way -> Way
addWayUnit unit (Way set) = Way . Set.insert (fromEnum unit) $ set
-- | Remove a 'WayUnit' from 'Way'.
removeWayUnit :: WayUnit -> Way -> Way
removeWayUnit unit (Way set) = Way . Set.delete (fromEnum unit) $ set
instance Show Way where
show way = if null tag then "v" else tag
where
tag = intercalate "_" . map show . wayToUnits $ way
instance Read Way where
readsPrec _ s = if s == "v" then [(wayFromUnits [], "")] else result
where
uniqueReads token = case reads token of
[(unit, "")] -> Just unit
_ -> Nothing
units = map uniqueReads . words . replaceEq '_' ' ' $ s
result = if Nothing `elem` units
then []
else [(wayFromUnits . map fromJust $ units, "")]
instance Eq Way where
Way a == Way b = a == b
instance Ord Way where
compare (Way a) (Way b) = compare a b
| bgamari/shaking-up-ghc | src/Way/Type.hs | bsd-3-clause | 2,727 | 0 | 13 | 725 | 756 | 404 | 352 | 56 | 1 |
import System.IO
import System.Cmd
import System.FilePath
import Text.Printf
import System.Directory
import Control.Monad
testdir = "openFile008_testdir"
-- Test repeated opening/closing of 1000 files. This is useful for guaging
-- the performance of open/close and file locking.
main = do
system ("rm -rf " ++ testdir)
createDirectory testdir
let filenames = [testdir </> printf "file%03d" (n::Int) | n <- [1..1000]]
forM_ [1..50] $ \_ -> do
hs <- mapM (\f -> openFile f WriteMode) filenames
mapM_ hClose hs
mapM_ removeFile filenames
removeDirectory testdir
| urbanslug/ghc | libraries/base/tests/IO/openFile008.hs | bsd-3-clause | 585 | 0 | 15 | 106 | 169 | 85 | 84 | 16 | 1 |
module Crosscells.Region where
data Coord = Coord Int Int -- ^ row col
deriving (Read, Show, Eq, Ord)
data Region = Region Coord Coord
deriving (Read, Show, Eq, Ord)
data Direction = U | D | L | R
deriving (Read, Show, Eq, Ord)
coordRow, coordCol :: Coord -> Int
coordRow (Coord r _) = r
coordCol (Coord _ c) = c
flipDirection :: Direction -> Direction
flipDirection U = D
flipDirection D = U
flipDirection L = R
flipDirection R = L
pointsTo :: Direction -> Coord -> Region -> Bool
pointsTo U pt reg = sameCol pt reg && above pt (topLeft reg)
pointsTo D pt reg = sameCol pt reg && above (topLeft reg) pt
pointsTo L pt reg = sameRow pt reg && leftOf pt (topLeft reg)
pointsTo R pt reg = sameRow pt reg && leftOf (topLeft reg) pt
sameCol, sameRow :: Coord -> Region -> Bool
sameRow (Coord r _) (Region (Coord r1 _) (Coord r2 _)) = r1 <= r && r <= r2
sameCol (Coord _ c) (Region (Coord _ c1) (Coord _ c2)) = c1 <= c && c <= c2
above, leftOf :: Coord -> Coord -> Bool
above (Coord r1 _) (Coord r2 _) = r1 < r2
leftOf (Coord _ c1) (Coord _ c2) = c1 < c2
topLeft :: Region -> Coord
topLeft (Region x _) = x
contained :: Region -> Coord -> Bool
contained (Region (Coord r1 c1) (Coord r2 c2)) (Coord r c) =
r1 < r && r < r2 && c1 < c && c < c2
| glguy/5puzzle | Crosscells/Region.hs | isc | 1,257 | 0 | 11 | 286 | 637 | 327 | 310 | 31 | 1 |
-- file ch03/ex05.hs
-- Write a function that determines whether its input list is a palindrome.
isPali :: (Eq a) => [a] -> Bool
isPali [] = True
isPali (x:[]) = True
isPali (x:xs) = x == last(xs) && isPali(init xs)
-- init is defined as: init (xs) = take (length xs - 1) xs | imrehg/rwhaskell | ch03/ex05.hs | mit | 274 | 0 | 8 | 54 | 90 | 48 | 42 | 4 | 1 |
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE RecordWildCards, NamedFieldPuns #-}
{-# LANGUAGE FlexibleContexts #-}
--{-# LANGUAGE NoMonomorphismRestriction #-}
module Sudoku where
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import "mtl" Control.Monad.State
n :: Int
n = 3
type Index = (Int, Int)
data Square = Square {
x :: (Int, Int),
y :: (Int, Int)
} deriving (Eq, Ord, Show)
xy :: Square -> Index
xy Square {..} = (fst x, fst y)
type Number = Int
type Map' = Map Index (Set Number)
data BoardState = BoardState {
grid :: Map',
rows :: Map',
cols :: Map',
rest :: Set Square,
board :: Map Square Number
}
indices = [(x, y) | x <- [1..n], y <- [1..n]]
squares = [Square {x, y} | x <- indices, y <- indices]
numbers = [1..n*n]
showNum :: Maybe Number -> String
showNum Nothing = " "
showNum (Just x) = show x
instance Show BoardState where
show BoardState {board} =
unlines $ map showRow indices
where showRow y = concat [showNum $ getSquare y x | x <- indices]
getSquare y x = Map.lookup Square {x, y} board
emptyMap' = Map.fromList [(i, Set.empty) | i <- indices]
initial :: BoardState
initial = BoardState {
grid = emptyMap',
rows = emptyMap',
cols = emptyMap',
rest = Set.fromList squares,
board = Map.empty
}
--solve :: (MonadTrans t, MonadState BoardState (t [])) => t [] ()
solve :: StateT BoardState [] ()
solve = do
boardState@BoardState{..} <- get
let next = Set.findMin rest
rest' = Set.delete next rest
maps = [grid, rows, cols]
ixs = map ($ next) [xy, y, x]
sets = zipWith (Map.!) maps ixs
num <- lift numbers
lift $ guard $ all (Set.notMember num) sets
let sets' = [Set.insert num s | s <- sets]
maps' = zipWith3 Map.insert ixs sets' maps
[grid', rows', cols'] = maps'
put $ boardState {
grid = grid',
rows = rows',
cols = cols',
rest = rest',
board = Map.insert next num board
}
when (not $ Set.null rest') solve
allSolutions = map snd $ runStateT solve initial
| vladfi1/hs-misc | Sudoku.hs | mit | 2,098 | 0 | 12 | 506 | 810 | 449 | 361 | 66 | 1 |
{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics (Generic)
import Data.Hashable
data Color = Red | Green | Blue deriving (Generic, Show)
instance Hashable Color where
example1 :: Int
example1 = hash Red
-- 839657738087498284
example2 :: Int
example2 = hashWithSalt 0xDEADBEEF Red
-- 62679985974121021
| riwsky/wiwinwlh | src/hashable.hs | mit | 308 | 0 | 6 | 48 | 79 | 45 | 34 | 9 | 1 |
module PuzzleIO where
import Data.Char
import Data.Matrix
type Puzzle = Matrix (Maybe Int)
showPuzzle = unlines . (map showRow) . toLists
showRow = unwords . map showNumber
showNumber :: Maybe Int -> String
showNumber (Just n) = show n
showNumber Nothing = "-"
readPuzzle :: IO Puzzle
readPuzzle = do
lines <- sequence $ take 9 $ repeat getLine
return $ puzzleFromLines lines
puzzleFromLines lines =
let chars = filter (not . isSpace) $ unwords lines
in
fromList 9 9 $ map toCell chars
toCell :: Char -> Maybe Int
toCell n = if isHexDigit n then Just (digitToInt n) else Nothing
| matthayter/haskell_sudoku | PuzzleIO.hs | mit | 600 | 0 | 12 | 123 | 231 | 114 | 117 | 18 | 2 |
module ARD.World where
import ARD.Camera
import ARD.Color
import ARD.Light
import ARD.Randomize
import ARD.Ray
import ARD.Shape
import ARD.ViewPlane
data World
= World
{ camera :: Camera
, viewPlane :: ViewPlane
, sceneObjects :: [Shape]
, lights :: [Light]
, ambientLight :: Light
, backgroundColor :: Color
, randomState :: Random
}
| crazymaik/ard-haskell | lib/ARD/World.hs | mit | 356 | 0 | 9 | 71 | 98 | 62 | 36 | 17 | 0 |
{-# LANGUAGE FlexibleContexts, UndecidableInstances #-}
-----------------------------------------------------------------------------
--
-- Module : RunID3Weka
-- Copyright :
-- License : MIT
--
-- Maintainer :
-- Stability :
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module RunID3Weka (
run
, runIterative
, drawDecisionTree
, FinishedSplittingThreshold(..)
) where
import DecisionTrees
import DecisionTrees.Definitions
import DecisionTrees.TreeBranching
import DecisionTrees.ID3
import DecisionTrees.Utils
import WekaData
import WekaData.Show.Name
import Control.Arrow
import Data.Typeable
import Data.Map.Strict (Map)
import Data.List ((\\))
import Data.Maybe (isJust)
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Data.Tree as Tree
import GHC.Float
import Data.Random
import Data.Random.Sample
import qualified Data.Random.Extras as RE
-----------------------------------------------------------------------------
buildAttr attr = uncurry WVal . (const attr &&& id)
instance Attribute WekaVal where
-- possibleDiscreteDomains :: attr -> [PossibleDiscreteDomain attr]
possibleDiscreteDomains (WVal attr@(WekaAttrNom _ domain) _) =
flists (buildAttr attr) fsubs
where fsubs = fullSubsets . Set.fromList $ domain
fl f = map f . Set.toList
flists f = fl (fl (fl f))
-- attributeName :: attr -> AttributeName
attributeName (WVal attr _) = AttrName $ wekaAttributeName attr
separateClass :: (?clazz :: ClassDescriptor) => WekaEntry -> (WekaVal, [WekaVal])
separateClass e@(WEntry set) = maybe err f $ lookupWValInSet c set
where Class c = ?clazz
f = id &&& (Set.toList . (`Set.delete` set))
err = error $ "Class attribute '" ++ c ++ "' not found in " ++ show e
instance Entry WekaEntry where
-- listAttributes :: entry -> [AttributeContainer]
listAttributes = map Attr . snd . separateClass
-- getClass :: entry -> AttributeContainer
getClass = Attr . fst . separateClass
-- classDomain :: entry -> Set AttributeContainer
classDomain = Set.fromList . f . fst . separateClass
where f (WVal attr@(WekaAttrNom _ domain) _) =
map (Attr . WVal attr) domain
-- attrByName :: AttributeName -> entry -> AttributeContainer
attrByName (AttrName name) e@(WEntry dta) =
maybe err Attr $ lookupWValInSet name dta
where err = error $ "Attribute '" ++ name
++ "' not found in " ++ show e
hasAttribute (AttrName name) (WEntry set) = isJust $ lookupWValInSet name set
-----------------------------------------------------------------------------
type Filename = String
run :: Filename -- ^ file name
-> String -- ^ class name
-> FinishedSplittingThreshold
-> IO (Decision WekaEntry AttributeContainer) -- ^ the decision tree
run filename classname fsThreshold =
do entries <- getEntries filename
let ?clazz = Class classname
let ?config = fsThreshold
buildDecisionTree entries
getEntries filename = do
raw@(RawWekaData name attrs dta) <- readWekaData filename
return $ wekaData2Sparse raw
-----------------------------------------------------------------------------
runIterative :: Filename -- ^ file name
-> String -- ^ class name
-> FinishedSplittingThreshold
-> Float -- ^ the percent of /test/ entries
-> IO (Decision WekaEntry AttributeContainer) -- ^ the decision tree
runIterative filename classname fsThreshold testPercent = do
entries <- getEntries filename
let testEntriesCount = float2Int $ int2Float (length entries) * testPercent
testEntries <- runRVar (RE.sample testEntriesCount entries) StdRandom
let learnEntries = entries \\ testEntries
let ?clazz = Class classname
let ?config = fsThreshold
buildDecisionTreeIterative learnEntries testEntries
undefined
-----------------------------------------------------------------------------
drawDecisionTree :: Decision WekaEntry AttributeContainer -> IO()
drawDecisionTree res = do let tr = decision2Tree show res
putStrLn $ Tree.drawTree tr
| fehu/min-dat--decision-trees | src/RunID3Weka.hs | mit | 4,305 | 0 | 14 | 914 | 970 | 516 | 454 | -1 | -1 |
module JSON where
import Text.JSON
import DB0
import DB.Get
import DB0
instance JSON Event where
showJSON (EvNewMessage mid) = makeObj [("newmessage",JSRational False $ fromIntegral mid)]
showJSON _ = JSNull
instance JSON Exposed where
showJSON (Exposed mid mdate mpid mtext mvote fs (Interface cv cp ci cr cc co cx)) = makeObj $ [
("id",JSRational False . fromIntegral $ mid),
("date",JSString $ toJSString $ mdate),
("parent",maybe JSNull (JSRational False . fromIntegral) mpid),
("text",JSString $ toJSString mtext),
("vote",JSRational False $ fromIntegral mvote),
("alter", JSArray $ map showJSON fs),
("canVote",JSBool cv),
("canPropose",JSBool cp),
("canIntervein",JSBool ci),
("canRespond",JSBool cr),
("canClose",JSBool cc),
("canOpen",JSBool co),
("canRetract",JSBool cx)
]
| paolino/mootzoo | JSON.hs | mit | 1,031 | 0 | 12 | 349 | 328 | 180 | 148 | 23 | 0 |
module Parser where
import Monad
import Types
import Data.Maybe (fromJust)
import Options.Applicative
import Options.Applicative.Types (ReadM (..), readerAsk, readerError)
fullParser :: Parser Args
fullParser = argParser
uriReadM :: ReadM URI
uriReadM = do
s <- readerAsk
case parseURI s of
Nothing -> readerError "Not a valid seed URI"
Just uri -> return uri
argParser :: Parser Args
argParser = Args
<$> argument uriReadM
( metavar "SEED"
<> help "The url to start the spider from" )
<*> option auto
( value 1
<> short 'f'
<> long "fetchers"
<> metavar "INT"
<> help "The number of fetchers to use concurrently")
<*> flag False True
( short 's'
<> long "fetcher-status-log"
<> help "Whether to log fetcher's status")
<*> strOption
( value "/tmp/fetcher.txt"
<> long "queue-log-file"
<> metavar "FILE"
<> help "Where to log fetcher's status")
<*> strOption
( value "mail.txt"
<> short 'o'
<> long "output"
<> metavar "FILE"
<> help "Where to output the email addresses")
<*> flag False True
( short 'u'
<> long "queue-log"
<> help "Whether to log queued URL's")
<*> strOption
( value "/tmp/url.txt"
<> long "queue-log-file"
<> metavar "FILE"
<> help "Where to log queued URL's")
<*> switch
( short 'd'
<> long "stay-within-domain"
<> help "Stay within the seed URL's domain")
parseArgs :: IO Args
parseArgs = execParser opts
where
opts = info (helper <*> fullParser)
( fullDesc
<> progDesc "Web spider with the objective to find email addresses."
<> header "HEAS: Haskell Email Address Spider" )
| NorfairKing/hess | src/Parser.hs | mit | 1,882 | 0 | 18 | 628 | 438 | 210 | 228 | 59 | 2 |
-- |
-- Module : Text.XML.Mapping.Schema.Mixed
-- Copyright : (c) Joseph Abrahamson 2013
-- License : MIT
-- .
-- Maintainer : me@jspha.com
-- Stability : experimental
-- Portability : non-portable
-- .
-- XML \"mixed\" content.
module Text.XML.Mapping.Schema.Mixed (
Mixed (Mixed, unMixed), textOnly, elementsOnly
) where
import Data.Either
import qualified Data.Text as T
newtype Mixed a = Mixed { unMixed :: [Either T.Text a] }
deriving ( Show, Eq, Ord )
textOnly :: Mixed a -> [T.Text]
textOnly = lefts . unMixed
elementsOnly :: Mixed a -> [a]
elementsOnly = rights . unMixed
| tel/xml-mapping | src/Text/XML/Mapping/Schema/Mixed.hs | mit | 633 | 0 | 9 | 147 | 138 | 88 | 50 | 12 | 1 |
module Main where
import qualified Data.ByteString.Lazy as Bs
import Data.List
import Data.Word (Word8)
import Data.Bits
import Data.Ord (comparing)
import System.Exit
import System.Environment
import System.Console.GetOpt
import Control.Monad.Error
data RleCode = EqRle {len::Int, byte::Word8}
| IncRle {len::Int, start::Word8}
| Raw {bytes::[Word8]}
deriving (Show)
----------------------------------------Decode----------------------------------
--decodes one RleCode to corresponding byte array
decode :: RleCode -> [Word8]
decode (EqRle l b) = replicate l b
decode (IncRle l s) = take l [s..]
decode (Raw xs) = xs
--reads rleCodes from input bytestream
readRleCode :: [Word8] -> [RleCode]
readRleCode [] = []
readRleCode (count:datas@(dataByte:ds))
| count == 0xFF = [] --FF is endOfStream
| count == 0x7F = error "0x7F:New PPU address command is not implemented"
| not (testBit count 7) = EqRle (fromIntegral count) dataByte : readRleCode ds
| testBit count 6 = IncRle count' dataByte : readRleCode ds
| otherwise = Raw (take count' datas) : readRleCode (drop count' datas)
where count' = fromIntegral $ count .&. 0x3F--clear two hi bits
----------------------------------------Encode----------------------------------
-- takes only ascending (+1) init part of list (e.g. [5,6,7,2,1]->[5,6,7])
takeAsc :: (Eq a, Num a) => [a] -> [a]
takeAsc [] = []
takeAsc xss@(x:xs) = (x:) $ map fst $ takeWhile (uncurry (==)) $ zip xs $ map (+1) xss
encodeEqRle:: [Word8] -> RleCode
encodeEqRle xs = EqRle (length eqGroup) (head eqGroup)
where eqGroup = head $ group xs
encodeIncRle :: [Word8] -> RleCode
encodeIncRle xs = IncRle (length asc) (head asc)
where asc = takeAsc xs
mergeRaws :: [RleCode] -> [RleCode]
mergeRaws [] = []
mergeRaws (Raw x: Raw y :xs) = mergeRaws $ Raw (x++y): xs
mergeRaws (x:xs) = x:mergeRaws xs
--encode inits of given list to the best RleCode comparing length
encode :: [Word8] -> [RleCode]--first we get single RleCodes and then merge all raw values
encode = mergeRaws.encode'
where
encode' [] = []
encode' xs@(x:xss)
| len maxCode <= 2 = Raw [x] : encode' xss --optimization: don't break raw chains with 2-bytes Rle
| otherwise = maxCode : encode' (drop (len maxCode) xs)
where maxCode = maximumBy (comparing len) [encodeIncRle xs, encodeEqRle xs]
--serialize list of RleCodes to game's format
writeRleCode:: [RleCode] -> [Word8]
writeRleCode [] = [0xFF] --End of stream sign
writeRleCode (EqRle l b:xs)
| l > 0x7E = 0x7E: b : writeRleCode (EqRle (l-0x7E) b: xs) --0x7E is max EqRle length
| otherwise = fromIntegral l: b: writeRleCode xs
writeRleCode (IncRle l s:xs)
| l > 0x3F = 0xFF: s : writeRleCode (IncRle (l-0x3F) (s+0x3F): xs)
| otherwise = (fromIntegral l .|. 0xC0) : s : writeRleCode xs --two high bits are set at incremental Rle
writeRleCode (Raw xs: xss)
| length xs > 0x3F = 0xBF: xs ++ writeRleCode (Raw (drop 0x3F xs) : xss)
| otherwise = (fromIntegral (length xs) .|. 0x80): xs ++ writeRleCode xss -- high bit is set for raw
----------------------------------------Command line parse part----------------------------------
data Action = Decode | Encode | NoAction deriving (Show, Eq)
data Options = Options
{optHelp :: Bool
,optVersion :: Bool
,optAction :: Action
}
deriving (Show)
defaultOptions :: Options
defaultOptions = Options
{optHelp = False
,optVersion = False
,optAction = NoAction
}
usage :: String
usage = usageInfo "Usage: eintourname [-d | -e] file_name [offset]" options
options :: [OptDescr (Options -> Options)]
options =
[ Option "d" ["decode"] (NoArg (\opts -> opts {optAction = Decode})) "decode from ROM. -d <file_name offset>"
, Option "e" ["encode"] (NoArg (\opts -> opts {optAction = Encode})) "encode from raw binary. -e <file_name>"
, Option "h?" ["help"] (NoArg (\ opts -> opts { optHelp = True })) "show help."
, Option "v" ["version"] (NoArg (\ opts -> opts { optVersion = True })) "show version number."
]
toolOpts :: [String] -> IO (Options, [String])
toolOpts argv =
case getOpt Permute options argv of
(o,n,[] ) -> return (foldl (flip id) defaultOptions o, n)
(_,_,errs) -> ioError (userError (concat errs ++ usage))
----------------------------------------------Main------------------------------------------------------
main :: IO()
main = do
argv <- getArgs
(opts, nonOpts) <- toolOpts argv
when (optVersion opts) $ do
putStrLn "Eintourname. NES Teenage Mutant Ninja Turtles - Tournament Fighters RLE utility. Version 0.1"
exitSuccess
when (optHelp opts) $ do
putStrLn usage
exitSuccess
let action = optAction opts
when (action == NoAction) $ do
putStrLn "Supply action flag"
putStrLn usage
exitFailure
if action == Decode
then do
when (length nonOpts /= 2) $ do
putStrLn "Supply exactly one file name and one offset for decoding"
putStrLn usage
exitFailure
let [fileName, sOffset] = nonOpts
input <- Bs.readFile fileName
let inputU8 = drop (read sOffset) $ Bs.unpack input
decoded = concatMap decode . readRleCode $ inputU8
Bs.writeFile "decoded.bin" (Bs.pack decoded)
else do --encoding
when (length nonOpts /= 1) $ do
putStrLn "Supply exactly one file name for encoding"
putStrLn usage
exitFailure
let [fileName] = nonOpts
input <- Bs.readFile fileName
let inputU8 = Bs.unpack input
encoded = writeRleCode . encode $ inputU8
Bs.writeFile "encoded.bin" (Bs.pack encoded)
| romhack/eintourname | eintourname.hs | mit | 5,824 | 4 | 16 | 1,376 | 1,917 | 986 | 931 | 118 | 2 |
module HConsole where
import Block
import Mino
import Graphics.Gloss
-- constants
scorePaneBackgroundColor, scorePaneBorderColor, scorePaneTextColor :: Color
scorePaneWidth, scorePaneInnerWidth, scorePaneHeight, scorePaneInnerHeight, scoreTextScale :: Float
scorePaneTextLocation, scorePaneBoxLocation, scorePaneLabelLocation :: (Float,Float)
scorePaneBackgroundColor = black
scorePaneBorderColor = makeColorI 0xFF 0xFF 0xFF 0xFF
scorePaneTextColor = makeColorI 0xFF 0xFF 0xFF 0xFF
scorePaneWidth = 200.0
scorePaneInnerWidth = 195.0
scorePaneHeight = 50.0
scorePaneInnerHeight = 45.0
scorePaneTextLocation = (-60,230)
scorePaneBoxLocation = (-10,240)
scorePaneLabelLocation = (-60,270)
scoreTextScale = 0.2
nextBoxBackgroundColor, nextBoxBorderColor, nextTextColor :: Color
nextBoxWidth, nextBoxInnerWidth, nextBoxHeight, nextBoxInnerHeight, nextTextScale :: Float
nextBlockLocation, nextBoxLocation, nextTextLocation :: (Float,Float)
nextBoxBackgroundColor = black
nextBoxBorderColor = white
nextTextColor = white
nextBoxWidth = 120.0
nextBoxInnerWidth = 115.0
nextBoxHeight = 80.0
nextBoxInnerHeight = 75.0
nextBlockLocation = (270,180)
nextBoxLocation = (160,150)
nextTextLocation = (150,200)
nextTextScale = 0.15
holdBoxBackgroundColor, holdBoxBorderColor, holdBoxTextColor :: Color
holdBoxWidth, holdBoxInnerWidth, holdBoxHeight, holdBoxInnerHeight, holdTextScale :: Float
holdBlockLocation, holdBoxLocation, holdTextLocation :: (Float,Float)
holdBoxBackgroundColor = black
holdBoxBorderColor = white
holdBoxTextColor = white
holdBoxWidth = 120.0
holdBoxInnerWidth = 115.0
holdBoxHeight = 80.0
holdBoxInnerHeight = 75.0
holdBlockLocation = (-70,180)
holdBoxLocation = (-180,150)
holdTextLocation = (-190,200)
holdTextScale = 0.15
levelBoxBackgroundColor, levelBoxBorderColor, levelBoxTextColor :: Color
levelBoxWidth, levelBoxInnerWidth, levelBoxHeight, levelBoxInnerHeight, levelTextScale :: Float
levelBlockLocation, levelBoxLocation, levelTextLocation, levelLabelLocation :: (Float,Float)
levelBoxBackgroundColor = black
levelBoxBorderColor = white
levelBoxTextColor = white
levelBoxWidth = 100.0
levelBoxInnerWidth = 95.0
levelBoxHeight = 50.0
levelBoxInnerHeight = 45.0
levelBlockLocation = (-60,50)
levelBoxLocation = (-170,20)
levelTextLocation = (-170,15)
levelLabelLocation = (-190,70)
levelTextScale = 0.15
renderScorePane :: Int -> Picture
renderScorePane score = pictures [scoreBorderBox, scoreBox, scoreText, scoreLabel]
where (tX,tY) = scorePaneTextLocation
(bX,bY) = scorePaneBoxLocation
(lX,lY) = scorePaneLabelLocation
scoreText = color scorePaneTextColor $
translate tX tY $
scale scoreTextScale scoreTextScale $
text $ show score
scoreLabel = color black $
translate lX lY $
scale 0.15 0.15 $
text "Score"
scoreBorderBox = color scorePaneBorderColor $
translate bX bY $
rectangleSolid scorePaneWidth scorePaneHeight
scoreBox = color scorePaneBackgroundColor $
translate bX bY $
rectangleSolid scorePaneInnerWidth scorePaneInnerHeight
renderNextMino :: Mino -> Picture
renderNextMino m = pictures [nextBorderBox, nextBox, nextBlocks, nextLabel]
where (tX,tY) = nextBlockLocation
(bX,bY) = nextBoxLocation
(lX,lY) = nextTextLocation
nextBlocks = pictures $ (renderBlock tX tY) <$> (minoBlocks m)
nextBorderBox = color nextBoxBorderColor $
translate bX bY $
rectangleSolid nextBoxWidth nextBoxHeight
nextBox = color nextBoxBackgroundColor $
translate bX bY $
rectangleSolid nextBoxInnerWidth nextBoxInnerHeight
nextLabel = color black $
translate lX lY $
scale nextTextScale nextTextScale $
text $ "Next"
renderHoldMino :: Maybe Mino -> Picture
renderHoldMino m = pictures [holdBorderBox, holdBox, holdBlocks, holdLabel]
where (tX,tY) = holdBlockLocation
(bX,bY) = holdBoxLocation
(lX,lY) = holdTextLocation
holdBlocks = case m of
Nothing -> pictures []
Just mino -> pictures $ (renderBlock tX tY) <$> (minoBlocks mino)
holdBorderBox = color holdBoxBorderColor $
translate bX bY $
rectangleSolid holdBoxWidth holdBoxHeight
holdBox = color holdBoxBackgroundColor $
translate bX bY $
rectangleSolid holdBoxInnerWidth holdBoxInnerHeight
holdLabel = color black $
translate lX lY $
scale holdTextScale holdTextScale $
text $ "Hold"
renderLevelBox :: Int -> Picture
renderLevelBox l = pictures [levelBorderBox, levelBox, levelText, levelLabel]
where (tX,tY) = levelTextLocation
(bX,bY) = levelBoxLocation
(lX,lY) = levelLabelLocation
levelText = color levelBoxTextColor $
translate tX tY $
scale levelTextScale levelTextScale $
text $ show l
levelBorderBox = color levelBoxBorderColor $
translate bX bY $
rectangleSolid levelBoxWidth levelBoxHeight
levelBox = color levelBoxBackgroundColor $
translate bX bY $
rectangleSolid levelBoxInnerWidth levelBoxInnerHeight
levelLabel = color black $
translate lX lY $
scale levelTextScale levelTextScale $
text $ "Level"
--data AltPicture = AltText String
-- | Nada
-- deriving (Show)
--renderAlt :: AltPicture -> IO()
--renderAlt a = case a of
-- AltText str -> do
-- GL.blend $= GL.Disabled
-- GL.preservingMatrix $ GLUT.renderString GLUT.Roman str
-- GL.blend $= GL.Enabled
-- Nada -> pure
| maple-shaft/HaskellTetris | src/HConsole.hs | mit | 6,272 | 0 | 13 | 1,806 | 1,295 | 737 | 558 | 133 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
import Gauge.Main
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Builder as BB
import Data.Monoid
import qualified Data.Streaming.ByteString.Builder as BB
main :: IO ()
main = defaultMain [ bgroup "Data.Streaming.ByteString.Builder.toByteStringIO"
(benchmarks bIO b100_10000 b10000_100 b10000_10000)
, bgroup "Data.ByteString.Builder.toLazyByteString"
(benchmarks bLazy b100_10000 b10000_100 b10000_10000)
]
where
bIO = whnfIO . BB.toByteStringIO (const (return ()))
bLazy = nf BB.toLazyByteString
benchmarks run bld100_10000 bld10000_100 bld10000_10000 =
[ bench' run bld100_10000 100 10000
, bench' run bld10000_100 10000 100
, bench' run bld10000_10000 10000 10000
]
bench' :: (b -> Benchmarkable) -> b -> Int -> Int -> Benchmark
bench' run bld' len reps = bench (show len ++ "/" ++ show reps) (run bld')
b100_10000 = bld BB.byteString 100 10000
b10000_100 = bld BB.byteString 10000 100
b10000_10000 = bld BB.byteString 10000 10000
bld :: Data.Monoid.Monoid a => (S.ByteString -> a) -> Int -> Int -> a
bld f len reps = mconcat (replicate reps (f (S.replicate len 'x')))
| fpco/streaming-commons | bench/builder-to-bytestring-io.hs | mit | 1,310 | 0 | 14 | 328 | 375 | 197 | 178 | 24 | 1 |
--
-- Manage asynchronous evaluation tasks
--
module Codex.Tasks (
TaskGroup, Queue,
createTaskGroup, forkTask,
createQueue, addQueue, cancelAll
) where
import Control.Monad.IO.Class
import Control.Concurrent
import Control.Exception (bracket_)
-- | a task group
-- a quantity semaphore to throttle the number of concurrent threads
newtype TaskGroup = TaskGroup QSem
-- Create a task group with n concurrent slots
createTaskGroup :: MonadIO m => Int -> m TaskGroup
createTaskGroup n = liftIO (TaskGroup <$> newQSem n)
-- Fork a new IO action under a task group
forkTask :: MonadIO m => TaskGroup -> IO () -> m ThreadId
forkTask (TaskGroup qsem) action
= liftIO $ forkIO (bracket_ (waitQSem qsem) (signalQSem qsem) action)
-- | a queue for pending evaluations
newtype Queue = Queue (MVar [ThreadId])
createQueue :: MonadIO m => m Queue
createQueue
= liftIO (Queue <$> newMVar [])
addQueue :: MonadIO m => ThreadId -> Queue -> m ()
addQueue threadId (Queue v)
= liftIO $ modifyMVar_ v (\list -> return (threadId:list))
cancelAll :: MonadIO m => Queue -> m ()
cancelAll (Queue v)
= liftIO $ modifyMVar_ v (\list -> mapM_ killThread list >> return [])
| pbv/codex | src/Codex/Tasks.hs | mit | 1,210 | 0 | 11 | 247 | 366 | 193 | 173 | 23 | 1 |
module Nagari where
import Control.Monad
import Data.Char
import qualified Data.List as L
import Data.Monoid
import Prelude hiding (filter, iterate, take, takeWhile, map)
import qualified Prelude as P
----------------
-- Data types --
----------------
-- | Parser combinator type.
newtype Parser a = Parser { runParser :: String -> [(a, String)] }
---------------
-- Instances --
---------------
instance Monoid (Parser a) where
-- | The identity function for another parser when combined with `mappend`.
mempty = Parser $ const []
-- | Allows forking of parsing logic, concatenating the results of several
-- parsers into one parser result.
(Parser f) `mappend` (Parser g) = Parser $ \xs ->
let fResult = f xs
gResult = g xs
in fResult ++ gResult
instance MonadPlus Parser where
mzero = mempty
mplus = mappend
instance Functor Parser where
-- | Allows for mapping over parser results with a function `f`.
fmap f p = Parser $ \xs ->
[(f y, ys) | (y, ys) <- runParser p xs]
instance Monad Parser where
-- | Always succeeds at parsing a value `x`.
return x = Parser $ \xs -> [(x, xs)]
-- | Allows for combination of parsers.
Parser p >>= f = Parser $ \xs ->
concat [runParser (f y) ys | (y, ys) <- p xs]
-- | Always fails at parsing a value.
fail _ = Parser $ const []
----------------------
-- Parsers builders --
----------------------
err :: String -> Parser a
err xs = Parser $ \ys -> error $ xs ++ " near '" ++ ys ++ "'\n"
-- | Alias for `mplus`.
and :: Parser a -> Parser a -> Parser a
and = mplus
-- | Builds a parser that first attempts to parse with a parser `p` and falls
-- back to parsing with a parser `q` on failure.
or :: Parser a -> Parser a -> Parser a
p `or` q = Parser $ \xs -> case runParser p xs of
[] -> runParser q xs
r -> r
-- | Builds a parser that first attempts to parse with a parser `p` and falls
-- back to parsing with a parser `q` on failure. Parser result type uses
-- `Either`.
or' :: Parser a -> Parser b -> Parser (Either b a)
p `or'` q = Parser $ \xs ->
case runParser p xs of
[] -> case runParser q xs of
[] -> []
r2 -> [(Left y, ys) | (y, ys) <- r2]
r1 -> [(Right y, ys) | (y, ys) <- r1]
-- | Alias for `fmap`.
map :: (a -> b) -> Parser a -> Parser b
map = fmap
-- | Succeeds at parsing a single character if the given predicate is true for
-- the parser result.
takeOneIf :: (Char -> Bool) -> Parser Char
takeOneIf p = Parser $ \xs -> case xs of
[] -> []
y:ys -> [(y, ys) | p y]
takeOneIf' :: (Char -> Bool) -> Parser Char
takeOneIf' p = do
x <- char
if p x then return x else fail ""
-- | Builds a parser which will apply itself to a string the given number of
-- times.
take :: Int -> Parser a -> Parser [a]
take = replicateM
-- | Used as helper function by `takeAll`.
takeAll' :: Parser a -> Parser a
takeAll' p = Parser $ \xs ->
let rs = runParser p xs
in rs ++ concat [runParser (takeAll' p) ys | (_, ys) <- rs]
-- | Builds a parser which will apply itself to a string until further
-- applications yield no results.
takeAll :: Parser a -> Parser [a]
takeAll p = Parser $ \xs -> case runParser (takeAll' p) xs of
[] -> []
rs -> let unParsed = snd . last $ rs
results = P.map fst rs
in [(results, unParsed)]
-- | Builds a parser that will succeed as long as the predicate `p` is true for
-- characters in the input stream.
takeWhile :: (Char -> Bool) -> Parser String
takeWhile p = Parser $ \xs -> case xs of
[] -> []
_ -> let (xsInit, xsTail) = span p xs
in [(xsInit, xsTail) | not . null $ xsInit]
-- | Finds the index of the first occurrence of a list `xs` in a list `ys`.
findIn :: (Eq a) => [a] -> [a] -> Maybe Int
findIn _ [] = Nothing
findIn [] _ = Nothing
findIn xs ys = L.elemIndex True $ L.map (L.isPrefixOf xs) (L.tails ys)
-- | Builds a parser which parses a string until an occurrence of string `s` is
-- found. Fails if nothing is found.
takeUntil :: String -> Parser String
takeUntil s = Parser $ \xs -> case findIn s xs of
Nothing -> []
Just i -> [splitAt i xs]
-- | Builds a parser which performs its action and then consumes any whitespace
-- after the parsed content.
token :: Parser a -> Parser a
token p = do
x <- p
takeWhile isSpace
return x
-- | Parses a sequence of letters.
letters :: Parser String
letters = takeWhile isAlpha
-- | Parses a tokenized sequence of letters.
word :: Parser String
word = token letters
-- | Parses a sequence of digits and returns its integer value.
number :: Parser Int
number = map read $ takeWhile isDigit
-- | Parses a specific string from the input.
accept :: String -> Parser String
accept s = do
t <- take (length s) char
if s == t then return t else fail ""
------------------
-- Core parsers --
------------------
-- | Parses a single character.
char :: Parser Char
char = Parser $ \xs -> case xs of
[] -> []
y:ys -> [(y, ys)]
-- | Parses a single whitespace character.
space :: Parser Char
space = takeOneIf isSpace
-- | Parses a single alphabetical character.
alpha :: Parser Char
alpha = takeOneIf isAlpha
-- | Parses a single digit character.
digit :: Parser Char
digit = takeOneIf isDigit
-- | Parses a single alpha-numerical character.
alphaNum :: Parser Char
alphaNum = takeOneIf isAlphaNum
-- | Parses one of a given character `x`.
lit :: Char -> Parser Char
lit x = takeOneIf (==x)
-- | Succeeds at parsing a character which is not the given character `x`.
unLit :: Char -> Parser Char
unLit x = takeOneIf (/=x)
| davesque/nagari | Nagari.hs | mit | 5,631 | 0 | 16 | 1,371 | 1,667 | 883 | 784 | 106 | 3 |
module Alder.Unique
( -- * Unique values
Unique
-- * Supplying 'Unique's
, MonadSupply(..)
-- * Tagging values
, Tagged(..)
, tag
, untag
) where
import Control.Monad
type Unique = Int
class Monad m => MonadSupply m where
getUnique :: m Unique
data Tagged a = !Unique :< a
tag :: MonadSupply m => a -> m (Tagged a)
tag a = liftM (:< a) getUnique
untag :: Tagged a -> a
untag (_ :< a) = a
| ghcjs/ghcjs-sodium | src/Alder/Unique.hs | mit | 440 | 0 | 9 | 131 | 151 | 84 | 67 | 18 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-trigger-action.html
module Stratosphere.ResourceProperties.GlueTriggerAction where
import Stratosphere.ResourceImports
-- | Full data type definition for GlueTriggerAction. See 'glueTriggerAction'
-- for a more convenient constructor.
data GlueTriggerAction =
GlueTriggerAction
{ _glueTriggerActionArguments :: Maybe Object
, _glueTriggerActionJobName :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToJSON GlueTriggerAction where
toJSON GlueTriggerAction{..} =
object $
catMaybes
[ fmap (("Arguments",) . toJSON) _glueTriggerActionArguments
, fmap (("JobName",) . toJSON) _glueTriggerActionJobName
]
-- | Constructor for 'GlueTriggerAction' containing required fields as
-- arguments.
glueTriggerAction
:: GlueTriggerAction
glueTriggerAction =
GlueTriggerAction
{ _glueTriggerActionArguments = Nothing
, _glueTriggerActionJobName = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-trigger-action.html#cfn-glue-trigger-action-arguments
gtaArguments :: Lens' GlueTriggerAction (Maybe Object)
gtaArguments = lens _glueTriggerActionArguments (\s a -> s { _glueTriggerActionArguments = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-trigger-action.html#cfn-glue-trigger-action-jobname
gtaJobName :: Lens' GlueTriggerAction (Maybe (Val Text))
gtaJobName = lens _glueTriggerActionJobName (\s a -> s { _glueTriggerActionJobName = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/GlueTriggerAction.hs | mit | 1,688 | 0 | 12 | 203 | 252 | 145 | 107 | 27 | 1 |
{-# htermination (inRangeChar :: Tup2 Char Char -> Char -> MyBool) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data Tup2 a b = Tup2 a b ;
data Char = Char MyInt ;
data MyInt = Pos Nat | Neg Nat ;
data Nat = Succ Nat | Zero ;
data Ordering = LT | EQ | GT ;
asAs :: MyBool -> MyBool -> MyBool;
asAs MyFalse x = MyFalse;
asAs MyTrue x = x;
primCharToInt :: Char -> MyInt;
primCharToInt (Char x) = x;
fromEnumChar :: Char -> MyInt
fromEnumChar = primCharToInt;
inRangeI vv = fromEnumChar vv;
primCmpNat :: Nat -> Nat -> Ordering;
primCmpNat Zero Zero = EQ;
primCmpNat Zero (Succ y) = LT;
primCmpNat (Succ x) Zero = GT;
primCmpNat (Succ x) (Succ y) = primCmpNat x y;
primCmpInt :: MyInt -> MyInt -> Ordering;
primCmpInt (Pos Zero) (Pos Zero) = EQ;
primCmpInt (Pos Zero) (Neg Zero) = EQ;
primCmpInt (Neg Zero) (Pos Zero) = EQ;
primCmpInt (Neg Zero) (Neg Zero) = EQ;
primCmpInt (Pos x) (Pos y) = primCmpNat x y;
primCmpInt (Pos x) (Neg y) = GT;
primCmpInt (Neg x) (Pos y) = LT;
primCmpInt (Neg x) (Neg y) = primCmpNat y x;
compareMyInt :: MyInt -> MyInt -> Ordering
compareMyInt = primCmpInt;
esEsOrdering :: Ordering -> Ordering -> MyBool
esEsOrdering LT LT = MyTrue;
esEsOrdering LT EQ = MyFalse;
esEsOrdering LT GT = MyFalse;
esEsOrdering EQ LT = MyFalse;
esEsOrdering EQ EQ = MyTrue;
esEsOrdering EQ GT = MyFalse;
esEsOrdering GT LT = MyFalse;
esEsOrdering GT EQ = MyFalse;
esEsOrdering GT GT = MyTrue;
not :: MyBool -> MyBool;
not MyTrue = MyFalse;
not MyFalse = MyTrue;
fsEsOrdering :: Ordering -> Ordering -> MyBool
fsEsOrdering x y = not (esEsOrdering x y);
ltEsMyInt :: MyInt -> MyInt -> MyBool
ltEsMyInt x y = fsEsOrdering (compareMyInt x y) GT;
inRangeChar :: Tup2 Char Char -> Char -> MyBool
inRangeChar (Tup2 c c') ci = asAs (ltEsMyInt (fromEnumChar c) (inRangeI ci)) (ltEsMyInt (inRangeI ci) (fromEnumChar c'));
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/inRange_2.hs | mit | 1,938 | 0 | 9 | 411 | 799 | 432 | 367 | 51 | 1 |
{-# LANGUAGE OverloadedStrings, Arrows #-}
module Main where
import Text.XML.HXT.Core
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.List
import Text.XML.HXT.Arrow.XmlState.RunIOStateArrow
import Text.XML.HXT.Arrow.XmlState.TypeDefs
type ImgState = [Image]
type ImgArrow = IOSLA (XIOState ImgState) XmlTree XmlTree
data Image = Image {
mimeType :: String
, base64Data :: BL.ByteString
} deriving (Show)
extractInlineImages :: ImgArrow
extractInlineImages = processTopDown ( extractImg `when` isInlineImg)
isInlineImg = isElem
>>> hasName "img"
>>> hasAttr "src"
>>> getAttrValue "src"
>>> isA isDataURI
where isDataURI = isPrefixOf "data:image/"
extractImg =
processAttrl (
(changeAttrValue . const $< createImage)
`when` hasName "src"
)
-- We are on the src attribute node at this point, so the children is the src value
createImage :: IOSLA (XIOState ImgState) XmlTree String
createImage =
(saveImg $< xshow getChildren)
-- >>> changeUserState (\x imgs -> (Image x ""):imgs )
saveImg :: String -> IOSLA (XIOState ImgState) XmlTree String
saveImg string =
-- in real app, process the data URI string and save IMG to DB
arrIO0 (do
putStrLn "Process this data and return a new URL"
putStrLn string
return "THIS URL IS RETURN AFTER IMAGE IS CREATED IN DB")
main = do
html <- getContents
let doc = readString [withParseHTML yes, withWarnings no] html
(s, xs) <- runIOSLA
( doc
>>> extractInlineImages
>>> writeDocument [withIndent yes ,withOutputEncoding utf8 ] "-"
) (initialState []) undefined
-- print $ xioUserState s
return ()
| danchoi/datauri | Main.hs | mit | 1,775 | 0 | 13 | 455 | 392 | 212 | 180 | -1 | -1 |
-- ArbolBinPropiedades.hs
-- Generador de árboles binarios de búsqueda y propiedades del TAD.
-- Tablas mediante matrices.
-- José A. Alonso Jiménez https://jaalonso.github.com
-- =====================================================================
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Tema_19.ArbolBinPropiedades where
-- Importación de la implementación de los ABB que se desea verificar.
import Tema_19.ArbolBin
-- import I1M.ArbolBin
import Data.List (nub, sort)
import Test.QuickCheck
-- ---------------------------------------------------------------------
-- Generador de ABB --
-- ---------------------------------------------------------------------
-- genABB es un generador de árboles binarios de búsqueda. Por ejemplo,
-- λ> sample genABB
-- -
-- (1 (-1 - -) -)
-- (1 - -)
-- (-1 (-3 - -) (1 - (4 - -)))
-- -
-- (10 (-7 - -) -)
-- (1 (-9 - -) (7 (5 - -) (10 - -)))
-- ...
genABB :: Gen (ABB Int)
genABB = do
xs <- listOf arbitrary
return (foldr inserta vacio xs)
-- Los árboles binarios de búsqueda son instancias de la clase
-- arbitraria.
instance Arbitrary (ABB Int) where
arbitrary = genABB
-- Propiedad. Todo los elementos generados por genABB son árboles binarios
-- de búsqueda.
prop_genABB_correcto :: ABB Int -> Bool
prop_genABB_correcto = valido
-- Comprobación.
-- λ> quickCheck prop_genABB_correcto
-- +++ OK, passed 100 tests.
-- listaOrdenada es un generador de listas ordenadas de números
-- enteros. Por ejemplo,
-- λ> sample listaOrdenada
-- [1]
-- [1]
-- [-2,-1,0]
-- [-1,0,1]
-- [-8,-5,-4,-3,3,4,8]
-- [-6,-3,8]
-- [-14,-13]
-- [-31,-23,-16,-13,-11,-5,1,4,11,14,15,21,26,29]
-- []
-- []
-- []
listaOrdenada :: Gen [Int]
listaOrdenada =
frequency [(1,return []),
(4,do xs <- orderedList
n <- arbitrary
return (nub ((case xs of
[] -> n
x:_ -> n `min` x)
:xs)))]
-- (ordenada xs) se verifica si xs es una lista ordenada creciente. Por
-- ejemplo,
-- ordenada [3,5,9] == True
-- ordenada [3,9,5] == False
ordenada :: [Int] -> Bool
ordenada xs = and [x < y | (x,y) <- zip xs (tail xs)]
-- Propiedad. El generador listaOrdenada produce listas ordenadas.
prop_listaOrdenada_correcta :: [Int] -> Property
prop_listaOrdenada_correcta _ =
forAll listaOrdenada ordenada
-- Comprobación:
-- λ> quickCheck prop_listaOrdenada_correcta
-- +++ OK, passed 100 tests.
-- Propiedad. Al eliminar las repeticiones en las listas producidas por el
-- generador orderedList se obtienen listas ordenadas.
prop_orderedList_correcta :: [Int] -> Property
prop_orderedList_correcta _ =
forAll orderedList (ordenada . nub)
-- Comprobación:
-- λ> quickCheck prop_orderedList_correcta
-- +++ OK, passed 100 tests.
-- ---------------------------------------------------------------------
-- Propiedades --
-- ---------------------------------------------------------------------
-- Propiedades de vacio
-- --------------------
-- Prop. vacio es un ABB.
prop_vacio_es_ABB :: Bool
prop_vacio_es_ABB =
valido (vacio :: ABB Int)
-- Comprobación:
-- λ> quickCheck prop_vacio_es_ABB
-- +++ OK, passed 100 tests.
-- Propiedades de inserta
-- ----------------------
-- Propiedad. Si a es un ABB, entonces (inserta v a) también lo es.
prop_inserta_es_valida :: Int -> ABB Int -> Bool
prop_inserta_es_valida v a =
valido (inserta v a)
-- Comprobación:
-- λ> quickCheck prop_inserta_es_valida
-- +++ OK, passed 100 tests.
-- Propiedad. El árbol que resulta de añadir un elemento a un ABB es no
-- vacío.
prop_inserta_es_no_vacio :: Int -> ABB Int -> Bool
prop_inserta_es_no_vacio x a =
inserta x a /= vacio
-- Comprobación.
-- λ> quickCheck prop_inserta_es_no_vacio
-- +++ OK, passed 100 tests.
-- Propiedad. Para todo x y a, x es un elemento de (inserta x a).
prop_elemento_de_inserta :: Int -> ABB Int -> Bool
prop_elemento_de_inserta x a =
pertenece x (inserta x a)
-- Comprobación:
-- λ> quickCheck prop_elemento_de_inserta
-- +++ OK, passed 100 tests.
-- Propiedades de pertenece
-- ------------------------
-- Propiedad. En en árbol vacio no hay ningún elemento.
prop_vacio_sin_elementos :: Int -> Bool
prop_vacio_sin_elementos x =
not (pertenece x vacio)
-- Comprobación:
-- λ> quickCheck prop_vacio_sin_elementos
-- +++ OK, passed 100 tests.
-- Propiedad. Los elementos de (inserta x a) son x y los elementos de
-- a.
prop_elementos_de_inserta :: Int -> Int -> ABB Int -> Bool
prop_elementos_de_inserta x y a =
pertenece y (inserta x a) == (x == y) || pertenece y a
-- Comprobación.
-- λ> quickCheck prop_elementos_de_inserta
-- +++ OK, passed 100 tests.
-- Propiedades de elimina
-- ----------------------
-- Propiedad. Si a es un ABB, entonces (elimina v a) también lo es.
prop_elimina_es_valida :: Int -> ABB Int -> Bool
prop_elimina_es_valida v a =
valido (elimina v a)
-- Comprobación:
-- λ> quickCheck prop_elimina_es_valida
-- +++ OK, passed 100 tests.
-- Prop. El resultado de eliminar el elemento x en (inserta x a) es
-- (elimina x a).
prop_elimina_agrega :: Int -> ABB Int -> Bool
prop_elimina_agrega x a =
elimina x (inserta x a) == elimina x a
-- Comprobación
-- λ> quickCheck prop_elimina_agrega
-- +++ OK, passed 100 tests.
-- Propiedades de crea
-- -------------------
-- Propiedad. (crea xs) es un ABB.
prop_crea_es_valida :: [Int] -> Bool
prop_crea_es_valida xs =
valido (crea xs)
-- Comprobación:
-- λ> quickCheck prop_crea_es_valida
-- +++ OK, passed 100 tests.
-- Propiedades de crea'
-- --------------------
-- Propiedad. Para todas las listas ordenadas xs, se tiene que (crea' xs)
-- es un ABB.
prop_crea'_es_valida :: [Int] -> Property
prop_crea'_es_valida _ =
forAll listaOrdenada (valido . crea')
-- Comprobación:
-- λ> quickCheck prop_crea'_es_valida
-- +++ OK, passed 100 tests.
-- Propiedades de elementos
-- ------------------------
-- Propiedad. (elementos (crea xs)) es igual a la lista xs ordenada y
-- sin repeticiones.
prop_elementos_crea :: [Int] -> Bool
prop_elementos_crea xs =
elementos (crea xs) == sort (nub xs)
-- Comprobación
-- λ> quickCheck prop_elementos_crea
-- +++ OK, passed 100 tests.
-- Propiedad. Si ys es una lista ordenada sin repeticiones, entonces
-- (elementos (crea' ys)) es igual ys.
prop_elementos_crea' :: [Int] -> Bool
prop_elementos_crea' xs =
elementos (crea' ys) == ys
where ys = sort (nub xs)
-- Comprobación
-- λ> quickCheck prop_elementos_crea'
-- +++ OK, passed 100 tests.
-- Propiedad. Un elemento pertenece a (elementos a) syss es un valor de a.
prop_en_elementos :: Int -> ABB Int -> Bool
prop_en_elementos v a =
pertenece v a == elem v (elementos a)
-- Comprobación:
-- λ> quickCheck prop_en_elementos
-- +++ OK, passed 100 tests.
-- Propiedades de menor
-- --------------------
-- Propiedad. (menor a) es menor o igual que todos los elementos de ABB
-- a.
prop_menoresMinimo ::Int -> ABB Int -> Bool
prop_menoresMinimo _ a =
and [menor a <= v | v <- elementos a]
-- Comprobación.
-- λ> quickCheck prop_menoresMinimo
-- +++ OK, passed 100 tests.
-- ---------------------------------------------------------------------
-- § Verificación --
-- ---------------------------------------------------------------------
return []
verificaABB :: IO Bool
verificaABB = $quickCheckAll
-- La verificación es
-- λ> verificaABB
-- === prop_genABB_correcto from ArbolBinPropiedades.hs:44 ===
-- +++ OK, passed 100 tests.
--
-- === prop_listaOrdenada_correcta from ArbolBinPropiedades.hs:83 ===
-- +++ OK, passed 100 tests.
--
-- === prop_orderedList_correcta from ArbolBinPropiedades.hs:93 ===
-- +++ OK, passed 100 tests.
--
-- === prop_vacio_es_ABB from ArbolBinPropiedades.hs:109 ===
-- +++ OK, passed 1 test.
--
-- === prop_inserta_es_valida from ArbolBinPropiedades.hs:121 ===
-- +++ OK, passed 100 tests.
--
-- === prop_inserta_es_no_vacio from ArbolBinPropiedades.hs:131 ===
-- +++ OK, passed 100 tests.
--
-- === prop_elemento_de_inserta from ArbolBinPropiedades.hs:140 ===
-- +++ OK, passed 100 tests.
--
-- === prop_vacio_sin_elementos from ArbolBinPropiedades.hs:152 ===
-- +++ OK, passed 100 tests.
--
-- === prop_elementos_de_inserta from ArbolBinPropiedades.hs:162 ===
-- +++ OK, passed 100 tests.
--
-- === prop_elimina_es_valida from ArbolBinPropiedades.hs:174 ===
-- +++ OK, passed 100 tests.
--
-- === prop_elimina_agrega from ArbolBinPropiedades.hs:184 ===
-- +++ OK, passed 100 tests.
--
-- === prop_crea_es_valida from ArbolBinPropiedades.hs:196 ===
-- +++ OK, passed 100 tests.
--
-- === prop_crea'_es_valida from ArbolBinPropiedades.hs:209 ===
-- +++ OK, passed 100 tests.
--
-- === prop_elementos_crea from ArbolBinPropiedades.hs:222 ===
-- +++ OK, passed 100 tests.
--
-- === prop_elementos_crea' from ArbolBinPropiedades.hs:232 ===
-- +++ OK, passed 100 tests.
--
-- === prop_en_elementos from ArbolBinPropiedades.hs:242 ===
-- +++ OK, passed 100 tests.
--
-- === prop_menoresMinimo from ArbolBinPropiedades.hs:255 ===
-- +++ OK, passed 100 tests.
--
-- True
| jaalonso/I1M-Cod-Temas | src/Tema_19/ArbolBinPropiedades.hs | gpl-2.0 | 9,576 | 0 | 19 | 1,998 | 1,105 | 656 | 449 | 78 | 2 |
module Paths_HTF_tutorial (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
version :: Version
version = Version {versionBranch = [0,1], versionTags = []}
bindir, libdir, datadir, libexecdir :: FilePath
bindir = "/home/antoine/.cabal/bin"
libdir = "/home/antoine/.cabal/lib/HTF-tutorial-0.1/ghc-7.4.1"
datadir = "/home/antoine/.cabal/share/HTF-tutorial-0.1"
libexecdir = "/home/antoine/.cabal/libexec"
getBinDir, getLibDir, getDataDir, getLibexecDir :: IO FilePath
getBinDir = catchIO (getEnv "HTF_tutorial_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "HTF_tutorial_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "HTF_tutorial_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "HTF_tutorial_libexecdir") (\_ -> return libexecdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
| AntoineSavage/haskell | cabal_htf_tutorial/dist/build/autogen/Paths_HTF_tutorial.hs | gpl-2.0 | 1,158 | 0 | 10 | 164 | 323 | 184 | 139 | 25 | 1 |
-- Exercício 05: Faça uma função que calcule a soma dos dígitos de um número.
module Main where
sumDigits :: Integer -> Integer
sumDigits n = foldl (+) 0 (toDigits' n)
where
toDigits' x
| x < 10 = [x]
| otherwise = toDigits' (div x 10) ++ [mod x 10]
main :: IO ()
main = do
print(sumDigits 22) | danielgoncalvesti/BIGDATA2017 | Atividade01/Haskell/Activity1/Exercises2/Ex5.hs | gpl-3.0 | 332 | 0 | 11 | 92 | 119 | 60 | 59 | 9 | 1 |
module Sound.Tidal.Config where
{-
Config.hs - For default Tidal configuration values.
Copyright (C) 2020, Alex McLean and contributors
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this library. If not, see <http://www.gnu.org/licenses/>.
-}
data Config = Config {cCtrlListen :: Bool,
cCtrlAddr :: String,
cCtrlPort :: Int,
cCtrlBroadcast :: Bool,
cFrameTimespan :: Double,
cTempoAddr :: String,
cTempoPort :: Int,
cTempoClientPort :: Int,
cSkipTicks :: Int,
cVerbose :: Bool
}
defaultConfig :: Config
defaultConfig = Config {cCtrlListen = True,
cCtrlAddr ="127.0.0.1",
cCtrlPort = 6010,
cCtrlBroadcast = False,
cFrameTimespan = 1/20,
cTempoAddr = "127.0.0.1",
cTempoPort = 9160,
cTempoClientPort = 0, -- choose at random
cSkipTicks = 10,
cVerbose = True
}
| tidalcycles/Tidal | src/Sound/Tidal/Config.hs | gpl-3.0 | 1,776 | 0 | 8 | 707 | 154 | 101 | 53 | 22 | 1 |
module Cache where
import Data.Functor
import Data.Binary
import Data.Digest.Pure.SHA
import System.IO.Error
-- FIXME hardcoded cache directory
-- |Performs IO action via cache. If key is cached, then it is
-- returned from there. Otherwise the action is performed for
-- real. The cache is a flat directory where older objects may freely
-- be purged by hand.
viaCache :: (Show a, Binary a, Binary b) => (a -> IO b) -> a -> IO b
viaCache act key = do
mbHit <- lookup
putStrLn $ (maybe "MISS" (const "HIT") mbHit) ++ " " ++ show key
case mbHit of
Nothing -> do
value <- act key
store value
return value
Just hit -> return hit
where
hexKey = showDigest $ sha1 $ encode key
lookup = do
stored <- tryIOError $ decodeFile $ "cache/" ++ hexKey
case stored of
Left e -> if isDoesNotExistError e
then return Nothing
else ioError e
Right a -> return $ Just a
store value = encodeFile ("cache/" ++ hexKey) value
| zouppen/hsgeocoder | Cache.hs | gpl-3.0 | 1,018 | 0 | 13 | 281 | 288 | 143 | 145 | 24 | 4 |
module Paths_eksaktnaRealna (
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 {versionBranch = [0,1,0,0], versionTags = []}
bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "C:\\Users\\Bojan\\AppData\\Roaming\\cabal\\bin"
libdir = "C:\\Users\\Bojan\\AppData\\Roaming\\cabal\\x86_64-windows-ghc-7.8.3\\eksaktnaRealna-0.1.0.0"
datadir = "C:\\Users\\Bojan\\AppData\\Roaming\\cabal\\x86_64-windows-ghc-7.8.3\\eksaktnaRealna-0.1.0.0"
libexecdir = "C:\\Users\\Bojan\\AppData\\Roaming\\cabal\\eksaktnaRealna-0.1.0.0"
sysconfdir = "C:\\Users\\Bojan\\AppData\\Roaming\\cabal\\etc"
getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "eksaktnaRealna_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "eksaktnaRealna_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "eksaktnaRealna_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "eksaktnaRealna_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "eksaktnaRealna_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "\\" ++ name)
| aljosaVodopija/eksaktnaRealna | dist/build/autogen/Paths_eksaktnaRealna.hs | gpl-3.0 | 1,527 | 0 | 10 | 182 | 371 | 213 | 158 | 28 | 1 |
import FRP.Yampa
import SDL hiding (Event,initialize,delay)
import Sdl2
import Types
import IO
import StopWatch
import Bluefish
import Core
import Control.Monad
import Helper
import qualified Data.Text as Text
import Foreign.C.Types
import qualified Linear as L
import Linear.Affine
import qualified Text.Show.Pretty as Pr
import System.Random
import qualified SDL.Image as SDLI
import qualified Data.Map.Strict as Map
{-# LANGUAGE Arrows, BangPatterns #-}
initWindow =
defaultWindow
{ windowInitialSize = L.V2 (windowWidth) (windowHeight)
, windowMode = Windowed }
vsyncRendererConfig =
RendererConfig
{ rendererType = AcceleratedVSyncRenderer
, rendererTargetTexture = False
}
main = do
initializeAll
HintRenderScaleQuality $= ScaleLinear
renderQuality <- get HintRenderScaleQuality
when (renderQuality /= ScaleLinear) $
putStrLn "Warning: Linear texture filtering not enabled!"
window <- createWindow (Text.pack "aquarium 1.0") initWindow
rd <- createRenderer window (-1) defaultRenderer
rendererDrawColor rd $= L.V4 0 0 0 0
handle <- storeStopwatch
g <- getStdGen
f <- loadTexture rd "./images/fish_sheet.png"
sh <- loadTexture rd "./images/SeahorseSheet.png"
bsw <- loadTexture rd "./images/seaweed_test.png"
ssw <- loadTexture rd "./images/SeaweedNew.png"
bub <- loadTexture rd "./images/Bubbles.png"
she <- loadTexture rd "./images/Seashell.png"
{-
b1 <- loadTexture rd "./images/background.png"
b2 <- loadTexture rd "./images/smallBack.png"
b3 <- loadTexture rd "./images/smallMidRocks.png"
b4 <- loadTexture rd "./images/smallMidStones.png"
b5 <- loadTexture rd "./images/smallFrontGreenCoral.png"
f1 <- loadTexture rd "./images/smallFrontRedCoral.png"
let render = Rendering rd
(Map.fromList [(FishPic,f)
,(SmallSeaweedPic,ssw)
,(BigSeaweedPic,bsw)])
[(b1,(0,0)),(b2,(511,315)),(b3,(0,208))
,(b4,(0,538)),(b5,(802,90))]
[(f1,(0,307))]
-}
--{-
b1 <- loadTexture rd "./images/background.png"
b2 <- loadTexture rd "./images/Back2.png"
b3 <- loadTexture rd "./images/MidRocks3.png"
b4 <- loadTexture rd "./images/Midstones4.png"
b5 <- loadTexture rd "./images/FrontGreenCorals.png"
f1 <- loadTexture rd "./images/FrontRedCorals.png"
f2 <- loadTexture rd "./images/foreground.png"
let render = Rendering rd
(Map.fromList [(FishPic,f)
,(SmallSeaweedPic,ssw)
,(BigSeaweedPic,bsw)
,(SeaHorsePic,sh)
,(BubblePic,bub)
,(ShellPic,she)])
[(b1,(0,0)),(b2,(0,0))]
[(b3,(0,0))]
[(b4,(0,0))]
[(b5,(0,0))]
[(f1,(0,0))]
---}
reactimate initialize (sense handle) (actuate render) (process g)
destroyRenderer rd
destroyWindow window
quit
-------------------------------------------------------------------------
| eniac314/aquarium | src/main.hs | gpl-3.0 | 3,257 | 0 | 14 | 931 | 655 | 355 | 300 | -1 | -1 |
-- -*-haskell-*-
-- Vision (for the Voice): an XMMS2 client.
--
-- Author: Oleg Belozeorov
-- Created: 28 Jun. 2010
--
-- Copyright (C) 2010, 2011 Oleg Belozeorov
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License as
-- published by the Free Software Foundation; either version 3 of
-- the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- General Public License for more details.
--
module Location.UI
( setupUI
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Trans
import Control.Concurrent
import Control.Concurrent.STM
import Control.Concurrent.STM.TGVar
import Graphics.UI.Gtk hiding (add)
import UI
import Builder
import XMMS
import Utils
import Location.Model
import Location.View
import Location.Control
setupUI browse = do
setupActions browse
setupToolbar
setupLocationEntry
setupLocationView
setupConnection
setupActions browse = do
bindActions
[ ("new-window" , newWindow browse )
, ("open-location" , openLocation )
, ("load" , loadCurrentLocation )
, ("down" , loadAtCursor (loadLocation . Go))
, ("browse-in-new-window" , browseInNewWindow browse )
, ("add-to-playlist" , addToPlaylist )
, ("replace-playlist" , replacePlaylist )
, ("back" , loadLocation Back )
, ("forward" , loadLocation Forward )
, ("up" , loadLocation Up )
, ("refresh" , loadLocation Refresh )
]
down <- action "down"
binw <- action "browse-in-new-window"
addp <- action "add-to-playlist"
repp <- action "replace-playlist"
back <- action "back"
forward <- action "forward"
up <- action "up"
refresh <- action "refresh"
let updateB = do
rows <- treeSelectionGetSelectedRows locationSel
(enp, enn) <- case rows of
[] ->
return (False, False)
[path] -> do
item <- itemByPath path
return (True, iIsDir item)
_ ->
return (True, False)
mapM_ (`actionSetSensitive` enp) [addp, repp]
mapM_ (`actionSetSensitive` enn) [down, binw]
updateN = do
(eb, ef, eu, er) <- canGo
actionSetSensitive back eb
actionSetSensitive forward ef
actionSetSensitive up eu
actionSetSensitive refresh er
lW <- atomically $ newTGWatch location
forkIO $ forever $ do
void $ atomically $ watch lW
postGUISync $ do
updateN
updateWindowTitle
locationSel `onSelectionChanged` updateB
postGUIAsync updateB
return ()
setupToolbar = do
toolbar <- getObject castToToolbar "toolbar"
item <- separatorToolItemNew
separatorToolItemSetDraw item False
toolbarInsert toolbar item 4
item <- toolItemNew
toolItemSetHomogeneous item False
toolItemSetExpand item True
containerAdd item locationEntry
toolbarInsert toolbar item 5
item <- separatorToolItemNew
separatorToolItemSetDraw item False
toolbarInsert toolbar item 6
setupLocationEntry = do
load <- action "load"
locationEntry `onEntryActivate` actionActivate load
locationEntry `onIconPress` \icon ->
case icon of
PrimaryIcon -> entrySetText locationEntry ""
SecondaryIcon -> actionActivate load
return ()
setupLocationView = do
popup <- getWidget castToMenu "ui/location-popup"
setupTreeViewPopup locationView popup
down <- action "down"
locationView `onRowActivated` \_ _ ->
actionActivate down
binw <- action "browse-in-new-window"
locationView `on` buttonPressEvent $ tryEvent $ do
MiddleButton <- eventButton
SingleClick <- eventClick
(x, y) <- eventCoordinates
liftIO $ do
maybePath <- treeViewGetPathAtPos locationView (round x, round y)
case maybePath of
Just (path, _, _) -> do
treeViewSetCursor locationView path Nothing
actionActivate binw
Nothing ->
return ()
return ()
setupConnection = do
ag <- getObject castToActionGroup "server-actions"
xcW <- atomically $ newTGWatch connectedV
forkIO $ forever $ do
conn <- atomically $ watch xcW
actionGroupSetSensitive ag conn
locationEntry `set` [secondaryIconSensitive := conn]
loadCurrentLocation = do
text <- trim <$> entryGetText locationEntry
case text of
[] -> do
cur <- getCurrentLocation
case cur of
[] -> return ()
_ -> do
entrySetText locationEntry cur
widgetGrabFocus locationView
_ -> loadLocation . Go $ makeURL text
loadAtCursor func = do
(path, _) <- treeViewGetCursor locationView
case path of
[_] -> do
item <- itemByPath path
when (iIsDir item) $ func $ iPath item
_ ->
return ()
browseInNewWindow browse = do
order <- getSortOrder
loadAtCursor (browse order . Just)
newWindow browse = do
order <- getSortOrder
browse order Nothing
updateWindowTitle = do
loc <- getCurrentLocation
setWindowTitle $ case loc of
[] -> "Vision location browser"
_ -> loc ++ " - Vision location browser"
| upwawet/vision | src/Location/UI.hs | gpl-3.0 | 5,598 | 0 | 20 | 1,596 | 1,359 | 664 | 695 | 148 | 3 |
-- Author: Viacheslav Lotsmanov
-- License: GPLv3 https://raw.githubusercontent.com/unclechu/crop-detector/master/LICENSE
module Main where
-- import Debug.Hood.Observe (runO, observe)
import System.Environment (getArgs)
import Data.List (find, minimumBy)
import Data.List.Split (chunksOf)
import Data.Word (Word8)
import Data.Maybe (isJust, mapMaybe, fromJust)
import Control.Parallel.Strategies (withStrategy, parList, rpar)
import qualified Data.Array.Repa as R
import qualified Data.Array.Repa.IO.DevIL as IL
main :: IO ()
main = do
[ modeArg, thresholdArg, origF, cropF ] <- getArgs
(IL.RGB orig) <- IL.runIL $ IL.readImage origF
(IL.RGB crop) <- IL.runIL $ IL.readImage cropF
let (ow, oh) = imgSize orig
(cw, ch) = imgSize crop
threshold = fromIntegral (read thresholdArg) :: Float
mode = case modeArg of
"every-pixel" -> [EveryPixelMode]
"every-pixel-parallel" -> [ParallelMode, EveryPixelMode]
"perfect-every-pixel" -> [PerfectMode, EveryPixelMode]
"perfect-every-pixel-parallel" ->
[PerfectMode, ParallelMode, EveryPixelMode]
"average" -> [AverageMode]
"average-parallel" -> [ParallelMode, AverageMode]
"perfect-average" -> [PerfectMode, AverageMode]
"perfect-average-parallel" ->
[PerfectMode, ParallelMode, AverageMode]
_ -> error "Unknown mode"
if cw > ow || ch > oh
then error $ foldr1 (++)
[ "Cropped image can't have size more than original image.\n"
, "Original image size: ", show ow, "x", show oh, ".\n"
, "Cropped image size: ", show cw, "x", show ch, "."
]
else let pairRGB = (getRGBMatrix orig, getRGBMatrix crop)
foundCrop = findCropPos pairRGB (ow, oh) (cw, ch) mode threshold
in case foundCrop of
Nothing -> error "Cropped image not found in original image"
Just (x, y) ->
-- print crop parameters "x y w h"
putStrLn $ init
$ foldr (\v acc -> show v ++ " " ++ acc) ""
[ x, oh-ch-y, cw, ch ]
data RGBt = RGBt Word8 Word8 Word8 deriving (Show)
data Mode = EveryPixelMode
| AverageMode
| PerfectMode
| ParallelMode
deriving (Enum, Eq, Show)
imgSize x = (w, h)
where (R.Z R.:. h R.:. w R.:. _) = R.extent x
getRGBMatrix img = [ [ getRGB img x y | y <- ys ] | x <- xs ]
where getRGB img x y = RGBt (ch 0) (ch 1) (ch 2)
where ch n = img R.! (R.Z R.:. y R.:. x R.:. n)
(w, h) = imgSize img
xs = [0..(w-1)]
ys = [0..(h-1)]
getRGBDiff a b = (diff cR + diff cG + diff cB) / 3
where cR (RGBt x _ _) = fromIntegral x
cG (RGBt _ x _) = fromIntegral x
cB (RGBt _ _ x) = fromIntegral x
diff f = abs $ f a - f b
-- threshold should be 0..255
cropByThisPos (orig, crop) (cw, ch) mode threshold (x, y) =
case mode of
[EveryPixelMode] -> everyPixelResult
[ParallelMode, EveryPixelMode] -> everyPixelResult
-- perfect mode for every-pixel works like average mode,
-- but with checking for every pixel matching.
[PerfectMode, EveryPixelMode] -> everyPixelResult
[PerfectMode, ParallelMode, EveryPixelMode] -> everyPixelResult
[AverageMode] -> average
[ParallelMode, AverageMode] -> average
[PerfectMode, AverageMode] -> average
[PerfectMode, ParallelMode, AverageMode] -> average
_ -> error "This mode is unimplemented yet"
where xs = [0..(cw-1)]
ys = [0..(ch-1)]
average = if averagePixelsDiff <= threshold
then Just (x, y, averagePixelsDiff)
else Nothing
pixelsDiffs = [ diff mx my | my <- ys, mx <- xs ]
isEveryPixelHasLowDiff = all (<= threshold) pixelsDiffs
everyPixelResult =
if isEveryPixelHasLowDiff then Just result
else Nothing
where result = if PerfectMode `elem` mode
then (x, y, averagePixelsDiff)
else (0, 0, 0)
averagePixelsDiff = sum pixelsDiffs
/ fromIntegral (length pixelsDiffs)
diff mx my = getRGBDiff (orig !! (x+mx) !! (y+my))
(crop !! mx !! my )
-- threshold in percents
findCropPos (orig, crop) (ow, oh) (cw, ch) mode threshold = findIt
where posMatrix = [ (x, y) | x <- xs, y <- ys ]
where xs = [0..posXlimit]
ys = [0..posYlimit]
posXlimit = ow - cw - 1
posYlimit = oh - ch - 1
posTotalCount = (posXlimit + 1) * (posYlimit + 1)
finder = cropByThisPos (orig, crop) (cw, ch) mode threshold8bit
where threshold8bit = threshold * 255 / 100
findFirst = find doWeHaveCropHere posMatrix
where doWeHaveCropHere = hasCropByThisPos finder
hasCropByThisPos f (x, y) = isJust $ f (x, y)
findBest =
case matches of
[] -> Nothing
_ -> Just $ pos $ minimumBy cmpByDiff matches
where matches = mapMaybe finder list
list = if ParallelMode `elem` mode
then withStrategy (parList rpar) posMatrix
else posMatrix
pos (x, y, _) = (x, y)
cmpByDiff (_, _, a) (_, _, b) = compare a b
findIt =
case mode of
[AverageMode] -> findFirst
[ParallelMode, AverageMode] -> findFirst
[PerfectMode, AverageMode] -> findBest
[PerfectMode, ParallelMode, AverageMode] -> findBest
[EveryPixelMode] -> findFirst
[ParallelMode, EveryPixelMode] -> findFirst
[PerfectMode, EveryPixelMode] -> findBest
[PerfectMode, ParallelMode, EveryPixelMode] -> findBest
_ -> error "This mode is unimplemented yet"
| unclechu/crop-detector | src/Main.hs | gpl-3.0 | 6,520 | 0 | 19 | 2,487 | 1,813 | 1,002 | 811 | 122 | 12 |
{-# LANGUAGE OverloadedStrings, FlexibleContexts #-}
module Java2js.GenFun(compileMethod, compileConstant) where
--
import Java2js.Type
import Java2js.Mangle
import Java2js.JVM.Assembler
import Java2js.JVM.ClassFile
import Data.Int (Int16, Int8)
import Data.ByteString.Lazy.Char8 (unpack, ByteString)
import Data.Text.Template (template, render, substitute)
import Data.List (intercalate)
import Data.String.Utils (replace)
import qualified Data.Set as S
import qualified Data.Map.Strict as M
import qualified Data.Text as T
import qualified Data.Text.Lazy as L
returnsValue :: MethodSignature -> Bool
returnsValue (MethodSignature _ ReturnsVoid) = False
returnsValue (MethodSignature _ _) = True
encodeJavaScriptString x = foldl (\ m f -> f m) x $ fmap (uncurry replace) [("\\", "\\\\"), ("\"","\\\""), ("\n", "\\n"), ("\r", "\\r")]
compileConstant :: Constant Direct -> String
compileConstant (CString str) = "(Java.mkString(\"" ++ encodeJavaScriptString (unpack str) ++"\"))"
compileConstant (CDouble v) = "(" ++ show v ++")"
compileConstant (CInteger v) = "(" ++ show v ++")"
compileConstant (CFloat v) = "(" ++ show v ++")"
compileConstant (CLong v) = "Java.mkLong(\"" ++ show v ++"\")"
compileConstant (CDouble v) = "(" ++ show v ++")"
compileConstant (CClass kls) = "(Java.classObjectOf(" ++ show kls ++"))"
compileConstant v = error $ "(" ++ show v ++")"
popStacks :: [FieldType] -> (String, String)
popStacks [] = ("","[]")
popStacks fields = (foldl (++) "" $ fmap (uncurry pop) (reverse $ zip [0..] fields), "["++(foldl (++) "" $ fmap (\i -> "i"++show i++",") [0..(length fields)-1])++"]")
where
pop :: Int -> FieldType -> String
pop i LongInt = "var i"++show i++"=stack.pop();stack.pop();"
pop i DoubleType = "var i"++show i++"=stack.pop();stack.pop();"
pop i _ = "var i"++show i++"=stack.pop();"
pushRet :: ReturnSignature -> String
pushRet (Returns LongInt) = "stack.push(null);"
pushRet (Returns DoubleType) = "stack.push(null);"
pushRet _ = ""
showImm :: IMM -> String
showImm I0 = "0"
showImm I1 = "1"
showImm I2 = "2"
showImm I3 = "3"
showCmp C_LT a b = a++"<"++b
showCmp C_LE a b = a++"<="++b
showCmp C_GT a b = a++">"++b
showCmp C_GE a b = a++">="++b
showCmp C_EQ a b = a++"=="++b
showCmp C_NE a b = a++"!="++b
isWideField :: NameType (Field Direct) -> Bool
isWideField nt = isWide (ntSignature nt)
where
isWide LongInt = True
isWide DoubleType = True
isWide _ = False
---
compileInst :: Klass -> Int -> Instruction -> String
compileInst _ _ (BIPUSH w) = "stack.push("++show ((fromIntegral w) :: Int8)++");"
compileInst _ _ (SIPUSH w) = "stack.push("++show ((fromIntegral w) :: Int16)++");"
compileInst klass _ (LDC1 idx) = "stack.push("++compileConstant constant++");"
where
pool = constantPool klass
Just constant = M.lookup (fromIntegral idx) pool
compileInst klass _ (LDC2 idx) = "stack.push("++compileConstant constant++");"
where
pool = constantPool klass
Just constant = M.lookup (fromIntegral idx) pool
compileInst klass _ (LDC2W idx) = "stack.push(null); stack.push("++compileConstant constant++");"
where
pool = constantPool klass
Just constant = M.lookup (fromIntegral idx) pool
--
compileInst _ _ (ICONST_0) = "stack.push(0);"
compileInst _ _ (ICONST_1) = "stack.push(1);"
compileInst _ _ (ICONST_2) = "stack.push(2);"
compileInst _ _ (ICONST_3) = "stack.push(3);"
compileInst _ _ (ICONST_4) = "stack.push(4);"
compileInst _ _ (ICONST_5) = "stack.push(5);"
compileInst _ _ (ICONST_M1) = "stack.push(-1);"
compileInst _ _ (LCONST_0) = "stack.push(null);stack.push(Java.Long.ZERO);"
compileInst _ _ (LCONST_1) = "stack.push(null);stack.push(Java.Long.ONE);"
compileInst _ _ (FCONST_0) = "stack.push(0);"
compileInst _ _ (FCONST_1) = "stack.push(1);"
compileInst _ _ (FCONST_2) = "stack.push(2);"
compileInst _ _ (DCONST_0) = "stack.push(null);stack.push(0);"
compileInst _ _ (DCONST_1) = "stack.push(null);stack.push(1);"
compileInst _ _ (ACONST_NULL) = "stack.push(null);"
compileInst _ _ (POP) = "stack.pop();"
compileInst _ _ (POP2) = "stack.pop();"
compileInst _ _ (DUP) = "stack.push(stack[stack.length-1]);"
compileInst _ _ (DUP2) = "stack.push(stack[stack.length-2]);stack.push(stack[stack.length-2]);"
compileInst _ _ (DUP_X1) = concat
["stack.push(stack[stack.length-1]);"
,"stack[stack.length-2] = stack[stack.length-3];"
,"stack[stack.length-3] = stack[stack.length-1];"]
compileInst _ _ (DUP_X2) = concat
["stack.push(stack[stack.length-1]);"
,"stack[stack.length-2] = stack[stack.length-3];"
,"stack[stack.length-3] = stack[stack.length-4];"]
compileInst _ _ (DUP2_X1) = concat
["stack.push(stack[stack.length-2]);"
,"stack.push(stack[stack.length-2]);"
,"stack[stack.length-3] = stack[stack.length-5];"
,"stack[stack.length-5] = stack[stack.length-2];"
,"stack[stack.length-4] = stack[stack.length-1];"]
compileInst _ _ (DUP2_X2) = concat
["stack.push(stack[stack.length-2]);"
,"stack.push(stack[stack.length-2]);"
,"stack[stack.length-3] = stack[stack.length-5];"
,"stack[stack.length-3] = stack[stack.length-6];"
,"stack[stack.length-4] = stack[stack.length-1];"
,"stack[stack.length-5] = stack[stack.length-2];"]
compileInst _ _ (SWAP) = "var tmp = stack[stack.length-1]; stack[stack.length-1] = stack[stack.length-2]; stack[stack.length-2]=tmp;"
--
compileInst _ _ (ALOAD idx) = "stack.push(local["++show idx++"]);"
compileInst _ _ (ILOAD idx) = "stack.push(local["++show idx++"] || 0);"
compileInst _ _ (LLOAD idx) = "stack.push(null);stack.push(local["++show idx++"] || Java.Long.ZERO);"
compileInst _ _ (FLOAD idx) = "stack.push(local["++show idx++"] || 0);"
compileInst _ _ (DLOAD idx) = "stack.push(null);stack.push(local["++show idx++"] || 0);"
compileInst _ _ (ALOAD_W idx) = "stack.push(local["++show idx++"]);"
compileInst _ _ (ILOAD_W idx) = "stack.push(local["++show idx++"] || 0);"
compileInst _ _ (LLOAD_W idx) = "stack.push(null);stack.push(local["++show idx++"] || 0);"
compileInst _ _ (FLOAD_W idx) = "stack.push(local["++show idx++"] || 0);"
compileInst _ _ (DLOAD_W idx) = "stack.push(null);stack.push(local["++show idx++"] || Java.Long.ZERO);"
compileInst _ _ (ALOAD_ idx) = "stack.push(local["++showImm idx++"]);"
compileInst _ _ (ILOAD_ idx) = "stack.push(local["++showImm idx++"] || 0);"
compileInst _ _ (LLOAD_ idx) = "stack.push(null);stack.push(local["++showImm idx++"] || Java.Long.ZERO);"
compileInst _ _ (FLOAD_ idx) = "stack.push(local["++showImm idx++"] || 0);"
compileInst _ _ (DLOAD_ idx) = "stack.push(null);stack.push(local["++showImm idx++"] || 0);"
compileInst _ _ (ASTORE idx) = "local["++show idx++"]=stack.pop();"
compileInst _ _ (ISTORE idx) = "local["++show idx++"]=stack.pop();"
compileInst _ _ (LSTORE idx) = "local["++show idx++"]=stack.pop();stack.pop();"
compileInst _ _ (FSTORE idx) = "local["++show idx++"]=stack.pop();"
compileInst _ _ (DSTORE idx) = "local["++show idx++"]=stack.pop();stack.pop();"
compileInst _ _ (ASTORE_W idx) = "local["++show idx++"]=stack.pop();"
compileInst _ _ (ISTORE_W idx) = "local["++show idx++"]=stack.pop();"
compileInst _ _ (LSTORE_W idx) = "local["++show idx++"]=stack.pop();stack.pop();"
compileInst _ _ (FSTORE_W idx) = "local["++show idx++"]=stack.pop();"
compileInst _ _ (DSTORE_W idx) = "local["++show idx++"]=stack.pop();stack.pop();"
compileInst _ _ (ASTORE_ idx) = "local["++showImm idx++"]=stack.pop();"
compileInst _ _ (ISTORE_ idx) = "local["++showImm idx++"]=stack.pop();"
compileInst _ _ (LSTORE_ idx) = "local["++showImm idx++"]=stack.pop();stack.pop();"
compileInst _ _ (FSTORE_ idx) = "local["++showImm idx++"]=stack.pop();"
compileInst _ _ (DSTORE_ idx) = "local["++showImm idx++"]=stack.pop();stack.pop();"
compileInst _ _ (SALOAD) = "var a = stack.pop(); var b = stack.pop(); stack.push(b[a]);"
compileInst _ _ (SASTORE) = "var a = stack.pop(); var b = stack.pop(); var c = stack.pop(); c[b]=a;"
compileInst _ _ (BALOAD) = "var a = stack.pop(); var b = stack.pop(); stack.push(b[a]);"
compileInst _ _ (BASTORE) = "var a = stack.pop(); var b = stack.pop(); var c = stack.pop(); c[b]=a;"
compileInst _ _ (CALOAD) = "var a = stack.pop(); var b = stack.pop(); stack.push(b[a]);"
compileInst _ _ (CASTORE) = "var a = stack.pop(); var b = stack.pop(); var c = stack.pop(); c[b]=a;"
compileInst _ _ (IALOAD) = "var a = stack.pop(); var b = stack.pop(); stack.push(b[a]);"
compileInst _ _ (IASTORE) = "var a = stack.pop(); var b = stack.pop(); var c = stack.pop(); c[b]=a;"
compileInst _ _ (LALOAD) = "var a = stack.pop(); var b = stack.pop(); stack.push(null); stack.push(b[a]);"
compileInst _ _ (LASTORE) = "var a = stack.pop(); stack.pop(); var b = stack.pop(); var c = stack.pop(); c[b]=a;"
compileInst _ _ (DALOAD) = "var a = stack.pop(); var b = stack.pop(); stack.push(null); stack.push(b[a]);"
compileInst _ _ (DASTORE) = "var a = stack.pop(); stack.pop(); var b = stack.pop(); var c = stack.pop(); c[b]=a;"
compileInst _ _ (AALOAD) = "var a = stack.pop(); var b = stack.pop(); stack.push(b[a]);"
compileInst _ _ (AASTORE) = "var a = stack.pop(); var b = stack.pop(); var c = stack.pop(); c[b]=a;"
compileInst _ _ (ARRAYLENGTH) = "var a = stack.pop(); stack.push(a.length);"
---
compileInst _ _ (IINC localNum delta) = "local["++show localNum++"]+="++show delta++";"
compileInst _ _ (IINC_W localNum delta) = "local["++show localNum++"]+="++show delta++";"
compileInst _ _ (IADD) = "stack.push((stack.pop()+stack.pop())|0);"
compileInst _ _ (LADD) = "var a = stack.pop(); stack.pop(); var b = stack.pop(); stack.pop(); stack.push(null); stack.push(a.add(b));"
compileInst _ _ (FADD) = "stack.push(stack.pop()+stack.pop());"
compileInst _ _ (DADD) = "var a = stack.pop(); stack.pop(); var b = stack.pop(); stack.pop(); stack.push(null); stack.push(a+b);"
compileInst _ _ (IMUL) = "stack.push((stack.pop()*stack.pop())|0);"
compileInst _ _ (LMUL) = "var a = stack.pop(); stack.pop(); var b = stack.pop(); stack.pop(); stack.push(null); stack.push(a.multiply(b));"
compileInst _ _ (FMUL) = "stack.push(stack.pop()*stack.pop());"
compileInst _ _ (DMUL) = "var a = stack.pop(); stack.pop(); var b = stack.pop(); stack.pop(); stack.push(null); stack.push(a*b);"
compileInst _ _ (ISUB) = "var a = stack.pop(); var b = stack.pop(); stack.push((b-a)|0);"
compileInst _ _ (LSUB) = "var a = stack.pop(); stack.pop(); var b = stack.pop(); stack.pop(); stack.push(null); stack.push(b.subtract(a));"
compileInst _ _ (FSUB) = "var a = stack.pop(); var b = stack.pop(); stack.push(b-a);"
compileInst _ _ (DSUB) = "var a = stack.pop(); stack.pop(); var b = stack.pop(); stack.pop(); stack.push(null); stack.push(b-a);"
compileInst _ _ (IDIV) = "var b = stack.pop(); var a = stack.pop(); stack.push((a/b) | 0);"
compileInst _ _ (LDIV) = "var b = stack.pop(); stack.pop(); var a = stack.pop(); stack.pop(); stack.push(null); stack.push(a.divide(b));"
compileInst _ _ (FDIV) = "var b = stack.pop(); var a = stack.pop(); stack.push(a/b);"
compileInst _ _ (DDIV) = "var b = stack.pop(); stack.pop(); var a = stack.pop(); stack.pop(); stack.push(null); stack.push(a/b);"
compileInst _ _ (IREM) = "var b = stack.pop(); var a = stack.pop(); stack.push(a-((a/b) | 0)*b);"
compileInst _ _ (LREM) = "var b = stack.pop(); stack.pop(); var a = stack.pop(); stack.pop(); stack.push(null); stack.push(a.remainder(b));"
compileInst _ _ (FREM) = "var b = stack.pop(); var a = stack.pop(); stack.push(a-(Math.floor(a/b))*b);"
compileInst _ _ (DREM) = "var b = stack.pop(); stack.pop(); var a = stack.pop(); stack.pop(); stack.push(null); stack.push(a-Math.floor(a/b)*b);"
compileInst _ _ (INEG) = "stack.push(-stack.pop());"
compileInst _ _ (LNEG) = "stack.push(stack.pop().negate());"
compileInst _ _ (FNEG) = "stack.push(-stack.pop());"
compileInst _ _ (DNEG) = "stack.push(-stack.pop());"
compileInst _ _ (IOR) = "stack.push(stack.pop() | stack.pop());"
compileInst _ _ (IAND) = "stack.push(stack.pop() & stack.pop());"
compileInst _ _ (IXOR) = "stack.push(stack.pop() ^ stack.pop());"
compileInst _ _ (IUSHR) = "var a = stack.pop(); var b = stack.pop(); stack.push(b >>> a);"
compileInst _ _ (ISHR) = "var a = stack.pop(); var b = stack.pop(); stack.push(b >> a);"
compileInst _ _ (ISHL) = "var a = stack.pop(); var b = stack.pop(); stack.push((b << a)|0);"
compileInst _ _ (LOR) = "var a = stack.pop(); stack.pop(); var b = stack.pop(); stack.pop(); stack.push(null); stack.push(a.or(b));"
compileInst _ _ (LAND) = "var a = stack.pop(); stack.pop(); var b = stack.pop(); stack.pop(); stack.push(null); stack.push(a.and(b));"
compileInst _ _ (LXOR) = "var a = stack.pop(); stack.pop(); var b = stack.pop(); stack.pop(); stack.push(null); stack.push(a.xor(b));"
compileInst _ _ (LUSHR) = "var a = stack.pop(); var b = stack.pop(); stack.pop(); stack.push(null); stack.push(b.and(Java.Long.Mask).shiftRight(a));"
compileInst _ _ (LSHR) = "var a = stack.pop(); var b = stack.pop(); stack.pop(); stack.push(null); stack.push(b.shiftRight(a));"
compileInst _ _ (LSHL) = "var a = stack.pop(); var b = stack.pop(); stack.pop(); stack.push(null); stack.push(b.shiftLeft(a).and(Java.Long.MASK));"
---
compileInst _ _ (I2D) = "var a = stack.pop(); stack.push(null); stack.push(a);"
compileInst _ _ (I2C) = "var a = stack.pop(); stack.push(a&0xffff);"
compileInst _ _ (I2F) = ""
compileInst _ _ (I2B) = "var a = stack.pop(); stack.push(a&0xffff);"
compileInst _ _ (I2S) = "var a = stack.pop(); stack.push(a&0xff);"
compileInst _ _ (I2L) = "var a = stack.pop(); stack.push(null); stack.push(Java.mkLong(a));"
compileInst _ _ (L2I) = "var a = stack.pop(); stack.pop(); stack.push(a.intValue());"
compileInst _ _ (L2F) = "var a = stack.pop(); stack.pop(); stack.push(a.floatValue());"
compileInst _ _ (L2D) = "var a = stack.pop(); stack.pop(); stack.push(null); stack.push(a.doubleValue());"
compileInst _ _ (F2L) = "var a = stack.pop(); stack.push(null); stack.push(Java.mkLong(a | 0));"
compileInst _ _ (F2D) = "var a = stack.pop(); stack.push(null); stack.push(a);"
compileInst _ _ (F2I) = "stack[stack.length-1] |= 0;"
compileInst _ _ (D2I) = "var a = stack.pop(); stack.pop(); stack.push(a & 0xffffffff);"
compileInst _ _ (D2F) = "var a = stack.pop(); stack.pop(); stack.push(a);"
compileInst _ _ (D2L) = "stack[stack.length-1] = stack.push(Java.mkLongFromDouble(stack[stack.length-1]));"
--
---FIXME: 型注釈入れないと共変・反変のチェックできない
compileInst _ _ (ANEWARRAY _) = "stack.push(Java.makeAAray(stack.pop()));"
compileInst _ _ (NEWARRAY _) = "stack.push(new Array(stack.pop()));"
compileInst _ _ (ATHROW) = "throw (stack.pop());"
compileInst _ _ (GOTO x) = "pc += "++show x++"; break;"
compileInst _ _ (GOTO_W x) = "pc += "++show x++"; break;"
compileInst _ _ (JSR x) = "stack.push(pc+3); pc += "++show x++"; break;"
compileInst _ _ (JSR_W x) = "stack.push(pc+5); pc += "++show x++"; break;"
compileInst _ _ (RET x) = "pc = pc=local["++show x++"]; break;"
compileInst _ _ (DCMP C_LT) = "var a = stack.pop(); stack.pop(); var b = stack.pop(); stack.pop(); if(b > a){stack.push(1);}else if(b < a){stack.push(-1);}else if(a==b){ stack.push(0); }else{ stack.push(1); }"
compileInst _ _ (DCMP C_GT) = "var a = stack.pop(); stack.pop(); var b = stack.pop(); stack.pop(); if(b > a){stack.push(1);}else if(b < a){stack.push(-1);}else if(a==b){ stack.push(0); }else{ stack.push(-1); }"
compileInst _ _ (LCMP) = "var a = stack.pop(); stack.pop(); var b = stack.pop(); stack.pop(); stack.push(-a.compareTo(b));"
compileInst _ _ (IF cmp x) = "var a = stack.pop(); if("++showCmp cmp "a" "0"++"){pc += "++show x++"; break;}"
compileInst _ _ (IF_ICMP cmp x) = "var a = stack.pop(); var b = stack.pop(); if("++showCmp cmp "b" "a"++"){pc += "++show x++"; break;}"
compileInst _ _ (IF_ACMP C_EQ x) = "var a = stack.pop(); var b = stack.pop(); if(a === b){pc += "++show x++"; break;}"
compileInst _ _ (IF_ACMP C_NE x) = "var a = stack.pop(); var b = stack.pop(); if(a !== b){pc += "++show x++"; break;}"
compileInst _ _ (IFNONNULL off) = "if(stack.pop() !== null){pc += "++show off++"; break;}"
compileInst _ _ (IFNULL off) = "if(stack.pop() === null){pc += "++show off++"; break;}"
compileInst _ _ (TABLESWITCH def low high offs) =
L.unpack $ substitute (T.pack "var a = stack.pop(); if (a < (${low}) || a > (${high})) { pc += ${def};break; }else{ pc+=(${offs})[a-(${low})];break; }") ctx
where
ctx "low" = T.pack (show low)
ctx "def" = T.pack (show def)
ctx "high" = T.pack (show high)
ctx "offs" = T.pack (show offs)
compileInst _ _ (LOOKUPSWITCH def _ offs) =
L.unpack $ substitute (T.pack "var a = stack.pop(); switch(a){ ${offs} default: pc += ${def};break; }; break;") ctx
where
ctx "def" = T.pack (show def)
ctx "offs" = T.pack $ foldl (\ b (v,off) -> b ++ "case "++show v++": pc += "++show off++"; break;") "" offs
---
compileInst klass _ (PUTSTATIC idx) = "Java[\""++klsName++"\"]()[\""++fldName++"\"] = stack.pop();" ++ pops
where
pool = constantPool klass
Just constant = M.lookup idx pool
CField kls nt = constant
klsName = unpack kls
fldName = unpack (ntName nt)
pops = if isWideField (nt) then "stack.pop();" else ""
compileInst klass _ (GETSTATIC idx) = pushs++"stack.push(Java[\""++klsName++"\"]()[\""++fldName++"\"]);"
where
pool = constantPool klass
Just constant = M.lookup idx pool
CField kls nt = constant
klsName = unpack kls
fldName = unpack (ntName nt)
pushs = if isWideField (nt) then "stack.push(null);" else ""
--
compileInst klass _ (PUTFIELD idx) = "var a = stack.pop();"++ pops ++ "var self = stack.pop(); self[\""++fldName++"\"] = a;"
where
pool = constantPool klass
Just constant = M.lookup idx pool
CField kls nt = constant
fldName = unpack (ntName nt)
pops = if isWideField (nt) then "stack.pop();" else ""
compileInst klass _ (GETFIELD idx) = concat ["var self = stack.pop();",pushs,"stack.push(self[\"",fldName,"\"]);"]
where
pool = constantPool klass
Just constant = M.lookup idx pool
CField kls nt = constant
fldName = unpack (ntName nt)
pushs = if isWideField (nt) then "stack.push(null);" else ""
compileInst klass _ (NEW idx) = "stack.push(new (Java[\""++klsName++"\"]())());"
where
pool = constantPool klass
Just constant = M.lookup idx pool
CClass kls = constant
klsName = unpack kls
compileInst klass _ (INVOKEVIRTUAL idx) =
pops++"var self = stack.pop(); "++pushRet mret++
if returns then "stack.push(self[\""++fldName++"\"].apply(self, "++args++"));"
else "self[\""++fldName++"\"].apply(self, "++args++");"
where
pool = constantPool klass
Just constant = M.lookup idx pool
MethodSignature margs mret = ntSignature nt
returns = returnsValue (ntSignature nt)
(pops, args) = popStacks (margs)
CMethod _ nt = constant
fldName = mangleMethod nt
compileInst klass _ (INVOKEINTERFACE idx _) =
pops++"var self = stack.pop(); "++pushRet mret++
if returns then "stack.push(self[\""++fldName++"\"].apply(self, "++args++"));"
else "self[\""++fldName++"\"].apply(self, "++args++");"
where
pool = constantPool klass
Just constant = M.lookup idx pool
MethodSignature margs mret = ntSignature nt
returns = returnsValue (ntSignature nt)
(pops, args) = popStacks (margs)
CIfaceMethod _ nt = constant
fldName = mangleMethod nt
compileInst klass _ (INVOKESPECIAL idx) =
pops++"var self = stack.pop(); "++pushRet mret++
if returns then "stack.push(Java[\""++klsName++"\"]().prototype[\""++fldName++"\"].apply(self, "++args++"));"
else "Java[\""++klsName++"\"]().prototype[\""++fldName++"\"].apply(self, "++args++");"
where
pool = constantPool klass
Just constant = M.lookup idx pool
MethodSignature margs mret = ntSignature nt
returns = returnsValue (ntSignature nt)
(pops, args) = popStacks (margs)
CMethod kls nt = constant
klsName = unpack kls
fldName = mangleMethod nt
compileInst klass _ (INVOKESTATIC idx) =
pops++pushRet mret++
if returns then "stack.push(Java[\""++klsName++"\"]()[\""++fldName++"\"].apply(null, "++args++"));"
else "Java[\""++klsName++"\"]()[\""++fldName++"\"].apply(null, "++args++");"
where
pool = constantPool klass
Just constant = M.lookup idx pool
MethodSignature margs mret = ntSignature nt
returns = returnsValue (ntSignature nt)
(pops, args) = popStacks (margs)
CMethod kls nt = constant
klsName = unpack kls
fldName = mangleMethod nt
--
compileInst klass _ (CHECKCAST idx) = "Java.checkCast(\""++klsName++"\", stack[stack.length-1]);"
where
pool = constantPool klass
Just constant = M.lookup idx pool
CClass kls = constant
klsName = unpack kls
compileInst klass _ (INSTANCEOF idx) = "stack.push(Java.instanceOf(\""++klsName++"\", stack.pop()));"
where
pool = constantPool klass
Just constant = M.lookup idx pool
CClass kls = constant
klsName = unpack kls
compileInst _ _ IRETURN = "return stack.pop();"
compileInst _ _ LRETURN = "return stack.pop();"
compileInst _ _ FRETURN = "return stack.pop();"
compileInst _ _ DRETURN = "return stack.pop();"
compileInst _ _ ARETURN = "return stack.pop();"
compileInst _ _ RETURN = "return;"
compileInst _ _ MONITORENTER = "throw 'MonitorEnter';"
compileInst _ _ MONITOREXIT = "throw 'MonitorExit';"
compileInst _ _ code = error(show code)
---
methodTemplate = template "\
\function(){\n\
\\tvar stack = [];\n\
\\tvar local=new Array(${locals});\n\
\\t${argbinding}\n\
\\tvar pc=0;\n\
\\twhile(true){\n\
\\t\ttry{\n\
\\t\tswitch(pc){\n\
\${body}\n\
\\t\t}}catch(e){\n\
\\t\t\t stack.push(e);\n\
\${exceptions}\
\\t\t\t throw e;\n\
\\t\t}\n\
\\t}\n\
\}\
\"
compileArgumentBind (MethodSignature args _) isStatic =
if isStatic then loop args 0 0
else "local[0]=this;"++loop args 1 0
where
loop [] _ _ = ""
loop (LongInt:args) aidx idx = "local["++show aidx++"] = arguments["++show idx++"];"++(loop args (aidx+2) (idx+1))
loop (DoubleType:args) aidx idx = "local["++show aidx++"] = arguments["++show idx++"];"++(loop args (aidx+2) (idx+1))
loop (_:args) aidx idx = "local["++show aidx++"] = arguments["++show idx++"];"++(loop args (aidx+1) (idx+1))
compileExceptionHandler :: Klass -> Code -> T.Text
compileExceptionHandler klass code = L.toStrict $ L.concat handlers
where
handlers = fmap makeHandler (codeExceptions code)
pool = constantPool klass
makeHandler (CodeException beg end to clsIdx) = substitute "\t\t\tif(${from} <= pc && pc <= ${to} && ${cond}){ pc = ${next}; continue; }\n" ctx
where
target = (M.lookup clsIdx pool) :: Maybe (Constant Direct)
makeCond Nothing = T.concat ["Java.instanceOf(\"java/lang/Object\",e)"]
makeCond (Just (CClass name)) = T.concat ["Java.instanceOf(",T.pack (show name),",e)"]
makeCond x = error $ show $ x
ctx "from" = T.pack (show beg)
ctx "to" = T.pack (show end)
ctx "next" = T.pack (show to)
ctx "cond" = makeCond target
compileMethod :: Klass -> (Method Direct, Maybe Code) -> String
compileMethod _ (_, Nothing) = "null";
compileMethod klass (meth, (Just code)) = L.unpack $ render methodTemplate ctx
where
ctx "exceptions" = compileExceptionHandler klass code
ctx "argbinding" = T.pack $ compileArgumentBind (methodSignature meth) (S.member ACC_STATIC (methodAccessFlags meth))
ctx "locals" = T.pack $ show (codeMaxLocals code)
ctx "body" = T.pack $ (intercalate "\n" (fmap (\(addr,inst) -> "\t\t\tcase "++show addr++": pc = "++show addr++"; /* "++(show inst)++" */ "++compileInst klass addr inst) (codeInstructions code)))
| ledyba/java.js | lib/Java2js/GenFun.hs | gpl-3.0 | 23,815 | 46 | 21 | 3,918 | 6,629 | 3,369 | 3,260 | 357 | 13 |
{-# 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.Blogger.Posts.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a list of posts, possibly filtered.
--
-- /See:/ <https://developers.google.com/blogger/docs/3.0/getting_started Blogger API Reference> for @blogger.posts.list@.
module Network.Google.Resource.Blogger.Posts.List
(
-- * REST Resource
PostsListResource
-- * Creating a Request
, postsList
, PostsList
-- * Request Lenses
, pllStatus
, pllOrderBy
, pllFetchImages
, pllEndDate
, pllBlogId
, pllStartDate
, pllFetchBodies
, pllView
, pllLabels
, pllPageToken
, pllMaxResults
) where
import Network.Google.Blogger.Types
import Network.Google.Prelude
-- | A resource alias for @blogger.posts.list@ method which the
-- 'PostsList' request conforms to.
type PostsListResource =
"blogger" :>
"v3" :>
"blogs" :>
Capture "blogId" Text :>
"posts" :>
QueryParams "status" PostsListStatus :>
QueryParam "orderBy" PostsListOrderBy :>
QueryParam "fetchImages" Bool :>
QueryParam "endDate" DateTime' :>
QueryParam "startDate" DateTime' :>
QueryParam "fetchBodies" Bool :>
QueryParam "view" PostsListView :>
QueryParam "labels" Text :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] PostList
-- | Retrieves a list of posts, possibly filtered.
--
-- /See:/ 'postsList' smart constructor.
data PostsList = PostsList'
{ _pllStatus :: !(Maybe [PostsListStatus])
, _pllOrderBy :: !PostsListOrderBy
, _pllFetchImages :: !(Maybe Bool)
, _pllEndDate :: !(Maybe DateTime')
, _pllBlogId :: !Text
, _pllStartDate :: !(Maybe DateTime')
, _pllFetchBodies :: !Bool
, _pllView :: !(Maybe PostsListView)
, _pllLabels :: !(Maybe Text)
, _pllPageToken :: !(Maybe Text)
, _pllMaxResults :: !(Maybe (Textual Word32))
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'PostsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pllStatus'
--
-- * 'pllOrderBy'
--
-- * 'pllFetchImages'
--
-- * 'pllEndDate'
--
-- * 'pllBlogId'
--
-- * 'pllStartDate'
--
-- * 'pllFetchBodies'
--
-- * 'pllView'
--
-- * 'pllLabels'
--
-- * 'pllPageToken'
--
-- * 'pllMaxResults'
postsList
:: Text -- ^ 'pllBlogId'
-> PostsList
postsList pPllBlogId_ =
PostsList'
{ _pllStatus = Nothing
, _pllOrderBy = Published
, _pllFetchImages = Nothing
, _pllEndDate = Nothing
, _pllBlogId = pPllBlogId_
, _pllStartDate = Nothing
, _pllFetchBodies = True
, _pllView = Nothing
, _pllLabels = Nothing
, _pllPageToken = Nothing
, _pllMaxResults = Nothing
}
-- | Statuses to include in the results.
pllStatus :: Lens' PostsList [PostsListStatus]
pllStatus
= lens _pllStatus (\ s a -> s{_pllStatus = a}) .
_Default
. _Coerce
-- | Sort search results
pllOrderBy :: Lens' PostsList PostsListOrderBy
pllOrderBy
= lens _pllOrderBy (\ s a -> s{_pllOrderBy = a})
-- | Whether image URL metadata for each post is included.
pllFetchImages :: Lens' PostsList (Maybe Bool)
pllFetchImages
= lens _pllFetchImages
(\ s a -> s{_pllFetchImages = a})
-- | Latest post date to fetch, a date-time with RFC 3339 formatting.
pllEndDate :: Lens' PostsList (Maybe UTCTime)
pllEndDate
= lens _pllEndDate (\ s a -> s{_pllEndDate = a}) .
mapping _DateTime
-- | ID of the blog to fetch posts from.
pllBlogId :: Lens' PostsList Text
pllBlogId
= lens _pllBlogId (\ s a -> s{_pllBlogId = a})
-- | Earliest post date to fetch, a date-time with RFC 3339 formatting.
pllStartDate :: Lens' PostsList (Maybe UTCTime)
pllStartDate
= lens _pllStartDate (\ s a -> s{_pllStartDate = a})
. mapping _DateTime
-- | Whether the body content of posts is included (default: true). This
-- should be set to false when the post bodies are not required, to help
-- minimize traffic.
pllFetchBodies :: Lens' PostsList Bool
pllFetchBodies
= lens _pllFetchBodies
(\ s a -> s{_pllFetchBodies = a})
-- | Access level with which to view the returned result. Note that some
-- fields require escalated access.
pllView :: Lens' PostsList (Maybe PostsListView)
pllView = lens _pllView (\ s a -> s{_pllView = a})
-- | Comma-separated list of labels to search for.
pllLabels :: Lens' PostsList (Maybe Text)
pllLabels
= lens _pllLabels (\ s a -> s{_pllLabels = a})
-- | Continuation token if the request is paged.
pllPageToken :: Lens' PostsList (Maybe Text)
pllPageToken
= lens _pllPageToken (\ s a -> s{_pllPageToken = a})
-- | Maximum number of posts to fetch.
pllMaxResults :: Lens' PostsList (Maybe Word32)
pllMaxResults
= lens _pllMaxResults
(\ s a -> s{_pllMaxResults = a})
. mapping _Coerce
instance GoogleRequest PostsList where
type Rs PostsList = PostList
type Scopes PostsList =
'["https://www.googleapis.com/auth/blogger",
"https://www.googleapis.com/auth/blogger.readonly"]
requestClient PostsList'{..}
= go _pllBlogId (_pllStatus ^. _Default)
(Just _pllOrderBy)
_pllFetchImages
_pllEndDate
_pllStartDate
(Just _pllFetchBodies)
_pllView
_pllLabels
_pllPageToken
_pllMaxResults
(Just AltJSON)
bloggerService
where go
= buildClient (Proxy :: Proxy PostsListResource)
mempty
| rueshyna/gogol | gogol-blogger/gen/Network/Google/Resource/Blogger/Posts/List.hs | mpl-2.0 | 6,647 | 0 | 23 | 1,819 | 1,148 | 659 | 489 | 160 | 1 |
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Small layer on top of @fast-logger@ which adds log-levels and
-- timestamp support and not much more.
module System.Logger
( -- * Settings
Settings
, defSettings
, logLevel
, setLogLevel
, logLevelOf
, setLogLevelOf
, output
, setOutput
, format
, setFormat
, delimiter
, setDelimiter
, netstrings
, setNetStrings
, bufSize
, setBufSize
, name
, setName
-- * Type definitions
, Logger
, Level (..)
, Output (..)
, DateFormat (..)
, iso8601UTC
-- * Core API
, new
, create
, level
, flush
, close
, clone
, settings
-- ** Logging
, log
, trace
, debug
, info
, warn
, err
, fatal
, module M
) where
import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.UnixTime
import System.Environment (lookupEnv)
import System.Logger.Message as M
import System.Logger.Settings
import Prelude hiding (log)
import qualified Data.Map.Strict as Map
import qualified System.Log.FastLogger as FL
data Logger = Logger
{ logger :: FL.LoggerSet
, settings :: Settings
, getDate :: IO (Msg -> Msg)
}
-- | Create a new 'Logger' with the given 'Settings'.
-- Please note that the 'logLevel' can be dynamically adjusted by setting
-- the environment variable @LOG_LEVEL@ accordingly. Likewise the buffer
-- size can be dynamically set via @LOG_BUFFER@ and netstrings encoding
-- can be enabled with @LOG_NETSTR=True@
--
-- Since version 0.11 one can also use @LOG_LEVEL_MAP@ to specify log
-- levels per (named) logger. The syntax uses standard haskell syntax for
-- association lists of type @[(Text, Level)]@. For example:
--
-- @
-- $ LOG_LEVEL=Info LOG_LEVEL_MAP='[("foo", Warn), ("bar", Trace)]' cabal repl
-- > g1 <- new defSettings
-- > let g2 = clone (Just "foo") g
-- > let g3 = clone (Just "bar") g
-- > let g4 = clone (Just "xxx") g
-- > logLevel (settings g1)
-- Info
-- > logLevel (settings g2)
-- Warn
-- > logLevel (settings g3)
-- Trace
-- > logLevel (settings g4)
-- Info
-- @
new :: MonadIO m => Settings -> m Logger
new s = liftIO $ do
!n <- fmap (readNote "Invalid LOG_BUFFER") <$> lookupEnv "LOG_BUFFER"
!l <- fmap (readNote "Invalid LOG_LEVEL") <$> lookupEnv "LOG_LEVEL"
!e <- fmap (readNote "Invalid LOG_NETSTR") <$> lookupEnv "LOG_NETSTR"
!m <- fromMaybe "[]" <$> lookupEnv "LOG_LEVEL_MAP"
let !k = logLevelMap s `mergeWith` m
let !s' = setLogLevel (fromMaybe (logLevel s) l)
. setNetStrings (fromMaybe (netstrings s) e)
. setLogLevelMap k
$ s
g <- fn (output s) (fromMaybe (bufSize s) n)
Logger g s' <$> mkGetDate (format s)
where
fn StdOut = FL.newStdoutLoggerSet
fn StdErr = FL.newStderrLoggerSet
fn (Path p) = flip FL.newFileLoggerSet p
mkGetDate Nothing = return (return id)
mkGetDate (Just f) = return (msg . (display f) <$> getUnixTime)
mergeWith m e = Map.fromList (readNote "Invalid LOG_LEVEL_MAP" e) `Map.union` m
-- | Invokes 'new' with default settings and the given output as log sink.
create :: MonadIO m => Output -> m Logger
create o = new $ setOutput o defSettings
readNote :: Read a => String -> String -> a
readNote m s = case reads s of
[(a, "")] -> a
_ -> error m
-- | Logs a message with the given level if greater or equal to the
-- logger's threshold.
log :: MonadIO m => Logger -> Level -> (Msg -> Msg) -> m ()
log g l m = unless (level g > l) . liftIO $ putMsg g l m
{-# INLINE log #-}
-- | Abbreviation of 'log' using the corresponding log level.
trace, debug, info, warn, err, fatal :: MonadIO m => Logger -> (Msg -> Msg) -> m ()
trace g = log g Trace
debug g = log g Debug
info g = log g Info
warn g = log g Warn
err g = log g Error
fatal g = log g Fatal
{-# INLINE trace #-}
{-# INLINE debug #-}
{-# INLINE info #-}
{-# INLINE warn #-}
{-# INLINE err #-}
{-# INLINE fatal #-}
-- | Clone the given logger and optionally give it a name
-- (use @Nothing@ to clear).
--
-- If 'logLevelOf' returns a custom 'Level' for this name
-- then the cloned logger will use it for its log messages.
clone :: Maybe Text -> Logger -> Logger
clone Nothing g = g { settings = setName Nothing (settings g) }
clone (Just n) g =
let s = settings g
l = fromMaybe (logLevel s) $ logLevelOf n s
in g { settings = setName (Just n) . setLogLevel l $ s }
-- | Force buffered bytes to output sink.
flush :: MonadIO m => Logger -> m ()
flush = liftIO . FL.flushLogStr . logger
-- | Closes the logger.
close :: MonadIO m => Logger -> m ()
close g = liftIO $ FL.rmLoggerSet (logger g)
-- | Inspect this logger's threshold.
level :: Logger -> Level
level = logLevel . settings
{-# INLINE level #-}
putMsg :: MonadIO m => Logger -> Level -> (Msg -> Msg) -> m ()
putMsg g l f = liftIO $ do
d <- getDate g
let n = netstrings $ settings g
let x = delimiter $ settings g
let s = nameMsg $ settings g
let m = render x n (d . lmsg l . s . f)
FL.pushLogStr (logger g) (FL.toLogStr m)
lmsg :: Level -> (Msg -> Msg)
lmsg Trace = msg (val "T")
lmsg Debug = msg (val "D")
lmsg Info = msg (val "I")
lmsg Warn = msg (val "W")
lmsg Error = msg (val "E")
lmsg Fatal = msg (val "F")
{-# INLINE lmsg #-}
| twittner/tinylog | src/System/Logger.hs | mpl-2.0 | 5,658 | 0 | 18 | 1,400 | 1,506 | 800 | 706 | 128 | 4 |
{-# 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.Logging.Projects.Locations.Operations.Cancel
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Starts asynchronous cancellation on a long-running operation. The server
-- makes a best effort to cancel the operation, but success is not
-- guaranteed. If the server doesn\'t support this method, it returns
-- google.rpc.Code.UNIMPLEMENTED. Clients can use Operations.GetOperation
-- or other methods to check whether the cancellation succeeded or whether
-- the operation completed despite cancellation. On successful
-- cancellation, the operation is not deleted; instead, it becomes an
-- operation with an Operation.error value with a google.rpc.Status.code of
-- 1, corresponding to Code.CANCELLED.
--
-- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.projects.locations.operations.cancel@.
module Network.Google.Resource.Logging.Projects.Locations.Operations.Cancel
(
-- * REST Resource
ProjectsLocationsOperationsCancelResource
-- * Creating a Request
, projectsLocationsOperationsCancel
, ProjectsLocationsOperationsCancel
-- * Request Lenses
, plocXgafv
, plocUploadProtocol
, plocAccessToken
, plocUploadType
, plocPayload
, plocName
, plocCallback
) where
import Network.Google.Logging.Types
import Network.Google.Prelude
-- | A resource alias for @logging.projects.locations.operations.cancel@ method which the
-- 'ProjectsLocationsOperationsCancel' request conforms to.
type ProjectsLocationsOperationsCancelResource =
"v2" :>
CaptureMode "name" "cancel" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] CancelOperationRequest :>
Post '[JSON] Empty
-- | Starts asynchronous cancellation on a long-running operation. The server
-- makes a best effort to cancel the operation, but success is not
-- guaranteed. If the server doesn\'t support this method, it returns
-- google.rpc.Code.UNIMPLEMENTED. Clients can use Operations.GetOperation
-- or other methods to check whether the cancellation succeeded or whether
-- the operation completed despite cancellation. On successful
-- cancellation, the operation is not deleted; instead, it becomes an
-- operation with an Operation.error value with a google.rpc.Status.code of
-- 1, corresponding to Code.CANCELLED.
--
-- /See:/ 'projectsLocationsOperationsCancel' smart constructor.
data ProjectsLocationsOperationsCancel =
ProjectsLocationsOperationsCancel'
{ _plocXgafv :: !(Maybe Xgafv)
, _plocUploadProtocol :: !(Maybe Text)
, _plocAccessToken :: !(Maybe Text)
, _plocUploadType :: !(Maybe Text)
, _plocPayload :: !CancelOperationRequest
, _plocName :: !Text
, _plocCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsOperationsCancel' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plocXgafv'
--
-- * 'plocUploadProtocol'
--
-- * 'plocAccessToken'
--
-- * 'plocUploadType'
--
-- * 'plocPayload'
--
-- * 'plocName'
--
-- * 'plocCallback'
projectsLocationsOperationsCancel
:: CancelOperationRequest -- ^ 'plocPayload'
-> Text -- ^ 'plocName'
-> ProjectsLocationsOperationsCancel
projectsLocationsOperationsCancel pPlocPayload_ pPlocName_ =
ProjectsLocationsOperationsCancel'
{ _plocXgafv = Nothing
, _plocUploadProtocol = Nothing
, _plocAccessToken = Nothing
, _plocUploadType = Nothing
, _plocPayload = pPlocPayload_
, _plocName = pPlocName_
, _plocCallback = Nothing
}
-- | V1 error format.
plocXgafv :: Lens' ProjectsLocationsOperationsCancel (Maybe Xgafv)
plocXgafv
= lens _plocXgafv (\ s a -> s{_plocXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plocUploadProtocol :: Lens' ProjectsLocationsOperationsCancel (Maybe Text)
plocUploadProtocol
= lens _plocUploadProtocol
(\ s a -> s{_plocUploadProtocol = a})
-- | OAuth access token.
plocAccessToken :: Lens' ProjectsLocationsOperationsCancel (Maybe Text)
plocAccessToken
= lens _plocAccessToken
(\ s a -> s{_plocAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plocUploadType :: Lens' ProjectsLocationsOperationsCancel (Maybe Text)
plocUploadType
= lens _plocUploadType
(\ s a -> s{_plocUploadType = a})
-- | Multipart request metadata.
plocPayload :: Lens' ProjectsLocationsOperationsCancel CancelOperationRequest
plocPayload
= lens _plocPayload (\ s a -> s{_plocPayload = a})
-- | The name of the operation resource to be cancelled.
plocName :: Lens' ProjectsLocationsOperationsCancel Text
plocName = lens _plocName (\ s a -> s{_plocName = a})
-- | JSONP
plocCallback :: Lens' ProjectsLocationsOperationsCancel (Maybe Text)
plocCallback
= lens _plocCallback (\ s a -> s{_plocCallback = a})
instance GoogleRequest
ProjectsLocationsOperationsCancel
where
type Rs ProjectsLocationsOperationsCancel = Empty
type Scopes ProjectsLocationsOperationsCancel =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/logging.admin"]
requestClient ProjectsLocationsOperationsCancel'{..}
= go _plocName _plocXgafv _plocUploadProtocol
_plocAccessToken
_plocUploadType
_plocCallback
(Just AltJSON)
_plocPayload
loggingService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsOperationsCancelResource)
mempty
| brendanhay/gogol | gogol-logging/gen/Network/Google/Resource/Logging/Projects/Locations/Operations/Cancel.hs | mpl-2.0 | 6,661 | 0 | 16 | 1,372 | 797 | 472 | 325 | 116 | 1 |
module Relude
( module Data.Foldable
, module Data.Traversable
, module Data.Monoid
, module Control.Arrow
, module Control.Applicative
, module Control.Lens
, module Data.String
, module Prelude
, module System.Environment
, ByteString, Map, Set, Text
, intersperse, catMaybes
) where
import Control.Applicative
import Control.Lens
import Data.ByteString (ByteString)
import Data.Foldable
import Data.Map (Map)
import Data.Monoid
import Data.Set (Set)
import Data.Text (Text)
import Data.Traversable
import Prelude hiding (all, and, any, concat, concatMap, elem,
foldl, foldl1, foldr, foldr1, mapM, mapM_, maximum,
minimum, notElem, or, product, sequence, sequence_,
sum, sum_)
import Control.Arrow
import Data.List (intersperse)
import Data.Maybe (catMaybes)
import Data.String
import System.Environment
| bsummer4/gcal | src/Relude.hs | agpl-3.0 | 981 | 0 | 5 | 272 | 245 | 157 | 88 | 30 | 0 |
import Control.Monad
main = do
[n, k, q] <- fmap ((take 3) . (map read) . words) getLine
xs <- fmap ((take n) . words) getLine
let xs' = reverse $ take n $ drop k $ cycle $ reverse xs
qs <- replicateM q readLn
mapM putStrLn $ map (xs' !!) qs
| itsbruce/hackerrank | alg/warmup/car.hs | unlicense | 263 | 0 | 14 | 74 | 145 | 70 | 75 | 7 | 1 |
module Server where
import Data.IORef
import Text.Printf
import Control.Monad
import Network.Socket
import Data.Time.Clock
import Data.Time.Format
import Control.Concurrent
import Control.Applicative
info :: String -> IO ()
info msg = do
time <- formatTime defaultTimeLocale rfc822DateFormat <$> getCurrentTime
putStrLn $ printf "%s - %s" time msg
recvLoop :: Socket -> Int -> IO String
recvLoop s = go []
where
go acc len
| len == 0 = return acc
| otherwise = do
m <- recv s len
if (length m == 0)
then return acc
else go (acc ++ m) (len - length m)
sendLoop :: Socket -> String -> IO ()
sendLoop s m
| null m = return ()
| otherwise = do
l <- send s m
sendLoop s (drop l m)
handle :: (Socket, SockAddr) -> String -> IO ()
handle (s, _) srvid = do
msg <- recvLoop s 4
case msg of
"ping" -> do
info "ping"
sendLoop s (printf "[%s] - pong\n" srvid)
_ -> sendLoop s (printf "[%s] - fail\n" srvid)
start :: IORef [MVar ()] -> IO (MVar ())
start ref = do
mvar <- newEmptyMVar
atomicModifyIORef' ref (\xs -> (mvar : xs, mvar))
signal :: MVar () -> IO ()
signal mvar = putMVar mvar ()
waitall :: IORef [MVar ()] -> IO ()
waitall ref = do
mvars <- atomicModifyIORef' ref (\xs -> ([], xs))
mapM_ takeMVar mvars
server :: IORef Bool -> Socket -> String -> IO ()
server ctrl s uuid = do
cont <- readIORef ctrl
wait <- newIORef []
when cont $ do
mvar <- start wait
accept s >>= \s -> forkFinally (handle s uuid) (const (signal mvar >> sClose (fst s)))
server ctrl s uuid
waitall wait
| dgvncsz0f/pong | src/Server.hs | unlicense | 1,623 | 0 | 19 | 434 | 727 | 348 | 379 | 55 | 2 |
data Dict
data Type s = Auto s
| Hira s
| Kata s
toKana :: Dict -> Type String -> String
toKana d t = genConvert d $ unwrapType t
genConvert :: Dict -> String -> String
genConvert d s = concatMap (convertWord d) (words s)
convertWord :: Dict -> String -> String
convertWord d s = concatMap (convertSyllable d) (syllables d s)
syllables :: Dict -> String -> [String]
syllables _ [] = []
syllables d s@(x:xs)
| fst cond = (:) (fst $ snd $ cond) (syllables d (snd $ snd $ cond))
| otherwise = (:) [x] (syllables d xs)
where
cond = aux max d s
max = min 3 $ length s
aux :: Int -> Dict -> String -> (Bool, (String, String))
aux 0 _ _ = (False, ([], []))
aux _ _ [] = (False, ([], []))
aux n d s
| d `containsKey` (take n s) = (True, (splitAt n s))
| otherwise = aux (pred n) d s
unwrapType :: Type String -> String
unwrapType (Auto s) = s
unwrapType (Hira s) = toLowercase s
unwrapType (Kata s) = toUppercase s
containsKey :: Dict -> String -> Bool
containsKey = undefined
convertSyllable :: Dict -> String -> String
convertSyllable = undefined
toLowercase :: String -> String
toLowercase = undefined
toUppercase :: String -> String
toUppercase = undefined
| SiIky/libr2k | proto.hs | unlicense | 1,287 | 0 | 12 | 361 | 573 | 299 | 274 | -1 | -1 |
module Main where
factors :: Int -> [Int]
factors n = [x | x <- [1..n], n `mod` x == 0]
prime :: Int -> Bool
prime n = factors n == [1, n]
primesTo :: Int -> [Int]
primesTo n = [x | x <- [2..n], prime x]
| Crossroadsman/ProgrammingInHaskell | 05/primes.hs | apache-2.0 | 231 | 0 | 8 | 76 | 127 | 70 | 57 | 7 | 1 |
module Main ( main ) where
import Control.Eff.Exception
import Control.Eff.Lift
import System.Environment ( getArgs )
import Codec.FFMpeg
import Codec.FFMpeg.Format
probe :: String -> IO ()
probe fn = do
putStrLn fn
me <- runLift $ runExc (openInput fn (return (1 :: Int)))
case me of
Left e -> print (e :: IOError)
Right _ -> return ()
return ()
main :: IO ()
main = initFFMpeg >> getArgs >>= mapM_ probe
| waldheinz/ffmpeg-effects | demos/Probe.hs | apache-2.0 | 447 | 0 | 14 | 112 | 177 | 91 | 86 | 16 | 2 |
{-# LANGUAGE FlexibleContexts #-}
import qualified Data.Text as T
import qualified Data.ByteString as B
import JtagRW ( UsbBlasterState
, withUSBBlaster
, toBits, fromBits
, virWrite, vdrWrite, vdrWriteRead
, virAddrOff, virAddrRead, virAddrWrite
, flush
, printState
)
import Protolude
--
-- FOR: DE0_Nano_project_JTAG.qar
-- Derived from https://github.com/GeezerGeek/open_sld/blob/master/sld_interface.py,
-- And: http://sourceforge.net/p/ixo-jtag/code/HEAD/tree/usb_jtag/
-- Load the initialTest.sof from open_sld on the board and run... ;-)
-- The initial test wires the DS0-Nano LED bank up to the SLD and prints last VDR
outLed :: Word8 -> (StateT UsbBlasterState) IO (Maybe ByteString)
outLed v = do
_ <- virWrite 1
_ <- vdrWrite $ toBits 5 v
_ <- virWrite 0
_ <- flush
return $ Just "todo"
doStuff :: (StateT UsbBlasterState) IO (Maybe B.ByteString)
doStuff = do
_ <- mapM outLed [0..127]
_ <- mapM outLed $ join $ replicate 16 [1, 2, 4, 8, 16, 32, 64, 32, 16, 8, 4, 2, 1]
_ <- mapM outLed [127,126..0]
return Nothing
main :: IO ()
main = do
dh <- withUSBBlaster 0x10 10 5 doStuff
case dh of
Just err -> putStrLn $ T.pack $ "Error:" ++ show err
Nothing -> pure ()
| tau-tao/FPGAIPFilter | test/FtdiTest1.hs | bsd-3-clause | 1,437 | 0 | 13 | 453 | 364 | 193 | 171 | 30 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
module Text.RE.Internal.QQ where
import Control.Exception
import Data.Typeable
import Language.Haskell.TH.Quote
data QQFailure =
QQFailure
{ _qqf_context :: String
, _qqf_component :: String
}
deriving (Show,Typeable)
instance Exception QQFailure where
qq0 :: String -> QuasiQuoter
qq0 ctx =
QuasiQuoter
{ quoteExp = const $ throw $ QQFailure ctx "expression"
, quotePat = const $ throw $ QQFailure ctx "pattern"
, quoteType = const $ throw $ QQFailure ctx "type"
, quoteDec = const $ throw $ QQFailure ctx "declaration"
}
| cdornan/idiot | Text/RE/Internal/QQ.hs | bsd-3-clause | 646 | 0 | 8 | 169 | 161 | 91 | 70 | 18 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Linear.Extra.Random where
import Control.Monad.Random
import Linear
import Control.Lens
instance Random r => Random (V2 r) where
randomR (a,b) g = flip runRand g $ do
x <- getRandomR (a^._x,b^._x)
y <- getRandomR (a^._y,b^._y)
return (V2 x y)
random g = flip runRand g $ do
x <- getRandom
y <- getRandom
return (V2 x y)
instance Random r => Random (V3 r) where
randomR (a,b) g = flip runRand g $ do
x <- getRandomR (a^._x,b^._x)
y <- getRandomR (a^._y,b^._y)
z <- getRandomR (a^._z,b^._z)
return (V3 x y z)
random g = flip runRand g $ do
x <- getRandom
y <- getRandom
z <- getRandom
return (V3 x y z)
instance Random r => Random (V4 r) where
randomR (a,b) g = flip runRand g $ do
x <- getRandomR (a^._x,b^._x)
y <- getRandomR (a^._y,b^._y)
z <- getRandomR (a^._z,b^._z)
w <- getRandomR (a^._w,b^._w)
return (V4 x y z w)
random g = flip runRand g $ do
x <- getRandom
y <- getRandom
z <- getRandom
w <- getRandom
return (V4 x y z w)
| lukexi/linear-extra | src/Linear/Extra/Random.hs | bsd-3-clause | 1,196 | 0 | 12 | 401 | 586 | 285 | 301 | 38 | 0 |
{-# LANGUAGE TemplateHaskell #-}
module Render.MEdgeT where
import Data.Word (Word16)
import Control.Lens (makeLenses)
import qualified Data.ByteString.Lazy as BL
import Types
import Util.Binary
import qualified Constants
mEdgeDiskSize :: Int
mEdgeDiskSize = 2 * Constants.sizeOfShort
makeLenses ''MEdgeT
newMEdgeT :: BL.ByteString -> MEdgeT
newMEdgeT = runGet getMEdgeT
getMEdgeT :: Get MEdgeT
getMEdgeT = do
v <- getWord162
return MEdgeT { _meV = v
, _meCachedEdgeOffset = 0
} | ksaveljev/hake-2 | src/Render/MEdgeT.hs | bsd-3-clause | 529 | 0 | 9 | 115 | 131 | 75 | 56 | 18 | 1 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
-- | Interface between OpenCV and inline-c(pp) (Haskell)
module OpenCV.Internal.C.Inline ( openCvCtx ) where
import "base" Foreign.Ptr ( FunPtr )
import "base" Data.Monoid ( (<>) )
import qualified "containers" Data.Map as M
import qualified "inline-c" Language.C.Inline as C
import qualified "inline-c" Language.C.Types as C
import qualified "inline-c" Language.C.Inline.Context as C
import qualified "inline-c-cpp" Language.C.Inline.Cpp as C
import "this" OpenCV.Internal.C.Types
-- | Context useful to work with the OpenCV library
--
-- Based on 'C.cppCtx', 'C.bsCtx' and 'C.vecCtx'.
--
-- 'C.ctxTypesTable': converts OpenCV basic types to their counterparts in
-- "OpenCV.Internal.C.Inline".
--
-- No 'C.ctxAntiQuoters'.
openCvCtx :: C.Context
openCvCtx = C.cppCtx <> C.bsCtx <> C.vecCtx <> ctx
where
ctx = mempty
{ C.ctxTypesTable = openCvTypesTable
}
openCvTypesTable :: C.TypesTable
openCvTypesTable = M.fromList
[ ( C.TypeName "bool" , [t| C.CInt |] )
, ( C.TypeName "Exception" , [t| C'CvCppException |] )
, ( C.TypeName "Matx12f" , [t| C'Matx12f |] )
, ( C.TypeName "Matx12d" , [t| C'Matx12d |] )
, ( C.TypeName "Matx13f" , [t| C'Matx13f |] )
, ( C.TypeName "Matx13d" , [t| C'Matx13d |] )
, ( C.TypeName "Matx14f" , [t| C'Matx14f |] )
, ( C.TypeName "Matx14d" , [t| C'Matx14d |] )
, ( C.TypeName "Matx16f" , [t| C'Matx16f |] )
, ( C.TypeName "Matx16d" , [t| C'Matx16d |] )
, ( C.TypeName "Matx21f" , [t| C'Matx21f |] )
, ( C.TypeName "Matx21d" , [t| C'Matx21d |] )
, ( C.TypeName "Matx22f" , [t| C'Matx22f |] )
, ( C.TypeName "Matx22d" , [t| C'Matx22d |] )
, ( C.TypeName "Matx23f" , [t| C'Matx23f |] )
, ( C.TypeName "Matx23d" , [t| C'Matx23d |] )
, ( C.TypeName "Matx31f" , [t| C'Matx31f |] )
, ( C.TypeName "Matx31d" , [t| C'Matx31d |] )
, ( C.TypeName "Matx32f" , [t| C'Matx32f |] )
, ( C.TypeName "Matx32d" , [t| C'Matx32d |] )
, ( C.TypeName "Matx33f" , [t| C'Matx33f |] )
, ( C.TypeName "Matx33d" , [t| C'Matx33d |] )
, ( C.TypeName "Matx34f" , [t| C'Matx34f |] )
, ( C.TypeName "Matx34d" , [t| C'Matx34d |] )
, ( C.TypeName "Matx41f" , [t| C'Matx41f |] )
, ( C.TypeName "Matx41d" , [t| C'Matx41d |] )
, ( C.TypeName "Matx43f" , [t| C'Matx43f |] )
, ( C.TypeName "Matx43d" , [t| C'Matx43d |] )
, ( C.TypeName "Matx44f" , [t| C'Matx44f |] )
, ( C.TypeName "Matx44d" , [t| C'Matx44d |] )
, ( C.TypeName "Matx51f" , [t| C'Matx51f |] )
, ( C.TypeName "Matx51d" , [t| C'Matx51d |] )
, ( C.TypeName "Matx61f" , [t| C'Matx61f |] )
, ( C.TypeName "Matx61d" , [t| C'Matx61d |] )
, ( C.TypeName "Matx66f" , [t| C'Matx66f |] )
, ( C.TypeName "Matx66d" , [t| C'Matx66d |] )
, ( C.TypeName "Vec2i" , [t| C'Vec2i |] )
, ( C.TypeName "Vec2f" , [t| C'Vec2f |] )
, ( C.TypeName "Vec2d" , [t| C'Vec2d |] )
, ( C.TypeName "Vec3i" , [t| C'Vec3i |] )
, ( C.TypeName "Vec3f" , [t| C'Vec3f |] )
, ( C.TypeName "Vec3d" , [t| C'Vec3d |] )
, ( C.TypeName "Vec4i" , [t| C'Vec4i |] )
, ( C.TypeName "Vec4f" , [t| C'Vec4f |] )
, ( C.TypeName "Vec4d" , [t| C'Vec4d |] )
, ( C.TypeName "Point2i" , [t| C'Point2i |] )
, ( C.TypeName "Point2f" , [t| C'Point2f |] )
, ( C.TypeName "Point2d" , [t| C'Point2d |] )
, ( C.TypeName "Point3i" , [t| C'Point3i |] )
, ( C.TypeName "Point3f" , [t| C'Point3f |] )
, ( C.TypeName "Point3d" , [t| C'Point3d |] )
, ( C.TypeName "Size2i" , [t| C'Size2i |] )
, ( C.TypeName "Size2f" , [t| C'Size2f |] )
, ( C.TypeName "Size2d" , [t| C'Size2d |] )
, ( C.TypeName "Rect2i" , [t| C'Rect2i |] )
, ( C.TypeName "Rect2f" , [t| C'Rect2f |] )
, ( C.TypeName "Rect2d" , [t| C'Rect2d |] )
, ( C.TypeName "RotatedRect" , [t| C'RotatedRect |] )
, ( C.TypeName "TermCriteria", [t| C'TermCriteria|] )
, ( C.TypeName "Scalar" , [t| C'Scalar |] )
, ( C.TypeName "Mat" , [t| C'Mat |] )
, ( C.TypeName "Range" , [t| C'Range |] )
, ( C.TypeName "KeyPoint" , [t| C'KeyPoint |] )
, ( C.TypeName "DMatch" , [t| C'DMatch |] )
--, ( C.TypeName "MSER" , [t| C'MSER |] )
, ( C.TypeName "Ptr_ORB" , [t| C'Ptr_ORB |] )
--, ( C.TypeName "BRISK" , [t| C'BRISK |] )
--, ( C.TypeName "KAZE" , [t| C'KAZE |] )
--, ( C.TypeName "AKAZE" , [t| C'AKAZE |] )
, ( C.TypeName "BFMatcher" , [t| C'BFMatcher |] )
, ( C.TypeName "Ptr_BackgroundSubtractorKNN" , [t| C'Ptr_BackgroundSubtractorKNN |] )
, ( C.TypeName "Ptr_BackgroundSubtractorMOG2", [t| C'Ptr_BackgroundSubtractorMOG2 |] )
, ( C.TypeName "VideoCapture", [t| C'VideoCapture |] )
, ( C.TypeName "MouseCallback" , [t| FunPtr C'MouseCallback |] )
, ( C.TypeName "TrackbarCallback", [t| FunPtr C'TrackbarCallback |] )
]
| Cortlandd/haskell-opencv | src/OpenCV/Internal/C/Inline.hs | bsd-3-clause | 5,328 | 0 | 9 | 1,614 | 1,453 | 974 | 479 | -1 | -1 |
{-# LANGUAGE CPP #-}
---------------------------------------------------------------------------
-- |
-- Copyright : (C) 2015 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : non-portable
--
-- Common projection matrices: e.g. perspective/orthographic transformation
-- matrices.
--
-- Analytically derived inverses are also supplied, because they can be
-- much more accurate in practice than computing them through general
-- purpose means
---------------------------------------------------------------------------
module Linear.Projection
( lookAt
, perspective, inversePerspective
, infinitePerspective, inverseInfinitePerspective
, frustum, inverseFrustum
, ortho, inverseOrtho
) where
import Control.Lens hiding (index)
import Linear.V3
import Linear.V4
import Linear.Matrix
import Linear.Epsilon
import Linear.Metric
#ifdef HLINT
{-# ANN module "HLint: ignore Reduce duplication" #-}
#endif
-- | Build a look at view matrix
lookAt
:: (Epsilon a, Floating a)
=> V3 a -- ^ Eye
-> V3 a -- ^ Center
-> V3 a -- ^ Up
-> M44 a
lookAt eye center up =
V4 (V4 (xa^._x) (xa^._y) (xa^._z) xd)
(V4 (ya^._x) (ya^._y) (ya^._z) yd)
(V4 (-za^._x) (-za^._y) (-za^._z) zd)
(V4 0 0 0 1)
where za = normalize $ center - eye
xa = normalize $ cross za up
ya = cross xa za
xd = -dot xa eye
yd = -dot ya eye
zd = dot za eye
-- | Build a matrix for a symmetric perspective-view frustum
perspective
:: Floating a
=> a -- ^ FOV (y direction, in radians)
-> a -- ^ Aspect ratio
-> a -- ^ Near plane
-> a -- ^ Far plane
-> M44 a
perspective fovy aspect near far =
V4 (V4 x 0 0 0)
(V4 0 y 0 0)
(V4 0 0 z w)
(V4 0 0 (-1) 0)
where tanHalfFovy = tan $ fovy / 2
x = 1 / (aspect * tanHalfFovy)
y = 1 / tanHalfFovy
z = -(far + near) / (far - near)
w = -(2 * far * near) / (far - near)
-- | Build an inverse perspective matrix
inversePerspective
:: Floating a
=> a -- ^ FOV (y direction, in radians)
-> a -- ^ Aspect ratio
-> a -- ^ Near plane
-> a -- ^ Far plane
-> M44 a
inversePerspective fovy aspect near far =
V4 (V4 a 0 0 0 )
(V4 0 b 0 0 )
(V4 0 0 0 (-1))
(V4 0 0 c d )
where tanHalfFovy = tan $ fovy / 2
a = aspect * tanHalfFovy
b = tanHalfFovy
c = -(far - near) / (2 * far * near)
d = (far + near) / (2 * far * near)
-- | Build a perspective matrix per the classic @glFrustum@ arguments.
frustum
:: Floating a
=> a -- ^ Left
-> a -- ^ Right
-> a -- ^ Bottom
-> a -- ^ Top
-> a -- ^ Near
-> a -- ^ Far
-> M44 a
frustum l r b t n f =
V4 (V4 x 0 a 0)
(V4 0 y e 0)
(V4 0 0 c d)
(V4 0 0 (-1) 0)
where
rml = r-l
tmb = t-b
fmn = f-n
x = 2*n/rml
y = 2*n/tmb
a = (r+l)/rml
e = (t+b)/tmb
c = negate (f+n)/fmn
d = (-2*f*n)/fmn
inverseFrustum
:: Floating a
=> a -- ^ Left
-> a -- ^ Right
-> a -- ^ Bottom
-> a -- ^ Top
-> a -- ^ Near
-> a -- ^ Far
-> M44 a
inverseFrustum l r b t n f =
V4 (V4 rx 0 0 ax)
(V4 0 ry 0 by)
(V4 0 0 0 (-1))
(V4 0 0 rd cd)
where
hrn = 0.5/n
hrnf = 0.5/(n*f)
rx = (r-l)*hrn
ry = (t-b)*hrn
ax = (r+l)*hrn
by = (t+b)*hrn
cd = (f+n)*hrnf
rd = (n-f)*hrnf
-- | Build a matrix for a symmetric perspective-view frustum with a far plane at infinite
infinitePerspective
:: Floating a
=> a -- ^ FOV (y direction, in radians)
-> a -- ^ Aspect Ratio
-> a -- ^ Near plane
-> M44 a
infinitePerspective fovy a n =
V4 (V4 x 0 0 0)
(V4 0 y 0 0)
(V4 0 0 (-1) w)
(V4 0 0 (-1) 0)
where
t = n*tan(fovy/2)
b = -t
l = b*a
r = t*a
x = (2*n)/(r-l)
y = (2*n)/(t-b)
w = -2*n
inverseInfinitePerspective
:: Floating a
=> a -- ^ FOV (y direction, in radians)
-> a -- ^ Aspect Ratio
-> a -- ^ Near plane
-> M44 a
inverseInfinitePerspective fovy a n =
V4 (V4 rx 0 0 0)
(V4 0 ry 0 0)
(V4 0 0 0 (-1))
(V4 0 0 rw (-rw))
where
t = n*tan(fovy/2)
b = -t
l = b*a
r = t*a
hrn = 0.5/n
rx = (r-l)*hrn
ry = (t-b)*hrn
rw = -hrn
-- | Build an orthographic perspective matrix from 6 clipping planes.
-- This matrix takes the region delimited by these planes and maps it
-- to normalized device coordinates between [-1,1]
--
-- This call is designed to mimic the parameters to the OpenGL @glOrtho@
-- call, so it has a slightly strange convention: Notably: the near and
-- far planes are negated.
--
-- Consequently:
--
-- @
-- 'ortho' l r b t n f !* 'V4' l b (-n) 1 = 'V4' (-1) (-1) (-1) 1
-- 'ortho' l r b t n f !* 'V4' r t (-f) 1 = 'V4' 1 1 1 1
-- @
--
-- Examples:
--
-- >>> ortho 1 2 3 4 5 6 !* V4 1 3 (-5) 1
-- V4 (-1.0) (-1.0) (-1.0) 1.0
--
-- >>> ortho 1 2 3 4 5 6 !* V4 2 4 (-6) 1
-- V4 1.0 1.0 1.0 1.0
ortho
:: Fractional a
=> a -- ^ Left
-> a -- ^ Right
-> a -- ^ Bottom
-> a -- ^ Top
-> a -- ^ Near
-> a -- ^ Far
-> M44 a
ortho l r b t n f =
V4 (V4 (-2*x) 0 0 ((r+l)*x))
(V4 0 (-2*y) 0 ((t+b)*y))
(V4 0 0 (2*z) ((f+n)*z))
(V4 0 0 0 1)
where x = recip(l-r)
y = recip(b-t)
z = recip(n-f)
-- | Build an inverse orthographic perspective matrix from 6 clipping planes
inverseOrtho
:: Fractional a
=> a -- ^ Left
-> a -- ^ Right
-> a -- ^ Bottom
-> a -- ^ Top
-> a -- ^ Near
-> a -- ^ Far
-> M44 a
inverseOrtho l r b t n f =
V4 (V4 x 0 0 c)
(V4 0 y 0 d)
(V4 0 0 z e)
(V4 0 0 0 1)
where x = 0.5*(r-l)
y = 0.5*(t-b)
z = 0.5*(n-f)
c = 0.5*(l+r)
d = 0.5*(b+t)
e = -0.5*(n+f)
| phaazon/linear | src/Linear/Projection.hs | bsd-3-clause | 5,852 | 2 | 12 | 1,856 | 2,144 | 1,171 | 973 | 183 | 1 |
module DepthFirstSearchTest where
import qualified DepthFirstSearch as DFS
import qualified Data.Set as Set
import Test.Hspec
import Test.QuickCheck
import Debug.Trace
makeGraph :: DFS.Graph
makeGraph = DFS.AdjList [ [1, 2] -- 0
, [0, 3] -- 1
, [0] -- 2
, [1, 4] -- 3
, [3] -- 4
, [] -- 5
]
test = hspec $ do
describe "Dfs traversal" $ do
it "should have right start/endtime for dfs traversal" $ do
let results = DFS.depthFirstSearch makeGraph
-- DFS.DFSResult nodeId startTime endTime
([ DFS.DFSResult 0 0 9
, DFS.DFSResult 1 1 6
, DFS.DFSResult 3 2 5
, DFS.DFSResult 4 3 4
, DFS.DFSResult 2 7 8
, DFS.DFSResult 5 10 11
]
, 12 -- final time
, Set.empty) -- no node should be left.
== results
| ashishnegi/hsalgos | test/DepthFirstSearchTest.hs | bsd-3-clause | 895 | 0 | 18 | 331 | 236 | 135 | 101 | 26 | 1 |
{-# LANGUAGE CPP, MagicHash, NondecreasingIndentation, UnboxedTuples #-}
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2005-2007
--
-- Running statements interactively
--
-- -----------------------------------------------------------------------------
module ETA.Main.InteractiveEval (
#ifdef GHCI
RunResult(..), Status(..), Resume(..), History(..),
runStmt, runStmtWithLocation, runDecls, runDeclsWithLocation,
parseImportDecl, SingleStep(..),
resume,
abandon, abandonAll,
getResumeContext,
getHistorySpan,
getModBreaks,
getHistoryModule,
back, forward,
setContext, getContext,
availsToGlobalRdrEnv,
getNamesInScope,
getRdrNamesInScope,
moduleIsInterpreted,
getInfo,
exprType,
typeKind,
parseName,
showModule,
isModuleInterpreted,
compileExpr, dynCompileExpr,
Term(..), obtainTermFromId, obtainTermFromVal, reconstructType
#endif
) where
#ifdef GHCI
#include "HsVersions.h"
import ETA.Main.InteractiveEvalTypes
import ETA.Main.GhcMonad
import ETA.Main.HscMain
import ETA.HsSyn.HsSyn
import ETA.Main.HscTypes
import ETA.BasicTypes.BasicTypes ( HValue )
import ETA.Types.InstEnv
import ETA.Types.FamInstEnv ( FamInst, orphNamesOfFamInst )
import ETA.Types.TyCon
import ETA.Types.Type hiding( typeKind )
import ETA.TypeCheck.TcType hiding( typeKind )
import ETA.BasicTypes.Var
import ETA.BasicTypes.Id
import ETA.BasicTypes.Name hiding ( varName )
import ETA.BasicTypes.NameSet
import ETA.BasicTypes.Avail
import ETA.BasicTypes.RdrName
import ETA.BasicTypes.VarSet
import ETA.BasicTypes.VarEnv
import ETA.Interactive.ByteCodeInstr
import ETA.Interactive.Linker
import ETA.Main.DynFlags
import ETA.BasicTypes.Unique
import ETA.BasicTypes.UniqSupply
import ETA.BasicTypes.Module
import ETA.Utils.Panic
import ETA.Utils.UniqFM
import ETA.Utils.Maybes
import ETA.Main.ErrUtils
import ETA.BasicTypes.SrcLoc
import ETA.Main.BreakArray
import ETA.Interactive.RtClosureInspect
import ETA.Utils.Outputable
import ETA.Utils.FastString
import ETA.Utils.MonadUtils
import System.Mem.Weak
import System.Directory
import Data.Dynamic
import Data.Either
import Data.List (find)
import Control.Monad
import Foreign
import Foreign.C
import GHC.Exts
import Data.Array
import ETA.Utils.Exception
import Control.Concurrent
import System.IO.Unsafe
-- -----------------------------------------------------------------------------
-- running a statement interactively
getResumeContext :: GhcMonad m => m [Resume]
getResumeContext = withSession (return . ic_resume . hsc_IC)
data SingleStep
= RunToCompletion
| SingleStep
| RunAndLogSteps
isStep :: SingleStep -> Bool
isStep RunToCompletion = False
isStep _ = True
mkHistory :: HscEnv -> HValue -> BreakInfo -> History
mkHistory hsc_env hval bi = let
decls = findEnclosingDecls hsc_env bi
in History hval bi decls
getHistoryModule :: History -> Module
getHistoryModule = breakInfo_module . historyBreakInfo
getHistorySpan :: HscEnv -> History -> SrcSpan
getHistorySpan hsc_env hist =
let inf = historyBreakInfo hist
num = breakInfo_number inf
in case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
Just hmi -> modBreaks_locs (getModBreaks hmi) ! num
_ -> panic "getHistorySpan"
getModBreaks :: HomeModInfo -> ModBreaks
getModBreaks hmi
| Just linkable <- hm_linkable hmi,
[BCOs _ modBreaks] <- linkableUnlinked linkable
= modBreaks
| otherwise
= emptyModBreaks -- probably object code
{- | Finds the enclosing top level function name -}
-- ToDo: a better way to do this would be to keep hold of the decl_path computed
-- by the coverage pass, which gives the list of lexically-enclosing bindings
-- for each tick.
findEnclosingDecls :: HscEnv -> BreakInfo -> [String]
findEnclosingDecls hsc_env inf =
let hmi = expectJust "findEnclosingDecls" $
lookupUFM (hsc_HPT hsc_env) (moduleName $ breakInfo_module inf)
mb = getModBreaks hmi
in modBreaks_decls mb ! breakInfo_number inf
-- | Update fixity environment in the current interactive context.
updateFixityEnv :: GhcMonad m => FixityEnv -> m ()
updateFixityEnv fix_env = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
setSession $ hsc_env { hsc_IC = ic { ic_fix_env = fix_env } }
-- | Run a statement in the current interactive context. Statement
-- may bind multple values.
runStmt :: GhcMonad m => String -> SingleStep -> m RunResult
runStmt = runStmtWithLocation "<interactive>" 1
-- | Run a statement in the current interactive context. Passing debug information
-- Statement may bind multple values.
runStmtWithLocation :: GhcMonad m => String -> Int ->
String -> SingleStep -> m RunResult
runStmtWithLocation source linenumber expr step =
do
hsc_env <- getSession
breakMVar <- liftIO $ newEmptyMVar -- wait on this when we hit a breakpoint
statusMVar <- liftIO $ newEmptyMVar -- wait on this when a computation is running
-- Turn off -fwarn-unused-bindings when running a statement, to hide
-- warnings about the implicit bindings we introduce.
let ic = hsc_IC hsc_env -- use the interactive dflags
idflags' = ic_dflags ic `wopt_unset` Opt_WarnUnusedBinds
hsc_env' = hsc_env{ hsc_IC = ic{ ic_dflags = idflags' } }
-- compile to value (IO [HValue]), don't run
r <- liftIO $ hscStmtWithLocation hsc_env' expr source linenumber
case r of
-- empty statement / comment
Nothing -> return (RunOk [])
Just (tyThings, hval, fix_env) -> do
updateFixityEnv fix_env
status <-
withVirtualCWD $
withBreakAction (isStep step) idflags' breakMVar statusMVar $ do
liftIO $ sandboxIO idflags' statusMVar hval
let ic = hsc_IC hsc_env
bindings = (ic_tythings ic, ic_rn_gbl_env ic)
size = ghciHistSize idflags'
handleRunStatus step expr bindings tyThings
breakMVar statusMVar status (emptyHistory size)
runDecls :: GhcMonad m => String -> m [Name]
runDecls = runDeclsWithLocation "<interactive>" 1
runDeclsWithLocation :: GhcMonad m => String -> Int -> String -> m [Name]
runDeclsWithLocation source linenumber expr =
do
hsc_env <- getSession
(tyThings, ic) <- liftIO $ hscDeclsWithLocation hsc_env expr source linenumber
setSession $ hsc_env { hsc_IC = ic }
hsc_env <- getSession
hsc_env' <- liftIO $ rttiEnvironment hsc_env
modifySession (\_ -> hsc_env')
return (map getName tyThings)
withVirtualCWD :: GhcMonad m => m a -> m a
withVirtualCWD m = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
let set_cwd = do
dir <- liftIO $ getCurrentDirectory
case ic_cwd ic of
Just dir -> liftIO $ setCurrentDirectory dir
Nothing -> return ()
return dir
reset_cwd orig_dir = do
virt_dir <- liftIO $ getCurrentDirectory
hsc_env <- getSession
let old_IC = hsc_IC hsc_env
setSession hsc_env{ hsc_IC = old_IC{ ic_cwd = Just virt_dir } }
liftIO $ setCurrentDirectory orig_dir
gbracket set_cwd reset_cwd $ \_ -> m
parseImportDecl :: GhcMonad m => String -> m (ImportDecl RdrName)
parseImportDecl expr = withSession $ \hsc_env -> liftIO $ hscImport hsc_env expr
emptyHistory :: Int -> BoundedList History
emptyHistory size = nilBL size
handleRunStatus :: GhcMonad m
=> SingleStep -> String-> ([TyThing],GlobalRdrEnv) -> [Id]
-> MVar () -> MVar Status -> Status -> BoundedList History
-> m RunResult
handleRunStatus step expr bindings final_ids
breakMVar statusMVar status history
| RunAndLogSteps <- step = tracing
| otherwise = not_tracing
where
tracing
| Break is_exception apStack info tid <- status
, not is_exception
= do
hsc_env <- getSession
b <- liftIO $ isBreakEnabled hsc_env info
if b
then not_tracing
-- This breakpoint is explicitly enabled; we want to stop
-- instead of just logging it.
else do
let history' = mkHistory hsc_env apStack info `consBL` history
-- probably better make history strict here, otherwise
-- our BoundedList will be pointless.
_ <- liftIO $ evaluate history'
status <- withBreakAction True (hsc_dflags hsc_env)
breakMVar statusMVar $ do
liftIO $ mask_ $ do
putMVar breakMVar () -- awaken the stopped thread
redirectInterrupts tid $
takeMVar statusMVar -- and wait for the result
handleRunStatus RunAndLogSteps expr bindings final_ids
breakMVar statusMVar status history'
| otherwise
= not_tracing
not_tracing
-- Hit a breakpoint
| Break is_exception apStack info tid <- status
= do
hsc_env <- getSession
let mb_info | is_exception = Nothing
| otherwise = Just info
(hsc_env1, names, span) <- liftIO $
bindLocalsAtBreakpoint hsc_env apStack mb_info
let
resume = Resume
{ resumeStmt = expr, resumeThreadId = tid
, resumeBreakMVar = breakMVar, resumeStatMVar = statusMVar
, resumeBindings = bindings, resumeFinalIds = final_ids
, resumeApStack = apStack, resumeBreakInfo = mb_info
, resumeSpan = span, resumeHistory = toListBL history
, resumeHistoryIx = 0 }
hsc_env2 = pushResume hsc_env1 resume
modifySession (\_ -> hsc_env2)
return (RunBreak tid names mb_info)
-- Completed with an exception
| Complete (Left e) <- status
= return (RunException e)
-- Completed successfully
| Complete (Right hvals) <- status
= do hsc_env <- getSession
let final_ic = extendInteractiveContextWithIds (hsc_IC hsc_env) final_ids
final_names = map getName final_ids
liftIO $ Linker.extendLinkEnv (zip final_names hvals)
hsc_env' <- liftIO $ rttiEnvironment hsc_env{hsc_IC=final_ic}
modifySession (\_ -> hsc_env')
return (RunOk final_names)
| otherwise
= panic "handleRunStatus" -- The above cases are in fact exhaustive
isBreakEnabled :: HscEnv -> BreakInfo -> IO Bool
isBreakEnabled hsc_env inf =
case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
Just hmi -> do
w <- getBreak (hsc_dflags hsc_env)
(modBreaks_flags (getModBreaks hmi))
(breakInfo_number inf)
case w of Just n -> return (n /= 0); _other -> return False
_ ->
return False
foreign import ccall "&rts_stop_next_breakpoint" stepFlag :: Ptr CInt
foreign import ccall "&rts_stop_on_exception" exceptionFlag :: Ptr CInt
setStepFlag :: IO ()
setStepFlag = poke stepFlag 1
resetStepFlag :: IO ()
resetStepFlag = poke stepFlag 0
-- this points to the IO action that is executed when a breakpoint is hit
foreign import ccall "&rts_breakpoint_io_action"
breakPointIOAction :: Ptr (StablePtr (Bool -> BreakInfo -> HValue -> IO ()))
-- When running a computation, we redirect ^C exceptions to the running
-- thread. ToDo: we might want a way to continue even if the target
-- thread doesn't die when it receives the exception... "this thread
-- is not responding".
--
-- Careful here: there may be ^C exceptions flying around, so we start the new
-- thread blocked (forkIO inherits mask from the parent, #1048), and unblock
-- only while we execute the user's code. We can't afford to lose the final
-- putMVar, otherwise deadlock ensues. (#1583, #1922, #1946)
sandboxIO :: DynFlags -> MVar Status -> IO [HValue] -> IO Status
sandboxIO dflags statusMVar thing =
mask $ \restore -> -- fork starts blocked
let runIt = liftM Complete $ try (restore $ rethrow dflags thing)
in if gopt Opt_GhciSandbox dflags
then do tid <- forkIO $ do res <- runIt
putMVar statusMVar res -- empty: can't block
redirectInterrupts tid $
takeMVar statusMVar
else -- GLUT on OS X needs to run on the main thread. If you
-- try to use it from another thread then you just get a
-- white rectangle rendered. For this, or anything else
-- with such restrictions, you can turn the GHCi sandbox off
-- and things will be run in the main thread.
--
-- BUT, note that the debugging features (breakpoints,
-- tracing, etc.) need the expression to be running in a
-- separate thread, so debugging is only enabled when
-- using the sandbox.
runIt
--
-- While we're waiting for the sandbox thread to return a result, if
-- the current thread receives an asynchronous exception we re-throw
-- it at the sandbox thread and continue to wait.
--
-- This is for two reasons:
--
-- * So that ^C interrupts runStmt (e.g. in GHCi), allowing the
-- computation to run its exception handlers before returning the
-- exception result to the caller of runStmt.
--
-- * clients of the GHC API can terminate a runStmt in progress
-- without knowing the ThreadId of the sandbox thread (#1381)
--
-- NB. use a weak pointer to the thread, so that the thread can still
-- be considered deadlocked by the RTS and sent a BlockedIndefinitely
-- exception. A symptom of getting this wrong is that conc033(ghci)
-- will hang.
--
redirectInterrupts :: ThreadId -> IO a -> IO a
redirectInterrupts target wait
= do wtid <- mkWeakThreadId target
wait `catch` \e -> do
m <- deRefWeak wtid
case m of
Nothing -> wait
Just target -> do throwTo target (e :: SomeException); wait
-- We want to turn ^C into a break when -fbreak-on-exception is on,
-- but it's an async exception and we only break for sync exceptions.
-- Idea: if we catch and re-throw it, then the re-throw will trigger
-- a break. Great - but we don't want to re-throw all exceptions, because
-- then we'll get a double break for ordinary sync exceptions (you'd have
-- to :continue twice, which looks strange). So if the exception is
-- not "Interrupted", we unset the exception flag before throwing.
--
rethrow :: DynFlags -> IO a -> IO a
rethrow dflags io = Exception.catch io $ \se -> do
-- If -fbreak-on-error, we break unconditionally,
-- but with care of not breaking twice
if gopt Opt_BreakOnError dflags &&
not (gopt Opt_BreakOnException dflags)
then poke exceptionFlag 1
else case fromException se of
-- If it is a "UserInterrupt" exception, we allow
-- a possible break by way of -fbreak-on-exception
Just UserInterrupt -> return ()
-- In any other case, we don't want to break
_ -> poke exceptionFlag 0
Exception.throwIO se
-- This function sets up the interpreter for catching breakpoints, and
-- resets everything when the computation has stopped running. This
-- is a not-very-good way to ensure that only the interactive
-- evaluation should generate breakpoints.
withBreakAction :: (ExceptionMonad m, MonadIO m) =>
Bool -> DynFlags -> MVar () -> MVar Status -> m a -> m a
withBreakAction step dflags breakMVar statusMVar act
= gbracket (liftIO setBreakAction) (liftIO . resetBreakAction) (\_ -> act)
where
setBreakAction = do
stablePtr <- newStablePtr onBreak
poke breakPointIOAction stablePtr
when (gopt Opt_BreakOnException dflags) $ poke exceptionFlag 1
when step $ setStepFlag
return stablePtr
-- Breaking on exceptions is not enabled by default, since it
-- might be a bit surprising. The exception flag is turned off
-- as soon as it is hit, or in resetBreakAction below.
onBreak is_exception info apStack = do
tid <- myThreadId
putMVar statusMVar (Break is_exception apStack info tid)
takeMVar breakMVar
resetBreakAction stablePtr = do
poke breakPointIOAction noBreakStablePtr
poke exceptionFlag 0
resetStepFlag
freeStablePtr stablePtr
noBreakStablePtr :: StablePtr (Bool -> BreakInfo -> HValue -> IO ())
noBreakStablePtr = unsafePerformIO $ newStablePtr noBreakAction
noBreakAction :: Bool -> BreakInfo -> HValue -> IO ()
noBreakAction False _ _ = putStrLn "*** Ignoring breakpoint"
noBreakAction True _ _ = return () -- exception: just continue
resume :: GhcMonad m => (SrcSpan->Bool) -> SingleStep -> m RunResult
resume canLogSpan step
= do
hsc_env <- getSession
let ic = hsc_IC hsc_env
resume = ic_resume ic
case resume of
[] -> liftIO $
throwGhcExceptionIO (ProgramError "not stopped at a breakpoint")
(r:rs) -> do
-- unbind the temporary locals by restoring the TypeEnv from
-- before the breakpoint, and drop this Resume from the
-- InteractiveContext.
let (resume_tmp_te,resume_rdr_env) = resumeBindings r
ic' = ic { ic_tythings = resume_tmp_te,
ic_rn_gbl_env = resume_rdr_env,
ic_resume = rs }
modifySession (\_ -> hsc_env{ hsc_IC = ic' })
-- remove any bindings created since the breakpoint from the
-- linker's environment
let new_names = map getName (filter (`notElem` resume_tmp_te)
(ic_tythings ic))
liftIO $ Linker.deleteFromLinkEnv new_names
when (isStep step) $ liftIO setStepFlag
case r of
Resume { resumeStmt = expr, resumeThreadId = tid
, resumeBreakMVar = breakMVar, resumeStatMVar = statusMVar
, resumeBindings = bindings, resumeFinalIds = final_ids
, resumeApStack = apStack, resumeBreakInfo = info, resumeSpan = span
, resumeHistory = hist } -> do
withVirtualCWD $ do
withBreakAction (isStep step) (hsc_dflags hsc_env)
breakMVar statusMVar $ do
status <- liftIO $ mask_ $ do
putMVar breakMVar ()
-- this awakens the stopped thread...
redirectInterrupts tid $
takeMVar statusMVar
-- and wait for the result
let prevHistoryLst = fromListBL 50 hist
hist' = case info of
Nothing -> prevHistoryLst
Just i
| not $canLogSpan span -> prevHistoryLst
| otherwise -> mkHistory hsc_env apStack i `consBL`
fromListBL 50 hist
handleRunStatus step expr bindings final_ids
breakMVar statusMVar status hist'
back :: GhcMonad m => m ([Name], Int, SrcSpan)
back = moveHist (+1)
forward :: GhcMonad m => m ([Name], Int, SrcSpan)
forward = moveHist (subtract 1)
moveHist :: GhcMonad m => (Int -> Int) -> m ([Name], Int, SrcSpan)
moveHist fn = do
hsc_env <- getSession
case ic_resume (hsc_IC hsc_env) of
[] -> liftIO $
throwGhcExceptionIO (ProgramError "not stopped at a breakpoint")
(r:rs) -> do
let ix = resumeHistoryIx r
history = resumeHistory r
new_ix = fn ix
--
when (new_ix > length history) $ liftIO $
throwGhcExceptionIO (ProgramError "no more logged breakpoints")
when (new_ix < 0) $ liftIO $
throwGhcExceptionIO (ProgramError "already at the beginning of the history")
let
update_ic apStack mb_info = do
(hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env
apStack mb_info
let ic = hsc_IC hsc_env1
r' = r { resumeHistoryIx = new_ix }
ic' = ic { ic_resume = r':rs }
modifySession (\_ -> hsc_env1{ hsc_IC = ic' })
return (names, new_ix, span)
-- careful: we want apStack to be the AP_STACK itself, not a thunk
-- around it, hence the cases are carefully constructed below to
-- make this the case. ToDo: this is v. fragile, do something better.
if new_ix == 0
then case r of
Resume { resumeApStack = apStack,
resumeBreakInfo = mb_info } ->
update_ic apStack mb_info
else case history !! (new_ix - 1) of
History apStack info _ ->
update_ic apStack (Just info)
-- -----------------------------------------------------------------------------
-- After stopping at a breakpoint, add free variables to the environment
result_fs :: FastString
result_fs = fsLit "_result"
bindLocalsAtBreakpoint
:: HscEnv
-> HValue
-> Maybe BreakInfo
-> IO (HscEnv, [Name], SrcSpan)
-- Nothing case: we stopped when an exception was raised, not at a
-- breakpoint. We have no location information or local variables to
-- bind, all we can do is bind a local variable to the exception
-- value.
bindLocalsAtBreakpoint hsc_env apStack Nothing = do
let exn_fs = fsLit "_exception"
exn_name = mkInternalName (getUnique exn_fs) (mkVarOccFS exn_fs) span
e_fs = fsLit "e"
e_name = mkInternalName (getUnique e_fs) (mkTyVarOccFS e_fs) span
e_tyvar = mkRuntimeUnkTyVar e_name liftedTypeKind
exn_id = Id.mkVanillaGlobal exn_name (mkTyVarTy e_tyvar)
ictxt0 = hsc_IC hsc_env
ictxt1 = extendInteractiveContextWithIds ictxt0 [exn_id]
span = mkGeneralSrcSpan (fsLit "<exception thrown>")
--
Linker.extendLinkEnv [(exn_name, unsafeCoerce# apStack)]
return (hsc_env{ hsc_IC = ictxt1 }, [exn_name], span)
-- Just case: we stopped at a breakpoint, we have information about the location
-- of the breakpoint and the free variables of the expression.
bindLocalsAtBreakpoint hsc_env apStack (Just info) = do
let
mod_name = moduleName (breakInfo_module info)
hmi = expectJust "bindLocalsAtBreakpoint" $
lookupUFM (hsc_HPT hsc_env) mod_name
breaks = getModBreaks hmi
index = breakInfo_number info
vars = breakInfo_vars info
result_ty = breakInfo_resty info
occs = modBreaks_vars breaks ! index
span = modBreaks_locs breaks ! index
-- Filter out any unboxed ids;
-- we can't bind these at the prompt
pointers = filter (\(id,_) -> isPointer id) vars
isPointer id | UnaryRep ty <- repType (idType id)
, PtrRep <- typePrimRep ty = True
| otherwise = False
(ids, offsets) = unzip pointers
free_tvs = mapUnionVarSet (tyVarsOfType . idType) ids
`unionVarSet` tyVarsOfType result_ty
-- It might be that getIdValFromApStack fails, because the AP_STACK
-- has been accidentally evaluated, or something else has gone wrong.
-- So that we don't fall over in a heap when this happens, just don't
-- bind any free variables instead, and we emit a warning.
mb_hValues <- mapM (getIdValFromApStack apStack) (map fromIntegral offsets)
let filtered_ids = [ id | (id, Just _hv) <- zip ids mb_hValues ]
when (any isNothing mb_hValues) $
debugTraceMsg (hsc_dflags hsc_env) 1 $
text "Warning: _result has been evaluated, some bindings have been lost"
us <- mkSplitUniqSupply 'I'
let (us1, us2) = splitUniqSupply us
tv_subst = newTyVars us1 free_tvs
new_ids = zipWith3 (mkNewId tv_subst) occs filtered_ids (uniqsFromSupply us2)
names = map idName new_ids
-- make an Id for _result. We use the Unique of the FastString "_result";
-- we don't care about uniqueness here, because there will only be one
-- _result in scope at any time.
let result_name = mkInternalName (getUnique result_fs)
(mkVarOccFS result_fs) span
result_id = Id.mkVanillaGlobal result_name (substTy tv_subst result_ty)
-- for each Id we're about to bind in the local envt:
-- - tidy the type variables
-- - globalise the Id (Ids are supposed to be Global, apparently).
--
let result_ok = isPointer result_id
all_ids | result_ok = result_id : new_ids
| otherwise = new_ids
id_tys = map idType all_ids
(_,tidy_tys) = tidyOpenTypes emptyTidyEnv id_tys
final_ids = zipWith setIdType all_ids tidy_tys
ictxt0 = hsc_IC hsc_env
ictxt1 = extendInteractiveContextWithIds ictxt0 final_ids
Linker.extendLinkEnv [ (name,hval) | (name, Just hval) <- zip names mb_hValues ]
when result_ok $ Linker.extendLinkEnv [(result_name, unsafeCoerce# apStack)]
hsc_env1 <- rttiEnvironment hsc_env{ hsc_IC = ictxt1 }
return (hsc_env1, if result_ok then result_name:names else names, span)
where
-- We need a fresh Unique for each Id we bind, because the linker
-- state is single-threaded and otherwise we'd spam old bindings
-- whenever we stop at a breakpoint. The InteractveContext is properly
-- saved/restored, but not the linker state. See #1743, test break026.
mkNewId :: TvSubst -> OccName -> Id -> Unique -> Id
mkNewId tv_subst occ id uniq
= Id.mkVanillaGlobalWithInfo name ty (idInfo id)
where
loc = nameSrcSpan (idName id)
name = mkInternalName uniq occ loc
ty = substTy tv_subst (idType id)
newTyVars :: UniqSupply -> TcTyVarSet -> TvSubst
-- Similarly, clone the type variables mentioned in the types
-- we have here, *and* make them all RuntimeUnk tyars
newTyVars us tvs
= mkTopTvSubst [ (tv, mkTyVarTy (mkRuntimeUnkTyVar name (tyVarKind tv)))
| (tv, uniq) <- varSetElems tvs `zip` uniqsFromSupply us
, let name = setNameUnique (tyVarName tv) uniq ]
rttiEnvironment :: HscEnv -> IO HscEnv
rttiEnvironment hsc_env@HscEnv{hsc_IC=ic} = do
let tmp_ids = [id | AnId id <- ic_tythings ic]
incompletelyTypedIds =
[id | id <- tmp_ids
, not $ noSkolems id
, (occNameFS.nameOccName.idName) id /= result_fs]
hsc_env' <- foldM improveTypes hsc_env (map idName incompletelyTypedIds)
return hsc_env'
where
noSkolems = isEmptyVarSet . tyVarsOfType . idType
improveTypes hsc_env@HscEnv{hsc_IC=ic} name = do
let tmp_ids = [id | AnId id <- ic_tythings ic]
Just id = find (\i -> idName i == name) tmp_ids
if noSkolems id
then return hsc_env
else do
mb_new_ty <- reconstructType hsc_env 10 id
let old_ty = idType id
case mb_new_ty of
Nothing -> return hsc_env
Just new_ty -> do
case improveRTTIType hsc_env old_ty new_ty of
Nothing -> return $
WARN(True, text (":print failed to calculate the "
++ "improvement for a type")) hsc_env
Just subst -> do
let dflags = hsc_dflags hsc_env
when (dopt Opt_D_dump_rtti dflags) $
printInfoForUser dflags alwaysQualify $
fsep [text "RTTI Improvement for", ppr id, equals, ppr subst]
let ic' = substInteractiveContext ic subst
return hsc_env{hsc_IC=ic'}
getIdValFromApStack :: HValue -> Int -> IO (Maybe HValue)
getIdValFromApStack apStack (I# stackDepth) = do
case getApStackVal# apStack (stackDepth +# 1#) of
-- The +1 is magic! I don't know where it comes
-- from, but this makes things line up. --SDM
(# ok, result #) ->
case ok of
0# -> return Nothing -- AP_STACK not found
_ -> return (Just (unsafeCoerce# result))
pushResume :: HscEnv -> Resume -> HscEnv
pushResume hsc_env resume = hsc_env { hsc_IC = ictxt1 }
where
ictxt0 = hsc_IC hsc_env
ictxt1 = ictxt0 { ic_resume = resume : ic_resume ictxt0 }
-- -----------------------------------------------------------------------------
-- Abandoning a resume context
abandon :: GhcMonad m => m Bool
abandon = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
resume = ic_resume ic
case resume of
[] -> return False
r:rs -> do
modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = rs } }
liftIO $ abandon_ r
return True
abandonAll :: GhcMonad m => m Bool
abandonAll = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
resume = ic_resume ic
case resume of
[] -> return False
rs -> do
modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = [] } }
liftIO $ mapM_ abandon_ rs
return True
-- when abandoning a computation we have to
-- (a) kill the thread with an async exception, so that the
-- computation itself is stopped, and
-- (b) fill in the MVar. This step is necessary because any
-- thunks that were under evaluation will now be updated
-- with the partial computation, which still ends in takeMVar,
-- so any attempt to evaluate one of these thunks will block
-- unless we fill in the MVar.
-- (c) wait for the thread to terminate by taking its status MVar. This
-- step is necessary to prevent race conditions with
-- -fbreak-on-exception (see #5975).
-- See test break010.
abandon_ :: Resume -> IO ()
abandon_ r = do
killThread (resumeThreadId r)
putMVar (resumeBreakMVar r) ()
_ <- takeMVar (resumeStatMVar r)
return ()
-- -----------------------------------------------------------------------------
-- Bounded list, optimised for repeated cons
data BoundedList a = BL
{-# UNPACK #-} !Int -- length
{-# UNPACK #-} !Int -- bound
[a] -- left
[a] -- right, list is (left ++ reverse right)
nilBL :: Int -> BoundedList a
nilBL bound = BL 0 bound [] []
consBL :: a -> BoundedList a -> BoundedList a
consBL a (BL len bound left right)
| len < bound = BL (len+1) bound (a:left) right
| null right = BL len bound [a] $! tail (reverse left)
| otherwise = BL len bound (a:left) $! tail right
toListBL :: BoundedList a -> [a]
toListBL (BL _ _ left right) = left ++ reverse right
fromListBL :: Int -> [a] -> BoundedList a
fromListBL bound l = BL (length l) bound l []
-- lenBL (BL len _ _ _) = len
-- -----------------------------------------------------------------------------
-- | Set the interactive evaluation context.
--
-- (setContext imports) sets the ic_imports field (which in turn
-- determines what is in scope at the prompt) to 'imports', and
-- constructs the ic_rn_glb_env environment to reflect it.
--
-- We retain in scope all the things defined at the prompt, and kept
-- in ic_tythings. (Indeed, they shadow stuff from ic_imports.)
setContext :: GhcMonad m => [InteractiveImport] -> m ()
setContext imports
= do { hsc_env <- getSession
; let dflags = hsc_dflags hsc_env
; all_env_err <- liftIO $ findGlobalRdrEnv hsc_env imports
; case all_env_err of
Left (mod, err) ->
liftIO $ throwGhcExceptionIO (formatError dflags mod err)
Right all_env -> do {
; let old_ic = hsc_IC hsc_env
final_rdr_env = all_env `icExtendGblRdrEnv` ic_tythings old_ic
; modifySession $ \_ ->
hsc_env{ hsc_IC = old_ic { ic_imports = imports
, ic_rn_gbl_env = final_rdr_env }}}}
where
formatError dflags mod err = ProgramError . showSDoc dflags $
text "Cannot add module" <+> ppr mod <+>
text "to context:" <+> text err
findGlobalRdrEnv :: HscEnv -> [InteractiveImport]
-> IO (Either (ModuleName, String) GlobalRdrEnv)
-- Compute the GlobalRdrEnv for the interactive context
findGlobalRdrEnv hsc_env imports
= do { idecls_env <- hscRnImportDecls hsc_env idecls
-- This call also loads any orphan modules
; return $ case partitionEithers (map mkEnv imods) of
([], imods_env) -> Right (foldr plusGlobalRdrEnv idecls_env imods_env)
(err : _, _) -> Left err }
where
idecls :: [LImportDecl RdrName]
idecls = [noLoc d | IIDecl d <- imports]
imods :: [ModuleName]
imods = [m | IIModule m <- imports]
mkEnv mod = case mkTopLevEnv (hsc_HPT hsc_env) mod of
Left err -> Left (mod, err)
Right env -> Right env
availsToGlobalRdrEnv :: ModuleName -> [AvailInfo] -> GlobalRdrEnv
availsToGlobalRdrEnv mod_name avails
= mkGlobalRdrEnv (gresFromAvails imp_prov avails)
where
-- We're building a GlobalRdrEnv as if the user imported
-- all the specified modules into the global interactive module
imp_prov = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
is_qual = False,
is_dloc = srcLocSpan interactiveSrcLoc }
mkTopLevEnv :: HomePackageTable -> ModuleName -> Either String GlobalRdrEnv
mkTopLevEnv hpt modl
= case lookupUFM hpt modl of
Nothing -> Left "not a home module"
Just details ->
case mi_globals (hm_iface details) of
Nothing -> Left "not interpreted"
Just env -> Right env
-- | Get the interactive evaluation context, consisting of a pair of the
-- set of modules from which we take the full top-level scope, and the set
-- of modules from which we take just the exports respectively.
getContext :: GhcMonad m => m [InteractiveImport]
getContext = withSession $ \HscEnv{ hsc_IC=ic } ->
return (ic_imports ic)
-- | Returns @True@ if the specified module is interpreted, and hence has
-- its full top-level scope available.
moduleIsInterpreted :: GhcMonad m => Module -> m Bool
moduleIsInterpreted modl = withSession $ \h ->
if modulePackageKey modl /= thisPackage (hsc_dflags h)
then return False
else case lookupUFM (hsc_HPT h) (moduleName modl) of
Just details -> return (isJust (mi_globals (hm_iface details)))
_not_a_home_module -> return False
-- | Looks up an identifier in the current interactive context (for :info)
-- Filter the instances by the ones whose tycons (or clases resp)
-- are in scope (qualified or otherwise). Otherwise we list a whole lot too many!
-- The exact choice of which ones to show, and which to hide, is a judgement call.
-- (see Trac #1581)
getInfo :: GhcMonad m => Bool -> Name -> m (Maybe (TyThing,Fixity,[ClsInst],[FamInst]))
getInfo allInfo name
= withSession $ \hsc_env ->
do mb_stuff <- liftIO $ hscTcRnGetInfo hsc_env name
case mb_stuff of
Nothing -> return Nothing
Just (thing, fixity, cls_insts, fam_insts) -> do
let rdr_env = ic_rn_gbl_env (hsc_IC hsc_env)
-- Filter the instances based on whether the constituent names of their
-- instance heads are all in scope.
let cls_insts' = filter (plausible rdr_env . orphNamesOfClsInst) cls_insts
fam_insts' = filter (plausible rdr_env . orphNamesOfFamInst) fam_insts
return (Just (thing, fixity, cls_insts', fam_insts'))
where
plausible rdr_env names
-- Dfun involving only names that are in ic_rn_glb_env
= allInfo
|| all ok (nameSetElems names)
where -- A name is ok if it's in the rdr_env,
-- whether qualified or not
ok n | n == name = True -- The one we looked for in the first place!
| isBuiltInSyntax n = True
| isExternalName n = any ((== n) . gre_name)
(lookupGRE_Name rdr_env n)
| otherwise = True
-- | Returns all names in scope in the current interactive context
getNamesInScope :: GhcMonad m => m [Name]
getNamesInScope = withSession $ \hsc_env -> do
return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
getRdrNamesInScope :: GhcMonad m => m [RdrName]
getRdrNamesInScope = withSession $ \hsc_env -> do
let
ic = hsc_IC hsc_env
gbl_rdrenv = ic_rn_gbl_env ic
gbl_names = concatMap greToRdrNames $ globalRdrEnvElts gbl_rdrenv
return gbl_names
-- ToDo: move to RdrName
greToRdrNames :: GlobalRdrElt -> [RdrName]
greToRdrNames GRE{ gre_name = name, gre_prov = prov }
= case prov of
LocalDef -> [unqual]
Imported specs -> concat (map do_spec (map is_decl specs))
where
occ = nameOccName name
unqual = Unqual occ
do_spec decl_spec
| is_qual decl_spec = [qual]
| otherwise = [unqual,qual]
where qual = Qual (is_as decl_spec) occ
-- | Parses a string as an identifier, and returns the list of 'Name's that
-- the identifier can refer to in the current interactive context.
parseName :: GhcMonad m => String -> m [Name]
parseName str = withSession $ \hsc_env -> liftIO $
do { lrdr_name <- hscParseIdentifier hsc_env str
; hscTcRnLookupRdrName hsc_env lrdr_name }
-- -----------------------------------------------------------------------------
-- Getting the type of an expression
-- | Get the type of an expression
-- Returns its most general type
exprType :: GhcMonad m => String -> m Type
exprType expr = withSession $ \hsc_env -> do
ty <- liftIO $ hscTcExpr hsc_env expr
return $ tidyType emptyTidyEnv ty
-- -----------------------------------------------------------------------------
-- Getting the kind of a type
-- | Get the kind of a type
typeKind :: GhcMonad m => Bool -> String -> m (Type, Kind)
typeKind normalise str = withSession $ \hsc_env -> do
liftIO $ hscKcType hsc_env normalise str
-----------------------------------------------------------------------------
-- Compile an expression, run it and deliver the resulting HValue
compileExpr :: GhcMonad m => String -> m HValue
compileExpr expr = withSession $ \hsc_env -> do
Just (ids, hval, fix_env) <- liftIO $ hscStmt hsc_env ("let __cmCompileExpr = "++expr)
updateFixityEnv fix_env
hvals <- liftIO hval
case (ids,hvals) of
([_],[hv]) -> return hv
_ -> panic "compileExpr"
-- -----------------------------------------------------------------------------
-- Compile an expression, run it and return the result as a dynamic
dynCompileExpr :: GhcMonad m => String -> m Dynamic
dynCompileExpr expr = do
iis <- getContext
let importDecl = ImportDecl {
ideclSourceSrc = Nothing,
ideclName = noLoc (mkModuleName "Data.Dynamic"),
ideclPkgQual = Nothing,
ideclSource = False,
ideclSafe = False,
ideclQualified = True,
ideclImplicit = False,
ideclAs = Nothing,
ideclHiding = Nothing
}
setContext (IIDecl importDecl : iis)
let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
Just (ids, hvals, fix_env) <- withSession $ \hsc_env ->
liftIO $ hscStmt hsc_env stmt
setContext iis
updateFixityEnv fix_env
vals <- liftIO (unsafeCoerce# hvals :: IO [Dynamic])
case (ids,vals) of
(_:[], v:[]) -> return v
_ -> panic "dynCompileExpr"
-----------------------------------------------------------------------------
-- show a module and it's source/object filenames
showModule :: GhcMonad m => ModSummary -> m String
showModule mod_summary =
withSession $ \hsc_env -> do
interpreted <- isModuleInterpreted mod_summary
let dflags = hsc_dflags hsc_env
return (showModMsg dflags (hscTarget dflags) interpreted mod_summary)
isModuleInterpreted :: GhcMonad m => ModSummary -> m Bool
isModuleInterpreted mod_summary = withSession $ \hsc_env ->
case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
Nothing -> panic "missing linkable"
Just mod_info -> return (not obj_linkable)
where
obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
----------------------------------------------------------------------------
-- RTTI primitives
obtainTermFromVal :: HscEnv -> Int -> Bool -> Type -> a -> IO Term
obtainTermFromVal hsc_env bound force ty x =
cvObtainTerm hsc_env bound force ty (unsafeCoerce# x)
obtainTermFromId :: HscEnv -> Int -> Bool -> Id -> IO Term
obtainTermFromId hsc_env bound force id = do
hv <- Linker.getHValue hsc_env (varName id)
cvObtainTerm hsc_env bound force (idType id) hv
-- Uses RTTI to reconstruct the type of an Id, making it less polymorphic
reconstructType :: HscEnv -> Int -> Id -> IO (Maybe Type)
reconstructType hsc_env bound id = do
hv <- Linker.getHValue hsc_env (varName id)
cvReconstructType hsc_env bound (idType id) hv
mkRuntimeUnkTyVar :: Name -> Kind -> TyVar
mkRuntimeUnkTyVar name kind = mkTcTyVar name kind RuntimeUnk
#endif /* GHCI */
| alexander-at-github/eta | compiler/ETA/Main/InteractiveEval.hs | bsd-3-clause | 42,109 | 13 | 34 | 11,838 | 9,071 | 4,660 | 4,411 | 2 | 0 |
{-# LANGUAGE CPP, BangPatterns #-}
--------------------------------------------------------------------------------
-- |
-- Module : GalFld.Algorithmen.Berlekamp
-- Note : Implementiert eine Berlekamp Faktorisierung
--
-- Funktioniert nur auf Quadratfreien Polynomen
--
-- Enthält den 1967 von Elwyn Berlekamp enwickelten Berlekamp-Algorithmus zur
-- Faktorisierung von Polynomen über endlichen Körpern.
--
--------------------------------------------------------------------------------
module GalFld.Algorithmen.Berlekamp
( appBerlekamp, sffAndBerlekamp
, findIrred, findIrreds, findTrivialsB
-- Algorithmus
, berlekampBasis
, berlekampFactor
)where
import Data.Maybe
import Data.List
import Control.Monad
import Control.Parallel
import Control.Parallel.Strategies
import GalFld.Core
import GalFld.Algorithmen.SFreeFactorization
--------------------------------------------------------------------------------
-- Wrapper
appBerlekamp :: (Show a, FiniteField a, Num a, Fractional a) =>
[(Int,Polynom a)] -> [(Int,Polynom a)]
appBerlekamp = appFact berlekampFactor
-- |Faktorisiert ein Polynom f über einem endlichen Körper
-- Benutzt wird dazu die Quadratfreie Faktorisierung mit anschließendem
-- Berlekamp
sffAndBerlekamp :: (Show a, Fractional a, Num a, FiniteField a)
=> Polynom a -> [(Int,Polynom a)]
sffAndBerlekamp f = appBerlekamp $ sff f
-- |Wählt aus einer Liste von Polynomen das erste Irreduzibele Polynom heraus
findIrred :: (Show a, Fractional a, Num a, FiniteField a) =>
[Polynom a] -> Polynom a
findIrred = head . findIrreds
-- |Filtert mittels SFF und Berlekamp aus einer Liste die irreduzibleneiner
-- liste heraus
#if 0
-- Ist lazy.
findIrreds :: (Show a, Fractional a, Num a, FiniteField a) => [Polynom a] -> [Polynom a]
findIrreds (f:fs) = findIrreds' (f:fs)
where findIrreds' [] = []
findIrreds' (f:fs)
| (not (hasNs f es) || uDegP f < 2)
&& isTrivialFact fSff
&& isTrivialFact fB = f : findIrreds' fs
| otherwise = findIrreds' fs
where fSff = appSff $ toFact f
fB = appBerlekamp fSff
es = elems $ getReprP f
#else
-- mit backtracking
findIrreds fs = do
f <- fs
let fSff = appSff $ toFact f
guard (isTrivialFact fSff)
let fB = appBerlekamp fSff
guard (isTrivialFact fB)
return f
#endif
-- |Gibt alle Faktorisierungen zurück, welche nach Berlekamp noch trivial sind
-- Wendet zuvor (die offensichtliche Faktorisierung und) SFF an
--
-- Ist parallelisiert mittels Strategie rpar.
findTrivialsB :: (Show a, Fractional a, Num a, FiniteField a) =>
[Polynom a] -> [[(Int,Polynom a)]]
findTrivialsB ps = [fs | fs <- parMap rpar appBerlekamp (findTrivialsSff ps)
, isTrivialFact fs]
--------------------------------------------------------------------------------
-- Algorithmus
-- |Berechnet eine Basis des Berlekampraums zu f,
-- d.h. gibt eine Matrix zurück, deren Zeilen gerade den Berlekampraum
-- aufspannen bzgl der kanonischen Basis { 1, x, x², x³, ... }
berlekampBasis :: (Show a, Fractional a, Num a, FiniteField a)
=> Polynom a -> Matrix a
berlekampBasis f = transposeM $ kernelM $ transposeM $!
fromListsM [red i | i <- [0..(n-1)]] - genDiagM 1 n
where !n = fromJust $ degP f
!q = elemCount a
!a = getReprP f
{-# INLINE red #-}
red i = takeFill 0 n $ p2List $ modByP (pTupUnsave [(i*q,1)]) f
-- |Faktorisiert ein Polynom f über einem endlichen Körper
-- Voraussetzungen: f ist quadratfrei
-- Ausgabe: Liste von irreduziblen, pw teilerfremden Polynomen
berlekampFactor :: (Show a, Fractional a, Num a, FiniteField a)
=> Polynom a -> [(Int,Polynom a)]
berlekampFactor f | isNullP f = []
| uDegP f < 2 = [(1,f)]
| otherwise = berlekampFactor' f m
where !m = berlekampBasis f
{-# INLINE berlekampFactor' #-}
berlekampFactor' :: (Show a, Num a, Fractional a, FiniteField a)
=> Polynom a -> Matrix a -> [(Int,Polynom a)]
berlekampFactor' f m | uDegP f <= 1 = [(1,f)]
| getNumRowsM m == 1 = [(1,f)]
| otherwise =
berlekampFactor' g n ++ berlekampFactor' g' n'
where {-# INLINE g #-}
g = head [x | x <- [ggTP f (h - pKonst s)
| s <- elems (getReprP f)] , x /= 1]
{-# INLINE g' #-}
g' = f @/ g
{-# INLINE h #-}
h = pList $ getRowM m 2
{-# INLINE n #-}
n = newKer m g
{-# INLINE n' #-}
n' = newKer m g'
{-# INLINE newKer #-}
newKer m g = fromListsM $! take r m'
where !(k,l) = boundsM m
!m' = toListsM $ echelonM $ fromListsM
[takeFill 0 l $ p2List $
modByP (pList (getRowM m i)) g | i <- [1..k]]
!r = k-1- fromMaybe (-1) (findIndex (all (==0))
$ reverse m')
{-# INLINE takeFill #-}
takeFill :: Num a => a -> Int -> [a] -> [a]
takeFill a n [] = replicate n a
takeFill a n (x:xs) = x : takeFill a (n-1) xs
#if 0
-- |Faktorisiert ein Polynom f über einem endlichen Körper
-- Voraussetzungen: f ist quadratfrei
-- Ausgabe: Liste von irreduziblen, pw teilerfremden Polynomen
--
-- ACHTUNG: dieser Algorithmus ist NOCH NICHT FERTIG implementiert.
-- Er liefert NUR MEISTENS das richtige und sollte nicht verwendet
-- werden.
--
berlekampFactor2 :: (Show a, Fractional a, Num a, FiniteField a)
=> Polynom a -> [(Int,Polynom a)]
berlekampFactor2 f | isNullP f = []
| uDegP f < 2 = [(1,f)]
| otherwise = berlekampFactor' f m
where !m = berlekampBasis f
{-# INLINE berlekampFactor' #-}
berlekampFactor' :: (Show a, Num a, Fractional a, FiniteField a)
=> Polynom a -> Matrix a -> [(Int,Polynom a)]
berlekampFactor' f m | uDegP f <= 1 = [(1,f)]
| getNumRowsM m == 1 = [(1,f)]
| otherwise =
concat [berlekampFactor' g (newKer m g) | g <- gs]
where {-# INLINE gs #-}
gs = [x | x <- [ggTP f (h - pKonst s)
| s <- elems (getReprP f)] , x /= 1]
{-# INLINE h #-}
h = pList $ getRowM m 2
{-# INLINE newKer #-}
newKer m g = fromListsM $! take r m'
where !(k,l) = boundsM m
!m' = toListsM $ echelonM $ fromListsM
[takeFill 0 l $ p2List $
modByP (pList (getRowM m i)) g | i <- [1..k]]
!r = k-1- fromMaybe (-1) (findIndex (all (==0))
$ reverse m')
#endif
| maximilianhuber/softwareProjekt | src/GalFld/Algorithmen/Berlekamp.hs | bsd-3-clause | 7,557 | 0 | 19 | 2,749 | 1,893 | 985 | 908 | 78 | 1 |
{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Network.DHT.Kademlia.Workers.Persistence (persistRoutingTable) where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Concurrent.Timer
import Control.Monad
import Data.Binary
import Data.Conduit
import Data.Conduit.Network
import Data.Time.Clock
import Data.Vector ((!), (//))
import Network.DHT.Kademlia.Bucket
import Network.DHT.Kademlia.Def
import Network.DHT.Kademlia.Util
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as BL
import qualified Data.Conduit.Binary as CB
import qualified Data.Conduit.List as CL
import qualified Data.HashTable.IO as H
import qualified Data.Text as T
import qualified Data.Vector as V
-- | Periodically persist the routing table incase this node goes offline
persistRoutingTable :: KademliaEnv -> Config -> IO ()
persistRoutingTable KademliaEnv{..} config = forkIO_ $ forever $ do
threadDelay $ secToMicro 10
writeRoutingTable fp routingTable
where
fp :: FilePath
fp = T.unpack $ cfgRoutingTablePath config
| phylake/kademlia | Network/DHT/Kademlia/Workers/Persistence.hs | bsd-3-clause | 1,315 | 0 | 9 | 268 | 251 | 162 | 89 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Bot.Action.Maven
( maven
, version
, parentVersion
, changeDependencyVersion
, updateDependencyVersions
, properties
, snapshots
) where
import Bot.Action.Action
import Bot.Action.XML
import Bot.Types
import Bot.Util
import Control.Arrow
import Control.Monad
import Control.Monad.IO.Class
import Data.List (inits)
import Data.Monoid ((<>))
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Text.XML.Light as X
import System.Directory
maven :: Text -> [(Text, [Text])] -> Project -> Action
maven cmd projectProfiles project = do
let path = projectPath project
isMavenProject <- liftIO $ doesFileExist $ path ++ "/pom.xml"
unless isMavenProject $ do
throwA $ "Not a project (pom.xml not found): {}" % pack path
let profiles = case lookup (projectName project) projectProfiles of
Nothing -> ""
Just ps -> "-P" <> (T.intercalate "," ps)
output <- silentProjectCommand ("mvn {} {}" %% (profiles, cmd)) project
liftIO $
if "BUILD FAILURE" `T.isInfixOf` output
then do
T.putStrLn $ red xMarkChar <> ". Command implicitly failed with 'BUILD FAILURE' log"
showOutput output
else T.putStrLn $ green checkMarkChar
version :: Project -> Action
version project = projectVersion project >>= (liftIO . T.putStrLn)
projectVersion :: Project -> ActionM Text
projectVersion project = do
pom <- readPOM project
readSingleValue pom ["project", "version"]
parentVersion :: Project -> Action
parentVersion project = do
pom <- readPOM project
name <- readSingleValue pom ["project", "parent", "artifactId"]
version <- readSingleValue pom ["project", "parent", "version"]
liftIO $ printf "{}: {}" (name, version)
changeDependencyVersion :: Project -> Text -> Text -> Action
changeDependencyVersion project depName newVersion = do
let pomPath = projectPath project ++ "/pom.xml"
openTag = "<touch.{}.version>" % depName
closeTag = "</touch.{}.version>" % depName
void $ bash ("sed 's|\\(.*{}\\).*\\({}.*\\)|\\1{}\\2|g' -i {}" %% (openTag, closeTag, newVersion, pomPath))
updateDependencyVersions :: [Project] -> Action
updateDependencyVersions projects = do
let steps = tail $ inits projects
forM_ (zip [0..] steps) $ \(i, s) -> do
changeVersionsAction s (projects !! i)
where
changeVersionsAction :: [Project] -> Project -> Action
changeVersionsAction ps t = forM_ ps $ \p -> do
let pName = projectName p
pVersion <- projectVersion p
changeDependencyVersion t pName pVersion
properties :: Project -> Maybe ((Text, Text) -> Bool) -> Action
properties project mf = do
pom <- readPOM project
ps <- readProperties pom
let f = maybe (const True) id mf
vs = filter f ps
liftIO $ do
putStrLn ""
mapM_ (\(n,v) -> T.putStrLn . indent 1 $ "{}: {}" %% (n, v)) vs
snapshots :: Project -> Action
snapshots project = do
pom <- readPOM project
props <- readProperties pom
parentName <- readSingleValue pom ["project", "parent", "artifactId"]
parentVersion <- readSingleValue pom ["project", "parent", "version"]
let ps = ((parentName, parentVersion):props)
let f (_, v) = "SNAPSHOT" `T.isInfixOf` v
vs = filter f ps
liftIO $ do
putStrLn ""
mapM_ (\(n,v) -> T.putStrLn . indent 1 $ "{}: {}" %% (n, v)) vs
readProperties :: [X.Content] -> ActionM [(Text, Text)]
readProperties rs = do
let path = ["project", "properties"]
prop = pack . X.qName . X.elName &&& value
ps = mapElementsAt path (map prop . X.elChildren) rs
case ps of
[] -> throwA $ "Couldn't find /{}" % T.intercalate "/" path
[p] -> return p
_ -> throwA $ "Found multiple /{}" % T.intercalate "/" path
readSingleValue :: [X.Content] -> Path -> ActionM Text
readSingleValue rs path = do
let vs = mapElementsAt path value rs
case vs of
[] -> throwA $ "Couldn't find /{}" % T.intercalate "/" path
[v] -> return v
_ -> throwA $ "Found multiple /{}" % T.intercalate "/" path
readPOM :: Project -> ActionM [X.Content]
readPOM project = do
let pom = projectPath project ++ "/pom.xml"
pomExists <- liftIO $ doesFileExist pom
unless pomExists $
throwA $ "pom doesn't exist at '{}'" % pack pom
readXML pom
| andregr/bot | lib/Bot/Action/Maven.hs | bsd-3-clause | 4,303 | 0 | 16 | 918 | 1,455 | 742 | 713 | -1 | -1 |
-- This afternoon
-- 1. How do we constrain fully crossed?
-- 2. Set up minimal example
-- a. Minimal block rewrite
-- b. Does it desugar correctly?
-- c. Write tests & update the error handling
-- 3. Deal with blocks for real
-- 4. Deal with exact constraint syntax/wording & wtf is going on with transitions
-- 1. Import that fixes all the errors
-------- Experiment ---------
main :: IO ()
main = experiment (Block (fully-crossed design) theConstraints)
where
----------- Streams --------------
color = Stream "color" ["red", "blue"]
shape = Stream "shape" ["circle", "square"]
--------- Transitions --------------
---------- Constraints -------------
theConstraints = Constraints (count (None, 3) color) -- this count syntax doesn't fly
-- syntax/constructor for "no constraints"
noConstraints = []
---------- Design ------------
design = cross [color, shape]
----------- Blocks ------------ # fully crossed constraints not good enough!!!
| anniecherk/pyschocnf | notes/parser_interface/minimal.hs | bsd-3-clause | 1,067 | 0 | 10 | 263 | 131 | 78 | 53 | 7 | 1 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.AMD.FramebufferSamplePositions
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.AMD.FramebufferSamplePositions (
-- * Extension Support
glGetAMDFramebufferSamplePositions,
gl_AMD_framebuffer_sample_positions,
-- * Enums
pattern GL_ALL_PIXELS_AMD,
pattern GL_PIXELS_PER_SAMPLE_PATTERN_X_AMD,
pattern GL_PIXELS_PER_SAMPLE_PATTERN_Y_AMD,
pattern GL_SUBSAMPLE_DISTANCE_AMD,
-- * Functions
glFramebufferSamplePositionsfvAMD,
glGetFramebufferParameterfvAMD,
glGetNamedFramebufferParameterfvAMD,
glNamedFramebufferSamplePositionsfvAMD
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| haskell-opengl/OpenGLRaw | src/Graphics/GL/AMD/FramebufferSamplePositions.hs | bsd-3-clause | 1,028 | 0 | 5 | 122 | 81 | 58 | 23 | 15 | 0 |
{-# LANGUAGE TypeOperators #-}
{-# Language RebindableSyntax #-}
{-# Language ScopedTypeVariables #-}
{-# Language FlexibleContexts #-}
module Main where
import Prelude hiding ((>>=), (>>), fail, return, id, print, mod)
import Symmetry.Language
import Symmetry.Verify
import Symmetry.SymbEx
import SrcHelper
type Msg = (Pid RSing) :+: -- Poke ProcessId
Int -- Ans Int
poke_msg :: SieveSem repr => repr (Pid RSing -> Msg)
poke_msg = lam $ \pid -> inl pid
ans_msg :: SieveSem repr => repr (Int -> Msg)
ans_msg = lam $ \n -> inr n
recv_poke :: SieveSem repr => repr (Process repr (Pid RSing))
recv_poke = do msg :: repr Msg <- recv
match msg id reject
recv_ans :: SieveSem repr => repr (Process repr Int)
recv_ans = do msg :: repr Msg <- recv
match msg reject id
class ( HelperSym repr
) => SieveSem repr
instance SieveSem SymbEx
sieve_main :: SieveSem repr => repr (Process repr ())
sieve_main = do me <- self
r_gen <- newRSing
gen <- spawn r_gen (app counter (int 2))
r_s <- newRSing
spawn r_s (app2 sieve gen me)
dump
dump :: SieveSem repr => repr (Process repr ())
dump = do let f_dump = lam $ \dump -> lam $ \_ ->
do x :: repr Int <- recv
app print x
app dump tt
app (fixM f_dump) tt
counter :: SieveSem repr => repr (Int -> Process repr ())
counter = lam $ \n ->
do let f_counter = lam $ \counter -> lam $ \n ->
do poke_from <- recv_poke
send poke_from (app ans_msg n)
app counter (plus n (int 1))
app (fixM f_counter) n
ret tt
sieve :: SieveSem repr => repr (Pid RSing -> Pid RSing -> Process repr ())
sieve = lam $ \input -> lam $ \output ->
do let f_sieve = lam $ \sieve -> lam $ \arg ->
do let input = proj1 arg
output = proj2 arg
me <- self
send input (app poke_msg me)
x <- recv_ans
send output x
r <- newRSing
f <- spawn r (app2 filter2 x input)
app sieve $ pair f output
app (fixM f_sieve) $ pair input output
ret tt
type T_ar3 = () :+: Pid RSing
type T_f3 = (Int,(Pid RSing,T_ar3))
f_filter :: SieveSem repr
=> repr ((T_f3 -> Process repr T_f3) -> T_f3 -> Process repr T_f3)
f_filter = lam $ \filter -> lam $ \arg ->
do let test_n = proj1 arg
input = proj1 $ proj2 arg
m_output = proj2 $ proj2 arg
match m_output
(lam $ \_ ->
do from <- recv_poke -- filter2
app filter $ pair3 test_n input (inr from))
(lam $ \output ->
do me <- self -- filter3
send input (app poke_msg me)
y <- recv_ans
test_v <- app2 divisible_by test_n y
ifte test_v
(app filter $ pair3 test_n input (inr output))
(do send output (app ans_msg y)
app filter $ pair3 test_n input (inl tt)))
filter2 :: SieveSem repr
=> repr (Int -> Pid RSing -> Process repr ())
filter2 = lam $ \test_n -> lam $ \input ->
do app (fixM f_filter) $ pair3 test_n input (inl tt)
ret tt
divisible_by :: SieveSem repr
=> repr (Int -> Int -> Process repr Boolean)
divisible_by = lam $ \x -> lam $ \y ->
do r <- app2 mod y x
ifte (eq r (int 0))
(ret $ inl tt)
(ret $ inr tt)
main :: IO ()
main = checkerMain $ exec sieve_main
| abakst/symmetry | checker/tests/todo/SrcSieve.hs | mit | 4,162 | 0 | 24 | 1,849 | 1,392 | 679 | 713 | -1 | -1 |
module SymBoilerPlate where
{-@ nonDet :: a -> x:Int -> {v:Int | 0 <= v && v < x } @-}
nonDet :: a -> Int -> Int
nonDet = undefined
{-@ nonDetRange :: x:Int -> y:Int -> {v:Int | x <= v && v < y} @-}
nonDetRange :: Int -> Int -> Int
nonDetRange = undefined
{-@
data Val p = VUnit {}
| VUnInit {}
| VInt { vInt :: Int }
| VString { vString :: String }
| VSet { vSetName :: String }
| VPid { vPid :: p }
| VInR { vInR :: Val p }
| VInL { vInL :: Val p }
| VPair { vLeft :: Val p, vRight :: Val p }
@-}
data Val p = VUnit {}
| VUnInit {}
| VInt { vInt :: Int }
| VString { vString :: String }
| VSet { vSetName :: String }
| VPid { vPid :: p }
| VInR { vInR :: Val p }
| VInL { vInL :: Val p }
| VPair { vLeft :: Val p, vRight :: Val p }
deriving (Show)
isVUnit, isVUnInit, isVInt, isVString, isVPid, isVInR, isVInL, isVPair, isVSet :: Val p -> Bool
isVUnit VUnit{} = True
isVUnit _ = False
isVUnInit VUnInit{} = True
isVUnInit _ = False
isVInt VInt{} = True
isVInt _ = False
isVString VString{} = True
isVString _ = False
isVSet VSet{} = True
isVSet _ = False
isVPid VPid{} = True
isVPid _ = False
isVInR VInR{} = True
isVInR _ = False
isVInL VInL{} = True
isVInL _ = False
isVPair VPair{} = True
isVPair _ = False
{-@ measure isVUnit @-}
{-@ measure isVUnInit @-}
{-@ measure isVInt @-}
{-@ measure isVString @-}
{-@ measure isVPid @-}
{-@ measure isVInL @-}
{-@ measure isVInR @-}
{-@ measure isVPair @-}
{-@ measure isVSet @-}
| abakst/symmetry | checker/include/SymBoilerPlate.hs | mit | 1,749 | 2 | 9 | 636 | 379 | 219 | 160 | 34 | 1 |
module EvalTest where
import Test.Tasty
import Test.Tasty.HUnit
import qualified Control.Exception as Exc
import EvaluationMonad
import GenStrat
import SolutionContext
import NormalizationStrategies
import CoreS.AST
import qualified CoreS.ASTUnitype as AST
import CoreS.Parse
import Norm.AllNormalizations as ALL
normalize :: CompilationUnit -> CompilationUnit
normalize = executeNormalizer ALL.normalizations
normalizeUAST :: AST.AST -> AST.AST
normalizeUAST = AST.inCore normalize
checkMatches :: FilePath -> [FilePath] -> IO (Maybe Bool)
checkMatches stud mods = do
let paths = Ctx stud mods
Just (Ctx stud mods) <- Exc.catch
(Just <$> resultEvalM ((fmap parseConv) <$> readRawContents paths))
((\e -> return Nothing `const` (e :: Exc.ErrorCall)) {-:: Exc.ErrorCall -> IO (Maybe (SolutionContext (CConv (Repr t))))-})
case stud of
Left _ -> return Nothing
Right stud ->
return $ Just $ or [ matches
normalizeUAST
(AST.toUnitype $ normalize stud)
(AST.toUnitype (normalize mod))
| (Right mod) <- mods ]
allTests :: TestTree
allTests = testGroup "Eval tests"
[
testCase "EVAL_hello_world_OK" $ assert test0
, testCase "EVAL_SumNumbers_FAIL" $ assert test1
, testCase "EVAL_Uppgift12a_2_OK" $ assert test2
, testCase "EVAL_Uppgift12a_3_OK" $ assert (not <$> test3)
, testCase "EVAL_Uppgift12a_4_FAIL" $ assert test4
, testCase "EVAL_Uppgift12a_5_OK" $ assert test5
]
test :: FilePath -> [FilePath] -> IO Bool
test s ms = do
matched <- checkMatches s ms
case matched of
Nothing -> return False
Just a -> return a
test0 :: IO Bool
test0 = test "Test/fixture/strategies/helloWorld_student.java" ["Test/fixture/strategies/helloWorld_model.java"]
test1 :: IO Bool
test1 = not <$> test "Test/Student_solutions/sumNumbers0.java" ["Test/Student_solutions/sumNumbers1.java" ]
test2 :: IO Bool
test2 = test "Test/Eval/Uppgift12a_stud1.java"
[
"modelsolution/uppgift12a/Uppgift12a_1.java"
, "modelsolution/uppgift12a/Uppgift12a_2.java"
, "modelsolution/uppgift12a/Uppgift12a_3.java"
]
test3 :: IO Bool
test3 = test "Test/Eval/Uppgift12a_stud2.java"
[
"modelsolution/uppgift12a/Uppgift12a_1.java"
, "modelsolution/uppgift12a/Uppgift12a_2.java"
, "modelsolution/uppgift12a/Uppgift12a_3.java"
]
test4 :: IO Bool
test4 = not <$> test "Test/Eval/Uppgift12a_stud3.java"
[
"modelsolution/uppgift12a/Uppgift12a_1.java"
, "modelsolution/uppgift12a/Uppgift12a_2.java"
, "modelsolution/uppgift12a/Uppgift12a_3.java"
]
test5 :: IO Bool
test5 = test "Test/Eval/Uppgift12a_stud4.java"
[
"modelsolution/uppgift12a/Uppgift12a_1.java"
, "modelsolution/uppgift12a/Uppgift12a_2.java"
, "modelsolution/uppgift12a/Uppgift12a_3.java"
]
| DATX02-17-26/DATX02-17-26 | Test/EvalTest.hs | gpl-2.0 | 3,113 | 0 | 17 | 804 | 647 | 337 | 310 | 73 | 2 |
{-|
Module : Devel.Args
Description : For handling command line arguments.
Copyright : (c) 2015 Njagi Mwaniki
License : MIT
Maintainer : njagi@urbanslug.com
Stability : experimental
Portability : POSIX
We handle command line arguments for yesod devel here.
-}
module Devel.CmdArgs
( cmdArgs
, CmdArgs (..)
) where
import Data.List.Split (splitOn)
import Options.Applicative
-- | All arguments are optional.
data CmdArgs = CmdArgs
{ buildFile :: FilePath
, runFunction :: String
, watchDirectories :: [String]
, versionNumber :: Bool -- Default: False
, isReverseProxy :: Bool -- Default: True
} deriving (Show, Eq)
cmdArgs :: Parser CmdArgs
cmdArgs = CmdArgs
<$> strOption
(long "path"
<> short 'p'
<> value "Application.hs"
<> metavar "FILEPATH"
<> help "The file with the function you want to run. Default is `Application.hs`.")
<*> strOption
(long "function"
<> short 'f'
<> value "develMain"
<> metavar "FUNCTION"
<> help "The function you want run. Default is `develMain`.")
<*> (splitOn "," <$> strOption
(long "watch-directories"
<> short 'w'
<> value []
<> metavar "DIRECTORY-LIST"
<> help "A comma-separated list of directories which have files we want to watch for changes in"))
<*> flag False True
(long "version"
<> short 'v'
<> help "Print the version of wai-devel you are using." )
<*> flag True False
(long "no-reverse-proxy"
<> short 'r'
<> help "use `-r` to disable reverse proxying." )
| urbanslug/yesod-devel | src/Devel/CmdArgs.hs | gpl-3.0 | 1,937 | 0 | 16 | 754 | 301 | 154 | 147 | 40 | 1 |
module PMC8 where
main :: Int
main = lengte (filter even [1..1000])
lengte :: [a] -> Int
lengte xs =
len xs 0
len :: [a] -> Int -> Int
len xs n =
case xs of
[] -> n
y:ys -> len ys $! (n + 1)
| roberth/uu-helium | test/correct/PMC8.hs | gpl-3.0 | 225 | 0 | 10 | 82 | 117 | 62 | 55 | 11 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.AutoScaling.TerminateInstanceInAutoScalingGroup
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Terminates the specified instance and optionally adjusts the desired
-- group size.
--
-- This call simply makes a termination request. The instances is not
-- terminated immediately.
--
-- /See:/ <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_TerminateInstanceInAutoScalingGroup.html AWS API Reference> for TerminateInstanceInAutoScalingGroup.
module Network.AWS.AutoScaling.TerminateInstanceInAutoScalingGroup
(
-- * Creating a Request
terminateInstanceInAutoScalingGroup
, TerminateInstanceInAutoScalingGroup
-- * Request Lenses
, tiiasgInstanceId
, tiiasgShouldDecrementDesiredCapacity
-- * Destructuring the Response
, terminateInstanceInAutoScalingGroupResponse
, TerminateInstanceInAutoScalingGroupResponse
-- * Response Lenses
, tiiasgrsActivity
, tiiasgrsResponseStatus
) where
import Network.AWS.AutoScaling.Types
import Network.AWS.AutoScaling.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'terminateInstanceInAutoScalingGroup' smart constructor.
data TerminateInstanceInAutoScalingGroup = TerminateInstanceInAutoScalingGroup'
{ _tiiasgInstanceId :: !Text
, _tiiasgShouldDecrementDesiredCapacity :: !Bool
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'TerminateInstanceInAutoScalingGroup' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tiiasgInstanceId'
--
-- * 'tiiasgShouldDecrementDesiredCapacity'
terminateInstanceInAutoScalingGroup
:: Text -- ^ 'tiiasgInstanceId'
-> Bool -- ^ 'tiiasgShouldDecrementDesiredCapacity'
-> TerminateInstanceInAutoScalingGroup
terminateInstanceInAutoScalingGroup pInstanceId_ pShouldDecrementDesiredCapacity_ =
TerminateInstanceInAutoScalingGroup'
{ _tiiasgInstanceId = pInstanceId_
, _tiiasgShouldDecrementDesiredCapacity = pShouldDecrementDesiredCapacity_
}
-- | The ID of the EC2 instance.
tiiasgInstanceId :: Lens' TerminateInstanceInAutoScalingGroup Text
tiiasgInstanceId = lens _tiiasgInstanceId (\ s a -> s{_tiiasgInstanceId = a});
-- | If 'true', terminating this instance also decrements the size of the
-- Auto Scaling group.
tiiasgShouldDecrementDesiredCapacity :: Lens' TerminateInstanceInAutoScalingGroup Bool
tiiasgShouldDecrementDesiredCapacity = lens _tiiasgShouldDecrementDesiredCapacity (\ s a -> s{_tiiasgShouldDecrementDesiredCapacity = a});
instance AWSRequest
TerminateInstanceInAutoScalingGroup where
type Rs TerminateInstanceInAutoScalingGroup =
TerminateInstanceInAutoScalingGroupResponse
request = postQuery autoScaling
response
= receiveXMLWrapper
"TerminateInstanceInAutoScalingGroupResult"
(\ s h x ->
TerminateInstanceInAutoScalingGroupResponse' <$>
(x .@? "Activity") <*> (pure (fromEnum s)))
instance ToHeaders
TerminateInstanceInAutoScalingGroup where
toHeaders = const mempty
instance ToPath TerminateInstanceInAutoScalingGroup
where
toPath = const "/"
instance ToQuery TerminateInstanceInAutoScalingGroup
where
toQuery TerminateInstanceInAutoScalingGroup'{..}
= mconcat
["Action" =:
("TerminateInstanceInAutoScalingGroup" ::
ByteString),
"Version" =: ("2011-01-01" :: ByteString),
"InstanceId" =: _tiiasgInstanceId,
"ShouldDecrementDesiredCapacity" =:
_tiiasgShouldDecrementDesiredCapacity]
-- | /See:/ 'terminateInstanceInAutoScalingGroupResponse' smart constructor.
data TerminateInstanceInAutoScalingGroupResponse = TerminateInstanceInAutoScalingGroupResponse'
{ _tiiasgrsActivity :: !(Maybe Activity)
, _tiiasgrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'TerminateInstanceInAutoScalingGroupResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tiiasgrsActivity'
--
-- * 'tiiasgrsResponseStatus'
terminateInstanceInAutoScalingGroupResponse
:: Int -- ^ 'tiiasgrsResponseStatus'
-> TerminateInstanceInAutoScalingGroupResponse
terminateInstanceInAutoScalingGroupResponse pResponseStatus_ =
TerminateInstanceInAutoScalingGroupResponse'
{ _tiiasgrsActivity = Nothing
, _tiiasgrsResponseStatus = pResponseStatus_
}
-- | A scaling activity.
tiiasgrsActivity :: Lens' TerminateInstanceInAutoScalingGroupResponse (Maybe Activity)
tiiasgrsActivity = lens _tiiasgrsActivity (\ s a -> s{_tiiasgrsActivity = a});
-- | The response status code.
tiiasgrsResponseStatus :: Lens' TerminateInstanceInAutoScalingGroupResponse Int
tiiasgrsResponseStatus = lens _tiiasgrsResponseStatus (\ s a -> s{_tiiasgrsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-autoscaling/gen/Network/AWS/AutoScaling/TerminateInstanceInAutoScalingGroup.hs | mpl-2.0 | 5,744 | 0 | 13 | 1,057 | 626 | 376 | 250 | 88 | 1 |
module SimpleJSON
(
JValue(..)
, getString
, getInt
, getDouble
, getBool
, getObject
, getArray
, isNull
) where
data JValue = JString String
| JNumber Double
| JBool Bool
| JNull
| JObject [(String, JValue)]
| JArray [JValue]
deriving (Eq, Ord, Show)
getString :: JValue -> Maybe String
getString (JString s) = Just s
getString _ = Nothing
getInt (JNumber n) = Just (truncate n)
getInt _ = Nothing
getDouble (JNumber n) = Just n
getDouble _ = Nothing
getBool (JBool b) = Just b
getBool _ = Nothing
getObject (JObject o) = Just o
getObject _ = Nothing
getArray (JArray a) = Just a
getArray _ = Nothing
isNull v = v == JNull
| timstclair/experimental | haskell/real_world_haskell/ch05/SimpleJSON.hs | unlicense | 818 | 0 | 8 | 310 | 273 | 145 | 128 | 31 | 1 |
{-# LANGUAGE GADTs, PolyKinds, RankNTypes #-}
module GADTVars where
import Data.Kind
import Data.Proxy
data T (k1 :: Type) (k2 :: Type) (a :: k2) (b :: k2) where
MkT :: T x1 Type (Proxy (y :: x1), z) z
| sdiehl/ghc | testsuite/tests/dependent/should_compile/mkGADTVars.hs | bsd-3-clause | 207 | 0 | 10 | 44 | 76 | 49 | 27 | -1 | -1 |
module MyHttp (RequestType (..), Request(..), Response(..), Context(..), ServerPart) where
data RequestType = Get | Post
data Request = Request
{ route :: String
, reqtype :: RequestType
}
data Response = Response
{ content :: String
, statusCode :: Int
}
instance Show Response where
show (Response cntnt stts) =
"Status Code: " ++ show stts ++ "\n" ++ "Content: " ++ cntnt
data Context = Context
{ request :: Request
, response :: Response
}
type ServerPart = Context -> Maybe Context
| nicolocodev/learnhappstack | 3_Composition/MyHttp.hs | mit | 527 | 0 | 10 | 123 | 166 | 99 | 67 | 15 | 0 |
module Model.Project.Sql where
import Import
import Model.Wiki.Sql
-- | Query that returns all WikiEdits made on any WikiPage on this Project
querProjectWikiEdits :: ProjectId -> SqlQuery (SqlExpr (Value WikiEditId))
querProjectWikiEdits project_id =
from $ \(wp `InnerJoin` we) -> do
on_ (wp ^. WikiPageId ==. we ^. WikiEditPage)
where_ (exprWikiPageOnProject wp project_id)
return (we ^. WikiEditId)
| Happy0/snowdrift | Model/Project/Sql.hs | agpl-3.0 | 421 | 0 | 13 | 74 | 115 | 61 | 54 | 9 | 1 |
{-
(c) The AQUA Project, Glasgow University, 1993-1998
\section{Common subexpression}
-}
{-# LANGUAGE CPP #-}
module ETA.SimplCore.CSE (cseProgram) where
#include "HsVersions.h"
import ETA.Core.CoreSubst
import ETA.BasicTypes.Var ( Var )
import ETA.BasicTypes.Id ( Id, idType, idInlineActivation, zapIdOccInfo, zapIdUsageInfo )
import ETA.Core.CoreUtils ( mkAltExpr
, exprIsTrivial
, stripTicksE, stripTicksT, stripTicksTopE, mkTick, mkTicks )
import ETA.Types.Type ( tyConAppArgs )
import ETA.Core.CoreSyn
import ETA.Utils.Outputable
import ETA.BasicTypes.BasicTypes ( isAlwaysActive )
import ETA.Core.TrieMap
import Data.List
{-
Simple common sub-expression
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we see
x1 = C a b
x2 = C x1 b
we build up a reverse mapping: C a b -> x1
C x1 b -> x2
and apply that to the rest of the program.
When we then see
y1 = C a b
y2 = C y1 b
we replace the C a b with x1. But then we *dont* want to
add x1 -> y1 to the mapping. Rather, we want the reverse, y1 -> x1
so that a subsequent binding
y2 = C y1 b
will get transformed to C x1 b, and then to x2.
So we carry an extra var->var substitution which we apply *before* looking up in the
reverse mapping.
Note [Shadowing]
~~~~~~~~~~~~~~~~
We have to be careful about shadowing.
For example, consider
f = \x -> let y = x+x in
h = \x -> x+x
in ...
Here we must *not* do CSE on the inner x+x! The simplifier used to guarantee no
shadowing, but it doesn't any more (it proved too hard), so we clone as we go.
We can simply add clones to the substitution already described.
Note [Case binders 1]
~~~~~~~~~~~~~~~~~~~~~~
Consider
f = \x -> case x of wild {
(a:as) -> case a of wild1 {
(p,q) -> ...(wild1:as)...
Here, (wild1:as) is morally the same as (a:as) and hence equal to wild.
But that's not quite obvious. In general we want to keep it as (wild1:as),
but for CSE purpose that's a bad idea.
So we add the binding (wild1 -> a) to the extra var->var mapping.
Notice this is exactly backwards to what the simplifier does, which is
to try to replaces uses of 'a' with uses of 'wild1'
Note [Case binders 2]
~~~~~~~~~~~~~~~~~~~~~~
Consider
case (h x) of y -> ...(h x)...
We'd like to replace (h x) in the alternative, by y. But because of
the preceding [Note: case binders 1], we only want to add the mapping
scrutinee -> case binder
to the reverse CSE mapping if the scrutinee is a non-trivial expression.
(If the scrutinee is a simple variable we want to add the mapping
case binder -> scrutinee
to the substitution
Note [CSE for INLINE and NOINLINE]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are some subtle interactions of CSE with functions that the user
has marked as INLINE or NOINLINE. (Examples from Roman Leshchinskiy.)
Consider
yes :: Int {-# NOINLINE yes #-}
yes = undefined
no :: Int {-# NOINLINE no #-}
no = undefined
foo :: Int -> Int -> Int {-# NOINLINE foo #-}
foo m n = n
{-# RULES "foo/no" foo no = id #-}
bar :: Int -> Int
bar = foo yes
We do not expect the rule to fire. But if we do CSE, then we risk
getting yes=no, and the rule does fire. Actually, it won't because
NOINLINE means that 'yes' will never be inlined, not even if we have
yes=no. So that's fine (now; perhaps in the olden days, yes=no would
have substituted even if 'yes' was NOINLINE.
But we do need to take care. Consider
{-# NOINLINE bar #-}
bar = <rhs> -- Same rhs as foo
foo = <rhs>
If CSE produces
foo = bar
then foo will never be inlined to <rhs> (when it should be, if <rhs>
is small). The conclusion here is this:
We should not add
<rhs> :-> bar
to the CSEnv if 'bar' has any constraints on when it can inline;
that is, if its 'activation' not always active. Otherwise we
might replace <rhs> by 'bar', and then later be unable to see that it
really was <rhs>.
Note that we do not (currently) do CSE on the unfolding stored inside
an Id, even if is a 'stable' unfolding. That means that when an
unfolding happens, it is always faithful to what the stable unfolding
originally was.
Note [CSE for case expressions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
case f x of y { pat -> ...let y = f x in ... }
Then we can CSE the inner (f x) to y. In fact 'case' is like a strict
let-binding, and we can use cseRhs for dealing with the scrutinee.
************************************************************************
* *
\section{Common subexpression}
* *
************************************************************************
-}
cseProgram :: CoreProgram -> CoreProgram
cseProgram binds = snd (mapAccumL cseBind emptyCSEnv binds)
cseBind :: CSEnv -> CoreBind -> (CSEnv, CoreBind)
cseBind env (NonRec b e)
= (env2, NonRec b'' e')
where
(env1, b') = addBinder env b
(env2, (b'', e')) = cseRhs env1 (b',e)
cseBind env (Rec pairs)
= (env2, Rec pairs')
where
(bs,es) = unzip pairs
(env1, bs') = addRecBinders env bs
(env2, pairs') = mapAccumL cseRhs env1 (bs' `zip` es)
cseRhs :: CSEnv -> (OutBndr, InExpr) -> (CSEnv, (OutBndr, OutExpr))
cseRhs env (id',rhs)
= case lookupCSEnv env rhs'' of
Nothing
| always_active -> (extendCSEnv env rhs' id', (zapped_id, rhs'))
| otherwise -> (env, (id', rhs'))
Just id
| always_active -> (extendCSSubst env id' id, (id', mkTicks ticks $ Var id))
| otherwise -> (env, (id', mkTicks ticks $ Var id))
-- In the Just case, we have
-- x = rhs
-- ...
-- x' = rhs
-- We are replacing the second binding with x'=x
-- and so must record that in the substitution so
-- that subsequent uses of x' are replaced with x,
-- See Trac #5996
where
zapped_id = zapIdUsageInfo id'
-- Putting the Id into the environment makes it possible that
-- it'll become shared more than it is now, which would
-- invalidate (the usage part of) its demand info. This caused
-- Trac #100218.
-- Easiest thing is to zap the usage info; subsequently
-- performing late demand-analysis will restore it. Don't zap
-- the strictness info; it's not necessary to do so, and losing
-- it is bad for performance if you don't do late demand
-- analysis
rhs' = cseExpr env rhs
ticks = stripTicksT tickishFloatable rhs'
rhs'' = stripTicksE tickishFloatable rhs'
-- We don't want to lose the source notes when a common sub
-- expression gets eliminated. Hence we push all (!) of them on
-- top of the replaced sub-expression. This is probably not too
-- useful in practice, but upholds our semantics.
always_active = isAlwaysActive (idInlineActivation id')
-- See Note [CSE for INLINE and NOINLINE]
tryForCSE :: CSEnv -> InExpr -> OutExpr
tryForCSE env expr
| exprIsTrivial expr' = expr' -- No point
| Just smaller <- lookupCSEnv env expr'' = foldr mkTick (Var smaller) ticks
| otherwise = expr'
where
expr' = cseExpr env expr
expr'' = stripTicksE tickishFloatable expr'
ticks = stripTicksT tickishFloatable expr'
cseExpr :: CSEnv -> InExpr -> OutExpr
cseExpr env (Type t) = Type (substTy (csEnvSubst env) t)
cseExpr env (Coercion c) = Coercion (substCo (csEnvSubst env) c)
cseExpr _ (Lit lit) = Lit lit
cseExpr env (Var v) = lookupSubst env v
cseExpr env (App f a) = App (cseExpr env f) (tryForCSE env a)
cseExpr env (Tick t e) = Tick t (cseExpr env e)
cseExpr env (Cast e co) = Cast (cseExpr env e) (substCo (csEnvSubst env) co)
cseExpr env (Lam b e) = let (env', b') = addBinder env b
in Lam b' (cseExpr env' e)
cseExpr env (Let bind e) = let (env', bind') = cseBind env bind
in Let bind' (cseExpr env' e)
cseExpr env (Case scrut bndr ty alts) = Case scrut' bndr''' ty alts'
where
alts' = cseAlts env2 scrut' bndr bndr'' alts
(env1, bndr') = addBinder env bndr
bndr'' = zapIdOccInfo bndr'
-- The swizzling from Note [Case binders 2] may
-- cause a dead case binder to be alive, so we
-- play safe here and bring them all to life
(env2, (bndr''', scrut')) = cseRhs env1 (bndr'', scrut)
-- Note [CSE for case expressions]
cseAlts :: CSEnv -> OutExpr -> InBndr -> InBndr -> [InAlt] -> [OutAlt]
cseAlts env scrut' bndr bndr' alts
= map cse_alt alts
where
scrut'' = stripTicksTopE tickishFloatable scrut'
(con_target, alt_env)
= case scrut'' of
Var v' -> (v', extendCSSubst env bndr v') -- See Note [Case binders 1]
-- map: bndr -> v'
_ -> (bndr', extendCSEnv env scrut' bndr') -- See Note [Case binders 2]
-- map: scrut' -> bndr'
arg_tys = tyConAppArgs (idType bndr)
cse_alt (DataAlt con, args, rhs)
| not (null args)
-- Don't try CSE if there are no args; it just increases the number
-- of live vars. E.g.
-- case x of { True -> ....True.... }
-- Don't replace True by x!
-- Hence the 'null args', which also deal with literals and DEFAULT
= (DataAlt con, args', tryForCSE new_env rhs)
where
(env', args') = addBinders alt_env args
new_env = extendCSEnv env' con_expr con_target
con_expr = mkAltExpr (DataAlt con) args' arg_tys
cse_alt (con, args, rhs)
= (con, args', tryForCSE env' rhs)
where
(env', args') = addBinders alt_env args
{-
************************************************************************
* *
\section{The CSE envt}
* *
************************************************************************
-}
type InExpr = CoreExpr -- Pre-cloning
type InBndr = CoreBndr
type InAlt = CoreAlt
type OutExpr = CoreExpr -- Post-cloning
type OutBndr = CoreBndr
type OutAlt = CoreAlt
data CSEnv = CS { cs_map :: CoreMap (OutExpr, Id) -- Key, value
, cs_subst :: Subst }
emptyCSEnv :: CSEnv
emptyCSEnv = CS { cs_map = emptyCoreMap, cs_subst = emptySubst }
lookupCSEnv :: CSEnv -> OutExpr -> Maybe Id
lookupCSEnv (CS { cs_map = csmap }) expr
= case lookupCoreMap csmap expr of
Just (_,e) -> Just e
Nothing -> Nothing
extendCSEnv :: CSEnv -> OutExpr -> Id -> CSEnv
extendCSEnv cse expr id
= cse { cs_map = extendCoreMap (cs_map cse) sexpr (sexpr,id) }
where sexpr = stripTicksE tickishFloatable expr
csEnvSubst :: CSEnv -> Subst
csEnvSubst = cs_subst
lookupSubst :: CSEnv -> Id -> OutExpr
lookupSubst (CS { cs_subst = sub}) x = lookupIdSubst (text "CSE.lookupSubst") sub x
extendCSSubst :: CSEnv -> Id -> Id -> CSEnv
extendCSSubst cse x y = cse { cs_subst = extendIdSubst (cs_subst cse) x (Var y) }
addBinder :: CSEnv -> Var -> (CSEnv, Var)
addBinder cse v = (cse { cs_subst = sub' }, v')
where
(sub', v') = substBndr (cs_subst cse) v
addBinders :: CSEnv -> [Var] -> (CSEnv, [Var])
addBinders cse vs = (cse { cs_subst = sub' }, vs')
where
(sub', vs') = substBndrs (cs_subst cse) vs
addRecBinders :: CSEnv -> [Id] -> (CSEnv, [Id])
addRecBinders cse vs = (cse { cs_subst = sub' }, vs')
where
(sub', vs') = substRecBndrs (cs_subst cse) vs
| alexander-at-github/eta | compiler/ETA/SimplCore/CSE.hs | bsd-3-clause | 12,560 | 0 | 12 | 4,082 | 2,021 | 1,097 | 924 | 117 | 3 |
{-
Copyright (C) 2009 John Goerzen <jgoerzen@complete.org>
All rights reserved.
For license and copyright information, see the file COPYRIGHT
-}
module TestInfrastructure where
import qualified Test.QuickCheck as QC
import qualified Test.HUnit as HU
import Test.HUnit.Tools
q :: QC.Testable a => String -> a -> HU.Test
q = qc2hu 250
qverbose :: QC.Testable a => String -> a -> HU.Test
qverbose = qc2hu 250
| cabrera/hdbc | testsrc/TestInfrastructure.hs | bsd-3-clause | 410 | 0 | 8 | 67 | 91 | 52 | 39 | 8 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module OperationalTests where
import Type
import Operational
base_send1 :: Test
base_send1 = Test "Base" "send1" [
Transactional [NewStream StringT "s_"] [(StreamSinkT StringT, "s_", s)],
NewList StringT out,
Transactional [Listen "l_" s (StringT, "a") [AppendList out (V "a")]] [(ListenerT, "l_", l)],
Transactional [Send s "a"] [],
Transactional [Send s "b"] [],
Unlisten l,
AssertEqual (lit ["a", "b" :: String]) out
]
where
s = "s"
out = "out"
l = "l"
operationalTests :: [Test]
operationalTests =
[base_send1]
| kevintvh/sodium | common-tests/OperationalTests.hs | bsd-3-clause | 604 | 0 | 13 | 134 | 217 | 121 | 96 | 19 | 1 |
-------------------------------------------------------------------------------
-- |
-- Module : CCO.Tree
-- Copyright : (c) 2008 Utrecht University
-- License : All rights reserved
--
-- Maintainer : stefan@cs.uu.nl
-- Stability : provisional
-- Portability : portable
--
-- A straightforward implementation of the ATerm format for exchanging
-- tree-structured data; see
--
-- * Mark van den Brand, Hayco de Jong, Paul Klint, and Pieter A. Olivier.
-- Efficient annotated terms.
-- /Software - Practice and Experience (SPE)/, 30(3):259-291, 2000.
--
-------------------------------------------------------------------------------
module CCO.Tree (
-- * The @ATerm@ type
ATerm (..) -- instances: Eq, Read, Show, Printable
, Con -- = String
-- * The @Tree@ class
, Tree (..)
-- * Parser
, parser -- :: Component String ATerm
) where
import CCO.Tree.ATerm (Con, ATerm (..))
import CCO.Tree.ATerm.Parser (parser)
import CCO.Tree.Base (Tree (fromTree, toTree))
import CCO.Tree.Instances () | UU-ComputerScience/uu-cco | uu-cco/src/CCO/Tree.hs | bsd-3-clause | 1,078 | 0 | 6 | 227 | 108 | 81 | 27 | 9 | 0 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.GHC
-- Copyright : Isaac Jones 2003-2007
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This is a fairly large module. It contains most of the GHC-specific code for
-- configuring, building and installing packages. It also exports a function
-- for finding out what packages are already installed. Configuring involves
-- finding the @ghc@ and @ghc-pkg@ programs, finding what language extensions
-- this version of ghc supports and returning a 'Compiler' value.
--
-- 'getInstalledPackages' involves calling the @ghc-pkg@ program to find out
-- what packages are installed.
--
-- Building is somewhat complex as there is quite a bit of information to take
-- into account. We have to build libs and programs, possibly for profiling and
-- shared libs. We have to support building libraries that will be usable by
-- GHCi and also ghc's @-split-objs@ feature. We have to compile any C files
-- using ghc. Linking, especially for @split-objs@ is remarkably complex,
-- partly because there tend to be 1,000's of @.o@ files and this can often be
-- more than we can pass to the @ld@ or @ar@ programs in one go.
--
-- Installing for libs and exes involves finding the right files and copying
-- them to the right places. One of the more tricky things about this module is
-- remembering the layout of files in the build directory (which is not
-- explicitly documented) and thus what search dirs are used for various kinds
-- of files.
module Distribution.Simple.GHC (
getGhcInfo,
configure, getInstalledPackages, getPackageDBContents,
buildLib, buildExe,
replLib, replExe,
startInterpreter,
installLib, installExe,
libAbiHash,
hcPkgInfo,
registerPackage,
componentGhcOptions,
componentCcGhcOptions,
getLibDir,
isDynamic,
getGlobalPackageDB,
pkgRoot
) where
import qualified Distribution.Simple.GHC.IPI641 as IPI641
import qualified Distribution.Simple.GHC.IPI642 as IPI642
import qualified Distribution.Simple.GHC.Internal as Internal
import Distribution.Simple.GHC.ImplInfo
import Distribution.PackageDescription as PD
( PackageDescription(..), BuildInfo(..), Executable(..), Library(..)
, allExtensions, libModules, exeModules
, hcOptions, hcSharedOptions, hcProfOptions )
import Distribution.InstalledPackageInfo
( InstalledPackageInfo )
import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo
( InstalledPackageInfo(..) )
import Distribution.Simple.PackageIndex (InstalledPackageIndex)
import qualified Distribution.Simple.PackageIndex as PackageIndex
import Distribution.Simple.LocalBuildInfo
( LocalBuildInfo(..), ComponentLocalBuildInfo(..)
, absoluteInstallDirs, depLibraryPaths )
import qualified Distribution.Simple.Hpc as Hpc
import Distribution.Simple.InstallDirs hiding ( absoluteInstallDirs )
import Distribution.Simple.BuildPaths
import Distribution.Simple.Utils
import Distribution.Package
( PackageName(..) )
import qualified Distribution.ModuleName as ModuleName
import Distribution.Simple.Program
( Program(..), ConfiguredProgram(..), ProgramConfiguration
, ProgramSearchPath
, rawSystemProgramStdout, rawSystemProgramStdoutConf
, getProgramInvocationOutput, requireProgramVersion, requireProgram
, userMaybeSpecifyPath, programPath, lookupProgram, addKnownProgram
, ghcProgram, ghcPkgProgram, haddockProgram, hsc2hsProgram, ldProgram )
import qualified Distribution.Simple.Program.HcPkg as HcPkg
import qualified Distribution.Simple.Program.Ar as Ar
import qualified Distribution.Simple.Program.Ld as Ld
import qualified Distribution.Simple.Program.Strip as Strip
import Distribution.Simple.Program.GHC
import Distribution.Simple.Setup
( toFlag, fromFlag, fromFlagOrDefault, configCoverage, configDistPref )
import qualified Distribution.Simple.Setup as Cabal
( Flag(..) )
import Distribution.Simple.Compiler
( CompilerFlavor(..), CompilerId(..), Compiler(..), compilerVersion
, PackageDB(..), PackageDBStack, AbiTag(..) )
import Distribution.Version
( Version(..), anyVersion, orLaterVersion )
import Distribution.System
( Platform(..), OS(..) )
import Distribution.Verbosity
import Distribution.Text
( display )
import Distribution.Utils.NubList
( NubListR, overNubListR, toNubListR )
import Language.Haskell.Extension (Extension(..), KnownExtension(..))
import Control.Monad ( unless, when )
import Data.Char ( isDigit, isSpace )
import Data.List
import qualified Data.Map as M ( fromList )
import Data.Maybe ( catMaybes )
#if __GLASGOW_HASKELL__ < 710
import Data.Monoid ( Monoid(..) )
#endif
import Data.Version ( showVersion )
import System.Directory
( doesFileExist, getAppUserDataDirectory, createDirectoryIfMissing )
import System.FilePath ( (</>), (<.>), takeExtension,
takeDirectory, replaceExtension,
splitExtension, isRelative )
import qualified System.Info
-- -----------------------------------------------------------------------------
-- Configuring
configure :: Verbosity -> Maybe FilePath -> Maybe FilePath
-> ProgramConfiguration
-> IO (Compiler, Maybe Platform, ProgramConfiguration)
configure verbosity hcPath hcPkgPath conf0 = do
(ghcProg, ghcVersion, conf1) <-
requireProgramVersion verbosity ghcProgram
(orLaterVersion (Version [6,4] []))
(userMaybeSpecifyPath "ghc" hcPath conf0)
let implInfo = ghcVersionImplInfo ghcVersion
-- This is slightly tricky, we have to configure ghc first, then we use the
-- location of ghc to help find ghc-pkg in the case that the user did not
-- specify the location of ghc-pkg directly:
(ghcPkgProg, ghcPkgVersion, conf2) <-
requireProgramVersion verbosity ghcPkgProgram {
programFindLocation = guessGhcPkgFromGhcPath ghcProg
}
anyVersion (userMaybeSpecifyPath "ghc-pkg" hcPkgPath conf1)
when (ghcVersion /= ghcPkgVersion) $ die $
"Version mismatch between ghc and ghc-pkg: "
++ programPath ghcProg ++ " is version " ++ display ghcVersion ++ " "
++ programPath ghcPkgProg ++ " is version " ++ display ghcPkgVersion
-- Likewise we try to find the matching hsc2hs and haddock programs.
let hsc2hsProgram' = hsc2hsProgram {
programFindLocation = guessHsc2hsFromGhcPath ghcProg
}
haddockProgram' = haddockProgram {
programFindLocation = guessHaddockFromGhcPath ghcProg
}
conf3 = addKnownProgram haddockProgram' $
addKnownProgram hsc2hsProgram' conf2
languages <- Internal.getLanguages verbosity implInfo ghcProg
extensions <- Internal.getExtensions verbosity implInfo ghcProg
ghcInfo <- Internal.getGhcInfo verbosity implInfo ghcProg
let ghcInfoMap = M.fromList ghcInfo
let comp = Compiler {
compilerId = CompilerId GHC ghcVersion,
compilerAbiTag = NoAbiTag,
compilerCompat = [],
compilerLanguages = languages,
compilerExtensions = extensions,
compilerProperties = ghcInfoMap
}
compPlatform = Internal.targetPlatform ghcInfo
-- configure gcc and ld
conf4 = Internal.configureToolchain implInfo ghcProg ghcInfoMap conf3
return (comp, compPlatform, conf4)
-- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find
-- the corresponding tool; e.g. if the tool is ghc-pkg, we try looking
-- for a versioned or unversioned ghc-pkg in the same dir, that is:
--
-- > /usr/local/bin/ghc-pkg-ghc-6.6.1(.exe)
-- > /usr/local/bin/ghc-pkg-6.6.1(.exe)
-- > /usr/local/bin/ghc-pkg(.exe)
--
guessToolFromGhcPath :: Program -> ConfiguredProgram
-> Verbosity -> ProgramSearchPath
-> IO (Maybe FilePath)
guessToolFromGhcPath tool ghcProg verbosity searchpath
= do let toolname = programName tool
path = programPath ghcProg
dir = takeDirectory path
versionSuffix = takeVersionSuffix (dropExeExtension path)
guessNormal = dir </> toolname <.> exeExtension
guessGhcVersioned = dir </> (toolname ++ "-ghc" ++ versionSuffix)
<.> exeExtension
guessVersioned = dir </> (toolname ++ versionSuffix)
<.> exeExtension
guesses | null versionSuffix = [guessNormal]
| otherwise = [guessGhcVersioned,
guessVersioned,
guessNormal]
info verbosity $ "looking for tool " ++ toolname
++ " near compiler in " ++ dir
exists <- mapM doesFileExist guesses
case [ file | (file, True) <- zip guesses exists ] of
-- If we can't find it near ghc, fall back to the usual
-- method.
[] -> programFindLocation tool verbosity searchpath
(fp:_) -> do info verbosity $ "found " ++ toolname ++ " in " ++ fp
return (Just fp)
where takeVersionSuffix :: FilePath -> String
takeVersionSuffix = takeWhileEndLE isSuffixChar
isSuffixChar :: Char -> Bool
isSuffixChar c = isDigit c || c == '.' || c == '-'
dropExeExtension :: FilePath -> FilePath
dropExeExtension filepath =
case splitExtension filepath of
(filepath', extension) | extension == exeExtension -> filepath'
| otherwise -> filepath
-- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find a
-- corresponding ghc-pkg, we try looking for both a versioned and unversioned
-- ghc-pkg in the same dir, that is:
--
-- > /usr/local/bin/ghc-pkg-ghc-6.6.1(.exe)
-- > /usr/local/bin/ghc-pkg-6.6.1(.exe)
-- > /usr/local/bin/ghc-pkg(.exe)
--
guessGhcPkgFromGhcPath :: ConfiguredProgram
-> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath)
guessGhcPkgFromGhcPath = guessToolFromGhcPath ghcPkgProgram
-- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find a
-- corresponding hsc2hs, we try looking for both a versioned and unversioned
-- hsc2hs in the same dir, that is:
--
-- > /usr/local/bin/hsc2hs-ghc-6.6.1(.exe)
-- > /usr/local/bin/hsc2hs-6.6.1(.exe)
-- > /usr/local/bin/hsc2hs(.exe)
--
guessHsc2hsFromGhcPath :: ConfiguredProgram
-> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath)
guessHsc2hsFromGhcPath = guessToolFromGhcPath hsc2hsProgram
-- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find a
-- corresponding haddock, we try looking for both a versioned and unversioned
-- haddock in the same dir, that is:
--
-- > /usr/local/bin/haddock-ghc-6.6.1(.exe)
-- > /usr/local/bin/haddock-6.6.1(.exe)
-- > /usr/local/bin/haddock(.exe)
--
guessHaddockFromGhcPath :: ConfiguredProgram
-> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath)
guessHaddockFromGhcPath = guessToolFromGhcPath haddockProgram
getGhcInfo :: Verbosity -> ConfiguredProgram -> IO [(String, String)]
getGhcInfo verbosity ghcProg = Internal.getGhcInfo verbosity implInfo ghcProg
where
Just version = programVersion ghcProg
implInfo = ghcVersionImplInfo version
-- | Given a single package DB, return all installed packages.
getPackageDBContents :: Verbosity -> PackageDB -> ProgramConfiguration
-> IO InstalledPackageIndex
getPackageDBContents verbosity packagedb conf = do
pkgss <- getInstalledPackages' verbosity [packagedb] conf
toPackageIndex verbosity pkgss conf
-- | Given a package DB stack, return all installed packages.
getInstalledPackages :: Verbosity -> Compiler -> PackageDBStack -> ProgramConfiguration
-> IO InstalledPackageIndex
getInstalledPackages verbosity comp packagedbs conf = do
checkPackageDbEnvVar
checkPackageDbStack comp packagedbs
pkgss <- getInstalledPackages' verbosity packagedbs conf
index <- toPackageIndex verbosity pkgss conf
return $! hackRtsPackage index
where
hackRtsPackage index =
case PackageIndex.lookupPackageName index (PackageName "rts") of
[(_,[rts])]
-> PackageIndex.insert (removeMingwIncludeDir rts) index
_ -> index -- No (or multiple) ghc rts package is registered!!
-- Feh, whatever, the ghc test suite does some crazy stuff.
-- | Given a list of @(PackageDB, InstalledPackageInfo)@ pairs, produce a
-- @PackageIndex@. Helper function used by 'getPackageDBContents' and
-- 'getInstalledPackages'.
toPackageIndex :: Verbosity
-> [(PackageDB, [InstalledPackageInfo])]
-> ProgramConfiguration
-> IO InstalledPackageIndex
toPackageIndex verbosity pkgss conf = do
-- On Windows, various fields have $topdir/foo rather than full
-- paths. We need to substitute the right value in so that when
-- we, for example, call gcc, we have proper paths to give it.
topDir <- getLibDir' verbosity ghcProg
let indices = [ PackageIndex.fromList (map (Internal.substTopDir topDir) pkgs)
| (_, pkgs) <- pkgss ]
return $! (mconcat indices)
where
Just ghcProg = lookupProgram ghcProgram conf
getLibDir :: Verbosity -> LocalBuildInfo -> IO FilePath
getLibDir verbosity lbi =
dropWhileEndLE isSpace `fmap`
rawSystemProgramStdoutConf verbosity ghcProgram
(withPrograms lbi) ["--print-libdir"]
getLibDir' :: Verbosity -> ConfiguredProgram -> IO FilePath
getLibDir' verbosity ghcProg =
dropWhileEndLE isSpace `fmap`
rawSystemProgramStdout verbosity ghcProg ["--print-libdir"]
-- | Return the 'FilePath' to the global GHC package database.
getGlobalPackageDB :: Verbosity -> ConfiguredProgram -> IO FilePath
getGlobalPackageDB verbosity ghcProg =
dropWhileEndLE isSpace `fmap`
rawSystemProgramStdout verbosity ghcProg ["--print-global-package-db"]
checkPackageDbEnvVar :: IO ()
checkPackageDbEnvVar =
Internal.checkPackageDbEnvVar "GHC" "GHC_PACKAGE_PATH"
checkPackageDbStack :: Compiler -> PackageDBStack -> IO ()
checkPackageDbStack comp = if flagPackageConf implInfo
then checkPackageDbStackPre76
else checkPackageDbStackPost76
where implInfo = ghcVersionImplInfo (compilerVersion comp)
checkPackageDbStackPost76 :: PackageDBStack -> IO ()
checkPackageDbStackPost76 (GlobalPackageDB:rest)
| GlobalPackageDB `notElem` rest = return ()
checkPackageDbStackPost76 rest
| GlobalPackageDB `elem` rest =
die $ "If the global package db is specified, it must be "
++ "specified first and cannot be specified multiple times"
checkPackageDbStackPost76 _ = return ()
checkPackageDbStackPre76 :: PackageDBStack -> IO ()
checkPackageDbStackPre76 (GlobalPackageDB:rest)
| GlobalPackageDB `notElem` rest = return ()
checkPackageDbStackPre76 rest
| GlobalPackageDB `notElem` rest =
die $ "With current ghc versions the global package db is always used "
++ "and must be listed first. This ghc limitation is lifted in GHC 7.6,"
++ "see http://hackage.haskell.org/trac/ghc/ticket/5977"
checkPackageDbStackPre76 _ =
die $ "If the global package db is specified, it must be "
++ "specified first and cannot be specified multiple times"
-- GHC < 6.10 put "$topdir/include/mingw" in rts's installDirs. This
-- breaks when you want to use a different gcc, so we need to filter
-- it out.
removeMingwIncludeDir :: InstalledPackageInfo -> InstalledPackageInfo
removeMingwIncludeDir pkg =
let ids = InstalledPackageInfo.includeDirs pkg
ids' = filter (not . ("mingw" `isSuffixOf`)) ids
in pkg { InstalledPackageInfo.includeDirs = ids' }
-- | Get the packages from specific PackageDBs, not cumulative.
--
getInstalledPackages' :: Verbosity -> [PackageDB] -> ProgramConfiguration
-> IO [(PackageDB, [InstalledPackageInfo])]
getInstalledPackages' verbosity packagedbs conf
| ghcVersion >= Version [6,9] [] =
sequence
[ do pkgs <- HcPkg.dump (hcPkgInfo conf) verbosity packagedb
return (packagedb, pkgs)
| packagedb <- packagedbs ]
where
Just ghcProg = lookupProgram ghcProgram conf
Just ghcVersion = programVersion ghcProg
getInstalledPackages' verbosity packagedbs conf = do
str <- rawSystemProgramStdoutConf verbosity ghcPkgProgram conf ["list"]
let pkgFiles = [ init line | line <- lines str, last line == ':' ]
dbFile packagedb = case (packagedb, pkgFiles) of
(GlobalPackageDB, global:_) -> return $ Just global
(UserPackageDB, _global:user:_) -> return $ Just user
(UserPackageDB, _global:_) -> return $ Nothing
(SpecificPackageDB specific, _) -> return $ Just specific
_ -> die "cannot read ghc-pkg package listing"
pkgFiles' <- mapM dbFile packagedbs
sequence [ withFileContents file $ \content -> do
pkgs <- readPackages file content
return (db, pkgs)
| (db , Just file) <- zip packagedbs pkgFiles' ]
where
-- Depending on the version of ghc we use a different type's Read
-- instance to parse the package file and then convert.
-- It's a bit yuck. But that's what we get for using Read/Show.
readPackages
| ghcVersion >= Version [6,4,2] []
= \file content -> case reads content of
[(pkgs, _)] -> return (map IPI642.toCurrent pkgs)
_ -> failToRead file
| otherwise
= \file content -> case reads content of
[(pkgs, _)] -> return (map IPI641.toCurrent pkgs)
_ -> failToRead file
Just ghcProg = lookupProgram ghcProgram conf
Just ghcVersion = programVersion ghcProg
failToRead file = die $ "cannot read ghc package database " ++ file
-- -----------------------------------------------------------------------------
-- Building
-- | Build a library with GHC.
--
buildLib, replLib :: Verbosity -> Cabal.Flag (Maybe Int)
-> PackageDescription -> LocalBuildInfo
-> Library -> ComponentLocalBuildInfo -> IO ()
buildLib = buildOrReplLib False
replLib = buildOrReplLib True
buildOrReplLib :: Bool -> Verbosity -> Cabal.Flag (Maybe Int)
-> PackageDescription -> LocalBuildInfo
-> Library -> ComponentLocalBuildInfo -> IO ()
buildOrReplLib forRepl verbosity numJobs pkg_descr lbi lib clbi = do
let libName = componentId clbi
libTargetDir = buildDir lbi
whenVanillaLib forceVanilla =
when (forceVanilla || withVanillaLib lbi)
whenProfLib = when (withProfLib lbi)
whenSharedLib forceShared =
when (forceShared || withSharedLib lbi)
whenGHCiLib = when (withGHCiLib lbi && withVanillaLib lbi)
ifReplLib = when forRepl
comp = compiler lbi
ghcVersion = compilerVersion comp
implInfo = getImplInfo comp
(Platform _hostArch hostOS) = hostPlatform lbi
(ghcProg, _) <- requireProgram verbosity ghcProgram (withPrograms lbi)
let runGhcProg = runGHC verbosity ghcProg comp
libBi <- hackThreadedFlag verbosity
comp (withProfLib lbi) (libBuildInfo lib)
let isGhcDynamic = isDynamic comp
dynamicTooSupported = supportsDynamicToo comp
doingTH = EnableExtension TemplateHaskell `elem` allExtensions libBi
forceVanillaLib = doingTH && not isGhcDynamic
forceSharedLib = doingTH && isGhcDynamic
-- TH always needs default libs, even when building for profiling
-- Determine if program coverage should be enabled and if so, what
-- '-hpcdir' should be.
let isCoverageEnabled = fromFlag $ configCoverage $ configFlags lbi
-- Component name. Not 'libName' because that has the "HS" prefix
-- that GHC gives Haskell libraries.
cname = display $ PD.package $ localPkgDescr lbi
distPref = fromFlag $ configDistPref $ configFlags lbi
hpcdir way
| forRepl = mempty -- HPC is not supported in ghci
| isCoverageEnabled = toFlag $ Hpc.mixDir distPref way cname
| otherwise = mempty
createDirectoryIfMissingVerbose verbosity True libTargetDir
-- TODO: do we need to put hs-boot files into place for mutually recursive
-- modules?
let cObjs = map (`replaceExtension` objExtension) (cSources libBi)
baseOpts = componentGhcOptions verbosity lbi libBi clbi libTargetDir
vanillaOpts = baseOpts `mappend` mempty {
ghcOptMode = toFlag GhcModeMake,
ghcOptNumJobs = numJobs,
ghcOptInputModules = toNubListR $ libModules lib,
ghcOptHPCDir = hpcdir Hpc.Vanilla
}
profOpts = vanillaOpts `mappend` mempty {
ghcOptProfilingMode = toFlag True,
ghcOptProfilingAuto = Internal.profDetailLevelFlag True
(withProfLibDetail lbi),
ghcOptHiSuffix = toFlag "p_hi",
ghcOptObjSuffix = toFlag "p_o",
ghcOptExtra = toNubListR $ hcProfOptions GHC libBi,
ghcOptHPCDir = hpcdir Hpc.Prof
}
sharedOpts = vanillaOpts `mappend` mempty {
ghcOptDynLinkMode = toFlag GhcDynamicOnly,
ghcOptFPic = toFlag True,
ghcOptHiSuffix = toFlag "dyn_hi",
ghcOptObjSuffix = toFlag "dyn_o",
ghcOptExtra = toNubListR $ hcSharedOptions GHC libBi,
ghcOptHPCDir = hpcdir Hpc.Dyn
}
linkerOpts = mempty {
ghcOptLinkOptions = toNubListR $ PD.ldOptions libBi,
ghcOptLinkLibs = toNubListR $ extraLibs libBi,
ghcOptLinkLibPath = toNubListR $ extraLibDirs libBi,
ghcOptLinkFrameworks = toNubListR $ PD.frameworks libBi,
ghcOptInputFiles = toNubListR
[libTargetDir </> x | x <- cObjs]
}
replOpts = vanillaOpts {
ghcOptExtra = overNubListR
Internal.filterGhciFlags $
(ghcOptExtra vanillaOpts),
ghcOptNumJobs = mempty
}
`mappend` linkerOpts
`mappend` mempty {
ghcOptMode = toFlag GhcModeInteractive,
ghcOptOptimisation = toFlag GhcNoOptimisation
}
vanillaSharedOpts = vanillaOpts `mappend` mempty {
ghcOptDynLinkMode = toFlag GhcStaticAndDynamic,
ghcOptDynHiSuffix = toFlag "dyn_hi",
ghcOptDynObjSuffix = toFlag "dyn_o",
ghcOptHPCDir = hpcdir Hpc.Dyn
}
unless (forRepl || null (libModules lib)) $
do let vanilla = whenVanillaLib forceVanillaLib (runGhcProg vanillaOpts)
shared = whenSharedLib forceSharedLib (runGhcProg sharedOpts)
useDynToo = dynamicTooSupported &&
(forceVanillaLib || withVanillaLib lbi) &&
(forceSharedLib || withSharedLib lbi) &&
null (hcSharedOptions GHC libBi)
if useDynToo
then do
runGhcProg vanillaSharedOpts
case (hpcdir Hpc.Dyn, hpcdir Hpc.Vanilla) of
(Cabal.Flag dynDir, Cabal.Flag vanillaDir) -> do
-- When the vanilla and shared library builds are done
-- in one pass, only one set of HPC module interfaces
-- are generated. This set should suffice for both
-- static and dynamically linked executables. We copy
-- the modules interfaces so they are available under
-- both ways.
copyDirectoryRecursive verbosity dynDir vanillaDir
_ -> return ()
else if isGhcDynamic
then do shared; vanilla
else do vanilla; shared
whenProfLib (runGhcProg profOpts)
-- build any C sources
unless (null (cSources libBi)) $ do
info verbosity "Building C Sources..."
sequence_
[ do let baseCcOpts = Internal.componentCcGhcOptions verbosity implInfo
lbi libBi clbi libTargetDir filename
vanillaCcOpts = if isGhcDynamic
-- Dynamic GHC requires C sources to be built
-- with -fPIC for REPL to work. See #2207.
then baseCcOpts { ghcOptFPic = toFlag True }
else baseCcOpts
profCcOpts = vanillaCcOpts `mappend` mempty {
ghcOptProfilingMode = toFlag True,
ghcOptObjSuffix = toFlag "p_o"
}
sharedCcOpts = vanillaCcOpts `mappend` mempty {
ghcOptFPic = toFlag True,
ghcOptDynLinkMode = toFlag GhcDynamicOnly,
ghcOptObjSuffix = toFlag "dyn_o"
}
odir = fromFlag (ghcOptObjDir vanillaCcOpts)
createDirectoryIfMissingVerbose verbosity True odir
needsRecomp <- checkNeedsRecompilation filename vanillaCcOpts
when needsRecomp $ do
runGhcProg vanillaCcOpts
unless forRepl $
whenSharedLib forceSharedLib (runGhcProg sharedCcOpts)
unless forRepl $ whenProfLib (runGhcProg profCcOpts)
| filename <- cSources libBi]
-- TODO: problem here is we need the .c files built first, so we can load them
-- with ghci, but .c files can depend on .h files generated by ghc by ffi
-- exports.
ifReplLib $ do
when (null (libModules lib)) $ warn verbosity "No exposed modules"
ifReplLib (runGhcProg replOpts)
-- link:
unless forRepl $ do
info verbosity "Linking..."
let cProfObjs = map (`replaceExtension` ("p_" ++ objExtension))
(cSources libBi)
cSharedObjs = map (`replaceExtension` ("dyn_" ++ objExtension))
(cSources libBi)
cid = compilerId (compiler lbi)
vanillaLibFilePath = libTargetDir </> mkLibName libName
profileLibFilePath = libTargetDir </> mkProfLibName libName
sharedLibFilePath = libTargetDir </> mkSharedLibName cid libName
ghciLibFilePath = libTargetDir </> Internal.mkGHCiLibName libName
libInstallPath = libdir $ absoluteInstallDirs pkg_descr lbi NoCopyDest
sharedLibInstallPath = libInstallPath </> mkSharedLibName cid libName
stubObjs <- fmap catMaybes $ sequence
[ findFileWithExtension [objExtension] [libTargetDir]
(ModuleName.toFilePath x ++"_stub")
| ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files
, x <- libModules lib ]
stubProfObjs <- fmap catMaybes $ sequence
[ findFileWithExtension ["p_" ++ objExtension] [libTargetDir]
(ModuleName.toFilePath x ++"_stub")
| ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files
, x <- libModules lib ]
stubSharedObjs <- fmap catMaybes $ sequence
[ findFileWithExtension ["dyn_" ++ objExtension] [libTargetDir]
(ModuleName.toFilePath x ++"_stub")
| ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files
, x <- libModules lib ]
hObjs <- Internal.getHaskellObjects implInfo lib lbi
libTargetDir objExtension True
hProfObjs <-
if (withProfLib lbi)
then Internal.getHaskellObjects implInfo lib lbi
libTargetDir ("p_" ++ objExtension) True
else return []
hSharedObjs <-
if (withSharedLib lbi)
then Internal.getHaskellObjects implInfo lib lbi
libTargetDir ("dyn_" ++ objExtension) False
else return []
unless (null hObjs && null cObjs && null stubObjs) $ do
rpaths <- getRPaths lbi clbi
let staticObjectFiles =
hObjs
++ map (libTargetDir </>) cObjs
++ stubObjs
profObjectFiles =
hProfObjs
++ map (libTargetDir </>) cProfObjs
++ stubProfObjs
ghciObjFiles =
hObjs
++ map (libTargetDir </>) cObjs
++ stubObjs
dynamicObjectFiles =
hSharedObjs
++ map (libTargetDir </>) cSharedObjs
++ stubSharedObjs
-- After the relocation lib is created we invoke ghc -shared
-- with the dependencies spelled out as -package arguments
-- and ghc invokes the linker with the proper library paths
ghcSharedLinkArgs =
mempty {
ghcOptShared = toFlag True,
ghcOptDynLinkMode = toFlag GhcDynamicOnly,
ghcOptInputFiles = toNubListR dynamicObjectFiles,
ghcOptOutputFile = toFlag sharedLibFilePath,
-- For dynamic libs, Mac OS/X needs to know the install location
-- at build time. This only applies to GHC < 7.8 - see the
-- discussion in #1660.
ghcOptDylibName = if (hostOS == OSX
&& ghcVersion < Version [7,8] [])
then toFlag sharedLibInstallPath
else mempty,
ghcOptNoAutoLinkPackages = toFlag True,
ghcOptPackageDBs = withPackageDB lbi,
ghcOptPackages = toNubListR $
Internal.mkGhcOptPackages clbi ,
ghcOptLinkLibs = toNubListR $ extraLibs libBi,
ghcOptLinkLibPath = toNubListR $ extraLibDirs libBi,
ghcOptLinkFrameworks = toNubListR $ PD.frameworks libBi,
ghcOptRPaths = rpaths
}
info verbosity (show (ghcOptPackages ghcSharedLinkArgs))
whenVanillaLib False $ do
Ar.createArLibArchive verbosity lbi vanillaLibFilePath staticObjectFiles
whenProfLib $ do
Ar.createArLibArchive verbosity lbi profileLibFilePath profObjectFiles
whenGHCiLib $ do
(ldProg, _) <- requireProgram verbosity ldProgram (withPrograms lbi)
Ld.combineObjectFiles verbosity ldProg
ghciLibFilePath ghciObjFiles
whenSharedLib False $
runGhcProg ghcSharedLinkArgs
-- | Start a REPL without loading any source files.
startInterpreter :: Verbosity -> ProgramConfiguration -> Compiler
-> PackageDBStack -> IO ()
startInterpreter verbosity conf comp packageDBs = do
let replOpts = mempty {
ghcOptMode = toFlag GhcModeInteractive,
ghcOptPackageDBs = packageDBs
}
checkPackageDbStack comp packageDBs
(ghcProg, _) <- requireProgram verbosity ghcProgram conf
runGHC verbosity ghcProg comp replOpts
-- | Build an executable with GHC.
--
buildExe, replExe :: Verbosity -> Cabal.Flag (Maybe Int)
-> PackageDescription -> LocalBuildInfo
-> Executable -> ComponentLocalBuildInfo -> IO ()
buildExe = buildOrReplExe False
replExe = buildOrReplExe True
buildOrReplExe :: Bool -> Verbosity -> Cabal.Flag (Maybe Int)
-> PackageDescription -> LocalBuildInfo
-> Executable -> ComponentLocalBuildInfo -> IO ()
buildOrReplExe forRepl verbosity numJobs _pkg_descr lbi
exe@Executable { exeName = exeName', modulePath = modPath } clbi = do
(ghcProg, _) <- requireProgram verbosity ghcProgram (withPrograms lbi)
let comp = compiler lbi
implInfo = getImplInfo comp
runGhcProg = runGHC verbosity ghcProg comp
exeBi <- hackThreadedFlag verbosity
comp (withProfExe lbi) (buildInfo exe)
-- exeNameReal, the name that GHC really uses (with .exe on Windows)
let exeNameReal = exeName' <.>
(if takeExtension exeName' /= ('.':exeExtension)
then exeExtension
else "")
let targetDir = (buildDir lbi) </> exeName'
let exeDir = targetDir </> (exeName' ++ "-tmp")
createDirectoryIfMissingVerbose verbosity True targetDir
createDirectoryIfMissingVerbose verbosity True exeDir
-- TODO: do we need to put hs-boot files into place for mutually recursive
-- modules? FIX: what about exeName.hi-boot?
-- Determine if program coverage should be enabled and if so, what
-- '-hpcdir' should be.
let isCoverageEnabled = fromFlag $ configCoverage $ configFlags lbi
distPref = fromFlag $ configDistPref $ configFlags lbi
hpcdir way
| forRepl = mempty -- HPC is not supported in ghci
| isCoverageEnabled = toFlag $ Hpc.mixDir distPref way exeName'
| otherwise = mempty
-- build executables
srcMainFile <- findFile (exeDir : hsSourceDirs exeBi) modPath
rpaths <- getRPaths lbi clbi
let isGhcDynamic = isDynamic comp
dynamicTooSupported = supportsDynamicToo comp
isHaskellMain = elem (takeExtension srcMainFile) [".hs", ".lhs"]
cSrcs = cSources exeBi ++ [srcMainFile | not isHaskellMain]
cObjs = map (`replaceExtension` objExtension) cSrcs
baseOpts = (componentGhcOptions verbosity lbi exeBi clbi exeDir)
`mappend` mempty {
ghcOptMode = toFlag GhcModeMake,
ghcOptInputFiles = toNubListR
[ srcMainFile | isHaskellMain],
ghcOptInputModules = toNubListR
[ m | not isHaskellMain, m <- exeModules exe]
}
staticOpts = baseOpts `mappend` mempty {
ghcOptDynLinkMode = toFlag GhcStaticOnly,
ghcOptHPCDir = hpcdir Hpc.Vanilla
}
profOpts = baseOpts `mappend` mempty {
ghcOptProfilingMode = toFlag True,
ghcOptProfilingAuto = Internal.profDetailLevelFlag False
(withProfExeDetail lbi),
ghcOptHiSuffix = toFlag "p_hi",
ghcOptObjSuffix = toFlag "p_o",
ghcOptExtra = toNubListR (hcProfOptions GHC exeBi),
ghcOptHPCDir = hpcdir Hpc.Prof
}
dynOpts = baseOpts `mappend` mempty {
ghcOptDynLinkMode = toFlag GhcDynamicOnly,
ghcOptHiSuffix = toFlag "dyn_hi",
ghcOptObjSuffix = toFlag "dyn_o",
ghcOptExtra = toNubListR $
hcSharedOptions GHC exeBi,
ghcOptHPCDir = hpcdir Hpc.Dyn
}
dynTooOpts = staticOpts `mappend` mempty {
ghcOptDynLinkMode = toFlag GhcStaticAndDynamic,
ghcOptDynHiSuffix = toFlag "dyn_hi",
ghcOptDynObjSuffix = toFlag "dyn_o",
ghcOptHPCDir = hpcdir Hpc.Dyn
}
linkerOpts = mempty {
ghcOptLinkOptions = toNubListR $ PD.ldOptions exeBi,
ghcOptLinkLibs = toNubListR $ extraLibs exeBi,
ghcOptLinkLibPath = toNubListR $ extraLibDirs exeBi,
ghcOptLinkFrameworks = toNubListR $ PD.frameworks exeBi,
ghcOptInputFiles = toNubListR
[exeDir </> x | x <- cObjs]
}
dynLinkerOpts = mempty {
ghcOptRPaths = rpaths
}
replOpts = baseOpts {
ghcOptExtra = overNubListR
Internal.filterGhciFlags
(ghcOptExtra baseOpts)
}
-- For a normal compile we do separate invocations of ghc for
-- compiling as for linking. But for repl we have to do just
-- the one invocation, so that one has to include all the
-- linker stuff too, like -l flags and any .o files from C
-- files etc.
`mappend` linkerOpts
`mappend` mempty {
ghcOptMode = toFlag GhcModeInteractive,
ghcOptOptimisation = toFlag GhcNoOptimisation
}
commonOpts | withProfExe lbi = profOpts
| withDynExe lbi = dynOpts
| otherwise = staticOpts
compileOpts | useDynToo = dynTooOpts
| otherwise = commonOpts
withStaticExe = (not $ withProfExe lbi) && (not $ withDynExe lbi)
-- For building exe's that use TH with -prof or -dynamic we actually have
-- to build twice, once without -prof/-dynamic and then again with
-- -prof/-dynamic. This is because the code that TH needs to run at
-- compile time needs to be the vanilla ABI so it can be loaded up and run
-- by the compiler.
-- With dynamic-by-default GHC the TH object files loaded at compile-time
-- need to be .dyn_o instead of .o.
doingTH = EnableExtension TemplateHaskell `elem` allExtensions exeBi
-- Should we use -dynamic-too instead of compiling twice?
useDynToo = dynamicTooSupported && isGhcDynamic
&& doingTH && withStaticExe
&& null (hcSharedOptions GHC exeBi)
compileTHOpts | isGhcDynamic = dynOpts
| otherwise = staticOpts
compileForTH
| forRepl = False
| useDynToo = False
| isGhcDynamic = doingTH && (withProfExe lbi || withStaticExe)
| otherwise = doingTH && (withProfExe lbi || withDynExe lbi)
linkOpts = commonOpts `mappend`
linkerOpts `mappend`
mempty { ghcOptLinkNoHsMain = toFlag (not isHaskellMain) } `mappend`
(if withDynExe lbi then dynLinkerOpts else mempty)
-- Build static/dynamic object files for TH, if needed.
when compileForTH $
runGhcProg compileTHOpts { ghcOptNoLink = toFlag True
, ghcOptNumJobs = numJobs }
unless forRepl $
runGhcProg compileOpts { ghcOptNoLink = toFlag True
, ghcOptNumJobs = numJobs }
-- build any C sources
unless (null cSrcs) $ do
info verbosity "Building C Sources..."
sequence_
[ do let opts = (Internal.componentCcGhcOptions verbosity implInfo lbi exeBi
clbi exeDir filename) `mappend` mempty {
ghcOptDynLinkMode = toFlag (if withDynExe lbi
then GhcDynamicOnly
else GhcStaticOnly),
ghcOptProfilingMode = toFlag (withProfExe lbi)
}
odir = fromFlag (ghcOptObjDir opts)
createDirectoryIfMissingVerbose verbosity True odir
needsRecomp <- checkNeedsRecompilation filename opts
when needsRecomp $
runGhcProg opts
| filename <- cSrcs ]
-- TODO: problem here is we need the .c files built first, so we can load them
-- with ghci, but .c files can depend on .h files generated by ghc by ffi
-- exports.
when forRepl $ runGhcProg replOpts
-- link:
unless forRepl $ do
info verbosity "Linking..."
runGhcProg linkOpts { ghcOptOutputFile = toFlag (targetDir </> exeNameReal) }
-- | Returns True if the modification date of the given source file is newer than
-- the object file we last compiled for it, or if no object file exists yet.
checkNeedsRecompilation :: FilePath -> GhcOptions -> IO Bool
checkNeedsRecompilation filename opts = filename `moreRecentFile` oname
where oname = getObjectFileName filename opts
-- | Finds the object file name of the given source file
getObjectFileName :: FilePath -> GhcOptions -> FilePath
getObjectFileName filename opts = oname
where odir = fromFlag (ghcOptObjDir opts)
oext = fromFlagOrDefault "o" (ghcOptObjSuffix opts)
oname = odir </> replaceExtension filename oext
-- | Calculate the RPATHs for the component we are building.
--
-- Calculates relative RPATHs when 'relocatable' is set.
getRPaths :: LocalBuildInfo
-> ComponentLocalBuildInfo -- ^ Component we are building
-> IO (NubListR FilePath)
getRPaths lbi clbi | supportRPaths hostOS = do
libraryPaths <- depLibraryPaths False (relocatable lbi) lbi clbi
let hostPref = case hostOS of
OSX -> "@loader_path"
_ -> "$ORIGIN"
relPath p = if isRelative p then hostPref </> p else p
rpaths = toNubListR (map relPath libraryPaths)
return rpaths
where
(Platform _ hostOS) = hostPlatform lbi
-- The list of RPath-supported operating systems below reflects the
-- platforms on which Cabal's RPATH handling is tested. It does _NOT_
-- reflect whether the OS supports RPATH.
-- E.g. when this comment was written, the *BSD operating systems were
-- untested with regards to Cabal RPATH handling, and were hence set to
-- 'False', while those operating systems themselves do support RPATH.
supportRPaths Linux = True
supportRPaths Windows = False
supportRPaths OSX = True
supportRPaths FreeBSD = False
supportRPaths OpenBSD = False
supportRPaths NetBSD = False
supportRPaths DragonFly = False
supportRPaths Solaris = False
supportRPaths AIX = False
supportRPaths HPUX = False
supportRPaths IRIX = False
supportRPaths HaLVM = False
supportRPaths IOS = False
supportRPaths Android = False
supportRPaths Ghcjs = False
supportRPaths Hurd = False
supportRPaths (OtherOS _) = False
-- Do _not_ add a default case so that we get a warning here when a new OS
-- is added.
getRPaths _ _ = return mempty
-- | Filter the "-threaded" flag when profiling as it does not
-- work with ghc-6.8 and older.
hackThreadedFlag :: Verbosity -> Compiler -> Bool -> BuildInfo -> IO BuildInfo
hackThreadedFlag verbosity comp prof bi
| not mustFilterThreaded = return bi
| otherwise = do
warn verbosity $ "The ghc flag '-threaded' is not compatible with "
++ "profiling in ghc-6.8 and older. It will be disabled."
return bi { options = filterHcOptions (/= "-threaded") (options bi) }
where
mustFilterThreaded = prof && compilerVersion comp < Version [6, 10] []
&& "-threaded" `elem` hcOptions GHC bi
filterHcOptions p hcoptss =
[ (hc, if hc == GHC then filter p opts else opts)
| (hc, opts) <- hcoptss ]
-- | Extracts a String representing a hash of the ABI of a built
-- library. It can fail if the library has not yet been built.
--
libAbiHash :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Library -> ComponentLocalBuildInfo -> IO String
libAbiHash verbosity _pkg_descr lbi lib clbi = do
libBi <- hackThreadedFlag verbosity
(compiler lbi) (withProfLib lbi) (libBuildInfo lib)
let
comp = compiler lbi
vanillaArgs =
(componentGhcOptions verbosity lbi libBi clbi (buildDir lbi))
`mappend` mempty {
ghcOptMode = toFlag GhcModeAbiHash,
ghcOptInputModules = toNubListR $ exposedModules lib
}
sharedArgs = vanillaArgs `mappend` mempty {
ghcOptDynLinkMode = toFlag GhcDynamicOnly,
ghcOptFPic = toFlag True,
ghcOptHiSuffix = toFlag "dyn_hi",
ghcOptObjSuffix = toFlag "dyn_o",
ghcOptExtra = toNubListR $ hcSharedOptions GHC libBi
}
profArgs = vanillaArgs `mappend` mempty {
ghcOptProfilingMode = toFlag True,
ghcOptProfilingAuto = Internal.profDetailLevelFlag True
(withProfLibDetail lbi),
ghcOptHiSuffix = toFlag "p_hi",
ghcOptObjSuffix = toFlag "p_o",
ghcOptExtra = toNubListR $ hcProfOptions GHC libBi
}
ghcArgs = if withVanillaLib lbi then vanillaArgs
else if withSharedLib lbi then sharedArgs
else if withProfLib lbi then profArgs
else error "libAbiHash: Can't find an enabled library way"
--
(ghcProg, _) <- requireProgram verbosity ghcProgram (withPrograms lbi)
hash <- getProgramInvocationOutput verbosity
(ghcInvocation ghcProg comp ghcArgs)
return (takeWhile (not . isSpace) hash)
componentGhcOptions :: Verbosity -> LocalBuildInfo
-> BuildInfo -> ComponentLocalBuildInfo -> FilePath
-> GhcOptions
componentGhcOptions = Internal.componentGhcOptions
componentCcGhcOptions :: Verbosity -> LocalBuildInfo
-> BuildInfo -> ComponentLocalBuildInfo
-> FilePath -> FilePath
-> GhcOptions
componentCcGhcOptions verbosity lbi =
Internal.componentCcGhcOptions verbosity implInfo lbi
where
comp = compiler lbi
implInfo = getImplInfo comp
-- -----------------------------------------------------------------------------
-- Installing
-- |Install executables for GHC.
installExe :: Verbosity
-> LocalBuildInfo
-> InstallDirs FilePath -- ^Where to copy the files to
-> FilePath -- ^Build location
-> (FilePath, FilePath) -- ^Executable (prefix,suffix)
-> PackageDescription
-> Executable
-> IO ()
installExe verbosity lbi installDirs buildPref
(progprefix, progsuffix) _pkg exe = do
let binDir = bindir installDirs
createDirectoryIfMissingVerbose verbosity True binDir
let exeFileName = exeName exe <.> exeExtension
fixedExeBaseName = progprefix ++ exeName exe ++ progsuffix
installBinary dest = do
installExecutableFile verbosity
(buildPref </> exeName exe </> exeFileName)
(dest <.> exeExtension)
when (stripExes lbi) $
Strip.stripExe verbosity (hostPlatform lbi) (withPrograms lbi)
(dest <.> exeExtension)
installBinary (binDir </> fixedExeBaseName)
-- |Install for ghc, .hi, .a and, if --with-ghci given, .o
installLib :: Verbosity
-> LocalBuildInfo
-> FilePath -- ^install location
-> FilePath -- ^install location for dynamic libraries
-> FilePath -- ^Build location
-> PackageDescription
-> Library
-> ComponentLocalBuildInfo
-> IO ()
installLib verbosity lbi targetDir dynlibTargetDir builtDir _pkg lib clbi = do
-- copy .hi files over:
whenVanilla $ copyModuleFiles "hi"
whenProf $ copyModuleFiles "p_hi"
whenShared $ copyModuleFiles "dyn_hi"
-- copy the built library files over:
whenVanilla $ installOrdinary builtDir targetDir vanillaLibName
whenProf $ installOrdinary builtDir targetDir profileLibName
whenGHCi $ installOrdinary builtDir targetDir ghciLibName
whenShared $ installShared builtDir dynlibTargetDir sharedLibName
where
install isShared srcDir dstDir name = do
let src = srcDir </> name
dst = dstDir </> name
createDirectoryIfMissingVerbose verbosity True dstDir
if isShared
then installExecutableFile verbosity src dst
else installOrdinaryFile verbosity src dst
when (stripLibs lbi) $ Strip.stripLib verbosity
(hostPlatform lbi) (withPrograms lbi) dst
installOrdinary = install False
installShared = install True
copyModuleFiles ext =
findModuleFiles [builtDir] [ext] (libModules lib)
>>= installOrdinaryFiles verbosity targetDir
cid = compilerId (compiler lbi)
libName = componentId clbi
vanillaLibName = mkLibName libName
profileLibName = mkProfLibName libName
ghciLibName = Internal.mkGHCiLibName libName
sharedLibName = (mkSharedLibName cid) libName
hasLib = not $ null (libModules lib)
&& null (cSources (libBuildInfo lib))
whenVanilla = when (hasLib && withVanillaLib lbi)
whenProf = when (hasLib && withProfLib lbi)
whenGHCi = when (hasLib && withGHCiLib lbi)
whenShared = when (hasLib && withSharedLib lbi)
-- -----------------------------------------------------------------------------
-- Registering
hcPkgInfo :: ProgramConfiguration -> HcPkg.HcPkgInfo
hcPkgInfo conf = HcPkg.HcPkgInfo { HcPkg.hcPkgProgram = ghcPkgProg
, HcPkg.noPkgDbStack = v < [6,9]
, HcPkg.noVerboseFlag = v < [6,11]
, HcPkg.flagPackageConf = v < [7,5]
, HcPkg.useSingleFileDb = v < [7,9]
}
where
v = versionBranch ver
Just ghcPkgProg = lookupProgram ghcPkgProgram conf
Just ver = programVersion ghcPkgProg
registerPackage
:: Verbosity
-> InstalledPackageInfo
-> PackageDescription
-> LocalBuildInfo
-> Bool
-> PackageDBStack
-> IO ()
registerPackage verbosity installedPkgInfo _pkg lbi _inplace packageDbs =
HcPkg.reregister (hcPkgInfo $ withPrograms lbi) verbosity
packageDbs (Right installedPkgInfo)
pkgRoot :: Verbosity -> LocalBuildInfo -> PackageDB -> IO FilePath
pkgRoot verbosity lbi = pkgRoot'
where
pkgRoot' GlobalPackageDB =
let Just ghcProg = lookupProgram ghcProgram (withPrograms lbi)
in fmap takeDirectory (getGlobalPackageDB verbosity ghcProg)
pkgRoot' UserPackageDB = do
appDir <- getAppUserDataDirectory "ghc"
let ver = compilerVersion (compiler lbi)
subdir = System.Info.arch ++ '-':System.Info.os
++ '-':showVersion ver
rootDir = appDir </> subdir
-- We must create the root directory for the user package database if it
-- does not yet exists. Otherwise '${pkgroot}' will resolve to a
-- directory at the time of 'ghc-pkg register', and registration will
-- fail.
createDirectoryIfMissing True rootDir
return rootDir
pkgRoot' (SpecificPackageDB fp) = return (takeDirectory fp)
-- -----------------------------------------------------------------------------
-- Utils
isDynamic :: Compiler -> Bool
isDynamic = Internal.ghcLookupProperty "GHC Dynamic"
supportsDynamicToo :: Compiler -> Bool
supportsDynamicToo = Internal.ghcLookupProperty "Support dynamic-too"
| thoughtpolice/cabal | Cabal/Distribution/Simple/GHC.hs | bsd-3-clause | 52,313 | 0 | 23 | 16,008 | 9,753 | 5,117 | 4,636 | 826 | 19 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module Utils.Http (send) where
import qualified Control.Exception as E
import Control.Monad.Error.Class (MonadError, throwError)
import Control.Monad.Trans (MonadIO, liftIO)
import qualified Data.ByteString.Char8 as BSC
import qualified Data.List as List
import Network (withSocketsDo)
import Network.HTTP.Client
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Network.HTTP.Types
send
:: (MonadIO m, MonadError String m)
=> String
-> (Request -> Manager -> IO a)
-> m a
send url handler =
do result <- liftIO (sendSafe url handler)
either throwError return result
sendSafe :: String -> (Request -> Manager -> IO a) -> IO (Either String a)
sendSafe url handler =
sendUnsafe url handler
`E.catch` handleHttpError url
`E.catch` (handleAnyError url :: E.SomeException -> IO (Either String b))
sendUnsafe :: String -> (Request -> Manager -> IO a) -> IO (Either err a)
sendUnsafe url handler =
do request <- parseUrl url
result <- withSocketsDo $ withManager tlsManagerSettings (handler request)
return (Right result)
handleHttpError :: String -> HttpException -> IO (Either String b)
handleHttpError url exception =
case exception of
StatusCodeException (Status _code err) headers _ ->
let details =
case List.lookup "X-Response-Body-Start" headers of
Just msg | not (BSC.null msg) -> msg
_ -> err
in
return . Left $ BSC.unpack details
_ -> handleAnyError url exception
handleAnyError :: (E.Exception e) => String -> e -> IO (Either String b)
handleAnyError url exception =
return . Left $
"failed with '" ++ show exception ++ "' when sending request to\n" ++
" <" ++ url ++ ">"
| laszlopandy/elm-package | src/Utils/Http.hs | bsd-3-clause | 1,824 | 0 | 21 | 414 | 587 | 304 | 283 | 45 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.