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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LINE 1 "Data.Either.hs" #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE PolyKinds, DataKinds, TypeFamilies, TypeOperators, UndecidableInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Either
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- The Either type, and associated operations.
--
-----------------------------------------------------------------------------
module Data.Either (
Either(..),
either,
lefts,
rights,
isLeft,
isRight,
partitionEithers,
) where
import GHC.Base
import GHC.Show
import GHC.Read
import Data.Type.Equality
-- $setup
-- Allow the use of some Prelude functions in doctests.
-- >>> import Prelude ( (+), (*), length, putStrLn )
{-
-- just for testing
import Test.QuickCheck
-}
{-|
The 'Either' type represents values with two possibilities: a value of
type @'Either' a b@ is either @'Left' a@ or @'Right' b@.
The 'Either' type is sometimes used to represent a value which is
either correct or an error; by convention, the 'Left' constructor is
used to hold an error value and the 'Right' constructor is used to
hold a correct value (mnemonic: \"right\" also means \"correct\").
==== __Examples__
The type @'Either' 'String' 'Int'@ is the type of values which can be either
a 'String' or an 'Int'. The 'Left' constructor can be used only on
'String's, and the 'Right' constructor can be used only on 'Int's:
>>> let s = Left "foo" :: Either String Int
>>> s
Left "foo"
>>> let n = Right 3 :: Either String Int
>>> n
Right 3
>>> :type s
s :: Either String Int
>>> :type n
n :: Either String Int
The 'fmap' from our 'Functor' instance will ignore 'Left' values, but
will apply the supplied function to values contained in a 'Right':
>>> let s = Left "foo" :: Either String Int
>>> let n = Right 3 :: Either String Int
>>> fmap (*2) s
Left "foo"
>>> fmap (*2) n
Right 6
The 'Monad' instance for 'Either' allows us to chain together multiple
actions which may fail, and fail overall if any of the individual
steps failed. First we'll write a function that can either parse an
'Int' from a 'Char', or fail.
>>> import Data.Char ( digitToInt, isDigit )
>>> :{
let parseEither :: Char -> Either String Int
parseEither c
| isDigit c = Right (digitToInt c)
| otherwise = Left "parse error"
>>> :}
The following should work, since both @\'1\'@ and @\'2\'@ can be
parsed as 'Int's.
>>> :{
let parseMultiple :: Either String Int
parseMultiple = do
x <- parseEither '1'
y <- parseEither '2'
return (x + y)
>>> :}
>>> parseMultiple
Right 3
But the following should fail overall, since the first operation where
we attempt to parse @\'m\'@ as an 'Int' will fail:
>>> :{
let parseMultiple :: Either String Int
parseMultiple = do
x <- parseEither 'm'
y <- parseEither '2'
return (x + y)
>>> :}
>>> parseMultiple
Left "parse error"
-}
data Either a b = Left a | Right b
deriving (Eq, Ord, Read, Show)
instance Functor (Either a) where
fmap _ (Left x) = Left x
fmap f (Right y) = Right (f y)
instance Applicative (Either e) where
pure = Right
Left e <*> _ = Left e
Right f <*> r = fmap f r
instance Monad (Either e) where
Left l >>= _ = Left l
Right r >>= k = k r
-- | Case analysis for the 'Either' type.
-- If the value is @'Left' a@, apply the first function to @a@;
-- if it is @'Right' b@, apply the second function to @b@.
--
-- ==== __Examples__
--
-- We create two values of type @'Either' 'String' 'Int'@, one using the
-- 'Left' constructor and another using the 'Right' constructor. Then
-- we apply \"either\" the 'length' function (if we have a 'String')
-- or the \"times-two\" function (if we have an 'Int'):
--
-- >>> let s = Left "foo" :: Either String Int
-- >>> let n = Right 3 :: Either String Int
-- >>> either length (*2) s
-- 3
-- >>> either length (*2) n
-- 6
--
either :: (a -> c) -> (b -> c) -> Either a b -> c
either f _ (Left x) = f x
either _ g (Right y) = g y
-- | Extracts from a list of 'Either' all the 'Left' elements.
-- All the 'Left' elements are extracted in order.
--
-- ==== __Examples__
--
-- Basic usage:
--
-- >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
-- >>> lefts list
-- ["foo","bar","baz"]
--
lefts :: [Either a b] -> [a]
lefts x = [a | Left a <- x]
-- | Extracts from a list of 'Either' all the 'Right' elements.
-- All the 'Right' elements are extracted in order.
--
-- ==== __Examples__
--
-- Basic usage:
--
-- >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
-- >>> rights list
-- [3,7]
--
rights :: [Either a b] -> [b]
rights x = [a | Right a <- x]
-- | Partitions a list of 'Either' into two lists.
-- All the 'Left' elements are extracted, in order, to the first
-- component of the output. Similarly the 'Right' elements are extracted
-- to the second component of the output.
--
-- ==== __Examples__
--
-- Basic usage:
--
-- >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
-- >>> partitionEithers list
-- (["foo","bar","baz"],[3,7])
--
-- The pair returned by @'partitionEithers' x@ should be the same
-- pair as @('lefts' x, 'rights' x)@:
--
-- >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]
-- >>> partitionEithers list == (lefts list, rights list)
-- True
--
partitionEithers :: [Either a b] -> ([a],[b])
partitionEithers = foldr (either left right) ([],[])
where
left a ~(l, r) = (a:l, r)
right a ~(l, r) = (l, a:r)
-- | Return `True` if the given value is a `Left`-value, `False` otherwise.
--
-- @since 4.7.0.0
--
-- ==== __Examples__
--
-- Basic usage:
--
-- >>> isLeft (Left "foo")
-- True
-- >>> isLeft (Right 3)
-- False
--
-- Assuming a 'Left' value signifies some sort of error, we can use
-- 'isLeft' to write a very simple error-reporting function that does
-- absolutely nothing in the case of success, and outputs \"ERROR\" if
-- any error occurred.
--
-- This example shows how 'isLeft' might be used to avoid pattern
-- matching when one does not care about the value contained in the
-- constructor:
--
-- >>> import Control.Monad ( when )
-- >>> let report e = when (isLeft e) $ putStrLn "ERROR"
-- >>> report (Right 1)
-- >>> report (Left "parse error")
-- ERROR
--
isLeft :: Either a b -> Bool
isLeft (Left _) = True
isLeft (Right _) = False
-- | Return `True` if the given value is a `Right`-value, `False` otherwise.
--
-- @since 4.7.0.0
--
-- ==== __Examples__
--
-- Basic usage:
--
-- >>> isRight (Left "foo")
-- False
-- >>> isRight (Right 3)
-- True
--
-- Assuming a 'Left' value signifies some sort of error, we can use
-- 'isRight' to write a very simple reporting function that only
-- outputs \"SUCCESS\" when a computation has succeeded.
--
-- This example shows how 'isRight' might be used to avoid pattern
-- matching when one does not care about the value contained in the
-- constructor:
--
-- >>> import Control.Monad ( when )
-- >>> let report e = when (isRight e) $ putStrLn "SUCCESS"
-- >>> report (Left "parse error")
-- >>> report (Right 1)
-- SUCCESS
--
isRight :: Either a b -> Bool
isRight (Left _) = False
isRight (Right _) = True
-- instance for the == Boolean type-level equality operator
type family EqEither a b where
EqEither ('Left x) ('Left y) = x == y
EqEither ('Right x) ('Right y) = x == y
EqEither a b = 'False
type instance a == b = EqEither a b
{-
{--------------------------------------------------------------------
Testing
--------------------------------------------------------------------}
prop_partitionEithers :: [Either Int Int] -> Bool
prop_partitionEithers x =
partitionEithers x == (lefts x, rights x)
-}
| phischu/fragnix | builtins/base/Data.Either.hs | bsd-3-clause | 8,051 | 1 | 9 | 1,708 | 848 | 510 | 338 | 50 | 1 |
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
{-@ LIQUID "--no-termination "@-}
import Language.Haskell.Liquid.Prelude
mmax x y
| x < y = y
| otherwise = x
for lo hi acc f
| lo < hi = for (lo + 1) hi (f lo acc) f
| otherwise = acc
sumRange i j = for i j 0 (+)
prop = liquidAssertB (m >= 0)
where m = sumRange 0 k
k = choose 0
prop2 = liquidAssertB (z >= x && z >= y)
where x = choose 0
y = choose 1
z = mmax x y
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/forloop.hs | bsd-3-clause | 471 | 0 | 9 | 152 | 206 | 104 | 102 | 17 | 1 |
{-# LANGUAGE DataKinds #-}
module Ivory.Tower.Monitor
( handler
, state
, stateInit
, monitorModuleDef
, Handler()
, Monitor()
) where
import Ivory.Tower.Types.Unique
import Ivory.Tower.Monad.Handler
import Ivory.Tower.Monad.Monitor
import Ivory.Tower.Monad.Base
import Ivory.Language
state :: (IvoryArea a, IvoryZero a)
=> String -> Monitor e (Ref 'Global a)
state n = state' n Nothing
stateInit :: (IvoryArea a, IvoryZero a)
=> String -> Init a -> Monitor e (Ref 'Global a)
stateInit n i = state' n (Just i)
state' :: (IvoryArea a, IvoryZero a)
=> String
-> Maybe (Init a)
-> Monitor e (Ref 'Global a)
state' n i = do
f <- freshname n
let a = area (showUnique f) i
monitorModuleDef $ defMemArea a
return (addrOf a)
| GaloisInc/tower | tower/src/Ivory/Tower/Monitor.hs | bsd-3-clause | 782 | 0 | 12 | 181 | 300 | 158 | 142 | 33 | 1 |
{-# language CPP #-}
-- | = Name
--
-- VK_EXT_sample_locations - device extension
--
-- == VK_EXT_sample_locations
--
-- [__Name String__]
-- @VK_EXT_sample_locations@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
-- 144
--
-- [__Revision__]
-- 1
--
-- [__Extension and Version Dependencies__]
--
-- - Requires Vulkan 1.0
--
-- - Requires @VK_KHR_get_physical_device_properties2@
--
-- [__Contact__]
--
-- - Daniel Rakos
-- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_sample_locations] @drakos-amd%0A<<Here describe the issue or question you have about the VK_EXT_sample_locations extension>> >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
-- 2017-08-02
--
-- [__Contributors__]
--
-- - Mais Alnasser, AMD
--
-- - Matthaeus G. Chajdas, AMD
--
-- - Maciej Jesionowski, AMD
--
-- - Daniel Rakos, AMD
--
-- - Slawomir Grajewski, Intel
--
-- - Jeff Bolz, NVIDIA
--
-- - Bill Licea-Kane, Qualcomm
--
-- == Description
--
-- This extension allows an application to modify the locations of samples
-- within a pixel used in rasterization. Additionally, it allows
-- applications to specify different sample locations for each pixel in a
-- group of adjacent pixels, which /can/ increase antialiasing quality
-- (particularly if a custom resolve shader is used that takes advantage of
-- these different locations).
--
-- It is common for implementations to optimize the storage of depth values
-- by storing values that /can/ be used to reconstruct depth at each sample
-- location, rather than storing separate depth values for each sample. For
-- example, the depth values from a single triangle /may/ be represented
-- using plane equations. When the depth value for a sample is needed, it
-- is automatically evaluated at the sample location. Modifying the sample
-- locations causes the reconstruction to no longer evaluate the same depth
-- values as when the samples were originally generated, thus the depth
-- aspect of a depth\/stencil attachment /must/ be cleared before rendering
-- to it using different sample locations.
--
-- Some implementations /may/ need to evaluate depth image values while
-- performing image layout transitions. To accommodate this, instances of
-- the 'SampleLocationsInfoEXT' structure /can/ be specified for each
-- situation where an explicit or automatic layout transition has to take
-- place. 'SampleLocationsInfoEXT' /can/ be chained from
-- 'Vulkan.Core10.OtherTypes.ImageMemoryBarrier' structures to provide
-- sample locations for layout transitions performed by
-- 'Vulkan.Core10.CommandBufferBuilding.cmdWaitEvents' and
-- 'Vulkan.Core10.CommandBufferBuilding.cmdPipelineBarrier' calls, and
-- 'RenderPassSampleLocationsBeginInfoEXT' /can/ be chained from
-- 'Vulkan.Core10.CommandBufferBuilding.RenderPassBeginInfo' to provide
-- sample locations for layout transitions performed implicitly by a render
-- pass instance.
--
-- == New Commands
--
-- - 'cmdSetSampleLocationsEXT'
--
-- - 'getPhysicalDeviceMultisamplePropertiesEXT'
--
-- == New Structures
--
-- - 'AttachmentSampleLocationsEXT'
--
-- - 'MultisamplePropertiesEXT'
--
-- - 'SampleLocationEXT'
--
-- - 'SubpassSampleLocationsEXT'
--
-- - Extending 'Vulkan.Core10.OtherTypes.ImageMemoryBarrier',
-- 'Vulkan.Core13.Promoted_From_VK_KHR_synchronization2.ImageMemoryBarrier2':
--
-- - 'SampleLocationsInfoEXT'
--
-- - Extending
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceProperties2':
--
-- - 'PhysicalDeviceSampleLocationsPropertiesEXT'
--
-- - Extending
-- 'Vulkan.Core10.Pipeline.PipelineMultisampleStateCreateInfo':
--
-- - 'PipelineSampleLocationsStateCreateInfoEXT'
--
-- - Extending 'Vulkan.Core10.CommandBufferBuilding.RenderPassBeginInfo':
--
-- - 'RenderPassSampleLocationsBeginInfoEXT'
--
-- == New Enum Constants
--
-- - 'EXT_SAMPLE_LOCATIONS_EXTENSION_NAME'
--
-- - 'EXT_SAMPLE_LOCATIONS_SPEC_VERSION'
--
-- - Extending 'Vulkan.Core10.Enums.DynamicState.DynamicState':
--
-- - 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT'
--
-- - Extending
-- 'Vulkan.Core10.Enums.ImageCreateFlagBits.ImageCreateFlagBits':
--
-- - 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_MULTISAMPLE_PROPERTIES_EXT'
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLE_LOCATIONS_PROPERTIES_EXT'
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PIPELINE_SAMPLE_LOCATIONS_STATE_CREATE_INFO_EXT'
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_RENDER_PASS_SAMPLE_LOCATIONS_BEGIN_INFO_EXT'
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT'
--
-- == Version History
--
-- - Revision 1, 2017-08-02 (Daniel Rakos)
--
-- - Internal revisions
--
-- == See Also
--
-- 'AttachmentSampleLocationsEXT', 'MultisamplePropertiesEXT',
-- 'PhysicalDeviceSampleLocationsPropertiesEXT',
-- 'PipelineSampleLocationsStateCreateInfoEXT',
-- 'RenderPassSampleLocationsBeginInfoEXT', 'SampleLocationEXT',
-- 'SampleLocationsInfoEXT', 'SubpassSampleLocationsEXT',
-- 'cmdSetSampleLocationsEXT', 'getPhysicalDeviceMultisamplePropertiesEXT'
--
-- == Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_EXT_sample_locations 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_sample_locations ( cmdSetSampleLocationsEXT
, getPhysicalDeviceMultisamplePropertiesEXT
, SampleLocationEXT(..)
, SampleLocationsInfoEXT(..)
, AttachmentSampleLocationsEXT(..)
, SubpassSampleLocationsEXT(..)
, RenderPassSampleLocationsBeginInfoEXT(..)
, PipelineSampleLocationsStateCreateInfoEXT(..)
, PhysicalDeviceSampleLocationsPropertiesEXT(..)
, MultisamplePropertiesEXT(..)
, EXT_SAMPLE_LOCATIONS_SPEC_VERSION
, pattern EXT_SAMPLE_LOCATIONS_SPEC_VERSION
, EXT_SAMPLE_LOCATIONS_EXTENSION_NAME
, pattern EXT_SAMPLE_LOCATIONS_EXTENSION_NAME
) where
import Vulkan.CStruct.Utils (FixedArray)
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 Data.Vector (generateM)
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.CStruct.Utils (advancePtrBytes)
import Vulkan.Core10.FundamentalTypes (bool32ToBool)
import Vulkan.Core10.FundamentalTypes (boolToBool32)
import Vulkan.CStruct.Utils (lowerArrayPtr)
import Vulkan.NamedType ((:::))
import Vulkan.Core10.FundamentalTypes (Bool32)
import Vulkan.Core10.Handles (CommandBuffer)
import Vulkan.Core10.Handles (CommandBuffer(..))
import Vulkan.Core10.Handles (CommandBuffer(CommandBuffer))
import Vulkan.Core10.Handles (CommandBuffer_T)
import Vulkan.Dynamic (DeviceCmds(pVkCmdSetSampleLocationsEXT))
import Vulkan.Core10.FundamentalTypes (Extent2D)
import Vulkan.Dynamic (InstanceCmds(pVkGetPhysicalDeviceMultisamplePropertiesEXT))
import Vulkan.Core10.Handles (PhysicalDevice)
import Vulkan.Core10.Handles (PhysicalDevice(..))
import Vulkan.Core10.Handles (PhysicalDevice(PhysicalDevice))
import Vulkan.Core10.Handles (PhysicalDevice_T)
import Vulkan.Core10.Enums.SampleCountFlagBits (SampleCountFlagBits)
import Vulkan.Core10.Enums.SampleCountFlagBits (SampleCountFlagBits(..))
import Vulkan.Core10.Enums.SampleCountFlagBits (SampleCountFlags)
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_MULTISAMPLE_PROPERTIES_EXT))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLE_LOCATIONS_PROPERTIES_EXT))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PIPELINE_SAMPLE_LOCATIONS_STATE_CREATE_INFO_EXT))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RENDER_PASS_SAMPLE_LOCATIONS_BEGIN_INFO_EXT))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkCmdSetSampleLocationsEXT
:: FunPtr (Ptr CommandBuffer_T -> Ptr SampleLocationsInfoEXT -> IO ()) -> Ptr CommandBuffer_T -> Ptr SampleLocationsInfoEXT -> IO ()
-- | vkCmdSetSampleLocationsEXT - Set sample locations dynamically for a
-- command buffer
--
-- = Description
--
-- This command sets the custom sample locations for subsequent drawing
-- commands when the graphics pipeline is created with
-- 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT'
-- set in
-- 'Vulkan.Core10.Pipeline.PipelineDynamicStateCreateInfo'::@pDynamicStates@,
-- and when the
-- 'PipelineSampleLocationsStateCreateInfoEXT'::@sampleLocationsEnable@
-- property of the bound graphics pipeline is
-- 'Vulkan.Core10.FundamentalTypes.TRUE'. Otherwise, this state is
-- specified by the
-- 'PipelineSampleLocationsStateCreateInfoEXT'::@sampleLocationsInfo@
-- values used to create the currently active pipeline.
--
-- == Valid Usage
--
-- - #VUID-vkCmdSetSampleLocationsEXT-sampleLocationsPerPixel-01529# The
-- @sampleLocationsPerPixel@ member of @pSampleLocationsInfo@ /must/
-- equal the @rasterizationSamples@ member of the
-- 'Vulkan.Core10.Pipeline.PipelineMultisampleStateCreateInfo'
-- structure the bound graphics pipeline has been created with
--
-- - #VUID-vkCmdSetSampleLocationsEXT-variableSampleLocations-01530# If
-- 'PhysicalDeviceSampleLocationsPropertiesEXT'::@variableSampleLocations@
-- is 'Vulkan.Core10.FundamentalTypes.FALSE' then the current render
-- pass /must/ have been begun by specifying a
-- 'RenderPassSampleLocationsBeginInfoEXT' structure whose
-- @pPostSubpassSampleLocations@ member contains an element with a
-- @subpassIndex@ matching the current subpass index and the
-- @sampleLocationsInfo@ member of that element /must/ match the sample
-- locations state pointed to by @pSampleLocationsInfo@
--
-- == Valid Usage (Implicit)
--
-- - #VUID-vkCmdSetSampleLocationsEXT-commandBuffer-parameter#
-- @commandBuffer@ /must/ be a valid
-- 'Vulkan.Core10.Handles.CommandBuffer' handle
--
-- - #VUID-vkCmdSetSampleLocationsEXT-pSampleLocationsInfo-parameter#
-- @pSampleLocationsInfo@ /must/ be a valid pointer to a valid
-- 'SampleLocationsInfoEXT' structure
--
-- - #VUID-vkCmdSetSampleLocationsEXT-commandBuffer-recording#
-- @commandBuffer@ /must/ be in the
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#commandbuffers-lifecycle recording state>
--
-- - #VUID-vkCmdSetSampleLocationsEXT-commandBuffer-cmdpool# The
-- 'Vulkan.Core10.Handles.CommandPool' that @commandBuffer@ was
-- allocated from /must/ support graphics operations
--
-- == Host Synchronization
--
-- - Host access to @commandBuffer@ /must/ be externally synchronized
--
-- - Host access to the 'Vulkan.Core10.Handles.CommandPool' that
-- @commandBuffer@ was allocated from /must/ be externally synchronized
--
-- == Command Properties
--
-- \'
--
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+
-- | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types> |
-- +============================================================================================================================+========================================================================================================================+=======================================================================================================================+
-- | Primary | Both | Graphics |
-- | Secondary | | |
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>,
-- 'Vulkan.Core10.Handles.CommandBuffer', 'SampleLocationsInfoEXT'
cmdSetSampleLocationsEXT :: forall io
. (MonadIO io)
=> -- | @commandBuffer@ is the command buffer into which the command will be
-- recorded.
CommandBuffer
-> -- | @pSampleLocationsInfo@ is the sample locations state to set.
SampleLocationsInfoEXT
-> io ()
cmdSetSampleLocationsEXT commandBuffer sampleLocationsInfo = liftIO . evalContT $ do
let vkCmdSetSampleLocationsEXTPtr = pVkCmdSetSampleLocationsEXT (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds)
lift $ unless (vkCmdSetSampleLocationsEXTPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdSetSampleLocationsEXT is null" Nothing Nothing
let vkCmdSetSampleLocationsEXT' = mkVkCmdSetSampleLocationsEXT vkCmdSetSampleLocationsEXTPtr
pSampleLocationsInfo <- ContT $ withCStruct (sampleLocationsInfo)
lift $ traceAroundEvent "vkCmdSetSampleLocationsEXT" (vkCmdSetSampleLocationsEXT' (commandBufferHandle (commandBuffer)) pSampleLocationsInfo)
pure $ ()
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkGetPhysicalDeviceMultisamplePropertiesEXT
:: FunPtr (Ptr PhysicalDevice_T -> SampleCountFlagBits -> Ptr MultisamplePropertiesEXT -> IO ()) -> Ptr PhysicalDevice_T -> SampleCountFlagBits -> Ptr MultisamplePropertiesEXT -> IO ()
-- | vkGetPhysicalDeviceMultisamplePropertiesEXT - Report sample count
-- specific multisampling capabilities of a physical device
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>,
-- 'MultisamplePropertiesEXT', 'Vulkan.Core10.Handles.PhysicalDevice',
-- 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlagBits'
getPhysicalDeviceMultisamplePropertiesEXT :: forall io
. (MonadIO io)
=> -- | @physicalDevice@ is the physical device from which to query the
-- additional multisampling capabilities.
--
-- #VUID-vkGetPhysicalDeviceMultisamplePropertiesEXT-physicalDevice-parameter#
-- @physicalDevice@ /must/ be a valid
-- 'Vulkan.Core10.Handles.PhysicalDevice' handle
PhysicalDevice
-> -- | @samples@ is a
-- 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlagBits' value
-- specifying the sample count to query capabilities for.
--
-- #VUID-vkGetPhysicalDeviceMultisamplePropertiesEXT-samples-parameter#
-- @samples@ /must/ be a valid
-- 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlagBits' value
("samples" ::: SampleCountFlagBits)
-> io (MultisamplePropertiesEXT)
getPhysicalDeviceMultisamplePropertiesEXT physicalDevice samples = liftIO . evalContT $ do
let vkGetPhysicalDeviceMultisamplePropertiesEXTPtr = pVkGetPhysicalDeviceMultisamplePropertiesEXT (case physicalDevice of PhysicalDevice{instanceCmds} -> instanceCmds)
lift $ unless (vkGetPhysicalDeviceMultisamplePropertiesEXTPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetPhysicalDeviceMultisamplePropertiesEXT is null" Nothing Nothing
let vkGetPhysicalDeviceMultisamplePropertiesEXT' = mkVkGetPhysicalDeviceMultisamplePropertiesEXT vkGetPhysicalDeviceMultisamplePropertiesEXTPtr
pPMultisampleProperties <- ContT (withZeroCStruct @MultisamplePropertiesEXT)
lift $ traceAroundEvent "vkGetPhysicalDeviceMultisamplePropertiesEXT" (vkGetPhysicalDeviceMultisamplePropertiesEXT' (physicalDeviceHandle (physicalDevice)) (samples) (pPMultisampleProperties))
pMultisampleProperties <- lift $ peekCStruct @MultisamplePropertiesEXT pPMultisampleProperties
pure $ (pMultisampleProperties)
-- | VkSampleLocationEXT - Structure specifying the coordinates of a sample
-- location
--
-- = Description
--
-- The domain space of the sample location coordinates has an upper-left
-- origin within the pixel in framebuffer space.
--
-- The values specified in a 'SampleLocationEXT' structure are always
-- clamped to the implementation-dependent sample location coordinate range
-- [@sampleLocationCoordinateRange@[0],@sampleLocationCoordinateRange@[1]]
-- that /can/ be queried using
-- 'PhysicalDeviceSampleLocationsPropertiesEXT'.
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>,
-- 'SampleLocationsInfoEXT'
data SampleLocationEXT = SampleLocationEXT
{ -- | @x@ is the horizontal coordinate of the sample’s location.
x :: Float
, -- | @y@ is the vertical coordinate of the sample’s location.
y :: Float
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (SampleLocationEXT)
#endif
deriving instance Show SampleLocationEXT
instance ToCStruct SampleLocationEXT where
withCStruct x f = allocaBytes 8 $ \p -> pokeCStruct p x (f p)
pokeCStruct p SampleLocationEXT{..} 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 SampleLocationEXT where
peekCStruct p = do
x <- peek @CFloat ((p `plusPtr` 0 :: Ptr CFloat))
y <- peek @CFloat ((p `plusPtr` 4 :: Ptr CFloat))
pure $ SampleLocationEXT
(coerce @CFloat @Float x) (coerce @CFloat @Float y)
instance Storable SampleLocationEXT where
sizeOf ~_ = 8
alignment ~_ = 4
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero SampleLocationEXT where
zero = SampleLocationEXT
zero
zero
-- | VkSampleLocationsInfoEXT - Structure specifying a set of sample
-- locations
--
-- = Description
--
-- This structure /can/ be used either to specify the sample locations to
-- be used for rendering or to specify the set of sample locations an image
-- subresource has been last rendered with for the purposes of layout
-- transitions of depth\/stencil images created with
-- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT'.
--
-- The sample locations in @pSampleLocations@ specify
-- @sampleLocationsPerPixel@ number of sample locations for each pixel in
-- the grid of the size specified in @sampleLocationGridSize@. The sample
-- location for sample i at the pixel grid location (x,y) is taken from
-- @pSampleLocations@[(x + y × @sampleLocationGridSize.width@) ×
-- @sampleLocationsPerPixel@ + i].
--
-- If the render pass has a fragment density map, the implementation will
-- choose the sample locations for the fragment and the contents of
-- @pSampleLocations@ /may/ be ignored.
--
-- == Valid Usage
--
-- - #VUID-VkSampleLocationsInfoEXT-sampleLocationsPerPixel-01526#
-- @sampleLocationsPerPixel@ /must/ be a bit value that is set in
-- 'PhysicalDeviceSampleLocationsPropertiesEXT'::@sampleLocationSampleCounts@
--
-- - #VUID-VkSampleLocationsInfoEXT-sampleLocationsCount-01527#
-- @sampleLocationsCount@ /must/ equal @sampleLocationsPerPixel@ ×
-- @sampleLocationGridSize.width@ × @sampleLocationGridSize.height@
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkSampleLocationsInfoEXT-sType-sType# @sType@ /must/ be
-- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT'
--
-- - #VUID-VkSampleLocationsInfoEXT-pSampleLocations-parameter# If
-- @sampleLocationsCount@ is not @0@, @pSampleLocations@ /must/ be a
-- valid pointer to an array of @sampleLocationsCount@
-- 'SampleLocationEXT' structures
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>,
-- 'AttachmentSampleLocationsEXT',
-- 'Vulkan.Core10.FundamentalTypes.Extent2D',
-- 'PipelineSampleLocationsStateCreateInfoEXT',
-- 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlagBits',
-- 'SampleLocationEXT', 'Vulkan.Core10.Enums.StructureType.StructureType',
-- 'SubpassSampleLocationsEXT', 'cmdSetSampleLocationsEXT'
data SampleLocationsInfoEXT = SampleLocationsInfoEXT
{ -- | @sampleLocationsPerPixel@ is a
-- 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlagBits' value
-- specifying the number of sample locations per pixel.
sampleLocationsPerPixel :: SampleCountFlagBits
, -- | @sampleLocationGridSize@ is the size of the sample location grid to
-- select custom sample locations for.
sampleLocationGridSize :: Extent2D
, -- | @pSampleLocations@ is a pointer to an array of @sampleLocationsCount@
-- 'SampleLocationEXT' structures.
sampleLocations :: Vector SampleLocationEXT
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (SampleLocationsInfoEXT)
#endif
deriving instance Show SampleLocationsInfoEXT
instance ToCStruct SampleLocationsInfoEXT where
withCStruct x f = allocaBytes 40 $ \p -> pokeCStruct p x (f p)
pokeCStruct p SampleLocationsInfoEXT{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
lift $ poke ((p `plusPtr` 16 :: Ptr SampleCountFlagBits)) (sampleLocationsPerPixel)
lift $ poke ((p `plusPtr` 20 :: Ptr Extent2D)) (sampleLocationGridSize)
lift $ poke ((p `plusPtr` 28 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (sampleLocations)) :: Word32))
pPSampleLocations' <- ContT $ allocaBytes @SampleLocationEXT ((Data.Vector.length (sampleLocations)) * 8)
lift $ Data.Vector.imapM_ (\i e -> poke (pPSampleLocations' `plusPtr` (8 * (i)) :: Ptr SampleLocationEXT) (e)) (sampleLocations)
lift $ poke ((p `plusPtr` 32 :: Ptr (Ptr SampleLocationEXT))) (pPSampleLocations')
lift $ f
cStructSize = 40
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr SampleCountFlagBits)) (zero)
poke ((p `plusPtr` 20 :: Ptr Extent2D)) (zero)
f
instance FromCStruct SampleLocationsInfoEXT where
peekCStruct p = do
sampleLocationsPerPixel <- peek @SampleCountFlagBits ((p `plusPtr` 16 :: Ptr SampleCountFlagBits))
sampleLocationGridSize <- peekCStruct @Extent2D ((p `plusPtr` 20 :: Ptr Extent2D))
sampleLocationsCount <- peek @Word32 ((p `plusPtr` 28 :: Ptr Word32))
pSampleLocations <- peek @(Ptr SampleLocationEXT) ((p `plusPtr` 32 :: Ptr (Ptr SampleLocationEXT)))
pSampleLocations' <- generateM (fromIntegral sampleLocationsCount) (\i -> peekCStruct @SampleLocationEXT ((pSampleLocations `advancePtrBytes` (8 * (i)) :: Ptr SampleLocationEXT)))
pure $ SampleLocationsInfoEXT
sampleLocationsPerPixel sampleLocationGridSize pSampleLocations'
instance Zero SampleLocationsInfoEXT where
zero = SampleLocationsInfoEXT
zero
zero
mempty
-- | VkAttachmentSampleLocationsEXT - Structure specifying the sample
-- locations state to use in the initial layout transition of attachments
--
-- = Description
--
-- If the image referenced by the framebuffer attachment at index
-- @attachmentIndex@ was not created with
-- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT'
-- then the values specified in @sampleLocationsInfo@ are ignored.
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>,
-- 'RenderPassSampleLocationsBeginInfoEXT', 'SampleLocationsInfoEXT'
data AttachmentSampleLocationsEXT = AttachmentSampleLocationsEXT
{ -- | @attachmentIndex@ is the index of the attachment for which the sample
-- locations state is provided.
--
-- #VUID-VkAttachmentSampleLocationsEXT-attachmentIndex-01531#
-- @attachmentIndex@ /must/ be less than the @attachmentCount@ specified in
-- 'Vulkan.Core10.Pass.RenderPassCreateInfo' the render pass specified by
-- 'Vulkan.Core10.CommandBufferBuilding.RenderPassBeginInfo'::@renderPass@
-- was created with
attachmentIndex :: Word32
, -- | @sampleLocationsInfo@ is the sample locations state to use for the
-- layout transition of the given attachment from the initial layout of the
-- attachment to the image layout specified for the attachment in the first
-- subpass using it.
--
-- #VUID-VkAttachmentSampleLocationsEXT-sampleLocationsInfo-parameter#
-- @sampleLocationsInfo@ /must/ be a valid 'SampleLocationsInfoEXT'
-- structure
sampleLocationsInfo :: SampleLocationsInfoEXT
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (AttachmentSampleLocationsEXT)
#endif
deriving instance Show AttachmentSampleLocationsEXT
instance ToCStruct AttachmentSampleLocationsEXT where
withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p)
pokeCStruct p AttachmentSampleLocationsEXT{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr Word32)) (attachmentIndex)
ContT $ pokeCStruct ((p `plusPtr` 8 :: Ptr SampleLocationsInfoEXT)) (sampleLocationsInfo) . ($ ())
lift $ f
cStructSize = 48
cStructAlignment = 8
pokeZeroCStruct p f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr Word32)) (zero)
ContT $ pokeCStruct ((p `plusPtr` 8 :: Ptr SampleLocationsInfoEXT)) (zero) . ($ ())
lift $ f
instance FromCStruct AttachmentSampleLocationsEXT where
peekCStruct p = do
attachmentIndex <- peek @Word32 ((p `plusPtr` 0 :: Ptr Word32))
sampleLocationsInfo <- peekCStruct @SampleLocationsInfoEXT ((p `plusPtr` 8 :: Ptr SampleLocationsInfoEXT))
pure $ AttachmentSampleLocationsEXT
attachmentIndex sampleLocationsInfo
instance Zero AttachmentSampleLocationsEXT where
zero = AttachmentSampleLocationsEXT
zero
zero
-- | VkSubpassSampleLocationsEXT - Structure specifying the sample locations
-- state to use for layout transitions of attachments performed after a
-- given subpass
--
-- = Description
--
-- If the image referenced by the depth\/stencil attachment used in the
-- subpass identified by @subpassIndex@ was not created with
-- 'Vulkan.Core10.Enums.ImageCreateFlagBits.IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT'
-- or if the subpass does not use a depth\/stencil attachment, and
-- 'PhysicalDeviceSampleLocationsPropertiesEXT'::@variableSampleLocations@
-- is 'Vulkan.Core10.FundamentalTypes.TRUE' then the values specified in
-- @sampleLocationsInfo@ are ignored.
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>,
-- 'RenderPassSampleLocationsBeginInfoEXT', 'SampleLocationsInfoEXT'
data SubpassSampleLocationsEXT = SubpassSampleLocationsEXT
{ -- | @subpassIndex@ is the index of the subpass for which the sample
-- locations state is provided.
--
-- #VUID-VkSubpassSampleLocationsEXT-subpassIndex-01532# @subpassIndex@
-- /must/ be less than the @subpassCount@ specified in
-- 'Vulkan.Core10.Pass.RenderPassCreateInfo' the render pass specified by
-- 'Vulkan.Core10.CommandBufferBuilding.RenderPassBeginInfo'::@renderPass@
-- was created with
subpassIndex :: Word32
, -- | @sampleLocationsInfo@ is the sample locations state to use for the
-- layout transition of the depth\/stencil attachment away from the image
-- layout the attachment is used with in the subpass specified in
-- @subpassIndex@.
--
-- #VUID-VkSubpassSampleLocationsEXT-sampleLocationsInfo-parameter#
-- @sampleLocationsInfo@ /must/ be a valid 'SampleLocationsInfoEXT'
-- structure
sampleLocationsInfo :: SampleLocationsInfoEXT
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (SubpassSampleLocationsEXT)
#endif
deriving instance Show SubpassSampleLocationsEXT
instance ToCStruct SubpassSampleLocationsEXT where
withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p)
pokeCStruct p SubpassSampleLocationsEXT{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr Word32)) (subpassIndex)
ContT $ pokeCStruct ((p `plusPtr` 8 :: Ptr SampleLocationsInfoEXT)) (sampleLocationsInfo) . ($ ())
lift $ f
cStructSize = 48
cStructAlignment = 8
pokeZeroCStruct p f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr Word32)) (zero)
ContT $ pokeCStruct ((p `plusPtr` 8 :: Ptr SampleLocationsInfoEXT)) (zero) . ($ ())
lift $ f
instance FromCStruct SubpassSampleLocationsEXT where
peekCStruct p = do
subpassIndex <- peek @Word32 ((p `plusPtr` 0 :: Ptr Word32))
sampleLocationsInfo <- peekCStruct @SampleLocationsInfoEXT ((p `plusPtr` 8 :: Ptr SampleLocationsInfoEXT))
pure $ SubpassSampleLocationsEXT
subpassIndex sampleLocationsInfo
instance Zero SubpassSampleLocationsEXT where
zero = SubpassSampleLocationsEXT
zero
zero
-- | VkRenderPassSampleLocationsBeginInfoEXT - Structure specifying sample
-- locations to use for the layout transition of custom sample locations
-- compatible depth\/stencil attachments
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkRenderPassSampleLocationsBeginInfoEXT-sType-sType# @sType@
-- /must/ be
-- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_RENDER_PASS_SAMPLE_LOCATIONS_BEGIN_INFO_EXT'
--
-- - #VUID-VkRenderPassSampleLocationsBeginInfoEXT-pAttachmentInitialSampleLocations-parameter#
-- If @attachmentInitialSampleLocationsCount@ is not @0@,
-- @pAttachmentInitialSampleLocations@ /must/ be a valid pointer to an
-- array of @attachmentInitialSampleLocationsCount@ valid
-- 'AttachmentSampleLocationsEXT' structures
--
-- - #VUID-VkRenderPassSampleLocationsBeginInfoEXT-pPostSubpassSampleLocations-parameter#
-- If @postSubpassSampleLocationsCount@ is not @0@,
-- @pPostSubpassSampleLocations@ /must/ be a valid pointer to an array
-- of @postSubpassSampleLocationsCount@ valid
-- 'SubpassSampleLocationsEXT' structures
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>,
-- 'AttachmentSampleLocationsEXT',
-- 'Vulkan.Core10.Enums.StructureType.StructureType',
-- 'SubpassSampleLocationsEXT'
data RenderPassSampleLocationsBeginInfoEXT = RenderPassSampleLocationsBeginInfoEXT
{ -- | @pAttachmentInitialSampleLocations@ is a pointer to an array of
-- @attachmentInitialSampleLocationsCount@ 'AttachmentSampleLocationsEXT'
-- structures specifying the attachment indices and their corresponding
-- sample location state. Each element of
-- @pAttachmentInitialSampleLocations@ /can/ specify the sample location
-- state to use in the automatic layout transition performed to transition
-- a depth\/stencil attachment from the initial layout of the attachment to
-- the image layout specified for the attachment in the first subpass using
-- it.
attachmentInitialSampleLocations :: Vector AttachmentSampleLocationsEXT
, -- | @pPostSubpassSampleLocations@ is a pointer to an array of
-- @postSubpassSampleLocationsCount@ 'SubpassSampleLocationsEXT' structures
-- specifying the subpass indices and their corresponding sample location
-- state. Each element of @pPostSubpassSampleLocations@ /can/ specify the
-- sample location state to use in the automatic layout transition
-- performed to transition the depth\/stencil attachment used by the
-- specified subpass to the image layout specified in a dependent subpass
-- or to the final layout of the attachment in case the specified subpass
-- is the last subpass using that attachment. In addition, if
-- 'PhysicalDeviceSampleLocationsPropertiesEXT'::@variableSampleLocations@
-- is 'Vulkan.Core10.FundamentalTypes.FALSE', each element of
-- @pPostSubpassSampleLocations@ /must/ specify the sample location state
-- that matches the sample locations used by all pipelines that will be
-- bound to a command buffer during the specified subpass. If
-- @variableSampleLocations@ is 'Vulkan.Core10.FundamentalTypes.TRUE', the
-- sample locations used for rasterization do not depend on
-- @pPostSubpassSampleLocations@.
postSubpassSampleLocations :: Vector SubpassSampleLocationsEXT
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (RenderPassSampleLocationsBeginInfoEXT)
#endif
deriving instance Show RenderPassSampleLocationsBeginInfoEXT
instance ToCStruct RenderPassSampleLocationsBeginInfoEXT where
withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p)
pokeCStruct p RenderPassSampleLocationsBeginInfoEXT{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RENDER_PASS_SAMPLE_LOCATIONS_BEGIN_INFO_EXT)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
lift $ poke ((p `plusPtr` 16 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (attachmentInitialSampleLocations)) :: Word32))
pPAttachmentInitialSampleLocations' <- ContT $ allocaBytes @AttachmentSampleLocationsEXT ((Data.Vector.length (attachmentInitialSampleLocations)) * 48)
Data.Vector.imapM_ (\i e -> ContT $ pokeCStruct (pPAttachmentInitialSampleLocations' `plusPtr` (48 * (i)) :: Ptr AttachmentSampleLocationsEXT) (e) . ($ ())) (attachmentInitialSampleLocations)
lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr AttachmentSampleLocationsEXT))) (pPAttachmentInitialSampleLocations')
lift $ poke ((p `plusPtr` 32 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (postSubpassSampleLocations)) :: Word32))
pPPostSubpassSampleLocations' <- ContT $ allocaBytes @SubpassSampleLocationsEXT ((Data.Vector.length (postSubpassSampleLocations)) * 48)
Data.Vector.imapM_ (\i e -> ContT $ pokeCStruct (pPPostSubpassSampleLocations' `plusPtr` (48 * (i)) :: Ptr SubpassSampleLocationsEXT) (e) . ($ ())) (postSubpassSampleLocations)
lift $ poke ((p `plusPtr` 40 :: Ptr (Ptr SubpassSampleLocationsEXT))) (pPPostSubpassSampleLocations')
lift $ f
cStructSize = 48
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RENDER_PASS_SAMPLE_LOCATIONS_BEGIN_INFO_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
f
instance FromCStruct RenderPassSampleLocationsBeginInfoEXT where
peekCStruct p = do
attachmentInitialSampleLocationsCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32))
pAttachmentInitialSampleLocations <- peek @(Ptr AttachmentSampleLocationsEXT) ((p `plusPtr` 24 :: Ptr (Ptr AttachmentSampleLocationsEXT)))
pAttachmentInitialSampleLocations' <- generateM (fromIntegral attachmentInitialSampleLocationsCount) (\i -> peekCStruct @AttachmentSampleLocationsEXT ((pAttachmentInitialSampleLocations `advancePtrBytes` (48 * (i)) :: Ptr AttachmentSampleLocationsEXT)))
postSubpassSampleLocationsCount <- peek @Word32 ((p `plusPtr` 32 :: Ptr Word32))
pPostSubpassSampleLocations <- peek @(Ptr SubpassSampleLocationsEXT) ((p `plusPtr` 40 :: Ptr (Ptr SubpassSampleLocationsEXT)))
pPostSubpassSampleLocations' <- generateM (fromIntegral postSubpassSampleLocationsCount) (\i -> peekCStruct @SubpassSampleLocationsEXT ((pPostSubpassSampleLocations `advancePtrBytes` (48 * (i)) :: Ptr SubpassSampleLocationsEXT)))
pure $ RenderPassSampleLocationsBeginInfoEXT
pAttachmentInitialSampleLocations' pPostSubpassSampleLocations'
instance Zero RenderPassSampleLocationsBeginInfoEXT where
zero = RenderPassSampleLocationsBeginInfoEXT
mempty
mempty
-- | VkPipelineSampleLocationsStateCreateInfoEXT - Structure specifying
-- sample locations for a pipeline
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>,
-- 'Vulkan.Core10.FundamentalTypes.Bool32', 'SampleLocationsInfoEXT',
-- 'Vulkan.Core10.Enums.StructureType.StructureType'
data PipelineSampleLocationsStateCreateInfoEXT = PipelineSampleLocationsStateCreateInfoEXT
{ -- | @sampleLocationsEnable@ controls whether custom sample locations are
-- used. If @sampleLocationsEnable@ is
-- 'Vulkan.Core10.FundamentalTypes.FALSE', the default sample locations are
-- used and the values specified in @sampleLocationsInfo@ are ignored.
sampleLocationsEnable :: Bool
, -- | @sampleLocationsInfo@ is the sample locations to use during
-- rasterization if @sampleLocationsEnable@ is
-- 'Vulkan.Core10.FundamentalTypes.TRUE' and the graphics pipeline is not
-- created with
-- 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT'.
--
-- #VUID-VkPipelineSampleLocationsStateCreateInfoEXT-sampleLocationsInfo-parameter#
-- @sampleLocationsInfo@ /must/ be a valid 'SampleLocationsInfoEXT'
-- structure
sampleLocationsInfo :: SampleLocationsInfoEXT
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PipelineSampleLocationsStateCreateInfoEXT)
#endif
deriving instance Show PipelineSampleLocationsStateCreateInfoEXT
instance ToCStruct PipelineSampleLocationsStateCreateInfoEXT where
withCStruct x f = allocaBytes 64 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PipelineSampleLocationsStateCreateInfoEXT{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_SAMPLE_LOCATIONS_STATE_CREATE_INFO_EXT)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
lift $ poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (sampleLocationsEnable))
ContT $ pokeCStruct ((p `plusPtr` 24 :: Ptr SampleLocationsInfoEXT)) (sampleLocationsInfo) . ($ ())
lift $ f
cStructSize = 64
cStructAlignment = 8
pokeZeroCStruct p f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_SAMPLE_LOCATIONS_STATE_CREATE_INFO_EXT)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
lift $ poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero))
ContT $ pokeCStruct ((p `plusPtr` 24 :: Ptr SampleLocationsInfoEXT)) (zero) . ($ ())
lift $ f
instance FromCStruct PipelineSampleLocationsStateCreateInfoEXT where
peekCStruct p = do
sampleLocationsEnable <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32))
sampleLocationsInfo <- peekCStruct @SampleLocationsInfoEXT ((p `plusPtr` 24 :: Ptr SampleLocationsInfoEXT))
pure $ PipelineSampleLocationsStateCreateInfoEXT
(bool32ToBool sampleLocationsEnable) sampleLocationsInfo
instance Zero PipelineSampleLocationsStateCreateInfoEXT where
zero = PipelineSampleLocationsStateCreateInfoEXT
zero
zero
-- | VkPhysicalDeviceSampleLocationsPropertiesEXT - Structure describing
-- sample location limits that can be supported by an implementation
--
-- = Description
--
-- If the 'PhysicalDeviceSampleLocationsPropertiesEXT' structure is
-- included in the @pNext@ chain of the
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceProperties2'
-- structure passed to
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceProperties2',
-- it is filled in with each corresponding implementation-dependent
-- property.
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>,
-- 'Vulkan.Core10.FundamentalTypes.Bool32',
-- 'Vulkan.Core10.FundamentalTypes.Extent2D',
-- 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlags',
-- 'Vulkan.Core10.Enums.StructureType.StructureType'
data PhysicalDeviceSampleLocationsPropertiesEXT = PhysicalDeviceSampleLocationsPropertiesEXT
{ -- | #limits-sampleLocationSampleCounts# @sampleLocationSampleCounts@ is a
-- bitmask of 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlagBits'
-- indicating the sample counts supporting custom sample locations.
sampleLocationSampleCounts :: SampleCountFlags
, -- | #limits-maxSampleLocationGridSize# @maxSampleLocationGridSize@ is the
-- maximum size of the pixel grid in which sample locations /can/ vary that
-- is supported for all sample counts in @sampleLocationSampleCounts@.
maxSampleLocationGridSize :: Extent2D
, -- | #limits-sampleLocationCoordinateRange#
-- @sampleLocationCoordinateRange@[2] is the range of supported sample
-- location coordinates.
sampleLocationCoordinateRange :: (Float, Float)
, -- | #limits-sampleLocationSubPixelBits# @sampleLocationSubPixelBits@ is the
-- number of bits of subpixel precision for sample locations.
sampleLocationSubPixelBits :: Word32
, -- | #limits-variableSampleLocations# @variableSampleLocations@ specifies
-- whether the sample locations used by all pipelines that will be bound to
-- a command buffer during a subpass /must/ match. If set to
-- 'Vulkan.Core10.FundamentalTypes.TRUE', the implementation supports
-- variable sample locations in a subpass. If set to
-- 'Vulkan.Core10.FundamentalTypes.FALSE', then the sample locations /must/
-- stay constant in each subpass.
variableSampleLocations :: Bool
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PhysicalDeviceSampleLocationsPropertiesEXT)
#endif
deriving instance Show PhysicalDeviceSampleLocationsPropertiesEXT
instance ToCStruct PhysicalDeviceSampleLocationsPropertiesEXT where
withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PhysicalDeviceSampleLocationsPropertiesEXT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLE_LOCATIONS_PROPERTIES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr SampleCountFlags)) (sampleLocationSampleCounts)
poke ((p `plusPtr` 20 :: Ptr Extent2D)) (maxSampleLocationGridSize)
let pSampleLocationCoordinateRange' = lowerArrayPtr ((p `plusPtr` 28 :: Ptr (FixedArray 2 CFloat)))
case (sampleLocationCoordinateRange) of
(e0, e1) -> do
poke (pSampleLocationCoordinateRange' :: Ptr CFloat) (CFloat (e0))
poke (pSampleLocationCoordinateRange' `plusPtr` 4 :: Ptr CFloat) (CFloat (e1))
poke ((p `plusPtr` 36 :: Ptr Word32)) (sampleLocationSubPixelBits)
poke ((p `plusPtr` 40 :: Ptr Bool32)) (boolToBool32 (variableSampleLocations))
f
cStructSize = 48
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLE_LOCATIONS_PROPERTIES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr SampleCountFlags)) (zero)
poke ((p `plusPtr` 20 :: Ptr Extent2D)) (zero)
let pSampleLocationCoordinateRange' = lowerArrayPtr ((p `plusPtr` 28 :: Ptr (FixedArray 2 CFloat)))
case ((zero, zero)) of
(e0, e1) -> do
poke (pSampleLocationCoordinateRange' :: Ptr CFloat) (CFloat (e0))
poke (pSampleLocationCoordinateRange' `plusPtr` 4 :: Ptr CFloat) (CFloat (e1))
poke ((p `plusPtr` 36 :: Ptr Word32)) (zero)
poke ((p `plusPtr` 40 :: Ptr Bool32)) (boolToBool32 (zero))
f
instance FromCStruct PhysicalDeviceSampleLocationsPropertiesEXT where
peekCStruct p = do
sampleLocationSampleCounts <- peek @SampleCountFlags ((p `plusPtr` 16 :: Ptr SampleCountFlags))
maxSampleLocationGridSize <- peekCStruct @Extent2D ((p `plusPtr` 20 :: Ptr Extent2D))
let psampleLocationCoordinateRange = lowerArrayPtr @CFloat ((p `plusPtr` 28 :: Ptr (FixedArray 2 CFloat)))
sampleLocationCoordinateRange0 <- peek @CFloat ((psampleLocationCoordinateRange `advancePtrBytes` 0 :: Ptr CFloat))
sampleLocationCoordinateRange1 <- peek @CFloat ((psampleLocationCoordinateRange `advancePtrBytes` 4 :: Ptr CFloat))
sampleLocationSubPixelBits <- peek @Word32 ((p `plusPtr` 36 :: Ptr Word32))
variableSampleLocations <- peek @Bool32 ((p `plusPtr` 40 :: Ptr Bool32))
pure $ PhysicalDeviceSampleLocationsPropertiesEXT
sampleLocationSampleCounts maxSampleLocationGridSize (((coerce @CFloat @Float sampleLocationCoordinateRange0), (coerce @CFloat @Float sampleLocationCoordinateRange1))) sampleLocationSubPixelBits (bool32ToBool variableSampleLocations)
instance Storable PhysicalDeviceSampleLocationsPropertiesEXT where
sizeOf ~_ = 48
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PhysicalDeviceSampleLocationsPropertiesEXT where
zero = PhysicalDeviceSampleLocationsPropertiesEXT
zero
zero
(zero, zero)
zero
zero
-- | VkMultisamplePropertiesEXT - Structure returning information about
-- sample count specific additional multisampling capabilities
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_sample_locations VK_EXT_sample_locations>,
-- 'Vulkan.Core10.FundamentalTypes.Extent2D',
-- 'Vulkan.Core10.Enums.StructureType.StructureType',
-- 'getPhysicalDeviceMultisamplePropertiesEXT'
data MultisamplePropertiesEXT = MultisamplePropertiesEXT
{ -- | @maxSampleLocationGridSize@ is the maximum size of the pixel grid in
-- which sample locations /can/ vary.
maxSampleLocationGridSize :: Extent2D }
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (MultisamplePropertiesEXT)
#endif
deriving instance Show MultisamplePropertiesEXT
instance ToCStruct MultisamplePropertiesEXT where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p MultisamplePropertiesEXT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_MULTISAMPLE_PROPERTIES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Extent2D)) (maxSampleLocationGridSize)
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_MULTISAMPLE_PROPERTIES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Extent2D)) (zero)
f
instance FromCStruct MultisamplePropertiesEXT where
peekCStruct p = do
maxSampleLocationGridSize <- peekCStruct @Extent2D ((p `plusPtr` 16 :: Ptr Extent2D))
pure $ MultisamplePropertiesEXT
maxSampleLocationGridSize
instance Storable MultisamplePropertiesEXT where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero MultisamplePropertiesEXT where
zero = MultisamplePropertiesEXT
zero
type EXT_SAMPLE_LOCATIONS_SPEC_VERSION = 1
-- No documentation found for TopLevel "VK_EXT_SAMPLE_LOCATIONS_SPEC_VERSION"
pattern EXT_SAMPLE_LOCATIONS_SPEC_VERSION :: forall a . Integral a => a
pattern EXT_SAMPLE_LOCATIONS_SPEC_VERSION = 1
type EXT_SAMPLE_LOCATIONS_EXTENSION_NAME = "VK_EXT_sample_locations"
-- No documentation found for TopLevel "VK_EXT_SAMPLE_LOCATIONS_EXTENSION_NAME"
pattern EXT_SAMPLE_LOCATIONS_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern EXT_SAMPLE_LOCATIONS_EXTENSION_NAME = "VK_EXT_sample_locations"
| expipiplus1/vulkan | src/Vulkan/Extensions/VK_EXT_sample_locations.hs | bsd-3-clause | 52,025 | 0 | 19 | 9,141 | 7,432 | 4,294 | 3,138 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
module Main where
import Lib
import Resources
import Authentication
import Control.Applicative (Applicative)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Logger (runNoLoggingT, runStdoutLoggingT)
import Control.Monad.Reader (MonadReader, ReaderT, asks, runReaderT)
import Control.Monad.Trans.Class (MonadTrans, lift)
import Data.Aeson (Value (Null), (.=), object)
import Data.Default (def)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import Data.Text.Lazy (Text, unpack)
import qualified Database.Persist as DB
import qualified Database.Persist.Postgresql as DB
import Network.Wai
import Network.Wai.Handler.Warp (Settings, defaultSettings, setFdCacheDuration, setPort)
import Network.Wai.Middleware.RequestLogger (logStdout, logStdoutDev)
import System.Environment (lookupEnv)
import System.Directory (createDirectory)
import Web.Heroku (parseDatabaseUrl)
import Web.Scotty.Trans
import Codec.MIME.Base64 (decodeToString)
import Network.Wai.Middleware.Cors (simpleCors)
import Data.CaseInsensitive (CI)
import Data.ByteString as B
import Web.ClientSession
main :: IO ()
main = do
c <- getConfig
migrateSchema c
runApplication c
migrateSchema :: Config -> IO ()
migrateSchema c =
liftIO $ flip DB.runSqlPersistMPool (pool c) $ DB.runMigration migrateAll
getConfig :: IO Config
getConfig = do
e <- getEnvironment
p <- getPool e
key <- getDefaultKey
return Config
{ environment = e
, pool = p
, key = key
}
getEnvironment :: IO Environment
getEnvironment =
fmap (maybe Development read) (lookupEnv "SCOTTY_ENV")
getPool :: Environment -> IO DB.ConnectionPool
getPool e = do
s <- getConnectionString e
let n = getConnectionSize e
case e of
Development -> runStdoutLoggingT
(DB.createPostgresqlPool s n)
Production -> runStdoutLoggingT
(DB.createPostgresqlPool s n)
Test -> runNoLoggingT
(DB.createPostgresqlPool s n)
getConnectionString :: Environment -> IO DB.ConnectionString
getConnectionString e = do
m <- lookupEnv "DATABASE_URL"
let s = case m of
Nothing -> getDefaultConnectionString e
Just u -> createConnectionString (parseDatabaseUrl u)
return s
getDefaultConnectionString :: Environment -> DB.ConnectionString
getDefaultConnectionString e =
let n = case e of
Development -> "lift_development"
Production -> "lift_production"
Test -> "lift_test"
in createConnectionString
[ ("host", "localhost")
, ("port", "5432")
, ("user", "postgres")
, ("dbname", n)
]
createConnectionString :: [(T.Text, T.Text)] -> DB.ConnectionString
createConnectionString l =
let f (k, v) = T.concat [k, "=", v]
in encodeUtf8 (T.unwords (Prelude.map f l))
getConnectionSize :: Environment -> Int
getConnectionSize Development = 1
getConnectionSize Production = 8
getConnectionSize Test = 1
runApplication :: Config -> IO ()
runApplication c = do
o <- getOptions (environment c)
let r m = runReaderT (runConfigM m) c
app = application c
scottyOptsT o r app
getOptions :: Environment -> IO Options
getOptions e = do
s <- getSettings e
return def
{ settings = s
, verbose = case e of
Development -> 1
Production -> 0
Test -> 0
}
getSettings :: Environment -> IO Settings
getSettings e = do
let s = defaultSettings
s' = case e of
Development -> setFdCacheDuration 0 s
Production -> s
Test -> s
m <- getPort
let s'' = case m of
Nothing -> s'
Just p -> setPort p s'
return s''
getPort :: IO (Maybe Int)
getPort = (fmap . fmap) read (lookupEnv "SCOTTY_PORT")
application :: Config -> ScottyT Error ConfigM ()
application c = do
let e = environment c
middleware (loggingM e)
let headerName = "Access-Control-Allow-Headers"
middleware $ modifyResponse $ mapResponseHeaders (\headers -> headers ++ [(headerName, "Content-Type, authorization"), ("Access-Control-Allow-Methods", "GET, POST, OPTIONS"), ("Access-Control-Allow-Origin", "*")])
defaultHandler (defaultH e)
get "/" home
post "/signin" $ authenticate >>= signinA
get "/logout" logoutA
get "/lifts" $ authenticate >>= getLiftsA
post "/lifts" $ authenticate >>= postLiftsA
post "/users" postUsersA
options "/users" optionsA
options (regex "/lifts") optionsA
notFound notFoundA
loggingM :: Environment -> Middleware
loggingM Development = logStdoutDev
loggingM Production = logStdout
loggingM Test = id
toKey :: DB.ToBackendKey DB.SqlBackend a =>
Integer -> DB.Key a
toKey i = DB.toSqlKey (fromIntegral (i :: Integer))
| clample/lift-tracker | app/Main.hs | bsd-3-clause | 4,681 | 0 | 15 | 894 | 1,465 | 763 | 702 | 139 | 4 |
{-# LANGUAGE TypeOperators, ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, TypeSynonymInstances #-}
{-# LANGUAGE UndecidableInstances, OverlappingInstances #-}
{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
{-# LANGUAGE CPP #-}
module Narradar.Types.DPIdentifiers
(module Narradar.Types.DPIdentifiers, ArityId(..), StringId
) where
import Control.Applicative
import Control.Arrow (first)
import Control.DeepSeq
import Data.Foldable (Foldable(..))
import Data.Hashable
import Data.Traversable (Traversable(..))
import Data.Typeable
import Prelude
import Narradar.Types.Term
import Narradar.Framework.Ppr
#ifdef HOOD
import Debug.Hood.Observe
#endif
type Id = DPIdentifier StringId
type DP a = RuleN (DPIdentifier a)
-- -----------------------
-- Concrete DP Identifiers
-- -----------------------
data DPIdentifier a = IdFunction a | IdDP a | AnyIdentifier
deriving (Ord, Typeable, Functor, Foldable, Traversable)
instance Eq a => Eq (DPIdentifier a) where
IdFunction f1 == IdFunction f2 = f1 == f2
IdDP f1 == IdDP f2 = f1 == f2
AnyIdentifier == _ = True
_ == AnyIdentifier = True
_ == _ = False
instance HasArity a => HasArity (DPIdentifier a) where
getIdArity (IdFunction f) = getIdArity f
getIdArity (IdDP f) = getIdArity f
getIdArity AnyIdentifier = 0
instance Pretty (DPIdentifier a) => Show (DPIdentifier a) where show = show . pPrint
instance Pretty (DPIdentifier String) where
pPrint (IdFunction f) = text f
pPrint (IdDP n) = text n <> text "#"
instance Pretty a => Pretty (DPIdentifier a) where
pPrint (IdFunction f) = pPrint f
pPrint (IdDP n) = pPrint n <> text "#"
instance NFData a => NFData (DPIdentifier a) where
rnf (IdFunction f) = rnf f
rnf (IdDP f) = rnf f
rnf AnyIdentifier = ()
instance Hashable a => Hashable (DPIdentifier a) where
hash (IdFunction f) = hash f
hash (IdDP f) = combine 1 (hash f)
#ifdef HOOD
instance Observable id => Observable (DPIdentifier id) where
observer (IdFunction a) = send "IdFunction" (return IdFunction << a)
observer (IdDP a) = send "IdDP" (return IdDP << a)
#endif
-- ------------
-- DP Symbols
-- ------------
class DPSymbol s where
markDPSymbol, unmarkDPSymbol :: s -> s
isDPSymbol :: s -> Bool
instance DPSymbol (DPIdentifier id) where
markDPSymbol (IdFunction f) = IdDP f
markDPSymbol f = f
unmarkDPSymbol (IdDP n) = IdFunction n
unmarkDPSymbol n = n
isDPSymbol (IdDP _ ) = True
isDPSymbol _ = False
functionSymbol = IdFunction; dpSymbol = IdDP
symbol (IdFunction f) = f; symbol(IdDP f) = f
--markDP, unmarkDP :: (MapId t, Functor (t id), DPSymbol id) => Term (t id) v -> Term (t id) v
markDP = evalTerm return (Impure . mapId markDPSymbol)
unmarkDP = evalTerm return (Impure . mapId unmarkDPSymbol)
returnDP = foldTerm return (Impure . mapId IdFunction)
--unmarkDPRule, markDPRule :: Rule t v -> Rule t v
markDPRule = fmap markDP
unmarkDPRule = fmap unmarkDP
| pepeiborra/narradar | src/Narradar/Types/DPIdentifiers.hs | bsd-3-clause | 3,373 | 0 | 9 | 715 | 945 | 492 | 453 | 69 | 1 |
module Lambda.Evaluator.Debug where
import DeepControl.Applicative
import DeepControl.Monad
import DeepControl.MonadTrans
import Lambda.Evaluator.Eval
import Lambda.Compiler
import Lambda.Parser (readSExpr)
import Lambda.Action
import Lambda.Convertor
import Lambda.Debug
import Lambda.DataType
import Lambda.DataType.Error.Eval (EvalError)
import qualified Lambda.DataType.Error.Eval as EErr
import qualified Lambda.DataType.PatternMatch as PM
-- for debug
import Debug.Trace
----------------------------------------------------------------------
-- unittest
----------------------------------------------------------------------
evalUnitTest :: Term -> Lambda ReturnT
evalUnitTest name = (*:) $ RETURN $ META ("(evalUnitTest "++ show name ++")") $ f (show name)
where
f :: Name -> Term -> Lambda ReturnT
f name unit@(LIST g msp) = localMSPBy msp $ do
let xs = toList g
str <- rec (length xs, 0, 0, 0, "") $ xs <$| \(TPL (TUPLE [expr, answer]) msp) -> (expr, answer, msp)
liftIO $ putStrLn str
(*:) VOID
where
rec :: (Int, Int, Int, Int, String) -> [(Term, Term, MSP)] -> Lambda String
rec (cases, tried, 0, 0, "") [] = (*:) $
"unittest ["++ name ++"] - "++
"Cases: "++ show cases ++" "++
"Tried: "++ show tried ++" "++
"Errors: 0 "++
"Failures: 0"
rec (cases, tried, errors, failures, mes) [] = (*:) $
"////////////////////////////////////////////////////////////////////"++"\n"++
"/// - unittest ["++ name ++"]"++"\n"++
mes++
"/// - "++
"Cases: "++ show cases ++" "++
"Tried: "++ show tried ++" "++
"Errors: "++ show errors ++" "++
"Failures: "++ show failures ++"\n"++
"/// - unittest ["++ name ++"]"++"\n"++
"////////////////////////////////////////////////////////////////////"
rec (cases, tried, errors, failures, mes) ((term, answer, msp):xs) = localMSPBy msp $ catch $ do
expr <- restore term
v <- thisEval_ term
if show v /= show answer
then do
answer <- restore answer
v <- restore v
let str1 = "/// ### failured in: "++ name ++": at "++ showMSP msp ++"\n"
str2 = "/// tried: "++ show expr ++"\n"++
"/// expected: "++ show answer ++"\n"++
"/// but got: "++ show v ++"\n"
rec (cases, tried+1, errors, failures+1, mes ++ str1 ++ str2) xs
else do
rec (cases, tried+1, errors, failures, mes) xs
where
catch x = x `catchError` \e -> do
let str = "/// ### errored in: "++ name ++": at "++ showMSP msp ++"\n"
++ (show e >- lines
>- foldr (\line acc -> "/// "++ line ++"\n"++ acc) "") ++"/// \n"
rec (cases, tried+1, errors+1, failures, mes ++ str) xs
showMSP :: MSP -> String
showMSP Nothing = "---"
showMSP (Just sp) = show sp
---------------------------------------------------------------------------------------
-- show
---------------------------------------------------------------------------------------
evalShowSExpr :: Term -> Lambda ReturnT
evalShowSExpr t = do
case readSExpr (show t) of
Left err -> liftIO $ putStrLn $ "evalDesugar: "++ show err
Right (s, []) -> liftIO $ putStrLn $ show (convert s :: SExpr_)
Right (s, rest) -> liftIO $ putStrLn $ "evalDesugar: rest: "++ rest
(*:) VOID
evalShowExpr :: Term -> Lambda ReturnT
evalShowExpr t = do
case readSExpr (show t) of
Left err -> liftIO $ putStrLn $ "evalDesugar: "++ show err
Right (s, []) -> do
e <- s >- desugarSExpr
liftIO $ putStrLn $ show (convert e :: Expr_)
Right (s, rest) -> liftIO $ putStrLn $ "evalDesugar: rest: "++ rest
(*:) VOID
---------------------------------------------------------------------------------------
-- misc
---------------------------------------------------------------------------------------
evalShowContext :: Lambda ReturnT
evalShowContext = do
showContext "---"
(*:) VOID
evalShowDef :: Lambda ReturnT
evalShowDef = do
showDef "---"
(*:) VOID
evalShowDef_ :: Lambda ReturnT
evalShowDef_ = do
showDef_ "---"
(*:) VOID
| ocean0yohsuke/Simply-Typed-Lambda | src/Lambda/Evaluator/Debug.hs | bsd-3-clause | 4,535 | 0 | 33 | 1,338 | 1,362 | 709 | 653 | 91 | 5 |
{-# Language TemplateHaskell #-}
{-|
Module : Client.Image.MircFormatting
Description : Parser for mIRC's text formatting encoding
Copyright : (c) Eric Mertens, 2016
License : ISC
Maintainer : emertens@gmail.com
This module parses mIRC encoded text and generates VTY images.
-}
module Client.Image.MircFormatting
( parseIrcText
, parseIrcText'
, plainText
, controlImage
, mircColor
, mircColors
) where
import Client.Image.PackedImage as I
import Client.Image.Palette (Palette, palMonospace)
import Control.Applicative ((<|>), empty)
import Control.Lens
import Data.Attoparsec.Text as Parse
import Data.Bits
import Data.Char
import Data.Maybe
import Data.Text (Text)
import Graphics.Vty.Attributes
import Data.Vector (Vector)
import qualified Data.Vector as Vector
import Numeric (readHex)
makeLensesFor
[ ("attrForeColor", "foreColorLens")
, ("attrBackColor", "backColorLens")
, ("attrStyle" , "styleLens" )]
''Attr
-- | Parse mIRC encoded format characters and hide the control characters.
parseIrcText :: Palette -> Text -> Image'
parseIrcText = parseIrcText' False
-- | Parse mIRC encoded format characters and render the control characters
-- explicitly. This view is useful when inputting control characters to make
-- it clear where they are in the text.
parseIrcText' :: Bool -> Palette -> Text -> Image'
parseIrcText' explicit pal
= either plainText id
. parseOnly (pIrcLine pal explicit False defAttr)
data Segment = TextSegment Text | ControlSegment Char
pSegment :: Parser Segment
pSegment = TextSegment <$> takeWhile1 (not . isControl)
<|> ControlSegment <$> satisfy isControl
pIrcLine :: Palette -> Bool -> Bool -> Attr -> Parser Image'
pIrcLine pal explicit mono fmt =
do seg <- option Nothing (Just <$> pSegment)
case seg of
Nothing -> return mempty
Just (TextSegment txt) ->
do rest <- pIrcLine pal explicit mono fmt
return (text' fmt txt <> rest)
Just (ControlSegment '\^C') ->
do (numberText, colorNumbers) <- match (pColorNumbers pColorNumber)
rest <- pIrcLine pal explicit mono (applyColors colorNumbers fmt)
return $ if explicit
then controlImage '\^C'
<> text' defAttr numberText
<> rest
else rest
Just (ControlSegment '\^D') ->
do (numberText, colorNumbers) <- match (pColorNumbers pColorHex)
rest <- pIrcLine pal explicit mono (applyColors colorNumbers fmt)
return $ if explicit
then controlImage '\^D'
<> text' defAttr numberText
<> rest
else rest
Just (ControlSegment '\^Q')
| explicit -> (controlImage '\^Q' <>) <$> rest
| otherwise -> rest
where
rest = pIrcLine pal explicit (not mono)
(if mono then defAttr else view palMonospace pal)
Just (ControlSegment c)
-- always render control codes that we don't understand
| isNothing mbFmt' || explicit ->
do rest <- next
return (controlImage c <> rest)
| otherwise -> next
where
mbFmt' = applyControlEffect c fmt
next = pIrcLine pal explicit mono (fromMaybe fmt mbFmt')
pColorNumbers ::
Parser (MaybeDefault Color) ->
Parser (Maybe (MaybeDefault Color, Maybe (MaybeDefault Color)))
pColorNumbers color = option Nothing $
do fc <- color
bc <- optional (Parse.char ',' *> color)
return (Just (fc,bc))
pColorNumber :: Parser (MaybeDefault Color)
pColorNumber =
do d1 <- digit
ds <- option [] (return <$> digit)
case mircColor (read (d1:ds)) of
Just c -> pure c
Nothing -> empty
pColorHex :: Parser (MaybeDefault Color)
pColorHex = SetTo <$> (rgbColor' <$> p <*> p <*> p)
where
p = do x <- satisfy isHexDigit
y <- satisfy isHexDigit
pure (fst (head (readHex [x,y])))
optional :: Parser a -> Parser (Maybe a)
optional p = option Nothing (Just <$> p)
applyColors :: Maybe (MaybeDefault Color, Maybe (MaybeDefault Color)) -> Attr -> Attr
applyColors Nothing = set foreColorLens Default
. set backColorLens Default
applyColors (Just (c1, Nothing)) = set foreColorLens c1 -- preserve background
applyColors (Just (c1, Just c2)) = set foreColorLens c1
. set backColorLens c2
mircColor :: Int -> Maybe (MaybeDefault Color)
mircColor 99 = Just Default
mircColor i = SetTo <$> mircColors Vector.!? i
mircColors :: Vector Color
mircColors =
Vector.fromList $
[ white -- white
, black -- black
, blue -- blue
, green -- green
, red -- red
, rgbColor' 127 0 0 -- brown
, rgbColor' 156 0 156 -- purple
, rgbColor' 252 127 0 -- yellow
, yellow -- yellow
, brightGreen -- green
, cyan -- brightBlue
, brightCyan -- brightCyan
, brightBlue -- brightBlue
, rgbColor' 255 0 255 -- brightRed
, rgbColor' 127 127 127 -- brightBlack
, rgbColor' 210 210 210 -- brightWhite
] ++
map (Color240 . subtract 16) [ -- https://modern.ircdocs.horse/formatting.html#colors-16-98
052, 094, 100, 058,
022, 029, 023, 024, 017, 054, 053, 089, 088, 130,
142, 064, 028, 035, 030, 025, 018, 091, 090, 125,
124, 166, 184, 106, 034, 049, 037, 033, 019, 129,
127, 161, 196, 208, 226, 154, 046, 086, 051, 075,
021, 171, 201, 198, 203, 215, 227, 191, 083, 122,
087, 111, 063, 177, 207, 205, 217, 223, 229, 193,
157, 158, 159, 153, 147, 183, 219, 212, 016, 233,
235, 237, 239, 241, 244, 247, 250, 254, 231 ]
rgbColor' :: Int -> Int -> Int -> Color
rgbColor' = rgbColor -- fix the type to Int
applyControlEffect :: Char -> Attr -> Maybe Attr
applyControlEffect '\^B' attr = Just $! toggleStyle bold attr
applyControlEffect '\^V' attr = Just $! toggleStyle reverseVideo attr
applyControlEffect '\^_' attr = Just $! toggleStyle underline attr
applyControlEffect '\^^' attr = Just $! toggleStyle strikethrough attr
applyControlEffect '\^]' attr = Just $! toggleStyle italic attr
applyControlEffect '\^O' _ = Just defAttr
applyControlEffect _ _ = Nothing
toggleStyle :: Style -> Attr -> Attr
toggleStyle s1 = over styleLens $ \old ->
case old of
SetTo s2 -> SetTo (xor s1 s2)
_ -> SetTo s1
-- | Safely render a control character.
controlImage :: Char -> Image'
controlImage = I.char attr . controlName
where
attr = withStyle defAttr reverseVideo
controlName c
| c < '\128' = chr (0x40 `xor` ord c)
| otherwise = '!'
-- | Render a 'String' with default attributes and replacing all of the
-- control characters with reverse-video letters corresponding to caret
-- notation.
plainText :: String -> Image'
plainText "" = mempty
plainText xs =
case break isControl xs of
(first, "" ) -> I.string defAttr first
(first, cntl:rest) -> I.string defAttr first <>
controlImage cntl <>
plainText rest
| glguy/irc-core | src/Client/Image/MircFormatting.hs | isc | 7,477 | 0 | 16 | 2,249 | 2,066 | 1,097 | 969 | 161 | 9 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE FunctionalDependencies #-}
-- data declarations that are empty
{-# LANGUAGE EmptyDataDecls #-}
module Symengine.Internal
(
cIntToEnum,
cIntFromEnum,
mkForeignPtr,
Wrapped(..),
with2,
with3,
with4,
CBasicSym,
CVecBasic,
SymengineException(NoException, RuntimeError, DivByZero, NotImplemented, DomainError, ParseError),
forceException,
throwOnSymIntException
) where
import Prelude
import Foreign.C.Types
import Foreign.Ptr
import Foreign.C.String
import Foreign.Storable
import Foreign.Marshal.Array
import Foreign.Marshal.Alloc
import Foreign.ForeignPtr
import Control.Applicative
import Control.Monad -- for foldM
import System.IO.Unsafe
import Control.Monad
import GHC.Real
import Control.Exception
import Data.Typeable
data SymengineException = NoException |
RuntimeError |
DivByZero |
NotImplemented |
DomainError |
ParseError deriving (Show, Enum, Eq, Typeable)
instance Exception SymengineException
-- interpret the CInt as a SymengineException, and
-- throw if it is actually an error
throwOnSymIntException :: CInt -> IO ()
throwOnSymIntException i = forceException . cIntToEnum $ i
forceException :: SymengineException -> IO ()
forceException exception =
case exception of
NoException -> return ()
error @ _ -> throwIO error
cIntToEnum :: Enum a => CInt -> a
cIntToEnum = toEnum . fromIntegral
cIntFromEnum :: Enum a => a -> CInt
cIntFromEnum = fromIntegral . fromEnum
-- |given a raw pointer IO (Ptr a) and a destructor function pointer, make a
-- foreign pointer
mkForeignPtr :: (IO (Ptr a)) -> FunPtr (Ptr a -> IO ()) -> IO (ForeignPtr a)
mkForeignPtr cons des = do
rawptr <- cons
finalized <- newForeignPtr des rawptr
return finalized
class Wrapped o i | o -> i where
with :: o -> (Ptr i -> IO a) -> IO a
with2 :: Wrapped o1 i1 => Wrapped o2 i2 => o1 -> o2 -> (Ptr i1 -> Ptr i2 -> IO a) -> IO a
with2 o1 o2 f = with o1 (\p1 -> with o2 (\p2 -> f p1 p2))
with3 :: Wrapped o1 i1 => Wrapped o2 i2 => Wrapped o3 i3 => o1 -> o2 -> o3 -> (Ptr i1 -> Ptr i2 -> Ptr i3 -> IO a) -> IO a
with3 o1 o2 o3 f = with2 o1 o2 (\p1 p2 -> with o3 (\p3 -> f p1 p2 p3))
with4:: Wrapped o1 i1 => Wrapped o2 i2 => Wrapped o3 i3 => Wrapped o4 i4 => o1 -> o2 -> o3 -> o4 -> (Ptr i1 -> Ptr i2 -> Ptr i3 -> Ptr i4 -> IO a) -> IO a
with4 o1 o2 o3 o4 f = with o1 (\p1 -> with3 o2 o3 o4 (\p2 p3 p4 -> f p1 p2 p3 p4))
-- BasicSym
data CBasicSym
-- VecBasic
data CVecBasic
-- CDenseMatrix
| bollu/symengine.hs-1 | src/Symengine/Internal.hs | mit | 2,666 | 1 | 19 | 640 | 856 | 452 | 404 | -1 | -1 |
-- HACKERRANK: String-o-Permute
-- https://www.hackerrank.com/challenges/string-o-permute
module Main where
import qualified Control.Monad as M
solve :: String -> String
solve [] = []
solve (x1:x2:xs) = x2:x1:(solve xs)
main :: IO ()
main = getLine >>= \tStr -> M.replicateM_ ((read::String->Int) tStr) (getLine >>= \l -> putStrLn (solve l))
| everyevery/programming_study | hackerrank/functional/string-o-permute/string-o-permute.hs | mit | 348 | 0 | 13 | 53 | 136 | 75 | 61 | 7 | 1 |
-------------------------------------------------------------------------
--
-- Haskell: The Craft of Functional Programming, 3e
-- Simon Thompson
-- (c) Addison-Wesley, 1996-2011.
--
-- Chapter 1
--
-- The Pictures example code is given in the file Pitures.hs.
-- This file can be used by importing it; more details are given in
-- Chapter 2.
--
-------------------------------------------------------------------------
module Chapter1 where
import Craft.Pictures hiding (rotate)
-- A first definition, of the integer value, size.
size :: Integer
size = 12+13
-- Some definitions using Pictures.
-- Inverting the colour of the horse picture, ...
blackHorse :: Picture
blackHorse = invertColour horse
-- ... rotating the horse picture, ...
rotateHorse :: Picture
rotateHorse = flipH (flipV horse)
-- Some function definitions.
-- To square an integer, ...
square :: Integer -> Integer
square n = n*n
-- ... to double an integer, and ...
double :: Integer -> Integer
double n = 2*n
-- ... to rotate a picture we can perform the two reflections,
-- and so we define
rotate :: Picture -> Picture
rotate pic = flipH (flipV pic)
-- A different definition of rotateHorse can use rotate
rotateHorse1 :: Picture
rotateHorse1 = rotate horse
-- where the new definition is of a different name: you can't change a definition
-- in a script.
-- Defining rotate a different way, as a composition of functions; see the
-- diagram in the book for a picture of what's going on.
rotate1 :: Picture -> Picture
rotate1 = flipH . flipV
-- Pictures
-- The definitions of the functions modelling pictures are in the file
-- Pictures.hs.
-- Tests and properties
-- The functions test_rotate, prop_rotate etc are in the Pictures.hs module
| Numberartificial/workflow | snipets/src/craft/Chapter1.hs | mit | 1,751 | 0 | 7 | 311 | 192 | 119 | 73 | 18 | 1 |
{- |
Module : $Header$
Description : Manchester syntax parser for OWL 2
Copyright : (c) DFKI GmbH, Uni Bremen 2007-2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : portable
Contains : Parser for the Manchester Syntax into Abstract Syntax of OWL 2
References : <http://www.w3.org/TR/2009/NOTE-owl2-manchester-syntax-20091027/>
-}
module OWL2.Parse where
import OWL2.AS
import OWL2.Symbols
import OWL2.Keywords
import OWL2.ColonKeywords
import Common.Keywords
import Common.Id
import Common.Lexer
import Common.Parsec
import Common.AnnoParser (commentLine)
import Common.Token (criticalKeywords)
import Common.Utils (nubOrd)
import qualified Common.IRI as IRI
import qualified Common.GlobalAnnotations as GA (PrefixMap)
import Text.ParserCombinators.Parsec
import Control.Monad (liftM2)
import Data.Char
import qualified Data.Map as Map
characters :: [Character]
characters = [minBound .. maxBound]
-- | OWL and CASL structured keywords including 'andS' and 'notS'
owlKeywords :: [String]
owlKeywords = notS : stringS : map show entityTypes
++ map show characters ++ keywords ++ criticalKeywords
ncNameStart :: Char -> Bool
ncNameStart c = isAlpha c || c == '_'
-- | rfc3987 plus '+' from scheme (scheme does not allow the dots)
ncNameChar :: Char -> Bool
ncNameChar c = isAlphaNum c || elem c ".+-_\183"
prefix :: CharParser st String
prefix = satisfy ncNameStart <:> many (satisfy ncNameChar)
iunreserved :: Char -> Bool
iunreserved c = isAlphaNum c || elem c "-._~" || ord c >= 160 && ord c <= 55295
-- maybe lower case hex-digits should be illegal
pctEncoded :: CharParser st String
pctEncoded = char '%' <:> hexDigit <:> single hexDigit
{- comma and parens are removed here
but would cause no problems for full IRIs within angle brackets -}
subDelims :: Char -> Bool
subDelims c = elem c "!$&'*+;="
iunreservedSubDelims :: String -> CharParser st Char
iunreservedSubDelims cs =
satisfy $ \ c -> iunreserved c || subDelims c || elem c cs
iunreservedPctEncodedSubDelims :: String -> CharParser st String
iunreservedPctEncodedSubDelims cs =
single (iunreservedSubDelims cs) <|> pctEncoded
ipChar :: CharParser st String
ipChar = iunreservedPctEncodedSubDelims ":@"
ifragment :: CharParser st String
ifragment = flat $ many (ipChar <|> single (char '/' <|> char '?'))
iquery :: CharParser st String
iquery = ifragment -- ignore iprivate
iregName :: CharParser st String
iregName = flat $ many $ iunreservedPctEncodedSubDelims ""
iuserinfo :: CharParser st String
iuserinfo = flat $ many $ iunreservedPctEncodedSubDelims ":"
-- | parse zero or at most n consecutive arguments
atMost :: Int -> GenParser tok st a -> GenParser tok st [a]
atMost n p = if n <= 0 then return [] else
p <:> atMost (n - 1) p <|> return []
-- | parse at least one but at most n conse
atMost1 :: Int -> GenParser tok st a -> GenParser tok st [a]
atMost1 n p = p <:> atMost (n - 1) p
decOctet :: CharParser st String
decOctet = atMost 3 digit
`checkWith` \ s -> let v = value 10 s in v <= 255 &&
(if v == 0 then s == "0" else take 1 s /= "0")
iPv4Adress :: CharParser st String
iPv4Adress = decOctet <++> string "."
<++> decOctet <++> string "."
<++> decOctet <++> string "."
<++> decOctet
ihost :: CharParser st String
ihost = iregName <|> iPv4Adress -- or ipLiteral
port :: CharParser st String
port = many digit
iauthority :: CharParser st String
iauthority = optionL (try $ iuserinfo <++> string "@") <++> ihost
<++> optionL (char ':' <:> port)
isegment :: CharParser st String
isegment = flat $ many ipChar
isegmentNz :: CharParser st String
isegmentNz = flat $ many1 ipChar
ipathAbempty :: CharParser st String
ipathAbempty = flat $ many (char '/' <:> isegment)
ipathAbsolute :: CharParser st String
ipathAbsolute = char '/' <:> optionL (isegmentNz <++> ipathAbempty)
{- within abbreviated IRIs only ipath-noscheme should be used
that excludes colons via isegment-nz-nc -}
ipathRootless :: CharParser st String
ipathRootless = isegmentNz <++> ipathAbempty
iauthorityWithPath :: CharParser st String
iauthorityWithPath = tryString "//" <++> iauthority <++> ipathAbempty
optQueryOrFrag :: CharParser st String
optQueryOrFrag = optionL (char '?' <:> iquery)
<++> optionL (char '#' <:> ifragment)
-- | covers irelative-part (therefore we omit curie)
ihierPart :: CharParser st String
ihierPart =
iauthorityWithPath <|> ipathAbsolute <|> ipathRootless
hierPartWithOpts :: CharParser st String
hierPartWithOpts = (char '#' <:> ifragment) <|> ihierPart <++> optQueryOrFrag
skips :: CharParser st a -> CharParser st a
skips = (<< skipMany
(forget space <|> forget commentLine <|> nestCommentOut <?> ""))
abbrIriNoPos :: CharParser st QName
abbrIriNoPos = try $ do
pre <- try $ prefix << char ':'
r <- hierPartWithOpts <|> return "" -- allow an empty local part
return nullQName { namePrefix = pre, localPart = r }
<|> fmap mkQName hierPartWithOpts
abbrIri :: CharParser st QName
abbrIri = do
p <- getPos
q <- abbrIriNoPos
return q { iriPos = Range [p],
iriType = if namePrefix q == "_" then NodeID else Abbreviated }
fullIri :: CharParser st QName
fullIri = do
char '<'
QN pre r _ _ p <- abbrIri
char '>'
return $ QN pre r Full (if null pre then r else pre ++ ":" ++ r) p
uriQ :: CharParser st QName
uriQ = fullIri <|> abbrIri
uriP :: CharParser st QName
uriP =
skips $ try $ checkWithUsing showQN uriQ $ \ q -> let p = namePrefix q in
if null p then notElem (localPart q) owlKeywords
else notElem p $ map (takeWhile (/= ':'))
$ colonKeywords
++ [ show d ++ e | d <- equivOrDisjointL, e <- [classesC, propertiesC]]
extEntity :: CharParser st ExtEntityType
extEntity =
fmap EntityType entityType
<|> option AnyEntity (pkeyword "Prefix" >> return PrefixO)
symbItem :: GenParser Char st SymbItems
symbItem = do
ext <- extEntity
i <- uriP
return $ SymbItems ext [i]
symbItems :: GenParser Char st SymbItems
symbItems = do
ext <- extEntity
iris <- symbs
return $ SymbItems ext iris
-- | parse a comma separated list of uris
symbs :: GenParser Char st [IRI]
symbs = uriP >>= \ u -> do
commaP `followedWith` uriP
us <- symbs
return $ u : us
<|> return [u]
-- | parse a possibly kinded list of comma separated symbol pairs
symbMapItems :: GenParser Char st SymbMapItems
symbMapItems = do
ext <- extEntity
iris <- symbPairs
return $ SymbMapItems ext iris
-- | parse a comma separated list of uri pairs
symbPairs :: GenParser Char st [(IRI, Maybe IRI)]
symbPairs = uriPair >>= \ u -> do
commaP `followedWith` uriP
us <- symbPairs
return $ u : us
<|> return [u]
uriPair :: GenParser Char st (IRI, Maybe IRI)
uriPair = uriP >>= \ u -> do
pToken $ toKey mapsTo
u2 <- uriP
return (u, Just u2)
<|> return (u, Nothing)
datatypeUri :: CharParser st QName
datatypeUri = fmap mkQName (choice $ map keyword datatypeKeys) <|> uriP
optSign :: CharParser st Bool
optSign = option False $ fmap (== '-') (oneOf "+-")
postDecimal :: CharParser st NNInt
postDecimal = char '.' >> option zeroNNInt getNNInt
getNNInt :: CharParser st NNInt
getNNInt = fmap (NNInt . map digitToInt) getNumber
intLit :: CharParser st IntLit
intLit = do
b <- optSign
n <- getNNInt
return $ negNNInt b n
decimalLit :: CharParser st DecLit
decimalLit = liftM2 DecLit intLit $ option zeroNNInt postDecimal
floatDecimal :: CharParser st DecLit
floatDecimal = do
n <- getNNInt
f <- option zeroNNInt postDecimal
return $ DecLit (negNNInt False n) f
<|> do
n <- postDecimal
return $ DecLit zeroInt n
floatingPointLit :: CharParser st FloatLit
floatingPointLit = do
b <- optSign
d <- floatDecimal
i <- option zeroInt (oneOf "eE" >> intLit)
optionMaybe $ oneOf "fF"
return $ FloatLit (negDec b d) i
languageTag :: CharParser st String
languageTag = atMost1 4 letter
<++> flat (many $ char '-' <:> atMost1 8 alphaNum)
rmQuotes :: String -> String
rmQuotes s = case s of
_ : tl@(_ : _) -> init tl
_ -> error "rmQuotes"
stringLiteral :: CharParser st Literal
stringLiteral = do
s <- fmap rmQuotes stringLit
do
string cTypeS
d <- datatypeUri
return $ Literal s $ Typed d
<|> do
string asP
t <- skips $ optionMaybe languageTag
return $ Literal s $ Untyped t
<|> skips (return $ Literal s $ Typed $ mkQName stringS)
literal :: CharParser st Literal
literal = do
f <- skips $ try floatingPointLit
<|> fmap decToFloat decimalLit
return $ NumberLit f
<|> stringLiteral
-- * description
owlClassUri :: CharParser st QName
owlClassUri = uriP
individualUri :: CharParser st QName
individualUri = uriP
individual :: CharParser st Individual
individual = do
i <- individualUri
return $ if namePrefix i == "_" then i {iriType = NodeID}
else i
skipChar :: Char -> CharParser st ()
skipChar = forget . skips . char
parensP :: CharParser st a -> CharParser st a
parensP = between (skipChar '(') (skipChar ')')
bracesP :: CharParser st a -> CharParser st a
bracesP = between (skipChar '{') (skipChar '}')
bracketsP :: CharParser st a -> CharParser st a
bracketsP = between (skipChar '[') (skipChar ']')
commaP :: CharParser st ()
commaP = forget $ skipChar ','
sepByComma :: CharParser st a -> CharParser st [a]
sepByComma p = sepBy1 p commaP
-- | plain string parser with skip
pkeyword :: String -> CharParser st ()
pkeyword s = forget . keywordNotFollowedBy s $ alphaNum <|> char '/'
keywordNotFollowedBy :: String -> CharParser st Char -> CharParser st String
keywordNotFollowedBy s c = skips $ try $ string s << notFollowedBy c
-- | keyword not followed by any alphanum
keyword :: String -> CharParser st String
keyword s = keywordNotFollowedBy s (alphaNum <|> char '_')
-- base OWLClass excluded
atomic :: CharParser st ClassExpression
atomic = parensP description
<|> fmap ObjectOneOf (bracesP $ sepByComma individual)
objectPropertyExpr :: CharParser st ObjectPropertyExpression
objectPropertyExpr = do
keyword inverseS
fmap ObjectInverseOf objectPropertyExpr
<|> fmap ObjectProp uriP
-- creating the facet-value pairs
facetValuePair :: CharParser st (ConstrainingFacet, RestrictionValue)
facetValuePair = do
df <- choice $ map (\ f -> keyword (showFacet f) >> return f)
[ LENGTH
, MINLENGTH
, MAXLENGTH
, PATTERN
, TOTALDIGITS
, FRACTIONDIGITS ] ++ map
(\ f -> keywordNotFollowedBy (showFacet f) (oneOf "<>=")
>> return f)
[ MININCLUSIVE
, MINEXCLUSIVE
, MAXINCLUSIVE
, MAXEXCLUSIVE ]
rv <- literal
return (facetToIRI df, rv)
-- it returns DataType Datatype or DatatypeRestriction Datatype [facetValuePair]
dataRangeRestriction :: CharParser st DataRange
dataRangeRestriction = do
e <- datatypeUri
option (DataType e []) $ fmap (DataType e) $ bracketsP
$ sepByComma facetValuePair
dataConjunct :: CharParser st DataRange
dataConjunct = fmap (mkDataJunction IntersectionOf)
$ sepBy1 dataPrimary $ keyword andS
dataRange :: CharParser st DataRange
dataRange = fmap (mkDataJunction UnionOf)
$ sepBy1 dataConjunct $ keyword orS
dataPrimary :: CharParser st DataRange
dataPrimary = do
keyword notS
fmap DataComplementOf dataPrimary
<|> fmap DataOneOf (bracesP $ sepByComma literal)
<|> dataRangeRestriction
mkDataJunction :: JunctionType -> [DataRange] -> DataRange
mkDataJunction ty ds = case nubOrd ds of
[] -> error "mkObjectJunction"
[x] -> x
ns -> DataJunction ty ns
-- parses "some" or "only"
someOrOnly :: CharParser st QuantifierType
someOrOnly = choice
$ map (\ f -> keyword (showQuantifierType f) >> return f)
[AllValuesFrom, SomeValuesFrom]
-- locates the keywords "min" "max" "exact" and their argument
card :: CharParser st (CardinalityType, Int)
card = do
c <- choice $ map (\ f -> keywordNotFollowedBy (showCardinalityType f) letter
>> return f)
[MinCardinality, MaxCardinality, ExactCardinality]
n <- skips getNumber
return (c, value 10 n)
-- tries to parse either a QName or a literal
individualOrConstant :: CharParser st (Either Individual Literal)
individualOrConstant = fmap Right literal <|> fmap Left individual
{- | applies the previous one to a list separated by commas
(the list needs to be all of the same type, of course) -}
individualOrConstantList :: CharParser st (Either [Individual] [Literal])
individualOrConstantList = do
ioc <- individualOrConstant
case ioc of
Left u -> fmap (Left . (u :)) $ optionL
$ commaP >> sepByComma individual
Right c -> fmap (Right . (c :)) $ optionL
$ commaP >> sepByComma literal
primaryOrDataRange :: CharParser st (Either ClassExpression DataRange)
primaryOrDataRange = do
ns <- many $ keyword notS -- allows multiple not before primary
ed <- do
u <- datatypeUri
fmap Left (restrictionAny $ ObjectProp u)
<|> fmap (Right . DataType u)
(bracketsP $ sepByComma facetValuePair)
<|> return (if isDatatypeKey u
then Right $ DataType u []
else Left $ Expression u) -- could still be a datatypeUri
<|> do
e <- bracesP individualOrConstantList
return $ case e of
Left us -> Left $ ObjectOneOf us
Right cs -> Right $ DataOneOf cs
<|> fmap Left restrictionOrAtomic
return $ if even (length ns) then ed else
case ed of
Left d -> Left $ ObjectComplementOf d
Right d -> Right $ DataComplementOf d
mkObjectJunction :: JunctionType -> [ClassExpression] -> ClassExpression
mkObjectJunction ty ds = case nubOrd ds of
[] -> error "mkObjectJunction"
[x] -> x
ns -> ObjectJunction ty ns
restrictionAny :: ObjectPropertyExpression -> CharParser st ClassExpression
restrictionAny opExpr = do
keyword valueS
e <- individualOrConstant
case e of
Left u -> return $ ObjectHasValue opExpr u
Right c -> case opExpr of
ObjectProp dpExpr -> return $ DataHasValue dpExpr c
_ -> unexpected "literal"
<|> do
keyword selfS
return $ ObjectHasSelf opExpr
<|> do -- sugar
keyword onlysomeS
ds <- bracketsP $ sepByComma description
let as = map (ObjectValuesFrom SomeValuesFrom opExpr) ds
o = ObjectValuesFrom AllValuesFrom opExpr
$ mkObjectJunction UnionOf ds
return $ mkObjectJunction IntersectionOf $ o : as
<|> do -- sugar
keyword hasS
iu <- individual
return $ ObjectValuesFrom SomeValuesFrom opExpr $ ObjectOneOf [iu]
<|> do
v <- someOrOnly
pr <- primaryOrDataRange
case pr of
Left p -> return $ ObjectValuesFrom v opExpr p
Right r -> case opExpr of
ObjectProp dpExpr -> return $ DataValuesFrom v dpExpr r
_ -> unexpected $ "dataRange after " ++ showQuantifierType v
<|> do
(c, n) <- card
mp <- optionMaybe primaryOrDataRange
case mp of
Nothing -> return $ ObjectCardinality $ Cardinality c n opExpr Nothing
Just pr -> case pr of
Left p ->
return $ ObjectCardinality $ Cardinality c n opExpr $ Just p
Right r -> case opExpr of
ObjectProp dpExpr ->
return $ DataCardinality $ Cardinality c n dpExpr $ Just r
_ -> unexpected $ "dataRange after " ++ showCardinalityType c
restriction :: CharParser st ClassExpression
restriction = objectPropertyExpr >>= restrictionAny
restrictionOrAtomic :: CharParser st ClassExpression
restrictionOrAtomic = do
opExpr <- objectPropertyExpr
restrictionAny opExpr <|> case opExpr of
ObjectProp euri -> return $ Expression euri
_ -> unexpected "inverse object property"
<|> atomic
optNot :: (a -> a) -> CharParser st a -> CharParser st a
optNot f p = (keyword notS >> fmap f p) <|> p
primary :: CharParser st ClassExpression
primary = optNot ObjectComplementOf restrictionOrAtomic
conjunction :: CharParser st ClassExpression
conjunction = do
curi <- fmap Expression $ try (owlClassUri << keyword thatS)
rs <- sepBy1 (optNot ObjectComplementOf restriction) $ keyword andS
return $ mkObjectJunction IntersectionOf $ curi : rs
<|> fmap (mkObjectJunction IntersectionOf)
(sepBy1 primary $ keyword andS)
description :: CharParser st ClassExpression
description =
fmap (mkObjectJunction UnionOf) $ sepBy1 conjunction $ keyword orS
entityType :: CharParser st EntityType
entityType = choice $ map (\ f -> keyword (show f) >> return f)
entityTypes
{- | same as annotation Target in Manchester Syntax,
named annotation Value in Abstract Syntax -}
annotationValue :: CharParser st AnnotationValue
annotationValue = do
l <- literal
return $ AnnValLit l
<|> do
i <- individual
return $ AnnValue i
equivOrDisjointL :: [EquivOrDisjoint]
equivOrDisjointL = [Equivalent, Disjoint]
equivOrDisjoint :: CharParser st EquivOrDisjoint
equivOrDisjoint = choice
$ map (\ f -> pkeyword (showEquivOrDisjoint f) >> return f)
equivOrDisjointL
subPropertyKey :: CharParser st ()
subPropertyKey = pkeyword subPropertyOfC
characterKey :: CharParser st ()
characterKey = pkeyword characteristicsC
sameOrDifferent :: CharParser st SameOrDifferent
sameOrDifferent = choice
$ map (\ f -> pkeyword (showSameOrDifferent f) >> return f)
[Same, Different]
sameOrDifferentIndu :: CharParser st SameOrDifferent
sameOrDifferentIndu = (pkeyword sameIndividualC >> return Same)
<|> (pkeyword differentIndividualsC >> return Different)
equivOrDisjointKeyword :: String -> CharParser st EquivOrDisjoint
equivOrDisjointKeyword ext = choice
$ map (\ f -> pkeyword (show f ++ ext) >> return f)
equivOrDisjointL
objectPropertyCharacter :: CharParser st Character
objectPropertyCharacter =
choice $ map (\ f -> keyword (show f) >> return f) characters
domainOrRange :: CharParser st DomainOrRange
domainOrRange = choice
$ map (\ f -> pkeyword (showDomainOrRange f) >> return f)
[ADomain, ARange]
nsEntry :: CharParser st (String, QName)
nsEntry = do
pkeyword prefixC
p <- skips (option "" prefix << char ':')
i <- skips fullIri
return (p, i)
<|> do
pkeyword namespaceC
p <- skips prefix
i <- skips fullIri
return (p, i)
importEntry :: CharParser st QName
importEntry = pkeyword importC >> uriP
convertPrefixMap :: GA.PrefixMap -> Map.Map String String
convertPrefixMap = Map.map $ IRI.iriToStringUnsecure . IRI.setAngles False
| mariefarrell/Hets | OWL2/Parse.hs | gpl-2.0 | 18,656 | 0 | 19 | 4,110 | 5,709 | 2,811 | 2,898 | 454 | 8 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.StorageGateway.DescribeMaintenanceStartTime
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | This operation returns your gateway's weekly maintenance start time including
-- the day and time of the week. Note that values are in terms of the gateway's
-- time zone.
--
-- <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeMaintenanceStartTime.html>
module Network.AWS.StorageGateway.DescribeMaintenanceStartTime
(
-- * Request
DescribeMaintenanceStartTime
-- ** Request constructor
, describeMaintenanceStartTime
-- ** Request lenses
, dmstGatewayARN
-- * Response
, DescribeMaintenanceStartTimeResponse
-- ** Response constructor
, describeMaintenanceStartTimeResponse
-- ** Response lenses
, dmstrDayOfWeek
, dmstrGatewayARN
, dmstrHourOfDay
, dmstrMinuteOfHour
, dmstrTimezone
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.StorageGateway.Types
import qualified GHC.Exts
newtype DescribeMaintenanceStartTime = DescribeMaintenanceStartTime
{ _dmstGatewayARN :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DescribeMaintenanceStartTime' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dmstGatewayARN' @::@ 'Text'
--
describeMaintenanceStartTime :: Text -- ^ 'dmstGatewayARN'
-> DescribeMaintenanceStartTime
describeMaintenanceStartTime p1 = DescribeMaintenanceStartTime
{ _dmstGatewayARN = p1
}
dmstGatewayARN :: Lens' DescribeMaintenanceStartTime Text
dmstGatewayARN = lens _dmstGatewayARN (\s a -> s { _dmstGatewayARN = a })
data DescribeMaintenanceStartTimeResponse = DescribeMaintenanceStartTimeResponse
{ _dmstrDayOfWeek :: Maybe Nat
, _dmstrGatewayARN :: Maybe Text
, _dmstrHourOfDay :: Maybe Nat
, _dmstrMinuteOfHour :: Maybe Nat
, _dmstrTimezone :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'DescribeMaintenanceStartTimeResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dmstrDayOfWeek' @::@ 'Maybe' 'Natural'
--
-- * 'dmstrGatewayARN' @::@ 'Maybe' 'Text'
--
-- * 'dmstrHourOfDay' @::@ 'Maybe' 'Natural'
--
-- * 'dmstrMinuteOfHour' @::@ 'Maybe' 'Natural'
--
-- * 'dmstrTimezone' @::@ 'Maybe' 'Text'
--
describeMaintenanceStartTimeResponse :: DescribeMaintenanceStartTimeResponse
describeMaintenanceStartTimeResponse = DescribeMaintenanceStartTimeResponse
{ _dmstrGatewayARN = Nothing
, _dmstrHourOfDay = Nothing
, _dmstrMinuteOfHour = Nothing
, _dmstrDayOfWeek = Nothing
, _dmstrTimezone = Nothing
}
dmstrDayOfWeek :: Lens' DescribeMaintenanceStartTimeResponse (Maybe Natural)
dmstrDayOfWeek = lens _dmstrDayOfWeek (\s a -> s { _dmstrDayOfWeek = a }) . mapping _Nat
dmstrGatewayARN :: Lens' DescribeMaintenanceStartTimeResponse (Maybe Text)
dmstrGatewayARN = lens _dmstrGatewayARN (\s a -> s { _dmstrGatewayARN = a })
dmstrHourOfDay :: Lens' DescribeMaintenanceStartTimeResponse (Maybe Natural)
dmstrHourOfDay = lens _dmstrHourOfDay (\s a -> s { _dmstrHourOfDay = a }) . mapping _Nat
dmstrMinuteOfHour :: Lens' DescribeMaintenanceStartTimeResponse (Maybe Natural)
dmstrMinuteOfHour =
lens _dmstrMinuteOfHour (\s a -> s { _dmstrMinuteOfHour = a })
. mapping _Nat
dmstrTimezone :: Lens' DescribeMaintenanceStartTimeResponse (Maybe Text)
dmstrTimezone = lens _dmstrTimezone (\s a -> s { _dmstrTimezone = a })
instance ToPath DescribeMaintenanceStartTime where
toPath = const "/"
instance ToQuery DescribeMaintenanceStartTime where
toQuery = const mempty
instance ToHeaders DescribeMaintenanceStartTime
instance ToJSON DescribeMaintenanceStartTime where
toJSON DescribeMaintenanceStartTime{..} = object
[ "GatewayARN" .= _dmstGatewayARN
]
instance AWSRequest DescribeMaintenanceStartTime where
type Sv DescribeMaintenanceStartTime = StorageGateway
type Rs DescribeMaintenanceStartTime = DescribeMaintenanceStartTimeResponse
request = post "DescribeMaintenanceStartTime"
response = jsonResponse
instance FromJSON DescribeMaintenanceStartTimeResponse where
parseJSON = withObject "DescribeMaintenanceStartTimeResponse" $ \o -> DescribeMaintenanceStartTimeResponse
<$> o .:? "DayOfWeek"
<*> o .:? "GatewayARN"
<*> o .:? "HourOfDay"
<*> o .:? "MinuteOfHour"
<*> o .:? "Timezone"
| romanb/amazonka | amazonka-storagegateway/gen/Network/AWS/StorageGateway/DescribeMaintenanceStartTime.hs | mpl-2.0 | 5,458 | 0 | 17 | 1,061 | 764 | 448 | 316 | 82 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.SDB.CreateDomain
-- 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)
--
-- The 'CreateDomain' operation creates a new domain. The domain name
-- should be unique among the domains associated with the Access Key ID
-- provided in the request. The 'CreateDomain' operation may take 10 or
-- more seconds to complete.
--
-- The client can create up to 100 domains per account.
--
-- If the client requires additional domains, go to
-- <http://aws.amazon.com/contact-us/simpledb-limit-request/>.
--
-- /See:/ <http://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API_CreateDomain.html AWS API Reference> for CreateDomain.
module Network.AWS.SDB.CreateDomain
(
-- * Creating a Request
createDomain
, CreateDomain
-- * Request Lenses
, cdDomainName
-- * Destructuring the Response
, createDomainResponse
, CreateDomainResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
import Network.AWS.SDB.Types
import Network.AWS.SDB.Types.Product
-- | /See:/ 'createDomain' smart constructor.
newtype CreateDomain = CreateDomain'
{ _cdDomainName :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateDomain' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cdDomainName'
createDomain
:: Text -- ^ 'cdDomainName'
-> CreateDomain
createDomain pDomainName_ =
CreateDomain'
{ _cdDomainName = pDomainName_
}
-- | The name of the domain to create. The name can range between 3 and 255
-- characters and can contain the following characters: a-z, A-Z, 0-9,
-- \'_\', \'-\', and \'.\'.
cdDomainName :: Lens' CreateDomain Text
cdDomainName = lens _cdDomainName (\ s a -> s{_cdDomainName = a});
instance AWSRequest CreateDomain where
type Rs CreateDomain = CreateDomainResponse
request = postQuery sDB
response = receiveNull CreateDomainResponse'
instance ToHeaders CreateDomain where
toHeaders = const mempty
instance ToPath CreateDomain where
toPath = const "/"
instance ToQuery CreateDomain where
toQuery CreateDomain'{..}
= mconcat
["Action" =: ("CreateDomain" :: ByteString),
"Version" =: ("2009-04-15" :: ByteString),
"DomainName" =: _cdDomainName]
-- | /See:/ 'createDomainResponse' smart constructor.
data CreateDomainResponse =
CreateDomainResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateDomainResponse' with the minimum fields required to make a request.
--
createDomainResponse
:: CreateDomainResponse
createDomainResponse = CreateDomainResponse'
| fmapfmapfmap/amazonka | amazonka-sdb/gen/Network/AWS/SDB/CreateDomain.hs | mpl-2.0 | 3,390 | 0 | 9 | 677 | 373 | 232 | 141 | 51 | 1 |
{-# LANGUAGE RankNTypes #-}
module Main where
import Test.Framework (defaultMain)
------------------------------------------------------------------------------
import qualified Data.HashTable.Test.Common as Common
import qualified Data.HashTable.ST.Basic as B
import qualified Data.HashTable.ST.Cuckoo as C
import qualified Data.HashTable.ST.Linear as L
import qualified Data.HashTable.IO as IO
------------------------------------------------------------------------------
main :: IO ()
main = defaultMain tests
where
dummyBasicTable = Common.dummyTable
:: forall k v . IO.IOHashTable (B.HashTable) k v
dummyCuckooTable = Common.dummyTable
:: forall k v . IO.IOHashTable (C.HashTable) k v
dummyLinearTable = Common.dummyTable
:: forall k v . IO.IOHashTable (L.HashTable) k v
basicTests = Common.tests "basic" dummyBasicTable
cuckooTests = Common.tests "cuckoo" dummyCuckooTable
linearTests = Common.tests "linear" dummyLinearTable
tests = [basicTests, linearTests, cuckooTests]
| cornell-pl/HsAdapton | weak-hashtables/test/suite/TestSuite.hs | bsd-3-clause | 1,086 | 0 | 10 | 208 | 226 | 139 | 87 | 20 | 1 |
module Web.Routes.Site where
import Data.ByteString
import Data.Monoid
import Data.Text (Text)
import Web.Routes.Base (decodePathInfo, encodePathInfo)
{-|
A site groups together the three functions necesary to make an application:
* A function to convert from the URL type to path segments.
* A function to convert from path segments to the URL, if possible.
* A function to return the application for a given URL.
There are two type parameters for Site: the first is the URL datatype, the
second is the application datatype. The application datatype will depend upon
your server backend.
-}
data Site url a
= Site {
{-|
Return the appropriate application for a given URL.
The first argument is a function which will give an appropriate
URL (as a String) for a URL datatype. This is usually
constructed by a combination of 'formatPathSegments' and the
prepending of an absolute application root.
Well behaving applications should use this function to
generating all internal URLs.
-}
handleSite :: (url -> [(Text, Maybe Text)] -> Text) -> url -> a
-- | This function must be the inverse of 'parsePathSegments'.
, formatPathSegments :: url -> ([Text], [(Text, Maybe Text)])
-- | This function must be the inverse of 'formatPathSegments'.
, parsePathSegments :: [Text] -> Either String url
}
-- | Override the \"default\" URL, ie the result of 'parsePathSegments' [].
setDefault :: url -> Site url a -> Site url a
setDefault defUrl (Site handle format parse) =
Site handle format parse'
where
parse' [] = Right defUrl
parse' x = parse x
instance Functor (Site url) where
fmap f site = site { handleSite = \showFn u -> f (handleSite site showFn u) }
-- | Retrieve the application to handle a given request.
--
-- NOTE: use 'decodePathInfo' to convert a 'ByteString' url to a properly decoded list of path segments
runSite :: Text -- ^ application root, with trailing slash
-> Site url a
-> [Text] -- ^ path info, (call 'decodePathInfo' on path with leading slash stripped)
-> (Either String a)
runSite approot site pathInfo =
case parsePathSegments site pathInfo of
(Left errs) -> (Left errs)
(Right url) -> Right $ handleSite site showFn url
where
showFn url qs =
let (pieces, qs') = formatPathSegments site url
in approot `mappend` (encodePathInfo pieces (qs ++ qs'))
| shockkolate/web-routes | Web/Routes/Site.hs | bsd-3-clause | 2,569 | 0 | 15 | 681 | 427 | 232 | 195 | 28 | 2 |
module Main where
import Test.QuickCheck
import Data.List
mult :: Int -> Int -> Int -> Int
mult x y z = x*y*z
prop_mult x y z = (x * y * z) == mult x y z
prop_factorial_monotone (Positive x) = factorial x <= (factorial x+1)
newtype SmallIntList = SmallIntList [Int] deriving (Eq,Show)
instance Arbitrary SmallIntList where
arbitrary = sized $ \s -> do
n <- choose (0,s `min` 8)
xs <- vectorOf n (choose (-10000,10000))
return (SmallIntList xs)
shrink (SmallIntList xs) = map SmallIntList (shrink xs)
main = do
quickCheck prop_mult
| chadbrewbaker/combinat | tests/Check.hs | bsd-3-clause | 599 | 0 | 15 | 160 | 256 | 132 | 124 | 16 | 1 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, TupleSections,
GeneralizedNewtypeDeriving, DeriveTraversable #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| JSON utility functions. -}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.JSON
( fromJResult
, fromJResultE
, readJSONWithDesc
, readEitherString
, JSRecord
, loadJSArray
, fromObj
, maybeFromObj
, fromObjWithDefault
, fromKeyValue
, fromJVal
, fromJValE
, jsonHead
, getMaybeJsonHead
, getMaybeJsonElem
, asJSObject
, asObjectList
, tryFromObj
, arrayMaybeFromJVal
, tryArrayMaybeFromObj
, toArray
, optionalJSField
, optFieldsToObj
, containerFromList
, lookupContainer
, alterContainerL
, readContainer
, mkUsedKeys
, allUsedKeys
, DictObject(..)
, showJSONtoDict
, readJSONfromDict
, ArrayObject(..)
, HasStringRepr(..)
, GenericContainer(..)
, emptyContainer
, Container
, MaybeForJSON(..)
, TimeAsDoubleJSON(..)
, Tuple5(..)
, nestedAccessByKey
, nestedAccessByKeyDotted
, branchOnField
, addField
, maybeParseMap
)
where
import Control.Applicative
import Control.DeepSeq
import Control.Monad.Error.Class
import Control.Monad.Writer
import qualified Data.Foldable as F
import qualified Data.Text as T
import qualified Data.Traversable as F
import Data.Maybe (fromMaybe, catMaybes)
import qualified Data.Map as Map
import qualified Data.Set as Set
import System.Time (ClockTime(..))
import Text.Printf (printf)
import qualified Text.JSON as J
import qualified Text.JSON.Types as JT
import Text.JSON.Pretty (pp_value)
-- Note: this module should not import any Ganeti-specific modules
-- beside BasicTypes, since it's used in THH which is used itself to
-- build many other modules.
import Ganeti.BasicTypes
-- Remove after we require >= 1.8.58
-- See: https://github.com/ndmitchell/hlint/issues/24
{-# ANN module "HLint: ignore Unused LANGUAGE pragma" #-}
-- * JSON-related functions
instance NFData J.JSValue where
rnf J.JSNull = ()
rnf (J.JSBool b) = rnf b
rnf (J.JSRational b r) = rnf b `seq` rnf r
rnf (J.JSString s) = rnf $ J.fromJSString s
rnf (J.JSArray a) = rnf a
rnf (J.JSObject o) = rnf o
instance (NFData a) => NFData (J.JSObject a) where
rnf = rnf . J.fromJSObject
-- | A type alias for a field of a JSRecord.
type JSField = (String, J.JSValue)
-- | A type alias for the list-based representation of J.JSObject.
type JSRecord = [JSField]
-- | Annotate @readJSON@ error messages with descriptions of what
-- is being parsed into what.
readJSONWithDesc :: (J.JSON a)
=> String -- ^ description of @a@
-> Bool -- ^ include input in
-- error messages
-> J.JSValue -- ^ input value
-> J.Result a
readJSONWithDesc name incInput input =
case J.readJSON input of
J.Ok r -> J.Ok r
J.Error e -> J.Error $ if incInput then msg ++ " from " ++ show input
else msg
where msg = "Can't parse value for '" ++ name ++ "': " ++ e
-- | Converts a JSON Result into a monadic value.
fromJResult :: Monad m => String -> J.Result a -> m a
fromJResult s (J.Error x) = fail (s ++ ": " ++ x)
fromJResult _ (J.Ok x) = return x
-- | Converts a JSON Result into a MonadError value.
fromJResultE :: (Error e, MonadError e m) => String -> J.Result a -> m a
fromJResultE s (J.Error x) = throwError . strMsg $ s ++ ": " ++ x
fromJResultE _ (J.Ok x) = return x
-- | Tries to read a string from a JSON value.
--
-- In case the value was not a string, we fail the read (in the
-- context of the current monad.
readEitherString :: (Monad m) => J.JSValue -> m String
readEitherString v =
case v of
J.JSString s -> return $ J.fromJSString s
_ -> fail "Wrong JSON type"
-- | Converts a JSON message into an array of JSON objects.
loadJSArray :: (Monad m)
=> String -- ^ Operation description (for error reporting)
-> String -- ^ Input message
-> m [J.JSObject J.JSValue]
loadJSArray s = fromJResult s . J.decodeStrict
-- | Helper function for missing-key errors
buildNoKeyError :: JSRecord -> String -> String
buildNoKeyError o k =
printf "key '%s' not found, object contains only %s" k (show (map fst o))
-- | Reads the value of a key in a JSON object.
fromObj :: (J.JSON a, Monad m) => JSRecord -> String -> m a
fromObj o k =
case lookup k o of
Nothing -> fail $ buildNoKeyError o k
Just val -> fromKeyValue k val
-- | Reads the value of an optional key in a JSON object. Missing
-- keys, or keys that have a \'null\' value, will be returned as
-- 'Nothing', otherwise we attempt deserialisation and return a 'Just'
-- value.
maybeFromObj :: (J.JSON a, Monad m) =>
JSRecord -> String -> m (Maybe a)
maybeFromObj o k =
case lookup k o of
Nothing -> return Nothing
-- a optional key with value JSNull is the same as missing, since
-- we can't convert it meaningfully anyway to a Haskell type, and
-- the Python code can emit 'null' for optional values (depending
-- on usage), and finally our encoding rules treat 'null' values
-- as 'missing'
Just J.JSNull -> return Nothing
Just val -> liftM Just (fromKeyValue k val)
-- | Reads the value of a key in a JSON object with a default if
-- missing. Note that both missing keys and keys with value \'null\'
-- will cause the default value to be returned.
fromObjWithDefault :: (J.JSON a, Monad m) =>
JSRecord -> String -> a -> m a
fromObjWithDefault o k d = liftM (fromMaybe d) $ maybeFromObj o k
arrayMaybeFromJVal :: (J.JSON a, Monad m) => J.JSValue -> m [Maybe a]
arrayMaybeFromJVal (J.JSArray xs) =
mapM parse xs
where
parse J.JSNull = return Nothing
parse x = liftM Just $ fromJVal x
arrayMaybeFromJVal v =
fail $ "Expecting array, got '" ++ show (pp_value v) ++ "'"
-- | Reads an array of optional items
arrayMaybeFromObj :: (J.JSON a, Monad m) =>
JSRecord -> String -> m [Maybe a]
arrayMaybeFromObj o k =
case lookup k o of
Just a -> arrayMaybeFromJVal a
_ -> fail $ buildNoKeyError o k
-- | Wrapper for arrayMaybeFromObj with better diagnostic
tryArrayMaybeFromObj :: (J.JSON a)
=> String -- ^ Textual "owner" in error messages
-> JSRecord -- ^ The object array
-> String -- ^ The desired key from the object
-> Result [Maybe a]
tryArrayMaybeFromObj t o = annotateResult t . arrayMaybeFromObj o
-- | Reads a JValue, that originated from an object key.
fromKeyValue :: (J.JSON a, Monad m)
=> String -- ^ The key name
-> J.JSValue -- ^ The value to read
-> m a
fromKeyValue k val =
fromJResult (printf "key '%s'" k) (J.readJSON val)
-- | Small wrapper over readJSON.
fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a
fromJVal v =
case J.readJSON v of
J.Error s -> fail ("Cannot convert value '" ++ show (pp_value v) ++
"', error: " ++ s)
J.Ok x -> return x
-- | Small wrapper over 'readJSON' for 'MonadError'.
fromJValE :: (Error e, MonadError e m, J.JSON a) => J.JSValue -> m a
fromJValE v =
case J.readJSON v of
J.Error s -> throwError . strMsg $
"Cannot convert value '" ++ show (pp_value v) ++
"', error: " ++ s
J.Ok x -> return x
-- | Helper function that returns Null or first element of the list.
jsonHead :: (J.JSON b) => [a] -> (a -> b) -> J.JSValue
jsonHead [] _ = J.JSNull
jsonHead (x:_) f = J.showJSON $ f x
-- | Helper for extracting Maybe values from a possibly empty list.
getMaybeJsonHead :: (J.JSON b) => [a] -> (a -> Maybe b) -> J.JSValue
getMaybeJsonHead [] _ = J.JSNull
getMaybeJsonHead (x:_) f = maybe J.JSNull J.showJSON (f x)
-- | Helper for extracting Maybe values from a list that might be too short.
getMaybeJsonElem :: (J.JSON b) => [a] -> Int -> (a -> Maybe b) -> J.JSValue
getMaybeJsonElem [] _ _ = J.JSNull
getMaybeJsonElem xs 0 f = getMaybeJsonHead xs f
getMaybeJsonElem (_:xs) n f
| n < 0 = J.JSNull
| otherwise = getMaybeJsonElem xs (n - 1) f
-- | Converts a JSON value into a JSON object.
asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue)
asJSObject (J.JSObject a) = return a
asJSObject _ = fail "not an object"
-- | Coneverts a list of JSON values into a list of JSON objects.
asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue]
asObjectList = mapM asJSObject
-- | Try to extract a key from an object with better error reporting
-- than fromObj.
tryFromObj :: (J.JSON a) =>
String -- ^ Textual "owner" in error messages
-> JSRecord -- ^ The object array
-> String -- ^ The desired key from the object
-> Result a
tryFromObj t o = annotateResult t . fromObj o
-- | Ensure a given JSValue is actually a JSArray.
toArray :: (Monad m) => J.JSValue -> m [J.JSValue]
toArray (J.JSArray arr) = return arr
toArray o =
fail $ "Invalid input, expected array but got " ++ show (pp_value o)
-- | Creates a Maybe JSField. If the value string is Nothing, the JSField
-- will be Nothing as well.
optionalJSField :: (J.JSON a) => String -> Maybe a -> Maybe JSField
optionalJSField name (Just value) = Just (name, J.showJSON value)
optionalJSField _ Nothing = Nothing
-- | Creates an object with all the non-Nothing fields of the given list.
optFieldsToObj :: [Maybe JSField] -> J.JSValue
optFieldsToObj = J.makeObj . catMaybes
-- * Container type (special type for JSON serialisation)
-- | Class of types that can be converted from Strings. This is
-- similar to the 'Read' class, but it's using a different
-- serialisation format, so we have to define a separate class. Mostly
-- useful for custom key types in JSON dictionaries, which have to be
-- backed by strings.
class HasStringRepr a where
fromStringRepr :: (Monad m) => String -> m a
toStringRepr :: a -> String
-- | Trivial instance 'HasStringRepr' for 'String'.
instance HasStringRepr String where
fromStringRepr = return
toStringRepr = id
-- | The container type, a wrapper over Data.Map
newtype GenericContainer a b =
GenericContainer { fromContainer :: Map.Map a b }
deriving (Show, Eq, Ord, Functor, F.Foldable, F.Traversable)
instance (NFData a, NFData b) => NFData (GenericContainer a b) where
rnf = rnf . Map.toList . fromContainer
-- | The empty container.
emptyContainer :: GenericContainer a b
emptyContainer = GenericContainer Map.empty
-- | Type alias for string keys.
type Container = GenericContainer String
-- | Creates a GenericContainer from a list of key-value pairs.
containerFromList :: Ord a => [(a,b)] -> GenericContainer a b
containerFromList = GenericContainer . Map.fromList
-- | Looks up a value in a container with a default value.
-- If a key has no value, a given monadic default is returned.
-- This allows simple error handling, as the default can be
-- 'mzero', 'failError' etc.
lookupContainer :: (Monad m, Ord a)
=> m b -> a -> GenericContainer a b -> m b
lookupContainer dflt k = maybe dflt return . Map.lookup k . fromContainer
-- | Updates a value inside a container.
-- The signature of the function is crafted so that it can be directly
-- used as a lens.
alterContainerL :: (Functor f, Ord a)
=> a
-> (Maybe b -> f (Maybe b))
-> GenericContainer a b
-> f (GenericContainer a b)
alterContainerL key f (GenericContainer m) =
fmap (\v -> GenericContainer $ Map.alter (const v) key m)
(f $ Map.lookup key m)
-- | Container loader.
readContainer :: (Monad m, HasStringRepr a, Ord a, J.JSON b) =>
J.JSObject J.JSValue -> m (GenericContainer a b)
readContainer obj = do
let kjvlist = J.fromJSObject obj
kalist <- mapM (\(k, v) -> do
k' <- fromStringRepr k
v' <- fromKeyValue k v
return (k', v')) kjvlist
return $ GenericContainer (Map.fromList kalist)
{-# ANN showContainer "HLint: ignore Use ***" #-}
-- | Container dumper.
showContainer :: (HasStringRepr a, J.JSON b) =>
GenericContainer a b -> J.JSValue
showContainer =
J.makeObj . map (\(k, v) -> (toStringRepr k, J.showJSON v)) .
Map.toList . fromContainer
instance (HasStringRepr a, Ord a, J.JSON b) =>
J.JSON (GenericContainer a b) where
showJSON = showContainer
readJSON (J.JSObject o) = readContainer o
readJSON v = fail $ "Failed to load container, expected object but got "
++ show (pp_value v)
-- * Types that (de)serialize in a special form of JSON
newtype UsedKeys = UsedKeys (Maybe (Set.Set String))
instance Monoid UsedKeys where
mempty = UsedKeys (Just Set.empty)
mappend (UsedKeys xs) (UsedKeys ys) = UsedKeys $ liftA2 Set.union xs ys
mkUsedKeys :: Set.Set String -> UsedKeys
mkUsedKeys = UsedKeys . Just
allUsedKeys :: UsedKeys
allUsedKeys = UsedKeys Nothing
-- | Class of objects that can be converted from and to 'JSObject'
-- lists-format.
class DictObject a where
toDict :: a -> [(String, J.JSValue)]
fromDictWKeys :: [(String, J.JSValue)] -> WriterT UsedKeys J.Result a
fromDict :: [(String, J.JSValue)] -> J.Result a
fromDict = liftM fst . runWriterT . fromDictWKeys
-- | A default implementation of 'showJSON' using 'toDict'.
showJSONtoDict :: (DictObject a) => a -> J.JSValue
showJSONtoDict = J.makeObj . toDict
-- | A default implementation of 'readJSON' using 'fromDict'.
-- Checks that the input value is a JSON object and
-- converts it using 'fromDict'.
-- Also checks the input contains only the used keys returned by 'fromDict'.
readJSONfromDict :: (DictObject a)
=> J.JSValue -> J.Result a
readJSONfromDict jsv = do
dict <- liftM J.fromJSObject $ J.readJSON jsv
(r, UsedKeys keys) <- runWriterT $ fromDictWKeys dict
-- check that no superfluous dictionary keys are present
case keys of
Just allowedSet | not (Set.null superfluous) ->
fail $ "Superfluous dictionary keys: "
++ show (Set.toAscList superfluous) ++ ", but only "
++ show (Set.toAscList allowedSet) ++ " allowed."
where
superfluous = Set.fromList (map fst dict) Set.\\ allowedSet
_ -> return ()
return r
-- | Class of objects that can be converted from and to @[JSValue]@ with
-- a fixed length and order.
class ArrayObject a where
toJSArray :: a -> [J.JSValue]
fromJSArray :: [J.JSValue] -> J.Result a
-- * General purpose data types for working with JSON
-- | A Maybe newtype that allows for serialization more appropriate to the
-- semantics of Maybe and JSON in our calls. Does not produce needless
-- and confusing dictionaries.
--
-- In particular, `J.JSNull` corresponds to `Nothing`.
-- This also means that this `Maybe a` newtype should not be used with `a`
-- values that themselves can serialize to `null`.
newtype MaybeForJSON a = MaybeForJSON { unMaybeForJSON :: Maybe a }
deriving (Show, Eq, Ord)
instance (J.JSON a) => J.JSON (MaybeForJSON a) where
readJSON J.JSNull = return $ MaybeForJSON Nothing
readJSON x = (MaybeForJSON . Just) `liftM` J.readJSON x
showJSON (MaybeForJSON (Just x)) = J.showJSON x
showJSON (MaybeForJSON Nothing) = J.JSNull
newtype TimeAsDoubleJSON
= TimeAsDoubleJSON { unTimeAsDoubleJSON :: ClockTime }
deriving (Show, Eq, Ord)
instance J.JSON TimeAsDoubleJSON where
readJSON v = do
t <- J.readJSON v :: J.Result Double
return . TimeAsDoubleJSON . uncurry TOD
$ divMod (round $ t * pico) (pico :: Integer)
where
pico :: (Num a) => a
pico = 10^(12 :: Int)
showJSON (TimeAsDoubleJSON (TOD ss ps)) = J.showJSON
(fromIntegral ss + fromIntegral ps / 10^(12 :: Int) :: Double)
-- Text.JSON from the JSON package only has instances for tuples up to size 4.
-- We use these newtypes so that we don't get a breakage once the 'json'
-- package adds instances for larger tuples (or have to resort to CPP).
newtype Tuple5 a b c d e = Tuple5 { unTuple5 :: (a, b, c, d, e) }
instance (J.JSON a, J.JSON b, J.JSON c, J.JSON d, J.JSON e)
=> J.JSON (Tuple5 a b c d e) where
readJSON (J.JSArray [a,b,c,d,e]) =
Tuple5 <$> ((,,,,) <$> J.readJSON a
<*> J.readJSON b
<*> J.readJSON c
<*> J.readJSON d
<*> J.readJSON e)
readJSON _ = fail "Unable to read Tuple5"
showJSON (Tuple5 (a, b, c, d, e)) =
J.JSArray
[ J.showJSON a
, J.showJSON b
, J.showJSON c
, J.showJSON d
, J.showJSON e
]
-- | Look up a value in a JSON object. Accessing @["a", "b", "c"]@ on an
-- object is equivalent as accessing @myobject.a.b.c@ on a JavaScript object.
--
-- An error is returned if the object doesn't have such an accessor or if
-- any value during the nested access is not an object at all.
nestedAccessByKey :: [String] -> J.JSValue -> J.Result J.JSValue
nestedAccessByKey keys json = case keys of
[] -> return json
k:ks -> case json of
J.JSObject obj -> J.valFromObj k obj >>= nestedAccessByKey ks
_ -> J.Error $ "Cannot access non-object with key '" ++ k ++ "'"
-- | Same as `nestedAccessByKey`, but accessing with a dotted string instead
-- (like @nestedAccessByKeyDotted "a.b.c"@).
nestedAccessByKeyDotted :: String -> J.JSValue -> J.Result J.JSValue
nestedAccessByKeyDotted s =
nestedAccessByKey (map T.unpack . T.splitOn (T.pack ".") . T.pack $ s)
-- | Branch decoding on a field in a JSON object.
branchOnField :: String -- ^ fieldname to branch on
-> (J.JSValue -> J.Result a)
-- ^ decoding function if field is present and @true@; field
-- will already be removed in the input
-> (J.JSValue -> J.Result a)
-- ^ decoding function otherwise
-> J.JSValue -> J.Result a
branchOnField k ifTrue ifFalse (J.JSObject jobj) =
let fields = J.fromJSObject jobj
jobj' = J.JSObject . J.toJSObject $ filter ((/=) k . fst) fields
in if lookup k fields == Just (J.JSBool True)
then ifTrue jobj'
else ifFalse jobj'
branchOnField k _ _ _ = J.Error $ "Need an object to branch on key " ++ k
-- | Add a field to a JSON object; to nothing, if the argument is not an object.
addField :: (String, J.JSValue) -> J.JSValue -> J.JSValue
addField (n,v) (J.JSObject obj) = J.JSObject $ JT.set_field obj n v
addField _ jsval = jsval
-- | Maybe obtain a map from a JSON object.
maybeParseMap :: J.JSON a => J.JSValue -> Maybe (Map.Map String a)
maybeParseMap = liftM fromContainer . readContainer <=< asJSObject
| grnet/snf-ganeti | src/Ganeti/JSON.hs | bsd-2-clause | 20,109 | 0 | 18 | 4,796 | 4,831 | 2,549 | 2,282 | -1 | -1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1998
\section[DataCon]{@DataCon@: Data Constructors}
-}
{-# LANGUAGE CPP, DeriveDataTypeable #-}
module DataCon (
-- * Main data types
DataCon, DataConRep(..),
SrcStrictness(..), SrcUnpackedness(..),
HsSrcBang(..), HsImplBang(..),
StrictnessMark(..),
ConTag,
-- ** Field labels
FieldLbl(..), FieldLabel, FieldLabelString,
-- ** Type construction
mkDataCon, fIRST_TAG,
buildAlgTyCon,
-- ** Type deconstruction
dataConRepType, dataConSig, dataConInstSig, dataConFullSig,
dataConName, dataConIdentity, dataConTag, dataConTyCon,
dataConOrigTyCon, dataConUserType,
dataConUnivTyVars, dataConExTyVars, dataConAllTyVars,
dataConEqSpec, eqSpecPreds, dataConTheta,
dataConStupidTheta,
dataConInstArgTys, dataConOrigArgTys, dataConOrigResTy,
dataConInstOrigArgTys, dataConRepArgTys,
dataConFieldLabels, dataConFieldType,
dataConSrcBangs,
dataConSourceArity, dataConRepArity, dataConRepRepArity,
dataConIsInfix,
dataConWorkId, dataConWrapId, dataConWrapId_maybe,
dataConImplicitTyThings,
dataConRepStrictness, dataConImplBangs, dataConBoxer,
splitDataProductType_maybe,
-- ** Predicates on DataCons
isNullarySrcDataCon, isNullaryRepDataCon, isTupleDataCon, isUnboxedTupleCon,
isVanillaDataCon, classDataCon, dataConCannotMatch,
isBanged, isMarkedStrict, eqHsBang, isSrcStrict, isSrcUnpacked,
-- ** Promotion related functions
promoteDataCon, promoteDataCon_maybe,
promoteType, promoteKind,
isPromotableType, computeTyConPromotability,
) where
#include "HsVersions.h"
import {-# SOURCE #-} MkId( DataConBoxer )
import Type
import ForeignCall( CType )
import TypeRep( Type(..) ) -- Used in promoteType
import PrelNames( liftedTypeKindTyConKey )
import Coercion
import Kind
import Unify
import TyCon
import FieldLabel
import Class
import Name
import Var
import Outputable
import Unique
import ListSetOps
import Util
import BasicTypes
import FastString
import Module
import VarEnv
import NameSet
import Binary
import qualified Data.Data as Data
import qualified Data.Typeable
import Data.Char
import Data.Word
import Data.List( mapAccumL, find )
{-
Data constructor representation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following Haskell data type declaration
data T = T !Int ![Int]
Using the strictness annotations, GHC will represent this as
data T = T Int# [Int]
That is, the Int has been unboxed. Furthermore, the Haskell source construction
T e1 e2
is translated to
case e1 of { I# x ->
case e2 of { r ->
T x r }}
That is, the first argument is unboxed, and the second is evaluated. Finally,
pattern matching is translated too:
case e of { T a b -> ... }
becomes
case e of { T a' b -> let a = I# a' in ... }
To keep ourselves sane, we name the different versions of the data constructor
differently, as follows.
Note [Data Constructor Naming]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Each data constructor C has two, and possibly up to four, Names associated with it:
OccName Name space Name of Notes
---------------------------------------------------------------------------
The "data con itself" C DataName DataCon In dom( GlobalRdrEnv )
The "worker data con" C VarName Id The worker
The "wrapper data con" $WC VarName Id The wrapper
The "newtype coercion" :CoT TcClsName TyCon
EVERY data constructor (incl for newtypes) has the former two (the
data con itself, and its worker. But only some data constructors have a
wrapper (see Note [The need for a wrapper]).
Each of these three has a distinct Unique. The "data con itself" name
appears in the output of the renamer, and names the Haskell-source
data constructor. The type checker translates it into either the wrapper Id
(if it exists) or worker Id (otherwise).
The data con has one or two Ids associated with it:
The "worker Id", is the actual data constructor.
* Every data constructor (newtype or data type) has a worker
* The worker is very like a primop, in that it has no binding.
* For a *data* type, the worker *is* the data constructor;
it has no unfolding
* For a *newtype*, the worker has a compulsory unfolding which
does a cast, e.g.
newtype T = MkT Int
The worker for MkT has unfolding
\\(x:Int). x `cast` sym CoT
Here CoT is the type constructor, witnessing the FC axiom
axiom CoT : T = Int
The "wrapper Id", \$WC, goes as follows
* Its type is exactly what it looks like in the source program.
* It is an ordinary function, and it gets a top-level binding
like any other function.
* The wrapper Id isn't generated for a data type if there is
nothing for the wrapper to do. That is, if its defn would be
\$wC = C
Note [The need for a wrapper]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Why might the wrapper have anything to do? Two reasons:
* Unboxing strict fields (with -funbox-strict-fields)
data T = MkT !(Int,Int)
\$wMkT :: (Int,Int) -> T
\$wMkT (x,y) = MkT x y
Notice that the worker has two fields where the wapper has
just one. That is, the worker has type
MkT :: Int -> Int -> T
* Equality constraints for GADTs
data T a where { MkT :: a -> T [a] }
The worker gets a type with explicit equality
constraints, thus:
MkT :: forall a b. (a=[b]) => b -> T a
The wrapper has the programmer-specified type:
\$wMkT :: a -> T [a]
\$wMkT a x = MkT [a] a [a] x
The third argument is a coercion
[a] :: [a]~[a]
INVARIANT: the dictionary constructor for a class
never has a wrapper.
A note about the stupid context
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Data types can have a context:
data (Eq a, Ord b) => T a b = T1 a b | T2 a
and that makes the constructors have a context too
(notice that T2's context is "thinned"):
T1 :: (Eq a, Ord b) => a -> b -> T a b
T2 :: (Eq a) => a -> T a b
Furthermore, this context pops up when pattern matching
(though GHC hasn't implemented this, but it is in H98, and
I've fixed GHC so that it now does):
f (T2 x) = x
gets inferred type
f :: Eq a => T a b -> a
I say the context is "stupid" because the dictionaries passed
are immediately discarded -- they do nothing and have no benefit.
It's a flaw in the language.
Up to now [March 2002] I have put this stupid context into the
type of the "wrapper" constructors functions, T1 and T2, but
that turned out to be jolly inconvenient for generics, and
record update, and other functions that build values of type T
(because they don't have suitable dictionaries available).
So now I've taken the stupid context out. I simply deal with
it separately in the type checker on occurrences of a
constructor, either in an expression or in a pattern.
[May 2003: actually I think this decision could evasily be
reversed now, and probably should be. Generics could be
disabled for types with a stupid context; record updates now
(H98) needs the context too; etc. It's an unforced change, so
I'm leaving it for now --- but it does seem odd that the
wrapper doesn't include the stupid context.]
[July 04] With the advent of generalised data types, it's less obvious
what the "stupid context" is. Consider
C :: forall a. Ord a => a -> a -> T (Foo a)
Does the C constructor in Core contain the Ord dictionary? Yes, it must:
f :: T b -> Ordering
f = /\b. \x:T b.
case x of
C a (d:Ord a) (p:a) (q:a) -> compare d p q
Note that (Foo a) might not be an instance of Ord.
************************************************************************
* *
\subsection{Data constructors}
* *
************************************************************************
-}
-- | A data constructor
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose','ApiAnnotation.AnnComma'
-- For details on above see note [Api annotations] in ApiAnnotation
data DataCon
= MkData {
dcName :: Name, -- This is the name of the *source data con*
-- (see "Note [Data Constructor Naming]" above)
dcUnique :: Unique, -- Cached from Name
dcTag :: ConTag, -- ^ Tag, used for ordering 'DataCon's
-- Running example:
--
-- *** As declared by the user
-- data T a where
-- MkT :: forall x y. (x~y,Ord x) => x -> y -> T (x,y)
-- *** As represented internally
-- data T a where
-- MkT :: forall a. forall x y. (a~(x,y),x~y,Ord x) => x -> y -> T a
--
-- The next six fields express the type of the constructor, in pieces
-- e.g.
--
-- dcUnivTyVars = [a]
-- dcExTyVars = [x,y]
-- dcEqSpec = [a~(x,y)]
-- dcOtherTheta = [x~y, Ord x]
-- dcOrigArgTys = [x,y]
-- dcRepTyCon = T
dcVanilla :: Bool, -- True <=> This is a vanilla Haskell 98 data constructor
-- Its type is of form
-- forall a1..an . t1 -> ... tm -> T a1..an
-- No existentials, no coercions, nothing.
-- That is: dcExTyVars = dcEqSpec = dcOtherTheta = []
-- NB 1: newtypes always have a vanilla data con
-- NB 2: a vanilla constructor can still be declared in GADT-style
-- syntax, provided its type looks like the above.
-- The declaration format is held in the TyCon (algTcGadtSyntax)
dcUnivTyVars :: [TyVar], -- Universally-quantified type vars [a,b,c]
-- INVARIANT: length matches arity of the dcRepTyCon
--- result type of (rep) data con is exactly (T a b c)
dcExTyVars :: [TyVar], -- Existentially-quantified type vars
-- In general, the dcUnivTyVars are NOT NECESSARILY THE SAME AS THE TYVARS
-- FOR THE PARENT TyCon. With GADTs the data con might not even have
-- the same number of type variables.
-- [This is a change (Oct05): previously, vanilla datacons guaranteed to
-- have the same type variables as their parent TyCon, but that seems ugly.]
-- INVARIANT: the UnivTyVars and ExTyVars all have distinct OccNames
-- Reason: less confusing, and easier to generate IfaceSyn
dcEqSpec :: [(TyVar,Type)], -- Equalities derived from the result type,
-- _as written by the programmer_
-- This field allows us to move conveniently between the two ways
-- of representing a GADT constructor's type:
-- MkT :: forall a b. (a ~ [b]) => b -> T a
-- MkT :: forall b. b -> T [b]
-- Each equality is of the form (a ~ ty), where 'a' is one of
-- the universally quantified type variables
-- The next two fields give the type context of the data constructor
-- (aside from the GADT constraints,
-- which are given by the dcExpSpec)
-- In GADT form, this is *exactly* what the programmer writes, even if
-- the context constrains only universally quantified variables
-- MkT :: forall a b. (a ~ b, Ord b) => a -> T a b
dcOtherTheta :: ThetaType, -- The other constraints in the data con's type
-- other than those in the dcEqSpec
dcStupidTheta :: ThetaType, -- The context of the data type declaration
-- data Eq a => T a = ...
-- or, rather, a "thinned" version thereof
-- "Thinned", because the Report says
-- to eliminate any constraints that don't mention
-- tyvars free in the arg types for this constructor
--
-- INVARIANT: the free tyvars of dcStupidTheta are a subset of dcUnivTyVars
-- Reason: dcStupidTeta is gotten by thinning the stupid theta from the tycon
--
-- "Stupid", because the dictionaries aren't used for anything.
-- Indeed, [as of March 02] they are no longer in the type of
-- the wrapper Id, because that makes it harder to use the wrap-id
-- to rebuild values after record selection or in generics.
dcOrigArgTys :: [Type], -- Original argument types
-- (before unboxing and flattening of strict fields)
dcOrigResTy :: Type, -- Original result type, as seen by the user
-- NB: for a data instance, the original user result type may
-- differ from the DataCon's representation TyCon. Example
-- data instance T [a] where MkT :: a -> T [a]
-- The OrigResTy is T [a], but the dcRepTyCon might be :T123
-- Now the strictness annotations and field labels of the constructor
dcSrcBangs :: [HsSrcBang],
-- See Note [Bangs on data constructor arguments]
--
-- The [HsSrcBang] as written by the programmer.
--
-- Matches 1-1 with dcOrigArgTys
-- Hence length = dataConSourceArity dataCon
dcFields :: [FieldLabel],
-- Field labels for this constructor, in the
-- same order as the dcOrigArgTys;
-- length = 0 (if not a record) or dataConSourceArity.
-- The curried worker function that corresponds to the constructor:
-- It doesn't have an unfolding; the code generator saturates these Ids
-- and allocates a real constructor when it finds one.
dcWorkId :: Id,
-- Constructor representation
dcRep :: DataConRep,
-- Cached
dcRepArity :: Arity, -- == length dataConRepArgTys
dcSourceArity :: Arity, -- == length dcOrigArgTys
-- Result type of constructor is T t1..tn
dcRepTyCon :: TyCon, -- Result tycon, T
dcRepType :: Type, -- Type of the constructor
-- forall a x y. (a~(x,y), x~y, Ord x) =>
-- x -> y -> T a
-- (this is *not* of the constructor wrapper Id:
-- see Note [Data con representation] below)
-- Notice that the existential type parameters come *second*.
-- Reason: in a case expression we may find:
-- case (e :: T t) of
-- MkT x y co1 co2 (d:Ord x) (v:r) (w:F s) -> ...
-- It's convenient to apply the rep-type of MkT to 't', to get
-- forall x y. (t~(x,y), x~y, Ord x) => x -> y -> T t
-- and use that to check the pattern. Mind you, this is really only
-- used in CoreLint.
dcInfix :: Bool, -- True <=> declared infix
-- Used for Template Haskell and 'deriving' only
-- The actual fixity is stored elsewhere
dcPromoted :: Promoted TyCon -- The promoted TyCon if this DataCon is promotable
-- See Note [Promoted data constructors] in TyCon
}
deriving Data.Typeable.Typeable
data DataConRep
= NoDataConRep -- No wrapper
| DCR { dcr_wrap_id :: Id -- Takes src args, unboxes/flattens,
-- and constructs the representation
, dcr_boxer :: DataConBoxer
, dcr_arg_tys :: [Type] -- Final, representation argument types,
-- after unboxing and flattening,
-- and *including* all evidence args
, dcr_stricts :: [StrictnessMark] -- 1-1 with dcr_arg_tys
-- See also Note [Data-con worker strictness] in MkId.hs
, dcr_bangs :: [HsImplBang] -- The actual decisions made (including failures)
-- about the original arguments; 1-1 with orig_arg_tys
-- See Note [Bangs on data constructor arguments]
}
-- Algebraic data types always have a worker, and
-- may or may not have a wrapper, depending on whether
-- the wrapper does anything.
--
-- Data types have a worker with no unfolding
-- Newtypes just have a worker, which has a compulsory unfolding (just a cast)
-- _Neither_ the worker _nor_ the wrapper take the dcStupidTheta dicts as arguments
-- The wrapper (if it exists) takes dcOrigArgTys as its arguments
-- The worker takes dataConRepArgTys as its arguments
-- If the worker is absent, dataConRepArgTys is the same as dcOrigArgTys
-- The 'NoDataConRep' case is important
-- Not only is this efficient,
-- but it also ensures that the wrapper is replaced
-- by the worker (because it *is* the worker)
-- even when there are no args. E.g. in
-- f (:) x
-- the (:) *is* the worker.
-- This is really important in rule matching,
-- (We could match on the wrappers,
-- but that makes it less likely that rules will match
-- when we bring bits of unfoldings together.)
-------------------------
-- | Bangs on data constructor arguments as the user wrote them in the
-- source code.
--
-- (HsSrcBang _ SrcUnpack SrcLazy) and
-- (HsSrcBang _ SrcUnpack NoSrcStrict) (without StrictData) makes no sense, we
-- emit a warning (in checkValidDataCon) and treat it like
-- (HsSrcBang _ NoSrcUnpack SrcLazy)
data HsSrcBang =
HsSrcBang (Maybe SourceText) -- Note [Pragma source text] in BasicTypes
SrcUnpackedness
SrcStrictness
deriving (Data.Data, Data.Typeable)
-- | Bangs of data constructor arguments as generated by the compiler
-- after consulting HsSrcBang, flags, etc.
data HsImplBang
= HsLazy -- ^ Lazy field
| HsStrict -- ^ Strict but not unpacked field
| HsUnpack (Maybe Coercion)
-- ^ Strict and unpacked field
-- co :: arg-ty ~ product-ty HsBang
deriving (Data.Data, Data.Typeable)
-- | What strictness annotation the user wrote
data SrcStrictness = SrcLazy -- ^ Lazy, ie '~'
| SrcStrict -- ^ Strict, ie '!'
| NoSrcStrict -- ^ no strictness annotation
deriving (Eq, Data.Data, Data.Typeable)
-- | What unpackedness the user requested
data SrcUnpackedness = SrcUnpack -- ^ {-# UNPACK #-} specified
| SrcNoUnpack -- ^ {-# NOUNPACK #-} specified
| NoSrcUnpack -- ^ no unpack pragma
deriving (Eq, Data.Data, Data.Typeable)
-------------------------
-- StrictnessMark is internal only, used to indicate strictness
-- of the DataCon *worker* fields
data StrictnessMark = MarkedStrict | NotMarkedStrict
{- Note [Bangs on data constructor arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data T = MkT !Int {-# UNPACK #-} !Int Bool
When compiling the module, GHC will decide how to represent
MkT, depending on the optimisation level, and settings of
flags like -funbox-small-strict-fields.
Terminology:
* HsSrcBang: What the user wrote
Constructors: HsSrcBang
* HsImplBang: What GHC decided
Constructors: HsLazy, HsStrict, HsUnpack
* If T was defined in this module, MkT's dcSrcBangs field
records the [HsSrcBang] of what the user wrote; in the example
[ HsSrcBang _ NoSrcUnpack SrcStrict
, HsSrcBang _ SrcUnpack SrcStrict
, HsSrcBang _ NoSrcUnpack NoSrcStrictness]
* However, if T was defined in an imported module, the importing module
must follow the decisions made in the original module, regardless of
the flag settings in the importing module.
Also see Note [Bangs on imported data constructors] in MkId
* The dcr_bangs field of the dcRep field records the [HsImplBang]
If T was defined in this module, Without -O the dcr_bangs might be
[HsStrict, HsStrict, HsLazy]
With -O it might be
[HsStrict, HsUnpack _, HsLazy]
With -funbox-small-strict-fields it might be
[HsUnpack, HsUnpack _, HsLazy]
With -XStrictData it might be
[HsStrict, HsUnpack _, HsStrict]
Note [Data con representation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The dcRepType field contains the type of the representation of a contructor
This may differ from the type of the constructor *Id* (built
by MkId.mkDataConId) for two reasons:
a) the constructor Id may be overloaded, but the dictionary isn't stored
e.g. data Eq a => T a = MkT a a
b) the constructor may store an unboxed version of a strict field.
Here's an example illustrating both:
data Ord a => T a = MkT Int! a
Here
T :: Ord a => Int -> a -> T a
but the rep type is
Trep :: Int# -> a -> T a
Actually, the unboxed part isn't implemented yet!
************************************************************************
* *
\subsection{Instances}
* *
************************************************************************
-}
instance Eq DataCon where
a == b = getUnique a == getUnique b
a /= b = getUnique a /= getUnique b
instance Ord DataCon where
a <= b = getUnique a <= getUnique b
a < b = getUnique a < getUnique b
a >= b = getUnique a >= getUnique b
a > b = getUnique a > getUnique b
compare a b = getUnique a `compare` getUnique b
instance Uniquable DataCon where
getUnique = dcUnique
instance NamedThing DataCon where
getName = dcName
instance Outputable DataCon where
ppr con = ppr (dataConName con)
instance OutputableBndr DataCon where
pprInfixOcc con = pprInfixName (dataConName con)
pprPrefixOcc con = pprPrefixName (dataConName con)
instance Data.Data DataCon where
-- don't traverse?
toConstr _ = abstractConstr "DataCon"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "DataCon"
instance Outputable HsSrcBang where
ppr (HsSrcBang _ prag mark) = ppr prag <+> ppr mark
instance Outputable HsImplBang where
ppr HsLazy = ptext (sLit "Lazy")
ppr (HsUnpack Nothing) = ptext (sLit "Unpacked")
ppr (HsUnpack (Just co)) = ptext (sLit "Unpacked") <> parens (ppr co)
ppr HsStrict = ptext (sLit "StrictNotUnpacked")
instance Outputable SrcStrictness where
ppr SrcLazy = char '~'
ppr SrcStrict = char '!'
ppr NoSrcStrict = empty
instance Outputable SrcUnpackedness where
ppr SrcUnpack = ptext (sLit "{-# UNPACK #-}")
ppr SrcNoUnpack = ptext (sLit "{-# NOUNPACK #-}")
ppr NoSrcUnpack = empty
instance Outputable StrictnessMark where
ppr MarkedStrict = ptext (sLit "!")
ppr NotMarkedStrict = empty
instance Binary SrcStrictness where
put_ bh SrcLazy = putByte bh 0
put_ bh SrcStrict = putByte bh 1
put_ bh NoSrcStrict = putByte bh 2
get bh =
do h <- getByte bh
case h of
0 -> return SrcLazy
1 -> return SrcLazy
_ -> return NoSrcStrict
instance Binary SrcUnpackedness where
put_ bh SrcNoUnpack = putByte bh 0
put_ bh SrcUnpack = putByte bh 1
put_ bh NoSrcUnpack = putByte bh 2
get bh =
do h <- getByte bh
case h of
0 -> return SrcNoUnpack
1 -> return SrcUnpack
_ -> return NoSrcUnpack
-- | Compare strictness annotations
eqHsBang :: HsImplBang -> HsImplBang -> Bool
eqHsBang HsLazy HsLazy = True
eqHsBang HsStrict HsStrict = True
eqHsBang (HsUnpack Nothing) (HsUnpack Nothing) = True
eqHsBang (HsUnpack (Just c1)) (HsUnpack (Just c2))
= eqType (coercionType c1) (coercionType c2)
eqHsBang _ _ = False
isBanged :: HsImplBang -> Bool
isBanged (HsUnpack {}) = True
isBanged (HsStrict {}) = True
isBanged HsLazy = False
isSrcStrict :: SrcStrictness -> Bool
isSrcStrict SrcStrict = True
isSrcStrict _ = False
isSrcUnpacked :: SrcUnpackedness -> Bool
isSrcUnpacked SrcUnpack = True
isSrcUnpacked _ = False
isMarkedStrict :: StrictnessMark -> Bool
isMarkedStrict NotMarkedStrict = False
isMarkedStrict _ = True -- All others are strict
{-
************************************************************************
* *
\subsection{Construction}
* *
************************************************************************
-}
-- | Build a new data constructor
mkDataCon :: Name
-> Bool -- ^ Is the constructor declared infix?
-> Promoted TyConRepName -- ^ Whether promoted, and if so the TyConRepName
-- for the promoted TyCon
-> [HsSrcBang] -- ^ Strictness/unpack annotations, from user
-> [FieldLabel] -- ^ Field labels for the constructor,
-- if it is a record, otherwise empty
-> [TyVar] -- ^ Universally quantified type variables
-> [TyVar] -- ^ Existentially quantified type variables
-> [(TyVar,Type)] -- ^ GADT equalities
-> ThetaType -- ^ Theta-type occuring before the arguments proper
-> [Type] -- ^ Original argument types
-> Type -- ^ Original result type
-> TyCon -- ^ Representation type constructor
-> ThetaType -- ^ The "stupid theta", context of the data
-- declaration e.g. @data Eq a => T a ...@
-> Id -- ^ Worker Id
-> DataConRep -- ^ Representation
-> DataCon
-- Can get the tag from the TyCon
mkDataCon name declared_infix prom_info
arg_stricts -- Must match orig_arg_tys 1-1
fields
univ_tvs ex_tvs
eq_spec theta
orig_arg_tys orig_res_ty rep_tycon
stupid_theta work_id rep
-- Warning: mkDataCon is not a good place to check invariants.
-- If the programmer writes the wrong result type in the decl, thus:
-- data T a where { MkT :: S }
-- then it's possible that the univ_tvs may hit an assertion failure
-- if you pull on univ_tvs. This case is checked by checkValidDataCon,
-- so the error is detected properly... it's just that asaertions here
-- are a little dodgy.
= con
where
is_vanilla = null ex_tvs && null eq_spec && null theta
con = MkData {dcName = name, dcUnique = nameUnique name,
dcVanilla = is_vanilla, dcInfix = declared_infix,
dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs,
dcEqSpec = eq_spec,
dcOtherTheta = theta,
dcStupidTheta = stupid_theta,
dcOrigArgTys = orig_arg_tys, dcOrigResTy = orig_res_ty,
dcRepTyCon = rep_tycon,
dcSrcBangs = arg_stricts,
dcFields = fields, dcTag = tag, dcRepType = rep_ty,
dcWorkId = work_id,
dcRep = rep,
dcSourceArity = length orig_arg_tys,
dcRepArity = length rep_arg_tys,
dcPromoted = mb_promoted }
-- The 'arg_stricts' passed to mkDataCon are simply those for the
-- source-language arguments. We add extra ones for the
-- dictionary arguments right here.
tag = assoc "mkDataCon" (tyConDataCons rep_tycon `zip` [fIRST_TAG..]) con
rep_arg_tys = dataConRepArgTys con
rep_ty = mkForAllTys univ_tvs $ mkForAllTys ex_tvs $
mkFunTys rep_arg_tys $
mkTyConApp rep_tycon (mkTyVarTys univ_tvs)
mb_promoted -- See Note [Promoted data constructors] in TyCon
= case prom_info of
NotPromoted -> NotPromoted
Promoted rep_nm -> Promoted (mkPromotedDataCon con name rep_nm prom_kind prom_roles)
prom_kind = promoteType (dataConUserType con)
prom_roles = map (const Nominal) (univ_tvs ++ ex_tvs) ++
map (const Representational) orig_arg_tys
eqSpecPreds :: [(TyVar,Type)] -> ThetaType
eqSpecPreds spec = [ mkEqPred (mkTyVarTy tv) ty | (tv,ty) <- spec ]
-- | The 'Name' of the 'DataCon', giving it a unique, rooted identification
dataConName :: DataCon -> Name
dataConName = dcName
-- | The tag used for ordering 'DataCon's
dataConTag :: DataCon -> ConTag
dataConTag = dcTag
-- | The type constructor that we are building via this data constructor
dataConTyCon :: DataCon -> TyCon
dataConTyCon = dcRepTyCon
-- | The original type constructor used in the definition of this data
-- constructor. In case of a data family instance, that will be the family
-- type constructor.
dataConOrigTyCon :: DataCon -> TyCon
dataConOrigTyCon dc
| Just (tc, _) <- tyConFamInst_maybe (dcRepTyCon dc) = tc
| otherwise = dcRepTyCon dc
-- | The representation type of the data constructor, i.e. the sort
-- type that will represent values of this type at runtime
dataConRepType :: DataCon -> Type
dataConRepType = dcRepType
-- | Should the 'DataCon' be presented infix?
dataConIsInfix :: DataCon -> Bool
dataConIsInfix = dcInfix
-- | The universally-quantified type variables of the constructor
dataConUnivTyVars :: DataCon -> [TyVar]
dataConUnivTyVars = dcUnivTyVars
-- | The existentially-quantified type variables of the constructor
dataConExTyVars :: DataCon -> [TyVar]
dataConExTyVars = dcExTyVars
-- | Both the universal and existentiatial type variables of the constructor
dataConAllTyVars :: DataCon -> [TyVar]
dataConAllTyVars (MkData { dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs })
= univ_tvs ++ ex_tvs
-- | Equalities derived from the result type of the data constructor, as written
-- by the programmer in any GADT declaration
dataConEqSpec :: DataCon -> [(TyVar,Type)]
dataConEqSpec = dcEqSpec
-- | The *full* constraints on the constructor type
dataConTheta :: DataCon -> ThetaType
dataConTheta (MkData { dcEqSpec = eq_spec, dcOtherTheta = theta })
= eqSpecPreds eq_spec ++ theta
-- | Get the Id of the 'DataCon' worker: a function that is the "actual"
-- constructor and has no top level binding in the program. The type may
-- be different from the obvious one written in the source program. Panics
-- if there is no such 'Id' for this 'DataCon'
dataConWorkId :: DataCon -> Id
dataConWorkId dc = dcWorkId dc
-- | Get the Id of the 'DataCon' wrapper: a function that wraps the "actual"
-- constructor so it has the type visible in the source program: c.f. 'dataConWorkId'.
-- Returns Nothing if there is no wrapper, which occurs for an algebraic data constructor
-- and also for a newtype (whose constructor is inlined compulsorily)
dataConWrapId_maybe :: DataCon -> Maybe Id
dataConWrapId_maybe dc = case dcRep dc of
NoDataConRep -> Nothing
DCR { dcr_wrap_id = wrap_id } -> Just wrap_id
-- | Returns an Id which looks like the Haskell-source constructor by using
-- the wrapper if it exists (see 'dataConWrapId_maybe') and failing over to
-- the worker (see 'dataConWorkId')
dataConWrapId :: DataCon -> Id
dataConWrapId dc = case dcRep dc of
NoDataConRep-> dcWorkId dc -- worker=wrapper
DCR { dcr_wrap_id = wrap_id } -> wrap_id
-- | Find all the 'Id's implicitly brought into scope by the data constructor. Currently,
-- the union of the 'dataConWorkId' and the 'dataConWrapId'
dataConImplicitTyThings :: DataCon -> [TyThing]
dataConImplicitTyThings (MkData { dcWorkId = work, dcRep = rep })
= [AnId work] ++ wrap_ids
where
wrap_ids = case rep of
NoDataConRep -> []
DCR { dcr_wrap_id = wrap } -> [AnId wrap]
-- | The labels for the fields of this particular 'DataCon'
dataConFieldLabels :: DataCon -> [FieldLabel]
dataConFieldLabels = dcFields
-- | Extract the type for any given labelled field of the 'DataCon'
dataConFieldType :: DataCon -> FieldLabelString -> Type
dataConFieldType con label
= case find ((== label) . flLabel . fst) (dcFields con `zip` dcOrigArgTys con) of
Just (_, ty) -> ty
Nothing -> pprPanic "dataConFieldType" (ppr con <+> ppr label)
-- | Strictness/unpack annotations, from user; or, for imported
-- DataCons, from the interface file
-- The list is in one-to-one correspondence with the arity of the 'DataCon'
dataConSrcBangs :: DataCon -> [HsSrcBang]
dataConSrcBangs = dcSrcBangs
-- | Source-level arity of the data constructor
dataConSourceArity :: DataCon -> Arity
dataConSourceArity (MkData { dcSourceArity = arity }) = arity
-- | Gives the number of actual fields in the /representation/ of the
-- data constructor. This may be more than appear in the source code;
-- the extra ones are the existentially quantified dictionaries
dataConRepArity :: DataCon -> Arity
dataConRepArity (MkData { dcRepArity = arity }) = arity
-- | The number of fields in the /representation/ of the constructor
-- AFTER taking into account the unpacking of any unboxed tuple fields
dataConRepRepArity :: DataCon -> RepArity
dataConRepRepArity dc = typeRepArity (dataConRepArity dc) (dataConRepType dc)
-- | Return whether there are any argument types for this 'DataCon's original source type
isNullarySrcDataCon :: DataCon -> Bool
isNullarySrcDataCon dc = null (dcOrigArgTys dc)
-- | Return whether there are any argument types for this 'DataCon's runtime representation type
isNullaryRepDataCon :: DataCon -> Bool
isNullaryRepDataCon dc = dataConRepArity dc == 0
dataConRepStrictness :: DataCon -> [StrictnessMark]
-- ^ Give the demands on the arguments of a
-- Core constructor application (Con dc args)
dataConRepStrictness dc = case dcRep dc of
NoDataConRep -> [NotMarkedStrict | _ <- dataConRepArgTys dc]
DCR { dcr_stricts = strs } -> strs
dataConImplBangs :: DataCon -> [HsImplBang]
-- The implementation decisions about the strictness/unpack of each
-- source program argument to the data constructor
dataConImplBangs dc
= case dcRep dc of
NoDataConRep -> replicate (dcSourceArity dc) HsLazy
DCR { dcr_bangs = bangs } -> bangs
dataConBoxer :: DataCon -> Maybe DataConBoxer
dataConBoxer (MkData { dcRep = DCR { dcr_boxer = boxer } }) = Just boxer
dataConBoxer _ = Nothing
-- | The \"signature\" of the 'DataCon' returns, in order:
--
-- 1) The result of 'dataConAllTyVars',
--
-- 2) All the 'ThetaType's relating to the 'DataCon' (coercion, dictionary, implicit
-- parameter - whatever)
--
-- 3) The type arguments to the constructor
--
-- 4) The /original/ result type of the 'DataCon'
dataConSig :: DataCon -> ([TyVar], ThetaType, [Type], Type)
dataConSig (MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs,
dcEqSpec = eq_spec, dcOtherTheta = theta,
dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
= (univ_tvs ++ ex_tvs, eqSpecPreds eq_spec ++ theta, arg_tys, res_ty)
dataConInstSig
:: DataCon
-> [Type] -- Instantiate the *universal* tyvars with these types
-> ([TyVar], ThetaType, [Type]) -- Return instantiated existentials
-- theta and arg tys
-- ^ Instantantiate the universal tyvars of a data con,
-- returning the instantiated existentials, constraints, and args
dataConInstSig (MkData { dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs
, dcEqSpec = eq_spec, dcOtherTheta = theta
, dcOrigArgTys = arg_tys })
univ_tys
= (ex_tvs'
, substTheta subst (eqSpecPreds eq_spec ++ theta)
, substTys subst arg_tys)
where
univ_subst = zipTopTvSubst univ_tvs univ_tys
(subst, ex_tvs') = mapAccumL Type.substTyVarBndr univ_subst ex_tvs
-- | The \"full signature\" of the 'DataCon' returns, in order:
--
-- 1) The result of 'dataConUnivTyVars'
--
-- 2) The result of 'dataConExTyVars'
--
-- 3) The result of 'dataConEqSpec'
--
-- 4) The result of 'dataConDictTheta'
--
-- 5) The original argument types to the 'DataCon' (i.e. before
-- any change of the representation of the type)
--
-- 6) The original result type of the 'DataCon'
dataConFullSig :: DataCon
-> ([TyVar], [TyVar], [(TyVar,Type)], ThetaType, [Type], Type)
dataConFullSig (MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs,
dcEqSpec = eq_spec, dcOtherTheta = theta,
dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
= (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, res_ty)
dataConOrigResTy :: DataCon -> Type
dataConOrigResTy dc = dcOrigResTy dc
-- | The \"stupid theta\" of the 'DataCon', such as @data Eq a@ in:
--
-- > data Eq a => T a = ...
dataConStupidTheta :: DataCon -> ThetaType
dataConStupidTheta dc = dcStupidTheta dc
dataConUserType :: DataCon -> Type
-- ^ The user-declared type of the data constructor
-- in the nice-to-read form:
--
-- > T :: forall a b. a -> b -> T [a]
--
-- rather than:
--
-- > T :: forall a c. forall b. (c~[a]) => a -> b -> T c
--
-- NB: If the constructor is part of a data instance, the result type
-- mentions the family tycon, not the internal one.
dataConUserType (MkData { dcUnivTyVars = univ_tvs,
dcExTyVars = ex_tvs, dcEqSpec = eq_spec,
dcOtherTheta = theta, dcOrigArgTys = arg_tys,
dcOrigResTy = res_ty })
= mkForAllTys ((univ_tvs `minusList` map fst eq_spec) ++ ex_tvs) $
mkFunTys theta $
mkFunTys arg_tys $
res_ty
-- | Finds the instantiated types of the arguments required to construct a 'DataCon' representation
-- NB: these INCLUDE any dictionary args
-- but EXCLUDE the data-declaration context, which is discarded
-- It's all post-flattening etc; this is a representation type
dataConInstArgTys :: DataCon -- ^ A datacon with no existentials or equality constraints
-- However, it can have a dcTheta (notably it can be a
-- class dictionary, with superclasses)
-> [Type] -- ^ Instantiated at these types
-> [Type]
dataConInstArgTys dc@(MkData {dcUnivTyVars = univ_tvs,
dcExTyVars = ex_tvs}) inst_tys
= ASSERT2( length univ_tvs == length inst_tys
, ptext (sLit "dataConInstArgTys") <+> ppr dc $$ ppr univ_tvs $$ ppr inst_tys)
ASSERT2( null ex_tvs, ppr dc )
map (substTyWith univ_tvs inst_tys) (dataConRepArgTys dc)
-- | Returns just the instantiated /value/ argument types of a 'DataCon',
-- (excluding dictionary args)
dataConInstOrigArgTys
:: DataCon -- Works for any DataCon
-> [Type] -- Includes existential tyvar args, but NOT
-- equality constraints or dicts
-> [Type]
-- For vanilla datacons, it's all quite straightforward
-- But for the call in MatchCon, we really do want just the value args
dataConInstOrigArgTys dc@(MkData {dcOrigArgTys = arg_tys,
dcUnivTyVars = univ_tvs,
dcExTyVars = ex_tvs}) inst_tys
= ASSERT2( length tyvars == length inst_tys
, ptext (sLit "dataConInstOrigArgTys") <+> ppr dc $$ ppr tyvars $$ ppr inst_tys )
map (substTyWith tyvars inst_tys) arg_tys
where
tyvars = univ_tvs ++ ex_tvs
-- | Returns the argument types of the wrapper, excluding all dictionary arguments
-- and without substituting for any type variables
dataConOrigArgTys :: DataCon -> [Type]
dataConOrigArgTys dc = dcOrigArgTys dc
-- | Returns the arg types of the worker, including *all* evidence, after any
-- flattening has been done and without substituting for any type variables
dataConRepArgTys :: DataCon -> [Type]
dataConRepArgTys (MkData { dcRep = rep
, dcEqSpec = eq_spec
, dcOtherTheta = theta
, dcOrigArgTys = orig_arg_tys })
= case rep of
NoDataConRep -> ASSERT( null eq_spec ) theta ++ orig_arg_tys
DCR { dcr_arg_tys = arg_tys } -> arg_tys
-- | The string @package:module.name@ identifying a constructor, which is attached
-- to its info table and used by the GHCi debugger and the heap profiler
dataConIdentity :: DataCon -> [Word8]
-- We want this string to be UTF-8, so we get the bytes directly from the FastStrings.
dataConIdentity dc = bytesFS (unitIdFS (moduleUnitId mod)) ++
fromIntegral (ord ':') : bytesFS (moduleNameFS (moduleName mod)) ++
fromIntegral (ord '.') : bytesFS (occNameFS (nameOccName name))
where name = dataConName dc
mod = ASSERT( isExternalName name ) nameModule name
isTupleDataCon :: DataCon -> Bool
isTupleDataCon (MkData {dcRepTyCon = tc}) = isTupleTyCon tc
isUnboxedTupleCon :: DataCon -> Bool
isUnboxedTupleCon (MkData {dcRepTyCon = tc}) = isUnboxedTupleTyCon tc
-- | Vanilla 'DataCon's are those that are nice boring Haskell 98 constructors
isVanillaDataCon :: DataCon -> Bool
isVanillaDataCon dc = dcVanilla dc
classDataCon :: Class -> DataCon
classDataCon clas = case tyConDataCons (classTyCon clas) of
(dict_constr:no_more) -> ASSERT( null no_more ) dict_constr
[] -> panic "classDataCon"
dataConCannotMatch :: [Type] -> DataCon -> Bool
-- Returns True iff the data con *definitely cannot* match a
-- scrutinee of type (T tys)
-- where T is the dcRepTyCon for the data con
-- NB: look at *all* equality constraints, not only those
-- in dataConEqSpec; see Trac #5168
dataConCannotMatch tys con
| null inst_theta = False -- Common
| all isTyVarTy tys = False -- Also common
| otherwise = typesCantMatch (concatMap predEqs inst_theta)
where
(_, inst_theta, _) = dataConInstSig con tys
-- TODO: could gather equalities from superclasses too
predEqs pred = case classifyPredType pred of
EqPred NomEq ty1 ty2 -> [(ty1, ty2)]
_ -> []
{-
************************************************************************
* *
Promotion
These functions are here becuase
- isPromotableTyCon calls dataConFullSig
- mkDataCon calls promoteType
- It's nice to keep the promotion stuff together
* *
************************************************************************
Note [The overall promotion story]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here is the overall plan.
* Compared to a TyCon T, the promoted 'T has
same Name (and hence Unique)
same TyConRepName
In future the two will collapse into one anyhow.
* Compared to a DataCon K, the promoted 'K (a type constructor) has
same Name (and hence Unique)
But it has a fresh TyConRepName; after all, the DataCon doesn't have
a TyConRepName at all. (See Note [Grand plan for Typeable] in TcTypeable
for TyConRepName.)
Why does 'K have the same unique as K? It's acceptable because we don't
mix types and terms, so we won't get them confused. And it's helpful mainly
so that we know when to print 'K as a qualified name in error message. The
PrintUnqualified stuff depends on whether K is lexically in scope.. but 'K
never is!
* It follows that the tick-mark (eg 'K) is not part of the Occ name of
either promoted data constructors or type constructors. Instead,
pretty-printing: the pretty-printer prints a tick in front of
- promoted DataCons (always)
- promoted TyCons (with -dppr-debug)
See TyCon.pprPromotionQuote
* For a promoted data constructor K, the pipeline goes like this:
User writes (in a type): K or 'K
Parser produces OccName: K{tc} or K{d}, respectively
Renamer makes Name: M.K{d}_r62 (i.e. same unique as DataCon K)
and K{tc} has been turned into K{d}
provided it was unambiguous
Typechecker makes TyCon: PromotedDataCon MK{d}_r62
Note [Checking whether a group is promotable]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We only want to promote a TyCon if all its data constructors
are promotable; it'd be very odd to promote some but not others.
But the data constructors may mention this or other TyCons.
So we treat the recursive uses as all OK (ie promotable) and
do one pass to check that each TyCon is promotable.
Currently type synonyms are not promotable, though that
could change.
-}
promoteDataCon :: DataCon -> TyCon
promoteDataCon (MkData { dcPromoted = Promoted tc }) = tc
promoteDataCon dc = pprPanic "promoteDataCon" (ppr dc)
promoteDataCon_maybe :: DataCon -> Promoted TyCon
promoteDataCon_maybe (MkData { dcPromoted = mb_tc }) = mb_tc
computeTyConPromotability :: NameSet -> TyCon -> Bool
computeTyConPromotability rec_tycons tc
= isAlgTyCon tc -- Only algebraic; not even synonyms
-- (we could reconsider the latter)
&& ok_kind (tyConKind tc)
&& case algTyConRhs tc of
DataTyCon { data_cons = cs } -> all ok_con cs
TupleTyCon { data_con = c } -> ok_con c
NewTyCon { data_con = c } -> ok_con c
AbstractTyCon {} -> False
where
ok_kind kind = all isLiftedTypeKind args && isLiftedTypeKind res
where -- Checks for * -> ... -> * -> *
(args, res) = splitKindFunTys kind
-- See Note [Promoted data constructors] in TyCon
ok_con con = all (isLiftedTypeKind . tyVarKind) ex_tvs
&& null eq_spec -- No constraints
&& null theta
&& all (isPromotableType rec_tycons) orig_arg_tys
where
(_, ex_tvs, eq_spec, theta, orig_arg_tys, _) = dataConFullSig con
isPromotableType :: NameSet -> Type -> Bool
-- Must line up with promoteType
-- But the function lives here because we must treat the
-- *recursive* tycons as promotable
isPromotableType rec_tcs con_arg_ty
= go con_arg_ty
where
go (TyConApp tc tys) = tys `lengthIs` tyConArity tc
&& (tyConName tc `elemNameSet` rec_tcs
|| isPromotableTyCon tc)
&& all go tys
go (FunTy arg res) = go arg && go res
go (TyVarTy {}) = True
go _ = False
{-
Note [Promoting a Type to a Kind]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppsoe we have a data constructor D
D :: forall (a:*). Maybe a -> T a
We promote this to be a type constructor 'D:
'D :: forall (k:BOX). 'Maybe k -> 'T k
The transformation from type to kind is done by promoteType
* Convert forall (a:*) to forall (k:BOX), and substitute
* Ensure all foralls are at the top (no higher rank stuff)
* Ensure that all type constructors mentioned (Maybe and T
in the example) are promotable; that is, they have kind
* -> ... -> * -> *
-}
-- | Promotes a type to a kind.
-- Assumes the argument satisfies 'isPromotableType'
promoteType :: Type -> Kind
promoteType ty
= mkForAllTys kvs (go rho)
where
(tvs, rho) = splitForAllTys ty
kvs = [ mkKindVar (tyVarName tv) superKind | tv <- tvs ]
env = zipVarEnv tvs kvs
go (TyConApp tc tys) | Promoted prom_tc <- promotableTyCon_maybe tc
= mkTyConApp prom_tc (map go tys)
go (FunTy arg res) = mkArrowKind (go arg) (go res)
go (TyVarTy tv) | Just kv <- lookupVarEnv env tv
= TyVarTy kv
go _ = panic "promoteType" -- Argument did not satisfy isPromotableType
promoteKind :: Kind -> SuperKind
-- Promote the kind of a type constructor
-- from (* -> * -> *) to (BOX -> BOX -> BOX)
promoteKind (TyConApp tc [])
| tc `hasKey` liftedTypeKindTyConKey = superKind
promoteKind (FunTy arg res) = FunTy (promoteKind arg) (promoteKind res)
promoteKind k = pprPanic "promoteKind" (ppr k)
{-
************************************************************************
* *
\subsection{Splitting products}
* *
************************************************************************
-}
-- | Extract the type constructor, type argument, data constructor and it's
-- /representation/ argument types from a type if it is a product type.
--
-- Precisely, we return @Just@ for any type that is all of:
--
-- * Concrete (i.e. constructors visible)
--
-- * Single-constructor
--
-- * Not existentially quantified
--
-- Whether the type is a @data@ type or a @newtype@
splitDataProductType_maybe
:: Type -- ^ A product type, perhaps
-> Maybe (TyCon, -- The type constructor
[Type], -- Type args of the tycon
DataCon, -- The data constructor
[Type]) -- Its /representation/ arg types
-- Rejecting existentials is conservative. Maybe some things
-- could be made to work with them, but I'm not going to sweat
-- it through till someone finds it's important.
splitDataProductType_maybe ty
| Just (tycon, ty_args) <- splitTyConApp_maybe ty
, Just con <- isDataProductTyCon_maybe tycon
= Just (tycon, ty_args, con, dataConInstArgTys con ty_args)
| otherwise
= Nothing
{-
************************************************************************
* *
Building an algebraic data type
* *
************************************************************************
buildAlgTyCon is here because it is called from TysWiredIn, which can
depend on this module, but not on BuildTyCl.
-}
buildAlgTyCon :: Name
-> [TyVar] -- ^ Kind variables and type variables
-> [Role]
-> Maybe CType
-> ThetaType -- ^ Stupid theta
-> AlgTyConRhs
-> RecFlag
-> Bool -- ^ True <=> this TyCon is promotable
-> Bool -- ^ True <=> was declared in GADT syntax
-> AlgTyConFlav
-> TyCon
buildAlgTyCon tc_name ktvs roles cType stupid_theta rhs
is_rec is_promotable gadt_syn parent
= tc
where
kind = mkPiKinds ktvs liftedTypeKind
-- tc and mb_promoted_tc are mutually recursive
tc = mkAlgTyCon tc_name kind ktvs roles cType stupid_theta
rhs parent is_rec gadt_syn
mb_promoted_tc
mb_promoted_tc
| is_promotable = Promoted (mkPromotedTyCon tc (promoteKind kind))
| otherwise = NotPromoted
| AlexanderPankiv/ghc | compiler/basicTypes/DataCon.hs | bsd-3-clause | 51,933 | 0 | 19 | 15,151 | 5,866 | 3,310 | 2,556 | 490 | 4 |
{-# LANGUAGE BangPatterns #-}
module Randomish
( randomishInts
, randomishDoubles)
where
import Data.Word
import Data.Vector.Unboxed (Vector)
import qualified Data.Vector.Unboxed.Mutable as MV
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Generic as G
-- | Use the "minimal standard" Lehmer generator to quickly generate some random
-- numbers with reasonable statistical properties. By "reasonable" we mean good
-- enough for games and test data, but not cryptography or anything where the
-- quality of the randomness really matters.
--
-- From "Random Number Generators: Good ones are hard to find"
-- Stephen K. Park and Keith W. Miller.
-- Communications of the ACM, Oct 1988, Volume 31, Number 10.
--
randomishInts
:: Int -- Length of vector.
-> Int -- Minumum value in output.
-> Int -- Maximum value in output.
-> Int -- Random seed.
-> Vector Int -- Vector of random numbers.
randomishInts !len !valMin' !valMax' !seed'
= let -- a magic number (don't change it)
multiplier :: Word64
multiplier = 16807
-- a merzenne prime (don't change it)
modulus :: Word64
modulus = 2^(31 :: Integer) - 1
-- if the seed is 0 all the numbers in the sequence are also 0.
seed
| seed' == 0 = 1
| otherwise = seed'
!valMin = fromIntegral valMin'
!valMax = fromIntegral valMax' + 1
!range = valMax - valMin
{-# INLINE f #-}
f x = multiplier * x `mod` modulus
in G.create
$ do
vec <- MV.new len
let go !ix !x
| ix == len = return ()
| otherwise
= do let x' = f x
MV.write vec ix $ fromIntegral $ (x `mod` range) + valMin
go (ix + 1) x'
go 0 (f $ f $ f $ fromIntegral seed)
return vec
-- | Generate some randomish doubles with terrible statistical properties.
-- This is good enough for test data, but not much else.
randomishDoubles
:: Int -- Length of vector
-> Double -- Minimum value in output
-> Double -- Maximum value in output
-> Int -- Random seed.
-> Vector Double -- Vector of randomish doubles.
randomishDoubles !len !valMin !valMax !seed
= let range = valMax - valMin
mx = 2^(30 :: Integer) - 1
mxf = fromIntegral mx
ints = randomishInts len 0 mx seed
in V.map (\n -> valMin + (fromIntegral n / mxf) * range) ints
| agremm/Matryoshka | examples/lib/Randomish.hs | bsd-3-clause | 2,267 | 87 | 11 | 515 | 519 | 300 | 219 | 52 | 1 |
{-# LANGUAGE StandaloneKindSignatures #-}
module SAKS_Fail007 where
import Data.Kind (Type)
type May a :: Type
data May a = Nay | Yay a
| sdiehl/ghc | testsuite/tests/saks/should_fail/saks_fail007.hs | bsd-3-clause | 139 | 0 | 6 | 26 | 35 | 23 | 12 | -1 | -1 |
module HN.Blaze
(module Text.Blaze.Extra
,module Text.Blaze.Html5
,module Text.Blaze.Html5.Attributes
,module Text.Blaze.Renderer.Text
,module Text.Blaze.Linkify
,module Text.Blaze.Pagination
,module Text.Blaze.Bootstrap
)
where
import Text.Blaze.Extra
import Text.Blaze.Html5 hiding (output,map,i,title,cite,style,summary,object,footer)
import Text.Blaze.Html5.Attributes hiding (label,span,cite,form,summary)
import Text.Blaze.Renderer.Text
import Text.Blaze.Linkify
import Text.Blaze.Pagination
import Text.Blaze.Bootstrap
| jwaldmann/haskellnews | src/HN/Blaze.hs | bsd-3-clause | 547 | 0 | 5 | 57 | 151 | 104 | 47 | 15 | 0 |
{-# LANGUAGE MagicHash #-}
{-# OPTIONS_GHC -Werror #-}
-- Trac #2806
module Foo where
import GHC.Base
foo :: Int
foo = 3
where (I# _x) = 4
| hvr/jhc | regress/tests/1_typecheck/4_fail/ghc/T2806.hs | mit | 149 | 0 | 8 | 37 | 36 | 22 | 14 | 7 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ConstraintKinds #-}
-- | Tag a Binary instance with the stack version number to ensure we're
-- reading a compatible format.
module Data.Binary.VersionTagged
( taggedDecodeOrLoad
, taggedEncodeFile
, Binary (..)
, BinarySchema
, HasStructuralInfo
, HasSemanticVersion
, decodeFileOrFailDeep
, NFData (..)
) where
import Control.DeepSeq (NFData (..))
import Control.Exception (Exception)
import Control.Monad.Catch (MonadThrow (..))
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Logger
import Data.Binary (Binary (..))
import Data.Binary.Get (ByteOffset)
import Data.Binary.Tagged (HasStructuralInfo, HasSemanticVersion)
import qualified Data.Binary.Tagged as BinaryTagged
import Data.Monoid ((<>))
import Data.Typeable (Typeable)
import Control.Exception.Enclosed (tryAnyDeep)
import Path
import Path.IO (ensureDir)
import qualified Data.Text as T
type BinarySchema a = (Binary a, NFData a, HasStructuralInfo a, HasSemanticVersion a)
-- | Write to the given file, with a binary-tagged tag.
taggedEncodeFile :: (BinarySchema a, MonadIO m)
=> Path Abs File
-> a
-> m ()
taggedEncodeFile fp x = liftIO $ do
ensureDir (parent fp)
BinaryTagged.taggedEncodeFile (toFilePath fp) x
-- | Read from the given file. If the read fails, run the given action and
-- write that back to the file. Always starts the file off with the version
-- tag.
taggedDecodeOrLoad :: (BinarySchema a, MonadIO m, MonadLogger m)
=> Path Abs File
-> m a
-> m a
taggedDecodeOrLoad fp mx = do
let fpt = T.pack (toFilePath fp)
$logDebug $ "Trying to decode " <> fpt
eres <- decodeFileOrFailDeep fp
case eres of
Left _ -> do
$logDebug $ "Failure decoding " <> fpt
x <- mx
taggedEncodeFile fp x
return x
Right x -> do
$logDebug $ "Success decoding " <> fpt
return x
-- | Ensure that there are no lurking exceptions deep inside the parsed
-- value... because that happens unfortunately. See
-- https://github.com/commercialhaskell/stack/issues/554
decodeFileOrFailDeep :: (BinarySchema a, MonadIO m, MonadThrow n)
=> Path loc File
-> m (n a)
decodeFileOrFailDeep fp = liftIO $ fmap (either throwM return) $ tryAnyDeep $ do
eres <- BinaryTagged.taggedDecodeFileOrFail (toFilePath fp)
case eres of
Left (offset, str) -> throwM $ DecodeFileFailure (toFilePath fp) offset str
Right x -> return x
data DecodeFileFailure = DecodeFileFailure FilePath ByteOffset String
deriving Typeable
instance Show DecodeFileFailure where
show (DecodeFileFailure fp offset str) = concat
[ "Decoding of "
, fp
, " failed at offset "
, show offset
, ": "
, str
]
instance Exception DecodeFileFailure
| phadej/stack | src/Data/Binary/VersionTagged.hs | bsd-3-clause | 3,108 | 0 | 14 | 785 | 718 | 387 | 331 | 73 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
module BinaryDerive where
import Data.Generics
import Data.List
deriveM :: (Typeable a, Data a) => a -> IO ()
deriveM (a :: a) = mapM_ putStrLn . lines $ derive (undefined :: a)
derive :: (Typeable a, Data a) => a -> String
derive x =
"instance " ++ context ++ "Binary " ++ inst ++ " where\n" ++
concat putDefs ++ getDefs
where
context
| nTypeChildren > 0 =
wrap (join ", " (map ("Binary "++) typeLetters)) ++ " => "
| otherwise = ""
inst = wrap $ tyConString typeName ++ concatMap (" "++) typeLetters
wrap x = if nTypeChildren > 0 then "("++x++")" else x
join sep lst = concat $ intersperse sep lst
nTypeChildren = length typeChildren
typeLetters = take nTypeChildren manyLetters
manyLetters = map (:[]) ['a'..'z']
(typeName,typeChildren) = splitTyConApp (typeOf x)
constrs :: [(Int, (String, Int))]
constrs = zip [0..] $ map gen $ dataTypeConstrs (dataTypeOf x)
gen con = ( showConstr con
, length $ gmapQ undefined $ fromConstr con `asTypeOf` x
)
putDefs = map ((++"\n") . putDef) constrs
putDef (n, (name, ps)) =
let wrap = if ps /= 0 then ("("++) . (++")") else id
pattern = name ++ concatMap (' ':) (take ps manyLetters)
in
" put " ++ wrap pattern ++" = "
++ concat [ "putWord8 " ++ show n | length constrs > 1 ]
++ concat [ " >> " | length constrs > 1 && ps > 0 ]
++ concat [ "return ()" | length constrs == 1 && ps == 0 ]
++ join " >> " (map ("put "++) (take ps manyLetters))
getDefs =
(if length constrs > 1
then " get = do\n tag_ <- getWord8\n case tag_ of\n"
else " get =")
++ concatMap ((++"\n")) (map getDef constrs) ++
(if length constrs > 1
then " _ -> fail \"no decoding\""
else ""
)
getDef (n, (name, ps)) =
let wrap = if ps /= 0 then ("("++) . (++")") else id
in
concat [ " " ++ show n ++ " ->" | length constrs > 1 ]
++ concatMap (\x -> " get >>= \\"++x++" ->") (take ps manyLetters)
++ " return "
++ wrap (name ++ concatMap (" "++) (take ps manyLetters))
| ezyang/binary | tools/derive/BinaryDerive.hs | bsd-3-clause | 2,273 | 4 | 18 | 739 | 863 | 454 | 409 | 48 | 6 |
{-# Language TemplateHaskell #-}
{-# Language DisambiguateRecordFields #-}
module T12130 where
import T12130a hiding (Block)
b = $(block)
| olsner/ghc | testsuite/tests/th/T12130.hs | bsd-3-clause | 141 | 0 | 6 | 21 | 24 | 16 | 8 | 5 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedLists#-}
module Tests.Math.Hclaws.Systems.ShallowWater (
tests
) where
import Test.Tasty (TestTree, testGroup)
import qualified Test.Tasty.QuickCheck as QC
import qualified Test.Tasty.SmallCheck as SC
import qualified Test.Tasty.HUnit as HU
import Test.Curves
import qualified Math.Hclaws.Systems.ShallowWater as SW
tests :: TestTree
tests =
testGroup "Math.Hclaws.Systems.ShallowWater"
[properties, unitTests]
properties :: TestTree
properties = testGroup "Properties"
[
]
unitTests :: TestTree
unitTests = testGroup "Unit Tests" $
[ waveFanTestGroup SW.solution1 SW.system "manual solution 1"
, waveFanTestGroup SW.solution2 SW.system "computed solution 2"
, waveFanTestGroup SW.solution3 SW.system "computed solution 3"
, waveFanTestGroup SW.solution4 SW.system "computed solution 4"
, waveFanTestGroup SW.solution5 SW.system "computed solution 5"
]
| mikebenfield/hclaws | test/Tests/Math/Hclaws/Systems/ShallowWater.hs | isc | 958 | 0 | 8 | 157 | 196 | 117 | 79 | 24 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
{- |
Module : Database.Couch.Explicit.Design
Description : Design Document-oriented requests to CouchDB, with explicit parameters
Copyright : Copyright (c) 2015, Michael Alan Dorman
License : MIT
Maintainer : mdorman@jaunder.io
Stability : experimental
Portability : POSIX
This module is intended to be @import qualified@. /No attempt/ has been made to keep names of types or functions from clashing with obvious or otherwise commonly-used names, or even other modules within this package.
The functions here are derived from (and presented in the same order as) the <http://docs.couchdb.org/en/1.6.1/api/ddoc/common.html Design Document API documentation>. For each function, we attempt to link back to the original documentation, as well as make a notation as to how complete and correct we feel our implementation is.
Each function takes a 'Database.Couch.Types.Context'---which, among other things, holds the name of the database---as its final parameter, and returns a 'Database.Couch.Types.Result'.
-}
module Database.Couch.Explicit.Design where
import Control.Monad.IO.Class (MonadIO)
import Data.Aeson (FromJSON, ToJSON, object,
toJSON)
import Data.Function (($))
import Data.Maybe (Maybe (Nothing))
import qualified Database.Couch.Explicit.DocBase as Base (accessBase, copy,
delete, get, meta,
put)
import Database.Couch.Internal (standardRequest)
import Database.Couch.RequestBuilder (RequestBuilder, addPath,
selectDoc, setJsonBody,
setMethod, setQueryParam)
import Database.Couch.Types (Context, DocId, DocRev,
ModifyDoc, Result,
RetrieveDoc, ViewParams,
toQueryParameters)
{- | <http://docs.couchdb.org/en/1.6.1/api/document/common.html#head--db-_design-ddoc Get the size and revision of the specified design document>
The return value is an object that should only contain the keys "rev" and "size", that can be easily parsed into a pair of (DocRev, Int):
>>> (,) <$> (getKey "rev" >>= toOutputType) <*> (getKey "size" >>= toOutputType)
If the specified DocRev matches, returns a JSON Null, otherwise a JSON value for the document.
Status: __Complete__ -}
meta :: (FromJSON a, MonadIO m)
=> RetrieveDoc -- ^ Parameters for the HEAD request
-> DocId -- ^ The ID of the design document
-> Maybe DocRev -- ^ A desired revision
-> Context
-> m (Result a)
meta = Base.meta "_design"
{- | <http://docs.couchdb.org/en/1.6.1/api/document/common.html#get--db-_design-ddoc Get the specified design document>
The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value':
>>> value :: Result Value <- Design.get "pandas" Nothing ctx
If the specified DocRev matches, returns a JSON Null, otherwise a JSON value for the document.
Status: __Complete__ -}
get :: (FromJSON a, MonadIO m)
=> RetrieveDoc -- ^ Parameters for the HEAD request
-> DocId -- ^ The ID of the design document
-> Maybe DocRev -- ^ A desired revision
-> Context
-> m (Result a)
get = Base.get "_design"
{- | <http://docs.couchdb.org/en/1.6.1/api/document/common.html#put--db-_design-ddoc Create or replace the specified design document>
The return value is an object that can hold "id" and "rev" keys, but if you don't need those values, it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator:
>>> value :: Result Bool <- Design.put modifyDoc "pandas" Nothing SomeValue ctx >>= asBool
Status: __Complete__ -}
put :: (FromJSON a, MonadIO m, ToJSON b)
=> ModifyDoc -- ^ Parameters for the request
-> DocId -- ^ The ID of the design document
-> Maybe DocRev -- ^ A desired revision
-> b
-> Context
-> m (Result a)
put = Base.put "_design"
{- | <http://docs.couchdb.org/en/1.6.1/api/document/common.html#delete--db-_design-ddoc Delete the specified design document>
The return value is an object that can hold "id" and "rev" keys, but if you don't need those values, it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator:
>>> value :: Result Bool <- Design.delete modifyDoc "pandas" Nothing ctx >>= asBool
Status: __Complete__ -}
delete :: (FromJSON a, MonadIO m)
=> ModifyDoc -- ^ Parameters for the request
-> DocId -- ^ The ID of the design document
-> Maybe DocRev -- ^ A desired revision
-> Context
-> m (Result a)
delete = Base.delete "_design"
{- | <http://docs.couchdb.org/en/1.6.1/api/document/common.html#copy--db-_design-ddoc Copy the specified design document>
The return value is an object that can hold "id" and "rev" keys, but if you don't need those values, it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator:
>>> value :: Result Bool <- Design.delete modifyDoc "pandas" Nothing ctx >>= asBool
Status: __Complete__ -}
copy :: (FromJSON a, MonadIO m)
=> ModifyDoc -- ^ Parameters for the request
-> DocId -- ^ The ID of the design document
-> Maybe DocRev -- ^ A desired revision
-> DocId
-> Context
-> m (Result a)
copy = Base.copy "_design"
{- | <http://docs.couchdb.org/en/1.6.1/api/ddoc/common.html#get--db-_design-ddoc-_info Get information on a design document>
The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value':
>>> value :: Result Value <- Design.info "pandas" ctx
Status: __Complete__ -}
info :: (FromJSON a, MonadIO m)
=> DocId -- ^ The ID of the design document
-> Context
-> m (Result a)
info doc =
standardRequest request
where
request = do
Base.accessBase "_design" doc Nothing
addPath "_info"
{- | <http://docs.couchdb.org/en/1.6.1/api/ddoc/views.html#get--db-_design-ddoc-_view-view Get a list of all database documents>
The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value':
>>> value :: Result Value <- Design.allDocs viewParams "pandas" "counter" ctx
Status: __Complete__ -}
allDocs :: (FromJSON a, MonadIO m)
=> ViewParams -- ^ Parameters for the request
-> DocId -- ^ The ID of the design document
-> DocId -- ^ The ID of the view
-> Context
-> m (Result a)
allDocs params doc view =
standardRequest $ viewBase params doc view
{- | <http://docs.couchdb.org/en/1.6.1/api/ddoc/views.html#post--db-_design-ddoc-_view-view Get a list of some database documents>
The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value':
>>> value :: Result Value <- Design.someDocs viewParams "pandas" "counter" ["a", "b"] ctx
Status: __Complete__ -}
someDocs :: (FromJSON a, MonadIO m)
=> ViewParams -- ^ Parameters for the request
-> DocId -- ^ The ID of the design document
-> DocId -- ^ The ID of the view
-> [DocId] -- ^ The IDs of the documents of interest
-> Context
-> m (Result a)
someDocs params doc view ids =
standardRequest request
where
request = do
setMethod "POST"
viewBase params doc view
let docs = object [("keys", toJSON ids)]
setJsonBody docs
-- * Internal combinators
-- | Base bits for all view queries
viewBase :: ViewParams -> DocId -> DocId -> RequestBuilder ()
viewBase params doc view = do
Base.accessBase "_design" doc Nothing
addPath "_view"
selectDoc view
setQueryParam $ toQueryParameters params
| mdorman/couch-simple | src/lib/Database/Couch/Explicit/Design.hs | mit | 8,043 | 0 | 15 | 2,008 | 836 | 456 | 380 | 94 | 1 |
{-# LANGUAGE BangPatterns #-}
module Feitoria.Types where
import Codec.MIME.Type
import qualified Data.ByteString as B
import Data.Time
import Data.Word
import Foreign.Ptr
import qualified Data.Text as T
import qualified Data.Vector as V
--data MMapTable = MMapTable {
-- mmapTblHeader :: !TableHeader
-- , mmapTblPtr :: !(Ptr ())
-- , mmapTblCols :: [MMapColumn]
-- , mmapTblNumColumns :: !Word64
-- , mmapTblNumRecords :: !Word64
-- , mmapTblColTblOffset :: !Int
-- , mmapTblStringLitOffset :: !Int
-- , mmapTblArrayLitOffset :: !Int
-- , mmapTblBinaryLitOffset :: !Int
-- }
--
--data MMapColumn = MMapColumn {
-- mmapHeader :: !ColumnHeader
-- , mmapOffset :: !Int
-- }
data CellType = CellTypeUInt
| CellTypeInt
| CellTypeDouble
| CellTypeDateTime
| CellTypeString
| CellTypeBinary MIMEType
| CellTypeBoolean
deriving (Eq, Ord, Show)
type Cell = Maybe CellData
data CellData = CellDataUInt Word64
| CellDataInt Int
| CellDataDouble Double
| CellDataDateTime UTCTime
| CellDataBoolean Bool
| CellDataString T.Text
| CellDataBinary B.ByteString
| CellDataArray (V.Vector CellData)
deriving (Eq, Ord, Show)
| MadSciGuys/feitoria | src/Feitoria/Types.hs | mit | 1,412 | 0 | 9 | 460 | 190 | 122 | 68 | 27 | 0 |
{-# htermination addToFM_C :: (Ord a, Ord k) => (b -> b -> b) -> FiniteMap (Either a k) b -> (Either a k) -> b -> FiniteMap (Either a k) b #-}
import FiniteMap
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/FiniteMap_addToFM_C_10.hs | mit | 160 | 0 | 3 | 35 | 5 | 3 | 2 | 1 | 0 |
module EntityWrapper.Schema
( module EntityWrapper.Schema
, module EntityWrapper.Schema.Virus
) where
import qualified Database.Orville.PostgreSQL as O
import EntityWrapper.Schema.Virus
schema :: O.SchemaDefinition
schema = [O.Table virusTable]
| flipstone/orville | orville-postgresql/test/EntityWrapper/Schema.hs | mit | 254 | 0 | 7 | 33 | 56 | 36 | 20 | 7 | 1 |
module Typing.Util where
import Typing.Env
import Typing.Kinds
import {-# SOURCE #-} Typing.Stmt
import Typing.Substitution
import Typing.Subtyping
import Typing.TypeError
import Typing.Types
import Util.Error
import Absyn.Base
import Absyn.Meta
import qualified Absyn.Untyped as U
import qualified Absyn.Typed as T
import Control.Monad (when)
import Data.Maybe (fromMaybe)
(<:!) :: Type -> Type -> Tc ()
actualTy <:! expectedTy =
when (not $ actualTy <: expectedTy) (throwError $ TypeError expectedTy actualTy)
assertKindStar :: Type -> Tc ()
assertKindStar ty =
let kind = kindOf ty
in when (kind /= Star) (throwError $ KindError ty Star kind)
resolveId :: U.Param -> Tc T.Id
resolveId (n, ty) = (,) n <$> resolveType ty
resolveType :: U.Type -> Tc Type
resolveType (U.TName v) =
lookupType v
resolveType (U.TArrow params ret) = do
params' <- mapM resolveType params
ret' <- resolveType ret
return $ Fun [] params' ret'
resolveType (U.TRecord fieldsTy) = do
fieldsTy' <- mapM resolveId fieldsTy
return $ Rec fieldsTy'
resolveType (U.TApp t1 t2) = do
t1' <- resolveType t1
t2' <- mapM resolveType t2
case t1' of
TyAbs params ty -> do
when (length params /= length t2) $ throwError TypeArityMismatch
return $ applySubst (zipSubst params t2') ty
_ -> return $ TyApp t1' t2'
resolveType U.TVoid = return void
resolveType U.TPlaceholder = undefined
resolveGenericBounds :: [(String, [String])] -> Tc [(String, [Intf])]
resolveGenericBounds gen =
mapM resolve gen
where
resolve (name, bounds) = do
bounds' <- mapM resolveConstraint bounds
return (name, bounds')
resolveConstraint intf = do
lookupInterface intf
resolveGenericVars :: [(String, [Intf])] -> Tc [BoundVar]
resolveGenericVars generics =
mapM aux generics
where
aux (g, bounds) = do
g' <- newVar g
return (g', bounds)
addGenerics :: [BoundVar] -> Tc ()
addGenerics generics =
mapM_ aux generics
where
aux (var, bounds) = do
insertType (varName var) (Var var bounds)
defaultBounds :: [a] -> [(a, [b])]
defaultBounds = map (flip (,) [])
i_fn :: U.Function -> Tc (T.Function, Type)
i_fn (meta :< fn) = do
gen' <- resolveGenericBounds (generics fn)
genericVars <- resolveGenericVars gen'
m <- startMarker
addGenerics genericVars
(ty, tyArgs, retType') <- fnTy (genericVars, params fn, retType fn)
mapM_ (uncurry insertValue) tyArgs
insertValue (name fn) ty
endMarker m
(body', bodyTy) <- i_body (body fn)
clearMarker m
bodyTy <:! retType'
let fn' = fn { body = body' }
return (meta :< fn', ty)
i_body :: U.CodeBlock -> Tc (T.CodeBlock, Type)
i_body (meta :< CodeBlock stmts) = do
m <- startMarker
(stmts', ty) <- i_stmts stmts
endMarker m
clearMarker m
return (meta :< CodeBlock stmts', fromMaybe void ty)
fnTy :: ([BoundVar], [(String, U.Type)], U.Type) -> Tc (Type, [(String, Type)], Type)
fnTy (generics, params, retType) = do
tyArgs <- mapM resolveId params
mapM_ (assertKindStar . snd) tyArgs
retType' <- resolveType retType
assertKindStar retType'
let tyArgs' = if null tyArgs
then [void]
else map snd tyArgs
let ty = Fun generics tyArgs' retType'
return (ty, tyArgs, retType')
| tadeuzagallo/verve-lang | src/Typing/Util.hs | mit | 3,258 | 0 | 16 | 687 | 1,305 | 657 | 648 | 98 | 2 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- |
-- Module : Game.Implement.Card
-- Copyright : (c) 2017 Christopher A. Gorski
-- License : MIT
-- Maintainer : Christopher A. Gorski <cgorski@cgorski.org>
--
-- The Game.Implement.Card module provides fundamental operations for a deck of cards.
module Game.Implement.Card
(
Card (..)
, ValuedCard (..)
, OrderedCard (..)
, OrderedValuedCard (..)
)
where
import Control.Monad.Random
import System.Random.Shuffle (shuffleM)
import Data.List (nub, maximumBy, minimumBy, sortBy, foldl1', tails)
-- |
-- Represents a physical card with no order and no value.
-- Inherited Enum, Eq, Ord and Bounded typeclasses are used to
-- distingish cards for the purposes of manipulation within lists.
-- Game value functions are provided by other typeclasses.
class (Enum c, Eq c, Ord c, Bounded c) => Card c where
-- |
-- Return all combinations of size n of a deck of cards
choose :: Int -> [c] -> [[c]]
choose 0 _ = [[]]
choose n lst = do
(x:xs) <- tails lst
rest <- choose (n-1) xs
return $ x : rest
-- |
-- Return a full deck of cards. Cards are unique. Order is not guaranteed.
--
-- >>> fullDeck :: [PlayingCard]
-- [Ace of Clubs,Two of Clubs,Three of Clubs,Four of Clubs,Five of Clubs,Six of Clubs,Seven of Clubs,Eight of Clubs,Nine of Clubs,Ten of Clubs,Jack of Clubs,Queen of Clubs,King of Clubs,Ace of Diamonds,Two of Diamonds,Three of Diamonds,Four of Diamonds,Five of Diamonds,Six of Diamonds,Seven of Diamonds,Eight of Diamonds,Nine of Diamonds,Ten of Diamonds,Jack of Diamonds,Queen of Diamonds,King of Diamonds,Ace of Hearts,Two of Hearts,Three of Hearts,Four of Hearts,Five of Hearts,Six of Hearts,Seven of Hearts,Eight of Hearts,Nine of Hearts,Ten of Hearts,Jack of Hearts,Queen of Hearts,King of Hearts,Ace of Spades,Two of Spades,Three of Spades,Four of Spades,Five of Spades,Six of Spades,Seven of Spades,Eight of Spades,Nine of Spades,Ten of Spades,Jack of Spades,Queen of Spades,King of Spades]
fullDeck :: [c]
-- |
-- Returns all unique cards in a list. All duplicates are removed.
dedupe :: [c] -> [c]
-- |
-- Draws cards from a deck, and groups them based on the list provided
-- in the first argument. Returns the grouped hands and the remaining deck.
-- Arguments that are negative or exceed bounds return Nothing.
--
-- For instance, to simulate a three player Hold'em game, one might wish
-- to draw two cards for each player, and five cards for the community:
--
-- >>> deck <- evalRandIO $ shuffle $ (fullDeck :: [PlayingCard])
-- >>> draw [2,2,2,5] deck
-- Just ([[Ace of Spades,Jack of Spades],[Queen of Hearts,Seven of Clubs],[Jack of Diamonds,Six of Hearts],[Jack of Hearts,Five of Spades,Three of Spades,Two of Diamonds,Ace of Hearts]],[Four of Clubs,Six of Diamonds,Four of Diamonds,Eight of Spades,Six of Clubs,Seven of Spades,Three of Diamonds,Ten of Diamonds,Eight of Hearts,Nine of Diamonds,Three of Clubs,Six of Spades,King of Clubs,Nine of Clubs,Four of Spades,Five of Diamonds,Nine of Spades,Queen of Spades,Ace of Diamonds,Four of Hearts,Two of Clubs,Five of Clubs,Two of Hearts,King of Diamonds,Ten of Spades,Eight of Clubs,Seven of Hearts,Three of Hearts,Queen of Diamonds,Queen of Clubs,Ten of Clubs,King of Hearts,Eight of Diamonds,Jack of Clubs,Ten of Hearts,Seven of Diamonds,Two of Spades,Nine of Hearts,King of Spades,Ace of Clubs,Five of Hearts])
draw :: [Int] -> [c] -> Maybe ([[c]],[c])
-- |
-- The same as 'draw', except throw away the deck
--
-- >>> deck <- evalRandIO $ shuffle $ (fullDeck :: [PlayingCard])
-- >>> draw_ [2,2,2,5] deck
-- Just [[Eight of Hearts,Queen of Hearts],[Two of Clubs,Seven of Diamonds],[Ten of Clubs,Three of Hearts],[Ace of Spades,Nine of Spades,Five of Spades,Four of Diamonds,Two of Spades]]
draw_ :: [Int] -> [c] -> Maybe [[c]]
-- |
-- The same as 'draw', except draw only one hand of specified size.
--
-- >>> deck <- evalRandIO $ shuffle $ (fullDeck :: [PlayingCard])
-- >>> draw1 5 deck
-- Just ([Six of Clubs,Ace of Hearts,Nine of Hearts,Four of Hearts,Two of Diamonds],[King of Diamonds,Queen of Spades,Four of Spades,Seven of Hearts,Five of Hearts,Seven of Clubs,Three of Hearts,Ace of Spades,Three of Diamonds,Seven of Diamonds,Two of Clubs,Five of Spades,King of Hearts,Jack of Hearts,Queen of Hearts,Ten of Clubs,Five of Clubs,Eight of Spades,Ace of Clubs,King of Clubs,Five of Diamonds,Queen of Diamonds,Eight of Hearts,Four of Clubs,Three of Clubs,Jack of Clubs,Jack of Diamonds,Ten of Diamonds,Queen of Clubs,Eight of Diamonds,Six of Diamonds,Eight of Clubs,Three of Spades,Two of Hearts,Six of Spades,King of Spades,Ten of Hearts,Nine of Spades,Nine of Diamonds,Two of Spades,Ten of Spades,Nine of Clubs,Four of Diamonds,Ace of Diamonds,Six of Hearts,Seven of Spades,Jack of Spades])
draw1 :: Int -> [c] -> Maybe ([c],[c])
-- |
-- The same as 'draw1', except throw away the deck.
--
-- >>> deck <- evalRandIO $ shuffle $ (fullDeck :: [PlayingCard])
-- >>> draw1_ 5 deck
-- Just [Five of Hearts,Ace of Diamonds,Ten of Hearts,Two of Spades,Six of Clubs]
draw1_ :: Int -> [c] -> Maybe [c]
-- |
-- Shuffle a deck of cards.
--
-- >>> deck <- evalRandIO $ shuffle $ (fullDeck :: [PlayingCard])
-- >>> [Three of Clubs,Nine of Spades,Five of Clubs,Two of Hearts,Four of Spades,King of Hearts,Ten of Hearts,Two of Clubs,Ace of Hearts,Eight of Diamonds,Six of Diamonds,Seven of Diamonds,Jack of Spades,Three of Hearts,Three of Spades,Queen of Clubs,Ten of Diamonds,Six of Spades,Two of Diamonds,Nine of Clubs,Five of Diamonds,Five of Spades,Seven of Spades,Jack of Clubs,Six of Hearts,Jack of Diamonds,Four of Hearts,Ace of Spades,Nine of Diamonds,King of Clubs,Two of Spades,Four of Clubs,Eight of Hearts,Queen of Hearts,Ace of Clubs,Five of Hearts,Ten of Spades,Six of Clubs,Ten of Clubs,Four of Diamonds,Three of Diamonds,Seven of Hearts,King of Diamonds,Ace of Diamonds,Nine of Hearts,Queen of Spades,Seven of Clubs,Jack of Hearts,King of Spades,Eight of Spades,Queen of Diamonds,Eight of Clubs]
shuffle :: RandomGen m => [c] -> Rand m [c]
-- |
-- Return a random card.
--
-- >>> card :: PlayingCard <- evalRandIO $ randomCard
-- >>> card
-- Four of Diamonds
randomCard :: RandomGen m => Rand m c
fullDeck = [minBound .. maxBound]
dedupe l = nub l
shuffle deck = shuffleM deck
randomCard =
let
minB = minBound :: (Bounded c, Card c) => c
maxB = maxBound :: (Bounded c, Card c) => c in
do
randomd <- getRandomR(fromEnum minB, fromEnum maxB)
return $ toEnum randomd
draw handSizeLst deck
| let
total = (foldl1' (+) handSizeLst)
anyNeg = (length (filter (\n -> n < 0) handSizeLst)) > 0
in
(total > (length deck)) || (total < 1) || anyNeg = Nothing
| otherwise = let
draw2 [] (houtput, doutput) = ((reverse houtput), doutput)
draw2 (nToTake:hst) (handOutput, deckOutput) = let
newHand = take nToTake deckOutput
newDeck = drop nToTake deckOutput in
draw2 hst (newHand:handOutput, newDeck)
in Just (draw2 handSizeLst ([],deck))
draw_ handSizes deck =
let f (Just (h, _)) = Just h
f _ = Nothing
in
f $ draw handSizes deck
draw1 handSize deck =
let
f (Just ([h], d)) = Just (h,d)
f _ = Nothing
in
f $ draw [handSize] deck
draw1_ handSize deck =
let
f (Just ([h], _)) = Just h
f _ = Nothing
in
f $ draw [handSize] deck
-- |
-- Represents a playing card with a game value. For instance,
-- a standard playing card with a type representing
-- rank and suit.
class (Card c) => ValuedCard c v where
-- |
-- Return a value associated with a card.
--
-- >>> card = PlayingCard Six Clubs
-- >>> toValue card :: Rank
-- Six
-- >>> toValue card :: Suit
-- Clubs
toValue :: c -> v
-- |
-- Return values associated with multiple cards.
--
-- >>> cards = [PlayingCard Six Clubs, PlayingCard Four Diamonds]
-- >>> toValueLst cards :: [Rank]
-- [Six,Four]
-- >>> toValueLst cards :: [Suit]
-- [Clubs,Diamonds]
toValueLst :: [c] -> [v]
toValueLst l = map toValue l
-- |
-- Orderings independent of a specific value
-- type of a Card.
class (Card c) => OrderedCard c o where
highestCardBy :: o -> [c] -> c
lowestCardBy :: o -> [c] -> c
compareCardBy :: o -> c -> c -> Ordering
sortCardsBy :: o -> [c] -> [c]
highestCardBy o cl = maximumBy (compareCardBy o) cl
lowestCardBy o cl = minimumBy (compareCardBy o) cl
sortCardsBy o cl = sortBy (compareCardBy o) cl
-- |
-- Orderings dependent on the specific value type of a Card
class (OrderedCard c o) => OrderedValuedCard c o vt where
-- |
-- Return an Int based on a card, an ordering and a value type.
toOrderedValue :: o -> vt -> c -> Int
| cgorski/general-games | src/Game/Implement/Card.hs | mit | 8,909 | 0 | 21 | 1,871 | 1,269 | 715 | 554 | 76 | 0 |
import qualified Data.Hash.MD5 as MD5
md5snum str x = MD5.md5s $ MD5.Str $ str ++ show x
firstSixZeros str x
| take 6 (md5snum str x) == "000000" = x
| otherwise = -1
main = do
let word_part = "iwrupvqb"
print $ head [firstSixZeros word_part x | x <- [0..], firstSixZeros word_part x > 0]
| RatanRSur/advent-of-haskell | day4/part2.hs | mit | 309 | 0 | 12 | 76 | 139 | 68 | 71 | 8 | 1 |
module Problem2 ( secondToLastElem ) where
secondToLastElem :: [a] -> a
secondToLastElem x = last (init x) | chanind/haskell-99-problems | Problem2.hs | mit | 107 | 0 | 7 | 17 | 38 | 21 | 17 | 3 | 1 |
{-# LANGUAGE OverloadedStrings, ViewPatterns #-}
module Y2018.M05.D25.Solution where
import Control.Arrow ((&&&))
import Control.Concurrent (threadDelay)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as BL
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.Types
import Network.HTTP.Conduit
import Network.HTTP.Types hiding (Query)
-- below imports available via 1HaskellADay
import Data.Logger hiding (mod)
import Data.LookupTable
import Store.SQL.Connection
import Store.SQL.Util.Indexed
import Store.SQL.Util.Logging
{--
Okay, let's do a little testy-testy.
Download some articles from the database, upload them to a rest endpoint, and
eh, that's today's exercise.
--}
nerEndpoint :: FilePath
nerEndpoint = "https://grby98heb8.execute-api.us-east-1.amazonaws.com/CORS"
{--
The curl command is:
curl -X POST -H "Content-Type: application/json" -d '{"text": "I am going to see Deadpool2 on Friday."}'
Or whatever you're sending from the database.
But you're going to do a HTTPS POST to the rest endpoint. So do that. AND get
the response, AND get the response type (200, 400, 504)
--}
data S = S { txt :: String }
instance FromRow S where
fromRow = S <$> field
type Conn1 = (Connection, LookupTable)
instance Show S where show = take 100 . txt
fetchStmt :: Int -> Int -> Query
fetchStmt n offset =
Query (B.pack ("SELECT id,full_text FROM article WHERE id > " ++ show offset
++ " LIMIT " ++ show n))
-- query looks like:
-- [sql|SELECT id,full_text FROM article WHERE id > ? LIMIT (?)|]
fetchIxArticle :: Connection -> Int -> Int -> IO [IxValue S]
fetchIxArticle conn n = query_ conn . fetchStmt n
-- fetches n articles.
-- Question: IDs are not sequential. What is the max id of the fetch?
curlCmd :: Conn1 -> Int -> IxValue S -> IO (Status, String)
curlCmd = cc' 30 0
cc' :: Int -> Int -> Conn1 -> Int -> IxValue S -> IO (Status, String)
cc' secs tries conn n msg =
if tries > 3 then return (Status 504 "failed", "")
else (newManager tlsManagerSettings >>= \mgr ->
parseRequest nerEndpoint >>= \req ->
let jsn = BL.pack ("{ \"text\": " ++ show (txt (val msg)) ++ " }")
req' = req { responseTimeout = responseTimeoutMicro (secs * 1000000),
method = "POST",
-- requestHeaders = [(CI "application", "json")],
requestBody = RequestBodyLBS jsn } in
httpLbs req' mgr >>= \((responseStatus &&& BL.unpack . responseBody) -> it) ->
logStatus conn n tries msg it >>
(if n `mod` 100 == 0
then info conn ("NER processed " ++ show n ++ " articles")
else return ()) >>
return it)
-- sends text, gets a response and status
logStatus :: Conn1 -> Int -> Int -> IxValue S -> (Status, String) -> IO ()
logStatus conn n tries art@(IxV x _) (stat, resp) =
if statusCode stat == 200
then debug conn n x resp
else warn conn tries n x stat resp >> cc' 30 (succ tries) conn n art >> return ()
where debug (conn,lk) n x msg =
roff conn lk DEBUG "Load Tester" "Y2018.M05.D25.Solution"
("Row " ++ show n ++ ", entities (article " ++ show x
++ "): " ++ take 200 resp)
warn :: Conn1 -> Int -> Int -> Integer -> Status -> String -> IO ()
warn (conn,lk) tries n x stat msg =
roff conn lk WARN "Load Tester" "Y2018.M05.D25.Solution"
("WARNING Row " ++ show n ++ ", code: "
++ show (statusCode stat) ++ " for article " ++ show x
++ ": " ++ msg)
info :: Conn1 -> String -> IO ()
info (conn,lk) = mkInfo "Load Tester" "Y2018.M05.D25.Solution" lk conn
-- And our application that brings it all together
main' :: [String] -> IO ()
main' [n, offset] =
let n1 = read n
off1 = read offset in
withConnection PILOT (\conn ->
initLogger conn >>= \lk ->
let log = info (conn,lk) in
log ("Load testing API Gateway with " ++ n ++ " articles from " ++ offset) >>
fetchIxArticle conn n1 off1 >>= \arts ->
log ("Fetched " ++ n ++ " articles") >>
mapM_ (\(x, art) -> curlCmd (conn, lk) x art >> threadDelay 2000) (zip [1..] arts) >>
log ("Processed entities for " ++ n ++ " articles") >>
log ("Max ID is " ++ show (maximum (map idx arts))))
{--
>>> main' (words "3 253013")
Stamped {stamped = Entry {sev = INFO, app = "Load Tester", mod = "Y2018.M05.D25.Solution", msg = "Load testing API Gateway with 3 articles from 253013"}, time = 2018-05-25 15:11:13.885881}
Stamped {stamped = Entry {sev = INFO, app = "Load Tester", mod = "Y2018.M05.D25.Solution", msg = "Fetched 3 articles"}, time = 2018-05-25 15:11:13.991414}
Stamped {stamped = Entry {sev = INFO, app = "Load Tester", mod = "Y2018.M05.D25.Solution", msg = "Processed entities for 3 articles"}, time = 2018-05-25 15:11:51.739545}
Stamped {stamped = Entry {sev = INFO, app = "Load Tester", mod = "Y2018.M05.D25.Solution", msg = "Max ID is 253016"}, time = 2018-05-25 15:11:51.743727}
--}
| geophf/1HaskellADay | exercises/HAD/Y2018/M05/D25/Solution.hs | mit | 5,075 | 0 | 24 | 1,175 | 1,255 | 669 | 586 | -1 | -1 |
module Main where
import Lib
import Text.Printf
n = 100::Integer
main :: IO ()
main = do
printf "Square of sum minus sum of squares = %d\n" (squareSum n - sumSquares n)
| JohnL4/ProjectEuler | Haskell/Problem006/app/Main.hs | mit | 174 | 0 | 10 | 37 | 56 | 30 | 26 | 7 | 1 |
{-# LANGUAGE OverloadedStrings, FlexibleContexts #-}
module Chatwork.V0.Api (
module Chatwork.V0.ChatworkConfig
, module Chatwork.V0.Type
, module Chatwork.V0.Message
, login
, loadChat
, loadRoom
, readChat
, getUpdate
, sendChat
, getRoomInfo
)
where
import Network.HTTP.Conduit
import Network.HTTP.Types
import Control.Applicative (pure, (<$>))
import Control.Monad.Trans.Resource (runResourceT)
import qualified Data.ByteString.Char8 as C
import Text.ParserCombinators.Parsec
import qualified Data.ByteString.Lazy as BL
import Chatwork.V0.ChatworkConfig
import Chatwork.V0.Type
import Chatwork.V0.Message
import Data.Time.Clock (getCurrentTime)
import Data.Time.Format (defaultTimeLocale, formatTime)
import Data.Aeson (eitherDecode, decode, encode, FromJSON, ToJSON, object, (.=), toJSON)
import System.IO.Unsafe (unsafePerformIO)
import qualified Control.Monad.State as State
import Control.Monad.IO.Class (liftIO)
import Prelude hiding (read)
import qualified Data.Text as T
import Data.List (intercalate)
import qualified Control.Exception as E
type QueryParam = [(String, String)]
type ApiResponse a = Either String (Chatwork.V0.Type.Response a)
sendChat :: String -> String -> Chatwork IO (ApiResponse ())
sendChat rid body = do
post "send_chat" params postdata
where
params = []
postdata = SendChatData {
text = body,
room_id = rid,
last_chat_id = "0",
read = "0",
edit_id = "0"
}
getUpdate :: String -> Chatwork IO (ApiResponse GetUpdate)
getUpdate _lastId = do
get "get_update" params
where params = [ ("last_id" , _lastId),
("new" , "1") ]
readChat :: RoomId -> MessageId -> Chatwork IO (ApiResponse ReadChat)
readChat roomId lastChatId = do
get "read" params
where params = [ ("last_chat_id" , lastChatId),
("room_id" , roomId) ]
loadChat :: RoomId -> Chatwork IO (ApiResponse LoadChat)
loadChat roomId = do
get "load_chat" params
where params = [ ("room_id" , roomId),
("last_chat_id" , "0"),
("first_chat_id" , "0"),
("jump_to_chat_id" , "0"),
("unread_num" , "0"),
("desc" , "1") ]
loadRoom :: LoadRequest -> Chatwork IO (ApiResponse ())
loadRoom request = do
post "get_room_info" [] (toJSON request)
getRoomInfo :: RoomId -> Chatwork IO (ApiResponse RespGetRoomInfo)
getRoomInfo roomId = do
post "get_room_info" [] pdata
where
pdata = object [
"i" .= object [
(T.pack roomId) .= object [
"c" .= (0 :: Int),
"u" .= (0 :: Int),
"l" .= (0 :: Int),
"t" .= (0 :: Int)
]
],
"p" .= ([] :: [Int]),
"m" .= ([] :: [Int]),
"d" .= ([] :: [Int]),
"t" .= object [],
"rid" .= (0 :: Int),
"type" .= ("" :: String),
"load_file_version" .= ("2" :: String)
]
get :: (FromJSON a) => String -> [(String, String)] -> Chatwork IO (ApiResponse a)
get cmd params = request "GET" cmd params Nothing
post :: (FromJSON a, ToJSON b) => String -> [(String, String)] -> b -> Chatwork IO (ApiResponse a)
post cmd params postdata = request "POST" cmd params (Just pdata)
where
pdata = RequestBodyLBS $ "pdata=" `BL.append` json
json = encode postdata
-- method command query paramter post data
request :: (FromJSON a) => Method -> String -> [(String, String)] -> Maybe RequestBody -> Chatwork IO (ApiResponse a)
request method cmd params postdata = do
let time = unsafePerformIO $ formatTime defaultTimeLocale "%s" <$> getCurrentTime
maybeAuth <- fmap auth State.get
case maybeAuth of
Just auth -> do
let query = (fmap.fmap) Just $ fmap (\(a, b) -> (C.pack a, C.pack b)) $ filter (not.null) $ ([("_", time), ("cmd", cmd)] ++ params ++ authParams auth)
base <- fmap base State.get
let url = base ++ "gateway.php?"
__req <- parseUrl url
let _req = setQueryString query __req
let contentType = ("Content-Type", C.pack "application/x-www-form-urlencoded; charset=UTF-8")
let req = case postdata of
Just m -> _req {cookieJar = Just (jar auth), method = method, requestBody = m, requestHeaders = [contentType]}
Nothing -> _req {cookieJar = Just (jar auth), method = method}
manager <- liftIO $ newManager tlsManagerSettings
runResourceT $ do
res <- httpLbs req manager
return $ eitherDecode (responseBody res)
`catchStateT` httpExceptionHandler
Nothing -> return (Left "auth failed")
catchStateT :: E.Exception e
=> State.StateT s IO a
-> (e -> State.StateT s IO a)
-> State.StateT s IO a
catchStateT a onE = do
s1 <- State.get
(result, s2) <- liftIO $ State.runStateT a s1 `E.catch` \e ->
State.runStateT (onE e) s1
State.put s2
return result
httpExceptionHandler :: (FromJSON a) => HttpException -> Chatwork IO (ApiResponse a)
httpExceptionHandler e = do
liftIO $ print e
return $ Left (show e)
authParams :: Auth -> QueryParam
authParams auth = [ ("myid" , myid auth),
-- ("account_id" , myid auth),
("_t" , accessToken auth),
("_v" , "1.80a"),
-- ("ver" , "1.80a"),
("_av" , "4") ]
login :: Chatwork IO (Maybe Auth)
login = do
_base <- fmap base State.get
req <- parseUrl $ _base ++ "login.php?lang=en&args="
password <- fmap pass State.get
email <- fmap user State.get
office <- fmap office State.get
let _params = fmap pack $ [("email", email), ("password", password), ("orgkey", office), ("auto_login", "on"), ("login", "Login")]
let _req = (urlEncodedBody _params req) {method="POST"}
manager <- liftIO $ newManager tlsManagerSettings
res <- httpLbs _req manager
let jar = responseCookieJar res
let body = responseBody res
let authinfo = either (\a -> []) id $ fmap (filter (not.emptuple)) (parse parseHTML "" ((C.unpack $ BL.toStrict body) ++ "\n"))
let myid = lookup "myid" authinfo
let token = lookup "ACCESS_TOKEN" authinfo
let auth = case (myid, token) of
(Just m, Just t) -> Just $ Auth {jar = jar, myid = m, accessToken = t}
_ -> Nothing
State.put ChatworkConfig { base = _base, office = office, user = email, pass = password, auth = auth}
liftIO.pure $ auth
where
pack (a, b) = (a, C.pack b)
emptuple (a, b) = a == "" && b == ""
find key ts = head $ map snd $ filter (\t -> fst t == key) ts
parseHTML :: GenParser Char st [(String, String)]
parseHTML = do
result <- many line
eof
return result
line :: GenParser Char st (String, String)
line =
do result <- anyAuthInfo
optional (char ';')
optional (char '\r')
eol
return result
jsString :: GenParser Char st String
jsString = do
oneOf "\"'"
s <- many (noneOf "'\"")
oneOf "\"'"
return s
anyAuthInfo :: GenParser Char st (String, String)
anyAuthInfo = do
var
try authInfo <|> do
many (noneOf "\n")
anyAuthInfo
<|> (many (noneOf "\n") >> return ("",""))
authInfo = _myid <|> _token
_myid = jsStrVar "myid"
_token = jsStrVar "ACCESS_TOKEN"
var :: GenParser Char st String
var = string "var" >> spaces >> return []
jsStrVar :: String -> GenParser Char st (String, String)
jsStrVar str = do
string str
spaces
char '='
spaces
s <- jsString
return (str, s)
eol :: GenParser Char st Char
eol = char '\n'
| totem3/cwhs | src/Chatwork/V0/Api.hs | mit | 7,809 | 0 | 24 | 2,212 | 2,702 | 1,440 | 1,262 | 193 | 3 |
{-# LANGUAGE RecordWildCards #-}
module StructuralIsomorphism.Declarations (
-- * Types
Constructor(..), DataType(..),
-- * Map from Template Haskell to these simpler types
constructor, dataType
) where
import Language.Haskell.TH.Syntax
data Constructor = Constructor { conName :: !Name
, conArguments :: ![StrictType] }
deriving (Eq, Ord, Show)
constructor :: Con -> Maybe Constructor
constructor (NormalC conName conArguments) = Just Constructor{..}
constructor (RecC conName fields) = Just Constructor{ conArguments =
[(s,ty) | (_,s,ty) <- fields]
, .. }
constructor (InfixC arg1 conName arg2) = Just Constructor{ conArguments = [arg1, arg2]
, .. }
constructor (ForallC _tvs _cxt _con) = Nothing
constructor (GadtC _names _tys _res) = Nothing
constructor (RecGadtC _names _fields _res) = Nothing
data DataType = DataType { dtContext :: !Cxt
, dtName :: !Name
, dtParameters :: ![TyVarBndr]
, dtKind :: !(Maybe Kind)
, dtConstructors :: ![Constructor]
, dtDeriving :: !Cxt }
deriving (Eq, Ord, Show)
dataType :: Dec -> Maybe DataType
dataType (DataD dtContext dtName dtParameters dtKind dtCons dtDeriving) = do
dtConstructors <- traverse constructor dtCons
Just DataType{..}
dataType (NewtypeD dtContext dtName dtParameters dtKind dtCon dtDeriving) = do
dtConstructors <- pure <$> constructor dtCon
Just DataType{..}
dataType _ =
Nothing
| antalsz/hs-to-coq | structural-isomorphism-plugin/src/StructuralIsomorphism/Declarations.hs | mit | 1,795 | 0 | 11 | 645 | 457 | 247 | 210 | 50 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Prelude as P
import Data.Binary as Bin
import Data.ByteString as BS
import Data.ByteString.Lazy as BSL
import Data.ByteString.Char8 as BSC
import Data.ByteString.Lazy.Char8 as BSLC
import Data.String
import Data.Maybe
import Data.Text as Txt
import Control.Exception
import Data.IP
import Network.Socket as NS
import System.IO as Sys
import System.Random
import Data.Streaming.Network
import Network.TCP.Proxy.Client
import Network.TCP.Proxy.Socks4 as Socks4
import qualified Network.TCP.Proxy.Server as Proxy
import Data.Map.Strict as Map
import Control.Concurrent.STM.TChan
import Control.Concurrent.STM.TVar
import Control.Concurrent.STM
import Control.Monad
import System.Log.Logger
import Data.Conduit.Binary as DCB
import Data.Conduit.List as CL
import Data.Conduit as DC
import Data.Conduit.List as DC
import Data.Conduit.Network
import qualified Network.BitTorrent.Shepherd as Tracker
import Network.BitTorrent.ClientControl
import Network.BitTorrent.ClientControl.UTorrent
import Network.BitSmuggler.BitTorrentSimulator as Sim
import Network.BitSmuggler.Utils
import Network.BitSmuggler.Common
import Network.BitSmuggler.Protocol
import Network.BitSmuggler.TorrentFile
import Data.Serialize as DS
import Control.Concurrent
import Control.Concurrent.Async
import qualified Filesystem.Path as FS
import Shelly as Sh
import Control.Monad.Trans.Resource
{-
project created to run experiments
-}
main = do
runResourceT $ genRandBytes 23456 100000000 $$ sinkFile "testFile.txt"
{-
main = do
P.putStrLn "running bit-smuggler script"
testHash = Bin.decode $ BSL.replicate 20 0
testDataFile = "/home/dan/repos/bitSmuggler/bit-smuggler/testdata/sampleCapture0"
localhost = "127.0.0.1"
initiatorConf = Sim.Config {resourceMap = Map.empty, rpcPort = 2015, peerPort = 3001}
testConnData = ConnectionData {connTorrent = Torrent testHash "this is the filename"
, dataFile = testDataFile
, peerAddr = (localhost, peerPort initiatorConf)
, proxyAddr = (localhost, 1080)}
receiverConf = Sim.Config {
resourceMap = Map.fromList [(Left testDataFile, testConnData)]
, rpcPort = 2016, peerPort = 3002}
initiatorPeer = do
Sim.runClient initiatorConf
receiverPeer = do
Sim.runClient receiverConf
-}
--logger = "scripts"
initCaptureHook incFile outFile a1 a2 = do
incHook <- captureHook incFile
outHook <- captureHook outFile
return $ Proxy.DataHooks (idleHook =$ incHook) (idleHook =$ outHook) (return ())
--captureHook :: Sys.FilePath -> IO (BS.ByteString -> IO BS.ByteString)
captureHook file = do
rgen <- newStdGen
let r = (fst $ random rgen) :: Int
tQueue <- newTQueueIO
debugM logger $ "setting up capture for " P.++ file
forkIO $ do
withFile (file P.++ (show r)) WriteMode $ \fileH -> do
sourceTQueue tQueue {- =$ (CL.map (DS.encode . NetworkChunk)) -} $$ sinkHandle fileH
debugM logger $ "done setting up capture"
return $ awaitForever
(\bs -> (liftIO $ atomically $ writeTQueue tQueue bs) >> DC.yield bs)
trafficCapture prefix port protocol redirects = do
-- updateGlobalLogger logger (setLevel DEBUG)
Proxy.run $ Proxy.Config { Proxy.proxyPort = port
, Proxy.initHook = initCaptureHook (prefix ++ "incomingCapture")
(prefix ++ "outgoingCapture")
, Proxy.handshake = protocol
, Proxy.redirects = redirects
}
printChunk = awaitForever $
\bs -> (liftIO $ debugM logger (show $ BS.length bs)) >> DC.yield bs
trafficProxy = do
Proxy.run $ Proxy.Config { Proxy.proxyPort = 1080
, Proxy.initHook
= (\_ _ -> return $ Proxy.DataHooks printChunk printChunk (return ()))
, Proxy.handshake = Socks4.serverProtocol
, Proxy.redirects = Map.empty
}
uTorrentStateFiles :: [String]
uTorrentStateFiles = ["dht.dat", "resume.dat", "rss.dat", "settings.dat", "dht_feed.dat"]
cleanUTorrentState torrentPath other = do
forM (P.map (torrentPath </> )
$ (P.map fromString (uTorrentStateFiles P.++ (P.map (P.++ ".old") uTorrentStateFiles))
P.++ other))
$ \file -> do
r <- try' $ shelly $ rm file
-- debugM logger $ "clean result" P.++ (show r)
return ()
return ()
webUIPortSeed = 9000
webUIPortPeer = 8000
trackerPort = 6666
utorrentDefCreds = ("admin", "")
testRun = do
updateGlobalLogger logger (setLevel DEBUG)
peerSeedTalk "/home/dan/tools/bittorrent/utorrent-server-alpha-v3_3_0/"
"/home/dan/tools/bittorrent/utorrent-server-alpha-v3_3_1/"
"../demo/localContact/testFile.txt"
"../demo/otherLocalContact/testFile.txt"
"../demo/localContact/testFile.torrent"
-- script - 2 utorrent clients talk to get a file
peerSeedTalk :: Sh.FilePath -> Sh.FilePath -> Sh.FilePath ->
Sh.FilePath -> Sh.FilePath -> IO ()
peerSeedTalk seedPath peerPath dataFilePath otherDataFilePath tFilePath = runResourceT $ do
let oldData = [FS.filename dataFilePath]
liftIO $ do
debugM logger $ show oldData
cleanUTorrentState seedPath oldData
cleanUTorrentState peerPath oldData
shelly $ cp dataFilePath seedPath --place file to be seeded
shelly $ cp otherDataFilePath peerPath --place file to be seeded
let seederPort = 9111
let peerPort = 10000
let revProxyPort = 1081
let socksProxyPort = 1080
trackEvents <- liftIO $ newTChanIO
tracker <- allocAsync $ async $ Tracker.runTracker
$ Tracker.Config { Tracker.listenPort = 6666
, Tracker.events = Just trackEvents}
liftIO $ waitFor (== Tracker.Booting) trackEvents
liftIO $ debugM logger "tracker is booting"
-- liftIO $ threadDelay $ 2 * milli
proxy <- allocAsync $ async
$ trafficCapture "seeder-"
revProxyPort (revProxy (P.read localhost) seederPort) Map.empty
liftIO $ threadDelay $ 1 * milli
liftIO $ debugM logger "launching seeder..."
seeder <- allocAsync $ runUTClient seedPath
liftIO $ threadDelay $ 2 * milli
liftIO $ debugM logger "launched seeder"
seedConn <- liftIO $ makeUTorrentConn localhost webUIPortSeed utorrentDefCreds
liftIO $ setSettings seedConn [BindPort seederPort, UPnP False, NATPMP False, RandomizePort False, DHTForNewTorrents False, TransportDisposition True False True False, LocalPeerDiscovery False, LimitLocalPeerBandwidth True, UploadSlotsPerTorrent 1] --, ProxySetType Socks4, ProxyIP "127.0.0.1", ProxyPort 1081, ProxyP2P True]
-- liftIO $ setSettings peerConn [BindPort
liftIO $ addTorrentFile seedConn $ pathToString tFilePath
liftIO $ setJobProperties seedConn
(fromJust $ textToInfoHash "f921dd6548298527d40757fb264de07f7a47767f")
[DownloadRate 20000, UploadRate 20000]
liftIO $ waitFor (\(Tracker.AnnounceEv a) -> True) trackEvents
liftIO $ debugM logger "got announce"
-- sleep for a while until that is announced; ideally i should put
proxy <- allocAsync $ async $ trafficCapture "peer-" socksProxyPort Socks4.serverProtocol
(Map.fromList [((Right (P.read localhost), seederPort)
,(Right (P.read localhost), revProxyPort) )])
liftIO $ threadDelay $ 1 * milli
peer <- allocAsync $ runUTClient peerPath
liftIO $ threadDelay $ 1 * milli
liftIO $ debugM logger "launched peer. telling it to connect"
peerConn <- liftIO $ makeUTorrentConn localhost webUIPortPeer utorrentDefCreds
liftIO $ setSettings peerConn [BindPort peerPort, UPnP False, NATPMP False, RandomizePort False, DHTForNewTorrents False, TransportDisposition True False True False, LocalPeerDiscovery False, ProxySetType Socks4, ProxyIP "127.0.0.1", ProxyPort socksProxyPort, ProxyP2P True]
liftIO $ addTorrentFile peerConn $ pathToString tFilePath
liftIO $ P.getLine
-- close procs
release $ fst peer
release $ fst proxy
release $ fst seeder
release $ fst tracker
return ()
testTCPClient = runTCPClient (clientSettings testTCPSrcPort "79.117.145.153") $ \app -> do
P.putStrLn "connected"
testTCPSrcPort = 6889
testTCPServer = runTCPServer (serverSettings testTCPSrcPort "*") $ \app -> do
P.putStrLn $ show $ appSockAddr app
runSimpleProxy = do
updateGlobalLogger logger (setLevel DEBUG)
updateGlobalLogger Proxy.logger (setLevel DEBUG)
Proxy.run $ Proxy.Config { Proxy.proxyPort = 1080
, Proxy.initHook = \_ _ -> debugM logger "wtf this ran now"
>> return Proxy.DataHooks {
Proxy.incoming = DC.map P.id
, Proxy.outgoing = DC.map P.id
, Proxy.onDisconnect = return ()
}
, Proxy.handshake = Socks4.serverProtocol
, Proxy.redirects = Map.empty
}
runSimpleRevProxy ip port = do
updateGlobalLogger logger (setLevel DEBUG)
Proxy.run $ Proxy.Config { Proxy.proxyPort = 2002
, Proxy.initHook = \_ _ -> return Proxy.DataHooks { Proxy.incoming = DC.map P.id
, Proxy.outgoing = DC.map P.id
, Proxy.onDisconnect = return ()
}
, Proxy.handshake = revProxy ip port
, Proxy.redirects = Map.empty
}
runTestRev = runSimpleRevProxy (IPv4 $ toIPv4 [127, 0, 0, 1]) 7882
revProxy ip port = return $ Proxy.ProxyAction {
Proxy.command = CONNECT
, Proxy.remoteAddr = (Right ip, port)
, Proxy.onConnection = \ _ -> return ()
}
tryMaybeBitTorrentProxy port = do
Proxy.run $ Proxy.Config {
Proxy.proxyPort = port
, Proxy.initHook
= (\ _ _ -> return $ Proxy.DataHooks idleHook idleHook (return ()))
, Proxy.handshake = Socks4.serverProtocol
, Proxy.redirects = Map.empty
}
idleHook = btStreamHandler (DC.map P.id)
-- this is so stupid I don't even..
pathToString ::Sh.FilePath -> String
pathToString fp = P.read . P.drop (P.length $ ("FilePath " :: String)) . show $ fp
-- careful with utserver failure - utserver fails "silently"
-- returning 0 even when it fails to read params
runUTClient path = async $ shelly $ chdir path
$ Sh.run (path </> ("utserver" :: Sh.FilePath)) []
-- treats an async as a resource that needs to be canceled on close
waitFor cond chan = do
n <- atomically $ readTChan chan
if (cond n) then return n
else waitFor cond chan
-- proc
testProc = do
ncop <- async $ do
r <- shelly $ Sh.run (fromString "nc") $ P.map Txt.pack ["-l", "1234"]
P.putStrLn $ show r
P.getLine
cancel ncop
P.getLine
clientInterrupt = do
updateGlobalLogger logger (setLevel DEBUG)
conn <- makeUTorrentConn "127.0.0.1" 8000 ("admin", "")
debugM logger "made first connection"
P.getLine -- wait for user input
let ih = fromJust $ textToInfoHash "ef967fc9d342a4ba5c4604c7b9f7b28e9e740b2f"
stopTorrent conn ih
P.getLine -- wait for user input
startTorrent conn ih
return ()
-- play to showcase the client functionality
runTorrentClientScript = do
updateGlobalLogger logger (setLevel DEBUG)
conn <- makeUTorrentConn "127.0.0.1" 9000 ("admin", "")
debugM logger "made first connection"
addMagnetLink conn archMagnet
pauseTorrent conn 593483888932971759637666321247479059714797631408
unpauseTorrent conn 593483888932971759637666321247479059714797631408
{-
r3 <- setSettings conn [UPnP False, NATPMP False, RandomizePort False, DHTForNewTorrents False, UTP True, LocalPeerDiscovery False, ProxySetType Socks4, ProxyIP "127.0.0.1", ProxyPort 1080, ProxyP2P True]
debugM logger $ show $ r3
addTorrentFile conn torrentFile
torrentFile <-return "/home/dan/testdata/sample100.torrent"
-}
r <- listTorrents conn
debugM logger $ "list of torrents is " ++ (show r)
return ()
archMagnet = "magnet:?xt=urn:btih:67f4bcecdca3e046c4dc759c9e5bfb2c48d277b0&dn=archlinux-2014.03.01-dual.iso&tr=udp://tracker.archlinux.org:6969&tr=http://tracker.archlinux.org:6969/announce"
runClientWithSettings peerPath tFilePath dataFilePath = do
let oldData = [FS.filename dataFilePath]
liftIO $ do
debugM logger $ show oldData
cleanUTorrentState peerPath oldData
shelly $ cp dataFilePath peerPath --place file to be seeded
liftIO $ debugM logger "launching peer..."
peer <- allocAsync $ runUTClient peerPath
liftIO $ threadDelay $ 2 * milli
liftIO $ debugM logger "launched peer"
peerConn <- liftIO $ makeUTorrentConn localhost webUIPortPeer utorrentDefCreds
liftIO $ setSettings peerConn [BindPort 5881, UPnP False, NATPMP False, RandomizePort False, DHTForNewTorrents False, LocalPeerDiscovery False]
liftIO $ addTorrentFile peerConn $ pathToString tFilePath
liftIO $ debugM logger "configured the client and told it to work on a file"
liftIO $ threadDelay $ 10 ^ 9
testRunClientWithSettings = do
updateGlobalLogger logger (setLevel DEBUG)
runResourceT $
runClientWithSettings "/home/dan/tools/bittorrent/utorrent-server-alpha-v3_3_1"
"../demo/localContact/testFile.torrent"
"../demo/contactFile/testFile.txt"
echoPort = 8887
echoClient = do
let msg = "hello" :: BS.ByteString
runTCPClient (clientSettings echoPort "127.0.0.1") $ \appData -> do
(appSource appData) =$ (foreverPing msg) $$ (appSink appData)
foreverPing msg = do
DC.yield msg
echoResp <- DCB.take (BS.length msg)
return ()
echoServer = do
runTCPServer (serverSettings echoPort "*") $ \appData -> do
(appSource appData) =$ (DC.mapM (\bs -> P.putStrLn "wtf" >> return bs))
$$ (appSink appData)
P.putStrLn "finished conn"
DC.sourceList ["omg"] $$ (appSink appData)
P.putStrLn "sent smth after connection was closed"
testGetSock = getSocketFamilyTCP "www.google.com" 80 NS.AF_UNSPEC
---- various toy functions
{-
tryAsyncInterrupt = do
take <- newTMVarIO 1
put <- newEmptyTMVarIO
async $ P.putStrLn "hello"
-}
| danoctavian/bit-smuggler | scripts/Main.hs | gpl-2.0 | 14,427 | 0 | 19 | 3,408 | 3,374 | 1,715 | 1,659 | 259 | 2 |
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
-- | Data type for holding server state.
--
-- The server state consists mainly of the allocators needed for different types of resources, such as nodes, buffers and buses.
module Sound.SC3.Server.State (
SyncId
, SyncIdAllocator
, syncIdAllocator
, NodeId
, NodeIdAllocator
, nodeIdAllocator
, BufferId
, BufferIdAllocator
, bufferIdAllocator
, ControlBusId
, ControlBusIdAllocator
, controlBusIdAllocator
, AudioBusId
, AudioBusIdAllocator
, audioBusIdAllocator
, Allocators
, mkAllocators
) where
import Data.Int (Int32)
import Sound.SC3.Server.Allocator (IdAllocator(..), RangeAllocator(..))
import qualified Sound.SC3.Server.Allocator.BlockAllocator.FirstFit as FirstFitAllocator
import qualified Sound.SC3.Server.Allocator.Range as Range
import qualified Sound.SC3.Server.Allocator.SetAllocator as SetAllocator
import qualified Sound.SC3.Server.Allocator.SimpleAllocator as SimpleAllocator
import qualified Sound.SC3.Server.Allocator.Wrapped as Wrapped
import Sound.SC3.Server.Process.Options (ServerOptions(..))
-- | Synchronisation barrier id.
newtype SyncId = SyncId Int32 deriving (Bounded, Enum, Eq, Integral, Num, Ord, Real, Show)
-- | Synchronisation barrier id allocator.
data SyncIdAllocator = forall a . (IdAllocator a, Id a ~ SyncId) => SyncIdAllocator !a
instance IdAllocator SyncIdAllocator where
type Id SyncIdAllocator = SyncId
alloc (SyncIdAllocator a) = Wrapped.alloc SyncIdAllocator a
free i (SyncIdAllocator a) = Wrapped.free SyncIdAllocator i a
statistics (SyncIdAllocator a) = Wrapped.statistics a
-- | Node id.
newtype NodeId = NodeId Int32 deriving (Bounded, Enum, Eq, Integral, Num, Ord, Real, Show)
-- | Node id allocator.
data NodeIdAllocator = forall a . (IdAllocator a, Id a ~ NodeId) => NodeIdAllocator !a
instance IdAllocator NodeIdAllocator where
type Id NodeIdAllocator = NodeId
alloc (NodeIdAllocator a) = Wrapped.alloc NodeIdAllocator a
free i (NodeIdAllocator a) = Wrapped.free NodeIdAllocator i a
statistics (NodeIdAllocator a) = Wrapped.statistics a
-- | Buffer id.
newtype BufferId = BufferId Int32 deriving (Bounded, Enum, Eq, Integral, Num, Ord, Real, Show)
-- | Buffer id allocator.
data BufferIdAllocator = forall a . (RangeAllocator a, Id a ~ BufferId) => BufferIdAllocator !a
instance IdAllocator BufferIdAllocator where
type Id BufferIdAllocator = BufferId
alloc (BufferIdAllocator a) = Wrapped.alloc BufferIdAllocator a
free i (BufferIdAllocator a) = Wrapped.free BufferIdAllocator i a
statistics (BufferIdAllocator a) = Wrapped.statistics a
instance RangeAllocator BufferIdAllocator where
allocRange n (BufferIdAllocator a) = Wrapped.allocRange BufferIdAllocator n a
freeRange r (BufferIdAllocator a) = Wrapped.freeRange BufferIdAllocator r a
-- | Control bus id.
newtype ControlBusId = ControlBusId Int32
deriving (Bounded, Enum, Eq, Integral, Num, Ord, Real, Show)
-- | Control bus id allocator.
data ControlBusIdAllocator = forall a . (RangeAllocator a, Id a ~ ControlBusId) => ControlBusIdAllocator !a
instance IdAllocator ControlBusIdAllocator where
type Id ControlBusIdAllocator = ControlBusId
alloc (ControlBusIdAllocator a) = Wrapped.alloc ControlBusIdAllocator a
free i (ControlBusIdAllocator a) = Wrapped.free ControlBusIdAllocator i a
statistics (ControlBusIdAllocator a) = Wrapped.statistics a
instance RangeAllocator ControlBusIdAllocator where
allocRange n (ControlBusIdAllocator a) = Wrapped.allocRange ControlBusIdAllocator n a
freeRange r (ControlBusIdAllocator a) = Wrapped.freeRange ControlBusIdAllocator r a
-- | Audio bus id.
newtype AudioBusId = AudioBusId Int32
deriving (Bounded, Enum, Eq, Integral, Num, Ord, Real, Show)
-- | Audio bus id allocator.
data AudioBusIdAllocator = forall a . (RangeAllocator a, Id a ~ AudioBusId) => AudioBusIdAllocator !a
instance IdAllocator AudioBusIdAllocator where
type Id AudioBusIdAllocator = AudioBusId
alloc (AudioBusIdAllocator a) = Wrapped.alloc AudioBusIdAllocator a
free i (AudioBusIdAllocator a) = Wrapped.free AudioBusIdAllocator i a
statistics (AudioBusIdAllocator a) = Wrapped.statistics a
instance RangeAllocator AudioBusIdAllocator where
allocRange n (AudioBusIdAllocator a) = Wrapped.allocRange AudioBusIdAllocator n a
freeRange r (AudioBusIdAllocator a) = Wrapped.freeRange AudioBusIdAllocator r a
-- | Server allocators.
data Allocators = Allocators {
syncIdAllocator :: SyncIdAllocator
, nodeIdAllocator :: NodeIdAllocator
, bufferIdAllocator :: BufferIdAllocator
, audioBusIdAllocator :: AudioBusIdAllocator
, controlBusIdAllocator :: ControlBusIdAllocator
}
-- | Create a new state with default allocators.
mkAllocators :: ServerOptions -> Allocators
mkAllocators os =
Allocators {
syncIdAllocator =
SyncIdAllocator $
SimpleAllocator.cons
(Range.range 0 (maxBound :: SyncId))
, nodeIdAllocator =
NodeIdAllocator $
SetAllocator.cons
(Range.range 1000 (1000 + fromIntegral (maxNumberOfNodes os)))
, bufferIdAllocator =
BufferIdAllocator $
FirstFitAllocator.bestFit
FirstFitAllocator.LazyCoalescing
(Range.range 0 (fromIntegral (numberOfSampleBuffers os)))
, audioBusIdAllocator =
AudioBusIdAllocator $
FirstFitAllocator.bestFit
FirstFitAllocator.LazyCoalescing
(Range.range
(fromIntegral numHardwareChannels)
(fromIntegral (numHardwareChannels + numberOfAudioBusChannels os)))
, controlBusIdAllocator =
ControlBusIdAllocator $
FirstFitAllocator.bestFit
FirstFitAllocator.LazyCoalescing
(Range.range 0 (fromIntegral (numberOfControlBusChannels os)))
}
where
numHardwareChannels = numberOfInputBusChannels os
+ numberOfOutputBusChannels os
| kaoskorobase/hsc3-server | Sound/SC3/Server/State.hs | gpl-2.0 | 6,115 | 0 | 15 | 1,162 | 1,440 | 778 | 662 | 122 | 1 |
module Data.Pocketmine.Block
( BlockType(..) ) where
import Data.Maybe (fromJust)
import Data.Tuple (swap)
import qualified Data.Map as M
{-
- Yes, I know most of this code is terribly inefficient doing linear lookups
- for everything. However! I'm currently in the "make it work" phase, which comes
- before the "make it beautiful" phase, which comes before the "make it fast" phase.
-
- So it's ugly too.
-
- I know.
-}
data BlockType = Air | Stone | GrassBlock | Dirt | Cobblestone
| OakPlank | Sapling | Bedrock | Water | StationaryWater
| Lava | StationaryLava | Sand | Gravel | GoldOre
| IronOre | CoalOre | Wood | Leaves | Sponge
| Glass | LapisOre | LapisBlock | Sandstone | Bed
| PoweredRail | Cobweb | TallGrass | DeadBush | Wool
| Dandelion | Poppy | BrownMushroom | RedMushroom | GoldBlock
| IronBlock | DoubleStoneSlab | StoneSlab | BrickBlock | TNT
| Bookshelf | MossStone | Obsidian | Torch | Fire
| MonsterSpawner | OakStairs | Chest | DiamondOre | DiamondBlock
| CraftingTable | Seeds | Farmland | Furnace | BurningFurnace
| SignPost | OakDoor | Ladder | Rail | CobblestoneStairs
| WallSign | IronDoor | RedstoneOre | GlowingRedstoneOre | SnowCover
| Ice | Snow | Cactus | Clay | SugarCane
| Fence | Pumpkin | Netherrack | Glowstone | JackOLantern
| CakeBlock | InvisibleBedrock | Trapdoor | StoneBrick | HugeBrownMushroom
| HugeRedMushroom | IronBars | GlassPane | Melon | PumpkinStem
| MelonStem | Vines | FenceGate | BrickStairs | StoneBrickStairs
| Mycellium | LilyPad | NetherBrick | NetherBrickStairs | EndPortalFrame
| EndStone | Cocoa | SandstoneStairs | EmeraldOre | EmeraldBlock
| SpruceStairs | BirchStairs | JungleStairs | CobblestoneWall | Carrots
| Potato | QuartzBlock | QuartzStairs | OakDoubleSlab | OakSlab
| StainedClay | AcaciaStairs
| DarkOakStairs | HayBlock | Carpet | HardClay | CoalBlock
| PackedIce | LargeFern | Podzol | Beetroot | StoneCutter | GlowingObsidian
| NetherReactor | UpdateGameBE | UpdateGameLE | NameBlock | Unknown Int
deriving (Show, Eq, Ord)
instance Enum BlockType where
fromEnum (Unknown i) = i
fromEnum e = fromJust $ M.lookup e enumMap
toEnum i = maybe (Unknown i) id $ M.lookup i idMap
enumMap = M.fromList blockIds
idMap = M.fromList (map swap blockIds)
blockIds = [(Air, 0x00),
(Stone, 0x01),
(GrassBlock, 0x02),
(Dirt, 0x03),
(Cobblestone, 0x04),
(OakPlank, 0x05),
(Sapling, 0x06),
(Bedrock, 0x07),
(Water, 0x08),
(StationaryWater, 0x09),
(Lava, 0x0a),
(StationaryLava, 0x0b),
(Sand, 0x0c),
(Gravel, 0x0d),
(GoldOre, 0x0e),
(IronOre, 0x0f),
(CoalOre, 0x10),
(Wood, 0x11),
(Leaves, 0x12),
(Sponge, 0x13),
(Glass, 0x14),
(LapisOre, 0x15),
(LapisBlock, 0x16),
(Sandstone, 0x18),
(Bed, 0x1a),
(PoweredRail, 0x1b),
(Cobweb, 0x1e),
(TallGrass, 0x1f),
(DeadBush, 0x20),
(Wool, 0x23),
(Dandelion, 0x25),
(Poppy, 0x26),
(BrownMushroom, 0x27),
(RedMushroom, 0x28),
(GoldBlock, 0x29),
(IronBlock, 0x2a),
(DoubleStoneSlab, 0x2b),
(StoneSlab, 0x2c),
(BrickBlock, 0x2d),
(TNT, 0x2e),
(Bookshelf, 0x2f),
(MossStone, 0x30),
(Obsidian, 0x31),
(Torch, 0x32),
(Fire, 0x33),
(MonsterSpawner, 0x34),
(OakStairs, 0x35),
(Chest, 0x36),
(DiamondOre, 0x38),
(DiamondBlock, 0x39),
(CraftingTable, 0x3a),
(Seeds, 0x3b),
(Farmland, 0x3c),
(Furnace, 0x3d),
(BurningFurnace, 0x3e),
(SignPost, 0x3f),
(OakDoor, 0x40),
(Ladder, 0x41),
(Rail, 0x42),
(CobblestoneStairs, 0x43),
(WallSign, 0x44),
(IronDoor, 0x47),
(RedstoneOre, 0x49),
(GlowingRedstoneOre, 0x4a),
(SnowCover, 0x4e),
(Ice, 0x4f),
(Snow, 0x50),
(Cactus, 0x51),
(Clay, 0x52),
(SugarCane, 0x53),
(Fence, 0x55),
(Pumpkin, 0x56),
(Netherrack, 0x57),
(Glowstone, 0x59),
(JackOLantern, 0x5b),
(CakeBlock, 0x5c),
(InvisibleBedrock, 0x5f),
(Trapdoor, 0x60),
(StoneBrick, 0x62),
(HugeBrownMushroom, 0x63),
(HugeRedMushroom, 0x64),
(IronBars, 0x65),
(GlassPane, 0x66),
(Melon, 0x67),
(PumpkinStem, 0x68),
(MelonStem, 0x69),
(Vines, 0x6a),
(FenceGate, 0x6b),
(BrickStairs, 0x6c),
(StoneBrickStairs, 0x6d),
(Mycellium, 0x6e),
(LilyPad, 0x6f),
(NetherBrick, 0x70),
(NetherBrickStairs, 0x72),
(EndPortalFrame, 0x78),
(EndStone, 0x79),
(Cocoa, 0x7f),
(SandstoneStairs, 0x80),
(EmeraldOre, 0x81),
(EmeraldBlock, 0x85),
(SpruceStairs, 0x86),
(BirchStairs, 0x87),
(JungleStairs, 0x88),
(CobblestoneWall, 0x89),
(Carrots, 0x8d),
(Potato, 0x8e),
(QuartzBlock, 0x9b),
(QuartzStairs, 0x9c),
(OakDoubleSlab, 0x9d),
(OakSlab, 0x9e),
(StainedClay, 0x9f),
(AcaciaStairs, 0xa3),
(DarkOakStairs, 0xa4),
(HayBlock, 0xaa),
(Carpet, 0xab),
(HardClay, 0xac),
(CoalBlock, 0xad),
(PackedIce, 0xae),
(LargeFern, 0xaf),
(Podzol, 0xf3),
(Beetroot, 0xf4),
(StoneCutter, 0xf5),
(GlowingObsidian, 0xf6),
(NetherReactor, 0xf7),
(UpdateGameBE, 0xf8),
(UpdateGameLE, 0xf9),
(NameBlock, 0xff)]
| greyson/HasCraft | src/Data/Pocketmine/Block.hs | gpl-2.0 | 7,719 | 0 | 9 | 3,699 | 1,697 | 1,110 | 587 | 165 | 1 |
{-# LANGUAGE RecordWildCards #-}
module VirMat.IO.Export.ANG.RasterEngine
( rasterTriangle
, rasterTriangleFaster
, flexmicroToANG
, getGrainMeshAndProp
, isInsideTriangle
) where
import Data.Vector (Vector)
import Data.Maybe (fromMaybe)
import Data.List
import Data.Function
import DeUni.Dim2.Base2D
import DeUni.Types
import File.ANGReader
import Hammer.MicroGraph
import Linear.Vect
import Texture.Orientation
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.HashSet as HS
import VirMat.Core.FlexMicro
-- =============================== tools for ANG's grid ==================================
toGrid :: ANGgrid -> (Double, Double) -> (Int, Int)
toGrid g (x, y) = (i, j)
where
i = round $ (x - xmin) / stepx
j = round $ (y - ymin) / stepy
(stepx, stepy) = xystep g
(xmin, ymin, _) = origin g
fromGrid :: ANGgrid -> (Int, Int) -> (Double, Double)
fromGrid g (i, j) = (x, y)
where
x = fromIntegral i * stepx + xmin
y = fromIntegral j * stepy + ymin
(stepx, stepy) = xystep g
(xmin, ymin, _) = origin g
-- | Get the linear position of a given node in the ANG square mesh.
toLinPos :: ANGgrid -> (Int, Int) -> Int
toLinPos g = \(y, x) -> y * nx + x
where (_, nx, _) = rowCols g
-- | Calculate a square grid with same step size in both directions.
calculateGrid :: Double -> Box Vec2 -> ANGgrid
calculateGrid step box = let
dx = xMax2D box - xMin2D box
dy = yMax2D box - yMin2D box
nx = ceiling $ abs (dx / step)
ny = ceiling $ abs (dy / step)
in ANGgrid
{ rowCols = (ny, nx, nx)
, xystep = (step, step)
, origin = (xMin2D box, yMin2D box, 0)
, hexGrid = False
}
-- ================================= Fast rasterization ==================================
getSegSlope :: Vec2D -> Vec2D -> Double
getSegSlope (Vec2 v1x v1y) (Vec2 v2x v2y) = (v2x - v1x) / (v2y - v1y)
-- | Fill row between two points.
fillRow :: ANGgrid -> Int -> Double -> Double -> [(Int, Int)]
fillRow g yline xstart xfinal = let
xs = fst $ toGrid g (xstart, undefined)
xf = fst $ toGrid g (xfinal, undefined)
in [(x, yline) | x <- [min xs xf .. max xs xf]]
-- | Get range of row (starting row, number of rows)
getRowsRange :: ANGgrid -> Vec2D -> Vec2D -> (Int, Int)
getRowsRange g (Vec2 _ v1y) (Vec2 _ v2y) = (ya, abs $ yb - ya)
where
ya = snd $ toGrid g (undefined, v1y)
yb = snd $ toGrid g (undefined, v2y)
fillBottomFlatTriangle :: ANGgrid -> Vec2D -> Vec2D -> Vec2D -> [(Int, Int)]
fillBottomFlatTriangle g p1 p2 p3 = let
m1 = getSegSlope p1 p2
m2 = getSegSlope p1 p3
(ya, n) = getRowsRange g p1 p2
v1x = _1 p1
func i = fillRow g (ya+i) (v1x + m1* fromIntegral i) (v1x + m2 * fromIntegral i)
in concatMap func [0 .. n]
fillTopFlatTriangle :: ANGgrid -> Vec2D -> Vec2D -> Vec2D -> [(Int, Int)]
fillTopFlatTriangle g p1 p2 p3 = let
m1 = getSegSlope p3 p1
m2 = getSegSlope p3 p2
(ya, n) = getRowsRange g p3 p1
v3x = _1 p3
func i = fillRow g (ya-i) (v3x + m1 * fromIntegral i) (v3x + m2 * fromIntegral i)
in concatMap func [0 .. n]
-- | Fast rasterization algorithm for filled triangles. Splits the triangle, if it is
-- necessary, in two: one bottom-flat and one top-flat. Then fill both triangles row-by-row.
rasterTriangleFaster :: ANGgrid -> Vec2D -> Vec2D -> Vec2D -> [(Int, Int)]
rasterTriangleFaster g p1 p2 p3
-- in case of bottomflat triangle
| v2y == v3y = fillBottomFlatTriangle g v1 v2 v3
-- in case of topflat triangle
| v1y == v2y = fillTopFlatTriangle g v1 v2 v3
| otherwise = let
-- split the triangle in a topflat and bottomflat
v4 = Vec2 (v1x + ((v2y - v1y) / (v3y - v1y)) * (v3x - v1x)) v2y
in fillBottomFlatTriangle g v1 v2 v4
++ fillTopFlatTriangle g v2 v4 v3
where
-- sort the vertices by y-coordinate, the v1 is the topmost vertice
[v1, v2, v3] = sortBy (compare `on` _2) [p1, p2, p3]
Vec2 v1x v1y = v1
Vec2 _ v2y = v2
Vec2 v3x v3y = v3
-- ================================ Simple rasterization =================================
boundingBox :: ANGgrid -> Vec2D -> Vec2D -> Vec2D -> ((Int, Int), (Int, Int))
boundingBox g (Vec2 ax ay) (Vec2 bx by) (Vec2 cx cy) = let
ur = toGrid g (max (max ax bx) cx, max (max ay by) cy)
ll = toGrid g (min (min ax bx) cx, min (min ay by) cy)
in (ll, ur)
crossProduct :: Vec2D -> Vec2D -> Double
crossProduct (Vec2 ax ay) (Vec2 bx by) = ax*by - ay*bx
-- | Simple algorithm for filled triangle's rasterization but the not the fastest. Test
-- which nodes are inside the given triangle. Optimized by testing only the nodes from an
-- bounding box. Note that ratio area (triangle) / area (box) determines the efficiency of
-- this algorithm and the best case is 0.5 (50%).
rasterTriangle :: ANGgrid -> Vec2D -> Vec2D -> Vec2D -> [(Int, Int)]
rasterTriangle g p1 p2 p3 = let
((llx,lly), (urx, ury)) = boundingBox g p1 p2 p3
mesh = [(i, j) | i <- [llx..urx], j <- [lly..ury]]
-- using memorization of "isInsideTriangle p1 p2 p3"
func = isInsideTriangle (p1, p2, p3) . mkVec2 . fromGrid g
in filter func mesh
-- | Test if point is inside the triangle. It has memorization on the first parameter
-- (triangle) therefore call it with partial application.
isInsideTriangle :: (Vec2D, Vec2D, Vec2D) -> Vec2D -> Bool
isInsideTriangle (p1, p2, p3 )= let
-- memorization
vs1 = p2 &- p1
vs2 = p3 &- p1
k = crossProduct vs1 vs2
in \x -> let
p = x &- p1
s = crossProduct p vs2 / k
t = crossProduct vs1 p / k
-- is inside triangle?
in (s >= 0) && (t >= 0) && (s + t <= 1)
-- ================================= ANG Construction ====================================
-- | Information associated to each point. For futher reference consult OIM manual.
mkPoint :: Quaternion -> Double -> (Int, Int) -> Int -> ANGpoint
mkPoint q cindex (x, y) ph = ANGpoint
{ rotation = q
, xpos = x
, ypos = y
, iq = 100
, ci = cindex
, phaseNum = ph
, detecInt = 1
, fit = 1
}
-- | Information describing the measuriment.
einfo :: ANGinfo
einfo = ANGinfo
{ workDist = 16 -- Double
, pixperum = 1 -- Double
, operator = "VirMat" -- String
, sampleID = "007" -- String
, scanID = "666" -- String
}
feAlpha :: ANGphase
feAlpha = ANGphase
{ phase = 1
, materialName = "Iron (Alpha)"
, formula = "Fe"
, info = ""
, symmetry = "43"
, latticeCons = (2.87, 2.87, 2.87, 90, 90, 90)
, numFamilies = 0 -- Int
, hklFamilies = [] -- [(Int, Int, Int, Int, Double, Int)]
, elasticConst = [] -- [(Double, Double, Double, Double, Double, Double)]
, categories = (0,0,0,0,0)
}
mkBackground :: ANGgrid -> V.Vector ANGpoint
mkBackground g = let
(ny, nx, _) = rowCols g
toXY i = let (y, x) = i `quotRem` ny in (x, y)
nullPoint (x, y) = ANGpoint
{ rotation = zerorot
, xpos = x
, ypos = y
, iq = 100
, ci = -1
, phaseNum = 0
, detecInt = 1
, fit = 1
}
in V.generate (ny*nx) (nullPoint . toXY)
-- | Hold the whole ANG data strcuture
angInit :: Double -> Box Vec2 -> ANGdata
angInit step box = let
ginfo = calculateGrid step box
in ANGdata
{ nodes = mkBackground ginfo
, grid = ginfo
, ebsdInfo = einfo
, phases = [feAlpha]
}
-- ================================== Raster FlexMicro ===================================
getGrainMesh :: HS.HashSet FaceID -> Int -> FlexMicro Vec2 a -> Maybe (Vector Vec2D, Vector (Int, Int, Int))
getGrainMesh fs n FlexMicro2D{..} = let
func acc fid = maybe acc (V.snoc acc) (getPropValue =<< getFaceProp fid flexGraph2D)
es = HS.foldl' func V.empty fs
in getSubOneTriangulation n flexPoints2D es
-- | Extract the grain's value and its triangular mesh with a given level of subdivision.
-- INPUT: grain ID, level of mesh subdivision, microstructure. OUTPUT: (nodes, triangles, property)
getGrainMeshAndProp :: GrainID -> Int -> FlexMicro Vec2 g -> Maybe (Vector Vec2D, Vector (Int, Int, Int), g)
getGrainMeshAndProp gid n fm@FlexMicro2D{..} = do
(prop, grainConn) <- getPropBoth =<< getGrainProp gid flexGraph2D
(ps, ts) <- getGrainMesh grainConn n fm
return (ps, ts, prop)
-- | Transform a microstructure to ANG using raster algorithm. INPUT: level of subdivision,
-- step size, bounding box, microstructure. OUTPUT: ANG data structure
flexmicroToANG :: Int -> Double -> Box Vec2 -> FlexMicro Vec2 Quaternion -> ANGdata
flexmicroToANG n step box fm@FlexMicro2D{..} = let
a0 = angInit step box
gs = getGrainIDList flexGraph2D
toPos = toLinPos (grid a0)
func m gid = let
(ps, ts, q) = fromMaybe (V.empty, V.empty, zerorot) (getGrainMeshAndProp gid n fm)
fillTriangle (p1, p2, p3) = let
xys = rasterTriangle (grid a0) (ps V.! p1) (ps V.! p2) (ps V.! p3)
in mapM_ (\xy -> let pos = toPos xy in VM.write m pos (mkPoint q 1 xy 1)) xys
in V.mapM_ fillTriangle ts
in a0 {nodes = V.modify (\m -> mapM_ (func m) gs) (nodes a0)}
-- ====================================== testing ========================================
test :: ANGdata
test = let
step = 0.5
box = Box2D {xMax2D = 10, xMin2D = 0, yMax2D = 10, yMin2D = 0}
a0 = angInit step box
xys = rasterTriangle (grid a0) (Vec2 1 1.2) (Vec2 1.4 8) (Vec2 7.1 8.1)
func m = mapM_ (\xy -> let
pos = toLinPos (grid a0) xy
in VM.write m pos (mkPoint zerorot 1 xy 1)
) xys
in a0 {nodes = V.modify func (nodes a0)}
| lostbean/VirMat | src/VirMat/IO/Export/ANG/RasterEngine.hs | gpl-3.0 | 9,574 | 0 | 22 | 2,319 | 3,262 | 1,782 | 1,480 | 193 | 1 |
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies #-}
{-|
This module exports routes for all the files in the static directory at
compile time, allowing compile-time verification that referenced files
exist. However, any files added during run-time can't be accessed this
way; use their FilePath or URL to access them.
This is a separate module to satisfy template haskell requirements.
-}
module Hledger.Web.Settings.StaticFiles where
import Yesod.Static
import Hledger.Web.Settings (staticDir)
$(staticFiles staticDir)
| Lainepress/hledger | hledger-web/Hledger/Web/Settings/StaticFiles.hs | gpl-3.0 | 534 | 0 | 7 | 76 | 36 | 22 | 14 | 5 | 0 |
{-# LANGUAGE FlexibleContexts #-}
module Jumpie.Parsec(
int,
safeParseFromFile
) where
import Text.Parsec.Prim(Stream,ParsecT)
import Text.Parsec.String(parseFromFile,Parser)
import Text.Parsec(many1,digit)
import Text.Read(read)
import Data.List((++))
import Text.Show(show)
import Data.String(String)
import Control.Applicative((<$>))
import Prelude(Char,error)
import Data.Int(Int)
import System.IO(IO)
import Data.Either(Either(Left,Right))
import Data.Function(($))
import Control.Monad(return)
int :: Stream s m Char => ParsecT s u m Int
int = rd <$> many1 digit
where rd = read :: String -> Int
safeParseFromFile :: Parser a -> String -> IO a
safeParseFromFile p f = do
result <- parseFromFile p f
return $ case result of
Left e -> error $ "Parse error: " ++ (show e)
Right r -> r
| pmiddend/jumpie | lib/Jumpie/Parsec.hs | gpl-3.0 | 811 | 0 | 13 | 126 | 314 | 179 | 135 | 27 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Flat where
import Data.Vector
import Data.Time
import Data.Csv
csvTimeFormat :: String
csvTimeFormat = iso8601DateFormat (Just "%H:%M:%S%z")
data HouseType = HouseTypeFrame | -- Каркасный.
HouseTypeBlock | -- Блочный.
HouseTypeBrick | -- Кирпичный.
HouseTypePanel | -- Панельный.
HouseTypeSolid -- Монолитный.
deriving Eq
data Parking = ParkingNone |
ParkingStreet |
ParkingGarage
deriving Eq
data Flat = Flat { flatId :: Maybe String
, flatAuthorId :: Maybe String
, flatLatitude :: Maybe Double
, flatLongitude :: Maybe Double
, flatAddress :: Maybe String
, flatUserAddress :: Maybe String
, flatPrice :: Maybe Int
, flatResale :: Maybe Bool
, flatRooms :: Maybe Int
, flatTotalFloors :: Maybe Int
, flatFloor :: Maybe Int
, flatEstateAgency :: Maybe Bool
, flatTotalArea :: Maybe Double
, flatLivingArea :: Maybe Double
, flatKitchenArea :: Maybe Double
, flatCreated :: Maybe ZonedTime
, flatUpdated :: Maybe ZonedTime
, flatHouseType :: Maybe HouseType
, flatYear :: Maybe Int
, flatBalcony :: Maybe Bool
, flatParking :: Maybe Parking
, flatCeilingHeight :: Maybe Double
, flatCottage :: Maybe Bool
, flatActual :: Maybe Bool
, flatUrl :: Maybe String
}
instance ToNamedRecord Flat where
toNamedRecord flat =
namedRecord [ "id" .= flatId flat
, "author_id" .= flatAuthorId flat
, "latitude" .= flatLatitude flat
, "longitude" .= flatLongitude flat
, "address" .= flatAddress flat
, "user_address" .= flatUserAddress flat
, "price" .= flatPrice flat
, "resale" .= fmap encodeBool (flatResale flat)
, "rooms" .= flatRooms flat
, "total_floors" .= flatTotalFloors flat
, "floor" .= flatFloor flat
, "estate_agency" .= fmap encodeBool (flatEstateAgency flat)
, "total_area" .= flatTotalArea flat
, "living_area" .= flatLivingArea flat
, "kitchen_area" .= flatKitchenArea flat
, "created" .= fmap encodeTime (flatCreated flat)
, "updated" .= fmap encodeTime (flatUpdated flat)
, "house_type" .= fmap encodeHouseType (flatHouseType flat)
, "year" .= flatYear flat
, "balcony" .= fmap encodeBool (flatBalcony flat)
, "parking" .= fmap encodeParking (flatParking flat)
, "ceiling_height" .= flatCeilingHeight flat
, "cottage" .= fmap encodeBool (flatCottage flat)
, "actual" .= fmap encodeBool (flatActual flat)
, "url" .= flatUrl flat
] where
encodeBool :: Bool -> Int
encodeBool b = if b then 1 else 0
encodeTime :: ZonedTime -> String
encodeTime = formatTime defaultTimeLocale csvTimeFormat
encodeHouseType :: HouseType -> String
encodeHouseType HouseTypeFrame = "frame"
encodeHouseType HouseTypeBlock = "block"
encodeHouseType HouseTypeBrick = "brick"
encodeHouseType HouseTypePanel = "panel"
encodeHouseType HouseTypeSolid = "solid"
encodeParking :: Parking -> String
encodeParking ParkingNone = "none"
encodeParking ParkingStreet = "street"
encodeParking ParkingGarage = "garage"
instance DefaultOrdered Flat where
headerOrder _ = fromList [ "id"
, "author_id"
, "latitude"
, "longitude"
, "address"
, "user_address"
, "price"
, "resale"
, "rooms"
, "total_floors"
, "floor"
, "estate_agency"
, "total_area"
, "living_area"
, "kitchen_area"
, "created"
, "updated"
, "house_type"
, "year"
, "balcony"
, "parking"
, "ceiling_height"
, "cottage"
, "actual"
, "url"
]
| kurnevsky/flats | src/Flat.hs | agpl-3.0 | 4,958 | 0 | 11 | 2,165 | 879 | 478 | 401 | 109 | 1 |
module Ch22Exercises where
import Control.Applicative
import Data.Maybe
x :: [Integer]
x = [1, 2, 3]
y :: [Integer]
y = [4, 5, 6]
z :: [Integer]
z = [7, 8, 9]
xs :: Maybe Integer
xs = lookup 3 $ zip x y
ys :: Maybe Integer
ys = lookup 6 $ zip y z
zs :: Maybe Integer
zs = lookup 4 $ zip x y
z' :: Integer -> Maybe Integer
z' n = lookup n $ zip x z
x1 :: Maybe (Integer, Integer)
x1 = (,) <$> xs <*> ys
x2 :: Maybe (Integer, Integer)
x2 = (,) <$> ys <*> zs
x3 :: Integer -> (Maybe Integer, Maybe Integer)
x3 = (,) <$> z' <*> z'
summed :: Num c => (c, c) -> c
summed = uncurry (+)
bolt :: Integer -> Bool
bolt = (&&) <$> (>3) <*> (<8)
seqA :: Integral a => a -> [Bool]
seqA = sequenceA [(>3), (<8), even]
s' :: Maybe Integer
s' = summed <$> ((,) <$> xs <*> ys)
main :: IO ()
main = do
print $ sequenceA [Just 3 :: Maybe Integer, Just 2, Just 1]
print $ sequenceA [x, y]
print $ sequenceA [xs, ys]
print $ summed <$> ((,) <$> xs <*> ys)
print $ fmap summed ((,) <$> xs <*> zs)
print $ bolt 7
print $ fmap bolt z
print $ sequenceA [(>3), (<8), even] (7 :: Integer)
print $ and . seqA $ (5 :: Integer)
print $ seqA . fromMaybe 0 $ s'
print $ bolt . fromMaybe 0 $ s'
| thewoolleyman/haskellbook | 22/11/maor/Ch22Exercises.hs | unlicense | 1,199 | 0 | 12 | 301 | 669 | 360 | 309 | 44 | 1 |
module HelperSequences.A006519Spec (main, spec) where
import Test.Hspec
import HelperSequences.A006519 (a006519)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A006519" $
it "correctly computes the first 20 elements" $
take 20 (map a006519 [1..]) `shouldBe` expectedValue where
expectedValue = [1,2,1,4,1,2,1,8,1,2,1,4,1,2,1,16,1,2,1,4]
| peterokagey/haskellOEIS | test/HelperSequences/A006519Spec.hs | apache-2.0 | 366 | 0 | 10 | 59 | 160 | 95 | 65 | 10 | 1 |
{-# LANGUAGE PackageImports #-}
import "ministeam" Application (getApplicationDev)
import Network.Wai.Handler.Warp
(runSettings, defaultSettings, settingsPort)
import Control.Concurrent (forkIO)
import System.Directory (doesFileExist, removeFile)
import System.Exit (exitSuccess)
import Control.Concurrent (threadDelay)
main :: IO ()
main = do
putStrLn "Starting devel application"
(port, app) <- getApplicationDev
forkIO $ runSettings defaultSettings
{ settingsPort = port
} app
loop
loop :: IO ()
loop = do
threadDelay 100000
e <- doesFileExist "dist/devel-terminate"
if e then terminateDevel else loop
terminateDevel :: IO ()
terminateDevel = exitSuccess
| XxNocturnxX/ministeam | devel.hs | bsd-2-clause | 703 | 0 | 10 | 123 | 186 | 101 | 85 | 23 | 2 |
module Foundation
( App (..)
, Route (..)
, AppMessage (..)
, resourcesApp
, Handler
, Widget
, Form
, maybeAuth
, requireAuth
, module Settings
, module Model
) where
import Prelude
import Yesod
import Yesod.Static
import Yesod.Auth
import Yesod.Auth.BrowserId
import Yesod.Auth.GoogleEmail
import Yesod.Default.Config
import Yesod.Default.Util (addStaticContentExternal)
import Yesod.Logger (Logger, logMsg, formatLogText)
import Network.HTTP.Conduit (Manager)
import qualified Settings
import qualified Database.Persist.Store
import Settings.StaticFiles
import Database.Persist.MongoDB
import Settings (widgetFile, Extra (..))
import Model
import Text.Jasmine (minifym)
import Web.ClientSession (getKey)
import Text.Hamlet (hamletFile)
-- | The site argument for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have
-- access to the data present here.
data App = App
{ settings :: AppConfig DefaultEnv Extra
, getLogger :: Logger
, getStatic :: Static -- ^ Settings for static file serving.
, connPool :: Database.Persist.Store.PersistConfigPool Settings.PersistConfig -- ^ Database connection pool.
, httpManager :: Manager
, persistConfig :: Settings.PersistConfig
}
-- Set up i18n messages. See the message folder.
mkMessage "App" "messages" "en"
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
-- http://www.yesodweb.com/book/handler
--
-- This function does three things:
--
-- * Creates the route datatype AppRoute. Every valid URL in your
-- application can be represented as a value of this type.
-- * Creates the associated type:
-- type instance Route App = AppRoute
-- * Creates the value resourcesApp which contains information on the
-- resources declared below. This is used in Handler.hs by the call to
-- mkYesodDispatch
--
-- What this function does *not* do is create a YesodSite instance for
-- App. Creating that instance requires all of the handler functions
-- for our application to be in scope. However, the handler functions
-- usually require access to the AppRoute datatype. Therefore, we
-- split these actions into two functions and place them in separate files.
mkYesodData "App" $(parseRoutesFile "config/routes")
type Form x = Html -> MForm App App (FormResult x, Widget)
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod App where
approot = ApprootMaster $ appRoot . settings
-- Store session data on the client in encrypted cookies,
-- default session idle timeout is 120 minutes
makeSessionBackend _ = do
key <- getKey "config/client_session_key.aes"
return . Just $ clientSessionBackend key 120
defaultLayout widget = do
master <- getYesod
mmsg <- getMessage
-- We break up the default layout into two components:
-- default-layout is the contents of the body tag, and
-- default-layout-wrapper is the entire page. Since the final
-- value passed to hamletToRepHtml cannot be a widget, this allows
-- you to use normal widget features in default-layout.
pc <- widgetToPageContent $ do
$(widgetFile "normalize")
addStylesheet $ StaticR css_bootstrap_css
$(widgetFile "default-layout")
hamletToRepHtml $(hamletFile "templates/default-layout-wrapper.hamlet")
-- This is done to provide an optimization for serving static files from
-- a separate domain. Please see the staticRoot setting in Settings.hs
urlRenderOverride y (StaticR s) =
Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s
urlRenderOverride _ _ = Nothing
-- The page to be redirected to when authentication is required.
authRoute _ = Just $ AuthR LoginR
messageLogger y loc level msg =
formatLogText (getLogger y) loc level msg >>= logMsg (getLogger y)
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent = addStaticContentExternal minifym base64md5 Settings.staticDir (StaticR . flip StaticRoute [])
-- Place Javascript at bottom of the body tag so the rest of the page loads first
jsLoader _ = BottomOfBody
-- How to run database actions.
instance YesodPersist App where
type YesodPersistBackend App = Action
runDB f = do
master <- getYesod
Database.Persist.Store.runPool
(persistConfig master)
f
(connPool master)
instance YesodAuth App where
type AuthId App = UserId
-- Where to send a user after successful login
loginDest _ = HomeR
-- Where to send a user after logout
logoutDest _ = HomeR
getAuthId creds = runDB $ do
x <- getBy $ UniqueUser $ credsIdent creds
case x of
Just (Entity uid _) -> return $ Just uid
Nothing -> do
fmap Just $ insert $ User (credsIdent creds) Nothing
-- You can add other plugins like BrowserID, email or OAuth here
authPlugins _ = [authBrowserId, authGoogleEmail]
authHttpManager = httpManager
-- This instance is required to use forms. You can modify renderMessage to
-- achieve customized and internationalized form validation messages.
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
-- Note: previous versions of the scaffolding included a deliver function to
-- send emails. Unfortunately, there are too many different options for us to
-- give a reasonable default. Instead, the information is available on the
-- wiki:
--
-- https://github.com/yesodweb/yesod/wiki/Sending-email
| jgenso/comunidadhaskell.org | Foundation.hs | bsd-2-clause | 6,083 | 0 | 17 | 1,324 | 871 | 487 | 384 | -1 | -1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGraphicsPathItem_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.QGraphicsPathItem_h where
import Foreign.C.Types
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QGraphicsItem
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 (QGraphicsPathItem ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPathItem_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QGraphicsPathItem_unSetUserMethod" qtc_QGraphicsPathItem_unSetUserMethod :: Ptr (TQGraphicsPathItem a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QGraphicsPathItemSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPathItem_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QGraphicsPathItem ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPathItem_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QGraphicsPathItemSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPathItem_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QGraphicsPathItem ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPathItem_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QGraphicsPathItemSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsPathItem_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGraphicsPathItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGraphicsPathItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsPathItem_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem 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_QGraphicsPathItem_setUserMethod" qtc_QGraphicsPathItem_setUserMethod :: Ptr (TQGraphicsPathItem a) -> CInt -> Ptr (Ptr (TQGraphicsPathItem x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsPathItem :: (Ptr (TQGraphicsPathItem x0) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsPathItem_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGraphicsPathItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGraphicsPathItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsPathItem_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem 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 (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGraphicsPathItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGraphicsPathItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsPathItem_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem 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_QGraphicsPathItem_setUserMethodVariant" qtc_QGraphicsPathItem_setUserMethodVariant :: Ptr (TQGraphicsPathItem a) -> CInt -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsPathItem :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsPathItem_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGraphicsPathItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGraphicsPathItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsPathItem_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem 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 (QGraphicsPathItem ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGraphicsPathItem_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QGraphicsPathItem_unSetHandler" qtc_QGraphicsPathItem_unSetHandler :: Ptr (TQGraphicsPathItem a) -> CWString -> IO (CBool)
instance QunSetHandler (QGraphicsPathItemSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGraphicsPathItem_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> IO (QRectF t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQRectF t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf 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_QGraphicsPathItem_setHandler1" qtc_QGraphicsPathItem_setHandler1 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQRectF t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem1 :: (Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQRectF t0))) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQRectF t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> IO (QRectF t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQRectF t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf 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 QqqboundingRect_h (QGraphicsPathItem ()) (()) where
qqboundingRect_h x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_boundingRect cobj_x0
foreign import ccall "qtc_QGraphicsPathItem_boundingRect" qtc_QGraphicsPathItem_boundingRect :: Ptr (TQGraphicsPathItem a) -> IO (Ptr (TQRectF ()))
instance QqqboundingRect_h (QGraphicsPathItemSc a) (()) where
qqboundingRect_h x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_boundingRect cobj_x0
instance QqboundingRect_h (QGraphicsPathItem ()) (()) where
qboundingRect_h x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
foreign import ccall "qtc_QGraphicsPathItem_boundingRect_qth" qtc_QGraphicsPathItem_boundingRect_qth :: Ptr (TQGraphicsPathItem a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QqboundingRect_h (QGraphicsPathItemSc a) (()) where
qboundingRect_h x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QPointF t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQPointF t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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_QGraphicsPathItem_setHandler2" qtc_QGraphicsPathItem_setHandler2 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem2 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPointF t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QPointF t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQPointF t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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 Qqcontains_h (QGraphicsPathItem ()) ((PointF)) where
qcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsPathItem_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y
foreign import ccall "qtc_QGraphicsPathItem_contains_qth" qtc_QGraphicsPathItem_contains_qth :: Ptr (TQGraphicsPathItem a) -> CDouble -> CDouble -> IO CBool
instance Qqcontains_h (QGraphicsPathItemSc a) ((PointF)) where
qcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsPathItem_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y
instance Qqqcontains_h (QGraphicsPathItem ()) ((QPointF t1)) where
qqcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_contains cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_contains" qtc_QGraphicsPathItem_contains :: Ptr (TQGraphicsPathItem a) -> Ptr (TQPointF t1) -> IO CBool
instance Qqqcontains_h (QGraphicsPathItemSc a) ((QPointF t1)) where
qqcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_contains cobj_x0 cobj_x1
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QGraphicsItem t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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_QGraphicsPathItem_setHandler3" qtc_QGraphicsPathItem_setHandler3 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem3 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QGraphicsItem t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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 QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr 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_QGraphicsPathItem_setHandler4" qtc_QGraphicsPathItem_setHandler4 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem4 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr 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 QisObscuredBy_h (QGraphicsPathItem ()) ((QGraphicsItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_isObscuredBy cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_isObscuredBy" qtc_QGraphicsPathItem_isObscuredBy :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QisObscuredBy_h (QGraphicsPathItemSc a) ((QGraphicsItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_isObscuredBy cobj_x0 cobj_x1
instance QisObscuredBy_h (QGraphicsPathItem ()) ((QGraphicsTextItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_isObscuredBy_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_isObscuredBy_graphicstextitem" qtc_QGraphicsPathItem_isObscuredBy_graphicstextitem :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QisObscuredBy_h (QGraphicsPathItemSc a) ((QGraphicsTextItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_isObscuredBy_graphicstextitem cobj_x0 cobj_x1
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> IO (QPainterPath t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQPainterPath t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf 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_QGraphicsPathItem_setHandler5" qtc_QGraphicsPathItem_setHandler5 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQPainterPath t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem5 :: (Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQPainterPath t0))) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQPainterPath t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> IO (QPainterPath t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> IO (Ptr (TQPainterPath t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf 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 QopaqueArea_h (QGraphicsPathItem ()) (()) where
opaqueArea_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_opaqueArea cobj_x0
foreign import ccall "qtc_QGraphicsPathItem_opaqueArea" qtc_QGraphicsPathItem_opaqueArea :: Ptr (TQGraphicsPathItem a) -> IO (Ptr (TQPainterPath ()))
instance QopaqueArea_h (QGraphicsPathItemSc a) (()) where
opaqueArea_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_opaqueArea cobj_x0
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- qObjectFromPtr x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
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_QGraphicsPathItem_setHandler6" qtc_QGraphicsPathItem_setHandler6 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem6 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- qObjectFromPtr x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
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 Qpaint_h (QGraphicsPathItem ()) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where
paint_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGraphicsPathItem_paint1 cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QGraphicsPathItem_paint1" qtc_QGraphicsPathItem_paint1 :: Ptr (TQGraphicsPathItem a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionGraphicsItem t2) -> Ptr (TQWidget t3) -> IO ()
instance Qpaint_h (QGraphicsPathItemSc a) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where
paint_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGraphicsPathItem_paint1 cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance Qshape_h (QGraphicsPathItem ()) (()) where
shape_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_shape cobj_x0
foreign import ccall "qtc_QGraphicsPathItem_shape" qtc_QGraphicsPathItem_shape :: Ptr (TQGraphicsPathItem a) -> IO (Ptr (TQPainterPath ()))
instance Qshape_h (QGraphicsPathItemSc a) (()) where
shape_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_shape cobj_x0
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf 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_QGraphicsPathItem_setHandler7" qtc_QGraphicsPathItem_setHandler7 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem7 :: (Ptr (TQGraphicsPathItem x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf 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 Qqtype_h (QGraphicsPathItem ()) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_type cobj_x0
foreign import ccall "qtc_QGraphicsPathItem_type" qtc_QGraphicsPathItem_type :: Ptr (TQGraphicsPathItem a) -> IO CInt
instance Qqtype_h (QGraphicsPathItemSc a) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_type cobj_x0
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> CInt -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1int = fromCInt x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int
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_QGraphicsPathItem_setHandler8" qtc_QGraphicsPathItem_setHandler8 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem8 :: (Ptr (TQGraphicsPathItem x0) -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> CInt -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1int = fromCInt x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int
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 Qadvance_h (QGraphicsPathItem ()) ((Int)) where
advance_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_advance cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGraphicsPathItem_advance" qtc_QGraphicsPathItem_advance :: Ptr (TQGraphicsPathItem a) -> CInt -> IO ()
instance Qadvance_h (QGraphicsPathItemSc a) ((Int)) where
advance_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_advance cobj_x0 (toCInt x1)
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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_QGraphicsPathItem_setHandler9" qtc_QGraphicsPathItem_setHandler9 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem9 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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 QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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_QGraphicsPathItem_setHandler10" qtc_QGraphicsPathItem_setHandler10 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem10 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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 QcollidesWithItem_h (QGraphicsPathItem ()) ((QGraphicsItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithItem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_collidesWithItem" qtc_QGraphicsPathItem_collidesWithItem :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QcollidesWithItem_h (QGraphicsPathItemSc a) ((QGraphicsItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithItem cobj_x0 cobj_x1
instance QcollidesWithItem_h (QGraphicsPathItem ()) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsPathItem_collidesWithItem1" qtc_QGraphicsPathItem_collidesWithItem1 :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsItem t1) -> CLong -> IO CBool
instance QcollidesWithItem_h (QGraphicsPathItemSc a) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QcollidesWithItem_h (QGraphicsPathItem ()) ((QGraphicsTextItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithItem_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_collidesWithItem_graphicstextitem" qtc_QGraphicsPathItem_collidesWithItem_graphicstextitem :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QcollidesWithItem_h (QGraphicsPathItemSc a) ((QGraphicsTextItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithItem_graphicstextitem cobj_x0 cobj_x1
instance QcollidesWithItem_h (QGraphicsPathItem ()) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsPathItem_collidesWithItem1_graphicstextitem" qtc_QGraphicsPathItem_collidesWithItem1_graphicstextitem :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsTextItem t1) -> CLong -> IO CBool
instance QcollidesWithItem_h (QGraphicsPathItemSc a) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QPainterPath t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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_QGraphicsPathItem_setHandler11" qtc_QGraphicsPathItem_setHandler11 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem11 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QPainterPath t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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 QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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_QGraphicsPathItem_setHandler12" qtc_QGraphicsPathItem_setHandler12 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem12 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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 QcollidesWithPath_h (QGraphicsPathItem ()) ((QPainterPath t1)) where
collidesWithPath_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithPath cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_collidesWithPath" qtc_QGraphicsPathItem_collidesWithPath :: Ptr (TQGraphicsPathItem a) -> Ptr (TQPainterPath t1) -> IO CBool
instance QcollidesWithPath_h (QGraphicsPathItemSc a) ((QPainterPath t1)) where
collidesWithPath_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithPath cobj_x0 cobj_x1
instance QcollidesWithPath_h (QGraphicsPathItem ()) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsPathItem_collidesWithPath1" qtc_QGraphicsPathItem_collidesWithPath1 :: Ptr (TQGraphicsPathItem a) -> Ptr (TQPainterPath t1) -> CLong -> IO CBool
instance QcollidesWithPath_h (QGraphicsPathItemSc a) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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_QGraphicsPathItem_setHandler13" qtc_QGraphicsPathItem_setHandler13 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem13 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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 QcontextMenuEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_contextMenuEvent" qtc_QGraphicsPathItem_contextMenuEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_contextMenuEvent cobj_x0 cobj_x1
instance QdragEnterEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_dragEnterEvent" qtc_QGraphicsPathItem_dragEnterEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragEnterEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_dragLeaveEvent" qtc_QGraphicsPathItem_dragLeaveEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragLeaveEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_dragMoveEvent" qtc_QGraphicsPathItem_dragMoveEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragMoveEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_dropEvent" qtc_QGraphicsPathItem_dropEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdropEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_dropEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QGraphicsPathItem ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_focusInEvent" qtc_QGraphicsPathItem_focusInEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QGraphicsPathItemSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QGraphicsPathItem ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_focusOutEvent" qtc_QGraphicsPathItem_focusOutEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QGraphicsPathItemSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_focusOutEvent cobj_x0 cobj_x1
instance QhoverEnterEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_hoverEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_hoverEnterEvent" qtc_QGraphicsPathItem_hoverEnterEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverEnterEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_hoverEnterEvent cobj_x0 cobj_x1
instance QhoverLeaveEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_hoverLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_hoverLeaveEvent" qtc_QGraphicsPathItem_hoverLeaveEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverLeaveEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_hoverLeaveEvent cobj_x0 cobj_x1
instance QhoverMoveEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_hoverMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_hoverMoveEvent" qtc_QGraphicsPathItem_hoverMoveEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverMoveEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_hoverMoveEvent cobj_x0 cobj_x1
instance QinputMethodEvent_h (QGraphicsPathItem ()) ((QInputMethodEvent t1)) where
inputMethodEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_inputMethodEvent" qtc_QGraphicsPathItem_inputMethodEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent_h (QGraphicsPathItemSc a) ((QInputMethodEvent t1)) where
inputMethodEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_inputMethodEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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_QGraphicsPathItem_setHandler14" qtc_QGraphicsPathItem_setHandler14 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem14 :: (Ptr (TQGraphicsPathItem x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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 (QGraphicsPathItem ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGraphicsPathItem_inputMethodQuery" qtc_QGraphicsPathItem_inputMethodQuery :: Ptr (TQGraphicsPathItem a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QGraphicsPathItemSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsPathItem_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum x2obj
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_QGraphicsPathItem_setHandler15" qtc_QGraphicsPathItem_setHandler15 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem15 :: (Ptr (TQGraphicsPathItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem15_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum x2obj
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 QitemChange_h (QGraphicsPathItem ()) ((GraphicsItemChange, QVariant t2)) where
itemChange_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPathItem_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
foreign import ccall "qtc_QGraphicsPathItem_itemChange" qtc_QGraphicsPathItem_itemChange :: Ptr (TQGraphicsPathItem a) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant ()))
instance QitemChange_h (QGraphicsPathItemSc a) ((GraphicsItemChange, QVariant t2)) where
itemChange_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPathItem_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
instance QkeyPressEvent_h (QGraphicsPathItem ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_keyPressEvent" qtc_QGraphicsPathItem_keyPressEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QGraphicsPathItemSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_keyPressEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QGraphicsPathItem ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_keyReleaseEvent" qtc_QGraphicsPathItem_keyReleaseEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QGraphicsPathItemSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_keyReleaseEvent cobj_x0 cobj_x1
instance QmouseDoubleClickEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_mouseDoubleClickEvent" qtc_QGraphicsPathItem_mouseDoubleClickEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_mouseMoveEvent" qtc_QGraphicsPathItem_mouseMoveEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_mousePressEvent" qtc_QGraphicsPathItem_mousePressEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_mouseReleaseEvent" qtc_QGraphicsPathItem_mouseReleaseEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_mouseReleaseEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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_QGraphicsPathItem_setHandler16" qtc_QGraphicsPathItem_setHandler16 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem16 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem16_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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 QsceneEvent_h (QGraphicsPathItem ()) ((QEvent t1)) where
sceneEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_sceneEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_sceneEvent" qtc_QGraphicsPathItem_sceneEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQEvent t1) -> IO CBool
instance QsceneEvent_h (QGraphicsPathItemSc a) ((QEvent t1)) where
sceneEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_sceneEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf 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_QGraphicsPathItem_setHandler17" qtc_QGraphicsPathItem_setHandler17 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem17 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem17_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf 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 QsetHandler (QGraphicsPathItem ()) (QGraphicsPathItem x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf 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_QGraphicsPathItem_setHandler18" qtc_QGraphicsPathItem_setHandler18 :: Ptr (TQGraphicsPathItem a) -> CWString -> Ptr (Ptr (TQGraphicsPathItem 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_QGraphicsPathItem18 :: (Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsPathItem18_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsPathItemSc a) (QGraphicsPathItem x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsPathItem18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsPathItem18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsPathItem_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsPathItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf 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 QsceneEventFilter_h (QGraphicsPathItem ()) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPathItem_sceneEventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsPathItem_sceneEventFilter" qtc_QGraphicsPathItem_sceneEventFilter :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter_h (QGraphicsPathItemSc a) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPathItem_sceneEventFilter cobj_x0 cobj_x1 cobj_x2
instance QsceneEventFilter_h (QGraphicsPathItem ()) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPathItem_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsPathItem_sceneEventFilter_graphicstextitem" qtc_QGraphicsPathItem_sceneEventFilter_graphicstextitem :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter_h (QGraphicsPathItemSc a) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsPathItem_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2
instance QwheelEvent_h (QGraphicsPathItem ()) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsPathItem_wheelEvent" qtc_QGraphicsPathItem_wheelEvent :: Ptr (TQGraphicsPathItem a) -> Ptr (TQGraphicsSceneWheelEvent t1) -> IO ()
instance QwheelEvent_h (QGraphicsPathItemSc a) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsPathItem_wheelEvent cobj_x0 cobj_x1
| keera-studios/hsQt | Qtc/Gui/QGraphicsPathItem_h.hs | bsd-2-clause | 98,043 | 0 | 18 | 20,812 | 30,664 | 14,671 | 15,993 | -1 | -1 |
module Frontend.Val(Val(..),
TVal(TVal),
WithVal(..)) where
import qualified Data.Map as M
import Name
import Frontend.NS
import Frontend.Expr
import Frontend.Type
-- Value
data Val = BoolVal Bool
| IntVal Integer
| StructVal (M.Map Ident TVal)
| EnumVal Ident
| PtrVal LExpr
-- | ArrayVal [TVal]
| NondetVal
class WithVal a where
val :: a -> Val
data TVal = TVal {ttyp::Type, tval::Val}
instance WithType TVal where
typ = ttyp
instance WithVal TVal where
val = tval
-- Assumed comparable types
instance Eq Val where
(==) (BoolVal b1) (BoolVal b2) = b1 == b2
(==) (IntVal i1) (IntVal i2) = i1 == i2
(==) (StructVal s1) (StructVal s2) = and $ map (uncurry (==)) (zip (map snd $ M.toList s1) (map snd $ M.toList s2))
(==) (PtrVal p1) (PtrVal p2) = error $ "Eq PtrVal not implemented"
-- (==) (ArrayVal a1) (ArrayVal a2) = and $ map (uncurry (==)) (zip a1 a2)
(==) _ _ = False
instance Eq TVal where
(==) (TVal t1 v1) (TVal t2 v2) = v1 == v2
instance Ord Val where
compare (IntVal i1) (IntVal i2) = compare i1 i2
compare _ _ = error "Incomparable values in Ord Val"
instance Ord TVal where
compare (TVal t1 v1) (TVal t2 v2) = compare v1 v2
| termite2/tsl | Frontend/Val.hs | bsd-3-clause | 1,399 | 0 | 13 | 469 | 476 | 260 | 216 | 36 | 0 |
import Data.Foldable (foldMap, foldr)
import Data.Monoid
import Data.Maybe
newtype Min a = Min { getMin :: Maybe a } deriving (Eq, Ord, Show)
newtype Max a = Max { getMax :: Maybe a } deriving (Eq, Ord, Show)
instance Ord a => Monoid (Min a) where
mempty = Min Nothing
Min (Nothing) `mappend` y = y
x `mappend` Min (Nothing) = x
Min (Just x) `mappend` Min (Just y) = Min $ Just (min x y)
instance Ord a => Monoid (Max a) where
mempty = Max Nothing
Max (Nothing) `mappend` y = y
x `mappend` Max (Nothing) = x
Max (Just x) `mappend` Max (Just y) = Max $ Just (max x y)
sum' :: (Foldable t, Num a) => t a -> a
sum' = foldr (+) 0
sum'' :: (Foldable t, Num a) => t a -> a
sum'' = getSum . foldMap Sum
product' :: (Foldable t, Num a) => t a -> a
product' = foldr (*) 1
product'' :: (Foldable t, Num a) => t a -> a
product'' = getProduct . foldMap Product
elem' :: (Functor t, Foldable t, Eq a) => a -> t a -> Bool
elem' a = getAny . foldMap Any . fmap (== a)
elem'' :: (Foldable t, Eq a) => a -> t a -> Bool
elem'' = any . (==)
minimum' :: (Foldable t, Ord a) => t a -> Maybe a
minimum' = foldr maybeMin Nothing
where maybeMin x Nothing = Just x
maybeMin x (Just y) = Just $ min x y
-- implement with foldMap needs a helper monoid (Min a)
minimum'' :: (Monoid a, Foldable t, Ord a) => t a -> Maybe a
minimum'' = getMin . foldMap (Min . Just)
maximum' :: (Foldable t, Ord a) => t a -> Maybe a
maximum' = foldr maybeMin Nothing
where maybeMin x Nothing = Just x
maybeMin x (Just y) = Just $ max x y
-- implement with foldMap needs a helper monoid (Min a)
maximum'' :: (Monoid a, Foldable t, Ord a) => t a -> Maybe a
maximum'' = getMax . foldMap (Max . Just)
-- using foldr
null' :: (Foldable t) => t a -> Bool
null' = foldr (\_ _ -> False) True
-- using foldMap
null'' :: (Foldable t) => t a -> Bool
null'' = getAll . foldMap (All . (\_ -> False))
-- using foldr
length' :: (Foldable t) => t a -> Int
length' = foldr (\_ b -> b + 1) 0
-- using foldMap
length'' :: (Foldable t) => t a -> Int
length'' = getSum . foldMap (Sum . (\_ -> 1))
-- using foldr
toList' :: (Foldable t) => t a -> [a]
toList' = foldr (\a b -> a : b) []
-- using foldMap
toList'' :: (Foldable t) => t a -> [a]
toList'' = foldMap (\a -> [a])
-- using foldMap
fold' :: (Foldable t, Monoid m) => t m -> m
fold' = foldMap id
-- using foldr
foldMap' :: (Foldable t, Monoid m) => (a -> m) -> t a -> m
foldMap' f = foldr (\a b -> f a <> b) mempty
| chengzh2008/hpffp | src/ch20-Foldable/foldable.hs | bsd-3-clause | 2,460 | 0 | 10 | 587 | 1,233 | 647 | 586 | 55 | 2 |
{-# LANGUAGE RankNTypes #-}
{-| Generic equal temperament pitch.
Use the type-level numbers to construct an temperement dividing
the octave in any number of equal-sized steps.
Common cases such as 6, 12 and 24 are provided for convenience.
-}
module Music.Pitch.Equal
(
-- * Equal temperament
Equal,
toEqual,
fromEqual,
equalToRatio,
size,
cast,
-- ** Synonyms
Equal6,
Equal12,
Equal17,
Equal24,
Equal36,
-- ** Extra type-level naturals
N20,
N30,
N17,
N24,
N36,
)
where
import Data.Maybe
import Data.Either
import Data.Semigroup
import Data.VectorSpace
import Data.AffineSpace
import Control.Monad
import Control.Applicative
import Music.Pitch.Absolute
import TypeUnary.Nat
-- Based on Data.Fixed
newtype Equal a = Equal { getEqual :: Int }
deriving instance Eq (Equal a)
deriving instance Ord (Equal a)
instance Show (Equal a) where
show (Equal a) = show a
-- OR:
-- showsPrec d (Equal x) = showParen (d > app_prec) $
-- showString "Equal " . showsPrec (app_prec+1) x
-- where app_prec = 10
instance IsNat a => Num (Equal a) where
Equal a + Equal b = Equal (a + b)
Equal a * Equal b = Equal (a * b)
negate (Equal a) = Equal (negate a)
abs (Equal a) = Equal (abs a)
signum (Equal a) = Equal (signum a)
fromInteger = toEqual . fromIntegral
instance IsNat a => Semigroup (Equal a) where
(<>) = (+)
instance IsNat a => Monoid (Equal a) where
mempty = 0
mappend = (+)
instance IsNat a => AdditiveGroup (Equal a) where
zeroV = 0
(^+^) = (+)
negateV = negate
instance IsNat a => VectorSpace (Equal a) where
type Scalar (Equal a) = Equal a
(*^) = (*)
-- Convenience to avoid ScopedTypeVariables etc
getSize :: IsNat a => Equal a -> Nat a
getSize _ = nat
{-| Size of this type (value not evaluated).
>>> size (undefined :: Equal N2)
2
>>> size (undefined :: Equal N12)
12
-}
size :: IsNat a => Equal a -> Int
size = natToZ . getSize
-- TODO I got this part wrong
--
-- This type implements limited values (useful for interval *steps*)
-- An ET-interval is just an int, with a type-level size (divMod is "separate")
-- -- | Create an equal-temperament value.
-- toEqual :: IsNat a => Int -> Maybe (Equal a)
-- toEqual = checkSize . Equal
--
-- -- | Unsafely create an equal-temperament value.
-- unsafeToEqual :: IsNat a => Int -> Equal a
-- unsafeToEqual n = case toEqual n of
-- Nothing -> error $ "Bad equal: " ++ show n
-- Just x -> x
--
-- checkSize :: IsNat a => Equal a -> Maybe (Equal a)
-- checkSize x = if 0 <= fromEqual x && fromEqual x < size x then Just x else Nothing
--
-- | Create an equal-temperament value.
toEqual :: IsNat a => Int -> Equal a
toEqual = Equal
-- | Extract an equal-temperament value.
fromEqual :: IsNat a => Equal a -> Int
fromEqual = getEqual
{-| Convert an equal-temeperament value to a frequency ratio.
>>> equalToRatio (7 :: Equal12)
1.4983070768766815
>>> equalToRatio (4 :: Equal12)
1.2599210498948732
-}
equalToRatio :: IsNat a => Equal a -> Double
equalToRatio x = 2**(realToFrac (fromEqual x) / realToFrac (size x))
{-| Safely cast a tempered value to another size.
>>> cast (1 :: Equal12) :: Equal24
2 :: Equal24
>>> cast (8 :: Equal12) :: Equal6
4 :: Equal6
>>> (2 :: Equal12) + cast (2 :: Equal24)
3 :: Equal12
-}
cast :: (IsNat a, IsNat b) => Equal a -> Equal b
cast = cast' undefined
cast' :: (IsNat a, IsNat b) => Equal b -> Equal a -> Equal b
cast' bDummy aDummy@(Equal a) = Equal $ (a * size bDummy) `div` size aDummy
type Equal6 = Equal N6
type Equal12 = Equal N12
type Equal17 = Equal N17
type Equal24 = Equal N24
type Equal36 = Equal N36
type N20 = N10 :*: N2
type N30 = N10 :*: N3
type N17 = N10 :+: N7
type N24 = N20 :+: N4
type N36 = N30 :+: N6
| music-suite/music-pitch | src/Music/Pitch/Equal.hs | bsd-3-clause | 3,792 | 0 | 10 | 868 | 888 | 488 | 400 | -1 | -1 |
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__
{-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-}
#endif
#if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703
{-# LANGUAGE Trustworthy #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Data.Set.Base
-- Copyright : (c) Daan Leijen 2002
-- License : BSD-style
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- An efficient implementation of sets.
--
-- These modules are intended to be imported qualified, to avoid name
-- clashes with Prelude functions, e.g.
--
-- > import Data.Set (Set)
-- > import qualified Data.Set as Set
--
-- The implementation of 'Set' is based on /size balanced/ binary trees (or
-- trees of /bounded balance/) as described by:
--
-- * Stephen Adams, \"/Efficient sets: a balancing act/\",
-- Journal of Functional Programming 3(4):553-562, October 1993,
-- <http://www.swiss.ai.mit.edu/~adams/BB/>.
--
-- * J. Nievergelt and E.M. Reingold,
-- \"/Binary search trees of bounded balance/\",
-- SIAM journal of computing 2(1), March 1973.
--
-- Note that the implementation is /left-biased/ -- the elements of a
-- first argument are always preferred to the second, for example in
-- 'union' or 'insert'. Of course, left-biasing can only be observed
-- when equality is an equivalence relation instead of structural
-- equality.
-----------------------------------------------------------------------------
-- [Note: Using INLINABLE]
-- ~~~~~~~~~~~~~~~~~~~~~~~
-- It is crucial to the performance that the functions specialize on the Ord
-- type when possible. GHC 7.0 and higher does this by itself when it sees th
-- unfolding of a function -- that is why all public functions are marked
-- INLINABLE (that exposes the unfolding).
-- [Note: Using INLINE]
-- ~~~~~~~~~~~~~~~~~~~~
-- For other compilers and GHC pre 7.0, we mark some of the functions INLINE.
-- We mark the functions that just navigate down the tree (lookup, insert,
-- delete and similar). That navigation code gets inlined and thus specialized
-- when possible. There is a price to pay -- code growth. The code INLINED is
-- therefore only the tree navigation, all the real work (rebalancing) is not
-- INLINED by using a NOINLINE.
--
-- All methods marked INLINE have to be nonrecursive -- a 'go' function doing
-- the real work is provided.
-- [Note: Type of local 'go' function]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- If the local 'go' function uses an Ord class, it sometimes heap-allocates
-- the Ord dictionary when the 'go' function does not have explicit type.
-- In that case we give 'go' explicit type. But this slightly decrease
-- performance, as the resulting 'go' function can float out to top level.
-- [Note: Local 'go' functions and capturing]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- As opposed to IntSet, when 'go' function captures an argument, increased
-- heap-allocation can occur: sometimes in a polymorphic function, the 'go'
-- floats out of its enclosing function and then it heap-allocates the
-- dictionary and the argument. Maybe it floats out too late and strictness
-- analyzer cannot see that these could be passed on stack.
--
-- For example, change 'member' so that its local 'go' function is not passing
-- argument x and then look at the resulting code for hedgeInt.
-- [Note: Order of constructors]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- The order of constructors of Set matters when considering performance.
-- Currently in GHC 7.0, when type has 2 constructors, a forward conditional
-- jump is made when successfully matching second constructor. Successful match
-- of first constructor results in the forward jump not taken.
-- On GHC 7.0, reordering constructors from Tip | Bin to Bin | Tip
-- improves the benchmark by up to 10% on x86.
module Data.Set.Base (
-- * Set type
Set(..) -- instance Eq,Ord,Show,Read,Data,Typeable
-- * Operators
, (\\)
-- * Query
, null
, size
, member
, notMember
, lookupLT
, lookupGT
, lookupLE
, lookupGE
, isSubsetOf
, isProperSubsetOf
-- * Construction
, empty
, singleton
, insert
, delete
-- * Combine
, union
, unions
, difference
, intersection
-- * Filter
, filter
, partition
, split
, splitMember
-- * Indexed
, lookupIndex
, findIndex
, elemAt
, deleteAt
-- * Map
, map
, mapMonotonic
-- * Folds
, foldr
, foldl
-- ** Strict folds
, foldr'
, foldl'
-- ** Legacy folds
, fold
-- * Min\/Max
, findMin
, findMax
, deleteMin
, deleteMax
, deleteFindMin
, deleteFindMax
, maxView
, minView
-- * Conversion
-- ** List
, elems
, toList
, fromList
-- ** Ordered list
, toAscList
, toDescList
, fromAscList
, fromDistinctAscList
-- * Debugging
, showTree
, showTreeWith
, valid
-- Internals (for testing)
, bin
, balanced
, join
, merge
) where
import Prelude hiding (filter,foldl,foldr,null,map)
import qualified Data.List as List
import Data.Bits (shiftL, shiftR)
import Data.Monoid (Monoid(..))
import qualified Data.Foldable as Foldable
import Data.Typeable
import Control.DeepSeq (NFData(rnf))
import Data.StrictPair
#if __GLASGOW_HASKELL__
import GHC.Exts ( build )
import Text.Read
import Data.Data
#endif
-- Use macros to define strictness of functions.
-- STRICT_x_OF_y denotes an y-ary function strict in the x-th parameter.
-- We do not use BangPatterns, because they are not in any standard and we
-- want the compilers to be compiled by as many compilers as possible.
#define STRICT_1_OF_2(fn) fn arg _ | arg `seq` False = undefined
#define STRICT_1_OF_3(fn) fn arg _ _ | arg `seq` False = undefined
#define STRICT_2_OF_3(fn) fn _ arg _ | arg `seq` False = undefined
{--------------------------------------------------------------------
Operators
--------------------------------------------------------------------}
infixl 9 \\ --
-- | /O(n+m)/. See 'difference'.
(\\) :: Ord a => Set a -> Set a -> Set a
m1 \\ m2 = difference m1 m2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE (\\) #-}
#endif
{--------------------------------------------------------------------
Sets are size balanced trees
--------------------------------------------------------------------}
-- | A set of values @a@.
-- See Note: Order of constructors
data Set a = Bin {-# UNPACK #-} !Size !a !(Set a) !(Set a)
| Tip
type Size = Int
instance Ord a => Monoid (Set a) where
mempty = empty
mappend = union
mconcat = unions
instance Foldable.Foldable Set where
fold Tip = mempty
fold (Bin _ k l r) = Foldable.fold l `mappend` k `mappend` Foldable.fold r
foldr = foldr
foldl = foldl
foldMap _ Tip = mempty
foldMap f (Bin _ k l r) = Foldable.foldMap f l `mappend` f k `mappend` Foldable.foldMap f r
#if __GLASGOW_HASKELL__
{--------------------------------------------------------------------
A Data instance
--------------------------------------------------------------------}
-- This instance preserves data abstraction at the cost of inefficiency.
-- We provide limited reflection services for the sake of data abstraction.
instance (Data a, Ord a) => Data (Set a) where
gfoldl f z set = z fromList `f` (toList set)
toConstr _ = fromListConstr
gunfold k z c = case constrIndex c of
1 -> k (z fromList)
_ -> error "gunfold"
dataTypeOf _ = setDataType
dataCast1 f = gcast1 f
fromListConstr :: Constr
fromListConstr = mkConstr setDataType "fromList" [] Prefix
setDataType :: DataType
setDataType = mkDataType "Data.Set.Base.Set" [fromListConstr]
#endif
{--------------------------------------------------------------------
Query
--------------------------------------------------------------------}
-- | /O(1)/. Is this the empty set?
null :: Set a -> Bool
null Tip = True
null (Bin {}) = False
{-# INLINE null #-}
-- | /O(1)/. The number of elements in the set.
size :: Set a -> Int
size Tip = 0
size (Bin sz _ _ _) = sz
{-# INLINE size #-}
-- | /O(log n)/. Is the element in the set?
member :: Ord a => a -> Set a -> Bool
member = go
where
STRICT_1_OF_2(go)
go _ Tip = False
go x (Bin _ y l r) = case compare x y of
LT -> go x l
GT -> go x r
EQ -> True
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE member #-}
#else
{-# INLINE member #-}
#endif
-- | /O(log n)/. Is the element not in the set?
notMember :: Ord a => a -> Set a -> Bool
notMember a t = not $ member a t
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE notMember #-}
#else
{-# INLINE notMember #-}
#endif
-- | /O(log n)/. Find largest element smaller than the given one.
--
-- > lookupLT 3 (fromList [3, 5]) == Nothing
-- > lookupLT 5 (fromList [3, 5]) == Just 3
lookupLT :: Ord a => a -> Set a -> Maybe a
lookupLT = goNothing
where
STRICT_1_OF_2(goNothing)
goNothing _ Tip = Nothing
goNothing x (Bin _ y l r) | x <= y = goNothing x l
| otherwise = goJust x y r
STRICT_1_OF_3(goJust)
goJust _ best Tip = Just best
goJust x best (Bin _ y l r) | x <= y = goJust x best l
| otherwise = goJust x y r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE lookupLT #-}
#else
{-# INLINE lookupLT #-}
#endif
-- | /O(log n)/. Find smallest element greater than the given one.
--
-- > lookupGT 4 (fromList [3, 5]) == Just 5
-- > lookupGT 5 (fromList [3, 5]) == Nothing
lookupGT :: Ord a => a -> Set a -> Maybe a
lookupGT = goNothing
where
STRICT_1_OF_2(goNothing)
goNothing _ Tip = Nothing
goNothing x (Bin _ y l r) | x < y = goJust x y l
| otherwise = goNothing x r
STRICT_1_OF_3(goJust)
goJust _ best Tip = Just best
goJust x best (Bin _ y l r) | x < y = goJust x y l
| otherwise = goJust x best r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE lookupGT #-}
#else
{-# INLINE lookupGT #-}
#endif
-- | /O(log n)/. Find largest element smaller or equal to the given one.
--
-- > lookupLE 2 (fromList [3, 5]) == Nothing
-- > lookupLE 4 (fromList [3, 5]) == Just 3
-- > lookupLE 5 (fromList [3, 5]) == Just 5
lookupLE :: Ord a => a -> Set a -> Maybe a
lookupLE = goNothing
where
STRICT_1_OF_2(goNothing)
goNothing _ Tip = Nothing
goNothing x (Bin _ y l r) = case compare x y of LT -> goNothing x l
EQ -> Just y
GT -> goJust x y r
STRICT_1_OF_3(goJust)
goJust _ best Tip = Just best
goJust x best (Bin _ y l r) = case compare x y of LT -> goJust x best l
EQ -> Just y
GT -> goJust x y r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE lookupLE #-}
#else
{-# INLINE lookupLE #-}
#endif
-- | /O(log n)/. Find smallest element greater or equal to the given one.
--
-- > lookupGE 3 (fromList [3, 5]) == Just 3
-- > lookupGE 4 (fromList [3, 5]) == Just 5
-- > lookupGE 6 (fromList [3, 5]) == Nothing
lookupGE :: Ord a => a -> Set a -> Maybe a
lookupGE = goNothing
where
STRICT_1_OF_2(goNothing)
goNothing _ Tip = Nothing
goNothing x (Bin _ y l r) = case compare x y of LT -> goJust x y l
EQ -> Just y
GT -> goNothing x r
STRICT_1_OF_3(goJust)
goJust _ best Tip = Just best
goJust x best (Bin _ y l r) = case compare x y of LT -> goJust x y l
EQ -> Just y
GT -> goJust x best r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE lookupGE #-}
#else
{-# INLINE lookupGE #-}
#endif
{--------------------------------------------------------------------
Construction
--------------------------------------------------------------------}
-- | /O(1)/. The empty set.
empty :: Set a
empty = Tip
{-# INLINE empty #-}
-- | /O(1)/. Create a singleton set.
singleton :: a -> Set a
singleton x = Bin 1 x Tip Tip
{-# INLINE singleton #-}
{--------------------------------------------------------------------
Insertion, Deletion
--------------------------------------------------------------------}
-- | /O(log n)/. Insert an element in a set.
-- If the set already contains an element equal to the given value,
-- it is replaced with the new value.
-- See Note: Type of local 'go' function
insert :: Ord a => a -> Set a -> Set a
insert = go
where
go :: Ord a => a -> Set a -> Set a
STRICT_1_OF_2(go)
go x Tip = singleton x
go x (Bin sz y l r) = case compare x y of
LT -> balanceL y (go x l) r
GT -> balanceR y l (go x r)
EQ -> Bin sz x l r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE insert #-}
#else
{-# INLINE insert #-}
#endif
-- Insert an element to the set only if it is not in the set.
-- Used by `union`.
-- See Note: Type of local 'go' function
insertR :: Ord a => a -> Set a -> Set a
insertR = go
where
go :: Ord a => a -> Set a -> Set a
STRICT_1_OF_2(go)
go x Tip = singleton x
go x t@(Bin _ y l r) = case compare x y of
LT -> balanceL y (go x l) r
GT -> balanceR y l (go x r)
EQ -> t
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE insertR #-}
#else
{-# INLINE insertR #-}
#endif
-- | /O(log n)/. Delete an element from a set.
-- See Note: Type of local 'go' function
delete :: Ord a => a -> Set a -> Set a
delete = go
where
go :: Ord a => a -> Set a -> Set a
STRICT_1_OF_2(go)
go _ Tip = Tip
go x (Bin _ y l r) = case compare x y of
LT -> balanceR y (go x l) r
GT -> balanceL y l (go x r)
EQ -> glue l r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE delete #-}
#else
{-# INLINE delete #-}
#endif
{--------------------------------------------------------------------
Subset
--------------------------------------------------------------------}
-- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
isProperSubsetOf :: Ord a => Set a -> Set a -> Bool
isProperSubsetOf s1 s2
= (size s1 < size s2) && (isSubsetOf s1 s2)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE isProperSubsetOf #-}
#endif
-- | /O(n+m)/. Is this a subset?
-- @(s1 `isSubsetOf` s2)@ tells whether @s1@ is a subset of @s2@.
isSubsetOf :: Ord a => Set a -> Set a -> Bool
isSubsetOf t1 t2
= (size t1 <= size t2) && (isSubsetOfX t1 t2)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE isSubsetOf #-}
#endif
isSubsetOfX :: Ord a => Set a -> Set a -> Bool
isSubsetOfX Tip _ = True
isSubsetOfX _ Tip = False
isSubsetOfX (Bin _ x l r) t
= found && isSubsetOfX l lt && isSubsetOfX r gt
where
(lt,found,gt) = splitMember x t
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE isSubsetOfX #-}
#endif
{--------------------------------------------------------------------
Minimal, Maximal
--------------------------------------------------------------------}
-- | /O(log n)/. The minimal element of a set.
findMin :: Set a -> a
findMin (Bin _ x Tip _) = x
findMin (Bin _ _ l _) = findMin l
findMin Tip = error "Set.findMin: empty set has no minimal element"
-- | /O(log n)/. The maximal element of a set.
findMax :: Set a -> a
findMax (Bin _ x _ Tip) = x
findMax (Bin _ _ _ r) = findMax r
findMax Tip = error "Set.findMax: empty set has no maximal element"
-- | /O(log n)/. Delete the minimal element. Returns an empty set if the set is empty.
deleteMin :: Set a -> Set a
deleteMin (Bin _ _ Tip r) = r
deleteMin (Bin _ x l r) = balanceR x (deleteMin l) r
deleteMin Tip = Tip
-- | /O(log n)/. Delete the maximal element. Returns an empty set if the set is empty.
deleteMax :: Set a -> Set a
deleteMax (Bin _ _ l Tip) = l
deleteMax (Bin _ x l r) = balanceL x l (deleteMax r)
deleteMax Tip = Tip
{--------------------------------------------------------------------
Union.
--------------------------------------------------------------------}
-- | The union of a list of sets: (@'unions' == 'foldl' 'union' 'empty'@).
unions :: Ord a => [Set a] -> Set a
unions = foldlStrict union empty
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE unions #-}
#endif
-- | /O(n+m)/. The union of two sets, preferring the first set when
-- equal elements are encountered.
-- The implementation uses the efficient /hedge-union/ algorithm.
union :: Ord a => Set a -> Set a -> Set a
union Tip t2 = t2
union t1 Tip = t1
union t1 t2 = hedgeUnion NothingS NothingS t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE union #-}
#endif
hedgeUnion :: Ord a => MaybeS a -> MaybeS a -> Set a -> Set a -> Set a
hedgeUnion _ _ t1 Tip = t1
hedgeUnion blo bhi Tip (Bin _ x l r) = join x (filterGt blo l) (filterLt bhi r)
hedgeUnion _ _ t1 (Bin _ x Tip Tip) = insertR x t1 -- According to benchmarks, this special case increases
-- performance up to 30%. It does not help in difference or intersection.
hedgeUnion blo bhi (Bin _ x l r) t2 = join x (hedgeUnion blo bmi l (trim blo bmi t2))
(hedgeUnion bmi bhi r (trim bmi bhi t2))
where bmi = JustS x
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE hedgeUnion #-}
#endif
{--------------------------------------------------------------------
Difference
--------------------------------------------------------------------}
-- | /O(n+m)/. Difference of two sets.
-- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
difference :: Ord a => Set a -> Set a -> Set a
difference Tip _ = Tip
difference t1 Tip = t1
difference t1 t2 = hedgeDiff NothingS NothingS t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE difference #-}
#endif
hedgeDiff :: Ord a => MaybeS a -> MaybeS a -> Set a -> Set a -> Set a
hedgeDiff _ _ Tip _ = Tip
hedgeDiff blo bhi (Bin _ x l r) Tip = join x (filterGt blo l) (filterLt bhi r)
hedgeDiff blo bhi t (Bin _ x l r) = merge (hedgeDiff blo bmi (trim blo bmi t) l)
(hedgeDiff bmi bhi (trim bmi bhi t) r)
where bmi = JustS x
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE hedgeDiff #-}
#endif
{--------------------------------------------------------------------
Intersection
--------------------------------------------------------------------}
-- | /O(n+m)/. The intersection of two sets. The implementation uses an
-- efficient /hedge/ algorithm comparable with /hedge-union/. Elements of the
-- result come from the first set, so for example
--
-- > import qualified Data.Set as S
-- > data AB = A | B deriving Show
-- > instance Ord AB where compare _ _ = EQ
-- > instance Eq AB where _ == _ = True
-- > main = print (S.singleton A `S.intersection` S.singleton B,
-- > S.singleton B `S.intersection` S.singleton A)
--
-- prints @(fromList [A],fromList [B])@.
intersection :: Ord a => Set a -> Set a -> Set a
intersection Tip _ = Tip
intersection _ Tip = Tip
intersection t1 t2 = hedgeInt NothingS NothingS t1 t2
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE intersection #-}
#endif
hedgeInt :: Ord a => MaybeS a -> MaybeS a -> Set a -> Set a -> Set a
hedgeInt _ _ _ Tip = Tip
hedgeInt _ _ Tip _ = Tip
hedgeInt blo bhi (Bin _ x l r) t2 = let l' = hedgeInt blo bmi l (trim blo bmi t2)
r' = hedgeInt bmi bhi r (trim bmi bhi t2)
in if x `member` t2 then join x l' r' else merge l' r'
where bmi = JustS x
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE hedgeInt #-}
#endif
{--------------------------------------------------------------------
Filter and partition
--------------------------------------------------------------------}
-- | /O(n)/. Filter all elements that satisfy the predicate.
filter :: (a -> Bool) -> Set a -> Set a
filter _ Tip = Tip
filter p (Bin _ x l r)
| p x = join x (filter p l) (filter p r)
| otherwise = merge (filter p l) (filter p r)
-- | /O(n)/. Partition the set into two sets, one with all elements that satisfy
-- the predicate and one with all elements that don't satisfy the predicate.
-- See also 'split'.
partition :: (a -> Bool) -> Set a -> (Set a,Set a)
partition p0 t0 = toPair $ go p0 t0
where
go _ Tip = (Tip :*: Tip)
go p (Bin _ x l r) = case (go p l, go p r) of
((l1 :*: l2), (r1 :*: r2))
| p x -> join x l1 r1 :*: merge l2 r2
| otherwise -> merge l1 r1 :*: join x l2 r2
{----------------------------------------------------------------------
Map
----------------------------------------------------------------------}
-- | /O(n*log n)/.
-- @'map' f s@ is the set obtained by applying @f@ to each element of @s@.
--
-- It's worth noting that the size of the result may be smaller if,
-- for some @(x,y)@, @x \/= y && f x == f y@
map :: Ord b => (a->b) -> Set a -> Set b
map f = fromList . List.map f . toList
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE map #-}
#endif
-- | /O(n)/. The
--
-- @'mapMonotonic' f s == 'map' f s@, but works only when @f@ is monotonic.
-- /The precondition is not checked./
-- Semi-formally, we have:
--
-- > and [x < y ==> f x < f y | x <- ls, y <- ls]
-- > ==> mapMonotonic f s == map f s
-- > where ls = toList s
mapMonotonic :: (a->b) -> Set a -> Set b
mapMonotonic _ Tip = Tip
mapMonotonic f (Bin sz x l r) = Bin sz (f x) (mapMonotonic f l) (mapMonotonic f r)
{--------------------------------------------------------------------
Fold
--------------------------------------------------------------------}
-- | /O(n)/. Fold the elements in the set using the given right-associative
-- binary operator. This function is an equivalent of 'foldr' and is present
-- for compatibility only.
--
-- /Please note that fold will be deprecated in the future and removed./
fold :: (a -> b -> b) -> b -> Set a -> b
fold = foldr
{-# INLINE fold #-}
-- | /O(n)/. Fold the elements in the set using the given right-associative
-- binary operator, such that @'foldr' f z == 'Prelude.foldr' f z . 'toAscList'@.
--
-- For example,
--
-- > toAscList set = foldr (:) [] set
foldr :: (a -> b -> b) -> b -> Set a -> b
foldr f z = go z
where
go z' Tip = z'
go z' (Bin _ x l r) = go (f x (go z' r)) l
{-# INLINE foldr #-}
-- | /O(n)/. A strict version of 'foldr'. Each application of the operator is
-- evaluated before using the result in the next application. This
-- function is strict in the starting value.
foldr' :: (a -> b -> b) -> b -> Set a -> b
foldr' f z = go z
where
STRICT_1_OF_2(go)
go z' Tip = z'
go z' (Bin _ x l r) = go (f x (go z' r)) l
{-# INLINE foldr' #-}
-- | /O(n)/. Fold the elements in the set using the given left-associative
-- binary operator, such that @'foldl' f z == 'Prelude.foldl' f z . 'toAscList'@.
--
-- For example,
--
-- > toDescList set = foldl (flip (:)) [] set
foldl :: (a -> b -> a) -> a -> Set b -> a
foldl f z = go z
where
go z' Tip = z'
go z' (Bin _ x l r) = go (f (go z' l) x) r
{-# INLINE foldl #-}
-- | /O(n)/. A strict version of 'foldl'. Each application of the operator is
-- evaluated before using the result in the next application. This
-- function is strict in the starting value.
foldl' :: (a -> b -> a) -> a -> Set b -> a
foldl' f z = go z
where
STRICT_1_OF_2(go)
go z' Tip = z'
go z' (Bin _ x l r) = go (f (go z' l) x) r
{-# INLINE foldl' #-}
{--------------------------------------------------------------------
List variations
--------------------------------------------------------------------}
-- | /O(n)/. An alias of 'toAscList'. The elements of a set in ascending order.
-- Subject to list fusion.
elems :: Set a -> [a]
elems = toAscList
{--------------------------------------------------------------------
Lists
--------------------------------------------------------------------}
-- | /O(n)/. Convert the set to a list of elements. Subject to list fusion.
toList :: Set a -> [a]
toList = toAscList
-- | /O(n)/. Convert the set to an ascending list of elements. Subject to list fusion.
toAscList :: Set a -> [a]
toAscList = foldr (:) []
-- | /O(n)/. Convert the set to a descending list of elements. Subject to list
-- fusion.
toDescList :: Set a -> [a]
toDescList = foldl (flip (:)) []
-- List fusion for the list generating functions.
#if __GLASGOW_HASKELL__
-- The foldrFB and foldlFB are foldr and foldl equivalents, used for list fusion.
-- They are important to convert unfused to{Asc,Desc}List back, see mapFB in prelude.
foldrFB :: (a -> b -> b) -> b -> Set a -> b
foldrFB = foldr
{-# INLINE[0] foldrFB #-}
foldlFB :: (a -> b -> a) -> a -> Set b -> a
foldlFB = foldl
{-# INLINE[0] foldlFB #-}
-- Inline elems and toList, so that we need to fuse only toAscList.
{-# INLINE elems #-}
{-# INLINE toList #-}
-- The fusion is enabled up to phase 2 included. If it does not succeed,
-- convert in phase 1 the expanded to{Asc,Desc}List calls back to
-- to{Asc,Desc}List. In phase 0, we inline fold{lr}FB (which were used in
-- a list fusion, otherwise it would go away in phase 1), and let compiler do
-- whatever it wants with to{Asc,Desc}List -- it was forbidden to inline it
-- before phase 0, otherwise the fusion rules would not fire at all.
{-# NOINLINE[0] toAscList #-}
{-# NOINLINE[0] toDescList #-}
{-# RULES "Set.toAscList" [~1] forall s . toAscList s = build (\c n -> foldrFB c n s) #-}
{-# RULES "Set.toAscListBack" [1] foldrFB (:) [] = toAscList #-}
{-# RULES "Set.toDescList" [~1] forall s . toDescList s = build (\c n -> foldlFB (\xs x -> c x xs) n s) #-}
{-# RULES "Set.toDescListBack" [1] foldlFB (\xs x -> x : xs) [] = toDescList #-}
#endif
-- | /O(n*log n)/. Create a set from a list of elements.
--
-- If the elemens are ordered, linear-time implementation is used,
-- with the performance equal to 'fromDistinctAscList'.
-- For some reason, when 'singleton' is used in fromList or in
-- create, it is not inlined, so we inline it manually.
fromList :: Ord a => [a] -> Set a
fromList [] = Tip
fromList [x] = Bin 1 x Tip Tip
fromList (x0 : xs0) | not_ordered x0 xs0 = fromList' (Bin 1 x0 Tip Tip) xs0
| otherwise = go (1::Int) (Bin 1 x0 Tip Tip) xs0
where
not_ordered _ [] = False
not_ordered x (y : _) = x >= y
{-# INLINE not_ordered #-}
fromList' t0 xs = foldlStrict ins t0 xs
where ins t x = insert x t
STRICT_1_OF_3(go)
go _ t [] = t
go _ t [x] = insertMax x t
go s l xs@(x : xss) | not_ordered x xss = fromList' l xs
| otherwise = case create s xss of
(r, ys, []) -> go (s `shiftL` 1) (join x l r) ys
(r, _, ys) -> fromList' (join x l r) ys
-- The create is returning a triple (tree, xs, ys). Both xs and ys
-- represent not yet processed elements and only one of them can be nonempty.
-- If ys is nonempty, the keys in ys are not ordered with respect to tree
-- and must be inserted using fromList'. Otherwise the keys have been
-- ordered so far.
STRICT_1_OF_2(create)
create _ [] = (Tip, [], [])
create s xs@(x : xss)
| s == 1 = if not_ordered x xss then (Bin 1 x Tip Tip, [], xss)
else (Bin 1 x Tip Tip, xss, [])
| otherwise = case create (s `shiftR` 1) xs of
res@(_, [], _) -> res
(l, [y], zs) -> (insertMax y l, [], zs)
(l, ys@(y:yss), _) | not_ordered y yss -> (l, [], ys)
| otherwise -> case create (s `shiftR` 1) yss of
(r, zs, ws) -> (join y l r, zs, ws)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromList #-}
#endif
{--------------------------------------------------------------------
Building trees from ascending/descending lists can be done in linear time.
Note that if [xs] is ascending that:
fromAscList xs == fromList xs
--------------------------------------------------------------------}
-- | /O(n)/. Build a set from an ascending list in linear time.
-- /The precondition (input list is ascending) is not checked./
fromAscList :: Eq a => [a] -> Set a
fromAscList xs
= fromDistinctAscList (combineEq xs)
where
-- [combineEq xs] combines equal elements with [const] in an ordered list [xs]
combineEq xs'
= case xs' of
[] -> []
[x] -> [x]
(x:xx) -> combineEq' x xx
combineEq' z [] = [z]
combineEq' z (x:xs')
| z==x = combineEq' z xs'
| otherwise = z:combineEq' x xs'
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE fromAscList #-}
#endif
-- | /O(n)/. Build a set from an ascending list of distinct elements in linear time.
-- /The precondition (input list is strictly ascending) is not checked./
-- For some reason, when 'singleton' is used in fromDistinctAscList or in
-- create, it is not inlined, so we inline it manually.
fromDistinctAscList :: [a] -> Set a
fromDistinctAscList [] = Tip
fromDistinctAscList (x0 : xs0) = go (1::Int) (Bin 1 x0 Tip Tip) xs0
where
STRICT_1_OF_3(go)
go _ t [] = t
go s l (x : xs) = case create s xs of
(r, ys) -> go (s `shiftL` 1) (join x l r) ys
STRICT_1_OF_2(create)
create _ [] = (Tip, [])
create s xs@(x : xs')
| s == 1 = (Bin 1 x Tip Tip, xs')
| otherwise = case create (s `shiftR` 1) xs of
res@(_, []) -> res
(l, y:ys) -> case create (s `shiftR` 1) ys of
(r, zs) -> (join y l r, zs)
{--------------------------------------------------------------------
Eq converts the set to a list. In a lazy setting, this
actually seems one of the faster methods to compare two trees
and it is certainly the simplest :-)
--------------------------------------------------------------------}
instance Eq a => Eq (Set a) where
t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
{--------------------------------------------------------------------
Ord
--------------------------------------------------------------------}
instance Ord a => Ord (Set a) where
compare s1 s2 = compare (toAscList s1) (toAscList s2)
{--------------------------------------------------------------------
Show
--------------------------------------------------------------------}
instance Show a => Show (Set a) where
showsPrec p xs = showParen (p > 10) $
showString "fromList " . shows (toList xs)
{--------------------------------------------------------------------
Read
--------------------------------------------------------------------}
instance (Read a, Ord a) => Read (Set a) where
#ifdef __GLASGOW_HASKELL__
readPrec = parens $ prec 10 $ do
Ident "fromList" <- lexP
xs <- readPrec
return (fromList xs)
readListPrec = readListPrecDefault
#else
readsPrec p = readParen (p > 10) $ \ r -> do
("fromList",s) <- lex r
(xs,t) <- reads s
return (fromList xs,t)
#endif
{--------------------------------------------------------------------
Typeable/Data
--------------------------------------------------------------------}
#include "Typeable.h"
INSTANCE_TYPEABLE1(Set,setTc,"Set")
{--------------------------------------------------------------------
NFData
--------------------------------------------------------------------}
instance NFData a => NFData (Set a) where
rnf Tip = ()
rnf (Bin _ y l r) = rnf y `seq` rnf l `seq` rnf r
{--------------------------------------------------------------------
Utility functions that return sub-ranges of the original
tree. Some functions take a `Maybe value` as an argument to
allow comparisons against infinite values. These are called `blow`
(Nothing is -\infty) and `bhigh` (here Nothing is +\infty).
We use MaybeS value, which is a Maybe strict in the Just case.
[trim blow bhigh t] A tree that is either empty or where [x > blow]
and [x < bhigh] for the value [x] of the root.
[filterGt blow t] A tree where for all values [k]. [k > blow]
[filterLt bhigh t] A tree where for all values [k]. [k < bhigh]
[split k t] Returns two trees [l] and [r] where all values
in [l] are <[k] and all keys in [r] are >[k].
[splitMember k t] Just like [split] but also returns whether [k]
was found in the tree.
--------------------------------------------------------------------}
data MaybeS a = NothingS | JustS !a
{--------------------------------------------------------------------
[trim blo bhi t] trims away all subtrees that surely contain no
values between the range [blo] to [bhi]. The returned tree is either
empty or the key of the root is between @blo@ and @bhi@.
--------------------------------------------------------------------}
trim :: Ord a => MaybeS a -> MaybeS a -> Set a -> Set a
trim NothingS NothingS t = t
trim (JustS lx) NothingS t = greater lx t where greater lo (Bin _ x _ r) | x <= lo = greater lo r
greater _ t' = t'
trim NothingS (JustS hx) t = lesser hx t where lesser hi (Bin _ x l _) | x >= hi = lesser hi l
lesser _ t' = t'
trim (JustS lx) (JustS hx) t = middle lx hx t where middle lo hi (Bin _ x _ r) | x <= lo = middle lo hi r
middle lo hi (Bin _ x l _) | x >= hi = middle lo hi l
middle _ _ t' = t'
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE trim #-}
#endif
{--------------------------------------------------------------------
[filterGt b t] filter all values >[b] from tree [t]
[filterLt b t] filter all values <[b] from tree [t]
--------------------------------------------------------------------}
filterGt :: Ord a => MaybeS a -> Set a -> Set a
filterGt NothingS t = t
filterGt (JustS b) t = filter' b t
where filter' _ Tip = Tip
filter' b' (Bin _ x l r) =
case compare b' x of LT -> join x (filter' b' l) r
EQ -> r
GT -> filter' b' r
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE filterGt #-}
#endif
filterLt :: Ord a => MaybeS a -> Set a -> Set a
filterLt NothingS t = t
filterLt (JustS b) t = filter' b t
where filter' _ Tip = Tip
filter' b' (Bin _ x l r) =
case compare x b' of LT -> join x l (filter' b' r)
EQ -> l
GT -> filter' b' l
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE filterLt #-}
#endif
{--------------------------------------------------------------------
Split
--------------------------------------------------------------------}
-- | /O(log n)/. The expression (@'split' x set@) is a pair @(set1,set2)@
-- where @set1@ comprises the elements of @set@ less than @x@ and @set2@
-- comprises the elements of @set@ greater than @x@.
split :: Ord a => a -> Set a -> (Set a,Set a)
split x0 t0 = toPair $ go x0 t0
where
go _ Tip = (Tip :*: Tip)
go x (Bin _ y l r)
= case compare x y of
LT -> let (lt :*: gt) = go x l in (lt :*: join y gt r)
GT -> let (lt :*: gt) = go x r in (join y l lt :*: gt)
EQ -> (l :*: r)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE split #-}
#endif
-- | /O(log n)/. Performs a 'split' but also returns whether the pivot
-- element was found in the original set.
splitMember :: Ord a => a -> Set a -> (Set a,Bool,Set a)
splitMember _ Tip = (Tip, False, Tip)
splitMember x (Bin _ y l r)
= case compare x y of
LT -> let (lt, found, gt) = splitMember x l
gt' = join y gt r
in gt' `seq` (lt, found, gt')
GT -> let (lt, found, gt) = splitMember x r
lt' = join y l lt
in lt' `seq` (lt', found, gt)
EQ -> (l, True, r)
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE splitMember #-}
#endif
{--------------------------------------------------------------------
Indexing
--------------------------------------------------------------------}
-- | /O(log n)/. Return the /index/ of an element, which is its zero-based
-- index in the sorted sequence of elements. The index is a number from /0/ up
-- to, but not including, the 'size' of the set. Calls 'error' when the element
-- is not a 'member' of the set.
--
-- > findIndex 2 (fromList [5,3]) Error: element is not in the set
-- > findIndex 3 (fromList [5,3]) == 0
-- > findIndex 5 (fromList [5,3]) == 1
-- > findIndex 6 (fromList [5,3]) Error: element is not in the set
-- See Note: Type of local 'go' function
findIndex :: Ord a => a -> Set a -> Int
findIndex = go 0
where
go :: Ord a => Int -> a -> Set a -> Int
STRICT_1_OF_3(go)
STRICT_2_OF_3(go)
go _ _ Tip = error "Set.findIndex: element is not in the set"
go idx x (Bin _ kx l r) = case compare x kx of
LT -> go idx x l
GT -> go (idx + size l + 1) x r
EQ -> idx + size l
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE findIndex #-}
#endif
-- | /O(log n)/. Lookup the /index/ of an element, which is its zero-based index in
-- the sorted sequence of elements. The index is a number from /0/ up to, but not
-- including, the 'size' of the set.
--
-- > isJust (lookupIndex 2 (fromList [5,3])) == False
-- > fromJust (lookupIndex 3 (fromList [5,3])) == 0
-- > fromJust (lookupIndex 5 (fromList [5,3])) == 1
-- > isJust (lookupIndex 6 (fromList [5,3])) == False
-- See Note: Type of local 'go' function
lookupIndex :: Ord a => a -> Set a -> Maybe Int
lookupIndex = go 0
where
go :: Ord a => Int -> a -> Set a -> Maybe Int
STRICT_1_OF_3(go)
STRICT_2_OF_3(go)
go _ _ Tip = Nothing
go idx x (Bin _ kx l r) = case compare x kx of
LT -> go idx x l
GT -> go (idx + size l + 1) x r
EQ -> Just $! idx + size l
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE lookupIndex #-}
#endif
-- | /O(log n)/. Retrieve an element by its /index/, i.e. by its zero-based
-- index in the sorted sequence of elements. If the /index/ is out of range (less
-- than zero, greater or equal to 'size' of the set), 'error' is called.
--
-- > elemAt 0 (fromList [5,3]) == 3
-- > elemAt 1 (fromList [5,3]) == 5
-- > elemAt 2 (fromList [5,3]) Error: index out of range
elemAt :: Int -> Set a -> a
STRICT_1_OF_2(elemAt)
elemAt _ Tip = error "Set.elemAt: index out of range"
elemAt i (Bin _ x l r)
= case compare i sizeL of
LT -> elemAt i l
GT -> elemAt (i-sizeL-1) r
EQ -> x
where
sizeL = size l
-- | /O(log n)/. Delete the element at /index/, i.e. by its zero-based index in
-- the sorted sequence of elements. If the /index/ is out of range (less than zero,
-- greater or equal to 'size' of the set), 'error' is called.
--
-- > deleteAt 0 (fromList [5,3]) == singleton 5
-- > deleteAt 1 (fromList [5,3]) == singleton 3
-- > deleteAt 2 (fromList [5,3]) Error: index out of range
-- > deleteAt (-1) (fromList [5,3]) Error: index out of range
deleteAt :: Int -> Set a -> Set a
deleteAt i t = i `seq`
case t of
Tip -> error "Set.deleteAt: index out of range"
Bin _ x l r -> case compare i sizeL of
LT -> balanceR x (deleteAt i l) r
GT -> balanceL x l (deleteAt (i-sizeL-1) r)
EQ -> glue l r
where
sizeL = size l
{--------------------------------------------------------------------
Utility functions that maintain the balance properties of the tree.
All constructors assume that all values in [l] < [x] and all values
in [r] > [x], and that [l] and [r] are valid trees.
In order of sophistication:
[Bin sz x l r] The type constructor.
[bin x l r] Maintains the correct size, assumes that both [l]
and [r] are balanced with respect to each other.
[balance x l r] Restores the balance and size.
Assumes that the original tree was balanced and
that [l] or [r] has changed by at most one element.
[join x l r] Restores balance and size.
Furthermore, we can construct a new tree from two trees. Both operations
assume that all values in [l] < all values in [r] and that [l] and [r]
are valid:
[glue l r] Glues [l] and [r] together. Assumes that [l] and
[r] are already balanced with respect to each other.
[merge l r] Merges two trees and restores balance.
Note: in contrast to Adam's paper, we use (<=) comparisons instead
of (<) comparisons in [join], [merge] and [balance].
Quickcheck (on [difference]) showed that this was necessary in order
to maintain the invariants. It is quite unsatisfactory that I haven't
been able to find out why this is actually the case! Fortunately, it
doesn't hurt to be a bit more conservative.
--------------------------------------------------------------------}
{--------------------------------------------------------------------
Join
--------------------------------------------------------------------}
join :: a -> Set a -> Set a -> Set a
join x Tip r = insertMin x r
join x l Tip = insertMax x l
join x l@(Bin sizeL y ly ry) r@(Bin sizeR z lz rz)
| delta*sizeL < sizeR = balanceL z (join x l lz) rz
| delta*sizeR < sizeL = balanceR y ly (join x ry r)
| otherwise = bin x l r
-- insertMin and insertMax don't perform potentially expensive comparisons.
insertMax,insertMin :: a -> Set a -> Set a
insertMax x t
= case t of
Tip -> singleton x
Bin _ y l r
-> balanceR y l (insertMax x r)
insertMin x t
= case t of
Tip -> singleton x
Bin _ y l r
-> balanceL y (insertMin x l) r
{--------------------------------------------------------------------
[merge l r]: merges two trees.
--------------------------------------------------------------------}
merge :: Set a -> Set a -> Set a
merge Tip r = r
merge l Tip = l
merge l@(Bin sizeL x lx rx) r@(Bin sizeR y ly ry)
| delta*sizeL < sizeR = balanceL y (merge l ly) ry
| delta*sizeR < sizeL = balanceR x lx (merge rx r)
| otherwise = glue l r
{--------------------------------------------------------------------
[glue l r]: glues two trees together.
Assumes that [l] and [r] are already balanced with respect to each other.
--------------------------------------------------------------------}
glue :: Set a -> Set a -> Set a
glue Tip r = r
glue l Tip = l
glue l r
| size l > size r = let (m,l') = deleteFindMax l in balanceR m l' r
| otherwise = let (m,r') = deleteFindMin r in balanceL m l r'
-- | /O(log n)/. Delete and find the minimal element.
--
-- > deleteFindMin set = (findMin set, deleteMin set)
deleteFindMin :: Set a -> (a,Set a)
deleteFindMin t
= case t of
Bin _ x Tip r -> (x,r)
Bin _ x l r -> let (xm,l') = deleteFindMin l in (xm,balanceR x l' r)
Tip -> (error "Set.deleteFindMin: can not return the minimal element of an empty set", Tip)
-- | /O(log n)/. Delete and find the maximal element.
--
-- > deleteFindMax set = (findMax set, deleteMax set)
deleteFindMax :: Set a -> (a,Set a)
deleteFindMax t
= case t of
Bin _ x l Tip -> (x,l)
Bin _ x l r -> let (xm,r') = deleteFindMax r in (xm,balanceL x l r')
Tip -> (error "Set.deleteFindMax: can not return the maximal element of an empty set", Tip)
-- | /O(log n)/. Retrieves the minimal key of the set, and the set
-- stripped of that element, or 'Nothing' if passed an empty set.
minView :: Set a -> Maybe (a, Set a)
minView Tip = Nothing
minView x = Just (deleteFindMin x)
-- | /O(log n)/. Retrieves the maximal key of the set, and the set
-- stripped of that element, or 'Nothing' if passed an empty set.
maxView :: Set a -> Maybe (a, Set a)
maxView Tip = Nothing
maxView x = Just (deleteFindMax x)
{--------------------------------------------------------------------
[balance x l r] balances two trees with value x.
The sizes of the trees should balance after decreasing the
size of one of them. (a rotation).
[delta] is the maximal relative difference between the sizes of
two trees, it corresponds with the [w] in Adams' paper.
[ratio] is the ratio between an outer and inner sibling of the
heavier subtree in an unbalanced setting. It determines
whether a double or single rotation should be performed
to restore balance. It is correspondes with the inverse
of $\alpha$ in Adam's article.
Note that according to the Adam's paper:
- [delta] should be larger than 4.646 with a [ratio] of 2.
- [delta] should be larger than 3.745 with a [ratio] of 1.534.
But the Adam's paper is errorneous:
- it can be proved that for delta=2 and delta>=5 there does
not exist any ratio that would work
- delta=4.5 and ratio=2 does not work
That leaves two reasonable variants, delta=3 and delta=4,
both with ratio=2.
- A lower [delta] leads to a more 'perfectly' balanced tree.
- A higher [delta] performs less rebalancing.
In the benchmarks, delta=3 is faster on insert operations,
and delta=4 has slightly better deletes. As the insert speedup
is larger, we currently use delta=3.
--------------------------------------------------------------------}
delta,ratio :: Int
delta = 3
ratio = 2
-- The balance function is equivalent to the following:
--
-- balance :: a -> Set a -> Set a -> Set a
-- balance x l r
-- | sizeL + sizeR <= 1 = Bin sizeX x l r
-- | sizeR > delta*sizeL = rotateL x l r
-- | sizeL > delta*sizeR = rotateR x l r
-- | otherwise = Bin sizeX x l r
-- where
-- sizeL = size l
-- sizeR = size r
-- sizeX = sizeL + sizeR + 1
--
-- rotateL :: a -> Set a -> Set a -> Set a
-- rotateL x l r@(Bin _ _ ly ry) | size ly < ratio*size ry = singleL x l r
-- | otherwise = doubleL x l r
-- rotateR :: a -> Set a -> Set a -> Set a
-- rotateR x l@(Bin _ _ ly ry) r | size ry < ratio*size ly = singleR x l r
-- | otherwise = doubleR x l r
--
-- singleL, singleR :: a -> Set a -> Set a -> Set a
-- singleL x1 t1 (Bin _ x2 t2 t3) = bin x2 (bin x1 t1 t2) t3
-- singleR x1 (Bin _ x2 t1 t2) t3 = bin x2 t1 (bin x1 t2 t3)
--
-- doubleL, doubleR :: a -> Set a -> Set a -> Set a
-- doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
-- doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
--
-- It is only written in such a way that every node is pattern-matched only once.
--
-- Only balanceL and balanceR are needed at the moment, so balance is not here anymore.
-- In case it is needed, it can be found in Data.Map.
-- Functions balanceL and balanceR are specialised versions of balance.
-- balanceL only checks whether the left subtree is too big,
-- balanceR only checks whether the right subtree is too big.
-- balanceL is called when left subtree might have been inserted to or when
-- right subtree might have been deleted from.
balanceL :: a -> Set a -> Set a -> Set a
balanceL x l r = case r of
Tip -> case l of
Tip -> Bin 1 x Tip Tip
(Bin _ _ Tip Tip) -> Bin 2 x l Tip
(Bin _ lx Tip (Bin _ lrx _ _)) -> Bin 3 lrx (Bin 1 lx Tip Tip) (Bin 1 x Tip Tip)
(Bin _ lx ll@(Bin _ _ _ _) Tip) -> Bin 3 lx ll (Bin 1 x Tip Tip)
(Bin ls lx ll@(Bin lls _ _ _) lr@(Bin lrs lrx lrl lrr))
| lrs < ratio*lls -> Bin (1+ls) lx ll (Bin (1+lrs) x lr Tip)
| otherwise -> Bin (1+ls) lrx (Bin (1+lls+size lrl) lx ll lrl) (Bin (1+size lrr) x lrr Tip)
(Bin rs _ _ _) -> case l of
Tip -> Bin (1+rs) x Tip r
(Bin ls lx ll lr)
| ls > delta*rs -> case (ll, lr) of
(Bin lls _ _ _, Bin lrs lrx lrl lrr)
| lrs < ratio*lls -> Bin (1+ls+rs) lx ll (Bin (1+rs+lrs) x lr r)
| otherwise -> Bin (1+ls+rs) lrx (Bin (1+lls+size lrl) lx ll lrl) (Bin (1+rs+size lrr) x lrr r)
(_, _) -> error "Failure in Data.Map.balanceL"
| otherwise -> Bin (1+ls+rs) x l r
{-# NOINLINE balanceL #-}
-- balanceR is called when right subtree might have been inserted to or when
-- left subtree might have been deleted from.
balanceR :: a -> Set a -> Set a -> Set a
balanceR x l r = case l of
Tip -> case r of
Tip -> Bin 1 x Tip Tip
(Bin _ _ Tip Tip) -> Bin 2 x Tip r
(Bin _ rx Tip rr@(Bin _ _ _ _)) -> Bin 3 rx (Bin 1 x Tip Tip) rr
(Bin _ rx (Bin _ rlx _ _) Tip) -> Bin 3 rlx (Bin 1 x Tip Tip) (Bin 1 rx Tip Tip)
(Bin rs rx rl@(Bin rls rlx rll rlr) rr@(Bin rrs _ _ _))
| rls < ratio*rrs -> Bin (1+rs) rx (Bin (1+rls) x Tip rl) rr
| otherwise -> Bin (1+rs) rlx (Bin (1+size rll) x Tip rll) (Bin (1+rrs+size rlr) rx rlr rr)
(Bin ls _ _ _) -> case r of
Tip -> Bin (1+ls) x l Tip
(Bin rs rx rl rr)
| rs > delta*ls -> case (rl, rr) of
(Bin rls rlx rll rlr, Bin rrs _ _ _)
| rls < ratio*rrs -> Bin (1+ls+rs) rx (Bin (1+ls+rls) x l rl) rr
| otherwise -> Bin (1+ls+rs) rlx (Bin (1+ls+size rll) x l rll) (Bin (1+rrs+size rlr) rx rlr rr)
(_, _) -> error "Failure in Data.Map.balanceR"
| otherwise -> Bin (1+ls+rs) x l r
{-# NOINLINE balanceR #-}
{--------------------------------------------------------------------
The bin constructor maintains the size of the tree
--------------------------------------------------------------------}
bin :: a -> Set a -> Set a -> Set a
bin x l r
= Bin (size l + size r + 1) x l r
{-# INLINE bin #-}
{--------------------------------------------------------------------
Utilities
--------------------------------------------------------------------}
foldlStrict :: (a -> b -> a) -> a -> [b] -> a
foldlStrict f = go
where
go z [] = z
go z (x:xs) = let z' = f z x in z' `seq` go z' xs
{-# INLINE foldlStrict #-}
{--------------------------------------------------------------------
Debugging
--------------------------------------------------------------------}
-- | /O(n)/. Show the tree that implements the set. The tree is shown
-- in a compressed, hanging format.
showTree :: Show a => Set a -> String
showTree s
= showTreeWith True False s
{- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
the tree that implements the set. If @hang@ is
@True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
@wide@ is 'True', an extra wide version is shown.
> Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
> 4
> +--2
> | +--1
> | +--3
> +--5
>
> Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
> 4
> |
> +--2
> | |
> | +--1
> | |
> | +--3
> |
> +--5
>
> Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
> +--5
> |
> 4
> |
> | +--3
> | |
> +--2
> |
> +--1
-}
showTreeWith :: Show a => Bool -> Bool -> Set a -> String
showTreeWith hang wide t
| hang = (showsTreeHang wide [] t) ""
| otherwise = (showsTree wide [] [] t) ""
showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
showsTree wide lbars rbars t
= case t of
Tip -> showsBars lbars . showString "|\n"
Bin _ x Tip Tip
-> showsBars lbars . shows x . showString "\n"
Bin _ x l r
-> showsTree wide (withBar rbars) (withEmpty rbars) r .
showWide wide rbars .
showsBars lbars . shows x . showString "\n" .
showWide wide lbars .
showsTree wide (withEmpty lbars) (withBar lbars) l
showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
showsTreeHang wide bars t
= case t of
Tip -> showsBars bars . showString "|\n"
Bin _ x Tip Tip
-> showsBars bars . shows x . showString "\n"
Bin _ x l r
-> showsBars bars . shows x . showString "\n" .
showWide wide bars .
showsTreeHang wide (withBar bars) l .
showWide wide bars .
showsTreeHang wide (withEmpty bars) r
showWide :: Bool -> [String] -> String -> String
showWide wide bars
| wide = showString (concat (reverse bars)) . showString "|\n"
| otherwise = id
showsBars :: [String] -> ShowS
showsBars bars
= case bars of
[] -> id
_ -> showString (concat (reverse (tail bars))) . showString node
node :: String
node = "+--"
withBar, withEmpty :: [String] -> [String]
withBar bars = "| ":bars
withEmpty bars = " ":bars
{--------------------------------------------------------------------
Assertions
--------------------------------------------------------------------}
-- | /O(n)/. Test if the internal set structure is valid.
valid :: Ord a => Set a -> Bool
valid t
= balanced t && ordered t && validsize t
ordered :: Ord a => Set a -> Bool
ordered t
= bounded (const True) (const True) t
where
bounded lo hi t'
= case t' of
Tip -> True
Bin _ x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
balanced :: Set a -> Bool
balanced t
= case t of
Tip -> True
Bin _ _ l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
balanced l && balanced r
validsize :: Set a -> Bool
validsize t
= (realsize t == Just (size t))
where
realsize t'
= case t' of
Tip -> Just 0
Bin sz _ l r -> case (realsize l,realsize r) of
(Just n,Just m) | n+m+1 == sz -> Just sz
_ -> Nothing
| ekmett/containers | Data/Set/Base.hs | bsd-3-clause | 54,658 | 0 | 21 | 14,626 | 11,947 | 6,175 | 5,772 | -1 | -1 |
{-# OPTIONS_GHC -F -pgmF inch #-}
{-# LANGUAGE RankNTypes, GADTs, KindSignatures, ScopedTypeVariables,
NPlusKPatterns #-}
module MergeSort where
import Vectors
comp f g x = f (g x)
data DTree :: * -> Integer -> * where
Empty :: DTree a 0
Leaf :: a -> DTree a 1
Even :: forall a (n :: Integer) . 1 <= n =>
DTree a n -> DTree a n -> DTree a (2*n)
Odd :: forall a (n :: Integer) . 1 <= n =>
DTree a (n+1) -> DTree a n -> DTree a (2*n+1)
deriving Show
insert :: forall a (n :: Integer) . a -> DTree a n -> DTree a (n+1)
insert i Empty = Leaf i
insert i (Leaf j) = Even (Leaf i) (Leaf j)
insert i (Even l r) = Odd (insert i l) r
insert i (Odd l r) = Even l (insert i r)
merge :: forall (m n :: Integer) .
Vec Integer m -> Vec Integer n -> Vec Integer (m+n)
merge VNil ys = ys
merge xs VNil = xs
merge (VCons x xs) (VCons y ys) | (<=) x y = VCons x (merge xs (VCons y ys))
| otherwise = VCons y (merge (VCons x xs) ys)
build = vifold Empty insert
flatten :: forall (n :: Integer) . DTree Integer n -> Vec Integer n
flatten Empty = VNil
flatten (Leaf i) = VCons i VNil
flatten (Even l r) = merge (flatten l) (flatten r)
flatten (Odd l r) = merge (flatten l) (flatten r)
sort = comp flatten build
data OVec :: Integer -> Integer -> Integer -> * where
ONil :: forall (l u :: Integer) . l <= u => OVec 0 l u
OCons :: forall (n l u :: Integer) . pi (x :: Integer) . l <= x =>
OVec n x u -> OVec (n+1) l u
deriving Show
ltCompare :: forall a. pi (x y :: Integer) . (x <= y => a) -> (x > y => a) -> a
ltCompare {x} {y} l g | {x <= y} = l
ltCompare {x} {y} l g | {x > y} = g
omerge :: forall (m n l u :: Integer) . OVec m l u -> OVec n l u -> OVec (m+n) l u
omerge ONil ys = ys
omerge xs ONil = xs
omerge (OCons {x} xs) (OCons {y} ys)
= ltCompare {x} {y} (OCons {x} (omerge xs (OCons {y} ys)))
(OCons {y} (omerge (OCons {x} xs) ys))
data In :: Integer -> Integer -> * where
In :: forall (l u :: Integer) . pi (x :: Integer) . (l <= x, x <= u) => In l u
deriving Show
oflatten :: forall (n l u :: Integer) . l <= u => DTree (In l u) n -> OVec n l u
oflatten Empty = ONil
oflatten (Leaf (In {i})) = OCons {i} ONil
oflatten (Even l r) = omerge (oflatten l) (oflatten r)
oflatten (Odd l r) = omerge (oflatten l) (oflatten r)
osort = comp oflatten build | adamgundry/inch | examples/MergeSort.hs | bsd-3-clause | 2,457 | 14 | 13 | 740 | 1,236 | 649 | 587 | -1 | -1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
module GithubWebhook.Types.Events.PushEvent
( PushEvent(..)
) where
import qualified Data.Text as T
import qualified Data.Aeson as A
import qualified Data.Aeson.TH as A
import qualified GithubWebhook.Types.SmallUser as SmallUser
import qualified GithubWebhook.Types.Repo as R
import qualified GithubWebhook.Types.Commit as C
import qualified GithubWebhook.Types.BigUser as BigUser
import GHC.Generics
import qualified Utils
data PushEvent = PushEvent
{ ref :: T.Text
, before :: T.Text
, after :: T.Text
, created :: Bool
, deleted :: Bool
, forced :: Bool
, baseRef :: Maybe T.Text
, compare :: T.Text
, commits :: [C.Commit]
, headCommit :: C.Commit
, repository :: R.Repo
, pusher :: SmallUser.SmallUser
, sender :: BigUser.BigUser } deriving (Eq, Generic, Show)
$(A.deriveJSON
A.defaultOptions
{A.fieldLabelModifier = Utils.camelCaseToSnakeCase}
''PushEvent) | bgwines/hueue | src/GithubWebhook/Types/Events/PushEvent.hs | bsd-3-clause | 997 | 0 | 10 | 192 | 247 | 160 | 87 | 31 | 0 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.NV.TransformFeedback2
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- All raw functions and tokens from the NV_transform_feedback2 extension, see
-- <http://www.opengl.org/registry/specs/NV/transform_feedback2.txt>.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.NV.TransformFeedback2 (
-- * Functions
glBindTransformFeedback,
glDeleteTransformFeedbacks,
glGenTransformFeedbacks,
glIsTransformFeedback,
glPauseTransformFeedback,
glResumeTransformFeedback,
glDrawTransformFeedback,
-- * Tokens
gl_TRANSFORM_FEEDBACK,
gl_TRANSFORM_FEEDBACK_BUFFER_PAUSED,
gl_TRANSFORM_FEEDBACK_BUFFER_ACTIVE,
gl_TRANSFORM_FEEDBACK_BINDING
) where
import Graphics.Rendering.OpenGL.Raw.ARB.TransformFeedback2
| mfpi/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/NV/TransformFeedback2.hs | bsd-3-clause | 1,062 | 0 | 4 | 134 | 70 | 54 | 16 | 13 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
-- | Description: Unique identifiers for internal an external use.
module Retcon.Identifier (
-- * Configuration names
EntityName(..),
SourceName(..),
-- * Unique identifiers
InternalID, ForeignID,
ForeignKey(..),
InternalKey(..),
-- * Checking compatibility
Synchronisable(..),
compatibleEntity,
compatibleSource,
) where
import Data.Aeson.TH
import Data.String
import Data.Text (Text)
import qualified Data.Text as T
import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.ToRow
-- | Unique name for an entity.
newtype EntityName = EntityName { ename :: Text }
deriving (Eq, Ord)
instance IsString EntityName where
fromString = EntityName . T.pack
instance Show EntityName where
show = T.unpack . ename
instance Read EntityName where
readsPrec _ s = [(EntityName (T.pack s), "")]
-- | Unique name for a data source.
newtype SourceName = SourceName { sname :: Text }
deriving (Eq, Ord)
instance Show SourceName where
show = T.unpack . sname
instance IsString SourceName where
fromString = SourceName . T.pack
instance Read SourceName where
readsPrec _ s = [(SourceName (T.pack s), "")]
-- | Types which participate, in one way or another, in the synchronisation
-- process.
class Synchronisable a where
-- | Get the 'EntityName' for which the value is valid.
getEntityName :: a -> EntityName
-- | Get the 'SourceName' for which the value is valid.
getSourceName :: a -> SourceName
--------------------------------------------------------------------------------
type InternalID = Int
type ForeignID = Text
-- | Uniquely identify a 'Document' shared across one or more 'DataSource's.
--
-- Each 'InternalKey' value can be mapped to the 'ForeignKey's for the
-- 'DataSource's which store copies of the associated 'Document'.
data InternalKey = InternalKey
{ ikEntity :: EntityName
, ikID :: InternalID
} deriving (Eq, Ord, Show)
instance Synchronisable InternalKey where
getEntityName = ikEntity
getSourceName _ = SourceName ""
-- | Uniquely identify a 'Document' stored in 'DataSource'.
data ForeignKey = ForeignKey
{ fkEntity :: EntityName
, fkSource :: SourceName
, fkID :: ForeignID
} deriving (Eq, Ord, Show)
instance Synchronisable ForeignKey where
getEntityName = fkEntity
getSourceName = fkSource
-- json
$(deriveJSON defaultOptions ''EntityName)
$(deriveJSON defaultOptions ''SourceName)
$(deriveJSON defaultOptions ''ForeignKey)
-- postgres
instance ToField EntityName where
toField (EntityName n) = toField n
instance ToField SourceName where
toField (SourceName n) = toField n
instance ToRow ForeignKey where
toRow (ForeignKey a b c) = toRow (a,b,c)
instance ToRow InternalKey where
toRow (InternalKey a b) = toRow (a,b)
--------------------------------------------------------------------------------
-- | Check that two synchronisable values have the same entity.
compatibleEntity
:: (Synchronisable a, Synchronisable b)
=> a
-> b
-> Bool
compatibleEntity a b = getEntityName a == getEntityName b
-- | Check that two synchronisable values have the same data source.
compatibleSource
:: (Synchronisable a, Synchronisable b)
=> a
-> b
-> Bool
compatibleSource a b = compatibleEntity a b && getSourceName a == getSourceName b
| anchor/retcon | lib/Retcon/Identifier.hs | bsd-3-clause | 3,539 | 0 | 11 | 763 | 749 | 422 | 327 | 76 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Graphics.X11.Xlib
-- Copyright : (c) Alastair Reid, 1999-2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- A collection of FFI declarations for interfacing with Xlib.
--
-- The library aims to provide a direct translation of the X
-- binding into Haskell so the most important documentation you
-- should read is /The Xlib Programming Manual/, available online at
-- <http://tronche.com/gui/x/xlib/>. Let me say that again because
-- it is very important. Get hold of this documentation and read it:
-- it tells you almost everything you need to know to use this library.
--
-----------------------------------------------------------------------------
module Graphics.X11.Xlib
( -- * Conventions
-- $conventions
-- * Types
module Graphics.X11.Types,
-- module Graphics.X11.Xlib.Types,
Display, Screen, Visual, GC, SetWindowAttributes,
Point(..), Rectangle(..), Arc(..), Segment(..), Color(..),
Pixel, Position, Dimension, Angle, ScreenNumber, Buffer,
-- * X11 library functions
module Graphics.X11.Xlib.Event,
module Graphics.X11.Xlib.Display,
module Graphics.X11.Xlib.Screen,
module Graphics.X11.Xlib.Window,
module Graphics.X11.Xlib.Context,
module Graphics.X11.Xlib.Color,
module Graphics.X11.Xlib.Font,
module Graphics.X11.Xlib.Atom,
module Graphics.X11.Xlib.Region,
module Graphics.X11.Xlib.Misc,
) where
import Graphics.X11.Types
import Graphics.X11.Xlib.Types
import Graphics.X11.Xlib.Event
import Graphics.X11.Xlib.Display
import Graphics.X11.Xlib.Screen
import Graphics.X11.Xlib.Window
import Graphics.X11.Xlib.Context
import Graphics.X11.Xlib.Color
import Graphics.X11.Xlib.Font
import Graphics.X11.Xlib.Atom
import Graphics.X11.Xlib.Region
import Graphics.X11.Xlib.Misc
{- $conventions
In translating the library, we had to change names to conform with
Haskell's lexical syntax: function names and names of constants must start
with a lowercase letter; type names must start with an uppercase letter.
The case of the remaining letters is unchanged.
In addition, we chose to take advantage of Haskell's module system to
allow us to drop common prefixes (@X@, @XA_@, etc.) attached to X11
identifiers.
We named enumeration types so that function types would be easier
to understand. For example, we added 'Status', 'WindowClass', etc.
Note that the types are synonyms for 'Int' so no extra typesafety was
obtained.
We consistently raise exceptions when a function returns an error code.
In practice, this only affects the following functions because most Xlib
functions do not return error codes: 'allocColor', 'allocNamedColor',
'fetchBuffer', 'fetchBytes', 'fontFromGC', 'getGeometry', 'getIconName',
'iconifyWindow', 'loadQueryFont', 'lookupColor', 'openDisplay',
'parseColor', 'queryBestCursor', 'queryBestSize', 'queryBestStipple',
'queryBestTile', 'rotateBuffers', 'selectInput', 'storeBuffer',
'storeBytes', 'withdrawWindow'.
-}
----------------------------------------------------------------
-- End
----------------------------------------------------------------
| FranklinChen/hugs98-plus-Sep2006 | packages/X11/Graphics/X11/Xlib.hs | bsd-3-clause | 3,374 | 12 | 5 | 538 | 289 | 213 | 76 | 28 | 0 |
{-# LANGUAGE OverloadedStrings #-}
-- | High level functions for downloading files.
module Control.Shell.Download
( URI
, fetch, fetchBytes
, fetchFile
, fetchTags, fetchXML, fetchFeed
) where
import Data.ByteString as BS (ByteString, writeFile)
import Data.ByteString.UTF8 as BS
import Data.ByteString.Lazy as LBS
import Data.ByteString.Lazy.UTF8 as LBS
import Data.String
import Network.HTTP.Simple
import Network.HTTP.Types
import Text.Feed.Import (parseFeedString)
import Text.Feed.Types (Feed)
import Text.HTML.TagSoup (Tag, parseTags)
import Text.XML.Light (Content, parseXML)
import Control.Shell
-- | A Uniform Resource Locator.
type URI = String
liftE :: Show e => IO (Either e a) -> Shell a
liftE m = do
res <- liftIO m
case res of
Left e -> fail (show e)
Right x -> return x
httpFail :: Int -> BS.ByteString -> Shell a
httpFail code reason =
fail $ "HTTP error " ++ show code ++ ": " ++ BS.toString reason
fetchSomething :: URI -> Shell LBS.ByteString
fetchSomething uri = do
req <- assert ("could not parse URI `" ++ uri ++ "'") $ do
try $ liftIO $ parseRequest uri
rsp <- httpLBS req
case getResponseStatus rsp of
(Status 200 _) -> return (getResponseBody rsp)
(Status code reason) -> httpFail code reason
-- | Download content specified by a URL, returning the content
-- as a strict 'ByteString'.
fetchBytes :: URI -> Shell BS.ByteString
fetchBytes = fmap LBS.toStrict . fetchSomething
-- | Download content specified by a URL, returning the content
-- as a 'String'. The content is interpreted as UTF8.
fetch :: URI -> Shell String
fetch = fmap LBS.toString . fetchSomething
-- | Download content specified by a URL, writing the content to
-- the file specified by the given 'FilePath'.
fetchFile :: FilePath -> URI -> Shell ()
fetchFile file = fetchSomething >=> liftIO . LBS.writeFile file
-- | Download the content as for 'fetch', but return it as a list of parsed
-- tags using the tagsoup html parser.
fetchTags :: URI -> Shell [Tag String]
fetchTags = fmap parseTags . fetch
-- | Download the content as for 'fetch', but return it as parsed XML, using
-- the xml-light parser.
fetchXML :: URI -> Shell [Content]
fetchXML = fmap parseXML . fetch
-- | Download the content as for 'fetch', but return it as as parsed RSS or
-- Atom content, using the feed library parser.
fetchFeed :: URI -> Shell Feed
fetchFeed uri = do
str <- LBS.toString <$> fetchSomething uri
assert ("could not parse feed from `" ++ uri ++ "'") (parseFeedString str)
| valderman/shellmate | shellmate-extras/Control/Shell/Download.hs | bsd-3-clause | 2,534 | 0 | 12 | 482 | 634 | 338 | 296 | -1 | -1 |
module QACG.CircGen.Bit.Toffoli
( tof
,tofMatchedD1
,leftTof
,rightTof
) where
import QACG.CircUtils.CircuitState
import Control.Exception(assert)
tof :: String -> String -> String -> CircuitState ()
tof a b c = do consts <- getConst 4
assert (length consts == 4) $ applyTof a b c consts
freeConst consts
where applyTof x y z [c0,c1,c2,c3]
= do hadamard z
cnot y c2
cnot x c0
cnot y c1
cnot z c2
cnot c0 c3
cnot x c1
cnot z c3
cnot c2 c0
tgate x
tgate y
tgate z
tgate c0
tgateInv c1
tgateInv c2
tgateInv c3
cnot c2 c0
cnot z c3
cnot x c1
cnot c0 c3
cnot z c2
cnot y c1
cnot x c0
cnot y c2
hadamard z
applyTof _ _ _ _ = assert False $ return () --Should never happen!
tofMatchedD1 :: String -> String -> String -> CircuitState ()
tofMatchedD1 e f g = do consts <- getConst 1
applyTof e f g (head consts)
freeConst consts
where applyTof x y z c
= do hadamard z
cnot z y
cnot x c
cnot z x
cnot y c
tgateInv x
tgateInv y
tgate z
tgate c
cnot y c
cnot z x
cnot x c
cnot z y
hadamard z
leftTof :: String -> String -> String -> CircuitState ()
leftTof x y z
= do hadamard z
cnot z y
cnot y x
tgate x
tgateInv y
tgate z
cnot z y
cnot y x
tgateInv x
cnot z x
hadamard z
rightTof :: String -> String -> String -> CircuitState ()
rightTof x y z
= do hadamard z
cnot z x
tgateInv x
cnot y x
cnot z y
tgate z
tgateInv y
tgate x
cnot y x
cnot z y
hadamard z
| aparent/qacg | src/QACG/CircGen/Bit/Toffoli.hs | bsd-3-clause | 2,226 | 0 | 11 | 1,174 | 758 | 319 | 439 | 83 | 2 |
#!/usr/bin/env stack
-- stack --install-ghc runghc --package=shake --package=extra --package=zip-archive --package=mime-types --package=http-types --package=http-conduit --package=text --package=conduit-combinators --package=conduit --package=case-insensitive --package=aeson --package=zlib --package tar
{-# OPTIONS_GHC -Wall -Werror #-}
{-# LANGUAGE RecordWildCards #-}
import Control.Applicative
import Control.Exception
import Control.Monad
import Control.Monad.Trans.Resource (runResourceT)
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy.Char8 as L8
import Data.List
import Data.Maybe
import Distribution.PackageDescription.Parse
import Distribution.Text
import Distribution.System
import Distribution.Package
import Distribution.PackageDescription hiding (options)
import Distribution.Verbosity
import System.Console.GetOpt
import System.Environment
import System.Directory
import System.IO.Error
import System.Process
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Zip as Zip
import qualified Codec.Compression.GZip as GZip
import Data.Aeson
import qualified Data.CaseInsensitive as CI
import Data.Conduit
import qualified Data.Conduit.Combinators as CC
import Data.List.Extra
import qualified Data.Text as T
import Development.Shake
import Development.Shake.FilePath
import Network.HTTP.Conduit
import Network.HTTP.Types
import Network.Mime
import Prelude -- Silence AMP warning
-- | Entrypoint.
main :: IO ()
main =
shakeArgsWith
shakeOptions { shakeFiles = releaseDir
, shakeVerbosity = Chatty
, shakeChange = ChangeModtimeAndDigestInput }
options $
\flags args -> do
gStackPackageDescription <-
packageDescription <$> readPackageDescription silent "stack.cabal"
gGithubAuthToken <- lookupEnv githubAuthTokenEnvVar
gGitRevCount <- length . lines <$> readProcess "git" ["rev-list", "HEAD"] ""
gGitSha <- trim <$> readProcess "git" ["rev-parse", "HEAD"] ""
gHomeDir <- getHomeDirectory
let gGpgKey = "9BEFB442"
gAllowDirty = False
gGithubReleaseTag = Nothing
Platform arch _ = buildPlatform
gArch = arch
gBinarySuffix = ""
gUploadLabel = Nothing
gLocalInstallRoot = "" -- Set to real value below.
gProjectRoot = "" -- Set to real value velow.
global0 = foldl (flip id) Global{..} flags
-- Need to get paths after options since the '--arch' argument can effect them.
localInstallRoot' <- getStackPath global0 "local-install-root"
projectRoot' <- getStackPath global0 "project-root"
let global = global0
{ gLocalInstallRoot = localInstallRoot'
, gProjectRoot = projectRoot' }
return $ Just $ rules global args
where
getStackPath global path = do
out <- readProcess stackProgName (stackArgs global ++ ["path", "--" ++ path]) ""
return $ trim $ fromMaybe out $ stripPrefix (path ++ ":") out
-- | Additional command-line options.
options :: [OptDescr (Either String (Global -> Global))]
options =
[ Option "" [gpgKeyOptName]
(ReqArg (\v -> Right $ \g -> g{gGpgKey = v}) "USER-ID")
"GPG user ID to sign distribution package with."
, Option "" [allowDirtyOptName] (NoArg $ Right $ \g -> g{gAllowDirty = True})
"Allow a dirty working tree for release."
, Option "" [githubAuthTokenOptName]
(ReqArg (\v -> Right $ \g -> g{gGithubAuthToken = Just v}) "TOKEN")
("Github personal access token (defaults to " ++
githubAuthTokenEnvVar ++
" environment variable).")
, Option "" [githubReleaseTagOptName]
(ReqArg (\v -> Right $ \g -> g{gGithubReleaseTag = Just v}) "TAG")
"Github release tag to upload to."
, Option "" [archOptName]
(ReqArg
(\v -> case simpleParse v of
Nothing -> Left $ "Unknown architecture in --arch option: " ++ v
Just arch -> Right $ \g -> g{gArch = arch})
"ARCHITECTURE")
"Architecture to build (e.g. 'i386' or 'x86_64')."
, Option "" [binaryVariantOptName]
(ReqArg (\v -> Right $ \g -> g{gBinarySuffix = v}) "SUFFIX")
"Extra suffix to add to binary executable archive filename."
, Option "" [uploadLabelOptName]
(ReqArg (\v -> Right $ \g -> g{gUploadLabel = Just v}) "LABEL")
"Label to give the uploaded release asset" ]
-- | Shake rules.
rules :: Global -> [String] -> Rules ()
rules global@Global{..} args = do
case args of
[] -> error "No wanted target(s) specified."
_ -> want args
phony releasePhony $ do
need [checkPhony]
need [uploadPhony]
phony cleanPhony $
removeFilesAfter releaseDir ["//*"]
phony checkPhony $
need [releaseCheckDir </> binaryExeFileName]
phony uploadPhony $
mapM_ (\f -> need [releaseDir </> f <.> uploadExt]) binaryPkgFileNames
phony buildPhony $
mapM_ (\f -> need [releaseDir </> f]) binaryPkgFileNames
distroPhonies ubuntuDistro ubuntuVersions debPackageFileName
distroPhonies debianDistro debianVersions debPackageFileName
distroPhonies centosDistro centosVersions rpmPackageFileName
distroPhonies fedoraDistro fedoraVersions rpmPackageFileName
phony archUploadPhony $ need [archDir </> archPackageFileName <.> uploadExt]
phony archBuildPhony $ need [archDir </> archPackageFileName]
releaseDir </> "*" <.> uploadExt %> \out -> do
let srcFile = dropExtension out
mUploadLabel =
if takeExtension srcFile == ascExt
then fmap (++ " (GPG signature)") gUploadLabel
else gUploadLabel
uploadToGithubRelease global srcFile mUploadLabel
copyFileChanged srcFile out
releaseCheckDir </> binaryExeFileName %> \out -> do
need [installBinDir </> stackExeFileName]
Stdout dirty <- cmd "git status --porcelain"
when (not gAllowDirty && not (null (trim dirty))) $
error ("Working tree is dirty. Use --" ++ allowDirtyOptName ++ " option to continue anyway.")
let instExeFile = installBinDir </> stackExeFileName
tmpExeFile = installBinDir </> stackExeFileName <.> "tmp"
--EKB FIXME: once 'stack install --path' implemented, use it instead of this temp file.
liftIO $ renameFile instExeFile tmpExeFile
actionFinally
(do opt <- addPath [installBinDir] []
-- () <- cmd opt stackProgName (stackArgs global) "build --pedantic --haddock --no-haddock-deps"
() <- cmd opt stackProgName (stackArgs global) "build --pedantic"
() <- cmd opt stackProgName (stackArgs global) "clean"
() <- cmd opt stackProgName (stackArgs global) "build --pedantic"
() <- cmd opt stackProgName (stackArgs global) "test --pedantic --flag stack:integration-tests"
return ())
(renameFile tmpExeFile instExeFile)
copyFileChanged (installBinDir </> stackExeFileName) out
releaseDir </> binaryPkgZipFileName %> \out -> do
stageFiles <- getBinaryPkgStageFiles
putNormal $ "zip " ++ out
liftIO $ do
entries <- forM stageFiles $ \stageFile -> do
Zip.readEntry
[Zip.OptLocation
(dropDirectoryPrefix (releaseStageDir </> binaryPkgStageDirName) stageFile)
False]
stageFile
let archive = foldr Zip.addEntryToArchive Zip.emptyArchive entries
L8.writeFile out (Zip.fromArchive archive)
releaseDir </> binaryPkgTarGzFileName %> \out -> do
stageFiles <- getBinaryPkgStageFiles
writeTarGz out releaseStageDir stageFiles
releaseStageDir </> binaryPkgStageDirName </> stackExeFileName %> \out -> do
copyFileChanged (releaseDir </> binaryExeFileName) out
releaseStageDir </> (binaryPkgStageDirName ++ "//*") %> \out -> do
copyFileChanged
(dropDirectoryPrefix (releaseStageDir </> binaryPkgStageDirName) out)
out
releaseDir </> binaryExeFileName %> \out -> do
need [installBinDir </> stackExeFileName]
case platformOS of
Windows -> do
-- Windows doesn't have or need a 'strip' command, so skip it.
-- Instead, we sign the executable
liftIO $ copyFile (installBinDir </> stackExeFileName) out
actionOnException
(command_ [] "c:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\Bin\\signtool.exe"
["sign"
,"/v"
,"/d", synopsis gStackPackageDescription
,"/du", homepage gStackPackageDescription
,"/n", "FP Complete, Corporation"
,"/t", "http://timestamp.verisign.com/scripts/timestamp.dll"
,out])
(removeFile out)
Linux ->
cmd "strip -p --strip-unneeded --remove-section=.comment -o"
[out, installBinDir </> stackExeFileName]
_ ->
cmd "strip -o"
[out, installBinDir </> stackExeFileName]
releaseDir </> binaryPkgSignatureFileName %> \out -> do
need [out -<.> ""]
_ <- liftIO $ tryJust (guard . isDoesNotExistError) (removeFile out)
cmd "gpg --detach-sig --armor"
[ "-u", gGpgKey
, dropExtension out ]
installBinDir </> stackExeFileName %> \out -> do
alwaysRerun
actionOnException
(cmd stackProgName (stackArgs global) "--install-ghc build --pedantic")
(removeFile out)
debDistroRules ubuntuDistro ubuntuVersions
debDistroRules debianDistro debianVersions
rpmDistroRules centosDistro centosVersions
rpmDistroRules fedoraDistro fedoraVersions
archDir </> archPackageFileName <.> uploadExt %> \out -> do
let pkgFile = dropExtension out
need [pkgFile]
() <- cmd "aws s3 cp"
[ pkgFile
, "s3://download.fpcomplete.com/archlinux/" ++ takeFileName pkgFile ]
copyFileChanged pkgFile out
archDir </> archPackageFileName %> \out -> do
docFiles <- getDocFiles
let inputFiles = concat
[[archStagedExeFile
,archStagedBashCompletionFile]
,map (archStagedDocDir </>) docFiles]
need inputFiles
putNormal $ "tar gzip " ++ out
writeTarGz out archStagingDir inputFiles
archStagedExeFile %> \out -> do
copyFileChanged (releaseDir </> binaryExeFileName) out
archStagedBashCompletionFile %> \out -> do
writeBashCompletion archStagedExeFile archStagingDir out
archStagedDocDir ++ "//*" %> \out -> do
let origFile = dropDirectoryPrefix archStagedDocDir out
copyFileChanged origFile out
where
debDistroRules debDistro0 debVersions = do
let anyVersion0 = anyDistroVersion debDistro0
distroVersionDir anyVersion0 </> debPackageFileName anyVersion0 <.> uploadExt %> \out -> do
let DistroVersion{..} = distroVersionFromPath out debVersions
pkgFile = dropExtension out
need [pkgFile]
() <- cmd "deb-s3 upload -b download.fpcomplete.com --preserve-versions"
[ "--sign=" ++ gGpgKey
, "--prefix=" ++ dvDistro ++ "/" ++ dvCodeName
, pkgFile ]
copyFileChanged pkgFile out
distroVersionDir anyVersion0 </> debPackageFileName anyVersion0 %> \out -> do
docFiles <- getDocFiles
let dv@DistroVersion{..} = distroVersionFromPath out debVersions
inputFiles = concat
[[debStagedExeFile dv
,debStagedBashCompletionFile dv]
,map (debStagedDocDir dv </>) docFiles]
need inputFiles
cmd "fpm -f -s dir -t deb"
"--deb-recommends git --deb-recommends gnupg"
"-d g++ -d gcc -d libc6-dev -d libffi-dev -d libgmp-dev -d make -d xz-utils -d zlib1g-dev"
["-n", stackProgName
,"-C", debStagingDir dv
,"-v", debPackageVersionStr dv
,"-p", out
,"-m", maintainer gStackPackageDescription
,"--description", synopsis gStackPackageDescription
,"--license", display (license gStackPackageDescription)
,"--url", homepage gStackPackageDescription]
(map (dropDirectoryPrefix (debStagingDir dv)) inputFiles)
debStagedExeFile anyVersion0 %> \out -> do
copyFileChanged (releaseDir </> binaryExeFileName) out
debStagedBashCompletionFile anyVersion0 %> \out -> do
let dv = distroVersionFromPath out debVersions
writeBashCompletion (debStagedExeFile dv) (debStagingDir dv) out
debStagedDocDir anyVersion0 ++ "//*" %> \out -> do
let dv@DistroVersion{..} = distroVersionFromPath out debVersions
origFile = dropDirectoryPrefix (debStagedDocDir dv) out
copyFileChanged origFile out
rpmDistroRules rpmDistro0 rpmVersions = do
let anyVersion0 = anyDistroVersion rpmDistro0
distroVersionDir anyVersion0 </> rpmPackageFileName anyVersion0 <.> uploadExt %> \out -> do
let DistroVersion{..} = distroVersionFromPath out rpmVersions
pkgFile = dropExtension out
need [pkgFile]
let rpmmacrosFile = gHomeDir </> ".rpmmacros"
rpmmacrosExists <- liftIO $ System.Directory.doesFileExist rpmmacrosFile
when rpmmacrosExists $
error ("'" ++ rpmmacrosFile ++ "' already exists. Move it out of the way first.")
actionFinally
(do writeFileLines rpmmacrosFile
[ "%_signature gpg"
, "%_gpg_name " ++ gGpgKey ]
() <- cmd "rpm-s3 --verbose --sign --bucket=download.fpcomplete.com"
[ "--repopath=" ++ dvDistro ++ "/" ++ dvVersion
, pkgFile ]
return ())
(liftIO $ removeFile rpmmacrosFile)
copyFileChanged pkgFile out
distroVersionDir anyVersion0 </> rpmPackageFileName anyVersion0 %> \out -> do
docFiles <- getDocFiles
let dv@DistroVersion{..} = distroVersionFromPath out rpmVersions
inputFiles = concat
[[rpmStagedExeFile dv
,rpmStagedBashCompletionFile dv]
,map (rpmStagedDocDir dv </>) docFiles]
need inputFiles
cmd "fpm -s dir -t rpm"
"-d perl -d make -d automake -d gcc -d gmp-devel -d libffi -d zlib -d xz -d tar"
["-n", stackProgName
,"-C", rpmStagingDir dv
,"-v", rpmPackageVersionStr dv
,"--iteration", rpmPackageIterationStr dv
,"-p", out
,"-m", maintainer gStackPackageDescription
,"--description", synopsis gStackPackageDescription
,"--license", display (license gStackPackageDescription)
,"--url", homepage gStackPackageDescription]
(map (dropDirectoryPrefix (rpmStagingDir dv)) inputFiles)
rpmStagedExeFile anyVersion0 %> \out -> do
copyFileChanged (releaseDir </> binaryExeFileName) out
rpmStagedBashCompletionFile anyVersion0 %> \out -> do
let dv = distroVersionFromPath out rpmVersions
writeBashCompletion (rpmStagedExeFile dv) (rpmStagingDir dv) out
rpmStagedDocDir anyVersion0 ++ "//*" %> \out -> do
let dv@DistroVersion{..} = distroVersionFromPath out rpmVersions
origFile = dropDirectoryPrefix (rpmStagedDocDir dv) out
copyFileChanged origFile out
writeBashCompletion stagedStackExeFile stageDir out = do
need [stagedStackExeFile]
(Stdout bashCompletionScript) <- cmd [stagedStackExeFile] "--bash-completion-script" [dropDirectoryPrefix stageDir stagedStackExeFile]
writeFileChanged out bashCompletionScript
getBinaryPkgStageFiles = do
docFiles <- getDocFiles
let stageFiles = concat
[[releaseStageDir </> binaryPkgStageDirName </> stackExeFileName]
,map ((releaseStageDir </> binaryPkgStageDirName) </>) docFiles]
need stageFiles
return stageFiles
getDocFiles = getDirectoryFiles "." ["LICENSE", "*.md", "doc//*"]
distroVersionFromPath path versions =
let path' = dropDirectoryPrefix releaseDir path
version = takeDirectory1 (dropDirectory1 path')
in DistroVersion (takeDirectory1 path') version (lookupVersionCodeName version versions)
distroPhonies distro0 versions0 makePackageFileName =
forM_ versions0 $ \(version0,_) -> do
let dv@DistroVersion{..} = DistroVersion distro0 version0 (lookupVersionCodeName version0 versions0)
phony (distroUploadPhony dv) $ need [distroVersionDir dv </> makePackageFileName dv <.> uploadExt]
phony (distroBuildPhony dv) $ need [distroVersionDir dv </> makePackageFileName dv]
lookupVersionCodeName version versions =
fromMaybe (error $ "lookupVersionCodeName: could not find " ++ show version ++ " in " ++ show versions) $
lookup version versions
releasePhony = "release"
checkPhony = "check"
uploadPhony = "upload"
cleanPhony = "clean"
buildPhony = "build"
distroUploadPhony DistroVersion{..} = "upload-" ++ dvDistro ++ "-" ++ dvVersion
distroBuildPhony DistroVersion{..} = "build-" ++ dvDistro ++ "-" ++ dvVersion
archUploadPhony = "upload-" ++ archDistro
archBuildPhony = "build-" ++ archDistro
releaseCheckDir = releaseDir </> "check"
releaseStageDir = releaseDir </> "stage"
installBinDir = gLocalInstallRoot </> "bin"
distroVersionDir DistroVersion{..} = releaseDir </> dvDistro </> dvVersion
binaryPkgFileNames = [binaryPkgFileName, binaryPkgSignatureFileName]
binaryPkgSignatureFileName = binaryPkgFileName <.> ascExt
binaryPkgFileName =
case platformOS of
Windows -> binaryPkgZipFileName
_ -> binaryPkgTarGzFileName
binaryPkgZipFileName = binaryName global <.> zipExt
binaryPkgTarGzFileName = binaryName global <.> tarGzExt
binaryPkgStageDirName = binaryName global
binaryExeFileName = binaryName global <.> exe
stackExeFileName = stackProgName <.> exe
debStagedDocDir dv = debStagingDir dv </> "usr/share/doc" </> stackProgName
debStagedBashCompletionFile dv = debStagingDir dv </> "etc/bash_completion.d/stack"
debStagedExeFile dv = debStagingDir dv </> "usr/bin/stack"
debStagingDir dv = distroVersionDir dv </> debPackageName dv
debPackageFileName dv = debPackageName dv <.> debExt
debPackageName dv = stackProgName ++ "_" ++ debPackageVersionStr dv ++ "_amd64"
debPackageVersionStr DistroVersion{..} = stackVersionStr global ++ "-0~" ++ dvCodeName
rpmStagedDocDir dv = rpmStagingDir dv </> "usr/share/doc" </> (stackProgName ++ "-" ++ rpmPackageVersionStr dv)
rpmStagedBashCompletionFile dv = rpmStagingDir dv </> "etc/bash_completion.d/stack"
rpmStagedExeFile dv = rpmStagingDir dv </> "usr/bin/stack"
rpmStagingDir dv = distroVersionDir dv </> rpmPackageName dv
rpmPackageFileName dv = rpmPackageName dv <.> rpmExt
rpmPackageName dv = stackProgName ++ "-" ++ rpmPackageVersionStr dv ++ "-" ++ rpmPackageIterationStr dv ++ ".x86_64"
rpmPackageIterationStr DistroVersion{..} = "0." ++ dvCodeName
rpmPackageVersionStr _ = stackVersionStr global
archStagedDocDir = archStagingDir </> "usr/share/doc" </> stackProgName
archStagedBashCompletionFile = archStagingDir </> "usr/share/bash-completion/completions/stack"
archStagedExeFile = archStagingDir </> "usr/bin/stack"
archStagingDir = archDir </> archPackageName
archPackageFileName = archPackageName <.> tarGzExt
archPackageName = stackProgName ++ "_" ++ stackVersionStr global ++ "-" ++ "x86_64"
archDir = releaseDir </> archDistro
ubuntuVersions =
[ ("12.04", "precise")
, ("14.04", "trusty")
, ("14.10", "utopic")
, ("15.04", "vivid") ]
debianVersions =
[ ("7", "wheezy")
, ("8", "jessie") ]
centosVersions =
[ ("7", "el7")
, ("6", "el6") ]
fedoraVersions =
[ ("21", "fc21")
, ("22", "fc22") ]
ubuntuDistro = "ubuntu"
debianDistro = "debian"
centosDistro = "centos"
fedoraDistro = "fedora"
archDistro = "arch"
anyDistroVersion distro = DistroVersion distro "*" "*"
zipExt = ".zip"
tarGzExt = tarExt <.> gzExt
gzExt = ".gz"
tarExt = ".tar"
ascExt = ".asc"
uploadExt = ".upload"
debExt = ".deb"
rpmExt = ".rpm"
-- | Upload file to Github release.
uploadToGithubRelease :: Global -> FilePath -> Maybe String -> Action ()
uploadToGithubRelease global@Global{..} file mUploadLabel = do
need [file]
putNormal $ "Uploading to Github: " ++ file
GithubRelease{..} <- getGithubRelease
resp <- liftIO $ callGithubApi global
[(CI.mk $ S8.pack "Content-Type", defaultMimeLookup (T.pack file))]
(Just file)
(replace
"{?name,label}"
("?name=" ++ urlEncodeStr (takeFileName file) ++
(case mUploadLabel of
Nothing -> ""
Just uploadLabel -> "&label=" ++ urlEncodeStr uploadLabel))
relUploadUrl)
case eitherDecode resp of
Left e -> error ("Could not parse Github asset upload response (" ++ e ++ "):\n" ++ L8.unpack resp ++ "\n")
Right (GithubReleaseAsset{..}) ->
when (assetState /= "uploaded") $
error ("Invalid asset state after Github asset upload: " ++ assetState)
where
urlEncodeStr = S8.unpack . urlEncode True . S8.pack
getGithubRelease = do
releases <- getGithubReleases
let tag = fromMaybe ("v" ++ stackVersionStr global) gGithubReleaseTag
return $ fromMaybe
(error ("Could not find Github release with tag '" ++ tag ++ "'.\n" ++
"Use --" ++ githubReleaseTagOptName ++ " option to specify a different tag."))
(find (\r -> relTagName r == tag) releases)
getGithubReleases :: Action [GithubRelease]
getGithubReleases = do
resp <- liftIO $ callGithubApi global
[] Nothing "https://api.github.com/repos/commercialhaskell/stack/releases"
case eitherDecode resp of
Left e -> error ("Could not parse Github releases (" ++ e ++ "):\n" ++ L8.unpack resp ++ "\n")
Right r -> return r
-- | Make a request to the Github API and return the response.
callGithubApi :: Global -> RequestHeaders -> Maybe FilePath -> String -> IO L8.ByteString
callGithubApi Global{..} headers mpostFile url = do
req0 <- parseUrl url
let authToken =
fromMaybe
(error $
"Github auth token required.\n" ++
"Use " ++ githubAuthTokenEnvVar ++ " environment variable\n" ++
"or --" ++ githubAuthTokenOptName ++ " option to specify.")
gGithubAuthToken
req1 =
req0
{ checkStatus = \_ _ _ -> Nothing
, requestHeaders =
[ (CI.mk $ S8.pack "Authorization", S8.pack $ "token " ++ authToken)
, (CI.mk $ S8.pack "User-Agent", S8.pack "commercialhaskell/stack") ] ++
headers }
req <- case mpostFile of
Nothing -> return req1
Just postFile -> do
lbs <- L8.readFile postFile
return $ req1
{ method = S8.pack "POST"
, requestBody = RequestBodyLBS lbs }
manager <- newManager tlsManagerSettings
runResourceT $ do
res <- http req manager
responseBody res $$+- CC.sinkLazy
-- | Create a .tar.gz files from files. The paths should be absolute, and will
-- be made relative to the base directory in the tarball.
writeTarGz :: FilePath -> FilePath -> [FilePath] -> Action ()
writeTarGz out baseDir inputFiles = liftIO $ do
content <- Tar.pack baseDir $ map (dropDirectoryPrefix baseDir) inputFiles
L8.writeFile out $ GZip.compress $ Tar.write content
-- | Drops a directory prefix from a path. The prefix automatically has a path
-- separator character appended. Fails if the path does not begin with the prefix.
dropDirectoryPrefix :: FilePath -> FilePath -> FilePath
dropDirectoryPrefix prefix path =
case stripPrefix (toStandard prefix ++ "/") (toStandard path) of
Nothing -> error ("dropDirectoryPrefix: cannot drop " ++ show prefix ++ " from " ++ show path)
Just stripped -> stripped
-- | Build a Docker image and write its ID to a file if changed.
buildDockerImage :: FilePath -> String -> FilePath -> Action String
buildDockerImage buildDir imageTag out = do
alwaysRerun
() <- cmd "docker build" ["--tag=" ++ imageTag, buildDir]
(Stdout imageIdOut) <- cmd "docker inspect --format={{.Id}}" [imageTag]
writeFileChanged out imageIdOut
return (trim imageIdOut)
-- | Name of the release binary (e.g. @stack-x.y.x-arch-os[-variant]@)
binaryName :: Global -> String
binaryName global@Global{..} =
concat
[ stackProgName
, "-"
, stackVersionStr global
, "-"
, platformName global
, if null gBinarySuffix then "" else "-" ++ gBinarySuffix ]
-- | String representation of stack package version.
stackVersionStr :: Global -> String
stackVersionStr =
display . pkgVersion . package . gStackPackageDescription
-- | Name of current platform.
platformName :: Global -> String
platformName Global{..} =
display (Platform gArch platformOS)
-- | Current operating system.
platformOS :: OS
platformOS =
let Platform _ os = buildPlatform
in os
-- | Directory in which to store build and intermediate files.
releaseDir :: FilePath
releaseDir = "_release"
-- | @GITHUB_AUTH_TOKEN@ environment variale name.
githubAuthTokenEnvVar :: String
githubAuthTokenEnvVar = "GITHUB_AUTH_TOKEN"
-- | @--github-auth-token@ command-line option name.
githubAuthTokenOptName :: String
githubAuthTokenOptName = "github-auth-token"
-- | @--github-release-tag@ command-line option name.
githubReleaseTagOptName :: String
githubReleaseTagOptName = "github-release-tag"
-- | @--gpg-key@ command-line option name.
gpgKeyOptName :: String
gpgKeyOptName = "gpg-key"
-- | @--allow-dirty@ command-line option name.
allowDirtyOptName :: String
allowDirtyOptName = "allow-dirty"
-- | @--arch@ command-line option name.
archOptName :: String
archOptName = "arch"
-- | @--binary-variant@ command-line option name.
binaryVariantOptName :: String
binaryVariantOptName = "binary-variant"
-- | @--upload-label@ command-line option name.
uploadLabelOptName :: String
uploadLabelOptName = "upload-label"
-- | Arguments to pass to all 'stack' invocations.
stackArgs :: Global -> [String]
stackArgs Global{..} = ["--arch=" ++ display gArch]
-- | Name of the 'stack' program.
stackProgName :: FilePath
stackProgName = "stack"
-- | Linux distribution/version combination.
data DistroVersion = DistroVersion
{ dvDistro :: !String
, dvVersion :: !String
, dvCodeName :: !String }
-- | A Github release, as returned by the Github API.
data GithubRelease = GithubRelease
{ relUploadUrl :: !String
, relTagName :: !String }
deriving (Show)
instance FromJSON GithubRelease where
parseJSON = withObject "GithubRelease" $ \o ->
GithubRelease
<$> o .: T.pack "upload_url"
<*> o .: T.pack "tag_name"
-- | A Github release asset, as returned by the Github API.
data GithubReleaseAsset = GithubReleaseAsset
{ assetState :: !String }
deriving (Show)
instance FromJSON GithubReleaseAsset where
parseJSON = withObject "GithubReleaseAsset" $ \o ->
GithubReleaseAsset
<$> o .: T.pack "state"
-- | Global values and options.
data Global = Global
{ gStackPackageDescription :: !PackageDescription
, gLocalInstallRoot :: !FilePath
, gGpgKey :: !String
, gAllowDirty :: !Bool
, gGithubAuthToken :: !(Maybe String)
, gGithubReleaseTag :: !(Maybe String)
, gGitRevCount :: !Int
, gGitSha :: !String
, gProjectRoot :: !FilePath
, gHomeDir :: !FilePath
, gArch :: !Arch
, gBinarySuffix :: !String
, gUploadLabel ::(Maybe String)}
deriving (Show)
| robstewart57/stack | etc/scripts/release.hs | bsd-3-clause | 28,996 | 0 | 25 | 7,815 | 6,422 | 3,254 | 3,168 | 602 | 6 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE DeriveFunctor #-}
-----------------------------------------------------------------------------
-- |
-- Module : Text.ParserCombinators.ReadP
-- Copyright : (c) The University of Glasgow 2002
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : non-portable (local universal quantification)
--
-- This is a library of parser combinators, originally written by Koen Claessen.
-- It parses all alternatives in parallel, so it never keeps hold of
-- the beginning of the input string, a common source of space leaks with
-- other parsers. The '(+++)' choice combinator is genuinely commutative;
-- it makes no difference which branch is \"shorter\".
-----------------------------------------------------------------------------
module Text.ParserCombinators.ReadP
(
-- * The 'ReadP' type
ReadP,
-- * Primitive operations
get,
look,
(+++),
(<++),
gather,
-- * Other operations
pfail,
eof,
satisfy,
char,
string,
munch,
munch1,
skipSpaces,
choice,
count,
between,
option,
optional,
many,
many1,
skipMany,
skipMany1,
sepBy,
sepBy1,
endBy,
endBy1,
chainr,
chainl,
chainl1,
chainr1,
manyTill,
-- * Running a parser
ReadS,
readP_to_S,
readS_to_P,
-- * Properties
-- $properties
)
where
import {-# SOURCE #-} GHC.Unicode ( isSpace )
import GHC.List ( replicate, null )
import GHC.Base hiding ( many )
infixr 5 +++, <++
------------------------------------------------------------------------
-- ReadS
-- | A parser for a type @a@, represented as a function that takes a
-- 'String' and returns a list of possible parses as @(a,'String')@ pairs.
--
-- Note that this kind of backtracking parser is very inefficient;
-- reading a large structure may be quite slow (cf 'ReadP').
type ReadS a = String -> [(a,String)]
-- ---------------------------------------------------------------------------
-- The P type
-- is representation type -- should be kept abstract
data P a
= Get (Char -> P a)
| Look (String -> P a)
| Fail
| Result a (P a)
| Final [(a,String)] -- invariant: list is non-empty!
deriving Functor
-- Monad, MonadPlus
instance Applicative P where
pure = return
(<*>) = ap
instance MonadPlus P where
mzero = empty
mplus = (<|>)
instance Monad P where
return x = Result x Fail
(Get f) >>= k = Get (\c -> f c >>= k)
(Look f) >>= k = Look (\s -> f s >>= k)
Fail >>= _ = Fail
(Result x p) >>= k = k x <|> (p >>= k)
(Final r) >>= k = final [ys' | (x,s) <- r, ys' <- run (k x) s]
fail _ = Fail
instance Alternative P where
empty = Fail
-- most common case: two gets are combined
Get f1 <|> Get f2 = Get (\c -> f1 c <|> f2 c)
-- results are delivered as soon as possible
Result x p <|> q = Result x (p <|> q)
p <|> Result x q = Result x (p <|> q)
-- fail disappears
Fail <|> p = p
p <|> Fail = p
-- two finals are combined
-- final + look becomes one look and one final (=optimization)
-- final + sthg else becomes one look and one final
Final r <|> Final t = Final (r ++ t)
Final r <|> Look f = Look (\s -> Final (r ++ run (f s) s))
Final r <|> p = Look (\s -> Final (r ++ run p s))
Look f <|> Final r = Look (\s -> Final (run (f s) s ++ r))
p <|> Final r = Look (\s -> Final (run p s ++ r))
-- two looks are combined (=optimization)
-- look + sthg else floats upwards
Look f <|> Look g = Look (\s -> f s <|> g s)
Look f <|> p = Look (\s -> f s <|> p)
p <|> Look f = Look (\s -> p <|> f s)
-- ---------------------------------------------------------------------------
-- The ReadP type
newtype ReadP a = R (forall b . (a -> P b) -> P b)
-- Functor, Monad, MonadPlus
instance Functor ReadP where
fmap h (R f) = R (\k -> f (k . h))
instance Applicative ReadP where
pure = return
(<*>) = ap
instance Monad ReadP where
return x = R (\k -> k x)
fail _ = R (\_ -> Fail)
R m >>= f = R (\k -> m (\a -> let R m' = f a in m' k))
instance Alternative ReadP where
empty = mzero
(<|>) = mplus
instance MonadPlus ReadP where
mzero = pfail
mplus = (+++)
-- ---------------------------------------------------------------------------
-- Operations over P
final :: [(a,String)] -> P a
-- Maintains invariant for Final constructor
final [] = Fail
final r = Final r
run :: P a -> ReadS a
run (Get f) (c:s) = run (f c) s
run (Look f) s = run (f s) s
run (Result x p) s = (x,s) : run p s
run (Final r) _ = r
run _ _ = []
-- ---------------------------------------------------------------------------
-- Operations over ReadP
get :: ReadP Char
-- ^ Consumes and returns the next character.
-- Fails if there is no input left.
get = R Get
look :: ReadP String
-- ^ Look-ahead: returns the part of the input that is left, without
-- consuming it.
look = R Look
pfail :: ReadP a
-- ^ Always fails.
pfail = R (\_ -> Fail)
(+++) :: ReadP a -> ReadP a -> ReadP a
-- ^ Symmetric choice.
R f1 +++ R f2 = R (\k -> f1 k <|> f2 k)
(<++) :: ReadP a -> ReadP a -> ReadP a
-- ^ Local, exclusive, left-biased choice: If left parser
-- locally produces any result at all, then right parser is
-- not used.
R f0 <++ q =
do s <- look
probe (f0 return) s 0#
where
probe (Get f) (c:s) n = probe (f c) s (n+#1#)
probe (Look f) s n = probe (f s) s n
probe p@(Result _ _) _ n = discard n >> R (p >>=)
probe (Final r) _ _ = R (Final r >>=)
probe _ _ _ = q
discard 0# = return ()
discard n = get >> discard (n-#1#)
gather :: ReadP a -> ReadP (String, a)
-- ^ Transforms a parser into one that does the same, but
-- in addition returns the exact characters read.
-- IMPORTANT NOTE: 'gather' gives a runtime error if its first argument
-- is built using any occurrences of readS_to_P.
gather (R m)
= R (\k -> gath id (m (\a -> return (\s -> k (s,a)))))
where
gath :: (String -> String) -> P (String -> P b) -> P b
gath l (Get f) = Get (\c -> gath (l.(c:)) (f c))
gath _ Fail = Fail
gath l (Look f) = Look (\s -> gath l (f s))
gath l (Result k p) = k (l []) <|> gath l p
gath _ (Final _) = error "do not use readS_to_P in gather!"
-- ---------------------------------------------------------------------------
-- Derived operations
satisfy :: (Char -> Bool) -> ReadP Char
-- ^ Consumes and returns the next character, if it satisfies the
-- specified predicate.
satisfy p = do c <- get; if p c then return c else pfail
char :: Char -> ReadP Char
-- ^ Parses and returns the specified character.
char c = satisfy (c ==)
eof :: ReadP ()
-- ^ Succeeds iff we are at the end of input
eof = do { s <- look
; if null s then return ()
else pfail }
string :: String -> ReadP String
-- ^ Parses and returns the specified string.
string this = do s <- look; scan this s
where
scan [] _ = do return this
scan (x:xs) (y:ys) | x == y = do _ <- get; scan xs ys
scan _ _ = do pfail
munch :: (Char -> Bool) -> ReadP String
-- ^ Parses the first zero or more characters satisfying the predicate.
-- Always succeds, exactly once having consumed all the characters
-- Hence NOT the same as (many (satisfy p))
munch p =
do s <- look
scan s
where
scan (c:cs) | p c = do _ <- get; s <- scan cs; return (c:s)
scan _ = do return ""
munch1 :: (Char -> Bool) -> ReadP String
-- ^ Parses the first one or more characters satisfying the predicate.
-- Fails if none, else succeeds exactly once having consumed all the characters
-- Hence NOT the same as (many1 (satisfy p))
munch1 p =
do c <- get
if p c then do s <- munch p; return (c:s)
else pfail
choice :: [ReadP a] -> ReadP a
-- ^ Combines all parsers in the specified list.
choice [] = pfail
choice [p] = p
choice (p:ps) = p +++ choice ps
skipSpaces :: ReadP ()
-- ^ Skips all whitespace.
skipSpaces =
do s <- look
skip s
where
skip (c:s) | isSpace c = do _ <- get; skip s
skip _ = do return ()
count :: Int -> ReadP a -> ReadP [a]
-- ^ @count n p@ parses @n@ occurrences of @p@ in sequence. A list of
-- results is returned.
count n p = sequence (replicate n p)
between :: ReadP open -> ReadP close -> ReadP a -> ReadP a
-- ^ @between open close p@ parses @open@, followed by @p@ and finally
-- @close@. Only the value of @p@ is returned.
between open close p = do _ <- open
x <- p
_ <- close
return x
option :: a -> ReadP a -> ReadP a
-- ^ @option x p@ will either parse @p@ or return @x@ without consuming
-- any input.
option x p = p +++ return x
optional :: ReadP a -> ReadP ()
-- ^ @optional p@ optionally parses @p@ and always returns @()@.
optional p = (p >> return ()) +++ return ()
many :: ReadP a -> ReadP [a]
-- ^ Parses zero or more occurrences of the given parser.
many p = return [] +++ many1 p
many1 :: ReadP a -> ReadP [a]
-- ^ Parses one or more occurrences of the given parser.
many1 p = liftM2 (:) p (many p)
skipMany :: ReadP a -> ReadP ()
-- ^ Like 'many', but discards the result.
skipMany p = many p >> return ()
skipMany1 :: ReadP a -> ReadP ()
-- ^ Like 'many1', but discards the result.
skipMany1 p = p >> skipMany p
sepBy :: ReadP a -> ReadP sep -> ReadP [a]
-- ^ @sepBy p sep@ parses zero or more occurrences of @p@, separated by @sep@.
-- Returns a list of values returned by @p@.
sepBy p sep = sepBy1 p sep +++ return []
sepBy1 :: ReadP a -> ReadP sep -> ReadP [a]
-- ^ @sepBy1 p sep@ parses one or more occurrences of @p@, separated by @sep@.
-- Returns a list of values returned by @p@.
sepBy1 p sep = liftM2 (:) p (many (sep >> p))
endBy :: ReadP a -> ReadP sep -> ReadP [a]
-- ^ @endBy p sep@ parses zero or more occurrences of @p@, separated and ended
-- by @sep@.
endBy p sep = many (do x <- p ; _ <- sep ; return x)
endBy1 :: ReadP a -> ReadP sep -> ReadP [a]
-- ^ @endBy p sep@ parses one or more occurrences of @p@, separated and ended
-- by @sep@.
endBy1 p sep = many1 (do x <- p ; _ <- sep ; return x)
chainr :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a
-- ^ @chainr p op x@ parses zero or more occurrences of @p@, separated by @op@.
-- Returns a value produced by a /right/ associative application of all
-- functions returned by @op@. If there are no occurrences of @p@, @x@ is
-- returned.
chainr p op x = chainr1 p op +++ return x
chainl :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a
-- ^ @chainl p op x@ parses zero or more occurrences of @p@, separated by @op@.
-- Returns a value produced by a /left/ associative application of all
-- functions returned by @op@. If there are no occurrences of @p@, @x@ is
-- returned.
chainl p op x = chainl1 p op +++ return x
chainr1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a
-- ^ Like 'chainr', but parses one or more occurrences of @p@.
chainr1 p op = scan
where scan = p >>= rest
rest x = do f <- op
y <- scan
return (f x y)
+++ return x
chainl1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a
-- ^ Like 'chainl', but parses one or more occurrences of @p@.
chainl1 p op = p >>= rest
where rest x = do f <- op
y <- p
rest (f x y)
+++ return x
manyTill :: ReadP a -> ReadP end -> ReadP [a]
-- ^ @manyTill p end@ parses zero or more occurrences of @p@, until @end@
-- succeeds. Returns a list of values returned by @p@.
manyTill p end = scan
where scan = (end >> return []) <++ (liftM2 (:) p scan)
-- ---------------------------------------------------------------------------
-- Converting between ReadP and Read
readP_to_S :: ReadP a -> ReadS a
-- ^ Converts a parser into a Haskell ReadS-style function.
-- This is the main way in which you can \"run\" a 'ReadP' parser:
-- the expanded type is
-- @ readP_to_S :: ReadP a -> String -> [(a,String)] @
readP_to_S (R f) = run (f return)
readS_to_P :: ReadS a -> ReadP a
-- ^ Converts a Haskell ReadS-style function into a parser.
-- Warning: This introduces local backtracking in the resulting
-- parser, and therefore a possible inefficiency.
readS_to_P r =
R (\k -> Look (\s -> final [bs'' | (a,s') <- r s, bs'' <- run (k a) s']))
-- ---------------------------------------------------------------------------
-- QuickCheck properties that hold for the combinators
{- $properties
The following are QuickCheck specifications of what the combinators do.
These can be seen as formal specifications of the behavior of the
combinators.
We use bags to give semantics to the combinators.
> type Bag a = [a]
Equality on bags does not care about the order of elements.
> (=~) :: Ord a => Bag a -> Bag a -> Bool
> xs =~ ys = sort xs == sort ys
A special equality operator to avoid unresolved overloading
when testing the properties.
> (=~.) :: Bag (Int,String) -> Bag (Int,String) -> Bool
> (=~.) = (=~)
Here follow the properties:
> prop_Get_Nil =
> readP_to_S get [] =~ []
>
> prop_Get_Cons c s =
> readP_to_S get (c:s) =~ [(c,s)]
>
> prop_Look s =
> readP_to_S look s =~ [(s,s)]
>
> prop_Fail s =
> readP_to_S pfail s =~. []
>
> prop_Return x s =
> readP_to_S (return x) s =~. [(x,s)]
>
> prop_Bind p k s =
> readP_to_S (p >>= k) s =~.
> [ ys''
> | (x,s') <- readP_to_S p s
> , ys'' <- readP_to_S (k (x::Int)) s'
> ]
>
> prop_Plus p q s =
> readP_to_S (p +++ q) s =~.
> (readP_to_S p s ++ readP_to_S q s)
>
> prop_LeftPlus p q s =
> readP_to_S (p <++ q) s =~.
> (readP_to_S p s +<+ readP_to_S q s)
> where
> [] +<+ ys = ys
> xs +<+ _ = xs
>
> prop_Gather s =
> forAll readPWithoutReadS $ \p ->
> readP_to_S (gather p) s =~
> [ ((pre,x::Int),s')
> | (x,s') <- readP_to_S p s
> , let pre = take (length s - length s') s
> ]
>
> prop_String_Yes this s =
> readP_to_S (string this) (this ++ s) =~
> [(this,s)]
>
> prop_String_Maybe this s =
> readP_to_S (string this) s =~
> [(this, drop (length this) s) | this `isPrefixOf` s]
>
> prop_Munch p s =
> readP_to_S (munch p) s =~
> [(takeWhile p s, dropWhile p s)]
>
> prop_Munch1 p s =
> readP_to_S (munch1 p) s =~
> [(res,s') | let (res,s') = (takeWhile p s, dropWhile p s), not (null res)]
>
> prop_Choice ps s =
> readP_to_S (choice ps) s =~.
> readP_to_S (foldr (+++) pfail ps) s
>
> prop_ReadS r s =
> readP_to_S (readS_to_P r) s =~. r s
-}
| spacekitteh/smcghc | libraries/base/Text/ParserCombinators/ReadP.hs | bsd-3-clause | 14,899 | 1 | 17 | 3,939 | 3,771 | 1,944 | 1,827 | 222 | 6 |
-- |
-- Type classes and built-in implementation for primitive Haskell types
--
module Ntha.Z3.Class (
-- ** Types whose values are encodable to Z3 internal AST
Z3Encoded(..),
-- ** Types representable as Z3 Sort
-- XXX: Unsound now
-- XXX: Too flexible, can be used to encode Type ADT
Z3Sorted(..),
-- ** Type proxy helper, used with Z3Sorted
Z3Sort(..),
-- ** Types with reserved value for Z3 encoding use
-- XXX: Magic value for built-in types
Z3Reserved(..),
-- ** Monad which can be instantiated into a concrete context
SMT(..)
) where
import Ntha.Z3.Logic
import Z3.Monad
import Control.Monad.Except
import qualified Data.Map as M
import qualified Data.Set as S
data Z3Sort a = Z3Sort
class Z3Encoded a where
encode :: SMT m e => a -> m e AST
-- | XXX: Unsound
class Z3Sorted a where
-- | Map a value to Sort, the value should be a type-level thing
sort :: SMT m e => a -> m e Sort
sort _ = sortPhantom (Z3Sort :: Z3Sort a)
-- | Map a Haskell type to Sort
sortPhantom :: SMT m e => Z3Sort a -> m e Sort
sortPhantom _ = smtError "sort error"
class Z3Encoded a => Z3Reserved a where
def :: a
class (MonadError String (m e), MonadZ3 (m e)) => SMT m e where
-- | Globally unique id
genFreshId :: m e Int
-- | Given data type declarations, extra field, and the SMT monad, return the fallible result in IO monad
runSMT :: Z3Sorted ty => [(String, [(String, [(String, ty)])])] -> e -> m e a -> IO (Either String a)
-- | Binding a variable String name to two things: an de Brujin idx as Z3 AST generated by mkBound and binder's Sort
bindQualified :: String -> AST -> Sort -> m e ()
-- | Get the above AST
-- FIXME: The context management need extra -- we need to make sure that old binding wouldn't be destoryed
-- XXX: We shouldn't expose a Map here. A fallible query interface is better
getQualifierCtx :: m e (M.Map String (AST, Sort))
-- | Get the preprocessed datatype context, a map from ADT's type name to its Z3 Sort
-- XXX: We shouldn't expose a Map here. A fallible query interface is better
getDataTypeCtx :: m e (M.Map String Sort)
-- | Get extra
getExtra :: m e e
-- | Set extra
modifyExtra :: (e -> e) -> m e ()
-- | User don't have to import throwError
smtError :: String -> m e a
smtError = throwError
instance Z3Reserved Int where
def = -1 -- XXX: Magic number
instance Z3Sorted Int where
sortPhantom _ = mkIntSort
instance Z3Encoded Int where
encode i = mkIntSort >>= mkInt i
instance Z3Reserved Double where
def = -1.0 -- XXX: Magic number
instance Z3Sorted Double where
sortPhantom _ = mkRealSort
instance Z3Encoded Double where
encode = mkRealNum
instance Z3Reserved Bool where
def = False -- XXX: Magic number
instance Z3Sorted Bool where
sortPhantom _ = mkBoolSort
instance Z3Encoded Bool where
encode = mkBool
-- The basic idea:
-- For each (k, v), assert in Z3 that if we select k from array we will get
-- the same value v
-- HACK: to set a default value for rest fields (or else we always get the last asserted value
-- as default, which is certainly not complying to finite map's definition), thus the
-- user should guarantee that he/she will never never think this value as a vaid one,
-- if not, he/she might get "a valid value mapped to a invalid key" semantics
instance (Z3Sorted k, Z3Encoded k, Z3Sorted v, Z3Reserved v) => Z3Encoded (M.Map k v) where
encode m = do
fid <- genFreshId
arrSort <- sort m
arr <- mkFreshConst ("map" ++ "_" ++ show fid) arrSort
mapM_ (\(k, v) -> do
kast <- encode k
vast <- encode v
sel <- mkSelect arr kast
mkEq sel vast >>= assert) (M.toList m)
arrValueDef <- mkArrayDefault arr
vdef <- encode (def :: v)
mkEq arrValueDef vdef >>= assert
return arr
instance (Z3Sorted k, Z3Sorted v) => Z3Sorted (M.Map k v) where
sortPhantom _ = do
sk <- sortPhantom (Z3Sort :: Z3Sort k)
sv <- sortPhantom (Z3Sort :: Z3Sort v)
mkArraySort sk sv
-- Basic idea:
-- Set v =def= Map v {0, 1}
-- Thank god, this is much more sound
instance (Z3Sorted v, Z3Encoded v) => Z3Encoded (S.Set v) where
encode s = do
setSort <- sort s
fid <- genFreshId
arr <- mkFreshConst ("set" ++ "_" ++ show fid) setSort
mapM_ (\e -> do
ast <- encode e
sel <- mkSelect arr ast
one <- (mkIntSort >>= mkInt 1)
mkEq sel one >>= assert) (S.toList s)
arrValueDef <- mkArrayDefault arr
zero <- (mkIntSort >>= mkInt 0)
mkEq zero arrValueDef >>= assert
return arr
instance Z3Sorted v => Z3Sorted (S.Set v) where
sortPhantom _ = do
sortElem <- sortPhantom (Z3Sort :: Z3Sort v)
intSort <- mkIntSort
mkArraySort sortElem intSort
instance (Z3Sorted t, Z3Sorted ty, Z3Encoded a) => Z3Encoded (Pred t ty a) where
encode PTrue = mkTrue
encode PFalse = mkFalse
encode (PConj p1 p2) = do
a1 <- encode p1
a2 <- encode p2
mkAnd [a1, a2]
encode (PDisj p1 p2) = do
a1 <- encode p1
a2 <- encode p2
mkOr [a1, a2]
encode (PXor p1 p2) = do
a1 <- encode p1
a2 <- encode p2
mkXor a1 a2
encode (PNeg p) = encode p >>= mkNot
encode (PForAll x ty p) = do
sym <- mkStringSymbol x
xsort <- sort ty
-- "0" is de brujin idx for current binder
-- it is passed to Z3 which returns an intenal (idx :: AST)
-- This (idx :: AST) will be used to replace the variable
-- in the abstraction body when encountered, thus it is stored
-- in context by bindQualified we provide
-- XXX: we should save and restore qualifier context here
idx <- mkBound 0 xsort
local $ do
bindQualified x idx xsort
body <- encode p
-- The first [] is [Pattern], which is not really useful here
mkForall [] [sym] [xsort] body
encode (PExists x ty p) = do
sym <- mkStringSymbol x
xsort <- sort ty
idx <- mkBound 0 xsort
local $ do
bindQualified x idx xsort
a <- encode p
mkExists [] [sym] [xsort] a
-- HACK
encode (PExists2 x y ty p) = do
sym1 <- mkStringSymbol x
sym2 <- mkStringSymbol y
xsort <- sort ty
idx1 <- mkBound 0 xsort
idx2 <- mkBound 1 xsort
local $ do
bindQualified x idx1 xsort
bindQualified y idx2 xsort
a <- encode p
mkExists [] [sym1, sym2] [xsort, xsort] a
encode (PImpli p1 p2) = do
a1 <- encode p1
a2 <- encode p2
mkImplies a1 a2
encode (PIff p1 p2) = do
a1 <- encode p1
a2 <- encode p2
mkIff a1 a2
encode (PAssert a) = encode a
| zjhmale/Ntha | src/Ntha/Z3/Class.hs | bsd-3-clause | 7,015 | 0 | 16 | 2,161 | 1,872 | 926 | 946 | -1 | -1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module System.EtCetera.LxcSpec where
import Control.Monad.Trans (liftIO)
import Data.List (intercalate)
import System.EtCetera.Internal (Optional(..))
import System.EtCetera.Lxc.Internal (Arch(..), emptyConfig, emptyNetwork, LxcConfig,
Network(..), NetworkType(..), parse, serialize,
SerializtionError(..), Switch(..),
LxcConfig(..))
import Test.Hspec (describe, it, shouldBe, Spec)
suite :: Spec
suite = do
describe "System.EtCetera.Lxc parse" $ do
it "parses single option line with new line char at the end" $
parse "lxc.aa_profile=/mnt/rootfs.complex" `shouldBe`
Right (emptyConfig {lxcAaProfile = Present "/mnt/rootfs.complex"})
it "parses single comment without new line" $
parse "# comment" `shouldBe`
Right emptyConfig
it "parses single comment with new line" $
parse "# comment\n" `shouldBe`
Right emptyConfig
it "parses network type correctly" $
parse "lxc.network.type = macvlan" `shouldBe`
(Right $ emptyConfig { lxcNetwork = [emptyNetwork { lxcNetworkType = Present Macvlan } ] })
it "parses multiple network declarations" $
parse (unlines [ "lxc.network.type = macvlan"
, "lxc.network.name = eth0"
, "lxc.network.type = veth"
, "lxc.network.name = eth1"
]) `shouldBe`
(Right $ emptyConfig { lxcNetwork = [ emptyNetwork { lxcNetworkType = Present Macvlan
, lxcNetworkName = Present "eth0"}
, emptyNetwork { lxcNetworkType = Present Veth
, lxcNetworkName = Present "eth1"}] } )
it "parses integer value correctly" $
parse "lxc.start.delay = 8" `shouldBe`
(Right $ emptyConfig { lxcStartDelay = Present 8})
it "parses multiple options" $
parse (unlines [ "lxc.aa_profile=/mnt/rootfs.complex"
, "lxc.include=/var/lib/lxc/lxc-common.conf"
, "lxc.include=/var/lib/lxc/custom"
]) `shouldBe`
Right (emptyConfig { lxcAaProfile = Present "/mnt/rootfs.complex"
, lxcInclude = [ "/var/lib/lxc/lxc-common.conf"
, "/var/lib/lxc/custom"
]})
it "parses mixed multiple options line with new line char at the end" $
parse (unlines [ "lxc.include=/var/lib/lxc/lxc-common.conf"
, "# comment"
, "lxc.aa_profile=/mnt/rootfs.complex"
, "# another comment"
, ""
, "lxc.include=/var/lib/lxc/custom"
]) `shouldBe`
Right (emptyConfig { lxcAaProfile = Present "/mnt/rootfs.complex"
, lxcInclude = [ "/var/lib/lxc/lxc-common.conf"
, "/var/lib/lxc/custom"
]})
it "parses mixed multiple lines without new line at the end" $
parse (intercalate "\n" [ "#comment "
, "lxc.include = /var/lib/lxc/lxc-common.conf"
, "lxc.include = /var/lib/lxc/custom"
, "lxc.rootfs = /mnt/rootfs.complex"
, "# another comment "
, "\t"
]) `shouldBe`
(Right $ emptyConfig { lxcInclude = [ "/var/lib/lxc/lxc-common.conf"
, "/var/lib/lxc/custom"]
, lxcRootfs = Present "/mnt/rootfs.complex"
})
it "parsing regression 2016.02.18.1" $
parse (intercalate "\n" [ "lxc.arch=x86_64\n"
, "lxc.rootfs=/var/lib/lxc/stream6-clone.nadaje.com/rootfs"
, "lxc.utsname=stream6-clone.nadaje.com"
, "lxc.include=/usr/share/lxc/config/debian.common.conf"
, "lxc.network.type=veth"
, "lxc.network.flags=up"
, "lxc.network.ipv4=10.0.0.3"
, "lxc.network.ipv4.gateway=10.0.0.2"
, "lxc.network.link=lxc-br01"
, "lxc.network.name=eth0"
, "\n"
, "\n"
]) `shouldBe`
(Right
emptyConfig
{ lxcArch = Present X86_64
, lxcRootfs = Present "/var/lib/lxc/stream6-clone.nadaje.com/rootfs"
, lxcUtsname = Present "stream6-clone.nadaje.com"
, lxcInclude = ["/usr/share/lxc/config/debian.common.conf"]
, lxcNetwork = [ emptyNetwork
{ lxcNetworkType = Present Veth
, lxcNetworkFlags = Present "up"
, lxcNetworkIpv4 = Present "10.0.0.3"
, lxcNetworkIpv4Gateway = Present "10.0.0.2"
, lxcNetworkLink = Present "lxc-br01"
, lxcNetworkName = Present "eth0"
}
]
})
describe "System.EtCetera.Lxc serialize" $ do
it "serializes multiple options" $
serialize (emptyConfig { lxcInclude = [ "/var/lib/lxc/lxc-common.conf"
, "/var/lib/lxc/custom"]
, lxcAaProfile = Present "/mnt/rootfs.complex"
}) `shouldBe`
(Right . unlines $ [ "lxc.aa_profile=/mnt/rootfs.complex"
, "lxc.include=/var/lib/lxc/lxc-common.conf"
, "lxc.include=/var/lib/lxc/custom"
])
it "serializes multiple correct networks" $
serialize
(emptyConfig
{ lxcNetwork = [ emptyNetwork { lxcNetworkType = Present Macvlan }
, emptyNetwork { lxcNetworkType = Present Veth
, lxcNetworkName = Present "eth0" }]
}) `shouldBe`
Right "lxc.network.type=macvlan\nlxc.network.type=veth\nlxc.network.name=eth0\n"
| paluh/et-cetera | test/System/EtCetera/LxcSpec.hs | bsd-3-clause | 6,700 | 0 | 19 | 2,844 | 941 | 534 | 407 | 114 | 1 |
#! /usr/bin/env stack
-- stack runghc
module Advent.Day8 where
import Advent
import Data.Char (chr)
import Numeric (readHex)
unencode ('"':s) = _unencode s
where
_unencode ('\\':'"':s) = '"':_unencode s
_unencode ('\\':'\\':s) = '\\':_unencode s
_unencode ('\\':'x':a:b:s) = (chr $ (fst . head) parses):_unencode s
where parses = readHex (a:b:[])
_unencode ('"':[]) = ""
_unencode (c:[]) = error "must end in '\"'"
_unencode (c:s) = c:_unencode s
_unencode x = error $ "WTF '" ++ x ++ "'"
unencode s = error $ "must start with '\"', was '" ++ s ++ "'"
encode s = '"':_encode s
where
_encode ('\\':s) = '\\':'\\':_encode s
_encode ('"':s) = '\\':'"':_encode s
_encode [] = '"':[]
_encode (c:s) = c:_encode s
solveA input = sum (map length words) - sum (map (length . unencode) words)
where words = filter ((>1) . length) $ lines input
solveB input = sum (map (length . encode) words) - sum (map length words)
where words = filter ((>1) . length) $ lines input
main = do
solvePuzzle 8 solveA
solvePuzzle 8 solveB
| cpennington/adventofcode | src/Advent/Day8.hs | bsd-3-clause | 1,084 | 0 | 12 | 246 | 520 | 265 | 255 | 26 | 7 |
{-# LANGUAGE TypeSynonymInstances #-}
module CarbonCopy.MailHeaders (
Header(..),
StrHeader,
HeaderMatcher,
extractHeaders,
msg_id_hdr,
from_hdr,
in_reply_to_hdr
) where
import Prelude as P
import Data.Char
import Data.ByteString.Char8 as BStr hiding (concatMap, takeWhile)
import Text.ParserCombinators.ReadP as R
data (Eq keyT) => Header keyT valueT = Header { name :: keyT, value :: valueT } deriving Eq
type StrHeader = Header String String
instance Show StrHeader where
show (Header name value) = show name ++ ":" ++ show value
type HeaderMatcher = ReadP StrHeader
msg_id_hdr = "message-id"
in_reply_to_hdr = "in-reply-to"
from_hdr = "from"
extractHeaders :: ByteString -> HeaderMatcher -> [StrHeader]
extractHeaders src matcher = concatMap parse . takeWhile ( /= BStr.empty) $ lines
where
lines = BStr.lines src
parse l = P.map fst $ readP_to_S matcher line
where line = BStr.unpack ( BStr.map toLower l ) ++ "\n"
| jdevelop/carboncopy | CarbonCopy/MailHeaders.hs | bsd-3-clause | 1,110 | 0 | 13 | 323 | 283 | 161 | 122 | 26 | 1 |
{-# LANGUAGE PatternGuards, TypeSynonymInstances, TypeFamilies, FlexibleInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : Berp.Compile.Compile
-- Copyright : (c) 2010 Bernie Pope
-- License : BSD-style
-- Maintainer : florbitous@gmail.com
-- Stability : experimental
-- Portability : ghc
--
-- The compiler for berp. The compiler translates Python 3 into Haskell.
--
-----------------------------------------------------------------------------
module Berp.Compile.Compile (compiler, Compilable (..)) where
import Prelude hiding (read, init, mapM, putStrLn, sequence)
import Language.Python.Common.PrettyAST ()
import Language.Python.Common.Pretty (prettyText)
import Language.Python.Common.AST as Py
import Data.Traversable
import Data.Foldable (foldrM)
import Language.Haskell.Exts.Syntax as Hask
import Language.Haskell.Exts.Build as Hask
import Control.Applicative
import qualified Data.Set as Set
import Data.Set ((\\))
import Control.Monad hiding (mapM, sequence)
import qualified Berp.Compile.PrimName as Prim
import Berp.Compile.Monad
import Berp.Compile.HsSyntaxUtils as Hask
import Berp.Compile.PySyntaxUtils as Py
import Berp.Compile.Utils
import Berp.Base.Mangle (mangle)
import Berp.Base.Hash (Hash (..))
import Berp.Compile.IdentString (IdentString (..), ToIdentString (..), identString)
import Berp.Compile.Scope as Scope (Scope (..), topBindings, funBindings)
import qualified Berp.Compile.Scope as Scope (isGlobal)
compiler :: Compilable a => a -> IO (CompileResult a)
compiler = runCompileMonad . compile
class Compilable a where
type CompileResult a :: *
compile :: a -> Compile (CompileResult a)
instance Compilable a => Compilable [a] where
type CompileResult [a] = [CompileResult a]
compile = mapM compile
instance Compilable a => Compilable (Maybe a) where
type CompileResult (Maybe a) = Maybe (CompileResult a)
compile = mapM compile
instance Compilable InterpreterStmt where
type CompileResult InterpreterStmt = Hask.Exp
compile (InterpreterStmt suite) = do
stmts <- nestedScope topBindings $ compile $ Block suite
return $ mkLambda stmts
where
mkLambda :: [Hask.Stmt] -> Hask.Exp
mkLambda stmts = lamE bogusSrcLoc [Prim.globalsPat] $ doBlock stmts
instance Compilable ModuleSpan where
type CompileResult ModuleSpan = String -> (Hask.Module, [String])
compile (Py.Module suite) = do
stmts <- nestedScope topBindings $ compile $ Block suite
-- let allStmts = stmts ++ [qualStmt Prim.mkModule]
importedModules <- Set.toList <$> getImports
return $ \modName ->
let init = initDecl $ doBlock stmts in
(Hask.Module bogusSrcLoc
(ModuleName modName) pragmas warnings exports
(imports importedModules) [init],
importedModules)
where
initDecl :: Hask.Exp -> Hask.Decl
-- initDecl = patBind bogusSrcLoc $ pvar $ name initName
initDecl = simpleFun bogusSrcLoc (name initName) (name Prim.globalsName)
pragmas = []
warnings = Nothing
exports = Just [EVar $ UnQual $ name initName]
srcImports names = mkImportStmts $ map mkSrcImport names
stdImports = mkImportStmts [(Prim.preludeModuleName,False,Just []),
(Prim.berpModuleName,False,Nothing)]
imports names = stdImports ++ srcImports (map mkBerpModuleName names)
initName :: String
initName = "init"
mkSrcImport :: String -> (ModuleName, Bool, Maybe [String])
mkSrcImport name = (ModuleName name, True, Just [initName])
mkImportStmts :: [(ModuleName, Bool, Maybe [String])] -> [ImportDecl]
mkImportStmts = map toImportStmt
toImportStmt :: (ModuleName, Bool, Maybe [String]) -> ImportDecl
toImportStmt (moduleName, qualified, items) =
ImportDecl
{ importLoc = bogusSrcLoc
, importModule = moduleName
, importQualified = qualified
, importSrc = False
, importAs = Nothing
, importSpecs = mkImportSpecs items
, importPkg = Nothing
}
mkImportSpecs :: Maybe [String] -> Maybe (Bool, [ImportSpec])
mkImportSpecs Nothing = Nothing
mkImportSpecs (Just items) = Just (False, map (IVar . name) items)
instance Compilable StatementSpan where
type (CompileResult StatementSpan) = [Stmt]
-- XXX is it necessary to compile generators this way?
-- can the yield statement be made to dynamically build a generator object?
compile (Fun {fun_name = fun, fun_args = params, fun_body = body}) = do
oldSeenYield <- getSeenYield
unSetSeenYield
bindings <- checkEither $ funBindings params body
compiledBody <- nestedScope bindings $ compileBlockDo $ Block body
let args = Hask.PList $ map (identToMangledPatVar . paramIdent) params
isGenerator <- getSeenYield
setSeenYield oldSeenYield
let lambdaBody =
if isGenerator
-- this warrants a special case of returnGenerator, otherwise
-- the compiled code is slightly uglier.
then app Prim.returnGenerator $ parens compiledBody
else compiledBody
lambda = lamE bogusSrcLoc [args] lambdaBody
arityExp = intE $ fromIntegral $ length params
doc = docString body
defExp = appFun Prim.def [arityExp, doc, parens lambda]
(binderStmts, binderExp) <- stmtBinder defExp
writeStmt <- qualStmt <$> compileWrite fun binderExp
return $ binderStmts ++ [writeStmt]
-- Handle the single assignment case specially. In the multi-assign case
-- we want to share the evaluation of the rhs, hence the use of compileExprComp.
-- This is not needed in the single assign case, and would be overkill in general.
compile (Assign { assign_to = [lhs], assign_expr = rhs }) = do
(stmtsRhs, compiledRhs) <- compileExprObject rhs
assignStmts <- compileAssign lhs compiledRhs
return $ stmtsRhs ++ assignStmts
compile (Assign { assign_to = lhss, assign_expr = rhs }) = do
(stmtsRhs, compiledRhs) <- compileExprComp rhs
(binderStmts, binderExp) <- stmtBinder compiledRhs
assignStmtss <- mapM (flip compileAssign binderExp) lhss
return $ stmtsRhs ++ binderStmts ++ concat assignStmtss
compile (Conditional { cond_guards = guards, cond_else = elseBranch })
| length guards == 1 && isEmptySuite elseBranch,
(condExp, condSuite) <- head guards = do
condVal <- compileExprBlock condExp
condBody <- compileSuiteDo condSuite
returnStmt $ appFun Prim.ifThen [parens condVal, parens condBody]
| otherwise = do
elseExp <- compileSuiteDo elseBranch
condExp <- foldM compileGuard elseExp $ reverse guards
returnStmt condExp
compile (Return { return_expr = maybeExpr })
| Just call@(Call {}) <- maybeExpr = do
(stmts, compiledExpr) <- compileTailCall call
let newStmt = qualStmt compiledExpr
return (stmts ++ [newStmt])
| otherwise = do
(stmts, compiledExpr) <- maybe (returnExp Prim.none) compileExprObject maybeExpr
let newStmt = qualStmt $ app Prim.ret $ parens compiledExpr
return (stmts ++ [newStmt])
{-
Even though it looks like we could eliminate stmt expressions, we do need to
compile them to code just in case they have side effects (like raising exceptions).
It is very hard to determine that an expression is effect free. Constant values
are the easy case, but probably not worth the effort. Furthermore, top-level
constant expressions must be preserved for the repl of the interpreter.
-}
compile (StmtExpr { stmt_expr = expr }) = do
(stmts, compiledExpr) <- compileExprComp expr
let newStmt = qualStmt $ compiledExpr
return (stmts ++ [newStmt])
compile (While { while_cond = cond, while_body = body, while_else = elseSuite }) = do
condVal <- compileExprBlock cond
bodyExp <- compileSuiteDo body
if isEmptySuite elseSuite
then returnStmt $ appFun Prim.while [parens condVal, parens bodyExp]
else do
elseExp <- compileSuiteDo elseSuite
returnStmt $ appFun Prim.whileElse [parens condVal, parens bodyExp, parens elseExp]
-- XXX fixme, only supports one target
compile (For { for_targets = [var], for_generator = generator, for_body = body, for_else = elseSuite }) = do
(generatorStmts, compiledGenerator) <- compileExprObject generator
compiledStmtss <- compile body
newVar <- freshHaskellVar
writeStmt <- qualStmt <$> compileWrite var (Hask.var newVar)
let lambdaBody = lamE bogusSrcLoc [pvar newVar] $ doBlock $ (writeStmt : concat compiledStmtss)
if isEmptySuite elseSuite
then return (generatorStmts ++ [qualStmt $ appFun Prim.for [compiledGenerator, parens lambdaBody]])
else do
compiledElse <- compileSuiteDo elseSuite
return (generatorStmts ++ [qualStmt $ appFun Prim.forElse [compiledGenerator, parens lambdaBody, parens compiledElse]])
compile (Pass {}) = returnStmt Prim.pass
compile (NonLocal {}) = return []
compile (Global {}) = return []
-- XXX need to check if we are compiling a local or global variable.
-- XXX perhaps the body of a class is evaluated in a similar fashion to a module?
-- more dynamic than currently. Yes it is!
compile (Class { class_name = ident, class_args = args, class_body = body }) = do
bindings <- checkEither $ funBindings [] body
-- XXX slightly dodgy since the syntax allows Argument types in class definitions but
-- I'm not sure what their meaning is, or if it is just a case of the grammar over specifying
-- the language
(argsStmtss, compiledArgs) <- mapAndUnzipM (compileExprObject . arg_expr) args
compiledBody <- nestedScope bindings $ compile $ Block body
let locals = Set.toList $ localVars bindings
attributes <- qualStmt <$> app Prim.pure <$> listE <$> mapM compileClassLocal locals
let klassExp = appFun Prim.klass
[ strE $ identString ident
, listE compiledArgs
, parens $ doBlock $ compiledBody ++ [attributes]]
(binderStmts, binderExp) <- stmtBinder klassExp
writeStmt <- qualStmt <$> compileWrite ident binderExp
return (concat argsStmtss ++ binderStmts ++ [writeStmt])
where
compileClassLocal :: IdentString -> Compile Hask.Exp
compileClassLocal ident = do
hashedIdent <- compile ident
let mangledIdent = identToMangledVar ident
return $ Hask.tuple [hashedIdent, mangledIdent]
compile (Try { try_body = body, try_excepts = handlers, try_else = elseSuite, try_finally = finally }) = do
bodyExp <- compileSuiteDo body
asName <- freshHaskellVar
handlerExp <- compileHandlers (Hask.var asName) handlers
let handlerLam = lamE bogusSrcLoc [pvar asName] handlerExp
compiledElse <- compile elseSuite
compiledFinally <- compile finally
returnStmt $ mkTry (parens bodyExp) handlerLam (concat compiledElse) (concat compiledFinally)
compile (Raise { raise_expr = RaiseV3 raised }) =
case raised of
Nothing -> returnStmt Prim.reRaise
Just (e, maybeFrom) ->
case maybeFrom of
Nothing -> do
(stmts, obj) <- compileExprObject e
let newStmt = qualStmt $ app Prim.raise obj
return (stmts ++ [newStmt])
Just fromExp -> do
(stmts1, obj1) <- compileExprObject e
(stmts2, obj2) <- compileExprObject fromExp
let newStmt = qualStmt $ appFun Prim.raiseFrom [obj1, obj2]
return (stmts1 ++ stmts2 ++ [newStmt])
compile (Break {}) = returnStmt Prim.break
compile (Continue {}) = returnStmt Prim.continue
compile (Import { import_items = items }) = concat <$> mapM compile items
compile stmt@(FromImport { from_module = mod, from_items = items }) = do
case import_relative_module mod of
Nothing -> unsupported $ prettyText stmt
Just dottedName ->
case dottedName of
[ident] -> do
let identStr = ident_string ident
berpIdentStr = mkBerpModuleName identStr
importExp = appFun Prim.importModule
[strE identStr, qvar (ModuleName berpIdentStr) (name initName)]
(binderStmts, binderExp) <- stmtBinder importExp
itemsStmts <- compileFromItems binderExp items
addImport identStr
return (binderStmts ++ itemsStmts)
_other -> unsupported $ prettyText stmt
compile other = unsupported $ prettyText other
compileRead :: ToIdentString a => a -> Compile Exp
compileRead ident = do
compiledIdent <- compile $ toIdentString ident
global <- isGlobal ident
{-
let reader = if global then Prim.readGlobal else Prim.readLocal
return $ appFun reader [Prim.globals, compiledIdent]
-}
return $
if global
then appFun Prim.readGlobal [Prim.globals, compiledIdent]
else appFun Prim.readLocal [compiledIdent]
compileWrite :: ToIdentString a => a -> Exp -> Compile Exp
compileWrite ident exp = do
compiledIdent <- compile $ toIdentString ident
global <- isGlobal ident
{-
let writer = if global then Prim.writeGlobal else Prim.writeLocal
return $ appFun writer [Prim.globals, compiledIdent, exp]
-}
return $
if global
then appFun Prim.writeGlobal [Prim.globals, compiledIdent, exp]
else appFun Prim.writeLocal [compiledIdent, exp]
compileFromItems :: Exp -> FromItemsSpan -> Compile [Hask.Stmt]
compileFromItems exp (ImportEverything {}) = do
topLevel <- isTopLevel
if topLevel
then returnStmt $ appFun Prim.importAll [Prim.globals, exp]
else fail "Syntax Error: import * only allowed at module level"
compileFromItems exp (FromItems { from_items_items = items }) =
concat <$> mapM (compileFromItem exp) items
compileFromItem :: Exp -> FromItemSpan -> Compile [Hask.Stmt]
compileFromItem exp (FromItem { from_item_name = item, from_as_name = maybeAsName }) = do
let objectName = maybe item id maybeAsName
compiledItem <- compile item
(projectStmts, obj) <- stmtBinder (infixApp exp (Prim.primOp ".") compiledItem)
writeStmt <- qualStmt <$> compileWrite objectName obj
return (projectStmts ++ [writeStmt])
instance Compilable ImportItemSpan where
type CompileResult ImportItemSpan = [Hask.Stmt]
compile (ImportItem {import_item_name = dottedName, import_as_name = maybeAsName }) =
case dottedName of
[ident] -> do
let identStr = ident_string ident
berpIdentStr = mkBerpModuleName identStr
importExp = appFun Prim.importModule
[strE identStr, qvar (ModuleName berpIdentStr) (name initName)]
(binderStmts, binderExp) <- stmtBinder importExp
let objectName = maybe ident id maybeAsName
writeStmt <- qualStmt <$> compileWrite objectName binderExp
addImport identStr
return (binderStmts ++ [writeStmt])
_other -> unsupported ("import of " ++ show dottedName)
mkBerpModuleName :: String -> String
mkBerpModuleName = ("Berp_" ++)
docString :: SuiteSpan -> Exp
docString (StmtExpr { stmt_expr = Strings { strings_strings = ss }} : _)
= parens $ Prim.string $ trimString $ concat ss
docString _other = Prim.none
mkTry :: Exp -> Exp -> [Stmt] -> [Stmt] -> Exp
mkTry body handler elseSuite finally =
case (elseSuite, finally) of
([], []) -> appFun Prim.try [body, handler]
(_:_, []) -> appFun Prim.tryElse [body, handler, elseBlock]
([], _:_) -> appFun Prim.tryFinally [body, handler, finallyBlock]
(_:_, _:_) -> appFun Prim.tryElseFinally [body, handler, elseBlock, finallyBlock]
where
elseBlock = parens $ doBlock elseSuite
finallyBlock = parens $ doBlock finally
instance Compilable IdentSpan where
type CompileResult IdentSpan = Hask.Exp
compile = compile . toIdentString
instance Compilable IdentString where
type CompileResult IdentString = Hask.Exp
compile ident = do
global <- isGlobal ident
if global
then do
let str = identString $ toIdentString ident
mangled = mangle str
-- hashedVal = intE $ fromIntegral $ hash str
hashedVal = intE $ fromIntegral $ hash mangled
return $ Hask.tuple [hashedVal, strE mangled]
else
return $ identToMangledVar ident
instance Compilable ExprSpan where
type (CompileResult ExprSpan) = ([Stmt], Exp)
compile (Py.Strings { strings_strings = ss }) =
returnExp $ Prim.string $ concat $ map trimString ss
compile (Py.Bool { bool_value = b}) = returnExp $ Prim.bool b
compile (Py.Int { int_value = i}) = returnExp $ intE i
compile (Py.Float { float_value = f}) = returnExp $ Lit $ Frac $ toRational f
compile (Py.Imaginary { imaginary_value = i}) =
returnExp $ app Prim.complex $ paren c
where
real = Lit $ Frac 0
imag = Lit $ Frac $ toRational i
c = infixApp real (op $ sym ":+") imag
compile (Py.Var { var_ident = ident}) = do
readExp <- compileRead ident
return ([], readExp)
compile (Py.BinaryOp { operator = op, left_op_arg = leftExp, right_op_arg = rightExp })
| Dot {} <- op, Py.Var { var_ident = method } <- rightExp = do
(leftStmts, compiledLeft) <- compileExprObject leftExp
compiledMethod <- compile method
let newExp = infixApp compiledLeft (Prim.opExp op) compiledMethod
return (leftStmts, newExp)
| otherwise = do
(leftStmts, compiledLeft) <- compileExprObject leftExp
(rightStmts, compiledRight) <- compileExprObject rightExp
let newExp = infixApp compiledLeft (Prim.opExp op) compiledRight
return (leftStmts ++ rightStmts, newExp)
compile (Py.UnaryOp { operator = op, op_arg = arg }) = do
(argStmts, compiledArg) <- compileExprObject arg
let compiledOp = compileUnaryOp op
return (argStmts, app compiledOp compiledArg)
compile (Call { call_fun = fun, call_args = args }) = do
(funStmts, compiledFun) <- compileExprObject fun
(argsStmtss, compiledArgs) <- mapAndUnzipM compile args
let newExp = infixApp compiledFun Prim.apply (listE compiledArgs)
return (funStmts ++ concat argsStmtss, newExp)
compile (Py.Tuple { tuple_exprs = elements }) = do
(stmtss, exprs) <- mapAndUnzipM compileExprObject elements
let newExp = app Prim.tuple $ listE exprs
return (concat stmtss, newExp)
compile (Py.Lambda { lambda_args = params, lambda_body = body }) = do
bindings <- checkEither $ funBindings params body
compiledBody <- nestedScope bindings $ compileExprBlock body
let args = Hask.PList $ map (identToMangledPatVar . paramIdent) params
let lambda = lamE bogusSrcLoc [args] compiledBody
returnExp $ appFun Prim.lambda [intE (fromIntegral $ length params), parens lambda]
compile (Py.List { list_exprs = elements }) = do
(stmtss, exprs) <- mapAndUnzipM compileExprObject elements
let newExp = app Prim.list $ listE exprs
return (concat stmtss, newExp)
compile (Py.Dictionary { dict_mappings = mappings }) = do
let compileExprObjectPair (e1, e2) = do
(stmts1, compiledE1) <- compileExprObject e1
(stmts2, compiledE2) <- compileExprObject e2
return (stmts1 ++ stmts2, (compiledE1, compiledE2))
(stmtss, exprPairs) <- mapAndUnzipM compileExprObjectPair mappings
let newExp = app Prim.dict $ listE $ map (\(x,y) -> Hask.tuple [x,y]) exprPairs
return (concat stmtss, newExp)
compile (Py.Set { set_exprs = elements }) = do
(stmtss, exprs) <- mapAndUnzipM compileExprObject elements
let newExp = app Prim.set $ listE exprs
return (concat stmtss, newExp)
compile (Subscript { subscriptee = obj_expr, subscript_expr = sub }) = do
(stmtss, exprs) <- mapAndUnzipM compileExprObject [obj_expr, sub]
let newExp = appFun Prim.subscript exprs
return (concat stmtss, newExp)
compile (Yield { yield_expr = maybeExpr }) = do
(stmts, compiledExpr) <- maybe (returnExp Prim.none) compileExprObject maybeExpr
let newExpr = app Prim.yield $ parens compiledExpr
setSeenYield True
return (stmts, newExpr)
compile (Py.Paren { paren_expr = e }) = compile e
compile (None {}) = returnExp Prim.none
compile (Py.Generator { gen_comprehension = comp }) = compileComprehens GenComprehension comp
compile (Py.ListComp { list_comprehension = comp }) = compileComprehens ListComprehension comp
compile (DictComp { dict_comprehension = comp }) =
compileComprehens DictComprehension $ normaliseDictComprehension comp
compile (SetComp { set_comprehension = comp }) = compileComprehens SetComprehension comp
compile other = unsupported $ prettyText other
data ComprehensType = GenComprehension | ListComprehension | DictComprehension | SetComprehension
deriving (Eq, Show)
-- XXX maybe it would make more sense if we normalised dict comprehensions in the parser.
-- could simplify the types somewhat.
normaliseDictComprehension :: ComprehensionSpan (ExprSpan, ExprSpan) -> ComprehensionSpan ExprSpan
normaliseDictComprehension comp@(Comprehension { comprehension_expr = (e1, e2) })
= comp { comprehension_expr = Py.tuple [e1, e2] }
compileComprehens :: ComprehensType -> ComprehensionSpan ExprSpan -> Compile ([Stmt], Exp)
compileComprehens GenComprehension comprehension = do
let resultStmt = stmtExpr $ yield $ comprehension_expr comprehension
desugaredFor <- desugarComprehensFor resultStmt $ comprehension_for comprehension
bindings <- checkEither $ funBindings [] desugaredFor
compiledBody <- nestedScope bindings $ compileBlockDo $ Block [desugaredFor]
let mkGenApp = app Prim.generator $ parens compiledBody
return ([], mkGenApp)
compileComprehens ty comprehension = do
v <- freshPythonVar
let newVar = Py.var v
let initStmt = comprehensInit ty newVar
resultStmt = comprehensUpdater ty newVar $ comprehension_expr comprehension
desugaredFor <- desugarComprehensFor resultStmt $ comprehension_for comprehension
bindings <- checkEither $ funBindings [] desugaredFor
let oldLocals = localVars bindings
newLocals = Set.insert (toIdentString v) oldLocals
let newBindings = bindings { localVars = newLocals }
compiledBody <- nestedScope newBindings $ compile $ Block [initStmt, desugaredFor]
-- XXX this should be a readLocal
return (compiledBody, app Prim.read $ identToMangledVar v)
comprehensInit :: ComprehensType -> ExprSpan -> StatementSpan
comprehensInit ListComprehension var = var `assign` list []
comprehensInit SetComprehension var = var `assign` set []
comprehensInit DictComprehension var = var `assign` dict []
comprehensInit GenComprehension _var = error $ "comprehensInit called on generator comprehension"
comprehensUpdater :: ComprehensType -> ExprSpan -> ExprSpan -> StatementSpan
comprehensUpdater ListComprehension lhs rhs =
stmtExpr $ call (binOp dot lhs $ Py.var $ ident "append") [rhs]
comprehensUpdater SetComprehension lhs rhs =
stmtExpr $ call (binOp dot lhs $ Py.var $ ident "add") [rhs]
comprehensUpdater DictComprehension lhs (Py.Tuple { tuple_exprs = [key, val] }) =
assign (subscript lhs key) val
comprehensUpdater GenComprehension _lhs _rhs =
error $ "comprehensUpdater called on generator comprehension"
comprehensUpdater _other _lhs _rhs =
error $ "comprehensUpdater called on badly formed comprehension"
desugarComprehensFor :: StatementSpan -> CompForSpan -> Compile StatementSpan
desugarComprehensFor result
(CompFor { comp_for_exprs = pat, comp_in_expr = inExpr, comp_for_iter = rest }) = do
stmts <- desugarComprehensMaybeIter result rest
return $ Py.for pat inExpr stmts
desugarComprehensMaybeIter :: StatementSpan -> (Maybe CompIterSpan) -> Compile [StatementSpan]
desugarComprehensMaybeIter result Nothing = return [result]
desugarComprehensMaybeIter result (Just iter) = desugarComprehensIter result iter
desugarComprehensIter :: StatementSpan -> CompIterSpan -> Compile [StatementSpan]
desugarComprehensIter result (IterFor { comp_iter_for = compFor })
= (:[]) <$> desugarComprehensFor result compFor
desugarComprehensIter result (IterIf { comp_iter_if = compIf })
= desugarComprehensIf result compIf
desugarComprehensIf :: StatementSpan -> CompIfSpan -> Compile [StatementSpan]
desugarComprehensIf result (CompIf { comp_if = ifPart, comp_if_iter = iter }) = do
stmts <- desugarComprehensMaybeIter result iter
let guards = [(ifPart, stmts)]
return [Py.conditional guards []]
compileTailCall :: ExprSpan -> Compile ([Stmt], Exp)
compileTailCall (Call { call_fun = fun, call_args = args }) = do
(funStmts, compiledFun) <- compileExprObject fun
(argsStmtss, compiledArgs) <- mapAndUnzipM compile args
let newExp = appFun Prim.tailCall [compiledFun, listE compiledArgs]
return (funStmts ++ concat argsStmtss, newExp)
compileTailCall other = error $ "compileTailCall on non call expression: " ++ show other
instance Compilable ArgumentSpan where
type (CompileResult ArgumentSpan) = ([Stmt], Exp)
compile (ArgExpr { arg_expr = expr }) = compileExprObject expr
compile other = unsupported $ prettyText other
newtype Block = Block [StatementSpan]
newtype TopBlock = TopBlock [StatementSpan]
instance Compilable TopBlock where
type (CompileResult TopBlock) = ([Hask.Stmt], [Hask.Stmt])
compile (TopBlock []) = return ([], [qualStmt Prim.pass])
compile (TopBlock stmts) = do
scope <- getScope
let locals = localVars scope
varDecls <- mapM declareTopInterpreterVar $ Set.toList locals
haskStmtss <- compile stmts
return (varDecls, concat haskStmtss)
instance Compilable Block where
type (CompileResult Block) = [Hask.Stmt]
compile (Block []) = return [qualStmt Prim.pass]
compile (Block stmts) = do
scope <- getScope
let locals = localVars scope
varDecls <- mapM declareVar $ Set.toList locals
haskStmtss <- compile stmts
return (varDecls ++ concat haskStmtss)
-- This compiles an Expression to something with type (Eval Object). In cases where
-- the expression is atomic, it wraps the result in a call to "pure".
-- This is because compiling an atomic expression gives something
-- of type Object.
compileExprComp :: Py.ExprSpan -> Compile ([Stmt], Exp)
compileExprComp exp
| isAtomicExpr exp = do
(stmts, compiledExp) <- compile exp
return (stmts, app Prim.pureObj $ parens compiledExp)
| otherwise = compile exp
-- This compiles an expression to something with type Object. In cases where
-- the expression is non-atomic, it binds the result of evaluating the expression
-- to a variable. This is because compiling a non-atomic expression gives something
-- of type (Eval Object)
compileExprObject :: Py.ExprSpan -> Compile ([Stmt], Exp)
compileExprObject exp
| isAtomicExpr exp = compile exp
| otherwise = do
(expStmts, compiledExp) <- compile exp
(binderStmts, binderExp) <- stmtBinder compiledExp
return (expStmts ++ binderStmts, binderExp)
compileHandlers :: Exp -> [HandlerSpan] -> Compile Exp
compileHandlers asName handlers = do
validate handlers
foldrM (compileHandler asName) (parens $ app Prim.raise asName) handlers
compileHandler :: Exp -> HandlerSpan -> Exp -> Compile Exp
compileHandler asName (Handler { handler_clause = clause, handler_suite = body }) nextHandler = do
bodyStmts <- compile body
case except_clause clause of
Nothing -> return $ appFun Prim.exceptDefault
[parens $ doBlock $ concat bodyStmts, parens nextHandler]
Just (exceptClass, maybeExceptVar) -> do
varStmts <-
case maybeExceptVar of
Nothing -> return []
Just (Py.Var { var_ident = ident }) -> do
identDecl <- declareVar ident
-- XXX I think this should always be a local variable assignment
let newAssign = qualStmt $ infixApp (Hask.var $ identToMangledName ident) Prim.assignOp asName
return [identDecl, newAssign]
other -> error $ "exception expression not a variable: " ++ show other
(classStmts, classObj) <- compileExprObject exceptClass
let newBody = parens $ doBlock (varStmts ++ concat bodyStmts)
newStmt = qualStmt $ appFun Prim.except [asName, classObj, newBody, parens nextHandler]
return $ doBlock (classStmts ++ [newStmt])
compileAssign :: Py.ExprSpan -> Hask.Exp -> Compile [Stmt]
compileAssign (Py.Paren { paren_expr = expr }) rhs = compileAssign expr rhs
compileAssign (Py.Tuple { tuple_exprs = patElements }) rhs =
compileUnpack patElements rhs
compileAssign (Py.List { list_exprs = patElements }) rhs =
compileUnpack patElements rhs
-- Right argument of dot is always a variable, because dot associates to the left
compileAssign (Py.BinaryOp { operator = Dot {}
, left_op_arg = lhs
, right_op_arg = Py.Var { var_ident = attribute}}
) rhs = do
(stmtsLhs, compiledLhs) <- compileExprObject lhs
compiledAttribute <- compile attribute
let newStmt = qualStmt $ appFun Prim.setAttr [compiledLhs, compiledAttribute, rhs]
return (stmtsLhs ++ [newStmt])
compileAssign (Py.Subscript { subscriptee = objExpr, subscript_expr = sub }) rhs = do
(stmtsObj, compiledObj) <- compileExprObject objExpr
(stmtsSub, compiledSub) <- compileExprObject sub
let newStmt = qualStmt $ appFun Prim.setItem [compiledObj, compiledSub, rhs]
return (stmtsObj ++ stmtsSub ++ [newStmt])
compileAssign (Py.Var { var_ident = ident}) rhs =
(:[]) <$> qualStmt <$> compileWrite ident rhs
compileAssign lhs _rhs = unsupported ("Assignment to " ++ prettyText lhs)
compileUnpack :: [Py.ExprSpan] -> Hask.Exp -> Compile [Stmt]
compileUnpack exps rhs = do
let pat = mkUnpackPat exps
returnStmt $ appFun Prim.unpack [pat, rhs]
where
mkUnpackPat :: [Py.ExprSpan] -> Hask.Exp
mkUnpackPat listExps =
appFun (Con $ UnQual $ name "G")
[ intE $ fromIntegral $ length listExps
, listE $ map unpackComponent listExps]
unpackComponent :: Py.ExprSpan -> Hask.Exp
unpackComponent (Py.Var { var_ident = ident }) =
App (Con $ UnQual $ name "V") (identToMangledVar ident)
unpackComponent (Py.List { list_exprs = elements }) = mkUnpackPat elements
unpackComponent (Py.Tuple { tuple_exprs = elements }) = mkUnpackPat elements
unpackComponent (Py.Paren { paren_expr = exp }) = unpackComponent exp
unpackComponent other = error $ "unpack assignment to " ++ prettyText other
compileUnaryOp :: Py.OpSpan -> Hask.Exp
compileUnaryOp (Plus {}) = Prim.unaryPlus
compileUnaryOp (Minus {}) = Prim.unaryMinus
compileUnaryOp (Invert {}) = Prim.invert
compileUnaryOp (Not {}) = Prim.not
compileUnaryOp other = error ("Syntax Error: not a valid unary operator: " ++ show other)
stmtBinder :: Exp -> Compile ([Stmt], Exp)
stmtBinder exp = do
v <- freshHaskellVar
let newStmt = genStmt bogusSrcLoc (pvar v) exp
return ([newStmt], Hask.var v)
compileExprBlock :: ExprSpan -> Compile Hask.Exp
compileExprBlock exp = do
(stmts, exp) <- compileExprComp exp
return $ doBlock (stmts ++ [qualStmt exp])
compileBlockDo :: Block -> Compile Hask.Exp
compileBlockDo block = doBlock <$> compile block
compileSuiteDo :: SuiteSpan -> Compile Exp
compileSuiteDo [] = return Prim.pass
compileSuiteDo stmts = do
compiledStmtss <- compile stmts
return $ doBlock $ concat compiledStmtss
nestedScope :: Scope -> Compile a -> Compile a
nestedScope bindings comp = do
outerScope <- getScope
let newEnclosingVars = enclosingVars outerScope `Set.union`
localVars outerScope `Set.union`
paramVars outerScope
let newLevel = nestingLevel outerScope + 1
newScope = bindings { nestingLevel = newLevel, enclosingVars = newEnclosingVars }
setScope newScope
result <- comp
setScope outerScope
return result
returnStmt :: Exp -> Compile [Stmt]
returnStmt e = return [qualStmt e]
returnExp :: Exp -> Compile ([Stmt], Exp)
returnExp e = return ([], e)
declareTopInterpreterVar :: ToIdentString a => a -> Compile Hask.Stmt
declareTopInterpreterVar ident = do
let mangledPatVar = identToMangledPatVar ident
str = strE $ identString ident
return $ genStmt bogusSrcLoc mangledPatVar $ app Prim.topVar str
declareVar :: ToIdentString a => a -> Compile Hask.Stmt
declareVar ident = do
let mangledPatVar = identToMangledPatVar ident
str = strE $ identString ident
return $ genStmt bogusSrcLoc mangledPatVar $ app Prim.variable str
compileGuard :: Hask.Exp -> (ExprSpan, SuiteSpan) -> Compile Hask.Exp
compileGuard elseExp (guard, body) =
Hask.conditional <$> compileExprBlock guard <*> compileSuiteDo body <*> pure elseExp
identToMangledName :: ToIdentString a => a -> Hask.Name
identToMangledName = name . mangle . identString
identToMangledVar :: ToIdentString a => a -> Hask.Exp
identToMangledVar = Hask.var . identToMangledName
identToMangledPatVar :: ToIdentString a => a -> Hask.Pat
identToMangledPatVar = pvar . identToMangledName
-- Check that the syntax is valid Python (the parser is sometimes too liberal).
class Validate t where
validate :: t -> Compile ()
instance Validate [HandlerSpan] where
validate [] = fail "Syntax Error: try statement must have one or more handlers"
validate [_] = return ()
validate (h:hs)
| Nothing <- except_clause $ handler_clause h
= if null hs then return ()
else fail "Syntax Error: default 'except:' must be last"
| otherwise = validate hs
-- Trim (one or three) quote marks off front and end of string which are left by the lexer/parser.
trimString :: String -> String
trimString [] = []
trimString (w:x:y:zs)
| all isQuote [w,x,y] && all (== w) [x,y] = trimStringEnd zs
| isQuote w = trimStringEnd (x:y:zs)
| otherwise = w:x:y:trimStringEnd zs
trimString (x:xs)
| isQuote x = trimStringEnd xs
| otherwise = x : trimStringEnd xs
trimStringEnd :: String -> String
trimStringEnd [] = []
trimStringEnd str@[x]
| isQuote x = []
| otherwise = str
trimStringEnd str@[x,y,z]
| all isQuote str && all (== x) [y,z] = []
| otherwise = x : trimStringEnd [y,z]
trimStringEnd (x:xs) = x : trimStringEnd xs
isQuote :: Char -> Bool
isQuote '\'' = True
isQuote '"' = True
isQuote _ = False
-- test if a variable is global
isGlobal :: ToIdentString a => a -> Compile Bool
isGlobal ident = withScope $ \scope -> Scope.isGlobal (toIdentString ident) scope
| bjpop/berp | libs/src/Berp/Compile/Compile.hs | bsd-3-clause | 35,150 | 0 | 25 | 7,948 | 10,239 | 5,207 | 5,032 | 623 | 5 |
{-# LANGUAGE OverloadedStrings #-}
{-
This file is part of the Haskell package cassava-streams. It is
subject to the license terms in the LICENSE file found in the
top-level directory of this distribution and at
git://pmade.com/cassava-streams/LICENSE. No part of cassava-streams
package, including this file, may be copied, modified, propagated, or
distributed except according to the terms contained in the LICENSE
file.
-}
--------------------------------------------------------------------------------
-- | A simple tutorial on using the cassava-streams library to glue
-- together cassava and io-streams.
--
-- Note: if you're reading this on Hackage or in Haddock then you
-- should switch to source view with the \"Source\" link at the top of
-- this page or open this file in your favorite text editor.
module System.IO.Streams.Csv.Tutorial
( -- * Types representing to-do items and their state
Item (..)
, TState (..)
-- * Functions which use cassava-streams functions
, onlyTodo
, markDone
) where
--------------------------------------------------------------------------------
import Control.Monad
import Data.Csv
import qualified Data.Vector as V
import System.IO
import qualified System.IO.Streams as Streams
import System.IO.Streams.Csv
--------------------------------------------------------------------------------
-- | A to-do item.
data Item = Item
{ title :: String -- ^ Title.
, state :: TState -- ^ State.
, time :: Maybe Double -- ^ Seconds taken to complete.
} deriving (Show, Eq)
instance FromNamedRecord Item where
parseNamedRecord m = Item <$> m .: "Title"
<*> m .: "State"
<*> m .: "Time"
instance ToNamedRecord Item where
toNamedRecord (Item t s tm) =
namedRecord [ "Title" .= t
, "State" .= s
, "Time" .= tm
]
--------------------------------------------------------------------------------
-- | Possible states for a to-do item.
data TState = Todo -- ^ Item needs to be completed.
| Done -- ^ Item has been finished.
deriving (Show, Eq)
instance FromField TState where
parseField "TODO" = return Todo
parseField "DONE" = return Done
parseField _ = mzero
instance ToField TState where
toField Todo = "TODO"
toField Done = "DONE"
--------------------------------------------------------------------------------
-- | The @onlyTodo@ function reads to-do 'Item's from the given input
-- handle (in CSV format) and writes them back to the output handle
-- (also in CSV format), but only if the items are in the @Todo@
-- state. In another words, the CSV data is filtered so that the
-- output handle only receives to-do 'Item's which haven't been
-- completed.
--
-- The io-streams @handleToInputStream@ function is used to create an
-- @InputStream ByteString@ stream from the given input handle.
--
-- That stream is then given to the cassava-streams function
-- 'decodeStreamByName' which converts the @InputStream ByteString@
-- stream into an @InputStream Item@ stream.
--
-- Notice that the cassava-streams function 'onlyValidRecords' is used
-- to transform the decoding stream into one that only produces valid
-- records. Any records which fail type conversion (via
-- @FromNamedRecord@ or @FromRecord@) will not escape from
-- 'onlyValidRecords' but instead will throw an exception.
--
-- Finally the io-streams @filter@ function is used to filter the
-- input stream so that it only produces to-do items which haven't
-- been completed.
onlyTodo :: Handle -- ^ Input handle where CSV data can be read.
-> Handle -- ^ Output handle where CSV data can be written.
-> IO ()
onlyTodo inH outH = do
-- A stream which produces items which are not 'Done'.
input <- Streams.handleToInputStream inH >>=
decodeStreamByName >>= onlyValidRecords >>=
Streams.filter (\item -> state item /= Done)
-- A stream to write items into. They will be converted to CSV.
output <- Streams.handleToOutputStream outH >>=
encodeStreamByName (V.fromList ["State", "Time", "Title"])
-- Connect the input and output streams.
Streams.connect input output
--------------------------------------------------------------------------------
-- | The @markDone@ function will read to-do items from the given
-- input handle and mark any matching items as @Done@. All to-do
-- items are written to the given output handle.
markDone :: String -- ^ Items with this title are marked as @Done@.
-> Handle -- ^ Input handle where CSV data can be read.
-> Handle -- ^ Output handle where CSV data can be written.
-> IO ()
markDone titleOfItem inH outH = do
-- Change matching items to the 'Done' state.
let markDone' item = if title item == titleOfItem
then item {state = Done}
else item
-- A stream which produces items and converts matching items to the
-- 'Done' state.
input <- Streams.handleToInputStream inH >>=
decodeStreamByName >>= onlyValidRecords >>=
Streams.map markDone'
-- A stream to write items into. They will be converted to CSV.
output <- Streams.handleToOutputStream outH >>=
encodeStreamByName (V.fromList ["State", "Time", "Title"])
-- Connect the input and output streams.
Streams.connect input output
| pjones/cassava-streams | src/System/IO/Streams/Csv/Tutorial.hs | bsd-3-clause | 5,484 | 0 | 13 | 1,217 | 608 | 350 | 258 | 61 | 2 |
{-# LANGUAGE GADTs #-}
{- |
* Parse 'String' into @['Node']@.
* Parse macro definitions in @['Node']@ giving a @'Context'@ and an @'Program' 'RenderI'@.
Only macro definition in the current level is parsed.
* @'IO' a@.
-}
module Text.Velocity.Example where
import Control.Error
import Text.Velocity
import Text.Velocity.Context
import Text.Velocity.Parse
import Text.Velocity.Render
import Text.Velocity.Types
example1 :: Either VelocityError Node
example1 = parseVelocity "-" "Hello world."
example2 :: Either VelocityError Node
example2 = parseVelocity "-" "$abc$!abc$!{abc}$abc.def$100#100 'dojima rice $exchange'"
example3 :: IO ()
example3 = runEitherT (parseVelocityFile "test/variable.vm") >>= print
example4 :: IO ()
example4 = runEitherT (renderVelocityFile2 con "test/variable.vm") >>= either print putStr
where
con = emptyContext
| edom/velocity | Text/Velocity/Example.hs | bsd-3-clause | 891 | 0 | 8 | 155 | 153 | 84 | 69 | 17 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE CPP #-}
-- #define DEBUG
{-|
Module : AERN2.PPoly.MinMax
Description : PPoly pointwise min and max
Copyright : (c) Michal Konecny, Eike Neumann
License : BSD3
Maintainer : mikkonecny@gmail.com
Stability : experimental
Portability : portable
Poly pointwise min and max
-}
module AERN2.PPoly.MinMax where
#ifdef DEBUG
import Debug.Trace (trace)
#define maybeTrace trace
#define maybeTraceIO putStrLn
#else
#define maybeTrace (\ (_ :: String) t -> t)
#define maybeTraceIO (\ (_ :: String) -> return ())
#endif
import MixedTypesNumPrelude
import AERN2.MP
import AERN2.MP.Dyadic
import AERN2.Interval
-- import AERN2.RealFun.Operations
import AERN2.Poly.Cheb
import AERN2.Poly.Cheb.MaximumInt (intify)
import AERN2.Poly.Conversion (cheb2Power)
import AERN2.Poly.Power.RootsIntVector (findRootsWithEvaluation)
import AERN2.Poly.Cheb.Ring ()
import AERN2.Poly.Ball
import AERN2.PPoly.Type
{- min/max -}
instance CanMinMaxAsymmetric PPoly PPoly where
type MinMaxType PPoly PPoly = PPoly
max = ppolyMax
min a b = negate (max (-a) (-b))
ppolyMax ::
PPoly -> PPoly -> PPoly
ppolyMax a b =
if ppoly_dom a /= ppoly_dom b then
error "ppolyMax: PPoly domains do not match."
else
PPoly (concat (map chebMax (refine a b)))
(ppoly_dom a)
where
chebMax ((Interval domL domR), p, q) =
polys
where
acGuide = getAccuracyGuide p `max` getAccuracyGuide q
precision = getPrecision p `max` getPrecision q
-- realAcc = getAccuracy p `min` getAccuracy q
diffC = centre $ p - q
diffC' = derivativeExact diffC
evalDiffOnInterval (Interval l r) =
evalDf diffC diffC' $
fromEndpointsAsIntervals (mpBallP precision l) (mpBallP precision r)
(_diffCIntErr, diffCInt) = intify diffC
diffCRoots =
map
(\(Interval l r, err) ->
(centre $ mpBallP (ac2prec acGuide) $ (l + r)/!2, errorBound err)) $
findRootsWithEvaluation
(cheb2Power diffCInt)
(abs . evalDiffOnInterval)
(\v -> (v <= (dyadic 0.5)^!(fromAccuracy acGuide)) == Just True)
(rational domL) (rational domR)
intervals :: [(DyadicInterval, ErrorBound)]
intervals =
reverse $
aux [] (domL, errorBound 0) (diffCRoots ++ [(domR, errorBound 0)])
where
aux is (l, e0) ((x, e1) : []) =
(Interval l x, max e0 e1) : is
aux is (l, e0) ((x, e1) : xs) =
aux ((Interval l x, max e0 e1) : is) (x, e1) xs
aux _ _ [] = []
biggest :: (DyadicInterval, ErrorBound) -> (DyadicInterval, Cheb)
biggest (i@(Interval l r), e) =
if (pm >= qm) == Just True then
(i, p')
else
(i, q')
where
-- TODO: check and fix the following if necesary
p' = updateRadius (+ e) p
q' = updateRadius (+ e) q
m = (dyadic 0.5) * (l + r)
pm = evalDirect p (mpBall m)
qm = evalDirect q (mpBall m)
polys :: [(DyadicInterval, Cheb)]
polys =
map biggest intervals
| michalkonecny/aern2 | aern2-fun-univariate/src/AERN2/PPoly/MinMax.hs | bsd-3-clause | 3,049 | 0 | 19 | 784 | 919 | 510 | 409 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ViewPatterns #-}
module Language.Haskell.Liquid.Bare.GhcSpec (
GhcSpec(..)
, makeGhcSpec
) where
import CoreSyn hiding (Expr)
import HscTypes
import Id
import NameSet
import TyCon
import Var
import TysWiredIn
import Control.Applicative ((<$>))
import Control.Monad.Reader
import Control.Monad.State
import Data.Bifunctor
import Data.Maybe
import Data.Monoid
import qualified Control.Exception as Ex
import qualified Data.List as L
import qualified Data.HashMap.Strict as M
import qualified Data.HashSet as S
import Language.Fixpoint.Misc
import Language.Fixpoint.Names (takeWhileSym, nilName, consName)
import Language.Fixpoint.Types hiding (BE)
import Language.Haskell.Liquid.Dictionaries
import Language.Haskell.Liquid.GhcMisc (getSourcePosE, getSourcePos, sourcePosSrcSpan)
import Language.Haskell.Liquid.PredType (makeTyConInfo)
import Language.Haskell.Liquid.RefType
import Language.Haskell.Liquid.Types
import Language.Haskell.Liquid.WiredIn
import Language.Haskell.Liquid.Visitors
import Language.Haskell.Liquid.CoreToLogic
import qualified Language.Haskell.Liquid.Measure as Ms
import Language.Haskell.Liquid.Bare.Check
import Language.Haskell.Liquid.Bare.DataType
import Language.Haskell.Liquid.Bare.Env
import Language.Haskell.Liquid.Bare.Existential
import Language.Haskell.Liquid.Bare.Measure
import Language.Haskell.Liquid.Bare.Misc (makeSymbols, mkVarExpr)
import Language.Haskell.Liquid.Bare.Plugged
import Language.Haskell.Liquid.Bare.RTEnv
import Language.Haskell.Liquid.Bare.Spec
import Language.Haskell.Liquid.Bare.SymSort
import Language.Haskell.Liquid.Bare.RefToLogic
------------------------------------------------------------------
---------- Top Level Output --------------------------------------
------------------------------------------------------------------
makeGhcSpec :: Config -> ModName -> [CoreBind] -> [Var] -> [Var] -> NameSet -> HscEnv -> Either Error LogicMap
-> [(ModName,Ms.BareSpec)]
-> IO GhcSpec
makeGhcSpec cfg name cbs vars defVars exports env lmap specs
= do sp <- throwLeft =<< execBare act initEnv
let renv = ghcSpecEnv sp cbs
throwLeft $ checkGhcSpec specs renv $ postProcess cbs renv sp
where
act = makeGhcSpec' cfg cbs vars defVars exports specs
throwLeft = either Ex.throw return
initEnv = BE name mempty mempty mempty env lmap' mempty mempty
lmap' = case lmap of {Left e -> Ex.throw e; Right x -> x `mappend` listLMap}
listLMap = toLogicMap [(nilName, [], hNil),
(consName, [x, xs], hCons (EVar <$> [x,xs]))
]
where
x = symbol "x"
xs = symbol "xs"
hNil = EApp (dummyLoc $ symbol nilDataCon ) []
hCons = EApp (dummyLoc $ symbol consDataCon)
postProcess :: [CoreBind] -> SEnv SortedReft -> GhcSpec -> GhcSpec
postProcess cbs specEnv sp@(SP {..}) = sp { tySigs = tySigs', texprs = ts, asmSigs = asmSigs', dicts = dicts' }
-- HEREHEREHEREHERE (addTyConInfo stuff)
where
(sigs, ts) = replaceLocalBinds tcEmbeds tyconEnv tySigs texprs specEnv cbs
tySigs' = mapSnd (addTyConInfo tcEmbeds tyconEnv <$>) <$> sigs
asmSigs' = mapSnd (addTyConInfo tcEmbeds tyconEnv <$>) <$> asmSigs
dicts' = dmapty (addTyConInfo tcEmbeds tyconEnv) dicts
ghcSpecEnv sp cbs = fromListSEnv binds
where
emb = tcEmbeds sp
binds = [(x, rSort t) | (x, Loc _ _ t) <- meas sp]
++ [(symbol v, rSort t) | (v, Loc _ _ t) <- ctors sp]
++ [(x, vSort v) | (x, v) <- freeSyms sp, isConLikeId v]
++ [(val x , rSort stringrSort) | Just (ELit x s) <- mkLit <$> lconsts, isString s]
rSort = rTypeSortedReft emb
vSort = rSort . varRSort
varRSort :: Var -> RSort
varRSort = ofType . varType
lconsts = literals cbs
stringrSort :: RSort
stringrSort = ofType stringTy
isString s = rTypeSort emb stringrSort == s
------------------------------------------------------------------------------------------------
makeGhcSpec' :: Config -> [CoreBind] -> [Var] -> [Var] -> NameSet -> [(ModName, Ms.BareSpec)] -> BareM GhcSpec
------------------------------------------------------------------------------------------------
makeGhcSpec' cfg cbs vars defVars exports specs
= do name <- modName <$> get
makeBounds name defVars cbs specs
makeRTEnv specs
(tycons, datacons, dcSs, tyi, embs) <- makeGhcSpecCHOP1 specs
modify $ \be -> be { tcEnv = tyi }
(cls, mts) <- second mconcat . unzip . mconcat <$> mapM (makeClasses name cfg vars) specs
(measures, cms', ms', cs', xs') <- makeGhcSpecCHOP2 cbs specs dcSs datacons cls embs
(invs, ialias, sigs, asms) <- makeGhcSpecCHOP3 cfg vars defVars specs name mts embs
syms <- makeSymbols (vars ++ map fst cs') xs' (sigs ++ asms ++ cs') ms' (invs ++ (snd <$> ialias))
let su = mkSubst [ (x, mkVarExpr v) | (x, v) <- syms]
return (emptySpec cfg)
>>= makeGhcSpec0 cfg defVars exports name
>>= makeGhcSpec1 vars embs tyi exports name sigs asms cs' ms' cms' su
>>= makeGhcSpec2 invs ialias measures su
>>= makeGhcSpec3 datacons tycons embs syms
>>= makeGhcSpec4 defVars specs name su
>>= makeSpecDictionaries embs vars specs
emptySpec :: Config -> GhcSpec
emptySpec cfg = SP [] [] [] [] [] [] [] [] [] mempty [] [] [] [] mempty mempty cfg mempty [] mempty mempty
makeGhcSpec0 cfg defVars exports name sp
= do targetVars <- makeTargetVars name defVars $ binders cfg
return $ sp { config = cfg
, exports = exports
, tgtVars = targetVars }
makeGhcSpec1 vars embs tyi exports name sigs asms cs' ms' cms' su sp
= do tySigs <- makePluggedSigs name embs tyi exports $ tx sigs
asmSigs <- makePluggedAsmSigs embs tyi $ tx asms
ctors <- makePluggedAsmSigs embs tyi $ tx cs'
lmap <- logicEnv <$> get
inlmap <- inlines <$> get
let ctors' = [ (x, txRefToLogic lmap inlmap <$> t) | (x, t) <- ctors ]
return $ sp { tySigs = tySigs
, asmSigs = asmSigs
, ctors = ctors'
, meas = tx' $ tx $ ms' ++ varMeasures vars ++ cms' }
where
tx = fmap . mapSnd . subst $ su
tx' = fmap (mapSnd $ fmap uRType)
makeGhcSpec2 invs ialias measures su sp
= return $ sp { invariants = subst su invs
, ialiases = subst su ialias
, measures = subst su
<$> M.elems (Ms.measMap measures)
++ Ms.imeas measures
}
makeGhcSpec3 datacons tycons embs syms sp
= do tcEnv <- gets tcEnv
lmap <- logicEnv <$> get
inlmap <- inlines <$> get
let dcons' = mapSnd (txRefToLogic lmap inlmap) <$> datacons
return $ sp { tyconEnv = tcEnv
, dconsP = dcons'
, tconsP = tycons
, tcEmbeds = embs
, freeSyms = [(symbol v, v) | (_, v) <- syms] }
makeGhcSpec4 defVars specs name su sp
= do decr' <- mconcat <$> mapM (makeHints defVars . snd) specs
texprs' <- mconcat <$> mapM (makeTExpr defVars . snd) specs
lazies <- mkThing makeLazy
lvars' <- mkThing makeLVar
hmeas <- mkThing makeHIMeas
quals <- mconcat <$> mapM makeQualifiers specs
let sigs = strengthenHaskellMeasures hmeas ++ tySigs sp
lmap <- logicEnv <$> get
inlmap <- inlines <$> get
let tx = mapSnd (fmap $ txRefToLogic lmap inlmap)
let mtx = txRefToLogic lmap inlmap
return $ sp { qualifiers = subst su quals
, decr = decr'
, texprs = texprs'
, lvars = lvars'
, lazy = lazies
, tySigs = tx <$> sigs
, asmSigs = tx <$> (asmSigs sp)
, measures = mtx <$> (measures sp)
}
where
mkThing mk = S.fromList . mconcat <$> sequence [ mk defVars s | (m, s) <- specs, m == name ]
makeGhcSpecCHOP1 specs
= do (tcs, dcs) <- mconcat <$> mapM makeConTypes specs
let tycons = tcs ++ wiredTyCons
let tyi = makeTyConInfo tycons
embs <- mconcat <$> mapM makeTyConEmbeds specs
datacons <- makePluggedDataCons embs tyi (concat dcs ++ wiredDataCons)
let dcSelectors = concat $ map makeMeasureSelectors datacons
return $ (tycons, second val <$> datacons, dcSelectors, tyi, embs)
makeGhcSpecCHOP3 cfg vars defVars specs name mts embs
= do sigs' <- mconcat <$> mapM (makeAssertSpec name cfg vars defVars) specs
asms' <- mconcat <$> mapM (makeAssumeSpec name cfg vars defVars) specs
invs <- mconcat <$> mapM makeInvariants specs
ialias <- mconcat <$> mapM makeIAliases specs
let dms = makeDefaultMethods vars mts
tyi <- gets tcEnv
let sigs = [ (x, txRefSort tyi embs . txExpToBind <$> t) | (_, x, t) <- sigs' ++ mts ++ dms ]
let asms = [ (x, txRefSort tyi embs . txExpToBind <$> t) | (_, x, t) <- asms' ]
return (invs, ialias, sigs, asms)
makeGhcSpecCHOP2 cbs specs dcSelectors datacons cls embs
= do measures' <- mconcat <$> mapM makeMeasureSpec specs
tyi <- gets tcEnv
name <- gets modName
mapM_ (makeHaskellInlines cbs name) specs
hmeans <- mapM (makeHaskellMeasures cbs name) specs
let measures = mconcat (measures':Ms.mkMSpec' dcSelectors:hmeans)
let (cs, ms) = makeMeasureSpec' measures
let cms = makeClassMeasureSpec measures
let cms' = [ (x, Loc l l' $ cSort t) | (Loc l l' x, t) <- cms ]
let ms' = [ (x, Loc l l' t) | (Loc l l' x, t) <- ms, isNothing $ lookup x cms' ]
let cs' = [ (v, Loc (getSourcePos v) (getSourcePosE v) (txRefSort tyi embs t)) | (v, t) <- meetDataConSpec cs (datacons ++ cls)]
let xs' = val . fst <$> ms
return (measures, cms', ms', cs', xs')
data ReplaceEnv = RE { _re_env :: M.HashMap Symbol Symbol
, _re_fenv :: SEnv SortedReft
, _re_emb :: TCEmb TyCon
, _re_tyi :: M.HashMap TyCon RTyCon
}
type ReplaceState = ( M.HashMap Var (Located SpecType)
, M.HashMap Var [Expr]
)
type ReplaceM = ReaderT ReplaceEnv (State ReplaceState)
replaceLocalBinds :: TCEmb TyCon
-> M.HashMap TyCon RTyCon
-> [(Var, Located SpecType)]
-> [(Var, [Expr])]
-> SEnv SortedReft
-> CoreProgram
-> ([(Var, Located SpecType)], [(Var, [Expr])])
replaceLocalBinds emb tyi sigs texprs senv cbs
= (M.toList s, M.toList t)
where
(s,t) = execState (runReaderT (mapM_ (`traverseBinds` return ()) cbs)
(RE M.empty senv emb tyi))
(M.fromList sigs, M.fromList texprs)
traverseExprs (Let b e)
= traverseBinds b (traverseExprs e)
traverseExprs (Lam b e)
= withExtendedEnv [b] (traverseExprs e)
traverseExprs (App x y)
= traverseExprs x >> traverseExprs y
traverseExprs (Case e _ _ as)
= traverseExprs e >> mapM_ (traverseExprs . thd3) as
traverseExprs (Cast e _)
= traverseExprs e
traverseExprs (Tick _ e)
= traverseExprs e
traverseExprs _
= return ()
traverseBinds b k = withExtendedEnv (bindersOf b) $ do
mapM_ traverseExprs (rhssOfBind b)
k
withExtendedEnv vs k
= do RE env' fenv' emb tyi <- ask
let env = L.foldl' (\m v -> M.insert (takeWhileSym (/='#') $ symbol v) (symbol v) m) env' vs
fenv = L.foldl' (\m v -> insertSEnv (symbol v) (rTypeSortedReft emb (ofType $ varType v :: RSort)) m) fenv' vs
withReaderT (const (RE env fenv emb tyi)) $ do
mapM_ replaceLocalBindsOne vs
k
replaceLocalBindsOne :: Var -> ReplaceM ()
replaceLocalBindsOne v
= do mt <- gets (M.lookup v . fst)
case mt of
Nothing -> return ()
Just (Loc l l' (toRTypeRep -> t@(RTypeRep {..}))) -> do
(RE env' fenv emb tyi) <- ask
let f m k = M.lookupDefault k k m
let (env,args) = L.mapAccumL (\e (v,t) -> (M.insert v v e, substa (f e) t))
env' (zip ty_binds ty_args)
let res = substa (f env) ty_res
let t' = fromRTypeRep $ t { ty_args = args, ty_res = res }
let msg = ErrTySpec (sourcePosSrcSpan l) (pprint v) t'
case checkTy msg emb tyi fenv t' of
Just err -> Ex.throw err
Nothing -> modify (first $ M.insert v (Loc l l' t'))
mes <- gets (M.lookup v . snd)
case mes of
Nothing -> return ()
Just es -> do
let es' = substa (f env) es
case checkTerminationExpr emb fenv (v, Loc l l' t', es') of
Just err -> Ex.throw err
Nothing -> modify (second $ M.insert v es')
| rolph-recto/liquidhaskell | src/Language/Haskell/Liquid/Bare/GhcSpec.hs | bsd-3-clause | 13,679 | 0 | 24 | 4,294 | 4,485 | 2,324 | 2,161 | 259 | 5 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE TypeFamilies #-}
module Physics.Falling3d.Transform3d
(
Transform3d
)
where
import Control.Monad(liftM)
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as M
import Data.Vector.Unboxed
import Physics.Falling.Math.Transform hiding(Vector)
import Data.Vect.Double.Util.Projective
type Transform3d = Proj4
instance DeltaTransform Transform3d Vec3 where
deltaTransform p v = v .* dt
where
t = fromProjective p
dt = trim t :: Mat3
deltaTransformTranspose p v = dt *. v
where
t = fromProjective p
dt = trim t :: Mat3
instance Translatable Transform3d Vec3 where
translation p = trim t :: Vec3
where
(Mat4 _ _ _ t) = fromProjective p
translate = translate4
instance Rotatable Transform3d Vec3 where
rotate orientationVector = if magnitude /= 0.0 then
rotateProj4 magnitude normal
else
id
where
magnitude = len orientationVector
normal = toNormalUnsafe $ orientationVector &* (1.0 / magnitude)
instance PerpProd Vec3 Vec3 where
perp = crossprod
instance Transform Transform3d Vec3
instance TransformSystem Transform3d Vec3 Vec3
newtype instance MVector s Vec3 = MV_Vec3 (MVector s (Double, Double, Double))
newtype instance Vector Vec3 = V_Vec3 (Vector (Double, Double, Double))
instance Unbox Vec3
instance M.MVector MVector Vec3 where
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicOverlaps #-}
{-# INLINE basicUnsafeNew #-}
{-# INLINE basicUnsafeReplicate #-}
{-# INLINE basicUnsafeRead #-}
{-# INLINE basicUnsafeWrite #-}
{-# INLINE basicClear #-}
{-# INLINE basicSet #-}
{-# INLINE basicUnsafeCopy #-}
{-# INLINE basicUnsafeGrow #-}
basicLength (MV_Vec3 v) = M.basicLength v
basicUnsafeSlice i n (MV_Vec3 v) = MV_Vec3 $ M.basicUnsafeSlice i n v
basicOverlaps (MV_Vec3 v1) (MV_Vec3 v2) = M.basicOverlaps v1 v2
basicUnsafeNew n = MV_Vec3 `liftM` M.basicUnsafeNew n
basicUnsafeReplicate n (Vec3 x y z) = MV_Vec3 `liftM` M.basicUnsafeReplicate n (x, y, z)
basicUnsafeRead (MV_Vec3 v) i = (\(x,y,z) -> Vec3 x y z) `liftM` M.basicUnsafeRead v i
basicUnsafeWrite (MV_Vec3 v) i (Vec3 x y z) = M.basicUnsafeWrite v i (x, y, z)
basicClear (MV_Vec3 v) = M.basicClear v
basicSet (MV_Vec3 v) (Vec3 x y z) = M.basicSet v (x, y, z)
basicUnsafeCopy (MV_Vec3 v1) (MV_Vec3 v2) = M.basicUnsafeCopy v1 v2
basicUnsafeGrow (MV_Vec3 v) n = MV_Vec3 `liftM` M.basicUnsafeGrow v n
instance G.Vector Vector Vec3 where
{-# INLINE basicUnsafeFreeze #-}
{-# INLINE basicUnsafeThaw #-}
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicUnsafeIndexM #-}
{-# INLINE elemseq #-}
basicUnsafeFreeze (MV_Vec3 v) = V_Vec3 `liftM` G.basicUnsafeFreeze v
basicUnsafeThaw (V_Vec3 v) = MV_Vec3 `liftM` G.basicUnsafeThaw v
basicLength (V_Vec3 v) = G.basicLength v
basicUnsafeSlice i n (V_Vec3 v) = V_Vec3 $ G.basicUnsafeSlice i n v
basicUnsafeIndexM (V_Vec3 v) i = (\(x,y,z) -> Vec3 x y z) `liftM` G.basicUnsafeIndexM v i
basicUnsafeCopy (MV_Vec3 mv) (V_Vec3 v) = G.basicUnsafeCopy mv v
elemseq _ = seq
| sebcrozet/falling3d | Physics/Falling3d/Transform3d.hs | bsd-3-clause | 3,759 | 0 | 10 | 1,158 | 965 | 520 | 445 | 74 | 0 |
module Data.Astro.TypesTest
(
tests
, testDecimalDegrees
, testDecimalHours
)
where
import Test.Framework (testGroup)
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.HUnit
import Test.HUnit.Approx
import Test.QuickCheck
import Data.Ratio ((%))
import Data.Astro.Types
tests = [testGroup "DecimalDegrees <-> DecimalHours" [
testDecimalDegrees "12.03 H -> 180.45 D" 0.000001 (DD 180.45) $ fromDecimalHours (DH 12.03)
, testDecimalHours "180.45 D -> 12.03 H" 0.000001 (DH 12.03) $ toDecimalHours (DD 180.45)
, testProperty "property" prop_DHConversion
]
, testGroup "DecimalDegrees <-> Radians" [
testCase "0 -> 0 (rad)" $ assertApproxEqual "" 0.000000001 0 $ toRadians (DD 0)
, testCase "45 -> PI/4" $ assertApproxEqual "" 0.000000001 (pi*0.25) $ toRadians (DD 45)
, testCase "90 -> PI/2" $ assertApproxEqual "" 0.000000001 (pi*0.5) $ toRadians (DD 90)
, testCase "180 -> PI" $ assertApproxEqual "" 0.000000001 pi $ toRadians (DD 180)
, testCase "360 -> 2*PI" $ assertApproxEqual "" 0.000000001 (pi*2) $ toRadians (DD 360)
, testDecimalDegrees "0 -> 0 (deg)" 0.000000001 (DD 0) (fromRadians 0)
, testDecimalDegrees "pi/4 -> 45" 0.000000001 (DD 45) (fromRadians (pi*0.25))
, testDecimalDegrees "pi/2 -> 90" 0.000000001 (DD 90) (fromRadians (pi*0.5))
, testDecimalDegrees "pi -> 180" 0.000000001 (DD 180) (fromRadians pi)
, testDecimalDegrees "2*pi -> 360" 0.000000001 (DD 360) (fromRadians (pi*2))
]
, testGroup "DecimalDegrees <-> DMS" [
testDecimalDegrees "182 31' 27''" 0.00001 (DD 182.52417) $ fromDMS 182 31 27
, testCase "182.5" $ toDMS (DD 182.5) @?= (182, 30, 0)
, testProperty "property" prop_DMSConversion
]
, testGroup "DecimalHours <-> HMS" [
testDecimalHours "HMS -> DH 6:00" 0.00000001 (DH 6.0) (fromHMS 6 0 0)
, testDecimalHours "HMS -> DH 18:00" 0.00000001 (DH 18.0) (fromHMS 18 0 0)
, testDecimalHours "HMS -> DH 18:30" 0.00000001 (DH $ (18*2 + 1) / 2) (fromHMS 18 30 0)
, testDecimalHours "HMS -> DH 00:00:30" 0.00000001 (DH $ 30 / (60*60)) (fromHMS 0 0 30)
, testDecimalHours "HMS -> DH 00:00:10" 0.00000001 (DH 0.002777777778) $ fromHMS 0 0 10
, testDecimalHours "HMS -> DH 23:59:59.99999" 0.00000001 (DH 24.0) $ fromHMS 23 59 59.99999
, testCase "DH -> HMS 6:00" $ toHMS (DH 6.0) @?= (6, 0, 0)
, testCase "DH -> HMS 18:00" $ toHMS (DH 18.0) @?= (18, 0, 0)
, testCase "DH -> HMS 18:30" $ toHMS (DH $ (18*2 + 1) / 2) @?= (18, 30, 0)
, testCase "DH -> HMS 00:00:30" $ toHMS (DH $ (30 / (60*60))) @?= (0, 0, 30)
, testProperty "property" prop_HMSConversion
]
, testGroup "Light travel time" [
testDecimalHours "7.7 AU" 0.0000001 1.06722 (lightTravelTime 7.7)
]
, testGroup "KM <-> AU" [
testCase "KM -> AU" $ assertApproxEqual "" 1e-5 (AU 7.8) (kmToAU 1166863391.46)
, testCase "AU -> KM" $ assertApproxEqual "" 1e-5 1166863391.46 (auToKM 7.8)
]
, testGroup "DD: standard typeclasses" [
testCase "show" $ "DD 15.5" @=? show (DD 15.5)
, testCase "showList" $ "[DD 15.3,DD 15.7]" @=? showList [DD 15.3, DD 15.7] ""
, testCase "showsPrec" $ "DD 15.5" @=? showsPrec 0 (DD 15.5) ""
, testCase "== (True)" $ True @=? (DD 15.5) == (DD 15.5)
, testCase "== (False)" $ False @=? (DD 15.3) == (DD 15.5)
, testCase "/= (True)" $ True @=? (DD 15.3) /= (DD 15.5)
, testCase "/= (False)" $ False @=? (DD 15.5) /= (DD 15.5)
, testCase "compare: LT" $ LT @=? (DD 15.3) `compare` (DD 15.5)
, testCase "compare: EQ" $ EQ @=? (DD 15.5) `compare` (DD 15.5)
, testCase "compare: GT" $ GT @=? (DD 15.7) `compare` (DD 15.5)
, testCase "<" $ True @=? (DD 15.3) < (DD 15.7)
, testCase "<=" $ True @=? (DD 15.3) <= (DD 15.7)
, testCase ">" $ False @=? (DD 15.3) > (DD 15.7)
, testCase ">=" $ False @=? (DD 15.3) >= (DD 15.7)
, testCase "max" $ (DD 15.7) @=? max (DD 15.3) (DD 15.7)
, testCase "min" $ (DD 15.3) @=? min (DD 15.3) (DD 15.7)
, testCase "abs" $ (DD 15.7) @=? abs (DD (-15.7))
, testCase "signum > 0" $ (DD 1.0) @=? signum (DD 15.5)
, testCase "signum = 0" $ (DD 0.0) @=? signum (DD 0.0)
, testCase "signum < 0" $ (DD $ -1.0) @=? signum (DD $ -15.5)
, testCase "toRational" $ (31 % 2) @=? toRational (DD 15.5)
, testCase "recip" $ (DD 0.01) @=? recip (DD 100)
, testCase "properFraction" $ (15, DD 0.5) @=? properFraction (DD 15.5)
]
, testGroup "DH: standard typeclasses" [
testCase "show" $ "DH 15.5" @=? show (DH 15.5)
, testCase "showList" $ "[DH 15.3,DH 15.7]" @=? showList [DH 15.3, DH 15.7] ""
, testCase "showsPrec" $ "DH 15.5" @=? showsPrec 0 (DH 15.5) ""
, testCase "== (True)" $ True @=? (DH 15.5) == (DH 15.5)
, testCase "== (False)" $ False @=? (DH 15.3) == (DH 15.5)
, testCase "/= (True)" $ True @=? (DH 15.3) /= (DH 15.5)
, testCase "/= (False)" $ False @=? (DH 15.5) /= (DH 15.5)
, testCase "compare: LT" $ LT @=? (DH 15.3) `compare` (DH 15.5)
, testCase "compare: EQ" $ EQ @=? (DH 15.5) `compare` (DH 15.5)
, testCase "compare: GT" $ GT @=? (DH 15.7) `compare` (DH 15.5)
, testCase "<" $ True @=? (DH 15.3) < (DH 15.7)
, testCase "<=" $ True @=? (DH 15.3) <= (DH 15.7)
, testCase ">" $ False @=? (DH 15.3) > (DH 15.7)
, testCase ">=" $ False @=? (DH 15.3) >= (DH 15.7)
, testCase "max" $ (DH 15.7) @=? max (DH 15.3) (DH 15.7)
, testCase "min" $ (DH 15.3) @=? min (DH 15.3) (DH 15.7)
, testCase "abs" $ (DH 15.7) @=? abs (DH (-15.7))
, testCase "signum > 0" $ (DH 1.0) @=? signum (DH 15.5)
, testCase "signum = 0" $ (DH 0.0) @=? signum (DH 0.0)
, testCase "signum < 0" $ (DH $ -1.0) @=? signum (DH $ -15.5)
, testCase "toRational" $ (31 % 2) @=? toRational (DH 15.5)
, testCase "recip" $ (DH 0.01) @=? recip (DH 100)
, testCase "properFraction" $ (15, DH 0.5) @=? properFraction (DH 15.5)
]
, testGroup "AU: standard typeclasses" [
testCase "show" $ "AU 15.5" @=? show (AU 15.5)
, testCase "showList" $ "[AU 15.3,AU 15.7]" @=? showList [AU 15.3, AU 15.7] ""
, testCase "showsPrec" $ "AU 15.5" @=? showsPrec 0 (AU 15.5) ""
, testCase "== (True)" $ True @=? (AU 15.5) == (AU 15.5)
, testCase "== (False)" $ False @=? (AU 15.3) == (AU 15.5)
, testCase "/= (True)" $ True @=? (AU 15.3) /= (AU 15.5)
, testCase "/= (False)" $ False @=? (AU 15.5) /= (AU 15.5)
, testCase "compare: LT" $ LT @=? (AU 15.3) `compare` (AU 15.5)
, testCase "compare: EQ" $ EQ @=? (AU 15.5) `compare` (AU 15.5)
, testCase "compare: GT" $ GT @=? (AU 15.7) `compare` (AU 15.5)
, testCase "<" $ True @=? (AU 15.3) < (AU 15.7)
, testCase "<=" $ True @=? (AU 15.3) <= (AU 15.7)
, testCase ">" $ False @=? (AU 15.3) > (AU 15.7)
, testCase ">=" $ False @=? (AU 15.3) >= (AU 15.7)
, testCase "max" $ (AU 15.7) @=? max (AU 15.3) (AU 15.7)
, testCase "min" $ (AU 15.3) @=? min (AU 15.3) (AU 15.7)
, testCase "+" $ (AU 17.5) @=? (AU 15.5) + (AU 2)
, testCase "-" $ (AU 13.5) @=? (AU 15.5) - (AU 2)
, testCase "*" $ (AU 31) @=? (AU 15.5) * (AU 2)
, testCase "negate" $ (AU 15.5) @=? negate (AU $ -15.5)
, testCase "abs" $ (AU 15.7) @=? abs (AU (-15.7))
, testCase "signum > 0" $ (AU 1.0) @=? signum (AU 15.5)
, testCase "signum = 0" $ (AU 0.0) @=? signum (AU 0.0)
, testCase "signum < 0" $ (AU $ -1.0) @=? signum (AU $ -15.5)
, testCase "fromInteger" $ (AU 17) @=? fromInteger 17
, testCase "toRational" $ (31 % 2) @=? toRational (AU 15.5)
, testCase "/" $ (AU 10) @=? (AU 30) / (AU 3)
, testCase "recip" $ (AU 0.01) @=? recip (AU 100)
, testCase "properFraction" $ (15, AU 0.5) @=? properFraction (AU 15.5)
]
]
testDecimalDegrees msg eps (DD expected) (DD actual) =
testCase msg $ assertApproxEqual "" eps expected actual
testDecimalHours msg eps (DH expected) (DH actual) =
testCase msg $ assertApproxEqual "" eps expected actual
prop_DHConversion n =
let DH h = toDecimalHours . fromDecimalHours $ DH n
DD d = fromDecimalHours . toDecimalHours $ DD n
eps = 0.00000001
in abs(n-h) < eps && abs(n-d) < eps
where types = (n::Double)
prop_DMSConversion dd =
let (d, m, s) = toDMS $ DD dd
DD d' = fromDMS d m s
in abs(dd-d') < 0.0000001
where types = (dd::Double)
prop_HMSConversion =
forAll (choose (0, 1.0)) $ checkHMSConversionProperties
checkHMSConversionProperties :: Double -> Bool
checkHMSConversionProperties n =
let (h, m, s) = toHMS $ DH n
DH n2 = fromHMS h m s
in abs (n-n2) < 0.00000001
| Alexander-Ignatyev/astro | test/Data/Astro/TypesTest.hs | bsd-3-clause | 9,736 | 0 | 16 | 3,163 | 3,730 | 1,878 | 1,852 | 149 | 1 |
module Foreign.Storable.OrphansSpec (main, spec) where
import Test.Hspec
import Data.Complex
import Data.Orphans ()
import Data.Ratio
import Foreign.Storable
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "Storable Complex instance" $ do
it "has twice the sizeOf its realPart" $ do
sizeOf ((1 :: Double) :+ 2) `shouldBe` 2*sizeOf (1 :: Double)
it "has the alignment of its realPart" $ do
alignment ((1 :: Double) :+ 2) `shouldBe` alignment (1 :: Double)
describe "Storable Ratio instance" $ do
it "has twice the sizeOf its parameterized type" $ do
sizeOf ((1 :: Int) % 2) `shouldBe` 2*sizeOf (1 :: Int)
it "has the alignment of its parameterized type" $ do
alignment ((1 :: Int) % 2) `shouldBe` alignment (1 :: Int)
| phadej/base-orphans | test/Foreign/Storable/OrphansSpec.hs | mit | 781 | 0 | 18 | 172 | 275 | 146 | 129 | 20 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Foreign.JavaScript.V8.ContextSpec (main, spec) where
import Test.Hspec
import Data.String.Builder (build)
import Control.Monad (replicateM_)
import Control.Exception (bracket)
import Foreign.JavaScript.V8
import Foreign.JavaScript.V8.Value (numberOfHandles)
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "Context" $ do
describe "contextNew" $ do
it "takes a template for the global object" $ do
withHandleScope $ do
t <- mkObjectTemplate
objectTemplateAddFunction t "reverse" jsReverse
objectTemplateAddFunction t "concat" jsConcat
bracket (contextNew t) dispose $ \c -> do
withContextScope c $ do
(runScript "reverse('foo')" >>= toString) `shouldReturn` "oof"
(runScript "concat('foo', 'bar')" >>= toString) `shouldReturn` "foobar"
it "does not leak handles" $ do
withHandleScope $ do
t <- mkObjectTemplate
numberOfHandles `shouldReturn` 1
c <- contextNew t
numberOfHandles `shouldReturn` 1
dispose c
describe "dispose" $ do
it "disposes the associated object template" $ do
withHandleScope $ do
t <- mkObjectTemplate
contextNew t >>= dispose
dispose t `shouldThrow` (== AlreadyDisposed)
it "can share values with other contexts" $ do
withHandleScope $ do
c1 <- mkObjectTemplate >>= contextNew
v <- withContextScope c1 $ do
runScript "'bar'"
t <- mkObjectTemplate
objectTemplateAddFunction t "foo" $ \_ -> do
return v
bracket (contextNew t) dispose $ \c2 -> do
withContextScope c2 $ do
(runScript "foo()" >>= toString) `shouldReturn` "bar"
dispose c1
it "can share objects with other contexts" $ do
withHandleScope $ do
c1 <- mkObjectTemplate >>= contextNew
v <- withContextScope c1 $ do
runScript . build $ do
"var foo = new Object()"
"foo.bar = 23"
"foo"
t <- mkObjectTemplate
objectTemplateAddFunction t "foo" $ \_ -> do
return v
bracket (contextNew t) dispose $ \c2 -> do
withContextScope c2 $ do
(runScript "foo().bar" >>= toString) `shouldReturn` "23"
dispose c1
describe "objectTemplateAddFunction" $ do
context "when the native function is called" $ do
it "does not leak handles" $ do
withHandleScope $ do
t <- mkObjectTemplate
objectTemplateAddFunction t "foo" $ \_ -> do
n <- numberOfHandles
replicateM_ 10 (runScript "new Object();")
numberOfHandles `shouldReturn` (n + 10)
mkUndefined
bracket (contextNew t) dispose $ \c -> withContextScope c $ do
numberOfHandles `shouldReturn` 1
_ <- runScript "foo()"
numberOfHandles `shouldReturn` 2
where
jsReverse args = do
s <- argumentsGet 0 args >>= toString
mkString (reverse s)
jsConcat args = do
a <- argumentsGet 0 args >>= toString
b <- argumentsGet 1 args >>= toString
mkString (a ++ b)
| sol/v8 | test/Foreign/JavaScript/V8/ContextSpec.hs | mit | 3,307 | 0 | 29 | 1,078 | 888 | 415 | 473 | 84 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Dashdo.Rdash (rdash, charts, controls, defaultSidebar, Sidebar(..)) where
import Dashdo.Types
import Lucid
import Lucid.Bootstrap3
import qualified Lucid.Rdash as RD
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import Data.Text hiding (map, intersperse, length)
import Data.Monoid
import Control.Applicative ((<$>))
sidebarMain :: Sidebar -> Html ()
sidebarMain sb = a_ [href_ "#"] $ do
toHtml $ title sb
span_ [class_ "menu-icon glyphicon glyphicon-transfer"] (return ())
sidebarList :: [RDashdo m] -> [RD.SidebarItem]
sidebarList rdashdos = (sidebarListItem <$> rdashdos) -- <> [div_ [id_ "dashdo-sidebar"] mempty ]
where
sidebarListItem = \rd ->
RD.SidebarLink (rdTitle rd) (pack $ rdFid rd) "tachometer"
data Sidebar = Sidebar
{ title:: T.Text
, subTitle:: T.Text
, footer:: Html ()
}
defaultSidebar :: Sidebar
defaultSidebar = Sidebar "Dashdo" "Dashboards" $ rowEven XS
[ a_ [href_ "https://github.com/diffusionkinetics/open/dashdo"] (i_ [class_ "fa fa-lg fa-github"] mempty <> "Github")
, a_ [href_ "#"] $ i_ [id_ "spinner", class_ "fa fa-cog fa-2x"] mempty
]
rdash :: [RDashdo m] -> Html () -> Sidebar -> TL.Text
rdash rdashdos headExtra sb = do
renderText $ doctypehtml_ $ do
head_ $ do
meta_ [charset_ "utf-8"]
meta_ [name_ "viewport", content_ "width=device-width"] -- TODO: add attribute initial-scale=1
-- If href doesn't end with a slash, redirect to the one with slashes
-- this is needed to make relative urls work
script_ $ T.unlines
[ "if (!window.location.href.match(/\\/$/)) {"
, " window.location.href = window.location.href + '/';"
, "}"
]
cdnFontAwesome
cdnCSS
RD.rdashCSS
cdnJqueryJS
headExtra
body_ $ do
let sb' = (RD.mkSidebar (sidebarMain sb) $ sidebarList rdashdos) <> div_ [id_ "dashdo-sidebar"] mempty
sbf = RD.mkSidebarFooter $ footer sb
sbw = RD.mkSidebarWrapper sb' sbf
cw = RD.mkPageContent $ do
RD.mkHeaderBar [RD.mkMetaBox [RD.mkMetaTitle (span_ [id_ "dashdo-title"] mempty)]]
div_ [id_ "dashdo-main"] mempty
pgw = form_ [id_ "dashdo-form", method_ "post"] $ RD.mkPageWrapperOpen sbw cw
--RD.mkIndexPage (RD.mkHead "Dashdo") (
pgw
cdnBootstrapJS
script_ [src_ "js/dashdo.js"] ("" :: Text)
script_ [src_ "js/runners/rdashdo.js"] ("" :: Text)
controls :: Monad m => HtmlT m () -> HtmlT m ()
controls content = do
div_ [class_ "row"] $
mkCol [(XS, 12), (MD, 12)] $
div_ [class_ "widget"] $ do
div_ [class_ "widget-header"] "Settings"
div_ [class_ "widget-body"] $
div_ [class_ "widget-content"] $
content
charts :: Monad m =>[(Text, HtmlT m ())] -> HtmlT m ()
charts cs = do
div_ [class_ "row"] $ sequence_ widgets
where
widgets = map widget cs
widget = \(titl, content) -> do
mkCol [(XS, 12), (MD, 12 `div` length cs)] $
div_ [class_ "widget"] $ do
div_ [class_ "widget-header"] (toHtml titl)
div_ [class_ "widget-body no-padding"] $
div_ [class_ "widget-content"] $
content
| diffusionkinetics/open | dashdo/src/Dashdo/Rdash.hs | mit | 3,346 | 0 | 27 | 887 | 1,043 | 532 | 511 | 74 | 1 |
module Generator where
import Data.Bits
import Data.Word
import Syntax
import Token
import Transform
opcodeOp :: Token -> Word8
opcodeOp tok = let (Just x) = lookup tok opList
in x
where opList =
[ (PUSHA, 0x0E),
(POPA, 0x0F),
(RET, 0x2A),
(NOP, 0x2B),
(IRET, 0x2E),
(HLT, 0x2F) ]
opcodeUnopReg :: Token -> Word8
opcodeUnopReg tok = let (Just x) = lookup tok opList
in x
where opList =
[ (PUSH8, 0x08),
(PUSH16, 0x0A),
(POP8, 0x0C),
(POP16, 0x0D),
(NOT, 0x22),
(CALL, 0x28),
(INT, 0x2C),
(JMP, 0x32),
(JE, 0x34),
(JNE, 0x36),
(JG, 0x38),
(JGE, 0x3A),
(JL, 0x3C),
(JLE, 0x3E) ]
opcodeUnopImm :: Token -> Word8
opcodeUnopImm tok = let (Just x) = lookup tok opList
in x
where opList =
[ (PUSH8, 0x09),
(PUSH16, 0x0B),
(CALL, 0x29),
(INT, 0x2D),
(JMP, 0x33),
(JE, 0x35),
(JNE, 0x37),
(JG, 0x39),
(JGE, 0x3B),
(JL, 0x3D),
(JLE, 0x3F) ]
opcodeBinopRegReg :: Token -> Word8
opcodeBinopRegReg tok = let (Just x) = lookup tok opList
in x
where opList =
[ (MOV, 0x00),
(ADD, 0x10),
(SUB, 0x12),
(MUL, 0x14),
(DIV, 0x16),
(SHR, 0x18),
(SHL, 0x1A),
(AND, 0x1C),
(OR, 0x1E),
(XOR, 0x20),
(CMP, 0x30) ]
opcodeBinopRegImm :: Token -> Word8
opcodeBinopRegImm tok = let (Just x) = lookup tok opList
in x
where opList =
[ (MOV, 0x01),
(ADD, 0x11),
(SUB, 0x13),
(MUL, 0x15),
(DIV, 0x17),
(SHR, 0x19),
(SHL, 0x1B),
(AND, 0x1D),
(OR, 0x1F),
(XOR, 0x21),
(CMP, 0x31) ]
opcodeBinopAddrReg :: Token -> Word8
opcodeBinopAddrReg tok = let (Just x) = lookup tok opList
in x
where opList =
[ (LOAD8, 0x02),
(LOAD16, 0x03),
(STORE8, 0x04),
(STORE16, 0x06) ]
opcodeBinopAddrImm :: Token -> Word8
opcodeBinopAddrImm tok = let (Just x) = lookup tok opList
in x
where opList =
[ (STORE8, 0x05),
(STORE16, 0x07) ]
integerToWord16 :: Integer -> Word16
integerToWord16 i = fromInteger $ i .&. 0xFFFF
word16ToWord8 :: Word16 -> Word8
word16ToWord8 i = fromInteger $ toInteger i .&. 0xFF
word16ToBytes :: Word16 -> [Word8]
word16ToBytes w = higher : lower : []
where higher = word16ToWord8 $ (w .&. 0xFF00) `shift` (-8)
lower = word16ToWord8 $ (w .&. 0x00FF)
integerToBytes :: Integer -> [Word8]
integerToBytes = word16ToBytes . integerToWord16
integerToWord8 :: Integer -> Word8
integerToWord8 i = fromInteger $ i .&. 0xFF
word8ToInt :: Word8 -> Int
word8ToInt = fromIntegral
immToBytes :: Imm -> [Word8]
immToBytes (Literal i) = integerToBytes i
addrToBytes :: Addr -> [Word8]
addrToBytes (AddrReg r) = (0x80 .|. integerToWord8 r) : [0x00, 0x00]
addrToBytes (AddrConstant i) = 0x00 : immToBytes i
magicNumber :: [Word8]
magicNumber = [0x26, 0x03, 0x20, 0x13]
generateHeader :: [AST] -> [Word8]
generateHeader ast = len ++ [0x00, 0x00] ++ rawHeaders
where len = integerToBytes . toInteger $ length headers
positions = readPositions 0 ast
headers = getHeader `fmap` positions
rawHeaders = concat $ flattenHeader `fmap` headers
flattenHeader (a, b, c) = a ++ b ++ c ++ [0x00, 0x00]
getHeader :: (Pos, Pos, [AST]) -> ([Word8], [Word8], [Word8])
getHeader (raw, mapped, ast) = (integerToBytes raw, integerToBytes mapped, size)
where size = integerToBytes $ getSize 0 remainingAst
remainingAst = takeWhile p ast
p (Position _) = False
p _ = True
assemble :: [AST] -> [Word8]
assemble ast = magicNumber ++ generateHeader ast ++ assembleAST nAst
where nAst = removePositions ast
assembleAST :: [AST] -> [Word8]
assembleAST [] = []
assembleAST (Syntax.EOF:_) = []
assembleAST (Op tok:xs) = opcodeOp tok : 0x00 : assembleAST xs
assembleAST (BinopRegReg op reg0 reg1 : xs) = opcodeBinopRegReg op :
integerToWord8 reg0 : 0x00 : integerToWord8 reg1 : assembleAST xs
assembleAST (BinopRegImm op reg imm : xs) = opcodeBinopRegImm op :
integerToWord8 reg : immToBytes imm ++ assembleAST xs
assembleAST (BinopAddrReg op addr reg : xs) = opcodeBinopAddrReg op :
addrToBytes addr ++ [0x00, integerToWord8 reg] ++ assembleAST xs
assembleAST (BinopAddrImm op addr imm : xs) = opcodeBinopAddrImm op :
addrToBytes addr ++ immToBytes imm ++ assembleAST xs
assembleAST (UnopReg op reg : xs) = opcodeUnopReg op : integerToWord8 reg :
assembleAST xs
assembleAST (UnopImm op imm : xs) = opcodeUnopImm op : 0x00 : immToBytes imm ++
assembleAST xs
assembleAST (Syntax.DB (Literal d) : xs) = integerToWord8 d : assembleAST xs
assembleAST (Syntax.DW (Literal d) : xs) = integerToBytes d ++ assembleAST xs
assembleAST (Syntax.RESB : xs) = 0x00 : assembleAST xs
assembleAST (Position _ : xs) = assembleAST xs
| dosenfrucht/mcasm | src/Generator.hs | gpl-2.0 | 5,353 | 0 | 10 | 1,721 | 1,951 | 1,082 | 869 | 150 | 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.ElasticTranscoder.ListJobsByStatus
-- 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)
--
-- The ListJobsByStatus operation gets a list of jobs that have a specified
-- status. The response body contains one element for each job that
-- satisfies the search criteria.
--
-- /See:/ <http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/ListJobsByStatus.html AWS API Reference> for ListJobsByStatus.
--
-- This operation returns paginated results.
module Network.AWS.ElasticTranscoder.ListJobsByStatus
(
-- * Creating a Request
listJobsByStatus
, ListJobsByStatus
-- * Request Lenses
, ljbsAscending
, ljbsPageToken
, ljbsStatus
-- * Destructuring the Response
, listJobsByStatusResponse
, ListJobsByStatusResponse
-- * Response Lenses
, ljbsrsNextPageToken
, ljbsrsJobs
, ljbsrsResponseStatus
) where
import Network.AWS.ElasticTranscoder.Types
import Network.AWS.ElasticTranscoder.Types.Product
import Network.AWS.Pager
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | The 'ListJobsByStatusRequest' structure.
--
-- /See:/ 'listJobsByStatus' smart constructor.
data ListJobsByStatus = ListJobsByStatus'
{ _ljbsAscending :: !(Maybe Text)
, _ljbsPageToken :: !(Maybe Text)
, _ljbsStatus :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListJobsByStatus' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ljbsAscending'
--
-- * 'ljbsPageToken'
--
-- * 'ljbsStatus'
listJobsByStatus
:: Text -- ^ 'ljbsStatus'
-> ListJobsByStatus
listJobsByStatus pStatus_ =
ListJobsByStatus'
{ _ljbsAscending = Nothing
, _ljbsPageToken = Nothing
, _ljbsStatus = pStatus_
}
-- | To list jobs in chronological order by the date and time that they were
-- submitted, enter 'true'. To list jobs in reverse chronological order,
-- enter 'false'.
ljbsAscending :: Lens' ListJobsByStatus (Maybe Text)
ljbsAscending = lens _ljbsAscending (\ s a -> s{_ljbsAscending = a});
-- | When Elastic Transcoder returns more than one page of results, use
-- 'pageToken' in subsequent 'GET' requests to get each successive page of
-- results.
ljbsPageToken :: Lens' ListJobsByStatus (Maybe Text)
ljbsPageToken = lens _ljbsPageToken (\ s a -> s{_ljbsPageToken = a});
-- | To get information about all of the jobs associated with the current AWS
-- account that have a given status, specify the following status:
-- 'Submitted', 'Progressing', 'Complete', 'Canceled', or 'Error'.
ljbsStatus :: Lens' ListJobsByStatus Text
ljbsStatus = lens _ljbsStatus (\ s a -> s{_ljbsStatus = a});
instance AWSPager ListJobsByStatus where
page rq rs
| stop (rs ^. ljbsrsNextPageToken) = Nothing
| stop (rs ^. ljbsrsJobs) = Nothing
| otherwise =
Just $ rq &
ljbsPageToken .~ rs ^. ljbsrsNextPageToken
instance AWSRequest ListJobsByStatus where
type Rs ListJobsByStatus = ListJobsByStatusResponse
request = get elasticTranscoder
response
= receiveJSON
(\ s h x ->
ListJobsByStatusResponse' <$>
(x .?> "NextPageToken") <*> (x .?> "Jobs" .!@ mempty)
<*> (pure (fromEnum s)))
instance ToHeaders ListJobsByStatus where
toHeaders = const mempty
instance ToPath ListJobsByStatus where
toPath ListJobsByStatus'{..}
= mconcat
["/2012-09-25/jobsByStatus/", toBS _ljbsStatus]
instance ToQuery ListJobsByStatus where
toQuery ListJobsByStatus'{..}
= mconcat
["Ascending" =: _ljbsAscending,
"PageToken" =: _ljbsPageToken]
-- | The 'ListJobsByStatusResponse' structure.
--
-- /See:/ 'listJobsByStatusResponse' smart constructor.
data ListJobsByStatusResponse = ListJobsByStatusResponse'
{ _ljbsrsNextPageToken :: !(Maybe Text)
, _ljbsrsJobs :: !(Maybe [Job'])
, _ljbsrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListJobsByStatusResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ljbsrsNextPageToken'
--
-- * 'ljbsrsJobs'
--
-- * 'ljbsrsResponseStatus'
listJobsByStatusResponse
:: Int -- ^ 'ljbsrsResponseStatus'
-> ListJobsByStatusResponse
listJobsByStatusResponse pResponseStatus_ =
ListJobsByStatusResponse'
{ _ljbsrsNextPageToken = Nothing
, _ljbsrsJobs = Nothing
, _ljbsrsResponseStatus = pResponseStatus_
}
-- | A value that you use to access the second and subsequent pages of
-- results, if any. When the jobs in the specified pipeline fit on one page
-- or when you\'ve reached the last page of results, the value of
-- 'NextPageToken' is 'null'.
ljbsrsNextPageToken :: Lens' ListJobsByStatusResponse (Maybe Text)
ljbsrsNextPageToken = lens _ljbsrsNextPageToken (\ s a -> s{_ljbsrsNextPageToken = a});
-- | An array of 'Job' objects that have the specified status.
ljbsrsJobs :: Lens' ListJobsByStatusResponse [Job']
ljbsrsJobs = lens _ljbsrsJobs (\ s a -> s{_ljbsrsJobs = a}) . _Default . _Coerce;
-- | The response status code.
ljbsrsResponseStatus :: Lens' ListJobsByStatusResponse Int
ljbsrsResponseStatus = lens _ljbsrsResponseStatus (\ s a -> s{_ljbsrsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-elastictranscoder/gen/Network/AWS/ElasticTranscoder/ListJobsByStatus.hs | mpl-2.0 | 6,124 | 0 | 13 | 1,273 | 880 | 518 | 362 | 103 | 1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="az-AZ">
<title>Code Dx | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/codedx/src/main/javahelp/org/zaproxy/zap/extension/codedx/resources/help_az_AZ/helpset_az_AZ.hs | apache-2.0 | 969 | 80 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
{-# LANGUAGE RankNTypes, FlexibleContexts #-}
{-| Implementation of functions specific to configuration management.
-}
{-
Copyright (C) 2013, 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.WConfd.ConfigWriter
( loadConfigFromFile
, readConfig
, writeConfig
, saveConfigAsyncTask
, distMCsAsyncTask
, distSSConfAsyncTask
) where
import Control.Applicative
import Control.Monad.Base
import Control.Monad.Error
import qualified Control.Monad.State.Strict as S
import Control.Monad.Trans.Control
import Data.Monoid
import Ganeti.BasicTypes
import Ganeti.Errors
import Ganeti.Config
import Ganeti.Logging
import Ganeti.Objects
import Ganeti.Rpc
import Ganeti.Runtime
import Ganeti.Utils
import Ganeti.Utils.Atomic
import Ganeti.Utils.AsyncWorker
import Ganeti.WConfd.ConfigState
import Ganeti.WConfd.Monad
import Ganeti.WConfd.Ssconf
-- | Loads the configuration from the file, if it hasn't been loaded yet.
-- The function is internal and isn't thread safe.
loadConfigFromFile :: FilePath
-> ResultG (ConfigData, FStat)
loadConfigFromFile path = withLockedFile path $ \_ -> do
stat <- liftBase $ getFStat path
cd <- mkResultT (loadConfig path)
return (cd, stat)
-- | Writes the current configuration to the file. The function isn't thread
-- safe.
-- Neither distributes the configuration (to nodes and ssconf) nor
-- updates the serial number.
writeConfigToFile :: (MonadBase IO m, MonadError GanetiException m, MonadLog m)
=> ConfigData -> FilePath -> FStat -> m FStat
writeConfigToFile cfg path oldstat = do
logDebug $ "Async. config. writer: Commencing write\
\ serial no " ++ show (serialOf cfg)
r <- toErrorBase $ atomicUpdateLockedFile_ path oldstat doWrite
logDebug "Async. config. writer: written"
return r
where
doWrite fname fh = do
setOwnerAndGroupFromNames fname GanetiWConfd
(DaemonGroup GanetiConfd)
setOwnerWGroupR fname
saveConfig fh cfg
-- Reads the current configuration state in the 'WConfdMonad'.
readConfig :: WConfdMonad ConfigData
readConfig = csConfigData <$> readConfigState
-- Replaces the current configuration state within the 'WConfdMonad'.
writeConfig :: ConfigData -> WConfdMonad ()
writeConfig cd = modifyConfigState $ const ((), mkConfigState cd)
-- * Asynchronous tasks
-- | Runs the given action on success, or logs an error on failure.
finishOrLog :: (Show e, MonadLog m)
=> Priority
-> String
-> (a -> m ())
-> GenericResult e a
-> m ()
finishOrLog logPrio logPrefix =
genericResult (logAt logPrio . (++) (logPrefix ++ ": ") . show)
-- | Creates a stateless asynchronous task that handles errors in its actions.
mkStatelessAsyncTask :: (MonadBaseControl IO m, MonadLog m, Show e, Monoid i)
=> Priority
-> String
-> (i -> ResultT e m ())
-> m (AsyncWorker i ())
mkStatelessAsyncTask logPrio logPrefix action =
mkAsyncWorker $ runResultT . action
>=> finishOrLog logPrio logPrefix return
-- | Creates an asynchronous task that handles errors in its actions.
-- If an error occurs, it's logged and the internal state remains unchanged.
mkStatefulAsyncTask :: (MonadBaseControl IO m, MonadLog m, Show e, Monoid i)
=> Priority
-> String
-> s
-> (s -> i -> ResultT e m s)
-> m (AsyncWorker i ())
mkStatefulAsyncTask logPrio logPrefix start action =
flip S.evalStateT start . mkAsyncWorker $ \i ->
S.get >>= lift . runResultT . flip action i
>>= finishOrLog logPrio logPrefix S.put -- put on success
-- | Construct an asynchronous worker whose action is to save the
-- configuration to the master file.
-- The worker's action reads the configuration using the given @IO@ action
-- and uses 'FStat' to check if the configuration hasn't been modified by
-- another process.
--
-- If 'Any' of the input requests is true, given additional worker
-- will be executed synchronously after sucessfully writing the configuration
-- file. Otherwise, they'll be just triggered asynchronously.
saveConfigAsyncTask :: FilePath -- ^ Path to the config file
-> FStat -- ^ The initial state of the config. file
-> IO ConfigState -- ^ An action to read the current config
-> [AsyncWorker () ()] -- ^ Workers to be triggered
-- afterwards
-> ResultG (AsyncWorker Any ())
saveConfigAsyncTask fpath fstat cdRef workers =
lift . mkStatefulAsyncTask
EMERGENCY "Can't write the master configuration file" fstat
$ \oldstat (Any flush) -> do
cd <- liftBase (csConfigData `liftM` cdRef)
writeConfigToFile cd fpath oldstat
<* if flush then logDebug "Running distribution synchronously"
>> triggerAndWaitMany_ workers
else logDebug "Running distribution asynchronously"
>> mapM trigger_ workers
-- | Performs a RPC call on the given list of nodes and logs any failures.
-- If any of the calls fails, fail the computation with 'failError'.
execRpcCallAndLog :: (Rpc a b) => [Node] -> a -> ResultG ()
execRpcCallAndLog nodes req = do
rs <- liftIO $ executeRpcCall nodes req
es <- logRpcErrors rs
unless (null es) $ failError "At least one of the RPC calls failed"
-- | Construct an asynchronous worker whose action is to distribute the
-- configuration to master candidates.
distMCsAsyncTask :: RuntimeEnts
-> FilePath -- ^ Path to the config file
-> IO ConfigState -- ^ An action to read the current config
-> ResultG (AsyncWorker () ())
distMCsAsyncTask ents cpath cdRef =
lift . mkStatelessAsyncTask ERROR "Can't distribute the configuration\
\ to master candidates"
$ \_ -> do
cd <- liftBase (csConfigData <$> cdRef) :: ResultG ConfigData
logDebug $ "Distributing the configuration to master candidates,\
\ serial no " ++ show (serialOf cd)
fupload <- prepareRpcCallUploadFile ents cpath
execRpcCallAndLog (getMasterCandidates cd) fupload
logDebug "Successfully finished distributing the configuration"
-- | Construct an asynchronous worker whose action is to construct SSConf
-- and distribute it to master candidates.
-- The worker's action reads the configuration using the given @IO@ action,
-- computes the current SSConf, compares it to the previous version, and
-- if different, distributes it.
distSSConfAsyncTask
:: IO ConfigState -- ^ An action to read the current config
-> ResultG (AsyncWorker () ())
distSSConfAsyncTask cdRef =
lift . mkStatefulAsyncTask ERROR "Can't distribute Ssconf" emptySSConf
$ \oldssc _ -> do
cd <- liftBase (csConfigData <$> cdRef) :: ResultG ConfigData
let ssc = mkSSConf cd
if oldssc == ssc
then logDebug "SSConf unchanged, not distributing"
else do
logDebug $ "Starting the distribution of SSConf\
\ serial no " ++ show (serialOf cd)
execRpcCallAndLog (getOnlineNodes cd)
(RpcCallWriteSsconfFiles ssc)
logDebug "Successfully finished distributing SSConf"
return ssc
| bitemyapp/ganeti | src/Ganeti/WConfd/ConfigWriter.hs | bsd-2-clause | 8,861 | 0 | 15 | 2,264 | 1,358 | 699 | 659 | -1 | -1 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE OverloadedStrings #-}
module Generate.Index (toHtml, getInfo, getPkg) where
import Control.Monad
import Control.Monad.Except (ExceptT, liftIO, runExceptT, throwError)
import Data.Aeson as Json
import qualified Data.ByteString.Lazy.UTF8 as BSU8
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import qualified Elm.Package as Pkg
import qualified Elm.Package.Description as Desc
import qualified Elm.Package.Paths as Paths
import qualified Elm.Package.Solution as S
import System.Directory (doesDirectoryExist, doesFileExist, getDirectoryContents)
import System.FilePath ((</>), splitDirectories, takeExtension)
import qualified Text.Blaze.Html5 as H
import qualified Generate.Help as Help
import qualified StaticFiles
-- INFO
data Info = Info
{ _pwd :: [String]
, _dirs :: [FilePath]
, _files :: [(FilePath, Bool)]
, _pkg :: Maybe PackageInfo
, _readme :: Maybe String
}
data PackageInfo = PackageInfo
{ _version :: Pkg.Version
, _repository :: String
, _summary :: String
, _dependencies :: [(Pkg.Name, Pkg.Version)]
}
-- TO JSON
instance ToJSON Info where
toJSON info =
object
[ "pwd" .= _pwd info
, "dirs" .= _dirs info
, "files" .= _files info
, "pkg" .= _pkg info
, "readme" .= _readme info
]
instance ToJSON PackageInfo where
toJSON pkgInfo =
object
[ "version" .= _version pkgInfo
, "repository" .= _repository pkgInfo
, "summary" .= _summary pkgInfo
, "dependencies" .= _dependencies pkgInfo
]
-- GENERATE HTML
toHtml :: Info -> H.Html
toHtml info@(Info pwd _ _ _ _) =
Help.makeHtml
(List.intercalate "/" ("~" : pwd))
("/" ++ StaticFiles.indexPath)
("Elm.Index.fullscreen(" ++ BSU8.toString (Json.encode info) ++ ");")
-- GET INFO FOR THIS LOCATION
getInfo :: FilePath -> IO Info
getInfo directory =
do packageInfo <- getPackageInfo
(dirs, files) <- getDirectoryInfo directory
readme <- getReadme directory
return $ Info
{ _pwd = toPwd directory
, _dirs = dirs
, _files = files
, _pkg = packageInfo
, _readme = readme
}
toPwd :: FilePath -> [String]
toPwd directory =
case splitDirectories directory of
"." : path ->
path
path ->
path
getPackageInfo :: IO (Maybe PackageInfo)
getPackageInfo =
fmap (either (const Nothing) Just) $ runExceptT $
do
desc <- getDescription
solutionExists <- liftIO (doesFileExist Paths.solvedDependencies)
when (not solutionExists) (throwError "file not found")
solution <- S.read id Paths.solvedDependencies
let publicSolution =
Map.intersection solution (Map.fromList (Desc.dependencies desc))
return $ PackageInfo
{ _version = Desc.version desc
, _repository = Desc.repo desc
, _summary = Desc.summary desc
, _dependencies = Map.toList publicSolution
}
getDescription :: ExceptT String IO Desc.Description
getDescription =
do descExists <- liftIO (doesFileExist Paths.description)
when (not descExists) (throwError "file not found")
Desc.read id Paths.description
getPkg :: IO Pkg.Name
getPkg =
fmap
(either (const Pkg.dummyName) Desc.name)
(runExceptT getDescription)
getDirectoryInfo :: FilePath -> IO ([FilePath], [(FilePath, Bool)])
getDirectoryInfo directory =
do directoryContents <-
getDirectoryContents directory
allDirectories <-
filterM (doesDirectoryExist . (directory </>)) directoryContents
let isLegit name =
List.notElem name [".", "..", "elm-stuff"]
let directories =
filter isLegit allDirectories
rawFiles <-
filterM (doesFileExist . (directory </>)) directoryContents
files <- mapM (inspectFile directory) rawFiles
return (directories, files)
inspectFile :: FilePath -> FilePath -> IO (FilePath, Bool)
inspectFile directory filePath =
if takeExtension filePath == ".elm" then
do source <- Text.readFile (directory </> filePath)
let hasMain = Text.isInfixOf "\nmain " source
return (filePath, hasMain)
else
return (filePath, False)
getReadme :: FilePath -> IO (Maybe String)
getReadme directory =
do exists <- doesFileExist (directory </> "README.md")
if exists
then
Just `fmap` readFile (directory </> "README.md")
else
return Nothing
| rehno-lindeque/elm-reactor | src/backend/Generate/Index.hs | bsd-3-clause | 4,630 | 0 | 16 | 1,153 | 1,302 | 706 | 596 | 122 | 2 |
{-
(c) The University of Glasgow, 1994-2006
Core pass to saturate constructors and PrimOps
-}
{-# LANGUAGE BangPatterns, CPP #-}
module CorePrep (
corePrepPgm, corePrepExpr, cvtLitInteger,
lookupMkIntegerName, lookupIntegerSDataConName
) where
#include "HsVersions.h"
import OccurAnal
import HscTypes
import PrelNames
import MkId ( realWorldPrimId )
import CoreUtils
import CoreArity
import CoreFVs
import CoreMonad ( CoreToDo(..) )
import CoreLint ( endPassIO )
import CoreSyn
import CoreSubst
import MkCore hiding( FloatBind(..) ) -- We use our own FloatBind here
import Type
import Literal
import Coercion
import TcEnv
import TyCon
import Demand
import Var
import VarSet
import VarEnv
import Id
import IdInfo
import TysWiredIn
import DataCon
import PrimOp
import BasicTypes
import Module
import UniqSupply
import Maybes
import OrdList
import ErrUtils
import DynFlags
import Util
import Pair
import Outputable
import Platform
import FastString
import Config
import Name ( NamedThing(..), nameSrcSpan )
import SrcLoc ( SrcSpan(..), realSrcLocSpan, mkRealSrcLoc )
import Data.Bits
import MonadUtils ( mapAccumLM )
import Data.List ( mapAccumL )
import Control.Monad
{-
-- ---------------------------------------------------------------------------
-- Overview
-- ---------------------------------------------------------------------------
The goal of this pass is to prepare for code generation.
1. Saturate constructor and primop applications.
2. Convert to A-normal form; that is, function arguments
are always variables.
* Use case for strict arguments:
f E ==> case E of x -> f x
(where f is strict)
* Use let for non-trivial lazy arguments
f E ==> let x = E in f x
(were f is lazy and x is non-trivial)
3. Similarly, convert any unboxed lets into cases.
[I'm experimenting with leaving 'ok-for-speculation'
rhss in let-form right up to this point.]
4. Ensure that *value* lambdas only occur as the RHS of a binding
(The code generator can't deal with anything else.)
Type lambdas are ok, however, because the code gen discards them.
5. [Not any more; nuked Jun 2002] Do the seq/par munging.
6. Clone all local Ids.
This means that all such Ids are unique, rather than the
weaker guarantee of no clashes which the simplifier provides.
And that is what the code generator needs.
We don't clone TyVars or CoVars. The code gen doesn't need that,
and doing so would be tiresome because then we'd need
to substitute in types and coercions.
7. Give each dynamic CCall occurrence a fresh unique; this is
rather like the cloning step above.
8. Inject bindings for the "implicit" Ids:
* Constructor wrappers
* Constructor workers
We want curried definitions for all of these in case they
aren't inlined by some caller.
9. Replace (lazy e) by e. See Note [lazyId magic] in MkId.hs
Also replace (noinline e) by e.
10. Convert (LitInteger i t) into the core representation
for the Integer i. Normally this uses mkInteger, but if
we are using the integer-gmp implementation then there is a
special case where we use the S# constructor for Integers that
are in the range of Int.
11. Uphold tick consistency while doing this: We move ticks out of
(non-type) applications where we can, and make sure that we
annotate according to scoping rules when floating.
This is all done modulo type applications and abstractions, so that
when type erasure is done for conversion to STG, we don't end up with
any trivial or useless bindings.
Invariants
~~~~~~~~~~
Here is the syntax of the Core produced by CorePrep:
Trivial expressions
triv ::= lit | var
| triv ty | /\a. triv
| truv co | /\c. triv | triv |> co
Applications
app ::= lit | var | app triv | app ty | app co | app |> co
Expressions
body ::= app
| let(rec) x = rhs in body -- Boxed only
| case body of pat -> body
| /\a. body | /\c. body
| body |> co
Right hand sides (only place where value lambdas can occur)
rhs ::= /\a.rhs | \x.rhs | body
We define a synonym for each of these non-terminals. Functions
with the corresponding name produce a result in that syntax.
-}
type CpeTriv = CoreExpr -- Non-terminal 'triv'
type CpeApp = CoreExpr -- Non-terminal 'app'
type CpeBody = CoreExpr -- Non-terminal 'body'
type CpeRhs = CoreExpr -- Non-terminal 'rhs'
{-
************************************************************************
* *
Top level stuff
* *
************************************************************************
-}
corePrepPgm :: HscEnv -> Module -> ModLocation -> CoreProgram -> [TyCon]
-> IO CoreProgram
corePrepPgm hsc_env this_mod mod_loc binds data_tycons =
withTiming (pure dflags)
(text "CorePrep"<+>brackets (ppr this_mod))
(const ()) $ do
us <- mkSplitUniqSupply 's'
initialCorePrepEnv <- mkInitialCorePrepEnv dflags hsc_env
let implicit_binds = mkDataConWorkers dflags mod_loc data_tycons
-- NB: we must feed mkImplicitBinds through corePrep too
-- so that they are suitably cloned and eta-expanded
binds_out = initUs_ us $ do
floats1 <- corePrepTopBinds initialCorePrepEnv binds
floats2 <- corePrepTopBinds initialCorePrepEnv implicit_binds
return (deFloatTop (floats1 `appendFloats` floats2))
endPassIO hsc_env alwaysQualify CorePrep binds_out []
return binds_out
where
dflags = hsc_dflags hsc_env
corePrepExpr :: DynFlags -> HscEnv -> CoreExpr -> IO CoreExpr
corePrepExpr dflags hsc_env expr =
withTiming (pure dflags) (text "CorePrep [expr]") (const ()) $ do
us <- mkSplitUniqSupply 's'
initialCorePrepEnv <- mkInitialCorePrepEnv dflags hsc_env
let new_expr = initUs_ us (cpeBodyNF initialCorePrepEnv expr)
dumpIfSet_dyn dflags Opt_D_dump_prep "CorePrep" (ppr new_expr)
return new_expr
corePrepTopBinds :: CorePrepEnv -> [CoreBind] -> UniqSM Floats
-- Note [Floating out of top level bindings]
corePrepTopBinds initialCorePrepEnv binds
= go initialCorePrepEnv binds
where
go _ [] = return emptyFloats
go env (bind : binds) = do (env', bind') <- cpeBind TopLevel env bind
binds' <- go env' binds
return (bind' `appendFloats` binds')
mkDataConWorkers :: DynFlags -> ModLocation -> [TyCon] -> [CoreBind]
-- See Note [Data constructor workers]
-- c.f. Note [Injecting implicit bindings] in TidyPgm
mkDataConWorkers dflags mod_loc data_tycons
= [ NonRec id (tick_it (getName data_con) (Var id))
-- The ice is thin here, but it works
| tycon <- data_tycons, -- CorePrep will eta-expand it
data_con <- tyConDataCons tycon,
let id = dataConWorkId data_con
]
where
-- If we want to generate debug info, we put a source note on the
-- worker. This is useful, especially for heap profiling.
tick_it name
| debugLevel dflags == 0 = id
| RealSrcSpan span <- nameSrcSpan name = tick span
| Just file <- ml_hs_file mod_loc = tick (span1 file)
| otherwise = tick (span1 "???")
where tick span = Tick (SourceNote span $ showSDoc dflags (ppr name))
span1 file = realSrcLocSpan $ mkRealSrcLoc (mkFastString file) 1 1
{-
Note [Floating out of top level bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NB: we do need to float out of top-level bindings
Consider x = length [True,False]
We want to get
s1 = False : []
s2 = True : s1
x = length s2
We return a *list* of bindings, because we may start with
x* = f (g y)
where x is demanded, in which case we want to finish with
a = g y
x* = f a
And then x will actually end up case-bound
Note [CafInfo and floating]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
What happens when we try to float bindings to the top level? At this
point all the CafInfo is supposed to be correct, and we must make certain
that is true of the new top-level bindings. There are two cases
to consider
a) The top-level binding is marked asCafRefs. In that case we are
basically fine. The floated bindings had better all be lazy lets,
so they can float to top level, but they'll all have HasCafRefs
(the default) which is safe.
b) The top-level binding is marked NoCafRefs. This really happens
Example. CoreTidy produces
$fApplicativeSTM [NoCafRefs] = D:Alternative retry# ...blah...
Now CorePrep has to eta-expand to
$fApplicativeSTM = let sat = \xy. retry x y
in D:Alternative sat ...blah...
So what we *want* is
sat [NoCafRefs] = \xy. retry x y
$fApplicativeSTM [NoCafRefs] = D:Alternative sat ...blah...
So, gruesomely, we must set the NoCafRefs flag on the sat bindings,
*and* substutite the modified 'sat' into the old RHS.
It should be the case that 'sat' is itself [NoCafRefs] (a value, no
cafs) else the original top-level binding would not itself have been
marked [NoCafRefs]. The DEBUG check in CoreToStg for
consistentCafInfo will find this.
This is all very gruesome and horrible. It would be better to figure
out CafInfo later, after CorePrep. We'll do that in due course.
Meanwhile this horrible hack works.
Note [Data constructor workers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Create any necessary "implicit" bindings for data con workers. We
create the rather strange (non-recursive!) binding
$wC = \x y -> $wC x y
i.e. a curried constructor that allocates. This means that we can
treat the worker for a constructor like any other function in the rest
of the compiler. The point here is that CoreToStg will generate a
StgConApp for the RHS, rather than a call to the worker (which would
give a loop). As Lennart says: the ice is thin here, but it works.
Hmm. Should we create bindings for dictionary constructors? They are
always fully applied, and the bindings are just there to support
partial applications. But it's easier to let them through.
Note [Dead code in CorePrep]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Imagine that we got an input program like this (see Trac #4962):
f :: Show b => Int -> (Int, b -> Maybe Int -> Int)
f x = (g True (Just x) + g () (Just x), g)
where
g :: Show a => a -> Maybe Int -> Int
g _ Nothing = x
g y (Just z) = if z > 100 then g y (Just (z + length (show y))) else g y unknown
After specialisation and SpecConstr, we would get something like this:
f :: Show b => Int -> (Int, b -> Maybe Int -> Int)
f x = (g$Bool_True_Just x + g$Unit_Unit_Just x, g)
where
{-# RULES g $dBool = g$Bool
g $dUnit = g$Unit #-}
g = ...
{-# RULES forall x. g$Bool True (Just x) = g$Bool_True_Just x #-}
g$Bool = ...
{-# RULES forall x. g$Unit () (Just x) = g$Unit_Unit_Just x #-}
g$Unit = ...
g$Bool_True_Just = ...
g$Unit_Unit_Just = ...
Note that the g$Bool and g$Unit functions are actually dead code: they
are only kept alive by the occurrence analyser because they are
referred to by the rules of g, which is being kept alive by the fact
that it is used (unspecialised) in the returned pair.
However, at the CorePrep stage there is no way that the rules for g
will ever fire, and it really seems like a shame to produce an output
program that goes to the trouble of allocating a closure for the
unreachable g$Bool and g$Unit functions.
The way we fix this is to:
* In cloneBndr, drop all unfoldings/rules
* In deFloatTop, run a simple dead code analyser on each top-level
RHS to drop the dead local bindings. For that call to OccAnal, we
disable the binder swap, else the occurrence analyser sometimes
introduces new let bindings for cased binders, which lead to the bug
in #5433.
The reason we don't just OccAnal the whole output of CorePrep is that
the tidier ensures that all top-level binders are GlobalIds, so they
don't show up in the free variables any longer. So if you run the
occurrence analyser on the output of CoreTidy (or later) you e.g. turn
this program:
Rec {
f = ... f ...
}
Into this one:
f = ... f ...
(Since f is not considered to be free in its own RHS.)
************************************************************************
* *
The main code
* *
************************************************************************
-}
cpeBind :: TopLevelFlag -> CorePrepEnv -> CoreBind
-> UniqSM (CorePrepEnv, Floats)
cpeBind top_lvl env (NonRec bndr rhs)
= do { (_, bndr1) <- cpCloneBndr env bndr
; let dmd = idDemandInfo bndr
is_unlifted = isUnliftedType (idType bndr)
; (floats, bndr2, rhs2) <- cpePair top_lvl NonRecursive
dmd
is_unlifted
env bndr1 rhs
-- See Note [Inlining in CorePrep]
; if cpe_ExprIsTrivial rhs2 && isNotTopLevel top_lvl
then return (extendCorePrepEnvExpr env bndr rhs2, floats)
else do {
; let new_float = mkFloat dmd is_unlifted bndr2 rhs2
-- We want bndr'' in the envt, because it records
-- the evaluated-ness of the binder
; return (extendCorePrepEnv env bndr bndr2,
addFloat floats new_float) }}
cpeBind top_lvl env (Rec pairs)
= do { let (bndrs,rhss) = unzip pairs
; (env', bndrs1) <- cpCloneBndrs env (map fst pairs)
; stuff <- zipWithM (cpePair top_lvl Recursive topDmd False env') bndrs1 rhss
; let (floats_s, bndrs2, rhss2) = unzip3 stuff
all_pairs = foldrOL add_float (bndrs2 `zip` rhss2)
(concatFloats floats_s)
; return (extendCorePrepEnvList env (bndrs `zip` bndrs2),
unitFloat (FloatLet (Rec all_pairs))) }
where
-- Flatten all the floats, and the currrent
-- group into a single giant Rec
add_float (FloatLet (NonRec b r)) prs2 = (b,r) : prs2
add_float (FloatLet (Rec prs1)) prs2 = prs1 ++ prs2
add_float b _ = pprPanic "cpeBind" (ppr b)
---------------
cpePair :: TopLevelFlag -> RecFlag -> Demand -> Bool
-> CorePrepEnv -> Id -> CoreExpr
-> UniqSM (Floats, Id, CpeRhs)
-- Used for all bindings
cpePair top_lvl is_rec dmd is_unlifted env bndr rhs
= do { (floats1, rhs1) <- cpeRhsE env rhs
-- See if we are allowed to float this stuff out of the RHS
; (floats2, rhs2) <- float_from_rhs floats1 rhs1
-- Make the arity match up
; (floats3, rhs3)
<- if manifestArity rhs1 <= arity
then return (floats2, cpeEtaExpand arity rhs2)
else WARN(True, text "CorePrep: silly extra arguments:" <+> ppr bndr)
-- Note [Silly extra arguments]
(do { v <- newVar (idType bndr)
; let float = mkFloat topDmd False v rhs2
; return ( addFloat floats2 float
, cpeEtaExpand arity (Var v)) })
-- Wrap floating ticks
; let (floats4, rhs4) = wrapTicks floats3 rhs3
-- Record if the binder is evaluated
-- and otherwise trim off the unfolding altogether
-- It's not used by the code generator; getting rid of it reduces
-- heap usage and, since we may be changing uniques, we'd have
-- to substitute to keep it right
; let bndr' | exprIsHNF rhs3 = bndr `setIdUnfolding` evaldUnfolding
| otherwise = bndr `setIdUnfolding` noUnfolding
; return (floats4, bndr', rhs4) }
where
platform = targetPlatform (cpe_dynFlags env)
arity = idArity bndr -- We must match this arity
---------------------
float_from_rhs floats rhs
| isEmptyFloats floats = return (emptyFloats, rhs)
| isTopLevel top_lvl = float_top floats rhs
| otherwise = float_nested floats rhs
---------------------
float_nested floats rhs
| wantFloatNested is_rec dmd is_unlifted floats rhs
= return (floats, rhs)
| otherwise = dontFloat floats rhs
---------------------
float_top floats rhs -- Urhgh! See Note [CafInfo and floating]
| mayHaveCafRefs (idCafInfo bndr)
, allLazyTop floats
= return (floats, rhs)
-- So the top-level binding is marked NoCafRefs
| Just (floats', rhs') <- canFloatFromNoCaf platform floats rhs
= return (floats', rhs')
| otherwise
= dontFloat floats rhs
dontFloat :: Floats -> CpeRhs -> UniqSM (Floats, CpeBody)
-- Non-empty floats, but do not want to float from rhs
-- So wrap the rhs in the floats
-- But: rhs1 might have lambdas, and we can't
-- put them inside a wrapBinds
dontFloat floats1 rhs
= do { (floats2, body) <- rhsToBody rhs
; return (emptyFloats, wrapBinds floats1 $
wrapBinds floats2 body) }
{- Note [Silly extra arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we had this
f{arity=1} = \x\y. e
We *must* match the arity on the Id, so we have to generate
f' = \x\y. e
f = \x. f' x
It's a bizarre case: why is the arity on the Id wrong? Reason
(in the days of __inline_me__):
f{arity=0} = __inline_me__ (let v = expensive in \xy. e)
When InlineMe notes go away this won't happen any more. But
it seems good for CorePrep to be robust.
-}
-- ---------------------------------------------------------------------------
-- CpeRhs: produces a result satisfying CpeRhs
-- ---------------------------------------------------------------------------
cpeRhsE :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeRhs)
-- If
-- e ===> (bs, e')
-- then
-- e = let bs in e' (semantically, that is!)
--
-- For example
-- f (g x) ===> ([v = g x], f v)
cpeRhsE _env expr@(Type {}) = return (emptyFloats, expr)
cpeRhsE _env expr@(Coercion {}) = return (emptyFloats, expr)
cpeRhsE env (Lit (LitInteger i _))
= cpeRhsE env (cvtLitInteger (cpe_dynFlags env) (getMkIntegerId env)
(cpe_integerSDataCon env) i)
cpeRhsE _env expr@(Lit {}) = return (emptyFloats, expr)
cpeRhsE env expr@(Var {}) = cpeApp env expr
cpeRhsE env expr@(App {}) = cpeApp env expr
cpeRhsE env (Let bind expr)
= do { (env', new_binds) <- cpeBind NotTopLevel env bind
; (floats, body) <- cpeRhsE env' expr
; return (new_binds `appendFloats` floats, body) }
cpeRhsE env (Tick tickish expr)
| tickishPlace tickish == PlaceNonLam && tickish `tickishScopesLike` SoftScope
= do { (floats, body) <- cpeRhsE env expr
-- See [Floating Ticks in CorePrep]
; return (unitFloat (FloatTick tickish) `appendFloats` floats, body) }
| otherwise
= do { body <- cpeBodyNF env expr
; return (emptyFloats, mkTick tickish' body) }
where
tickish' | Breakpoint n fvs <- tickish
-- See also 'substTickish'
= Breakpoint n (map (getIdFromTrivialExpr . lookupCorePrepEnv env) fvs)
| otherwise
= tickish
cpeRhsE env (Cast expr co)
= do { (floats, expr') <- cpeRhsE env expr
; return (floats, Cast expr' co) }
cpeRhsE env expr@(Lam {})
= do { let (bndrs,body) = collectBinders expr
; (env', bndrs') <- cpCloneBndrs env bndrs
; body' <- cpeBodyNF env' body
; return (emptyFloats, mkLams bndrs' body') }
cpeRhsE env (Case scrut bndr ty alts)
= do { (floats, scrut') <- cpeBody env scrut
; let bndr1 = bndr `setIdUnfolding` evaldUnfolding
-- Record that the case binder is evaluated in the alternatives
; (env', bndr2) <- cpCloneBndr env bndr1
; alts' <- mapM (sat_alt env') alts
; return (floats, Case scrut' bndr2 ty alts') }
where
sat_alt env (con, bs, rhs)
= do { (env2, bs') <- cpCloneBndrs env bs
; rhs' <- cpeBodyNF env2 rhs
; return (con, bs', rhs') }
cvtLitInteger :: DynFlags -> Id -> Maybe DataCon -> Integer -> CoreExpr
-- Here we convert a literal Integer to the low-level
-- represenation. Exactly how we do this depends on the
-- library that implements Integer. If it's GMP we
-- use the S# data constructor for small literals.
-- See Note [Integer literals] in Literal
cvtLitInteger dflags _ (Just sdatacon) i
| inIntRange dflags i -- Special case for small integers
= mkConApp sdatacon [Lit (mkMachInt dflags i)]
cvtLitInteger dflags mk_integer _ i
= mkApps (Var mk_integer) [isNonNegative, ints]
where isNonNegative = if i < 0 then mkConApp falseDataCon []
else mkConApp trueDataCon []
ints = mkListExpr intTy (f (abs i))
f 0 = []
f x = let low = x .&. mask
high = x `shiftR` bits
in mkConApp intDataCon [Lit (mkMachInt dflags low)] : f high
bits = 31
mask = 2 ^ bits - 1
-- ---------------------------------------------------------------------------
-- CpeBody: produces a result satisfying CpeBody
-- ---------------------------------------------------------------------------
-- | Convert a 'CoreExpr' so it satisfies 'CpeBody', without
-- producing any floats (any generated floats are immediately
-- let-bound using 'wrapBinds'). Generally you want this, esp.
-- when you've reached a binding form (e.g., a lambda) and
-- floating any further would be incorrect.
cpeBodyNF :: CorePrepEnv -> CoreExpr -> UniqSM CpeBody
cpeBodyNF env expr
= do { (floats, body) <- cpeBody env expr
; return (wrapBinds floats body) }
-- | Convert a 'CoreExpr' so it satisfies 'CpeBody'; also produce
-- a list of 'Floats' which are being propagated upwards. In
-- fact, this function is used in only two cases: to
-- implement 'cpeBodyNF' (which is what you usually want),
-- and in the case when a let-binding is in a case scrutinee--here,
-- we can always float out:
--
-- case (let x = y in z) of ...
-- ==> let x = y in case z of ...
--
cpeBody :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeBody)
cpeBody env expr
= do { (floats1, rhs) <- cpeRhsE env expr
; (floats2, body) <- rhsToBody rhs
; return (floats1 `appendFloats` floats2, body) }
--------
rhsToBody :: CpeRhs -> UniqSM (Floats, CpeBody)
-- Remove top level lambdas by let-binding
rhsToBody (Tick t expr)
| tickishScoped t == NoScope -- only float out of non-scoped annotations
= do { (floats, expr') <- rhsToBody expr
; return (floats, mkTick t expr') }
rhsToBody (Cast e co)
-- You can get things like
-- case e of { p -> coerce t (\s -> ...) }
= do { (floats, e') <- rhsToBody e
; return (floats, Cast e' co) }
rhsToBody expr@(Lam {})
| Just no_lam_result <- tryEtaReducePrep bndrs body
= return (emptyFloats, no_lam_result)
| all isTyVar bndrs -- Type lambdas are ok
= return (emptyFloats, expr)
| otherwise -- Some value lambdas
= do { fn <- newVar (exprType expr)
; let rhs = cpeEtaExpand (exprArity expr) expr
float = FloatLet (NonRec fn rhs)
; return (unitFloat float, Var fn) }
where
(bndrs,body) = collectBinders expr
rhsToBody expr = return (emptyFloats, expr)
-- ---------------------------------------------------------------------------
-- CpeApp: produces a result satisfying CpeApp
-- ---------------------------------------------------------------------------
data CpeArg = CpeArg CoreArg
| CpeCast Coercion
| CpeTick (Tickish Id)
{- Note [runRW arg]
~~~~~~~~~~~~~~~~~~~
If we got, say
runRW# (case bot of {})
which happened in Trac #11291, we do /not/ want to turn it into
(case bot of {}) realWorldPrimId#
because that gives a panic in CoreToStg.myCollectArgs, which expects
only variables in function position. But if we are sure to make
runRW# strict (which we do in MkId), this can't happen
-}
cpeApp :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeRhs)
-- May return a CpeRhs because of saturating primops
cpeApp top_env expr
= do { let (terminal, args, depth) = collect_args expr
; cpe_app top_env terminal args depth
}
where
-- We have a nested data structure of the form
-- e `App` a1 `App` a2 ... `App` an, convert it into
-- (e, [CpeArg a1, CpeArg a2, ..., CpeArg an], depth)
-- We use 'CpeArg' because we may also need to
-- record casts and ticks. Depth counts the number
-- of arguments that would consume strictness information
-- (so, no type or coercion arguments.)
collect_args :: CoreExpr -> (CoreExpr, [CpeArg], Int)
collect_args e = go e [] 0
where
go (App fun arg) as depth
= go fun (CpeArg arg : as)
(if isTyCoArg arg then depth else depth + 1)
go (Cast fun co) as depth
= go fun (CpeCast co : as) depth
go (Tick tickish fun) as depth
| tickishPlace tickish == PlaceNonLam
&& tickish `tickishScopesLike` SoftScope
= go fun (CpeTick tickish : as) depth
go terminal as depth = (terminal, as, depth)
cpe_app :: CorePrepEnv
-> CoreExpr
-> [CpeArg]
-> Int
-> UniqSM (Floats, CpeRhs)
cpe_app env (Var f) (CpeArg Type{} : CpeArg arg : args) depth
| f `hasKey` lazyIdKey -- Replace (lazy a) with a, and
|| f `hasKey` noinlineIdKey -- Replace (noinline a) with a
-- Consider the code:
--
-- lazy (f x) y
--
-- We need to make sure that we need to recursively collect arguments on
-- "f x", otherwise we'll float "f x" out (it's not a variable) and
-- end up with this awful -ddump-prep:
--
-- case f x of f_x {
-- __DEFAULT -> f_x y
-- }
--
-- rather than the far superior "f x y". Test case is par01.
= let (terminal, args', depth') = collect_args arg
in cpe_app env terminal (args' ++ args) (depth + depth' - 1)
cpe_app env (Var f) [CpeArg _runtimeRep@Type{}, CpeArg _type@Type{}, CpeArg arg] 1
| f `hasKey` runRWKey
-- Replace (runRW# f) by (f realWorld#), beta reducing if possible (this
-- is why we return a CorePrepEnv as well)
= case arg of
Lam s body -> cpe_app (extendCorePrepEnv env s realWorldPrimId) body [] 0
_ -> cpe_app env arg [CpeArg (Var realWorldPrimId)] 1
cpe_app env (Var v) args depth
= do { v1 <- fiddleCCall v
; let e2 = lookupCorePrepEnv env v1
hd = getIdFromTrivialExpr_maybe e2
-- NB: depth from collect_args is right, because e2 is a trivial expression
-- and thus its embedded Id *must* be at the same depth as any
-- Apps it is under are type applications only (c.f.
-- cpe_ExprIsTrivial). But note that we need the type of the
-- expression, not the id.
; (app, floats) <- rebuild_app args e2 (exprType e2) emptyFloats stricts
; mb_saturate hd app floats depth }
where
stricts = case idStrictness v of
StrictSig (DmdType _ demands _)
| listLengthCmp demands depth /= GT -> demands
-- length demands <= depth
| otherwise -> []
-- If depth < length demands, then we have too few args to
-- satisfy strictness info so we have to ignore all the
-- strictness info, e.g. + (error "urk")
-- Here, we can't evaluate the arg strictly, because this
-- partial application might be seq'd
-- We inlined into something that's not a var and has no args.
-- Bounce it back up to cpeRhsE.
cpe_app env fun [] _ = cpeRhsE env fun
-- N-variable fun, better let-bind it
cpe_app env fun args depth
= do { (fun_floats, fun') <- cpeArg env evalDmd fun ty
-- The evalDmd says that it's sure to be evaluated,
-- so we'll end up case-binding it
; (app, floats) <- rebuild_app args fun' ty fun_floats []
; mb_saturate Nothing app floats depth }
where
ty = exprType fun
-- Saturate if necessary
mb_saturate head app floats depth =
case head of
Just fn_id -> do { sat_app <- maybeSaturate fn_id app depth
; return (floats, sat_app) }
_other -> return (floats, app)
-- Deconstruct and rebuild the application, floating any non-atomic
-- arguments to the outside. We collect the type of the expression,
-- the head of the application, and the number of actual value arguments,
-- all of which are used to possibly saturate this application if it
-- has a constructor or primop at the head.
rebuild_app
:: [CpeArg] -- The arguments (inner to outer)
-> CpeApp
-> Type
-> Floats
-> [Demand]
-> UniqSM (CpeApp, Floats)
rebuild_app [] app _ floats ss = do
MASSERT(null ss) -- make sure we used all the strictness info
return (app, floats)
rebuild_app (a : as) fun' fun_ty floats ss = case a of
CpeArg arg@(Type arg_ty) ->
rebuild_app as (App fun' arg) (piResultTy fun_ty arg_ty) floats ss
CpeArg arg@(Coercion {}) ->
rebuild_app as (App fun' arg) (funResultTy fun_ty) floats ss
CpeArg arg -> do
let (ss1, ss_rest) -- See Note [lazyId magic] in MkId
= case (ss, isLazyExpr arg) of
(_ : ss_rest, True) -> (topDmd, ss_rest)
(ss1 : ss_rest, False) -> (ss1, ss_rest)
([], _) -> (topDmd, [])
(arg_ty, res_ty) = expectJust "cpeBody:collect_args" $
splitFunTy_maybe fun_ty
(fs, arg') <- cpeArg top_env ss1 arg arg_ty
rebuild_app as (App fun' arg') res_ty (fs `appendFloats` floats) ss_rest
CpeCast co ->
let Pair _ty1 ty2 = coercionKind co
in rebuild_app as (Cast fun' co) ty2 floats ss
CpeTick tickish ->
-- See [Floating Ticks in CorePrep]
rebuild_app as fun' fun_ty (addFloat floats (FloatTick tickish)) ss
isLazyExpr :: CoreExpr -> Bool
-- See Note [lazyId magic] in MkId
isLazyExpr (Cast e _) = isLazyExpr e
isLazyExpr (Tick _ e) = isLazyExpr e
isLazyExpr (Var f `App` _ `App` _) = f `hasKey` lazyIdKey
isLazyExpr _ = False
-- ---------------------------------------------------------------------------
-- CpeArg: produces a result satisfying CpeArg
-- ---------------------------------------------------------------------------
-- This is where we arrange that a non-trivial argument is let-bound
cpeArg :: CorePrepEnv -> Demand
-> CoreArg -> Type -> UniqSM (Floats, CpeTriv)
cpeArg env dmd arg arg_ty
= do { (floats1, arg1) <- cpeRhsE env arg -- arg1 can be a lambda
; (floats2, arg2) <- if want_float floats1 arg1
then return (floats1, arg1)
else dontFloat floats1 arg1
-- Else case: arg1 might have lambdas, and we can't
-- put them inside a wrapBinds
; if cpe_ExprIsTrivial arg2 -- Do not eta expand a trivial argument
then return (floats2, arg2)
else do
{ v <- newVar arg_ty
; let arg3 = cpeEtaExpand (exprArity arg2) arg2
arg_float = mkFloat dmd is_unlifted v arg3
; return (addFloat floats2 arg_float, varToCoreExpr v) } }
where
is_unlifted = isUnliftedType arg_ty
want_float = wantFloatNested NonRecursive dmd is_unlifted
{-
Note [Floating unlifted arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider C (let v* = expensive in v)
where the "*" indicates "will be demanded". Usually v will have been
inlined by now, but let's suppose it hasn't (see Trac #2756). Then we
do *not* want to get
let v* = expensive in C v
because that has different strictness. Hence the use of 'allLazy'.
(NB: the let v* turns into a FloatCase, in mkLocalNonRec.)
------------------------------------------------------------------------------
-- Building the saturated syntax
-- ---------------------------------------------------------------------------
maybeSaturate deals with saturating primops and constructors
The type is the type of the entire application
-}
maybeSaturate :: Id -> CpeApp -> Int -> UniqSM CpeRhs
maybeSaturate fn expr n_args
| Just DataToTagOp <- isPrimOpId_maybe fn -- DataToTag must have an evaluated arg
-- A gruesome special case
= saturateDataToTag sat_expr
| hasNoBinding fn -- There's no binding
= return sat_expr
| otherwise
= return expr
where
fn_arity = idArity fn
excess_arity = fn_arity - n_args
sat_expr = cpeEtaExpand excess_arity expr
-------------
saturateDataToTag :: CpeApp -> UniqSM CpeApp
-- See Note [dataToTag magic]
saturateDataToTag sat_expr
= do { let (eta_bndrs, eta_body) = collectBinders sat_expr
; eta_body' <- eval_data2tag_arg eta_body
; return (mkLams eta_bndrs eta_body') }
where
eval_data2tag_arg :: CpeApp -> UniqSM CpeBody
eval_data2tag_arg app@(fun `App` arg)
| exprIsHNF arg -- Includes nullary constructors
= return app -- The arg is evaluated
| otherwise -- Arg not evaluated, so evaluate it
= do { arg_id <- newVar (exprType arg)
; let arg_id1 = setIdUnfolding arg_id evaldUnfolding
; return (Case arg arg_id1 (exprType app)
[(DEFAULT, [], fun `App` Var arg_id1)]) }
eval_data2tag_arg (Tick t app) -- Scc notes can appear
= do { app' <- eval_data2tag_arg app
; return (Tick t app') }
eval_data2tag_arg other -- Should not happen
= pprPanic "eval_data2tag" (ppr other)
{-
Note [dataToTag magic]
~~~~~~~~~~~~~~~~~~~~~~
Horrid: we must ensure that the arg of data2TagOp is evaluated
(data2tag x) --> (case x of y -> data2tag y)
(yuk yuk) take into account the lambdas we've now introduced
How might it not be evaluated? Well, we might have floated it out
of the scope of a `seq`, or dropped the `seq` altogether.
************************************************************************
* *
Simple CoreSyn operations
* *
************************************************************************
-}
cpe_ExprIsTrivial :: CoreExpr -> Bool
-- Version that doesn't consider an scc annotation to be trivial.
-- See also 'exprIsTrivial'
cpe_ExprIsTrivial (Var _) = True
cpe_ExprIsTrivial (Type _) = True
cpe_ExprIsTrivial (Coercion _) = True
cpe_ExprIsTrivial (Lit _) = True
cpe_ExprIsTrivial (App e arg) = not (isRuntimeArg arg) && cpe_ExprIsTrivial e
cpe_ExprIsTrivial (Lam b e) = not (isRuntimeVar b) && cpe_ExprIsTrivial e
cpe_ExprIsTrivial (Tick t e) = not (tickishIsCode t) && cpe_ExprIsTrivial e
cpe_ExprIsTrivial (Cast e _) = cpe_ExprIsTrivial e
cpe_ExprIsTrivial (Case e _ _ []) = cpe_ExprIsTrivial e
-- See Note [Empty case is trivial] in CoreUtils
cpe_ExprIsTrivial _ = False
{-
-- -----------------------------------------------------------------------------
-- Eta reduction
-- -----------------------------------------------------------------------------
Note [Eta expansion]
~~~~~~~~~~~~~~~~~~~~~
Eta expand to match the arity claimed by the binder Remember,
CorePrep must not change arity
Eta expansion might not have happened already, because it is done by
the simplifier only when there at least one lambda already.
NB1:we could refrain when the RHS is trivial (which can happen
for exported things). This would reduce the amount of code
generated (a little) and make things a little words for
code compiled without -O. The case in point is data constructor
wrappers.
NB2: we have to be careful that the result of etaExpand doesn't
invalidate any of the assumptions that CorePrep is attempting
to establish. One possible cause is eta expanding inside of
an SCC note - we're now careful in etaExpand to make sure the
SCC is pushed inside any new lambdas that are generated.
Note [Eta expansion and the CorePrep invariants]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It turns out to be much much easier to do eta expansion
*after* the main CorePrep stuff. But that places constraints
on the eta expander: given a CpeRhs, it must return a CpeRhs.
For example here is what we do not want:
f = /\a -> g (h 3) -- h has arity 2
After ANFing we get
f = /\a -> let s = h 3 in g s
and now we do NOT want eta expansion to give
f = /\a -> \ y -> (let s = h 3 in g s) y
Instead CoreArity.etaExpand gives
f = /\a -> \y -> let s = h 3 in g s y
-}
cpeEtaExpand :: Arity -> CpeRhs -> CpeRhs
cpeEtaExpand arity expr
| arity == 0 = expr
| otherwise = etaExpand arity expr
{-
-- -----------------------------------------------------------------------------
-- Eta reduction
-- -----------------------------------------------------------------------------
Why try eta reduction? Hasn't the simplifier already done eta?
But the simplifier only eta reduces if that leaves something
trivial (like f, or f Int). But for deLam it would be enough to
get to a partial application:
case x of { p -> \xs. map f xs }
==> case x of { p -> map f }
-}
tryEtaReducePrep :: [CoreBndr] -> CoreExpr -> Maybe CoreExpr
tryEtaReducePrep bndrs expr@(App _ _)
| ok_to_eta_reduce f
, n_remaining >= 0
, and (zipWith ok bndrs last_args)
, not (any (`elemVarSet` fvs_remaining) bndrs)
, exprIsHNF remaining_expr -- Don't turn value into a non-value
-- else the behaviour with 'seq' changes
= Just remaining_expr
where
(f, args) = collectArgs expr
remaining_expr = mkApps f remaining_args
fvs_remaining = exprFreeVars remaining_expr
(remaining_args, last_args) = splitAt n_remaining args
n_remaining = length args - length bndrs
ok bndr (Var arg) = bndr == arg
ok _ _ = False
-- We can't eta reduce something which must be saturated.
ok_to_eta_reduce (Var f) = not (hasNoBinding f)
ok_to_eta_reduce _ = False -- Safe. ToDo: generalise
tryEtaReducePrep bndrs (Let bind@(NonRec _ r) body)
| not (any (`elemVarSet` fvs) bndrs)
= case tryEtaReducePrep bndrs body of
Just e -> Just (Let bind e)
Nothing -> Nothing
where
fvs = exprFreeVars r
-- NB: do not attempt to eta-reduce across ticks
-- Otherwise we risk reducing
-- \x. (Tick (Breakpoint {x}) f x)
-- ==> Tick (breakpoint {x}) f
-- which is bogus (Trac #17228)
-- tryEtaReducePrep bndrs (Tick tickish e)
-- = fmap (mkTick tickish) $ tryEtaReducePrep bndrs e
tryEtaReducePrep _ _ = Nothing
{-
************************************************************************
* *
Floats
* *
************************************************************************
Note [Pin demand info on floats]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We pin demand info on floated lets so that we can see the one-shot thunks.
-}
data FloatingBind
= FloatLet CoreBind -- Rhs of bindings are CpeRhss
-- They are always of lifted type;
-- unlifted ones are done with FloatCase
| FloatCase
Id CpeBody
Bool -- The bool indicates "ok-for-speculation"
-- | See Note [Floating Ticks in CorePrep]
| FloatTick (Tickish Id)
data Floats = Floats OkToSpec (OrdList FloatingBind)
instance Outputable FloatingBind where
ppr (FloatLet b) = ppr b
ppr (FloatCase b r ok) = brackets (ppr ok) <+> ppr b <+> equals <+> ppr r
ppr (FloatTick t) = ppr t
instance Outputable Floats where
ppr (Floats flag fs) = text "Floats" <> brackets (ppr flag) <+>
braces (vcat (map ppr (fromOL fs)))
instance Outputable OkToSpec where
ppr OkToSpec = text "OkToSpec"
ppr IfUnboxedOk = text "IfUnboxedOk"
ppr NotOkToSpec = text "NotOkToSpec"
-- Can we float these binds out of the rhs of a let? We cache this decision
-- to avoid having to recompute it in a non-linear way when there are
-- deeply nested lets.
data OkToSpec
= OkToSpec -- Lazy bindings of lifted type
| IfUnboxedOk -- A mixture of lazy lifted bindings and n
-- ok-to-speculate unlifted bindings
| NotOkToSpec -- Some not-ok-to-speculate unlifted bindings
mkFloat :: Demand -> Bool -> Id -> CpeRhs -> FloatingBind
mkFloat dmd is_unlifted bndr rhs
| use_case = FloatCase bndr rhs (exprOkForSpeculation rhs)
| is_hnf = FloatLet (NonRec bndr rhs)
| otherwise = FloatLet (NonRec (setIdDemandInfo bndr dmd) rhs)
-- See Note [Pin demand info on floats]
where
is_hnf = exprIsHNF rhs
is_strict = isStrictDmd dmd
use_case = is_unlifted || is_strict && not is_hnf
-- Don't make a case for a value binding,
-- even if it's strict. Otherwise we get
-- case (\x -> e) of ...!
emptyFloats :: Floats
emptyFloats = Floats OkToSpec nilOL
isEmptyFloats :: Floats -> Bool
isEmptyFloats (Floats _ bs) = isNilOL bs
wrapBinds :: Floats -> CpeBody -> CpeBody
wrapBinds (Floats _ binds) body
= foldrOL mk_bind body binds
where
mk_bind (FloatCase bndr rhs _) body = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
mk_bind (FloatLet bind) body = Let bind body
mk_bind (FloatTick tickish) body = mkTick tickish body
addFloat :: Floats -> FloatingBind -> Floats
addFloat (Floats ok_to_spec floats) new_float
= Floats (combine ok_to_spec (check new_float)) (floats `snocOL` new_float)
where
check (FloatLet _) = OkToSpec
check (FloatCase _ _ ok_for_spec)
| ok_for_spec = IfUnboxedOk
| otherwise = NotOkToSpec
check FloatTick{} = OkToSpec
-- The ok-for-speculation flag says that it's safe to
-- float this Case out of a let, and thereby do it more eagerly
-- We need the top-level flag because it's never ok to float
-- an unboxed binding to the top level
unitFloat :: FloatingBind -> Floats
unitFloat = addFloat emptyFloats
appendFloats :: Floats -> Floats -> Floats
appendFloats (Floats spec1 floats1) (Floats spec2 floats2)
= Floats (combine spec1 spec2) (floats1 `appOL` floats2)
concatFloats :: [Floats] -> OrdList FloatingBind
concatFloats = foldr (\ (Floats _ bs1) bs2 -> appOL bs1 bs2) nilOL
combine :: OkToSpec -> OkToSpec -> OkToSpec
combine NotOkToSpec _ = NotOkToSpec
combine _ NotOkToSpec = NotOkToSpec
combine IfUnboxedOk _ = IfUnboxedOk
combine _ IfUnboxedOk = IfUnboxedOk
combine _ _ = OkToSpec
deFloatTop :: Floats -> [CoreBind]
-- For top level only; we don't expect any FloatCases
deFloatTop (Floats _ floats)
= foldrOL get [] floats
where
get (FloatLet b) bs = occurAnalyseRHSs b : bs
get b _ = pprPanic "corePrepPgm" (ppr b)
-- See Note [Dead code in CorePrep]
occurAnalyseRHSs (NonRec x e) = NonRec x (occurAnalyseExpr_NoBinderSwap e)
occurAnalyseRHSs (Rec xes) = Rec [(x, occurAnalyseExpr_NoBinderSwap e) | (x, e) <- xes]
---------------------------------------------------------------------------
canFloatFromNoCaf :: Platform -> Floats -> CpeRhs -> Maybe (Floats, CpeRhs)
-- Note [CafInfo and floating]
canFloatFromNoCaf platform (Floats ok_to_spec fs) rhs
| OkToSpec <- ok_to_spec -- Worth trying
, Just (subst, fs') <- go (emptySubst, nilOL) (fromOL fs)
= Just (Floats OkToSpec fs', subst_expr subst rhs)
| otherwise
= Nothing
where
subst_expr = substExpr (text "CorePrep")
go :: (Subst, OrdList FloatingBind) -> [FloatingBind]
-> Maybe (Subst, OrdList FloatingBind)
go (subst, fbs_out) [] = Just (subst, fbs_out)
go (subst, fbs_out) (FloatLet (NonRec b r) : fbs_in)
| rhs_ok r
= go (subst', fbs_out `snocOL` new_fb) fbs_in
where
(subst', b') = set_nocaf_bndr subst b
new_fb = FloatLet (NonRec b' (subst_expr subst r))
go (subst, fbs_out) (FloatLet (Rec prs) : fbs_in)
| all rhs_ok rs
= go (subst', fbs_out `snocOL` new_fb) fbs_in
where
(bs,rs) = unzip prs
(subst', bs') = mapAccumL set_nocaf_bndr subst bs
rs' = map (subst_expr subst') rs
new_fb = FloatLet (Rec (bs' `zip` rs'))
go (subst, fbs_out) (ft@FloatTick{} : fbs_in)
= go (subst, fbs_out `snocOL` ft) fbs_in
go _ _ = Nothing -- Encountered a caffy binding
------------
set_nocaf_bndr subst bndr
= (extendIdSubst subst bndr (Var bndr'), bndr')
where
bndr' = bndr `setIdCafInfo` NoCafRefs
------------
rhs_ok :: CoreExpr -> Bool
-- We can only float to top level from a NoCaf thing if
-- the new binding is static. However it can't mention
-- any non-static things or it would *already* be Caffy
rhs_ok = rhsIsStatic platform (\_ -> False)
(\i -> pprPanic "rhsIsStatic" (integer i))
-- Integer literals should not show up
wantFloatNested :: RecFlag -> Demand -> Bool -> Floats -> CpeRhs -> Bool
wantFloatNested is_rec dmd is_unlifted floats rhs
= isEmptyFloats floats
|| isStrictDmd dmd
|| is_unlifted
|| (allLazyNested is_rec floats && exprIsHNF rhs)
-- Why the test for allLazyNested?
-- v = f (x `divInt#` y)
-- we don't want to float the case, even if f has arity 2,
-- because floating the case would make it evaluated too early
allLazyTop :: Floats -> Bool
allLazyTop (Floats OkToSpec _) = True
allLazyTop _ = False
allLazyNested :: RecFlag -> Floats -> Bool
allLazyNested _ (Floats OkToSpec _) = True
allLazyNested _ (Floats NotOkToSpec _) = False
allLazyNested is_rec (Floats IfUnboxedOk _) = isNonRec is_rec
{-
************************************************************************
* *
Cloning
* *
************************************************************************
-}
-- ---------------------------------------------------------------------------
-- The environment
-- ---------------------------------------------------------------------------
-- Note [Inlining in CorePrep]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- There is a subtle but important invariant that must be upheld in the output
-- of CorePrep: there are no "trivial" updatable thunks. Thus, this Core
-- is impermissible:
--
-- let x :: ()
-- x = y
--
-- (where y is a reference to a GLOBAL variable). Thunks like this are silly:
-- they can always be profitably replaced by inlining x with y. Consequently,
-- the code generator/runtime does not bother implementing this properly
-- (specifically, there is no implementation of stg_ap_0_upd_info, which is the
-- stack frame that would be used to update this thunk. The "0" means it has
-- zero free variables.)
--
-- In general, the inliner is good at eliminating these let-bindings. However,
-- there is one case where these trivial updatable thunks can arise: when
-- we are optimizing away 'lazy' (see Note [lazyId magic], and also
-- 'cpeRhsE'.) Then, we could have started with:
--
-- let x :: ()
-- x = lazy @ () y
--
-- which is a perfectly fine, non-trivial thunk, but then CorePrep will
-- drop 'lazy', giving us 'x = y' which is trivial and impermissible.
-- The solution is CorePrep to have a miniature inlining pass which deals
-- with cases like this. We can then drop the let-binding altogether.
--
-- Why does the removal of 'lazy' have to occur in CorePrep?
-- The gory details are in Note [lazyId magic] in MkId, but the
-- main reason is that lazy must appear in unfoldings (optimizer
-- output) and it must prevent call-by-value for catch# (which
-- is implemented by CorePrep.)
--
-- An alternate strategy for solving this problem is to have the
-- inliner treat 'lazy e' as a trivial expression if 'e' is trivial.
-- We decided not to adopt this solution to keep the definition
-- of 'exprIsTrivial' simple.
--
-- There is ONE caveat however: for top-level bindings we have
-- to preserve the binding so that we float the (hacky) non-recursive
-- binding for data constructors; see Note [Data constructor workers].
--
-- Note [CorePrep inlines trivial CoreExpr not Id]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Why does cpe_env need to be an IdEnv CoreExpr, as opposed to an
-- IdEnv Id? Naively, we might conjecture that trivial updatable thunks
-- as per Note [Inlining in CorePrep] always have the form
-- 'lazy @ SomeType gbl_id'. But this is not true: the following is
-- perfectly reasonable Core:
--
-- let x :: ()
-- x = lazy @ (forall a. a) y @ Bool
--
-- When we inline 'x' after eliminating 'lazy', we need to replace
-- occurences of 'x' with 'y @ bool', not just 'y'. Situations like
-- this can easily arise with higher-rank types; thus, cpe_env must
-- map to CoreExprs, not Ids.
data CorePrepEnv
= CPE { cpe_dynFlags :: DynFlags
, cpe_env :: IdEnv CoreExpr -- Clone local Ids
-- ^ This environment is used for three operations:
--
-- 1. To support cloning of local Ids so that they are
-- all unique (see item (6) of CorePrep overview).
--
-- 2. To support beta-reduction of runRW, see
-- Note [runRW magic] and Note [runRW arg].
--
-- 3. To let us inline trivial RHSs of non top-level let-bindings,
-- see Note [lazyId magic], Note [Inlining in CorePrep]
-- and Note [CorePrep inlines trivial CoreExpr not Id] (#12076)
, cpe_mkIntegerId :: Id
, cpe_integerSDataCon :: Maybe DataCon
}
lookupMkIntegerName :: DynFlags -> HscEnv -> IO Id
lookupMkIntegerName dflags hsc_env
= guardIntegerUse dflags $ liftM tyThingId $
lookupGlobal hsc_env mkIntegerName
lookupIntegerSDataConName :: DynFlags -> HscEnv -> IO (Maybe DataCon)
lookupIntegerSDataConName dflags hsc_env = case cIntegerLibraryType of
IntegerGMP -> guardIntegerUse dflags $ liftM (Just . tyThingDataCon) $
lookupGlobal hsc_env integerSDataConName
IntegerSimple -> return Nothing
-- | Helper for 'lookupMkIntegerName' and 'lookupIntegerSDataConName'
guardIntegerUse :: DynFlags -> IO a -> IO a
guardIntegerUse dflags act
| thisPackage dflags == primUnitId
= return $ panic "Can't use Integer in ghc-prim"
| thisPackage dflags == integerUnitId
= return $ panic "Can't use Integer in integer-*"
| otherwise = act
mkInitialCorePrepEnv :: DynFlags -> HscEnv -> IO CorePrepEnv
mkInitialCorePrepEnv dflags hsc_env
= do mkIntegerId <- lookupMkIntegerName dflags hsc_env
integerSDataCon <- lookupIntegerSDataConName dflags hsc_env
return $ CPE {
cpe_dynFlags = dflags,
cpe_env = emptyVarEnv,
cpe_mkIntegerId = mkIntegerId,
cpe_integerSDataCon = integerSDataCon
}
extendCorePrepEnv :: CorePrepEnv -> Id -> Id -> CorePrepEnv
extendCorePrepEnv cpe id id'
= cpe { cpe_env = extendVarEnv (cpe_env cpe) id (Var id') }
extendCorePrepEnvExpr :: CorePrepEnv -> Id -> CoreExpr -> CorePrepEnv
extendCorePrepEnvExpr cpe id expr
= cpe { cpe_env = extendVarEnv (cpe_env cpe) id expr }
extendCorePrepEnvList :: CorePrepEnv -> [(Id,Id)] -> CorePrepEnv
extendCorePrepEnvList cpe prs
= cpe { cpe_env = extendVarEnvList (cpe_env cpe)
(map (\(id, id') -> (id, Var id')) prs) }
lookupCorePrepEnv :: CorePrepEnv -> Id -> CoreExpr
lookupCorePrepEnv cpe id
= case lookupVarEnv (cpe_env cpe) id of
Nothing -> Var id
Just exp -> exp
getMkIntegerId :: CorePrepEnv -> Id
getMkIntegerId = cpe_mkIntegerId
------------------------------------------------------------------------------
-- Cloning binders
-- ---------------------------------------------------------------------------
cpCloneBndrs :: CorePrepEnv -> [Var] -> UniqSM (CorePrepEnv, [Var])
cpCloneBndrs env bs = mapAccumLM cpCloneBndr env bs
cpCloneBndr :: CorePrepEnv -> Var -> UniqSM (CorePrepEnv, Var)
cpCloneBndr env bndr
| isLocalId bndr, not (isCoVar bndr)
= do bndr' <- setVarUnique bndr <$> getUniqueM
-- We are going to OccAnal soon, so drop (now-useless) rules/unfoldings
-- so that we can drop more stuff as dead code.
-- See also Note [Dead code in CorePrep]
let bndr'' = bndr' `setIdUnfolding` noUnfolding
`setIdSpecialisation` emptyRuleInfo
return (extendCorePrepEnv env bndr bndr'', bndr'')
| otherwise -- Top level things, which we don't want
-- to clone, have become GlobalIds by now
-- And we don't clone tyvars, or coercion variables
= return (env, bndr)
------------------------------------------------------------------------------
-- Cloning ccall Ids; each must have a unique name,
-- to give the code generator a handle to hang it on
-- ---------------------------------------------------------------------------
fiddleCCall :: Id -> UniqSM Id
fiddleCCall id
| isFCallId id = (id `setVarUnique`) <$> getUniqueM
| otherwise = return id
------------------------------------------------------------------------------
-- Generating new binders
-- ---------------------------------------------------------------------------
newVar :: Type -> UniqSM Id
newVar ty
= seqType ty `seq` do
uniq <- getUniqueM
return (mkSysLocalOrCoVar (fsLit "sat") uniq ty)
------------------------------------------------------------------------------
-- Floating ticks
-- ---------------------------------------------------------------------------
--
-- Note [Floating Ticks in CorePrep]
--
-- It might seem counter-intuitive to float ticks by default, given
-- that we don't actually want to move them if we can help it. On the
-- other hand, nothing gets very far in CorePrep anyway, and we want
-- to preserve the order of let bindings and tick annotations in
-- relation to each other. For example, if we just wrapped let floats
-- when they pass through ticks, we might end up performing the
-- following transformation:
--
-- src<...> let foo = bar in baz
-- ==> let foo = src<...> bar in src<...> baz
--
-- Because the let-binding would float through the tick, and then
-- immediately materialize, achieving nothing but decreasing tick
-- accuracy. The only special case is the following scenario:
--
-- let foo = src<...> (let a = b in bar) in baz
-- ==> let foo = src<...> bar; a = src<...> b in baz
--
-- Here we would not want the source tick to end up covering "baz" and
-- therefore refrain from pushing ticks outside. Instead, we copy them
-- into the floating binds (here "a") in cpePair. Note that where "b"
-- or "bar" are (value) lambdas we have to push the annotations
-- further inside in order to uphold our rules.
--
-- All of this is implemented below in @wrapTicks@.
-- | Like wrapFloats, but only wraps tick floats
wrapTicks :: Floats -> CoreExpr -> (Floats, CoreExpr)
wrapTicks (Floats flag floats0) expr = (Floats flag floats1, expr')
where (floats1, expr') = foldrOL go (nilOL, expr) floats0
go (FloatTick t) (fs, e) = ASSERT(tickishPlace t == PlaceNonLam)
(mapOL (wrap t) fs, mkTick t e)
go other (fs, e) = (other `consOL` fs, e)
wrap t (FloatLet bind) = FloatLet (wrapBind t bind)
wrap t (FloatCase b r ok) = FloatCase b (mkTick t r) ok
wrap _ other = pprPanic "wrapTicks: unexpected float!"
(ppr other)
wrapBind t (NonRec binder rhs) = NonRec binder (mkTick t rhs)
wrapBind t (Rec pairs) = Rec (mapSnd (mkTick t) pairs)
| snoyberg/ghc | compiler/coreSyn/CorePrep.hs | bsd-3-clause | 57,558 | 1 | 19 | 15,683 | 9,549 | 5,017 | 4,532 | 619 | 18 |
-- |
-- Module: Data.Aeson.Types
-- Copyright: (c) 2011-2016 Bryan O'Sullivan
-- (c) 2011 MailRank, Inc.
-- License: BSD3
-- Maintainer: Bryan O'Sullivan <bos@serpentine.com>
-- Stability: experimental
-- Portability: portable
--
-- Types for working with JSON data.
module Data.Aeson.Types
(
-- * Core JSON types
Value(..)
, Encoding
, unsafeToEncoding
, fromEncoding
, Series
, Array
, emptyArray
, Pair
, Object
, emptyObject
-- * Convenience types and functions
, DotNetTime(..)
, typeMismatch
-- * Type conversion
, Parser
, Result(..)
, FromJSON(..)
, fromJSON
, parse
, parseEither
, parseMaybe
, ToJSON(..)
, KeyValue(..)
, modifyFailure
-- ** Keys for maps
, ToJSONKey(..)
, ToJSONKeyFunction(..)
, toJSONKeyText
, contramapToJSONKeyFunction
, FromJSONKey(..)
, FromJSONKeyFunction(..)
, fromJSONKeyCoerce
, coerceFromJSONKeyFunction
, mapFromJSONKeyFunction
-- ** Liftings to unary and binary type constructors
, FromJSON1(..)
, parseJSON1
, FromJSON2(..)
, parseJSON2
, ToJSON1(..)
, toJSON1
, toEncoding1
, ToJSON2(..)
, toJSON2
, toEncoding2
-- ** Generic JSON classes
, GFromJSON(..)
, FromArgs(..)
, GToJSON(..)
, GToEncoding(..)
, ToArgs(..)
, Zero
, One
, genericToJSON
, genericLiftToJSON
, genericToEncoding
, genericLiftToEncoding
, genericParseJSON
, genericLiftParseJSON
-- * Inspecting @'Value's@
, withObject
, withText
, withArray
, withNumber
, withScientific
, withBool
, pairs
, foldable
, (.:)
, (.:?)
, (.:!)
, (.!=)
, object
, listEncoding
, listValue
, listParser
-- * Generic and TH encoding configuration
, Options(..)
, SumEncoding(..)
, camelTo
, camelTo2
, defaultOptions
, defaultTaggedObject
) where
import Prelude ()
import Prelude.Compat
import Data.Aeson.Encoding (Encoding, unsafeToEncoding, fromEncoding, Series, pairs)
import Data.Aeson.Types.Class
import Data.Aeson.Types.Internal
import Data.Foldable (toList)
-- | Encode a 'Foldable' as a JSON array.
foldable :: (Foldable t, ToJSON a) => t a -> Encoding
foldable = toEncoding . toList
{-# INLINE foldable #-}
| tolysz/prepare-ghcjs | spec-lts8/aeson/Data/Aeson/Types.hs | bsd-3-clause | 2,392 | 0 | 7 | 671 | 443 | 306 | 137 | 87 | 1 |
module B1 (myFringe)where
import D1 hiding (sumSquares)
import qualified D1
instance SameOrNot Float where
isSame a b = a ==b
isNotSame a b = a /=b
myFringe:: Tree a -> [a]
myFringe (Leaf x ) = [x]
myFringe (Branch left right) = myFringe right
sumSquares (x:xs)= x^2 + sumSquares xs
sumSquares [] =0
| kmate/HaRe | old/testing/renaming/B1.hs | bsd-3-clause | 320 | 0 | 7 | 73 | 145 | 77 | 68 | 11 | 1 |
module WhereIn3 where
sumSquares x y
= (sq_1 pow x) + (sq_1 pow y) where pow = 2
sq_1 pow 0 = 0
sq_1 pow z = z ^ pow
anotherFun 0 y = sq y
sq x = x ^ 2
| kmate/HaRe | old/testing/liftOneLevel/WhereIn3_AstOut.hs | bsd-3-clause | 163 | 0 | 7 | 53 | 90 | 46 | 44 | 7 | 1 |
{-# LANGUAGE CPP #-}
module GHCi.Signals (installSignalHandlers) where
import Control.Concurrent
import Control.Exception
import System.Mem.Weak ( deRefWeak )
#ifndef mingw32_HOST_OS
import System.Posix.Signals
#endif
#if defined(mingw32_HOST_OS)
import GHC.ConsoleHandler
#endif
-- | Install standard signal handlers for catching ^C, which just throw an
-- exception in the target thread. The current target thread is the
-- thread at the head of the list in the MVar passed to
-- installSignalHandlers.
installSignalHandlers :: IO ()
installSignalHandlers = do
main_thread <- myThreadId
wtid <- mkWeakThreadId main_thread
let interrupt = do
r <- deRefWeak wtid
case r of
Nothing -> return ()
Just t -> throwTo t UserInterrupt
#if !defined(mingw32_HOST_OS)
_ <- installHandler sigQUIT (Catch interrupt) Nothing
_ <- installHandler sigINT (Catch interrupt) Nothing
#else
-- GHC 6.3+ has support for console events on Windows
-- NOTE: running GHCi under a bash shell for some reason requires
-- you to press Ctrl-Break rather than Ctrl-C to provoke
-- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
-- why --SDM 17/12/2004
let sig_handler ControlC = interrupt
sig_handler Break = interrupt
sig_handler _ = return ()
_ <- installHandler (Catch sig_handler)
#endif
return ()
| tolysz/prepare-ghcjs | spec-lts8/ghci/GHCi/Signals.hs | bsd-3-clause | 1,393 | 0 | 16 | 292 | 186 | 97 | 89 | 18 | 2 |
{-# LANGUAGE UndecidableInstances, OverlappingInstances, Rank2Types,
KindSignatures, EmptyDataDecls, MultiParamTypeClasses, CPP #-}
{-
(C) 2004--2005 Ralf Laemmel, Simon D. Foster
This module approximates Data.Generics.Basics.
-}
module T1735_Help.Basics (
module Data.Typeable,
module T1735_Help.Context,
module T1735_Help.Basics
) where
import Data.Typeable
import T1735_Help.Context
------------------------------------------------------------------------------
-- The ingenious Data class
class (Typeable a, Sat (ctx a)) => Data ctx a
where
gfoldl :: Proxy ctx
-> (forall b c. Data ctx b => w (b -> c) -> b -> w c)
-> (forall g. g -> w g)
-> a -> w a
-- Default definition for gfoldl
-- which copes immediately with basic datatypes
--
gfoldl _ _ z = z
gunfold :: Proxy ctx
-> (forall b r. Data ctx b => c (b -> r) -> c r)
-> (forall r. r -> c r)
-> Constr
-> c a
toConstr :: Proxy ctx -> a -> Constr
dataTypeOf :: Proxy ctx -> a -> DataType
-- incomplete implementation
gunfold _ _ _ _ = undefined
dataTypeOf _ _ = undefined
-- | Mediate types and unary type constructors
dataCast1 :: Typeable t
=> Proxy ctx
-> (forall b. Data ctx b => w (t b))
-> Maybe (w a)
dataCast1 _ _ = Nothing
-- | Mediate types and binary type constructors
dataCast2 :: Typeable t
=> Proxy ctx
-> (forall b c. (Data ctx b, Data ctx c) => w (t b c))
-> Maybe (w a)
dataCast2 _ _ = Nothing
------------------------------------------------------------------------------
-- Generic transformations
type GenericT ctx = forall a. Data ctx a => a -> a
-- Generic map for transformations
gmapT :: Proxy ctx -> GenericT ctx -> GenericT ctx
gmapT ctx f x = unID (gfoldl ctx k ID x)
where
k (ID g) y = ID (g (f y))
-- The identity type constructor
newtype ID x = ID { unID :: x }
------------------------------------------------------------------------------
-- Generic monadic transformations
type GenericM m ctx = forall a. Data ctx a => a -> m a
-- Generic map for monadic transformations
gmapM :: Monad m => Proxy ctx -> GenericM m ctx -> GenericM m ctx
gmapM ctx f = gfoldl ctx k return
where k c x = do c' <- c
x' <- f x
return (c' x')
------------------------------------------------------------------------------
-- Generic queries
type GenericQ ctx r = forall a. Data ctx a => a -> r
-- Map for queries
gmapQ :: Proxy ctx -> GenericQ ctx r -> GenericQ ctx [r]
gmapQ ctx f = gmapQr ctx (:) [] f
gmapQr :: Data ctx a
=> Proxy ctx
-> (r' -> r -> r)
-> r
-> GenericQ ctx r'
-> a
-> r
gmapQr ctx o r f x = unQr (gfoldl ctx k (const (Qr id)) x) r
where
k (Qr g) y = Qr (\s -> g (f y `o` s))
-- The type constructor used in definition of gmapQr
newtype Qr r a = Qr { unQr :: r -> r }
------------------------------------------------------------------------------
--
-- Generic unfolding
--
------------------------------------------------------------------------------
-- | Build a term skeleton
fromConstr :: Data ctx a => Proxy ctx -> Constr -> a
fromConstr ctx = fromConstrB ctx undefined
-- | Build a term and use a generic function for subterms
fromConstrB :: Data ctx a
=> Proxy ctx
-> (forall b. Data ctx b => b)
-> Constr
-> a
fromConstrB ctx f = unID . gunfold ctx k z
where
k c = ID (unID c f)
z = ID
-- | Monadic variation on \"fromConstrB\"
fromConstrM :: (Monad m, Data ctx a)
=> Proxy ctx
-> (forall b. Data ctx b => m b)
-> Constr
-> m a
fromConstrM ctx f = gunfold ctx k z
where
k c = do { c' <- c; b <- f; return (c' b) }
z = return
------------------------------------------------------------------------------
--
-- Datatype and constructor representations
--
------------------------------------------------------------------------------
--
-- | Representation of datatypes.
-- | A package of constructor representations with names of type and module.
-- | The list of constructors could be an array, a balanced tree, or others.
--
data DataType = DataType
{ tycon :: String
, datarep :: DataRep
}
deriving Show
-- | Representation of constructors
data Constr = Constr
{ conrep :: ConstrRep
, constring :: String
, confields :: [String] -- for AlgRep only
, confixity :: Fixity -- for AlgRep only
, datatype :: DataType
}
instance Show Constr where
show = constring
-- | Equality of constructors
instance Eq Constr where
c == c' = constrRep c == constrRep c'
-- | Public representation of datatypes
data DataRep = AlgRep [Constr]
| IntRep
| FloatRep
| StringRep
| NoRep
deriving (Eq,Show)
-- | Public representation of constructors
data ConstrRep = AlgConstr ConIndex
| IntConstr Integer
| FloatConstr Double
| StringConstr String
deriving (Eq,Show)
--
-- | Unique index for datatype constructors.
-- | Textual order is respected. Starts at 1.
--
type ConIndex = Int
-- | Fixity of constructors
data Fixity = Prefix
| Infix -- Later: add associativity and precedence
deriving (Eq,Show)
------------------------------------------------------------------------------
--
-- Observers for datatype representations
--
------------------------------------------------------------------------------
-- | Gets the type constructor including the module
dataTypeName :: DataType -> String
dataTypeName = tycon
-- | Gets the public presentation of datatypes
dataTypeRep :: DataType -> DataRep
dataTypeRep = datarep
-- | Gets the datatype of a constructor
constrType :: Constr -> DataType
constrType = datatype
-- | Gets the public presentation of constructors
constrRep :: Constr -> ConstrRep
constrRep = conrep
-- | Look up a constructor by its representation
repConstr :: DataType -> ConstrRep -> Constr
repConstr dt cr =
case (dataTypeRep dt, cr) of
(AlgRep cs, AlgConstr i) -> cs !! (i-1)
(IntRep, IntConstr i) -> mkIntConstr dt i
(FloatRep, FloatConstr f) -> mkFloatConstr dt f
(StringRep, StringConstr str) -> mkStringConstr dt str
_ -> error "repConstr"
------------------------------------------------------------------------------
--
-- Representations of algebraic data types
--
------------------------------------------------------------------------------
-- | Constructs an algebraic datatype
mkDataType :: String -> [Constr] -> DataType
mkDataType str cs = DataType
{ tycon = str
, datarep = AlgRep cs
}
-- | Constructs a constructor
mkConstr :: DataType -> String -> [String] -> Fixity -> Constr
mkConstr dt str fields fix =
Constr
{ conrep = AlgConstr idx
, constring = str
, confields = fields
, confixity = fix
, datatype = dt
}
where
idx = head [ i | (c,i) <- dataTypeConstrs dt `zip` [1..],
showConstr c == str ]
-- | Gets the constructors
dataTypeConstrs :: DataType -> [Constr]
dataTypeConstrs dt = case datarep dt of
(AlgRep cons) -> cons
_ -> error "dataTypeConstrs"
-- | Gets the field labels of a constructor
constrFields :: Constr -> [String]
constrFields = confields
-- | Gets the fixity of a constructor
constrFixity :: Constr -> Fixity
constrFixity = confixity
------------------------------------------------------------------------------
--
-- From strings to constr's and vice versa: all data types
--
------------------------------------------------------------------------------
-- | Gets the string for a constructor
showConstr :: Constr -> String
showConstr = constring
-- | Lookup a constructor via a string
readConstr :: DataType -> String -> Maybe Constr
readConstr dt str =
case dataTypeRep dt of
AlgRep cons -> idx cons
IntRep -> mkReadCon (\i -> (mkPrimCon dt str (IntConstr i)))
FloatRep -> mkReadCon (\f -> (mkPrimCon dt str (FloatConstr f)))
StringRep -> Just (mkStringConstr dt str)
NoRep -> Nothing
where
-- Read a value and build a constructor
mkReadCon :: Read t => (t -> Constr) -> Maybe Constr
mkReadCon f = case (reads str) of
[(t,"")] -> Just (f t)
_ -> Nothing
-- Traverse list of algebraic datatype constructors
idx :: [Constr] -> Maybe Constr
idx cons = let fit = filter ((==) str . showConstr) cons
in if fit == []
then Nothing
else Just (head fit)
------------------------------------------------------------------------------
--
-- Convenience funtions: algebraic data types
--
------------------------------------------------------------------------------
-- | Test for an algebraic type
isAlgType :: DataType -> Bool
isAlgType dt = case datarep dt of
(AlgRep _) -> True
_ -> False
-- | Gets the constructor for an index
indexConstr :: DataType -> ConIndex -> Constr
indexConstr dt idx = case datarep dt of
(AlgRep cs) -> cs !! (idx-1)
_ -> error "indexConstr"
-- | Gets the index of a constructor
constrIndex :: Constr -> ConIndex
constrIndex con = case constrRep con of
(AlgConstr idx) -> idx
_ -> error "constrIndex"
-- | Gets the maximum constructor index
maxConstrIndex :: DataType -> ConIndex
maxConstrIndex dt = case dataTypeRep dt of
AlgRep cs -> length cs
_ -> error "maxConstrIndex"
------------------------------------------------------------------------------
--
-- Representation of primitive types
--
------------------------------------------------------------------------------
-- | Constructs the Int type
mkIntType :: String -> DataType
mkIntType = mkPrimType IntRep
-- | Constructs the Float type
mkFloatType :: String -> DataType
mkFloatType = mkPrimType FloatRep
-- | Constructs the String type
mkStringType :: String -> DataType
mkStringType = mkPrimType StringRep
-- | Helper for mkIntType, mkFloatType, mkStringType
mkPrimType :: DataRep -> String -> DataType
mkPrimType dr str = DataType
{ tycon = str
, datarep = dr
}
-- Makes a constructor for primitive types
mkPrimCon :: DataType -> String -> ConstrRep -> Constr
mkPrimCon dt str cr = Constr
{ datatype = dt
, conrep = cr
, constring = str
, confields = error $ concat ["constrFields : ", (tycon dt), " is primative"]
, confixity = error "constrFixity"
}
mkIntConstr :: DataType -> Integer -> Constr
mkIntConstr dt i = case datarep dt of
IntRep -> mkPrimCon dt (show i) (IntConstr i)
_ -> error "mkIntConstr"
mkFloatConstr :: DataType -> Double -> Constr
mkFloatConstr dt f = case datarep dt of
FloatRep -> mkPrimCon dt (show f) (FloatConstr f)
_ -> error "mkFloatConstr"
mkStringConstr :: DataType -> String -> Constr
mkStringConstr dt str = case datarep dt of
StringRep -> mkPrimCon dt str (StringConstr str)
_ -> error "mkStringConstr"
------------------------------------------------------------------------------
--
-- Non-representations for non-presentable types
--
------------------------------------------------------------------------------
-- | Constructs a non-representation
mkNorepType :: String -> DataType
mkNorepType str = DataType
{ tycon = str
, datarep = NoRep
}
-- | Test for a non-representable type
isNorepType :: DataType -> Bool
isNorepType dt = case datarep dt of
NoRep -> True
_ -> False
| siddhanathan/ghc | testsuite/tests/typecheck/should_run/T1735_Help/Basics.hs | bsd-3-clause | 13,203 | 0 | 15 | 4,357 | 2,841 | 1,526 | 1,315 | -1 | -1 |
{-
© 2012 Johan Kiviniemi <devel@johan.kiviniemi.name>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-}
module Network.Rcon.Parse
( parseQueryPacket
, parseResponsePacket
) where
-- https://developer.valvesoftware.com/wiki/Source_RCON_Protocol
import Network.Rcon.Types
import Control.Applicative
import Control.Monad
import Data.Attoparsec
import qualified Data.Attoparsec as AP
import Data.Bits (shiftL, (.|.))
import qualified Data.ByteString as BS
import Data.Word
parseQueryPacket :: BS.ByteString -> Either String QueryPacket
parseQueryPacket = parseOnly (queryPacket <* endOfInput)
parseResponsePacket :: BS.ByteString -> Either String ResponsePacket
parseResponsePacket = parseOnly (responsePacket <* endOfInput)
queryPacket :: Parser QueryPacket
queryPacket =
do id_ <- word32le
type_ <- word32le
case type_ of
3 -> authQ id_
2 -> execCommandQ id_
_ -> fail ("queryPacket: unknown type " ++ show type_)
responsePacket :: Parser ResponsePacket
responsePacket =
do id_ <- word32le
type_ <- word32le
case type_ of
2 -> authR id_
0 -> dataR id_
_ -> fail ("responsePacket: unknown type " ++ show type_)
authQ :: Word32 -> Parser QueryPacket
authQ id_ = AuthQ id_ <$> (byteString0 <* emptyByteString0)
execCommandQ :: Word32 -> Parser QueryPacket
execCommandQ id_ = ExecCommandQ id_ <$> (byteString0 <* emptyByteString0)
authR :: Word32 -> Parser ResponsePacket
authR id_ = AuthR id_ <$> (byteString0 <* emptyByteString0)
dataR :: Word32 -> Parser ResponsePacket
dataR id_ = DataR id_ <$> (byteString0 <* emptyByteString0)
word32le :: Parser Word32
word32le = do [a, b, c, d] <- replicateM 4 (fromIntegral <$> anyWord8)
return $ (a `shiftL` 0x00)
.|. (b `shiftL` 0x08)
.|. (c `shiftL` 0x10)
.|. (d `shiftL` 0x18)
<?> "word32le"
byteString0 :: Parser BS.ByteString
byteString0 = AP.takeWhile (/= 0) <* word8 0
<?> "0-terminated ByteString"
emptyByteString0 :: Parser ()
emptyByteString0 = () <$ word8 0
<?> "empty 0-terminated ByteString"
-- vim:set et sw=2 sts=2:
| ion1/rcon-haskell | Network/Rcon/Parse.hs | isc | 2,916 | 0 | 13 | 673 | 581 | 308 | 273 | 52 | 3 |
module Geometria.Cuboide
( volume
, area
) where
volume :: Float -> Float -> Float -> Float
volume a b c = areaRetangulo a b * c
area :: Float -> Float -> Float -> Float
area a b c = areaRetangulo a b * 2 + areaRetangulo a c * 2 + areaRetangulo c b * 2
areaRetangulo :: Float -> Float -> Float
areaRetangulo a b = a * b
| tonussi/freezing-dubstep | proj1/Cuboide.hs | mit | 329 | 0 | 10 | 81 | 143 | 73 | 70 | 9 | 1 |
{-# LANGUAGE DeriveFunctor #-}
module Test.Smoke.Types.Results where
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Test.Smoke.Paths
import Test.Smoke.Types.Assert
import Test.Smoke.Types.Base
import Test.Smoke.Types.Errors
import Test.Smoke.Types.Plans
import Test.Smoke.Types.Tests
class IsSuccess a where
isSuccess :: a -> Bool
isFailure :: a -> Bool
isFailure = not . isSuccess
type Results = [SuiteResult]
data SuiteResult
= SuiteResultError SuiteName SuiteError
| SuiteResult SuiteName (ResolvedPath Dir) [TestResult]
data TestResult
= TestResult
{ resultPlan :: TestPlan,
resultStatus :: EqualityResult Status,
resultStdOut :: AssertionResult StdOut,
resultStdErr :: AssertionResult StdErr,
resultFiles :: Map (RelativePath File) (AssertionResult TestFileContents)
}
| TestError Test SmokeError
| TestIgnored Test
instance IsSuccess TestResult where
isSuccess (TestResult _ statusResult stdOutResult stdErrResult filesResults) =
isSuccess statusResult && isSuccess stdOutResult && isSuccess stdErrResult && all isSuccess (Map.elems filesResults)
isSuccess TestError {} =
False
isSuccess TestIgnored {} =
False
data EqualityResult a
= EqualitySuccess
| EqualityFailure (Expected a) (Actual a)
deriving (Functor)
instance IsSuccess (EqualityResult a) where
isSuccess EqualitySuccess = True
isSuccess EqualityFailure {} = False
data AssertionResult a
= AssertionSuccess
| AssertionFailure (AssertionFailures a)
deriving (Functor)
instance IsSuccess (AssertionResult a) where
isSuccess AssertionSuccess = True
isSuccess AssertionFailure {} = False
| SamirTalwar/Smoke | src/lib/Test/Smoke/Types/Results.hs | mit | 1,689 | 0 | 11 | 293 | 437 | 244 | 193 | 48 | 0 |
module AddStuff where
addStuff :: Integer -> Integer -> Integer
addStuff a b = a + b + 5
addTen = addStuff 5
fifteen = addTen 5
main :: IO ()
main = do
let x = addStuff 10 15
y = addTen 100
z = fifteen
putStrLn "=== Calculations ==="
putStr "addStuff 10 15: "
print x
putStr "addTen 100 : "
print y
putStr "fifteen : "
print z
-- print
-- print fifteen
| Lyapunov/haskell-programming-from-first-principles | chapter_5/addstuff.hs | mit | 408 | 0 | 10 | 131 | 137 | 64 | 73 | 17 | 1 |
module Yesod.Auth.WeiXin.Utils where
import ClassyPrelude
import Yesod
import Control.Monad.Except hiding (replicateM)
import Data.List ((!!))
import Network.Wai (rawQueryString)
import System.Random (randomIO)
import qualified Control.Exception.Safe as ExcSafe
import Yesod.Compat
import WeiXin.PublicPlatform
import Yesod.Auth.WeiXin.Class
logSource :: Text
logSource = "WeixinAuthPlugin"
{-
hWithRedirectUrl :: (MonadHandler m, site ~ HandlerSite m, YesodAuthWeiXin site)
=> Route site
-> [(Text, Text)]
-> OAuthScope
-- ^ used only when inside WX
-> (WxppAppID -> UrlText -> m a)
-> m a
hWithRedirectUrl oauth_return_route params0 oauth_scope f = do
is_client_wx <- isJust <$> handlerGetWeixinClientVersion
let params = filter ((/= "code") . fst) params0
url_render <- getUrlRenderParams
let oauth_retrurn_url = UrlText $ url_render oauth_return_route params
oauth_retrurn_url2 <- liftHandlerT $ wxAuthConfigFixReturnUrl oauth_retrurn_url
let oauth_rdr_and_app_id = do
if is_client_wx
then do
app_id <- fmap fst wxAuthConfigInsideWX
random_state <- wxppOAuthMakeRandomState app_id
let m_comp_app_id = Nothing
let url = wxppOAuthRequestAuthInsideWx
m_comp_app_id
app_id
oauth_scope
oauth_retrurn_url2
random_state
return (app_id, url)
else do
app_id <- fmap fst wxAuthConfigOutsideWX
random_state <- wxppOAuthMakeRandomState app_id
let url = wxppOAuthRequestAuthOutsideWx app_id
oauth_retrurn_url2
random_state
return (app_id, url)
(app_id, rdr_url) <- liftHandlerT oauth_rdr_and_app_id
f app_id rdr_url
--}
neverCache :: MonadHandler m => m ()
neverCache = do
addHeader "Cache-Control" "no-cache, no-store, must-revalidate"
addHeader "Pragma" "no-cache"
addHeader "Expires" "0"
getCurrentUrl :: MonadHandler m => m Text
getCurrentUrl = do
req <- waiRequest
current_route <- getCurrentRoute >>= maybe (error "getCurrentRoute failed") return
url_render <- getUrlRender
return $ url_render current_route <> decodeUtf8 (rawQueryString req)
getOAuthAccessTokenBySecretOrBroker :: (IsString e, WxppApiBroker a
, HasWxppUrlConfig env, HasWxppUrlConfig env, HasWreqSession env
, ExcSafe.MonadCatch m, MonadIO m, MonadLogger m
)
=> env
-> Either WxppAppSecret a
-> WxppAppID
-> OAuthCode
-> ExceptT e m (Maybe OAuthAccessTokenResult)
getOAuthAccessTokenBySecretOrBroker wx_api_env secret_or_broker app_id code = do
case secret_or_broker of
Left secret -> do
err_or_atk_info <- lift $ tryWxppWsResult $
flip runReaderT wx_api_env $
wxppOAuthGetAccessToken app_id secret code
case err_or_atk_info of
Left err -> do
if fmap wxppToErrorCodeX (wxppCallWxError err) == Just (wxppToErrorCode WxppOAuthCodeHasBeenUsed)
then return Nothing
else do
$logErrorS logSource $
"wxppOAuthGetAccessToken failed: " <> tshow err
throwError "微信服务接口错误,请稍后重试"
Right x -> return $ Just x
Right broker -> do
bres <- liftIO $ wxppApiBrokerOAuthGetAccessToken broker app_id code
case bres of
Nothing -> do
$logErrorS logSource $
"wxppApiBrokerOAuthGetAccessToken return Nothing"
throwError "程序配置错误,请稍后重试"
Just (WxppWsResp (Left err@(WxppAppError wxerr _msg))) -> do
if wxppToErrorCodeX wxerr == wxppToErrorCode WxppOAuthCodeHasBeenUsed
then return Nothing
else do
$logErrorS logSource $
"wxppApiBrokerOAuthGetAccessToken failed: " <> tshow err
throwError "微信服务接口错误,请稍后重试"
Just (WxppWsResp (Right x)) -> return $ Just x
handlerGetQrCodeStateStorage :: (MonadHandler m, HandlerSite m ~ site, YesodAuthWeiXin site)
=> m ( Text -> HandlerOf site (Maybe WxScanQrCodeSess)
, Text -> WxScanQrCodeSess -> HandlerOf site ()
)
handlerGetQrCodeStateStorage = do
master_site <- getYesod
let m_storage = wxAuthQrCodeStateStorage master_site
case m_storage of
Just x -> return x
Nothing -> permissionDenied "no session storage available"
handlerGetQrCodeStateStorageAndSession :: ( m ~ HandlerOf site, YesodAuthWeiXin site)
=> Text
-> m ( ( Text -> HandlerOf site (Maybe WxScanQrCodeSess)
, Text -> WxScanQrCodeSess -> HandlerOf site ()
)
, WxScanQrCodeSess
)
handlerGetQrCodeStateStorageAndSession sess = do
(get_stat, save_stat) <- handlerGetQrCodeStateStorage
m_sess_dat <- get_stat sess
sess_dat <- case m_sess_dat of
Just x -> return x
Nothing -> permissionDenied "invalid session"
return ((get_stat, save_stat), sess_dat)
randomPick :: MonadIO m => [a] -> m a
randomPick choices = do
idx' <- liftIO randomIO
let idx = abs idx' `rem` chlen
return $ choices !! idx
where
chlen = length choices
randomString :: MonadIO m => Int -> [Char] -> m [Char]
randomString len chars = replicateM len (randomPick chars)
randomUrlSafeString :: MonadIO m => Int -> m [Char]
randomUrlSafeString = flip randomString $ ['0'..'9'] <> ['a'..'z'] <> ['A'..'Z'] <> "-_"
| txkaduo/yesod-auth-wx | Yesod/Auth/WeiXin/Utils.hs | mit | 6,525 | 0 | 23 | 2,426 | 1,099 | 537 | 562 | -1 | -1 |
{------------------------------------------------------------------------------
uPuppet: Catalog rendering in JSON
------------------------------------------------------------------------------}
module UPuppet.ShowJSON ( showJSON ) where
import UPuppet.CState
import UPuppet.Catalog
import UPuppet.AST
import Data.Aeson
import Data.Text (Text,pack)
import Data.ByteString.Char8 (unpack)
import Data.ByteString.Lazy (toStrict)
-- would be nice if a type like this was used everywhere for resources.
-- creating a local version here so we can use it with the JSON typeclass
-- (paul)
data ResourceT = ResourceT (Name, Name, [(Attri, UPuppet.AST.Value)])
showJSON :: CState -> Catalog -> String
showJSON st catalog = unpack $ toStrict $ encode (map ResourceT catalog)
instance ToJSON ResourceT where
-- only emit parameter map if nonempty
toJSON ( ResourceT ( typeString, titleString, [] ) ) =
object [ typeJSON, titleJSON ]
where
typeJSON = paramToJSON ( "type", ValueString typeString )
titleJSON = paramToJSON( "title", ValueString titleString )
toJSON ( ResourceT ( typeString, titleString, params ) ) =
object [ typeJSON, titleJSON, paramsJSON ]
where
typeJSON = paramToJSON ( "type", ValueString typeString )
titleJSON = paramToJSON( "title", ValueString titleString )
paramsJSON = (pack "parameters") .=
( object $ map paramToJSON params )
paramToJSON :: (Attri, UPuppet.AST.Value) -> (Text,Data.Aeson.Value)
paramToJSON (attr,value) = (pack attr) .= toJSON value
instance ToJSON UPuppet.AST.Value where
toJSON (ValueInt n) = toJSON n
toJSON (ValueBool b) = toJSON b
toJSON (ValueString str) = toJSON str
toJSON (ValueFloat f) = toJSON f
toJSON (ValueArray vs) = toJSON vs
toJSON (ValueHash vvs) = object $ map hashPairToJSON vvs
toJSON (ValueRef rn t) = toJSON (rn ++ "[" ++ t ++ "]")
-- I think that the type definitions are wrong here?
-- surely, the hash keys should be strings (only) ?
-- (paul)
hashPairToJSON :: (UPuppet.AST.Value, UPuppet.AST.Value) -> (Text,Data.Aeson.Value)
hashPairToJSON (attrValue,value) = case attrValue of
(ValueString s) -> (pack s) .= toJSON value
otherwise -> error "hash key is not a string???"
| dcspaul/uPuppet | Src/UPuppet/ShowJSON.hs | mit | 2,224 | 11 | 11 | 384 | 612 | 336 | 276 | 36 | 2 |
module Pattern1 where
data Bool = False | True
not True = False
not False = True
| Lemmih/haskell-tc | tests/Pattern1.hs | mit | 83 | 0 | 5 | 19 | 30 | 17 | 13 | 4 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Hpack.Render.Dsl (
-- * AST
Element (..)
, Value (..)
-- * Render
, RenderSettings (..)
, CommaStyle (..)
, defaultRenderSettings
, Alignment (..)
, Nesting
, render
-- * Utils
, sortFieldsBy
#ifdef TEST
, Lines (..)
, renderValue
, addSortKey
#endif
) where
import Data.String
import Data.List
data Value =
Literal String
| CommaSeparatedList [String]
| LineSeparatedList [String]
| WordList [String]
deriving (Eq, Show)
data Element = Stanza String [Element] | Group Element Element | Field String Value | Verbatim String
deriving (Eq, Show)
data Lines = SingleLine String | MultipleLines [String]
deriving (Eq, Show)
data CommaStyle = LeadingCommas | TrailingCommas
deriving (Eq, Show)
newtype Nesting = Nesting Int
deriving (Eq, Show, Num, Enum)
newtype Alignment = Alignment Int
deriving (Eq, Show, Num)
data RenderSettings = RenderSettings {
renderSettingsIndentation :: Int
, renderSettingsFieldAlignment :: Alignment
, renderSettingsCommaStyle :: CommaStyle
} deriving (Eq, Show)
defaultRenderSettings :: RenderSettings
defaultRenderSettings = RenderSettings 2 0 LeadingCommas
render :: RenderSettings -> Nesting -> Element -> [String]
render settings nesting (Stanza name elements) = indent settings nesting name : renderElements settings (succ nesting) elements
render settings nesting (Group a b) = render settings nesting a ++ render settings nesting b
render settings nesting (Field name value) = renderField settings nesting name value
render settings nesting (Verbatim str) = map (indent settings nesting) (lines str)
renderElements :: RenderSettings -> Nesting -> [Element] -> [String]
renderElements settings nesting = concatMap (render settings nesting)
renderField :: RenderSettings -> Nesting -> String -> Value -> [String]
renderField settings@RenderSettings{..} nesting name value = case renderValue settings value of
SingleLine "" -> []
SingleLine x -> [indent settings nesting (name ++ ": " ++ padding ++ x)]
MultipleLines [] -> []
MultipleLines xs -> (indent settings nesting name ++ ":") : map (indent settings $ succ nesting) xs
where
Alignment fieldAlignment = renderSettingsFieldAlignment
padding = replicate (fieldAlignment - length name - 2) ' '
renderValue :: RenderSettings -> Value -> Lines
renderValue RenderSettings{..} v = case v of
Literal s -> SingleLine s
WordList ws -> SingleLine $ unwords ws
LineSeparatedList xs -> renderLineSeparatedList renderSettingsCommaStyle xs
CommaSeparatedList xs -> renderCommaSeparatedList renderSettingsCommaStyle xs
renderLineSeparatedList :: CommaStyle -> [String] -> Lines
renderLineSeparatedList style = MultipleLines . map (padding ++)
where
padding = case style of
LeadingCommas -> " "
TrailingCommas -> ""
renderCommaSeparatedList :: CommaStyle -> [String] -> Lines
renderCommaSeparatedList style = MultipleLines . case style of
LeadingCommas -> map renderLeadingComma . zip (True : repeat False)
TrailingCommas -> map renderTrailingComma . reverse . zip (True : repeat False) . reverse
where
renderLeadingComma :: (Bool, String) -> String
renderLeadingComma (isFirst, x)
| isFirst = " " ++ x
| otherwise = ", " ++ x
renderTrailingComma :: (Bool, String) -> String
renderTrailingComma (isLast, x)
| isLast = x
| otherwise = x ++ ","
instance IsString Value where
fromString = Literal
indent :: RenderSettings -> Nesting -> String -> String
indent RenderSettings{..} (Nesting nesting) s = replicate (nesting * renderSettingsIndentation) ' ' ++ s
sortFieldsBy :: [String] -> [Element] -> [Element]
sortFieldsBy existingFieldOrder =
map snd
. sortOn fst
. addSortKey
. map (\a -> (existingIndex a, a))
where
existingIndex :: Element -> Maybe Int
existingIndex (Field name _) = name `elemIndex` existingFieldOrder
existingIndex _ = Nothing
addSortKey :: [(Maybe Int, a)] -> [((Int, Int), a)]
addSortKey = go (-1) . zip [0..]
where
go :: Int -> [(Int, (Maybe Int, a))] -> [((Int, Int), a)]
go n xs = case xs of
[] -> []
(x, (Just y, a)) : ys -> ((y, x), a) : go y ys
(x, (Nothing, a)) : ys -> ((n, x), a) : go n ys
| haskell-tinc/hpack | src/Hpack/Render/Dsl.hs | mit | 4,314 | 0 | 14 | 834 | 1,478 | 792 | 686 | 96 | 4 |
module Storage.Distributed where
| axman6/HaskellMR | src/Storage/Distributed.hs | mit | 34 | 0 | 3 | 4 | 6 | 4 | 2 | 1 | 0 |
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module Yage.Geometry
( module Yage.Geometry
, module Elements
) where
import Yage.Lens
import Yage.Math
import Yage.Prelude hiding (any, sum, toList, (++))
import Control.Applicative (liftA3)
import Data.Binary
import Data.Foldable (any, toList)
import Data.Vector ((++))
import qualified Data.Vector as V
import qualified Data.Vector.Binary ()
import Yage.Geometry.Elements as Elements
-- wrapping neccassry because of ghc bug
-- https://github.com/bos/vector-binary-instances/issues/4
newtype GeoSurface e = GeoSurface { unGeoSurface :: Vector e }
deriving ( Show, Eq, Ord, Functor, Foldable, Traversable, Generic )
data Geometry e v = Geometry
{ _geoVertices :: Vector v
-- ^ all vertices of this geometry
, _geoSurfaces :: Vector (GeoSurface e)
-- ^ list of surfaces of the geometry. defined by objects (like Triangle Int) with indices to `geoVertices`
} deriving ( Show, Eq, Ord, Functor, Foldable, Traversable, Generic )
makeLenses ''Geometry
type TriGeo = Geometry (Triangle Int)
-- | constructs a TriGeo from vertices, interpreted as triangles, as single surface and without reindexing
makeSimpleTriGeo :: Vector v -> TriGeo v
makeSimpleTriGeo verts = Geometry verts simpleIxs
where
triCnt = V.length verts `div` 3
simpleIxs = V.singleton . GeoSurface $ V.zipWith3 Triangle
(V.generate triCnt (3*))
(V.generate triCnt (\i -> i*3+1))
(V.generate triCnt (\i -> i*3+2))
-- | like `makeSimpleTriGeo` but extracts vertices from a `Foldable`
makeSimpleTriGeoF :: ( HasTriangles t, Foldable f ) => f (t v) -> TriGeo v
makeSimpleTriGeoF = makeSimpleTriGeo . V.concatMap (V.fromList . vertices) . V.map triangles . V.fromList . toList
empty :: Geometry e v
empty = Geometry V.empty V.empty
{--
indexedSurface :: Eq v => Surface (Triangle v) -> TriGeo v
indexedSurface triSurf =
let surfVec = V.fromList $ nub $ concatMap vertices $ getSurface triSurf
in Geometry { geoVerices = undefined
, geoElements = undefined
}
--}
type Pos = V3
type Normal = V3
type Tex = V2
type TBN a = M33 a
-- | calc tangent spaces for each triangle. averages for normals and tangents are calculated on surfaces
calcTangentSpaces :: ( Epsilon a, Floating a ) =>
TriGeo (Pos a) ->
TriGeo (Tex a) ->
TriGeo (TBN a)
calcTangentSpaces posGeo texGeo =
calcTangentSpaces' posGeo texGeo $ calcNormals posGeo
calcNormals :: ( Epsilon a, Floating a )
=> TriGeo (Pos a) -> TriGeo (Normal a)
calcNormals geo = uncurry Geometry normalsOverSurfaces
where
normalsOverSurfaces = V.foldl' normalsForSurface (V.empty, V.empty) (geo^.geoSurfaces)
normalsForSurface (normsAccum, surfacesAccum) (GeoSurface surface) =
let (normVerts, normedSurface) = V.foldl' (normalsForTriangle surface) (normsAccum, V.empty) surface
in (normVerts, surfacesAccum `V.snoc` (GeoSurface normedSurface) )
normalsForTriangle inSurface (vertsAccum, surfaceAccum) triangle =
let normedTri = fmap (calcAvgNorm inSurface) triangle
idx = V.length vertsAccum
idxTri = Triangle idx (idx + 1) (idx + 2)
in vertsAccum `seq`
surfaceAccum `seq`
(vertsAccum ++ (V.fromList . toList $ normedTri), surfaceAccum `V.snoc` idxTri)
posVerts = geo^.geoVertices
calcAvgNorm surface idx = averageNorm $ V.map (triangleUnnormal . toPosTri) $ getShares idx surface
toPosTri = fmap (posVerts V.!)
calcTangentSpaces' :: forall a. ( Epsilon a, Floating a ) =>
TriGeo (Pos a) ->
TriGeo (Tex a) ->
TriGeo (Normal a) ->
TriGeo (TBN a)
calcTangentSpaces' posGeo texGeo normGeo
| not compatibleSurfaces = error "calcTangentSpaces': surfaces doesn't match"
| otherwise = uncurry Geometry tbnOverSurfaces
where
tbnOverSurfaces = V.foldl' tbnForSurface (V.empty, V.empty) pntIdxs
tbnForSurface (tbnAccum, surfacesAccum) (GeoSurface geoSurface) =
let (tbnVerts, tbnSurface) = V.foldl' (tbnForTriangle geoSurface) (tbnAccum, V.empty) geoSurface
in tbnVerts `seq`
surfacesAccum `seq`
(tbnVerts, surfacesAccum `V.snoc` (GeoSurface tbnSurface) )
tbnForTriangle inSurface (vertsAccum, surfaceAccum) triangle =
let tbnTriangle = fmap (calcTangentSpace inSurface) triangle
idx = V.length vertsAccum
idxTri = Triangle idx (idx + 1) (idx + 2)
in vertsAccum `seq`
surfaceAccum `seq`
(vertsAccum ++ (V.fromList . toList $ tbnTriangle), surfaceAccum `V.snoc` idxTri )
pntIdxs :: Vector (GeoSurface (Triangle (Int, Int, Int)))
pntIdxs =
let mkSurface (GeoSurface p) (GeoSurface n) (GeoSurface t) = GeoSurface $ V.zipWith3 (liftA3 (,,)) p n t
in V.zipWith3 mkSurface (posGeo^.geoSurfaces) ( normGeo^.geoSurfaces) ( texGeo^.geoSurfaces)
toPNTTri :: ( Epsilon a, Floating a) => Triangle (Int, Int, Int) -> (Triangle (Pos a), Triangle (Normal a), Triangle (Tex a))
toPNTTri tri = ( (V.!) (posGeo^.geoVertices) . (^._1) <$> tri
, (V.!) (normGeo^.geoVertices) . (^._2) <$> tri
, (V.!) (texGeo^.geoVertices) . (^._3) <$> tri
)
calcTangentSpace :: ( Epsilon a, Floating a) => V.Vector (Triangle (Int, Int, Int)) -> (Int, Int, Int) -> M33 a
calcTangentSpace geoSurface (posIdx, normIdx, _texIdx) =
let normal = V.unsafeIndex (normGeo^.geoVertices) normIdx
toPTTri (p,_,t) = (p,t)
sharePosIdx :: Int -> Triangle (Int, Int, Int) -> Bool
sharePosIdx i = any (\(p,_,_) -> p==i)
~(V3 t b _n) = V.sum $ V.map (uncurry triangleTangentSpace . toPTTri . toPNTTri) $ V.filter (sharePosIdx posIdx) geoSurface
in orthonormalize $ V3 t b normal
compatibleSurfaces =
let posSurfaces = posGeo^.geoSurfaces^..traverse.to (length.unGeoSurface)
texSurfaces = texGeo^.geoSurfaces^..traverse.to (length.unGeoSurface)
normSurfaces = normGeo^.geoSurfaces^..traverse.to (length.unGeoSurface)
in posSurfaces == texSurfaces && posSurfaces == normSurfaces
getShares :: Int -> Vector (Triangle Int) -> Vector (Triangle Int)
getShares i = V.filter (any (==i))
instance Binary e => Binary (GeoSurface e)
instance (Binary e, Binary v) => Binary (Geometry e v)
instance (NFData e) => NFData (GeoSurface e) where rnf = genericRnf
instance (NFData e, NFData v) => NFData (Geometry e v) where rnf = genericRnf
| MaxDaten/yage-geometry | src/Yage/Geometry.hs | mit | 7,237 | 0 | 17 | 1,890 | 2,124 | 1,143 | 981 | -1 | -1 |
-- | pontarius core
module Main where
| Philonous/pontarius-core | src/Main.hs | mit | 39 | 0 | 2 | 8 | 5 | 4 | 1 | 1 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.