code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.IAM.DeactivateMFADevice
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deactivates the specified MFA device and removes it from association
-- with the user name for which it was originally enabled.
--
-- For more information about creating and working with virtual MFA
-- devices, go to
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_VirtualMFA.html Using a Virtual MFA Device>
-- in the /Using IAM/ guide.
--
-- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_DeactivateMFADevice.html AWS API Reference> for DeactivateMFADevice.
module Network.AWS.IAM.DeactivateMFADevice
(
-- * Creating a Request
deactivateMFADevice
, DeactivateMFADevice
-- * Request Lenses
, dmdUserName
, dmdSerialNumber
-- * Destructuring the Response
, deactivateMFADeviceResponse
, DeactivateMFADeviceResponse
) where
import Network.AWS.IAM.Types
import Network.AWS.IAM.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'deactivateMFADevice' smart constructor.
data DeactivateMFADevice = DeactivateMFADevice'
{ _dmdUserName :: !Text
, _dmdSerialNumber :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeactivateMFADevice' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dmdUserName'
--
-- * 'dmdSerialNumber'
deactivateMFADevice
:: Text -- ^ 'dmdUserName'
-> Text -- ^ 'dmdSerialNumber'
-> DeactivateMFADevice
deactivateMFADevice pUserName_ pSerialNumber_ =
DeactivateMFADevice'
{ _dmdUserName = pUserName_
, _dmdSerialNumber = pSerialNumber_
}
-- | The name of the user whose MFA device you want to deactivate.
dmdUserName :: Lens' DeactivateMFADevice Text
dmdUserName = lens _dmdUserName (\ s a -> s{_dmdUserName = a});
-- | The serial number that uniquely identifies the MFA device. For virtual
-- MFA devices, the serial number is the device ARN.
dmdSerialNumber :: Lens' DeactivateMFADevice Text
dmdSerialNumber = lens _dmdSerialNumber (\ s a -> s{_dmdSerialNumber = a});
instance AWSRequest DeactivateMFADevice where
type Rs DeactivateMFADevice =
DeactivateMFADeviceResponse
request = postQuery iAM
response = receiveNull DeactivateMFADeviceResponse'
instance ToHeaders DeactivateMFADevice where
toHeaders = const mempty
instance ToPath DeactivateMFADevice where
toPath = const "/"
instance ToQuery DeactivateMFADevice where
toQuery DeactivateMFADevice'{..}
= mconcat
["Action" =: ("DeactivateMFADevice" :: ByteString),
"Version" =: ("2010-05-08" :: ByteString),
"UserName" =: _dmdUserName,
"SerialNumber" =: _dmdSerialNumber]
-- | /See:/ 'deactivateMFADeviceResponse' smart constructor.
data DeactivateMFADeviceResponse =
DeactivateMFADeviceResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeactivateMFADeviceResponse' with the minimum fields required to make a request.
--
deactivateMFADeviceResponse
:: DeactivateMFADeviceResponse
deactivateMFADeviceResponse = DeactivateMFADeviceResponse'
| olorin/amazonka | amazonka-iam/gen/Network/AWS/IAM/DeactivateMFADevice.hs | mpl-2.0 | 3,910 | 0 | 9 | 755 | 445 | 272 | 173 | 63 | 1 |
{-# LANGUAGE CPP, ForeignFunctionInterface, DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-----------------------------------------------------------------------------------------
{-| Module : WxcTypes
Copyright : (c) Daan Leijen 2003, 2004
License : wxWindows
Maintainer : [email protected]
Stability : provisional
Portability : portable
Basic types and marshalling code for the wxWidgets C library.
-}
-----------------------------------------------------------------------------------------
module Graphics.UI.WXCore.WxcTypes(
-- * Object types
Object, objectNull, objectIsNull, objectCast, objectIsManaged
, objectDelete
, objectFromPtr, managedObjectFromPtr
, withObjectPtr, withObjectRef
, withObjectResult, withManagedObjectResult
, objectFinalize, objectNoFinalize
-- , Managed, managedNull, managedIsNull, managedCast, createManaged, withManaged, managedTouch
-- * Type synonyms
, Id
, Style
, EventId
-- * Basic types
, fromBool, toBool
-- ** Point
, Point, Point2(Point,pointX,pointY), point, pt, pointFromVec, pointFromSize, pointZero, pointNull
-- ** Size
, Size, Size2D(Size,sizeW,sizeH), sz, sizeFromPoint, sizeFromVec, sizeZero, sizeNull
-- ** Vector
, Vector, Vector2(Vector,vecX,vecY), vector, vec, vecFromPoint, vecFromSize, vecZero, vecNull
-- ** Rectangle
, Rect, Rect2D(Rect,rectLeft,rectTop,rectWidth,rectHeight)
, rectTopLeft, rectTopRight, rectBottomLeft, rectBottomRight, rectBottom, rectRight
, rect, rectBetween, rectFromSize, rectZero, rectNull, rectSize, rectIsEmpty
-- ** Color
, Color(..), rgb, colorRGB, rgba, colorRGBA, colorRed, colorGreen, colorBlue, colorAlpha
, intFromColor, colorFromInt, fromColor, toColor, colorOk, colorIsOk
-- * Marshalling
-- ** Basic types
, withPointResult, withWxPointResult, toCIntPointX, toCIntPointY, fromCPoint, withCPoint
, withPointDoubleResult, toCDoublePointX, toCDoublePointY, fromCPointDouble, withCPointDouble
, withSizeResult, withWxSizeResult, toCIntSizeW, toCIntSizeH, fromCSize, withCSize
, withSizeDoubleResult, toCDoubleSizeW, toCDoubleSizeH, fromCSizeDouble, withCSizeDouble
, withVectorResult, withWxVectorResult, toCIntVectorX, toCIntVectorY, fromCVector, withCVector
, withVectorDoubleResult, toCDoubleVectorX, toCDoubleVectorY, fromCVectorDouble, withCVectorDouble
, withRectResult, withWxRectResult, withWxRectPtr, toCIntRectX, toCIntRectY, toCIntRectW, toCIntRectH, fromCRect, withCRect
, withRectDoubleResult, toCDoubleRectX, toCDoubleRectY, toCDoubleRectW, toCDoubleRectH, fromCRectDouble, withCRectDouble
, withArray, withArrayString, withArrayWString, withArrayInt, withArrayIntPtr, withArrayObject
, withArrayIntResult, withArrayIntPtrResult, withArrayStringResult, withArrayWStringResult, withArrayObjectResult
, colourFromColor, colorFromColour
, colourCreate, colourSafeDelete -- , colourCreateRGB, colourRed, colourGreen, colourBlue colourAlpha
-- ** Managed object types
-- , managedAddFinalizer
, TreeItem, treeItemInvalid, treeItemIsOk, treeItemFromInt
, withRefTreeItemId, withTreeItemIdPtr, withTreeItemIdRef, withManagedTreeItemIdResult
, withStringRef, withStringPtr, withManagedStringResult
, withRefColour, withColourRef, withColourPtr, withManagedColourResult
, withRefBitmap, withManagedBitmapResult
, withRefCursor, withManagedCursorResult
, withRefIcon, withManagedIconResult
, withRefPen, withManagedPenResult
, withRefBrush, withManagedBrushResult
, withRefFont, withManagedFontResult
, withRefImage
, withRefListItem
, withRefFontData
, withRefPrintData
, withRefPageSetupDialogData
, withRefPrintDialogData
, withRefDateTime, withManagedDateTimeResult
, withRefGridCellCoordsArray, withManagedGridCellCoordsArrayResult
-- ** Primitive types
-- *** CString
, CString(..), withCString, withStringResult
, CWString(..), withCWString, withWStringResult
-- *** ByteString
, withByteStringResult, withLazyByteStringResult
-- *** CInt
, CInt(..), toCInt, fromCInt, withIntResult
-- *** IntPtr
, IntPtr(..)
-- *** CIntPtr
, CIntPtr(..), toCIntPtr, fromCIntPtr, withIntPtrResult
-- *** Word
, Word(..)
-- *** 8 bit Word
, Word8(..)
-- *** 64 bit Integer
, Int64(..)
-- *** CDouble
, CDouble(..), toCDouble, fromCDouble, withDoubleResult
-- *** CChar
, CChar(..), toCChar, fromCChar, withCharResult
, CWchar(..), toCWchar
-- *** CBool
, CBool(..), toCBool, fromCBool, withBoolResult
-- ** Pointers
, Ptr(..), ptrNull, ptrIsNull, ptrCast, ForeignPtr, FunPtr, toCFunPtr
) where
import Control.Exception
import System.IO.Unsafe( unsafePerformIO )
import Foreign.C
import Foreign.Ptr
import Foreign.Storable
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array
import Foreign.Marshal.Utils (fromBool, toBool)
{- note: for GHC 6.10.2 or higher, recommends to use "import Foreign.Concurrent"
See http://www.haskell.org/pipermail/cvs-ghc/2009-January/047120.html -}
import Foreign.ForeignPtr hiding (newForeignPtr,addForeignPtrFinalizer)
import Foreign.Concurrent
import Data.Array.MArray (MArray)
import Data.Array.Unboxed (IArray, UArray)
import Data.Bits( shiftL, shiftR, (.&.), (.|.) )
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as LB
import qualified Data.ByteString.Char8 as BC (pack)
import qualified Data.ByteString.Lazy.Char8 as LBC (pack)
{- note: this is just for instances for the WX library and not necessary for WXCore -}
import Data.Dynamic
import Data.Int
import Data.Word
import Debug.Trace (traceIO)
import Graphics.UI.WXCore.WxcObject
import Graphics.UI.WXCore.WxcClassTypes
{-----------------------------------------------------------------------------------------
Objects
-----------------------------------------------------------------------------------------}
-- | An @Id@ is used to identify objects during event handling.
type Id = Int
-- | An @EventId@ is identifies specific events.
type EventId = Int
-- | A @Style@ is normally used as a flag mask to specify some window style
type Style = Int
-- | Delete a wxObject, works for managed and unmanaged objects.
objectDelete :: WxObject a -> IO ()
objectDelete obj
= if objectIsManaged obj
then objectFinalize obj
else withObjectPtr obj $ \p ->
wxObject_SafeDelete p
-- | Create a managed object that will be deleted using |wxObject_SafeDelete|.
managedObjectFromPtr :: Ptr (TWxObject a) -> IO (WxObject a)
managedObjectFromPtr p
= do mp <- wxManagedPtr_CreateFromObject p
objectFromManagedPtr mp
-- | Create a managed object that will be deleted using |wxObject_SafeDelete|.
withManagedObjectResult :: IO (Ptr (TWxObject a)) -> IO (WxObject a)
withManagedObjectResult io
= do p <- io
managedObjectFromPtr p
-- | Return an unmanaged object.
withObjectResult :: IO (Ptr a) -> IO (Object a)
withObjectResult io
= do p <- io
return (objectFromPtr p)
-- | Extract the object pointer and raise an exception if @NULL@.
-- Otherwise continue with the valid pointer.
withObjectRef :: String -> Object a -> (Ptr a -> IO b) -> IO b
withObjectRef msg obj f
= withObjectPtr obj $ \p ->
withValidPtr msg p f
-- | Execute the continuation when the pointer is not null and
-- raise an error otherwise.
withValidPtr :: String -> Ptr a -> (Ptr a -> IO b) -> IO b
withValidPtr msg p f
= if (p == nullPtr)
then ioError (userError ("wxHaskell: NULL object" ++ (if null msg then "" else ": " ++ msg)))
else f p
foreign import ccall wxManagedPtr_CreateFromObject :: Ptr (TWxObject a) -> IO (ManagedPtr (TWxObject a))
foreign import ccall wxObject_SafeDelete :: Ptr (TWxObject a) -> IO ()
{-----------------------------------------------------------------------------------------
Point
-----------------------------------------------------------------------------------------}
--- | Define Point type synonym for backward compatibility.
type Point = Point2 Int
-- | A point has an x and y coordinate. Coordinates are normally relative to the
-- upper-left corner of their view frame, where a positive x goes to the right and
-- a positive y to the bottom of the view.
data (Num a) => Point2 a = Point
{ pointX :: !a -- ^ x component of a point.
, pointY :: !a -- ^ y component of a point.
}
deriving (Eq,Show,Read,Typeable)
-- | Construct a point.
point :: (Num a) => a -> a -> Point2 a
point x y = Point x y
-- | Shorter function to construct a point.
pt :: (Num a) => a -> a -> Point2 a
pt x y = Point x y
pointFromVec :: (Num a) => Vector -> Point2 a
pointFromVec (Vector x y)
= Point (fromIntegral x) (fromIntegral y)
pointFromSize :: (Num a) => Size -> Point2 a
pointFromSize (Size w h)
= Point (fromIntegral w) (fromIntegral h)
-- | Point at the origin.
pointZero :: (Num a) => Point2 a
pointZero
= Point 0 0
-- | A `null' point is not a legal point (x and y are -1) and can be used for some
-- wxWidgets functions to select a default point.
pointNull :: (Num a) => Point2 a
pointNull
= Point (-1) (-1)
-- marshalling
withCPoint :: Point2 Int -> (CInt -> CInt -> IO a) -> IO a
withCPoint (Point x y) f
= f (toCInt x) (toCInt y)
withPointResult :: (Ptr CInt -> Ptr CInt -> IO ()) -> IO (Point2 Int)
withPointResult f
= alloca $ \px ->
alloca $ \py ->
do f px py
x <- peek px
y <- peek py
return (fromCPoint x y)
toCIntPointX, toCIntPointY :: Point2 Int -> CInt
toCIntPointX (Point x y) = toCInt x
toCIntPointY (Point x y) = toCInt y
fromCPoint :: CInt -> CInt -> Point2 Int
fromCPoint x y
= Point (fromCInt x) (fromCInt y)
withCPointDouble :: Point2 Double -> (CDouble -> CDouble -> IO a) -> IO a
withCPointDouble (Point x y) f
= f (toCDouble x) (toCDouble y)
withPointDoubleResult :: (Ptr CDouble -> Ptr CDouble -> IO ()) -> IO (Point2 Double)
withPointDoubleResult f
= alloca $ \px ->
alloca $ \py ->
do f px py
x <- peek px
y <- peek py
return (fromCPointDouble x y)
toCDoublePointX, toCDoublePointY :: Point2 Double -> CDouble
toCDoublePointX (Point x y) = toCDouble x
toCDoublePointY (Point x y) = toCDouble y
fromCPointDouble :: CDouble -> CDouble -> Point2 Double
fromCPointDouble x y
= Point (fromCDouble x) (fromCDouble y)
{-
-- | A @wxPoint@ object.
type WxPointObject a = Ptr (CWxPointObject a)
type TWxPointObject a = CWxPointObject a
data CWxPointObject a = CWxPointObject
-}
withWxPointResult :: IO (Ptr (TWxPoint a)) -> IO (Point2 Int)
withWxPointResult io
= do pt <- io
x <- wxPoint_GetX pt
y <- wxPoint_GetY pt
wxPoint_Delete pt
return (fromCPoint x y)
foreign import ccall wxPoint_Delete :: Ptr (TWxPoint a) -> IO ()
foreign import ccall wxPoint_GetX :: Ptr (TWxPoint a) -> IO CInt
foreign import ccall wxPoint_GetY :: Ptr (TWxPoint a) -> IO CInt
{-----------------------------------------------------------------------------------------
Size
-----------------------------------------------------------------------------------------}
--- | Define Point type synonym for backward compatibility.
type Size = Size2D Int
-- | A @Size@ has a width and height.
data (Num a) => Size2D a = Size
{ sizeW :: !a -- ^ the width of a size
, sizeH :: !a -- ^ the height of a size
}
deriving (Eq,Show,Typeable)
-- | Construct a size from a width and height.
size :: (Num a) => a -> a -> Size2D a
size w h
= Size w h
-- | Short function to construct a size
sz :: (Num a) => a -> a -> Size2D a
sz w h
= Size w h
sizeFromPoint :: (Num a) => Point2 a -> Size2D a
sizeFromPoint (Point x y)
= Size x y
sizeFromVec :: (Num a) => Vector2 a -> Size2D a
sizeFromVec (Vector x y)
= Size x y
sizeZero :: (Num a) => Size2D a
sizeZero
= Size 0 0
-- | A `null' size is not a legal size (width and height are -1) and can be used for some
-- wxWidgets functions to select a default size.
sizeNull :: (Num a) => Size2D a
sizeNull
= Size (-1) (-1)
-- marshalling
withCSize :: Size -> (CInt -> CInt -> IO a) -> IO a
withCSize (Size w h) f
= f (toCInt w) (toCInt h)
withSizeResult :: (Ptr CInt -> Ptr CInt -> IO ()) -> IO Size
withSizeResult f
= alloca $ \cw ->
alloca $ \ch ->
do f cw ch
w <- peek cw
h <- peek ch
return (fromCSize w h)
fromCSize :: CInt -> CInt -> Size
fromCSize w h
= Size (fromCInt w) (fromCInt h)
toCIntSizeW, toCIntSizeH :: Size -> CInt
toCIntSizeW (Size w h) = toCInt w
toCIntSizeH (Size w h) = toCInt h
withCSizeDouble :: Size2D Double -> (CDouble -> CDouble -> IO a) -> IO a
withCSizeDouble (Size w h) f
= f (toCDouble w) (toCDouble h)
withSizeDoubleResult :: (Ptr CDouble -> Ptr CDouble -> IO ()) -> IO (Size2D Double)
withSizeDoubleResult f
= alloca $ \cw ->
alloca $ \ch ->
do f cw ch
w <- peek cw
h <- peek ch
return (fromCSizeDouble w h)
fromCSizeDouble :: CDouble -> CDouble -> Size2D Double
fromCSizeDouble w h
= Size (fromCDouble w) (fromCDouble h)
toCDoubleSizeW, toCDoubleSizeH :: Size2D Double -> CDouble
toCDoubleSizeW (Size w h) = toCDouble w
toCDoubleSizeH (Size w h) = toCDouble h
{-
-- | A @wxSize@ object.
type WxSizeObject a = Ptr (CWxSizeObject a)
type TWxSizeObject a = CWxSizeObject a
data CWxSizeObject a = CWxSizeObject
-}
withWxSizeResult :: IO (Ptr (TWxSize a)) -> IO Size
withWxSizeResult io
= do sz <- io
w <- wxSize_GetWidth sz
h <- wxSize_GetHeight sz
wxSize_Delete sz
return (fromCSize w h)
foreign import ccall wxSize_Delete :: Ptr (TWxSize a) -> IO ()
foreign import ccall wxSize_GetWidth :: Ptr (TWxSize a) -> IO CInt
foreign import ccall wxSize_GetHeight :: Ptr (TWxSize a) -> IO CInt
{-----------------------------------------------------------------------------------------
Vector
-----------------------------------------------------------------------------------------}
--- | Define Point type synonym for backward compatibility.
type Vector = Vector2 Int
-- | A vector with an x and y delta.
data (Num a) => Vector2 a = Vector
{ vecX :: !a -- ^ delta-x component of a vector
, vecY :: !a -- ^ delta-y component of a vector
}
deriving (Eq,Show,Read,Typeable)
-- | Construct a vector.
vector :: (Num a) => a -> a -> Vector2 a
vector dx dy = Vector dx dy
-- | Short function to construct a vector.
vec :: (Num a) => a -> a -> Vector2 a
vec dx dy = Vector dx dy
-- | A zero vector
vecZero :: (Num a) => Vector2 a
vecZero
= Vector 0 0
-- | A `null' vector has a delta x and y of -1 and can be used for some
-- wxWidgets functions to select a default vector.
vecNull :: (Num a) => Vector2 a
vecNull
= Vector (-1) (-1)
vecFromPoint :: (Num a) => Point2 a -> Vector2 a
vecFromPoint (Point x y)
= Vector x y
vecFromSize :: Size -> Vector
vecFromSize (Size w h)
= Vector w h
-- marshalling
withCVector :: Vector -> (CInt -> CInt -> IO a) -> IO a
withCVector (Vector x y) f
= f (toCInt x) (toCInt y)
withVectorResult :: (Ptr CInt -> Ptr CInt -> IO ()) -> IO Vector
withVectorResult f
= alloca $ \px ->
alloca $ \py ->
do f px py
x <- peek px
y <- peek py
return (fromCVector x y)
toCIntVectorX, toCIntVectorY :: Vector -> CInt
toCIntVectorX (Vector x y) = toCInt x
toCIntVectorY (Vector x y) = toCInt y
fromCVector :: CInt -> CInt -> Vector
fromCVector x y
= Vector (fromCInt x) (fromCInt y)
withCVectorDouble :: Vector2 Double -> (CDouble -> CDouble -> IO a) -> IO a
withCVectorDouble (Vector x y) f
= f (toCDouble x) (toCDouble y)
withVectorDoubleResult :: (Ptr CDouble -> Ptr CDouble -> IO ()) -> IO (Vector2 Double)
withVectorDoubleResult f
= alloca $ \px ->
alloca $ \py ->
do f px py
x <- peek px
y <- peek py
return (fromCVectorDouble x y)
toCDoubleVectorX, toCDoubleVectorY :: Vector2 Double -> CDouble
toCDoubleVectorX (Vector x y) = toCDouble x
toCDoubleVectorY (Vector x y) = toCDouble y
fromCVectorDouble :: CDouble -> CDouble -> Vector2 Double
fromCVectorDouble x y
= Vector (fromCDouble x) (fromCDouble y)
withWxVectorResult :: IO (Ptr (TWxPoint a)) -> IO Vector
withWxVectorResult io
= do pt <- io
x <- wxPoint_GetX pt
y <- wxPoint_GetY pt
wxPoint_Delete pt
return (fromCVector x y)
{-----------------------------------------------------------------------------------------
Rectangle
-----------------------------------------------------------------------------------------}
--- | Define Point type synonym for backward compatibility.
type Rect = Rect2D Int
-- | A rectangle is defined by the left x coordinate, the top y coordinate,
-- the width and the height.
data (Num a) => Rect2D a = Rect
{ rectLeft :: !a
, rectTop :: !a
, rectWidth :: !a
, rectHeight :: !a
}
deriving (Eq,Show,Read,Typeable)
rectTopLeft, rectTopRight, rectBottomLeft, rectBottomRight :: (Num a) => Rect2D a -> Point2 a
rectTopLeft (Rect l t w h) = Point l t
rectTopRight (Rect l t w h) = Point (l+w) t
rectBottomLeft (Rect l t w h) = Point l (t+h)
rectBottomRight (Rect l t w h) = Point (l+w) (t+h)
rectBottom, rectRight :: (Num a) => Rect2D a -> a
rectBottom (Rect x y w h) = y + h
rectRight (Rect x y w h) = x + w
-- | Create a rectangle at a certain (upper-left) point with a certain size.
rect :: (Num a) => Point2 a -> Size2D a -> Rect2D a
rect (Point x y) (Size w h)
= Rect x y w h
-- | Construct a (positive) rectangle between two (arbitrary) points.
rectBetween :: (Num a, Ord a) => Point2 a -> Point2 a -> Rect2D a
rectBetween (Point x0 y0) (Point x1 y1)
= Rect (min x0 x1) (min y0 y1) (abs (x1-x0)) (abs (y1-y0))
-- | An empty rectangle at (0,0).
rectZero :: (Num a) => Rect2D a
rectZero
= Rect 0 0 0 0
-- | An `null' rectangle is not a valid rectangle (@Rect -1 -1 -1 -1@) but can
-- used for some wxWidgets functions to select a default rectangle. (i.e. 'frameCreate').
rectNull :: (Num a) => Rect2D a
rectNull
= Rect (-1) (-1) (-1) (-1)
-- | Get the size of a rectangle.
rectSize :: (Num a) => Rect2D a -> Size2D a
rectSize (Rect l t w h)
= Size w h
-- | Create a rectangle of a certain size with the upper-left corner at ('pt' 0 0).
rectFromSize :: (Num a) => Size2D a -> Rect2D a
rectFromSize (Size w h)
= Rect 0 0 w h
rectIsEmpty :: (Num a, Eq a) => Rect2D a -> Bool
rectIsEmpty (Rect l t w h)
= (w==0 && h==0)
-- marshalling 1
withCRect :: Rect -> (CInt -> CInt -> CInt -> CInt -> IO a) -> IO a
withCRect (Rect x0 y0 x1 y1) f
= f (toCInt (x0)) (toCInt (y0)) (toCInt (x1)) (toCInt (y1))
withRectResult :: (Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()) -> IO Rect
withRectResult f
= alloca $ \cx ->
alloca $ \cy ->
alloca $ \cw ->
alloca $ \ch ->
do f cx cy cw ch
x <- peek cx
y <- peek cy
w <- peek cw
h <- peek ch
return (fromCRect x y w h)
fromCRect :: CInt -> CInt -> CInt -> CInt -> Rect
fromCRect x y w h
= Rect (fromCInt x) (fromCInt y) (fromCInt w) (fromCInt h)
toCIntRectX, toCIntRectY, toCIntRectW, toCIntRectH :: Rect -> CInt
toCIntRectX (Rect x y w h) = toCInt x
toCIntRectY (Rect x y w h) = toCInt y
toCIntRectW (Rect x y w h) = toCInt w
toCIntRectH (Rect x y w h) = toCInt h
withCRectDouble :: Rect2D Double -> (CDouble -> CDouble -> CDouble -> CDouble -> IO a) -> IO a
withCRectDouble (Rect x0 y0 x1 y1) f
= f (toCDouble (x0)) (toCDouble (y0)) (toCDouble (x1)) (toCDouble (y1))
withRectDoubleResult :: (Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()) -> IO (Rect2D Double)
withRectDoubleResult f
= alloca $ \cx ->
alloca $ \cy ->
alloca $ \cw ->
alloca $ \ch ->
do f cx cy cw ch
x <- peek cx
y <- peek cy
w <- peek cw
h <- peek ch
return (fromCRectDouble x y w h)
fromCRectDouble :: CDouble -> CDouble -> CDouble -> CDouble -> Rect2D Double
fromCRectDouble x y w h
= Rect (fromCDouble x) (fromCDouble y) (fromCDouble w) (fromCDouble h)
toCDoubleRectX, toCDoubleRectY, toCDoubleRectW, toCDoubleRectH :: Rect2D Double -> CDouble
toCDoubleRectX (Rect x y w h) = toCDouble x
toCDoubleRectY (Rect x y w h) = toCDouble y
toCDoubleRectW (Rect x y w h) = toCDouble w
toCDoubleRectH (Rect x y w h) = toCDouble h
-- marshalling 2
{-
-- | A @wxRect@ object.
type WxRectObject a = Ptr (CWxRectObject a)
type TWxRectObject a = CWxRectObject a
data CWxRectObject a = CWxRectObject
-}
withWxRectRef :: String -> Rect -> (Ptr (TWxRect r) -> IO a) -> IO a
withWxRectRef msg r f
= withWxRectPtr r $ \p -> withValidPtr msg p f
withWxRectPtr :: Rect -> (Ptr (TWxRect r) -> IO a) -> IO a
withWxRectPtr r f
= bracket (withCRect r wxRect_Create)
(wxRect_Delete)
f
withWxRectResult :: IO (Ptr (TWxRect a)) -> IO Rect
withWxRectResult io
= do rt <- io
x <- wxRect_GetX rt
y <- wxRect_GetY rt
w <- wxRect_GetWidth rt
h <- wxRect_GetHeight rt
wxRect_Delete rt
return (fromCRect x y w h)
foreign import ccall wxRect_Create :: CInt -> CInt -> CInt -> CInt -> IO (Ptr (TWxRect a))
foreign import ccall wxRect_Delete :: Ptr (TWxRect a) -> IO ()
foreign import ccall wxRect_GetX :: Ptr (TWxRect a) -> IO CInt
foreign import ccall wxRect_GetY :: Ptr (TWxRect a) -> IO CInt
foreign import ccall wxRect_GetWidth :: Ptr (TWxRect a) -> IO CInt
foreign import ccall wxRect_GetHeight :: Ptr (TWxRect a) -> IO CInt
{-----------------------------------------------------------------------------------------
CInt
-----------------------------------------------------------------------------------------}
withIntResult :: IO CInt -> IO Int
withIntResult io
= do x <- io
return (fromCInt x)
toCInt :: Int -> CInt
toCInt i = fromIntegral i
fromCInt :: CInt -> Int
fromCInt ci
= fromIntegral ci
{-----------------------------------------------------------------------------------------
CIntPtr
-----------------------------------------------------------------------------------------}
withIntPtrResult :: IO CIntPtr -> IO IntPtr
withIntPtrResult io
= do x <- io
return (fromCIntPtr x)
toCIntPtr :: IntPtr -> CIntPtr
toCIntPtr i = fromIntegral i
fromCIntPtr :: CIntPtr -> IntPtr
fromCIntPtr ci
= fromIntegral ci
{-----------------------------------------------------------------------------------------
CDouble
-----------------------------------------------------------------------------------------}
withDoubleResult :: IO CDouble -> IO Double
withDoubleResult io
= do x <- io
return (fromCDouble x)
toCDouble :: Double -> CDouble
toCDouble d = realToFrac d
fromCDouble :: CDouble -> Double
fromCDouble cd
= realToFrac cd
{-----------------------------------------------------------------------------------------
CBool
-----------------------------------------------------------------------------------------}
type CBool = CInt
toCBool :: Bool -> CBool
toCBool = intToCBool . fromBool
withBoolResult :: IO CBool -> IO Bool
withBoolResult io
= do x <- io
return (fromCBool x)
fromCBool :: CBool -> Bool
fromCBool = toBool . cboolToInt
foreign import ccall "intToBool" intToCBool :: Int -> CBool
foreign import ccall "boolToInt" cboolToInt :: CBool -> Int
{-----------------------------------------------------------------------------------------
CString
-----------------------------------------------------------------------------------------}
withStringResult :: (Ptr CChar -> IO CInt) -> IO String
withStringResult f
= do len <- f nullPtr
if (len<=0)
then return ""
else withCString (replicate (fromCInt len) ' ') $ \cstr ->
do f cstr
peekCStringLen (cstr,fromCInt len)
withWStringResult :: (Ptr CWchar -> IO CInt) -> IO String
withWStringResult f
= do len <- f nullPtr
if (len<=0)
then return ""
else withCWString (replicate (fromCInt len) ' ') $ \cstr ->
do f cstr
peekCWString cstr
{-----------------------------------------------------------------------------------------
ByteString
-----------------------------------------------------------------------------------------}
-- TODO: replace this by more efficient implementation.
-- e.g. use mmap when bytestring support mmap interface.
withByteStringResult :: (Ptr CChar -> IO CInt) -> IO B.ByteString
withByteStringResult f
= do len <- f nullPtr
if (len<=0)
then return $ BC.pack ""
else withCString (replicate (fromCInt len) ' ') $ \cstr ->
do f cstr
B.packCStringLen (cstr,fromCInt len)
withLazyByteStringResult :: (Ptr CChar -> IO CInt) -> IO LB.ByteString
withLazyByteStringResult f
= do str <- withStringResult f
return $ LBC.pack str
{-----------------------------------------------------------------------------------------
Arrays
-----------------------------------------------------------------------------------------}
withArrayStringResult :: (Ptr (Ptr CChar) -> IO CInt) -> IO [String]
withArrayStringResult f
= do clen <- f nullPtr
let len = fromCInt clen
if (len <= 0)
then return []
else allocaArray len $ \carr ->
do f carr
arr <- peekArray len carr
mapM peekCString arr
-- FIXME: factorise with withArrayStringResult
withArrayWStringResult :: (Ptr (Ptr CWchar) -> IO CInt) -> IO [String]
withArrayWStringResult f
= do clen <- f nullPtr
let len = fromCInt clen
if (len <= 0)
then return []
else allocaArray len $ \carr ->
do f carr
arr <- peekArray len carr
mapM peekCWString arr
withArrayIntResult :: (Ptr CInt -> IO CInt) -> IO [Int]
withArrayIntResult f
= do clen <- f nullPtr
let len = fromCInt clen
if (len <= 0)
then return []
else allocaArray len $ \carr ->
do f carr
xs <- peekArray len carr
return (map fromCInt xs)
withArrayIntPtrResult :: (Ptr CIntPtr -> IO CInt) -> IO [IntPtr]
withArrayIntPtrResult f
= do clen <- f nullPtr
let len = fromCInt clen
if (len <= 0)
then return []
else allocaArray len $ \carr ->
do f carr
xs <- peekArray len carr
return (map fromCIntPtr xs)
withArrayObjectResult :: (Ptr (Ptr a) -> IO CInt) -> IO [Object a]
withArrayObjectResult f
= do clen <- f nullPtr
let len = fromCInt clen
if (len <= 0)
then return []
else allocaArray len $ \carr ->
do f carr
ps <- peekArray len carr
return (map objectFromPtr ps)
withArrayString :: [String] -> (CInt -> Ptr CString -> IO a) -> IO a
withArrayString xs f
= withCStrings xs [] $ \cxs ->
withArray0 ptrNull cxs $ \carr ->
f (toCInt len) carr
where
len = length xs
withCStrings [] cxs f
= f (reverse cxs)
withCStrings (x:xs) cxs f
= withCString x $ \cx ->
withCStrings xs (cx:cxs) f
-- FIXME: factorise with withArrayString
withArrayWString :: [String] -> (CInt -> Ptr CWString -> IO a) -> IO a
withArrayWString xs f
= withCWStrings xs [] $ \cxs ->
withArray0 ptrNull cxs $ \carr ->
f (toCInt len) carr
where
len = length xs
withCWStrings [] cxs f
= f (reverse cxs)
withCWStrings (x:xs) cxs f
= withCWString x $ \cx ->
withCWStrings xs (cx:cxs) f
withArrayInt :: [Int] -> (CInt -> Ptr CInt -> IO a) -> IO a
withArrayInt xs f
= withArray0 0 (map toCInt xs) $ \carr ->
f (toCInt (length xs)) carr
withArrayIntPtr :: [IntPtr] -> (CInt -> Ptr CIntPtr -> IO a) -> IO a
withArrayIntPtr xs f
= withArray0 0 (map toCIntPtr xs) $ \carr ->
f (toCInt (length xs)) carr
withArrayObject :: [Ptr a] -> (CInt -> Ptr (Ptr a) -> IO b) -> IO b
withArrayObject xs f
= withArray0 ptrNull xs $ \carr ->
f (toCInt (length xs)) carr
{-----------------------------------------------------------------------------------------
CCHar
-----------------------------------------------------------------------------------------}
toCChar :: Char -> CChar
toCChar = castCharToCChar
-- generalised to work with Char and CChar
withCharResult :: (Num a, Integral a, Show a) => IO a -> IO Char
withCharResult io
= do x <- io
if (x < 0)
then do traceIO ("Recieved negative unicode: " ++ (show x))
return '\n'
else return (fromCWchar x)
{- The (x < 0) if expression in withCharResult is a workaround for
"processExecAsyncTimed dies with Prelude.chr bad argument"- bug
reported here
http://sourceforge.net/mailarchive/message.php?msg_id=54647.129.16.31.149.1111686341.squirrel%40webmail.chalmers.se
and here
http://www.mail-archive.com/[email protected]/msg00267.html
Windows GUI-only programs have no stdin, stdout or stderr. So we use Debug.Trace.traceIO
for reporting message.
http://www.haskell.org/ghc/docs/6.8.2/html/users_guide/terminal-interaction.html
http://www.haskell.org/ghc/docs/7.4.1/html/libraries/base-4.5.0.0/Debug-Trace.html#v:traceIO
-}
fromCChar :: CChar -> Char
fromCChar = castCCharToChar
{-----------------------------------------------------------------------------------------
CCHar
-----------------------------------------------------------------------------------------}
toCWchar :: (Num a) => Char -> a
toCWchar = fromIntegral . fromEnum
fromCWchar :: (Num a, Integral a) => a -> Char
fromCWchar = toEnum . fromIntegral
{-----------------------------------------------------------------------------------------
CFunPtr
-----------------------------------------------------------------------------------------}
toCFunPtr :: FunPtr a -> Ptr a
toCFunPtr fptr
= castFunPtrToPtr fptr
-- | Null pointer, use with care.
ptrNull :: Ptr a
ptrNull
= nullPtr
-- | Test for null.
ptrIsNull :: Ptr a -> Bool
ptrIsNull p
= (p == ptrNull)
-- | Cast a pointer type, use with care.
ptrCast :: Ptr a -> Ptr b
ptrCast p
= castPtr p
{-----------------------------------------------------------------------------------------
Marshalling of classes that are managed
-----------------------------------------------------------------------------------------}
-- | A @Managed a@ is a pointer to an object of type @a@, just like 'Object'. However,
-- managed objects are automatically deleted when garbage collected. This is used for
-- certain classes that are not managed by the wxWidgets library, like 'Bitmap's
type Managed a = ForeignPtr a
-- | Create a managed object. Takes a finalizer as argument. This is normally a
-- a delete function like 'windowDelete'.
createManaged :: IO () -> Ptr a -> IO (Managed a)
createManaged final obj
= newForeignPtr obj final
-- | Add an extra finalizer to a managed object.
managedAddFinalizer :: IO () -> Managed a -> IO ()
managedAddFinalizer io managed
= addForeignPtrFinalizer managed io
-- | Do something with the object from a managed object.
withManaged :: Managed a -> (Ptr a -> IO b) -> IO b
withManaged fptr f
= withForeignPtr fptr f
-- | Keep a managed object explicitly alive.
managedTouch :: Managed a -> IO ()
managedTouch fptr
= touchForeignPtr fptr
-- | A null pointer, use with care.
{-# NOINLINE managedNull #-}
managedNull :: Managed a
managedNull
= unsafePerformIO (createManaged (return ()) ptrNull)
-- | Test for null.
managedIsNull :: Managed a -> Bool
managedIsNull managed
= (managed == managedNull)
-- | Cast a managed object, use with care.
managedCast :: Managed a -> Managed b
managedCast fptr
= castForeignPtr fptr
{-----------------------------------------------------------------------------------------
Classes assigned by value.
-----------------------------------------------------------------------------------------}
assignRef :: IO (Ptr (TWxObject a)) -> (Ptr (TWxObject a) -> IO ()) -> IO (WxObject a)
assignRef create f
= withManagedObjectResult (assignRefPtr create f)
assignRefPtr :: IO (Ptr a) -> (Ptr a -> IO ()) -> IO (Ptr a)
assignRefPtr create f
= do p <- create
f p
return p
withManagedBitmapResult :: IO (Ptr (TBitmap a)) -> IO (Bitmap a)
withManagedBitmapResult io
= do p <- io
static <- wxBitmap_IsStatic p
if (static)
then return (objectFromPtr p)
else do mp <- wxManagedPtr_CreateFromBitmap p
objectFromManagedPtr mp
foreign import ccall wxManagedPtr_CreateFromBitmap :: Ptr (TBitmap a) -> IO (ManagedPtr (TBitmap a))
foreign import ccall wxBitmap_IsStatic :: Ptr (TBitmap a) -> IO Bool
withManagedIconResult :: IO (Ptr (TIcon a)) -> IO (Icon a)
withManagedIconResult io
= do p <- io
if (wxIcon_IsStatic p)
then return (objectFromPtr p)
else do mp <- wxManagedPtr_CreateFromIcon p
objectFromManagedPtr mp
foreign import ccall wxManagedPtr_CreateFromIcon :: Ptr (TIcon a) -> IO (ManagedPtr (TIcon a))
foreign import ccall wxIcon_IsStatic :: Ptr (TIcon a) -> Bool
withManagedBrushResult :: IO (Ptr (TBrush a)) -> IO (Brush a)
withManagedBrushResult io
= do p <- io
if (wxBrush_IsStatic p)
then return (objectFromPtr p)
else do mp <- wxManagedPtr_CreateFromBrush p
objectFromManagedPtr mp
foreign import ccall wxManagedPtr_CreateFromBrush :: Ptr (TBrush a) -> IO (ManagedPtr (TBrush a))
foreign import ccall wxBrush_IsStatic :: Ptr (TBrush a) -> Bool
withManagedCursorResult :: IO (Ptr (TCursor a)) -> IO (Cursor a)
withManagedCursorResult io
= do p <- io
if (wxCursor_IsStatic p)
then return (objectFromPtr p)
else do mp <- wxManagedPtr_CreateFromCursor p
objectFromManagedPtr mp
foreign import ccall wxManagedPtr_CreateFromCursor :: Ptr (TCursor a) -> IO (ManagedPtr (TCursor a))
foreign import ccall wxCursor_IsStatic :: Ptr (TCursor a) -> Bool
withManagedFontResult :: IO (Ptr (TFont a)) -> IO (Font a)
withManagedFontResult io
= do p <- io
if (wxFont_IsStatic p)
then return (objectFromPtr p)
else do mp <- wxManagedPtr_CreateFromFont p
objectFromManagedPtr mp
foreign import ccall wxManagedPtr_CreateFromFont :: Ptr (TFont a) -> IO (ManagedPtr (TFont a))
foreign import ccall wxFont_IsStatic :: Ptr (TFont a) -> Bool
withManagedPenResult :: IO (Ptr (TPen a)) -> IO (Pen a)
withManagedPenResult io
= do p <- io
if (wxPen_IsStatic p)
then return (objectFromPtr p)
else do mp <- wxManagedPtr_CreateFromPen p
objectFromManagedPtr mp
foreign import ccall wxManagedPtr_CreateFromPen :: Ptr (TPen a) -> IO (ManagedPtr (TPen a))
foreign import ccall wxPen_IsStatic :: Ptr (TPen a) -> Bool
withRefBitmap :: (Ptr (TBitmap a) -> IO ()) -> IO (Bitmap a)
withRefBitmap f
= withManagedBitmapResult $ assignRefPtr wxBitmap_Create f
foreign import ccall "wxBitmap_CreateDefault" wxBitmap_Create :: IO (Ptr (TBitmap a))
withRefCursor :: (Ptr (TCursor a) -> IO ()) -> IO (Cursor a)
withRefCursor f
= withManagedCursorResult $ assignRefPtr (wx_Cursor_CreateFromStock 1) f
foreign import ccall "Cursor_CreateFromStock" wx_Cursor_CreateFromStock :: CInt -> IO (Ptr (TCursor a))
withRefIcon :: (Ptr (TIcon a) -> IO ()) -> IO (Icon a)
withRefIcon f
= withManagedIconResult $ assignRefPtr wxIcon_Create f
foreign import ccall "wxIcon_CreateDefault" wxIcon_Create :: IO (Ptr (TIcon a))
withRefImage :: (Ptr (TImage a) -> IO ()) -> IO (Image a)
withRefImage f
= assignRef wxImage_Create f
foreign import ccall "wxImage_CreateDefault" wxImage_Create :: IO (Ptr (TImage a))
withRefFont :: (Ptr (TFont a) -> IO ()) -> IO (Font a)
withRefFont f
= withManagedFontResult $ assignRefPtr wxFont_Create f
foreign import ccall "wxFont_CreateDefault" wxFont_Create :: IO (Ptr (TFont a))
withRefPen :: (Ptr (TPen a) -> IO ()) -> IO (Pen a)
withRefPen f
= withManagedPenResult $ assignRefPtr wxPen_Create f
foreign import ccall "wxPen_CreateDefault" wxPen_Create :: IO (Ptr (TPen a))
withRefBrush :: (Ptr (TBrush a) -> IO ()) -> IO (Brush a)
withRefBrush f
= withManagedBrushResult $ assignRefPtr wxBrush_Create f
foreign import ccall "wxBrush_CreateDefault" wxBrush_Create :: IO (Ptr (TBrush a))
withRefFontData :: (Ptr (TFontData a) -> IO ()) -> IO (FontData a)
withRefFontData f
= assignRef wxFontData_Create f
foreign import ccall "wxFontData_Create" wxFontData_Create :: IO (Ptr (TFontData a))
withRefListItem :: (Ptr (TListItem a) -> IO ()) -> IO (ListItem a)
withRefListItem f
= assignRef wxListItem_Create f
foreign import ccall "wxListItem_Create" wxListItem_Create :: IO (Ptr (TListItem a))
withRefPrintData :: (Ptr (TPrintData a) -> IO ()) -> IO (PrintData a)
withRefPrintData f
= assignRef wxPrintData_Create f
foreign import ccall "wxPrintData_Create" wxPrintData_Create :: IO (Ptr (TPrintData a))
withRefPrintDialogData :: (Ptr (TPrintDialogData a) -> IO ()) -> IO (PrintDialogData a)
withRefPrintDialogData f
= assignRef wxPrintDialogData_Create f
foreign import ccall "wxPrintDialogData_CreateDefault" wxPrintDialogData_Create :: IO (Ptr (TPrintDialogData a))
withRefPageSetupDialogData :: (Ptr (TPageSetupDialogData a) -> IO ()) -> IO (PageSetupDialogData a)
withRefPageSetupDialogData f
= assignRef wxPageSetupDialogData_Create f
foreign import ccall "wxPageSetupDialogData_Create" wxPageSetupDialogData_Create :: IO (Ptr (TPageSetupDialogData a))
withManagedDateTimeResult :: IO (Ptr (TDateTime a)) -> IO (DateTime a)
withManagedDateTimeResult io
= do p <- io
if (p==nullPtr)
then return (objectFromPtr p)
else do mp <- wxManagedPtr_CreateFromDateTime p
objectFromManagedPtr mp
foreign import ccall wxManagedPtr_CreateFromDateTime :: Ptr (TDateTime a) -> IO (ManagedPtr (TDateTime a))
withRefDateTime :: (Ptr (TDateTime a) -> IO ()) -> IO (DateTime a)
withRefDateTime f
= withManagedDateTimeResult $ assignRefPtr wxDateTime_Create f
foreign import ccall "wxDateTime_Create" wxDateTime_Create :: IO (Ptr (TDateTime a))
withManagedGridCellCoordsArrayResult :: IO (Ptr (TGridCellCoordsArray a)) -> IO (GridCellCoordsArray a)
withManagedGridCellCoordsArrayResult io
= do p <- io
if (p==nullPtr)
then return (objectFromPtr p)
else do mp <- wxManagedPtr_CreateFromGridCellCoordsArray p
objectFromManagedPtr mp
foreign import ccall wxManagedPtr_CreateFromGridCellCoordsArray :: Ptr (TGridCellCoordsArray a) -> IO (ManagedPtr (TGridCellCoordsArray a))
withRefGridCellCoordsArray :: (Ptr (TGridCellCoordsArray a) -> IO ()) -> IO (GridCellCoordsArray a)
withRefGridCellCoordsArray f
= withManagedGridCellCoordsArrayResult $ assignRefPtr wxGridCellCoordsArray_Create f
foreign import ccall "wxGridCellCoordsArray_Create" wxGridCellCoordsArray_Create :: IO (Ptr (TGridCellCoordsArray a))
{-----------------------------------------------------------------------------------------
Tree items
-----------------------------------------------------------------------------------------}
-- | Identifies tree items. Note: Replaces the @TreeItemId@ object and takes automatically
-- care of allocation issues.
newtype TreeItem = TreeItem IntPtr
deriving (Eq,Show,Read)
-- | Invalid tree item.
treeItemInvalid :: TreeItem
treeItemInvalid = TreeItem 0
-- | Is a tree item ok? (i.e. not invalid).
treeItemIsOk :: TreeItem -> Bool
treeItemIsOk (TreeItem val)
= (val /= 0)
treeItemFromInt :: IntPtr -> TreeItem
treeItemFromInt i
= TreeItem i
withRefTreeItemId :: (Ptr (TTreeItemId ()) -> IO ()) -> IO TreeItem
withRefTreeItemId f
= do item <- assignRefPtr treeItemIdCreate f
val <- treeItemIdGetValue item
treeItemIdDelete item
return (TreeItem (fromCIntPtr val))
withTreeItemIdRef :: String -> TreeItem -> (Ptr (TTreeItemId a) -> IO b) -> IO b
withTreeItemIdRef msg t f
= withTreeItemIdPtr t $ \p -> withValidPtr msg p f
withTreeItemIdPtr :: TreeItem -> (Ptr (TTreeItemId a) -> IO b) -> IO b
withTreeItemIdPtr (TreeItem val) f
= do item <- treeItemIdCreateFromValue (toCIntPtr val)
x <- f item
treeItemIdDelete item
return x
withManagedTreeItemIdResult :: IO (Ptr (TTreeItemId a)) -> IO TreeItem
withManagedTreeItemIdResult io
= do item <- io
val <- treeItemIdGetValue item
treeItemIdDelete item
return (TreeItem (fromCIntPtr val))
foreign import ccall "wxTreeItemId_Create" treeItemIdCreate :: IO (Ptr (TTreeItemId a))
foreign import ccall "wxTreeItemId_GetValue" treeItemIdGetValue :: Ptr (TTreeItemId a) -> IO CIntPtr
foreign import ccall "wxTreeItemId_CreateFromValue" treeItemIdCreateFromValue :: CIntPtr -> IO (Ptr (TTreeItemId a))
foreign import ccall "wxTreeItemId_Delete" treeItemIdDelete :: Ptr (TTreeItemId a) -> IO ()
{-----------------------------------------------------------------------------------------
String
-----------------------------------------------------------------------------------------}
{-
-- | A @wxString@ object.
type WxStringObject a = Ptr (CWxStringObject a)
type TWxStringObject a = CWxStringObject a
data CWxStringObject a = CWxStringObject
-}
-- FIXME: I am blithely changing these over to use CWString instead of String
-- whereas in the rest of the code, I actually make a new version of the fns
withStringRef :: String -> String -> (Ptr (TWxString s) -> IO a) -> IO a
withStringRef msg s f
= withStringPtr s $ \p -> withValidPtr msg p f
withStringPtr :: String -> (Ptr (TWxString s) -> IO a) -> IO a
withStringPtr s f
= withCWString s $ \cstr ->
bracket (wxString_Create cstr)
(wxString_Delete)
f
withManagedStringResult :: IO (Ptr (TWxString a)) -> IO String
withManagedStringResult io
= do wxs <- io
len <- wxString_Length wxs
s <- if (len<=0)
then return ""
else withCWString (replicate (fromCInt len) ' ') $ \cstr ->
do wxString_GetString wxs cstr
peekCWStringLen (cstr, fromCInt len)
wxString_Delete wxs
return s
foreign import ccall wxString_Create :: Ptr CWchar -> IO (Ptr (TWxString a))
foreign import ccall wxString_CreateLen :: Ptr CWchar -> CInt -> IO (Ptr (TWxString a))
foreign import ccall wxString_Delete :: Ptr (TWxString a) -> IO ()
foreign import ccall wxString_GetString :: Ptr (TWxString a) -> Ptr CWchar -> IO CInt
foreign import ccall wxString_Length :: Ptr (TWxString a) -> IO CInt
{-----------------------------------------------------------------------------------------
Color
-----------------------------------------------------------------------------------------}
-- | An abstract data type to define colors.
--
-- Note: Haddock 0.8 and 0.9 doesn't support GeneralizedNewtypeDeriving. So, This class
-- doesn't have 'IArray' class's unboxed array instance now. If you want to use this type
-- with unboxed array, you must write code like this.
--
-- > {-# LANGUAGE GeneralizedNewtypeDeriving, StandaloneDeriving, MultiParamTypeClasses #-}
-- > import Graphics.UI.WXCore.WxcTypes
-- > ...
-- > deriving instance IArray UArray Color
--
-- We can't derive 'MArray' class's unboxed array instance this way. This is a bad point
-- of current 'MArray' class definition.
--
newtype Color = Color Word
deriving (Eq, Typeable) -- , IArray UArray)
instance Show Color where
showsPrec d c
= showParen (d > 0) (showString "rgba(" . shows (colorRed c) .
showChar ',' . shows (colorGreen c) .
showChar ',' . shows (colorBlue c) .
showChar ',' . shows (colorAlpha c) .
showChar ')' )
-- | Create a color from a red\/green\/blue triple.
colorRGB :: (Integral a) => a -> a -> a -> Color
colorRGB r g b = Color (shiftL (fromIntegral r) 24 .|. shiftL (fromIntegral g) 16 .|. shiftL (fromIntegral b) 8 .|. 255)
-- | Create a color from a red\/green\/blue triple.
rgb :: (Integral a) => a -> a -> a -> Color
rgb r g b = colorRGB r g b
-- | Create a color from a red\/green\/blue\/alpha quadruple.
colorRGBA :: (Integral a) => a -> a -> a -> a -> Color
colorRGBA r g b a = Color (shiftL (fromIntegral r) 24 .|. shiftL (fromIntegral g) 16 .|. shiftL (fromIntegral b) 8 .|. (fromIntegral a))
-- | Create a color from a red\/green\/blue\/alpha quadruple.
rgba :: (Integral a) => a -> a -> a -> a -> Color
rgba r g b a = colorRGBA r g b a
-- | Return an 'Int' where the three least significant bytes contain
-- the red, green, and blue component of a color.
intFromColor :: Color -> Int
intFromColor rgb
= let r = colorRed rgb
g = colorGreen rgb
b = colorBlue rgb
in (shiftL (fromIntegral r) 16 .|. shiftL (fromIntegral g) 8 .|. b)
-- | Set the color according to an rgb integer. (see 'rgbIntFromColor').
colorFromInt :: Int -> Color
colorFromInt rgb
= let r = (shiftR rgb 16) .&. 0xFF
g = (shiftR rgb 8) .&. 0xFF
b = rgb .&. 0xFF
in colorRGB r g b
-- | Return an 'Num' class's numeric representation where the three
-- least significant the red, green, and blue component of a color.
fromColor :: (Num a) => Color -> a
fromColor (Color rgb)
= fromIntegral rgb
-- | Set the color according to 'Integral' class's numeric representation.
-- (see 'rgbaIntFromColor').
toColor :: (Integral a) => a -> Color
toColor
= Color . fromIntegral
-- marshalling 1
-- | Returns a red color component
colorRed :: (Num a) => Color -> a
colorRed (Color rgba) = fromIntegral ((shiftR rgba 24) .&. 0xFF)
-- | Returns a green color component
colorGreen :: (Num a) => Color -> a
colorGreen (Color rgba) = fromIntegral ((shiftR rgba 16) .&. 0xFF)
-- | Returns a blue color component
colorBlue :: (Num a) => Color -> a
colorBlue (Color rgba) = fromIntegral ((shiftR rgba 8) .&. 0xFF)
-- | Returns a alpha channel component
colorAlpha :: (Num a) => Color -> a
colorAlpha (Color rgba) = fromIntegral (rgba .&. 0xFF)
-- | This is an illegal color, corresponding to @nullColour@.
colorNull :: Color
colorNull
= Color (-1)
{-# DEPRECATED colorOk "Use colorIsOk instead" #-}
-- | deprecated: use 'colorIsOk' instead.
colorOk :: Color -> Bool
colorOk = colorIsOk
-- | Check of a color is valid (@Colour::IsOk@)
colorIsOk :: Color -> Bool
colorIsOk = (/= colorNull)
-- marshalling 2
{-
type Colour a = Object (CColour a)
type ColourPtr a = Ptr (CColour a)
data CColour a = CColour
-}
withRefColour :: (Ptr (TColour a) -> IO ()) -> IO Color
withRefColour f
= withManagedColourResult $
assignRefPtr colourCreate f
withManagedColourResult :: IO (Ptr (TColour a)) -> IO Color
withManagedColourResult io
= do pcolour <- io
color <- do ok <- colourIsOk pcolour
if (ok==0)
then return colorNull
else do rgba <- colourGetUnsignedInt pcolour
return (toColor rgba)
colourSafeDelete pcolour
return color
withColourRef :: String -> Color -> (Ptr (TColour a) -> IO b) -> IO b
withColourRef msg c f
= withColourPtr c $ \p -> withValidPtr msg p f
withColourPtr :: Color -> (Ptr (TColour a) -> IO b) -> IO b
withColourPtr c f
= do pcolour <- colourCreateFromUnsignedInt (fromColor c)
x <- f pcolour
colourSafeDelete pcolour
return x
colourFromColor :: Color -> IO (Colour ())
colourFromColor c
= if (colorOk c)
then do p <- colourCreateFromUnsignedInt (fromColor c)
if (colourIsStatic p)
then return (objectFromPtr p)
else do mp <- wxManagedPtr_CreateFromColour p
objectFromManagedPtr mp
else withObjectResult colourNull
colorFromColour :: Colour a -> IO Color
colorFromColour c
= withObjectRef "colorFromColour" c $ \pcolour ->
do ok <- colourIsOk pcolour
if (ok==0)
then return colorNull
else do rgba <- colourGetUnsignedInt pcolour
return (toColor rgba)
foreign import ccall "wxColour_CreateEmpty" colourCreate :: IO (Ptr (TColour a))
foreign import ccall "wxColour_CreateFromInt" colourCreateFromInt :: CInt -> IO (Ptr (TColour a))
foreign import ccall "wxColour_GetInt" colourGetInt :: Ptr (TColour a) -> IO CInt
foreign import ccall "wxColour_CreateFromUnsignedInt" colourCreateFromUnsignedInt :: Word -> IO (Ptr (TColour a))
foreign import ccall "wxColour_GetUnsignedInt" colourGetUnsignedInt :: Ptr (TColour a) -> IO Word
foreign import ccall "wxColour_SafeDelete" colourSafeDelete :: Ptr (TColour a) -> IO ()
foreign import ccall "wxColour_IsStatic" colourIsStatic :: Ptr (TColour a) -> Bool
foreign import ccall "wxColour_IsOk" colourIsOk :: Ptr (TColour a) -> IO CInt
foreign import ccall "Null_Colour" colourNull :: IO (Ptr (TColour a))
foreign import ccall wxManagedPtr_CreateFromColour :: Ptr (TColour a) -> IO (ManagedPtr (TColour a))
| ekmett/wxHaskell | wxcore/src/haskell/Graphics/UI/WXCore/WxcTypes.hs | lgpl-2.1 | 49,920 | 0 | 18 | 11,108 | 14,155 | 7,197 | 6,958 | 944 | 3 |
<?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="zh-CN">
<title>Ruby Scripting</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>搜索</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/jruby/src/main/javahelp/org/zaproxy/zap/extension/jruby/resources/help_zh_CN/helpset_zh_CN.hs | apache-2.0 | 960 | 81 | 65 | 157 | 407 | 206 | 201 | -1 | -1 |
module BCode
( BCode(..)
, BCodePath(..)
, encode
, decode
, search
, searchInt
, searchStr
) where
import Control.Applicative ((<$>), (<*>), (<|>), (*>), (<*))
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import Data.Char (ord, isDigit, digitToInt)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Word (Word8)
import Text.Parsec.ByteString (Parser)
import qualified Text.Parsec.Char as P
import qualified Text.Parsec.Error as P
import qualified Text.Parsec.Combinator as P
import qualified Text.ParserCombinators.Parsec.Prim as P
data BCode
= BInt Integer
| BStr ByteString
| BList [BCode]
| BDict (Map ByteString BCode)
deriving (Show, Read, Ord, Eq)
instance Eq P.ParseError where
_ == _ = False
toW8 :: Char -> Word8
toW8 = fromIntegral . ord
wrap :: Char -> Char -> ByteString -> ByteString
wrap a b c = B.concat [B8.pack [a], c, B8.pack [b]]
between :: Char -> Char -> Parser a -> Parser a
between a b c = P.char a *> c <* P.char b
getUInt :: (Num a) => Parser a
getUInt = fromIntegral <$> digit
where
digit = str2int <$> P.many1 (P.satisfy isDigit)
str2int = foldl (\acc x -> acc * 10 + digitToInt x) 0
getBInt :: Parser BCode
getBInt = BInt <$> between 'i' 'e' getInt
where
sign = (P.char '-' >> return negate) <|> return id
getInt = sign <*> getUInt
getBStr :: Parser BCode
getBStr = do
count <- getUInt
P.char ':'
BStr . B8.pack <$> P.count count P.anyToken
getBList :: Parser BCode
getBList = BList <$> between 'l' 'e' (P.many getBCode)
getBDict :: Parser BCode
getBDict = BDict . M.fromList <$> between 'd' 'e' (P.many getPair)
where
getPair = do
(BStr key) <- getBStr
value <- getBCode
return (key, value)
getBCode :: Parser BCode
getBCode = getBInt <|> getBStr <|> getBList <|> getBDict
decode :: ByteString -> Either P.ParseError BCode
decode input = P.parse getBCode "" input
encode :: BCode -> ByteString
encode = put
where
put (BInt i) = wrap 'i' 'e' $ int2bs i
put (BStr s) = B.concat [int2bs $ B.length s, B8.pack ":", s]
put (BList l) = wrap 'l' 'e' $ B.concat (map put l)
put (BDict d) = wrap 'd' 'e' $ B.concat (map encodePair $ M.toList d)
int2bs :: (Integral a) => a -> ByteString
int2bs = B8.pack . show . fromIntegral
encodePair :: (ByteString, BCode) -> ByteString
encodePair (k, v) = put (BStr k) `B.append` put v
data BCodePath = BCodePInt Int
| BCodePStr String
search :: [BCodePath] -> BCode -> Maybe BCode
search [] a = Just a
search (BCodePInt x:xs) (BList l)
| x < 0 || (x + 1) > length l = Nothing
| otherwise = search xs (l !! x)
search (BCodePStr x:xs) (BDict d) =
M.lookup (B8.pack x) d >>= search xs
search _ _ = Nothing
searchInt :: String -> BCode -> Maybe Integer
searchInt key bc = do
(BInt i) <- search [BCodePStr key] bc
return i
searchStr :: String -> BCode -> Maybe ByteString
searchStr key bc = do
(BStr s) <- search [BCodePStr key] bc
return s
| artems/htorr | src/BCode.hs | bsd-3-clause | 3,114 | 0 | 12 | 736 | 1,289 | 681 | 608 | 88 | 4 |
{-
- Copyright (c) 2010 Mats Rauhala <[email protected]>
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the "Software"), to deal in the Software without
- restriction, including without limitation the rights to use,
- copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the
- Software is furnished to do so, subject to the following
- conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- OTHER DEALINGS IN THE SOFTWARE.
-}
module Files where
import System.Directory (doesFileExist, getDirectoryContents)
import System.FilePath
import Control.Monad (forM)
import Control.Monad.Error
import Data.List (isPrefixOf)
batterydir :: FilePath
batterydir = "/sys/class/power_supply/"
batteryfile :: ErrorT String IO FilePath
batteryfile = do
all <- liftIO $ getDirectoryContents batterydir
case filter (("BAT" `isPrefixOf`)) all of
[] -> throwError "No batteries present"
(x:_) -> return $ batterydir </> x
full :: ErrorT String IO FilePath
full = (</> "charge_full") `fmap` batteryfile
charge :: ErrorT String IO FilePath
charge = (</> "charge_now") `fmap` batteryfile
status :: ErrorT String IO FilePath
status = (</> "status") `fmap` batteryfile
readFileM :: FilePath -> ErrorT String IO String
readFileM = liftIO . readFile
| sjakobi/zsh-battery | Files.hs | bsd-3-clause | 1,995 | 0 | 11 | 369 | 249 | 141 | 108 | 22 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.OrgMode.Parse.Attoparsec.Section
-- Copyright : © 2015 Parnell Springmeyer
-- License : All Rights Reserved
-- Maintainer : Parnell Springmeyer <[email protected]>
-- Stability : stable
--
-- Parsing combinators for org-mode sections.
----------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module Data.OrgMode.Parse.Attoparsec.Section where
import Control.Applicative ((<$>), (<*>), (<|>))
import Data.Attoparsec.Text as T
import Data.Attoparsec.Types as TP
import Data.Monoid (mempty)
import Data.Text (Text, pack,
unlines)
import Prelude hiding (unlines)
import Data.OrgMode.Parse.Attoparsec.PropertyDrawer
import Data.OrgMode.Parse.Attoparsec.Time
import Data.OrgMode.Parse.Types
-- | Parse a heading section
--
-- Heading sections contain optionally a property drawer,
-- a list of clock entries, code blocks (not yet implemented),
-- plain lists (not yet implemented), and unstructured text.
parseSection :: TP.Parser Text Section
parseSection = Section
<$> (Plns <$> parsePlannings)
<*> many' parseClock
<*> option mempty parseDrawer
<*> (unlines <$> many' nonHeaderLine)
where
-- | Parse a non-heading line of a section.
nonHeaderLine :: TP.Parser Text Text
nonHeaderLine = nonHeaderLine0 <|> nonHeaderLine1
where
nonHeaderLine0 = endOfLine >> return (pack "")
nonHeaderLine1 = pack <$> do
h <- notChar '*'
t <- manyTill anyChar endOfLine
return (h:t)
| imalsogreg/orgmode-parse | src/Data/OrgMode/Parse/Attoparsec/Section.hs | bsd-3-clause | 1,970 | 0 | 12 | 624 | 266 | 162 | 104 | 25 | 1 |
{-
Copyright (C) 2007-2010 John MacFarlane <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Readers.TeXMath
Copyright : Copyright (C) 2007-2010 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <[email protected]>
Stability : alpha
Portability : portable
Conversion of TeX math to a list of 'Pandoc' inline elements.
-}
module Text.Pandoc.Readers.TeXMath ( readTeXMath ) where
import Text.Pandoc.Definition
import Text.TeXMath.Types
import Text.TeXMath.Parser
-- | Converts a raw TeX math formula to a list of 'Pandoc' inlines.
-- Defaults to raw formula between @$@ characters if entire formula
-- can't be converted.
readTeXMath :: String -- ^ String to parse (assumes @'\n'@ line endings)
-> [Inline]
readTeXMath inp = case texMathToPandoc inp of
Left _ -> [Str ("$" ++ inp ++ "$")]
Right res -> res
texMathToPandoc :: String -> Either String [Inline]
texMathToPandoc inp = inp `seq`
case parseFormula inp of
Left err -> Left err
Right exps -> case expsToInlines exps of
Nothing -> Left "Formula too complex for [Inline]"
Just r -> Right r
expsToInlines :: [Exp] -> Maybe [Inline]
expsToInlines xs = do
res <- mapM expToInlines xs
return (concat res)
expToInlines :: Exp -> Maybe [Inline]
expToInlines (ENumber s) = Just [Str s]
expToInlines (EIdentifier s) = Just [Emph [Str s]]
expToInlines (EMathOperator s) = Just [Str s]
expToInlines (ESymbol t s) = Just $ addSpace t (Str s)
where addSpace Op x = [x, thinspace]
addSpace Bin x = [medspace, x, medspace]
addSpace Rel x = [widespace, x, widespace]
addSpace Pun x = [x, thinspace]
addSpace _ x = [x]
thinspace = Str "\x2006"
medspace = Str "\x2005"
widespace = Str "\x2004"
expToInlines (EStretchy x) = expToInlines x
expToInlines (EDelimited start end xs) = do
xs' <- mapM expToInlines xs
return $ [Str start] ++ concat xs' ++ [Str end]
expToInlines (EGrouped xs) = expsToInlines xs
expToInlines (ESpace "0.167em") = Just [Str "\x2009"]
expToInlines (ESpace "0.222em") = Just [Str "\x2005"]
expToInlines (ESpace "0.278em") = Just [Str "\x2004"]
expToInlines (ESpace "0.333em") = Just [Str "\x2004"]
expToInlines (ESpace "1em") = Just [Str "\x2001"]
expToInlines (ESpace "2em") = Just [Str "\x2001\x2001"]
expToInlines (ESpace _) = Just [Str " "]
expToInlines (EBinary _ _ _) = Nothing
expToInlines (ESub x y) = do
x' <- expToInlines x
y' <- expToInlines y
return $ x' ++ [Subscript y']
expToInlines (ESuper x y) = do
x' <- expToInlines x
y' <- expToInlines y
return $ x' ++ [Superscript y']
expToInlines (ESubsup x y z) = do
x' <- expToInlines x
y' <- expToInlines y
z' <- expToInlines z
return $ x' ++ [Subscript y'] ++ [Superscript z']
expToInlines (EDown x y) = expToInlines (ESub x y)
expToInlines (EUp x y) = expToInlines (ESuper x y)
expToInlines (EDownup x y z) = expToInlines (ESubsup x y z)
expToInlines (EText TextNormal x) = Just [Str x]
expToInlines (EText TextBold x) = Just [Strong [Str x]]
expToInlines (EText TextMonospace x) = Just [Code nullAttr x]
expToInlines (EText TextItalic x) = Just [Emph [Str x]]
expToInlines (EText _ x) = Just [Str x]
expToInlines (EOver (EGrouped [EIdentifier [c]]) (ESymbol Accent [accent])) =
case accent of
'\x203E' -> Just [Emph [Str [c,'\x0304']]] -- bar
'\x00B4' -> Just [Emph [Str [c,'\x0301']]] -- acute
'\x0060' -> Just [Emph [Str [c,'\x0300']]] -- grave
'\x02D8' -> Just [Emph [Str [c,'\x0306']]] -- breve
'\x02C7' -> Just [Emph [Str [c,'\x030C']]] -- check
'.' -> Just [Emph [Str [c,'\x0307']]] -- dot
'\x00B0' -> Just [Emph [Str [c,'\x030A']]] -- ring
'\x20D7' -> Just [Emph [Str [c,'\x20D7']]] -- arrow right
'\x20D6' -> Just [Emph [Str [c,'\x20D6']]] -- arrow left
'\x005E' -> Just [Emph [Str [c,'\x0302']]] -- hat
'\x0302' -> Just [Emph [Str [c,'\x0302']]] -- hat
'~' -> Just [Emph [Str [c,'\x0303']]] -- tilde
_ -> Nothing
expToInlines _ = Nothing
| sol/pandoc | src/Text/Pandoc/Readers/TeXMath.hs | gpl-2.0 | 4,922 | 0 | 13 | 1,182 | 1,540 | 773 | 767 | 83 | 17 |
#!/usr/bin/env runhaskell
-- Generate data.h and data.c
import Data.List (intercalate, partition, unfoldr)
-- http://unthingable.eat-up.org/tag/music.html
-- | Euclidean rhythm generator
euclidean :: Int -- ^ fill steps
-> Int -- ^ total steps
-> [Bool]
euclidean k n = concat . efold $
replicate k [True] ++ replicate (n - k) [False]
-- | A hybrid of zip and outer join, takes two lists of different lengths and
-- concatenates their elements pairwise
ezip :: [[a]] -> [[a]] -> [[a]]
ezip x [] = x
ezip [] x = x
ezip (x:xs) (y:ys) = (x ++ y) : ezip xs ys
-- | Repeatedly applies the tail end of the sequence under construction to the
-- head, using ezip, until either there are 3 or fewer subpatterns or the
-- pattern is cyclic.
efold :: Eq a => [[a]] -> [[a]]
efold xs
| length xs <= 3 = xs
| null a = xs
| otherwise = efold $ ezip a b
where (a, b) = partition (/= last xs) xs
-- | All the Euclidean rhythms of a given length
allEuclideans :: Int -> [[Bool]]
allEuclideans n = fmap (`euclidean` n) [0..n]
-- | Pad a list of `Bool` with False out to length `n`
pad :: Int -> [Bool] -> [Bool]
pad n xs
| length xs >= n = xs
| otherwise = pad n $ xs ++ [False]
-- | Chunking algorithm
chunk :: Int -> [a] -> [[a]]
chunk n = takeWhile (not.null) . unfoldr (Just . splitAt n)
-- | Split a list of bools into a list of list of bools, each padded to 8 bits
-- (e.g char)
bitArray :: [Bool] -> [[Bool]]
bitArray xs = pad 8 <$> chunk 8 xs
bitArrayCLiteral :: [[[Bool]]] -> String
bitArrayCLiteral xs = multiLineCArray $ oneLineCArray <$> (fmap . fmap) bitCLiteral xs
where oneLineCArray :: [String] -> String
oneLineCArray ys = "{" ++ intercalate ", " ys ++ "}"
multiLineCArray :: [String] -> String
multiLineCArray ys = "{\n" ++ intercalate ",\n" (fmap ("\t"++) ys) ++ "\n}"
bitCLiteral :: [Bool] -> String
bitCLiteral ys = "0b" ++ fmap lit ys
where lit True = '1'
lit False = '0'
bytes :: Int -> Int
bytes x = x `div` 8 + p
where p = if x `rem` 8 > 0 then 1 else 0
arrayPrototype :: Int -> String
arrayPrototype x = "const char table_euclidean_" ++ show x ++ "[" ++ show (x + 1) ++ "][" ++ show (bytes x) ++ "]"
array :: Int -> String
array x = arrayPrototype x ++ " = " ++ bitArrayCLiteral (bitArray <$> allEuclideans x) ++ ";"
dataC :: String
dataC = intercalate "\n\n" (fmap array [1..32]) ++ "\n"
headerC :: String
headerC = "#ifndef _EUCLIDEAN_DATA_H_\n" ++
"#define _EUCLIDEAN_DATA_H_\n" ++
concatMap (\i -> "extern " ++ arrayPrototype i ++ ";\n") [1..32] ++
"#endif\n"
main :: IO ()
main = do writeFile "data.h" headerC
writeFile "data.c" dataC
| scanner-darkly/mod | teletype/euclidean/euclidean.hs | gpl-2.0 | 2,761 | 0 | 12 | 702 | 938 | 498 | 440 | 53 | 2 |
module Reflex.DynamicWriter
{-# DEPRECATED "Use 'Reflex.DynamicWriter.Class' and 'Reflex.DynamicWrite.Base' instead, or just import 'Reflex'" #-}
( module X
) where
import Reflex.DynamicWriter.Base as X
import Reflex.DynamicWriter.Class as X
| ryantrinkle/reflex | src/Reflex/DynamicWriter.hs | bsd-3-clause | 249 | 0 | 4 | 34 | 29 | 21 | 8 | 5 | 0 |
{-# LANGUAGE TupleSections, GeneralizedNewtypeDeriving #-}
-- |A simple graph implementation backed by 'Data.HashMap'.
module Data.RDF.MGraph(MGraph, empty, mkRdf, triplesOf, uniqTriplesOf, select, query)
where
import Prelude hiding (pred)
import Control.DeepSeq (NFData)
import Data.RDF.Types
import Data.RDF.Query
import Data.RDF.Namespace
import qualified Data.Map as Map
import Data.Hashable()
import Data.HashMap.Strict(HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.HashSet(HashSet)
import qualified Data.HashSet as Set
import Data.List
-- |A map-based graph implementation.
--
-- Worst-case time complexity of the graph functions, with respect
-- to the number of triples, are:
--
-- * 'empty' : O(1)
--
-- * 'mkRdf' : O(n)
--
-- * 'triplesOf': O(n)
--
-- * 'select' : O(n)
--
-- * 'query' : O(log n)
newtype MGraph = MGraph (TMaps, Maybe BaseUrl, PrefixMappings)
deriving (NFData)
instance RDF MGraph where
baseUrl = baseUrl'
prefixMappings = prefixMappings'
addPrefixMappings = addPrefixMappings'
empty = empty'
mkRdf = mkRdf'
triplesOf = triplesOf'
uniqTriplesOf = uniqTriplesOf'
select = select'
query = query'
instance Show MGraph where
show gr = concatMap (\t -> show t ++ "\n") (triplesOf gr)
-- some convenience type alias for readability
-- An adjacency map for a subject, mapping from a predicate node to
-- to the adjacent nodes via that predicate.
type AdjacencyMap = HashMap Predicate (HashSet Node)
type Adjacencies = HashSet Node
type TMap = HashMap Node AdjacencyMap
type TMaps = (TMap, TMap)
baseUrl' :: MGraph -> Maybe BaseUrl
baseUrl' (MGraph (_, baseURL, _)) = baseURL
prefixMappings' :: MGraph -> PrefixMappings
prefixMappings' (MGraph (_, _, pms)) = pms
addPrefixMappings' :: MGraph -> PrefixMappings -> Bool -> MGraph
addPrefixMappings' (MGraph (ts, baseURL, pms)) pms' replace =
let merge = if replace then flip mergePrefixMappings else mergePrefixMappings
in MGraph (ts, baseURL, merge pms pms')
empty' :: MGraph
empty' = MGraph ((HashMap.empty, HashMap.empty), Nothing, PrefixMappings Map.empty)
mkRdf' :: Triples -> Maybe BaseUrl -> PrefixMappings -> MGraph
mkRdf' ts baseURL pms = MGraph (mergeTs (HashMap.empty, HashMap.empty) ts, baseURL, pms)
mergeTs :: TMaps -> [Triple] -> TMaps
mergeTs = foldl' mergeT
where
mergeT :: TMaps -> Triple -> TMaps
mergeT m t = mergeT' m (subjectOf t) (predicateOf t) (objectOf t)
mergeT' :: TMaps -> Subject -> Predicate -> Object -> TMaps
mergeT' (spo, ops) s p o = (mergeT'' spo s p o, mergeT'' ops o p s)
mergeT'' :: TMap -> Subject -> Predicate -> Object -> TMap
mergeT'' m s p o =
if s `HashMap.member` m then
(if p `HashMap.member` adjs then HashMap.insert s addPredObj m
else HashMap.insert s addNewPredObjMap m)
else HashMap.insert s newPredMap m
where
adjs = HashMap.lookupDefault HashMap.empty s m
newPredMap :: HashMap Predicate (HashSet Object)
newPredMap = HashMap.singleton p (Set.singleton o)
addNewPredObjMap :: HashMap Predicate (HashSet Object)
addNewPredObjMap = HashMap.insert p (Set.singleton o) adjs
addPredObj :: HashMap Predicate (HashSet Object)
addPredObj = HashMap.insert p (Set.insert o (get p adjs)) adjs
--get :: (Ord k, Hashable k) => k -> HashMap k v -> v
get = HashMap.lookupDefault Set.empty
-- 3 following functions support triplesOf
triplesOf' :: MGraph -> Triples
triplesOf' (MGraph ((spoMap, _), _, _)) = concatMap (uncurry tripsSubj) subjPredMaps
where subjPredMaps = HashMap.toList spoMap
-- naive implementation for now
uniqTriplesOf' :: MGraph -> Triples
uniqTriplesOf' = nub . expandTriples
tripsSubj :: Subject -> AdjacencyMap -> Triples
tripsSubj s adjMap = concatMap (uncurry (tfsp s)) (HashMap.toList adjMap)
where tfsp = tripsForSubjPred
tripsForSubjPred :: Subject -> Predicate -> Adjacencies -> Triples
tripsForSubjPred s p adjs = map (Triple s p) (Set.toList adjs)
-- supports select
select' :: MGraph -> NodeSelector -> NodeSelector -> NodeSelector -> Triples
select' (MGraph ((spoMap,_),_,_)) subjFn predFn objFn =
map (\(s,p,o) -> Triple s p o) $ Set.toList $ sel1 subjFn predFn objFn spoMap
sel1 :: NodeSelector -> NodeSelector -> NodeSelector -> TMap -> HashSet (Node, Node, Node)
sel1 (Just subjFn) p o spoMap =
Set.unions $ map (sel2 p o) $ filter (\(x,_) -> subjFn x) $ HashMap.toList spoMap
sel1 Nothing p o spoMap = Set.unions $ map (sel2 p o) $ HashMap.toList spoMap
sel2 :: NodeSelector -> NodeSelector -> (Node, HashMap Node (HashSet Node)) -> HashSet (Node, Node, Node)
sel2 (Just predFn) mobjFn (s, ps) =
Set.map (\(p,o) -> (s,p,o)) $
foldl' Set.union Set.empty $
map (sel3 mobjFn) poMapS :: HashSet (Node, Node, Node)
where
poMapS :: [(Node, HashSet Node)]
poMapS = filter (\(k,_) -> predFn k) $ HashMap.toList ps
sel2 Nothing mobjFn (s, ps) =
Set.map (\(p,o) -> (s,p,o)) $
foldl' Set.union Set.empty $
map (sel3 mobjFn) poMaps
where
poMaps = HashMap.toList ps
sel3 :: NodeSelector -> (Node, HashSet Node) -> HashSet (Node, Node)
sel3 (Just objFn) (p, os) = Set.map (\o -> (p, o)) $ Set.filter objFn os
sel3 Nothing (p, os) = Set.map (\o -> (p, o)) os
-- support query
query' :: MGraph -> Maybe Node -> Maybe Predicate -> Maybe Node -> Triples
query' (MGraph (m,_ , _)) subj pred obj = map f $ Set.toList $ q1 subj pred obj m
where f (s, p, o) = Triple s p o
q1 :: Maybe Node -> Maybe Node -> Maybe Node -> TMaps -> HashSet (Node, Node, Node)
q1 (Just s) p o (spoMap, _ ) = q2 p o (s, HashMap.lookupDefault HashMap.empty s spoMap)
q1 s p (Just o) (_ , opsMap) = Set.map (\(o',p',s') -> (s',p',o')) $ q2 p s (o, HashMap.lookupDefault HashMap.empty o opsMap)
q1 Nothing p o (spoMap, _ ) = Set.unions $ map (q2 p o) $ HashMap.toList spoMap
q2 :: Maybe Node -> Maybe Node -> (Node, HashMap Node (HashSet Node)) -> HashSet (Node, Node, Node)
q2 (Just p) o (s, pmap) =
maybe Set.empty (Set.map (\ (p', o') -> (s, p', o')) . q3 o . (p,)) $ HashMap.lookup p pmap
q2 Nothing o (s, pmap) = Set.map (\(x,y) -> (s,x,y)) $ Set.unions $ map (q3 o) opmaps
where opmaps ::[(Node, HashSet Node)]
opmaps = HashMap.toList pmap
q3 :: Maybe Node -> (Node, HashSet Node) -> HashSet (Node, Node)
q3 (Just o) (p, os) = if o `Set.member` os then Set.singleton (p, o) else Set.empty
q3 Nothing (p, os) = Set.map (\o -> (p, o)) os
| ddssff/rdf4h | src/Data/RDF/MGraph.hs | bsd-3-clause | 6,482 | 0 | 13 | 1,312 | 2,474 | 1,346 | 1,128 | 112 | 3 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
-- | Construct a @Plan@ for how to build
module Stack.Build.ConstructPlan
( constructPlan
) where
import Control.Exception.Lifted
import Control.Monad
import Control.Monad.Catch (MonadCatch)
import Control.Monad.IO.Class
import Control.Monad.Logger (MonadLogger)
import Control.Monad.RWS.Strict
import Control.Monad.Trans.Resource
import qualified Data.ByteString.Char8 as S8
import Data.Either
import Data.Function
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8With)
import Data.Text.Encoding.Error (lenientDecode)
import Distribution.Package (Dependency (..))
import Distribution.Version (anyVersion)
import Network.HTTP.Client.Conduit (HasHttpManager)
import Prelude hiding (FilePath, pi, writeFile)
import Stack.Build.Cache
import Stack.Build.Haddock
import Stack.Build.Installed
import Stack.Build.Source
import Stack.Types.Build
import Stack.BuildPlan
import Stack.Package
import Stack.PackageIndex
import Stack.Types
data PackageInfo
= PIOnlyInstalled Version InstallLocation Installed
| PIOnlySource PackageSource
| PIBoth PackageSource Installed
combineSourceInstalled :: PackageSource
-> (Version, InstallLocation, Installed)
-> PackageInfo
combineSourceInstalled ps (version, location, installed) =
assert (piiVersion ps == version) $
assert (piiLocation ps == location) $
case location of
-- Always trust something in the snapshot
Snap -> PIOnlyInstalled version location installed
Local -> PIBoth ps installed
type CombinedMap = Map PackageName PackageInfo
combineMap :: SourceMap -> InstalledMap -> CombinedMap
combineMap = Map.mergeWithKey
(\_ s i -> Just $ combineSourceInstalled s i)
(fmap PIOnlySource)
(fmap (\(v, l, i) -> PIOnlyInstalled v l i))
data AddDepRes
= ADRToInstall Task
| ADRFound InstallLocation Version Installed
deriving Show
data W = W
{ wFinals :: !(Map PackageName (Either ConstructPlanException (Task, LocalPackageTB)))
, wInstall :: !(Map Text InstallLocation)
-- ^ executable to be installed, and location where the binary is placed
, wDirty :: !(Map PackageName Text)
-- ^ why a local package is considered dirty
, wDeps :: !(Set PackageName)
-- ^ Packages which count as dependencies
}
instance Monoid W where
mempty = W mempty mempty mempty mempty
mappend (W a b c d) (W w x y z) = W (mappend a w) (mappend b x) (mappend c y) (mappend d z)
type M = RWST
Ctx
W
(Map PackageName (Either ConstructPlanException AddDepRes))
IO
data Ctx = Ctx
{ mbp :: !MiniBuildPlan
, baseConfigOpts :: !BaseConfigOpts
, loadPackage :: !(PackageName -> Version -> Map FlagName Bool -> IO Package)
, combinedMap :: !CombinedMap
, toolToPackages :: !(Dependency -> Map PackageName VersionRange)
, ctxEnvConfig :: !EnvConfig
, callStack :: ![PackageName]
, extraToBuild :: !(Set PackageName)
, latestVersions :: !(Map PackageName Version)
, wanted :: !(Set PackageName)
}
instance HasStackRoot Ctx
instance HasPlatform Ctx
instance HasGHCVariant Ctx
instance HasConfig Ctx
instance HasBuildConfig Ctx where
getBuildConfig = getBuildConfig . getEnvConfig
instance HasEnvConfig Ctx where
getEnvConfig = ctxEnvConfig
constructPlan :: forall env m.
(MonadCatch m, MonadReader env m, HasEnvConfig env, MonadIO m, MonadLogger m, MonadBaseControl IO m, HasHttpManager env)
=> MiniBuildPlan
-> BaseConfigOpts
-> [LocalPackage]
-> Set PackageName -- ^ additional packages that must be built
-> Map GhcPkgId PackageIdentifier -- ^ locally registered
-> (PackageName -> Version -> Map FlagName Bool -> IO Package) -- ^ load upstream package
-> SourceMap
-> InstalledMap
-> m Plan
constructPlan mbp0 baseConfigOpts0 locals extraToBuild0 locallyRegistered loadPackage0 sourceMap installedMap = do
menv <- getMinimalEnvOverride
caches <- getPackageCaches menv
let latest = Map.fromListWith max $ map toTuple $ Map.keys caches
econfig <- asks getEnvConfig
let onWanted lp = do
case lpExeComponents lp of
Nothing -> return ()
Just _ -> void $ addDep False $ packageName $ lpPackage lp
case lpTestBench lp of
Just tb -> addFinal lp tb
Nothing -> return ()
let inner = do
mapM_ onWanted $ filter lpWanted locals
mapM_ (addDep False) $ Set.toList extraToBuild0
((), m, W efinals installExes dirtyReason deps) <- liftIO $ runRWST inner (ctx econfig latest) M.empty
let toEither (_, Left e) = Left e
toEither (k, Right v) = Right (k, v)
(errlibs, adrs) = partitionEithers $ map toEither $ M.toList m
(errfinals, finals) = partitionEithers $ map toEither $ M.toList efinals
errs = errlibs ++ errfinals
if null errs
then do
let toTask (_, ADRFound _ _ _) = Nothing
toTask (name, ADRToInstall task) = Just (name, task)
tasks = M.fromList $ mapMaybe toTask adrs
takeSubset =
case boptsBuildSubset $ bcoBuildOpts baseConfigOpts0 of
BSAll -> id
BSOnlySnapshot -> stripLocals
BSOnlyDependencies -> stripNonDeps deps
return $ takeSubset Plan
{ planTasks = tasks
, planFinals = M.fromList finals
, planUnregisterLocal = mkUnregisterLocal tasks dirtyReason locallyRegistered sourceMap
, planInstallExes =
if boptsInstallExes $ bcoBuildOpts baseConfigOpts0
then installExes
else Map.empty
}
else throwM $ ConstructPlanExceptions errs (bcStackYaml $ getBuildConfig econfig)
where
ctx econfig latest = Ctx
{ mbp = mbp0
, baseConfigOpts = baseConfigOpts0
, loadPackage = loadPackage0
, combinedMap = combineMap sourceMap installedMap
, toolToPackages = \ (Dependency name _) ->
maybe Map.empty (Map.fromSet (\_ -> anyVersion)) $
Map.lookup (S8.pack . packageNameString . fromCabalPackageName $ name) toolMap
, ctxEnvConfig = econfig
, callStack = []
, extraToBuild = extraToBuild0
, latestVersions = latest
, wanted = wantedLocalPackages locals
}
-- TODO Currently, this will only consider and install tools from the
-- snapshot. It will not automatically install build tools from extra-deps
-- or local packages.
toolMap = getToolMap mbp0
-- | Determine which packages to unregister based on the given tasks and
-- already registered local packages
mkUnregisterLocal :: Map PackageName Task
-> Map PackageName Text
-> Map GhcPkgId PackageIdentifier
-> SourceMap
-> Map GhcPkgId (PackageIdentifier, Maybe Text)
mkUnregisterLocal tasks dirtyReason locallyRegistered sourceMap =
Map.unions $ map toUnregisterMap $ Map.toList locallyRegistered
where
toUnregisterMap (gid, ident) =
case M.lookup name tasks of
Nothing ->
case M.lookup name sourceMap of
Just (PSUpstream _ Snap _) -> Map.singleton gid
( ident
, Just "Switching to snapshot installed package"
)
_ -> Map.empty
Just _ -> Map.singleton gid
( ident
, Map.lookup name dirtyReason
)
where
name = packageIdentifierName ident
addFinal :: LocalPackage -> LocalPackageTB -> M ()
addFinal lp lptb = do
depsRes <- addPackageDeps False package
res <- case depsRes of
Left e -> return $ Left e
Right (missing, present, _minLoc) -> do
ctx <- ask
return $ Right (Task
{ taskProvides = PackageIdentifier
(packageName package)
(packageVersion package)
, taskConfigOpts = TaskConfigOpts missing $ \missing' ->
let allDeps = Map.union present missing'
in configureOpts
(getEnvConfig ctx)
(baseConfigOpts ctx)
allDeps
True -- wanted
Local
package
, taskPresent = present
, taskType = TTLocal lp
}, lptb)
tell mempty { wFinals = Map.singleton (packageName package) res }
where
package = lptbPackage lptb
addDep :: Bool -- ^ is this being used by a dependency?
-> PackageName -> M (Either ConstructPlanException AddDepRes)
addDep treatAsDep' name = do
ctx <- ask
let treatAsDep = treatAsDep' || name `Set.notMember` wanted ctx
when treatAsDep $ markAsDep name
m <- get
case Map.lookup name m of
Just res -> return res
Nothing -> do
res <- addDep' treatAsDep name
modify $ Map.insert name res
return res
addDep' :: Bool -- ^ is this being used by a dependency?
-> PackageName -> M (Either ConstructPlanException AddDepRes)
addDep' treatAsDep name = do
ctx <- ask
if name `elem` callStack ctx
then return $ Left $ DependencyCycleDetected $ name : callStack ctx
else local
(\ctx' -> ctx' { callStack = name : callStack ctx' }) $ do
(addDep'' treatAsDep name)
addDep'' :: Bool -- ^ is this being used by a dependency?
-> PackageName -> M (Either ConstructPlanException AddDepRes)
addDep'' treatAsDep name = do
ctx <- ask
case Map.lookup name $ combinedMap ctx of
-- TODO look up in the package index and see if there's a
-- recommendation available
Nothing -> return $ Left $ UnknownPackage name
Just (PIOnlyInstalled version loc installed) -> do
tellExecutablesUpstream name version loc Map.empty -- slightly hacky, no flags since they likely won't affect executable names
return $ Right $ ADRFound loc version installed
Just (PIOnlySource ps) -> do
tellExecutables name ps
installPackage treatAsDep name ps
Just (PIBoth ps installed) -> do
tellExecutables name ps
needInstall <- checkNeedInstall treatAsDep name ps installed (wanted ctx)
if needInstall
then installPackage treatAsDep name ps
else return $ Right $ ADRFound (piiLocation ps) (piiVersion ps) installed
tellExecutables :: PackageName -> PackageSource -> M () -- TODO merge this with addFinal above?
tellExecutables _ (PSLocal lp)
| lpWanted lp = tellExecutablesPackage Local $ lpPackage lp
| otherwise = return ()
tellExecutables name (PSUpstream version loc flags) = do
tellExecutablesUpstream name version loc flags
tellExecutablesUpstream :: PackageName -> Version -> InstallLocation -> Map FlagName Bool -> M ()
tellExecutablesUpstream name version loc flags = do
ctx <- ask
when (name `Set.member` extraToBuild ctx) $ do
p <- liftIO $ loadPackage ctx name version flags
tellExecutablesPackage loc p
tellExecutablesPackage :: InstallLocation -> Package -> M ()
tellExecutablesPackage loc p = do
cm <- asks combinedMap
-- Determine which components are enabled so we know which ones to copy
let myComps =
case Map.lookup (packageName p) cm of
Nothing -> assert False Set.empty
Just (PIOnlyInstalled _ _ _) -> Set.empty
Just (PIOnlySource ps) -> goSource ps
Just (PIBoth ps _) -> goSource ps
goSource (PSLocal lp) = fromMaybe Set.empty $ lpExeComponents lp
goSource (PSUpstream _ _ _) = Set.empty
tell mempty { wInstall = m myComps }
where
m myComps = Map.fromList $ map (, loc) $ Set.toList
$ filterComps myComps $ packageExes p
filterComps myComps x
| Set.null myComps = x
| otherwise = Set.intersection x $ Set.map toExe myComps
toExe x = fromMaybe x $ T.stripPrefix "exe:" x
-- TODO There are a lot of duplicated computations below. I've kept that for
-- simplicity right now
installPackage :: Bool -- ^ is this being used by a dependency?
-> PackageName -> PackageSource -> M (Either ConstructPlanException AddDepRes)
installPackage treatAsDep name ps = do
ctx <- ask
package <- psPackage name ps
depsRes <- addPackageDeps treatAsDep package
case depsRes of
Left e -> return $ Left e
Right (missing, present, minLoc) -> do
return $ Right $ ADRToInstall Task
{ taskProvides = PackageIdentifier
(packageName package)
(packageVersion package)
, taskConfigOpts = TaskConfigOpts missing $ \missing' ->
let allDeps = Map.union present missing'
destLoc = piiLocation ps <> minLoc
in configureOpts
(getEnvConfig ctx)
(baseConfigOpts ctx)
allDeps
(psWanted ps)
-- An assertion to check for a recurrence of
-- https://github.com/commercialhaskell/stack/issues/345
(assert (destLoc == piiLocation ps) destLoc)
package
, taskPresent = present
, taskType =
case ps of
PSLocal lp -> TTLocal lp
PSUpstream _ loc _ -> TTUpstream package $ loc <> minLoc
}
checkNeedInstall :: Bool
-> PackageName -> PackageSource -> Installed -> Set PackageName -> M Bool
checkNeedInstall treatAsDep name ps installed wanted = assert (piiLocation ps == Local) $ do
package <- psPackage name ps
depsRes <- addPackageDeps treatAsDep package
case depsRes of
Left _e -> return True -- installPackage will find the error again
Right (missing, present, _loc)
| Set.null missing -> checkDirtiness ps installed package present wanted
| otherwise -> do
tell mempty { wDirty = Map.singleton name $
let t = T.intercalate ", " $ map (T.pack . packageNameString . packageIdentifierName) (Set.toList missing)
in T.append "missing dependencies: " $
if T.length t < 100
then t
else T.take 97 t <> "..." }
return True
addPackageDeps :: Bool -- ^ is this being used by a dependency?
-> Package -> M (Either ConstructPlanException (Set PackageIdentifier, Map PackageIdentifier GhcPkgId, InstallLocation))
addPackageDeps treatAsDep package = do
ctx <- ask
deps' <- packageDepsWithTools package
deps <- forM (Map.toList deps') $ \(depname, range) -> do
eres <- addDep treatAsDep depname
let mlatest = Map.lookup depname $ latestVersions ctx
case eres of
Left e ->
let bd =
case e of
UnknownPackage name -> assert (name == depname) NotInBuildPlan
_ -> Couldn'tResolveItsDependencies
in return $ Left (depname, (range, mlatest, bd))
Right adr | not $ adrVersion adr `withinRange` range ->
return $ Left (depname, (range, mlatest, DependencyMismatch $ adrVersion adr))
Right (ADRToInstall task) -> return $ Right
(Set.singleton $ taskProvides task, Map.empty, taskLocation task)
Right (ADRFound loc _ (Executable _)) -> return $ Right
(Set.empty, Map.empty, loc)
Right (ADRFound loc _ (Library ident gid)) -> return $ Right
(Set.empty, Map.singleton ident gid, loc)
case partitionEithers deps of
([], pairs) -> return $ Right $ mconcat pairs
(errs, _) -> return $ Left $ DependencyPlanFailures
(PackageIdentifier
(packageName package)
(packageVersion package))
(Map.fromList errs)
where
adrVersion (ADRToInstall task) = packageIdentifierVersion $ taskProvides task
adrVersion (ADRFound _ v _) = v
checkDirtiness :: PackageSource
-> Installed
-> Package
-> Map PackageIdentifier GhcPkgId
-> Set PackageName
-> M Bool
checkDirtiness ps installed package present wanted = do
ctx <- ask
moldOpts <- tryGetFlagCache installed
let configOpts = configureOpts
(getEnvConfig ctx)
(baseConfigOpts ctx)
present
(psWanted ps)
(piiLocation ps) -- should be Local always
package
buildOpts = bcoBuildOpts (baseConfigOpts ctx)
wantConfigCache = ConfigCache
{ configCacheOpts = configOpts
, configCacheDeps = Set.fromList $ Map.elems present
, configCacheComponents =
case ps of
PSLocal lp -> Set.map renderComponent $ lpComponents lp
PSUpstream _ _ _ -> Set.empty
, configCacheHaddock =
shouldHaddockPackage buildOpts wanted (packageName package) ||
-- Disabling haddocks when old config had haddocks doesn't make dirty.
maybe False configCacheHaddock moldOpts
}
let mreason =
case moldOpts of
Nothing -> Just "old configure information not found"
Just oldOpts
| Just reason <- describeConfigDiff oldOpts wantConfigCache -> Just reason
| psDirty ps -> Just "local file changes"
| otherwise -> Nothing
case mreason of
Nothing -> return False
Just reason -> do
tell mempty { wDirty = Map.singleton (packageName package) reason }
return True
describeConfigDiff :: ConfigCache -> ConfigCache -> Maybe Text
describeConfigDiff old new
| configCacheDeps old /= configCacheDeps new = Just "dependencies changed"
| not $ Set.null newComponents =
Just $ "components added: " `T.append` T.intercalate ", "
(map (decodeUtf8With lenientDecode) (Set.toList newComponents))
| not (configCacheHaddock old) && configCacheHaddock new = Just "rebuilding with haddocks"
| oldOpts /= newOpts = Just $ T.pack $ concat
[ "flags changed from "
, show oldOpts
, " to "
, show newOpts
]
| otherwise = Nothing
where
-- options set by stack
isStackOpt t = any (`T.isPrefixOf` t)
[ "--dependency="
, "--constraint="
, "--package-db="
, "--libdir="
, "--bindir="
, "--enable-tests"
, "--enable-benchmarks"
]
userOpts = filter (not . isStackOpt)
. map T.pack
. (\(ConfigureOpts x y) -> x ++ y)
. configCacheOpts
(oldOpts, newOpts) = removeMatching (userOpts old) (userOpts new)
removeMatching (x:xs) (y:ys)
| x == y = removeMatching xs ys
removeMatching xs ys = (xs, ys)
newComponents = configCacheComponents new `Set.difference` configCacheComponents old
psDirty :: PackageSource -> Bool
psDirty (PSLocal lp) = lpDirtyFiles lp
psDirty (PSUpstream _ _ _) = False -- files never change in an upstream package
psWanted :: PackageSource -> Bool
psWanted (PSLocal lp) = lpWanted lp
psWanted (PSUpstream _ _ _) = False
psPackage :: PackageName -> PackageSource -> M Package
psPackage _ (PSLocal lp) = return $ lpPackage lp
psPackage name (PSUpstream version _ flags) = do
ctx <- ask
liftIO $ loadPackage ctx name version flags
-- | Get all of the dependencies for a given package, including guessed build
-- tool dependencies.
packageDepsWithTools :: Package -> M (Map PackageName VersionRange)
packageDepsWithTools p = do
ctx <- ask
return $ Map.unionsWith intersectVersionRanges
$ packageDeps p
: map (toolToPackages ctx) (packageTools p)
-- | Strip out anything from the @Plan@ intended for the local database
stripLocals :: Plan -> Plan
stripLocals plan = plan
{ planTasks = Map.filter checkTask $ planTasks plan
, planFinals = Map.empty
, planUnregisterLocal = Map.empty
, planInstallExes = Map.filter (/= Local) $ planInstallExes plan
}
where
checkTask task =
case taskType task of
TTLocal _ -> False
TTUpstream _ Local -> False
TTUpstream _ Snap -> True
stripNonDeps :: Set PackageName -> Plan -> Plan
stripNonDeps deps plan = plan
{ planTasks = Map.filter checkTask $ planTasks plan
, planFinals = Map.empty
, planInstallExes = Map.empty -- TODO maybe don't disable this?
}
where
checkTask task = packageIdentifierName (taskProvides task) `Set.member` deps
markAsDep :: PackageName -> M ()
markAsDep name = tell mempty { wDeps = Set.singleton name }
| kairuku/stack | src/Stack/Build/ConstructPlan.hs | bsd-3-clause | 22,289 | 0 | 27 | 7,214 | 5,696 | 2,864 | 2,832 | 486 | 9 |
module PfeSocket(listenOnPFE,connectToPFE,acceptPFE,removePFE,
pfeClient,clientOps,serverOps,sResult,errorString) where
import Prelude hiding (putStr,readIO)
import Network(listenOn,accept,connectTo,PortID(..))
import IO(hPutStrLn,hPrint,hGetLine,hGetContents,hClose,hSetBuffering,BufferMode(..))
import AbstractIO
import MUtils(ifM,done)
import SIO
listenOnPFE dir = ifM (doesFileExist (pfePath dir)) tryConnect listen
where
listen = listenOn (pfePort dir)
tryConnect =
do r <- try connect
case r of
Left _ -> cleanUp>>listen
Right _ -> backoff
connect = do h <- connectToPFE dir
hPutStrLn h ""
s <- hGetContents h
seq (length s) done -- to avoid crashing the server
hClose h
backoff = fail "PFE Server is already running"
cleanUp = removePFE dir
acceptPFE s = do a@(h,_,_) <- accept s
hSetBuffering h IO.LineBuffering
return a
connectToPFE dir =
do h <- connectTo "localhost" (pfePort dir)
hSetBuffering h LineBuffering
return h
pfeClient h args =
do inBase $ hPutStrLn h (unwords args)
clientLoop
inBase $ hClose h
where
clientLoop =
do msg <- inBase $ hReadLn h
case msg of
Stdout s -> putStr s >> clientLoop
Stderr s -> ePutStr s >> clientLoop
Result r -> case r of
Left s -> fail s
Right () -> done
removePFE = removeFile . pfePath
pfePort = UnixSocket . pfePath
pfePath dir = dir++"/pfeserver"
data Msg = Stdout String | Stderr String | Result Result deriving (Read,Show)
type Result = Either String ()
serverOps h = StdIO {put=sPut h, eput=sePut h}
clientOps = StdIO {put=putStr, eput=ePutStr {-. color-}}
-- where color s = "\ESC[31m"++s++"\ESC[m"
sPut h = hPrint h . Stdout
sePut h = hPrint h . Stderr
sResult h = hPrint h . Result . either (Left . show) Right
hReadLn h = readIO =<< hGetLine h
-- Work around the ugly way GHC prints user errors...
errorString e =
if isUserError e
then dropPrefix "user error\nReason: " (ioeGetErrorString e)
else show e
dropPrefix (x:xs) (y:ys) | x==y = dropPrefix xs ys
dropPrefix _ ys = ys
| forste/haReFork | tools/pfe/PfeSocket.hs | bsd-3-clause | 2,141 | 10 | 13 | 507 | 706 | 373 | 333 | 58 | 4 |
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveFoldable, DeriveTraversable #-}
module Distribution.Client.Dependency.Modular.PSQ where
-- Priority search queues.
--
-- I am not yet sure what exactly is needed. But we need a data structure with
-- key-based lookup that can be sorted. We're using a sequence right now with
-- (inefficiently implemented) lookup, because I think that queue-based
-- operations and sorting turn out to be more efficiency-critical in practice.
import Data.Foldable
import Data.Function
import Data.List as S hiding (foldr)
import Data.Traversable
import Prelude hiding (foldr)
newtype PSQ k v = PSQ [(k, v)]
deriving (Eq, Show, Functor, Foldable, Traversable)
keys :: PSQ k v -> [k]
keys (PSQ xs) = fmap fst xs
lookup :: Eq k => k -> PSQ k v -> Maybe v
lookup k (PSQ xs) = S.lookup k xs
map :: (v1 -> v2) -> PSQ k v1 -> PSQ k v2
map f (PSQ xs) = PSQ (fmap (\ (k, v) -> (k, f v)) xs)
mapKeys :: (k1 -> k2) -> PSQ k1 v -> PSQ k2 v
mapKeys f (PSQ xs) = PSQ (fmap (\ (k, v) -> (f k, v)) xs)
mapWithKey :: (k -> a -> b) -> PSQ k a -> PSQ k b
mapWithKey f (PSQ xs) = PSQ (fmap (\ (k, v) -> (k, f k v)) xs)
mapWithKeyState :: (s -> k -> a -> (b, s)) -> PSQ k a -> s -> PSQ k b
mapWithKeyState p (PSQ xs) s0 =
PSQ (foldr (\ (k, v) r s -> case p s k v of
(w, n) -> (k, w) : (r n))
(const []) xs s0)
delete :: Eq k => k -> PSQ k a -> PSQ k a
delete k (PSQ xs) = PSQ (snd (partition ((== k) . fst) xs))
fromList :: [(k, a)] -> PSQ k a
fromList = PSQ
cons :: k -> a -> PSQ k a -> PSQ k a
cons k x (PSQ xs) = PSQ ((k, x) : xs)
snoc :: PSQ k a -> k -> a -> PSQ k a
snoc (PSQ xs) k x = PSQ (xs ++ [(k, x)])
casePSQ :: PSQ k a -> r -> (k -> a -> PSQ k a -> r) -> r
casePSQ (PSQ xs) n c =
case xs of
[] -> n
(k, v) : ys -> c k v (PSQ ys)
splits :: PSQ k a -> PSQ k (a, PSQ k a)
splits = go id
where
go f xs = casePSQ xs
(PSQ [])
(\ k v ys -> cons k (v, f ys) (go (f . cons k v) ys))
sortBy :: (a -> a -> Ordering) -> PSQ k a -> PSQ k a
sortBy cmp (PSQ xs) = PSQ (S.sortBy (cmp `on` snd) xs)
sortByKeys :: (k -> k -> Ordering) -> PSQ k a -> PSQ k a
sortByKeys cmp (PSQ xs) = PSQ (S.sortBy (cmp `on` fst) xs)
filterKeys :: (k -> Bool) -> PSQ k a -> PSQ k a
filterKeys p (PSQ xs) = PSQ (S.filter (p . fst) xs)
filter :: (a -> Bool) -> PSQ k a -> PSQ k a
filter p (PSQ xs) = PSQ (S.filter (p . snd) xs)
length :: PSQ k a -> Int
length (PSQ xs) = S.length xs
-- | "Lazy length".
--
-- Only approximates the length, but doesn't force the list.
llength :: PSQ k a -> Int
llength (PSQ []) = 0
llength (PSQ (_:[])) = 1
llength (PSQ (_:_:[])) = 2
llength (PSQ _) = 3
null :: PSQ k a -> Bool
null (PSQ xs) = S.null xs
toList :: PSQ k a -> [(k, a)]
toList (PSQ xs) = xs
| DavidAlphaFox/ghc | libraries/Cabal/cabal-install/Distribution/Client/Dependency/Modular/PSQ.hs | bsd-3-clause | 2,802 | 0 | 15 | 750 | 1,491 | 779 | 712 | 61 | 2 |
{-# OPTIONS -fno-warn-redundant-constraints #-}
-- !!! This is the example given in TcDeriv
--
module ShouldSucceed where
data T a b
= C1 (Foo a) (Bar b)
| C2 Int (T b a)
| C3 (T a a)
deriving Eq
data Foo a = MkFoo Double a deriving ()
instance (Eq a) => Eq (Foo a)
data Bar a = MkBar Int Int deriving ()
instance (Ping b) => Eq (Bar b)
class Ping a
| urbanslug/ghc | testsuite/tests/deriving/should_compile/drv003.hs | bsd-3-clause | 365 | 0 | 8 | 90 | 146 | 82 | 64 | -1 | -1 |
-- !! check if tc type substitutions really do
-- !! clone (or if not, work around it by cloning
-- !! all binders in first pass of the simplifier).
module ShouldCompile where
f,g :: Eq a => (a,b)
f = g
g = f
| sdiehl/ghc | testsuite/tests/typecheck/should_compile/tc099.hs | bsd-3-clause | 210 | 0 | 6 | 46 | 37 | 24 | 13 | 4 | 1 |
{-# LANGUAGE PatternSynonyms #-}
module Main where
pattern First x <- x:_ where
First x = foo [x, x, x]
foo :: [a] -> [a]
foo xs@(First x) = replicate (length xs + 1) x
main = mapM_ print $ First ()
| ghc-android/ghc | testsuite/tests/patsyn/should_run/bidir-explicit-scope.hs | bsd-3-clause | 204 | 0 | 8 | 47 | 105 | 56 | 49 | 7 | 1 |
module System.Apotiki.Debian.Control (DebInfo, ctlFromData) where
import System.Apotiki.Utils
import Data.Attoparsec.Combinator (manyTill, many1)
import Data.ByteString.Char8 (pack, unpack)
import Data.List (intersperse)
import qualified Data.Map as M
import qualified Data.ByteString as B
import qualified Data.Attoparsec.ByteString as P
type DebInfo = M.Map String String
ctlValParser :: P.Parser String
ctlValParser = do
P.string $ pack " "
val <- unpack `fmap` P.takeWhile (P.notInClass "\n")
P.string $ pack "\n"
return val
ctlFlatDescParser = (concat . intersperse "\n ") `fmap` many1 ctlValParser
ctlEntryParser :: P.Parser (String, String)
ctlEntryParser = do
k <- unpack `fmap` P.takeWhile (P.notInClass ":")
P.string $ pack ":"
v <- if (k == "Description") then ctlFlatDescParser else ctlValParser
return (k, strip v)
ctlParser :: P.Parser DebInfo
ctlParser = M.fromList `fmap` many1 ctlEntryParser
ctlFromData :: B.ByteString -> Either String DebInfo
ctlFromData input = P.parseOnly ctlParser input
ctlFromFile :: String -> IO (Either String DebInfo)
ctlFromFile path = do
content <- B.readFile path
return (ctlFromData content)
| pyr/apotiki | System/Apotiki/Debian/Control.hs | isc | 1,167 | 0 | 12 | 176 | 398 | 213 | 185 | 30 | 2 |
to_tens :: Integer -> [Integer]
to_tens 0 = []
to_tens n = to_tens (n `div` 10) ++ [n `mod` 10]
isPrime :: Integer -> Bool
isPrime 1 = False
isPrime k
| k <= 0 = False
|otherwise = null [ x | x <- [2..(truncate $ sqrt $ fromIntegral k)], k `mod` x == 0]
from_tens xs = sum $ map (\(a,b) -> 10^a * b) $ zip [0..] $ reverse xs
truncate_left' xs 0 = xs
truncate_left' (x:[]) _ = []
truncate_left' (x:xs) 1 = xs
truncate_left' (x:xs) n = (truncate_left' (xs) (n-1))
truncate_left num n = from_tens $ truncate_left' (to_tens num) n
truncate_right num n = let xs = to_tens num
in from_tens $ reverse $ truncate_left' (reverse xs) n
is_truncatable_prime 2 = False
is_truncatable_prime 3 = False
is_truncatable_prime 5 = False
is_truncatable_prime 7 = False
is_truncatable_prime n = let
l = length $ to_tens n
in
and $ map isPrime $ map (truncate_left n) [0..(l-1)] ++ map (truncate_right n) [0..(l-1)]
-- ++ ((truncate_left n) [0..(l-1)]))
ans = filter is_truncatable_prime [x| x <- [11,13..739397], isPrime x] | stefan-j/ProjectEuler | q37.hs | mit | 1,093 | 10 | 13 | 268 | 509 | 262 | 247 | 24 | 1 |
-- Isomorphism
-- https://www.codewars.com/kata/5922543bf9c15705d0000020
module ISO where
import Data.Void
import Data.Tuple(swap)
import Control.Arrow ((***), (+++))
type ISO a b = (a -> b, b -> a)
substL :: ISO a b -> (a -> b)
substL = fst
substR :: ISO a b -> (b -> a)
substR = snd
isoBool :: ISO Bool Bool
isoBool = (id, id)
isoBoolNot :: ISO Bool Bool
isoBoolNot = (not, not)
refl :: ISO a a
refl = (id, id)
symm :: ISO a b -> ISO b a
symm = swap
trans :: ISO a b -> ISO b c -> ISO a c
trans (ab, ba) (bc, cb) = (bc . ab, ba . cb)
isoTuple :: ISO a b -> ISO c d -> ISO (a, c) (b, d)
isoTuple (ab, ba) (cd, dc) = (ab *** cd, ba *** dc)
isoList :: ISO a b -> ISO [a] [b]
isoList (ab, ba) = (map ab, map ba)
isoMaybe :: ISO a b -> ISO (Maybe a) (Maybe b)
isoMaybe (ab, ba) = (fmap ab, fmap ba)
isoEither :: ISO a b -> ISO c d -> ISO (Either a c) (Either b d)
isoEither (ab, ba) (cd, dc) = (ab +++ cd, ba +++ dc)
isoFunc :: ISO a b -> ISO c d -> ISO (a -> c) (b -> d)
isoFunc (ab, ba) (cd, dc) = (\f -> cd . f . ba, \f -> dc . f . ab)
isoUnMaybe :: ISO (Maybe a) (Maybe b) -> ISO a b
isoUnMaybe m@(mamb, mbma) = (get . mamb . Just, substL $ isoUnMaybe $ symm m)
where get (Just b) = b
get Nothing = getJust (mamb Nothing)
getJust (Just b) = b
getJust Nothing = undefined
isoEU :: ISO (Either [()] ()) (Either [()] Void)
isoEU = (Left . either ( (): ) (const []), ab)
where ab (Left []) = Right ()
ab (Left (_:x)) = Left x
ab (Right v) = absurd v
isoSymm :: ISO (ISO a b) (ISO b a)
isoSymm = (symm, symm)
| gafiatulin/codewars | src/3 kyu/Isomorphism.hs | mit | 1,582 | 0 | 11 | 419 | 924 | 497 | 427 | 42 | 3 |
module S8_1 where
-- Tipo das funções utilizadas em divideAndConquer
--ind :: p -> Bool
--solve :: p -> s
--divide :: p -: [s]
--combine :: p -> [s] -> s
divideAndConquer :: ( p -> Bool) -> (p -> s) -> (p -> [p]) -> (p -> [s] -> s)
-> p -> s
divideAndConquer ind solve divide combine initPb
= dc' initPb
where dc' pb
| ind pb = solve pb
| otherwise = combine pb (map dc' (divide pb))
msort xs = divideAndConquer ind id divide combine xs
where ind xs = length xs <= 1
divide xs = let n = length xs `div` 2
in [take n xs , drop n xs]
combine _ [l1,l2] = merge l1 l2
merge :: (Ord a) => [a] -> [a] -> [a]
merge [] b = b
merge a [] = a
merge a@(x:xs) b@(y:ys) | (x<=y) = x : (merge xs b)
| otherwise = y : (merge a ys)
qsort xs = divideAndConquer ind id divide combine xs
where ind xs = length xs <= 1
divide (x:xs) = [[ y | y<-xs, y<=x],
[ y | y<-xs, y>x] ]
combine (x:_) [l1,l2] = l1 ++ [x] ++ l2
l = [3,1,4,1,5,9,2]
{- Examples of evaluations and results
? msort l
[1, 1, 2, 3, 4, 5, 9]
? qsort l
[1, 1, 2, 3, 4, 5, 9]
-}
| gustavoramos00/tecnicas-topdown | S8_1.hs | mit | 1,261 | 0 | 12 | 472 | 529 | 279 | 250 | 24 | 1 |
module PosNegIf where
posOrNeg x =
if x >= 0
then "Pos "
else "Neg "
-- note no returns or paren
| HaskellForCats/HaskellForCats | simpcondi1.hs | mit | 106 | 6 | 6 | 31 | 31 | 18 | 13 | 5 | 2 |
module Nodes.Statement where
import Nodes
import Nodes.Expression (Expr)
data Stmt
= Line { expr :: Expr }
instance AstNode Stmt where
ast (Line expr) = ast expr
| milankinen/cbhs | src/nodes/Statement.hs | mit | 169 | 0 | 8 | 34 | 59 | 33 | 26 | 7 | 0 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Betfair.StreamingAPI.API.ToRequest
( ToRequest
, toRequest
) where
-- import Protolude
import Betfair.StreamingAPI.API.Request
import qualified Betfair.StreamingAPI.Requests.AuthenticationMessage as A
import qualified Betfair.StreamingAPI.Requests.HeartbeatMessage as H
import qualified Betfair.StreamingAPI.Requests.MarketSubscriptionMessage as M
import qualified Betfair.StreamingAPI.Requests.OrderSubscriptionMessage as O
class ToRequest a where
toRequest :: a -> Request
instance ToRequest A.AuthenticationMessage where
toRequest a = Authentication a
instance ToRequest H.HeartbeatMessage where
toRequest a = Heartbeat a
instance ToRequest M.MarketSubscriptionMessage where
toRequest a = MarketSubscribe a
instance ToRequest O.OrderSubscriptionMessage where
toRequest a = OrderSubscribe a
| joe9/streaming-betfair-api | src/Betfair/StreamingAPI/API/ToRequest.hs | mit | 917 | 0 | 7 | 133 | 168 | 100 | 68 | 20 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
import Data.Attoparsec.ByteString.Char8 hiding (take)
import qualified Data.ByteString as B
import Control.Applicative
import Data.List (sortBy, groupBy, maximumBy, transpose)
import Data.Ord (comparing)
import Data.Function (on)
import qualified Data.MultiSet as MS
main :: IO ()
main = do
deer <- parseAssert pHerd <$> B.readFile "input.txt"
let time = 2503
print . snd . maxOccur $ scores time deer
maxOccur :: Ord a => MS.MultiSet a -> (a, Int)
maxOccur = maximumBy (comparing snd) . MS.toOccurList
scores :: Time -> [Reindeer] -> MS.MultiSet Reindeer
scores time deer = MS.fromList . concat . take time . zipManyWith best $ deer_dists
where best = map fst . last . groupBy ((==) `on` snd) . sortBy (comparing snd)
best :: [(Reindeer, Distance)] -> [Reindeer]
deer_dists = map single_dists deer
deer_dists :: [[(Reindeer, Distance)]]
single_dists d = map ((,) d) $ distances d
single_dists :: Reindeer -> [(Reindeer, Distance)]
zipManyWith :: ([a] -> b) -> [[a]] -> [b]
zipManyWith f = map f . transpose
distances :: Reindeer -> [Distance]
distances = tail . scanl (+) 0 . gains
traveled :: Time -> Reindeer -> Distance
traveled t = sum . take t . gains
gains :: Reindeer -> [Distance]
gains Reindeer{..} = cycle $ replicate flyTime speed ++ replicate restTime 0
pHerd :: Parser [Reindeer]
pHerd = pReindeer `sepBy` endOfLine <* ending
where ending = many endOfLine <* endOfInput
pReindeer :: Parser Reindeer
pReindeer = Reindeer <$>
pName <* " can fly " <*>
decimal <* " km/s for " <*>
decimal <* " seconds, but then must rest for " <*>
decimal <* " seconds."
where pName = many letter_ascii
data Reindeer = Reindeer {
name :: String,
speed :: Int,
flyTime :: Int,
restTime :: Int
} deriving (Eq, Show, Ord)
type Distance = Int
type Time = Int
parseAssert :: Parser a -> B.ByteString -> a
parseAssert parser input =
case parseOnly parser input of
Right p -> p
Left err -> error $ "Bad parse: " ++ err
| devonhollowood/adventofcode | 2015/day14/day14.hs | mit | 2,114 | 0 | 12 | 473 | 752 | 406 | 346 | 55 | 2 |
lucky :: Int -> String
lucky 7 = "LUCKY NUMBER SEVEN!"
lucky x = "Sorry, you're out of luck, pal!"
sayMe :: Int -> String
sayMe 1 = "One!"
sayMe 2 = "Two!"
sayMe 3 = "Three!"
sayMe 4 = "Four!"
sayMe 5 = "Five!"
sayMe x = "Not between 1 and 5"
factrial :: Int -> Int
factrial 0 = 1
factrial n = n * factrial (n - 1)
addVectors :: (Double, Double) -> (Double, Double) -> (Double, Double)
addVectors (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
first :: (a, b, c) -> a
first (x, _, _) = x
second :: (a, b, c) -> b
second (_, y, _) = y
third :: (a, b, c) -> c
third (_, _, z) = z
xs = [(1, 3), (4, 3), (2, 4)]
{- [a + b | (a, b) <- xs] -}
{- head' :: [a] -> a -}
{- head' [] = error "Can't call head on an empty list." -}
{- head' (x:_) = x -}
head' :: [a] -> a
head' xs = case xs of [] -> error "Can't call head on an empty list."
(x:_) -> x
tell :: (Show a) => [a] -> String
tell [] = "The list is empty"
tell (x:[]) = "The list is one element: " ++ show x
tell (x:y:[]) = "The list is two elements: " ++ show x ++ " and " ++ show y
tell (x:y:_) = "This list is long. The first two elements are: " ++ show x ++ " and " ++ show y
firstLetter :: String -> String
firstLetter "" = "Empty string, whoops!"
firstLetter all@(x:xs) = "The first letter of " ++ all ++ " is " ++ [x]
bmiTell :: Double -> Double -> String
bmiTell weight height
| weight / height ^ 2 <= 18.5 = "You're underweight!"
| weight / height ^ 2 <= 25.0 = "You're supposedly normal."
| weight / height ^ 2 <= 30.0 = "You're overweight!"
| otherwise = "You're a whale, congratulations!"
{- bmiTell' :: Double -> Double -> String -}
{- bmiTell' weight height -}
{- | bmi <= 18.5 = "You're underweight!" -}
{- | bmi <= 25.0 = "You're supposedly normal." -}
{- | bmi <= 30.0 = "You're overweight!" -}
{- | otherwise = "You're a whale, congratulations!" -}
{- where bmi = weight / height ^ 2 -}
{- bmiTell' :: Double -> Double -> String -}
{- bmiTell' weight height -}
{- | bmi <= underweight = "You're underweight!" -}
{- | bmi <= normal = "You're supposedly normal." -}
{- | bmi <= overweight = "You're overweight!" -}
{- | otherwise = "You're a whale, congratulations!" -}
{- where bmi = weight / height ^ 2 -}
{- underweight = 18.5 -}
{- normal = 25.0 -}
{- overweight = 30.0 -}
bmiTell' :: Double -> Double -> String
bmiTell' weight height
| bmi <= underweight = "You're underweight!"
| bmi <= normal = "You're supposedly normal."
| bmi <= overweight = "You're overweight!"
| otherwise = "You're a whale, congratulations!"
where bmi = weight / height ^ 2
(underweight, normal, overweight) = (18.5, 25.0, 30.0)
max' :: (Ord a) => a -> a -> a
max' a b
| a <= b = b
| otherwise = a
myCompare :: (Ord a) => a -> a -> Ordering
a `myCompare` b
| a == b = EQ
| a <= b = LT
| otherwise = GT
badGreeting :: String
badGreeting = "Who are you?"
niceGreeting :: String
niceGreeting = "Hello!"
greet :: String -> String
greet "Juan" = niceGreeting ++ " Juan!"
greet "Fernando" = niceGreeting ++ " Fernando!"
greet name = badGreeting ++ " " ++ name
initials :: String -> String -> String
initials firstname lastname = [f] ++ ". " ++ [l] ++ "."
where (f:_) = firstname
(l:_) = lastname
calcBmis :: [(Double, Double)] -> [Double]
calcBmis xs = [bmi w h | (w, h) <- xs]
where bmi weight height = weight / height ^ 2
{- calcBmis' :: [(Double, Double)] -> [Double] -}
{- calcBmis' xs = [bmi | (w, h) <- xs, let bmi = w / h ^ 2] -}
calcBmis' :: [(Double, Double)] -> [Double]
calcBmis' xs = [bmi | (w, h) <- xs, let bmi = w / h ^ 2, bmi > 25.0]
cylinder :: Double -> Double -> Double
cylinder r h =
let sideArea = 2 * pi * r * h
topArea = pi * r ^ 2
in sideArea * topArea
{- 4 * (let a = 9 in a + 1) + 2 -}
{- 42 -}
{- [let square x = x * x in (square 5, square 3, square 2)] -}
{- [(25,9,4)] -}
{- (let a = 100; b = 200; c = 300 in a * b * c, -}
{- let foo = "Hey "; bar = "there!" in foo ++ bar) -}
{- (6000000,"Hey there!") -}
{- (let (a, b, c) = (1, 2, 3) in a + b + c) * 100 -}
{- 600 -}
describeList :: [a] -> String
describeList ls = "The list is "
++ case ls of [] -> "empty."
[x] -> "a singleton list."
xs -> "a longer list."
describeList' :: [a] -> String
describeList' ls = "The list is " ++ what ls
where what [] = "empty."
what [x] = "a singleton list."
what xs = "a longer list."
| yhoshino11/learning_haskell | ch3.hs | mit | 4,601 | 0 | 11 | 1,295 | 1,357 | 735 | 622 | 88 | 3 |
module Compiler.GCC.JIT.Monad.Result where
import Compiler.GCC.JIT.Monad.Utilities
import Compiler.GCC.JIT.Monad.Types
import Compiler.GCC.JIT.Foreign.Types
import Compiler.GCC.JIT.Foreign.Context
import Foreign.Ptr
import Data.ByteString (ByteString)
import Control.Monad.IO.Class (liftIO)
-- * Result functions
-- | Create a result from the current context
withResult :: (JITResult -> JITState s a) -> JITState s a
withResult f = do
rez <- compile
ret <- f rez
release rez
return ret
-- | Compile the current context and return the result, it is recomend to use 'withResult' instead since you will have to manually free the result from this function with 'releaseResult'
compile :: JITState s JITResult
compile = inContext contextCompile
-- | gcc_jit_result_get_code
getCode :: JITResult
-> ByteString -- ^ Function name
-> JITState s (FunPtr a)
getCode = liftIO2 resultGetCode
-- | gcc_jit_result_get_global
getGlobal :: JITResult
-> ByteString -- ^ Global name
-> JITState s (Ptr a)
getGlobal = liftIO2 resultGetGlobal
-- | Compile the current context to a file
compileToFile :: JITOutputKind -- ^ Output file type
-> ByteString -- ^ Output file path
-> JITState s ()
compileToFile = inContext2 contextCompileToFile
| Slowki/hgccjit | src/Compiler/GCC/JIT/Monad/Result.hs | mit | 1,311 | 0 | 9 | 263 | 251 | 141 | 110 | 28 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Aether.Parser
-- Copyright : (c) Allen Guo 2013
-- License : MIT
--
-- Maintainer : Allen Guo <[email protected]>
-- Stability : alpha
--
-- This module contains several simple XML-parsing regex
-- functions, as well as other text utility functions.
--
-----------------------------------------------------------------------------
module Aether.Parser ( extractBetween
, extractAllAttrValues
, extractAttrValue
, trim
) where
import Data.Text (pack, strip, unpack)
import Text.Regex (matchRegex, mkRegex, mkRegexWithOpts, splitRegex)
-- | Given a list of strings, returns those strings that are
-- non-null as a list.
nonNull :: [String] -> [String]
nonNull = filter (/= [])
-- | Returns the given string with whitespace trimmed.
trim :: String -> String
trim = unpack . strip . pack
-- | A utility regex function that returns the first match found with
-- the given text and regex string. Returns an empty string if no matches
-- are found.
stdRegex :: String -> String -> String
stdRegex text regex =
case matchRegex (mkRegexWithOpts regex False False) text of
Nothing -> ""
Just matches -> head matches
-- | @extractBetween text start end@ will return the portion of @text@ between
-- @start@ and @end@ as a string.
extractBetween :: String -> String -> String -> String
extractBetween start end text = stdRegex text $ start ++ "(.*)" ++ end
-- | @extractAttrValue text attr@, where @text@ is a XML string, returns
-- the value of the first instance of the XML attribute @attr@. Returns
-- an empty string If no instances of @attr@ exist in the given XML string.
extractAttrValue :: String -> String -> String
extractAttrValue attr text =
case extractAllAttrValues attr text of
[] -> ""
xs -> head xs
-- | @extractAllAttrValues text attr@, where @text@ is a XML string, returns
-- the values of all instances of the XML attribute @attr@.
extractAllAttrValues :: String -> String -> [String]
extractAllAttrValues attr text = nonNull $ map extract chunks where
extract = flip stdRegex (attr ++ "=\"([^\"]*)\"")
chunks = splitRegex (mkRegex "<") text | guoguo12/aether | src/Aether/Parser.hs | mit | 2,275 | 0 | 9 | 463 | 355 | 201 | 154 | 26 | 2 |
{-
Author: Nick(Mykola) Pershyn
Language: Haskell
Program: Dominion Server
-}
import Data.List
import System.IO
import System.Process
import System.Environment
import System.Exit
import DominionTypes
main = do
myArgs <- getArgs
let players = myArgs
let playerProcs = map (\x -> createProcess (proc x []){std_in = CreatePipe, std_out = CreatePipe, std_err = CreatePipe}) players
player <- head playerProcs
hPutStrLn (getInput player) "5"
hFlush (getInput player)
answer <- hGetContents (getOutput player)
putStr answer
getInput :: (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) -> Handle
getInput (h, _, _, _) = fromMaybe stdin h
getOutput :: (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) -> Handle
getOutput (_, h, _, _) = fromMaybe stdout h
| LinuxUser404/haskell-dominion | src/DominionServer.hs | gpl-2.0 | 786 | 0 | 17 | 130 | 274 | 142 | 132 | 19 | 1 |
module TH.MetaLabel (
makeMakeLabel
, makeMakeLabels
) where
import Types
import Utils
import Prelude
import Language.Haskell.TH
import Language.Haskell.TH.Syntax (sequenceQ)
makeMakeLabels :: [(String, String)] -> Q [Dec]
makeMakeLabels ns = fmap concat $ sequenceQ $ map makeMakeLabel ns
makeMakeLabel :: (String, String) -> Q [Dec]
makeMakeLabel (short, labelName) = return [makeLabelSig, makeLabelFun, makeLabelsSig, makeLabelsFun]
where
funNameStr :: String
funNameStr = "make" ++ pascalCase short
funName :: Name
funName = mkName funNameStr
funsName :: Name
funsName = mkName $ funNameStr ++ "s"
makeLabelSig :: Dec
makeLabelSig = SigD funName
$ AppT
(AppT
ArrowT
(ConT ''String))
(ConT ''DecsQ)
makeLabelFun :: Dec
makeLabelFun = FunD funName
[
Clause
[]
(NormalB $
AppE
(VarE $ mkName "makeLabel")
-- (AppE
-- (VarE 'mkName)
(LitE $ StringL $ labelName))
[]
]
makeLabelsSig :: Dec
makeLabelsSig = SigD funsName
$ AppT
(AppT
ArrowT
(AppT
ListT
(ConT ''String)))
(ConT ''DecsQ)
makeLabelsFun :: Dec
makeLabelsFun = FunD funsName
[
Clause
[]
(NormalB $
AppE
(VarE $ mkName "makeLabels")
-- (AppE
-- (VarE 'mkName)
(LitE $ StringL $ labelName))
[]
]
| NorfairKing/the-notes | src/TH/MetaLabel.hs | gpl-2.0 | 2,057 | 0 | 15 | 1,073 | 417 | 226 | 191 | -1 | -1 |
{- |
Description : logic for OMG's query/view/transformation language
Copyright : (c) Otto-von-Guericke University of Magdeburg
License : GPLv2 or higher, see LICENSE.txt
The "QVTR" folder contains the skeleton of
an instance of "Logic.Logic" for the query/view/transformation language defined by OMG and used in the context of UML and model driven engineering, see <https://en.wikipedia.org/wiki/QVT>.
-}
module QVTR where
| spechub/Hets | QVTR.hs | gpl-2.0 | 436 | 0 | 2 | 70 | 5 | 4 | 1 | 1 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Snippets
-- License : GPL-2
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
module Yi.Snippets where
import Control.Applicative
import Control.Arrow
import Control.Lens hiding (Action)
import Control.Monad
import Control.Monad.RWS hiding (mapM, mapM_, sequence, get, put)
import Data.Binary
import Data.Char (isSpace)
import Data.Default
#if __GLASGOW_HASKELL__ < 708
import Data.DeriveTH
#else
import GHC.Generics (Generic)
#endif
import Data.Foldable (find)
import Data.List hiding (find, elem, concat, concatMap)
import Data.Maybe (catMaybes)
import qualified Data.Text as T
import Data.Typeable
import Yi.Buffer
import Yi.Editor
import Yi.Keymap
import Yi.Keymap.Keys
import qualified Yi.Rope as R
import Yi.TextCompletion
import Yi.Types (YiVariable)
type SnippetCmd = RWST (Int, Int) [MarkInfo] () BufferM
data SnippetMark = SimpleMark !Int
| ValuedMark !Int R.YiString
| DependentMark !Int
data MarkInfo = SimpleMarkInfo { userIndex :: !Int
, startMark :: !Mark }
| ValuedMarkInfo { userIndex :: !Int
, startMark :: !Mark
, endMark :: !Mark }
| DependentMarkInfo { userIndex :: !Int
, startMark :: !Mark
, endMark :: !Mark }
deriving (Eq, Show)
#if __GLASGOW_HASKELL__ < 708
$(derive makeBinary ''MarkInfo)
#else
deriving instance Generic MarkInfo
instance Binary MarkInfo
#endif
newtype BufferMarks = BufferMarks { bufferMarks :: [MarkInfo] }
deriving (Eq, Show, Monoid, Typeable, Binary)
newtype DependentMarks = DependentMarks { marks :: [[MarkInfo]] }
deriving (Eq, Show, Monoid, Typeable, Binary)
instance Default BufferMarks where
def = BufferMarks []
instance Default DependentMarks where
def = DependentMarks []
instance YiVariable BufferMarks
instance YiVariable DependentMarks
instance Ord MarkInfo where
a `compare` b = userIndex a `compare` userIndex b
cursor :: Int -> SnippetMark
cursor = SimpleMark
cursorWith :: Int -> R.YiString -> SnippetMark
cursorWith = ValuedMark
dep :: Int -> SnippetMark
dep = DependentMark
isDependentMark :: MarkInfo -> Bool
isDependentMark (SimpleMarkInfo{}) = False
isDependentMark (ValuedMarkInfo{}) = False
isDependentMark (DependentMarkInfo{}) = True
bufferMarkers :: MarkInfo -> [Mark]
bufferMarkers (SimpleMarkInfo _ s) = [s]
bufferMarkers m = [startMark m, endMark m]
-- used to translate a datatype into a snippet cmd for
-- freely combining data with '&'
class MkSnippetCmd a b | a -> b where
mkSnippetCmd :: a -> SnippetCmd b
instance MkSnippetCmd String () where
mkSnippetCmd = text . R.fromString
instance MkSnippetCmd R.YiString () where
mkSnippetCmd = text
instance MkSnippetCmd T.Text () where
mkSnippetCmd = text . R.fromText
instance MkSnippetCmd (SnippetCmd a) a where
mkSnippetCmd = id
-- mkSnippetCmd for 'cursor...'-functions
instance MkSnippetCmd SnippetMark () where
mkSnippetCmd (SimpleMark i) = do
mk <- mkMark
tell [SimpleMarkInfo i mk]
mkSnippetCmd (ValuedMark i str) = do
start <- mkMark
lift $ insertN str
end <- mkMark
tell [ValuedMarkInfo i start end]
mkSnippetCmd (DependentMark i) = do
start <- mkMark
end <- mkMark
tell [DependentMarkInfo i start end]
-- create a mark at current position
mkMark :: MonadTrans t => t BufferM Mark
mkMark = lift $ do p <- pointB
newMarkB $ MarkValue p Backward
-- Indentation support has been temporarily removed
text :: R.YiString -> SnippetCmd ()
text txt = do
(_, indent) <- ask
indentSettings <- lift indentSettingsB
lift . foldl' (>>) (return ()) .
intersperse (newlineB >> indentToB indent) .
map (if expandTabs indentSettings
then insertN . expand indentSettings ""
else insertN) $ lines' txt
where
lines' txt' = case R.last txt' of
Just '\n' -> R.lines txt' <> [mempty]
_ -> R.lines txt
expand :: IndentSettings -> R.YiString -> R.YiString -> R.YiString
expand is str rst = case R.head rst of
Nothing -> R.reverse str
Just '\t' -> let t = R.replicateChar (tabSize is) ' ' <> str
in expand is t (R.drop 1 rst)
Just s -> expand is (s `R.cons` str) rst
-- unfortunatelly data converted to snippets are no monads, but '&' is
-- very similar to '>>' and '&>' is similar to '>>=', since
-- SnippetCmd's can be used monadically
infixr 5 &
(&) :: (MkSnippetCmd a any , MkSnippetCmd b c) => a -> b -> SnippetCmd c
str & rst = mkSnippetCmd str >> mkSnippetCmd rst
(&>) :: (MkSnippetCmd a b, MkSnippetCmd c d) => a -> (b -> c) -> SnippetCmd d
str &> rst = mkSnippetCmd str >>= mkSnippetCmd . rst
runSnippet :: Bool -> SnippetCmd a -> BufferM a
runSnippet deleteLast s = do
line <- lineOf =<< pointB
indent <- indentOfCurrentPosB
(a, markInfo) <- evalRWST s (line, indent) ()
unless (null markInfo) $ do
let newMarks = sort $ filter (not . isDependentMark) markInfo
let newDepMarks = filter (not . len1) $
groupBy belongTogether $
sort markInfo
getBufferDyn >>= putBufferDyn.(BufferMarks newMarks `mappend`)
unless (null newDepMarks) $
getBufferDyn >>= putBufferDyn.(DependentMarks newDepMarks `mappend`)
moveToNextBufferMark deleteLast
return a
where
len1 (_:[]) = True
len1 _ = False
belongTogether a b = userIndex a == userIndex b
updateUpdatedMarks :: [Update] -> BufferM ()
updateUpdatedMarks upds = findEditedMarks upds >>=
mapM_ updateDependents
findEditedMarks :: [Update] -> BufferM [MarkInfo]
findEditedMarks upds = liftM (nub . concat) (mapM findEditedMarks' upds)
where
findEditedMarks' :: Update -> BufferM [MarkInfo]
findEditedMarks' upd = do
let p = updatePoint upd
ms <- return . nub . concat . marks =<< getBufferDyn
ms' <- forM ms $ \m ->do
r <- adjMarkRegion m
return $ if (updateIsDelete upd && p `nearRegion` r)
|| p `inRegion` r
then Just m
else Nothing
return . catMaybes $ ms'
dependentSiblings :: MarkInfo -> [[MarkInfo]] -> [MarkInfo]
dependentSiblings mark deps =
case find (elem mark) deps of
Nothing -> []
Just lst -> filter (not . (mark==)) lst
updateDependents :: MarkInfo -> BufferM ()
updateDependents m = getBufferDyn >>= updateDependents' m . marks
updateDependents' :: MarkInfo -> [[MarkInfo]] -> BufferM ()
updateDependents' mark deps =
case dependentSiblings mark deps of
[] -> return ()
deps' -> do
txt <- markText mark
forM_ deps' $ \d -> do
dTxt <- markText d
when (txt /= dTxt) $ setMarkText txt d
markText :: MarkInfo -> BufferM R.YiString
markText m = markRegion m >>= readRegionB
setMarkText :: R.YiString -> MarkInfo -> BufferM ()
setMarkText txt (SimpleMarkInfo _ start) = do
p <- use $ markPointA start
c <- readAtB p
if isSpace c
then insertNAt txt p
else do
r <- regionOfPartNonEmptyAtB unitViWordOnLine Forward p
modifyRegionB (const txt) r
setMarkText txt mi = do
start <- use $ markPointA $ startMark mi
end <- use $ markPointA $ endMark mi
let r = mkRegion start end
modifyRegionB (const txt) r
when (start == end) $
markPointA (endMark mi) .= end + Point (R.length txt)
withSimpleRegion :: MarkInfo -> (Region -> BufferM Region) -> BufferM Region
withSimpleRegion (SimpleMarkInfo _ s) f = do
p <- use $ markPointA s
c <- readAtB p
if isSpace c
then return $ mkRegion p p -- return empty region
else f =<< regionOfPartNonEmptyAtB unitViWordOnLine Forward p
withSimpleRegion r _ = error $ "withSimpleRegion: " <> show r
markRegion :: MarkInfo -> BufferM Region
markRegion m@SimpleMarkInfo{} = withSimpleRegion m $ \r -> do
os <- findOverlappingMarksWith safeMarkRegion concat True r m
rOs <- mapM safeMarkRegion os
return . mkRegion (regionStart r) $ foldl' minEnd (regionEnd r) rOs
where
minEnd end r = if regionEnd r < end
then end
else min end $ regionStart r
markRegion m = liftM2 mkRegion
(use $ markPointA $ startMark m)
(use $ markPointA $ endMark m)
safeMarkRegion :: MarkInfo -> BufferM Region
safeMarkRegion m@(SimpleMarkInfo _ _) = withSimpleRegion m return
safeMarkRegion m = markRegion m
adjMarkRegion :: MarkInfo -> BufferM Region
adjMarkRegion s@(SimpleMarkInfo _ _) = markRegion s
adjMarkRegion m = do
s <- use $ markPointA $ startMark m
e <- use $ markPointA $ endMark m
c <- readAtB e
when (isWordChar c) $ do adjustEnding e
repairOverlappings e
e' <- use $ markPointA $ endMark m
s' <- adjustStart s e'
return $ mkRegion s' e'
where
adjustEnding end = do
r' <- regionOfPartNonEmptyAtB unitViWordOnLine Forward end
markPointA (endMark m) .= (regionEnd r')
adjustStart s e = do
txt <- readRegionB (mkRegion s e)
let sP = s + (Point . R.length $ R.takeWhile isSpace txt)
when (sP > s) $
markPointA (startMark m) .= sP
return sP
-- test if we generated overlappings and repair
repairOverlappings origEnd = do overlappings <- allOverlappingMarks True m
unless (null overlappings) $
markPointA (endMark m) .= origEnd
findOverlappingMarksWith :: (MarkInfo -> BufferM Region)
-> ([[MarkInfo]] -> [MarkInfo])
-> Bool -> Region -> MarkInfo -> BufferM [MarkInfo]
findOverlappingMarksWith fMarkRegion flattenMarks border r m =
let markFilter = filter (m /=) . flattenMarks . marks
regOverlap = liftM (regionsOverlap border r) . fMarkRegion
in liftM markFilter getBufferDyn >>= filterM regOverlap
findOverlappingMarks :: ([[MarkInfo]] -> [MarkInfo]) -> Bool -> Region ->
MarkInfo -> BufferM [MarkInfo]
findOverlappingMarks = findOverlappingMarksWith markRegion
regionsOverlappingMarks :: Bool -> Region -> MarkInfo -> BufferM [MarkInfo]
regionsOverlappingMarks = findOverlappingMarks concat
overlappingMarks :: Bool -> Bool -> MarkInfo -> BufferM [MarkInfo]
overlappingMarks border belongingTogether mark = do
r <- markRegion mark
findOverlappingMarks (if belongingTogether
then dependentSiblings mark
else concat)
border
r
mark
allOverlappingMarks :: Bool -> MarkInfo -> BufferM [MarkInfo]
allOverlappingMarks border = overlappingMarks border False
dependentOverlappingMarks :: Bool -> MarkInfo -> BufferM [MarkInfo]
dependentOverlappingMarks border = overlappingMarks border True
nextBufferMark :: Bool -> BufferM (Maybe MarkInfo)
nextBufferMark deleteLast = do
BufferMarks ms <- getBufferDyn
if null ms
then return Nothing
else do
let mks = if deleteLast then const $ tail ms else (tail ms <>)
putBufferDyn . BufferMarks . mks $ [head ms]
return . Just $ head ms
isDependentMarker :: (MonadState FBuffer m, Functor m) => Mark -> m Bool
isDependentMarker bMark = do
DependentMarks ms <- getBufferDyn
return . elem bMark . concatMap bufferMarkers . concat $ ms
safeDeleteMarkB :: Mark -> BufferM ()
safeDeleteMarkB m = do
b <- isDependentMarker m
unless b (deleteMarkB m)
moveToNextBufferMark :: Bool -> BufferM ()
moveToNextBufferMark deleteLast = nextBufferMark deleteLast >>= \case
Just p -> mv p
Nothing -> return ()
where
mv (SimpleMarkInfo _ m) = do
moveTo =<< use (markPointA m)
when deleteLast $ safeDeleteMarkB m
mv (ValuedMarkInfo _ s e) = do
sp <- use $ markPointA s
ep <- use $ markPointA e
deleteRegionB (mkRegion sp ep)
moveTo sp
when deleteLast $ do
safeDeleteMarkB s
safeDeleteMarkB e
mv r = error $ "moveToNextBufferMark.mv: " <> show r
-- Keymap support
newtype SupertabExt = Supertab (R.YiString -> Maybe (BufferM ()))
instance Monoid SupertabExt where
mempty = Supertab $ const Nothing
(Supertab f) `mappend` (Supertab g) =
Supertab $ \s -> f s `mplus` g s
superTab :: (MonadInteract m Action Event) => Bool -> SupertabExt -> m ()
superTab caseSensitive (Supertab expander) =
some (spec KTab ?>>! doSuperTab) >> deprioritize >>! resetComplete
where
doSuperTab = do canExpand <- withCurrentBuffer $ do
sol <- atSol
ws <- hasWhiteSpaceBefore
return $ sol || ws
if canExpand
then insertTab
else runCompleter
insertTab = withCurrentBuffer $ mapM_ insertB =<< tabB
runCompleter = do w <- withCurrentBuffer readPrevWordB
case expander w of
Just cmd -> withCurrentBuffer $ bkillWordB >> cmd
_ -> autoComplete
autoComplete = wordCompleteString' caseSensitive >>=
withCurrentBuffer . (bkillWordB >>) . (insertN . R.fromText)
-- | Convert snippet description list into a SuperTab extension
fromSnippets :: Bool -> [(R.YiString, SnippetCmd ())] -> SupertabExt
fromSnippets deleteLast snippets =
Supertab $ \str -> lookup str $ map (second $ runSnippet deleteLast) snippets
snippet :: MkSnippetCmd a b => a -> SnippetCmd b
snippet = mkSnippetCmd
| atsukotakahashi/wi | src/library/Yi/Snippets.hs | gpl-2.0 | 14,467 | 2 | 21 | 4,055 | 4,310 | 2,153 | 2,157 | -1 | -1 |
{- |
Properties of node-connected components.
-}
module Data.Grid.Node
(
-- * Everything here is node-connected
Noded (..)
-- * Basic node characteristics
, Bus (..)
-- * Static node-connected components
, ShuntAdmittance (..)
, Generator (..)
, Load (..)
) where
-- Local:
import Data.Grid.Types
import Data.Grid.Topology
-- Properties having to do with buses.
-- | A bus something which is connected to a topology node, and which has
-- a uniform voltage level.
class (Noded a) => Bus a where
busVoltage :: a -> CVoltage
busVoltage b = mkPolar (busVMagnitude b) (busVAngle b)
busVMagnitude :: a -> Voltage
busVMagnitude = magnitude . busVoltage
busVAngle :: a -> Angle
busVAngle = phase . busVoltage
-- | A Shunt admittance.
class (Noded a) => ShuntAdmittance a where
shuntAdmittance :: a -> Complex Admittance
shuntAdmittance a = shuntConductance a :+ shuntReactance a
shuntConductance :: a -> Conductance
shuntConductance = realPart . shuntAdmittance
shuntReactance :: a -> Reactance
shuntReactance = imagPart . shuntAdmittance
-- | A generator, information about generation at a node.
class (Noded a) => Generator a where
genPower :: a -> CPower
genMax :: a -> CPower
genMin :: a -> CPower
genVoltage :: a -> Voltage
-- | A Load, information about demand at a node.
class (Noded a) => Load a where
loadPower :: a -> CPower
| JohanPauli/Hunger | src/Data/Grid/Node.hs | gpl-3.0 | 1,377 | 0 | 9 | 269 | 320 | 182 | 138 | 30 | 0 |
module Language.C2ATS.FlatGlobalDecl
( FlatGlobalDecl (..)
, FlatG (..)
, MapFlatG (..)
, noposSueref
, realPath
) where
import Data.Map (Map)
import System.Process
import System.Exit
import Language.C
import Language.C.Analysis
data FlatGlobalDecl = FGObj IdentDecl
| FGTag TagDef
| FGType TypeDef
| FGRaw (String, NodeInfo)
instance CNode FlatGlobalDecl where
nodeInfo (FGObj d) = nodeInfo d
nodeInfo (FGTag d) = nodeInfo d
nodeInfo (FGType d) = nodeInfo d
nodeInfo (FGRaw (_, n)) = n
type FlatG = (SUERef, FlatGlobalDecl)
type MapFlatG = Map (Maybe FilePath) [FlatG]
noposSueref :: String -> SUERef
noposSueref s = NamedRef $ mkIdent nopos s $ Name (-1)
realPath :: FilePath -> IO FilePath
realPath file = do
(ExitSuccess,rfile,_) <- readProcessWithExitCode "realpath" [file] ""
return $ init rfile
| metasepi/c2ats | src/Language/C2ATS/FlatGlobalDecl.hs | gpl-3.0 | 944 | 0 | 9 | 261 | 302 | 167 | 135 | 28 | 1 |
module Wordify.Rules.Game(Game,
makeGame,
movesMade,
gameStatus,
board,
bag,
dictionary,
moveNumber,
player1,
player2,
optionalPlayers,
currentPlayer,
getPlayer,
playerNumber,
GameStatus(InProgress, Finished),
players,
passes,
numberOfPlayers,
history,
History(History)) where
import Wordify.Rules.Player
import Wordify.Rules.Board
import Wordify.Rules.Dictionary
import Wordify.Rules.LetterBag
import Wordify.Rules.ScrabbleError
import Data.Maybe
import Wordify.Rules.Game.Internal
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Safe
import Control.Monad
import Control.Applicative
import qualified Data.List.Safe as LS
{- |
Starts a new game.
A game has at least 2 players, and 2 optional players (player 3 and 4.) The players should be newly created,
as tiles from the letter bag will be distributed to each player.
Takes a letter bag and dictionary, which should be localised to the same language.
Yields a tuple with the first player and the initial game state. Returns a 'Left' if there are not enough
tiles in the letter bag to distribute to the players.
-}
makeGame :: (Player, Player, Maybe (Player, Maybe Player)) -> LetterBag -> Dictionary -> Either ScrabbleError Game
makeGame playing startBag dict =
do
(remainingBag, initialPlayers) <- initialisePlayers playing startBag
case initialPlayers of
firstPlayer : secondPlayer : optionals ->
return $ Game firstPlayer secondPlayer (toOptionalPlayers optionals) emptyBoard
remainingBag dict firstPlayer firstPlayerNumber firstMoveNumber initialPasses initialGameState initialHistory
_ -> Left $ MiscError "Unexpected error in logic. There were not at least two players. This should never happen."
where
initialHistory = History startBag Seq.empty
firstPlayerNumber = 1
firstMoveNumber = 1
initialPasses = 0
initialGameState = InProgress
toOptionalPlayers :: [Player] -> Maybe (Player, Maybe Player)
toOptionalPlayers (x : []) = Just (x, Nothing)
toOptionalPlayers (x : y : []) = Just (x, Just y)
toOptionalPlayers _ = Nothing
initialisePlayers :: (Player, Player, Maybe (Player, Maybe Player)) -> LetterBag -> Either ScrabbleError (LetterBag, [Player])
initialisePlayers (play1, play2, maybePlayers) initialBag =
let transitions = distributeFinite givePlayerTiles initialBag allPlayers
in case (join . lastMay) transitions of
Nothing -> Left $ NotEnoughLettersInStartingBag (bagSize initialBag)
Just (finalBag, _) -> Right (finalBag, map snd (catMaybes transitions))
where
allPlayers = [play1, play2] ++ optionalsToPlayers maybePlayers
givePlayerTiles currentBag giveTo =
(\(newTiles, newBag) -> (newBag, giveTiles giveTo newTiles)) <$> takeLetters currentBag 7
distributeFinite :: (b -> a -> Maybe (b, a)) -> b -> [a] -> [Maybe (b, a)]
distributeFinite takeUsing distributeFrom = go takeUsing (Just distributeFrom)
where
go :: (b -> a -> Maybe (b,a)) -> Maybe b -> [a] -> [Maybe (b, a)]
go _ _ [] = []
go giveBy Nothing (_ : receivers) = Nothing : go giveBy Nothing receivers
go giveBy (Just distributer) (receiver : receivers) =
case giveBy distributer receiver of
Nothing -> Nothing : go giveBy Nothing receivers
Just (currentDistributer, currentReceiver) ->
Just (currentDistributer, currentReceiver) : go giveBy (Just currentDistributer) receivers
optionalsToPlayers :: Maybe (Player, Maybe Player) -> [Player]
optionalsToPlayers optionals = case optionals of
Nothing -> []
Just (player3, Nothing) -> [player3]
Just (player3, Just player4) -> [player3, player4]
players :: Game -> [Player]
players game = [player1 game, player2 game] ++ optionalsToPlayers (optionalPlayers game)
getPlayer :: Game -> Int -> Maybe Player
getPlayer game playerNumber = (players game) LS.!! (playerNumber - 1)
numberOfPlayers :: Game -> Int
numberOfPlayers game = 2 + maybe 0 (\(_, maybePlayer4) -> if isJust maybePlayer4 then 2 else 1) (optionalPlayers game)
{- |
Returns a history of the moves made in the game.
-}
movesMade :: Game -> [Move]
movesMade game =
case history game of
History _ moves -> F.toList moves
| Happy0/haskellscrabble | src/Wordify/Rules/Game.hs | gpl-3.0 | 4,959 | 0 | 15 | 1,519 | 1,191 | 648 | 543 | 89 | 5 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.YouTube.Types
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.YouTube.Types
(
-- * Service Configuration
youTubeService
-- * OAuth Scopes
, youTubeUploadScope
, youTubeScope
, youTubeChannelMembershipsCreatorScope
, youTubePartnerScope
, youTubeForceSslScope
, youTubeReadOnlyScope
, youTubePartnerChannelAuditScope
-- * LiveChatMessageAuthorDetails
, LiveChatMessageAuthorDetails
, liveChatMessageAuthorDetails
, lcmadIsVerified
, lcmadIsChatOwner
, lcmadChannelId
, lcmadProFileImageURL
, lcmadIsChatModerator
, lcmadDisplayName
, lcmadIsChatSponsor
, lcmadChannelURL
-- * ContentRatingCceRating
, ContentRatingCceRating (..)
-- * ContentRatingChfilmRating
, ContentRatingChfilmRating (..)
-- * SubscriptionSubscriberSnippet
, SubscriptionSubscriberSnippet
, subscriptionSubscriberSnippet
, sssChannelId
, sssThumbnails
, sssTitle
, sssDescription
-- * ContentRatingMccaaRating
, ContentRatingMccaaRating (..)
-- * VideosListChart
, VideosListChart (..)
-- * IngestionInfo
, IngestionInfo
, ingestionInfo
, iiRtmpsIngestionAddress
, iiBackupIngestionAddress
, iiIngestionAddress
, iiRtmpsBackupIngestionAddress
, iiStreamName
-- * ChannelAuditDetails
, ChannelAuditDetails
, channelAuditDetails
, cadContentIdClaimsGoodStanding
, cadCopyrightStrikesGoodStanding
, cadCommUnityGuidelinesGoodStanding
-- * Thumbnail
, Thumbnail
, thumbnail
, tHeight
, tURL
, tWidth
-- * ContentRatingMpaaRating
, ContentRatingMpaaRating (..)
-- * CaptionSnippetTrackKind
, CaptionSnippetTrackKind (..)
-- * VideoSnippetLiveBroadcastContent
, VideoSnippetLiveBroadcastContent (..)
-- * ChannelConversionPingContext
, ChannelConversionPingContext (..)
-- * LiveChatTextMessageDetails
, LiveChatTextMessageDetails
, liveChatTextMessageDetails
, lctmdMessageText
-- * ActivityContentDetailsRecommendation
, ActivityContentDetailsRecommendation
, activityContentDetailsRecommendation
, acdrResourceId
, acdrSeedResourceId
, acdrReason
-- * LiveChatMessageRetractedDetails
, LiveChatMessageRetractedDetails
, liveChatMessageRetractedDetails
, lcmrdRetractedMessageId
-- * ContentRatingRcnofRating
, ContentRatingRcnofRating (..)
-- * PlayListListResponse
, PlayListListResponse
, playListListResponse
, pllrEtag
, pllrTokenPagination
, pllrNextPageToken
, pllrPageInfo
, pllrKind
, pllrItems
, pllrVisitorId
, pllrEventId
, pllrPrevPageToken
-- * VideoStatusPrivacyStatus
, VideoStatusPrivacyStatus (..)
-- * ChannelSectionSnippet
, ChannelSectionSnippet
, channelSectionSnippet
, cssStyle
, cssChannelId
, cssLocalized
, cssTitle
, cssType
, cssPosition
, cssDefaultLanguage
-- * ChannelStatus
, ChannelStatus
, channelStatus
, csIsLinked
, csLongUploadsStatus
, csPrivacyStatus
, csSelfDeclaredMadeForKids
, csMadeForKids
-- * LiveBroadcastStatusLifeCycleStatus
, LiveBroadcastStatusLifeCycleStatus (..)
-- * CaptionSnippetFailureReason
, CaptionSnippetFailureReason (..)
-- * ThirdPartyLinksDeleteType
, ThirdPartyLinksDeleteType (..)
-- * LiveChatUserBannedMessageDetailsBanType
, LiveChatUserBannedMessageDetailsBanType (..)
-- * VideoProcessingDetailsProcessingFailureReason
, VideoProcessingDetailsProcessingFailureReason (..)
-- * InvideoPositionType
, InvideoPositionType (..)
-- * LiveStreamSnippet
, LiveStreamSnippet
, liveStreamSnippet
, lssPublishedAt
, lssChannelId
, lssIsDefaultStream
, lssTitle
, lssDescription
-- * ContentRatingFskRating
, ContentRatingFskRating (..)
-- * SearchResult
, SearchResult
, searchResult
, srEtag
, srSnippet
, srKind
, srId
-- * ContentRatingMekuRating
, ContentRatingMekuRating (..)
-- * MembershipsLevel
, MembershipsLevel
, membershipsLevel
, mlEtag
, mlSnippet
, mlKind
, mlId
-- * TokenPagination
, TokenPagination
, tokenPagination
-- * ResourceId
, ResourceId
, resourceId
, riKind
, riChannelId
, riVideoId
, riPlayListId
-- * VideoContentDetailsDefinition
, VideoContentDetailsDefinition (..)
-- * ContentRatingEefilmRating
, ContentRatingEefilmRating (..)
-- * SearchListResponse
, SearchListResponse
, searchListResponse
, slrEtag
, slrTokenPagination
, slrNextPageToken
, slrRegionCode
, slrPageInfo
, slrKind
, slrItems
, slrVisitorId
, slrEventId
, slrPrevPageToken
-- * LiveBroadcastStatusPrivacyStatus
, LiveBroadcastStatusPrivacyStatus (..)
-- * PlayListStatus
, PlayListStatus
, playListStatus
, plsPrivacyStatus
-- * LiveChatMessageListResponse
, LiveChatMessageListResponse
, liveChatMessageListResponse
, lcmlrOfflineAt
, lcmlrEtag
, lcmlrTokenPagination
, lcmlrNextPageToken
, lcmlrPageInfo
, lcmlrKind
, lcmlrItems
, lcmlrVisitorId
, lcmlrPollingIntervalMillis
, lcmlrEventId
-- * ChannelListResponse
, ChannelListResponse
, channelListResponse
, clrEtag
, clrTokenPagination
, clrNextPageToken
, clrPageInfo
, clrKind
, clrItems
, clrVisitorId
, clrEventId
, clrPrevPageToken
-- * ContentRatingPefilmRating
, ContentRatingPefilmRating (..)
-- * ChannelProFileDetails
, ChannelProFileDetails
, channelProFileDetails
, cpfdChannelId
, cpfdProFileImageURL
, cpfdDisplayName
, cpfdChannelURL
-- * SuperChatEventListResponse
, SuperChatEventListResponse
, superChatEventListResponse
, scelrEtag
, scelrTokenPagination
, scelrNextPageToken
, scelrPageInfo
, scelrKind
, scelrItems
, scelrVisitorId
, scelrEventId
-- * VideoAbuseReportReasonListResponse
, VideoAbuseReportReasonListResponse
, videoAbuseReportReasonListResponse
, varrlrEtag
, varrlrKind
, varrlrItems
, varrlrVisitorId
, varrlrEventId
-- * CdnSettingsResolution
, CdnSettingsResolution (..)
-- * LiveChatUserBannedMessageDetails
, LiveChatUserBannedMessageDetails
, liveChatUserBannedMessageDetails
, lcubmdBanType
, lcubmdBannedUserDetails
, lcubmdBanDurationSeconds
-- * SearchResultSnippetLiveBroadcastContent
, SearchResultSnippetLiveBroadcastContent (..)
-- * LiveBroadcastContentDetails
, LiveBroadcastContentDetails
, liveBroadcastContentDetails
, lbcdEnableContentEncryption
, lbcdEnableLowLatency
, lbcdLatencyPreference
, lbcdEnableAutoStop
, lbcdClosedCaptionsType
, lbcdEnableEmbed
, lbcdStartWithSlate
, lbcdProjection
, lbcdMonitorStream
, lbcdStereoLayout
, lbcdBoundStreamId
, lbcdRecordFromStart
, lbcdMesh
, lbcdEnableClosedCaptions
, lbcdEnableAutoStart
, lbcdBoundStreamLastUpdateTimeMs
, lbcdEnableDvr
-- * ContentRatingAnatelRating
, ContentRatingAnatelRating (..)
-- * SearchListOrder
, SearchListOrder (..)
-- * ChannelSection
, ChannelSection
, channelSection
, csEtag
, csSnippet
, csKind
, csContentDetails
, csTargeting
, csId
, csLocalizations
-- * ContentRatingCccRating
, ContentRatingCccRating (..)
-- * ChannelContentDetailsRelatedPlayLists
, ChannelContentDetailsRelatedPlayLists
, channelContentDetailsRelatedPlayLists
, ccdrplFavorites
, ccdrplWatchHistory
, ccdrplWatchLater
, ccdrplUploads
, ccdrplLikes
-- * LiveStream
, LiveStream
, liveStream
, lsStatus
, lsEtag
, lsSnippet
, lsKind
, lsContentDetails
, lsId
, lsCdn
-- * ActivityContentDetailsFavorite
, ActivityContentDetailsFavorite
, activityContentDetailsFavorite
, acdfResourceId
-- * VideoContentDetails
, VideoContentDetails
, videoContentDetails
, vcdCountryRestriction
, vcdHasCustomThumbnail
, vcdDefinition
, vcdDimension
, vcdCaption
, vcdRegionRestriction
, vcdProjection
, vcdDuration
, vcdContentRating
, vcdLicensedContent
-- * CaptionSnippetAudioTrackType
, CaptionSnippetAudioTrackType (..)
-- * ImageSettings
, ImageSettings
, imageSettings
, isBannerMobileLowImageURL
, isBannerTabletExtraHdImageURL
, isSmallBrandedBannerImageImapScript
, isBannerTvHighImageURL
, isBannerMobileHdImageURL
, isBannerTvMediumImageURL
, isBannerTvImageURL
, isBannerTabletImageURL
, isBannerMobileImageURL
, isTrackingImageURL
, isBannerMobileMediumHdImageURL
, isLargeBrandedBannerImageURL
, isBannerExternalURL
, isBackgRoundImageURL
, isSmallBrandedBannerImageURL
, isBannerImageURL
, isWatchIconImageURL
, isBannerTvLowImageURL
, isBannerMobileExtraHdImageURL
, isLargeBrandedBannerImageImapScript
, isBannerTabletLowImageURL
, isBannerTabletHdImageURL
-- * MembersListMode
, MembersListMode (..)
-- * VideoTopicDetails
, VideoTopicDetails
, videoTopicDetails
, vtdTopicIds
, vtdRelevantTopicIds
, vtdTopicCategories
-- * ActivityContentDetailsComment
, ActivityContentDetailsComment
, activityContentDetailsComment
, acdcResourceId
-- * ChannelStatusPrivacyStatus
, ChannelStatusPrivacyStatus (..)
-- * ThirdPartyLink
, ThirdPartyLink
, thirdPartyLink
, tplStatus
, tplEtag
, tplSnippet
, tplKind
, tplLinkingToken
-- * LiveBroadcastStatus
, LiveBroadcastStatus
, liveBroadcastStatus
, lbsLiveBroadcastPriority
, lbsRecordingStatus
, lbsLifeCycleStatus
, lbsPrivacyStatus
, lbsSelfDeclaredMadeForKids
, lbsMadeForKids
-- * ActivityContentDetailsUpload
, ActivityContentDetailsUpload
, activityContentDetailsUpload
, acduVideoId
-- * ActivityContentDetailsPlayListItem
, ActivityContentDetailsPlayListItem
, activityContentDetailsPlayListItem
, acdpliResourceId
, acdpliPlayListId
, acdpliPlayListItemId
-- * SuperStickerMetadata
, SuperStickerMetadata
, superStickerMetadata
, ssmAltText
, ssmStickerId
, ssmAltTextLanguage
-- * ActivityContentDetailsSocial
, ActivityContentDetailsSocial
, activityContentDetailsSocial
, acdsResourceId
, acdsImageURL
, acdsAuthor
, acdsReferenceURL
, acdsType
-- * VideoSuggestionsEditorSuggestionsItem
, VideoSuggestionsEditorSuggestionsItem (..)
-- * ContentRatingCatvfrRating
, ContentRatingCatvfrRating (..)
-- * ContentRatingCnaRating
, ContentRatingCnaRating (..)
-- * LiveChatBan
, LiveChatBan
, liveChatBan
, lcbEtag
, lcbSnippet
, lcbKind
, lcbId
-- * ThirdPartyLinkStatusLinkStatus
, ThirdPartyLinkStatusLinkStatus (..)
-- * ContentRatingChvrsRating
, ContentRatingChvrsRating (..)
-- * ActivityContentDetailsSubscription
, ActivityContentDetailsSubscription
, activityContentDetailsSubscription
, aResourceId
-- * ActivityContentDetailsLike
, ActivityContentDetailsLike
, activityContentDetailsLike
, acdlResourceId
-- * PlayListContentDetails
, PlayListContentDetails
, playListContentDetails
, plcdItemCount
-- * ContentRatingIncaaRating
, ContentRatingIncaaRating (..)
-- * ContentRatingSmsaRating
, ContentRatingSmsaRating (..)
-- * LiveChatSuperChatDetails
, LiveChatSuperChatDetails
, liveChatSuperChatDetails
, lcscdUserComment
, lcscdAmountMicros
, lcscdAmountDisplayString
, lcscdCurrency
, lcscdTier
-- * PageInfo
, PageInfo
, pageInfo
, piResultsPerPage
, piTotalResults
-- * ContentRatingCbfcRating
, ContentRatingCbfcRating (..)
-- * VideoStatus
, VideoStatus
, videoStatus
, vsFailureReason
, vsPublicStatsViewable
, vsRejectionReason
, vsPublishAt
, vsUploadStatus
, vsPrivacyStatus
, vsEmbeddable
, vsSelfDeclaredMadeForKids
, vsLicense
, vsMadeForKids
-- * ContentRatingKfcbRating
, ContentRatingKfcbRating (..)
-- * TestItemTestItemSnippet
, TestItemTestItemSnippet
, testItemTestItemSnippet
-- * VideoFileDetails
, VideoFileDetails
, videoFileDetails
, vfdBitrateBps
, vfdCreationTime
, vfdDurationMs
, vfdFileSize
, vfdFileType
, vfdContainer
, vfdVideoStreams
, vfdAudioStreams
, vfdFileName
-- * ThumbnailSetResponse
, ThumbnailSetResponse
, thumbnailSetResponse
, tsrEtag
, tsrKind
, tsrItems
, tsrVisitorId
, tsrEventId
-- * LiveStreamConfigurationIssueSeverity
, LiveStreamConfigurationIssueSeverity (..)
-- * LiveBroadcastListResponse
, LiveBroadcastListResponse
, liveBroadcastListResponse
, lblrEtag
, lblrTokenPagination
, lblrNextPageToken
, lblrPageInfo
, lblrKind
, lblrItems
, lblrVisitorId
, lblrEventId
, lblrPrevPageToken
-- * ThirdPartyLinkSnippetType
, ThirdPartyLinkSnippetType (..)
-- * ChannelContentDetails
, ChannelContentDetails
, channelContentDetails
, ccdRelatedPlayLists
-- * SearchListVideoDefinition
, SearchListVideoDefinition (..)
-- * ActivityContentDetailsChannelItem
, ActivityContentDetailsChannelItem
, activityContentDetailsChannelItem
, acdciResourceId
-- * VideoListResponse
, VideoListResponse
, videoListResponse
, vlrEtag
, vlrTokenPagination
, vlrNextPageToken
, vlrPageInfo
, vlrKind
, vlrItems
, vlrVisitorId
, vlrEventId
, vlrPrevPageToken
-- * VideoMonetizationDetails
, VideoMonetizationDetails
, videoMonetizationDetails
, vmdAccess
-- * VideoAgeGatingVideoGameRating
, VideoAgeGatingVideoGameRating (..)
-- * ContentRatingLsfRating
, ContentRatingLsfRating (..)
-- * VideoSuggestionsTagSuggestion
, VideoSuggestionsTagSuggestion
, videoSuggestionsTagSuggestion
, vstsTag
, vstsCategoryRestricts
-- * ContentRatingMpaatRating
, ContentRatingMpaatRating (..)
-- * AbuseType
, AbuseType
, abuseType
, atId
-- * LiveChatModeratorListResponse
, LiveChatModeratorListResponse
, liveChatModeratorListResponse
, lEtag
, lTokenPagination
, lNextPageToken
, lPageInfo
, lKind
, lItems
, lVisitorId
, lEventId
, lPrevPageToken
-- * ActivitySnippet
, ActivitySnippet
, activitySnippet
, asPublishedAt
, asChannelTitle
, asChannelId
, asThumbnails
, asGroupId
, asTitle
, asType
, asDescription
-- * ChannelTopicDetails
, ChannelTopicDetails
, channelTopicDetails
, ctdTopicIds
, ctdTopicCategories
-- * LiveChatBanSnippetType
, LiveChatBanSnippetType (..)
-- * ContentRatingBfvcRating
, ContentRatingBfvcRating (..)
-- * VideoCategoryListResponse
, VideoCategoryListResponse
, videoCategoryListResponse
, vclrEtag
, vclrTokenPagination
, vclrNextPageToken
, vclrPageInfo
, vclrKind
, vclrItems
, vclrVisitorId
, vclrEventId
, vclrPrevPageToken
-- * VideoProcessingDetails
, VideoProcessingDetails
, videoProcessingDetails
, vpdProcessingFailureReason
, vpdProcessingIssuesAvailability
, vpdProcessingProgress
, vpdThumbnailsAvailability
, vpdTagSuggestionsAvailability
, vpdProcessingStatus
, vpdEditorSuggestionsAvailability
, vpdFileDetailsAvailability
-- * CommentThreadSnippet
, CommentThreadSnippet
, commentThreadSnippet
, ctsIsPublic
, ctsChannelId
, ctsCanReply
, ctsVideoId
, ctsTotalReplyCount
, ctsTopLevelComment
-- * SearchListVideoDuration
, SearchListVideoDuration (..)
-- * SearchListVideoCaption
, SearchListVideoCaption (..)
-- * VideosListMyRating
, VideosListMyRating (..)
-- * ChannelSectionListResponse
, ChannelSectionListResponse
, channelSectionListResponse
, cslrEtag
, cslrKind
, cslrItems
, cslrVisitorId
, cslrEventId
-- * CommentSnippetViewerRating
, CommentSnippetViewerRating (..)
-- * SuperChatEvent
, SuperChatEvent
, superChatEvent
, sceEtag
, sceSnippet
, sceKind
, sceId
-- * VideoAbuseReportReason
, VideoAbuseReportReason
, videoAbuseReportReason
, varrEtag
, varrSnippet
, varrKind
, varrId
-- * LiveStreamConfigurationIssue
, LiveStreamConfigurationIssue
, liveStreamConfigurationIssue
, lsciSeverity
, lsciReason
, lsciType
, lsciDescription
-- * LiveChatMessage
, LiveChatMessage
, liveChatMessage
, lcmEtag
, lcmSnippet
, lcmKind
, lcmAuthorDetails
, lcmId
-- * Channel
, Channel
, channel
, chaStatus
, chaEtag
, chaAuditDetails
, chaContentOwnerDetails
, chaSnippet
, chaKind
, chaTopicDetails
, chaContentDetails
, chaConversionPings
, chaBrandingSettings
, chaId
, chaStatistics
, chaLocalizations
-- * ChannelSectionTargeting
, ChannelSectionTargeting
, channelSectionTargeting
, cstRegions
, cstCountries
, cstLanguages
-- * ContentRatingFcbmRating
, ContentRatingFcbmRating (..)
-- * LiveStreamListResponse
, LiveStreamListResponse
, liveStreamListResponse
, lslrEtag
, lslrTokenPagination
, lslrNextPageToken
, lslrPageInfo
, lslrKind
, lslrItems
, lslrVisitorId
, lslrEventId
, lslrPrevPageToken
-- * TestItem
, TestItem
, testItem
, tiSnippet
, tiGaia
, tiFeaturedPart
, tiId
-- * LiveBroadcastsListBroadcastStatus
, LiveBroadcastsListBroadcastStatus (..)
-- * ContentRatingMoctwRating
, ContentRatingMoctwRating (..)
-- * ContentRatingBmukkRating
, ContentRatingBmukkRating (..)
-- * ChannelLocalizations
, ChannelLocalizations
, channelLocalizations
, clAddtional
-- * PlayListSnippet
, PlayListSnippet
, playListSnippet
, plsPublishedAt
, plsChannelTitle
, plsChannelId
, plsThumbnails
, plsLocalized
, plsTitle
, plsThumbnailVideoId
, plsDescription
, plsTags
, plsDefaultLanguage
-- * ContentRatingIcaaRating
, ContentRatingIcaaRating (..)
-- * VideoGetRatingResponse
, VideoGetRatingResponse
, videoGetRatingResponse
, vgrrEtag
, vgrrKind
, vgrrItems
, vgrrVisitorId
, vgrrEventId
-- * SuperChatEventSnippet
, SuperChatEventSnippet
, superChatEventSnippet
, scesDisplayString
, scesSupporterDetails
, scesCreatedAt
, scesSuperStickerMetadata
, scesAmountMicros
, scesMessageType
, scesChannelId
, scesCommentText
, scesCurrency
, scesIsSuperStickerEvent
-- * VideoAbuseReportReasonSnippet
, VideoAbuseReportReasonSnippet
, videoAbuseReportReasonSnippet
, varrsSecondaryReasons
, varrsLabel
-- * VideoStatusRejectionReason
, VideoStatusRejectionReason (..)
-- * Caption
, Caption
, caption
, capEtag
, capSnippet
, capKind
, capId
-- * VideoContentDetailsRegionRestriction
, VideoContentDetailsRegionRestriction
, videoContentDetailsRegionRestriction
, vcdrrAllowed
, vcdrrBlocked
-- * InvideoTiming
, InvideoTiming
, invideoTiming
, itDurationMs
, itOffSetMs
, itType
-- * PlayListLocalizations
, PlayListLocalizations
, playListLocalizations
, pllAddtional
-- * ContentRatingCzfilmRating
, ContentRatingCzfilmRating (..)
-- * VideoProcessingDetailsProcessingProgress
, VideoProcessingDetailsProcessingProgress
, videoProcessingDetailsProcessingProgress
, vpdppTimeLeftMs
, vpdppPartsTotal
, vpdppPartsProcessed
-- * ChannelSnippet
, ChannelSnippet
, channelSnippet
, csPublishedAt
, csCountry
, csThumbnails
, csLocalized
, csCustomURL
, csTitle
, csDescription
, csDefaultLanguage
-- * ThumbnailDetails
, ThumbnailDetails
, thumbnailDetails
, tdMedium
, tdMaxres
, tdDefault
, tdStandard
, tdHigh
-- * MonitorStreamInfo
, MonitorStreamInfo
, monitorStreamInfo
, msiBroadcastStreamDelayMs
, msiEmbedHTML
, msiEnableMonitorStream
-- * LiveChatMessageSnippet
, LiveChatMessageSnippet
, liveChatMessageSnippet
, lcmsMessageDeletedDetails
, lcmsSuperStickerDetails
, lcmsLiveChatId
, lcmsPublishedAt
, lcmsUserBannedDetails
, lcmsTextMessageDetails
, lcmsMessageRetractedDetails
, lcmsSuperChatDetails
, lcmsType
, lcmsAuthorChannelId
, lcmsFanFundingEventDetails
, lcmsHasDisplayContent
, lcmsDisplayMessage
-- * ContentRatingRussiaRating
, ContentRatingRussiaRating (..)
-- * ContentRatingCicfRating
, ContentRatingCicfRating (..)
-- * ContentRatingFmocRating
, ContentRatingFmocRating (..)
-- * LiveBroadcastsTransitionBroadcastStatus
, LiveBroadcastsTransitionBroadcastStatus (..)
-- * I18nRegion
, I18nRegion
, i18nRegion
, irEtag
, irSnippet
, irKind
, irId
-- * ChannelStatistics
, ChannelStatistics
, channelStatistics
, csCommentCount
, csSubscriberCount
, csVideoCount
, csHiddenSubscriberCount
, csViewCount
-- * LiveChatFanFundingEventDetails
, LiveChatFanFundingEventDetails
, liveChatFanFundingEventDetails
, lcffedUserComment
, lcffedAmountMicros
, lcffedAmountDisplayString
, lcffedCurrency
-- * ContentRatingNbcRating
, ContentRatingNbcRating (..)
-- * LiveBroadcastStatusLiveBroadcastPriority
, LiveBroadcastStatusLiveBroadcastPriority (..)
-- * LiveStreamHealthStatusStatus
, LiveStreamHealthStatusStatus (..)
-- * ActivityContentDetails
, ActivityContentDetails
, activityContentDetails
, acdPromotedItem
, acdChannelItem
, acdBulletin
, acdFavorite
, acdUpload
, acdComment
, acdSocial
, acdSubscription
, acdPlayListItem
, acdLike
, acdRecommendation
-- * LiveBroadcastContentDetailsLatencyPreference
, LiveBroadcastContentDetailsLatencyPreference (..)
-- * VideoCategory
, VideoCategory
, videoCategory
, vcEtag
, vcSnippet
, vcKind
, vcId
-- * VideoRatingRating
, VideoRatingRating (..)
-- * VideoSuggestionsProcessingWarningsItem
, VideoSuggestionsProcessingWarningsItem (..)
-- * VideoLocalizations
, VideoLocalizations
, videoLocalizations
, vlAddtional
-- * ChannelSectionContentDetails
, ChannelSectionContentDetails
, channelSectionContentDetails
, cscdChannels
, cscdPlayLists
-- * InvideoPositionCornerPosition
, InvideoPositionCornerPosition (..)
-- * Video
, Video
, video
, vStatus
, vEtag
, vProjectDetails
, vRecordingDetails
, vSnippet
, vKind
, vTopicDetails
, vContentDetails
, vAgeGating
, vFileDetails
, vSuggestions
, vId
, vStatistics
, vLocalizations
, vLiveStreamingDetails
, vPlayer
, vProcessingDetails
, vMonetizationDetails
-- * LiveBroadcast
, LiveBroadcast
, liveBroadcast
, lbStatus
, lbEtag
, lbSnippet
, lbKind
, lbContentDetails
, lbId
, lbStatistics
-- * ChannelStatusLongUploadsStatus
, ChannelStatusLongUploadsStatus (..)
-- * LiveChatModerator
, LiveChatModerator
, liveChatModerator
, livEtag
, livSnippet
, livKind
, livId
-- * LiveStreamContentDetails
, LiveStreamContentDetails
, liveStreamContentDetails
, lscdClosedCaptionsIngestionURL
, lscdIsReusable
-- * ThirdPartyLinkStatus
, ThirdPartyLinkStatus
, thirdPartyLinkStatus
, tplsLinkStatus
-- * LiveChatModeratorSnippet
, LiveChatModeratorSnippet
, liveChatModeratorSnippet
, lLiveChatId
, lModeratorDetails
-- * ContentRatingCscfRating
, ContentRatingCscfRating (..)
-- * ThirdPartyLinksListType
, ThirdPartyLinksListType (..)
-- * LiveBroadcastStatusRecordingStatus
, LiveBroadcastStatusRecordingStatus (..)
-- * VideoFileDetailsVideoStreamRotation
, VideoFileDetailsVideoStreamRotation (..)
-- * PropertyValue
, PropertyValue
, propertyValue
, pvProperty
, pvValue
-- * ContentRatingRtcRating
, ContentRatingRtcRating (..)
-- * LevelDetails
, LevelDetails
, levelDetails
, ldDisplayName
-- * VideoSnippet
, VideoSnippet
, videoSnippet
, vsDefaultAudioLanguage
, vsPublishedAt
, vsChannelTitle
, vsChannelId
, vsThumbnails
, vsLocalized
, vsCategoryId
, vsTitle
, vsLiveBroadcastContent
, vsDescription
, vsTags
, vsDefaultLanguage
-- * CommentThreadsListModerationStatus
, CommentThreadsListModerationStatus (..)
-- * LiveBroadcastSnippet
, LiveBroadcastSnippet
, liveBroadcastSnippet
, lbsActualEndTime
, lbsLiveChatId
, lbsPublishedAt
, lbsScheduledEndTime
, lbsChannelId
, lbsScheduledStartTime
, lbsThumbnails
, lbsTitle
, lbsActualStartTime
, lbsIsDefaultBroadcast
, lbsDescription
-- * ContentRatingSmaisRating
, ContentRatingSmaisRating (..)
-- * AccessPolicy
, AccessPolicy
, accessPolicy
, apException
, apAllowed
-- * LiveChatMessageDeletedDetails
, LiveChatMessageDeletedDetails
, liveChatMessageDeletedDetails
, lcmddDeletedMessageId
-- * RelatedEntity
, RelatedEntity
, relatedEntity
, reEntity
-- * ContentRatingYtRating
, ContentRatingYtRating (..)
-- * CommentThreadListResponse
, CommentThreadListResponse
, commentThreadListResponse
, ctlrEtag
, ctlrTokenPagination
, ctlrNextPageToken
, ctlrPageInfo
, ctlrKind
, ctlrItems
, ctlrVisitorId
, ctlrEventId
-- * MembershipsDurationAtLevel
, MembershipsDurationAtLevel
, membershipsDurationAtLevel
, mdalMemberTotalDurationMonths
, mdalMemberSince
, mdalLevel
-- * WatchSettings
, WatchSettings
, watchSettings
, wsFeaturedPlayListId
, wsBackgRoundColor
, wsTextColor
-- * CdnSettings
, CdnSettings
, cdnSettings
, csIngestionInfo
, csFrameRate
, csFormat
, csResolution
, csIngestionType
-- * VideoContentDetailsCaption
, VideoContentDetailsCaption (..)
-- * LiveBroadcastStatistics
, LiveBroadcastStatistics
, liveBroadcastStatistics
, lbsTotalChatCount
-- * SubscriptionsListOrder
, SubscriptionsListOrder (..)
-- * VideoCategorySnippet
, VideoCategorySnippet
, videoCategorySnippet
, vcsAssignable
, vcsChannelId
, vcsTitle
-- * I18nLanguage
, I18nLanguage
, i18nLanguage
, ilEtag
, ilSnippet
, ilKind
, ilId
-- * ContentRatingBbfcRating
, ContentRatingBbfcRating (..)
-- * VideoStatistics
, VideoStatistics
, videoStatistics
, vsLikeCount
, vsCommentCount
, vsFavoriteCount
, vsDislikeCount
, vsViewCount
-- * ActivityListResponse
, ActivityListResponse
, activityListResponse
, alrEtag
, alrTokenPagination
, alrNextPageToken
, alrPageInfo
, alrKind
, alrItems
, alrVisitorId
, alrEventId
, alrPrevPageToken
-- * ContentRatingTvpgRating
, ContentRatingTvpgRating (..)
-- * CommentsListTextFormat
, CommentsListTextFormat (..)
-- * VideosRateRating
, VideosRateRating (..)
-- * ActivityContentDetailsBulletin
, ActivityContentDetailsBulletin
, activityContentDetailsBulletin
, acdbResourceId
-- * LiveBroadcastContentDetailsProjection
, LiveBroadcastContentDetailsProjection (..)
-- * CaptionSnippetStatus
, CaptionSnippetStatus (..)
-- * VideoAbuseReport
, VideoAbuseReport
, videoAbuseReport
, varSecondaryReasonId
, varReasonId
, varVideoId
, varLanguage
, varComments
-- * ContentRatingSkfilmRating
, ContentRatingSkfilmRating (..)
-- * ChannelSectionSnippetType
, ChannelSectionSnippetType (..)
-- * LiveBroadcastsListBroadcastType
, LiveBroadcastsListBroadcastType (..)
-- * ContentRatingFpbRatingReasonsItem
, ContentRatingFpbRatingReasonsItem (..)
-- * VideoProcessingDetailsProcessingStatus
, VideoProcessingDetailsProcessingStatus (..)
-- * ActivityContentDetailsPromotedItemCtaType
, ActivityContentDetailsPromotedItemCtaType (..)
-- * VideoFileDetailsAudioStream
, VideoFileDetailsAudioStream
, videoFileDetailsAudioStream
, vfdasBitrateBps
, vfdasVendor
, vfdasCodec
, vfdasChannelCount
-- * I18nRegionListResponse
, I18nRegionListResponse
, i18nRegionListResponse
, irlrEtag
, irlrKind
, irlrItems
, irlrVisitorId
, irlrEventId
-- * SearchListChannelType
, SearchListChannelType (..)
-- * ContentRatingKmrbRating
, ContentRatingKmrbRating (..)
-- * ContentRatingOflcRating
, ContentRatingOflcRating (..)
-- * MembershipsDuration
, MembershipsDuration
, membershipsDuration
, mdMemberTotalDurationMonths
, mdMemberSince
-- * ContentRatingCNCRating
, ContentRatingCNCRating (..)
-- * CaptionListResponse
, CaptionListResponse
, captionListResponse
, cEtag
, cKind
, cItems
, cVisitorId
, cEventId
-- * PlayListItemStatus
, PlayListItemStatus
, playListItemStatus
, plisPrivacyStatus
-- * InvideoPosition
, InvideoPosition
, invideoPosition
, ipCornerPosition
, ipType
-- * ContentRatingEcbmctRating
, ContentRatingEcbmctRating (..)
-- * VideoContentDetailsProjection
, VideoContentDetailsProjection (..)
-- * ContentRatingGrfilmRating
, ContentRatingGrfilmRating (..)
-- * LiveChatSuperStickerDetails
, LiveChatSuperStickerDetails
, liveChatSuperStickerDetails
, lcssdSuperStickerMetadata
, lcssdAmountMicros
, lcssdAmountDisplayString
, lcssdCurrency
, lcssdTier
-- * LiveBroadcastContentDetailsStereoLayout
, LiveBroadcastContentDetailsStereoLayout (..)
-- * CommentThreadsListOrder
, CommentThreadsListOrder (..)
-- * LiveStreamHealthStatus
, LiveStreamHealthStatus
, liveStreamHealthStatus
, lshsStatus
, lshsConfigurationIssues
, lshsLastUpdateTimeSeconds
-- * Xgafv
, Xgafv (..)
-- * ChannelSectionLocalizations
, ChannelSectionLocalizations
, channelSectionLocalizations
, cslAddtional
-- * ContentRatingIlfilmRating
, ContentRatingIlfilmRating (..)
-- * SubscriptionListResponse
, SubscriptionListResponse
, subscriptionListResponse
, sEtag
, sTokenPagination
, sNextPageToken
, sPageInfo
, sKind
, sItems
, sVisitorId
, sEventId
, sPrevPageToken
-- * ContentRatingNbcplRating
, ContentRatingNbcplRating (..)
-- * VideoStatusUploadStatus
, VideoStatusUploadStatus (..)
-- * VideoLocalization
, VideoLocalization
, videoLocalization
, vlTitle
, vlDescription
-- * ContentRatingRteRating
, ContentRatingRteRating (..)
-- * CommentListResponse
, CommentListResponse
, commentListResponse
, comEtag
, comTokenPagination
, comNextPageToken
, comPageInfo
, comKind
, comItems
, comVisitorId
, comEventId
-- * VideoPlayer
, VideoPlayer
, videoPlayer
, vpEmbedHeight
, vpEmbedWidth
, vpEmbedHTML
-- * CommentThreadsListTextFormat
, CommentThreadsListTextFormat (..)
-- * LocalizedString
, LocalizedString
, localizedString
, lsValue
, lsLanguage
-- * ContentRatingIfcoRating
, ContentRatingIfcoRating (..)
-- * MembershipsLevelSnippet
, MembershipsLevelSnippet
, membershipsLevelSnippet
, mlsLevelDetails
, mlsCreatorChannelId
-- * PlayListItemListResponse
, PlayListItemListResponse
, playListItemListResponse
, plilrEtag
, plilrTokenPagination
, plilrNextPageToken
, plilrPageInfo
, plilrKind
, plilrItems
, plilrVisitorId
, plilrEventId
, plilrPrevPageToken
-- * CommentsSetModerationStatusModerationStatus
, CommentsSetModerationStatusModerationStatus (..)
-- * SearchResultSnippet
, SearchResultSnippet
, searchResultSnippet
, srsPublishedAt
, srsChannelTitle
, srsChannelId
, srsThumbnails
, srsTitle
, srsLiveBroadcastContent
, srsDescription
-- * ActivityContentDetailsSocialType
, ActivityContentDetailsSocialType (..)
-- * ContentRatingMedietilsynetRating
, ContentRatingMedietilsynetRating (..)
-- * PlayListItemStatusPrivacyStatus
, PlayListItemStatusPrivacyStatus (..)
-- * SubscriptionContentDetailsActivityType
, SubscriptionContentDetailsActivityType (..)
-- * ContentRatingFpbRating
, ContentRatingFpbRating (..)
-- * LiveBroadcastContentDetailsClosedCaptionsType
, LiveBroadcastContentDetailsClosedCaptionsType (..)
-- * SearchListVideoDimension
, SearchListVideoDimension (..)
-- * ContentRatingNkclvRating
, ContentRatingNkclvRating (..)
-- * Activity
, Activity
, activity
, aEtag
, aSnippet
, aKind
, aContentDetails
, aId
-- * InvideoBranding
, InvideoBranding
, invideoBranding
, ibImageURL
, ibTargetChannelId
, ibTiming
, ibImageBytes
, ibPosition
-- * ChannelBannerResource
, ChannelBannerResource
, channelBannerResource
, cbrEtag
, cbrKind
, cbrURL
-- * SearchListVideoType
, SearchListVideoType (..)
-- * I18nLanguageListResponse
, I18nLanguageListResponse
, i18nLanguageListResponse
, illrEtag
, illrKind
, illrItems
, illrVisitorId
, illrEventId
-- * PlayListPlayer
, PlayListPlayer
, playListPlayer
, plpEmbedHTML
-- * CommentSnippetAuthorChannelId
, CommentSnippetAuthorChannelId
, commentSnippetAuthorChannelId
, csaciValue
-- * ContentRatingMibacRating
, ContentRatingMibacRating (..)
-- * ContentRatingResorteviolenciaRating
, ContentRatingResorteviolenciaRating (..)
-- * ContentRatingEgfilmRating
, ContentRatingEgfilmRating (..)
-- * ChannelBrandingSettings
, ChannelBrandingSettings
, channelBrandingSettings
, cbsImage
, cbsHints
, cbsChannel
, cbsWatch
-- * CommentThread
, CommentThread
, commentThread
, ctEtag
, ctSnippet
, ctKind
, ctReplies
, ctId
-- * PlayListLocalization
, PlayListLocalization
, playListLocalization
, pllTitle
, pllDescription
-- * ChannelToStoreLinkDetails
, ChannelToStoreLinkDetails
, channelToStoreLinkDetails
, ctsldStoreURL
, ctsldStoreName
-- * ContentRatingMccypRating
, ContentRatingMccypRating (..)
-- * MemberSnippet
, MemberSnippet
, memberSnippet
, msMemberDetails
, msCreatorChannelId
, msMembershipsDetails
-- * LiveChatBanSnippet
, LiveChatBanSnippet
, liveChatBanSnippet
, lcbsLiveChatId
, lcbsBannedUserDetails
, lcbsBanDurationSeconds
, lcbsType
-- * PlayListStatusPrivacyStatus
, PlayListStatusPrivacyStatus (..)
-- * SubscriptionContentDetails
, SubscriptionContentDetails
, subscriptionContentDetails
, scdActivityType
, scdTotalItemCount
, scdNewItemCount
-- * ContentRatingCsaRating
, ContentRatingCsaRating (..)
-- * ChannelConversionPings
, ChannelConversionPings
, channelConversionPings
, ccpPings
-- * LocalizedProperty
, LocalizedProperty
, localizedProperty
, lpDefault
, lpLocalized
, lpDefaultLanguage
-- * ChannelSectionSnippetStyle
, ChannelSectionSnippetStyle (..)
-- * ThirdPartyLinkSnippet
, ThirdPartyLinkSnippet
, thirdPartyLinkSnippet
, tplsChannelToStoreLink
, tplsType
-- * Member
, Member
, member
, mEtag
, mSnippet
, mKind
-- * ChannelLocalization
, ChannelLocalization
, channelLocalization
, clTitle
, clDescription
-- * PlayListItemContentDetails
, PlayListItemContentDetails
, playListItemContentDetails
, plicdStartAt
, plicdNote
, plicdVideoPublishedAt
, plicdVideoId
, plicdEndAt
-- * ContentRatingEirinRating
, ContentRatingEirinRating (..)
-- * VideoSuggestionsProcessingHintsItem
, VideoSuggestionsProcessingHintsItem (..)
-- * VideoAgeGating
, VideoAgeGating
, videoAgeGating
, vagAlcoholContent
, vagRestricted
, vagVideoGameRating
-- * ContentRatingNfrcRating
, ContentRatingNfrcRating (..)
-- * ActivitySnippetType
, ActivitySnippetType (..)
-- * ContentRatingMocRating
, ContentRatingMocRating (..)
-- * SearchListVideoEmbeddable
, SearchListVideoEmbeddable (..)
-- * ContentRatingMcstRating
, ContentRatingMcstRating (..)
-- * LanguageTag
, LanguageTag
, languageTag
, ltValue
-- * SearchListEventType
, SearchListEventType (..)
-- * VideoFileDetailsVideoStream
, VideoFileDetailsVideoStream
, videoFileDetailsVideoStream
, vfdvsHeightPixels
, vfdvsBitrateBps
, vfdvsVendor
, vfdvsRotation
, vfdvsFrameRateFps
, vfdvsCodec
, vfdvsAspectRatio
, vfdvsWidthPixels
-- * ChannelConversionPing
, ChannelConversionPing
, channelConversionPing
, ccpContext
, ccpConversionURL
-- * PlayListItem
, PlayListItem
, playListItem
, pliStatus
, pliEtag
, pliSnippet
, pliKind
, pliContentDetails
, pliId
-- * ContentRatingMenaMpaaRating
, ContentRatingMenaMpaaRating (..)
-- * ActivityContentDetailsRecommendationReason
, ActivityContentDetailsRecommendationReason (..)
-- * ContentRatingKijkwijzerRating
, ContentRatingKijkwijzerRating (..)
-- * VideoSuggestionsProcessingErrorsItem
, VideoSuggestionsProcessingErrorsItem (..)
-- * VideoFileDetailsFileType
, VideoFileDetailsFileType (..)
-- * MembershipsDetails
, MembershipsDetails
, membershipsDetails
, mdHighestAccessibleLevel
, mdMembershipsDurationAtLevels
, mdMembershipsDuration
, mdAccessibleLevels
, mdHighestAccessibleLevelDisplayName
-- * ContentRatingMtrcbRating
, ContentRatingMtrcbRating (..)
-- * ContentRatingFcoRating
, ContentRatingFcoRating (..)
-- * CaptionSnippet
, CaptionSnippet
, captionSnippet
, csFailureReason
, csStatus
, csLastUpdated
, csTrackKind
, csIsDraft
, csIsCC
, csVideoId
, csName
, csIsLarge
, csLanguage
, csIsAutoSynced
, csIsEasyReader
, csAudioTrackType
-- * CdnSettingsFrameRate
, CdnSettingsFrameRate (..)
-- * Comment
, Comment
, comment
, ccEtag
, ccSnippet
, ccKind
, ccId
-- * I18nRegionSnippet
, I18nRegionSnippet
, i18nRegionSnippet
, irsName
, irsGl
-- * LiveStreamConfigurationIssueType
, LiveStreamConfigurationIssueType (..)
-- * SearchListSafeSearch
, SearchListSafeSearch (..)
-- * Subscription
, Subscription
, subscription
, subEtag
, subSubscriberSnippet
, subSnippet
, subKind
, subContentDetails
, subId
-- * SearchListVideoSyndicated
, SearchListVideoSyndicated (..)
-- * ContentRatingDjctqRatingReasonsItem
, ContentRatingDjctqRatingReasonsItem (..)
-- * Entity
, Entity
, entity
, eTypeId
, eURL
, eId
-- * AbuseReport
, AbuseReport
, abuseReport
, arSubject
, arRelatedEntities
, arAbuseTypes
, arDescription
-- * VideoRecordingDetails
, VideoRecordingDetails
, videoRecordingDetails
, vrdLocation
, vrdLocationDescription
, vrdRecordingDate
-- * CdnSettingsIngestionType
, CdnSettingsIngestionType (..)
-- * InvideoTimingType
, InvideoTimingType (..)
-- * VideoRating
, VideoRating
, videoRating
, vRating
, vVideoId
-- * ContentRatingAgcomRating
, ContentRatingAgcomRating (..)
-- * CommentSnippet
, CommentSnippet
, commentSnippet
, cViewerRating
, cPublishedAt
, cAuthorChannelURL
, cModerationStatus
, cLikeCount
, cChannelId
, cTextOriginal
, cVideoId
, cTextDisplay
, cAuthorProFileImageURL
, cAuthorDisplayName
, cUpdatedAt
, cAuthorChannelId
, cCanRate
, cParentId
-- * LiveStreamStatus
, LiveStreamStatus
, liveStreamStatus
, lssStreamStatus
, lssHealthStatus
-- * VideoSuggestions
, VideoSuggestions
, videoSuggestions
, vsProcessingErrors
, vsProcessingHints
, vsEditorSuggestions
, vsProcessingWarnings
, vsTagSuggestions
-- * CommentSnippetModerationStatus
, CommentSnippetModerationStatus (..)
-- * MembershipsLevelListResponse
, MembershipsLevelListResponse
, membershipsLevelListResponse
, mllrEtag
, mllrKind
, mllrItems
, mllrVisitorId
, mllrEventId
-- * PlayListItemSnippet
, PlayListItemSnippet
, playListItemSnippet
, plisResourceId
, plisPublishedAt
, plisChannelTitle
, plisChannelId
, plisThumbnails
, plisTitle
, plisPlayListId
, plisVideoOwnerChannelTitle
, plisVideoOwnerChannelId
, plisDescription
, plisPosition
-- * VideoProjectDetails
, VideoProjectDetails
, videoProjectDetails
-- * SearchListVideoLicense
, SearchListVideoLicense (..)
-- * ContentRating
, ContentRating
, contentRating
, crFpbRatingReasons
, crPefilmRating
, crCccRating
, crAnatelRating
, crMpaaRating
, crCceRating
, crMccaaRating
, crChfilmRating
, crIcaaRating
, crFcbmRating
, crBmukkRating
, crMoctwRating
, crNfvcbRating
, crDjctqRatingReasons
, crAgcomRating
, crCnaRating
, crCatvfrRating
, crCbfcRating
, crKfcbRating
, crSmsaRating
, crChvrsRating
, crIncaaRating
, crMcstRating
, crNfrcRating
, crCsaRating
, crMocRating
, crEirinRating
, crFskRating
, crEefilmRating
, crRcnofRating
, crMekuRating
, crIlfilmRating
, crIfcoRating
, crNbcplRating
, crGrfilmRating
, crRteRating
, crAcbRating
, crCatvRating
, crMdaRating
, crNmcRating
, crDjctqRating
, crSmaisRating
, crCscfRating
, crTvpgRating
, crRtcRating
, crYtRating
, crBbfcRating
, crMenaMpaaRating
, crKijkwijzerRating
, crMtrcbRating
, crFcoRating
, crCicfRating
, crCzfilmRating
, crNbcRating
, crFmocRating
, crRussiaRating
, crEgfilmRating
, crResorteviolenciaRating
, crMibacRating
, crMedietilsynetRating
, crMccypRating
, crNkclvRating
, crFpbRating
, crLsfRating
, crBfvcRating
, crMpaatRating
, crEcbmctRating
, crCNCRating
, crSkfilmRating
, crOflcRating
, crKmrbRating
-- * PlayList
, PlayList
, playList
, plStatus
, plEtag
, plSnippet
, plKind
, plContentDetails
, plId
, plLocalizations
, plPlayer
-- * LiveChatMessageSnippetType
, LiveChatMessageSnippetType (..)
-- * LiveStreamStatusStreamStatus
, LiveStreamStatusStreamStatus (..)
-- * VideoStatusLicense
, VideoStatusLicense (..)
-- * ContentRatingNfvcbRating
, ContentRatingNfvcbRating (..)
-- * ChannelSettings
, ChannelSettings
, channelSettings
, cShowRelatedChannels
, cDefaultTab
, cFeaturedChannelsTitle
, cCountry
, cProFileColor
, cModerateComments
, cKeywords
, cUnsubscribedTrailer
, cTrackingAnalyticsAccountId
, cFeaturedChannelsURLs
, cShowBrowseView
, cTitle
, cDescription
, cDefaultLanguage
-- * SubscriptionSnippet
, SubscriptionSnippet
, subscriptionSnippet
, ssResourceId
, ssPublishedAt
, ssChannelTitle
, ssChannelId
, ssThumbnails
, ssTitle
, ssDescription
-- * VideoLiveStreamingDetails
, VideoLiveStreamingDetails
, videoLiveStreamingDetails
, vlsdActualEndTime
, vlsdConcurrentViewers
, vlsdScheduledEndTime
, vlsdScheduledStartTime
, vlsdActualStartTime
, vlsdActiveLiveChatId
-- * ContentRatingMdaRating
, ContentRatingMdaRating (..)
-- * ContentRatingNmcRating
, ContentRatingNmcRating (..)
-- * ActivityContentDetailsPromotedItem
, ActivityContentDetailsPromotedItem
, activityContentDetailsPromotedItem
, acdpiDestinationURL
, acdpiClickTrackingURL
, acdpiForecastingURL
, acdpiDescriptionText
, acdpiCtaType
, acdpiVideoId
, acdpiAdTag
, acdpiCreativeViewURL
, acdpiImpressionURL
, acdpiCustomCtaButtonText
-- * ContentRatingAcbRating
, ContentRatingAcbRating (..)
-- * ContentRatingDjctqRating
, ContentRatingDjctqRating (..)
-- * GeoPoint
, GeoPoint
, geoPoint
, gpLatitude
, gpAltitude
, gpLongitude
-- * CommentThreadReplies
, CommentThreadReplies
, commentThreadReplies
, ctrComments
-- * ChannelSectionLocalization
, ChannelSectionLocalization
, channelSectionLocalization
, cslTitle
-- * VideoAbuseReportSecondaryReason
, VideoAbuseReportSecondaryReason
, videoAbuseReportSecondaryReason
, varsrId
, varsrLabel
-- * VideoStatusFailureReason
, VideoStatusFailureReason (..)
-- * ChannelContentOwnerDetails
, ChannelContentOwnerDetails
, channelContentOwnerDetails
, ccodTimeLinked
, ccodContentOwner
-- * I18nLanguageSnippet
, I18nLanguageSnippet
, i18nLanguageSnippet
, ilsHl
, ilsName
-- * ContentRatingCatvRating
, ContentRatingCatvRating (..)
-- * MemberListResponse
, MemberListResponse
, memberListResponse
, mlrEtag
, mlrTokenPagination
, mlrNextPageToken
, mlrPageInfo
, mlrKind
, mlrItems
, mlrVisitorId
, mlrEventId
) where
import Network.Google.Prelude
import Network.Google.YouTube.Types.Product
import Network.Google.YouTube.Types.Sum
-- | Default request referring to version 'v3' of the YouTube Data API v3. This contains the host and root path used as a starting point for constructing service requests.
youTubeService :: ServiceConfig
youTubeService
= defaultService (ServiceId "youtube:v3")
"youtube.googleapis.com"
-- | Manage your YouTube videos
youTubeUploadScope :: Proxy '["https://www.googleapis.com/auth/youtube.upload"]
youTubeUploadScope = Proxy
-- | Manage your YouTube account
youTubeScope :: Proxy '["https://www.googleapis.com/auth/youtube"]
youTubeScope = Proxy
-- | See a list of your current active channel members, their current level,
-- and when they became a member
youTubeChannelMembershipsCreatorScope :: Proxy '["https://www.googleapis.com/auth/youtube.channel-memberships.creator"]
youTubeChannelMembershipsCreatorScope = Proxy
-- | View and manage your assets and associated content on YouTube
youTubePartnerScope :: Proxy '["https://www.googleapis.com/auth/youtubepartner"]
youTubePartnerScope = Proxy
-- | See, edit, and permanently delete your YouTube videos, ratings, comments
-- and captions
youTubeForceSslScope :: Proxy '["https://www.googleapis.com/auth/youtube.force-ssl"]
youTubeForceSslScope = Proxy
-- | View your YouTube account
youTubeReadOnlyScope :: Proxy '["https://www.googleapis.com/auth/youtube.readonly"]
youTubeReadOnlyScope = Proxy
-- | View private information of your YouTube channel relevant during the
-- audit process with a YouTube partner
youTubePartnerChannelAuditScope :: Proxy '["https://www.googleapis.com/auth/youtubepartner-channel-audit"]
youTubePartnerChannelAuditScope = Proxy
| brendanhay/gogol | gogol-youtube/gen/Network/Google/YouTube/Types.hs | mpl-2.0 | 49,201 | 0 | 7 | 12,127 | 5,634 | 3,918 | 1,716 | 1,510 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Content.Repricingrules.Create
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a repricing rule for your Merchant Center account.
--
-- /See:/ <https://developers.google.com/shopping-content/v2/ Content API for Shopping Reference> for @content.repricingrules.create@.
module Network.Google.Resource.Content.Repricingrules.Create
(
-- * REST Resource
RepricingrulesCreateResource
-- * Creating a Request
, repricingrulesCreate
, RepricingrulesCreate
-- * Request Lenses
, repXgafv
, repMerchantId
, repUploadProtocol
, repAccessToken
, repRuleId
, repUploadType
, repPayload
, repCallback
) where
import Network.Google.Prelude
import Network.Google.ShoppingContent.Types
-- | A resource alias for @content.repricingrules.create@ method which the
-- 'RepricingrulesCreate' request conforms to.
type RepricingrulesCreateResource =
"content" :>
"v2.1" :>
Capture "merchantId" (Textual Int64) :>
"repricingrules" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "ruleId" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] RepricingRule :>
Post '[JSON] RepricingRule
-- | Creates a repricing rule for your Merchant Center account.
--
-- /See:/ 'repricingrulesCreate' smart constructor.
data RepricingrulesCreate =
RepricingrulesCreate'
{ _repXgafv :: !(Maybe Xgafv)
, _repMerchantId :: !(Textual Int64)
, _repUploadProtocol :: !(Maybe Text)
, _repAccessToken :: !(Maybe Text)
, _repRuleId :: !(Maybe Text)
, _repUploadType :: !(Maybe Text)
, _repPayload :: !RepricingRule
, _repCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RepricingrulesCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'repXgafv'
--
-- * 'repMerchantId'
--
-- * 'repUploadProtocol'
--
-- * 'repAccessToken'
--
-- * 'repRuleId'
--
-- * 'repUploadType'
--
-- * 'repPayload'
--
-- * 'repCallback'
repricingrulesCreate
:: Int64 -- ^ 'repMerchantId'
-> RepricingRule -- ^ 'repPayload'
-> RepricingrulesCreate
repricingrulesCreate pRepMerchantId_ pRepPayload_ =
RepricingrulesCreate'
{ _repXgafv = Nothing
, _repMerchantId = _Coerce # pRepMerchantId_
, _repUploadProtocol = Nothing
, _repAccessToken = Nothing
, _repRuleId = Nothing
, _repUploadType = Nothing
, _repPayload = pRepPayload_
, _repCallback = Nothing
}
-- | V1 error format.
repXgafv :: Lens' RepricingrulesCreate (Maybe Xgafv)
repXgafv = lens _repXgafv (\ s a -> s{_repXgafv = a})
-- | Required. The id of the merchant who owns the repricing rule.
repMerchantId :: Lens' RepricingrulesCreate Int64
repMerchantId
= lens _repMerchantId
(\ s a -> s{_repMerchantId = a})
. _Coerce
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
repUploadProtocol :: Lens' RepricingrulesCreate (Maybe Text)
repUploadProtocol
= lens _repUploadProtocol
(\ s a -> s{_repUploadProtocol = a})
-- | OAuth access token.
repAccessToken :: Lens' RepricingrulesCreate (Maybe Text)
repAccessToken
= lens _repAccessToken
(\ s a -> s{_repAccessToken = a})
-- | Required. The id of the rule to create.
repRuleId :: Lens' RepricingrulesCreate (Maybe Text)
repRuleId
= lens _repRuleId (\ s a -> s{_repRuleId = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
repUploadType :: Lens' RepricingrulesCreate (Maybe Text)
repUploadType
= lens _repUploadType
(\ s a -> s{_repUploadType = a})
-- | Multipart request metadata.
repPayload :: Lens' RepricingrulesCreate RepricingRule
repPayload
= lens _repPayload (\ s a -> s{_repPayload = a})
-- | JSONP
repCallback :: Lens' RepricingrulesCreate (Maybe Text)
repCallback
= lens _repCallback (\ s a -> s{_repCallback = a})
instance GoogleRequest RepricingrulesCreate where
type Rs RepricingrulesCreate = RepricingRule
type Scopes RepricingrulesCreate =
'["https://www.googleapis.com/auth/content"]
requestClient RepricingrulesCreate'{..}
= go _repMerchantId _repXgafv _repUploadProtocol
_repAccessToken
_repRuleId
_repUploadType
_repCallback
(Just AltJSON)
_repPayload
shoppingContentService
where go
= buildClient
(Proxy :: Proxy RepricingrulesCreateResource)
mempty
| brendanhay/gogol | gogol-shopping-content/gen/Network/Google/Resource/Content/Repricingrules/Create.hs | mpl-2.0 | 5,565 | 0 | 19 | 1,340 | 882 | 510 | 372 | 127 | 1 |
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
{-# LANGUAGE OverloadedStrings #-}
module Network.APNS.Protocol.Types where
import Data.Aeson
import Data.Aeson.TH
import Data.Aeson.Types
import Data.ByteString (ByteString)
import Data.Word
import Data.Text (Text)
import qualified Data.HashMap.Strict as M
newtype Token = Token
{ unToken :: Text } deriving (Eq, Show)
newtype NotificationId = NotificationId
{ unNotify :: Word32 } deriving (Eq, Show)
data Aps = Aps
-- TODO: apsAlert could be more strongly typed, i.e., string or dictionary
{ apsAlert :: !Value
, apsBadge :: !(Maybe Int)
, apsSound :: !(Maybe Text)
, apsContentAvailable :: !Int
, apsCategory :: !(Maybe Text)
} deriving (Eq, Show)
instance ToJSON Aps where
toJSON (Aps a b s ca c) = object
$ "alert" .= a
# "badge" .= b
# "sound" .= s
# "content-available" .= ca
# "category" .= c
# []
data ApnsNotification = ApnsNotification
{ apnsAps :: !Aps
, apnsExtra :: !(Maybe Object)
} deriving (Eq, Show)
instance ToJSON ApnsNotification where
toJSON (ApnsNotification a e) =
let (Object o) = object [ "aps" .= a ]
in maybe (Object o) (\e' -> Object $ o `M.union` e') e
-- | Possible error types returned by apple when sending notifications
data ErrorResponse = NoError
| ProcessingError
| MissingDeviceToken
| MissingTopic
| MissingPayload
| InvalidTokenSize
| InvalidTopicSize
| InvalidPayloadSize
| InvalidToken
| Shutdown
| Unknown
deriving (Eq, Show)
data ApnsResponse = ApnsResponse
{ arCommand :: Word8
, arStatus :: ErrorResponse
, arIdt :: NotificationId
} deriving (Eq, Show)
-- data ApnsResponse = ApnsResponse
-- { arInternal :: ApnsResponseInternal
-- , arToken :: Token
-- } deriving (Eq, Show)
-- | Feedback that comes from apple services
data ApnsFeedback = ApnsFeedback
{ afTime :: Word32
, afLen :: Word16
, afToken :: Token
} deriving (Eq, Show)
-- Misc util
append :: Pair -> [Pair] -> [Pair]
append (_, Null) pp = pp
append p pp = p:pp
{-# INLINE append #-}
infixr 5 #
(#) :: Pair -> [Pair] -> [Pair]
(#) = append
{-# INLINE (#) #-}
| tiago-loureiro/apns | src/Network/APNS/Protocol/Types.hs | mpl-2.0 | 2,607 | 0 | 16 | 798 | 601 | 350 | 251 | 80 | 1 |
module ModuleConf where
import Conf
import Distribution.PackageDescription (Library,ConfVar,CondTree,condLibrary)
import Distribution.Package (Dependency)
import Distribution.PackageDescription.Parse (readPackageDescription)
import Distribution.Verbosity (silent)
import Control.Monad.IO.Class (liftIO)
data ModuleFlag = ModuleFlag
packageConfiguration :: FilePath -> ConfT [String] ModuleFlag IO ([String],[FilePath])
packageConfiguration filepath = do
genericPackageDescription <- liftIO (readPackageDescription silent filepath)
case condLibrary genericPackageDescription of
Nothing -> liftIO (putStrLn "No Library") >> return ([],[])
Just l -> libraryConfig l
libraryConfig :: CondTree ConfVar [Dependency] Library -> ConfT [String] ModuleFlag m ([String],[FilePath])
libraryConfig = undefined
| phischu/conf | src/ModuleConf.hs | agpl-3.0 | 829 | 0 | 13 | 108 | 237 | 131 | 106 | 16 | 2 |
module HW05_ExprT where
data ExprT = Lit Integer
| Add ExprT ExprT
| Mul ExprT ExprT
deriving (Show, Eq)
| haroldcarr/learn-haskell-coq-ml-etc | haskell/course/2014-06-upenn/cis194/src/HW05_ExprT.hs | unlicense | 130 | 0 | 6 | 44 | 38 | 22 | 16 | 5 | 0 |
module Main where
import Primes
import Digits
import Data.List
isPandigital :: Int -> Bool
isPandigital num = [1..length numDigits] == (sort numDigits)
where
numDigits = digits num
biggestPandigitalPrime = head [ x | x <- downwards(7654321), isPandigital x, isPrime x ]
where
downwards num = num:downwards(num-1)
main = print $ biggestPandigitalPrime
| kliuchnikau/project-euler | 041/Main.hs | apache-2.0 | 367 | 0 | 10 | 67 | 132 | 69 | 63 | 10 | 1 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TupleSections #-}
module Tetris.Board where
import Control.Lens
import Data.Bool
import Data.Maybe
import Data.Monoid
import Data.Eq
import Data.Function (($),flip)
import Data.Functor (fmap)
import Data.Int
import Data.Ord (compare)
import qualified Data.List as List
import Data.Set
import Data.String
import GHC.Num
import GHC.Show
import Prelude (error)
import Tetris.Coord
-- | The board is a Set that contains occupied coords
type Board = Set Coord
-- Check if a row of the board is full, ie if all the columns are in the board
isFull :: Board -> Row -> Bool
isFull board row = List.all (\col -> (row,col) `member` board) allColumns
-- Erase rows by removing them from the board
eraseRows :: [Row] -> Board -> Board
eraseRows rows = (\\ coordsToRemove)
where coordsToRemove = fromList $ List.concatMap (\c -> fmap (,c) rows) allColumns
-- the game is over when the highest row is not empty (ie we touched the ceil)
isGameOver :: Board -> Bool
isGameOver board = List.any (\c -> (Digit Zero,c) `member` board) allColumns
-- We start from the row with the highest "toInt" value (that is the lowest
-- row that change in the board) and the we replace each line when we encounter
-- it.
--
-- We then clean the first n rows where n is the number of rows to remove
collapseRows :: [Row] -> Board -> Board
collapseRows [] board = board
collapseRows uFullRows board =
let (i,board',_) = List.foldl' collapseRow (0,board,sFullRows) rowsToChange
-- i - 1 because, e.g., if all rows must be removed then i == 22 but we need 21 (the maxBound)
in case fromInt (i-1) of
-- this error should never occur because i should always be in the
-- rows range, if happens then raise error
Nothing -> throwError $ "The row to erase cannot have number " <> show (i-1)
-- remove the first rows because they fell below
Just lastRow -> eraseRows (fromTo (Digit Zero) lastRow) board'
where
sFullRows = List.sortBy (flip compare) uFullRows -- reverse sorting
rowsToChange = List.reverse $ fromTo (Digit Zero) $ List.head sFullRows
collapseRow :: (Int,Board,[Row]) -> Row -> (Int,Board,[Row])
collapseRow (i,cBoard,frs) currRow =
case uncons frs of
-- when cr == h, the row should be eliminated:
-- skip it and replace it later
Just (h,t) -> if currRow == h then (i+1,cBoard,t)
else collapseRow' i cBoard currRow `extendWith` frs
Nothing -> collapseRow' i cBoard currRow `extendWith` frs
extendWith :: (a,b) -> c -> (a,b,c)
(x,y) `extendWith` z = (x,y,z)
-- row to keep but move => copy this row i rows below
collapseRow' :: Int -> Board -> Row -> (Int,Board)
collapseRow' i cBoard currRow =
let maybeRowToReplace = fromInt (i + toInt currRow)
in case maybeRowToReplace of
-- should not happen because we start from a row to replace,
-- if happens then raise error
Nothing -> throwError $ "The row to replace cannot have number " <> show (i + toInt currRow)
Just rowToReplace ->
-- remove the row to replace and then shift the current row
let cBoard' = cBoard \\ makeFullRow rowToReplace
newRow = fromList $ fmap (rowToReplace,) $
List.foldl' (\l c -> if (currRow,c) `member` cBoard
then c:l
else l)
[] allColumns
in (i,cBoard' `union` newRow)
makeFullRow :: Row -> Set Coord
makeFullRow row = fromList $ fmap (row,) allColumns
-- this will be used for "impossible" state errors to exit asap from the
-- program
throwError :: String -> a
throwError = error
| melrief/tetris | src/Tetris/Board.hs | apache-2.0 | 3,981 | 0 | 22 | 1,072 | 932 | 526 | 406 | 64 | 6 |
{-# LANGUAGE TemplateHaskell #-}
{-| PyType helper for Ganeti Haskell code.
-}
{-
Copyright (C) 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.THH.PyType
( PyType(..)
, pyType
, pyOptionalType
) where
import Control.Applicative
import Control.Monad
import Data.List (intercalate)
import Language.Haskell.TH
import Language.Haskell.TH.Syntax (Lift(..))
import Ganeti.PyValue
-- | Represents a Python encoding of types.
data PyType
= PTMaybe PyType
| PTApp PyType [PyType]
| PTOther String
| PTAny
| PTDictOf
| PTListOf
| PTNone
| PTObject
| PTOr
| PTSetOf
| PTTupleOf
deriving (Show, Eq, Ord)
-- TODO: We could use th-lift to generate this instance automatically.
instance Lift PyType where
lift (PTMaybe x) = [| PTMaybe x |]
lift (PTApp tf as) = [| PTApp tf as |]
lift (PTOther i) = [| PTOther i |]
lift PTAny = [| PTAny |]
lift PTDictOf = [| PTDictOf |]
lift PTListOf = [| PTListOf |]
lift PTNone = [| PTNone |]
lift PTObject = [| PTObject |]
lift PTOr = [| PTOr |]
lift PTSetOf = [| PTSetOf |]
lift PTTupleOf = [| PTTupleOf |]
instance PyValue PyType where
-- Use lib/ht.py type aliases to avoid Python creating redundant
-- new match functions for commonly used OpCode param types.
showValue (PTMaybe (PTOther "NonEmptyString")) = ht "MaybeString"
showValue (PTMaybe (PTOther "Bool")) = ht "MaybeBool"
showValue (PTMaybe PTDictOf) = ht "MaybeDict"
showValue (PTMaybe PTListOf) = ht "MaybeList"
showValue (PTMaybe x) = ptApp (ht "Maybe") [x]
showValue (PTApp tf as) = ptApp (showValue tf) as
showValue (PTOther i) = ht i
showValue PTAny = ht "Any"
showValue PTDictOf = ht "DictOf"
showValue PTListOf = ht "ListOf"
showValue PTNone = ht "None"
showValue PTObject = ht "Object"
showValue PTOr = ht "Or"
showValue PTSetOf = ht "SetOf"
showValue PTTupleOf = ht "TupleOf"
ht :: String -> String
ht = ("ht.T" ++)
ptApp :: String -> [PyType] -> String
ptApp name ts = name ++ "(" ++ intercalate ", " (map showValue ts) ++ ")"
-- | Converts a Haskell type name into a Python type name.
pyTypeName :: Name -> PyType
pyTypeName name =
case nameBase name of
"()" -> PTNone
"Map" -> PTDictOf
"Set" -> PTSetOf
"ListSet" -> PTSetOf
"Either" -> PTOr
"GenericContainer" -> PTDictOf
"JSValue" -> PTAny
"JSObject" -> PTObject
str -> PTOther str
-- | Converts a Haskell type into a Python type.
pyType :: Type -> Q PyType
pyType t | not (null args) = PTApp `liftM` pyType fn `ap` mapM pyType args
where (fn, args) = pyAppType t
pyType (ConT name) = return $ pyTypeName name
pyType ListT = return PTListOf
pyType (TupleT 0) = return PTNone
pyType (TupleT _) = return PTTupleOf
pyType typ = fail $ "unhandled case for type " ++ show typ
-- | Returns a type and its type arguments.
pyAppType :: Type -> (Type, [Type])
pyAppType = g []
where
g as (AppT typ1 typ2) = g (typ2 : as) typ1
g as typ = (typ, as)
-- | @pyType opt typ@ converts Haskell type @typ@ into a Python type,
-- where @opt@ determines if the converted type is optional (i.e.,
-- Maybe).
pyOptionalType :: Bool -> Type -> Q PyType
pyOptionalType True typ = PTMaybe <$> pyType typ
pyOptionalType False typ = pyType typ
| yiannist/ganeti | src/Ganeti/THH/PyType.hs | bsd-2-clause | 4,876 | 0 | 10 | 1,289 | 971 | 520 | 451 | 83 | 9 |
{-# LANGUAGE TypeFamilies, TypeOperators, TupleSections #-}
{-# OPTIONS_GHC -Wall #-}
----------------------------------------------------------------------
-- |
-- Module : FunctorCombo.Holey
-- Copyright : (c) Conal Elliott 2010
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Filling and extracting derivatives (one-hole contexts)
----------------------------------------------------------------------
module FunctorCombo.Holey (Loc,Holey(..),fill) where
import Control.Arrow (first,second)
import FunctorCombo.Functor
import FunctorCombo.Derivative
{--------------------------------------------------------------------
Extraction
--------------------------------------------------------------------}
-- | Location, i.e., one-hole context and a value for the hole.
type Loc f a = (Der f a, a)
-- | Alternative interface for 'fillC'.
fill :: Holey f => Loc f a -> f a
fill = uncurry fillC
-- | Filling and creating one-hole contexts
class Functor f => Holey f where
fillC :: Der f a -> a -> f a -- ^ Fill a hole
extract :: f a -> f (Loc f a) -- ^ All extractions
-- The Functor constraint simplifies several signatures below.
instance Holey (Const z) where
fillC = voidF
extract (Const z) = Const z
instance Holey Id where
fillC (Const ()) = Id
extract (Id a) = Id (Const (), a)
-- fillC (Const ()) a = Id a
-- fill (Const (), a) = Id a
instance (Holey f, Holey g) => Holey (f :+: g) where
fillC (InL df) = InL . fillC df
fillC (InR df) = InR . fillC df
extract (InL fa) = InL ((fmap.first) InL (extract fa))
extract (InR ga) = InR ((fmap.first) InR (extract ga))
-- fillC (InL df) a) = InL (fillC df a)
-- fillC (InR df) a) = InR (fillC df a)
-- fill (InL df, a) = InL (fill (df, a))
-- fill (InR df, a) = InR (fill (df, a))
-- fillC = eitherF ((result.result) InL fillC) ((result.result) InR fillC)
{-
InL fa :: (f :+: g) a
fa :: f a
extract fa :: f (Loc f a)
(fmap.first) InL (extract fa) :: f ((Der f :+: Der g) a, a)
(fmap.first) InL (extract fa) :: f ((Der (f :+: g) a), a)
InL ((fmap.first) InL (extract fa)) :: (f :+: g) ((Der (f :+: g) a), a)
-}
-- Der (f :*: g) = Der f :*: g :+: f :*: Der g
instance (Holey f, Holey g) => Holey (f :*: g) where
fillC (InL (dfa :*: ga)) = (:*: ga) . fillC dfa
fillC (InR ( fa :*: dga)) = (fa :*:) . fillC dga
extract (fa :*: ga) = (fmap.first) (InL . (:*: ga)) (extract fa) :*:
(fmap.first) (InR . (fa :*:)) (extract ga)
-- fillC (InL (dfa :*: ga)) a = fillC dfa a :*: ga
-- fillC (InR ( fa :*: dga)) a = fa :*: fillC dga a
-- fill (InL (dfa :*: ga), a) = fill (dfa, a) :*: ga
-- fill (InR ( fa :*: dga), a) = fa :*: fill (dga, a)
{-
fa :*: ga :: (f :*: g) a
fa :: f a
extract fa :: f (Loc f a)
(fmap.first) (:*: ga) (extract fa) :: f ((Der f :*: g) a, a)
(fmap.first) (InL . (:*: ga)) (extract fa)
:: f (((Der f :*: g) :+: (f :*: Der g)) a, a)
(fmap.first) (InL . (:*: ga)) (extract fa) :: f ((Der (f :*: g)) a, a)
(fmap.first) (InR . (fa :*:)) (extract ga) :: g ((Der (f :*: g)) a, a)
(fmap.first) (InL . (:*: ga)) (extract fa) :*: (fmap.first) (InR . (fa :*:)) (extract ga)
:: (f :*: g) (Der (f :*: g) a, a)
-}
-- type instance Der (g :. f) = Der g :. f :*: Der f
lassoc :: (p,(q,r)) -> ((p,q),r)
lassoc (p,(q,r)) = ((p,q),r)
squishP :: Functor f => (a, f b) -> f (a,b)
squishP (a,fb) = fmap (a,) fb
tweak1 :: Functor f => (dg (fa), f (dfa, a)) -> f ((dg (fa), dfa), a)
tweak1 = fmap lassoc . squishP
chainRule :: (dg (f a), df a) -> ((dg :. f) :*: df) a
chainRule (dgfa, dfa) = O dgfa :*: dfa
tweak2 :: Functor f => (dg (f a), f (df a, a)) -> f (((dg :. f) :*: df) a, a)
tweak2 = (fmap.first) chainRule . tweak1
-- And more specifically,
--
-- tweak2 :: Functor f => (Der g (f a), f (Loc f a)) -> f (((Der g :. f) :*: Der f) a, a)
-- tweak2 :: Functor f => (Der g (f a), f (Loc f a)) -> f (Der (g :. f) a, a)
-- tweak2 :: Functor f => (Der g (f a), f (Loc f a)) -> f (Loc (g :. f) a)
{-
(dg fa, f (dfa,a))
f (dg fa, (df,a))
f ((dg fa, dfa), a)
-}
extractGF :: (Holey f, Holey g) =>
g (f a) -> g (f (Loc (g :. f) a))
extractGF = fmap (tweak2 . second extract) . extract
{-
gfa :: g (f a)
extract gfa :: g (Der g (f a), f a)
fmap (second extract) (extract gfa) :: g (Der g (f a), f (Loc f a))
fmap (tweak2 . second extract) (extract gfa)
:: g (f (Loc (g :. f) a))
-}
-- Der (g :. f) = Der g :. f :*: Der f
instance (Holey f, Holey g) => Holey (g :. f) where
fillC (O dgfa :*: dfa) = O. fillC dgfa . fillC dfa
-- fillC (O dgfa :*: dfa) a = O (fillC dgfa (fillC dfa a))
-- extract (O gfa) = O (extractGF gfa)
extract = inO extractGF
-- fill (O dgfa :*: dfa, a) = O (fill (dgfa, fill (dfa, a)))
{-
O dgfa :*: dfa :: Der (g :. f) a
O dgfa :*: dfa :: (Der g :. f :*: Der f) a
dgfa :: Der g (f a)
dfa :: Der f a
fillC dfa a :: f a
fillC dgfa (fillC dfa a) :: g (f a)
O (fillC dgfa (fillC dfa a)) :: (g :. f) a
-}
| conal/functor-combo | src/FunctorCombo/Holey.hs | bsd-3-clause | 5,004 | 0 | 13 | 1,209 | 1,093 | 600 | 493 | 44 | 1 |
{-# LANGUAGE ViewPatterns, RecordWildCards #-}
module Cabal(
Cabal(..), CabalSection(..), CabalSectionType,
parseCabal,
selectCabalFile,
selectHiFiles
) where
import System.IO.Extra
import System.Directory.Extra
import System.FilePath
import qualified Data.HashMap.Strict as Map
import Util
import Data.Char
import Data.Maybe
import Data.List.Extra
import Data.Tuple.Extra
import Data.Either.Extra
import Data.Semigroup
import Prelude
selectCabalFile :: FilePath -> IO FilePath
selectCabalFile dir = do
xs <- listFiles dir
case filter ((==) ".cabal" . takeExtension) xs of
[x] -> return x
_ -> fail $ "Didn't find exactly 1 cabal file in " ++ dir
-- | Return the (exposed Hi files, internal Hi files, not found)
selectHiFiles :: FilePath -> Map.HashMap FilePathEq a -> CabalSection -> ([a], [a], [ModuleName])
selectHiFiles distDir his sect@CabalSection{..} = (external, internal, bad1++bad2)
where
(bad1, external) = partitionEithers $
[findHi his sect $ Left cabalMainIs | cabalMainIs /= ""] ++
[findHi his sect $ Right x | x <- cabalExposedModules]
(bad2, internal) = partitionEithers
[findHi his sect $ Right x | x <- filter (not . isPathsModule) cabalOtherModules]
findHi :: Map.HashMap FilePathEq a -> CabalSection -> Either FilePath ModuleName -> Either ModuleName a
findHi his cabal@CabalSection{..} name =
-- error $ show (poss, Map.keys his)
maybe (Left mname) Right $ firstJust (`Map.lookup` his) poss
where
mname = either takeFileName id name
poss = map filePathEq $ possibleHi distDir cabalSourceDirs cabalSectionType $ either (return . dropExtension) (splitOn ".") name
-- | This code is fragile and keeps going wrong, should probably try a less "guess everything"
-- and a more refined filter and test.
possibleHi :: FilePath -> [FilePath] -> CabalSectionType -> [String] -> [FilePath]
possibleHi distDir sourceDirs sectionType components =
[ joinPath (root : x : components) <.> "dump-hi"
| extra <- [".",distDir]
, root <- concat [["build" </> extra </> x </> (x ++ "-tmp")
,"build" </> extra </> x </> x
,"build" </> extra </> x </> (x ++ "-tmp") </> distDir </> "build" </> x </> (x ++ "-tmp")]
| Just x <- [cabalSectionTypeName sectionType]] ++
["build", "build" </> distDir </> "build"]
, x <- sourceDirs ++ ["."]]
data Cabal = Cabal
{cabalName :: PackageName
,cabalSections :: [CabalSection]
} deriving Show
instance Semigroup Cabal where
Cabal x1 x2 <> Cabal y1 y2 = Cabal (x1?:y1) (x2++y2)
instance Monoid Cabal where
mempty = Cabal "" []
mappend = (<>)
data CabalSectionType = Library (Maybe String) | Executable String | TestSuite String | Benchmark String
deriving (Eq,Ord)
cabalSectionTypeName :: CabalSectionType -> Maybe String
cabalSectionTypeName (Library x) = x
cabalSectionTypeName (Executable x) = Just x
cabalSectionTypeName (TestSuite x) = Just x
cabalSectionTypeName (Benchmark x) = Just x
instance Show CabalSectionType where
show (Library Nothing) = "library"
show (Library (Just x)) = "library:" ++ x
show (Executable x) = "exe:" ++ x
show (TestSuite x) = "test:" ++ x
show (Benchmark x) = "bench:" ++ x
instance Read CabalSectionType where
readsPrec _ "library" = [(Library Nothing,"")]
readsPrec _ x
| Just x <- stripPrefix "exe:" x = [(Executable x, "")]
| Just x <- stripPrefix "test:" x = [(TestSuite x, "")]
| Just x <- stripPrefix "bench:" x = [(Benchmark x, "")]
| Just x <- stripPrefix "library:" x = [(Library (Just x), "")]
readsPrec _ _ = []
data CabalSection = CabalSection
{cabalSectionType :: CabalSectionType
,cabalMainIs :: FilePath
,cabalExposedModules :: [ModuleName]
,cabalOtherModules :: [ModuleName]
,cabalSourceDirs :: [FilePath]
,cabalPackages :: [PackageName]
} deriving Show
instance Semigroup CabalSection where
CabalSection x1 x2 x3 x4 x5 x6 <> CabalSection y1 y2 y3 y4 y5 y6 =
CabalSection x1 (x2?:y2) (x3<>y3) (x4<>y4) (x5<>y5) (x6<>y6)
instance Monoid CabalSection where
mempty = CabalSection (Library Nothing) "" [] [] [] []
mappend = (<>)
parseCabal :: FilePath -> IO Cabal
parseCabal = fmap parseTop . readFile'
parseTop = mconcatMap f . parseHanging . filter (not . isComment) . lines
where
isComment = isPrefixOf "--" . trimStart
keyName = (lower *** fst . word1) . word1
f (keyName -> (key, name), xs) = case key of
"name:" -> mempty{cabalName=name}
"library" -> case name of
"" -> mempty{cabalSections=[parseSection (Library Nothing) xs]}
x -> mempty{cabalSections=[parseSection (Library (Just x)) xs]}
"executable" -> mempty{cabalSections=[parseSection (Executable name) xs]}
"test-suite" -> mempty{cabalSections=[parseSection (TestSuite name) xs]}
"benchmark" -> mempty{cabalSections=[parseSection (Benchmark name) xs]}
_ -> mempty
parseSection typ xs = mempty{cabalSectionType=typ} <> parse xs
where
parse = mconcatMap f . parseHanging
keyValues (x,xs) = let (x1,x2) = word1 x in (lower x1, trimEqual $ filter (not . null) $ x2:xs)
trimEqual xs = map (drop n) xs
where n = minimum $ 0 : map (length . takeWhile isSpace) xs
listSplit = concatMap (wordsBy (`elem` " ,"))
isPackageNameChar x = isAlphaNum x || x == '-'
parsePackage = dropSuffix "-any" . takeWhile isPackageNameChar . trim
f (keyValues -> (k,vs)) = case k of
"if" -> parse vs
"else" -> parse vs
"build-depends:" -> mempty{cabalPackages = map parsePackage . splitOn "," $ unwords vs}
"hs-source-dirs:" -> mempty{cabalSourceDirs=listSplit vs}
"exposed-modules:" -> mempty{cabalExposedModules=listSplit vs}
"other-modules:" -> mempty{cabalOtherModules=listSplit vs}
"main-is:" -> mempty{cabalMainIs=headDef "" vs}
_ -> mempty
| ndmitchell/weeder | src/Cabal.hs | bsd-3-clause | 6,213 | 0 | 20 | 1,554 | 2,102 | 1,109 | 993 | -1 | -1 |
module Data.TTask.File.Compatibility.V0_0_1_0
( readProject
) where
import Data.Functor
import Safe
import Data.Time
import Control.Lens
import qualified Data.TTask.Types.Types as T
data Task = Task
{ taskId :: T.Id
, taskDescription :: String
, taskPoint :: Int
, taskStatus :: T.TStatus
, taskWorkTimes :: [T.WorkTime]
} deriving (Show, Read, Eq)
data UserStory = UserStory
{ storyId :: T.Id
, storyDescription :: String
, storyTasks :: [Task]
, storyStatus :: T.TStatus
} deriving (Show, Read, Eq)
data Sprint = Sprint
{ sprintId :: T.Id
, sprintDescription :: String
, sprintStorys :: [UserStory]
, sprintStatus :: T.TStatus
} deriving (Show, Read, Eq)
data Project = Project
{ projectName :: String
, projectBacklog :: [UserStory]
, projectSprints :: [Sprint]
, projectStatus :: T.TStatus
} deriving (Show, Read, Eq)
data TTaskContents
= TTaskProject Project
| TTaskSprint Sprint
| TTaskStory UserStory
| TTaskTask Task
-------
readProject :: String -> Maybe T.Project
readProject = (convert <$>) . readOldProject
readOldProject :: String -> Maybe Project
readOldProject s = readMay s
convert :: Project -> T.Project
convert p = T.Project
{ T._projectName = projectName p
, T._projectBacklog = map convertStory $ projectBacklog p
, T._projectSprints = map convertSprint $ projectSprints p
, T._projectStatus = projectStatus p
}
-------
convertTask :: Task -> T.Task
convertTask t = T.Task
{ T._taskId = taskId t
, T._taskDescription = taskDescription t
, T._taskPoint = taskPoint t
, T._taskStatus = taskStatus t
, T._taskWorkTimes = taskWorkTimes t
}
convertStory :: UserStory -> T.UserStory
convertStory u = T.UserStory
{ T._storyId = storyId u
, T._storyDescription = storyDescription u
, T._storyTasks = map convertTask $ storyTasks u
, T._storyStatus = storyStatus u
}
convertSprint :: Sprint -> T.Sprint
convertSprint s = T.Sprint
{ T._sprintId = sprintId s
, T._sprintDescription = sprintDescription s
, T._sprintStorys = map convertStory $ sprintStorys s
, T._sprintStatus = sprintStatus s
}
| tokiwoousaka/ttask | src/Data/TTask/File/Compatibility/V0_0_1_0.hs | bsd-3-clause | 2,120 | 0 | 10 | 414 | 654 | 371 | 283 | 66 | 1 |
module DataParsers where
import CSV
import Text.ParserCombinators.Parsec hiding (labels)
import DataTypes
import Control.Monad.Except
import Data.IORef
import Data.Char
import Text.Read hiding (String)
fromRight :: Either a b -> b
fromRight (Right b) = b
maybeToTop :: Maybe WVal -> WVal
maybeToTop (Just w) = w
maybeToTop Nothing = Top
zipSingle :: a -> [b] -> [(a, b)]
zipSingle a [] = []
zipSingle a (b:bs) = (a, b) : zipSingle a bs
readMaybeInteger str = readMaybe fixedStr :: Maybe Integer
where fixedStr = if last str == '.' then init str else str
readMaybeDouble str = readMaybe fixedStr :: Maybe Double
where fixedStr = if last str == '.' then init str else str
parseTyped :: WType -> String -> Maybe WVal
parseTyped TString str = Just $ String str
parseTyped TBool boolStr
| str `elem` ["true", "1", "yes"] = Just $ Bool True
| str `elem` ["false", "0", "no"] = Just $ Bool False
| otherwise = Nothing
where str = map toLower boolStr
parseTyped TIntegral str = fmap Integral (readMaybeInteger str)
parseTyped TFloat str = fmap Float (readMaybeDouble str)
-- [IOThrowsError [Maybe WVal]]
parseTypedRow :: [WType] -> [String] -> IOThrowsError [WVal]
parseTypedRow types rows
| (length types == length rows) = return $ map maybeToTop $ zipWith parseTyped types rows --map (uncurry parseTyped) (zip types rows)
| otherwise = throwError $ CSVParseError $ "Inconsistent number of columns, " ++ show (length types) ++ " vs. " ++ show (length rows)
parseTypedStringTable :: [WType] -> [[String]] -> IOThrowsError [[WVal]]
parseTypedStringTable types strTable = sequenceA (map (parseTypedRow types) strTable)
parseCSVDelim :: Char -> Table -> String -> IOThrowsError WVal
parseCSVDelim delim table toParseFile = do
result <- liftIO $ parseFromFile (csvFile delim) toParseFile
case result of
Left err -> throwError $ CSVParseError (show err)
Right _ -> return Unit
let tableStrings = fromRight result
table' <- liftIO $ readIORef table
let tableTypes = format table'
let (tableValueStrings, newLabels) = if hasHeader table'
then (tail tableStrings, head tableStrings)
else (tableStrings, labels table')
if (hasHeader table') && length tableTypes /= length newLabels
then throwError $ CSVParseError $ "Inconsistent number of columns, " ++ show (length newLabels) ++ " vs. " ++ show (length tableTypes)
else return Unit
newRows <- parseTypedStringTable tableTypes tableValueStrings
let newTable' = table' { rows = newRows, labels = newLabels }
liftIO $ writeIORef table newTable'
return Unit
| knalbant/wrangell | DataParsers.hs | bsd-3-clause | 2,658 | 0 | 13 | 557 | 916 | 461 | 455 | 54 | 4 |
{-# LANGUAGE FlexibleContexts #-}
module Cologne.Shaders.Debug (
debug
) where
import Control.Monad.ST
import Data.STRef (newSTRef, readSTRef, writeSTRef)
import Control.Monad.State (State, runState)
import Data.Vect (Vec3(Vec3), (&+), (&*), (&.), (&^), len, normalize)
import Data.Vector.Mutable (MVector, new, read, write)
import Data.Vector (Vector, unsafeFreeze, forM_, enumFromN)
import Graphics.Formats.Assimp (lookAt, position, horizontalFOV, aspect, up,
Camera(Camera))
import Cologne.Primitives hiding (intersect)
import Cologne.AssimpImport (ColorInfo)
-- Just return the color we intersect multiplied by the cosine of the angle of
-- intersection.
radiance :: (AccelStruct a (Vec3 , Vec3, ReflectionType)) =>
a
-> Ray
-> Int
-> Vec3
radiance scene ray _ = do
case aIntersect scene ray of
Miss -> Vec3 0 0 0
Intersection _ (color, _, _) nrm ->
color &* (abs (((direction ray) &. nrm) / ((len (direction ray)) * (len nrm))))
debug :: Context [Primitive ColorInfo] ColorInfo
-> Vector (Vector Vec3)
debug (Context options cams scene) = runST generatePicture
where
generatePicture :: ST s (Vector (Vector Vec3))
generatePicture = do
pic <- new h
forM_ (enumFromN 0 h) $ \row -> do
vec <- new w
forM_ (enumFromN 0 w) $ \column -> do
let val = radiance scene (ray column row) 0
write vec column val
unsafeFreeze vec >>= write pic (h-row-1)
unsafeFreeze pic
w = width options
h = height options
samp = samples options
cam | length cams > 0 = head cams
| otherwise = Camera "" (Vec3 0 0 500) (Vec3 0 1 0)
(Vec3 0 0.1 (-1)) 0.5 1e-2 1e5 1
dir x y = (cx &* (((fromIntegral x) / fromIntegral w) - 0.5))
&+ (cy &* (((fromIntegral y) / fromIntegral h) - 0.5))
&+ (lookAt cam)
ray x y = Ray ((position cam) &+ ((dir x y) &* 140.0)) (normalize (dir x y))
cx = Vec3 (0.5135 * fromIntegral w / fromIntegral h) 0 0
cy = normalize (cx &^ (lookAt cam)) &* 0.5135
| joelburget/Cologne | Cologne/Shaders/Debug.hs | bsd-3-clause | 2,120 | 0 | 22 | 574 | 844 | 449 | 395 | 48 | 2 |
-- | Settings are centralized, as much as possible, into this file. This
-- includes database connection settings, static file locations, etc.
-- In addition, you can configure a number of different aspects of Yesod
-- by overriding methods in the Yesod typeclass. That instance is
-- declared in the Foundation.hs file.
module Settings where
import ClassyPrelude.Yesod
import Control.Exception (throw)
import Data.Aeson (Result (..), fromJSON, withObject, (.!=),
(.:?))
import Data.FileEmbed (embedFile)
import Data.Yaml (decodeEither')
import Database.Persist.Sqlite (SqliteConf)
import Language.Haskell.TH.Syntax (Exp, Name, Q)
import Network.Wai.Handler.Warp (HostPreference)
import Yesod.Default.Config2 (applyEnvValue, configSettingsYml)
import Yesod.Default.Util (WidgetFileSettings, widgetFileNoReload,
widgetFileReload)
-- | Runtime settings to configure this application. These settings can be
-- loaded from various sources: defaults, environment variables, config files,
-- theoretically even a database.
data AppSettings = AppSettings
{ appStaticDir :: String
-- ^ Directory from which to serve static files.
, appDatabaseConf :: SqliteConf
-- ^ Configuration settings for accessing the database.
, appRoot :: Text
-- ^ Base for all generated URLs.
, appHost :: HostPreference
-- ^ Host/interface the server should bind to.
, appPort :: Int
-- ^ Port to listen on
, appIpFromHeader :: Bool
-- ^ Get the IP address from the header when logging. Useful when sitting
-- behind a reverse proxy.
, appOauthClientSecret :: Text
-- ^ Oauth2 client secret
, appDetailedRequestLogging :: Bool
-- ^ Use detailed request logging system
, appShouldLogAll :: Bool
-- ^ Should all log messages be displayed?
, appReloadTemplates :: Bool
-- ^ Use the reload version of templates
, appMutableStatic :: Bool
-- ^ Assume that files in the static dir may change after compilation
, appSkipCombining :: Bool
-- ^ Perform no stylesheet/script combining
-- Example app-specific configuration values.
, appCopyright :: Text
-- ^ Copyright text to appear in the footer of the page
, appAnalytics :: Maybe Text
-- ^ Google Analytics code
}
instance FromJSON AppSettings where
parseJSON = withObject "AppSettings" $ \o -> do
let defaultDev =
#if DEVELOPMENT
True
#else
False
#endif
appStaticDir <- o .: "static-dir"
appDatabaseConf <- o .: "database"
appRoot <- o .: "approot"
appHost <- fromString <$> o .: "host"
appPort <- o .: "port"
appIpFromHeader <- o .: "ip-from-header"
appOauthClientSecret <- o .: "oauth-client-secret"
appDetailedRequestLogging <- o .:? "detailed-logging" .!= defaultDev
appShouldLogAll <- o .:? "should-log-all" .!= defaultDev
appReloadTemplates <- o .:? "reload-templates" .!= defaultDev
appMutableStatic <- o .:? "mutable-static" .!= defaultDev
appSkipCombining <- o .:? "skip-combining" .!= defaultDev
appCopyright <- o .: "copyright"
appAnalytics <- o .:? "analytics"
return AppSettings {..}
-- | Settings for 'widgetFile', such as which template languages to support and
-- default Hamlet settings.
--
-- For more information on modifying behavior, see:
--
-- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile
widgetFileSettings :: WidgetFileSettings
widgetFileSettings = def
-- | How static files should be combined.
combineSettings :: CombineSettings
combineSettings = def
-- The rest of this file contains settings which rarely need changing by a
-- user.
widgetFile :: String -> Q Exp
widgetFile = (if appReloadTemplates compileTimeAppSettings
then widgetFileReload
else widgetFileNoReload)
widgetFileSettings
-- | Raw bytes at compile time of @config/settings.yml@
configSettingsYmlBS :: ByteString
configSettingsYmlBS = $(embedFile configSettingsYml)
-- | @config/settings.yml@, parsed to a @Value@.
configSettingsYmlValue :: Value
configSettingsYmlValue = either throw id $ decodeEither' configSettingsYmlBS
-- | A version of @AppSettings@ parsed at compile time from @config/settings.yml@.
compileTimeAppSettings :: AppSettings
compileTimeAppSettings =
case fromJSON $ applyEnvValue False mempty configSettingsYmlValue of
Error e -> error e
Success settings -> settings
-- The following two functions can be used to combine multiple CSS or JS files
-- at compile time to decrease the number of http requests.
-- Sample usage (inside a Widget):
--
-- > $(combineStylesheets 'StaticR [style1_css, style2_css])
combineStylesheets :: Name -> [Route Static] -> Q Exp
combineStylesheets = combineStylesheets'
(appSkipCombining compileTimeAppSettings)
combineSettings
combineScripts :: Name -> [Route Static] -> Q Exp
combineScripts = combineScripts'
(appSkipCombining compileTimeAppSettings)
combineSettings
| mitchellwrosen/dohaskell | src/Settings.hs | bsd-3-clause | 5,495 | 0 | 12 | 1,486 | 719 | 412 | 307 | -1 | -1 |
-- -----------------------------------------------------------------------------
--
-- Info.hs, part of Alex
--
-- (c) Simon Marlow 2003
--
-- Generate a human-readable rendition of the state machine.
--
-- ----------------------------------------------------------------------------}
module Text.Luthor.Info ( infoDFA ) where
import Text.Luthor.Syntax
import qualified Data.Map
import Text.Luthor.Pretty
import Data.CharSet
import Data.Array
-- -----------------------------------------------------------------------------
-- Generate a human readable dump of the state machine
infoDFA :: Int -> String -> DFA SNum Code -> ShowS
infoDFA _ func_nm dfa
= str "Scanner : " . str func_nm . nl
. str "States : " . shows (length dfa_list) . nl
. nl . infoDFA'
where
dfa_list = Map.toAscList (dfa_states dfa)
infoDFA' = interleave_shows nl (map infoStateN dfa_list)
infoStateN (i,s) = str "State " . shows i . nl . infoState s
infoState :: State SNum Code -> ShowS
infoState (State accs out)
= foldr (.) id (map infoAccept accs)
. infoArr out . nl
infoArr out
= char '\t' . interleave_shows (str "\n\t")
(map infoTransition (Map.toAscList out))
infoAccept (Acc p act lctx rctx)
= str "\tAccept" . paren (shows p) . space
. outputLCtx lctx . space
. showRCtx rctx
. (case act of
Nothing -> id
Just code -> str " { " . str code . str " }")
. nl
infoTransition (char',state)
= str (ljustify 8 (show char'))
. str " -> "
. shows state
outputLCtx Nothing
= id
outputLCtx (Just set)
= paren (outputArr (charSetToArray set)) . char '^'
outputArr arr
= str "Array.array " . shows (bounds arr) . space
. shows (assocs arr)
| ekmett/luthor | Text/Luthor/Info.hs | bsd-3-clause | 1,781 | 11 | 20 | 425 | 487 | 256 | 231 | 40 | 3 |
module Network.Kafka.Protocol where
| iand675/hs-kafka | src/Network/Kafka/Protocol.hs | bsd-3-clause | 36 | 0 | 3 | 3 | 7 | 5 | 2 | 1 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
module Main where
import System.Console.CmdArgs
import Com.DiagClient(sendData)
import DiagnosticConfig
import Control.Monad (when)
import Network.Socket
import Script.ErrorMemory
import Script.LoggingFramework
import Numeric(showHex,readHex)
import Util.Encoding
import Data.Word
import LuaTester(executeLuaScript)
import Diagnoser.DiagScriptTester(runTestScript)
import Text.ParserCombinators.Parsec hiding (many, optional, (<|>))
import Text.Parsec.Token
import Control.Applicative
data DiagTool = Diagsend { ip :: String, diagId :: String, message :: String }
| ReadDtc { ip :: String, dtcKind :: Int }
| Logging { logIp :: String, enableLogging :: Bool, showLogging :: Bool }
| DiagTest { ip :: String, script :: String }
| LuaTest { script :: String }
deriving (Show, Data, Typeable)
defaultIp = "127.0.0.1"
diagSend = Diagsend {ip = defaultIp &= help "ip address",
diagId = "10" &= help "diagnosis id",
message = "[0x22,0xF1,0x90]" &= help "diagnostic message to be sent"}
dtc = ReadDtc { ip = defaultIp &= help "ip address",
dtcKind = 1 &= name "k" &= help "[primary = 1, secondary = 2]" } &= help "read DTCs in ecu"
logging = Logging { logIp = defaultIp &= name "i" &= help "ip address",
enableLogging = def &= help "enable logging",
showLogging = def &= help "show mapping"
} &= help "change logging settings"
diagTest = DiagTest { ip = defaultIp &= help "ip address",
script = def &= help "diagnoser script to run" }
luaTest = LuaTest { script = def &= help "lua script to run" }
parseTesterId :: String -> Either ParseError Word8
parseTesterId = parse hexnumber "(unknown)"
parseDiagMsg :: String -> Either ParseError [Word8]
parseDiagMsg = parse hexlist "(unknown)"
hexlist :: CharParser () [Word8]
hexlist = between (char '[') (char ']') (hexnumber `sepBy` char ',')
hexnumber = fst . head . readHex <$> (skipMany (string "0x") *> many1 hexDigit)
main :: IO ()
main = withSocketsDo $ do
actions <- cmdArgs $ (modes [diagSend,dtc,logging,diagTest,luaTest]
&= summary "DiagnosisTool 0.3.0, (c) Oliver Mueller 2010-2011")
&= verbosity
execute actions
execute :: DiagTool -> IO ()
execute (ReadDtc ip x)
| x == 1 = readPrimaryErrorMemory c
| x == 2 = readSecondaryErrorMemory c
where c = femConfig ip
execute (Logging logIp e m) = do
when e enable
when m $ showMappingWithConf conf
execute (DiagTest ip s) = do
-- print $ "running script " ++ s
-- runTestScript s ip
return ()
execute (Diagsend ip diagid m) =
case parseTesterId diagid of
(Right tid) -> do let config = mkConf tid ip
case parseDiagMsg m of
(Right msg) -> sendData config msg >> return ()
_ -> print "diag message format not correct (use s.th. like 0x22,0xF1)" >> return ()
_ -> return ()
| marcmo/hsDiagnosis | Main.hs | bsd-3-clause | 3,113 | 0 | 15 | 841 | 896 | 478 | 418 | 66 | 3 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RankNTypes #-}
module Test.Themis.Keyword (
Keyword
, runKeyword
, Context(..)
, Action
, safeAction
, safeActionRollback
, action
, actionRollback
, Interpretation(..)
, step
, info
, assertEquals
, satisfies
) where
import Control.Monad.Error
import Control.Monad.State
import Control.Monad.Trans
import qualified Control.Monad.Trans.Error as CME
import qualified Control.Monad.Trans.State as CMS
{-
Every testeable system with test steps can be represented by keywords.
Keywords are composable actions. These actions has optional backup steps.
Keywords represents a script which can be evaluated with the given
context of the interpretation of each keyword. This way multiple
reusable scripts can be written in the haskell do notation.
-}
data Keyword k a where
KRet :: a -> Keyword k a
KWord :: k a -> Keyword k a
KInfo :: k a -> Keyword k a
KLog :: String -> Keyword k ()
KAssert :: Bool -> String -> Keyword k ()
KBind :: Keyword k a -> (a -> Keyword k b) -> Keyword k b
instance Monad (Keyword k) where
return = KRet
m >>= k = KBind m k
-- | The 'k' step that will be interpreted in some action.
step :: k a -> Keyword k a
step = KWord
-- | The 'k' information what has no rollback
info :: k a -> Keyword k a
info = KInfo
-- | Assertion on the first value, the assertion fails if the
-- first value is False. After the failure the revering actions
-- will be computed.
assertion :: Bool -> String -> Keyword k ()
assertion = KAssert
-- | Logs a message
log :: String -> Keyword k ()
log = KLog
-- | The action consits of a computation that can fail
-- and possibly a revert action.
newtype Action m e a = Action (m (Either e a), Maybe (a -> m ()))
-- | The interpretation of a 'k' basic keyword consists of a pair
-- the first is a computation which computes an error result or a
-- unit, and a revert action of the computation.
newtype Interpretation k m e = Interpretation { unInterpret :: forall a . k a -> Action m e a }
safeAction :: (Functor m, Monad m, Error e) => m a -> Action m e a
safeAction action = Action (fmap Right action, Nothing)
safeActionRollback :: (Functor m, Monad m, Error e) => m a -> (a -> m b) -> Action m e a
safeActionRollback action rollback = Action (fmap Right action, Just (void . rollback))
-- The action has no rollback but the action can fail.
action :: (Functor m, Monad m, Error e) => m (Either e a) -> Action m e a
action act = Action (act, Nothing)
-- The action has a given rollback and the action can fail
actionRollback :: (Functor m, Monad m, Error e) => m (Either e a) -> (a -> m b) -> Action m e a
actionRollback action rollback = Action (action, Just (void . rollback))
-- | The keyword evaluation context consists of an interpretation
-- function, which turns every 'k' command into a monadic computation
data Context k m e = Context {
keywordInterpretation :: Interpretation k m e
, logInterpretation :: String -> m ()
}
newtype Interpreter m e a = KI { unKI :: CME.ErrorT e (CMS.StateT [m ()] m) a }
deriving (Monad, MonadState [m ()], MonadError e)
evalStage0 :: (Monad m, Error e) => Context k m e -> Keyword k a -> Interpreter m e a
evalStage0 ctx (KRet a) = return a
evalStage0 ctx (KInfo k) = do
let Action (step,revert) = (unInterpret $ keywordInterpretation ctx) k
x <- KI . lift $ lift step
case x of
Left e -> throwError e
Right y -> return y
evalStage0 ctx (KLog m) = KI . lift . lift $ logInterpretation ctx m
evalStage0 ctx (KWord k) = do
let Action (step,revert) = (unInterpret $ keywordInterpretation ctx) k
x <- KI . lift $ lift step
case x of
Left e -> throwError e
Right y -> do
maybe (return ()) (\r -> modify (r y:)) revert
return y
evalStage0 ctx (KBind m k) = do
x <- evalStage0 ctx m
evalStage0 ctx (k x)
evalStage0 ctx (KAssert a msg) = unless a . throwError $ strMsg msg
evalStage1 :: (Functor m, Monad m, Error e) => Interpreter m e a -> m (Either e a)
evalStage1 m = do
(result, revert) <- flip CMS.runStateT [] . CME.runErrorT $ unKI m
case result of
Left err -> do sequence_ revert
return (Left err)
Right a -> return (Right a)
-- | The 'runKeyword' interprets the given keyword in a computational context, and
-- reverts the steps if any error occurs.
runKeyword :: (Functor m, Monad m, Error e) => Context k m e -> Keyword k a -> m (Either e a)
runKeyword ctx k = evalStage1 $ evalStage0 ctx k
-- * Helpers
voide :: (Functor m, Monad m, Error e) => m a -> m (Either e ())
voide m = do m >> return (Right ())
-- * Assertions
-- | Checks if the found value equals to the expected one, if it differs
-- the test will fail
assertEquals :: (Show a, Eq a) => a -> a -> String -> Keyword k ()
assertEquals expected found msg =
assertion (found == expected) (concat [msg, " found: ", show found, " expected: ", show expected])
-- | Checks if the found value satisfies the given predicate, it not the test will fail
satisfies :: (Show a) => a -> (a -> Bool) -> String -> Keyword k ()
satisfies value pred msg =
assertion (pred value) (concat [msg, " value: ", show value, " does not satisfies the predicate."])
| andorp/themis | src/Test/Themis/Keyword.hs | bsd-3-clause | 5,287 | 0 | 17 | 1,192 | 1,737 | 899 | 838 | 93 | 3 |
module Config where
import Data.List
import HSH
-- put any custom default excluded directories or aliased filetypes here etc
sourceFiles :: [String] -> String -> IO [String]
sourceFiles ftypes dir = run ("find", dir:args) where
args = intercalate ["-or"] [["-iname", "*." ++ ftype] | ftype <- ftypes]
| facebookarchive/lex-pass | src/Config.hs | bsd-3-clause | 306 | 0 | 10 | 52 | 94 | 53 | 41 | 6 | 1 |
{-# LANGUAGE CPP, DisambiguateRecordFields, RecordWildCards, NamedFieldPuns #-}
{-# LANGUAGE BangPatterns #-}
-- | This module implements parsing and unparsing functions for
-- OpenFlow messages. It exports a driver that can be used to read messages
-- from a file handle and write messages to a handle.
module Nettle.OpenFlow.MessagesBinary (
-- messageDriver2
-- * Parsing and unparsing methods
getHeader
, getSCMessage
, getSCMessageBody
, putSCMessage
, getCSMessage
, getCSMessageBody
, putCSMessage
, OFPHeader(..)
) where
import qualified Data.ByteString as BS
import Data.ByteString (ByteString)
import Nettle.Ethernet.EthernetAddress
import Nettle.Ethernet.EthernetFrame
import Nettle.IPv4.IPAddress
import Nettle.IPv4.IPPacket
import qualified Nettle.OpenFlow.Messages as M
import Nettle.OpenFlow.Port
import Nettle.OpenFlow.Action
import Nettle.OpenFlow.Switch
import Nettle.OpenFlow.Match
import Nettle.OpenFlow.Packet
import Nettle.OpenFlow.FlowTable
import qualified Nettle.OpenFlow.FlowTable as FlowTable
import Nettle.OpenFlow.Statistics
import Nettle.OpenFlow.Error
import Control.Monad (when)
import Control.Exception
import Data.Word
import Data.Bits
import Nettle.OpenFlow.StrictPut
import Data.Binary.Strict.Get
import qualified Data.ByteString as B
import Data.Maybe (fromJust, isJust)
import Data.List as List
import Data.Char (chr)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Bimap (Bimap, (!), (!>))
import qualified Data.Bimap as Bimap
import System.IO
import Control.Concurrent (yield)
import Data.IORef
import Data.Char (ord)
import Debug.Trace
type MessageTypeCode = Word8
ofptHello :: MessageTypeCode
ofptHello = 0
ofptError :: MessageTypeCode
ofptError = 1
ofptEchoRequest :: MessageTypeCode
ofptEchoRequest = 2
ofptEchoReply :: MessageTypeCode
ofptEchoReply = 3
ofptVendor :: MessageTypeCode
ofptVendor = 4
ofptFeaturesRequest :: MessageTypeCode
ofptFeaturesRequest = 5
ofptFeaturesReply :: MessageTypeCode
ofptFeaturesReply = 6
ofptGetConfigRequest :: MessageTypeCode
ofptGetConfigRequest = 7
ofptGetConfigReply :: MessageTypeCode
ofptGetConfigReply = 8
ofptSetConfig :: MessageTypeCode
ofptSetConfig = 9
ofptPacketIn :: MessageTypeCode
ofptPacketIn = 10
ofptFlowRemoved :: MessageTypeCode
ofptFlowRemoved = 11
ofptPortStatus :: MessageTypeCode
ofptPortStatus = 12
ofptPacketOut :: MessageTypeCode
ofptPacketOut = 13
ofptFlowMod :: MessageTypeCode
ofptFlowMod = 14
ofptPortMod :: MessageTypeCode
ofptPortMod = 15
ofptStatsRequest :: MessageTypeCode
ofptStatsRequest = 16
ofptStatsReply :: MessageTypeCode
ofptStatsReply = 17
ofptBarrierRequest :: MessageTypeCode
ofptBarrierRequest = 18
ofptBarrierReply :: MessageTypeCode
ofptBarrierReply = 19
ofptQueueGetConfigRequest :: MessageTypeCode
ofptQueueGetConfigRequest = 20
ofptQueueGetConfigReply :: MessageTypeCode
ofptQueueGetConfigReply = 21
-- | Parser for @SCMessage@s
getSCMessage :: Get (M.TransactionID, M.SCMessage)
getSCMessage = do hdr <- getHeader
getSCMessageBody hdr
-- | Parser for @CSMessage@s
getCSMessage :: Get (M.TransactionID, M.CSMessage)
getCSMessage = do hdr <- getHeader
getCSMessageBody hdr
-- | Unparser for @SCMessage@s
putSCMessage :: (M.TransactionID, M.SCMessage) -> Put
putSCMessage (xid, msg) =
case msg of
M.SCHello -> putH ofptHello headerSize
M.SCEchoRequest bytes -> do putH ofptEchoRequest (headerSize + length bytes)
putWord8s bytes
M.SCEchoReply bytes -> do putH ofptEchoReply (headerSize + length bytes)
putWord8s bytes
M.PacketIn pktInfo -> do let bodyLen = packetInMessageBodyLen pktInfo
putH ofptPacketIn (headerSize + bodyLen)
putPacketInRecord pktInfo
M.Features features -> do putH ofptFeaturesReply (headerSize + 24 + 48 * length (ports features))
putSwitchFeaturesRecord features
M.Error error -> do putH ofptError (headerSize + 2 + 2)
putSwitchError error
where vid = ofpVersion
putH tcode len = putHeader (OFPHeader vid tcode (fromIntegral len) xid)
packetInMessageBodyLen :: PacketInfo -> Int
packetInMessageBodyLen pktInfo = 10 + fromIntegral (packetLength pktInfo)
putPacketInRecord :: PacketInfo -> Put
putPacketInRecord pktInfo@(PacketInfo {..}) =
do putWord32be $ maybe (-1) id bufferID
putWord16be $ fromIntegral packetLength
putWord16be receivedOnPort
putWord8 $ reason2Code reasonSent
putWord8 0
putByteString packetData
{- Header -}
type OpenFlowVersionID = Word8
ofpVersion :: OpenFlowVersionID
#if OPENFLOW_VERSION == 1
ofpVersion = 0x01
#endif
#if OPENFLOW_VERSION == 152
ofpVersion = 0x98
#endif
#if OPENFLOW_VERSION == 151
ofpVersion = 0x97
#endif
-- | OpenFlow message header
data OFPHeader =
OFPHeader { msgVersion :: !OpenFlowVersionID
, msgType :: !MessageTypeCode
, msgLength :: !Word16
, msgTransactionID :: !M.TransactionID
} deriving (Show,Eq)
headerSize :: Int
headerSize = 8
-- | Unparser for OpenFlow message header
putHeader :: OFPHeader -> Put
putHeader (OFPHeader {..}) = do putWord8 msgVersion
putWord8 msgType
putWord16be msgLength
putWord32be msgTransactionID
-- | Parser for the OpenFlow message header
getHeader :: Get OFPHeader
getHeader = do v <- getWord8
t <- getWord8
l <- getWord16be
x <- getWord32be
return $ OFPHeader v t l x
{-# INLINE getHeader #-}
-- Get SCMessage body
{-# INLINE getSCMessageBody #-}
getSCMessageBody :: OFPHeader -> Get (M.TransactionID, M.SCMessage)
getSCMessageBody hdr@(OFPHeader {..}) =
if msgType == ofptPacketIn
then do packetInRecord <- getPacketInRecord len
return (msgTransactionID, M.PacketIn packetInRecord)
else if msgType == ofptEchoRequest
then do bytes <- getWord8s (len - headerSize)
return (msgTransactionID, M.SCEchoRequest bytes)
else if msgType == ofptEchoReply
then do bytes <- getWord8s (len - headerSize)
return (msgTransactionID, M.SCEchoReply bytes)
else if msgType == ofptFeaturesReply
then do switchFeaturesRecord <- getSwitchFeaturesRecord len
return (msgTransactionID, M.Features switchFeaturesRecord)
else if msgType == ofptHello
then return (msgTransactionID, M.SCHello)
else if msgType == ofptPortStatus
then do body <- getPortStatus
return (msgTransactionID, M.PortStatus body)
else if msgType == ofptError
then do body <- getSwitchError len
return (msgTransactionID, M.Error body)
else if msgType == ofptFlowRemoved
then do body <- getFlowRemovedRecord
return (msgTransactionID, M.FlowRemoved body)
else if msgType == ofptBarrierReply
then return (msgTransactionID, M.BarrierReply)
else if msgType == ofptStatsReply
then do body <- getStatsReply len
return (msgTransactionID, M.StatsReply body)
else if msgType == ofptQueueGetConfigReply
then do qcReply <- getQueueConfigReply len
return (msgTransactionID, M.QueueConfigReply qcReply)
else error ("Unrecognized message header: " ++ show hdr)
where len = fromIntegral msgLength
getCSMessageBody :: OFPHeader -> Get (M.TransactionID, M.CSMessage)
getCSMessageBody header@(OFPHeader {..}) =
if msgType == ofptPacketOut
then do packetOut <- getPacketOut len
return (msgTransactionID, M.PacketOut packetOut)
else if msgType == ofptFlowMod
then do mod <- getFlowMod len
return (msgTransactionID, M.FlowMod mod)
else if msgType == ofptHello
then return (msgTransactionID, M.CSHello)
else if msgType == ofptEchoRequest
then do bytes <- getWord8s (len - headerSize)
return (msgTransactionID, M.CSEchoRequest bytes)
else if msgType == ofptEchoReply
then do bytes <- getWord8s (len - headerSize)
return (msgTransactionID, M.CSEchoReply bytes)
else if msgType == ofptFeaturesRequest
then return (msgTransactionID, M.FeaturesRequest)
else if msgType == ofptSetConfig
then do _ <- getSetConfig
return (msgTransactionID, M.SetConfig)
else if msgType == ofptVendor
then do vMsg <- getVendorMessage
return (msgTransactionID, M.Vendor vMsg)
else error ("Unrecognized message type with header: " ++ show header)
where len = fromIntegral msgLength
-----------------------
-- Queue Config parser
-----------------------
getQueueConfigReply :: Int -> Get QueueConfigReply
getQueueConfigReply len =
do portID <- getWord16be
skip 6
qs <- getQueues 16 []
return (PortQueueConfig portID qs)
where
getQueues pos acc =
if pos < len
then do (q, n) <- getQueue
let pos' = pos + n
pos' `seq` getQueues pos' (q:acc)
else return acc
getQueue =
do qid <- getWord32be
qdlen <- getWord16be
skip 2
qprops <- getQueueProps qdlen 8 [] -- at byte 8 because of ofp_packet_queue header and len includes header (my guess).
return (QueueConfig qid qprops, fromIntegral qdlen)
where
getQueueProps qdlen pos acc =
if pos < qdlen
then do (prop, propLen) <- getQueueProp
let pos' = pos + propLen
pos' `seq` getQueueProps qdlen pos' (prop : acc)
else return acc
getQueueProp =
do propType <- getWord16be
propLen <- getWord16be
skip 4
rate <- getWord16be
skip 6
let rate' = if rate > 1000 then Disabled else Enabled rate
let prop
| propType == ofpqtMinRate = MinRateQueue rate'
| propType == ofpqtMaxRate = MaxRateQueue rate'
| otherwise = error ("Unexpected queue property type code " ++ show propType)
return (prop, propLen)
ofpqtMinRate :: Word16
ofpqtMinRate = 1
ofpqtMaxRate :: Word16 -- Indigo switches support max rate this way
ofpqtMaxRate = 2
----------------------
-- Set Config parser
----------------------
getSetConfig :: Get (Word16, Word16)
getSetConfig = do flags <- getWord16be
missSendLen <- getWord16be
return (flags, missSendLen)
-------------------------------------------
-- Vendor parser
-------------------------------------------
getVendorMessage :: Get ByteString
getVendorMessage = do
r <- remaining
getByteString r
-------------------------------------------
-- SWITCH FEATURES PARSER
-------------------------------------------
putSwitchFeaturesRecord (SwitchFeatures {..}) = do
putWord64be switchID
putWord32be $ fromIntegral packetBufferSize
putWord8 $ fromIntegral numberFlowTables
sequence_ $ replicate 3 (putWord8 0)
putWord32be $ switchCapabilitiesBitVector capabilities
putWord32be $ actionTypesBitVector supportedActions
sequence_ [ putPhyPort p | p <- ports ]
getSwitchFeaturesRecord len = do
dpid <- getWord64be
nbufs <- getWord32be
ntables <- getWord8
skip 3
caps <- getWord32be
acts <- getWord32be
ports <- sequence (replicate num_ports getPhyPort)
return (SwitchFeatures dpid (fromIntegral nbufs) (fromIntegral ntables) (bitMap2SwitchCapabilitySet caps) (bitMap2SwitchActionSet acts) ports)
where ports_offset = 32
num_ports = (len - ports_offset) `div` size_ofp_phy_port
size_ofp_phy_port = 48
putPhyPort :: Port -> Put
putPhyPort (Port {..}) =
do putWord16be portID
putEthernetAddress portAddress
mapM_ putWord8 $ take ofpMaxPortNameLen (map (fromIntegral . ord) portName ++ repeat 0)
putWord32be $ portConfigsBitVector portConfig
putWord32be $ portState2Code portLinkDown portSTPState
putWord32be $ featuresBitVector $ maybe [] id portCurrentFeatures
putWord32be $ featuresBitVector $ maybe [] id portAdvertisedFeatures
putWord32be $ featuresBitVector $ maybe [] id portSupportedFeatures
putWord32be $ featuresBitVector $ maybe [] id portPeerFeatures
getPhyPort :: Get Port
getPhyPort = do
port_no <- getWord16be
hw_addr <- getEthernetAddress
name_arr <- getWord8s ofpMaxPortNameLen
let port_name = [ chr (fromIntegral b) | b <- takeWhile (/=0) name_arr ]
cfg <- getWord32be
st <- getWord32be
let (linkDown, stpState) = code2PortState st
curr <- getWord32be
adv <- getWord32be
supp <- getWord32be
peer <- getWord32be
return $ Port { portID = port_no,
portName = port_name,
portAddress = hw_addr,
portConfig = bitMap2PortConfigAttributeSet cfg,
portLinkDown = linkDown,
portSTPState = stpState,
portCurrentFeatures = decodePortFeatureSet curr,
portAdvertisedFeatures = decodePortFeatureSet adv,
portSupportedFeatures = decodePortFeatureSet supp,
portPeerFeatures = decodePortFeatureSet peer
}
ofpMaxPortNameLen = 16
featuresBitVector :: [PortFeature] -> Word32
featuresBitVector = foldl (\v f -> v .|. featureBitMask f) 0
featureBitMask :: PortFeature -> Word32
featureBitMask feat =
case lookup feat featurePositions of
Nothing -> error "unexpected port feature"
Just i -> bit i
decodePortFeatureSet :: Word32 -> Maybe [PortFeature]
decodePortFeatureSet word
| word == 0 = Nothing
| otherwise = Just $ concat [ if word `testBit` position then [feat] else [] | (feat, position) <- featurePositions ]
featurePositions :: [(PortFeature, Int)]
featurePositions = [ (Rate10MbHD, 0),
(Rate10MbFD, 1),
(Rate100MbHD, 2),
(Rate100MbFD, 3),
(Rate1GbHD, 4),
(Rate1GbFD, 5),
(Rate10GbFD, 6),
(Copper, 7),
(Fiber, 8),
(AutoNegotiation, 9),
(Pause, 10),
(AsymmetricPause, 11) ]
ofppsLinkDown, ofppsStpListen, ofppsStpLearn, ofppsStpForward :: Word32
ofppsLinkDown = 1 `shiftL` 0 -- 1 << 0
ofppsStpListen = 0 `shiftL` 8 -- 0 << 8
ofppsStpLearn = 1 `shiftL` 8 -- 1 << 8
ofppsStpForward = 2 `shiftL` 8 -- 2 << 8
ofppsStpBlock = 3 `shiftL` 8 -- 3 << 8
ofppsStpMask = 3 `shiftL` 8 -- 3 << 8
code2PortState :: Word32 -> (Bool, SpanningTreePortState)
code2PortState w = (w .&. ofppsLinkDown /= 0, stpState)
where stpState
| flag == ofppsStpListen = STPListening
| flag == ofppsStpLearn = STPLearning
| flag == ofppsStpForward = STPForwarding
| flag == ofppsStpBlock = STPBlocking
| otherwise = error "Unrecognized port status code."
flag = w .&. ofppsStpMask
portState2Code :: Bool -> SpanningTreePortState -> Word32
portState2Code isUp stpState =
let b1 = if isUp then ofppsLinkDown else 0
b2 = case stpState of
STPListening -> ofppsStpListen
STPLearning -> ofppsStpLearn
STPForwarding -> ofppsStpForward
STPBlocking -> ofppsStpBlock
in b1 .|. b2
bitMap2PortConfigAttributeSet :: Word32 -> [PortConfigAttribute]
bitMap2PortConfigAttributeSet bmap = filter inBMap $ enumFrom $ toEnum 0
where inBMap attr = let mask = portAttribute2BitMask attr
in mask .&. bmap == mask
portConfigsBitVector :: [PortConfigAttribute] -> Word32
portConfigsBitVector = foldl (\v a -> v .|. portAttribute2BitMask a) 0
portAttribute2BitMask :: PortConfigAttribute -> Word32
portAttribute2BitMask PortDown = shiftL 1 0
portAttribute2BitMask STPDisabled = shiftL 1 1
portAttribute2BitMask OnlySTPackets = shiftL 1 2
portAttribute2BitMask NoSTPackets = shiftL 1 3
portAttribute2BitMask NoFlooding = shiftL 1 4
portAttribute2BitMask DropForwarded = shiftL 1 5
portAttribute2BitMask NoPacketInMsg = shiftL 1 6
portAttributeSet2BitMask :: [PortConfigAttribute] -> Word32
portAttributeSet2BitMask = foldl f 0
where f mask b = mask .|. portAttribute2BitMask b
bitMap2SwitchCapabilitySet :: Word32 -> [SwitchCapability]
bitMap2SwitchCapabilitySet bmap = filter inBMap $ enumFrom $ toEnum 0
where inBMap attr = let mask = switchCapability2BitMask attr
in mask .&. bmap == mask
switchCapabilitiesBitVector :: [SwitchCapability] -> Word32
switchCapabilitiesBitVector =
foldl (\vector c -> vector .|. switchCapability2BitMask c) 0
switchCapability2BitMask :: SwitchCapability -> Word32
switchCapability2BitMask HasFlowStats = shiftL 1 0
switchCapability2BitMask HasTableStats = shiftL 1 1
switchCapability2BitMask HasPortStats = shiftL 1 2
switchCapability2BitMask SpanningTree = shiftL 1 3
-- #if OPENFLOW_VERSION==151 || OPENFLOW_VERSION==152
switchCapability2BitMask MayTransmitOverMultiplePhysicalInterfaces = shiftL 1 4
-- #endif
switchCapability2BitMask CanReassembleIPFragments = shiftL 1 5
-- #if OPENFLOW_VERSION==1
switchCapability2BitMask HasQueueStatistics = shiftL 1 6
switchCapability2BitMask CanMatchIPAddressesInARPPackets = shiftL 1 7
-- #endif
bitMap2SwitchActionSet :: Word32 -> [ActionType]
bitMap2SwitchActionSet bmap = filter inBMap $ enumFrom $ toEnum 0
where inBMap attr = let mask = actionType2BitMask attr
in mask .&. bmap == mask
actionTypesBitVector :: [ActionType] -> Word32
actionTypesBitVector = foldl (\v a -> v .|. actionType2BitMask a) 0
{-
code2ActionType :: Word16 -> ActionType
code2ActionType code =
case Bimap.lookupR code $ actionType2CodeBijection of
Just x -> x
Nothing -> error ("In code2ActionType: encountered unknown action type code: " ++ show code)
-}
code2ActionType :: Word16 -> ActionType
code2ActionType !code =
case code of
0 -> OutputToPortType
1 -> SetVlanVIDType
2 -> SetVlanPriorityType
3 -> StripVlanHeaderType
4 -> SetEthSrcAddrType
5 -> SetEthDstAddrType
6 -> SetIPSrcAddrType
7 -> SetIPDstAddrType
8 -> SetIPTypeOfServiceType
9 -> SetTransportSrcPortType
10 -> SetTransportDstPortType
11 -> EnqueueType
0xffff -> VendorActionType
{-# INLINE code2ActionType #-}
actionType2Code :: ActionType -> Word16
actionType2Code OutputToPortType = 0
actionType2Code SetVlanVIDType = 1
actionType2Code SetVlanPriorityType = 2
actionType2Code StripVlanHeaderType = 3
actionType2Code SetEthSrcAddrType = 4
actionType2Code SetEthDstAddrType = 5
actionType2Code SetIPSrcAddrType = 6
actionType2Code SetIPDstAddrType = 7
actionType2Code SetIPTypeOfServiceType = 8
actionType2Code SetTransportSrcPortType = 9
actionType2Code SetTransportDstPortType = 10
actionType2Code EnqueueType = 11
actionType2Code VendorActionType = 0xffff
{-# INLINE actionType2Code #-}
{-
actionType2Code a =
case Bimap.lookup a actionType2CodeBijection of
Just x -> x
Nothing -> error ("In actionType2Code: encountered unknown action type: " ++ show a)
-}
actionType2CodeBijection :: Bimap ActionType Word16
actionType2CodeBijection =
Bimap.fromList [(OutputToPortType, 0)
, (SetVlanVIDType, 1)
, (SetVlanPriorityType, 2)
, (StripVlanHeaderType, 3)
, (SetEthSrcAddrType, 4)
, (SetEthDstAddrType, 5)
, (SetIPSrcAddrType, 6)
, (SetIPDstAddrType, 7)
, (SetIPTypeOfServiceType, 8)
, (SetTransportSrcPortType, 9)
, (SetTransportDstPortType, 10)
, (EnqueueType, 11)
, (VendorActionType, 0xffff)
]
actionType2BitMask :: ActionType -> Word32
actionType2BitMask = shiftL 1 . fromIntegral . actionType2Code
------------------------------------------
-- Packet In Parser
------------------------------------------
{-# INLINE getPacketInRecord #-}
getPacketInRecord :: Int -> Get PacketInfo
getPacketInRecord len = do
bufID <- getWord32be
totalLen <- getWord16be
in_port <- getWord16be
reasonCode <- getWord8
skip 1
bytes <- getByteString (fromIntegral data_len)
let reason = code2Reason reasonCode
let mbufID = if (bufID == maxBound) then Nothing else Just bufID
let frame = {-# SCC "getPacketInRecord1" #-} fst (runGet getEthernetFrame bytes)
return $ PacketInfo mbufID (fromIntegral totalLen) in_port reason bytes frame
where data_offset = 18 -- 8 + 4 + 2 + 2 + 1 + 1
data_len = len - data_offset
{-# INLINE code2Reason #-}
code2Reason :: Word8 -> PacketInReason
code2Reason !code
| code == 0 = NotMatched
| code == 1 = ExplicitSend
| otherwise = error ("Received unknown packet-in reason code: " ++ show code ++ ".")
{-# INLINE reason2Code #-}
reason2Code :: PacketInReason -> Word8
reason2Code NotMatched = 0
reason2Code ExplicitSend = 1
------------------------------------------
-- Port Status parser
------------------------------------------
getPortStatus :: Get PortStatus
getPortStatus = do
reasonCode <- getWord8
skip 7
portDesc <- getPhyPort
return $ (code2PortStatusUpdateReason reasonCode, portDesc)
code2PortStatusUpdateReason code =
if code == 0
then PortAdded
else if code == 1
then PortDeleted
else if code == 2
then PortModified
else error ("Unkown port status update reason code: " ++ show code)
------------------------------------------
-- Switch Error parser
------------------------------------------
getSwitchError :: Int -> Get SwitchError
getSwitchError len = do
typ <- getWord16be
code <- getWord16be
bytes <- getWord8s (len - headerSize - 4)
return (code2ErrorType typ code bytes)
putSwitchError :: SwitchError -> Put
putSwitchError (BadRequest VendorNotSupported []) =
do putWord16be 1
putWord16be 3
code2ErrorType :: Word16 -> Word16 -> [Word8] -> SwitchError
#if OPENFLOW_VERSION==151
code2ErrorType typ code bytes
| typ == 0 = HelloFailed (helloErrorCodesMap ! code) [ chr (fromIntegral b) | b <- takeWhile (/=0) bytes ]
| typ == 1 = BadRequest (requestErrorCodeMap ! code) bytes
| typ == 2 = BadAction code bytes
| typ == 3 = FlowModFailed code bytes
#endif
#if OPENFLOW_VERSION==152
code2ErrorType typ code bytes
| typ == 0 = HelloFailed (helloErrorCodesMap ! code) [ chr (fromIntegral b) | b <- takeWhile (/=0) bytes ]
| typ == 1 = BadRequest (requestErrorCodeMap ! code) bytes
| typ == 2 = BadAction (actionErrorCodeMap ! code) bytes
| typ == 3 = FlowModFailed (flowModErrorCodeMap ! code) bytes
#endif
#if OPENFLOW_VERSION==1
code2ErrorType typ code bytes
| typ == 0 = HelloFailed (helloErrorCodesMap ! code) [ chr (fromIntegral b) | b <- takeWhile (/=0) bytes ]
| typ == 1 = BadRequest (requestErrorCodeMap ! code) bytes
| typ == 2 = BadAction (actionErrorCodeMap ! code) bytes
| typ == 3 = FlowModFailed (flowModErrorCodeMap ! code) bytes
| typ == 4 = PortModFailed (portModErrorCodeMap ! code) bytes
| typ == 5 = QueueOperationFailed (queueOpErrorCodeMap ! code) bytes
#endif
helloErrorCodesMap = Bimap.fromList [ (0, IncompatibleVersions)
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
, (1 , HelloPermissionsError)
#endif
]
requestErrorCodeMap = Bimap.fromList [ (0, VersionNotSupported),
(1 , MessageTypeNotSupported),
(2 , StatsRequestTypeNotSupported),
(3 , VendorNotSupported),
(4, VendorSubtypeNotSupported)
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
, (5 , RequestPermissionsError)
#endif
#if OPENFLOW_VERSION==1
, (6 , BadRequestLength)
, (7, BufferEmpty)
, (8, UnknownBuffer)
#endif
]
actionErrorCodeMap = Bimap.fromList [ (0, UnknownActionType),
(1, BadActionLength),
(2, UnknownVendorID),
(3, UnknownActionTypeForVendor),
(4, BadOutPort),
(5, BadActionArgument)
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
, (6, ActionPermissionsError)
#endif
#if OPENFLOW_VERSION==1
, (7, TooManyActions)
, (8, InvalidQueue)
#endif
]
flowModErrorCodeMap = Bimap.fromList [ (0, TablesFull)
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
, (1, OverlappingFlow)
, (2, FlowModPermissionsError)
, (3, EmergencyModHasTimeouts)
#endif
#if OPENFLOW_VERSION==1
, (4, BadCommand)
, (5, UnsupportedActionList)
#endif
]
portModErrorCodeMap = Bimap.fromList [ (0, BadPort)
, (1, BadHardwareAddress)
]
queueOpErrorCodeMap = Bimap.fromList [ (0, QueueOpBadPort)
, (1, QueueDoesNotExist)
, (2, QueueOpPermissionsError)
]
------------------------------------------
-- FlowRemoved parser
------------------------------------------
#if OPENFLOW_VERSION==151
getFlowRemovedRecord :: Get FlowRemoved
getFlowRemovedRecord = do
m <- getMatch
p <- get
rcode <- get
skip 1
dur <- getWord32be
skip 4
pktCount <- getWord64be
byteCount <- getWord64be
return $ FlowRemoved m p (code2FlowRemovalReason rcode) (fromIntegral dur) (fromIntegral pktCount) (fromIntegral byteCount)
#endif
#if OPENFLOW_VERSION==152
getFlowRemovedRecord :: Get FlowRemoved
getFlowRemovedRecord = do
m <- getMatch
p <- getWord16be
rcode <- getWord8
skip 1
dur <- getWord32be
idle_timeout <- getWord16be
skip 6
pktCount <- getWord64be
byteCount <- getWord64be
return $ FlowRemoved m p (code2FlowRemovalReason rcode) (fromIntegral dur) (fromIntegral idle_timeout) (fromIntegral pktCount) (fromIntegral byteCount)
#endif
#if OPENFLOW_VERSION==1
getFlowRemovedRecord :: Get FlowRemoved
getFlowRemovedRecord = do
m <- getMatch
cookie <- getWord64be
p <- getWord16be
rcode <- getWord8
skip 1
dur <- getWord32be
dur_nsec <- getWord32be
idle_timeout <- getWord16be
skip 2
pktCount <- getWord64be
byteCount <- getWord64be
return $ FlowRemovedRecord m cookie p (code2FlowRemovalReason rcode) (fromIntegral dur) (fromIntegral dur_nsec) (fromIntegral idle_timeout) (fromIntegral pktCount) (fromIntegral byteCount)
#endif
#if OPENFLOW_VERSION==151
flowRemovalReason2CodeBijection :: Bimap FlowRemovalReason Word8
flowRemovalReason2CodeBijection =
Bimap.fromList [(IdleTimerExpired, 0),
(HardTimerExpired, 1) ]
#endif
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
flowRemovalReason2CodeBijection :: Bimap FlowRemovalReason Word8
flowRemovalReason2CodeBijection =
Bimap.fromList [(IdleTimerExpired, 0),
(HardTimerExpired, 1),
(DeletedByController, 2) ]
#endif
code2FlowRemovalReason rcode = (Bimap.!>) flowRemovalReason2CodeBijection rcode
-----------------------------------------
-- Stats Reply parser
-----------------------------------------
getStatsReply :: Int -> Get StatsReply
getStatsReply headerLen = do
statsType <- getWord16be
flags <- getWord16be
let bodyLen = headerLen - (headerSize + 4)
let moreFlag = flags == 0x0001
if statsType == ofpstFlow
then do flowStats <- getFlowStatsReplies bodyLen
return (FlowStatsReply moreFlag flowStats)
else if statsType == ofpstPort
then do portStats <- getPortStatsReplies bodyLen
return (PortStatsReply moreFlag portStats)
else if statsType == ofpstAggregate
then do aggStats <- getAggregateStatsReplies bodyLen
return (AggregateFlowStatsReply aggStats)
else if statsType == ofpstTable
then do tableStats <- getTableStatsReplies bodyLen
return (TableStatsReply moreFlag tableStats)
else if statsType == ofpstDesc
then do desc <- getDescriptionReply
return (DescriptionReply desc)
else
#if OPENFLOW_VERSION==1
if statsType == ofpstQueue
then do queueStats <- getQueueStatsReplies bodyLen
return (QueueStatsReply moreFlag queueStats)
else
#endif
error ("unhandled stats reply message with type: " ++ show statsType)
#if OPENFLOW_VERSION==1
getQueueStatsReplies :: Int -> Get [QueueStats]
getQueueStatsReplies bodyLen = do
sequence (replicate cnt getQueueStatsReply)
where cnt = let (d,m) = bodyLen `divMod` queueStatsLength
in if m == 0
then d
else error ("Body of queue stats reply must be a multiple of " ++ show queueStatsLength)
queueStatsLength = 32
getQueueStatsReply = do
portNo <- getWord16be
skip 2
qid <- getWord32be
tx_bytes <- getWord64be
tx_packets <- getWord64be
tx_errs <- getWord64be
return (QueueStats { queueStatsPortID = portNo,
queueStatsQueueID = qid,
queueStatsTransmittedBytes = fromIntegral tx_bytes,
queueStatsTransmittedPackets = fromIntegral tx_packets,
queueStatsTransmittedErrors = fromIntegral tx_errs })
#endif
getDescriptionReply :: Get Description
getDescriptionReply = do
mfr <- getCharsRightPadded descLen
hw <- getCharsRightPadded descLen
sw <- getCharsRightPadded descLen
serial <- getCharsRightPadded descLen
dp <- getCharsRightPadded serialNumLen
return ( Description { manufacturerDesc = mfr
, hardwareDesc = hw
, softwareDesc = sw
, serialNumber = serial
#if OPENFLOW_VERSION==1
, datapathDesc = dp
#endif
} )
where descLen = 256
serialNumLen = 32
getCharsRightPadded :: Int -> Get String
getCharsRightPadded n = do
bytes <- getWord8s n
return [ chr (fromIntegral b) | b <- takeWhile (/=0) bytes]
getTableStatsReplies :: Int -> Get [TableStats]
getTableStatsReplies bodyLen = sequence (replicate cnt getTableStatsReply)
where cnt = let (d,m) = bodyLen `divMod` tableStatsLength
in if m == 0
then d
else error ("Body of Table stats reply must be a multiple of " ++ show tableStatsLength)
tableStatsLength = 64
getTableStatsReply :: Get TableStats
getTableStatsReply = do
tableID <- getWord8
skip 3
name_bytes <- getWord8s maxTableNameLen
let name = [ chr (fromIntegral b) | b <- name_bytes ]
wcards <- getWord32be
maxEntries <- getWord32be
activeCount <- getWord32be
lookupCount <- getWord64be
matchedCount <- getWord64be
return ( TableStats { tableStatsTableID = tableID,
tableStatsTableName = name,
tableStatsMaxEntries = fromIntegral maxEntries,
tableStatsActiveCount = fromIntegral activeCount,
tableStatsLookupCount = fromIntegral lookupCount,
tableStatsMatchedCount = fromIntegral matchedCount } )
where maxTableNameLen = 32
getFlowStatsReplies :: Int -> Get [FlowStats]
getFlowStatsReplies bodyLen
| bodyLen == 0 = return []
| otherwise = do (fs,fsLen) <- getFlowStatsReply
rest <- getFlowStatsReplies (bodyLen - fsLen)
return (fs : rest)
getFlowStatsReply :: Get (FlowStats, Int)
getFlowStatsReply = do len <- getWord16be
tid <- getWord8
skip 1
match <- getMatch
dur_sec <- getWord32be
#if OPENFLOW_VERSION==1
dur_nanosec <- getWord32be
#endif
priority <- getWord16be
idle_to <- getWord16be
hard_to <- getWord16be
#if OPENFLOW_VERSION==151
skip 6
#endif
#if OPENFLOW_VERSION==152
skip 2
#endif
#if OPENFLOW_VERSION==1
skip 6
cookie <- getWord64be
#endif
packet_count <- getWord64be
byte_count <- getWord64be
let numActions = (fromIntegral len - flowStatsReplySize) `div` actionSize
actions <- sequence (replicate numActions getAction)
let stats = FlowStats { flowStatsTableID = tid,
flowStatsMatch = match,
flowStatsDurationSeconds = fromIntegral dur_sec,
#if OPENFLOW_VERSION==1
flowStatsDurationNanoseconds = fromIntegral dur_nanosec,
#endif
flowStatsPriority = priority,
flowStatsIdleTimeout = fromIntegral idle_to,
flowStatsHardTimeout = fromIntegral hard_to,
#if OPENFLOW_VERSION==1
flowStatsCookie = cookie,
#endif
flowStatsPacketCount = fromIntegral packet_count,
flowStatsByteCount = fromIntegral byte_count,
flowStatsActions = actions }
return (stats, fromIntegral len)
where actionSize = 8
#if OPENFLOW_VERSION==151 || OPENFLOW_VERSION==152
flowStatsReplySize = 72
#endif
#if OPENFLOW_VERSION==1
flowStatsReplySize = 88
#endif
getAction :: Get Action
getAction = do
action_type <- getWord16be
action_len <- getWord16be
getActionForType (code2ActionType action_type) action_len
getActionForType :: ActionType -> Word16 -> Get Action
getActionForType OutputToPortType _ =
do port <- getWord16be
max_len <- getWord16be
return (SendOutPort (action port max_len))
where action !port !max_len
| port <= 0xff00 = PhysicalPort port
| port == ofppInPort = InPort
| port == ofppFlood = Flood
| port == ofppAll = AllPhysicalPorts
| port == ofppController = ToController max_len
| port == ofppTable = WithTable
{-# INLINE action #-}
getActionForType SetVlanVIDType _ =
do vlanid <- getWord16be
skip 2
return (SetVlanVID vlanid)
getActionForType SetVlanPriorityType _ =
do pcp <- getWord8
skip 3
return (SetVlanPriority pcp)
getActionForType StripVlanHeaderType _ =
do skip 4
return StripVlanHeader
getActionForType SetEthSrcAddrType _ =
do addr <- getEthernetAddress
skip 6
return (SetEthSrcAddr addr)
getActionForType SetEthDstAddrType _ =
do addr <- getEthernetAddress
skip 6
return (SetEthDstAddr addr)
getActionForType SetIPSrcAddrType _ =
do addr <- getIPAddress
return (SetIPSrcAddr addr)
getActionForType SetIPDstAddrType _ =
do addr <- getIPAddress
return (SetIPDstAddr addr)
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
getActionForType SetIPTypeOfServiceType _ =
do tos <- getWord8
skip 3
return (SetIPToS tos)
#endif
getActionForType SetTransportSrcPortType _ =
do port <- getWord16be
return (SetTransportSrcPort port)
getActionForType SetTransportDstPortType _ =
do port <- getWord16be
return (SetTransportDstPort port)
#if OPENFLOW_VERSION==1
getActionForType EnqueueType _ =
do port <- getWord16be
skip 6
qid <- getWord32be
return (Enqueue port qid)
getActionForType VendorActionType action_len =
do vendorid <- getWord32be
bytes <- getWord8s (fromIntegral action_len - 2 - 2 - 4)
return (VendorAction vendorid bytes)
#endif
getAggregateStatsReplies :: Int -> Get AggregateFlowStats
getAggregateStatsReplies bodyLen = do
pkt_cnt <- getWord64be
byte_cnt <- getWord64be
flow_cnt <- getWord32be
skip 4
return (AggregateFlowStats (fromIntegral pkt_cnt) (fromIntegral byte_cnt) (fromIntegral flow_cnt))
getPortStatsReplies :: Int -> Get [(PortID,PortStats)]
getPortStatsReplies bodyLen = sequence (replicate numPorts getPortStatsReply)
where numPorts = bodyLen `div` portStatsSize
portStatsSize = 104
getPortStatsReply :: Get (PortID, PortStats)
getPortStatsReply = do port_no <- getWord16be
skip 6
rx_packets <- getWord64be
tx_packets <- getWord64be
rx_bytes <- getWord64be
tx_bytes <- getWord64be
rx_dropped <- getWord64be
tx_dropped <- getWord64be
rx_errors <- getWord64be
tx_errors <- getWord64be
rx_frame_err <- getWord64be
rx_over_err <- getWord64be
rx_crc_err <- getWord64be
collisions <- getWord64be
return $ (port_no,
PortStats {
portStatsReceivedPackets = checkValid rx_packets,
portStatsSentPackets = checkValid tx_packets,
portStatsReceivedBytes = checkValid rx_bytes,
portStatsSentBytes = checkValid tx_bytes,
portStatsReceiverDropped = checkValid rx_dropped,
portStatsSenderDropped = checkValid tx_dropped,
portStatsReceiveErrors = checkValid rx_errors,
portStatsTransmitError = checkValid tx_errors,
portStatsReceivedFrameErrors = checkValid rx_frame_err,
portStatsReceiverOverrunError = checkValid rx_over_err,
portStatsReceiverCRCError = checkValid rx_crc_err,
portStatsCollisions = checkValid collisions }
)
where checkValid :: Word64 -> Maybe Double
checkValid x = if x == -1
then Nothing
else Just (fromIntegral x)
----------------------------------------------
-- Unparsers for CSMessages
----------------------------------------------
-- | Unparser for @CSMessage@s
putCSMessage :: (M.TransactionID, M.CSMessage) -> Put
putCSMessage (xid, msg) =
case msg of
M.FlowMod mod -> do let mod'@(FlowModRecordInternal {..}) = flowModToFlowModInternal mod
putH ofptFlowMod (flowModSizeInBytes' actions')
putFlowMod mod'
M.PacketOut packetOut -> {-# SCC "putCSMessage1" #-}
do putH ofptPacketOut (sendPacketSizeInBytes packetOut)
putSendPacket packetOut
M.CSHello -> putH ofptHello headerSize
M.CSEchoRequest bytes -> do putH ofptEchoRequest (headerSize + length bytes)
putWord8s bytes
M.CSEchoReply bytes -> do putH ofptEchoReply (headerSize + length bytes)
putWord8s bytes
M.FeaturesRequest -> putH ofptFeaturesRequest headerSize
M.PortMod portModRecord -> do putH ofptPortMod portModLength
putPortMod portModRecord
M.BarrierRequest -> do putH ofptBarrierRequest headerSize
M.StatsRequest request -> do putH ofptStatsRequest (statsRequestSize request)
putStatsRequest request
M.GetQueueConfig request -> do putH ofptQueueGetConfigRequest 12
putQueueConfigRequest request
M.ExtQueueModify p qCfgs -> do
putH ofptVendor (headerSize + 16 + sum (map lenQueueConfig qCfgs))
putWord32be 0x000026e1 -- OPENFLOW_VENDOR_ID
putWord32be 0 -- OFP_EXT_QUEUE_MODIFY
putWord16be p
putWord32be 0 >> putWord16be 0
mapM_ putQueueConfig qCfgs
M.ExtQueueDelete p qCfgs -> do
putH ofptVendor (headerSize + 16 + sum(map lenQueueConfig qCfgs))
putWord32be 0x000026e1 -- OPENFLOW_VENDOR_ID
putWord32be 1 -- OFP_EXT_QUEUE_DELETE
putWord16be p
putWord32be 0 >> putWord16be 0
mapM_ putQueueConfig qCfgs
M.Vendor bytes -> do
putH ofptVendor (headerSize + BS.length bytes)
putByteString bytes
where vid = ofpVersion
putH tcode len = putHeader (OFPHeader vid tcode (fromIntegral len) xid)
{-# INLINE putCSMessage #-}
putQueueConfigRequest :: QueueConfigRequest -> Put
putQueueConfigRequest (QueueConfigRequest portID) =
do putWord16be portID
putWord16be 0 --padding
------------------------------------------
-- Unparser for packet out message
------------------------------------------
sendPacketSizeInBytes :: PacketOut -> Int
sendPacketSizeInBytes (PacketOutRecord bufferIDData _ actions) =
headerSize + 4 + 2 + 2 + sum (map actionSizeInBytes actions) + fromIntegral (either (const 0) B.length bufferIDData)
{-# INLINE putSendPacket #-}
putSendPacket :: PacketOut -> Put
putSendPacket (PacketOutRecord {..}) = do
{-# SCC "putSendPacket1" #-} putWord32be $ either id (const (-1)) bufferIDData
{-# SCC "putSendPacket2" #-} putWord16be (maybe ofppNone id packetInPort)
{-# SCC "putSendPacket3" #-} putWord16be (fromIntegral actionArraySize)
{-# SCC "putSendPacket4" #-} mapM_ putAction packetActions
{-# SCC "putSendPacket5" #-} either (const $ return ()) putByteString bufferIDData
where actionArraySize = {-# SCC "putSendPacket6" #-} sum $ map actionSizeInBytes packetActions
getPacketOut :: Int -> Get PacketOut
getPacketOut len = do
bufID' <- getWord32be
port' <- getWord16be
actionArraySize' <- getWord16be
actions <- getActionsOfSize (fromIntegral actionArraySize')
x <- remaining
packetData <- if bufID' == -1
then let bytesOfData = len - headerSize - 4 - 2 - 2 - fromIntegral actionArraySize'
in getByteString (fromIntegral bytesOfData)
else return B.empty
return $ PacketOutRecord { bufferIDData = if bufID' == -1
then Right packetData
else Left bufID'
, packetInPort = if port' == ofppNone then Nothing else Just port'
, packetActions = actions
}
getActionsOfSize :: Int -> Get [Action]
getActionsOfSize n
| n > 0 = do a <- getAction
as <- getActionsOfSize (n - actionSizeInBytes a)
return (a : as)
| n == 0 = return []
| n < 0 = error "bad number of actions or bad action size"
{-# INLINE getActionsOfSize #-}
------------------------------------------
-- Unparser for flow mod message
------------------------------------------
#if OPENFLOW_VERSION==151
flowModSizeInBytes' :: [Action] -> Int
flowModSizeInBytes' actions =
headerSize + matchSize + 20 + sum (map actionSizeInBytes actions)
#endif
#if OPENFLOW_VERSION==152
flowModSizeInBytes' :: [Action] -> Int
flowModSizeInBytes' actions =
headerSize + matchSize + 20 + sum (map actionSizeInBytes actions)
#endif
#if OPENFLOW_VERSION==1
flowModSizeInBytes' :: [Action] -> Int
flowModSizeInBytes' actions =
headerSize + matchSize + 24 + sum (map actionSizeInBytes actions)
#endif
data FlowModRecordInternal = FlowModRecordInternal {
command' :: FlowModType
, match' :: Match
, actions' :: [Action]
, priority' :: Priority
, idleTimeOut' :: Maybe TimeOut
, hardTimeOut' :: Maybe TimeOut
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
, flags' :: [FlowModFlag]
#endif
, bufferID' :: Maybe BufferID
, outPort' :: Maybe PseudoPort
#if OPENFLOW_VERSION==1
, cookie' :: Cookie
#endif
} deriving (Eq,Show)
-- | Specification: @ofp_flow_mod_command@.
data FlowModType
= FlowAddType
| FlowModifyType
| FlowModifyStrictType
| FlowDeleteType
| FlowDeleteStrictType
deriving (Show,Eq,Ord)
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
-- | A set of flow mod attributes can be added to a flow modification command.
data FlowModFlag = SendFlowRemoved | CheckOverlap | Emergency deriving (Show,Eq,Ord,Enum)
#endif
flowModToFlowModInternal :: FlowMod -> FlowModRecordInternal
flowModToFlowModInternal (DeleteFlows {..}) =
FlowModRecordInternal {match' = match,
#if OPENFLOW_VERSION==1
cookie' = 0,
#endif
command' = FlowDeleteType,
idleTimeOut' = Nothing,
hardTimeOut' = Nothing,
priority' = 0,
bufferID' = Nothing,
outPort' = outPort,
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
flags' = [],
#endif
actions' = []
}
flowModToFlowModInternal (DeleteExactFlow {..}) =
FlowModRecordInternal {match' = match,
#if OPENFLOW_VERSION==1
cookie' = 0,
#endif
command' = FlowDeleteStrictType,
idleTimeOut' = Nothing,
hardTimeOut' = Nothing,
priority' = priority,
bufferID' = Nothing,
outPort' = outPort,
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
flags' = [],
#endif
actions' = []
}
flowModToFlowModInternal (AddFlow {..}) =
FlowModRecordInternal { match' = match,
#if OPENFLOW_VERSION==1
cookie' = cookie,
#endif
command' = FlowAddType,
idleTimeOut' = Just idleTimeOut,
hardTimeOut' = Just hardTimeOut,
priority' = priority,
bufferID' = applyToPacket,
outPort' = Nothing,
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
flags' = concat [ if not overlapAllowed then [CheckOverlap] else [],
if notifyWhenRemoved then [SendFlowRemoved] else []] ,
#endif
actions' = actions
}
flowModToFlowModInternal (AddEmergencyFlow {..}) =
FlowModRecordInternal { match' = match,
#if OPENFLOW_VERSION==1
cookie' = cookie,
#endif
command' = FlowAddType,
idleTimeOut' = Nothing,
hardTimeOut' = Nothing,
priority' = priority,
bufferID' = Nothing,
outPort' = Nothing,
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
flags' = Emergency : if not overlapAllowed then [CheckOverlap] else [],
#endif
actions' = actions
}
flowModToFlowModInternal (ModifyFlows {..}) =
FlowModRecordInternal {match' = match,
#if OPENFLOW_VERSION==1
cookie' = ifMissingCookie,
#endif
command' = FlowModifyType,
idleTimeOut' = Just ifMissingIdleTimeOut,
hardTimeOut' = Just ifMissingHardTimeOut,
priority' = ifMissingPriority,
bufferID' = Nothing,
outPort' = Nothing,
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
flags' = concat [ if not ifMissingOverlapAllowed then [CheckOverlap] else [],
if ifMissingNotifyWhenRemoved then [SendFlowRemoved] else []] ,
#endif
actions' = newActions
}
flowModToFlowModInternal (ModifyExactFlow {..}) =
FlowModRecordInternal {match' = match,
#if OPENFLOW_VERSION==1
cookie' = ifMissingCookie,
#endif
command' = FlowModifyStrictType,
idleTimeOut' = Just ifMissingIdleTimeOut,
hardTimeOut' = Just ifMissingHardTimeOut,
priority' = priority,
bufferID' = Nothing,
outPort' = Nothing,
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
flags' = concat [ if not ifMissingOverlapAllowed then [CheckOverlap] else [],
if ifMissingNotifyWhenRemoved then [SendFlowRemoved] else []] ,
#endif
actions' = newActions
}
#if OPENFLOW_VERSION==151
putFlowMod :: FlowModRecordInternal -> Put
putFlowMod (FlowModRecordInternal {..}) = do
putMatch match'
putWord16be $ flowModTypeBimap ! command'
putWord16be $ maybeTimeOutToCode idleTimeOut'
putWord16be $ maybeTimeOutToCode hardTimeOut'
putWord16be priority'
putWord32be $ maybe (-1) id bufferID'
putWord16be $ maybe ofppNone fakePort2Code outPort'
putWord16be 0
putWord32be 0
sequence_ [putAction a | a <- actions']
#endif
#if OPENFLOW_VERSION==152
putFlowMod :: FlowModRecordInternal -> Put
putFlowMod (FlowModRecordInternal {..}) = do
putMatch match'
putWord16be $ flowModTypeBimap ! command'
putWord16be $ maybeTimeOutToCode idleTimeOut'
putWord16be $ maybeTimeOutToCode hardTimeOut'
putWord16be priority'
putWord32be $ maybe (-1) id bufferID'
putWord16be $ maybe ofppNone fakePort2Code outPort'
putWord16be $ flagSet2BitMap flags'
putWord32be 0
sequence_ [putAction a | a <- actions']
#endif
#if OPENFLOW_VERSION==1
putFlowMod :: FlowModRecordInternal -> Put
putFlowMod (FlowModRecordInternal {..}) = do
putMatch match'
putWord64be cookie'
putWord16be $ flowModTypeBimap ! command'
putWord16be $ maybeTimeOutToCode idleTimeOut'
putWord16be $ maybeTimeOutToCode hardTimeOut'
putWord16be priority'
putWord32be $ maybe (-1) id bufferID'
putWord16be $ maybe ofppNone fakePort2Code outPort'
putWord16be $ flagSet2BitMap flags'
sequence_ [putAction a | a <- actions']
getBufferID :: Get (Maybe BufferID)
getBufferID = do w <- getWord32be
if w == -1
then return Nothing
else return (Just w)
getOutPort :: Get (Maybe PseudoPort)
getOutPort = do w <- getWord16be
if w == ofppNone
then return Nothing
else return (Just (code2FakePort w))
getFlowModInternal :: Int -> Get FlowModRecordInternal
getFlowModInternal len =
do match <- getMatch
cookie <- getWord64be
modType <- getFlowModType
idleTimeOut <- getTimeOutFromCode
hardTimeOut <- getTimeOutFromCode
priority <- getWord16be
mBufferID <- getBufferID
outPort <- getOutPort
flags <- getFlowModFlags
let bytesInActionList = len - 72
actions <- getActionsOfSize (fromIntegral bytesInActionList)
return $ FlowModRecordInternal { command' = modType
, match' = match
, actions' = actions
, priority' = priority
, idleTimeOut' = idleTimeOut
, hardTimeOut' = hardTimeOut
, flags' = flags
, bufferID' = mBufferID
, outPort' = outPort
, cookie' = cookie
}
getFlowMod :: Int -> Get FlowMod
getFlowMod len = getFlowModInternal len >>= return . flowModInternal2FlowMod
flowModInternal2FlowMod :: FlowModRecordInternal -> FlowMod
flowModInternal2FlowMod (FlowModRecordInternal {..}) =
case command' of
FlowDeleteType -> DeleteFlows { match = match', outPort = outPort' }
FlowDeleteStrictType -> DeleteExactFlow { match = match', outPort = outPort', priority = priority' }
FlowAddType ->
if elem Emergency flags'
then AddEmergencyFlow { match = match'
, priority = priority'
, actions = actions'
, cookie = cookie'
, overlapAllowed = elem CheckOverlap flags'
}
else AddFlow { match = match'
, priority = priority'
, actions = actions'
, cookie = cookie'
, idleTimeOut = fromJust idleTimeOut'
, hardTimeOut = fromJust hardTimeOut'
, notifyWhenRemoved = elem SendFlowRemoved flags'
, applyToPacket = bufferID'
, overlapAllowed = elem CheckOverlap flags'
}
FlowModifyType -> ModifyFlows { match = match'
, newActions = actions'
, ifMissingPriority = priority'
, ifMissingCookie = cookie'
, ifMissingIdleTimeOut = fromJust idleTimeOut'
, ifMissingHardTimeOut = fromJust hardTimeOut'
, ifMissingOverlapAllowed = CheckOverlap `elem` flags'
, ifMissingNotifyWhenRemoved = SendFlowRemoved `elem` flags'
}
FlowModifyStrictType -> ModifyExactFlow { match = match'
, newActions = actions'
, priority = priority'
, ifMissingCookie = cookie'
, ifMissingIdleTimeOut = fromJust idleTimeOut'
, ifMissingHardTimeOut = fromJust hardTimeOut'
, ifMissingOverlapAllowed = CheckOverlap `elem` flags'
, ifMissingNotifyWhenRemoved = SendFlowRemoved `elem` flags'
}
#endif
maybeTimeOutToCode :: Maybe TimeOut -> Word16
maybeTimeOutToCode Nothing = 0
maybeTimeOutToCode (Just to) =
case to of
Permanent -> 0
ExpireAfter t -> t
{-# INLINE maybeTimeOutToCode #-}
getTimeOutFromCode :: Get (Maybe TimeOut)
getTimeOutFromCode = do code <- getWord16be
if code == 0
then return Nothing
else return (Just (ExpireAfter code))
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
flagSet2BitMap :: [FlowModFlag] -> Word16
flagSet2BitMap flagSet = foldl (.|.) 0 bitMasks
where bitMasks = map (\f -> fromJust $ lookup f flowModFlagToBitMaskBijection) flagSet
flowModFlagToBitMaskBijection :: [(FlowModFlag,Word16)]
flowModFlagToBitMaskBijection = [(SendFlowRemoved, shiftL 1 0),
(CheckOverlap, shiftL 1 1),
(Emergency, shiftL 1 2) ]
bitMap2FlagSet :: Word16 -> [FlowModFlag]
bitMap2FlagSet w = [ flag | (flag,mask) <- flowModFlagToBitMaskBijection, mask .&. w /= 0 ]
getFlowModFlags :: Get [FlowModFlag]
getFlowModFlags = do w <- getWord16be
return (bitMap2FlagSet w)
#endif
ofpfcAdd, ofpfcModify, ofpfcModifyStrict, ofpfcDelete, ofpfcDeleteStrict :: Word16
ofpfcAdd = 0
ofpfcModify = 1
ofpfcModifyStrict = 2
ofpfcDelete = 3
ofpfcDeleteStrict = 4
flowModTypeBimap :: Bimap FlowModType Word16
flowModTypeBimap =
Bimap.fromList [
(FlowAddType, ofpfcAdd),
(FlowModifyType, ofpfcModify),
(FlowModifyStrictType, ofpfcModifyStrict),
(FlowDeleteType, ofpfcDelete),
(FlowDeleteStrictType, ofpfcDeleteStrict)
]
getFlowModType :: Get FlowModType
getFlowModType = do code <- getWord16be
return (flowModTypeBimap !> code)
putAction :: Action -> Put
putAction act =
case act of
(SendOutPort port) ->
do -- putWord16be 0
-- putWord16be 8
putWord32be 8
putPseudoPort port
(SetVlanVID vlanid) ->
do putWord16be 1
putWord16be 8
putWord16be vlanid
putWord16be 0
(SetVlanPriority priority) ->
do putWord16be 2
putWord16be 8
putWord8 priority
putWord8 0
putWord8 0
putWord8 0
(StripVlanHeader) ->
do putWord16be 3
putWord16be 8
putWord32be 0
(SetEthSrcAddr addr) ->
do putWord16be 4
putWord16be 16
putEthernetAddress addr
sequence_ (replicate 6 (putWord8 0))
(SetEthDstAddr addr) ->
do putWord16be 5
putWord16be 16
putEthernetAddress addr
sequence_ (replicate 6 (putWord8 0))
(SetIPSrcAddr addr) ->
do putWord16be 6
putWord16be 8
putWord32be (ipAddressToWord32 addr)
(SetIPDstAddr addr) ->
do putWord16be 7
putWord16be 8
putWord32be (ipAddressToWord32 addr)
(SetIPToS tos) ->
do putWord16be 8
putWord16be 8
putWord8 tos
sequence_ (replicate 3 (putWord8 0))
(SetTransportSrcPort port) ->
do putWord16be 9
putWord16be 8
putWord16be port
putWord16be 0
(SetTransportDstPort port) ->
do putWord16be 10
putWord16be 8
putWord16be port
putWord16be 0
(Enqueue port qid) ->
do putWord16be 11
putWord16be 16
putWord16be port
sequence_ (replicate 6 (putWord8 0))
putWord32be qid
(VendorAction vendorID bytes) ->
do let l = 2 + 2 + 4 + length bytes
when (l `mod` 8 /= 0) (error "Vendor action must have enough data to make the action length a multiple of 8 bytes")
putWord16be 0xffff
putWord16be (fromIntegral l)
putWord32be vendorID
mapM_ putWord8 bytes
putPseudoPort :: PseudoPort -> Put
putPseudoPort (ToController maxLen) =
do putWord16be ofppController
putWord16be maxLen
putPseudoPort port =
do putWord16be (fakePort2Code port)
putWord16be 0
{-# INLINE putPseudoPort #-}
actionSizeInBytes :: Action -> Int
actionSizeInBytes (SendOutPort _) = 8
actionSizeInBytes (SetVlanVID _) = 8
actionSizeInBytes (SetVlanPriority _) = 8
actionSizeInBytes StripVlanHeader = 8
actionSizeInBytes (SetEthSrcAddr _) = 16
actionSizeInBytes (SetEthDstAddr _) = 16
actionSizeInBytes (SetIPSrcAddr _) = 8
actionSizeInBytes (SetIPDstAddr _) = 8
actionSizeInBytes (SetIPToS _) = 8
actionSizeInBytes (SetTransportSrcPort _) = 8
actionSizeInBytes (SetTransportDstPort _) = 8
actionSizeInBytes (Enqueue _ _) = 16
actionSizeInBytes (VendorAction _ bytes) = let l = 2 + 2 + 4 + length bytes
in if l `mod` 8 /= 0
then error "Vendor action must have enough data to make the action length a multiple of 8 bytes"
else l
{-# INLINE actionSizeInBytes #-}
typeOfAction :: Action -> ActionType
typeOfAction !a =
case a of
SendOutPort _ -> OutputToPortType
SetVlanVID _ -> SetVlanVIDType
SetVlanPriority _ -> SetVlanPriorityType
StripVlanHeader -> StripVlanHeaderType
SetEthSrcAddr _ -> SetEthSrcAddrType
SetEthDstAddr _ -> SetEthDstAddrType
SetIPSrcAddr _ -> SetIPSrcAddrType
SetIPDstAddr _ -> SetIPDstAddrType
SetIPToS _ -> SetIPTypeOfServiceType
SetTransportSrcPort _ -> SetTransportSrcPortType
SetTransportDstPort _ -> SetTransportDstPortType
Enqueue _ _ -> EnqueueType
VendorAction _ _ -> VendorActionType
{-# INLINE typeOfAction #-}
------------------------------------------
-- Port mod unparser
------------------------------------------
portModLength :: Word16
portModLength = 32
putPortMod :: PortMod -> Put
putPortMod (PortModRecord {..} ) =
do putWord16be portNumber
putEthernetAddress hwAddr
putConfigBitMap
putMaskBitMap
putAdvertiseBitMap
putPad
where putConfigBitMap = putWord32be (portAttributeSet2BitMask onAttrs)
putMaskBitMap = putWord32be (portAttributeSet2BitMask offAttrs)
putAdvertiseBitMap = putWord32be 0
putPad = putWord32be 0
attrsChanging = List.union onAttrs offAttrs
onAttrs = Map.keys $ Map.filter (==True) attributesToSet
offAttrs = Map.keys $ Map.filter (==False) attributesToSet
----------------------------------------
-- Stats requests unparser
----------------------------------------
statsRequestSize :: StatsRequest -> Int
statsRequestSize (FlowStatsRequest _ _ _) = headerSize + 2 + 2 + matchSize + 1 + 1 + 2
#if OPENFLOW_VERSION==151 || OPENFLOW_VERSION==152
statsRequestSize (PortStatsRequest) = headerSize + 2 + 2
#endif
#if OPENFLOW_VERSION==1
statsRequestSize (PortStatsRequest _) = headerSize + 2 + 2 + 2 + 6
#endif
statsRequestSize (DescriptionRequest) = headerSize + 2 + 2
putStatsRequest :: StatsRequest -> Put
putStatsRequest (FlowStatsRequest match tableQuery mPort) =
do putWord16be ofpstFlow
putWord16be 0
putMatch match
putWord8 (tableQueryToCode tableQuery)
putWord8 0 --pad
putWord16be $ maybe ofppNone fakePort2Code mPort
putStatsRequest (AggregateFlowStatsRequest match tableQuery mPort) =
do putWord16be ofpstAggregate
putWord16be 0
putMatch match
putWord8 (tableQueryToCode tableQuery)
putWord8 0 --pad
putWord16be $ maybe ofppNone fakePort2Code mPort
putStatsRequest TableStatsRequest =
do putWord16be ofpstTable
putWord16be 0
putStatsRequest DescriptionRequest =
do putWord16be ofpstDesc
putWord16be 0
#if OPENFLOW_VERSION==151 || OPENFLOW_VERSION==152
putStatsRequest PortStatsRequest =
do putWord16be ofpstPort
putWord16be 0
#endif
#if OPENFLOW_VERSION==1
putStatsRequest (QueueStatsRequest portQuery queueQuery) =
do putWord16be ofpstQueue
putWord16be 0
putWord16be (queryToPortNumber portQuery)
putWord16be 0 --padding
putWord32be (queryToQueueID queueQuery)
putStatsRequest (PortStatsRequest query) =
do putWord16be ofpstPort
putWord16be 0
putWord16be (queryToPortNumber query)
sequence_ (replicate 6 (putWord8 0))
queryToPortNumber :: PortQuery -> Word16
queryToPortNumber AllPorts = ofppNone
queryToPortNumber (SinglePort p) = p
queryToQueueID :: QueueQuery -> QueueID
queryToQueueID AllQueues = 0xffffffff
queryToQueueID (SingleQueue q) = q
#endif
ofppInPort, ofppTable, ofppNormal, ofppFlood, ofppAll, ofppController, ofppLocal, ofppNone :: Word16
ofppInPort = 0xfff8
ofppTable = 0xfff9
ofppNormal = 0xfffa
ofppFlood = 0xfffb
ofppAll = 0xfffc
ofppController = 0xfffd
ofppLocal = 0xfffe
ofppNone = 0xffff
fakePort2Code :: PseudoPort -> Word16
fakePort2Code (PhysicalPort portID) = portID
fakePort2Code InPort = ofppInPort
fakePort2Code Flood = ofppFlood
fakePort2Code AllPhysicalPorts = ofppAll
fakePort2Code (ToController _) = ofppController
fakePort2Code NormalSwitching = ofppNormal
fakePort2Code WithTable = ofppTable
{-# INLINE fakePort2Code #-}
code2FakePort :: Word16 -> PseudoPort
code2FakePort w
| w <= 0xff00 = PhysicalPort w
| w == ofppInPort = InPort
| w == ofppFlood = Flood
| w == ofppAll = AllPhysicalPorts
| w == ofppController = ToController 0
| w == ofppNormal = NormalSwitching
| w == ofppTable = WithTable
| otherwise = error ("unknown pseudo port number: " ++ show w)
tableQueryToCode :: TableQuery -> Word8
tableQueryToCode AllTables = 0xff
#if OPENFLOW_VERSION==1
tableQueryToCode EmergencyTable = 0xfe
#endif
tableQueryToCode (Table t) = t
#if OPENFLOW_VERSION==151 || OPENFLOW_VERSION==152
ofpstDesc, ofpstFlow, ofpstAggregate, ofpstTable, ofpstPort, ofpstVendor :: Word16
ofpstDesc = 0
ofpstFlow = 1
ofpstAggregate = 2
ofpstTable = 3
ofpstPort = 4
ofpstVendor = 0xffff
#endif
#if OPENFLOW_VERSION==1
ofpstDesc, ofpstFlow, ofpstAggregate, ofpstTable, ofpstPort, ofpstQueue, ofpstVendor :: Word16
ofpstDesc = 0
ofpstFlow = 1
ofpstAggregate = 2
ofpstTable = 3
ofpstPort = 4
ofpstQueue = 5
ofpstVendor = 0xffff
#endif
---------------------------------------------
-- Parser and Unparser for Match
---------------------------------------------
matchSize :: Int
matchSize = 40
getMatch :: Get Match
getMatch = do
wcards <- getWord32be
inport <- getWord16be
srcEthAddr <- getEthernetAddress
dstEthAddr <- getEthernetAddress
dl_vlan <- getWord16be
dl_vlan_pcp <- getWord8
skip 1
dl_type <- getWord16be
nw_tos <- getWord8
nw_proto <- getWord8
skip 2
nw_src <- getWord32be
nw_dst <- getWord32be
tp_src <- getWord16be
tp_dst <- getWord16be
return $ ofpMatch2Match $ OFPMatch wcards inport srcEthAddr dstEthAddr dl_vlan dl_vlan_pcp dl_type nw_tos nw_proto nw_src nw_dst tp_src tp_dst
putMatch :: Match -> Put
putMatch m = do
putWord32be $ ofpm_wildcards m'
putWord16be $ ofpm_in_port m'
putEthernetAddress $ ofpm_dl_src m'
putEthernetAddress $ ofpm_dl_dst m'
putWord16be $ ofpm_dl_vlan m'
putWord8 $ ofpm_dl_vlan_pcp m'
putWord8 0 -- padding
putWord16be $ ofpm_dl_type m'
putWord8 $ ofpm_nw_tos m'
putWord8 $ ofpm_nw_proto m'
putWord16be 0 -- padding
putWord32be $ ofpm_nw_src m'
putWord32be $ ofpm_nw_dst m'
putWord16be $ ofpm_tp_src m'
putWord16be $ ofpm_tp_dst m'
where m' = match2OFPMatch m
data OFPMatch = OFPMatch { ofpm_wildcards :: !Word32,
ofpm_in_port :: !Word16,
ofpm_dl_src, ofpm_dl_dst :: !EthernetAddress,
ofpm_dl_vlan :: !Word16,
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
ofpm_dl_vlan_pcp :: !Word8,
#endif
ofpm_dl_type :: !Word16,
#if OPENFLOW_VERSION==1
ofpm_nw_tos :: !Word8,
#endif
ofpm_nw_proto :: !Word8,
ofpm_nw_src, ofpm_nw_dst :: !Word32,
ofpm_tp_src, ofpm_tp_dst :: !Word16 } deriving (Show,Eq)
ofpMatch2Match :: OFPMatch -> Match
ofpMatch2Match ofpm = Match
(getField 0 ofpm_in_port)
(getField 2 ofpm_dl_src)
(getField 3 ofpm_dl_dst)
(getField 1 ofpm_dl_vlan)
#if OPENFLOW_VERSION==152 || OPENFLOW_VERSION==1
(getField 20 ofpm_dl_vlan_pcp)
#endif
(getField 4 ofpm_dl_type)
#if OPENFLOW_VERSION==1
(getField 21 ofpm_nw_tos)
#endif
(getField 5 ofpm_nw_proto)
(IPAddress (ofpm_nw_src ofpm) // src_prefix_len)
(IPAddress (ofpm_nw_dst ofpm) // dst_prefix_len)
(getField 6 ofpm_tp_src)
(getField 7 ofpm_tp_dst)
where getField wcindex getter = if testBit (ofpm_wildcards ofpm) wcindex
then Nothing
else Just (getter ofpm)
nw_src_shift = 8
nw_dst_shift = 14
nw_src_mask = shiftL ((shiftL 1 6) - 1) nw_src_shift
nw_dst_mask = shiftL ((shiftL 1 6) - 1) nw_dst_shift
nw_src_num_ignored = fromIntegral (shiftR (ofpm_wildcards ofpm .&. nw_src_mask) nw_src_shift)
nw_dst_num_ignored = fromIntegral (shiftR (ofpm_wildcards ofpm .&. nw_dst_mask) nw_dst_shift)
src_prefix_len = 32 - min 32 nw_src_num_ignored
dst_prefix_len = 32 - min 32 nw_dst_num_ignored
match2OFPMatch :: Match -> OFPMatch
match2OFPMatch (Match {..})
= OFPMatch { ofpm_wildcards = wildcard',
ofpm_in_port = maybe 0 id inPort,
ofpm_dl_src = maybe nullEthAddr id srcEthAddress,
ofpm_dl_dst = maybe nullEthAddr id dstEthAddress,
ofpm_dl_vlan = maybe 0 id vLANID,
ofpm_dl_vlan_pcp = maybe 0 id vLANPriority,
ofpm_dl_type = maybe 0 id ethFrameType,
ofpm_nw_tos = maybe 0 id ipTypeOfService,
ofpm_nw_proto = maybe 0 id matchIPProtocol,
ofpm_nw_src = fromIntegral $ ipAddressToWord32 $ addressPart srcIPAddress,
ofpm_nw_dst = fromIntegral $ ipAddressToWord32 $ addressPart dstIPAddress,
ofpm_tp_src = maybe 0 id srcTransportPort,
ofpm_tp_dst = maybe 0 id dstTransportPort }
where
wildcard' :: Word32
wildcard' = shiftL (fromIntegral numIgnoredBitsSrc) 8 .|.
shiftL (fromIntegral numIgnoredBitsDst) 14 .|.
(maybe (flip setBit 0) (const id) inPort $
maybe (flip setBit 1) (const id) vLANID $
maybe (flip setBit 2) (const id) srcEthAddress $
maybe (flip setBit 3) (const id) dstEthAddress $
maybe (flip setBit 4) (const id) ethFrameType $
maybe (flip setBit 5) (const id) matchIPProtocol $
maybe (flip setBit 6) (const id) srcTransportPort $
maybe (flip setBit 7) (const id) dstTransportPort $
maybe (flip setBit 20) (const id) vLANPriority $
maybe (flip setBit 21) (const id) ipTypeOfService $
0
)
numIgnoredBitsSrc = 32 - (prefixLength srcIPAddress)
numIgnoredBitsDst = 32 - (prefixLength dstIPAddress)
nullEthAddr = ethernetAddress 0 0 0 0 0 0
lenQueueProp (MinRateQueue _) = 16
lenQueueProp (MaxRateQueue _) = 16
putQueueProp (MinRateQueue (Enabled rate)) = putQueueProp' ofpqtMinRate rate
putQueueProp (MaxRateQueue (Enabled rate)) = putQueueProp' ofpqtMaxRate rate
-- struct ofp_queue_prop_min_rate
putQueueProp' propType rate = do
putWord16be propType
putWord16be 16 -- length
putWord32be 0 -- padding
putWord16be rate
putWord32be 0 -- padding
putWord16be 0 --padding
lenQueueConfig (QueueConfig _ props) = 8 + sum (map lenQueueProp props)
-- struct ofp_packet_queue
putQueueConfig (QueueConfig qid props) = do
putWord32be qid
putWord16be (8 + sum (map lenQueueProp props))
putWord16be 0 -- padding
mapM_ putQueueProp props
-----------------------------------
-- Utilities
-----------------------------------
getWord8s :: Int -> Get [Word8]
getWord8s n = sequence $ replicate n getWord8
putWord8s :: [Word8] -> Put
putWord8s bytes = sequence_ [putWord8 b | b <- bytes]
| brownsys/nettle-openflow | src/Nettle/OpenFlow/MessagesBinary.hs | bsd-3-clause | 76,633 | 6 | 26 | 26,102 | 16,295 | 8,358 | 7,937 | -1 | -1 |
module Main where
import Data.List (intersperse)
import Data.List.Split (splitOn)
import System.Environment (getArgs)
import Control.Distributed.Task.Distribution.LogConfiguration (initDefaultLogging)
import Control.Distributed.Task.Distribution.RunComputation
import Control.Distributed.Task.Distribution.TaskDistribution (startSlaveNode, showSlaveNodes, showSlaveNodesWithData, shutdownSlaveNodes)
import Control.Distributed.Task.TaskSpawning.RemoteExecutionSupport
import Control.Distributed.Task.Types.HdfsConfigTypes
import Control.Distributed.Task.Types.TaskTypes
import FullBinaryExamples
import RemoteExecutable
import DemoTask
main :: IO ()
main = withRemoteExecutionSupport calculateRatio $ do
initDefaultLogging ""
args <- getArgs
case args of
("master" : masterArgs) -> runMaster (parseMasterOpts masterArgs)
["slave", slaveHost, slavePort] -> startSlaveNode (slaveHost, (read slavePort))
["showslaves"] -> showSlaveNodes localConfig
["slaveswithhdfsdata", host, port, hdfsFilePath] -> showSlaveNodesWithData (host, read port) hdfsFilePath
["shutdown"] -> shutdownSlaveNodes localConfig
_ -> userSyntaxError "unknown mode"
-- note: assumes no nodes with that configuration, should be read as parameters
localConfig :: HdfsConfig
localConfig = ("localhost", 44440)
userSyntaxError :: String -> undefined
userSyntaxError reason = error $ usageInfo ++ reason ++ "\n"
usageInfo :: String
usageInfo = "Syntax: master"
++ " <host>"
++ " <port>"
++ " <module:<module path>|fullbinary|serializethunkdemo:<demo function>:<demo arg>|objectcodedemo>"
++ " <simpledata:numDBs|hdfs:<file path>[:<subdir depth>[:<filename filter prefix>]]"
++ " <collectonmaster|discard|storeinhdfs:<outputprefix>[:<outputsuffix>]>\n"
++ "| slave <slave host> <slave port>\n"
++ "| showslaves\n"
++ "| slaveswithhdfsdata <thrift host> <thrift port> <hdfs file path>\n"
++ "| shutdown\n"
++ "\n"
++ "demo functions (with demo arg description): append:<suffix> | filter:<infixfilter> | visitcalc:unused \n"
parseMasterOpts :: [String] -> MasterOptions
parseMasterOpts args =
case args of
[masterHost, port, taskSpec, dataSpec, resultSpec] -> MasterOptions masterHost (read port) (parseTaskSpec taskSpec) (parseDataSpec dataSpec) (parseResultSpec resultSpec)
_ -> userSyntaxError "wrong number of master options"
where
parseTaskSpec :: String -> TaskSpec
parseTaskSpec taskArgs =
case splitOn ":" taskArgs of
["module", modulePath] -> SourceCodeSpec modulePath
["fullbinary"] -> FullBinaryDeployment
["serializethunkdemo", demoFunction, demoArg] -> mkSerializeThunkDemoArgs demoFunction demoArg
["objectcodedemo"] -> ObjectCodeModuleDeployment remoteExecutable
_ -> userSyntaxError $ "unknown task specification: " ++ taskArgs
where
mkSerializeThunkDemoArgs :: String -> String -> TaskSpec
mkSerializeThunkDemoArgs "append" demoArg = SerializedThunk (appendDemo demoArg)
mkSerializeThunkDemoArgs "filter" demoArg = SerializedThunk (filterDemo demoArg)
mkSerializeThunkDemoArgs "visitcalc" _ = SerializedThunk calculateRatio
mkSerializeThunkDemoArgs d a = userSyntaxError $ "unknown demo: " ++ d ++ ":" ++ a
parseDataSpec :: String -> DataSpec
parseDataSpec inputArgs =
case splitOn ":" inputArgs of
["simpledata", numDBs] -> SimpleDataSpec $ read numDBs
("hdfs": hdfsPath: rest) -> HdfsDataSpec hdfsPath depth filter'
where depth = if length rest > 0 then read (rest !! 0) else 0; filter' = if length rest > 1 then Just (rest !! 1) else Nothing
_ -> userSyntaxError $ "unknown data specification: " ++ inputArgs
parseResultSpec resultArgs =
case splitOn ":" resultArgs of
["collectonmaster"] -> CollectOnMaster resultProcessor
("storeinhdfs":outputPrefix:rest) -> StoreInHdfs outputPrefix $ if null rest then "" else head rest
["discard"] -> Discard
_ -> userSyntaxError $ "unknown result specification: " ++ resultArgs
resultProcessor :: [TaskResult] -> IO ()
resultProcessor res = do
putStrLn $ joinStrings "\n" $ map show $ concat res
putStrLn $ "got " ++ (show $ length $ concat res) ++ " results in total"
joinStrings :: String -> [String] -> String
joinStrings separator = concat . intersperse separator
| michaxm/task-distribution | app/Main.hs | bsd-3-clause | 4,444 | 0 | 15 | 825 | 994 | 528 | 466 | 78 | 17 |
module Mistral.TypeCheck.Interface (
genIface
) where
import Mistral.ModuleSystem.Interface
import Mistral.TypeCheck.AST
import Mistral.Utils.SCC ( groupElems )
import Data.Foldable ( foldMap )
import qualified Data.Map as Map
-- | Generate an interface from a core module.
genIface :: Module -> Iface
genIface m = Iface { ifaceModName = modName m
, ifaceDeps = modDeps m
, ifaceDatas = modDatas m
, ifaceBinds = modTypes m
, ifaceTySyns = Map.empty
, ifaceTypes = Map.empty
, ifaceInsts = modInsts m }
-- | Generate the binding map for a core module.
modTypes :: Module -> Map.Map Name IfaceBind
modTypes m = foldMap Map.fromList [ concatMap (map modBindType . groupElems) (modBinds m) ]
modBindType :: Bind a -> (Name, IfaceBind)
modBindType b = (bName b, IfaceBind (bType b))
| GaloisInc/mistral | src/Mistral/TypeCheck/Interface.hs | bsd-3-clause | 927 | 0 | 10 | 271 | 234 | 132 | 102 | 19 | 1 |
module ETA.TypeCheck.TcFlatten(
FlattenEnv(..), FlattenMode(..), mkFlattenEnv,
flatten, flattenMany, flatten_many,
flattenFamApp, flattenTyVarOuter,
unflatten,
eqCanRewrite, eqCanRewriteFR, canRewriteOrSame,
CtFlavourRole, ctEvFlavourRole, ctFlavourRole
) where
import ETA.TypeCheck.TcRnTypes
import ETA.TypeCheck.TcType
import ETA.Types.Type
import ETA.TypeCheck.TcEvidence
import ETA.Types.TyCon
import ETA.Types.TypeRep
import ETA.Types.Kind( isSubKind )
import ETA.Types.Coercion ( tyConRolesX )
import ETA.BasicTypes.Var
import ETA.BasicTypes.VarEnv
import ETA.BasicTypes.NameEnv
import ETA.Utils.Outputable
import ETA.BasicTypes.VarSet
import ETA.TypeCheck.TcSMonad as TcS
import ETA.Main.DynFlags( DynFlags )
import ETA.Utils.Util
import ETA.Utils.Bag
import ETA.Utils.FastString
import Control.Monad( when, liftM )
import ETA.Utils.MonadUtils ( zipWithAndUnzipM )
import GHC.Exts ( inline )
{-
Note [The flattening story]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* A CFunEqCan is either of form
[G] <F xis> : F xis ~ fsk -- fsk is a FlatSkol
[W] x : F xis ~ fmv -- fmv is a unification variable,
-- but untouchable,
-- with MetaInfo = FlatMetaTv
where
x is the witness variable
fsk/fmv is a flatten skolem
xis are function-free
CFunEqCans are always [Wanted], or [Given], never [Derived]
fmv untouchable just means that in a CTyVarEq, say,
fmv ~ Int
we do NOT unify fmv.
* KEY INSIGHTS:
- A given flatten-skolem, fsk, is known a-priori to be equal to
F xis (the LHS), with <F xis> evidence
- A unification flatten-skolem, fmv, stands for the as-yet-unknown
type to which (F xis) will eventually reduce
* Inert set invariant: if F xis1 ~ fsk1, F xis2 ~ fsk2
then xis1 /= xis2
i.e. at most one CFunEqCan with a particular LHS
* Each canonical CFunEqCan x : F xis ~ fsk/fmv has its own
distinct evidence variable x and flatten-skolem fsk/fmv.
Why? We make a fresh fsk/fmv when the constraint is born;
and we never rewrite the RHS of a CFunEqCan.
* Function applications can occur in the RHS of a CTyEqCan. No reason
not allow this, and it reduces the amount of flattening that must occur.
* Flattening a type (F xis):
- If we are flattening in a Wanted/Derived constraint
then create new [W] x : F xis ~ fmv
else create new [G] x : F xis ~ fsk
with fresh evidence variable x and flatten-skolem fsk/fmv
- Add it to the work list
- Replace (F xis) with fsk/fmv in the type you are flattening
- You can also add the CFunEqCan to the "flat cache", which
simply keeps track of all the function applications you
have flattened.
- If (F xis) is in the cache already, just
use its fsk/fmv and evidence x, and emit nothing.
- No need to substitute in the flat-cache. It's not the end
of the world if we start with, say (F alpha ~ fmv1) and
(F Int ~ fmv2) and then find alpha := Int. Athat will
simply give rise to fmv1 := fmv2 via [Interacting rule] below
* Canonicalising a CFunEqCan [G/W] x : F xis ~ fsk/fmv
- Flatten xis (to substitute any tyvars; there are already no functions)
cos :: xis ~ flat_xis
- New wanted x2 :: F flat_xis ~ fsk/fmv
- Add new wanted to flat cache
- Discharge x = F cos ; x2
* Unification flatten-skolems, fmv, ONLY get unified when either
a) The CFunEqCan takes a step, using an axiom
b) During un-flattening
They are never unified in any other form of equality.
For example [W] ffmv ~ Int is stuck; it does not unify with fmv.
* We *never* substitute in the RHS (i.e. the fsk/fmv) of a CFunEqCan.
That would destroy the invariant about the shape of a CFunEqCan,
and it would risk wanted/wanted interactions. The only way we
learn information about fsk is when the CFunEqCan takes a step.
However we *do* substitute in the LHS of a CFunEqCan (else it
would never get to fire!)
* [Interacting rule]
(inert) [W] x1 : F tys ~ fmv1
(work item) [W] x2 : F tys ~ fmv2
Just solve one from the other:
x2 := x1
fmv2 := fmv1
This just unites the two fsks into one.
Always solve given from wanted if poss.
* [Firing rule: wanteds]
(work item) [W] x : F tys ~ fmv
instantiate axiom: ax_co : F tys ~ rhs
Dischard fmv:
fmv := alpha
x := ax_co ; sym x2
[W] x2 : alpha ~ rhs (Non-canonical)
discharging the work item. This is the way that fmv's get
unified; even though they are "untouchable".
NB: this deals with the case where fmv appears in xi, which can
happen; it just happens through the non-canonical stuff
Possible short cut (shortCutReduction) if rhs = G rhs_tys,
where G is a type function. Then
- Flatten rhs_tys (cos : rhs_tys ~ rhs_xis)
- Add G rhs_xis ~ fmv to flat cache
- New wanted [W] x2 : G rhs_xis ~ fmv
- Discharge x := co ; G cos ; x2
* [Firing rule: givens]
(work item) [G] g : F tys ~ fsk
instantiate axiom: co : F tys ~ rhs
Now add non-canonical (since rhs is not flat)
[G] (sym g ; co) : fsk ~ rhs
Short cut (shortCutReduction) for when rhs = G rhs_tys and G is a type function
[G] (co ; g) : G tys ~ fsk
But need to flatten tys: flat_cos : tys ~ flat_tys
[G] (sym (G flat_cos) ; co ; g) : G flat_tys ~ fsk
Why given-fsks, alone, doesn't work
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Could we get away with only flatten meta-tyvars, with no flatten-skolems? No.
[W] w : alpha ~ [F alpha Int]
---> flatten
w = ...w'...
[W] w' : alpha ~ [fsk]
[G] <F alpha Int> : F alpha Int ~ fsk
--> unify (no occurs check)
alpha := [fsk]
But since fsk = F alpha Int, this is really an occurs check error. If
that is all we know about alpha, we will succeed in constraint
solving, producing a program with an infinite type.
Even if we did finally get (g : fsk ~ Boo)l by solving (F alpha Int ~ fsk)
using axiom, zonking would not see it, so (x::alpha) sitting in the
tree will get zonked to an infinite type. (Zonking always only does
refl stuff.)
Why flatten-meta-vars, alone doesn't work
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Look at Simple13, with unification-fmvs only
[G] g : a ~ [F a]
---> Flatten given
g' = g;[x]
[G] g' : a ~ [fmv]
[W] x : F a ~ fmv
--> subst a in x
x = F g' ; x2
[W] x2 : F [fmv] ~ fmv
And now we have an evidence cycle between g' and x!
If we used a given instead (ie current story)
[G] g : a ~ [F a]
---> Flatten given
g' = g;[x]
[G] g' : a ~ [fsk]
[G] <F a> : F a ~ fsk
---> Substitute for a
[G] g' : a ~ [fsk]
[G] F (sym g'); <F a> : F [fsk] ~ fsk
Why is it right to treat fmv's differently to ordinary unification vars?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
f :: forall a. a -> a -> Bool
g :: F Int -> F Int -> Bool
Consider
f (x:Int) (y:Bool)
This gives alpha~Int, alpha~Bool. There is an inconsistency,
but really only one error. SherLoc may tell you which location
is most likely, based on other occurrences of alpha.
Consider
g (x:Int) (y:Bool)
Here we get (F Int ~ Int, F Int ~ Bool), which flattens to
(fmv ~ Int, fmv ~ Bool)
But there are really TWO separate errors. We must not complain
about Int~Bool. Moreover these two errors could arise in entirely
unrelated parts of the code. (In the alpha case, there must be
*some* connection (eg v:alpha in common envt).)
Note [Orient equalities with flatten-meta-vars on the left]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This example comes from IndTypesPerfMerge
From the ambiguity check for
f :: (F a ~ a) => a
we get:
[G] F a ~ a
[W] F alpha ~ alpha, alpha ~ a
From Givens we get
[G] F a ~ fsk, fsk ~ a
Now if we flatten we get
[W] alpha ~ fmv, F alpha ~ fmv, alpha ~ a
Now, processing the first one first, choosing alpha := fmv
[W] F fmv ~ fmv, fmv ~ a
And now we are stuck. We must either *unify* fmv := a, or
use the fmv ~ a to rewrite F fmv ~ fmv, so we can make it
meet up with the given F a ~ blah.
Solution: always put fmvs on the left, so we get
[W] fmv ~ alpha, F alpha ~ fmv, alpha ~ a
The point is that fmvs are very uninformative, so doing alpha := fmv
is a bad idea. We want to use other constraints on alpha first.
Note [Derived constraints from wanted CTyEqCans]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Is this type ambiguous: (Foo e ~ Maybe e) => Foo e
(indexed-types/should_fail/T4093a)
[G] Foo e ~ Maybe e
[W] Foo e ~ Foo ee -- ee is a unification variable
[W] Foo ee ~ Maybe ee)
---
[G] Foo e ~ fsk
[G] fsk ~ Maybe e
[W] Foo e ~ fmv1
[W] Foo ee ~ fmv2
[W] fmv1 ~ fmv2
[W] fmv2 ~ Maybe ee
---> fmv1 := fsk by matching LHSs
[W] Foo ee ~ fmv2
[W] fsk ~ fmv2
[W] fmv2 ~ Maybe ee
--->
[W] Foo ee ~ fmv2
[W] fmv2 ~ Maybe e
[W] fmv2 ~ Maybe ee
Now maybe we shuld get [D] e ~ ee, and then we'd solve it entirely.
But if in a smilar situation we got [D] Int ~ Bool we'd be back
to complaining about wanted/wanted interactions. Maybe this arises
also for fundeps?
Here's another example:
f :: [a] -> [b] -> blah
f (e1 :: F Int) (e2 :: F Int)
we get
F Int ~ fmv
fmv ~ [alpha]
fmv ~ [beta]
We want: alpha := beta (which might unlock something else). If we
generated [D] [alpha] ~ [beta] we'd be good here.
Current story: we don't generate these derived constraints. We could, but
we'd want to make them very weak, so we didn't get the Int~Bool complaint.
************************************************************************
* *
* Other notes (Oct 14)
I have not revisted these, but I didn't want to discard them
* *
************************************************************************
Try: rewrite wanted with wanted only for fmvs (not all meta-tyvars)
But: fmv ~ alpha[0]
alpha[0] ~ fmv’
Now we don’t see that fmv ~ fmv’, which is a problem for injectivity detection.
Conclusion: rewrite wanteds with wanted for all untouchables.
skol ~ untch, must re-orieint to untch ~ skol, so that we can use it to rewrite.
************************************************************************
* *
* Examples
Here is a long series of examples I had to work through
* *
************************************************************************
Simple20
~~~~~~~~
axiom F [a] = [F a]
[G] F [a] ~ a
-->
[G] fsk ~ a
[G] [F a] ~ fsk (nc)
-->
[G] F a ~ fsk2
[G] fsk ~ [fsk2]
[G] fsk ~ a
-->
[G] F a ~ fsk2
[G] a ~ [fsk2]
[G] fsk ~ a
-----------------------------------
----------------------------------------
indexed-types/should_compile/T44984
[W] H (F Bool) ~ H alpha
[W] alpha ~ F Bool
-->
F Bool ~ fmv0
H fmv0 ~ fmv1
H alpha ~ fmv2
fmv1 ~ fmv2
fmv0 ~ alpha
flatten
~~~~~~~
fmv0 := F Bool
fmv1 := H (F Bool)
fmv2 := H alpha
alpha := F Bool
plus
fmv1 ~ fmv2
But these two are equal under the above assumptions.
Solve by Refl.
--- under plan B, namely solve fmv1:=fmv2 eagerly ---
[W] H (F Bool) ~ H alpha
[W] alpha ~ F Bool
-->
F Bool ~ fmv0
H fmv0 ~ fmv1
H alpha ~ fmv2
fmv1 ~ fmv2
fmv0 ~ alpha
-->
F Bool ~ fmv0
H fmv0 ~ fmv1
H alpha ~ fmv2 fmv2 := fmv1
fmv0 ~ alpha
flatten
fmv0 := F Bool
fmv1 := H fmv0 = H (F Bool)
retain H alpha ~ fmv2
because fmv2 has been filled
alpha := F Bool
----------------------------
indexed-types/should_failt/T4179
after solving
[W] fmv_1 ~ fmv_2
[W] A3 (FCon x) ~ fmv_1 (CFunEqCan)
[W] A3 (x (aoa -> fmv_2)) ~ fmv_2 (CFunEqCan)
----------------------------------------
indexed-types/should_fail/T7729a
a) [W] BasePrimMonad (Rand m) ~ m1
b) [W] tt m1 ~ BasePrimMonad (Rand m)
---> process (b) first
BasePrimMonad (Ramd m) ~ fmv_atH
fmv_atH ~ tt m1
---> now process (a)
m1 ~ s_atH ~ tt m1 -- An obscure occurs check
----------------------------------------
typecheck/TcTypeNatSimple
Original constraint
[W] x + y ~ x + alpha (non-canonical)
==>
[W] x + y ~ fmv1 (CFunEqCan)
[W] x + alpha ~ fmv2 (CFuneqCan)
[W] fmv1 ~ fmv2 (CTyEqCan)
(sigh)
----------------------------------------
indexed-types/should_fail/GADTwrong1
[G] Const a ~ ()
==> flatten
[G] fsk ~ ()
work item: Const a ~ fsk
==> fire top rule
[G] fsk ~ ()
work item fsk ~ ()
Surely the work item should rewrite to () ~ ()? Well, maybe not;
it'a very special case. More generally, our givens look like
F a ~ Int, where (F a) is not reducible.
----------------------------------------
indexed_types/should_fail/T8227:
Why using a different can-rewrite rule in CFunEqCan heads
does not work.
Assuming NOT rewriting wanteds with wanteds
Inert: [W] fsk_aBh ~ fmv_aBk -> fmv_aBk
[W] fmv_aBk ~ fsk_aBh
[G] Scalar fsk_aBg ~ fsk_aBh
[G] V a ~ f_aBg
Worklist includes [W] Scalar fmv_aBi ~ fmv_aBk
fmv_aBi, fmv_aBk are flatten unificaiton variables
Work item: [W] V fsk_aBh ~ fmv_aBi
Note that the inert wanteds are cyclic, because we do not rewrite
wanteds with wanteds.
Then we go into a loop when normalise the work-item, because we
use rewriteOrSame on the argument of V.
Conclusion: Don't make canRewrite context specific; instead use
[W] a ~ ty to rewrite a wanted iff 'a' is a unification variable.
----------------------------------------
Here is a somewhat similar case:
type family G a :: *
blah :: (G a ~ Bool, Eq (G a)) => a -> a
blah = error "urk"
foo x = blah x
For foo we get
[W] Eq (G a), G a ~ Bool
Flattening
[W] G a ~ fmv, Eq fmv, fmv ~ Bool
We can't simplify away the Eq Bool unless we substitute for fmv.
Maybe that doesn't matter: we would still be left with unsolved
G a ~ Bool.
--------------------------
Trac #9318 has a very simple program leading to
[W] F Int ~ Int
[W] F Int ~ Bool
We don't want to get "Error Int~Bool". But if fmv's can rewrite
wanteds, we will
[W] fmv ~ Int
[W] fmv ~ Bool
--->
[W] Int ~ Bool
************************************************************************
* *
* The main flattening functions
* *
************************************************************************
Note [Flattening]
~~~~~~~~~~~~~~~~~~~~
flatten ty ==> (xi, cc)
where
xi has no type functions, unless they appear under ForAlls
cc = Auxiliary given (equality) constraints constraining
the fresh type variables in xi. Evidence for these
is always the identity coercion, because internally the
fresh flattening skolem variables are actually identified
with the types they have been generated to stand in for.
Note that it is flatten's job to flatten *every type function it sees*.
flatten is only called on *arguments* to type functions, by canEqGiven.
Recall that in comments we use alpha[flat = ty] to represent a
flattening skolem variable alpha which has been generated to stand in
for ty.
----- Example of flattening a constraint: ------
flatten (List (F (G Int))) ==> (xi, cc)
where
xi = List alpha
cc = { G Int ~ beta[flat = G Int],
F beta ~ alpha[flat = F beta] }
Here
* alpha and beta are 'flattening skolem variables'.
* All the constraints in cc are 'given', and all their coercion terms
are the identity.
NB: Flattening Skolems only occur in canonical constraints, which
are never zonked, so we don't need to worry about zonking doing
accidental unflattening.
Note that we prefer to leave type synonyms unexpanded when possible,
so when the flattener encounters one, it first asks whether its
transitive expansion contains any type function applications. If so,
it expands the synonym and proceeds; if not, it simply returns the
unexpanded synonym.
Note [Flattener EqRels]
~~~~~~~~~~~~~~~~~~~~~~~
When flattening, we need to know which equality relation -- nominal
or representation -- we should be respecting. The only difference is
that we rewrite variables by representational equalities when fe_eq_rel
is ReprEq.
-}
data FlattenEnv
= FE { fe_mode :: FlattenMode
, fe_loc :: CtLoc
, fe_flavour :: CtFlavour
, fe_eq_rel :: EqRel } -- See Note [Flattener EqRels]
data FlattenMode -- Postcondition for all three: inert wrt the type substitution
= FM_FlattenAll -- Postcondition: function-free
| FM_Avoid TcTyVar Bool -- See Note [Lazy flattening]
-- Postcondition:
-- * tyvar is only mentioned in result under a rigid path
-- e.g. [a] is ok, but F a won't happen
-- * If flat_top is True, top level is not a function application
-- (but under type constructors is ok e.g. [F a])
| FM_SubstOnly -- See Note [Flattening under a forall]
mkFlattenEnv :: FlattenMode -> CtEvidence -> FlattenEnv
mkFlattenEnv fm ctev = FE { fe_mode = fm
, fe_loc = ctEvLoc ctev
, fe_flavour = ctEvFlavour ctev
, fe_eq_rel = ctEvEqRel ctev }
feRole :: FlattenEnv -> Role
feRole = eqRelRole . fe_eq_rel
{-
Note [Lazy flattening]
~~~~~~~~~~~~~~~~~~~~~~
The idea of FM_Avoid mode is to flatten less aggressively. If we have
a ~ [F Int]
there seems to be no great merit in lifting out (F Int). But if it was
a ~ [G a Int]
then we *do* want to lift it out, in case (G a Int) reduces to Bool, say,
which gets rid of the occurs-check problem. (For the flat_top Bool, see
comments above and at call sites.)
HOWEVER, the lazy flattening actually seems to make type inference go
*slower*, not faster. perf/compiler/T3064 is a case in point; it gets
*dramatically* worse with FM_Avoid. I think it may be because
floating the types out means we normalise them, and that often makes
them smaller and perhaps allows more re-use of previously solved
goals. But to be honest I'm not absolutely certain, so I am leaving
FM_Avoid in the code base. What I'm removing is the unique place
where it is *used*, namely in TcCanonical.canEqTyVar.
See also Note [Conservative unification check] in TcUnify, which gives
other examples where lazy flattening caused problems.
Bottom line: FM_Avoid is unused for now (Nov 14).
Note: T5321Fun got faster when I disabled FM_Avoid
T5837 did too, but it's pathalogical anyway
Note [Phantoms in the flattener]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have
data Proxy p = Proxy
and we're flattening (Proxy ty) w.r.t. ReprEq. Then, we know that `ty`
is really irrelevant -- it will be ignored when solving for representational
equality later on. So, we omit flattening `ty` entirely. This may
violate the expectation of "xi"s for a bit, but the canonicaliser will
soon throw out the phantoms when decomposing a TyConApp. (Or, the
canonicaliser will emit an insoluble, in which case the unflattened version
yields a better error message anyway.)
Note [flatten_many performance]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In programs with lots of type-level evaluation, flatten_many becomes
part of a tight loop. For example, see test perf/compiler/T9872a, which
calls flatten_many a whopping 7,106,808 times. It is thus important
that flatten_many be efficient.
Performance testing showed that the current implementation is indeed
efficient. It's critically important that zipWithAndUnzipM be
specialized to TcS, and it's also quite helpful to actually `inline`
it. On test T9872a, here are the allocation stats (Dec 16, 2014):
* Unspecialized, uninlined: 8,472,613,440 bytes allocated in the heap
* Specialized, uninlined: 6,639,253,488 bytes allocated in the heap
* Specialized, inlined: 6,281,539,792 bytes allocated in the heap
To improve performance even further, flatten_many_nom is split off
from flatten_many, as nominal equality is the common case. This would
be natural to write using mapAndUnzipM, but even inlined, that function
is not as performant as a hand-written loop.
* mapAndUnzipM, inlined: 7,463,047,432 bytes allocated in the heap
* hand-written recursion: 5,848,602,848 bytes allocated in the heap
If you make any change here, pay close attention to the T9872{a,b,c} tests
and T5321Fun.
If we need to make this yet more performant, a possible way forward is to
duplicate the flattener code for the nominal case, and make that case
faster. This doesn't seem quite worth it, yet.
-}
------------------
flatten :: FlattenMode -> CtEvidence -> TcType -> TcS (Xi, TcCoercion)
flatten mode ev ty
= runFlatten (flatten_one fmode ty)
where
fmode = mkFlattenEnv mode ev
flattenMany :: FlattenMode -> CtEvidence -> [Role]
-> [TcType] -> TcS ([Xi], [TcCoercion])
-- Flatten a bunch of types all at once. Roles on the coercions returned
-- always match the corresponding roles passed in.
flattenMany mode ev roles tys
= runFlatten (flatten_many fmode roles tys)
where
fmode = mkFlattenEnv mode ev
flattenFamApp :: FlattenMode -> CtEvidence
-> TyCon -> [TcType] -> TcS (Xi, TcCoercion)
flattenFamApp mode ev tc tys
= runFlatten (flatten_fam_app fmode tc tys)
where
fmode = mkFlattenEnv mode ev
------------------
flatten_many :: FlattenEnv -> [Role] -> [Type] -> TcS ([Xi], [TcCoercion])
-- Coercions :: Xi ~ Type, at roles given
-- Returns True iff (no flattening happened)
-- NB: The EvVar inside the 'fe_ev :: CtEvidence' is unused,
-- we merely want (a) Given/Solved/Derived/Wanted info
-- (b) the GivenLoc/WantedLoc for when we create new evidence
flatten_many fmode roles tys
-- See Note [flatten_many performance]
= inline zipWithAndUnzipM go roles tys
where
go Nominal ty = flatten_one (setFEEqRel fmode NomEq) ty
go Representational ty = flatten_one (setFEEqRel fmode ReprEq) ty
go Phantom ty = -- See Note [Phantoms in the flattener]
return (ty, mkTcPhantomCo ty ty)
-- | Like 'flatten_many', but assumes that every role is nominal.
flatten_many_nom :: FlattenEnv -> [Type] -> TcS ([Xi], [TcCoercion])
flatten_many_nom _ [] = return ([], [])
-- See Note [flatten_many performance]
flatten_many_nom fmode (ty:tys)
= --ASSERT( fe_eq_rel fmode == NomEq )
do { (xi, co) <- flatten_one fmode ty
; (xis, cos) <- flatten_many_nom fmode tys
; return (xi:xis, co:cos) }
------------------
flatten_one :: FlattenEnv -> TcType -> TcS (Xi, TcCoercion)
-- Flatten a type to get rid of type function applications, returning
-- the new type-function-free type, and a collection of new equality
-- constraints. See Note [Flattening] for more detail.
--
-- Postcondition: Coercion :: Xi ~ TcType
-- The role on the result coercion matches the EqRel in the FlattenEnv
flatten_one fmode xi@(LitTy {}) = return (xi, mkTcReflCo (feRole fmode) xi)
flatten_one fmode (TyVarTy tv)
= flattenTyVar fmode tv
flatten_one fmode (AppTy ty1 ty2)
= do { (xi1,co1) <- flatten_one fmode ty1
; case (fe_eq_rel fmode, nextRole xi1) of
(NomEq, _) -> flatten_rhs xi1 co1 NomEq
(ReprEq, Nominal) -> flatten_rhs xi1 co1 NomEq
(ReprEq, Representational) -> flatten_rhs xi1 co1 ReprEq
(ReprEq, Phantom) ->
return (mkAppTy xi1 ty2, co1 `mkTcAppCo` mkTcNomReflCo ty2) }
where
flatten_rhs xi1 co1 eq_rel2
= do { (xi2,co2) <- flatten_one (setFEEqRel fmode eq_rel2) ty2
; traceTcS "flatten/appty"
(ppr ty1 $$ ppr ty2 $$ ppr xi1 $$
ppr co1 $$ ppr xi2 $$ ppr co2)
; let role1 = feRole fmode
role2 = eqRelRole eq_rel2
; return ( mkAppTy xi1 xi2
, mkTcTransAppCo role1 co1 xi1 ty1
role2 co2 xi2 ty2
role1 ) } -- output should match fmode
flatten_one fmode (FunTy ty1 ty2)
= do { (xi1,co1) <- flatten_one fmode ty1
; (xi2,co2) <- flatten_one fmode ty2
; return (mkFunTy xi1 xi2, mkTcFunCo (feRole fmode) co1 co2) }
flatten_one fmode (TyConApp tc tys)
-- Expand type synonyms that mention type families
-- on the RHS; see Note [Flattening synonyms]
| Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys
, let expanded_ty = mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys'
= case fe_mode fmode of
FM_FlattenAll | anyNameEnv isTypeFamilyTyCon (tyConsOfType rhs)
-> flatten_one fmode expanded_ty
| otherwise
-> flattenTyConApp fmode tc tys
_ -> flattenTyConApp fmode tc tys
-- Otherwise, it's a type function application, and we have to
-- flatten it away as well, and generate a new given equality constraint
-- between the application and a newly generated flattening skolem variable.
| isTypeFamilyTyCon tc
= flatten_fam_app fmode tc tys
-- For * a normal data type application
-- * data family application
-- we just recursively flatten the arguments.
| otherwise
-- FM_Avoid stuff commented out; see Note [Lazy flattening]
-- , let fmode' = case fmode of -- Switch off the flat_top bit in FM_Avoid
-- FE { fe_mode = FM_Avoid tv _ }
-- -> fmode { fe_mode = FM_Avoid tv False }
-- _ -> fmode
= flattenTyConApp fmode tc tys
flatten_one fmode ty@(ForAllTy {})
-- We allow for-alls when, but only when, no type function
-- applications inside the forall involve the bound type variables.
= do { let (tvs, rho) = splitForAllTys ty
; (rho', co) <- flatten_one (setFEMode fmode FM_SubstOnly) rho
-- Substitute only under a forall
-- See Note [Flattening under a forall]
; return (mkForAllTys tvs rho', foldr mkTcForAllCo co tvs) }
flattenTyConApp :: FlattenEnv -> TyCon -> [TcType] -> TcS (Xi, TcCoercion)
flattenTyConApp fmode tc tys
= do { (xis, cos) <- case fe_eq_rel fmode of
NomEq -> flatten_many_nom fmode tys
ReprEq -> flatten_many fmode (tyConRolesX role tc) tys
; return (mkTyConApp tc xis, mkTcTyConAppCo role tc cos) }
where
role = feRole fmode
{-
Note [Flattening synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Not expanding synonyms aggressively improves error messages, and
keeps types smaller. But we need to take care.
Suppose
type T a = a -> a
and we want to flatten the type (T (F a)). Then we can safely flatten
the (F a) to a skolem, and return (T fsk). We don't need to expand the
synonym. This works because TcTyConAppCo can deal with synonyms
(unlike TyConAppCo), see Note [TcCoercions] in TcEvidence.
But (Trac #8979) for
type T a = (F a, a) where F is a type function
we must expand the synonym in (say) T Int, to expose the type function
to the flattener.
Note [Flattening under a forall]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Under a forall, we
(a) MUST apply the inert substitution
(b) MUST NOT flatten type family applications
Hence FMSubstOnly.
For (a) consider c ~ a, a ~ T (forall b. (b, [c]))
If we don't apply the c~a substitution to the second constraint
we won't see the occurs-check error.
For (b) consider (a ~ forall b. F a b), we don't want to flatten
to (a ~ forall b.fsk, F a b ~ fsk)
because now the 'b' has escaped its scope. We'd have to flatten to
(a ~ forall b. fsk b, forall b. F a b ~ fsk b)
and we have not begun to think about how to make that work!
************************************************************************
* *
Flattening a type-family application
* *
************************************************************************
-}
flatten_fam_app, flatten_exact_fam_app, flatten_exact_fam_app_fully
:: FlattenEnv -> TyCon -> [TcType] -> TcS (Xi, TcCoercion)
-- flatten_fam_app can be over-saturated
-- flatten_exact_fam_app is exactly saturated
-- flatten_exact_fam_app_fully lifts out the application to top level
-- Postcondition: Coercion :: Xi ~ F tys
flatten_fam_app fmode tc tys -- Can be over-saturated
= --ASSERT( tyConArity tc <= length tys ) -- Type functions are saturated
-- The type function might be *over* saturated
-- in which case the remaining arguments should
-- be dealt with by AppTys
do { let (tys1, tys_rest) = splitAt (tyConArity tc) tys
; (xi1, co1) <- flatten_exact_fam_app fmode tc tys1
-- co1 :: xi1 ~ F tys1
-- all Nominal roles b/c the tycon is oversaturated
; (xis_rest, cos_rest) <- flatten_many fmode (repeat Nominal) tys_rest
-- cos_res :: xis_rest ~ tys_rest
; return ( mkAppTys xi1 xis_rest -- NB mkAppTys: rhs_xi might not be a type variable
-- cf Trac #5655
, mkTcAppCos co1 cos_rest -- (rhs_xi :: F xis) ; (F cos :: F xis ~ F tys)
) }
flatten_exact_fam_app fmode tc tys
= case fe_mode fmode of
FM_FlattenAll -> flatten_exact_fam_app_fully fmode tc tys
FM_SubstOnly -> do { (xis, cos) <- flatten_many fmode roles tys
; return ( mkTyConApp tc xis
, mkTcTyConAppCo (feRole fmode) tc cos ) }
FM_Avoid tv flat_top ->
do { (xis, cos) <- flatten_many fmode roles tys
; if flat_top || tv `elemVarSet` tyVarsOfTypes xis
then flatten_exact_fam_app_fully fmode tc tys
else return ( mkTyConApp tc xis
, mkTcTyConAppCo (feRole fmode) tc cos ) }
where
-- These are always going to be Nominal for now,
-- but not if #8177 is implemented
roles = tyConRolesX (feRole fmode) tc
flatten_exact_fam_app_fully fmode tc tys
-- See Note [Reduce type family applications eagerly]
= try_to_reduce tc tys False id $
do { (xis, cos) <- flatten_many_nom (setFEEqRel (setFEMode fmode FM_FlattenAll) NomEq) tys
; let ret_co = mkTcTyConAppCo (feRole fmode) tc cos
-- ret_co :: F xis ~ F tys
; mb_ct <- lookupFlatCache tc xis
; case mb_ct of
Just (co, rhs_ty, flav) -- co :: F xis ~ fsk
| (flav, NomEq) `canRewriteOrSameFR` (feFlavourRole fmode)
-> -- Usable hit in the flat-cache
-- We certainly *can* use a Wanted for a Wanted
do { traceTcS "flatten/flat-cache hit" $ (ppr tc <+> ppr xis $$ ppr rhs_ty $$ ppr co)
; (fsk_xi, fsk_co) <- flatten_one fmode rhs_ty
-- The fsk may already have been unified, so flatten it
-- fsk_co :: fsk_xi ~ fsk
; return (fsk_xi, fsk_co `mkTcTransCo`
maybeTcSubCo (fe_eq_rel fmode)
(mkTcSymCo co) `mkTcTransCo`
ret_co) }
-- :: fsk_xi ~ F xis
-- Try to reduce the family application right now
-- See Note [Reduce type family applications eagerly]
_ -> try_to_reduce tc xis True (`mkTcTransCo` ret_co) $
do { let fam_ty = mkTyConApp tc xis
; (ev, fsk) <- newFlattenSkolem (fe_flavour fmode)
(fe_loc fmode)
fam_ty
; let fsk_ty = mkTyVarTy fsk
co = ctEvCoercion ev
; extendFlatCache tc xis (co, fsk_ty, ctEvFlavour ev)
-- The new constraint (F xis ~ fsk) is not necessarily inert
-- (e.g. the LHS may be a redex) so we must put it in the work list
; let ct = CFunEqCan { cc_ev = ev
, cc_fun = tc
, cc_tyargs = xis
, cc_fsk = fsk }
; emitFlatWork ct
; traceTcS "flatten/flat-cache miss" $ (ppr fam_ty $$ ppr fsk $$ ppr ev)
; return (fsk_ty, maybeTcSubCo (fe_eq_rel fmode)
(mkTcSymCo co)
`mkTcTransCo` ret_co) }
}
where
try_to_reduce :: TyCon -- F, family tycon
-> [Type] -- args, not necessarily flattened
-> Bool -- add to the flat cache?
-> ( TcCoercion -- :: xi ~ F args
-> TcCoercion ) -- what to return from outer function
-> TcS (Xi, TcCoercion) -- continuation upon failure
-> TcS (Xi, TcCoercion)
try_to_reduce tc tys cache update_co k
= do { mb_match <- matchFam tc tys
; case mb_match of
Just (norm_co, norm_ty)
-> do { traceTcS "Eager T.F. reduction success" $
vcat [ppr tc, ppr tys, ppr norm_ty, ppr cache]
; (xi, final_co) <- flatten_one fmode norm_ty
; let co = norm_co `mkTcTransCo` mkTcSymCo final_co
; when cache $
extendFlatCache tc tys (co, xi, fe_flavour fmode)
; return (xi, update_co $ mkTcSymCo co) }
Nothing -> k }
{- Note [Reduce type family applications eagerly]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we come across a type-family application like (Append (Cons x Nil) t),
then, rather than flattening to a skolem etc, we may as well just reduce
it on the spot to (Cons x t). This saves a lot of intermediate steps.
Examples that are helped are tests T9872, and T5321Fun.
Performance testing indicates that it's best to try this *twice*, once
before flattening arguments and once after flattening arguments.
Adding the extra reduction attempt before flattening arguments cut
the allocation amounts for the T9872{a,b,c} tests by half. Testing
also indicated that the early reduction should not use the flat-cache,
but that the later reduction should. It's possible that with more
examples, we might learn that these knobs should be set differently.
Once we've got a flat rhs, we extend the flatten-cache to record the
result. Doing so can save lots of work when the same redex shows up
more than once. Note that we record the link from the redex all the
way to its *final* value, not just the single step reduction.
************************************************************************
* *
Flattening a type variable
* *
************************************************************************
Note [The inert equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Definition [Can-rewrite relation]
A "can-rewrite" relation between flavours, written f1 >= f2, is a
binary relation with the following properties
R1. >= is transitive
R2. If f1 >= f, and f2 >= f,
then either f1 >= f2 or f2 >= f1
Lemma. If f1 >= f then f1 >= f1
Proof. By property (R2), with f1=f2
Definition [Generalised substitution]
A "generalised substitution" S is a set of triples (a -f-> t), where
a is a type variable
t is a type
f is a flavour
such that
(WF1) if (a -f1-> t1) in S
(a -f2-> t2) in S
then neither (f1 >= f2) nor (f2 >= f1) hold
(WF2) if (a -f-> t) is in S, then t /= a
Definition [Applying a generalised substitution]
If S is a generalised substitution
S(f,a) = t, if (a -fs-> t) in S, and fs >= f
= a, otherwise
Application extends naturally to types S(f,t), modulo roles.
See Note [Flavours with roles].
Theorem: S(f,a) is well defined as a function.
Proof: Suppose (a -f1-> t1) and (a -f2-> t2) are both in S,
and f1 >= f and f2 >= f
Then by (R2) f1 >= f2 or f2 >= f1, which contradicts (WF)
Notation: repeated application.
S^0(f,t) = t
S^(n+1)(f,t) = S(f, S^n(t))
Definition: inert generalised substitution
A generalised substitution S is "inert" iff
(IG1) there is an n such that
for every f,t, S^n(f,t) = S^(n+1)(f,t)
(IG2) if (b -f-> t) in S, and f >= f, then S(f,t) = t
that is, each individual binding is "self-stable"
----------------------------------------------------------------
Our main invariant:
the inert CTyEqCans should be an inert generalised substitution
----------------------------------------------------------------
Note that inertness is not the same as idempotence. To apply S to a
type, you may have to apply it recursive. But inertness does
guarantee that this recursive use will terminate.
---------- The main theorem --------------
Suppose we have a "work item"
a -fw-> t
and an inert generalised substitution S,
such that
(T1) S(fw,a) = a -- LHS of work-item is a fixpoint of S(fw,_)
(T2) S(fw,t) = t -- RHS of work-item is a fixpoint of S(fw,_)
(T3) a not in t -- No occurs check in the work item
(K1) if (a -fs-> s) is in S then not (fw >= fs)
(K2) if (b -fs-> s) is in S, where b /= a, then
(K2a) not (fs >= fs)
or (K2b) not (fw >= fs)
or (K2c) a not in s
(K3) If (b -fs-> s) is in S with (fw >= fs), then
(K3a) If the role of fs is nominal: s /= a
(K3b) If the role of fs is representational: EITHER
a not in s, OR
the path from the top of s to a includes at least one non-newtype
then the extended substition T = S+(a -fw-> t)
is an inert generalised substitution.
The idea is that
* (T1-2) are guaranteed by exhaustively rewriting the work-item
with S(fw,_).
* T3 is guaranteed by a simple occurs-check on the work item.
* (K1-3) are the "kick-out" criteria. (As stated, they are really the
"keep" criteria.) If the current inert S contains a triple that does
not satisfy (K1-3), then we remove it from S by "kicking it out",
and re-processing it.
* Note that kicking out is a Bad Thing, because it means we have to
re-process a constraint. The less we kick out, the better.
TODO: Make sure that kicking out really *is* a Bad Thing. We've assumed
this but haven't done the empirical study to check.
* Assume we have G>=G, G>=W, D>=D, and that's all. Then, when performing
a unification we add a new given a -G-> ty. But doing so does NOT require
us to kick out an inert wanted that mentions a, because of (K2a). This
is a common case, hence good not to kick out.
* Lemma (L1): The conditions of the Main Theorem imply that there is no
(a fs-> t) in S, s.t. (fs >= fw).
Proof. Suppose the contrary (fs >= fw). Then because of (T1),
S(fw,a)=a. But since fs>=fw, S(fw,a) = s, hence s=a. But now we
have (a -fs-> a) in S, which contradicts (WF2).
* The extended substitution satisfies (WF1) and (WF2)
- (K1) plus (L1) guarantee that the extended substiution satisfies (WF1).
- (T3) guarantees (WF2).
* (K2) is about inertness. Intuitively, any infinite chain T^0(f,t),
T^1(f,t), T^2(f,T).... must pass through the new work item infnitely
often, since the substution without the work item is inert; and must
pass through at least one of the triples in S infnitely often.
- (K2a): if not(fs>=fs) then there is no f that fs can rewrite (fs>=f),
and hence this triple never plays a role in application S(f,a).
It is always safe to extend S with such a triple.
(NB: we could strengten K1) in this way too, but see K3.
- (K2b): If this holds, we can't pass through this triple infinitely
often, because if we did then fs>=f, fw>=f, hence fs>=fw,
contradicting (L1), or fw>=fs contradicting K2b.
- (K2c): if a not in s, we hae no further opportunity to apply the
work item.
NB: this reasoning isn't water tight.
Key lemma to make it watertight.
Under the conditions of the Main Theorem,
forall f st fw >= f, a is not in S^k(f,t), for any k
Also, consider roles more carefully. See Note [Flavours with roles].
Completeness
~~~~~~~~~~~~~
K3: completeness. (K3) is not necessary for the extended substitution
to be inert. In fact K1 could be made stronger by saying
... then (not (fw >= fs) or not (fs >= fs))
But it's not enough for S to be inert; we also want completeness.
That is, we want to be able to solve all soluble wanted equalities.
Suppose we have
work-item b -G-> a
inert-item a -W-> b
Assuming (G >= W) but not (W >= W), this fulfills all the conditions,
so we could extend the inerts, thus:
inert-items b -G-> a
a -W-> b
But if we kicked-out the inert item, we'd get
work-item a -W-> b
inert-item b -G-> a
Then rewrite the work-item gives us (a -W-> a), which is soluble via Refl.
So we add one more clause to the kick-out criteria
Another way to understand (K3) is that we treat an inert item
a -f-> b
in the same way as
b -f-> a
So if we kick out one, we should kick out the other. The orientation
is somewhat accidental.
When considering roles, we also need the second clause (K3b). Consider
inert-item a -W/R-> b c
work-item c -G/N-> a
The work-item doesn't get rewritten by the inert, because (>=) doesn't hold.
We've satisfied conditions (T1)-(T3) and (K1) and (K2). If all we had were
condition (K3a), then we would keep the inert around and add the work item.
But then, consider if we hit the following:
work-item2 b -G/N-> Id
where
newtype Id x = Id x
For similar reasons, if we only had (K3a), we wouldn't kick the
representational inert out. And then, we'd miss solving the inert, which
now reduced to reflexivity. The solution here is to kick out representational
inerts whenever the tyvar of a work item is "exposed", where exposed means
not under some proper data-type constructor, like [] or Maybe. See
isTyVarExposed in TcType. This is encoded in (K3b).
Note [Flavours with roles]
~~~~~~~~~~~~~~~~~~~~~~~~~~
The system described in Note [The inert equalities] discusses an abstract
set of flavours. In GHC, flavours have two components: the flavour proper,
taken from {Wanted, Derived, Given}; and the equality relation (often called
role), taken from {NomEq, ReprEq}. When substituting w.r.t. the inert set,
as described in Note [The inert equalities], we must be careful to respect
roles. For example, if we have
inert set: a -G/R-> Int
b -G/R-> Bool
type role T nominal representational
and we wish to compute S(W/R, T a b), the correct answer is T a Bool, NOT
T Int Bool. The reason is that T's first parameter has a nominal role, and
thus rewriting a to Int in T a b is wrong. Indeed, this non-congruence of
subsitution means that the proof in Note [The inert equalities] may need
to be revisited, but we don't think that the end conclusion is wrong.
-}
flattenTyVar :: FlattenEnv -> TcTyVar -> TcS (Xi, TcCoercion)
-- "Flattening" a type variable means to apply the substitution to it
-- The substitution is actually the union of
-- * the unifications that have taken place (either before the
-- solver started, or in TcInteract.solveByUnification)
-- * the CTyEqCans held in the inert set
--
-- Postcondition: co : xi ~ tv
flattenTyVar fmode tv
= do { mb_yes <- flattenTyVarOuter fmode tv
; case mb_yes of
Left tv' -> -- Done
do { traceTcS "flattenTyVar1" (ppr tv $$ ppr (tyVarKind tv'))
; return (ty', mkTcReflCo (feRole fmode) ty') }
where
ty' = mkTyVarTy tv'
Right (ty1, co1) -- Recurse
-> do { (ty2, co2) <- flatten_one fmode ty1
; traceTcS "flattenTyVar3" (ppr tv $$ ppr ty2)
; return (ty2, co2 `mkTcTransCo` co1) }
}
flattenTyVarOuter :: FlattenEnv -> TcTyVar
-> TcS (Either TyVar (TcType, TcCoercion))
-- Look up the tyvar in
-- a) the internal MetaTyVar box
-- b) the tyvar binds
-- c) the inerts
-- Return (Left tv') if it is not found, tv' has a properly zonked kind
-- (Right (ty, co) if found, with co :: ty ~ tv;
flattenTyVarOuter fmode tv
| not (isTcTyVar tv) -- Happens when flatten under a (forall a. ty)
= Left `liftM` flattenTyVarFinal fmode tv
-- So ty contains refernces to the non-TcTyVar a
| otherwise
= do { mb_ty <- isFilledMetaTyVar_maybe tv
; case mb_ty of {
Just ty -> do { traceTcS "Following filled tyvar" (ppr tv <+> equals <+> ppr ty)
; return (Right (ty, mkTcReflCo (feRole fmode) ty)) } ;
Nothing ->
-- Try in the inert equalities
-- See Definition [Applying a generalised substitution]
do { ieqs <- getInertEqs
; case lookupVarEnv ieqs tv of
Just (ct:_) -- If the first doesn't work,
-- the subsequent ones won't either
| CTyEqCan { cc_ev = ctev, cc_tyvar = tv, cc_rhs = rhs_ty } <- ct
, ctEvFlavourRole ctev `eqCanRewriteFR` feFlavourRole fmode
-> do { traceTcS "Following inert tyvar" (ppr tv <+> equals <+> ppr rhs_ty $$ ppr ctev)
; let rewrite_co1 = mkTcSymCo (ctEvCoercion ctev)
rewrite_co = case (ctEvEqRel ctev, fe_eq_rel fmode) of
(ReprEq, _rel) -> --ASSERT( _rel == ReprEq )
-- if this ASSERT fails, then
-- eqCanRewriteFR answered incorrectly
rewrite_co1
(NomEq, NomEq) -> rewrite_co1
(NomEq, ReprEq) -> mkTcSubCo rewrite_co1
; return (Right (rhs_ty, rewrite_co)) }
-- NB: ct is Derived then fmode must be also, hence
-- we are not going to touch the returned coercion
-- so ctEvCoercion is fine.
_other -> Left `liftM` flattenTyVarFinal fmode tv
} } }
flattenTyVarFinal :: FlattenEnv -> TcTyVar -> TcS TyVar
flattenTyVarFinal fmode tv
= -- Done, but make sure the kind is zonked
do { let kind = tyVarKind tv
kind_fmode = setFEMode fmode FM_SubstOnly
; (new_knd, _kind_co) <- flatten_one kind_fmode kind
; return (setVarType tv new_knd) }
{-
Note [An alternative story for the inert substitution]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(This entire note is just background, left here in case we ever want
to return the the previousl state of affairs)
We used (GHC 7.8) to have this story for the inert substitution inert_eqs
* 'a' is not in fvs(ty)
* They are *inert* in the weaker sense that there is no infinite chain of
(i1 `eqCanRewrite` i2), (i2 `eqCanRewrite` i3), etc
This means that flattening must be recursive, but it does allow
[G] a ~ [b]
[G] b ~ Maybe c
This avoids "saturating" the Givens, which can save a modest amount of work.
It is easy to implement, in TcInteract.kick_out, by only kicking out an inert
only if (a) the work item can rewrite the inert AND
(b) the inert cannot rewrite the work item
This is signifcantly harder to think about. It can save a LOT of work
in occurs-check cases, but we don't care about them much. Trac #5837
is an example; all the constraints here are Givens
[G] a ~ TF (a,Int)
-->
work TF (a,Int) ~ fsk
inert fsk ~ a
--->
work fsk ~ (TF a, TF Int)
inert fsk ~ a
--->
work a ~ (TF a, TF Int)
inert fsk ~ a
---> (attempting to flatten (TF a) so that it does not mention a
work TF a ~ fsk2
inert a ~ (fsk2, TF Int)
inert fsk ~ (fsk2, TF Int)
---> (substitute for a)
work TF (fsk2, TF Int) ~ fsk2
inert a ~ (fsk2, TF Int)
inert fsk ~ (fsk2, TF Int)
---> (top-level reduction, re-orient)
work fsk2 ~ (TF fsk2, TF Int)
inert a ~ (fsk2, TF Int)
inert fsk ~ (fsk2, TF Int)
---> (attempt to flatten (TF fsk2) to get rid of fsk2
work TF fsk2 ~ fsk3
work fsk2 ~ (fsk3, TF Int)
inert a ~ (fsk2, TF Int)
inert fsk ~ (fsk2, TF Int)
--->
work TF fsk2 ~ fsk3
inert fsk2 ~ (fsk3, TF Int)
inert a ~ ((fsk3, TF Int), TF Int)
inert fsk ~ ((fsk3, TF Int), TF Int)
Because the incoming given rewrites all the inert givens, we get more and
more duplication in the inert set. But this really only happens in pathalogical
casee, so we don't care.
-}
eqCanRewrite :: CtEvidence -> CtEvidence -> Bool
eqCanRewrite ev1 ev2 = ctEvFlavourRole ev1 `eqCanRewriteFR` ctEvFlavourRole ev2
-- | Whether or not one 'Ct' can rewrite another is determined by its
-- flavour and its equality relation
type CtFlavourRole = (CtFlavour, EqRel)
-- | Extract the flavour and role from a 'CtEvidence'
ctEvFlavourRole :: CtEvidence -> CtFlavourRole
ctEvFlavourRole ev = (ctEvFlavour ev, ctEvEqRel ev)
-- | Extract the flavour and role from a 'Ct'
ctFlavourRole :: Ct -> CtFlavourRole
ctFlavourRole = ctEvFlavourRole . cc_ev
-- | Extract the flavour and role from a 'FlattenEnv'
feFlavourRole :: FlattenEnv -> CtFlavourRole
feFlavourRole (FE { fe_flavour = flav, fe_eq_rel = eq_rel })
= (flav, eq_rel)
eqCanRewriteFR :: CtFlavourRole -> CtFlavourRole -> Bool
-- Very important function!
-- See Note [eqCanRewrite]
eqCanRewriteFR (Given, NomEq) (_, _) = True
eqCanRewriteFR (Given, ReprEq) (_, ReprEq) = True
eqCanRewriteFR _ _ = False
canRewriteOrSame :: CtEvidence -> CtEvidence -> Bool
-- See Note [canRewriteOrSame]
canRewriteOrSame ev1 ev2 = ev1 `eqCanRewrite` ev2 ||
ctEvFlavourRole ev1 == ctEvFlavourRole ev2
canRewriteOrSameFR :: CtFlavourRole -> CtFlavourRole -> Bool
canRewriteOrSameFR fr1 fr2 = fr1 `eqCanRewriteFR` fr2 || fr1 == fr2
{-
Note [eqCanRewrite]
~~~~~~~~~~~~~~~~~~~
(eqCanRewrite ct1 ct2) holds if the constraint ct1 (a CTyEqCan of form
tv ~ ty) can be used to rewrite ct2. It must satisfy the properties of
a can-rewrite relation, see Definition [Can-rewrite relation]
At the moment we don't allow Wanteds to rewrite Wanteds, because that can give
rise to very confusing type error messages. A good example is Trac #8450.
Here's another
f :: a -> Bool
f x = ( [x,'c'], [x,True] ) `seq` True
Here we get
[W] a ~ Char
[W] a ~ Bool
but we do not want to complain about Bool ~ Char!
Accordingly, we also don't let Deriveds rewrite Deriveds.
With the solver handling Coercible constraints like equality constraints,
the rewrite conditions must take role into account, never allowing
a representational equality to rewrite a nominal one.
Note [canRewriteOrSame]
~~~~~~~~~~~~~~~~~~~~~~~
canRewriteOrSame is similar but
* returns True for Wanted/Wanted.
* works for all kinds of constraints, not just CTyEqCans
See the call sites for explanations.
************************************************************************
* *
Unflattening
* *
************************************************************************
An unflattening example:
[W] F a ~ alpha
flattens to
[W] F a ~ fmv (CFunEqCan)
[W] fmv ~ alpha (CTyEqCan)
We must solve both!
-}
unflatten :: Cts -> Cts -> TcS Cts
unflatten tv_eqs funeqs
= do { dflags <- getDynFlags
; tclvl <- getTcLevel
; traceTcS "Unflattening" $ braces $
vcat [ ptext (sLit "Funeqs =") <+> pprCts funeqs
, ptext (sLit "Tv eqs =") <+> pprCts tv_eqs ]
-- Step 1: unflatten the CFunEqCans, except if that causes an occurs check
-- See Note [Unflatten using funeqs first]
; funeqs <- foldrBagM (unflatten_funeq dflags) emptyCts funeqs
; traceTcS "Unflattening 1" $ braces (pprCts funeqs)
-- Step 2: unify the irreds, if possible
; tv_eqs <- foldrBagM (unflatten_eq dflags tclvl) emptyCts tv_eqs
; traceTcS "Unflattening 2" $ braces (pprCts tv_eqs)
-- Step 3: fill any remaining fmvs with fresh unification variables
; funeqs <- mapBagM finalise_funeq funeqs
; traceTcS "Unflattening 3" $ braces (pprCts funeqs)
-- Step 4: remove any irreds that look like ty ~ ty
; tv_eqs <- foldrBagM finalise_eq emptyCts tv_eqs
; let all_flat = tv_eqs `andCts` funeqs
; traceTcS "Unflattening done" $ braces (pprCts all_flat)
; return all_flat }
where
----------------
unflatten_funeq :: DynFlags -> Ct -> Cts -> TcS Cts
unflatten_funeq dflags ct@(CFunEqCan { cc_fun = tc, cc_tyargs = xis
, cc_fsk = fmv, cc_ev = ev }) rest
= do { -- fmv should be a flatten meta-tv; we now fix its final
-- value, and then zonking will eliminate it
filled <- tryFill dflags fmv (mkTyConApp tc xis) ev
; return (if filled then rest else ct `consCts` rest) }
unflatten_funeq _ other_ct _
= pprPanic "unflatten_funeq" (ppr other_ct)
----------------
finalise_funeq :: Ct -> TcS Ct
finalise_funeq (CFunEqCan { cc_fsk = fmv, cc_ev = ev })
= do { demoteUnfilledFmv fmv
; return (mkNonCanonical ev) }
finalise_funeq ct = pprPanic "finalise_funeq" (ppr ct)
----------------
unflatten_eq :: DynFlags -> TcLevel -> Ct -> Cts -> TcS Cts
unflatten_eq dflags tclvl ct@(CTyEqCan { cc_ev = ev, cc_tyvar = tv, cc_rhs = rhs }) rest
| isFmvTyVar tv
= do { lhs_elim <- tryFill dflags tv rhs ev
; if lhs_elim then return rest else
do { rhs_elim <- try_fill dflags tclvl ev rhs (mkTyVarTy tv)
; if rhs_elim then return rest else
return (ct `consCts` rest) } }
| otherwise
= return (ct `consCts` rest)
unflatten_eq _ _ ct _ = pprPanic "unflatten_irred" (ppr ct)
----------------
finalise_eq :: Ct -> Cts -> TcS Cts
finalise_eq (CTyEqCan { cc_ev = ev, cc_tyvar = tv
, cc_rhs = rhs, cc_eq_rel = eq_rel }) rest
| isFmvTyVar tv
= do { ty1 <- zonkTcTyVar tv
; ty2 <- zonkTcType rhs
; let is_refl = ty1 `tcEqType` ty2
; if is_refl then do { when (isWanted ev) $
setEvBind (ctEvId ev)
(EvCoercion $
mkTcReflCo (eqRelRole eq_rel) rhs)
; return rest }
else return (mkNonCanonical ev `consCts` rest) }
| otherwise
= return (mkNonCanonical ev `consCts` rest)
finalise_eq ct _ = pprPanic "finalise_irred" (ppr ct)
----------------
try_fill dflags tclvl ev ty1 ty2
| Just tv1 <- tcGetTyVar_maybe ty1
, isTouchableOrFmv tclvl tv1
, typeKind ty1 `isSubKind` tyVarKind tv1
= tryFill dflags tv1 ty2 ev
| otherwise
= return False
tryFill :: DynFlags -> TcTyVar -> TcType -> CtEvidence -> TcS Bool
-- (tryFill tv rhs ev) sees if 'tv' is an un-filled MetaTv
-- If so, and if tv does not appear in 'rhs', set tv := rhs
-- bind the evidence (which should be a CtWanted) to Refl<rhs>
-- and return True. Otherwise return False
tryFill dflags tv rhs ev
= --ASSERT2( not (isGiven ev), ppr ev )
do { is_filled <- isFilledMetaTyVar tv
; if is_filled then return False else
do { rhs' <- zonkTcType rhs
; case occurCheckExpand dflags tv rhs' of
OC_OK rhs'' -- Normal case: fill the tyvar
-> do { when (isWanted ev) $
setEvBind (ctEvId ev)
(EvCoercion (mkTcReflCo (ctEvRole ev) rhs''))
; setWantedTyBind tv rhs''
; return True }
_ -> -- Occurs check
return False } }
{-
Note [Unflatten using funeqs first]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[W] G a ~ Int
[W] F (G a) ~ G a
do not want to end up with
[W} F Int ~ Int
because that might actually hold! Better to end up with the two above
unsolved constraints. The flat form will be
G a ~ fmv1 (CFunEqCan)
F fmv1 ~ fmv2 (CFunEqCan)
fmv1 ~ Int (CTyEqCan)
fmv1 ~ fmv2 (CTyEqCan)
Flatten using the fun-eqs first.
-}
-- | Change the 'EqRel' in a 'FlattenEnv'. Avoids allocating a
-- new 'FlattenEnv' where possible.
setFEEqRel :: FlattenEnv -> EqRel -> FlattenEnv
setFEEqRel fmode@(FE { fe_eq_rel = old_eq_rel }) new_eq_rel
| old_eq_rel == new_eq_rel = fmode
| otherwise = fmode { fe_eq_rel = new_eq_rel }
-- | Change the 'FlattenMode' in a 'FlattenEnv'. Avoids allocating
-- a new 'FlattenEnv' where possible.
setFEMode :: FlattenEnv -> FlattenMode -> FlattenEnv
setFEMode fmode@(FE { fe_mode = old_mode }) new_mode
| old_mode `eq` new_mode = fmode
| otherwise = fmode { fe_mode = new_mode }
where
FM_FlattenAll `eq` FM_FlattenAll = True
FM_SubstOnly `eq` FM_SubstOnly = True
FM_Avoid tv1 b1 `eq` FM_Avoid tv2 b2 = tv1 == tv2 && b1 == b2
_ `eq` _ = False
| alexander-at-github/eta | compiler/ETA/TypeCheck/TcFlatten.hs | bsd-3-clause | 58,244 | 47 | 25 | 16,486 | 5,173 | 2,798 | 2,375 | 349 | 9 |
{-# LANGUAGE OverloadedStrings #-}
module Spin
( SourceID
, Source (..)
, session
, yield
, dedup
, Sink (..)
, sinkFile
, sinkYarn
, spin
) where
import Control.Monad (ap, liftM)
import Control.Monad.IO.Class (MonadIO (..), liftIO)
import Control.Monad.Trans.Class (MonadTrans (..))
import Control.Monad.Trans.Resource (MonadResource (..), allocate)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import System.IO
import Fiber
import qualified Yarn
type SourceID = Text
data Source m a = Init (Source m a) (Source m a) SourceID
| HaveOutput (Source m a) Fiber
| NeedIO (m (Source m a))
| Finishing (Source m a) SourceID
| Done a
instance Monad m => Functor (Source m) where
fmap = liftM
instance Monad m => Applicative (Source m) where
pure = return
(<*>) = ap
instance Monad m => Monad (Source m) where
return = Done
Init src1 src2 sid >>= f = Init (src1 >>= f) (src2 >>= f) sid
HaveOutput src fib >>= f = HaveOutput (src >>= f) fib
NeedIO msrc >>= f = NeedIO ((>>= f) `liftM` msrc)
Finishing src sid >>= f = Finishing (src >>= f) sid
Done x >>= f = f x
instance MonadTrans Source where
lift = NeedIO . (Done `liftM`)
instance MonadIO m => MonadIO (Source m) where
liftIO = lift . liftIO
session :: Monad m => SourceID -> Source m () -> Source m ()
session sid src = Init src (Done ()) sid >> Finishing (Done ()) sid
yield :: Fiber -> Source m ()
yield = HaveOutput (Done ())
dedup :: MonadIO m => Source m a -> Source m a
dedup = go
where
go (Init s1 s2 sid) = NeedIO $ do
ls <- liftIO $ T.lines <$> T.readFile "known_sources.list"
return $ if sid `elem` ls
then go s2
else Init (go s1) (error "impossible case") sid
go (HaveOutput src o) = HaveOutput (go src) o
go (NeedIO a) = NeedIO $ go `liftM` a
go (Finishing src sid) = NeedIO $ do
liftIO $ withFile "known_sources.list" AppendMode $ \h ->
T.hPutStrLn h sid
return $ Finishing (go src) sid
go src@(Done _) = src
data Sink m = NeedInput (Fiber -> m (Sink m))
| DoIO (m (Sink m))
| Closed
sinkFile :: MonadResource m => FilePath -> Sink m
sinkFile fp = DoIO $ do
(relKey, y) <- allocate (Yarn.openFile fp Yarn.ReadWriteMode) Yarn.close
return $ go relKey y
where
go relKey y = NeedInput $ \fib -> do
liftIO $ Yarn.insert fib y
return $ go relKey y
sinkYarn :: MonadIO m => Yarn.Yarn -> Sink m
sinkYarn y = self
where
self = NeedInput $ \fib -> do
liftIO $ Yarn.insert fib y
return self
spin :: Monad m => Source m a -> Sink m -> m ()
spin = go []
where
go stk (Init s _ sid) sink = go (sid : stk) s sink
go [] (Finishing _ _) _ = fail "nothing to pop"
go (sid:stk) (Finishing s sid') sink
| sid /= sid' = fail "failed to pop"
| otherwise = go stk s sink
go _ (Done _) _ = return ()
go stk (NeedIO a) sink = do
src <- a
go stk src sink
go stk src@(HaveOutput src' fib) sink = case sink of
Closed -> return ()
DoIO a -> do
sink' <- a
go stk src sink'
NeedInput put -> do
sink' <- put fib
go stk src' sink'
| yuttie/fibers | Spin.hs | bsd-3-clause | 3,531 | 0 | 14 | 1,199 | 1,427 | 729 | 698 | 95 | 8 |
-- Copyright (c) 2015 Eric McCorkle. 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.
--
-- 3. Neither the name of the author nor the names of any contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHORS 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 AUTHORS
-- 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.
{-# OPTIONS_GHC -Wall -Werror #-}
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
-- | This module defines a class for things that can be alpha-renamed.
module IR.Common.Rename.Class(
Rename(..)
) where
import Data.Array.IArray(IArray, Ix)
import qualified Data.Array.IArray as IArray
-- | Class of things that can be alpha-renamed.
class Rename id syntax where
-- | Rename all ids in the given syntax construct.
rename :: (id -> id)
-- ^ A function which renames ids.
-> syntax
-- ^ The syntax construct to rename.
-> syntax
-- ^ The input, with the renaming function applied to all
-- ids.
instance (Rename id syntax) => Rename id (Maybe syntax) where
rename f (Just t) = Just (rename f t)
rename _ Nothing = Nothing
instance (Rename id syntax) => Rename id [syntax] where
rename f = map (rename f)
instance (Rename id syntax, Ix idx, IArray arr syntax) =>
Rename id (arr idx syntax) where
rename f = IArray.amap (rename f)
| emc2/iridium | src/IR/Common/Rename/Class.hs | bsd-3-clause | 2,588 | 0 | 9 | 520 | 276 | 166 | 110 | 18 | 0 |
fibs :: [Integer]
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
main :: IO ()
main = print $ fst $ head $ dropWhile not1000 $ zip [0..] fibs
where not1000 (_,x) = (length $ show x) /= 1000
| stulli/projectEuler | eu25.hs | bsd-3-clause | 192 | 0 | 10 | 47 | 109 | 57 | 52 | 5 | 1 |
module RefacWhereLet(whereToLet) where
import PrettyPrint
import PosSyntax
import AbstractIO
import Maybe
import TypedIds
import UniqueNames hiding (srcLoc)
import PNT
import TiPNT
import List
import RefacUtils hiding (getParams)
import PFE0 (findFile)
import MUtils (( # ))
import RefacLocUtils
import System
import IO
{- This refactoring converts a where into a let. Could potentially narrow the scrope of those involved bindings.
Copyright : (c) Christopher Brown 2008
Maintainer : [email protected]
Stability : provisional
Portability : portable
-}
whereToLet args
= do let fileName = ghead "filename" args
--fileName'= moduleName fileName
--modName = Module fileName'
row = read (args!!1)::Int
col = read (args!!2)::Int
modName <-fileNameToModName fileName
(inscps, exps, mod, tokList)<-parseSourceFile fileName
let pnt = locToPNT fileName (row, col) mod
if not (checkInFun pnt mod)
then error "Please select a definition within a where clause!"
else do
if (pnt /= defaultPNT)
then do
((_,m), (newToks, newMod))<-applyRefac (doWhereToLet pnt)
(Just (inscps, exps, mod, tokList)) fileName
writeRefactoredFiles False [((fileName,m), (newToks,newMod))]
AbstractIO.putStrLn "Completed.\n"
else error "\nInvalid cursor position!"
doWhereToLet pnt (_,_,t)
= do
mod <- convertToWhere pnt t
return mod
convertToWhere pnt t
= applyTP (full_tdTP (idTP `adhocTP` conInMatch
`adhocTP` conInPat
`adhocTP` conInAlt
)) t
where
conInMatch (match@(HsMatch loc name pats (HsBody e) ds)::HsMatchP)
| canBeConverted ds pnt
= do
let decl = definingDecls [pNTtoPN pnt] ds True True
let updateRHS = (Exp (HsLet decl e))
ds' <- rmDecl (pNTtoPN pnt) True ds
-- we need to check that nothing else in the where
-- clause depends on this entity...
allDecs <- mapM hsFreeAndDeclaredPNs ds'
if (declToPName2 $ ghead "conInMatch" decl) `elem` (concat (map fst allDecs))
then error "Entity cannot be converted as another declaration in the where clause depends on it!"
else do e' <- update e updateRHS e
return (HsMatch loc name pats (HsBody e') ds')
conInMatch (match@(HsMatch loc name pats g@(HsGuard e) ds)::HsMatchP)
| canBeConverted ds pnt
= do let decl = definingDecls [pNTtoPN pnt] ds True True
let updateRHS = (HsBody (Exp (HsLet decl (rmGuard g))))
ds' <- rmDecl (pNTtoPN pnt) True ds
allDecs <- mapM hsFreeAndDeclaredPNs ds'
if (declToPName2 $ ghead "conInMatch Guard" decl) `elem` (concat (map fst allDecs))
then error "Entity cannot be converted as another declaration in the where clause depends on it!"
else do e' <- update g updateRHS g
return (HsMatch loc name pats e' ds')
conInMatch x = return x
conInPat (pat@(Dec (HsPatBind loc p (HsBody e) ds))::HsDeclP)
| canBeConverted ds pnt
= do
let decl = definingDecls [pNTtoPN pnt] ds True True
let updateRHS = (Exp (HsLet decl e))
ds' <- rmDecl (pNTtoPN pnt) True ds
allDecs <- mapM hsFreeAndDeclaredPNs ds'
if (declToPName2 $ ghead "conInPat" decl) `elem` (concat (map fst allDecs))
then error "Entity cannot be converted as another declaration in the where clause depends on it!"
else do e' <- update e updateRHS e
return (Dec (HsPatBind loc p (HsBody e') ds'))
conInPat (pat@(Dec (HsPatBind loc p g@(HsGuard e) ds))::HsDeclP)
| canBeConverted ds pnt
= do let decl = definingDecls [pNTtoPN pnt] ds True True
let updateRHS = (HsBody (Exp (HsLet decl (rmGuard g))))
ds' <- rmDecl (pNTtoPN pnt) True ds
allDecs <- mapM hsFreeAndDeclaredPNs ds'
if (declToPName2 $ ghead "conInPat" decl) `elem` (concat (map fst allDecs))
then error "Entity cannot be converted as another declaration in the where clause depends on it!"
else do e' <- update g updateRHS g
return (Dec (HsPatBind loc p e' ds'))
conInPat x = return x
conInAlt (alt@(HsAlt loc p (HsBody e) ds)::HsAltP)
| canBeConverted ds pnt
= do let decl = definingDecls [pNTtoPN pnt] ds True True
let updateRHS = (Exp (HsLet decl e))
ds' <- rmDecl (pNTtoPN pnt) True ds
e' <- update e updateRHS e
return (HsAlt loc p (HsBody e') ds')
conInAlt (alt@(HsAlt loc p g@(HsGuard e) ds)::HsAltP)
| canBeConverted ds pnt
= do let decl = definingDecls [pNTtoPN pnt] ds True True
let updateRHS = (HsBody (Exp (HsLet decl (rmGuard g))))
ds' <- rmDecl (pNTtoPN pnt) True ds
e' <- updateGuardAlt g updateRHS g
return (HsAlt loc p e' ds')
conInAlt x = return x
updateGuardAlt oldRhs newRhs t
= applyTP (once_tdTP (failTP `adhocTP` inRhs)) t
where
inRhs (r::RhsP)
| r == oldRhs && srcLocs r == srcLocs oldRhs
= do (newRhs',_) <- updateToks oldRhs newRhs prettyprintGuardsAlt
return newRhs'
inRhs r = mzero
rmGuard ((HsGuard gs)::RhsP)
= let (_,e1,e2)=glast "guardToIfThenElse" gs
in if ((pNtoName.expToPN) e1)=="otherwise"
then (foldl mkIfThenElse e2 (tail(reverse gs)))
else (foldl mkIfThenElse defaultElse (reverse gs))
mkIfThenElse e (_,e1, e2)=(Exp (HsIf e1 e2 e))
defaultElse=(Exp (HsApp (Exp (HsId (HsVar (PNT (PN (UnQual "error") (G (PlainModule "Prelude") "error"
(N (Just loc0)))) Value (N (Just loc0)))))) (Exp (HsLit loc0 (HsString "UnMatched Pattern")))))
canBeConverted :: [HsDeclP] -> PNT -> Bool
canBeConverted ds pnt
= pnt `elem` map declToPNT ds
checkInFun :: Term t => PNT -> t -> Bool
checkInFun pnt t
= checkInMatch pnt t || checkInPat pnt t || checkInAlt pnt t
where
checkInAlt pnt t
= fromMaybe (False)
(applyTU (once_tdTU (failTU `adhocTU` inAlt)) t)
checkInPat pnt t
= fromMaybe (False)
(applyTU (once_tdTU (failTU `adhocTU` inPat)) t)
checkInMatch pnt t
= fromMaybe (False)
(applyTU (once_tdTU (failTU `adhocTU` inMatch)) t)
inAlt (alt@(HsAlt loc p rhs ds)::HsAltP)
| findPNT pnt ds = Just True
inAlt _ = Nothing
--The selected sub-expression is in the rhs of a match
inMatch (match@(HsMatch loc1 _ pats rhs ds)::HsMatchP)
| findPNT pnt ds
= Just True
inMatch _ = Nothing
--The selected sub-expression is in the rhs of a pattern-binding
inPat (pat@(Dec (HsPatBind loc1 ps rhs ds))::HsDeclP)
| findPNT pnt ds
= Just True
inPat _ = Nothing
| forste/haReFork | refactorer/RefacWhereLet.hs | bsd-3-clause | 7,907 | 0 | 26 | 2,988 | 2,403 | 1,201 | 1,202 | -1 | -1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
module Iso where
import Data.Functor.Contravariant (Contravariant, (>$<), contramap)
import Person
import Control.Monad.Reader
import Data.Profunctor
import Data.Functor.Identity
import Getter (view)
-- | Exchange an ContraExchange types which are useful to define Isos
-- It like the container for two isomorphic functions
data Exchange a b s t = Exchange (s -> a) (b -> t)
data ContraExchange a b t s = ContraExchange (s -> a) (b -> t)
instance Functor (Exchange a b s) where
fmap f (Exchange sa bt) = Exchange sa (f . bt)
instance Contravariant (ContraExchange a b t) where
contramap f (ContraExchange sa bt) = ContraExchange (sa . f) bt
fromContraEx :: ContraExchange a b t s -> Exchange a b s t
fromContraEx (ContraExchange sa bt) = Exchange sa bt
toContraEx :: Exchange a b s t -> ContraExchange a b t s
toContraEx (Exchange sa bt) = ContraExchange sa bt
-- | Profuctor (Exchange a b)
instance Profunctor (Exchange a b) where
lmap f ex = fromContraEx $ f >$< toContraEx ex
rmap f ex = f <$> ex
dimap f g ex = fromContraEx $ f >$< toContraEx (g <$> ex)
-- | Iso Type
type Iso s t a b =
forall p f . (Profunctor p, Functor f) => p a (f b) -> p s (f t)
type AnIso s t a b =
(Exchange a b) a (Identity b) -> (Exchange a b) s (Identity t)
iso :: (s -> a) -> (b -> t) -> Iso s t a b
iso sa bt = dimap sa (fmap bt)
withIso :: AnIso s t a b -> ((s -> a) -> (b -> t) -> r) -> r
withIso ai k =
let Exchange sa bt = ai $ Exchange id Identity
in k sa (runIdentity . bt)
from :: AnIso s t a b -> Iso b a t s
from ai = withIso ai $ \sa bt -> iso bt sa
-- | Value examples
type HTuple = ( String
, Int
, Gender
, Ethnicity
, Maybe String
, Maybe SuperPower)
makeHuman :: HTuple -> Human
makeHuman (name', age', gender', eth', heroNm', supPower') =
Human name' age' gender' eth' heroNm' supPower'
unmakeHuman :: Human -> HTuple
unmakeHuman Human{..} = (name, age, gender, ethnicity, heroName, superPower)
unmakeHumanIso :: Iso Human Human HTuple HTuple
unmakeHumanIso = iso unmakeHuman makeHuman
makeHumanIso :: Iso HTuple HTuple Human Human
makeHumanIso = from unmakeHumanIso
-- An Iso is a Lens and thus a Getter
humanTuple :: IO HTuple
humanTuple = (runReaderT $ view unmakeHumanIso) human2
aHuman :: IO Human
aHuman = humanTuple >>= runReaderT (view makeHumanIso)
| sebashack/LensPlayground | src/Iso.hs | bsd-3-clause | 2,440 | 0 | 11 | 563 | 922 | 492 | 430 | 54 | 1 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, TupleSections, ScopedTypeVariables #-}
{-|
A module defining an interface for type attribution, the process by which
nodes in an AST are assigned constrained types.
-}
module Language.K3.TypeSystem.Monad.Iface.TypeAttribution
( TypeVarAttrI(..)
) where
import Language.K3.Core.Common
import Language.K3.TypeSystem.Data
-- |The typeclass defining the interface of monads supporting type variable
-- attribution. This allows UIDs to be matched with the type variables which
-- will represent them. The relevant constraints are assumed to be available
-- in context.
class (Monad m) => TypeVarAttrI m where
attributeVar :: UID -> AnyTVar -> m ()
attributeConstraints :: ConstraintSet -> m ()
| DaMSL/K3 | src/Language/K3/TypeSystem/Monad/Iface/TypeAttribution.hs | apache-2.0 | 761 | 0 | 10 | 116 | 89 | 55 | 34 | 8 | 0 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
module Kalium.Nucleus.Vector.Program where
import Kalium.Prelude
import Kalium.Util
import Control.Monad.Rename
data NameSpecial
= OpAdd
| OpSubtract
| OpMultiply
| OpDivide
| OpDiv
| OpMod
| OpLess
| OpMore
| OpLessEquals
| OpMoreEquals
| OpEquals
| OpNotEquals
| OpAnd
| OpOr
| OpNot
| OpTrue
| OpFalse
| OpRange
| OpElem
| OpShow
| OpNegate
| OpIf
| OpFold
| OpFoldTainted
| OpFlipMapTaintedIgnore
| OpMapTaintedIgnore
| OpProduct
| OpSum
| OpAnd'
| OpOr'
| OpPrintLn
| OpReadLn
| OpPutLn
| OpPut
| OpChr
| OpChrOrd
| OpGetLn
| OpGetChar
| OpId
| OpUnit
| OpPair
| OpFst
| OpSnd
| OpSwap
| OpNil
| OpCons
| OpSingleton
| OpIx
| OpIxSet
| OpLength
| OpTaint
| OpBind
| OpBindIgnore
| OpFmap
| OpFmapIgnore
| OpIgnore
| OpWhen
| OpConcat
| OpTake
| OpReplicate
| OpRepeat
| OpIntToDouble
| OpUndefined
| OpMain
| OpTypeInteger
| OpTypeDouble
| OpTypeBoolean
| OpTypeChar
| OpTypeUnit
| OpTypeList
| OpTypePair
| OpTypeFunction
| OpTypeTaint
deriving (Eq, Ord)
data Name = NameSpecial NameSpecial
| NameGen Integer
deriving (Eq, Ord)
alias :: (MonadNameGen m) => EndoKleisli' m Name
alias (NameGen m) = NameGen <$> rename m
alias _ = NameGen <$> mkname Nothing
data Type
= TypeBeta Type Type
| TypeAccess Name
deriving (Eq, Ord)
pattern TypeInteger = TypeAccess (NameSpecial OpTypeInteger)
pattern TypeDouble = TypeAccess (NameSpecial OpTypeDouble)
pattern TypeBoolean = TypeAccess (NameSpecial OpTypeBoolean)
pattern TypeChar = TypeAccess (NameSpecial OpTypeChar)
pattern TypeUnit = TypeAccess (NameSpecial OpTypeUnit)
pattern TypeList = TypeAccess (NameSpecial OpTypeList)
pattern TypePair = TypeAccess (NameSpecial OpTypePair)
pattern TypeFunction= TypeAccess (NameSpecial OpTypeFunction)
pattern TypeTaint = TypeAccess (NameSpecial OpTypeTaint)
data Literal
= LitInteger Integer
| LitDouble Rational
| LitChar Char
deriving (Eq)
data Program
= Program
{ _programFuncs :: Map Name Func
} deriving (Eq)
data Func
= Func
{ _funcType :: Type
, _funcExpression :: Expression
} deriving (Eq)
data Expression' pext ext
= Access Name
| Primary Literal
| Lambda (Pattern' pext) (Expression' pext ext)
| Beta (Expression' pext ext) (Expression' pext ext)
| Ext ext
deriving (Eq)
type Expression = Expression' Void Void
data Pattern' pext
= PTuple (Pattern' pext) (Pattern' pext)
| PAccess Name Type
| PWildCard
| PUnit
| PExt pext
deriving (Eq)
type Pattern = Pattern' Void
pattern OpAccess op = Access (NameSpecial op)
pattern LitUnit = OpAccess OpUnit
pattern App1 op a = op `Beta` a
pattern App2 op a1 a2 = op `Beta` a1 `Beta` a2
pattern App3 op a1 a2 a3 = op `Beta` a1 `Beta` a2 `Beta` a3
pattern AppOp1 op a = App1 (OpAccess op) a
pattern AppOp2 op a1 a2 = App2 (OpAccess op) a1 a2
pattern AppOp3 op a1 a2 a3 = App3 (OpAccess op) a1 a2 a3
pattern Lambda2 p1 p2 a = Lambda p1 (Lambda p2 a)
pattern Into p x a = Beta (Lambda p a) x
pattern Eta p x a = Lambda p (Beta x a)
pattern Ignore a = AppOp1 OpIgnore a
pattern Taint a = AppOp1 OpTaint a
pattern Bind a1 a2 = AppOp2 OpBind a1 a2
pattern Follow p x a = Bind x (Lambda p a)
lambda :: [Pattern' pext] -> Expression' pext ext -> Expression' pext ext
lambda = flip (foldr Lambda)
unlambda :: Expression' pext ext -> ([Pattern' pext], Expression' pext ext)
unlambda = \case
Lambda p a -> let (ps, b) = unlambda a in (p:ps, b)
e -> ([], e)
pattern TypeApp1 t t1 = t `TypeBeta` t1
pattern TypeApp2 t t1 t2 = t `TypeBeta` t1 `TypeBeta` t2
tyfun :: [Type] -> Type -> Type
tyfun = flip (foldr (TypeApp2 TypeFunction))
untyfun :: Type -> ([Type], Type)
untyfun = \case
TypeApp2 TypeFunction tyArg tyRes ->
let (tyArgs, tyRes') = untyfun tyRes
in (tyArg:tyArgs, tyRes')
ty -> ([], ty)
beta :: [Expression' pext ext] -> Expression' pext ext
beta = foldl1 Beta
unbeta :: Expression' pext ext -> [Expression' pext ext]
unbeta = reverse . go where
go = \case
Beta a b -> b : go a
e -> [e]
etaExpand
:: (MonadNameGen m)
=> [Type] -> EndoKleisli' m (Expression' pext ext)
etaExpand tys e = do
(unzip -> (exps, pats)) <- forM tys $ \ty -> do
name <- NameGen <$> mkname Nothing
return (Access name, PAccess name ty)
return $ lambda pats $ beta (e:exps)
typeDrivenUnlambda
:: (MonadNameGen m)
=> Type -> Expression -> m ( ([Pattern],[Type]) , (Expression,Type) )
typeDrivenUnlambda ty a =
let (tys, ty') = untyfun ty
( ps, a') = unlambda a
tysLength = length tys
psLength = length ps
in if | tysLength < psLength -> do
error "lambda-abstraction with non-function type"
| tysLength > psLength -> do
let tys' = drop psLength tys
b <- etaExpand tys' a -- TODO: or is it a'?
typeDrivenUnlambda ty b
| otherwise -> return ( (ps,tys) , (a',ty') )
makeLenses ''Func
makeLenses ''Program
| rscprof/kalium | src/Kalium/Nucleus/Vector/Program.hs | bsd-3-clause | 5,397 | 0 | 14 | 1,491 | 1,860 | 986 | 874 | -1 | -1 |
{-# LANGUAGE Haskell98, BangPatterns #-}
{-# LINE 1 "Data/ByteString/Lazy/Search.hs" #-}
-- |
-- Module : Data.ByteString.Lazy.Search
-- Copyright : Daniel Fischer
-- Chris Kuklewicz
-- Licence : BSD3
-- Maintainer : Daniel Fischer <[email protected]>
-- Stability : Provisional
-- Portability : non-portable (BangPatterns)
--
-- Fast overlapping Boyer-Moore search of lazy
-- 'L.ByteString' values. Breaking, splitting and replacing
-- using the Boyer-Moore algorithm.
--
-- Descriptions of the algorithm can be found at
-- <http://www-igm.univ-mlv.fr/~lecroq/string/node14.html#SECTION00140>
-- and
-- <http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm>
--
-- Original authors: Daniel Fischer (daniel.is.fischer at googlemail.com) and
-- Chris Kuklewicz (haskell at list.mightyreason.com).
module Data.ByteString.Lazy.Search( -- * Overview
-- $overview
-- ** Performance
-- $performance
-- ** Caution
-- $caution
-- ** Complexity
-- $complexity
-- ** Partial application
-- $partial
-- ** Integer overflow
-- $overflow
-- * Finding substrings
indices
, nonOverlappingIndices
-- * Breaking on substrings
, breakOn
, breakAfter
, breakFindAfter
-- * Replacing
, replace
-- * Splitting
, split
, splitKeepEnd
, splitKeepFront
-- * Convenience
, strictify
) where
import qualified Data.ByteString.Lazy.Search.Internal.BoyerMoore as BM
import Data.ByteString.Search.Substitution
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.Int (Int64)
-- $overview
--
-- This module provides functions related to searching a substring within
-- a string, using the Boyer-Moore algorithm with minor modifications
-- to improve the overall performance and ameliorate the worst case
-- performance degradation of the original Boyer-Moore algorithm for
-- periodic patterns.
--
-- Efficiency demands that the pattern be a strict 'S.ByteString',
-- to work with a lazy pattern, convert it to a strict 'S.ByteString'
-- first via 'strictify' (provided it is not too long).
-- If support for long lazy patterns is needed, mail a feature-request.
--
-- When searching a pattern in a UTF-8-encoded 'S.ByteString', be aware that
-- these functions work on bytes, not characters, so the indices are
-- byte-offsets, not character offsets.
-- $performance
--
-- In general, the Boyer-Moore algorithm is the most efficient method to
-- search for a pattern inside a string. The advantage over other algorithms
-- (e.g. Naïve, Knuth-Morris-Pratt, Horspool, Sunday) can be made
-- arbitrarily large for specially selected patterns and targets, but
-- usually, it's a factor of 2–3 versus Knuth-Morris-Pratt and of
-- 6–10 versus the naïve algorithm. The Horspool and Sunday
-- algorithms, which are simplified variants of the Boyer-Moore algorithm,
-- typically have performance between Boyer-Moore and Knuth-Morris-Pratt,
-- mostly closer to Boyer-Moore. The advantage of the Boyer-moore variants
-- over other algorithms generally becomes larger for longer patterns. For
-- very short patterns (or patterns with a very short period), other
-- algorithms, e.g. "Data.ByteString.Lazy.Search.DFA" can be faster (my
-- tests suggest that \"very short\" means two, maybe three bytes).
--
-- In general, searching in a strict 'S.ByteString' is slightly faster
-- than searching in a lazy 'L.ByteString', but for long targets the
-- smaller memory footprint of lazy 'L.ByteString's can make searching
-- those (sometimes much) faster. On the other hand, there are cases
-- where searching in a strict target is much faster, even for long targets.
--
-- On 32-bit systems, 'Int'-arithmetic is much faster than 'Int64'-arithmetic,
-- so when there are many matches, that can make a significant difference.
--
-- Also, the modification to ameliorate the case of periodic patterns
-- is defeated by chunk-boundaries, so long patterns with a short period
-- and many matches exhibit poor behaviour (consider using @indices@ from
-- "Data.ByteString.Lazy.Search.DFA" or "Data.ByteString.Lazy.Search.KMP"
-- in those cases, the former for medium-length patterns, the latter for
-- long patterns; none of the functions except 'indices' suffer from
-- this problem, though).
-- $caution
--
-- When working with a lazy target string, the relation between the pattern
-- length and the chunk size can play a big rôle.
-- Crossing chunk boundaries is relatively expensive, so when that becomes
-- a frequent occurrence, as may happen when the pattern length is close
-- to or larger than the chunk size, performance is likely to degrade.
-- If it is needed, steps can be taken to ameliorate that effect, but unless
-- entirely separate functions are introduced, that would hurt the
-- performance for the more common case of patterns much shorter than
-- the default chunk size.
-- $complexity
--
-- Preprocessing the pattern is /O/(@patternLength@ + σ) in time and
-- space (σ is the alphabet size, 256 here) for all functions.
-- The time complexity of the searching phase for 'indices'
-- is /O/(@targetLength@ \/ @patternLength@) in the best case.
-- For non-periodic patterns, the worst case complexity is
-- /O/(@targetLength@), but for periodic patterns, the worst case complexity
-- is /O/(@targetLength@ * @patternLength@) for the original Boyer-Moore
-- algorithm.
--
-- The searching functions in this module contain a modification which
-- drastically improves the performance for periodic patterns, although
-- less for lazy targets than for strict ones.
-- If I'm not mistaken, the worst case complexity for periodic patterns
-- is /O/(@targetLength@ * (1 + @patternLength@ \/ @chunkSize@)).
--
-- The other functions don't have to deal with possible overlapping
-- patterns, hence the worst case complexity for the processing phase
-- is /O/(@targetLength@) (respectively /O/(@firstIndex + patternLength@)
-- for the breaking functions if the pattern occurs).
-- $partial
--
-- All functions can usefully be partially applied. Given only a pattern,
-- the pattern is preprocessed only once, allowing efficient re-use.
-- $overflow
--
-- The current code uses @Int@ to keep track of the locations in the
-- target string. If the length of the pattern plus the length of any
-- strict chunk of the target string is greater or equal to
-- @'maxBound' :: 'Int'@ then this will overflow causing an error. We try
-- to detect this and call 'error' before a segfault occurs.
------------------------------------------------------------------------------
-- Exported Functions --
------------------------------------------------------------------------------
-- | @'indices'@ finds the starting indices of all possibly overlapping
-- occurrences of the pattern in the target string.
-- If the pattern is empty, the result is @[0 .. 'length' target]@.
{-# INLINE indices #-}
indices :: S.ByteString -- ^ Strict pattern to find
-> L.ByteString -- ^ Lazy string to search
-> [Int64] -- ^ Offsets of matches
indices = BM.matchSL
-- | @'nonOverlappingIndices'@ finds the starting indices of all
-- non-overlapping occurrences of the pattern in the target string.
-- It is more efficient than removing indices from the list produced
-- by 'indices'.
{-# INLINE nonOverlappingIndices #-}
nonOverlappingIndices :: S.ByteString -- ^ Strict pattern to find
-> L.ByteString -- ^ Lazy string to search
-> [Int64] -- ^ Offsets of matches
nonOverlappingIndices = BM.matchNOL
-- | @'breakOn' pattern target@ splits @target@ at the first occurrence
-- of @pattern@. If the pattern does not occur in the target, the
-- second component of the result is empty, otherwise it starts with
-- @pattern@. If the pattern is empty, the first component is empty.
-- For a non-empty pattern, the first component is generated lazily,
-- thus the first parts of it can be available before the pattern has
-- been found or determined to be absent.
--
-- @
-- 'uncurry' 'L.append' . 'breakOn' pattern = 'id'
-- @
{-# INLINE breakOn #-}
breakOn :: S.ByteString -- ^ Strict pattern to search for
-> L.ByteString -- ^ Lazy string to search in
-> (L.ByteString, L.ByteString)
-- ^ Head and tail of string broken at substring
breakOn = BM.breakSubstringL
-- | @'breakAfter' pattern target@ splits @target@ behind the first occurrence
-- of @pattern@. An empty second component means that either the pattern
-- does not occur in the target or the first occurrence of pattern is at
-- the very end of target. If you need to discriminate between those cases,
-- use breakFindAfter.
-- If the pattern is empty, the first component is empty.
-- For a non-empty pattern, the first component is generated lazily,
-- thus the first parts of it can be available before the pattern has
-- been found or determined to be absent.
--
-- @
-- 'uncurry' 'L.append' . 'breakAfter' pattern = 'id'
-- @
{-# INLINE breakAfter #-}
breakAfter :: S.ByteString -- ^ Strict pattern to search for
-> L.ByteString -- ^ Lazy string to search in
-> (L.ByteString, L.ByteString)
-- ^ Head and tail of string broken after substring
breakAfter = BM.breakAfterL
-- | @'breakFindAfter'@ does the same as 'breakAfter' but additionally indicates
-- whether the pattern is present in the target.
--
-- @
-- 'fst' . 'breakFindAfter' pat = 'breakAfter' pat
-- @
{-# INLINE breakFindAfter #-}
breakFindAfter :: S.ByteString -- ^ Strict pattern to search for
-> L.ByteString -- ^ Lazy string to search in
-> ((L.ByteString, L.ByteString), Bool)
-- ^ Head and tail of string broken after substring
-- and presence of pattern
breakFindAfter = BM.breakFindAfterL
-- | @'replace' pat sub text@ replaces all (non-overlapping) occurrences of
-- @pat@ in @text@ with @sub@. If occurrences of @pat@ overlap, the first
-- occurrence that does not overlap with a replaced previous occurrence
-- is substituted. Occurrences of @pat@ arising from a substitution
-- will not be substituted. For example:
--
-- @
-- 'replace' \"ana\" \"olog\" \"banana\" = \"bologna\"
-- 'replace' \"ana\" \"o\" \"bananana\" = \"bono\"
-- 'replace' \"aab\" \"abaa\" \"aaabb\" = \"aabaab\"
-- @
--
-- The result is a lazy 'L.ByteString',
-- which is lazily produced, without copying.
-- Equality of pattern and substitution is not checked, but
--
-- @
-- 'replace' pat pat text == text
-- @
--
-- holds (the internal structure is generally different).
-- If the pattern is empty but not the substitution, the result
-- is equivalent to (were they 'String's) @cycle sub@.
--
-- For non-empty @pat@ and @sub@ a lazy 'L.ByteString',
--
-- @
-- 'L.concat' . 'Data.List.intersperse' sub . 'split' pat = 'replace' pat sub
-- @
--
-- and analogous relations hold for other types of @sub@.
{-# INLINE replace #-}
replace :: Substitution rep
=> S.ByteString -- ^ Strict pattern to replace
-> rep -- ^ Replacement string
-> L.ByteString -- ^ Lazy string to modify
-> L.ByteString -- ^ Lazy result
replace = BM.replaceAllL
-- | @'split' pattern target@ splits @target@ at each (non-overlapping)
-- occurrence of @pattern@, removing @pattern@. If @pattern@ is empty,
-- the result is an infinite list of empty 'L.ByteString's, if @target@
-- is empty but not @pattern@, the result is an empty list, otherwise
-- the following relations hold (where @patL@ is the lazy 'L.ByteString'
-- corresponding to @pat@):
--
-- @
-- 'L.concat' . 'Data.List.intersperse' patL . 'split' pat = 'id',
-- 'length' ('split' pattern target) ==
-- 'length' ('nonOverlappingIndices' pattern target) + 1,
-- @
--
-- no fragment in the result contains an occurrence of @pattern@.
{-# INLINE split #-}
split :: S.ByteString -- ^ Strict pattern to split on
-> L.ByteString -- ^ Lazy string to split
-> [L.ByteString] -- ^ Fragments of string
split = BM.splitDropL
-- | @'splitKeepEnd' pattern target@ splits @target@ after each (non-overlapping)
-- occurrence of @pattern@. If @pattern@ is empty, the result is an
-- infinite list of empty 'L.ByteString's, otherwise the following
-- relations hold:
--
-- @
-- 'L.concat' . 'splitKeepEnd' pattern = 'id',
-- @
--
-- all fragments in the result except possibly the last end with
-- @pattern@, no fragment contains more than one occurrence of @pattern@.
{-# INLINE splitKeepEnd #-}
splitKeepEnd :: S.ByteString -- ^ Strict pattern to split on
-> L.ByteString -- ^ Lazy string to split
-> [L.ByteString] -- ^ Fragments of string
splitKeepEnd = BM.splitKeepEndL
-- | @'splitKeepFront'@ is like 'splitKeepEnd', except that @target@ is split
-- before each occurrence of @pattern@ and hence all fragments
-- with the possible exception of the first begin with @pattern@.
-- No fragment contains more than one non-overlapping occurrence
-- of @pattern@.
{-# INLINE splitKeepFront #-}
splitKeepFront :: S.ByteString -- ^ Strict pattern to split on
-> L.ByteString -- ^ Lazy string to split
-> [L.ByteString] -- ^ Fragments of string
splitKeepFront = BM.splitKeepFrontL
-- | @'strictify'@ converts a lazy 'L.ByteString' to a strict 'S.ByteString'
-- to make it a suitable pattern.
strictify :: L.ByteString -> S.ByteString
strictify = S.concat . L.toChunks
| phischu/fragnix | tests/packages/scotty/Data.ByteString.Lazy.Search.hs | bsd-3-clause | 14,655 | 0 | 9 | 3,651 | 669 | 504 | 165 | 67 | 1 |
{-# LANGUAGE Haskell98, MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
{-# LINE 1 "Control/Monad/Cont/Class.hs" #-}
{- |
Module : Control.Monad.Cont.Class
Copyright : (c) The University of Glasgow 2001,
(c) Jeff Newbern 2003-2007,
(c) Andriy Palamarchuk 2007
License : BSD-style (see the file LICENSE)
Maintainer : [email protected]
Stability : experimental
Portability : portable
[Computation type:] Computations which can be interrupted and resumed.
[Binding strategy:] Binding a function to a monadic value creates
a new continuation which uses the function as the continuation of the monadic
computation.
[Useful for:] Complex control structures, error handling,
and creating co-routines.
[Zero and plus:] None.
[Example type:] @'Cont' r a@
The Continuation monad represents computations in continuation-passing style
(CPS).
In continuation-passing style function result is not returned,
but instead is passed to another function,
received as a parameter (continuation).
Computations are built up from sequences
of nested continuations, terminated by a final continuation (often @id@)
which produces the final result.
Since continuations are functions which represent the future of a computation,
manipulation of the continuation functions can achieve complex manipulations
of the future of the computation,
such as interrupting a computation in the middle, aborting a portion
of a computation, restarting a computation, and interleaving execution of
computations.
The Continuation monad adapts CPS to the structure of a monad.
Before using the Continuation monad, be sure that you have
a firm understanding of continuation-passing style
and that continuations represent the best solution to your particular
design problem.
Many algorithms which require continuations in other languages do not require
them in Haskell, due to Haskell's lazy semantics.
Abuse of the Continuation monad can produce code that is impossible
to understand and maintain.
-}
module Control.Monad.Cont.Class (
MonadCont(..),
) where
import Control.Monad.Trans.Cont (ContT)
import qualified Control.Monad.Trans.Cont as ContT
import Control.Monad.Trans.Error as Error
import Control.Monad.Trans.Except as Except
import Control.Monad.Trans.Identity as Identity
import Control.Monad.Trans.List as List
import Control.Monad.Trans.Maybe as Maybe
import Control.Monad.Trans.Reader as Reader
import Control.Monad.Trans.RWS.Lazy as LazyRWS
import Control.Monad.Trans.RWS.Strict as StrictRWS
import Control.Monad.Trans.State.Lazy as LazyState
import Control.Monad.Trans.State.Strict as StrictState
import Control.Monad.Trans.Writer.Lazy as LazyWriter
import Control.Monad.Trans.Writer.Strict as StrictWriter
import Control.Monad
import Data.Monoid
class Monad m => MonadCont m where
{- | @callCC@ (call-with-current-continuation)
calls a function with the current continuation as its argument.
Provides an escape continuation mechanism for use with Continuation monads.
Escape continuations allow to abort the current computation and return
a value immediately.
They achieve a similar effect to 'Control.Monad.Error.throwError'
and 'Control.Monad.Error.catchError'
within an 'Control.Monad.Error.Error' monad.
Advantage of this function over calling @return@ is that it makes
the continuation explicit,
allowing more flexibility and better control
(see examples in "Control.Monad.Cont").
The standard idiom used with @callCC@ is to provide a lambda-expression
to name the continuation. Then calling the named continuation anywhere
within its scope will escape from the computation,
even if it is many layers deep within nested computations.
-}
callCC :: ((a -> m b) -> m a) -> m a
instance MonadCont (ContT r m) where
callCC = ContT.callCC
-- ---------------------------------------------------------------------------
-- Instances for other mtl transformers
instance (Error e, MonadCont m) => MonadCont (ErrorT e m) where
callCC = Error.liftCallCC callCC
instance MonadCont m => MonadCont (ExceptT e m) where
callCC = Except.liftCallCC callCC
instance MonadCont m => MonadCont (IdentityT m) where
callCC = Identity.liftCallCC callCC
instance MonadCont m => MonadCont (ListT m) where
callCC = List.liftCallCC callCC
instance MonadCont m => MonadCont (MaybeT m) where
callCC = Maybe.liftCallCC callCC
instance MonadCont m => MonadCont (ReaderT r m) where
callCC = Reader.liftCallCC callCC
instance (Monoid w, MonadCont m) => MonadCont (LazyRWS.RWST r w s m) where
callCC = LazyRWS.liftCallCC' callCC
instance (Monoid w, MonadCont m) => MonadCont (StrictRWS.RWST r w s m) where
callCC = StrictRWS.liftCallCC' callCC
instance MonadCont m => MonadCont (LazyState.StateT s m) where
callCC = LazyState.liftCallCC' callCC
instance MonadCont m => MonadCont (StrictState.StateT s m) where
callCC = StrictState.liftCallCC' callCC
instance (Monoid w, MonadCont m) => MonadCont (LazyWriter.WriterT w m) where
callCC = LazyWriter.liftCallCC callCC
instance (Monoid w, MonadCont m) => MonadCont (StrictWriter.WriterT w m) where
callCC = StrictWriter.liftCallCC callCC
| phischu/fragnix | tests/packages/scotty/Control.Monad.Cont.Class.hs | bsd-3-clause | 5,256 | 0 | 12 | 863 | 691 | 390 | 301 | 48 | 0 |
-- This module actually contains data. It is specific to the Gtk+ libs that
-- we're playing with. If we really cared enough we could split this
-- information out into seperate data files that get read in at runtime.
-- However for now it's easier just to edit the data here and recompile.
module MarshalFixup where
import Data.Version
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Map as Map
import Data.Map (Map)
cTypeNameToHSType :: String -> String
cTypeNameToHSType ('A':'t':'k':remainder) = remainder
cTypeNameToHSType ('G':'t':'k':remainder) = remainder
cTypeNameToHSType "GdkWindow" = "DrawWindow"
cTypeNameToHSType ('G':'d':'k':remainder) = remainder
cTypeNameToHSType "PangoLayout" = "PangoLayout"
cTypeNameToHSType ('P':'a':'n':'g':'o':remainder) = remainder
cTypeNameToHSType ('G':'n':'o':'m':'e':remainder) = remainder
cTypeNameToHSType ('V':'t':'e':remainder) = remainder
cTypeNameToHSType other = other
-- some special cases for when converting "gtk_foo_bar" to "GtkFooBar"
-- eg instead of doing gtk_hadjustment -> GtkHadjustment
-- we would prefer gtk_hadjustment -> GtkHAdjustment
-- so list those special cases here:
fixCFunctionName :: String -> String
fixCFunctionName "hadjustment" = "HAdjustment"
fixCFunctionName "vadjustment" = "VAdjustment"
fixCFunctionName "hscale" = "HScale"
fixCFunctionName "vscale" = "VScale"
fixCFunctionName "hbox" = "HBox"
fixCFunctionName "vbox" = "VBox"
fixCFunctionName "hbutton" = "HButton"
fixCFunctionName "vbutton" = "VButton"
fixCFunctionName "hpaned" = "HPaned"
fixCFunctionName "vpaned" = "VPaned"
fixCFunctionName "hborder" = "HBorder"
fixCFunctionName "vborder" = "VBorder"
fixCFunctionName "hseparator" = "HSeparator"
fixCFunctionName "vseparator" = "VSeparator"
fixCFunctionName "hscrollbar" = "HScrollbar"
fixCFunctionName "vscrollbar" = "VScrollbar"
fixCFunctionName "uri" = "URI"
fixCFunctionName "uris" = "URIs"
fixCFunctionName "xscale" = "XScale"
fixCFunctionName "yscale" = "YScale"
fixCFunctionName "xalign" = "XAlign"
fixCFunctionName "yalign" = "YAlign"
fixCFunctionName "xpad" = "XPad"
fixCFunctionName "ypad" = "YPad"
fixCFunctionName other = other
-- In some cases the way we work out the minimum version of the module doesn't
-- work (since the docs sometimes miss marking the version of some functions)
-- So to fix it just specify here the version of the library from which the
-- module is available.
fixModuleAvailableSince :: String -> Maybe Version
fixModuleAvailableSince "GtkComboBox" = version [2,4]
fixModuleAvailableSince "GtkFileChooser" = version [2,4]
fixModuleAvailableSince "GtkCellView" = version [2,6]
fixModuleAvailableSince "GtkIconView" = version [2,6]
fixModuleAvailableSince "GtkMenuToolButton" = version [2,6]
fixModuleAvailableSince _ = Nothing
version v = Just Version { versionBranch = v, versionTags = [] }
-- Most of the time the gtk-doc documentation have titles that correspond to
-- the C name of the object. But sadly sometimes they don't so we fix up that
-- mapping here.
fixModuleDocMapping :: String -> String
fixModuleDocMapping "GtkClipboard" = "Clipboards"
fixModuleDocMapping "GtkSettings" = "Settings"
fixModuleDocMapping "GtkStyle" = "Styles"
fixModuleDocMapping other = other
-- These are ones we have bound and so we can make documentation references to
-- them. Otherwise we generate FIXME messages in the docs.
knownMiscType :: String -> Bool
knownMiscType "GtkTreePath" = True
knownMiscType "GtkTreeIter" = True
knownMiscType "GdkColor" = True
knownMiscType "GtkTextIter" = True
knownMiscType "GtkIconSet" = True
knownMiscType _ = False
-- These are classes from which no other class derives or is ever likely to
-- derive. In this case we can use the actual type rather than the type class
-- For example: GtkAdjustment we say
-- > Adjustment -> ...
-- rather than
-- > AdjustmentClass adjustment => adjustment -> ...
leafClass :: String -> Bool
leafClass = flip Set.member leafClasses
leafClasses = Set.fromList
["GtkAdjustment"
,"GdkPixbuf"
,"GdkPixbufAnimation"
,"GdkBitmap"
,"GdkPixmap"
,"GtkImage"
,"GtkIconFactory"
,"GtkEntryCompletion"
,"GtkFileFilter"
,"GtkUIManager"
,"GtkActionGroup"
,"GtkRadioButton"
,"GtkEventBox"
,"GtkExpander"
,"GtkAccelGroup"
,"GtkTooltips"
,"GtkTextChildAnchor"
,"GdkWindow"
,"GdkDisplay"
,"GdkScreen"
,"GdkColormap"
,"GtkTreeViewColumn"
,"GtkStyle"
]
-- This is a table of fixup information. It lists function parameters that
-- can be null and so should therefore be converted to use a Maybe type.
-- The perameters are identifed by C function name and parameter name.
--
-- Note that if you set this to True for any parameter then the docs for this
-- function will use @Nothing@ in place of NULL rather than a FIXME message. So
-- make sure all possibly-null parameters have been fixed since all NULLs in
-- the function docs are suppressed (since there is no automatic way of working
-- out which function doc NULLs correspond to which parameters).
--
maybeNullParameter :: String -> String -> Bool
maybeNullParameter fun param =
case Map.lookup fun maybeNullParameters of
Nothing -> False
Just [param'] -> param == param'
Just params -> param `elem` params
maybeNullParameters :: Map String [String]
maybeNullParameters = Map.fromList
[("gtk_entry_completion_set_model", ["model"])
,("gtk_label_new", ["str"])
,("gtk_about_dialog_set_license", ["license"])
,("gtk_about_dialog_set_logo", ["logo"])
,("gtk_about_dialog_set_logo_icon_name", ["logo"])
,("gtk_layout_new", ["hadjustment", "vadjustment"])
,("gtk_notebook_set_menu_label", ["menuLabel"])
,("gtk_scrolled_window_new", ["hadjustment", "vadjustment"])
,("gtk_combo_box_set_model", ["model"])
,("gtk_menu_set_screen", ["screen"])
,("gtk_menu_item_set_accel_path", ["accelPath"])
,("gtk_toolbar_set_drop_highlight_item", ["toolItem"])
,("gtk_text_buffer_new", ["table"])
,("gtk_text_buffer_create_mark", ["markName"])
,("gtk_cell_view_set_displayed_row", ["path"])
,("gtk_about_dialog_set_logo_icon_name", ["iconName"])
,("gtk_widget_modify_fg", ["color"])
,("gtk_widget_modify_bg", ["color"])
,("gtk_widget_modify_text", ["color"])
,("gtk_widget_modify_base", ["color"])
,("gtk_action_group_add_action_with_accel", ["accelerator"])
,("gtk_radio_tool_button_new", ["group"])
,("gtk_radio_tool_button_new_from_stock", ["group"])
,("gtk_tool_button_set_label", ["label"])
,("gtk_tool_button_set_icon_widget", ["iconWidget"])
,("gtk_tool_button_set_label_widget", ["labelWidget"])
,("gtk_ui_manager_add_ui", ["action"])
,("gtk_menu_tool_button_new", ["iconWidget", "label"])
,("gtk_menu_tool_button_set_menu", ["menu"])
,("gtk_tool_button_new", ["iconWidget", "label"])
,("gtk_tool_button_set_stock_id", ["stockId"])
,("gtk_action_new", ["tooltip", "stockId"])
,("gtk_toggle_action_new", ["tooltip", "stockId"])
,("gtk_radio_action_new", ["tooltip", "stockId"])
,("gtk_tree_model_iter_n_children", ["iter"])
,("gtk_tree_model_iter_nth_child", ["parent"])
,("gtk_tree_store_insert", ["parent"])
,("gtk_tree_store_prepend", ["parent"])
,("gtk_tree_store_append", ["parent"])
,("gtk_list_store_move_before", ["sibling"])
,("gtk_list_store_move_after", ["sibling"])
,("gtk_tree_view_set_expander_column", ["column"])
,("gtk_tree_view_set_hadjustment", ["adjustment"])
,("gtk_tree_view_set_vadjustment", ["adjustment"])
]
-- similarly for method return values/types.
maybeNullResult :: String -> Bool
maybeNullResult = flip Set.member maybeNullResults
maybeNullResults :: Set String
maybeNullResults = Set.fromList
["gtk_entry_completion_get_entry"
,"gtk_entry_completion_get_model"
,"gtk_accel_label_get_accel_widget"
,"gtk_progress_bar_get_text"
,"gtk_bin_get_child"
,"gtk_container_get_focus_hadjustment"
,"gtk_container_get_focus_vadjustment"
,"gtk_paned_get_child1"
,"gtk_paned_get_child2"
,"gtk_label_get_mnemonic_widget"
,"gtk_notebook_get_menu_label"
,"gtk_notebook_get_menu_label_text"
,"gtk_notebook_get_nth_page"
,"gtk_notebook_get_tab_label"
,"gtk_notebook_get_tab_label_text"
,"gtk_combo_box_get_model"
,"gtk_image_menu_item_get_image"
,"gtk_menu_get_title"
,"gtk_menu_item_get_submenu"
,"gtk_tool_item_retrieve_proxy_menu_item"
,"gtk_tool_item_get_proxy_menu_item"
,"gtk_toolbar_get_nth_item"
,"gtk_file_chooser_get_filename"
,"gtk_file_chooser_get_current_folder"
,"gtk_file_chooser_get_uri"
,"gtk_file_chooser_get_preview_widget"
,"gtk_file_chooser_get_preview_filename"
,"gtk_file_chooser_get_preview_uri"
,"gtk_file_chooser_get_extra_widget"
,"gtk_file_chooser_get_filter"
,"gtk_font_selection_get_font_name"
,"gtk_font_selection_dialog_get_font_name"
,"gtk_text_mark_get_name"
,"gtk_text_mark_get_buffer"
,"gtk_text_tag_table_lookup"
,"gtk_text_buffer_get_mark"
,"gtk_text_view_get_window"
,"gtk_icon_view_get_path_at_pos"
,"gtk_combo_box_get_active_text"
,"gtk_scale_get_layout"
,"gtk_button_get_image"
,"gtk_image_get_animation"
,"gtk_window_get_transient_for"
,"gtk_window_get_role"
,"gtk_window_get_title"
,"gtk_widget_render_icon"
,"gtk_widget_get_composite_name"
,"gtk_action_get_accel_path"
,"gtk_action_group_get_action"
,"gtk_tool_button_get_label"
,"gtk_tool_button_get_icon_widget"
,"gtk_tool_button_get_label_widget"
,"gtk_ui_manager_get_widget"
,"gtk_ui_manager_get_action"
,"gtk_menu_tool_button_get_menu"
,"gtk_tool_button_get_stock_id"
,"gtk_about_dialog_get_license"
,"gtk_menu_get_attach_widget"
,"gtk_tree_view_column_get_title"
,"gtk_frame_get_label_widget"
,"gtk_tree_view_get_model"
,"gtk_tree_view_get_hadjustment"
,"gtk_tree_view_get_vadjustment"
]
-- Often the documentation for parameters or the return value of functions
-- that is included in the gtk-doc docs are just pointless. So this table
-- lists the function and parameter names for which we do not want to use the
-- gtk-doc documentation.
nukeParamDoc :: String -> String -> Bool
nukeParamDoc ('g':'t':'k':'_':'u':'i':'_':'m':'a':'n':'a':'g':'e':'r':'_':_) "self" = True
nukeParamDoc fun param =
case Map.lookup fun nukeParamDocs of
Nothing -> False
Just [param'] -> param == param'
Just params -> param `elem` params
nukeParamDocs :: Map String [String]
nukeParamDocs = Map.fromList
[("gtk_button_box_get_layout", ["returns"])
,("gtk_button_set_label", ["label"])
,("gtk_button_get_label", ["returns"])
,("gtk_toggle_button_get_active", ["returns"])
,("gtk_image_new_from_file", ["filename"])
,("gtk_image_new_from_pixbuf", ["pixbuf"])
,("gtk_label_new", ["str"])
,("gtk_label_set_text", ["str"])
,("gtk_label_set_label", ["str"])
,("gtk_label_set_justify", ["jtype"])
,("gtk_label_get_justify", ["returns"])
,("gtk_label_set_use_underline", ["setting"])
,("gtk_label_get_use_underline", ["returns"])
,("gtk_label_get_layout", ["returns"])
,("gtk_label_get_text", ["returns"])
,("gtk_label_get_label", ["returns"])
,("gtk_label_set_text_with_mnemonic", ["str"])
,("gtk_progress_bar_set_text", ["text"])
,("gtk_progress_bar_get_orientation", ["returns"])
,("gtk_progress_bar_set_orientation", ["orientation"])
,("gtk_statusbar_set_has_resize_grip", ["setting"])
,("gtk_statusbar_get_has_resize_grip", ["returns"])
,("gtk_editable_get_editable", ["returns"])
,("gtk_entry_set_text", ["text"])
,("gtk_entry_get_text", ["returns"])
,("gtk_entry_append_text", ["text"])
,("gtk_entry_prepend_text", ["text"])
,("gtk_entry_set_invisible_char", ["ch"])
,("gtk_entry_set_has_frame", ["setting"])
,("gtk_entry_set_completion", ["completion"])
,("gtk_spin_button_get_value", ["returns"])
,("gtk_spin_button_get_value_as_int", ["returns"])
,("gtk_spin_button_set_value", ["value"])
,("gtk_expander_new", ["label"])
,("gtk_expander_set_expanded", ["expanded"])
,("gtk_expander_get_expanded", ["returns"])
,("gtk_expander_set_spacing", ["spacing"])
,("gtk_expander_set_label", ["label"])
,("gtk_expander_get_label", ["returns"])
,("gtk_expander_get_use_markup", ["returns"])
,("gtk_fixed_set_has_window", ["hasWindow"])
,("gtk_fixed_get_has_window", ["returns"])
,("gtk_notebook_get_n_pages", ["returns"])
,("gtk_adjustment_set_value", ["value"])
,("gtk_adjustment_get_value", ["returns"])
,("gtk_arrow_new", ["arrowType", "shadowType"])
,("gtk_arrow_set", ["arrowType", "shadowType"])
,("gtk_calendar_set_display_options", ["flags"])
,("gtk_calendar_display_options", ["flags"])
,("gtk_calendar_get_display_options", ["returns"])
,("gtk_event_box_set_visible_window", ["visibleWindow"])
,("gtk_event_box_get_visible_window", ["returns"])
,("gtk_event_box_set_above_child", ["aboveChild"])
,("gtk_event_box_get_above_child", ["returns"])
,("gtk_handle_box_set_shadow_type", ["type"])
,("gtk_viewport_get_hadjustment", ["returns"])
,("gtk_viewport_get_vadjustment", ["returns"])
,("gtk_viewport_set_hadjustment", ["adjustment"])
,("gtk_viewport_set_vadjustment", ["adjustment"])
,("gtk_frame_set_label_widget", ["labelWidget"])
,("gtk_frame_set_shadow_type", ["type"])
,("gtk_frame_get_shadow_type", ["returns"])
,("gtk_scrolled_window_get_hadjustment", ["returns"])
,("gtk_scrolled_window_get_vadjustment", ["returns"])
,("gtk_scrolled_window_get_placement", ["returns"])
,("gtk_scrolled_window_set_shadow_type", ["type"])
,("gtk_scrolled_window_get_shadow_type", ["returns"])
,("gtk_scrolled_window_set_hadjustment", ["hadjustment"])
,("gtk_scrolled_window_set_vadjustment", ["hadjustment"])
,("gtk_window_set_title", ["title"])
,("gtk_window_set_resizable", ["resizable"])
,("gtk_window_set_position", ["position"])
,("gtk_window_set_destroy_with_parent", ["setting"])
,("gtk_window_set_decorated", ["setting"])
,("gtk_color_selection_is_adjusting", ["returns"])
,("gtk_check_menu_item_set_active", ["isActive"])
,("gtk_check_menu_item_get_active", ["returns"])
,("gtk_check_menu_item_set_inconsistent", ["setting"])
,("gtk_check_menu_item_get_inconsistent", ["returns"])
,("gtk_check_menu_item_set_draw_as_radio", ["drawAsRadio"])
,("gtk_check_menu_item_get_draw_as_radio", ["returns"])
,("gtk_combo_set_use_arrows", ["val"])
,("gtk_combo_set_use_arrows_always", ["val"])
,("gtk_combo_set_case_sensitive", ["val"])
,("gtk_combo_box_set_wrap_width", ["width"])
,("gtk_combo_box_set_row_span_column", ["rowSpan"])
,("gtk_combo_box_set_column_span_column", ["columnSpan"])
,("gtk_combo_box_set_model", ["model"])
,("gtk_combo_box_append_text", ["text"])
,("gtk_combo_box_prepend_text", ["text"])
,("gtk_menu_set_title", ["title"])
,("gtk_menu_item_set_submenu", ["submenu"])
,("gtk_menu_item_get_right_justified", ["returns"])
,("gtk_option_menu_get_menu", ["returns"])
,("gtk_option_menu_set_menu", ["menu"])
,("gtk_tool_item_get_homogeneous", ["returns"])
,("gtk_tool_item_set_expand", ["expand"])
,("gtk_tool_item_get_expand", ["returns"])
,("gtk_tool_item_set_use_drag_window", ["useDragWindow"])
,("gtk_tool_item_get_use_drag_window", ["returns"])
,("gtk_tool_item_set_visible_horizontal", ["visibleHorizontal"])
,("gtk_tool_item_get_visible_horizontal", ["returns"])
,("gtk_tool_item_set_visible_vertical", ["visibleVertical"])
,("gtk_tool_item_get_visible_vertical", ["returns"])
,("gtk_tool_item_set_is_important", ["isImportant"])
,("gtk_tool_item_get_icon_size", ["returns"])
,("gtk_tool_item_get_orientation", ["returns"])
,("gtk_tool_item_get_toolbar_style", ["returns"])
,("gtk_tool_item_get_relief_style", ["returns"])
,("gtk_tool_item_get_is_important", ["returns"])
,("gtk_tool_item_retrieve_proxy_menu_item", ["returns"])
,("gtk_toolbar_set_orientation", ["orientation"])
,("gtk_toolbar_get_orientation", ["returns"])
,("gtk_toolbar_set_style", ["style"])
,("gtk_toolbar_get_style", ["returns"])
,("gtk_toolbar_get_tooltips", ["returns"])
,("gtk_toolbar_get_icon_size", ["returns"])
,("gtk_toolbar_get_n_items", ["returns"])
,("gtk_toolbar_set_show_arrow", ["showArrow"])
,("gtk_toolbar_get_show_arrow", ["returns"])
,("gtk_toolbar_get_relief_style", ["returns"])
,("gtk_toolbar_set_icon_size", ["iconSize"])
,("gtk_file_chooser_get_action", ["returns"])
,("gtk_file_chooser_set_local_only", ["localOnly"])
,("gtk_file_chooser_get_local_only", ["returns"])
,("gtk_file_chooser_set_select_multiple", ["selectMultiple"])
,("gtk_file_chooser_get_select_multiple", ["returns"])
,("gtk_file_chooser_get_filenames", ["returns"])
,("gtk_file_chooser_add_filter", ["filter"])
,("gtk_file_chooser_remove_filter", ["filter"])
,("gtk_file_chooser_set_filter", ["filter"])
,("gtk_file_chooser_add_shortcut_folder", ["returns"])
,("gtk_file_chooser_remove_shortcut_folder", ["returns"])
,("gtk_file_chooser_add_shortcut_folder_uri", ["returns"])
,("gtk_file_chooser_remove_shortcut_folder_uri", ["returns"])
,("gtk_file_chooser_get_uris", ["returns"])
,("gtk_file_chooser_list_filters", ["returns"])
,("gtk_file_chooser_list_shortcut_folders", ["returns"])
,("gtk_file_chooser_list_shortcut_folder_uris", ["returns"])
,("gtk_font_selection_get_preview_text", ["returns"])
,("gtk_font_selection_set_preview_text", ["text"])
,("gtk_font_selection_dialog_get_preview_text", ["returns"])
,("gtk_font_selection_dialog_set_preview_text", ["text"])
,("gtk_text_mark_get_name", ["returns"])
,("gtk_text_mark_get_buffer", ["returns"])
,("gtk_text_mark_get_visible", ["returns"])
,("gtk_text_mark_get_deleted", ["returns"])
,("gtk_text_mark_set_visible", ["setting"])
,("gtk_text_mark_get_left_gravity", ["returns"])
,("gtk_text_tag_new", ["name"])
,("gtk_text_tag_get_priority", ["returns"])
,("gtk_text_tag_set_priority", ["priority"])
,("gtk_text_tag_table_add", ["tag"])
,("gtk_text_tag_table_remove", ["tag"])
,("gtk_text_tag_table_get_size", ["returns"])
,("gtk_text_buffer_get_line_count", ["returns"])
,("gtk_text_buffer_get_char_count", ["returns"])
,("gtk_text_buffer_get_tag_table", ["returns"])
,("gtk_text_buffer_get_text", ["returns"])
,("gtk_text_buffer_get_slice", ["returns"])
,("gtk_text_buffer_insert_at_cursor", ["text", "len"])
,("gtk_text_buffer_get_insert", ["returns"])
,("gtk_text_buffer_get_selection_bound", ["returns"])
,("gtk_text_buffer_set_modified", ["setting"])
,("gtk_text_buffer_get_end_iter", ["iter"])
,("gtk_text_view_new_with_buffer", ["buffer"])
,("gtk_text_view_set_buffer", ["buffer"])
,("gtk_text_view_get_buffer", ["returns"])
,("gtk_text_view_get_iter_location", ["iter", "location"])
,("gtk_text_view_set_wrap_mode", ["wrapMode"])
,("gtk_text_view_get_wrap_mode", ["returns"])
,("gtk_text_view_set_editable", ["setting"])
,("gtk_text_view_get_editable", ["returns"])
,("gtk_text_view_set_cursor_visible", ["setting"])
,("gtk_text_view_get_cursor_visible", ["returns"])
,("gtk_text_view_set_pixels_above_lines", ["pixelsAboveLines"])
,("gtk_text_view_get_pixels_above_lines", ["returns"])
,("gtk_text_view_set_pixels_below_lines", ["pixelsBelowLines"])
,("gtk_text_view_get_pixels_below_lines", ["returns"])
,("gtk_text_view_set_pixels_inside_wrap", ["pixelsInsideWrap"])
,("gtk_text_view_get_pixels_inside_wrap", ["returns"])
,("gtk_text_view_set_justification", ["justification"])
,("gtk_text_view_get_justification", ["returns"])
,("gtk_text_view_get_default_attributes", ["returns"])
,("gtk_color_button_get_color", ["color"])
,("gtk_combo_box_get_wrap_width", ["returns"])
,("gtk_combo_box_get_row_span_column", ["returns"])
,("gtk_combo_box_get_column_span_column", ["returns"])
,("gtk_combo_box_get_active_text", ["returns"])
,("gtk_combo_box_get_add_tearoffs", ["returns"])
,("gtk_combo_box_set_focus_on_click", ["returns"])
,("gtk_image_get_pixel_size", ["returns"])
,("gtk_image_set_from_file", ["filename"])
,("gtk_progress_bar_set_ellipsize", ["mode"])
,("gtk_progress_bar_get_ellipsize", ["returns"])
,("gtk_widget_get_modifier_style", ["returns"])
,("gtk_widget_get_default_direction", ["returns"])
,("gtk_widget_get_direction", ["returns"])
,("gtk_widget_set_direction", ["dir"])
,("gtk_widget_get_name", ["returns"])
,("gtk_text_view_get_overwrite", ["returns"])
,("gtk_action_get_name", ["returns"])
,("gtk_toggle_action_get_active", ["returns"])
,("gtk_toggle_action_set_draw_as_radio", ["drawAsRadio"])
,("gtk_toggle_action_get_draw_as_radio", ["returns"])
,("gtk_separator_tool_item_set_draw", ["draw"])
,("gtk_separator_tool_item_get_draw", ["returns"])
,("gtk_tool_button_get_stock_id", ["returns"])
,("gtk_ui_manager_get_action_groups", ["returns"])
,("gtk_action_group_set_sensitive", ["sensitive"])
,("gtk_action_group_get_sensitive", ["returns"])
,("gtk_action_group_get_visible", ["returns"])
,("gtk_action_group_set_visible", ["visible"])
,("gtk_action_group_remove_action", ["action"])
,("gtk_menu_tool_button_get_menu", ["returns"])
,("gtk_toggle_tool_button_set_active", ["isActive"])
,("gtk_toggle_tool_button_get_active", ["returns"])
,("gtk_tool_button_get_label", ["returns"])
,("gtk_tool_button_get_use_underline", ["returns"])
,("gtk_tool_button_set_use_underline", ["useUnderline"])
,("gtk_action_group_add_action", ["action"])
,("gtk_action_get_proxies", ["returns"])
,("gtk_about_dialog_get_authors", ["returns"])
,("gtk_about_dialog_get_artists", ["returns"])
,("gtk_about_dialog_get_documenters", ["returns"])
,("gtk_about_dialog_get_license", ["returns"])
,("gtk_about_dialog_get_version", ["returns"])
,("gtk_about_dialog_get_copyright", ["returns"])
,("gtk_about_dialog_get_comments", ["returns"])
,("gtk_about_dialog_get_website", ["returns"])
,("gtk_about_dialog_get_website_label", ["returns"])
,("gtk_about_dialog_get_translator_credits", ["returns"])
,("gtk_about_dialog_get_logo", ["returns"])
,("gtk_about_dialog_get_logo_icon_name", ["returns"])
,("gtk_about_dialog_set_version", ["version"])
,("gtk_about_dialog_set_copyright", ["copyright"])
,("gtk_about_dialog_set_comments", ["comments"])
,("gtk_about_dialog_set_website_label", ["websiteLabel"])
,("gtk_about_dialog_set_translator_credits", ["translatorCredits"])
,("gtk_file_selection_get_selections", ["returns"])
,("gtk_tree_model_get_flags", ["returns"])
]
nukeParameterDocumentation :: String -> String -> Bool
nukeParameterDocumentation = nukeParamDoc
-- On win32 for glib/gtk 2.6 they changed the interpretation of functions that
-- take or return system file names (as opposed to user displayable
-- representations of file names). Previously the string encoding of the file
-- name was that of the systems native 'codepage' which was usually ascii but
-- could be one of several obscure multi-byte encodings. For 2.6 they have
-- changed to always use a UTF8 encoding. However to maintain binary backwards
-- compatability they kept the old names and added new ones with a _utf8 suffix
-- for the new interpretation. However the old names are only in the binary,
-- they are not exposed through the C header files so all software building
-- against glib/gtk 2.6 on windows must use the _utf8 versions. Hence we
-- generate code uses the _utf8 version if we're building on windows and using
-- gtk version 2.6 or later. Ugh.
win32FileNameFunctions :: Set String
win32FileNameFunctions = Set.fromList
["gtk_image_new_from_file"
,"gdk_pixbuf_new_from_file"
,"gdk_pixbuf_savev"
,"gtk_icon_source_get_filename"
,"gtk_icon_source_set_filename"
,"gtk_image_set_from_file"
,"gtk_file_chooser_get_filename"
,"gtk_file_chooser_set_filename"
,"gtk_file_chooser_select_filename"
,"gtk_file_chooser_unselect_filename"
,"gtk_file_chooser_get_filenames"
,"gtk_file_chooser_set_current_folder"
,"gtk_file_chooser_get_current_folder"
,"gtk_file_chooser_get_preview_filename"
,"gtk_file_chooser_add_shortcut_folder"
,"gtk_file_chooser_remove_shortcut_folder"
,"gtk_file_chooser_list_shortcut_folders"
,"gtk_file_selection_set_filename"
,"gtk_file_selection_get_filename"
,"gtk_file_selection_get_selections"
,"gtk_ui_manager_add_ui_from_file"
,"gtk_window_set_icon_from_file"]
actionSignalWanted :: String -> String -> Bool
actionSignalWanted "GtkButton" "clicked" = True
actionSignalWanted "GtkWidget" "popup_menu" = True
actionSignalWanted "GtkWidget" "show_help" = True
actionSignalWanted _ _ = False
| k0001/gtk2hs | tools/apiGen/src/MarshalFixup.hs | gpl-3.0 | 24,475 | 0 | 21 | 2,568 | 4,918 | 3,135 | 1,783 | 488 | 3 |
{-#LANGUAGE RecordWildCards, ScopedTypeVariables, TypeFamilies#-}
module CV.Features (SURFParams, defaultSURFParams, mkSURFParams, getSURF
,moments,Moments,getSpatialMoment,getCentralMoment,getNormalizedCentralMoment) where
import CV.Image
import CV.Bindings.Types
import CV.Bindings.Features
import Foreign.Ptr
import Control.Monad
import Foreign.Storable
import Foreign.Marshal.Array
import Foreign.Marshal.Utils
import Utils.GeometryClass
import System.IO.Unsafe
-- TODO: Move this to some utility module
-- withMask :: Maybe (Image GrayScale D8) -> (Ptr C'CvArr -> IO α) -> IO α
-- withMask m f = case m of
-- Just m -> withImage m (f.castPtr)
-- Nothing -> f nullPtr
-- | Parameters for SURF feature extraction
newtype SURFParams = SP C'CvSURFParams deriving Show
mkSURFParams :: Double
-- ^ only features with keypoint.hessian
-- larger than that are extracted.
-- good default value is ~300-500 (can depend on the
-- average local contrast and sharpness of the image).
-- user can further filter out some features based on
-- their hessian values and other characteristics.
-> Int
-- ^ The number of octaves to be used for extraction.
-- With each next octave the feature size is doubled
-- (3 by default)
-> Int
-- ^ The number of layers within each octave (4 by default)
-> Bool
-- ^ If true, getSurf returns extended descriptors of 128 floats. Otherwise
-- returns 64 floats.
-> SURFParams
mkSURFParams a b c d = SP $ C'CvSURFParams (fromBool d)
(realToFrac a)
(fromIntegral b)
(fromIntegral c)
-- | Default parameters for getSURF
defaultSURFParams :: SURFParams
defaultSURFParams = mkSURFParams 400 3 4 False
-- | Extract Speeded Up Robust Features from an image.
getSURF :: SURFParams
-- ^ Method parameters. See `defaultSURFParams` and `mkSURFParams`
-> Image GrayScale D8
-- ^ Input GrayScale image
-> Maybe (Image GrayScale D8)
-- ^ Optional Binary mask image
-> [(C'CvSURFPoint,[Float])]
getSURF (SP params) image mask = unsafePerformIO $
withNewMemory $ \ptr_mem ->
withMask mask $ \ptr_mask ->
with nullPtr $ \ptr_ptr_keypoints ->
with nullPtr $ \ptr_ptr_descriptors ->
with params $ \ptr_params ->
withImage image $ \ptr_image -> do
ptr_keypoints' <- peek ptr_ptr_keypoints
c'wrapExtractSURF (castPtr ptr_image) ptr_mask ptr_ptr_keypoints
ptr_ptr_descriptors ptr_mem ptr_params 0
ptr_keypoints <- peek ptr_ptr_keypoints
ptr_descriptors <- peek ptr_ptr_descriptors
a <- cvSeqToList ptr_keypoints
b <- if c'CvSURFParams'extended params == 1
then do
es :: [FloatBlock128] <- cvSeqToList ptr_descriptors
return (map (\(FP128 e) -> e) es)
else do
es :: [FloatBlock64] <- cvSeqToList ptr_descriptors
return (map (\(FP64 e) -> e) es)
return (zip a b)
newtype FloatBlock64 = FP64 [Float] deriving (Show)
newtype FloatBlock128 = FP128 [Float] deriving (Show)
instance Storable FloatBlock64 where
sizeOf _ = sizeOf (undefined :: Float) * 64
alignment _ = 4
peek ptr = FP64 `fmap` peekArray 64 (castPtr ptr)
poke ptr (FP64 e) = pokeArray (castPtr ptr) e
instance Storable FloatBlock128 where
sizeOf _ = sizeOf (undefined :: Float) * 128
alignment _ = 4
peek ptr = FP128 `fmap` peekArray 128 (castPtr ptr)
poke ptr (FP128 e) = pokeArray (castPtr ptr) e
type Moments = C'CvMoments
moments :: Image GrayScale D32 -> Moments
moments img = unsafePerformIO $
withGenImage img $ \c_img ->
with (C'CvMoments 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) $ \res -> do
c'cvMoments c_img res 0
peek res
getSpatialMoment :: (Int,Int) -> Moments -> Double
getSpatialMoment (x,y) m = realToFrac $
unsafePerformIO $
with m $ \c_m ->
c'cvGetSpatialMoment c_m (fromIntegral x) (fromIntegral y)
getCentralMoment :: (Int,Int) -> Moments -> Double
getCentralMoment (x,y) m = realToFrac $
unsafePerformIO $
with m $ \c_m ->
c'cvGetCentralMoment c_m (fromIntegral x) (fromIntegral y)
getNormalizedCentralMoment :: (Int,Int) -> Moments -> Double
getNormalizedCentralMoment (x,y) m = realToFrac $
unsafePerformIO $
with m $ \c_m ->
c'cvGetNormalizedCentralMoment c_m (fromIntegral x) (fromIntegral y)
| BeautifulDestinations/CV | CV/Features.hs | bsd-3-clause | 5,004 | 0 | 29 | 1,621 | 1,090 | 577 | 513 | 84 | 2 |
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow 1994-2004
--
-- -----------------------------------------------------------------------------
{-# OPTIONS_GHC -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
-- http://ghc.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details
module SPARC.Regs (
-- registers
showReg,
virtualRegSqueeze,
realRegSqueeze,
classOfRealReg,
allRealRegs,
-- machine specific info
gReg, iReg, lReg, oReg, fReg,
fp, sp, g0, g1, g2, o0, o1, f0, f1, f6, f8, f22, f26, f27,
-- allocatable
allocatableRegs,
-- args
argRegs,
allArgRegs,
callClobberedRegs,
--
mkVirtualReg,
regDotColor
)
where
import CodeGen.Platform.SPARC
import Reg
import RegClass
import Size
import Unique
import Outputable
import FastTypes
import FastBool
{-
The SPARC has 64 registers of interest; 32 integer registers and 32
floating point registers. The mapping of STG registers to SPARC
machine registers is defined in StgRegs.h. We are, of course,
prepared for any eventuality.
The whole fp-register pairing thing on sparcs is a huge nuisance. See
includes/stg/MachRegs.h for a description of what's going on
here.
-}
-- | Get the standard name for the register with this number.
showReg :: RegNo -> String
showReg n
| n >= 0 && n < 8 = "%g" ++ show n
| n >= 8 && n < 16 = "%o" ++ show (n-8)
| n >= 16 && n < 24 = "%l" ++ show (n-16)
| n >= 24 && n < 32 = "%i" ++ show (n-24)
| n >= 32 && n < 64 = "%f" ++ show (n-32)
| otherwise = panic "SPARC.Regs.showReg: unknown sparc register"
-- Get the register class of a certain real reg
classOfRealReg :: RealReg -> RegClass
classOfRealReg reg
= case reg of
RealRegSingle i
| i < 32 -> RcInteger
| otherwise -> RcFloat
RealRegPair{} -> RcDouble
-- | regSqueeze_class reg
-- Calculuate the maximum number of register colors that could be
-- denied to a node of this class due to having this reg
-- as a neighbour.
--
{-# INLINE virtualRegSqueeze #-}
virtualRegSqueeze :: RegClass -> VirtualReg -> FastInt
virtualRegSqueeze cls vr
= case cls of
RcInteger
-> case vr of
VirtualRegI{} -> _ILIT(1)
VirtualRegHi{} -> _ILIT(1)
_other -> _ILIT(0)
RcFloat
-> case vr of
VirtualRegF{} -> _ILIT(1)
VirtualRegD{} -> _ILIT(2)
_other -> _ILIT(0)
RcDouble
-> case vr of
VirtualRegF{} -> _ILIT(1)
VirtualRegD{} -> _ILIT(1)
_other -> _ILIT(0)
_other -> _ILIT(0)
{-# INLINE realRegSqueeze #-}
realRegSqueeze :: RegClass -> RealReg -> FastInt
realRegSqueeze cls rr
= case cls of
RcInteger
-> case rr of
RealRegSingle regNo
| regNo < 32 -> _ILIT(1)
| otherwise -> _ILIT(0)
RealRegPair{} -> _ILIT(0)
RcFloat
-> case rr of
RealRegSingle regNo
| regNo < 32 -> _ILIT(0)
| otherwise -> _ILIT(1)
RealRegPair{} -> _ILIT(2)
RcDouble
-> case rr of
RealRegSingle regNo
| regNo < 32 -> _ILIT(0)
| otherwise -> _ILIT(1)
RealRegPair{} -> _ILIT(1)
_other -> _ILIT(0)
-- | All the allocatable registers in the machine,
-- including register pairs.
allRealRegs :: [RealReg]
allRealRegs
= [ (RealRegSingle i) | i <- [0..63] ]
++ [ (RealRegPair i (i+1)) | i <- [32, 34 .. 62 ] ]
-- | Get the regno for this sort of reg
gReg, lReg, iReg, oReg, fReg :: Int -> RegNo
gReg x = x -- global regs
oReg x = (8 + x) -- output regs
lReg x = (16 + x) -- local regs
iReg x = (24 + x) -- input regs
fReg x = (32 + x) -- float regs
-- | Some specific regs used by the code generator.
g0, g1, g2, fp, sp, o0, o1, f0, f1, f6, f8, f22, f26, f27 :: Reg
f6 = RegReal (RealRegSingle (fReg 6))
f8 = RegReal (RealRegSingle (fReg 8))
f22 = RegReal (RealRegSingle (fReg 22))
f26 = RegReal (RealRegSingle (fReg 26))
f27 = RegReal (RealRegSingle (fReg 27))
-- g0 is always zero, and writes to it vanish.
g0 = RegReal (RealRegSingle (gReg 0))
g1 = RegReal (RealRegSingle (gReg 1))
g2 = RegReal (RealRegSingle (gReg 2))
-- FP, SP, int and float return (from C) regs.
fp = RegReal (RealRegSingle (iReg 6))
sp = RegReal (RealRegSingle (oReg 6))
o0 = RegReal (RealRegSingle (oReg 0))
o1 = RegReal (RealRegSingle (oReg 1))
f0 = RegReal (RealRegSingle (fReg 0))
f1 = RegReal (RealRegSingle (fReg 1))
-- | Produce the second-half-of-a-double register given the first half.
{-
fPair :: Reg -> Maybe Reg
fPair (RealReg n)
| n >= 32 && n `mod` 2 == 0 = Just (RealReg (n+1))
fPair (VirtualRegD u)
= Just (VirtualRegHi u)
fPair reg
= trace ("MachInstrs.fPair: can't get high half of supposed double reg " ++ showPpr reg)
Nothing
-}
-- | All the regs that the register allocator can allocate to,
-- with the the fixed use regs removed.
--
allocatableRegs :: [RealReg]
allocatableRegs
= let isFree rr
= case rr of
RealRegSingle r
-> isFastTrue (freeReg r)
RealRegPair r1 r2
-> isFastTrue (freeReg r1)
&& isFastTrue (freeReg r2)
in filter isFree allRealRegs
-- | The registers to place arguments for function calls,
-- for some number of arguments.
--
argRegs :: RegNo -> [Reg]
argRegs r
= case r of
0 -> []
1 -> map (RegReal . RealRegSingle . oReg) [0]
2 -> map (RegReal . RealRegSingle . oReg) [0,1]
3 -> map (RegReal . RealRegSingle . oReg) [0,1,2]
4 -> map (RegReal . RealRegSingle . oReg) [0,1,2,3]
5 -> map (RegReal . RealRegSingle . oReg) [0,1,2,3,4]
6 -> map (RegReal . RealRegSingle . oReg) [0,1,2,3,4,5]
_ -> panic "MachRegs.argRegs(sparc): don't know about >6 arguments!"
-- | All all the regs that could possibly be returned by argRegs
--
allArgRegs :: [Reg]
allArgRegs
= map (RegReal . RealRegSingle) [oReg i | i <- [0..5]]
-- These are the regs that we cannot assume stay alive over a C call.
-- TODO: Why can we assume that o6 isn't clobbered? -- BL 2009/02
--
callClobberedRegs :: [Reg]
callClobberedRegs
= map (RegReal . RealRegSingle)
( oReg 7 :
[oReg i | i <- [0..5]] ++
[gReg i | i <- [1..7]] ++
[fReg i | i <- [0..31]] )
-- | Make a virtual reg with this size.
mkVirtualReg :: Unique -> Size -> VirtualReg
mkVirtualReg u size
| not (isFloatSize size)
= VirtualRegI u
| otherwise
= case size of
FF32 -> VirtualRegF u
FF64 -> VirtualRegD u
_ -> panic "mkVReg"
regDotColor :: RealReg -> SDoc
regDotColor reg
= case classOfRealReg reg of
RcInteger -> text "blue"
RcFloat -> text "red"
_other -> text "green"
| ryantm/ghc | compiler/nativeGen/SPARC/Regs.hs | bsd-3-clause | 6,744 | 208 | 12 | 1,583 | 1,342 | 936 | 406 | 152 | 10 |
<?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="pl-PL">
<title>Common Library</title>
<maps>
<homeID>commonlib</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/commonlib/src/main/javahelp/help_pl_PL/helpset_pl_PL.hs | apache-2.0 | 965 | 90 | 29 | 156 | 390 | 209 | 181 | -1 | -1 |
{-# OPTIONS_GHC -cpp #-}
{-+
This module implements environments (symbol tables) as finite maps.
Finite maps are not necessarily faster than simple association lists, since
although lookups change from O(n) to O(log n), extension changes from
O(1) to O(log n), and the latter cost can be the dominating cost...
-}
module TiEnvFM(Env,extenv1,extenv,empty,lookup,domain,range) where
import Prelude hiding (lookup) -- for Hugs
import qualified Prelude -- Haskell report change workaround
import Map60204
--import PrettyPrint(Printable(..),fsep) -- for debugging
#if __GLASGOW_HASKELL__ >= 604
import qualified Data.Map as M (Map)
newtype Env key info = Env (M.Map key info)
#else
import qualified Data.FiniteMap as M (FiniteMap)
newtype Env key info = Env (M.FiniteMap key info)
#endif
extenv1 x t (Env bs) = Env (insertM x t bs)
extenv bs1 (Env bs2) = Env (addListToM bs2 bs1)
empty = Env emptyM
lookup (Env env) x = lookupM x env
domain (Env env) = keysM env
range (Env env) = elemsM env
-- Why isn't there a Show instance for FiniteMap?!
instance (Show key,Show info) => Show (Env key info) where
showsPrec n (Env env) = showsPrec n (toListM env)
-- Why isn't there a Functor instance for FiniteMap?!
instance Functor (Env key) where
fmap f (Env bs) = Env (mapM' f bs)
{-
-- For debugging:
instance (Printable key,Printable info) => Printable (Env key info) where
ppi (Env env) = fsep (keysFM env)
-}
| kmate/HaRe | old/tools/base/TI/TiEnvFM.hs | bsd-3-clause | 1,422 | 0 | 8 | 249 | 307 | 168 | 139 | 17 | 1 |
module B (name) where
name :: String
name = "Samantha"
| sdiehl/ghc | testsuite/tests/driver/T16511/B1.hs | bsd-3-clause | 56 | 0 | 4 | 11 | 19 | 12 | 7 | 3 | 1 |
module Mod120_A(T) where
data T = Foo
| urbanslug/ghc | testsuite/tests/module/Mod120_A.hs | bsd-3-clause | 39 | 0 | 5 | 8 | 16 | 10 | 6 | 2 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Main where
import Turtle
import qualified Data.Maybe as Maybe
import qualified Search as Search
main :: IO ()
main = sh $ do
boss <- options "Day 21" parser
let minimal = Loadout 0 Nothing Nothing Nothing
let won_fight load = battle (makePlayer load) boss == "Player"
cheapest_steps <-
case Search.djikstra upgrade won_fight [] minimal of
Just victory -> return (snd victory)
Nothing -> die "Victory is impossible!"
let cheapest = snd $ last cheapest_steps
let cheapest_cost = loadoutCost cheapest
printf "Cheapest winning loadout (part 1):\n"
printf (" "%s%"\n") . itemName $ weapons !! weaponIdx cheapest
printf (" "%s%"\n") $
maybe "No armor" (itemName . (armors !!)) (armorIdx cheapest)
printf (" "%s%"\n") $
maybe "No left ring" (itemName . (rings !!)) (leftRingIdx cheapest)
printf (" "%s%"\n") $
maybe "No right ring" (itemName . (rings !!)) (rightRingIdx cheapest)
printf ("Total cost (part 1): "%d%"\n") cheapest_cost
let maximal = Loadout 4 (Just 4) (Just 4) (Just 5)
most_expensive_steps <-
case Search.djikstra downgrade (not . won_fight) [] maximal of
Just victory -> return (snd victory)
Nothing -> die "Victory is certain!"
let most_expensive = snd $ last most_expensive_steps
let most_expensive_cost = loadoutCost most_expensive
printf "Most expensive losing loadout (part 2):\n"
printf (" "%s%"\n") . itemName $ weapons !! weaponIdx most_expensive
printf (" "%s%"\n") $
maybe "No armor" (itemName . (armors !!)) (armorIdx most_expensive)
printf (" "%s%"\n") $
maybe "No left ring" (itemName . (rings !!)) (leftRingIdx most_expensive)
printf (" "%s%"\n") $
maybe "No right ring" (itemName . (rings !!)) (rightRingIdx most_expensive)
printf ("Total cost (part 2): "%d%"\n") most_expensive_cost
battle :: Character -> Character -> PlayerName
battle p1 p2
| hp p1 <= 0 = name p2
| otherwise = battle damaged_p2 p1
where
damaged_p2 =
let raw_damage = damage p1 - armor p2
in p2 {hp = hp p2 - if raw_damage < 1 then 1 else raw_damage}
upgrade ::
Loadout -- current loadout
-> [(Int, Loadout)] -- [(incremental cost, new loadout)]
upgrade loadout =
Maybe.catMaybes [
(\idx -> loadout { weaponIdx = idx })
<$> try_upgrade (Just $ weaponIdx loadout) weapons,
(\idx -> loadout { armorIdx = Just idx })
<$> try_upgrade (armorIdx loadout) armors,
do
ridx <- rightRingIdx loadout
lidx <- try_upgrade (leftRingIdx loadout) rings
if lidx < ridx
then Just $ loadout {leftRingIdx = Just lidx}
else Nothing
,
(\idx -> loadout { rightRingIdx = Just idx })
<$> try_upgrade (rightRingIdx loadout) rings
]
& map (\new -> (loadoutCost new - loadoutCost loadout, new))
where
try_upgrade Nothing table = Just 0
try_upgrade (Just idx) table =
if idx + 1 >= length table
then Nothing
else Just (idx + 1)
downgrade ::
Loadout -- current loadout
-> [(Int, Loadout)] -- [(incremental savings, new loadout)]
downgrade loadout =
Maybe.catMaybes [
do
wmidx <- try_downgrade (Just $ weaponIdx loadout) weapons
(\idx -> loadout { weaponIdx = idx }) <$> wmidx,
(\midx -> loadout { armorIdx = midx })
<$> try_downgrade (armorIdx loadout) armors,
(\midx -> loadout { leftRingIdx = midx })
<$> try_downgrade (leftRingIdx loadout) rings,
do
rmidx <- try_downgrade (rightRingIdx loadout) rings
let lmidx = leftRingIdx loadout
if Maybe.isNothing lmidx && Maybe.isNothing rmidx || lmidx < rmidx
then Just $ loadout {rightRingIdx = rmidx}
else Nothing
]
& map (\new -> (loadoutCost loadout - loadoutCost new, new))
where
try_downgrade Nothing table = Nothing
try_downgrade (Just idx) table =
if idx == 0
then Just Nothing
else Just . Just $ idx - 1
loadoutCost :: Loadout -> Int
loadoutCost Loadout{..} =
cost (weapons !! weaponIdx)
+ maybe 0 (cost . (armors !!)) armorIdx
+ maybe 0 (cost . (rings !!)) leftRingIdx
+ maybe 0 (cost . (rings !!)) rightRingIdx
makePlayer :: Loadout -> Character
makePlayer Loadout{..} =
Character {
name = "Player",
hp = 100,
damage =
damageBonus (weapons !! weaponIdx)
+ maybe 0 (damageBonus . (rings !!)) leftRingIdx
+ maybe 0 (damageBonus . (rings !!)) rightRingIdx,
armor =
maybe 0 (armorBonus . (armors !!)) armorIdx
+ maybe 0 (armorBonus . (rings !!)) leftRingIdx
+ maybe 0 (armorBonus . (rings !!)) rightRingIdx
}
type PlayerName = Text
data Character = Character {
name :: Text,
hp :: Int,
damage :: Int,
armor :: Int
} deriving (Show)
data Item = Item {
itemName :: Text,
cost :: Int,
damageBonus :: Int,
armorBonus :: Int
} deriving (Eq, Ord, Show)
data Loadout = Loadout {
weaponIdx :: Int,
armorIdx :: Maybe Int,
leftRingIdx :: Maybe Int,
rightRingIdx :: Maybe Int
} deriving (Eq, Ord, Show)
weapons = [
Item "Dagger" 8 4 0,
Item "Shortsword" 10 5 0,
Item "Warhammer" 25 6 0,
Item "Longsword" 40 7 0,
Item "Greataxe" 74 8 0
]
armors = [
Item "Leather" 13 0 1,
Item "Chainmail" 31 0 2,
Item "Splintmail" 53 0 3,
Item "Bandedmail" 75 0 4,
Item "Platemail" 102 0 5
]
rings = [
Item "Defense +1" 20 0 1,
Item "Damage +1" 25 1 0,
Item "Defense +2" 40 0 2,
Item "Damage +2" 50 2 0,
Item "Defense +3" 80 0 3,
Item "Damage +3" 100 3 0
]
parser =
Character "Boss"
<$> (fromIntegral <$> optInteger "health" 'p' "Boss health")
<*> (fromIntegral <$> optInteger "damage" 'd' "Boss damage")
<*> (fromIntegral <$> optInteger "armor" 'a' "Boss armor")
| devonhollowood/adventofcode | 2015/day21/day21.hs | mit | 5,700 | 0 | 15 | 1,341 | 2,086 | 1,077 | 1,009 | 158 | 4 |
module Three where
import Test.QuickCheck
import Test.QuickCheck.Checkers
data Three a b c = Three a b c
deriving (Eq, Ord, Show)
--
instance Functor (Three a b) where
fmap f (Three a b c) = Three a b (f c)
instance Foldable (Three a b) where
foldMap f (Three a b c) = f c
instance Traversable (Three a b) where
traverse f (Three a b c) = Three a b <$> f c
--
instance (Arbitrary a, Arbitrary b, Arbitrary c) => Arbitrary (Three a b c) where
arbitrary = Three <$> arbitrary <*> arbitrary <*> arbitrary
instance (Eq a, Eq b, Eq c) => EqProp (Three a b c) where
(=-=) = eq
| NickAger/LearningHaskell | HaskellProgrammingFromFirstPrinciples/Chapter21/Exercises/src/Three.hs | mit | 593 | 0 | 8 | 137 | 286 | 150 | 136 | 15 | 0 |
module Gen.Core
( surroundWith
, smallArbitrary
, maybeGen
, genNothing
, module Language.GoLite.Syntax
, module Control.Monad
, module Test.Hspec
, module Test.Hspec.QuickCheck
, module Test.QuickCheck
) where
import Language.GoLite.Syntax
import Control.Monad
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck hiding ( Positive ) -- Conflicts with Types.Positive
import Test.QuickCheck.Gen ( Gen(MkGen) )
-- | Creates a function which will surround a string with the given string.
surroundWith :: String -> (String -> String)
surroundWith s = (\x -> s ++ x ++ s)
-- | Generates a size-1 arbitrary value.
smallArbitrary :: Arbitrary a => Gen a
smallArbitrary = (resize 1 arbitrary)
-- | Generates either just a value from the given generator, or nothing.
-- The body is the same as the instance for Arbitrary (Maybe a)
-- (https://goo.gl/zimSLs), -- but available as a standalone function.
maybeGen :: Gen a -> Gen (Maybe a)
maybeGen g = frequency [(1, pure Nothing), (3, liftM Just g)]
-- | Generates Nothing.
genNothing :: Gen (Maybe a)
genNothing = (MkGen $ \_ _ -> Nothing) | djeik/goto | test/Gen/Core.hs | mit | 1,104 | 0 | 8 | 176 | 266 | 157 | 109 | 24 | 1 |
module
Foo
| chreekat/vim-haskell-syntax | test/golden/module-firstline.hs | mit | 11 | 0 | 2 | 2 | 4 | 3 | 1 | -1 | -1 |
--
-- Find the greatest product of five consecutive digits in the 1000-digit number.
--
number
= "73167176531330624919225119674426574742355349194934"
++ "96983520312774506326239578318016984801869478851843"
++ "85861560789112949495459501737958331952853208805511"
++ "12540698747158523863050715693290963295227443043557"
++ "66896648950445244523161731856403098711121722383113"
++ "62229893423380308135336276614282806444486645238749"
++ "30358907296290491560440772390713810515859307960866"
++ "70172427121883998797908792274921901699720888093776"
++ "65727333001053367881220235421809751254540594752243"
++ "52584907711670556013604839586446706324415722155397"
++ "53697817977846174064955149290862569321978468622482"
++ "83972241375657056057490261407972968652414535100474"
++ "82166370484403199890008895243450658541227588666881"
++ "16427171479924442928230863465674813919123162824586"
++ "17866458359124566529476545682848912883142607690042"
++ "24219022671055626321111109370544217506941658960408"
++ "07198403850962455444362981230987879927244284909188"
++ "84580156166097919133875499200524063689912560717606"
++ "05886116467109405077541002256983155200055935729725"
++ "71636269561882670428252483600823257530420752963450"
chunkSize = 5
chunks
= map (\ x -> take chunkSize $ drop x number) [0 .. length number - chunkSize]
toNumbers :: String -> [Int]
toNumbers
= map (\ x -> read [x] :: Int)
main = print $ maximum $ map (product . toNumbers) chunks
| stu-smith/project-euler-haskell | Euler-008.hs | mit | 1,556 | 41 | 9 | 217 | 226 | 103 | 123 | 28 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module Dissent.Protocol.Shuffle.Leader where
import Control.Monad.Error
import Control.Monad.Trans.Resource
import Data.List (sortBy)
import qualified Network.Socket as NS
import qualified Dissent.Crypto.Rsa as R
import qualified Dissent.Network.Quorum as NQ
import qualified Dissent.Network.Socket as NS
import qualified Dissent.Types.Quorum as TQ
import qualified Dissent.Types.Peer as TP
run :: TQ.Quorum -> IO ()
run quorum = runResourceT $ do
result <- runErrorT $ do
sockets <- phase1 quorum
ciphers <- phase2 sockets
_ <- phase3 sockets ciphers
return ()
case result of
Left e -> error ("Something went wrong: " ++ e)
Right b -> return b
-- | In the first phase, our leader will open a socket that
-- slaves can connect to, and will wait for all slaves to
-- connect to the quorum.
--
-- This is a blocking operation.
phase1 :: ( MonadIO m
, MonadError String m
, MonadResource m)
=> TQ.Quorum -- ^ The Quorum we operate on
-> m [NS.Socket] -- ^ The sockets we accepted
phase1 quorum =
let accepted = NQ.accept quorum TP.Leader
-- Returns all accepted sockets from all slaves.
--
-- This is a blocking operation.
sockets = (return . map fst) =<< accepted
-- After a connection has been established with a slave, we
-- expect a handshake to occur. At the present moment, this
-- handshake only involves a peer telling us his id, so we know
-- which socket to associate with which peer.
--
-- This is a blocking operation.
handShake socket = do
peerId <- liftIO $ NS.receiveAndDecode socket
either throwError return peerId
-- Now, after this process, we have a list of sockets, and a list
-- of peer ids. Once we put them in a zipped list, we have a convenient
-- way to sort them by peer id, thus allowing us to easily look up a
-- socket by a peer's id.
sortSockets :: [(TP.Id, NS.Socket)] -> [(TP.Id, NS.Socket)]
sortSockets =
let predicate lhs rhs | fst lhs < fst rhs = LT
| fst lhs > fst rhs = GT
| otherwise = EQ
in sortBy predicate
in do
unorderedSockets <- liftResourceT sockets
-- Retrieve all peer ids
peerIds <- mapM handShake unorderedSockets
-- Combine the sockets with the peer ids, sort them based on the peer id,
-- and get a list of the sockets out of it.
return (map snd (sortSockets (zip peerIds unorderedSockets)))
-- | In the second phase, the leader receives all the encrypted messages from all
-- the slaves.
--
-- This is a blocking operation.
phase2 :: ( MonadIO m
, MonadError String m)
=> [NS.Socket] -- ^ The Sockets we accepted
-> m [R.Encrypted] -- ^ All the encrypted messages we received from the
-- slaves.
phase2 sockets = do
ciphers <- liftIO $ mapM NS.receiveAndDecode sockets
either throwError return (sequence ciphers)
-- | In the third phase, the leader sends all the ciphers to the first node
-- in the quorum.
--
-- Note that in our implementation, the first node is always the leader
-- itself.
phase3 :: MonadIO m
=> [NS.Socket] -- ^ All connections to all slaves
-> [R.Encrypted] -- ^ The ciphers we received from all slaves
-> m ()
phase3 sockets ciphers =
let firstSocket :: NS.Socket
firstSocket = head sockets
in do
liftIO $ NS.encodeAndSend firstSocket ciphers
return ()
| solatis/dissent | src/Dissent/Protocol/Shuffle/Leader.hs | mit | 3,730 | 0 | 17 | 1,122 | 684 | 366 | 318 | 59 | 2 |
#!/usr/bin/env stack
-- stack --install-ghc runghc --package turtle
{-# LANGUAGE OverloadedStrings #-}
import Turtle
main = stdout $ grep ((star dot) <> "monads" <> (star dot)) $ input "README.md"
| JoshuaGross/haskell-learning-log | Code/turtle/grep.hs | mit | 210 | 1 | 12 | 42 | 52 | 26 | 26 | 3 | 1 |
Config
{ font = "xft:Inconsolata:size=13"
, bgColor = "#3a3a3a"
, fgColor = "#dcdccc"
, position = Top
, commands =
[ Run MPD
[ "--template", "<statei> <fc=#8cd0d3><title></fc> - <fc=#f0dfaf><artist></fc> - <lapsed>/<remaining>"
, "--"
, "-P", "<fc=#bfebbf>>></fc>"
, "-Z", "<fc=#dca3a3>##</fc>"
, "-S", "<fc=#dca3a3>##</fc>"
] 5
, Run CoreTemp
[ "--Low", "40"
, "--High", "60"
, "--low", "#87af87"
, "--normal", "#ffd7af"
, "--high", "#dca3a3"
, "--template", "T: <core0>°C"
] 10
, Run MultiCpu
[ "--Low", "5"
, "--High", "50"
, "--low", "#87af87"
, "--normal", "#ffd7af"
, "--high", "#dca3a3"
, "--template", "P: <total>%"
] 10
, Run Memory
[ "--Low", "33"
, "--High", "66"
, "--low", "#87af87"
, "--normal", "#ffd7af"
, "--high", "#dca3a3"
, "--template", "M: <usedratio>%"
] 10
, Run DynNetwork
[ "--Low", "16384"
, "--High", "1048576"
, "--low", "#87af87"
, "--normal", "#ffd7af"
, "--high", "#dca3a3"
, "--template", "N: <rx>KB/<tx>KB"
] 10
, Run Volume "default" "Master"
[ "--template", "V: <volume>% <status>"
, "--"
, "--on", "[on]"
, "--off", "[mu]"
, "--onc", "#87af87"
, "--offc", "#dca3a3"
] 5
, Run Date "<fc=#ffd7af>%a %b %_d</fc> <fc=#8cd0d3>%l:%M</fc>" "date" 10
, Run StdinReader
]
, alignSep = "}{"
, template = "%StdinReader% }{ %mpd% | %default:Master% | %dynnetwork% | %coretemp% | %multicpu% | %memory% %date% "
}
| randalloveson/dotfiles | xmonad/.xmonad/xmobar.hs | mit | 2,230 | 0 | 9 | 1,093 | 337 | 208 | 129 | -1 | -1 |
module Rebase.Data.Functor.Sum
(
module Data.Functor.Sum
)
where
import Data.Functor.Sum
| nikita-volkov/rebase | library/Rebase/Data/Functor/Sum.hs | mit | 92 | 0 | 5 | 12 | 23 | 16 | 7 | 4 | 0 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeFamilies #-}
module App.State
( ServerState(..)
, HasConnections
, GameState
, IsConnection(..)
, defaultInitialState
, defaultInitialStateWithRandomPositions
) where
import App.ConnectionMgnt
import ClassyPrelude
import Config.GameConfig (defaultConfig, defaultConfigWithRandomPositions)
import GameNg (GameState (..), initialStateFromConfig)
import Network.Protocol (Player)
data ServerState conn =
ServerState
{ stateConnections :: ClientConnections conn
, gameState :: GameState
, playerMap :: Map Player ConnectionId
}
instance IsConnection conn => HasConnections (ServerState conn) where
type Conn (ServerState conn) = conn
getConnections =
stateConnections
setConnections conns state =
state
{ stateConnections = conns
}
defaultInitialStateWithRandomPositions :: IO (ServerState conn)
defaultInitialStateWithRandomPositions = do
config <- defaultConfigWithRandomPositions
return ServerState
{ stateConnections = ClientConnections mempty 0
, gameState = GameRunning_ $ initialStateFromConfig config
, playerMap = mempty
}
defaultInitialState :: ServerState conn
defaultInitialState =
ServerState
{ stateConnections = ClientConnections mempty 0
, gameState = GameRunning_ $ initialStateFromConfig defaultConfig
, playerMap = mempty
}
| Haskell-Praxis/core-catcher | src/App/State.hs | mit | 1,560 | 0 | 11 | 413 | 286 | 164 | 122 | 39 | 1 |
{-|
Module : TrackParameter
Description : Short description
Copyright : (c) Laurent Bulteau, Romeo Rizzi, Stéphane Vialette, 2016-1017
License : MIT
Maintainer : [email protected]
Stability : experimental
Here is a longer description of this module, containing some
commentary with @some markup@.
-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Foldable as Foldable
import System.Console.CmdArgs
import System.Random
import qualified Data.Algorithm.PPattern.Perm.Monotone as Perm.Monotone
import qualified Data.Algorithm.PPattern.Perm.Random as Perm.Random
data Options = Options { size :: Int
, trials :: Int
, seed :: Int
} deriving (Data, Typeable)
options :: Options
options = Options { size = def &= help "The permutation size"
, trials = def &= help "The number of trials"
, seed = def &= help "The seed of the random generator"
}
&= verbosity
&= summary "split-parameter v0.1.0.0, (C) Laurent Bulteau, Romeo Rizzi, Stéphane Vialette, 2016-1017"
&= program "split-parameter"
-- Estimate distribution
trackParamter :: RandomGen g => Int -> Int -> g -> [Int]
trackParamter n t = aux [] 1
where
aux acc i g
| i > t = acc
| otherwise = aux (k : acc) (i+1) g'
where
(p, g') = Perm.Random.rand' n g
k = Perm.Monotone.longestDecreasingLength p
go :: RandomGen g => Int -> Int -> g -> IO ()
go n t g = Foldable.mapM_ putStr $ fmap (\k -> show n ++ "," ++ show k ++ "\n") ks
where
ks = trackParamter n t g
main :: IO ()
main = do
opts <- cmdArgs options
go (size opts) (trials opts)$ mkStdGen (seed opts)
| vialette/ppattern-tmp | src/TrackParameter.hs | mit | 1,823 | 3 | 12 | 527 | 459 | 237 | 222 | 32 | 1 |
{-# LANGUAGE DeriveGeneric #-}
module Kantour.KcData.Map.Image where
import Data.Aeson
import GHC.Generics
import qualified Data.HashMap.Strict as HM
import Kantour.KcData.Map.Sprite
import qualified Data.Text as T
data Image = Image
{ frames :: HM.HashMap T.Text Sprite
, meta :: Maybe Value
} deriving (Generic)
instance FromJSON Image
| Javran/tuppence | src/Kantour/KcData/Map/Image.hs | mit | 347 | 0 | 10 | 53 | 90 | 56 | 34 | 12 | 0 |
pertenece :: a -> ArbolG a -> Bool
pertenece a AVG = False
pertenece a (AG r s) = if ( a == r) then true else (aux a s)
aux :: (Eq a) => a -> [ArbolG a] -> Bool
aux a [] = False;
aux a (h:t) if pertenece a h then True else aux a t
| josegury/HaskellFuntions | Arboles/HojaPerteneceArbol.hs | mit | 234 | 0 | 9 | 62 | 144 | 74 | 70 | -1 | -1 |
module Language.MSH.BuiltIn where
newClassName :: String
newClassName = "New"
newArgsTypeName :: String
newArgsTypeName = "Args"
newKwdName :: String
newKwdName = "new" | mbg/monadic-state-hierarchies | Language/MSH/BuiltIn.hs | mit | 173 | 0 | 4 | 25 | 37 | 23 | 14 | 7 | 1 |
module TypeKwonDo where
chk :: Eq b => (a -> b) -> a -> b -> Bool
chk aToB a b = aToB a == b
arith :: Num b => (a -> b) -> Integer -> a -> b
arith aToB int a = aToB a + fromInteger int
| rasheedja/HaskellFromFirstPrinciples | Chapter6/typeKwonDo.hs | mit | 187 | 0 | 8 | 52 | 107 | 54 | 53 | 5 | 1 |
module Utils where
trim :: [Char] -> [Char]
trim = reverse . removeTrailing ' ' . reverse . removeTrailing ' '
where
removeTrailing :: Char -> [Char] -> [Char]
removeTrailing _ [] = []
removeTrailing a (c:cs)
| (a == c) = removeTrailing a cs
| otherwise = (c:cs)
listOf :: Char -> Int -> [Char]
listOf _ 0 = []
listOf c i = c : listOf c (i-1)
| Qinusty/NoteUp | src/Utils.hs | gpl-2.0 | 355 | 0 | 11 | 82 | 182 | 95 | 87 | 11 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module Nirum.Parser ( Parser
, ParseError
, aliasTypeDeclaration
, annotation
, annotationSet
, docs
, enumTypeDeclaration
, file
, handleNameDuplication
, handleNameDuplicationError
, identifier
, importName
, imports
, listModifier
, mapModifier
, method
, module'
, modulePath
, name
, optionModifier
, parse
, parseFile
, recordTypeDeclaration
, serviceDeclaration
, setModifier
, typeDeclaration
, typeExpression
, typeExpressionWithoutOptionModifier
, typeIdentifier
, unboxedTypeDeclaration
, unionTypeDeclaration
) where
import Control.Monad (unless, void, when)
import Data.Void
import qualified System.IO as SIO
import qualified Data.List as L
import Data.Map.Strict as Map hiding (foldl, toList)
import Data.Set hiding (foldl)
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Text.Megaparsec hiding (ParseError, parse)
import Text.Megaparsec.Char ( char
, digitChar
, eol
, noneOf
, spaceChar
, string
, string'
)
import qualified Text.Megaparsec.Error as E
import Text.Megaparsec.Char.Lexer (charLiteral)
import Text.Read hiding (choice)
import qualified Nirum.Constructs.Annotation as A
import Nirum.Constructs.Annotation.Internal hiding ( Text
, annotations
, name
)
import qualified Nirum.Constructs.Annotation.Internal as AI
import Nirum.Constructs.Declaration (Declaration)
import qualified Nirum.Constructs.Declaration as D
import Nirum.Constructs.Docs (Docs (Docs))
import Nirum.Constructs.DeclarationSet as DeclarationSet hiding (toList)
import Nirum.Constructs.Identifier ( Identifier
, identifierRule
, reservedKeywords
, toString
)
import Nirum.Constructs.Module (Module (Module))
import Nirum.Constructs.ModulePath (ModulePath (ModulePath, ModuleName))
import Nirum.Constructs.Name (Name (Name, facialName))
import Nirum.Constructs.Service ( Method (Method)
, Parameter (Parameter)
, Service (Service)
)
import Nirum.Constructs.TypeDeclaration as TD hiding ( fields
, modulePath
, importName
)
import Nirum.Constructs.TypeExpression ( TypeExpression ( ListModifier
, MapModifier
, OptionModifier
, SetModifier
, TypeIdentifier
)
)
type Parser = Parsec Void T.Text
type ParseError = E.ParseError Char Void
-- | State-tracking 'many'.
many' :: [a] -> ([a] -> Parser a) -> Parser [a]
many' i p = do
r <- optional (p i)
case r of
Nothing -> return i
Just v -> many' (i ++ [v]) p
-- FIXME: i ++ [v] is not efficient
-- | Get the facial name of a declaration.
declFacialName :: Declaration d => d -> Identifier
declFacialName = facialName . D.name
-- CHECK: If a new reserved keyword is introduced, it has to be also
-- added to `reservedKeywords` set in the `Nirum.Constructs.Identifier`
-- module.
comment :: Parser ()
comment = string "//" >> void (many $ noneOf ("\n" :: String)) <?> "comment"
spaces :: Parser ()
spaces = skipMany $ void spaceChar <|> comment
spaces1 :: Parser ()
spaces1 = skipSome $ void spaceChar <|> comment
identifier :: Parser Identifier
identifier =
quotedIdentifier <|> bareIdentifier <?> "identifier"
where
bareIdentifier :: Parser Identifier
bareIdentifier = try $ do
ident <- lookAhead identifierRule
if ident `Data.Set.member` reservedKeywords
then fail $ "\"" ++ toString ident ++ "\" is a reserved keyword; "
++ "wrap it with backquotes to use it as a normal "
++ "identifier (i.e. \"`" ++ toString ident ++ "`\")"
else identifierRule
quotedIdentifier :: Parser Identifier
quotedIdentifier = do
char '`'
identifier' <- identifierRule
char '`'
return identifier'
name :: Parser Name
name = do
facialName' <- identifier <?> "facial name"
behindName <- option facialName' $ try $ do
spaces
char '/'
spaces
identifier <?> "behind name"
return $ Name facialName' behindName
uniqueIdentifier :: [Identifier] -> String -> Parser Identifier
uniqueIdentifier forwardNames label' = try $ do
ident <- lookAhead identP
when (ident `elem` forwardNames)
(fail $ "the " ++ label' ++ " `" ++ toString ident ++
"` is duplicated")
identP
where
identP :: Parser Identifier
identP = identifier <?> label'
uniqueName :: [Identifier] -> String -> Parser Name
uniqueName forwardNames label' = try $ do
Name fName _ <- lookAhead nameP
when (fName `elem` forwardNames)
(fail $ "the " ++ label' ++ " `" ++ toString fName ++
"` is duplicated")
nameP
where
nameP :: Parser Name
nameP = name <?> label'
integer :: Parser Integer
integer = do
v <- many digitChar
case readMaybe v of
Just i -> return i
Nothing -> fail "digit expected." -- never happened
annotationArgumentValue :: Parser AnnotationArgument
annotationArgumentValue = do
startQuote <- optional $ try $ char '"'
case startQuote of
Just _ -> do
v <- manyTill charLiteral (char '"')
return $ AI.Text $ T.pack v
Nothing ->
Integer <$> integer
annotationArgument :: Parser (Identifier, AnnotationArgument)
annotationArgument = do
arg <- identifier <?> "annotation parameter"
spaces
char '='
spaces
value <- annotationArgumentValue <?> "annotation argument value"
return (arg, value)
annotation :: Parser A.Annotation
annotation = do
char '@'
spaces
name' <- identifier
spaces
args' <- option Map.empty $ do
char '('
spaces
args <- (`sepEndBy` char ',') $ do
spaces
a <- annotationArgument
spaces
return a
spaces
char ')'
return $ Map.fromList args
return $ A.Annotation name' args'
annotationSet :: Parser A.AnnotationSet
annotationSet = do
annotations <- many $ do
spaces
a <- annotation
spaces
return a
case A.fromList annotations of
Right annotations' -> return annotations'
Left (A.AnnotationNameDuplication _) -> fail "annotation name duplicate"
typeExpression :: Parser TypeExpression
typeExpression =
try optionModifier <|> typeExpressionWithoutOptionModifier
<?> "type expression"
typeExpressionWithoutOptionModifier :: Parser TypeExpression
typeExpressionWithoutOptionModifier =
try setModifier <|> listModifier <|> mapModifier <|> typeIdentifier
typeIdentifier :: Parser TypeExpression
typeIdentifier = do
typeIdentifier' <- identifier <?> "type identifier"
return $ TypeIdentifier typeIdentifier'
optionModifier :: Parser TypeExpression
optionModifier = do
expr <- typeExpressionWithoutOptionModifier
spaces
char '?'
return $ OptionModifier expr
setModifier :: Parser TypeExpression
setModifier = do
char '{'
spaces
expr <- typeExpression <?> "element type of set type"
spaces
char '}'
return $ SetModifier expr
listModifier :: Parser TypeExpression
listModifier = do
char '['
spaces
expr <- typeExpression <?> "element type of list type"
spaces
char ']'
return $ ListModifier expr
mapModifier :: Parser TypeExpression
mapModifier = do
char '{'
spaces
key <- typeExpression <?> "key type of map type"
spaces
char ':'
spaces
value <- typeExpression <?> "value type of map type"
spaces
char '}'
return $ MapModifier key value
docs :: Parser Docs
docs = do
comments <- sepEndBy1 (do
char '#'
void $ optional $ char ' '
line <- many $ noneOf ("\r\n" :: String)
return $ T.pack line
) (eol >> spaces) <?> "comments"
return $ Docs $ T.unlines comments
annotationsWithDocs :: Monad m
=> A.AnnotationSet
-> Maybe Docs
-> m A.AnnotationSet
annotationsWithDocs set' (Just docs') = A.insertDocs docs' set'
annotationsWithDocs set' Nothing = return set'
aliasTypeDeclaration :: [Identifier] -> Parser TypeDeclaration
aliasTypeDeclaration forwardNames = do
annotationSet' <- annotationSet <?> "type alias annotations"
string' "type" <?> "type alias keyword"
spaces
typeName <- uniqueIdentifier forwardNames "alias type name"
let name' = Name typeName typeName
spaces
char '='
spaces
canonicalType' <- typeExpression <?> "canonical type of alias"
spaces
char ';'
docs' <- optional $ try $ spaces >> (docs <?> "type alias docs")
annotationSet'' <- annotationsWithDocs annotationSet' docs'
return $ TypeDeclaration name' (Alias canonicalType') annotationSet''
unboxedTypeDeclaration :: [Identifier] -> Parser TypeDeclaration
unboxedTypeDeclaration forwardNames = do
annotationSet' <- annotationSet <?> "unboxed type annotations"
string' "unboxed" <?> "unboxed type keyword"
spaces
typeName <- uniqueIdentifier forwardNames "unboxed type name"
let name' = Name typeName typeName
spaces
char '('
spaces
innerType' <- typeExpression <?> "inner type of unboxed type"
spaces
char ')'
spaces
char ';'
docs' <- optional $ try $ spaces >> (docs <?> "unboxed type docs")
annotationSet'' <- annotationsWithDocs annotationSet' docs'
return $ TypeDeclaration name' (UnboxedType innerType') annotationSet''
enumMember :: [Identifier] -> Parser EnumMember
enumMember forwardNames = do
annotationSet' <- annotationSet <?> "enum member annotations"
spaces
memberName <- uniqueName forwardNames "enum member name"
spaces
docs' <- optional $ do
d <- docs <?> "enum member docs"
spaces
return d
annotationSet'' <- annotationsWithDocs annotationSet' docs'
return $ EnumMember memberName annotationSet''
handleNameDuplication :: Declaration a
=> String
-> [a]
-> (DeclarationSet a -> Parser b)
-> Parser b
handleNameDuplication label' declarations cont = do
set <- handleNameDuplicationError label' $
DeclarationSet.fromList declarations
cont set
handleNameDuplicationError :: String -> Either NameDuplication a -> Parser a
handleNameDuplicationError _ (Right v) = return v
handleNameDuplicationError label' (Left dup) =
fail ("the " ++ nameType ++ " " ++ label' ++ " name `" ++
toString name' ++ "` is duplicated")
where
(nameType, name') = case dup of
BehindNameDuplication (Name _ bname) -> ("behind", bname)
FacialNameDuplication (Name fname _) -> ("facial", fname)
enumTypeDeclaration :: [Identifier] -> Parser TypeDeclaration
enumTypeDeclaration forwardNames = do
annotationSet' <- annotationSet <?> "enum type annotations"
string "enum" <?> "enum keyword"
spaces
typeName@(Name typeFName _) <- uniqueName forwardNames "enum type name"
spaces
frontDocs <- optional $ do
d <- docs <?> "enum type docs"
spaces
return d
char '='
spaces
docs' <- case frontDocs of
d@(Just _) -> return d
Nothing -> optional $ do
d <- docs <?> "enum type docs"
spaces
return d
annotationSet'' <- annotationsWithDocs annotationSet' docs'
members' <- sepBy1
(enumMember (typeFName : forwardNames))
(spaces >> char '|' >> spaces)
<?> "enum members"
case DeclarationSet.fromList members' of
Left (BehindNameDuplication (Name _ bname)) ->
fail ("the behind member name `" ++ toString bname ++
"` is duplicated")
Left (FacialNameDuplication (Name fname _)) ->
fail ("the facial member name `" ++ toString fname ++
"` is duplicated")
Right memberSet -> do
spaces
char ';'
return $ TypeDeclaration typeName (EnumType memberSet)
annotationSet''
fieldsOrParameters :: forall a . (String, String)
-> (Name -> TypeExpression -> A.AnnotationSet -> a)
-> Parser [a]
fieldsOrParameters (label', pluralLabel) make = do
annotationSet' <- annotationSet <?> (label' ++ " annotations")
spaces
typeExpr <- typeExpression <?> (label' ++ " type")
spaces1
name' <- name <?> (label' ++ " name")
spaces
let makeWithDocs = make name' typeExpr . A.union annotationSet'
. annotationsFromDocs
followedByComma makeWithDocs <|> do
d <- optional docs' <?> (label' ++ " docs")
return [makeWithDocs d]
where
recur :: Parser [a]
recur = fieldsOrParameters (label', pluralLabel) make
followedByComma :: (Maybe Docs -> a) -> Parser [a]
followedByComma makeWithDocs = do
char ','
spaces
d <- optional docs' <?> (label' ++ " docs")
rest <- option [] recur <?> ("rest of " ++ pluralLabel)
return $ makeWithDocs d : rest
docs' :: Parser Docs
docs' = do
d <- docs <?> (label' ++ " docs")
spaces
return d
annotationsFromDocs :: Maybe Docs -> A.AnnotationSet
annotationsFromDocs Nothing = A.empty
annotationsFromDocs (Just d) = A.singleton $ A.docs d
fields :: Parser [Field]
fields = fieldsOrParameters ("label", "labels") Field
fieldSet :: Parser (DeclarationSet Field)
fieldSet = do
fields' <- fields <?> "fields"
handleNameDuplication "field" fields' return
recordTypeDeclaration :: [Identifier] -> Parser TypeDeclaration
recordTypeDeclaration forwardNames = do
annotationSet' <- annotationSet <?> "record type annotations"
string "record" <?> "record keyword"
spaces
typeName <- uniqueName forwardNames "record type name"
spaces
char '('
spaces
docs' <- optional $ do
d <- docs <?> "record type docs"
spaces
return d
fields' <- fieldSet <?> "record fields"
spaces
char ')'
spaces
char ';'
annotationSet'' <- annotationsWithDocs annotationSet' docs'
return $ TypeDeclaration typeName (RecordType fields') annotationSet''
tag :: [Identifier] -> Parser (Tag, Bool)
tag forwardNames = do
annotationSet' <- annotationSet <?> "union tag annotations"
spaces
default' <- optional (string "default" <?> "default tag")
spaces
tagName' <- uniqueName forwardNames "union tag name"
spaces
paren <- optional $ char '('
spaces
frontDocs <- optional $ do
d <- docs <?> "union tag docs"
spaces
return d
fields' <- case paren of
Just _ -> do
spaces
f <- fieldSet <?> "union tag fields"
spaces
char ')'
return f
Nothing -> return DeclarationSet.empty
spaces
docs' <- case frontDocs of
d@(Just _) -> return d
Nothing -> optional $ do
d <- docs <?> "union tag docs"
spaces
return d
annotationSet'' <- annotationsWithDocs annotationSet' docs'
return ( Tag tagName' fields' annotationSet''
, case default' of
Just _ -> True
Nothing -> False
)
unionTypeDeclaration :: [Identifier] -> Parser TypeDeclaration
unionTypeDeclaration forwardNames = do
annotationSet' <- annotationSet <?> "union type annotations"
string "union" <?> "union keyword"
spaces
typeName <- uniqueName forwardNames "union type name"
spaces
docs' <- optional $ do
d <- docs <?> "union type docs"
spaces
return d
char '='
spaces
tags' <- sepBy1
(tag forwardNames)
(try (spaces >> char '|' >> spaces))
<?> "union tags"
let tags'' = [t | (t, _) <- tags']
let defaultTag' = do
(t''', _) <- L.find snd tags'
return t'''
spaces
char ';'
annotationSet'' <- annotationsWithDocs annotationSet' docs'
if length (L.filter snd tags') > 1
then fail "A union type cannot have more than a default tag."
else do
ut <- handleNameDuplicationError "tag" $
unionType tags'' defaultTag'
return $ TypeDeclaration typeName ut annotationSet''
typeDeclaration :: [Identifier] -> Parser TypeDeclaration
typeDeclaration forwardNames = do
-- Preconsume the common prefix (annotations) to disambiguate
-- the continued branches of parsers.
spaces
annotationSet' <- annotationSet <?> "type annotations"
spaces
typeDecl <- choice
[ unless' ["union", "record", "enum", "unboxed"]
(aliasTypeDeclaration forwardNames)
, unless' ["union", "record", "enum"]
(unboxedTypeDeclaration forwardNames)
, unless' ["union", "record"]
(enumTypeDeclaration forwardNames)
, unless' ["union"]
(recordTypeDeclaration forwardNames)
, unionTypeDeclaration forwardNames
] <?> "type declaration (e.g. enum, record, unboxed, union)"
-- In theory, though it preconsumes annotationSet' before parsing typeDecl
-- so that typeDecl itself has no annotations, to prepare for an
-- unlikely situation (that I bet it'll never happen)
-- unite the preconsumed annotationSet' with typeDecl's annotations
-- (that must be empty).
let annotations = A.union annotationSet' $ typeAnnotations typeDecl
return $ typeDecl { typeAnnotations = annotations }
where
unless' :: [T.Text] -> Parser a -> Parser a
unless' [] _ = fail "no candidates" -- Must never happen
unless' [s] p = notFollowedBy (string s) >> p
unless' (x : xs) p = notFollowedBy (string x) >> unless' xs p
parameters :: Parser [Parameter]
parameters = fieldsOrParameters ("parameter", "parameters") Parameter
parameterSet :: Parser (DeclarationSet Parameter)
parameterSet = option DeclarationSet.empty $ try $ do
params <- parameters <?> "method parameters"
handleNameDuplication "parameter" params return
method :: Parser Method
method = do
annotationSet' <- annotationSet <?> "service method annotation"
returnType <- optional $ try $ do
rt <- typeExpression <?> "method return type"
spaces1
notFollowedBy $ char '('
return rt
methodName <- name <?> "method name"
spaces
char '('
spaces
docs' <- optional $ do
d <- docs <?> "method docs"
spaces
return d
params <- parameterSet
spaces
char ')'
spaces
errorType <- optional $ do
string "throws" <?> "throws keyword"
spaces
e <- typeExpression <?> "method error type"
spaces
return e
annotationSet'' <- annotationsWithDocs annotationSet' docs'
return $ Method methodName params returnType errorType annotationSet''
methods :: Parser [Method]
methods = method `sepEndBy` try (spaces >> char ',' >> spaces)
methodSet :: Parser (DeclarationSet Method)
methodSet = do
methods' <- methods <?> "service methods"
handleNameDuplication "method" methods' return
serviceDeclaration :: [Identifier] -> Parser TypeDeclaration
serviceDeclaration forwardNames = do
annotationSet' <- annotationSet <?> "service annotation"
string "service" <?> "service keyword"
spaces
serviceName' <- uniqueName forwardNames "service name"
spaces
char '('
spaces
docs' <- optional $ do
d <- docs <?> "service docs"
spaces
return d
methods' <- methodSet <?> "service methods"
spaces
char ')'
spaces
char ';'
annotationSet'' <- annotationsWithDocs annotationSet' docs'
return $ ServiceDeclaration serviceName' (Service methods') annotationSet''
modulePath :: Parser ModulePath
modulePath = do
idents <- sepBy1 (identifier <?> "module identifier")
(try (spaces >> char '.' >> spaces))
<?> "module path"
case makePath idents of
Nothing -> fail "module path cannot be empty"
Just path -> return path
where
makePath :: [Identifier] -> Maybe ModulePath
makePath = foldl f Nothing
f :: Maybe ModulePath -> Identifier -> Maybe ModulePath
f Nothing i = Just $ ModuleName i
f (Just p) i = Just $ ModulePath p i
importName :: [Identifier]
-> Parser (Identifier, Identifier, A.AnnotationSet)
importName forwardNames = do
aSet <- annotationSet <?> "import annotations"
spaces
iName <- identifier <?> "name to import"
hasAlias <- optional $ try $ do
spaces
string' "as"
aName <- case hasAlias of
Just _ -> do
spaces
uniqueIdentifier forwardNames "alias name to import"
Nothing ->
return iName
return (aName, iName, aSet)
imports :: [Identifier] -> Parser [TypeDeclaration]
imports forwardNames = do
string' "import" <?> "import keyword"
spaces
path <- modulePath <?> "module path"
spaces
char '('
spaces
idents <- many' [] $ \ importNames' -> do
notFollowedBy $ choice [char ')', char ',' >> spaces >> char ')']
let forwardNames' = [i | (i, _, _) <- importNames'] ++ forwardNames
unless (L.null importNames') $ do
string' ","
spaces
n <- importName forwardNames'
spaces
return n
when (L.null idents) $ fail "parentheses cannot be empty"
void $ optional $ string' ","
spaces
char ')'
spaces
char ';'
return [ Import path imp source aSet
| (imp, source, aSet) <- idents
]
module' :: Parser Module
module' = do
spaces
docs' <- optional $ do
d <- docs <?> "module docs"
spaces
return d
spaces
importLists <- many $ do
importList <- imports []
spaces
return importList
let imports' = [i | l <- importLists, i <- l]
types <- many' imports' $ \ tds -> do
typeDecl <- do
-- Preconsume the common prefix (annotations) to disambiguate
-- the continued branches of parsers.
spaces
annotationSet' <- annotationSet <?> "annotations"
spaces
let forwardNames =
[ n
| td <- tds
, n <- declFacialName td : toList (D.extraPublicNames td)
]
decl <- choice
[ notFollowedBy (string "service")
>> typeDeclaration forwardNames
, serviceDeclaration forwardNames <?> "service declaration"
]
-- In theory, though it preconsumes annotationSet' before parsing
-- decl so that decl itself has no annotations, to prepare for an
-- unlikely situation (that I bet it'll never happen)
-- unite the preconsumed annotationSet' with decl's annotations
-- (that must be empty).
return $ case decl of
TypeDeclaration { typeAnnotations = set } ->
decl { typeAnnotations = A.union annotationSet' set }
ServiceDeclaration { serviceAnnotations = set } ->
decl { serviceAnnotations = A.union annotationSet' set }
_ -> decl -- Never happen!
spaces
return typeDecl
handleNameDuplication "type" types $
\ typeSet -> return $ Module typeSet docs'
file :: Parser Module
file = do
mod' <- module'
eof
return mod'
parse :: FilePath -- ^ Source path (although it's only used for error message)
-> T.Text -- ^ Input source code
-> Either ParseError Module
parse = runParser file
parseFile :: FilePath -- ^ Source path
-> IO (Either ParseError Module)
parseFile path = do
code <- SIO.withFile path SIO.ReadMode $ \ h -> do
SIO.hSetEncoding h SIO.utf8_bom
TIO.hGetContents h
return $ runParser file path code
| spoqa/nirum | src/Nirum/Parser.hs | gpl-3.0 | 25,667 | 0 | 25 | 8,317 | 6,295 | 3,042 | 3,253 | 659 | 4 |
module Main where
import System.Environment (getArgs)
import Data.List (sort, permutations)
followingInteger :: Int -> Int
followingInteger n =
head $ sort $ filter (> n) $ map read $ permutations $ ("0" ++ show n)
processLine :: String -> String
processLine = show . followingInteger . read
main :: IO ()
main = do
[inputFile] <- getArgs
input <- readFile inputFile
mapM_ putStrLn $ map processLine $ lines input
| cryptica/CodeEval | Challenges/44_FollowingInteger/main.hs | gpl-3.0 | 435 | 0 | 10 | 90 | 161 | 83 | 78 | 13 | 1 |
module Sound.Tidal.MIDI.Kindohm.CustomParams where
import Sound.Tidal.Params
-- volca keys
(kportamento, kportamento_p) = pF "kportamento" (Just 0)
(kcutoff, kcutoff_p) = pF "kcutoff" (Just 0)
(klfopitchint, klfopitchint_p) = pF "klfopitchint" (Just 0)
(klforate, klforate_p) = pF "klforate" (Just 0)
(klfocutoffint, klfocutoffint_p) = pF "klfocutoffint" (Just 0)
(kattack, kattack_p) = pF "kattack" (Just 0)
(kdecay, kdecay_p) = pF "kdecay" (Just 0)
(ksustain, ksustain_p) = pF "ksustain" (Just 0)
(kdelaytime, kdelaytime_p) = pF "kdelaytime" (Just 0)
(kdelayfeedback, kdelayfeedback_p) = pF "kdelayfeedback" (Just 0)
-- minilogue
(noise, noise_p) = pF "noise" (Just 0)
(shape1, shape1_p) = pF "shape1" (Just 0)
(shape2, shape2_p) = pF "shape2" (Just 0)
(vol1, vol1_p) = pF "vol1" (Just 1)
(vol2, vol2_p) = pF "vol2" (Just 1)
(xmod, xmod_p) = pF "xmod" (Just 0)
(pitchmod, pitchmod_p) = pF "pitchmod" (Just 0.5)
(egint, egint_p) = pF "egint" (Just 0.5)
(egattack, egattack_p) = pF "egattack" (Just 0)
(egdecay, egdecay_p) = pF "egdecay" (Just 0)
(egsustain, egsustain_p) = pF "egsustain" (Just 1)
(egrelease, egrelease_p) = pF "egrelease" (Just 0)
(voicedepth, voicedepth_p) = pF "voicedepth" (Just 0)
(oct1, oct1_p) = pF "oct1" (Just 0.5)
(oct2, oct2_p) = pF "oct2" (Just 0.5)
(wave1, wave1_p) = pF "wave1" (Just 1)
(wave2, wave2_p) = pF "wave2" (Just 1)
(sync, sync_p) = pF "sync" (Just 0)
(ring, ring_p) = pF "ring" (Just 0)
(lfotarget, lfotarget_p) = pF "lfotarget" (Just 0)
(lforate, lforate_p) = pF "lforate" (Just 0)
(lfomod, lfomod_p) = pF "lfomod" (Just 0)
(lfowave, lfowave_p) = pF "lfowave" (Just 0.5)
(mlpitch1, mlpitch1_p) = pF "pitch1" (Just 0.5)
(mlpitch2, mlpitch2_p) = pF "pitch2" (Just 0.5)
-- for rytm
(tun, tun_p) = pF "tun" (Just 0.5)
(perf1, perf1_p) = pF "perf1" (Just 0)
(perf2, perf2_p) = pF "perf2" (Just 0)
(perf3, perf3_p) = pF "perf3" (Just 0)
(perf4, perf4_p) = pF "perf4" (Just 0)
(perf5, perf5_p) = pF "perf5" (Just 0)
(perf6, perf6_p) = pF "perf6" (Just 0)
(perf7, perf7_p) = pF "perf7" (Just 0)
(perf8, perf8_p) = pF "perf8" (Just 0)
(perf9, perf9_p) = pF "perf9" (Just 0)
(perf10, perf10_p) = pF "perf10" (Just 0)
(perf11, perf11_p) = pF "perf11" (Just 0)
(perf12, perf12_p) = pF "perf12" (Just 0)
(synth1, synth1_p) = pF "synth1" (Just 1)
(synth2, synth2_p) = pF "synth2" (Just 0)
(synth3, synth3_p) = pF "synth3" (Just 0)
(synth4, synth4_p) = pF "synth4" (Just 0)
(synth5, synth5_p) = pF "synth5" (Just 0)
(synth6, synth6_p) = pF "synth6" (Just 0)
(synth7, synth7_p) = pF "synth7" (Just 0)
(synth8, synth8_p) = pF "synth8" (Just 0)
(reverb, reverb_p) = pF "reverb" (Just 0)
(scene1, scene1_p) = pF "scene1" (Just 0)
-- for Harmor
(x, x_p) = pF "x" (Just 0.5)
(y, y_p) = pF "y" (Just 0.5)
(z, z_p) = pF "z" (Just 0.5)
(ab, ab_p) = pF "ab" (Just 0.5)
-- 0-coast
(porttime, porttime_p) = pF "porttime" (Just 0)
(port, port_p) = pF "port" (Just 0)
| kindohm/tidal-midi-rack | Sound/Tidal/MIDI/Kindohm/CustomParams.hs | gpl-3.0 | 2,888 | 0 | 7 | 472 | 1,492 | 784 | 708 | 66 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Drive.Teamdrives.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deprecated use drives.delete instead.
--
-- /See:/ <https://developers.google.com/drive/ Drive API Reference> for @drive.teamdrives.delete@.
module Network.Google.Resource.Drive.Teamdrives.Delete
(
-- * REST Resource
TeamdrivesDeleteResource
-- * Creating a Request
, teamdrivesDelete
, TeamdrivesDelete
-- * Request Lenses
, tdTeamDriveId
) where
import Network.Google.Drive.Types
import Network.Google.Prelude
-- | A resource alias for @drive.teamdrives.delete@ method which the
-- 'TeamdrivesDelete' request conforms to.
type TeamdrivesDeleteResource =
"drive" :>
"v3" :>
"teamdrives" :>
Capture "teamDriveId" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] ()
-- | Deprecated use drives.delete instead.
--
-- /See:/ 'teamdrivesDelete' smart constructor.
newtype TeamdrivesDelete =
TeamdrivesDelete'
{ _tdTeamDriveId :: Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TeamdrivesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tdTeamDriveId'
teamdrivesDelete
:: Text -- ^ 'tdTeamDriveId'
-> TeamdrivesDelete
teamdrivesDelete pTdTeamDriveId_ =
TeamdrivesDelete' {_tdTeamDriveId = pTdTeamDriveId_}
-- | The ID of the Team Drive
tdTeamDriveId :: Lens' TeamdrivesDelete Text
tdTeamDriveId
= lens _tdTeamDriveId
(\ s a -> s{_tdTeamDriveId = a})
instance GoogleRequest TeamdrivesDelete where
type Rs TeamdrivesDelete = ()
type Scopes TeamdrivesDelete =
'["https://www.googleapis.com/auth/drive"]
requestClient TeamdrivesDelete'{..}
= go _tdTeamDriveId (Just AltJSON) driveService
where go
= buildClient
(Proxy :: Proxy TeamdrivesDeleteResource)
mempty
| brendanhay/gogol | gogol-drive/gen/Network/Google/Resource/Drive/Teamdrives/Delete.hs | mpl-2.0 | 2,688 | 0 | 12 | 592 | 303 | 186 | 117 | 49 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.NetworkEndpointGroups.TestIAMPermissions
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns permissions that a caller has on the specified resource.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.networkEndpointGroups.testIamPermissions@.
module Network.Google.Resource.Compute.NetworkEndpointGroups.TestIAMPermissions
(
-- * REST Resource
NetworkEndpointGroupsTestIAMPermissionsResource
-- * Creating a Request
, networkEndpointGroupsTestIAMPermissions
, NetworkEndpointGroupsTestIAMPermissions
-- * Request Lenses
, negtipProject
, negtipZone
, negtipPayload
, negtipResource
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.networkEndpointGroups.testIamPermissions@ method which the
-- 'NetworkEndpointGroupsTestIAMPermissions' request conforms to.
type NetworkEndpointGroupsTestIAMPermissionsResource
=
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"zones" :>
Capture "zone" Text :>
"networkEndpointGroups" :>
Capture "resource" Text :>
"testIamPermissions" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] TestPermissionsRequest :>
Post '[JSON] TestPermissionsResponse
-- | Returns permissions that a caller has on the specified resource.
--
-- /See:/ 'networkEndpointGroupsTestIAMPermissions' smart constructor.
data NetworkEndpointGroupsTestIAMPermissions =
NetworkEndpointGroupsTestIAMPermissions'
{ _negtipProject :: !Text
, _negtipZone :: !Text
, _negtipPayload :: !TestPermissionsRequest
, _negtipResource :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'NetworkEndpointGroupsTestIAMPermissions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'negtipProject'
--
-- * 'negtipZone'
--
-- * 'negtipPayload'
--
-- * 'negtipResource'
networkEndpointGroupsTestIAMPermissions
:: Text -- ^ 'negtipProject'
-> Text -- ^ 'negtipZone'
-> TestPermissionsRequest -- ^ 'negtipPayload'
-> Text -- ^ 'negtipResource'
-> NetworkEndpointGroupsTestIAMPermissions
networkEndpointGroupsTestIAMPermissions pNegtipProject_ pNegtipZone_ pNegtipPayload_ pNegtipResource_ =
NetworkEndpointGroupsTestIAMPermissions'
{ _negtipProject = pNegtipProject_
, _negtipZone = pNegtipZone_
, _negtipPayload = pNegtipPayload_
, _negtipResource = pNegtipResource_
}
-- | Project ID for this request.
negtipProject :: Lens' NetworkEndpointGroupsTestIAMPermissions Text
negtipProject
= lens _negtipProject
(\ s a -> s{_negtipProject = a})
-- | The name of the zone for this request.
negtipZone :: Lens' NetworkEndpointGroupsTestIAMPermissions Text
negtipZone
= lens _negtipZone (\ s a -> s{_negtipZone = a})
-- | Multipart request metadata.
negtipPayload :: Lens' NetworkEndpointGroupsTestIAMPermissions TestPermissionsRequest
negtipPayload
= lens _negtipPayload
(\ s a -> s{_negtipPayload = a})
-- | Name or id of the resource for this request.
negtipResource :: Lens' NetworkEndpointGroupsTestIAMPermissions Text
negtipResource
= lens _negtipResource
(\ s a -> s{_negtipResource = a})
instance GoogleRequest
NetworkEndpointGroupsTestIAMPermissions
where
type Rs NetworkEndpointGroupsTestIAMPermissions =
TestPermissionsResponse
type Scopes NetworkEndpointGroupsTestIAMPermissions =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient
NetworkEndpointGroupsTestIAMPermissions'{..}
= go _negtipProject _negtipZone _negtipResource
(Just AltJSON)
_negtipPayload
computeService
where go
= buildClient
(Proxy ::
Proxy
NetworkEndpointGroupsTestIAMPermissionsResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/NetworkEndpointGroups/TestIAMPermissions.hs | mpl-2.0 | 5,061 | 0 | 18 | 1,159 | 550 | 326 | 224 | 98 | 1 |
{-
Created : 2014 Feb by Harold Carr.
Last Modified : 2014 Jul 06 (Sun) 00:45:08 by Harold Carr.
-}
{-# LANGUAGE BangPatterns #-}
module C05 where
import Control.DeepSeq
import Data.List (find)
import qualified Test.HUnit as T
import qualified Test.HUnit.Util as U
------------------------------------------------------------------------------
-- p. 111
data TimeMachine = TM { manufacturer :: String, year :: Integer } deriving (Eq, Show)
timeMachinesFrom :: String -> Integer -> [TimeMachine]
timeMachinesFrom m y = TM m y : timeMachinesFrom m (y+1)
timelyIncMachines :: [TimeMachine]
timelyIncMachines = timeMachinesFrom "Timely Inc." 100
fibonacci :: [Integer]
fibonacci = 0 : 1 : zipWith (+) fibonacci (tail fibonacci)
infinite2020Machines :: [TimeMachine]
infinite2020Machines = TM "Timely Inc." 2020 : infinite2020Machines
infinite2020Machines' :: [TimeMachine]
infinite2020Machines' = repeat $ TM "Timely Inc." 2020
specialOffer :: [TimeMachine]
specialOffer = cycle [TM m 2005, TM m 1994, TM m 908]
where m = "Timely Inc."
fibonacci2 :: [Integer]
fibonacci2 = map fst $ iterate (\(n,n1) -> (n1,n+n1)) (0,1)
lazy :: T.Test
lazy = T.TestList
[
U.teq "lazy01" (take 3 timelyIncMachines)
[ TM {manufacturer = "Timely Inc.", year = 100}
, TM {manufacturer = "Timely Inc.", year = 101}
, TM {manufacturer = "Timely Inc.", year = 102}
]
, U.teq "lazy02" (find (\(TM { year = y}) -> y > 2018) timelyIncMachines)
(Just (TM {manufacturer = "Timely Inc.", year = 2019}))
, U.teq "lazy03" (zip [(1::Int) .. ] "abcd")
[(1,'a'),(2,'b'),(3,'c'),(4,'d')]
, U.teq "lazy04" (fibonacci !! 20)
6765
, U.teq "lazy05" (fibonacci2 !! 20)
6765
]
------------------------------------------------------------------------------
-- Exercise 5-1 - p. 115
-- http://www.amazon.com/Lambda-Calculus-Types-Perspectives-Logic/dp/0521766141
-- based on Miranda program by D. Turner
primes :: [Integer]
primes = sieve [2..]
where
sieve (p:x) = p : sieve [n | n <- x , (n `mod` p) > 0]
sieve [] = error "HC: should not happen"
-- TODO: this hangs after printing last prime in range : doesn't print final list bracket
primesUpTo :: Integer -> [Integer]
primesUpTo n = [p | p <- primes, p < n]
e51 :: T.Test
e51 = T.TestList
[
U.teq "e510" (take 20 primes) [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71]
]
------------------------------------------------------------------------------
-- Exercise 5-2 - p. 118
e52 :: [T.Test]
e52 = U.tt "e52"
[ fibonacci !! 3
, ( 0 : 1 : zipWith (+) fibonacci (tail fibonacci)) !! 3
, (head $ tail $ zipWith (+) fibonacci (tail fibonacci))
, (head $ tail $ zipWith (+) [0,1,1,2,3] (tail [0,1,1,2,3])) -- shorthand for lots more here
, (head $ tail $ zipWith (+) [0,1,1,2,3] [1,1,2,3])
, (head $ tail $ [0+1,1+1,1+2,2+3])
, (head $ [1+1,1+2,2+3])
, 1+1
]
2
------------------------------------------------------------------------------
-- p. 120
-- foldl (+) 0 [1 .. 1000000000] -- Segmentation fault: 11
-- foldl' (+) 0 [1 .. 1000000000] -- 500000000500000000
sumForce :: [Integer] -> Integer
sumForce xs = sumForce' xs 0
where sumForce' [] z = z
sumForce' (y:ys) z = let s = z + y in s `seq` sumForce' ys s
sumForce2 :: [Integer] -> Integer
sumForce2 xs = sumForce' xs 0
where sumForce' [] z = z
sumForce' (y:ys) z = sumForce' ys $! (z+y)
-- sumForce [1 .. 1000000000]
-- sumForce2 [1 .. 1000000000]
------------------------------------------------------------------------------
-- bang patterns - p. 121
-- !y : make sure following addition is NOT given a thunk.
-- !s : make addition happen at each step (instead of building a thunk)
sumYears :: [TimeMachine] -> Integer
sumYears xs = sumYears' xs 0
where sumYears' [] z = z
sumYears' (TM _ !y :ys) z = let !s = z + y in sumYears' ys s
------------------------------------------------------------------------------
-- irrefutable patten - p. 121
-- matching on it never fails - so avoid deconstruction in pattern match
junk :: Maybe a
junk = case longOperation of
~(Just x) -> Just x
where
longOperation = undefined
foo :: a
foo = undefined
------------------------------------------------------------------------------
-- strict field - p. 128
data ListL a = ListL !Integer [a]
-- unpacked - p. 128
-- unpack data in place rather than reference to data
data ClientU = GovOrgU {-# UNPACK #-} !Int String
| CompanyU {-# UNPACK #-} !Int String PersonU String
| IndividualU {-# UNPACK #-} !Int PersonU
deriving Show
data PersonU = PersonU String String deriving Show
-- lazy/strict containers - p. 129
{-
e.g.,
Data.Map.Lazy : only key evaluated when inserting
Data.Map.Strict : both key and value evaluated when inserting
-}
-- Control.DeepSeq (deepseq ($!!)) -- similar to seq and ($!) but goes all the way
-- to make a data types support deep evaluation with deepseq, make them instances NFData type class
-- force all the fields and return ()
instance NFData ClientU where
rnf (GovOrgU i n) = i `deepseq` n `deepseq` ()
rnf (CompanyU i n (PersonU f l) r) = i `deepseq` n `deepseq` f `deepseq` l `deepseq` r `deepseq` ()
rnf (IndividualU i (PersonU f l)) = i `deepseq` f `deepseq` l `deepseq` ()
------------------------------------------------------------------------------
c05 :: IO T.Counts
c05 = do
_ <- T.runTestTT lazy
_ <- T.runTestTT e51
T.runTestTT $ T.TestList $ e52
-- End of file.
| haroldcarr/learn-haskell-coq-ml-etc | haskell/book/2014-Alejandro_Serrano_Mena-Beginning_Haskell/old/code/src/C05.hs | unlicense | 5,883 | 0 | 15 | 1,447 | 1,662 | 943 | 719 | 93 | 2 |
module CostasLikeArrays.A320574 where
import Helpers.CostasLikeArrays (distinctDistances, countPermutationsUpToDihedralSymmetry)
import Helpers.Records (allMax)
import Data.List (permutations)
a320574 :: Int -> Int
a320574 n = countPermutationsUpToDihedralSymmetry n $ allMax distinctDistances $ permutations [0..n-1]
| peterokagey/haskellOEIS | src/CostasLikeArrays/A320574.hs | apache-2.0 | 319 | 0 | 8 | 30 | 82 | 45 | 37 | 6 | 1 |
module Permutations.A329851Spec (main, spec) where
import Test.Hspec
import Permutations.A329851 (a329851)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A329851" $
it "correctly computes the first six elements" $
map a329851 [0..5] `shouldBe` expectedValue where
expectedValue = [0, 2, 12, 120, 1320, 17856]
| peterokagey/haskellOEIS | test/Permutations/A329851Spec.hs | apache-2.0 | 338 | 0 | 8 | 62 | 112 | 64 | 48 | 10 | 1 |
{-# LANGUAGE OverloadedStrings, CPP #-}
module FormStructure.Countries where
#ifndef __HASTE__
import Data.Text.Lazy (Text)
#else
type Text = String
#endif
countries :: [(Text, Text)]
countries =
[ ("", "--select--")
, ("AF", "Afghanistan")
, ("AX", "Åland Islands")
, ("AL", "Albania")
, ("DZ", "Algeria")
, ("AS", "American Samoa")
, ("AD", "Andorra")
, ("AO", "Angola")
, ("AI", "Anguilla")
, ("AQ", "Antarctica")
, ("AG", "Antigua and Barbuda")
, ("AR", "Argentina")
, ("AM", "Armenia")
, ("AW", "Aruba")
, ("AU", "Australia")
, ("AT", "Austria")
, ("AZ", "Azerbaijan")
, ("BS", "Bahamas")
, ("BH", "Bahrain")
, ("BD", "Bangladesh")
, ("BB", "Barbados")
, ("BY", "Belarus")
, ("BE", "Belgium")
, ("BZ", "Belize")
, ("BJ", "Benin")
, ("BM", "Bermuda")
, ("BT", "Bhutan")
, ("BO", "Bolivia, Plurinational State of")
, ("BQ", "Bonaire, Sint Eustatius and Saba")
, ("BA", "Bosnia and Herzegovina")
, ("BW", "Botswana")
, ("BV", "Bouvet Island")
, ("BR", "Brazil")
, ("IO", "British Indian Ocean Territory")
, ("BN", "Brunei Darussalam")
, ("BG", "Bulgaria")
, ("BF", "Burkina Faso")
, ("BI", "Burundi")
, ("KH", "Cambodia")
, ("CM", "Cameroon")
, ("CA", "Canada")
, ("CV", "Cape Verde")
, ("KY", "Cayman Islands")
, ("CF", "Central African Republic")
, ("TD", "Chad")
, ("CL", "Chile")
, ("CN", "China")
, ("CX", "Christmas Island")
, ("CC", "Cocos (Keeling) Islands")
, ("CO", "Colombia")
, ("KM", "Comoros")
, ("CG", "Congo")
, ("CD", "Congo, the Democratic Republic of the")
, ("CK", "Cook Islands")
, ("CR", "Costa Rica")
, ("CI", "Côte d'Ivoire")
, ("HR", "Croatia")
, ("CU", "Cuba")
, ("CW", "Curaçao")
, ("CY", "Cyprus")
, ("CZ", "Czech Republic")
, ("DK", "Denmark")
, ("DJ", "Djibouti")
, ("DM", "Dominica")
, ("DO", "Dominican Republic")
, ("EC", "Ecuador")
, ("EG", "Egypt")
, ("SV", "El Salvador")
, ("GQ", "Equatorial Guinea")
, ("ER", "Eritrea")
, ("EE", "Estonia")
, ("ET", "Ethiopia")
, ("FK", "Falkland Islands (Malvinas)")
, ("FO", "Faroe Islands")
, ("FJ", "Fiji")
, ("FI", "Finland")
, ("FR", "France")
, ("GF", "French Guiana")
, ("PF", "French Polynesia")
, ("TF", "French Southern Territories")
, ("GA", "Gabon")
, ("GM", "Gambia")
, ("GE", "Georgia")
, ("DE", "Germany")
, ("GH", "Ghana")
, ("GI", "Gibraltar")
, ("GR", "Greece")
, ("GL", "Greenland")
, ("GD", "Grenada")
, ("GP", "Guadeloupe")
, ("GU", "Guam")
, ("GT", "Guatemala")
, ("GG", "Guernsey")
, ("GN", "Guinea")
, ("GW", "Guinea-Bissau")
, ("GY", "Guyana")
, ("HT", "Haiti")
, ("HM", "Heard Island and McDonald Islands")
, ("VA", "Holy See (Vatican City State)")
, ("HN", "Honduras")
, ("HK", "Hong Kong")
, ("HU", "Hungary")
, ("IS", "Iceland")
, ("IN", "India")
, ("ID", "Indonesia")
, ("IR", "Iran, Islamic Republic of")
, ("IQ", "Iraq")
, ("IE", "Ireland")
, ("IM", "Isle of Man")
, ("IL", "Israel")
, ("IT", "Italy")
, ("JM", "Jamaica")
, ("JP", "Japan")
, ("JE", "Jersey")
, ("JO", "Jordan")
, ("KZ", "Kazakhstan")
, ("KE", "Kenya")
, ("KI", "Kiribati")
, ("KP", "Korea, Democratic People's Republic of")
, ("KR", "Korea, Republic of")
, ("KW", "Kuwait")
, ("KG", "Kyrgyzstan")
, ("LA", "Lao People's Democratic Republic")
, ("LV", "Latvia")
, ("LB", "Lebanon")
, ("LS", "Lesotho")
, ("LR", "Liberia")
, ("LY", "Libya")
, ("LI", "Liechtenstein")
, ("LT", "Lithuania")
, ("LU", "Luxembourg")
, ("MO", "Macao")
, ("MK", "Macedonia, the former Yugoslav Republic of")
, ("MG", "Madagascar")
, ("MW", "Malawi")
, ("MY", "Malaysia")
, ("MV", "Maldives")
, ("ML", "Mali")
, ("MT", "Malta")
, ("MH", "Marshall Islands")
, ("MQ", "Martinique")
, ("MR", "Mauritania")
, ("MU", "Mauritius")
, ("YT", "Mayotte")
, ("MX", "Mexico")
, ("FM", "Micronesia, Federated States of")
, ("MD", "Moldova, Republic of")
, ("MC", "Monaco")
, ("MN", "Mongolia")
, ("ME", "Montenegro")
, ("MS", "Montserrat")
, ("MA", "Morocco")
, ("MZ", "Mozambique")
, ("MM", "Myanmar")
, ("NA", "Namibia")
, ("NR", "Nauru")
, ("NP", "Nepal")
, ("NL", "Netherlands")
, ("NC", "New Caledonia")
, ("NZ", "New Zealand")
, ("NI", "Nicaragua")
, ("NE", "Niger")
, ("NG", "Nigeria")
, ("NU", "Niue")
, ("NF", "Norfolk Island")
, ("MP", "Northern Mariana Islands")
, ("NO", "Norway")
, ("OM", "Oman")
, ("PK", "Pakistan")
, ("PW", "Palau")
, ("PS", "Palestinian Territory, Occupied")
, ("PA", "Panama")
, ("PG", "Papua New Guinea")
, ("PY", "Paraguay")
, ("PE", "Peru")
, ("PH", "Philippines")
, ("PN", "Pitcairn")
, ("PL", "Poland")
, ("PT", "Portugal")
, ("PR", "Puerto Rico")
, ("QA", "Qatar")
, ("RE", "Réunion")
, ("RO", "Romania")
, ("RU", "Russian Federation")
, ("RW", "Rwanda")
, ("BL", "Saint Barthélemy")
, ("SH", "Saint Helena, Ascension and Tristan da Cunha")
, ("KN", "Saint Kitts and Nevis")
, ("LC", "Saint Lucia")
, ("MF", "Saint Martin (French part)")
, ("PM", "Saint Pierre and Miquelon")
, ("VC", "Saint Vincent and the Grenadines")
, ("WS", "Samoa")
, ("SM", "San Marino")
, ("ST", "Sao Tome and Principe")
, ("SA", "Saudi Arabia")
, ("SN", "Senegal")
, ("RS", "Serbia")
, ("SC", "Seychelles")
, ("SL", "Sierra Leone")
, ("SG", "Singapore")
, ("SX", "Sint Maarten (Dutch part)")
, ("SK", "Slovakia")
, ("SI", "Slovenia")
, ("SB", "Solomon Islands")
, ("SO", "Somalia")
, ("ZA", "South Africa")
, ("GS", "South Georgia and the South Sandwich Islands")
, ("SS", "South Sudan")
, ("ES", "Spain")
, ("LK", "Sri Lanka")
, ("SD", "Sudan")
, ("SR", "Suriname")
, ("SJ", "Svalbard and Jan Mayen")
, ("SZ", "Swaziland")
, ("SE", "Sweden")
, ("CH", "Switzerland")
, ("SY", "Syrian Arab Republic")
, ("TW", "Taiwan, Province of China")
, ("TJ", "Tajikistan")
, ("TZ", "Tanzania, United Republic of")
, ("TH", "Thailand")
, ("TL", "Timor-Leste")
, ("TG", "Togo")
, ("TK", "Tokelau")
, ("TO", "Tonga")
, ("TT", "Trinidad and Tobago")
, ("TN", "Tunisia")
, ("TR", "Turkey")
, ("TM", "Turkmenistan")
, ("TC", "Turks and Caicos Islands")
, ("TV", "Tuvalu")
, ("UG", "Uganda")
, ("UA", "Ukraine")
, ("AE", "United Arab Emirates")
, ("GB", "United Kingdom")
, ("US", "United States")
, ("UM", "United States Minor Outlying Islands")
, ("UY", "Uruguay")
, ("UZ", "Uzbekistan")
, ("VU", "Vanuatu")
, ("VE", "Venezuela, Bolivarian Republic of")
, ("VN", "Viet Nam")
, ("VG", "Virgin Islands, British")
, ("VI", "Virgin Islands, U.S.")
, ("WF", "Wallis and Futuna")
, ("EH", "Western Sahara")
, ("YE", "Yemen")
, ("ZM", "Zambia")
, ("ZW", "Zimbabwe")
] | DataStewardshipPortal/ds-elixir-cz | FormStructure/Countries.hs | apache-2.0 | 6,814 | 0 | 6 | 1,455 | 2,290 | 1,527 | 763 | 255 | 1 |
import SMHI
import Haste
import Haste.Graphics.Canvas
main :: IO ()
main =
do
writeLog "Starting"
-- Just canvas <- getCanvasById "canvasMonths"
plotData "Hour"
plotData "Day"
plotData "Months"
return ()
| daherb/smhi-plot | Main.hs | artistic-2.0 | 230 | 0 | 8 | 55 | 61 | 28 | 33 | 11 | 1 |
module HuttonSScript where
import HERMIT.API
script :: Shell ()
script = return ()
| ku-fpg/better-life | examples/HERMIT/HuttonSScript.hs | bsd-2-clause | 85 | 0 | 6 | 15 | 29 | 16 | 13 | 4 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.