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 GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ViewPatterns #-}
module Assembler where
import Asm
import Free
import Control.Monad.Identity
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.State hiding ( put )
import qualified Data.Binary.Put as P
import Data.Bits
import qualified Data.ByteString.Lazy as BS
import qualified Data.IntMap as M
import Data.Word
type LabelTable addr = M.IntMap addr
data LabelError = UndefinedLabel
data AssemblerError label addr
= UnsupportedOpcode (Asm label addr ())
| InvalidOpcode
| UnassignedLabel
| LabelError LabelError
data AssemblerState addr
= AssemblerState
{ _codeOffset :: addr
, _labelMap :: LabelTable (Maybe addr)
}
-- | Assembler labels in the code.
newtype Label
= LabelVal
{ unLabel :: Int
}
deriving (Eq, Show)
-- | An initial assembler state whose code offset is zero and whose label map
-- contains one key assigned to the start address.
initialState :: Num a => AssemblerState a
initialState
= AssemblerState
{ _codeOffset = 0
, _labelMap = M.singleton 0 (Just 0)
}
newtype AssemblerT label addr m a
= AssemblerT
{ runAssemblerT
:: StateT (AssemblerState addr)
(ExceptT (AssemblerError label addr)
m)
a
}
deriving
( Functor
, Applicative
, Monad
, MonadState (AssemblerState addr)
, MonadError (AssemblerError label addr)
)
type R addr a = (ReaderT (LabelTable addr) (ExceptT LabelError P.PutM) a)
type AssemblerM addr = AssemblerT Label addr Identity
type Assembler addr a = AssemblerM addr (R addr a)
put :: P.Put -> R addr ()
put = lift . lift
offset :: Num addr => addr -> AssemblerM addr ()
offset a = modify $ \s -> s { _codeOffset = _codeOffset s + a }
-- | Assigns an arbitrary address to a label.
unsafeSetLabel :: Label -> Maybe addr -> AssemblerM addr ()
unsafeSetLabel (LabelVal l) addr
= modify $ \s -> s { _labelMap = M.insert l addr (_labelMap s) }
-- | Gets the current offset in the assembled code.
codeOffset :: AssemblerM addr addr
codeOffset = gets _codeOffset
-- | Gets the label map of the assembler.
labelMap :: AssemblerM addr (LabelTable (Maybe addr))
labelMap = gets _labelMap
-- | Looks up the code offset of a label.
lookupLabel :: Label -> R addr addr
lookupLabel (LabelVal i) = do
addr <- asks (i `M.lookup`)
case addr of
Nothing -> do
throwError UndefinedLabel
Just a -> do
return a
emit :: (Monad m, Monad n) => m (n b) -> n a -> m (n b)
emit m a = do
r <- m
return $ do
_ <- a
r
emitPut :: Monad m
=> m (ReaderT (LabelTable addr) (ExceptT LabelError P.PutM) b)
-> P.Put
-> m (ReaderT (LabelTable addr) (ExceptT LabelError P.PutM) b)
emitPut m a = emit m (put a)
assembleArg :: Integral addr
=> Asm Label addr (Assembler addr ())
-> Assembler addr ()
assembleArg a = case a of
Ret m -> do
offset 1
emitPut m $ do
P.putWord8 0xc3
Add (R Rax) (I i) m -> do
offset 2
emitPut m $ do
P.putWord8 0x04
P.putWord8 (fromIntegral i)
Add (R reg) (I i) m -> do
offset 3
emitPut m $ do
P.putWord8 0x80
binEncode $ opcodeExtension RegisterDirect 0 reg
P.putWord8 (fromIntegral i)
Add (IR reg) (I i) m -> do
offset 3
emitPut m $ do
P.putWord8 0x80
binEncode $ opcodeExtension ZeroIndirect 0 reg
P.putWord8 (fromIntegral i)
Sub (R Rax) (I i) m -> do
offset 2
emitPut m $ do
P.putWord8 0x2c
P.putWord8 (fromIntegral i)
Sub (R reg) (I i) m -> do
offset 3
emitPut m $ do
P.putWord8 0x80
binEncode $ opcodeExtension RegisterDirect 5 reg
P.putWord8 (fromIntegral i)
Sub (IR reg) (I i) m -> do
offset 3
emitPut m $ do
P.putWord8 0x80
binEncode $ opcodeExtension ZeroIndirect 5 reg
P.putWord8 (fromIntegral i)
Mov (R reg) (I i) m -> do
offset 10
emitPut m $ do
binEncode $ rexW rexPrefix
P.putWord8 (0xb8 + index reg)
P.putWord64le (fromIntegral i)
Mov (R r1) (R r2) m -> do
offset 3
emitPut m $ do
binEncode $ rexW rexPrefix
P.putWord8 0x8b
binEncode $ registerDirect r1 r2
Mov (R r1) (IR r2) m -> do
offset 3
emitPut m $ do
binEncode $ rexW rexPrefix
P.putWord8 0x8b
binEncode $ zeroIndirect r1 r2
Mov (IR r1) (R r2) m -> do
offset 3
emitPut m $ do
binEncode $ rexW rexPrefix
P.putWord8 0x89
binEncode $ zeroIndirect r1 r2
Inc (R reg) m -> do
offset 2
emitPut m $ do
P.putWord8 0xfe
binEncode $ opcodeExtension RegisterDirect 0 reg
Inc (IR reg) m -> do
offset 2
emitPut m $ do
P.putWord8 0xfe
binEncode $ opcodeExtension ZeroIndirect 0 reg
Dec (R reg) m -> do
offset 2
emitPut m $ do
P.putWord8 0xfe
binEncode $ opcodeExtension RegisterDirect 1 reg
Dec (IR reg) m -> do
offset 2
emitPut m $ do
P.putWord8 0xfe
binEncode $ opcodeExtension ZeroIndirect 1 reg
Loop (L l) m -> do
offset 2
off <- codeOffset
emit m $ do
addr <- lookupLabel l
put $ do
P.putWord8 0xe2
P.putWord8 (fromIntegral $ addr - off)
NewLabel k -> do
m <- labelMap
let (i, _) = M.findMax m
let l = LabelVal (i + 1)
unsafeSetLabel l Nothing
k l
SetLabel l m -> do
o <- codeOffset
unsafeSetLabel l (Just o)
m
Here k -> do
o <- codeOffset
k o
Syscall m -> do
offset 2
emitPut m $ do
P.putWord8 0x0f
P.putWord8 0x05
Push (R reg) m -> do
offset 1
emitPut m $ P.putWord8 (0x50 + index reg)
Pop (R reg) m -> do
offset 1
emitPut m $ P.putWord8 (0x58 + index reg)
Int (I 3) m -> do
offset 1
emitPut m $ P.putWord8 0xcc
Int (I v) m -> do
offset 2
emitPut m $ do
P.putWord8 0xcd
P.putWord8 (fromIntegral v)
Cmp (R Rax) (I i) m -> do
offset 2
emitPut m $ do
P.putWord8 0x3c
P.putWord8 (fromIntegral i)
Cmp (IR reg) (I i) m -> do
offset 3
emitPut m $ do
P.putWord8 0x80
binEncode $ opcodeExtension ZeroIndirect 7 reg
P.putWord8 (fromIntegral i)
Cmp (R r1) (R r2) m -> do
offset 2
emitPut m $ do
P.putWord8 0x3a
binEncode $ registerDirect r1 r2
Cmp (R r1) (IR r2) m -> do
offset 2
emitPut m $ do
P.putWord8 0x3a
binEncode $ zeroIndirect r1 r2
Cmp (IR r1) (R r2) m -> do
offset 2
emitPut m $ do
P.putWord8 0x38
binEncode $ zeroIndirect r2 r1
Je (L l) m -> do
offset 6
off <- codeOffset
emit m $ do
addr <- lookupLabel l
put $ do
P.putWord8 0x0f
P.putWord8 0x84
P.putWord32le (fromIntegral $ addr - off)
Jne (L l) m -> do
offset 6
off <- codeOffset
emit m $ do
addr <- lookupLabel l
put $ do
P.putWord8 0x0f
P.putWord8 0x85
P.putWord32le (fromIntegral $ addr - off)
_ -> do
throwError $ UnsupportedOpcode (a $> ())
assemble :: AsmF Label Word64 ()
-> Either (AssemblerError Label Word64) BS.ByteString
assemble asm = do
let e = runIdentity
. runExceptT
. flip runStateT initialState
. runAssemblerT
. foldFM assembleArg
$ (asm $> return ())
(r, s) <- e
let m = sequence (_labelMap s)
labels <- case m of
Nothing -> Left UnassignedLabel
Just ls -> return ls
let e' = uncurry ($>)
. P.runPutM
. runExceptT
. flip runReaderT labels
$ r
case e' of
Left l -> Left $ LabelError l
Right x -> return x
class BinaryEncodable a where
binEncode :: a -> P.Put
data RexPrefix
= RexPrefix
{ _rexW :: !Bool
, _rexR :: !Bool
, _rexX :: !Bool
, _rexB :: !Bool
}
deriving (Eq, Show)
-- | An REX prefix with no flags set.
rexPrefix :: RexPrefix
rexPrefix
= RexPrefix
{ _rexW = False
, _rexR = False
, _rexX = False
, _rexB = False
}
-- | Enable the W flag of the REX prefix.
rexW :: RexPrefix -> RexPrefix
rexW p = p { _rexW = True }
-- | Enable the R flag of the REX prefix.
rexR :: RexPrefix -> RexPrefix
rexR p = p { _rexR = True }
-- | Enable the X flag of the REX prefix.
rexX :: RexPrefix -> RexPrefix
rexX p = p { _rexX = True }
-- | Enable the B flag of the REX prefix.
rexB :: RexPrefix -> RexPrefix
rexB p = p { _rexB = True }
boolBit :: Num a => Bool -> a
boolBit True = 1
boolBit False = 0
instance BinaryEncodable RexPrefix where
binEncode (RexPrefix (boolBit -> w) (boolBit -> r) (boolBit -> x) (boolBit -> b))
= P.putWord8 byte where
byte
= (1 `shift` 6)
.|. (w `shift` 3)
.|. (r `shift` 2)
.|. (x `shift` 1)
.|. b
data DispType
= ZeroIndirect
| OneIndirect
| FourIndirect
| RegisterDirect
deriving (Eq, Show)
dispVal :: Num a => DispType -> a
dispVal d = case d of
ZeroIndirect -> 0 -- b00
OneIndirect -> 1 -- b01
FourIndirect -> 2 -- b10
RegisterDirect -> 3 -- b11
-- | A ModR/M byte.
data ModRm
= ModRmRr DispType Register Register
-- ^ A ModR/M byte with a displacement type and two registers. The
-- interpretation of the ModR/M byte depends on the instruction it is
-- involved in. The first register is the /reg/ field of the byte, and
-- the second is the R/M field.
| ModRmOpEx DispType Word8 Register
-- ^ A ModR/M byte without a displacement, but with an opcode extension
-- field and a single "Register" representing the R/M field.
-- Only the three least-significant bits of the opcode extension are kept!
deriving (Eq, Show)
registerDirect :: Register -> Register -> ModRm
registerDirect reg rm = ModRmRr RegisterDirect reg rm
zeroIndirect :: Register -> Register -> ModRm
zeroIndirect reg rm = ModRmRr ZeroIndirect reg rm
oneIndirect :: Register -> Register -> ModRm
oneIndirect reg rm = ModRmRr OneIndirect reg rm
fourIndirect :: Register -> Register -> ModRm
fourIndirect reg rm = ModRmRr FourIndirect reg rm
opcodeExtension :: DispType -> Word8 -> Register -> ModRm
opcodeExtension = ModRmOpEx
instance BinaryEncodable ModRm where
binEncode (ModRmRr (dispVal -> d) (index -> reg) (index -> rm))
= P.putWord8
$ (d `shift` 6)
.|. (reg `shift` 3)
.|. rm
binEncode (ModRmOpEx (dispVal -> d) ex (index -> rm))
= P.putWord8
$ (d `shift` 6)
.|. ((7 .&. ex) `shift` 3)
.|. rm
|
djeik/fuckdown2
|
src/Assembler.hs
|
mit
| 11,585 | 0 | 19 | 4,153 | 3,871 | 1,862 | 2,009 | 355 | 32 |
module Main where
import Data.List
import Control.Concurrent
import Control.Monad
import Codec.Picture
import qualified Data.Matrix as M
import qualified Data.Vector as V
type RealNum = Float
type Vector = M.Matrix RealNum
type Point = Vector
type Radius = RealNum
type Transform = M.Matrix RealNum
yellowPixel = PixelRGB8 255 215 0
blackPixel = PixelRGB8 33 33 33
-- | Ray Starting vector, Direction
data Ray = Ray Point Vector deriving (Show, Eq)
data Geometry = Sphere Radius Point
-- | Camera
-- World to camera, cameraToWorld, clipHither, clipYon
data Camera = Camera RealNum RealNum
deriving (Show)
rayEpsilon :: RealNum
rayEpsilon = 1e-7
a = M.fromList 1 4 [1..4::Float]
toRadians :: RealNum -> RealNum
toRadians deg = deg * pi / 180.0
-- | Vector length (norm)
vlength :: Vector -> RealNum
vlength v = sqrt (sumSqrs v)
where sumSqrs m = V.foldl (\x y -> x**2 + y) 0 (M.getRow 1 m)
-- | Dot product of vectors
dot :: Vector -> Vector -> RealNum
dot v1 v2 = V.sum $ V.map (\(x,y) -> x*y) (V.zip a b)
where
a = M.getRow 1 v1
b = M.getRow 1 v2
screenWidth :: Int
screenWidth = 200
screenHeight :: Int
screenHeight = 150
maxRaySteps :: Integer
maxRaySteps = 5
defaultCamera = Camera near far
where
near = 0.01
far = 200.0
-- | builds a new vector in homogeneous coordinates
buildVector x y z = M.fromList 4 1 [x,y,z,1]
defaultSphere :: Geometry
defaultSphere = Sphere 3.0 (buildVector 10 0 0)
-- | cameraTranform builds a projection matrix (Camera to World) from a Camera
perspective :: RealNum -> RealNum -> RealNum -> Transform
perspective fov n f = perspectMatrix * eyeCoordScale fov
where
perspectMatrix = m
m = M.fromList 4 4 [1,0,0,0,
0,1,0,0,
0,0,a,b,
0,0,1,0]
a = f*invDenom
b = (-f)*n*invDenom
invDenom = 1.0/(f-n)
-- | Scales to canonical viewing volume
eyeCoordScale :: RealNum -> Transform
eyeCoordScale fov = scaleT v
where
v = buildVector i i 1
i = invTanAng fov
invTanAng :: RealNum -> RealNum
invTanAng fov = 1.0 / tan(toRadians fov / 2.0)
identityTransform :: Transform
identityTransform = M.identity 4
normalize :: Vector -> Vector
normalize v = M.fromList 4 1 [x/l, y/l, z/l, 1]
where
x = M.getElem 1 1 v
y = M.getElem 2 1 v
z = M.getElem 3 1 v
w = M.getElem 4 1 v
l = sqrt (x**2 + y**2 + z**2 + w**2)
scaleT :: Vector -> Transform
scaleT v = M.fromList 4 4 [x,0,0,0,
0,y,0,0,
0,0,z,0,
0,0,0,1]
where
x = M.getElem 1 1 v
y = M.getElem 2 1 v
z = M.getElem 3 1 v
translateT :: Vector -> Transform
translateT v = m + identityTransform
where
m = M.fromList 4 4 [0,0,0,x,
0,0,0,y,
0,0,0,z,
0,0,0,0]
x = M.getElem 1 1 v
y = M.getElem 2 1 v
z = M.getElem 3 1 v
-- samples = [M.fromList 4 1 [x, y, 0, 0] | x <- [0..screenWidth], y <- [0..screenHeight]]
-- | Squares a vector
squareVector :: Vector -> RealNum
squareVector v = M.getElem 1 1 (M.transpose a * a)
quadratic :: RealNum -> RealNum -> RealNum -> RealNum
quadratic a b c =
b**2 - 4*a*c
intersects :: Ray -> Geometry -> Bool
intersects (Ray o v) (Sphere radius p) =
discriminant >= 0
where
discriminant = quadratic a b c
a = dot v v
b = 2 * dot os v
c = dot os os - radius * 2
os = p - o
distance :: Ray -> Geometry -> RealNum
distance (Ray o v) (Sphere radius p)
= (-b + sqrt discriminant) / (2*a)
where
discriminant = quadratic a b c
a = dot v v
b = 2 * dot os v
c = dot os os - radius ** 2
os = p - o
rayTrace :: Int -> Int -> PixelRGB8
rayTrace x y =
if intersects r defaultSphere then
PixelRGB8 (round (5*d)) 128 0
else
blackPixel
where
r = generateRay x y defaultCamera
d = distance r defaultSphere
generateRay :: Int -> Int -> Camera -> Ray
generateRay x y c = Ray origin direction
where
origin = buildVector 0 0 0
direction = normalize $ perspective 55.0 0.1 50.0 * buildVector ndx ndy 0
--ndx = 2*(fromIntegral x / fromIntegral screenWidth) - 1
--ndy = 2*(fromIntegral y / fromIntegral screenHeight) - 1
ndx = (fromIntegral x / fromIntegral screenWidth)
ndy = (fromIntegral y / fromIntegral screenHeight)
main :: IO ()
main =
writePng "image.png" ( generateImage rayTrace screenWidth screenHeight)
|
rfdickerson/haskell-raytracer
|
src/Main.hs
|
mit
| 4,486 | 0 | 15 | 1,254 | 1,667 | 898 | 769 | 121 | 2 |
{-# LANGUAGE FlexibleContexts #-}
module Wf.Network.Http.Request
( Request(..)
, HttpVersion
, RequestMethod
, RequestHeader
, RequestQuery
, UrlEncoded(..)
, queryParam
) where
import Wf.Network.Http.Types (Request(..), HttpVersion, RequestMethod, RequestHeader, RequestQuery, UrlEncoded(..))
import Control.Monad (join)
import Control.Eff (Member, Eff)
import Control.Eff.Reader.Strict (Reader, ask)
import qualified Data.ByteString as B (ByteString)
import qualified Network.Wai as Wai (Request, queryString)
queryParam
:: Member (Reader Wai.Request) r
=> B.ByteString -> Eff r (Maybe B.ByteString)
queryParam pname =
return . join . lookup pname . Wai.queryString =<< ask
|
bigsleep/Wf
|
src/Wf/Network/Http/Request.hs
|
mit
| 691 | 0 | 10 | 95 | 212 | 130 | 82 | 20 | 1 |
-- | Contains internal data structures which represents original datum.
{- Parser notes:
- Face vertex only, no point or line vertices allowed.
- Vertex tag allows only <PREF> tags, no inline <P> tags allowed. Same for
normals and texture coordinates.
-}
module Codec.Soten.Data.XglData (
Model(..)
, Author(..)
, LightingTag(..)
, Mesh(..)
, Material(..)
, Face(..)
, Vertex(..)
, Transform(..)
, Object(..)
) where
import Linear
( V3(..)
, V2(..)
)
import Codec.Soten.Types
( Index
)
-- | Describes the lighting in an environment.
data LightingTag
-- | Describes light that has equal intensity in all directions.
= LightingTagAmbient
{ -- | Ambient light color.
lightingTagAmbientColor :: !(V3 Float)
}
-- | Describes a light that comes from a particular direction, as if there
-- was a light source an infinite distance away.
| LightingTagDirectional
{ -- | Describes the direction that light is shining from.
lightingTagDirectionalDirection :: !(V3 Float)
-- | The components of lighting that are reflected diffusely by materials.
, lightingTagDirectionalDiffuse :: !(V3 Float)
-- | The components of lighting that are reflected spectrally by
-- materials.
, lightingTagDirectionalSpecular :: !(V3 Float)
}
-- | Describes an environmental sphere of light that illuminates the object.
| LightingTagSphereMap
{
-- | Specifies the center of the sphere.
lightingTagSphereMapCenter :: !(V3 Float)
-- | A scalar that specifies the radius of the sphere map.
, lightingTagSphereMapRadius :: !Float
}
deriving (Show, Eq)
-- | Determines the original author of the file.
data Author =
Author
{ -- | Represents the author name.
authorName :: !String
-- | The version of the model file. Contains "." as a delimiter.
, authorVersion :: !String
} deriving (Show, Eq)
-- | A collection of related triangles, lines and points that approximate a
-- 3D object.
data Mesh =
Mesh
{ -- | Defined in the current scope.
meshID :: !Int
-- | Represents a position in a 3D coordinate space.
, meshPositions :: ![V3 Float]
-- | Represents a position in a 3D coordinate space.
, meshNormals :: ![V3 Float]
-- | Represents a position on the 2D space of a texture.
, meshTextureCoordinates :: ![V2 Float]
-- | Faces list.
, meshFaces :: ![Face]
-- | Materials list.
, meshMaterials :: ![Material]
} deriving (Show, Eq)
-- | Represents the way that a surface interacts with the light that hits it.
data Material =
Material
{ -- | Defined in the current scope.
materialID :: !Int
-- | The fraction of ambient red, green, and blue light that the object
-- reflects.
, materialAmbient :: !(V3 Float)
-- | The fraction of diffuse red, green, and blue light that the object
-- reflects.
, materialDiffuse :: !(V3 Float)
-- | The fraction of specular red, green, and blue light that the object
-- reflects.
, materialSpecular :: !(Maybe (V3 Float))
-- | The amount of red, green, and blue light that the object emits.
, materialEmiss :: !(Maybe (V3 Float))
-- | Indicates how opaque the material is.
, materialShine :: !(Maybe Float)
-- | Indicates how a specular reflection from the material drops off.
, materialAlpha :: !(Maybe Float)
} deriving (Show, Eq)
-- | Represents a vertex with required position and optional normal and texture
-- coordinates.
data Vertex =
Vertex
{ -- | Position tag reference.
vertexPosition :: !Index
-- | Normal tag reference.
, vertexNormal :: !(Maybe Index)
-- | Texture tag reference.
, vertexTexture :: !(Maybe Index)
} deriving (Show, Eq)
-- | Represents a triangular face that is part of a 3D object.
data Face =
Face
{ -- | Material tag.
faceMaterial :: !Index
-- | Vertex 1.
, faceVertex1 :: !Vertex
-- | Vertex 2.
, faceVertex2 :: !Vertex
-- | Vertex 3.
, faceVertex3 :: !Vertex
} deriving (Show, Eq)
-- | Represents a non-skewing three-dimensional transform.
data Transform =
Transform
{ -- | The positive Z-axis of transformed points will point in the direction
-- of this vector.
transForward :: !(V3 Float)
-- | The positive Y-axis of transformed points will point as closely as
-- possible to this vector.
, transUp :: !(V3 Float)
-- | Points are translated so that the origin in the original space is
-- moved to specified position.
, transPosition :: !(V3 Float)
-- | Points are scaled toward the origin of their original space by the
-- specified scaling amount.
, transScale :: !(Maybe Float)
} deriving (Show, Eq)
-- | Represents a 3D object at a specific location in the world.
data Object =
Object
{ -- | This transform is used to map the mesh into the space of the parent
-- tag.
objectTransform :: !(Maybe Transform)
-- | Mesh tag reference.
, objectMesh :: !(Maybe Index)
} deriving (Show, Eq)
-- | Data structure to store all stl-specific model datum.
data Model =
Model
{ -- | Represents the color that the object in the world should be
-- displayed on.
modelBackgroundColor :: !(V3 Float)
-- | Describes the lighting in an environment.
, modelLightingTags :: ![LightingTag]
-- | Displayable name for an object or world.
, modelName :: !(Maybe String)
-- | Original author.
, modelAuthor :: !(Maybe Author)
-- | List of model meshes.
, modelMeshes :: ![Mesh]
-- | List of model objects.
, modelObjects :: ![Object]
} deriving (Show, Eq)
|
triplepointfive/soten
|
src/Codec/Soten/Data/XglData.hs
|
mit
| 6,024 | 0 | 13 | 1,744 | 817 | 495 | 322 | 164 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
import Models
import Config
import Actions.Types
import Actions
import qualified Database.Persist as DB
import qualified Database.Persist.Postgresql as DB
import Web.Scotty.Trans
import Data.Aeson (Value (Null), (.=), object)
import Control.Monad.Trans
import Control.Monad.Reader
main :: IO ()
main = do
c <- getConfig
run application c
application :: ScottyT Failure ConfigM ()
application = do
runDB (DB.runMigration migrateAll)
e <- lift (asks environment)
middleware $ loggingM e
post "/user" $ withJSON registerA
get "/authorizationToken" . void $ withParams loginA
post "/invitation" . void . withJSON $ withAuthorization createInviteA
get "/invitation" . void $ withParams getInvitesA
defaultHandler $ defaultH e
defaultH :: Environment -> Failure -> Action ()
defaultH e (Failure stat message) = do
status stat
let o = case e of
Development -> object ["error" .= message]
Production -> Null
Test -> object ["error" .= message]
json o
|
benweitzman/PhoBuddies
|
src/Main.hs
|
mit
| 1,109 | 0 | 15 | 208 | 341 | 172 | 169 | 35 | 3 |
module Framework.L0 where
import Framework.LangFramework
data Program
= Prog [Func] Main
data Main =
Main [Block]
data Func
= Func Name [Var] [Block]
data Block = Block Label [Expr] | EmptyBlock [Expr]
data Expr
= SetP Var Prim
| SetB Var Bop
| SetC Var Call
| Begin [Expr]
| Ret Prim
| Jump Prim
| Branch Bop Prim Prim
| CallFunc Call
deriving (Show, Eq)
data Call
= FuncCall Prim [Prim]
deriving (Show, Eq)
data Bop
= Binop Op Prim Prim
deriving (Show, Eq)
|
cgswords/Grift
|
Framework/L0.hs
|
mit
| 556 | 0 | 7 | 182 | 195 | 112 | 83 | 25 | 0 |
module Discern.GHC.Type where
import Discern.Type
import qualified Class as G
import qualified GHC as G
import qualified Name as G
import qualified Outputable as G
import qualified Type as G
import qualified Var as G
unTypeTyVar :: Type -> Either String TyVar
unTypeTyVar (TypeTyVar tv) = Right tv
unTypeTyVar _ = Left "unTypeTyCon: Type wasn't a TyVar."
ghcTyVarToTyVar :: G.TyVar -> TyVar
ghcTyVarToTyVar = mkLocalTyVar . G.getOccString
ghcTypeToConstraint :: G.Type -> Either String (Type -> Type)
ghcTypeToConstraint gt = let (c, ts) = G.getClassPredTys gt
in TypeConstraint (ghcClassToClass c) <$> mapM (\t -> ghcTypeToType t >>= unTypeTyVar) ts
ghcClassToClass :: G.Class -> Class
ghcClassToClass c = Class (G.getOccString c) (G.classArity c)
ghcTyConToTyCon :: G.TyCon -> TyCon
ghcTyConToTyCon tc = TyCon (G.getOccString tc) (length (G.tyConTyVars tc))
ghcTypeToType :: G.Type -> Either String Type
ghcTypeToType gt
| G.isForAllTy gt = let (tvs, t) = G.splitForAllTys gt
tvs' = map ghcTyVarToTyVar tvs
in TypeUQuant tvs' <$> ghcTypeToType t
| G.isTyVarTy gt = return (TypeTyVar
(ghcTyVarToTyVar
(G.getTyVar "ghcTypeToType: getTyVar failed" gt)))
| G.isFunTy gt = let (a, r) = G.splitFunTy gt
in if G.isPredTy a
then (ghcTypeToConstraint a) <*> (ghcTypeToType r)
else do
a' <- ghcTypeToType a
r' <- ghcTypeToType r
return $ TypeTyConApp funTyCon [a', r']
| G.isPredTy gt = Left "Pred type in unhandleable position."
| G.isAlgType gt = case G.splitTyConApp_maybe gt
of Nothing -> Left ("Weird algebraic type: " ++ (G.showSDocUnsafe (G.ppr gt)))
(Just (tc, ts)) -> TypeTyConApp (ghcTyConToTyCon tc) <$> mapM ghcTypeToType ts
| otherwise = case G.splitAppTy_maybe gt
of Nothing -> Left ("Weird unknown type: " ++ (G.showSDocUnsafe (G.ppr gt)))
(Just (tl, tr)) -> TypeApp <$> ghcTypeToType tl <*> ghcTypeToType tr
exprType :: String -> G.Ghc (Either String Type)
exprType = (ghcTypeToType <$>) . G.exprType
ghcDataConTypeToType :: G.DataCon -> Either String Type
ghcDataConTypeToType dc = normalizeScopedType tvs <$> ghcTypeToType (G.dataConType dc)
where tvs = map ghcTyVarToTyVar (G.tyConTyVars (G.dataConTyCon dc))
ghcClassMethTypeToType :: G.Id -> Either String Type
ghcClassMethTypeToType i = classTyVars >>= (\tvs -> normalizeScopedType tvs <$> ghcTypeToType (G.varType i))
where classTyVars = case G.isClassOpId_maybe i
of Nothing -> Left "ghcClassMethTypeToType: Id wasn't a class method."
(Just c) -> Right (map ghcTyVarToTyVar (G.classTyVars c))
|
TravisWhitaker/discern
|
src/Discern/GHC/Type.hs
|
mit
| 3,042 | 0 | 16 | 938 | 913 | 458 | 455 | 52 | 4 |
module Help.Command where
import Data.List
data Command = Command {
cmd :: String,
grupos :: [OptionGroup]
}
instance Show Command where
show (Command c o) = c ++ " " ++ show o
data OptionGroup = OptionGroup {
groupName :: String,
options :: [Option]
}
mapGroup :: (Option -> a) -> OptionGroup -> [a]
mapGroup f (OptionGroup _ ops) = map f ops
instance Show OptionGroup where
show (OptionGroup d os) = d ++ " - " ++ show os
data Option = FixedText String
| Single String String
| Extended [String] String
instance Show Option where
show (FixedText s) = s
show (Single c d) = c ++ " - " ++ d
show (Extended xs c) = show xs ++ " - " ++ c
getKey (Single k _) = [k]
getKey (Extended k _) = k
getKey (FixedText _ ) = []
|
Miguel-Fontes/hs-file-watcher
|
src/Help/Command.hs
|
mit
| 789 | 0 | 9 | 219 | 325 | 172 | 153 | 24 | 1 |
module Context where
import Data.List (nub)
type Context = [(String,String)]
ctx = []
has :: String -> Context -> Bool
has x [] = False
has x ((k,v):cs) = if (x==k) then True else has x cs
get :: String -> Context -> String
get x ((k,v):cs) = if (x==k) then v else get x cs
put :: String -> String -> Context -> Context
put k v cs = (k,v):cs
---
-- type Context' = [([String],[[String]])]
trans :: Eq a => [(a, b)] -> [(a, [b])]
trans cs = cs'
where dom = nub (map fst cs)
cs' = map (\k -> (k,map snd (filter ((==k).fst) cs))) dom
c = [("x","v1"),("x","v2"),("x","v3"),("y","v4")]
|
thiry/DComp
|
src/Context.hs
|
gpl-2.0
| 635 | 0 | 16 | 166 | 351 | 202 | 149 | 16 | 2 |
module Scene.Main
( scene
, MainState(..)
) where
import Data.IORef
import System.Directory (createDirectoryIfMissing, doesFileExist)
import System.Environment (getEnv)
import Demo -- (ReplayInfo(), demoData)
import Game (isGameover, render, update)
import Monadius
import Recorder
import Util (padding)
import GLWrapper
import GlobalVariables
data MainState
= Ending GlobalVariables
| Opening GlobalVariables
| Main GlobalVariables (IORef Recorder)
when t action = if t then action else return ()
scene :: GlobalVariables -> IORef Recorder -> [Key] -> IO MainState
scene vars gs keystate = do
modifyIORef gs (update keystate)
gamestate <- readIORef gs
initGraphics
render gamestate
swapBuffers
let getV = getVariables $ gameBody gamestate
let currentLevel = baseGameLevel getV
let currentArea = maximum $ filter (\i -> (savePoints !! i) < (gameClock getV)) [0..(length savePoints-1)]
let currentSave = if mode gamestate == Playback then saveState vars else (currentLevel,currentArea)
let currentHi = max (saveHiScore vars) (hiScore getV)
let vars' = vars{saveState=currentSave,saveHiScore = currentHi}
if (isGameover gamestate)
then gameover vars vars' gamestate currentLevel
else return $ Main vars' gs
gameover vars vars' gamestate currentLevel = do
when (mode gamestate == Record) (writeReplay vars gamestate $ show (ReplayInfo (recordSaveState vars,(encode2 . preEncodedKeyBuf) gamestate)))
return $ if currentLevel>1 && (not $ isCheat vars) && (mode gamestate /= Playback)
then Ending vars'
else Opening vars'
writeReplay vs gamestate str = do
home <- getEnv "HOME"
let replayFile = home ++ replayFileName
createDirectoryIfMissing True replayFile
filename <- searchForNewFile (
"replay\\" ++ (showsave . recordSaveState) vs ++ "-" ++ (showsave . saveState) vs ++ "." ++
((padding '0' 8) . show . totalScore . getVariables . gameBody) gamestate ++ "pts") 0
writeFile (replayFile ++ filename) str
where
replayFileName = "/.monadius-replay/"
showsave (a,b) = show (a,b+1)
searchForNewFile prefix i = do
let fn = prefix ++ (uniqStrs!!i) ++ replayFileExtension
b <- doesFileExist fn
if not b then return fn else do searchForNewFile prefix $ i + 1
uniqStrs = ("") : (map (("." ++) . show) ([1..] :: [Int]))
|
keqh/Monadius_rewrite
|
Monadius/Scene/Main.hs
|
gpl-2.0
| 2,327 | 0 | 19 | 435 | 835 | 426 | 409 | 54 | 3 |
{-# LANGUAGE CPP, TypeFamilies, DeriveDataTypeable #-}
module PGIP.GraphQL.Result.ConservativityStatus where
import Data.Data
data ConservativityStatus =
ConservativityStatus { required :: String
, proved :: String
} deriving (Show, Typeable, Data)
|
spechub/Hets
|
PGIP/GraphQL/Result/ConservativityStatus.hs
|
gpl-2.0
| 300 | 0 | 8 | 79 | 50 | 31 | 19 | 7 | 0 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 [email protected]
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid 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 grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.LevelPuzzle.LevelPuzzleWorld.OutputState
(
#ifdef GRID_STYLE_FANCY
module Game.LevelPuzzle.LevelPuzzleWorld.OutputState.Fancy,
#endif
#ifdef GRID_STYLE_PLAIN
module Game.LevelPuzzle.LevelPuzzleWorld.OutputState.Plain,
#endif
) where
#ifdef GRID_STYLE_FANCY
import Game.LevelPuzzle.LevelPuzzleWorld.OutputState.Fancy
#endif
#ifdef GRID_STYLE_PLAIN
import Game.LevelPuzzle.LevelPuzzleWorld.OutputState.Plain
#endif
|
karamellpelle/grid
|
source/Game/LevelPuzzle/LevelPuzzleWorld/OutputState.hs
|
gpl-3.0
| 1,193 | 0 | 5 | 180 | 71 | 60 | 11 | 2 | 0 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 [email protected]
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid 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 grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.Run.RunWorld.Scene.Fancy.Values where
import MyPrelude
--valueTweak :: Float
--valueTweak =
--------------------------------------------------------------------------------
-- For
valueTweakForI :: Float
valueTweakForI = (12.0)
valueTweakForJ :: Float
valueTweakForJ = (-2.081)
valueTweakForK :: Float
valueTweakForK = (-0.396)
valueTweakForL :: Float
valueTweakForL = (-1.628)
--------------------------------------------------------------------------------
-- Rot
valueTweakRotI :: Float
valueTweakRotI = (0.948)
valueTweakRotJ :: Float
valueTweakRotJ = (-3.383)
valueTweakRotK :: Float
valueTweakRotK = (-0.200)
valueTweakRotL :: Float
valueTweakRotL = (-5.890)
--------------------------------------------------------------------------------
-- Osc
valueTweakOsc0I :: Float
valueTweakOsc0I = 1.713
valueTweakOsc0J :: Float
valueTweakOsc0J = 0.283
valueTweakOsc0K :: Float
valueTweakOsc0K = 0.354
valueTweakOsc0L :: Float
valueTweakOsc0L = 0.637
valueTweakOsc1I :: Float
valueTweakOsc1I = 1.713
valueTweakOsc1J :: Float
valueTweakOsc1J = 0.283
valueTweakOsc1K :: Float
valueTweakOsc1K = 0.354
valueTweakOsc1L :: Float
valueTweakOsc1L = 0.637
valueTweakOsc2I :: Float
valueTweakOsc2I = 1.713
valueTweakOsc2J :: Float
valueTweakOsc2J = 0.283
valueTweakOsc2K :: Float
valueTweakOsc2K = 0.354
valueTweakOsc2L :: Float
valueTweakOsc2L = 0.637
--------------------------------------------------------------------------------
-- Pulse
valueTweakPulse0I :: Float
valueTweakPulse0I = (-32.0)
valueTweakPulse0J :: Float
valueTweakPulse0J = (-6.935)
valueTweakPulse0K :: Float
valueTweakPulse0K = (0.0)
valueTweakPulse0L :: Float
valueTweakPulse0L = (0.0)
valueTweakPulse1I :: Float
valueTweakPulse1I = (-16.0)
valueTweakPulse1J :: Float
valueTweakPulse1J = (-4.0)
valueTweakPulse1K :: Float
valueTweakPulse1K = (0.0)
valueTweakPulse1L :: Float
valueTweakPulse1L = (0.0)
|
karamellpelle/grid
|
source/Game/Run/RunWorld/Scene/Fancy/Values.hs
|
gpl-3.0
| 2,672 | 0 | 6 | 374 | 389 | 248 | 141 | 58 | 1 |
import Data.List
import System
data Lit a = Id a | Not a deriving Show
type T = Int
type CNF = [[Lit (T,T,T)]]
level :: T
level = 4
verts :: T
verts = 2^level-1
edges :: T
edges = 2^level-2+1 -- "virtual" edge 0 from node 1 to "parent"
between :: T -> T -> T -> Bool
between l u x = l <= x && x <= u
encode :: (T,T,T) -> T
encode (a,b,c) = if between 1 edges a && between 1 verts b && between 1 verts c then res else error "Encoding error" where
res = 1 + (b-1) + (c-1) * verts + (a-1) * verts^2
decode :: T -> (T,T,T)
decode x = (a+1,b+1,c+1) where
x' = x-1
(x'',b) = x' `divMod` verts
(a,c) = x'' `divMod` verts
varCount :: T
varCount = edges * verts * verts
varCombs :: [(T,T,T)]
varCombs = [ (p,x,y) | p <- [1..edges], x <- [1..verts], y <- [1..verts] ]
anotatel :: (a -> b) -> a -> (b,a)
anotatel f x = (f x,x)
edge0 :: CNF
edge0 = [ [ Id (1,1,1) ] ]
everyEdgeAL :: CNF
everyEdgeAL = [ [ Id (p,x,y) | x <- [1..verts], y <- [1..verts] ] | p <- [1..edges] ]
-- can everuEdgeAM be 2 * size / verts ?
-- everyEdgeAM :: CNF
-- everyEdgeAM = [ [Not (p,x,y),Not (p,w,z)]
-- | p <- [2..edges]
-- , x <- [1..verts]
-- , w <- [1..verts]
-- , x /= w
-- , y <- [1..verts]
-- , z <- [1..verts]
-- , y /= z
-- ]
everyEdgeAM :: CNF
everyEdgeAM = everyEdgeAM1 ++ everyEdgeAM2
everyEdgeAM1 :: CNF
everyEdgeAM1 = [ [Not (p,x,y),Not (p,x,w)]
| p <- [1..edges]
, y <- [1..verts]
, w <- [1..verts]
, y /= w
, x <- [1..verts]
]
everyEdgeAM2 :: CNF
everyEdgeAM2 = [ [Not (p,y,x),Not (p,w,x)]
| p <- [1..edges]
, y <- [1..verts]
, w <- [1..verts]
, y /= w
, x <- [1..verts]
]
everyValAL :: CNF
everyValAL = [ [ Id (p,i,a) | p <- [1..edges], a <- [1..verts] ] | i <- [1..verts] ]
everyValAM :: CNF
everyValAM = [ [Not (p,i,a) ,Not (q,i,b)]
| i <- [1..verts]
, p <- [1..edges]
, q <- [1..edges]
, p /= q
, a <- [1..verts]
, b <- [1..verts]
, a /= b
]
lengthsAll :: CNF
lengthsAll = [ concat [ [Id (p,a,a+d),Id (p,a+d,a)] | a <- [1..verts-d], p <- [2..edges] ] | d <- [1..edges-1] ]
treeCons :: CNF
treeCons = [ [Not (p,w,x),Not (p`div`2,y,z)]
| p <- [2..edges] -- maybe 4
, x <- [1..verts]
, y <- [1..verts]
, x /= y
, w <- [1..verts]
, z <- [1..verts]
]
formula :: CNF
formula = concat
[ edge0
, everyEdgeAL
, everyEdgeAM
, everyValAL
, everyValAM
, lengthsAll
, treeCons
]
ppLit :: Lit (T,T,T) -> String
ppLit (Id x) = show (encode x)
ppLit (Not x) = '-': show (encode x)
ppFormula = unlines . map (ppDj . map ppLit) where
ppDj = (++ "0") . concatMap (++" ")
prepareX f = "p cnf " ++ show varCount ++ " _\n" ++ ppFormula f
mainB f = readFile f >>= print . map decode . filter (>0). map (read::String -> T) . words . last . lines
mainA f = writeFile f $ prepareX formula
main' :: [String] -> IO ()
main' ["-g",f] = mainA f
main' ["-d",f] = mainB f
main' _ = error "look to source how to call me (-g/-d filename to Generate/Decode filename)"
main :: IO ()
main = do
args <- getArgs
main' args
|
xkollar/handy-haskell
|
other/pt-2012-03/sat/kwak.hs
|
gpl-3.0
| 3,100 | 0 | 14 | 840 | 1,595 | 888 | 707 | 93 | 2 |
{- Copyright (C) 2009 John Millikin <[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 3 of the License, or
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, see <http://www.gnu.org/licenses/>.
-}
module Main () where
import Test.HUnit
import Tests.Core (coreTests)
allTests = "allTests" ~: TestList [coreTests]
main = do
runTestTT allTests
|
astro/network-protocol-xmpp
|
Tests.hs
|
gpl-3.0
| 845 | 0 | 7 | 173 | 49 | 28 | 21 | 6 | 1 |
import Control.Monad
import Data.List
import System.Environment
import System.Exit
import System.IO
import System.Random
data Cell = Alive | Dead
deriving (Show, Eq)
step Alive Alive Alive = Dead
step Alive Alive Dead = Alive
step Alive Dead Alive = Alive
step Alive Dead Dead = Dead
step Dead Alive Alive = Alive
step Dead Alive Dead = Alive
step Dead Dead Alive = Alive
step Dead Dead Dead = Dead
deads 0 = []
deads n = Dead : deads (n-1)
alives 0 = []
alives n = Alive : alives (n-1)
sample = deads 19 ++ [Alive]
iter xs = a : iter_ xs ++ [z]
where
a = step (last xs) (head xs) (xs !! 2)
z = step ((reverse xs) !! 2) (head $ reverse xs) (head xs)
iter_ (x:y:z:[]) = [step x y z]
iter_ (x:y:z:xs) = step x y z : iter_ (y:z:xs)
rule110 xs n = xs : rule110' xs n
rule110' xs 0 = []
rule110' xs n = done : rule110' done (n-1)
where
done = iter xs
display [] = return ()
display (x:xs) = do
putStrLn $ conv x
display xs
conv [] = ""
conv (x:xs)
| x == Dead = " " ++ conv xs
| x == Alive = "x" ++ conv xs
conv' [] = ""
conv' (x:xs)
| x == Dead = "0 " ++ conv' xs
| x == Alive = "1 " ++ conv' xs
writeTape [] img = return ()
writeTape (x:xs) img = do
hPutStrLn img $ conv' x
writeTape xs img
numbersToCell [] = []
numbersToCell (x:xs)
| x == 1 = Alive : numbersToCell xs
| x == 0 = Dead : numbersToCell xs
randomlist :: Int -> StdGen -> [Int]
randomlist n = take n . unfoldr (Just . randomR (0,1))
main = do
args <- getArgs
g <- newStdGen
when (null args) $ error "Usage: ./rule110 steps size"
let size = read (args !! 0) :: Int
steps = read (args !! 1) :: Int
tape = deads steps ++ [Alive]
word = numbersToCell $ randomlist size g
img <- openFile "img.ppm" WriteMode
hPutStrLn img "P1"
hPutStrLn img $ show size ++ " " ++ show (steps+1)
--putStrLn $ show word
--display $ rule110 word steps
writeTape ( rule110 word steps ) img
hClose img
return ()
|
h3nnn4n/Rule110
|
Rule110.hs
|
gpl-3.0
| 2,069 | 0 | 12 | 612 | 1,002 | 491 | 511 | 66 | 1 |
module Main where
import Control.Monad (replicateM_)
import Data.Attoparsec.ByteString.Char8
import Data.List (intercalate)
import Pipes
import System.Environment (getArgs)
import System.IO
import HEP.Analysis.Histogram1D
import HEP.Data.LHEF (skipTillEnd)
main :: IO ()
main = do
putStrLn $ "# " ++ intercalate ", " ["bins", "Pdecay"]
infile <- fmap head getArgs
printHist infile histPdecay unitNormalize
histPdecay :: MonadIO m => Handle -> m (Hist1D Double)
histPdecay = consHist pDecay 1000 0 1
where
pDecay :: Parser Double
pDecay = do
skipSpace
_ <- many' $ char '#' >> skipTillEnd
replicateM_ 3 (double >> skipSpace >> char ',' >> skipSpace)
double <* skipTillEnd
|
cbpark/scalar-portal
|
src/hist_pdecay.hs
|
gpl-3.0
| 884 | 0 | 13 | 309 | 233 | 121 | 112 | 22 | 1 |
{-# LANGUAGE FlexibleInstances #-}
module Pudding.Utilities.ComplexFunctions
( cabs
, scaleComplex
) where
import Data.Complex
import Pudding.Utilities.FloatEq
import Pudding.Utilities.DoubleFunctions
complexEq :: Complex Double -> Complex Double -> Bool
complexEq a b = (realPart a) ~= (realPart b) &&
(imagPart a) ~= (imagPart b)
scaleComplex :: Double -> Complex Double -> Complex Double
scaleComplex a b = (a :+ 0) * b
cabs :: (Complex Double) -> Double
cabs = realPart . abs
instance FloatEq (Complex Double) where
(~=) = complexEq
|
jfulseca/Pudding
|
src/Pudding/Utilities/ComplexFunctions.hs
|
gpl-3.0
| 550 | 0 | 9 | 92 | 183 | 99 | 84 | 16 | 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.MapsEngine.Tables.Features.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Return a single feature, given its ID.
--
-- /See:/ <https://developers.google.com/maps-engine/ Google Maps Engine API Reference> for @mapsengine.tables.features.get@.
module Network.Google.Resource.MapsEngine.Tables.Features.Get
(
-- * REST Resource
TablesFeaturesGetResource
-- * Creating a Request
, tablesFeaturesGet
, TablesFeaturesGet
-- * Request Lenses
, tfgVersion
, tfgId
, tfgSelect
, tfgTableId
) where
import Network.Google.MapsEngine.Types
import Network.Google.Prelude
-- | A resource alias for @mapsengine.tables.features.get@ method which the
-- 'TablesFeaturesGet' request conforms to.
type TablesFeaturesGetResource =
"mapsengine" :>
"v1" :>
"tables" :>
Capture "tableId" Text :>
"features" :>
Capture "id" Text :>
QueryParam "version" TablesFeaturesGetVersion :>
QueryParam "select" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Feature
-- | Return a single feature, given its ID.
--
-- /See:/ 'tablesFeaturesGet' smart constructor.
data TablesFeaturesGet = TablesFeaturesGet'
{ _tfgVersion :: !(Maybe TablesFeaturesGetVersion)
, _tfgId :: !Text
, _tfgSelect :: !(Maybe Text)
, _tfgTableId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'TablesFeaturesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tfgVersion'
--
-- * 'tfgId'
--
-- * 'tfgSelect'
--
-- * 'tfgTableId'
tablesFeaturesGet
:: Text -- ^ 'tfgId'
-> Text -- ^ 'tfgTableId'
-> TablesFeaturesGet
tablesFeaturesGet pTfgId_ pTfgTableId_ =
TablesFeaturesGet'
{ _tfgVersion = Nothing
, _tfgId = pTfgId_
, _tfgSelect = Nothing
, _tfgTableId = pTfgTableId_
}
-- | The table version to access. See Accessing Public Data for information.
tfgVersion :: Lens' TablesFeaturesGet (Maybe TablesFeaturesGetVersion)
tfgVersion
= lens _tfgVersion (\ s a -> s{_tfgVersion = a})
-- | The ID of the feature to get.
tfgId :: Lens' TablesFeaturesGet Text
tfgId = lens _tfgId (\ s a -> s{_tfgId = a})
-- | A SQL-like projection clause used to specify returned properties. If
-- this parameter is not included, all properties are returned.
tfgSelect :: Lens' TablesFeaturesGet (Maybe Text)
tfgSelect
= lens _tfgSelect (\ s a -> s{_tfgSelect = a})
-- | The ID of the table.
tfgTableId :: Lens' TablesFeaturesGet Text
tfgTableId
= lens _tfgTableId (\ s a -> s{_tfgTableId = a})
instance GoogleRequest TablesFeaturesGet where
type Rs TablesFeaturesGet = Feature
type Scopes TablesFeaturesGet =
'["https://www.googleapis.com/auth/mapsengine",
"https://www.googleapis.com/auth/mapsengine.readonly"]
requestClient TablesFeaturesGet'{..}
= go _tfgTableId _tfgId _tfgVersion _tfgSelect
(Just AltJSON)
mapsEngineService
where go
= buildClient
(Proxy :: Proxy TablesFeaturesGetResource)
mempty
|
rueshyna/gogol
|
gogol-maps-engine/gen/Network/Google/Resource/MapsEngine/Tables/Features/Get.hs
|
mpl-2.0
| 3,969 | 0 | 16 | 945 | 546 | 323 | 223 | 81 | 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.DFAReporting.EventTags.Patch
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates an existing event tag. This method supports patch semantics.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.eventTags.patch@.
module Network.Google.Resource.DFAReporting.EventTags.Patch
(
-- * REST Resource
EventTagsPatchResource
-- * Creating a Request
, eventTagsPatch
, EventTagsPatch
-- * Request Lenses
, etpProFileId
, etpPayload
, etpId
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.eventTags.patch@ method which the
-- 'EventTagsPatch' request conforms to.
type EventTagsPatchResource =
"dfareporting" :>
"v2.7" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"eventTags" :>
QueryParam "id" (Textual Int64) :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] EventTag :> Patch '[JSON] EventTag
-- | Updates an existing event tag. This method supports patch semantics.
--
-- /See:/ 'eventTagsPatch' smart constructor.
data EventTagsPatch = EventTagsPatch'
{ _etpProFileId :: !(Textual Int64)
, _etpPayload :: !EventTag
, _etpId :: !(Textual Int64)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'EventTagsPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'etpProFileId'
--
-- * 'etpPayload'
--
-- * 'etpId'
eventTagsPatch
:: Int64 -- ^ 'etpProFileId'
-> EventTag -- ^ 'etpPayload'
-> Int64 -- ^ 'etpId'
-> EventTagsPatch
eventTagsPatch pEtpProFileId_ pEtpPayload_ pEtpId_ =
EventTagsPatch'
{ _etpProFileId = _Coerce # pEtpProFileId_
, _etpPayload = pEtpPayload_
, _etpId = _Coerce # pEtpId_
}
-- | User profile ID associated with this request.
etpProFileId :: Lens' EventTagsPatch Int64
etpProFileId
= lens _etpProFileId (\ s a -> s{_etpProFileId = a})
. _Coerce
-- | Multipart request metadata.
etpPayload :: Lens' EventTagsPatch EventTag
etpPayload
= lens _etpPayload (\ s a -> s{_etpPayload = a})
-- | Event tag ID.
etpId :: Lens' EventTagsPatch Int64
etpId
= lens _etpId (\ s a -> s{_etpId = a}) . _Coerce
instance GoogleRequest EventTagsPatch where
type Rs EventTagsPatch = EventTag
type Scopes EventTagsPatch =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient EventTagsPatch'{..}
= go _etpProFileId (Just _etpId) (Just AltJSON)
_etpPayload
dFAReportingService
where go
= buildClient (Proxy :: Proxy EventTagsPatchResource)
mempty
|
rueshyna/gogol
|
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/EventTags/Patch.hs
|
mpl-2.0
| 3,594 | 0 | 15 | 841 | 507 | 298 | 209 | 73 | 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.ExternalVPNGateways.Insert
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a ExternalVpnGateway in the specified project using the data
-- included in the request.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.externalVpnGateways.insert@.
module Network.Google.Resource.Compute.ExternalVPNGateways.Insert
(
-- * REST Resource
ExternalVPNGatewaysInsertResource
-- * Creating a Request
, externalVPNGatewaysInsert
, ExternalVPNGatewaysInsert
-- * Request Lenses
, evgiRequestId
, evgiProject
, evgiPayload
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.externalVpnGateways.insert@ method which the
-- 'ExternalVPNGatewaysInsert' request conforms to.
type ExternalVPNGatewaysInsertResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"global" :>
"externalVpnGateways" :>
QueryParam "requestId" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] ExternalVPNGateway :>
Post '[JSON] Operation
-- | Creates a ExternalVpnGateway in the specified project using the data
-- included in the request.
--
-- /See:/ 'externalVPNGatewaysInsert' smart constructor.
data ExternalVPNGatewaysInsert =
ExternalVPNGatewaysInsert'
{ _evgiRequestId :: !(Maybe Text)
, _evgiProject :: !Text
, _evgiPayload :: !ExternalVPNGateway
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ExternalVPNGatewaysInsert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'evgiRequestId'
--
-- * 'evgiProject'
--
-- * 'evgiPayload'
externalVPNGatewaysInsert
:: Text -- ^ 'evgiProject'
-> ExternalVPNGateway -- ^ 'evgiPayload'
-> ExternalVPNGatewaysInsert
externalVPNGatewaysInsert pEvgiProject_ pEvgiPayload_ =
ExternalVPNGatewaysInsert'
{ _evgiRequestId = Nothing
, _evgiProject = pEvgiProject_
, _evgiPayload = pEvgiPayload_
}
-- | An optional request ID to identify requests. Specify a unique request ID
-- so that if you must retry your request, the server will know to ignore
-- the request if it has already been completed. For example, consider a
-- situation where you make an initial request and the request times out.
-- If you make the request again with the same request ID, the server can
-- check if original operation with the same request ID was received, and
-- if so, will ignore the second request. This prevents clients from
-- accidentally creating duplicate commitments. The request ID must be a
-- valid UUID with the exception that zero UUID is not supported
-- (00000000-0000-0000-0000-000000000000).
evgiRequestId :: Lens' ExternalVPNGatewaysInsert (Maybe Text)
evgiRequestId
= lens _evgiRequestId
(\ s a -> s{_evgiRequestId = a})
-- | Project ID for this request.
evgiProject :: Lens' ExternalVPNGatewaysInsert Text
evgiProject
= lens _evgiProject (\ s a -> s{_evgiProject = a})
-- | Multipart request metadata.
evgiPayload :: Lens' ExternalVPNGatewaysInsert ExternalVPNGateway
evgiPayload
= lens _evgiPayload (\ s a -> s{_evgiPayload = a})
instance GoogleRequest ExternalVPNGatewaysInsert
where
type Rs ExternalVPNGatewaysInsert = Operation
type Scopes ExternalVPNGatewaysInsert =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient ExternalVPNGatewaysInsert'{..}
= go _evgiProject _evgiRequestId (Just AltJSON)
_evgiPayload
computeService
where go
= buildClient
(Proxy :: Proxy ExternalVPNGatewaysInsertResource)
mempty
|
brendanhay/gogol
|
gogol-compute/gen/Network/Google/Resource/Compute/ExternalVPNGateways/Insert.hs
|
mpl-2.0
| 4,672 | 0 | 16 | 1,013 | 484 | 292 | 192 | 77 | 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.StorageTransfer.TransferOperations.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)
--
-- This method is not supported and the server returns \`UNIMPLEMENTED\`.
--
-- /See:/ <https://cloud.google.com/storage/transfer Google Storage Transfer API Reference> for @storagetransfer.transferOperations.delete@.
module Network.Google.Resource.StorageTransfer.TransferOperations.Delete
(
-- * REST Resource
TransferOperationsDeleteResource
-- * Creating a Request
, transferOperationsDelete
, TransferOperationsDelete
-- * Request Lenses
, todXgafv
, todUploadProtocol
, todPp
, todAccessToken
, todUploadType
, todBearerToken
, todName
, todCallback
) where
import Network.Google.Prelude
import Network.Google.StorageTransfer.Types
-- | A resource alias for @storagetransfer.transferOperations.delete@ method which the
-- 'TransferOperationsDelete' request conforms to.
type TransferOperationsDeleteResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Text :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Empty
-- | This method is not supported and the server returns \`UNIMPLEMENTED\`.
--
-- /See:/ 'transferOperationsDelete' smart constructor.
data TransferOperationsDelete = TransferOperationsDelete'
{ _todXgafv :: !(Maybe Text)
, _todUploadProtocol :: !(Maybe Text)
, _todPp :: !Bool
, _todAccessToken :: !(Maybe Text)
, _todUploadType :: !(Maybe Text)
, _todBearerToken :: !(Maybe Text)
, _todName :: !Text
, _todCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'TransferOperationsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'todXgafv'
--
-- * 'todUploadProtocol'
--
-- * 'todPp'
--
-- * 'todAccessToken'
--
-- * 'todUploadType'
--
-- * 'todBearerToken'
--
-- * 'todName'
--
-- * 'todCallback'
transferOperationsDelete
:: Text -- ^ 'todName'
-> TransferOperationsDelete
transferOperationsDelete pTodName_ =
TransferOperationsDelete'
{ _todXgafv = Nothing
, _todUploadProtocol = Nothing
, _todPp = True
, _todAccessToken = Nothing
, _todUploadType = Nothing
, _todBearerToken = Nothing
, _todName = pTodName_
, _todCallback = Nothing
}
-- | V1 error format.
todXgafv :: Lens' TransferOperationsDelete (Maybe Text)
todXgafv = lens _todXgafv (\ s a -> s{_todXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
todUploadProtocol :: Lens' TransferOperationsDelete (Maybe Text)
todUploadProtocol
= lens _todUploadProtocol
(\ s a -> s{_todUploadProtocol = a})
-- | Pretty-print response.
todPp :: Lens' TransferOperationsDelete Bool
todPp = lens _todPp (\ s a -> s{_todPp = a})
-- | OAuth access token.
todAccessToken :: Lens' TransferOperationsDelete (Maybe Text)
todAccessToken
= lens _todAccessToken
(\ s a -> s{_todAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
todUploadType :: Lens' TransferOperationsDelete (Maybe Text)
todUploadType
= lens _todUploadType
(\ s a -> s{_todUploadType = a})
-- | OAuth bearer token.
todBearerToken :: Lens' TransferOperationsDelete (Maybe Text)
todBearerToken
= lens _todBearerToken
(\ s a -> s{_todBearerToken = a})
-- | The name of the operation resource to be deleted.
todName :: Lens' TransferOperationsDelete Text
todName = lens _todName (\ s a -> s{_todName = a})
-- | JSONP
todCallback :: Lens' TransferOperationsDelete (Maybe Text)
todCallback
= lens _todCallback (\ s a -> s{_todCallback = a})
instance GoogleRequest TransferOperationsDelete where
type Rs TransferOperationsDelete = Empty
type Scopes TransferOperationsDelete =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient TransferOperationsDelete'{..}
= go _todName _todXgafv _todUploadProtocol
(Just _todPp)
_todAccessToken
_todUploadType
_todBearerToken
_todCallback
(Just AltJSON)
storageTransferService
where go
= buildClient
(Proxy :: Proxy TransferOperationsDeleteResource)
mempty
|
rueshyna/gogol
|
gogol-storage-transfer/gen/Network/Google/Resource/StorageTransfer/TransferOperations/Delete.hs
|
mpl-2.0
| 5,425 | 0 | 17 | 1,283 | 848 | 492 | 356 | 119 | 1 |
----------------------------------------------------------------------
-- |
-- Module : Graphics.UI.Awesomium.Javascript.JSValue
-- Copyright : (c) 2012 Maksymilian Owsianny
-- License : LGPL-3 (see the file LICENSE)
--
-- Maintainer : [email protected]
-- Stability : Experimental
-- Portability : Portable? (needs FFI)
--
----------------------------------------------------------------------
module Graphics.UI.Awesomium.Javascript.JSValue
( JSValue, JSValueType(..)
, createNullValue
, createBoolValue
, createIntegerValue
, createDoubleValue
, createStringValue
, createObjectValue
, createArrayValue
, destroy
, with
, getType
, toString
, toInteger
, toDouble
, toBoolean
, getArray
, getObject
) where
import Graphics.UI.Awesomium.Raw
import Prelude (IO, Int, Double, Bool, String)
import Control.Exception (bracket)
createNullValue :: IO JSValue
createNullValue = awe_jsvalue_create_null_value
createBoolValue :: Bool -> IO JSValue
createBoolValue = awe_jsvalue_create_bool_value
createIntegerValue :: Int -> IO JSValue
createIntegerValue = awe_jsvalue_create_integer_value
createDoubleValue :: Double -> IO JSValue
createDoubleValue = awe_jsvalue_create_double_value
createStringValue :: String -> IO JSValue
createStringValue = awe_jsvalue_create_string_value
createObjectValue :: JSObject -> IO JSValue
createObjectValue = awe_jsvalue_create_object_value
createArrayValue :: JSArray -> IO JSValue
createArrayValue = awe_jsvalue_create_array_value
destroy :: JSValue -> IO ()
destroy = awe_jsvalue_destroy
with :: IO JSValue -> (JSValue -> IO b) -> IO b
with c = bracket c destroy
getType :: JSValue -> IO JSValueType
getType = awe_jsvalue_get_type
toString :: JSValue -> IO String
toString = awe_jsvalue_to_string
toInteger :: JSValue -> IO Int
toInteger = awe_jsvalue_to_integer
toDouble :: JSValue -> IO Double
toDouble = awe_jsvalue_to_double
toBoolean :: JSValue -> IO Bool
toBoolean = awe_jsvalue_to_boolean
getArray :: JSValue -> IO JSArray
getArray = awe_jsvalue_get_array
getObject :: JSValue -> IO JSObject
getObject = awe_jsvalue_get_object
|
MaxOw/awesomium
|
src/Graphics/UI/Awesomium/Javascript/JSValue.hs
|
lgpl-3.0
| 2,195 | 0 | 9 | 350 | 412 | 236 | 176 | 53 | 1 |
module Git.Command.FastImport (run) where
run :: [String] -> IO ()
run args = return ()
|
wereHamster/yag
|
Git/Command/FastImport.hs
|
unlicense
| 88 | 0 | 7 | 15 | 42 | 23 | 19 | 3 | 1 |
-- Copyright 1999-2011 The Text.XHtml Authors.
--
-- Licensed under the Apache License, Version 2.0 (the "License"); you may not
-- use this file except in compliance with the License. You may obtain a copy
-- of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-- License for the specific language governing permissions and limitations under
-- the License.
-- #hide
module Text.XHtml.Transitional.Elements where
import Text.XHtml.Internals
-- * Extra elements in XHTML Transitional
{-# DEPRECATED applet "This element is deprecated in XHTML 1.0" #-}
applet :: Html -> Html
applet = tag "applet"
{-# DEPRECATED basefont "This element is deprecated in XHTML 1.0" #-}
basefont :: Html
basefont = itag "basefont"
{-# DEPRECATED center "This element is deprecated in XHTML 1.0" #-}
center :: Html -> Html
center = tag "center"
{-# DEPRECATED dir "This element is deprecated in XHTML 1.0" #-}
dir :: Html -> Html
dir = tag "dir"
{-# DEPRECATED font "This element is deprecated in XHTML 1.0" #-}
font :: Html -> Html
font = tag "font"
iframe :: Html -> Html
iframe = tag "iframe"
{-# DEPRECATED isindex "This element is deprecated in XHTML 1.0" #-}
isindex :: Html
isindex = itag "isindex"
{-# DEPRECATED themenu "This element is deprecated in XHTML 1.0" #-}
themenu :: Html -> Html
themenu = tag "menu"
{-# DEPRECATED strike "This element is deprecated in XHTML 1.0" #-}
strike :: Html -> Html
strike = tag "strike"
{-# DEPRECATED underline "This element is deprecated in XHTML 1.0" #-}
underline :: Html -> Html
underline = tag "u"
|
robinbb/hs-text-xhtml
|
Text/XHtml/Transitional/Elements.hs
|
apache-2.0
| 2,067 | 0 | 5 | 591 | 200 | 120 | 80 | 31 | 1 |
stringEq :: [Char] -> [Char] -> Bool
stringEq [] [] = True
stringEq (x:xs) (y:ys) = x == y && stringEq xs ys
stringEq _ _ = False
|
EricYT/Haskell
|
src/real_haskell/chapter-6/naiveeq.hs
|
apache-2.0
| 134 | 0 | 7 | 32 | 81 | 42 | 39 | 4 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-missing-fields #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-----------------------------------------------------------------
-- Autogenerated by Thrift Compiler (0.9.3) --
-- --
-- DO NOT EDIT UNLESS YOU ARE SURE YOU KNOW WHAT YOU ARE DOING --
-----------------------------------------------------------------
module ITim_Iface where
import Prelude (($), (.), (>>=), (==), (++))
import qualified Prelude as P
import qualified Control.Exception as X
import qualified Control.Monad as M ( liftM, ap, when )
import Data.Functor ( (<$>) )
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Hashable as H
import qualified Data.Int as I
import qualified Data.Maybe as M (catMaybes)
import qualified Data.Text.Lazy.Encoding as E ( decodeUtf8, encodeUtf8 )
import qualified Data.Text.Lazy as LT
import qualified GHC.Generics as G (Generic)
import qualified Data.Typeable as TY ( Typeable )
import qualified Data.HashMap.Strict as Map
import qualified Data.HashSet as Set
import qualified Data.Vector as Vector
import qualified Test.QuickCheck.Arbitrary as QC ( Arbitrary(..) )
import qualified Test.QuickCheck as QC ( elements )
import qualified Thrift as T
import qualified Thrift.Types as T
import qualified Thrift.Arbitraries as T
import Tim_Types
class ITim_Iface a where
timStream :: a -> TimParam -> P.IO ()
timStarttls :: a -> P.IO ()
timLogin :: a -> Tid -> LT.Text -> P.IO ()
timAck :: a -> TimAckBean -> P.IO ()
timPresence :: a -> TimPBean -> P.IO ()
timMessage :: a -> TimMBean -> P.IO ()
timPing :: a -> LT.Text -> P.IO ()
timError :: a -> TimError -> P.IO ()
timLogout :: a -> P.IO ()
timRegist :: a -> Tid -> LT.Text -> P.IO ()
timRoser :: a -> TimRoster -> P.IO ()
timMessageList :: a -> TimMBeanList -> P.IO ()
timPresenceList :: a -> TimPBeanList -> P.IO ()
timMessageIq :: a -> TimMessageIq -> LT.Text -> P.IO ()
timMessageResult :: a -> TimMBean -> P.IO ()
timProperty :: a -> TimPropertyBean -> P.IO ()
timRemoteUserAuth :: a -> Tid -> LT.Text -> TimAuth -> P.IO TimRemoteUserBean
timRemoteUserGet :: a -> Tid -> TimAuth -> P.IO TimRemoteUserBean
timRemoteUserEdit :: a -> Tid -> TimUserBean -> TimAuth -> P.IO TimRemoteUserBean
timResponsePresence :: a -> TimPBean -> TimAuth -> P.IO TimResponseBean
timResponseMessage :: a -> TimMBean -> TimAuth -> P.IO TimResponseBean
timResponseMessageIq :: a -> TimMessageIq -> LT.Text -> TimAuth -> P.IO TimMBeanList
timResponsePresenceList :: a -> TimPBeanList -> TimAuth -> P.IO TimResponseBean
timResponseMessageList :: a -> TimMBeanList -> TimAuth -> P.IO TimResponseBean
|
donnie4w/tim
|
protocols/gen-hs/ITim_Iface.hs
|
apache-2.0
| 2,952 | 0 | 12 | 545 | 797 | 463 | 334 | 56 | 0 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ru-RU">
<title>Groovy Support</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
secdec/zap-extensions
|
addOns/groovy/src/main/javahelp/org/zaproxy/zap/extension/groovy/resources/help_ru_RU/helpset_ru_RU.hs
|
apache-2.0
| 959 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
isPrime :: Int -> Bool
isPrime 1 = False
isPrime n = let lim = floor $ sqrt $ fromIntegral n
in foldl (\acc x -> acc && rem n x /= 0) True [2..lim]
|
plilja/h99
|
p31.hs
|
apache-2.0
| 161 | 0 | 12 | 48 | 83 | 41 | 42 | 4 | 1 |
import LogicGrowsOnTrees.Parallel.Adapter.Threads (driver)
import LogicGrowsOnTrees.Parallel.Main (RunOutcome(..),TerminationReason(..),simpleMainForExploreTree)
import LogicGrowsOnTrees.Utils.WordSum (WordSum(..))
import LogicGrowsOnTrees.Examples.Queens (nqueensUsingBitsSolutions)
main :: IO ()
main =
simpleMainForExploreTree
driver
mempty
(\(RunOutcome _ termination_reason) -> do
case termination_reason of
Aborted _ -> error "search aborted"
Completed (WordSum count) -> putStrLn $ show count ++ " solutions were found"
Failure _ message -> error $ "error: " ++ message
)
(fmap (const $ WordSum 1) (nqueensUsingBitsSolutions 10))
|
gcross/LogicGrowsOnTrees
|
LogicGrowsOnTrees/tutorial/tutorial-11.hs
|
bsd-2-clause
| 743 | 0 | 15 | 172 | 192 | 104 | 88 | 15 | 3 |
{-# LANGUAGE CPP, ForeignFunctionInterface #-}
module Network.Socket.ByteString.Internal
( mkInvalidRecvArgError
#if !defined(mingw32_HOST_OS)
, c_writev
, c_sendmsg
#endif
) where
import System.IO.Error (ioeSetErrorString, mkIOError)
#if !defined(mingw32_HOST_OS)
import Foreign.C.Types (CInt)
import Foreign.Ptr (Ptr)
import System.Posix.Types (CSsize)
import Network.Socket.ByteString.IOVec (IOVec)
import Network.Socket.ByteString.MsgHdr (MsgHdr)
#endif
#ifdef __GLASGOW_HASKELL__
# if __GLASGOW_HASKELL__ < 611
import GHC.IOBase (IOErrorType(..))
# else
import GHC.IO.Exception (IOErrorType(..))
# endif
#elif __HUGS__
import Hugs.Prelude (IOErrorType(..))
#endif
mkInvalidRecvArgError :: String -> IOError
mkInvalidRecvArgError loc = ioeSetErrorString (mkIOError
#ifdef __GLASGOW_HASKELL__
InvalidArgument
#else
IllegalOperation
#endif
loc Nothing Nothing) "non-positive length"
#if !defined(mingw32_HOST_OS)
foreign import ccall unsafe "writev"
c_writev :: CInt -> Ptr IOVec -> CInt -> IO CSsize
foreign import ccall unsafe "sendmsg"
c_sendmsg :: CInt -> Ptr MsgHdr -> CInt -> IO CSsize
#endif
|
tibbe/network-bytestring
|
Network/Socket/ByteString/Internal.hs
|
bsd-2-clause
| 1,229 | 0 | 9 | 247 | 232 | 142 | 90 | 19 | 1 |
{-# LANGUAGE CPP #-}
#ifdef TEMPLATE_HASKELL
{-# LANGUAGE TemplateHaskell #-}
#endif
module Happstack.Server.Internal.SocketTH(supportsIPv6) where
#ifdef TEMPLATE_HASKELL
import Language.Haskell.TH
#endif
import Network.Socket(SockAddr(..))
-- find out at compile time if the SockAddr6 / HostAddress6 constructors are available
supportsIPv6 :: Bool
#ifdef TEMPLATE_HASKELL
supportsIPv6 = $(let c = ["Network.Socket.SockAddrInet6", "Network.Socket.Internal.SockAddrInet6"] ; d = ''SockAddr
isInet6 :: Con -> Bool
isInet6 (NormalC n _) = show n `elem` c
isInet6 _ = False
in
do info <- reify d
case info of
#if MIN_VERSION_template_haskell(2,11,0)
TyConI (DataD _ _ _ _ cs _) ->
#else
TyConI (DataD _ _ _ cs _) ->
#endif
if any isInet6 cs
then [| True |]
else [| False |]
_ -> error "supportsIPv6: SockAddr is no longer a TyConI ?!?! Giving up."
)
#else
supportsIPv6 = False
#endif
|
arybczak/happstack-server
|
src/Happstack/Server/Internal/SocketTH.hs
|
bsd-3-clause
| 1,170 | 0 | 16 | 420 | 197 | 115 | 82 | 5 | 1 |
{-# LANGUAGE OverloadedStrings, RankNTypes #-}
module EventToElement (
eventToElementAll,
eventToElement,
showElement,
convert,
) where
import Data.Conduit
-- import Control.Arrow
import Control.Applicative
import Data.XML.Types
-- import Data.Text (Text)
import qualified Data.Text as T
import Control.Monad.IO.Class
eventToElementAll :: (Monad m, MonadIO m) => Conduit Event m Element
eventToElementAll = do
mev <- await
case mev of
Just EventBeginDocument -> eventToElementAll
Just (EventBeginElement (Name "stream" _ _) _) -> eventToElementAll
Just (EventBeginElement nm ats) -> do
mel <- toElement nm ats
case mel of
Just el -> do
yield el
eventToElementAll
_ -> return ()
Just (EventEndElement (Name "stream" _ _)) ->
liftIO $ putStrLn "end stream"
Just ev -> error $ "eventToElementAll: bad: " ++ show ev
_ -> return ()
eventToElement :: Monad m => Conduit Event m Element
eventToElement = do
mev <- await
case mev of
Just (EventBeginElement nm ats) -> do
mel <- toElement nm ats
case mel of
Just el -> do
yield el
eventToElement
_ -> return ()
Just ev -> error $ "bad: " ++ show ev
_ -> return ()
toElement :: Monad m => Name -> [(Name, [Content])] ->
Consumer Event m (Maybe Element)
toElement nm ats = do
mev <- await
case mev of
Just ev -> do
ret <- Element nm ats <$> toNodeList nm ev
return $ Just ret
_ -> return Nothing
toNodeList :: Monad m => Name -> Event -> Consumer Event m [Node]
toNodeList nm (EventEndElement n)
| nm == n = return []
| otherwise = error "not match tag names"
toNodeList nm (EventContent c) = do
mev <- await
case mev of
Just ev -> (NodeContent c :) <$> toNodeList nm ev
_ -> return [NodeContent c]
toNodeList nm0 (EventBeginElement nm ats) = do
mel <- toElement nm ats
case mel of
Just el -> do
mev <- await
case mev of
Just ev -> (NodeElement el :) <$> toNodeList nm0 ev
_ -> return [NodeElement el]
_ -> return []
toNodeList _ _ = error "not implemented"
convert :: Monad m => (i -> o) -> Conduit i m o
convert f = do
mx <- await
case mx of
Just x -> yield $ f x
_ -> return ()
{-
testEventList :: [Event]
testEventList = [
EventBeginElement hello [],
EventContent $ ContentText "world",
EventEndElement hello,
EventBeginElement (name "yoshio") [],
EventBeginElement (name "j") [],
EventContent $ ContentText "hacker",
EventEndElement (name "j"),
EventEndElement (name "yoshio")
]
hello :: Name
hello = Name "hello" Nothing Nothing
name :: Text -> Name
name n = Name n Nothing Nothing
eventListToElement :: [Event] -> (Element, [Event])
eventListToElement (EventBeginElement name attrs : rest) =
first (Element name attrs) $ eventListToNodeList rest
eventListToElement _ = error "Not element"
eventListToNodeList :: [Event] -> ([Node], [Event])
eventListToNodeList [] = ([], [])
eventListToNodeList (EventEndElement _ : rest) = ([], rest)
eventListToNodeList (EventContent cnt : rest) =
first (NodeContent cnt :) $ eventListToNodeList rest
eventListToNodeList evs@(EventBeginElement _ _ : _) =
(NodeElement elm : nds, evs'')
where
(elm, evs') = eventListToElement evs
(nds, evs'') = eventListToNodeList evs'
eventListToNodeList _ = error "eventListToNodeList: not implemented yet"
-}
showElement :: Element -> String
showElement (Element nm ats []) =
"<" ++ showNameOpen nm ++ showAttributeList ats ++ "/>"
showElement (Element nm ats nds) =
"<" ++ showNameOpen nm ++ showAttributeList ats ++ ">" ++
concatMap showNode nds ++ "</" ++ showName nm ++ ">"
showName, showNameOpen :: Name -> String
showName (Name n _ (Just np)) = T.unpack np ++ ":" ++ T.unpack n
-- showName (Name n (Just ns) _) = -- "{" ++ T.unpack ns ++ "}" ++ T.unpack n
-- T.unpack n ++ " " ++ "xmlns=\"" ++ T.unpack ns ++ "\""
showName (Name n _ _) = T.unpack n
showNameOpen (Name n _ (Just np)) = T.unpack np ++ ":" ++ T.unpack n
showNameOpen (Name n (Just ns) _) = -- "{" ++ T.unpack ns ++ "}" ++ T.unpack n
T.unpack n ++ " " ++ "xmlns=\"" ++ T.unpack ns ++ "\""
showNameOpen (Name n _ _) = T.unpack n
showAttributeList :: [(Name, [Content])] -> String
showAttributeList = concatMap $ (' ' :) . showAttribute
showAttribute :: (Name, [Content]) -> String
showAttribute (n, cs) = showName n ++ "=\"" ++ concatMap showContent cs ++ "\""
showContent :: Content -> String
showContent (ContentText t) = T.unpack t
showContent _ = error "EventListToNodeList.showContent: not implemented"
showNode :: Node -> String
showNode (NodeElement e) = showElement e
showNode (NodeContent c) = showContent c
showNode (NodeComment c) = "<!-- " ++ T.unpack c ++ "-->"
showNode _ = error "EventListToNodeList.showNode: not implemented"
|
YoshikuniJujo/forest
|
subprojects/xmpp-analysis/EventToElement.hs
|
bsd-3-clause
| 4,692 | 20 | 17 | 922 | 1,393 | 678 | 715 | 100 | 7 |
module Horbits.Orbit.Anomaly where
import Control.Applicative
import Control.Monad
import Data.List.NonEmpty as NE
import Horbits.Dimensional.Prelude
class Anomaly a where
eccentricity :: a -> Dimensionless Double
meanAnomaly :: a -> Dimensionless Double
meanAnomaly a = Dimensional $ ea - e * sin ea
where
Dimensional e = eccentricity a
Dimensional ea = eccentricAnomaly a
eccentricAnomaly :: a -> Dimensionless Double
eccentricAnomaly a = Dimensional . NE.last $ NE.unfold next e0
where
Dimensional e = eccentricity a
Dimensional m = meanAnomaly a
dnext en = (en - e * sin en - m) / (1 - e * cos en)
next en = (en, (en -) <$> mfilter (not . nearZero) (Just $ dnext en))
e0 = if e > 0.8 then pi else m
trueAnomaly :: a -> Dimensionless Double
trueAnomaly a = Dimensional $ 2 * atan (sqrt ((1 + e) / (1 - e)) * tan (ea / 2))
where
Dimensional e = eccentricity a
Dimensional ea = eccentricAnomaly a
data MeanAnomaly = MeanAnomaly (Dimensionless Double) (Dimensionless Double)
instance Anomaly MeanAnomaly where
eccentricity (MeanAnomaly e _) = e
meanAnomaly (MeanAnomaly _ m) = m
data EccentricAnomaly = EccentricAnomaly (Dimensionless Double) (Dimensionless Double)
instance Anomaly EccentricAnomaly where
eccentricity (EccentricAnomaly e _) = e
eccentricAnomaly (EccentricAnomaly _ ea) = ea
|
chwthewke/horbits
|
src/horbits/Horbits/Orbit/Anomaly.hs
|
bsd-3-clause
| 1,487 | 0 | 15 | 402 | 505 | 256 | 249 | 30 | 0 |
module Util
( expandRecur
, minimumOf, maximumOf
, replace, replace2
, rotates
, splitString
) where
import Data.Text (split, pack, unpack)
expandRecur :: Foldable t => (a -> Either (t a) [b]) -> a -> [b]
expandRecur f = g . f
where g (Left as) = concatMap (expandRecur f) as
g (Right b) = b
minimumOf :: (Foldable t, Functor t, Ord b) => (a -> b) -> t a -> b
minimumOf = xxxOf minimum
maximumOf :: (Foldable t, Functor t, Ord b) => (a -> b) -> t a -> b
maximumOf = xxxOf maximum
replace :: [a] -> Int -> a -> [a]
replace xs p x = take p xs ++ [x] ++ drop (p + 1) xs
replace2 :: [[a]] -> Int -> Int -> a -> [[a]]
replace2 xss row col x = replace xss row newLine
where newLine = replace (xss !! row) col x
rotates xs = take (length xs) $ iterate rotate xs
rotate (x:xs) = xs ++ [x]
splitString :: Char -> String -> [String]
splitString sep str = map unpack $ split (== sep) $ pack str
xxxOf :: (Foldable t, Functor t, Ord b) => (t b -> b) -> (a -> b) -> t a -> b
xxxOf agg f = agg . fmap f
|
tyfkda/SolokusSolver
|
src/Util.hs
|
bsd-3-clause
| 1,034 | 0 | 11 | 264 | 552 | 290 | 262 | 26 | 2 |
module Sexy.Instances.BoolC () where
import Sexy.Instances.BoolC.Bool ()
|
DanBurton/sexy
|
src/Sexy/Instances/BoolC.hs
|
bsd-3-clause
| 74 | 0 | 4 | 8 | 20 | 14 | 6 | 2 | 0 |
module Level.Render where
#include "Utils.cpp"
import Data.Foldable (foldrM)
import Control.Monad (forM_, mapM_)
import qualified Graphics.GL as GL
import qualified Ressources as R
import qualified Gamgine.Gfx as G
import Gamgine.Math.Vect as V
import qualified Gamgine.State.RenderState as RS
import qualified GameData.Level as LV
import qualified GameData.Layer as LY
import qualified GameData.Boundary as BD
import qualified GameData.Entity as E
import qualified Rendering.Renderer as RD
import qualified Rendering.Ressources as RR
import qualified Entity.Render as ER
import Gamgine.Gfx ((<<<), (<<))
IMPORT_LENS_AS_LE
render :: RS.RenderState -> LV.Level -> IO LV.Level
render rstate level = do
renderBackground (bgx, bgy) bgTexId
renderInactLayer
renderActLayer
renderEntities
rs' <- runRenderers rstate $ LV.renderers level
return level {LV.renderers = rs'}
where
renderInactLayer = forM_ inactLays $ (mapM_ $ ER.render E.InactiveLayerScope rstate) . LY.entities
renderActLayer = mapM_ (ER.render E.ActiveLayerScope rstate) $ LY.entities actLayer
renderEntities = mapM_ (ER.render E.LevelScope rstate) $ LV.entities level
inactLays = LV.inactiveLayers level
actLayer = LE.getL LV.activeLayerL level
(bgx:.bgy:._) = BD.boundaryArea . LV.boundary $ level
bgTexId = RR.textureId RR.Background $ RS.ressources rstate
renderBackground :: (Double,Double) -> GL.GLuint -> IO ()
renderBackground (sizeX, sizeY) texId = do
G.withTexture2d texId $
G.withPrimitive GL.GL_QUADS $ do
let coords = G.quadTexCoords 100 100
vertices = G.quad (0,0) (max 2000 sizeX, max 1000 sizeY)
GL.glColor3f <<< G.rgb 1 1 1
forM_ (zip coords vertices) (\(c,v) -> do
GL.glTexCoord2f << c
GL.glVertex2f << v)
runRenderers :: RS.RenderState -> [RD.Renderer] -> IO [RD.Renderer]
runRenderers renderState rs = do
foldrM (\r rs -> do
(finished, r') <- RD.runRenderer r renderState
if finished
then return rs
else return $ r' : rs) [] rs
|
dan-t/layers
|
src/Level/Render.hs
|
bsd-3-clause
| 2,118 | 0 | 16 | 465 | 686 | 371 | 315 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
-- -----------------------------------------------------------------------------
-- |
-- Module : PixelParty.Main
-- Copyright : (c) Andreas-Christoph Bernstein 2011
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : [email protected]
-- Stability : unstable
-- Portability : not portable
--
-- Draws fullscreen quad with a user supplied fragment shader.
--
--------------------------------------------------------------------------------
module PixelParty.Main (pixelparty) where
-- TODO:
-- add ping-pong flag:
-- render to texture. supply that texture as an input for the next frame
import Control.Monad (when, forM_, unless)
import Control.Monad.State
import qualified Data.Map as M
import Foreign ((.|.))
import Foreign.Marshal.Array (allocaArray, peekArray, withArrayLen)
import Foreign (Storable, nullPtr, withArray, sizeOf, castPtr, Ptr)
import Foreign.C.String (peekCString, withCAString)
import Graphics.GL.Core41 as GL
import Graphics.GL.Types as GL
import qualified Data.Time as T
import qualified Graphics.UI.SDL as SDL
import PixelParty.CmdLine
import PixelParty.Types
import PixelParty.ShaderIncludes
import PixelParty.Shader
import qualified PixelParty.Texture2D as Tex
import qualified PixelParty.Window as W
-- -----------------------------------------------------------------------------
-- helper
-- from OpenGL-2.4.0.1/Graphics/Rendering/OpenGL/GL/Shaders.hs
getString :: GL.GLenum -> IO String
getString e = GL.glGetString e >>= \ptr ->
if ptr == nullPtr then return "" else peekCString . castPtr $ ptr
buffer :: (Storable a) => GL.GLenum -> GL.GLenum -> [a] -> IO GL.GLuint
buffer target usage xs = do
b <- gen GL.glGenBuffers
GL.glBindBuffer target b
withArray xs $ \ptr -> GL.glBufferData target (size xs) (castPtr ptr) usage
return b
-- -----------------------------------------------------------------------------
gens :: (GL.GLsizei -> Ptr GL.GLuint -> IO ()) -> Int -> IO GL.GLuint
gens what n = fmap head $ allocaArray n $ \buf -> what (fromIntegral n) buf >> peekArray n buf
gen :: (GL.GLsizei -> Ptr GL.GLuint -> IO ()) -> IO GL.GLuint
gen what = gens what 1
createVBO :: P ()
createVBO =
let vertices :: [GL.GLfloat]
vertices = [ -1.0, -1.0, 0.0, 1.0 ,
-1.0, 1.0, 0.0, 1.0 ,
1.0, 1.0, 0.0, 1.0 ,
1.0, -1.0, 0.0, 1.0 ]
indices :: [GL.GLubyte]
indices = [0,1,2,0,2,3]
in do
vao <- io $ gen GL.glGenVertexArrays
io $ GL.glBindVertexArray vao
vbo <- io $ buffer GL.GL_ARRAY_BUFFER GL.GL_STATIC_DRAW vertices
io $ do
GL.glVertexAttribPointer 0 4 GL.GL_FLOAT (fromIntegral GL.GL_FALSE) 0 nullPtr
GL.glEnableVertexAttribArray 0
ibo <- io $ buffer GL.GL_ELEMENT_ARRAY_BUFFER GL.GL_STATIC_DRAW indices
modify (\s -> s{vaoId = vao,arrayBuffer = vbo,elementBuffer = ibo})
io $ do
errorCheckValue <- GL.glGetError
--when (errorCheckValue /= GL.GL_NO_ERROR)
-- GLUT.reportErrors
return ()
{-
createTextures :: [FilePath] -> P ()
createTextures imgs = do
io $ GL.glEnable GL.GL_TEXTURE
ts <- io $ mapM (uncurry Tex.loadTexture) (zip imgs [GL.GL_TEXTURE0..])
io $ mapM_ Tex.enableTexture ts
modify (\s -> s {textures = ts})
-}
createShaders :: CmdLine -> P ()
createShaders opts = do
errorCheckValue <- io GL.glGetError
let path = ".":include opts
(v,f,g,p) <- io $ loadProgramFrom path (vshader opts) (fshader opts) (gshader opts)
io $ GL.glUseProgram (unGLProgram p)
modify (\s -> s { programId = p, vertexShaderId = v, fragmentShaderId = f
, geometryShaderId = g})
let names = ["resolution","time","mouse","tex0","tex1","tex2","tex3"]
ls <- io $ mapM (uniformLoc p) names
let m = M.fromList $ zip names ls
modify (\s -> s { uniforms = m })
io $ case M.lookup "resolution" m of
Nothing -> return ()
Just loc -> GL.glUniform2f loc (fromIntegral $ width opts) (fromIntegral $ height opts)
io $ forM_ [0,1,2,3] $ \i ->
case M.lookup ("tex"++show i) m of
Nothing -> return ()
Just loc -> GL.glUniform1i loc i
initialize :: CmdLine -> P ()
initialize opts = do
createShaders opts
createVBO
-- createTextures (tex opts)
io $ do
GL.glDepthFunc (depthTest defaultPartyState)
GL.glClearColor 1.0 0.0 0.0 0.0
windowTitle :: String
windowTitle = "pixelparty"
size as = fromIntegral (length as * sizeOf (head as))
pixelparty :: CmdLine -> IO ()
pixelparty opts = do
win <- W.openWindow windowTitle (width opts , height opts)
now <- T.getCurrentTime
let st = defaultPartyState
{ vertFile = vshader opts
, fragFile = fshader opts
, geomShFile = gshader opts
, startTime = now
, fpsLastTime = now
, sdlWindow = win}
runP st $ do
initialize opts
-- mainloop (process >> render >> fpsCounter)
mainloop (render >> fpsCounter)
cleanup
return ()
where
mainloop a = gets done >>= flip unless (a >> mainloop a)
-- process = io SDL.pollEvent >>= handle
-- -----------------------------------------------------------------------------
-- | Event handler
{-
handle :: SDL.Event -> P ()
handle SDL.NoEvent = return ()
handle SDL.Quit = stop
handle (SDL.KeyDown keysym) | SDL.symKey keysym == SDL.SDLK_ESCAPE = stop
handle (SDL.KeyDown (SDL.Keysym SDL.SDLK_r [] _)) = reload
handle (SDL.KeyDown (SDL.Keysym SDL.SDLK_s [] _)) = screenshot
handle (SDL.VideoResize w h) = do
modify (\s -> s {currentWidth = w, currentHeight = h})
s <- io $ W.resizeWindow w h
io $ GL.glViewport 0 0 (fromIntegral w) (fromIntegral h)
us <- gets uniforms
io $ case M.lookup "resolution" us of
Nothing -> return ()
Just loc -> GL.glUniform2f loc (fromIntegral w) (fromIntegral h)
handle _ = return ()
-}
stop :: P ()
stop = modify (\s -> s {done = True})
reload :: P ()
reload = do
state <- get
let current = programId state
path = ".":[] -- TODO include opts
(v,f,g,p) <- io $ loadProgramFrom path (vertFile state) (fragFile state) (geomShFile state)
ok <- io $ linkStatus p
if ok then do
io $ GL.glUseProgram (unGLProgram p)
modify (\s -> s { programId = p, vertexShaderId = v, fragmentShaderId = f
, geometryShaderId = g})
let names = ["resolution","time","mouse","tex0","tex1","tex2","tex3"]
ls <- io $ mapM (uniformLoc p) names
let m = M.fromList $ zip names ls
modify (\s -> s { uniforms = m })
io $ case M.lookup "resolution" m of
Nothing -> return ()
Just loc -> GL.glUniform2f loc (fromIntegral $ currentWidth state) (fromIntegral $ currentHeight state)
io $ forM_ [0,1,2,3] $ \i ->
case M.lookup ("tex"++show i) m of
Nothing -> return ()
Just loc -> GL.glUniform1i loc i
else io $ do
print "Error: reload failed"
GL.glUseProgram (unGLProgram current)
-- | makes a screenshot and saves the image as "pixelparty.jpg"
screenshot :: P ()
screenshot = return () -- get >>= \s -> io $ Tex.screenshot "pixelparty.jpg" (currentWidth s) (currentHeight s)
cleanup :: P ()
cleanup = do
state <- get
errorCheckValue <- io GL.glGetError
io $ GL.glUseProgram 0
io . GL.glDeleteProgram . unGLProgram . programId $ state
io $ GL.glDisableVertexAttribArray 0
io $ GL.glBindBuffer GL.GL_ARRAY_BUFFER 0
io $ withArrayLen [arrayBuffer state] $ GL.glDeleteBuffers . fromIntegral
io $ GL.glBindBuffer GL.GL_ELEMENT_ARRAY_BUFFER 0
io $ withArrayLen [elementBuffer state] $ GL.glDeleteBuffers . fromIntegral
io $ GL.glBindVertexArray 0
io $ withArrayLen [vaoId state] $
GL.glDeleteVertexArrays . fromIntegral
io $ withArrayLen (map fst (textures state)) $
GL.glDeleteTextures . fromIntegral
errorCheckValue <- io GL.glGetError
{-
when (errorCheckValue /= GL.GL_NO_ERROR) $ do
putStrLn "ERROR: Could not destroy the GL objects"
GLUT.reportErrors
-}
return ()
fpsCounter :: P ()
fpsCounter = do
c <- gets frameCount
if c > 49 then do
now <- io T.getCurrentTime
last <- gets fpsLastTime
let t = T.diffUTCTime now last
f = round (50/t)
modify (\s -> s{frameCount = 0, fpsLastTime = now})
-- io $ SDL.setCaption (windowTitle ++ "@" ++ show f ++ " fps") windowTitle
else modify (\s -> s{frameCount = frameCount s + 1})
return ()
render :: P ()
render = do
state <- get
io $ do
now <- T.getCurrentTime
let t = T.diffUTCTime now (startTime state)
case M.lookup "time" (uniforms state) of
Nothing -> return ()
Just loc -> GL.glUniform1f loc (realToFrac t)
GL.glClear $ GL_COLOR_BUFFER_BIT .|. GL_DEPTH_BUFFER_BIT
GL.glDrawElements GL.GL_TRIANGLES 6 GL.GL_UNSIGNED_BYTE nullPtr
SDL.glSwapWindow (sdlWindow state)
|
bernstein/pixelparty
|
src/PixelParty/Main.hs
|
bsd-3-clause
| 8,863 | 0 | 17 | 1,968 | 2,575 | 1,315 | 1,260 | 169 | 4 |
{-# LANGUAGE TemplateHaskell,DataKinds #-}
module HLearn.Optimization.QuasiNewton
where
import Control.DeepSeq
import Control.Monad
import Control.Monad.Random
import Control.Monad.ST
import Control.Lens
import Data.List
import Data.List.Extras
import Data.Typeable
import Debug.Trace
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Storable.Mutable as VSM
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Generic.Mutable as VGM
import qualified Data.Vector.Algorithms.Intro as Intro
import Numeric.LinearAlgebra hiding ((<>))
import HLearn.Algebra
import HLearn.Algebra.LinearAlgebra as LA
import HLearn.History
import HLearn.Optimization.Common
import HLearn.Optimization.LineMinimization as LineMin
data BFGS a = BFGS
{ __x1 :: !(Tensor 1 a)
, __fx1 :: !(Tensor 0 a)
, __fx0 :: !(Tensor 0 a)
, __f'x1 :: !(Tensor 1 a)
, __f''x1 :: !(Tensor 2 a)
, __alpha1 :: !(Tensor 0 a)
}
-- { __x1 :: !a
-- , __fx1 :: !(Scalar a)
-- , __fx0 :: !(Scalar a)
-- , __f'x1 :: !a
-- , __f''x1 :: !(LA.Matrix (Scalar a))
-- , __alpha1 :: !(Scalar a)
-- }
deriving (Typeable)
makeLenses ''BFGS
-- deriving instance (Show a, Show (Scalar a), Show (LA.Matrix (Scalar a))) => Show (BFGS a)
instance (ValidTensor a) => Has_x1 BFGS a where x1 = _x1
instance (ValidTensor a) => Has_fx1 BFGS a where fx1 = _fx1
instance (ValidTensor a) => Has_fx0 BFGS a where fx0 = _fx0
instance (ValidTensor a) => Has_f'x1 BFGS a where f'x1 = _f'x1
instance (ValidTensor a) => Has_stepSize BFGS a where stepSize = _alpha1
-- instance Has_x1 BFGS a where x1 = _x1
-- instance Has_fx1 BFGS a where fx1 = _fx1
-- instance Has_fx0 BFGS a where fx0 = _fx0
-- instance Has_f'x1 BFGS a where f'x1 = _f'x1
-- instance Has_stepSize BFGS a where stepSize = _alpha1
quasiNewton' f f' f'' x0 = optimize
(step_quasiNewton f f')
$ BFGS
{ __x1 = x0
, __fx1 = f x0
, __fx0 = infinity
, __f'x1 = f' x0
, __f''x1 = f'' x0
, __alpha1 = 1e-2
}
quasiNewton f f' x0 = optimize
( step_quasiNewton f f' )
( BFGS
{ __x1 = x0
, __fx1 = f x0
, __fx0 = infinity
, __f'x1 = f' x0
, __f''x1 = LA.eye (VG.length x0)
, __alpha1 = 1e-10
}
)
step_quasiNewton ::
( vec ~ LA.Vector r
, mat ~ LA.Matrix r
, r ~ Scalar r
, VectorSpace r
, Field r
, Ord r
, Typeable r
, Show r
, IsScalar r
) => (vec -> r)
-> (vec -> vec)
-> BFGS vec
-> History (BFGS vec)
step_quasiNewton f f' opt = do
let x0 = opt^.x1
fx0 = opt^.fx1
f'x0 = opt^.f'x1
f''x0 = opt^._f''x1
alpha0 = opt^.stepSize
d = inverse $ f''x0 `LA.matProduct` f'x0
g alpha = f $ x0 <> alpha .* d
-- alpha <- fmap _bt_x $ backtracking (0.75) f f'
-- (Backtracking
-- { _bt_x = 1
-- , _bt_fx = g 1
-- , _bt_f'x = f' $ x0 <> d
-- , _init_dir = d
-- , _init_x = x0
-- , _init_fx = fx0
-- , _init_f'x = f'x0
-- })
-- [ stop_wolfe 1e-4 0.9
-- , maxIterations 100
-- ]
bracket <- LineMin.lineBracket g (alpha0/2) (alpha0*2)
brent <- LineMin.brent g bracket [maxIterations 200,LineMin.brentTollerance 1e-6]
let alpha = LineMin._x brent
let x1 = x0 <> alpha .* d
f'x1 = f' x1
let p=x1 <> inverse x0
q=f'x1 <> inverse f'x0
let xsi = 1
tao = inner q $ f''x0 `LA.matProduct` q
v = p /. (inner p q) <> inverse (f''x0 `LA.matProduct` q) /. tao
f''x1 = f''x0
<> (LA.v2m p `LA.matProduct` LA.v2m' p) /. (inner p q)
<> inverse (f''x0 `LA.matProduct` LA.v2m q
`LA.matProduct` LA.v2m' q
`LA.matProduct` f''x0) /. tao
<> (xsi*tao) .* (LA.v2m v `LA.matProduct` LA.v2m' v)
let go a1 a0 = if (a1>=0 && a0 >=0) || (a1<=0&&a0<=0)
then a1
else a1
x1mod = VG.zipWith go x1 x0
return $ BFGS
{ __x1 = x1mod
, __fx1 = f x1mod
, __fx0 = opt^.fx1
, __f'x1 = f' x1mod
, __f''x1 = f''x1
, __alpha1 = alpha
}
-- report $ BFGS
-- { _x1 = x1
-- , _fx1 = f x1
-- , _fx0 = fx1 opt
-- , _f'x1 = f' x1
-- , _f''x1 = f''x1
-- , _alpha1 = alpha
-- }
|
ehlemur/HLearn
|
src/HLearn/Optimization/QuasiNewton.hs
|
bsd-3-clause
| 4,622 | 0 | 20 | 1,519 | 1,259 | 709 | 550 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, TypeFamilies, TupleSections, FlexibleContexts,
PackageImports #-}
import Data.UUID
import System.Environment
import System.Random
import Control.Applicative
import Control.Monad
import "monads-tf" Control.Monad.State
import Control.Concurrent (forkIO)
import Data.Pipe
import Data.HandleLike
import Text.XML.Pipe
import Network
import XmppServer
data SHandle s h = SHandle h
instance HandleLike h => HandleLike (SHandle s h) where
type HandleMonad (SHandle s h) = StateT s (HandleMonad h)
type DebugLevel (SHandle s h) = DebugLevel h
hlPut (SHandle h) = lift . hlPut h
hlGet (SHandle h) = lift . hlGet h
hlClose (SHandle h) = lift $ hlClose h
hlDebug (SHandle h) = (lift .) . hlDebug h
main :: IO ()
main = do
pn : _ <- getArgs
socket <- listenOn . PortNumber . fromIntegral $ (read :: String -> Int) pn
forever $ do
(h, _, _) <- accept socket
uuids <- randoms <$> getStdGen
voidM . forkIO . (`evalStateT` initXmppState uuids)
. xmpp $ SHandle h
xmpp :: (MonadState (HandleMonad h), StateType (HandleMonad h) ~ XmppState,
HandleLike h) => h -> HandleMonad h ()
xmpp h = do
voidM . runPipe $ input h =$= makeP =$= output h
hlPut h $ xmlString [XmlEnd (("stream", Nothing), "stream")]
hlClose h
makeP :: (MonadState m, StateType m ~ XmppState) =>
Pipe Common Common m ()
makeP = (,) `liftM` await `ap` lift (gets receiver) >>= \p -> case p of
(Just (SRStream _), Nothing) -> do
yield SRXmlDecl
lift nextUuid >>= \u -> yield $ SRStream [
(Id, toASCIIBytes u),
(From, "localhost"), (Version, "1.0"), (Lang, "en") ]
lift nextUuid >>= digestMd5 Nothing >>= \un -> lift . modify .
setReceiver $ Jid un "localhost" Nothing
makeP
(Just (SRStream _), _) -> do
yield SRXmlDecl
lift nextUuid >>= \u -> yield $ SRStream [
(Id, toASCIIBytes u),
(From, "localhost"), (Version, "1.0"), (Lang, "en") ]
yield $ SRFeatures
[Rosterver Optional, Bind Required, Session Optional]
makeP
(Just (SRIq Set i Nothing Nothing
(IqBind (Just Required) (Resource n))), _) -> do
lift $ modify (setResource n)
Just j <- lift $ gets receiver
yield . SRIq Result i Nothing Nothing
. IqBind Nothing $ BJid j
makeP
(Just (SRIq Set i Nothing Nothing IqSession), mrcv) -> do
yield (SRIq Result i Nothing mrcv IqSessionNull)
makeP
(Just (SRIq Get i Nothing Nothing (IqRoster Nothing)), mrcv) -> do
yield . SRIq Result i Nothing mrcv
. IqRoster . Just $ Roster (Just "1") []
makeP
(Just (SRPresence _ _), Just rcv) ->
yield (SRMessage Chat "hoge" (Just sender) rcv .
MBody $ MessageBody "Hi!") >> makeP
_ -> return ()
voidM :: Monad m => m a -> m ()
voidM = (>> return ())
sender :: Jid
sender = Jid "yoshio" "localhost" (Just "profanity")
|
YoshikuniJujo/xmpipe
|
old/notlssv.hs
|
bsd-3-clause
| 2,736 | 22 | 18 | 549 | 1,217 | 614 | 603 | 78 | 7 |
{-# LANGUAGE OverloadedStrings #-}
import Network.API.TLDR
import Network.API.TLDR.HTTP
import Network.API.TLDR.Types
--import qualified Data.ByteString.Lazy.Char8 as B
import Data.Aeson
import Control.Monad (when)
import Network.Http.Client
import System.Exit (exitFailure)
import Test.HUnit
(Test(..), Counts(..),
runTestTT, assertFailure,
assertEqual) -- assertBool)
categoryJSONTest :: Test
categoryJSONTest = TestCase $ do
let decoded = decode "[{\"name\":\"World News\",\"slug\":\"world-news\"}, {\"name\":\"Tech News\",\"slug\":\"tech-news\"}]" :: Maybe [Category]
case decoded of
Nothing -> assertFailure "should be a list of Category types"
Just categories -> do
assertEqual "two categories" 2 (length categories)
assertEqual "first name is World News" "World News" (categoryName $ head categories)
assertEqual "second name is Tech News" "Tech News" (categoryName $ categories !! 1)
assertEqual "first slug is world-news" "world-news" (categorySlug $ head categories)
-- etc.
userJSONTest :: Test
userJSONTest = TestCase $ do
let decoded = decode "{\"username\":\"josh\",\"lastActive\":\"2012-03-05T12:34:56.033Z\",\"createdAt\":\"2012-03-05T12:34:56.033Z\", \"twitterHandle\":\"joshrotenberg\", \"gravatar\":{\"url\":\"http://foo.com\"}}" :: Maybe User
case decoded of
Nothing -> assertFailure "should be a user"
Just user -> do
assertEqual "username is josh" (userUsername user) "josh"
assertEqual "twitterHandle is joshrotenberg" (userTwitterHandle user) "joshrotenberg"
case userGravatar user of
Nothing -> assertFailure "no gravatar"
Just g -> assertEqual "its an url" (gravatarUrl g) "http://foo.com"
-- should test the timestamps too i guess
fetchUserTest :: Test
fetchUserTest = TestCase $ do
x <- fetchUser "9000"
assertEqual "what" 1 1
unitTests :: Test
unitTests = TestList
[ TestLabel "Categories" categoryJSONTest
, TestLabel "User" userJSONTest
, TestLabel "FetchUser" fetchUserTest
]
main :: IO ()
main = do counts <- runTestTT unitTests
let bad = errors counts + failures counts
when (bad > 0) exitFailure
|
joshrotenberg/tldrio-hs
|
Test/TLDR.hs
|
bsd-3-clause
| 2,553 | 0 | 18 | 767 | 484 | 243 | 241 | 46 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Hooks.ProjectHistory
-- Copyright :
-- License : BSD3-style (see LICENSE)
--
-- Maintainer :
-- Stability : unstable
-- Portability : unportable
--
-- Keeps track of project viewing order.
--
-----------------------------------------------------------------------------
module XMonad.Hooks.ProjectHistory
( -- * Usage
-- $usage
-- * Hooking
projectHistoryHook
, projectHistoryDeleteHook
-- * Querying
, projectHistory
) where
import XMonad
import XMonad.StackSet (currentTag)
import XMonad.StackSet as W
import qualified XMonad.Util.ExtensibleState as XS
import Control.Applicative
import Data.Maybe
import System.IO (hPutStrLn
,stderr)
-- $usage
-- To record the order in which you view projects, you can use this
-- module with the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Hooks.ProjectHistory (projectHistoryHook)
--
-- Then add the hook to your 'logHook':
--
-- > main = xmonad $ def
-- > { ...
-- > , logHook = ... >> projectHistoryHook >> ...
-- > , ...
-- > }
--
-- To make use of the collected data, a query function is provided.
type ProjectName = String
data ProjectHistory =
ProjectHistory { history :: [ProjectName] -- ^ Project names in reverse-chronological order.
}
deriving (Typeable, Read, Show)
instance ExtensionClass ProjectHistory where
initialValue = ProjectHistory []
extensionType = PersistentExtension
focus' :: Maybe (Stack a) -> Maybe a
focus' = maybe Nothing (Just . W.focus)
-- | A 'logHook' that keeps track of the order in which projects have
-- been viewed.
projectHistoryHook :: ProjectName -> X ()
projectHistoryHook projectName = do
return projectName >>= (XS.modify . makeFirst)
projectHistoryDeleteHook :: ProjectName -> X ()
projectHistoryDeleteHook projectName = do
return projectName >>= (XS.modify . delete_)
-- | A list of workspace tags in the order they have been viewed, with the
-- most recent first. No duplicates are present, but not all workspaces are
-- guaranteed to appear, and there may be workspaces that no longer exist.
projectHistory :: X [ProjectName]
projectHistory = XS.gets history
-- | Cons the 'Project' onto the 'ProjectHistory' if it is not
-- already there, or move it to the front if it is.
makeFirst :: ProjectName -> ProjectHistory -> ProjectHistory
makeFirst w v = let (xs, ys) = break (w ==) $ history v
in v { history = w : (xs ++ drop 1 ys) }
delete_ :: ProjectName -> ProjectHistory -> ProjectHistory
delete_ w v = let (xs, ys) = break (w ==) $ history v
in v { history = (xs ++ drop 1 ys) }
|
eb-gh-cr/XMonadContrib1
|
XMonad/Hooks/ProjectHistory.hs
|
bsd-3-clause
| 2,936 | 0 | 12 | 714 | 470 | 273 | 197 | 37 | 1 |
{-# LANGUAGE DeriveGeneric
, DataKinds
, KindSignatures
, InstanceSigs
, RecordWildCards #-}
module Data.Wizard where
import qualified Data.Wizard.Command as Com
import Data.Wizard.Model
import qualified Data.Text as T
import GHC.TypeLits
import Data.FiniteDouble
import Control.Arrow((***))
import Data.ComponentSystem
import Data.Functor.Apply
import Data.ComponentSystem.Terrain
initialState :: GameState
initialState = emptyGameState {terrainState = newTerrainState}
getDimensions :: (Int, Int)
getDimensions = let (x, y) = (finiteZero, finiteZero) :: GamePosition
in (fromIntegral $ natVal x, fromIntegral $ natVal y)
addPlayer :: PlayerId -> GameState -> GameState
addPlayer pid g@(GameState{..})= let add = addComponent (TextId pid)
size = fromIntegral $ 5 * T.length pid
in
g { positionSys = add (finiteZero,finiteZero) positionSys
, velocitySys = add (0, 0) velocitySys
, playerSys = add pid playerSys
, boundSys = add (RectangleBound (clampedCast size) (clampedCast size)) boundSys}
removePlayer :: PlayerId -> GameState -> GameState
removePlayer n g@(GameState {..}) = let del = deleteComponent (TextId n)
in g { positionSys = del positionSys
, velocitySys = del velocitySys
, playerSys = del playerSys}
updateGame :: PlayerId -> Com.GameCommand -> GameState -> GameState
updateGame pId (Com.Move d) g@(GameState{..}) = g {velocitySys = updateComponent (Just . setVelocity 20 d) (TextId pId) velocitySys}
updateGame pId (Com.StopMove d) g@(GameState{..}) = g {velocitySys = updateComponent (Just . stopVelocity d) (TextId pId) velocitySys}
updateGame pId (Com.Configuration Com.AddPlayer) g = addPlayer pId g
updateGame pId (Com.Configuration Com.RemovePlayer) g = removePlayer pId g
stepGame :: Double -> GameState -> IO GameState
stepGame i g@GameState{..} = do
let g' = g {positionSys = updateSys (move i <$> velocitySys <.>) positionSys}
updateTerrain g'
setVelocity :: Double -> Com.Direction -> Velocity -> Velocity
setVelocity speed d (x,y) = case d of
Com.Up -> (x, -speed)
Com.Down -> (x, speed)
Com.Left -> (-speed, y)
Com.Right -> (speed, y)
stopVelocity :: Com.Direction -> Velocity -> Velocity
stopVelocity d (x,y) = case d of
Com.Up -> (x, 0)
Com.Down -> (x, 0)
Com.Left -> (0, y)
Com.Right -> (0, y)
move :: (KnownNat w, KnownNat h) => Double -> Vector -> (FiniteDouble w, FiniteDouble h) -> (FiniteDouble w, FiniteDouble h)
move delta (vecx, vecy) p = (\ (fx, fy) -> (fx$ vecx*delta, fy $ vecy * delta )) $ (clampedAdd *** clampedAdd) p
|
smobs/elblog
|
server/src/Data/Wizard.hs
|
bsd-3-clause
| 3,073 | 0 | 15 | 966 | 976 | 531 | 445 | 55 | 4 |
module System.Win32.Notify
( Event(..)
, EventVariety(..)
, Handler
, WatchId(..)
, WatchManager(..)
, initWatchManager
, killWatch
, killWatchManager
, watch
, watchDirectory
) where
import Control.Concurrent
import Control.Concurrent.MVar
import Data.Bits
import Data.List (intersect)
import Data.Map (Map)
import System.Directory
import System.Win32 (closeHandle)
import System.Win32.File
import System.Win32.FileNotify
import qualified Data.Map as Map
data EventVariety
= Modify
| Move
| Create
| Delete
deriving Eq
data Event
-- | A file was modified. @Modified isDirectory file@
= Modified
{ isDirectory :: Bool
, filePath :: FilePath
}
-- TODO: Problems with receiving (oldName, nil), (nil, newName) events at
-- unpredictable times mean that, for now, rename detection is disabled.
{-
-- A file was moved within the directory.
| Renamed
{ isDirectory :: Bool
, oldName :: Maybe FilePath
, newName :: Maybe FilePath
}
-}
-- | A file was created. @Created isDirectory file@
| Created
{ isDirectory :: Bool
, filePath :: FilePath
}
-- | A file was deleted. @Deleted isDirectory file@
| Deleted
{ isDirectory :: Bool
, filePath :: FilePath
}
deriving (Eq, Show)
type Handler = Event -> IO ()
data WatchId = WatchId ThreadId ThreadId Handle deriving (Eq, Ord, Show)
type WatchMap = Map WatchId Handler
data WatchManager = WatchManager (MVar WatchMap)
void :: IO ()
void = return ()
initWatchManager :: IO WatchManager
initWatchManager = do
mvarMap <- newMVar Map.empty
return (WatchManager mvarMap)
killWatchManager :: WatchManager -> IO ()
killWatchManager (WatchManager mvarMap) = do
watchMap <- readMVar mvarMap
flip mapM_ (Map.keys watchMap) $ killWatch
varietiesToFnFlags :: [EventVariety] -> FileNotificationFlag
varietiesToFnFlags = foldl (.|.) 0 . map evToFnFlag'
where evToFnFlag' :: EventVariety -> FileNotificationFlag
evToFnFlag' ev = case ev of
Modify -> fILE_NOTIFY_CHANGE_LAST_WRITE
Move -> fILE_NOTIFY_CHANGE_FILE_NAME .|. fILE_NOTIFY_CHANGE_DIR_NAME
Create -> fILE_NOTIFY_CHANGE_FILE_NAME .|. fILE_NOTIFY_CHANGE_DIR_NAME
Delete -> fILE_NOTIFY_CHANGE_FILE_NAME .|. fILE_NOTIFY_CHANGE_DIR_NAME
-- watchDirectoryOnce :: FilePath -> Bool -> [EventVariety] -> IO
-- watchDirectoryOnce dir wst evs = do
-- h <- getWatchHandle dir
-- readDirectoryChanges h wst (evToFnFlag evs) >>= actsToEvent
watchDirectory :: WatchManager -> FilePath -> Bool -> [EventVariety] -> Handler -> IO WatchId
watchDirectory (WatchManager mvarMap) dir watchSubTree varieties handler = do
watchHandle <- getWatchHandle dir
chanEvents <- newChan
tid1 <- forkIO $ dispatcher chanEvents
tid2 <- forkIO $ osEventsReader watchHandle chanEvents
modifyMVar_ mvarMap $ \watchMap -> return (Map.insert (WatchId tid1 tid2 watchHandle) handler watchMap)
return (WatchId tid1 tid2 watchHandle)
where
dispatcher :: Chan [Event] -> IO ()
dispatcher chanEvents = do
events <- readChan chanEvents
mapM_ maybeHandle events
dispatcher chanEvents
osEventsReader :: Handle -> Chan [Event] -> IO ()
osEventsReader watchHandle chanEvents = do
events <- (readDirectoryChanges watchHandle watchSubTree (varietiesToFnFlags varieties) >>= actsToEvents)
writeChan chanEvents events
osEventsReader watchHandle chanEvents
maybeHandle :: Handler
maybeHandle event =
if (==) (eventToVariety event) `any` varieties then handler event else void
watch :: WatchManager -> FilePath -> Bool -> [EventVariety] -> IO (WatchId, Chan [Event])
watch (WatchManager mvarMap) dir watchSubTree varieties = do
watchHandle <- getWatchHandle dir
chanEvents <- newChan
tid <- forkIO $ osEventsReader watchHandle chanEvents
modifyMVar_ mvarMap $ \watchMap -> return (Map.insert (WatchId tid tid watchHandle) (\_ -> void) watchMap)
return ((WatchId tid tid watchHandle), chanEvents)
where
osEventsReader :: Handle -> Chan [Event] -> IO ()
osEventsReader watchHandle chanEvents = do
events <- (readDirectoryChanges watchHandle watchSubTree (varietiesToFnFlags varieties) >>= actsToEvents)
writeChan chanEvents events
osEventsReader watchHandle chanEvents
killWatch :: WatchId -> IO ()
killWatch (WatchId tid1 tid2 handle) = do
killThread tid1
if tid1 /= tid2 then killThread tid2 else void
closeHandle handle
eventToVariety :: Event -> EventVariety
eventToVariety event = case event of
Created _ _ -> Create
Deleted _ _ -> Delete
Modified _ _ -> Modify
-- Renamed _ _ _ -> [Move]
actsToEvents :: [(Action, String)] -> IO [Event]
actsToEvents = mapM actToEvent
where
actToEvent (act, fn) = do
isDir <- doesDirectoryExist fn
case act of
FileModified -> return $ Modified isDir fn
FileAdded -> return $ Created isDir fn
FileRemoved -> return $ Deleted isDir fn
FileRenamedOld -> return $ Deleted isDir fn
FileRenamedNew -> return $ Created isDir fn
-- actsToEvent [(FileRenamedOld, fnold),(FileRenamedNew, fnnew)] = do
-- isDir <- doesDirectoryExist fnnew
-- return $ Renamed isDir (Just fnold) fnnew
|
haskell-fswatch/win32-notify
|
src/System/Win32/Notify.hs
|
bsd-3-clause
| 5,537 | 0 | 14 | 1,377 | 1,324 | 685 | 639 | 113 | 5 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE RankNTypes #-}
module Graphics.UI.WX.Turtle(
-- * meta data
xturtleVersion,
-- * types and classes
Field,
Turtle,
ColorClass,
-- * Field functions
-- ** meta
openField,
closeField,
waitField,
topleft,
center,
-- ** on events
oninputtext,
onclick,
onrelease,
ondrag,
onmotion,
onkeypress,
ontimer,
-- * Turtle functions
-- ** meta
newTurtle,
killTurtle,
inputs,
runInputs,
getSVG,
-- ** move turtle
forward,
backward,
goto,
setx,
sety,
left,
right,
setheading,
circle,
home,
undo,
sleep,
flush,
-- ** draw
dot,
stamp,
beginfill,
endfill,
write,
image,
bgcolor,
clear,
-- ** change states
addshape,
beginpoly,
endpoly,
getshapes,
shape,
shapesize,
hideturtle,
showturtle,
penup,
pendown,
pencolor,
pensize,
fillcolor,
radians,
degrees,
speed,
flushoff,
flushon,
-- ** informations
position,
xcor,
ycor,
distance,
heading,
towards,
isdown,
isvisible,
windowWidth,
windowHeight
) where
import Graphics.UI.WX.Turtle.Data(shapeTable, speedTable)
import Graphics.UI.WX.Turtle.State(
TurtleState, direction, visible, undonum, drawed, polyPoints)
import qualified Graphics.UI.WX.Turtle.State as S(position, degrees, pendown)
import Graphics.UI.WX.Turtle.Input(TurtleInput(..), turtleSeries)
import Graphics.UI.WX.Turtle.Move(
Field, Coordinates(..), openField, closeField, waitField,
topleft, center, coordinates, fieldSize, forkField, flushField,
addLayer, clearLayer, addCharacter, clearCharacter, moveTurtle,
oninputtext, onclick, onrelease, ondrag, onmotion, onkeypress, ontimer)
import Text.XML.YJSVG(SVG(..), Position(..), Color(..))
import qualified Text.XML.YJSVG as S(center, topleft)
import Control.Concurrent(killThread, newChan, writeChan, getChanContents)
import Control.Monad(replicateM_, zipWithM_)
import Control.Arrow((&&&))
import Data.IORef(IORef, newIORef, readIORef)
import Data.IORef.Tools(atomicModifyIORef_)
import Data.Fixed(mod')
--------------------------------------------------------------------------------
xturtleVersion :: (Int, String)
xturtleVersion = (69, "0.1.11")
--------------------------------------------------------------------------------
data Turtle = Turtle {
field :: Field, input :: TurtleInput -> IO (),
info :: forall a . (TurtleState -> a) -> IO a,
shapes :: IORef [(String, [(Double, Double)])],
inputs :: IO [TurtleInput], killTurtle :: IO ()}
class ColorClass a where getColor :: a -> Color
instance ColorClass String where getColor = ColorName
instance (Integral r, Integral g, Integral b) => ColorClass (r, g, b) where
getColor (r, g, b) =
RGB (fromIntegral r) (fromIntegral g) (fromIntegral b)
--------------------------------------------------------------------------------
newTurtle :: Field -> IO Turtle
newTurtle f = do
index <- newIORef 1; shapesRef <- newIORef shapeTable
chan <- newChan; hist <- getChanContents chan
let states = turtleSeries hist
l <- addLayer f; c <- addCharacter f
thr <- forkField f $ zipWithM_ (moveTurtle f c l) states $ tail states
let t = Turtle {
field = f,
input = (atomicModifyIORef_ index succ >>) . writeChan chan,
info = \n -> fmap (n . (states !!)) $ readIORef index,
shapes = shapesRef,
inputs = fmap (flip take hist . pred) $ readIORef index,
killTurtle = flushField f True $
clearLayer l >> clearCharacter c >> killThread thr}
shape t "classic" >> input t (Undonum 0) >> return t
runInputs :: Turtle -> [TurtleInput] -> IO ()
runInputs = mapM_ . input
getSVG :: Turtle -> IO [SVG]
getSVG = fmap reverse . flip info drawed
convertPosition :: Turtle -> Position -> IO Position
convertPosition t p = do
(w, h) <- windowSize t
coord <- coordinates $ field t
return $ case coord of
CoordCenter -> S.center w h p
CoordTopLeft -> S.topleft w h p
--------------------------------------------------------------------------------
forward, backward :: Turtle -> Double -> IO ()
forward t = input t . Forward
backward t = forward t . negate
goto :: Turtle -> Double -> Double -> IO ()
goto t@Turtle{field = f} x y = do
coord <- coordinates f
input t $ Goto $ case coord of
CoordCenter -> Center x y
CoordTopLeft -> TopLeft x y
setx, sety :: Turtle -> Double -> IO ()
setx t x = do
pos <- info t S.position >>= convertPosition t
input t $ Goto $ case pos of
Center _ y -> Center x y
TopLeft _ y -> TopLeft x y
sety t y = do
pos <- info t S.position >>= convertPosition t
input t $ Goto $ case pos of
Center x _ -> Center x y
TopLeft x _ -> TopLeft x y
left, right, setheading :: Turtle -> Double -> IO ()
left t = input t . TurnLeft
right t = left t . negate
setheading t = input t . Rotate
circle :: Turtle -> Double -> IO ()
circle t r = do
deg <- info t S.degrees
forward t (r * pi / 36)
left t (deg / 36)
replicateM_ 35 $ forward t (2 * r * pi / 36) >> left t (deg / 36)
forward t (r * pi / 36)
input t $ Undonum 74
home :: Turtle -> IO ()
home t = goto t 0 0 >> setheading t 0 >> input t (Undonum 3)
undo :: Turtle -> IO ()
undo t = info t undonum >>= flip replicateM_ (input t Undo)
sleep :: Turtle -> Int -> IO ()
sleep t = input t . Sleep
flush :: Turtle -> IO ()
flush = (`input` Flush)
--------------------------------------------------------------------------------
dot :: Turtle -> Double -> IO ()
dot t = input t . Dot
stamp :: Turtle -> IO ()
stamp = (`input` Stamp)
beginfill, endfill :: Turtle -> IO ()
beginfill = (`input` SetFill True)
endfill = (`input` SetFill False)
write :: Turtle -> String -> Double -> String -> IO ()
write t fnt sz = input t . Write fnt sz
image :: Turtle -> FilePath -> Double -> Double -> IO ()
image t fp = curry $ input t . uncurry (PutImage fp)
bgcolor :: ColorClass c => Turtle -> c -> IO ()
bgcolor t = input t . Bgcolor . getColor
clear :: Turtle -> IO ()
clear = (`input` Clear)
--------------------------------------------------------------------------------
addshape :: Turtle -> String -> [(Double, Double)] -> IO ()
addshape t n s = atomicModifyIORef_ (shapes t) ((n, s) :)
beginpoly :: Turtle -> IO ()
beginpoly = (`input` SetPoly True)
endpoly :: Turtle -> IO [(Double, Double)]
endpoly t = input t (SetPoly False) >> info t polyPoints >>=
mapM (fmap (posX &&& posY) . convertPosition t)
getshapes :: Turtle -> IO [String]
getshapes = fmap (map fst) . readIORef . shapes
shape :: Turtle -> String -> IO ()
shape t n = readIORef (shapes t) >>=
maybe (putStrLn $ "no shape named " ++ n) (input t . Shape) . lookup n
shapesize :: Turtle -> Double -> Double -> IO ()
shapesize t = curry $ input t . uncurry Shapesize
hideturtle, showturtle :: Turtle -> IO ()
hideturtle = (`input` SetVisible False)
showturtle = (`input` SetVisible True)
penup, pendown :: Turtle -> IO ()
penup = (`input` SetPendown False)
pendown = (`input` SetPendown True)
pencolor :: ColorClass c => Turtle -> c -> IO ()
pencolor t = input t . Pencolor . getColor
fillcolor :: ColorClass c => Turtle -> c -> IO ()
fillcolor t = input t . Fillcolor . getColor
pensize :: Turtle -> Double -> IO ()
pensize t = input t . Pensize
radians :: Turtle -> IO ()
radians = (`degrees` (2 * pi))
degrees :: Turtle -> Double -> IO ()
degrees t = input t . Degrees
speed :: Turtle -> String -> IO ()
speed t str = case lookup str speedTable of
Just (ps, ds) -> do
input t $ PositionStep ps
input t $ DirectionStep ds
input t $ Undonum 3
Nothing -> putStrLn "no such speed"
flushoff, flushon :: Turtle -> IO ()
flushoff = (`input` SetFlush False)
flushon = (`input` SetFlush True)
--------------------------------------------------------------------------------
position :: Turtle -> IO (Double, Double)
position t = fmap (posX &&& posY) $ info t S.position >>= convertPosition t
xcor, ycor :: Turtle -> IO Double
xcor = fmap fst . position
ycor = fmap snd . position
distance :: Turtle -> Double -> Double -> IO Double
distance t x0 y0 = do
(x, y) <- position t
return $ ((x - x0) ** 2 + (y - y0) ** 2) ** (1 / 2)
heading :: Turtle -> IO Double
heading t = do
deg <- info t S.degrees
dir <- fmap (* (deg / (2 * pi))) $ info t direction
return $ dir `mod'` deg
towards :: Turtle -> Double -> Double -> IO Double
towards t x0 y0 = do
(x, y) <- position t
deg <- info t S.degrees
let dir = atan2 (y0 - y) (x0 - x) * deg / (2 * pi)
return $ if dir < 0 then dir + deg else dir
isdown, isvisible :: Turtle -> IO Bool
isdown = flip info S.pendown
isvisible = flip info visible
windowWidth, windowHeight :: Turtle -> IO Double
windowWidth = fmap fst . windowSize
windowHeight = fmap snd . windowSize
windowSize :: Turtle -> IO (Double, Double)
windowSize = fieldSize . field
|
YoshikuniJujo/wxturtle
|
src/Graphics/UI/WX/Turtle.hs
|
bsd-3-clause
| 8,671 | 178 | 17 | 1,648 | 3,629 | 1,932 | 1,697 | 254 | 2 |
------------------------------------------------------------
-- The Xtract tool - an XML-grep.
------------------------------------------------------------
module Main where
import System (getArgs, exitWith, ExitCode(..))
import IO
import Char (toLower)
import List (isSuffixOf)
import Text.XML.HaXml.Types
import Text.XML.HaXml.Posn (posInNewCxt)
import Text.XML.HaXml.Parse (xmlParse)
import Text.XML.HaXml.Html.Parse (htmlParse)
import Text.XML.HaXml.Xtract.Parse (xtract)
import Text.PrettyPrint.HughesPJ (render, vcat, hcat, empty)
import Text.XML.HaXml.Pretty (content)
import Text.XML.HaXml.Html.Generate (htmlprint)
main =
getArgs >>= \args->
if length args < 1 then
putStrLn "Usage: Xtract <pattern> [xmlfile ...]" >>
exitWith (ExitFailure 1)
else
let (pattern:files) = args
-- findcontents =
-- if null files then (getContents >>= \x-> return [xmlParse "<stdin>"x])
-- else mapM (\x-> do c <- (if x=="-" then getContents else readFile x)
-- return ((if isHTML x
-- then htmlParse x else xmlParse x) c))
-- files
in
-- findcontents >>= \cs->
-- ( hPutStrLn stdout . render . vcat
-- . map (vcat . map content . selection . getElem)) cs
mapM_ (\x-> do c <- (if x=="-" then getContents else readFile x)
( if isHTML x then
hPutStrLn stdout . render . htmlprint .
xtract (map toLower pattern) . getElem x . htmlParse x
else hPutStrLn stdout . render . format .
xtract pattern . getElem x . xmlParse x) c
hFlush stdout)
files
getElem x (Document _ _ e _) = CElem e (posInNewCxt x Nothing)
isHTML x = ".html" `isSuffixOf` x || ".htm" `isSuffixOf` x
format [] = empty
format cs@(CString _ _ _:_) = hcat . map content $ cs
format cs@(CRef _ _:_) = hcat . map content $ cs
format cs = vcat . map content $ cs
|
FranklinChen/hugs98-plus-Sep2006
|
packages/HaXml/src/tools/Xtract.hs
|
bsd-3-clause
| 2,061 | 0 | 23 | 610 | 513 | 284 | 229 | 33 | 4 |
{-# LANGUAGE FlexibleContexts #-}
module RDSTests.DBSnapshotTests
( runDBSnapshotTests
)
where
import Control.Applicative ((<$>))
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Resource (MonadResource, MonadBaseControl)
import Data.Text (Text)
import Test.Hspec
import Cloud.AWS.RDS
import Cloud.AWS.RDS.Types
import Cloud.AWS.RDS.Util
import Util
import RDSTests.Util
region :: Text
region = "ap-northeast-1"
runDBSnapshotTests :: IO ()
runDBSnapshotTests = hspec $ do
describeDBSnapshotsTest
createDBSnapshotTest
copyDBSnapshotTest
describeDBSnapshotsTest :: Spec
describeDBSnapshotsTest = do
describe "describeDBSnapshots doesn't fail" $ do
it "describeDBSnapshots doesn't throw any exception" $ do
testRDS region (
describeDBSnapshots Nothing Nothing Nothing Nothing Nothing
) `miss` anyConnectionException
createDBSnapshotTest :: Spec
createDBSnapshotTest = do
describe "{create,delete}DBSnapshot doesn't fail" $ do
it "{create,delete}DBSnapshot doesn't throw any exception" $ do
testRDS region (do
dbsid <- liftIO $ getRandomText "hspec-create-delete-"
dbiid <- dbInstanceIdentifier . head <$>
describeDBInstances Nothing Nothing Nothing
withDBSnapshot dbiid dbsid $
waitUntilAvailable . dbSnapshotIdentifier
) `miss` anyConnectionException
waitUntilAvailable :: (MonadBaseControl IO m, MonadResource m) => Text -> RDS m DBSnapshot
waitUntilAvailable = wait
(\dbs -> dbSnapshotStatus dbs == "available")
(\dbsid -> describeDBSnapshots Nothing (Just dbsid) Nothing Nothing Nothing)
copyDBSnapshotTest :: Spec
copyDBSnapshotTest = do
describe "copyDBSnapshot doesn't fail" $ do
it "copyDBSnapshot doesn't throw any exception" $ do
testRDS region (do
target <- liftIO $ getRandomText "hspec-copy-"
source <- dbSnapshotIdentifier . head <$>
describeDBSnapshots Nothing Nothing Nothing Nothing (Just "automated")
copyDBSnapshot source target
waitUntilAvailable target
deleteDBSnapshot target
) `miss` anyConnectionException
|
worksap-ate/aws-sdk
|
test/RDSTests/DBSnapshotTests.hs
|
bsd-3-clause
| 2,309 | 0 | 22 | 582 | 483 | 248 | 235 | 54 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{- HLINT ignore "Reduce duplication" -}
module DTX2MIDISpec where
import Codec.Midi (Midi (..))
import qualified Codec.Midi as Midi
import DTX2MIDI
import DTX2MIDI.DTX
import DTX2MIDI.DTX.Parser
import Test.Hspec
spec :: Spec
spec = do
describe "keyCompletion" $ do
it "returns filled measure ids" $ do
keyCompletion ["001", "005"] `shouldBe` ["000", "001", "002", "003", "004", "005"]
describe "objectCompletion" $ do
it "returns missing measure objects that are filled with empty hi-hats" $ do
objectCompletion ["001", "005"]
`shouldBe` [ Object "000" $ HiHatClose ["00"],
Object "002" $ HiHatClose ["00"],
Object "003" $ HiHatClose ["00"],
Object "004" $ HiHatClose ["00"]
]
describe "completedNoteObjects" $ do
it "returns note objects that are filled with empty hi-hats" $ do
let input =
[ Object "001" $ HiHatClose ["01", "01", "01", "01", "01", "01", "01", "01"],
Object "001" $ Snare ["00", "02", "00", "02"],
Object "001" $ BassDrum ["03", "00", "00", "00", "03", "03", "00", "00"],
Object "002" $ UnsupportedEvent "61" "61",
Object "004" $ HiHatClose ["01", "01", "01", "01", "01", "01", "01", "01"],
Object "004" $ Snare ["00", "02", "00", "02"],
Object "004" $ BassDrum ["03", "00", "00", "00", "03", "03", "00", "00"],
Object "005" $ UnsupportedEvent "61" "61"
]
let expected =
[ Object "000" $ HiHatClose ["00"],
Object "001" $ HiHatClose ["01", "01", "01", "01", "01", "01", "01", "01"],
Object "001" $ Snare ["00", "02", "00", "02"],
Object "001" $ BassDrum ["03", "00", "00", "00", "03", "03", "00", "00"],
Object "002" $ HiHatClose ["00"],
Object "003" $ HiHatClose ["00"],
Object "004" $ HiHatClose ["01", "01", "01", "01", "01", "01", "01", "01"],
Object "004" $ Snare ["00", "02", "00", "02"],
Object "004" $ BassDrum ["03", "00", "00", "00", "03", "03", "00", "00"]
]
completedNoteObjects input `shouldBe` expected
describe "dtxToMIDI" $ do
let chan = 9
let vel = 127
let bd = 35
let sd = 38
let hh = 42
let genMidi = \tracks ->
Midi
{ Midi.fileType = Midi.SingleTrack,
Midi.timeDiv = Midi.TicksPerBeat 96,
Midi.tracks = tracks
}
it "returns midi with specified bpm when the header has a BPM" $ do
-- input
let dtx =
[ LineHeader $ Header "BPM" "" "180",
LineObject $ Object "001" $ HiHatClose ["01", "01", "01", "01", "01", "01", "01", "01"],
LineObject $ Object "001" $ Snare ["00", "02", "00", "02"],
LineObject $ Object "001" $ BassDrum ["03", "00", "00", "00", "03", "03", "00", "00"]
]
-- expected
let tracks =
[ [ (0, Midi.ProgramChange chan 0),
(0, Midi.TempoChange 333333),
(96 * 4, Midi.NoteOn chan bd vel),
(0, Midi.NoteOn chan hh vel),
(48, Midi.NoteOff chan bd vel),
(0, Midi.NoteOff chan hh vel),
(0, Midi.NoteOn chan hh vel),
(48, Midi.NoteOff chan hh vel),
(0, Midi.NoteOn chan sd vel),
(0, Midi.NoteOn chan hh vel),
(48, Midi.NoteOff chan hh vel),
(0, Midi.NoteOn chan hh vel),
(48, Midi.NoteOff chan sd vel),
(0, Midi.NoteOff chan hh vel),
(0, Midi.NoteOn chan bd vel),
(0, Midi.NoteOn chan hh vel),
(48, Midi.NoteOff chan bd vel),
(0, Midi.NoteOff chan hh vel),
(0, Midi.NoteOn chan bd vel),
(0, Midi.NoteOn chan hh vel),
(48, Midi.NoteOff chan bd vel),
(0, Midi.NoteOff chan hh vel),
(0, Midi.NoteOn chan sd vel),
(0, Midi.NoteOn chan hh vel),
(48, Midi.NoteOff chan hh vel),
(0, Midi.NoteOn chan hh vel),
(48, Midi.NoteOff chan sd vel),
(0, Midi.NoteOff chan hh vel)
]
]
midi <- dtxToMIDI dtx
midi `shouldBe` genMidi tracks
it "returns midi with default bpm when the header has not a BPM" $ do
-- input
let dtx =
[ LineObject $ Object "001" $ HiHatClose ["01", "01", "01", "01", "01", "01", "01", "01"],
LineObject $ Object "001" $ Snare ["00", "02", "00", "02"],
LineObject $ Object "001" $ BassDrum ["03", "00", "00", "00", "03", "03", "00", "00"]
]
-- expected
let tracks =
[ [ (0, Midi.ProgramChange chan 0),
(0, Midi.TempoChange 500000),
(96 * 4, Midi.NoteOn chan bd vel),
(0, Midi.NoteOn chan hh vel),
(48, Midi.NoteOff chan bd vel),
(0, Midi.NoteOff chan hh vel),
(0, Midi.NoteOn chan hh vel),
(48, Midi.NoteOff chan hh vel),
(0, Midi.NoteOn chan sd vel),
(0, Midi.NoteOn chan hh vel),
(48, Midi.NoteOff chan hh vel),
(0, Midi.NoteOn chan hh vel),
(48, Midi.NoteOff chan sd vel),
(0, Midi.NoteOff chan hh vel),
(0, Midi.NoteOn chan bd vel),
(0, Midi.NoteOn chan hh vel),
(48, Midi.NoteOff chan bd vel),
(0, Midi.NoteOff chan hh vel),
(0, Midi.NoteOn chan bd vel),
(0, Midi.NoteOn chan hh vel),
(48, Midi.NoteOff chan bd vel),
(0, Midi.NoteOff chan hh vel),
(0, Midi.NoteOn chan sd vel),
(0, Midi.NoteOn chan hh vel),
(48, Midi.NoteOff chan hh vel),
(0, Midi.NoteOn chan hh vel),
(48, Midi.NoteOff chan sd vel),
(0, Midi.NoteOff chan hh vel)
]
]
midi <- dtxToMIDI dtx
midi `shouldBe` genMidi tracks
it "returns midi with the missing measure completed by rests" $ do
-- input
let dtx =
[ LineObject $ Object "001" $ BassDrum ["03", "03", "03", "03"],
LineObject $ Object "003" $ BassDrum ["03", "03", "03", "03"]
]
-- expected
let tracks =
[ [ (0, Midi.ProgramChange chan 0),
(0, Midi.TempoChange 500000),
(96 * 4, Midi.NoteOn chan bd vel),
(96, Midi.NoteOff chan bd vel),
(0, Midi.NoteOn chan bd vel),
(96, Midi.NoteOff chan bd vel),
(0, Midi.NoteOn chan bd vel),
(96, Midi.NoteOff chan bd vel),
(0, Midi.NoteOn chan bd vel),
(96, Midi.NoteOff chan bd vel),
(96 * 4, Midi.NoteOn chan bd vel),
(96, Midi.NoteOff chan bd vel),
(0, Midi.NoteOn chan bd vel),
(96, Midi.NoteOff chan bd vel),
(0, Midi.NoteOn chan bd vel),
(96, Midi.NoteOff chan bd vel),
(0, Midi.NoteOn chan bd vel),
(96, Midi.NoteOff chan bd vel)
]
]
midi <- dtxToMIDI dtx
midi `shouldBe` genMidi tracks
it "returns midi with the unsupported event measure completed by rests" $ do
-- input
let dtx =
[ LineObject $ Object "001" $ BassDrum ["03", "03", "03", "03"],
LineObject $ Object "002" $ UnsupportedEvent "02" "0.5",
LineObject $ Object "003" $ BassDrum ["03", "03", "03", "03"]
]
-- expected
let tracks =
[ [ (0, Midi.ProgramChange chan 0),
(0, Midi.TempoChange 500000),
(96 * 4, Midi.NoteOn chan bd vel),
(96, Midi.NoteOff chan bd vel),
(0, Midi.NoteOn chan bd vel),
(96, Midi.NoteOff chan bd vel),
(0, Midi.NoteOn chan bd vel),
(96, Midi.NoteOff chan bd vel),
(0, Midi.NoteOn chan bd vel),
(96, Midi.NoteOff chan bd vel),
(96 * 4, Midi.NoteOn chan bd vel),
(96, Midi.NoteOff chan bd vel),
(0, Midi.NoteOn chan bd vel),
(96, Midi.NoteOff chan bd vel),
(0, Midi.NoteOn chan bd vel),
(96, Midi.NoteOff chan bd vel),
(0, Midi.NoteOn chan bd vel),
(96, Midi.NoteOff chan bd vel)
]
]
midi <- dtxToMIDI dtx
midi `shouldBe` genMidi tracks
|
akiomik/dtx2midi
|
test/DTX2MIDISpec.hs
|
bsd-3-clause
| 8,917 | 0 | 20 | 3,498 | 3,088 | 1,692 | 1,396 | 177 | 1 |
{-# LANGUAGE OverloadedStrings, NoImplicitPrelude #-}
module Talks.Free.UglyExample where
import Talks.Free.Prelude
import Talks.Free.Ugly
import Data.Text (unpack)
import Data.Monoid ((<>))
import Data.Foldable (elem)
runUglyExample :: IO ()
runUglyExample =
-- turn up logging
do setSetting "log.level" "noisy"
-- generate some passwords
p1 <- mkPassword
setSetting "password.length" "6"
p2 <- mkPassword
-- store some passwords
storePassword "p1" p1
storePassword "p2" p2
-- generate and store some more passwords
clearSetting "password.length"
setSetting "log.level" "quiet"
p3 <- mkPassword
p4 <- mkPassword
let p5 = "passw0rd"
storePassword "p3" p4 -- Oops!
storePassword "p4" p4
storePassword "p5" p5
setSetting "log.level" "noisy"
p1' <- lookupPassword "p1"
p2' <- lookupPassword "p2"
p3' <- lookupPassword "p3"
p4' <- lookupPassword "p4"
p5' <- lookupPassword "p5"
putStrLn $ if p1 `elem` p1'
then "=== store worked as expected: " <> unpack p1
else "=== what happened?"
putStrLn $ if p2 `elem` p2'
then "=== store worked as expected: " <> unpack p2
else "=== what happened?"
putStrLn $ if p3 `elem` p3'
then "=== store worked as expected: " <> unpack p3
else "=== what happened?"
putStrLn $ if p4 `elem` p4'
then "=== store worked as expected: " <> unpack p4
else "=== what happened?"
putStrLn $ if p5 `elem` p5'
then "=== store worked as expected: " <> unpack p5
else "=== what happened?"
|
markhibberd/fp-syd-free
|
src/Talks/Free/UglyExample.hs
|
bsd-3-clause
| 1,636 | 0 | 10 | 451 | 377 | 187 | 190 | 44 | 6 |
{-# LANGUAGE NamedFieldPuns #-}
-- |
-- Module: Data.Pool
-- Copyright: (c) 2013 Kim Altintop, (c) 2011 MailRank, Inc.
-- License: BSD3
-- Maintainer: Kim Altintop <[email protected]>
-- Stability: experimental
-- Portability: portable
--
-- A high-performance striped pooling abstraction for managing flexibly-sized
-- collections of resources such as database connections.
--
-- This module is based on @resource-pool@. For more comprehensive
-- documentation, please refer to the original package:
-- <http://hackage.haskell.org/package/resource-pool>
--
module Data.Pool
( Pool(nStripes, idleTime, maxResources)
, LocalPool
, createPool
, destroyResource
, purgePool
, putResource
, takeResource
, tryTakeResource
, tryWithResource
, withResource
)
where
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import Control.Monad.Catch (MonadMask)
import qualified Control.Monad.Catch as E
import Control.Monad.IO.Class
import Data.Hashable (hash)
import Data.IORef (IORef, mkWeakIORef, newIORef)
import Data.List (partition)
import Data.Time.Clock
import Data.Vector (Vector, (!))
import qualified Data.Vector as V
import Data.Word
data Resource a = Resource
{ resource :: !a
, lastUse :: !UTCTime
}
data LocalPool a = LocalPool
{ inUse :: !(TVar Word32)
, resources :: !(TVar [Resource a])
, lfin :: !(IORef ())
}
data Pool a = Pool
{ create :: IO a
, destroy :: a -> IO ()
, nStripes :: !Word32
, idleTime :: !NominalDiffTime
, maxResources :: !Word32
, localPools :: !(Vector (LocalPool a))
, fin :: !(IORef ())
}
instance Show (Pool a) where
show p = "Pool {nStripes = " ++ show (nStripes p) ++ ", " ++
"idleTime = " ++ show (idleTime p) ++ ", " ++
"maxResources = " ++ show (maxResources p) ++ "}"
createPool :: IO a
-- ^ Action to create a new resource
-> (a -> IO ())
-- ^ Action to destroy a resource
-> Word32
-- ^ Stripe count
-> NominalDiffTime
-- ^ Amount of time after which an unused resource can be released
-> Word32
-- ^ Maximum number of resources per stripe
-> IO (Pool a)
createPool create destroy nStripes idleTime maxResources = do
locals <- V.replicateM (fromIntegral nStripes) $ LocalPool
<$> newTVarIO 0
<*> newTVarIO []
<*> newIORef ()
reapId <- forkIO $ reaper destroy idleTime locals
pool <- Pool create destroy nStripes idleTime maxResources locals
<$> newIORef ()
addFinalizer (fin pool) $ do
killThread reapId
purgePool pool
V.forM_ locals $ \ lp -> addFinalizer (lfin lp) $ purgeLocalPool destroy lp
return pool
where
addFinalizer ref = void . mkWeakIORef ref
-- | Destroys all resources currently not in use and removes them from the pool.
--
-- Note that resources are automatically released when the 'Pool' is
-- garbage-collected. This function is however useful in situations where a
-- 'Pool' is explicitly discarded and resources should be freed immediately.
purgePool :: Pool a -> IO ()
purgePool p = V.forM_ (localPools p) $ purgeLocalPool (destroy p)
withResource :: (MonadIO m, MonadMask m) => Pool a -> (a -> m b) -> m b
{-# SPECIALIZE withResource :: Pool a -> (a -> IO b) -> IO b #-}
withResource p act = E.mask $ \ restore -> do
(r, lp) <- takeResource p
res <- restore (act r) `E.onException` destroyResource p lp r
putResource lp r
return res
{-# INLINABLE withResource #-}
-- | Similar to 'withResource', but only performs the action if a resource could
-- be taken from the pool /without blocking/. Otherwise, 'tryWithResource'
-- returns immediately with 'Nothing' (ie. the action function is /not/ called).
-- Conversely, if a resource can be borrowed from the pool without blocking, the
-- action is performed and it's result is returned, wrapped in a 'Just'.
tryWithResource :: (MonadIO m, MonadMask m)
=> Pool a -> (a -> m b) -> m (Maybe b)
{-# SPECIALIZE tryWithResource :: Pool a -> (a -> IO b) -> IO (Maybe b) #-}
tryWithResource p act = E.mask $ \ restore -> do
mres <- tryTakeResource p
case mres of
Just (r, lp) -> do
res <- restore (act r) `E.onException` destroyResource p lp r
putResource lp r
return (Just res)
Nothing -> restore $ return Nothing
{-# INLINABLE tryWithResource #-}
takeResource :: MonadIO m => Pool a -> m (a, LocalPool a)
{-# SPECIALIZE takeResource :: Pool a -> IO (a, LocalPool a) #-}
takeResource p = do
lp <- getLocalPool p
r <- liftIO . join . atomically $ do
rs <- readTVar (resources lp)
case rs of
(x:xs) -> do
writeTVar (resources lp) xs
return . return . resource $ x
[] -> do
used <- readTVar (inUse lp)
when (used == maxResources p) retry
writeTVar (inUse lp) $! used + 1
return $ liftIO (create p)
`E.onException` modify_ (inUse lp) (subtract 1)
return (r, lp)
{-# INLINABLE takeResource #-}
-- | A non-blocking version of 'takeResource'. The 'tryTakeResource' function
-- returns immediately, with 'Nothing' if the pool is exhausted, or @'Just' (a,
-- 'LocalPool' a)@ if a resource could be borrowed from the pool successfully.
tryTakeResource :: MonadIO m => Pool a -> m (Maybe (a, LocalPool a))
{-# SPECIALIZE tryTakeResource :: Pool a -> IO (Maybe (a, LocalPool a)) #-}
tryTakeResource p = do
lp <- getLocalPool p
r <- liftIO . join . atomically $ do
rs <- readTVar (resources lp)
case rs of
(x:xs) -> do
writeTVar (resources lp) xs
return . return . Just . resource $ x
[] -> do
used <- readTVar (inUse lp)
if used == maxResources p
then return . return $ Nothing
else do
writeTVar (inUse lp) $! used + 1
return $ Just
<$> liftIO (create p)
`E.onException` modify_ (inUse lp) (subtract 1)
return $ flip (,) lp <$> r
{-# INLINABLE tryTakeResource #-}
putResource :: MonadIO m => LocalPool a -> a -> m ()
{-# SPECIALIZE putResource :: LocalPool a -> a -> IO () #-}
putResource lp r = liftIO $ do
now <- getCurrentTime
atomically $ modifyTVar' (resources lp) (Resource r now:)
{-# INLINABLE putResource #-}
destroyResource :: MonadIO m => Pool a -> LocalPool a -> a -> m ()
{-# SPECIALIZE destroyResource :: Pool a -> LocalPool a -> a -> IO () #-}
destroyResource p lp r = liftIO $ do
ignoreExceptions $ destroy p r
modify_ (inUse lp) (subtract 1)
{-# INLINABLE destroyResource #-}
--------------------------------------------------------------------------------
-- Internal --
--------------------------------------------------------------------------------
reaper :: (a -> IO ()) -> NominalDiffTime -> Vector (LocalPool a) -> IO ()
reaper destroy idleTime pools = forever $ do
threadDelay (1 * 1000000)
now <- getCurrentTime
let isStale r = now `diffUTCTime` lastUse r > idleTime
V.forM_ pools $ \ (LocalPool inUse resources _) -> do
rs <- atomically $ do
(stale,fresh) <- partition isStale <$> readTVar resources
unless (null stale) $ do
writeTVar resources fresh
modifyTVar' inUse $ subtract (fromIntegral (length stale))
return (map resource stale)
forM_ rs $ liftIO . ignoreExceptions . destroy
purgeLocalPool :: (a -> IO ()) -> LocalPool a -> IO ()
purgeLocalPool destroy (LocalPool inUse resources _) = do
rs <- atomically $ do
rs <- readTVar resources
modifyTVar' inUse $ subtract (fromIntegral (length rs))
modifyTVar' resources $ const []
return rs
forM_ rs $ liftIO . ignoreExceptions . destroy . resource
{-# INLINABLE purgeLocalPool #-}
getLocalPool :: MonadIO m => Pool a -> m (LocalPool a)
{-# SPECIALIZE getLocalPool :: Pool a -> IO (LocalPool a) #-}
getLocalPool p = do
i <- liftIO $ ((`mod` fromIntegral (nStripes p)) . hash) <$> myThreadId
return $ localPools p ! i
{-# INLINABLE getLocalPool #-}
modify_ :: TVar a -> (a -> a) -> IO ()
modify_ t f = atomically $ modifyTVar' t f
{-# INLINABLE modify_ #-}
ignoreExceptions :: IO () -> IO ()
ignoreExceptions = E.handleAll (const $ return ())
{-# INLINABLE ignoreExceptions #-}
|
kim/ex-pool
|
Data/Pool.hs
|
bsd-3-clause
| 9,073 | 0 | 24 | 2,735 | 2,303 | 1,156 | 1,147 | 185 | 3 |
module Atomo.Spawn where
import Control.Concurrent
import Control.Monad.State
import Atomo.Types
-- | Spawn a process to execute x. Returns the Process value.
spawn :: VM Value -> VM Value
spawn x = do
e <- get
chan <- liftIO newChan
tid <- liftIO . forkIO $ do
runWith (x >> return (particle "ok")) (e { channel = chan })
return ()
return (Process chan tid)
|
vito/atomo
|
src/Atomo/Spawn.hs
|
bsd-3-clause
| 396 | 0 | 16 | 101 | 135 | 67 | 68 | 12 | 1 |
module Pos.Infra.StateLock
( module X
) where
import Pos.DB.GState.Lock as X
|
input-output-hk/pos-haskell-prototype
|
infra/src/Pos/Infra/StateLock.hs
|
mit
| 102 | 0 | 4 | 36 | 22 | 16 | 6 | 3 | 0 |
{-
Parser.hs: Parser for the Hamlet language
Copyright (c) 2009, ETH Zurich.
All rights reserved.
This file is distributed under the terms in the attached LICENSE file.
If you do not find this file, copies can be found by writing to:
ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
-}
module Parser where
import HamletAst
import Text.ParserCombinators.Parsec as Parsec
import Text.ParserCombinators.Parsec.Expr
import Text.ParserCombinators.Parsec.Pos
import Text.ParserCombinators.Parsec.Char as C
import qualified Text.ParserCombinators.Parsec.Token as P
import Text.ParserCombinators.Parsec.Language( javaStyle )
import Data.Char
import Numeric
import Data.List
import Data.Maybe
import Text.Printf
import System.Environment
import System.Exit
import System.Console.GetOpt
import System.IO
import System.FilePath.Posix
parseCaps filename = parseFromFile capsFile filename
lexer = P.makeTokenParser $! (javaStyle
{ P.reservedNames = [ "is_always_copy"
, "is_never_copy"
, "from"
, "can_retype_multiple"
]
, P.reservedOpNames = ["+"]
, P.identLetter = C.alphaNum <|> C.char '_'
})
whiteSpace = P.whiteSpace lexer
reserved = P.reserved lexer
identifier = P.identifier lexer
reservedOp = P.reservedOp lexer
integer = P.integer lexer
stringLit = P.stringLiteral lexer
comma = P.comma lexer
commaSep = P.commaSep lexer
commaSep1 = P.commaSep1 lexer
parens = P.parens lexer
braces = P.braces lexer
brackets = P.brackets lexer
semiSep = P.semiSep lexer
symbol = P.symbol lexer
missingSep name =
symbol ";" <?> " ';' missing from end of " ++ name
capsFile =
do
whiteSpace
defs <- many definesCst
caps <- capDefFold []
return $ Capabilities defs caps
where
capDefFold caps = do cap <- capabilitiesDef caps
capDefFold (cap:caps)
<|> (return $ reverse caps)
-- parse global definition
definesCst =
do
reserved "define"
name <- identifier
val <- integer
missingSep (name ++ " define")
return $! Define name (fromInteger val)
-- parse a single capability definition
capabilitiesDef caps =
do
reserved "cap"
name <- identifier
geq <- generalEqualityP name
from <- if isNothing geq then fromP caps else return Nothing
fromSelf <- if isNothing geq then fromSelfP name else return False
(fields, rangeExpr, eqFields, multi) <- braces $ capabilityDef name
missingSep ("cap " ++ name ++ " definition")
return $ Capability (CapName name) geq from fromSelf multi fields rangeExpr eqFields
-- parse optional general equality (always/never copy)
generalEqualityP name = do
(reserved "is_always_copy" >> (return $ Just True))
<|> (reserved "is_never_copy" >> (return $ Just False))
<|> (return Nothing)
-- parse optional "from <base cap name>"
fromP caps = withFromP <|> return Nothing
where withFromP = do
reserved "from"
from <- choice $ map (\s -> reserved s >> return s) capNames
return $ Just $ CapName from
capNames = map (\(CapName n) -> n) $ map name caps
-- parse optional "from_self"
fromSelfP name = (reserved "from_self" >> (return True)) <|> (return False)
-- parse the body of a capability definition
capabilityDef name = do
-- check for "can_retype_multiple"
multi <- (do reserved "can_retype_multiple"
missingSep ("can_retype_multiple in " ++ name)
return True)
<|> (return False)
-- read sequence of field, address, size, and equality definitions
annotatedFields <- many $ capFieldOrExpr name
(fields, addresses, sizes, eqExprs) <- return $ unzipDefs annotatedFields
-- lengths to check
let numAddrs = length addresses
numSizes = length sizes
-- check that there are either 0 or 1 of both address and size definitions
if numAddrs > 1
then unexpected ("multiple address definitions for cap " ++ name)
else return ()
if numSizes > 1
then unexpected ("multiple size definitions for cap " ++ name)
else return ()
if numAddrs < 1 && numSizes > 0
then unexpected ("have size definition but no address definition for cap " ++ name)
else return ()
-- merge address and size expressions if present
let rangeExpr = if null addresses
then Nothing
else Just $
if null sizes
then (head addresses, ZeroSize)
else (head addresses, head sizes)
return (fields, rangeExpr, eqExprs, multi)
where
-- un-maybe lists from capfields parsing
unzipDefs annotatedFields = (fs, as, ss, es)
where fs = catMaybes afs
as = catMaybes aas
ss = catMaybes ass
es = catMaybes ess
(afs, aas, ass, ess) = unzip4 annotatedFields
capFieldOrExpr name = (reserved "address" >> (addrField <|> addrExpr))
<|>
(((reserved "size" >> (return False)) <|>
(reserved "size_bits" >> (return True)))
>>= (\isBits -> sizeField isBits <|> sizeExpr isBits))
<|>
(reserved "eq" >> eqField)
<|>
regField
where
addrField = do
-- handle field marked as address
field <- capTypeField
return $
let expr = AddressExpr $ NameExpr $ fieldName field
in (Just field, Just expr, Nothing, Nothing)
addrExpr = do
-- handle address expression
addrExpr <- braces addressExprP
missingSep ("address definition for " ++ name)
return (Nothing, Just addrExpr, Nothing, Nothing)
sizeField isBits = do
-- handle field marked as size or size_bits
field <- capTypeField
return $
let mkSize = if isBits then SizeBitsExpr else SizeExpr
expr = mkSize $ NameExpr $ fieldName field
in (Just field, Nothing, Just expr, Nothing)
eqField = do
-- handle field marked as eq
field <- capTypeField
return (Just field, Nothing, Nothing, Just $ NameField $ fieldName field)
sizeExpr isBits = do
-- handle size expression
expr <- braces (if isBits then sizeBitsExprP else sizeExprP)
missingSep ("size definition for " ++ name)
return (Nothing, Nothing, Just expr, Nothing)
regField = do
-- handle regular field
field <- capTypeField
return (Just field, Nothing, Nothing, Nothing)
fieldName (CapField _ (NameField n)) = n
-- parse cap field (name, type, semicolon)
capTypeField = do
typ <- stringLit <|> identifier
name <- identifier
missingSep ("field " ++ name)
return $ CapField (read typ) (NameField name)
-- parse address expression
addressExprP = (reserved "mem_to_phys" >> parens exprP >>= (return . MemToPhysOp))
<|> (reserved "get_address" >> parens exprP >>= (return . GetAddrOp))
<|> (exprP >>= (return . AddressExpr))
-- parse size expression
sizeExprP = exprP >>= (return . SizeExpr)
-- parse size_bits expression
sizeBitsExprP = exprP >>= (return . SizeBitsExpr)
-- parse subexpression for the above
exprP = do
left <- identifier
(do reservedOp "+"
right <- identifier
return $ AddExpr left right
<|> (return $ NameExpr left))
|
razvan9310/barrelfish
|
tools/hamlet/Parser.hs
|
mit
| 7,866 | 0 | 15 | 2,463 | 1,919 | 984 | 935 | 161 | 6 |
module SmallestSrcLocContainingCursor (testSelect) where
import Test.Tasty
import Test.Tasty.HUnit
import Prelude hiding (span)
import Language.Astview.SmallestSrcLocContainingCursor
(smallestSrcLocContainingCursorPos)
import Language.Astview.DataTree(annotateWithPaths)
import Language.Astview.Language
import Data.Tree (Tree(Node))
testSelect :: TestTree
testSelect =
testGroup "selecting the greatest sorrounding source location"
[t1,t2,t3,t4,t5,t6]
-- |a shorter name
select :: SrcSpan -> Ast -> Maybe [Int]
select = smallestSrcLocContainingCursorPos
mkTree :: String -> SrcSpan -> [Tree AstNode] -> Tree AstNode
mkTree l s cs = annotateWithPaths $ Node (AstNode l (Just s) [] Identificator) cs
t1 :: TestTree
t1 = testCase "return first occourence" $
select (span 1 2 1 7) (Ast ast) @?= Just [0] where
ast = mkTree "a" (span 1 2 1 7) []
t2 :: TestTree
t2 = testCase "return immediate successor" $
let r = span 1 2 3 9
ast = mkTree "a" (span 1 1 16 3) [c]
c = mkTree "b" r []
in
select (span 1 3 3 6) (Ast ast)
@?=
Just [0,0]
t3 :: TestTree
t3 = testCase "return root if successor does not match" $
let r = span 1 1 19 7
ast = mkTree "a" r [c]
c = mkTree "b" (span 10 2 17 9 ) []
in
select (span 1 2 3 9) (Ast ast)
@?=
Just [0]
t4 :: TestTree
t4 = testCase "return leaf in three containing spans" $
let r = span 2 1 4 2
ast = mkTree "a" (span 1 1 16 3) [c1]
c1 = mkTree "b" (span 1 1 5 9) [c2]
c2 = mkTree "b" r []
in
select (span 2 1 3 1) (Ast ast)
@?=
Just [0,0,0]
t5 :: TestTree
t5 = testCase "triangle, select the correct child" $
let r = span 2 1 4 5
ast = mkTree "a" (span 1 1 16 3) [c1,c2]
c1 = mkTree "b" (span 10 1 15 9) []
c2 = mkTree "b" r []
in
select (span 2 1 3 1) (Ast ast)
@?=
Just [0,1]
t6 :: TestTree
t6 = testCase "triangle, select multiple locations" $
let r = span 2 1 4 2
ast = mkTree "a" (span 1 1 16 3) [c1,c2]
c1 = mkTree "b" (span 10 1 15 9) []
c2 = mkTree "b" r [c3]
c3 = mkTree "b" r []
in
select (span 2 1 3 1) (Ast ast)
@?=
Just [0,1]
|
jokusi/Astview
|
test/SmallestSrcLocContainingCursor.hs
|
mit
| 2,354 | 0 | 12 | 770 | 944 | 489 | 455 | 65 | 1 |
{- |
Module : ./HasCASL/MinType.hs
Description : choose a minimal type for overloaded terms
Copyright : (c) Christian Maeder and Uni Bremen 2003
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
choose a minimal type
-}
module HasCASL.MinType
( q2p
, typeNub
, haveCommonSupertype
, getCommonSupertype
) where
import HasCASL.As
import HasCASL.FoldType
import HasCASL.Le
import HasCASL.AsUtils
import HasCASL.TypeAna
import HasCASL.Unify
import HasCASL.Constrain
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Common.Lib.Rel as Rel
import Common.DocUtils
import Common.Id
import Common.Result
import Common.Lib.State
import Common.Utils
import Data.List as List
import Data.Maybe
q2p :: (a, b, c, d) -> (c, d)
q2p (_, _, c, d) = (c, d)
typeNub :: Env -> (a -> (Type, Term)) -> [a] -> [a]
typeNub e f = let
comp (ty1, t1) (ty2, t2) = eqTerm e t1 t2 &&
lesserType e ty1 ty2
lt a b = comp (f a) (f b)
in keepMins lt
eqTerm :: Env -> Term -> Term -> Bool
eqTerm e t1 t2 = case (t1, t2) of
(TypedTerm t _ _ _, _) -> eqTerm e t t2
(_, TypedTerm t _ _ _) -> eqTerm e t1 t
(QualVar (VarDecl v1 _s1 _ _), QualVar (VarDecl v2 _s2 _ _)) ->
v1 == v2
(QualOp _ i1 s1 _ _ _, QualOp _ i2 s2 _ _ _) -> i1 == i2
&& haveCommonSupertype e s1 s2
(ApplTerm tf1 ta1 _, ApplTerm tf2 ta2 _) ->
eqTerm e tf1 tf2 && eqTerm e ta1 ta2
(TupleTerm ts1 _, TupleTerm ts2 _) ->
length ts1 == length ts2 && and (zipWith (eqTerm e) ts1 ts2)
(QuantifiedTerm q1 vs1 f1 _, QuantifiedTerm q2 vs2 f2 _) ->
(q1, vs1) == (q2, vs2) && eqTerm e f1 f2
(LambdaTerm ps1 p1 f1 _, LambdaTerm ps2 p2 f2 _) ->
and (zipWith (eqTerm e) ps1 ps2) && p1 == p2 && eqTerm e f1 f2
&& length ps1 == length ps2
(CaseTerm f1 e1 _, CaseTerm f2 e2 _) ->
eqTerm e f1 f2 && length e1 == length e2
&& and (zipWith (eqProgEq e) e1 e2)
(LetTerm _ e1 f1 _, LetTerm _ e2 f2 _) ->
eqTerm e f1 f2 && length e1 == length e2
&& and (zipWith (eqProgEq e) e1 e2)
_ -> False
eqProgEq :: Env -> ProgEq -> ProgEq -> Bool
eqProgEq e (ProgEq p1 t1 _) (ProgEq p2 t2 _) = eqTerm e p1 p2 && eqTerm e t1 t2
addToEnv :: (Type, VarKind) -> Env -> Env
addToEnv (ty, vk) e = case ty of
TypeName i rk c | c > 0 ->
execState (addLocalTypeVar False (TypeVarDefn NonVar vk rk c) i) e
_ -> e
haveCommonSupertype :: Env -> TypeScheme -> TypeScheme -> Bool
haveCommonSupertype e s = isJust . getCommonSupertype e s
getCommonSupertype :: Env -> TypeScheme -> TypeScheme -> Maybe TypeTriple
getCommonSupertype e s1 s2 =
evalState (toEnvState $ haveCommonSupertypeE e s1 s2) e
type TypeTriple = (Type, [Type], Type, [Type], [TypeArg], Type)
haveCommonSupertypeE :: Env -> TypeScheme -> TypeScheme
-> State Int (Maybe TypeTriple)
haveCommonSupertypeE eIn s1 s2 = do
(t1, l1) <- freshInst s1
(t2, l2) <- freshInst s2
cst <- mkSingleSubst (genName "commonSupertype", rStar)
let cs = Set.fromList [Subtyping t1 cst, Subtyping t2 cst]
e = foldr addToEnv eIn $ (cst, VarKind universe) : l1 ++ l2
Result _ mr <- shapeRelAndSimplify False e cs (Just cst)
return $ case mr of
Nothing -> Nothing
Just (sbst, rcs) -> let (qs, subC) = partitionC rcs
in case reduceCommonSubtypes
(Rel.transClosure $ fromTypeMap $ typeMap e)
(toListC subC) of
Just msb | Set.null qs -> let
doSubst = subst $ compSubst sbst msb
[ty, ty1, ty2] = map doSubst [cst, t1, t2]
fvs = foldr1 List.union $ map freeTVars [ty1, ty2, ty]
svs = sortBy comp fvs
comp a b = compare (fst a) $ fst b
tvs = localTypeVars e
newArgs = map ( \ (_, (i, _)) -> case Map.lookup i tvs of
Nothing -> error $ "generalizeS " ++ show (i, ty)
++ "\n" ++ showDoc (s1, s2) ""
Just (TypeVarDefn v vk rk c) ->
TypeArg i v vk rk c Other nullRange) svs
genArgs = generalize newArgs
[gty, gty1, gty2] = map genArgs [ty, ty1, ty2]
gl1 = map (genArgs . doSubst . fst) l1
gl2 = map (genArgs . doSubst . fst) l2
in Just (gty1, gl1, gty2, gl2, genTypeArgs newArgs, gty)
_ -> Nothing
reduceCommonSubtypes :: Rel.Rel Type -> [(Type, Type)] -> Maybe Subst
reduceCommonSubtypes e l = let
mygroup = groupBy ( \ (a, b) (c, d) -> case (a, b, d) of
(TypeName _ _ n, TypeName _ _ 0, TypeName _ _ 0)
-> n > 0 && a == c
_ -> False)
mypart = partition ( \ s -> case s of
[] -> error "reduceCommonSubtypes1"
[_] -> False
_ -> True)
(csubts, rest) = mypart $ mygroup l
swap = map $ \ (a, b) -> (b, a)
(csuperts, rest2) = mypart $ mygroup $ sort $ swap (concat rest)
mkPair s = case s of
(a, _) : _ -> (a, map snd s)
_ -> error "reduceCommonSubtypes2"
subM = mapM (commonSubtype e True . mkPair) csubts
superM = mapM (commonSubtype e False . mkPair) csuperts
in case (concat rest2, subM, superM) of
([], Just l1, Just l2) -> Just $ Map.fromList $ l1 ++ l2
_ -> Nothing
commonSubtype :: Rel.Rel Type -> Bool -> (Type, [Type]) -> Maybe (Int, Type)
commonSubtype trel b (ty, l) =
let tySet = foldl1 Set.intersection
$ map (if b then Rel.predecessors trel else Rel.succs trel) l
in case ty of
TypeName _ _ n | not (Set.null tySet) && n > 0
-> Just (n, Set.findMin tySet)
_ -> Nothing
|
spechub/Hets
|
HasCASL/MinType.hs
|
gpl-2.0
| 5,871 | 0 | 31 | 1,830 | 2,374 | 1,229 | 1,145 | 129 | 11 |
{- |
Module : $Header$
Description : devGraph rule that calls provers for specific logics
Copyright : (c) J. Gerken, T. Mossakowski, K. Luettich, Uni Bremen 2002-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable(Logic)
devGraph rule that calls provers for specific logics
Proof rule "basic inference" in the development graphs calculus.
Follows Sect. IV:4.4 of the CASL Reference Manual.
References:
T. Mossakowski, S. Autexier and D. Hutter:
Extending Development Graphs With Hiding.
H. Hussmann (ed.): Fundamental Approaches to Software Engineering 2001,
Lecture Notes in Computer Science 2029, p. 269-283,
Springer-Verlag 2001.
-}
module Proofs.InferBasic
( basicInferenceNode
) where
import Static.GTheory
import Static.DevGraph
import Static.ComputeTheory
import Proofs.EdgeUtils
import Proofs.AbstractState
import Proofs.FreeDefLinks
import Common.LibName
import Common.Result
import Common.ResultT
import Common.AS_Annotation
import Logic.Logic
import Logic.Prover
import Logic.Grothendieck
import Logic.Comorphism
import Logic.Coerce
import Comorphisms.KnownProvers
import GUI.Utils
import GUI.ProverGUI
import Interfaces.DataTypes
import Interfaces.Utils
import Data.IORef
import Data.Graph.Inductive.Graph
import Data.Maybe
import Control.Monad.Trans
selectProver :: [(G_prover, AnyComorphism)]
-> ResultT IO (G_prover, AnyComorphism)
selectProver ps = case ps of
[] -> fail "No prover available"
[p] -> return p
_ -> do
sel <- lift $ listBox "Choose a translation to a prover-supported logic"
$ map (\ (aGN, cm) -> shows cm $ " (" ++ getProverName aGN ++ ")") ps
i <- case sel of
Just j -> return j
_ -> fail "Proofs.Proofs: selection"
return $ ps !! i
proveTheory :: Logic lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism symbol raw_symbol proof_tree
=> lid -> Prover sign sentence morphism sublogics proof_tree
-> String -> Theory sign sentence proof_tree
-> [FreeDefMorphism sentence morphism]
-> IO ( [ProofStatus proof_tree]
, [(Named sentence, ProofStatus proof_tree)])
proveTheory _ =
fromMaybe (\ _ _ -> fail "proveGUI not implemented") . proveGUI
{- | applies basic inference to a given node. The result is a theory which is
either a model after a consistency check or a new theory for the node
label -}
basicInferenceNode :: LogicGraph -> LibName -> DGraph -> LNode DGNodeLab
-> LibEnv -> IORef IntState
-> IO (Result G_theory)
basicInferenceNode lg ln dGraph (node, lbl) libEnv intSt =
runResultT $ do
-- compute the theory (that may contain proved theorems) and its name
thForProof <- liftR $ getGlobalTheory lbl
let thName = libToFileName ln ++ "_" ++ getDGNodeName lbl
freedefs = getCFreeDefMorphs libEnv ln dGraph node
ps <- lift $ getUsableProvers ProveGUI (sublogicOfTh thForProof) lg
kpMap <- liftR knownProversGUI
{- let kpMap = foldl (\m (G_prover _ p,c) ->
case Map.lookup (proverName p) m of
Just cs -> Map.insert (proverName p) (c:cs) m
Nothing -> Map.insert (proverName p) [c] m) Map.empty ps -}
ResultT $ proverGUI ProofActions
{ proveF = proveKnownPMap lg intSt freedefs
, fineGrainedSelectionF = proveFineGrainedSelect lg intSt freedefs
, recalculateSublogicF = return . recalculateSublogicAndSelectedTheory
} thName (hidingLabelWarning lbl) thForProof kpMap ps
proveKnownPMap :: LogicGraph
-> IORef IntState
-> [GFreeDefMorphism]
-> ProofState -> IO (Result ProofState)
proveKnownPMap lg intSt freedefs st =
maybe (proveFineGrainedSelect lg intSt freedefs st)
(callProver st intSt False freedefs) $
lookupKnownProver st ProveGUI
callProver :: ProofState
-> IORef IntState
-> Bool -- indicates if a translation was chosen
-> [GFreeDefMorphism]
-> (G_prover, AnyComorphism) -> IO (Result ProofState)
callProver st intSt trans_chosen freedefs p_cm@(_, acm) =
runResultT $ do
(_, exit) <- lift $ pulseBar "prepare for proving" "please wait..."
G_theory_with_prover lid th p <- liftR $ prepareForProving st p_cm
freedefs1 <- mapM (\ (GFreeDefMorphism fdlid fd) ->
coerceFreeDefMorphism fdlid lid "" fd) freedefs
lift exit
(ps, _) <- lift $ proveTheory lid p (theoryName st) th freedefs1
let st' = markProved acm lid ps st
lift $ addCommandHistoryToState intSt st'
(if trans_chosen then Just p_cm else Nothing) ps "" (False, 0)
return st'
proveFineGrainedSelect :: LogicGraph
-> IORef IntState
-> [GFreeDefMorphism]
-> ProofState -> IO (Result ProofState)
proveFineGrainedSelect lg intSt freedefs st =
runResultT $ do
let sl = sublogicOfTheory st
cmsToProvers <- lift $ getUsableProvers ProveGUI sl lg
pr <- selectProver cmsToProvers
ResultT $ callProver st { comorphismsToProvers = cmsToProvers }
intSt True freedefs pr
|
mariefarrell/Hets
|
Proofs/InferBasic.hs
|
gpl-2.0
| 5,261 | 0 | 18 | 1,254 | 1,133 | 574 | 559 | 99 | 4 |
-- Print module
-- By G.W. Schwartz
--
{- | Collection of functions for the printing of data (converting data
structures into strings for use with writing to output files).
-}
{-# LANGUAGE BangPatterns #-}
module Math.Diversity.Print ( printDiversity
, printRarefaction
, printRarefactionCurve ) where
-- Built in
import Data.List
import Data.Maybe
import qualified Data.Map.Strict as Map
-- Local
import Math.Diversity.Types
import Math.Diversity.Diversity
-- Return the results of the diversity analysis in string form for saving
-- to a file
printDiversity :: Label -> Order -> Window -> PositionMap -> String
printDiversity label order window positionMap = header ++ body
where
header = "label,order,window,position,weight,diversity\n"
body = unlines
. map mapLine
. Map.toAscList
$ positionMap
mapLine (p, xs) = intercalate "," . line p $ xs
line p xs = [ label
, show order
, show window
, show p
, show . Map.foldl' (+) 0 $ xs
, show . diversityOfMap order $ xs
]
-- Return the results of the rarefaction analysis in string form for saving
-- to a file
printRarefaction :: Bool
-> Double
-> Label
-> Window
-> PositionMap
-> IO String
printRarefaction
bySample g label window positionMap = do
body <- fmap unlines . mapM mapLine . Map.toAscList $ positionMap
return (header ++ body)
where
header = "label,window,position,weight,\
\additional_sampling,g_proportion,richness,\
\S_est,S_est_var\n"
mapLine (p, xs) = fmap (intercalate ",") . line p $ xs
line p xs = do
-- The minimum number of samples needed before any additional
-- sampling returns less than the threshold (min) number of species
return [ label
, show window
, show p
, show . Map.foldl' (+) 0 $ xs
, show . additionalSampling bySample $ xs
, show g
, show . sobs $ xs
, show . sest bySample $ xs
, show . var bySample $ xs
]
sest True xs = sobs xs + chao2 xs
sest False xs = sobs xs + chao1 xs
var True = chao2Var
var False = chao1Var
sobs = fromIntegral . richness
additionalSampling True = sampleG g
additionalSampling False = individualG g
-- Return the results of the rarefaction analysis of the entire curve in
-- string form for saving to a file
printRarefactionCurve :: Bool
-> Bool
-> Bool
-> Int
-> Int
-> Int
-> Int
-> Label
-> Window
-> PositionMap
-> IO String
printRarefactionCurve
asDF bySample fastBin runs start interval end label window positionMap = do
body <- fmap unlines . mapM mapLine . Map.toAscList $ positionMap
return (header asDF ++ body)
where
header False = "label,window,position,weight,percent_above,\
\expected_richness,mad\n"
header True = "label,window,position,weight,percent_above,subsample,\
\expected_richness,mad\n"
mapLine (!p, !xs) = line asDF p xs
line False p xs = do
curve <- getRarefactionCurve bySample xs
return . intercalate "," $ [ label
, show window
, show p
, show . Map.foldl' (+) 0 $ xs
, show
. rarefactionViable
. map (maybe (-1) snd . snd)
$ curve
, intercalate "/"
. map (maybe "NA" (show . fst) . snd)
$ curve
, intercalate "/"
. map (maybe "NA" (show . snd) . snd)
$ curve
]
line True p xs = do
curve <- getRarefactionCurve bySample xs
return . intercalate "\n"
. map ( \(!x, !y)
-> intercalate "," [ label
, show window
, show p
, show . Map.foldl' (+) 0 $ xs
, show
. rarefactionViable
. map (maybe (-1) snd . snd)
$ curve
, show x
, maybe "NA" (show . fst) y
, maybe "NA" (show . snd) y
] )
$ curve
getRarefactionCurve True = rarefactionSampleCurve fastBin start interval end
getRarefactionCurve False = rarefactionCurve
fastBin
runs
(fromIntegral start)
(fromIntegral interval)
(fromIntegral end)
|
DrexelSystemsImmunologyLab/diversity
|
src/src-lib/Math/Diversity/Print.hs
|
gpl-3.0
| 5,669 | 0 | 23 | 2,738 | 1,115 | 570 | 545 | 109 | 4 |
module Command.STUN where
import Network.Socket (Socket, SockAddr(..), PortNumber, hostAddressToTuple)
import Network.Socket.ByteString (sendTo, recv)
import Control.Applicative ((<|>))
import Network.Stun
import Network.Stun.Internal
import Data.Serialize
import Control.Concurrent.Timeout (timeout)
import Network.Vanguard.Core
-- List of stun servers
stunserver :: (String, Maybe PortNumber)
stunserver = ("stun.ekiga.net", Just 3478)
-- Uses a given socket to stun with. More useful than the
-- Network.Stun library functions.
stunOn :: Socket -> SockAddr -> IO (Maybe (Addr, PortNumber))
stunOn sock server = do
brq <- bindRequest
let msg = encode brq
resp <- doSTUN msg sock server timeouts
case resp of
Just m -> do
let reply = decode m
ext = fmap getExternal reply
case ext of
Right address@(Just _) -> return $ address >>= decompose
_ -> return Nothing
_ -> return Nothing
where
doSTUN msg sock server [] = return Nothing
doSTUN msg sock server (to:tos) = do
sendTo sock msg server
rep <- timeout to $ recv sock 4096
case rep of
m@(Just _ ) -> return m
Nothing -> doSTUN msg sock server tos
timeouts = [500000,1000000,2000000]
-- getExternal takes a STUN response and extracts the
-- external socket address of the request.
getExternal :: Message -> Maybe SockAddr
getExternal msg = xma <|> ma -- Two possible encodings
where
ma = case findAttribute (messageAttributes msg) of
Right [ad] -> Just (unMA ad)
_ -> Nothing
xma = case findAttribute (messageAttributes msg) of
Right [xad] -> Just $ fromXorMappedAddress (transactionID msg) xad
_ -> Nothing
|
rlupton20/vanguard-dataplane
|
app/Command/STUN.hs
|
gpl-3.0
| 1,712 | 0 | 18 | 392 | 531 | 276 | 255 | 40 | 5 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, TupleSections,
GeneralizedNewtypeDeriving, DeriveTraversable #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| JSON utility functions. -}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.JSON
( fromJResult
, fromJResultE
, readJSONWithDesc
, readEitherString
, JSRecord
, loadJSArray
, fromObj
, maybeFromObj
, fromObjWithDefault
, fromKeyValue
, fromJVal
, fromJValE
, jsonHead
, getMaybeJsonHead
, getMaybeJsonElem
, asJSObject
, asObjectList
, tryFromObj
, arrayMaybeFromJVal
, tryArrayMaybeFromObj
, toArray
, optionalJSField
, optFieldsToObj
, containerFromList
, lookupContainer
, alterContainerL
, readContainer
, mkUsedKeys
, allUsedKeys
, DictObject(..)
, showJSONtoDict
, readJSONfromDict
, ArrayObject(..)
, HasStringRepr(..)
, GenericContainer(..)
, emptyContainer
, Container
, MaybeForJSON(..)
, TimeAsDoubleJSON(..)
, Tuple5(..)
, nestedAccessByKey
, nestedAccessByKeyDotted
, branchOnField
, addField
)
where
import Control.Applicative
import Control.DeepSeq
import Control.Monad.Error.Class
import Control.Monad.Writer
import qualified Data.Foldable as F
import qualified Data.Text as T
import qualified Data.Traversable as F
import Data.Maybe (fromMaybe, catMaybes)
import qualified Data.Map as Map
import qualified Data.Set as Set
import System.Time (ClockTime(..))
import Text.Printf (printf)
import qualified Text.JSON as J
import qualified Text.JSON.Types as JT
import Text.JSON.Pretty (pp_value)
-- Note: this module should not import any Ganeti-specific modules
-- beside BasicTypes, since it's used in THH which is used itself to
-- build many other modules.
import Ganeti.BasicTypes
-- Remove after we require >= 1.8.58
-- See: https://github.com/ndmitchell/hlint/issues/24
{-# ANN module "HLint: ignore Unused LANGUAGE pragma" #-}
-- * JSON-related functions
instance NFData J.JSValue where
rnf J.JSNull = ()
rnf (J.JSBool b) = rnf b
rnf (J.JSRational b r) = rnf b `seq` rnf r
rnf (J.JSString s) = rnf $ J.fromJSString s
rnf (J.JSArray a) = rnf a
rnf (J.JSObject o) = rnf o
instance (NFData a) => NFData (J.JSObject a) where
rnf = rnf . J.fromJSObject
-- | A type alias for a field of a JSRecord.
type JSField = (String, J.JSValue)
-- | A type alias for the list-based representation of J.JSObject.
type JSRecord = [JSField]
-- | Annotate @readJSON@ error messages with descriptions of what
-- is being parsed into what.
readJSONWithDesc :: (J.JSON a)
=> String -- ^ description of @a@
-> Bool -- ^ include input in
-- error messages
-> J.JSValue -- ^ input value
-> J.Result a
readJSONWithDesc name incInput input =
case J.readJSON input of
J.Ok r -> J.Ok r
J.Error e -> J.Error $ if incInput then msg ++ " from " ++ show input
else msg
where msg = "Can't parse value for '" ++ name ++ "': " ++ e
-- | Converts a JSON Result into a monadic value.
fromJResult :: Monad m => String -> J.Result a -> m a
fromJResult s (J.Error x) = fail (s ++ ": " ++ x)
fromJResult _ (J.Ok x) = return x
-- | Converts a JSON Result into a MonadError value.
fromJResultE :: (Error e, MonadError e m) => String -> J.Result a -> m a
fromJResultE s (J.Error x) = throwError . strMsg $ s ++ ": " ++ x
fromJResultE _ (J.Ok x) = return x
-- | Tries to read a string from a JSON value.
--
-- In case the value was not a string, we fail the read (in the
-- context of the current monad.
readEitherString :: (Monad m) => J.JSValue -> m String
readEitherString v =
case v of
J.JSString s -> return $ J.fromJSString s
_ -> fail "Wrong JSON type"
-- | Converts a JSON message into an array of JSON objects.
loadJSArray :: (Monad m)
=> String -- ^ Operation description (for error reporting)
-> String -- ^ Input message
-> m [J.JSObject J.JSValue]
loadJSArray s = fromJResult s . J.decodeStrict
-- | Helper function for missing-key errors
buildNoKeyError :: JSRecord -> String -> String
buildNoKeyError o k =
printf "key '%s' not found, object contains only %s" k (show (map fst o))
-- | Reads the value of a key in a JSON object.
fromObj :: (J.JSON a, Monad m) => JSRecord -> String -> m a
fromObj o k =
case lookup k o of
Nothing -> fail $ buildNoKeyError o k
Just val -> fromKeyValue k val
-- | Reads the value of an optional key in a JSON object. Missing
-- keys, or keys that have a \'null\' value, will be returned as
-- 'Nothing', otherwise we attempt deserialisation and return a 'Just'
-- value.
maybeFromObj :: (J.JSON a, Monad m) =>
JSRecord -> String -> m (Maybe a)
maybeFromObj o k =
case lookup k o of
Nothing -> return Nothing
-- a optional key with value JSNull is the same as missing, since
-- we can't convert it meaningfully anyway to a Haskell type, and
-- the Python code can emit 'null' for optional values (depending
-- on usage), and finally our encoding rules treat 'null' values
-- as 'missing'
Just J.JSNull -> return Nothing
Just val -> liftM Just (fromKeyValue k val)
-- | Reads the value of a key in a JSON object with a default if
-- missing. Note that both missing keys and keys with value \'null\'
-- will cause the default value to be returned.
fromObjWithDefault :: (J.JSON a, Monad m) =>
JSRecord -> String -> a -> m a
fromObjWithDefault o k d = liftM (fromMaybe d) $ maybeFromObj o k
arrayMaybeFromJVal :: (J.JSON a, Monad m) => J.JSValue -> m [Maybe a]
arrayMaybeFromJVal (J.JSArray xs) =
mapM parse xs
where
parse J.JSNull = return Nothing
parse x = liftM Just $ fromJVal x
arrayMaybeFromJVal v =
fail $ "Expecting array, got '" ++ show (pp_value v) ++ "'"
-- | Reads an array of optional items
arrayMaybeFromObj :: (J.JSON a, Monad m) =>
JSRecord -> String -> m [Maybe a]
arrayMaybeFromObj o k =
case lookup k o of
Just a -> arrayMaybeFromJVal a
_ -> fail $ buildNoKeyError o k
-- | Wrapper for arrayMaybeFromObj with better diagnostic
tryArrayMaybeFromObj :: (J.JSON a)
=> String -- ^ Textual "owner" in error messages
-> JSRecord -- ^ The object array
-> String -- ^ The desired key from the object
-> Result [Maybe a]
tryArrayMaybeFromObj t o = annotateResult t . arrayMaybeFromObj o
-- | Reads a JValue, that originated from an object key.
fromKeyValue :: (J.JSON a, Monad m)
=> String -- ^ The key name
-> J.JSValue -- ^ The value to read
-> m a
fromKeyValue k val =
fromJResult (printf "key '%s'" k) (J.readJSON val)
-- | Small wrapper over readJSON.
fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a
fromJVal v =
case J.readJSON v of
J.Error s -> fail ("Cannot convert value '" ++ show (pp_value v) ++
"', error: " ++ s)
J.Ok x -> return x
-- | Small wrapper over 'readJSON' for 'MonadError'.
fromJValE :: (Error e, MonadError e m, J.JSON a) => J.JSValue -> m a
fromJValE v =
case J.readJSON v of
J.Error s -> throwError . strMsg $
"Cannot convert value '" ++ show (pp_value v) ++
"', error: " ++ s
J.Ok x -> return x
-- | Helper function that returns Null or first element of the list.
jsonHead :: (J.JSON b) => [a] -> (a -> b) -> J.JSValue
jsonHead [] _ = J.JSNull
jsonHead (x:_) f = J.showJSON $ f x
-- | Helper for extracting Maybe values from a possibly empty list.
getMaybeJsonHead :: (J.JSON b) => [a] -> (a -> Maybe b) -> J.JSValue
getMaybeJsonHead [] _ = J.JSNull
getMaybeJsonHead (x:_) f = maybe J.JSNull J.showJSON (f x)
-- | Helper for extracting Maybe values from a list that might be too short.
getMaybeJsonElem :: (J.JSON b) => [a] -> Int -> (a -> Maybe b) -> J.JSValue
getMaybeJsonElem [] _ _ = J.JSNull
getMaybeJsonElem xs 0 f = getMaybeJsonHead xs f
getMaybeJsonElem (_:xs) n f
| n < 0 = J.JSNull
| otherwise = getMaybeJsonElem xs (n - 1) f
-- | Converts a JSON value into a JSON object.
asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue)
asJSObject (J.JSObject a) = return a
asJSObject _ = fail "not an object"
-- | Coneverts a list of JSON values into a list of JSON objects.
asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue]
asObjectList = mapM asJSObject
-- | Try to extract a key from an object with better error reporting
-- than fromObj.
tryFromObj :: (J.JSON a) =>
String -- ^ Textual "owner" in error messages
-> JSRecord -- ^ The object array
-> String -- ^ The desired key from the object
-> Result a
tryFromObj t o = annotateResult t . fromObj o
-- | Ensure a given JSValue is actually a JSArray.
toArray :: (Monad m) => J.JSValue -> m [J.JSValue]
toArray (J.JSArray arr) = return arr
toArray o =
fail $ "Invalid input, expected array but got " ++ show (pp_value o)
-- | Creates a Maybe JSField. If the value string is Nothing, the JSField
-- will be Nothing as well.
optionalJSField :: (J.JSON a) => String -> Maybe a -> Maybe JSField
optionalJSField name (Just value) = Just (name, J.showJSON value)
optionalJSField _ Nothing = Nothing
-- | Creates an object with all the non-Nothing fields of the given list.
optFieldsToObj :: [Maybe JSField] -> J.JSValue
optFieldsToObj = J.makeObj . catMaybes
-- * Container type (special type for JSON serialisation)
-- | Class of types that can be converted from Strings. This is
-- similar to the 'Read' class, but it's using a different
-- serialisation format, so we have to define a separate class. Mostly
-- useful for custom key types in JSON dictionaries, which have to be
-- backed by strings.
class HasStringRepr a where
fromStringRepr :: (Monad m) => String -> m a
toStringRepr :: a -> String
-- | Trivial instance 'HasStringRepr' for 'String'.
instance HasStringRepr String where
fromStringRepr = return
toStringRepr = id
-- | The container type, a wrapper over Data.Map
newtype GenericContainer a b =
GenericContainer { fromContainer :: Map.Map a b }
deriving (Show, Eq, Ord, Functor, F.Foldable, F.Traversable)
instance (NFData a, NFData b) => NFData (GenericContainer a b) where
rnf = rnf . Map.toList . fromContainer
-- | The empty container.
emptyContainer :: GenericContainer a b
emptyContainer = GenericContainer Map.empty
-- | Type alias for string keys.
type Container = GenericContainer String
-- | Creates a GenericContainer from a list of key-value pairs.
containerFromList :: Ord a => [(a,b)] -> GenericContainer a b
containerFromList = GenericContainer . Map.fromList
-- | Looks up a value in a container with a default value.
-- If a key has no value, a given monadic default is returned.
-- This allows simple error handling, as the default can be
-- 'mzero', 'failError' etc.
lookupContainer :: (Monad m, Ord a)
=> m b -> a -> GenericContainer a b -> m b
lookupContainer dflt k = maybe dflt return . Map.lookup k . fromContainer
-- | Updates a value inside a container.
-- The signature of the function is crafted so that it can be directly
-- used as a lens.
alterContainerL :: (Functor f, Ord a)
=> a
-> (Maybe b -> f (Maybe b))
-> GenericContainer a b
-> f (GenericContainer a b)
alterContainerL key f (GenericContainer m) =
fmap (\v -> GenericContainer $ Map.alter (const v) key m)
(f $ Map.lookup key m)
-- | Container loader.
readContainer :: (Monad m, HasStringRepr a, Ord a, J.JSON b) =>
J.JSObject J.JSValue -> m (GenericContainer a b)
readContainer obj = do
let kjvlist = J.fromJSObject obj
kalist <- mapM (\(k, v) -> do
k' <- fromStringRepr k
v' <- fromKeyValue k v
return (k', v')) kjvlist
return $ GenericContainer (Map.fromList kalist)
{-# ANN showContainer "HLint: ignore Use ***" #-}
-- | Container dumper.
showContainer :: (HasStringRepr a, J.JSON b) =>
GenericContainer a b -> J.JSValue
showContainer =
J.makeObj . map (\(k, v) -> (toStringRepr k, J.showJSON v)) .
Map.toList . fromContainer
instance (HasStringRepr a, Ord a, J.JSON b) =>
J.JSON (GenericContainer a b) where
showJSON = showContainer
readJSON (J.JSObject o) = readContainer o
readJSON v = fail $ "Failed to load container, expected object but got "
++ show (pp_value v)
-- * Types that (de)serialize in a special form of JSON
newtype UsedKeys = UsedKeys (Maybe (Set.Set String))
instance Monoid UsedKeys where
mempty = UsedKeys (Just Set.empty)
mappend (UsedKeys xs) (UsedKeys ys) = UsedKeys $ liftA2 Set.union xs ys
mkUsedKeys :: Set.Set String -> UsedKeys
mkUsedKeys = UsedKeys . Just
allUsedKeys :: UsedKeys
allUsedKeys = UsedKeys Nothing
-- | Class of objects that can be converted from and to 'JSObject'
-- lists-format.
class DictObject a where
toDict :: a -> [(String, J.JSValue)]
fromDictWKeys :: [(String, J.JSValue)] -> WriterT UsedKeys J.Result a
fromDict :: [(String, J.JSValue)] -> J.Result a
fromDict = liftM fst . runWriterT . fromDictWKeys
-- | A default implementation of 'showJSON' using 'toDict'.
showJSONtoDict :: (DictObject a) => a -> J.JSValue
showJSONtoDict = J.makeObj . toDict
-- | A default implementation of 'readJSON' using 'fromDict'.
-- Checks that the input value is a JSON object and
-- converts it using 'fromDict'.
-- Also checks the input contains only the used keys returned by 'fromDict'.
readJSONfromDict :: (DictObject a)
=> J.JSValue -> J.Result a
readJSONfromDict jsv = do
dict <- liftM J.fromJSObject $ J.readJSON jsv
(r, UsedKeys keys) <- runWriterT $ fromDictWKeys dict
-- check that no superfluous dictionary keys are present
case keys of
Just allowedSet | not (Set.null superfluous) ->
fail $ "Superfluous dictionary keys: "
++ show (Set.toAscList superfluous) ++ ", but only "
++ show (Set.toAscList allowedSet) ++ " allowed."
where
superfluous = Set.fromList (map fst dict) Set.\\ allowedSet
_ -> return ()
return r
-- | Class of objects that can be converted from and to @[JSValue]@ with
-- a fixed length and order.
class ArrayObject a where
toJSArray :: a -> [J.JSValue]
fromJSArray :: [J.JSValue] -> J.Result a
-- * General purpose data types for working with JSON
-- | A Maybe newtype that allows for serialization more appropriate to the
-- semantics of Maybe and JSON in our calls. Does not produce needless
-- and confusing dictionaries.
--
-- In particular, `J.JSNull` corresponds to `Nothing`.
-- This also means that this `Maybe a` newtype should not be used with `a`
-- values that themselves can serialize to `null`.
newtype MaybeForJSON a = MaybeForJSON { unMaybeForJSON :: Maybe a }
deriving (Show, Eq, Ord)
instance (J.JSON a) => J.JSON (MaybeForJSON a) where
readJSON J.JSNull = return $ MaybeForJSON Nothing
readJSON x = (MaybeForJSON . Just) `liftM` J.readJSON x
showJSON (MaybeForJSON (Just x)) = J.showJSON x
showJSON (MaybeForJSON Nothing) = J.JSNull
newtype TimeAsDoubleJSON
= TimeAsDoubleJSON { unTimeAsDoubleJSON :: ClockTime }
deriving (Show, Eq, Ord)
instance J.JSON TimeAsDoubleJSON where
readJSON v = do
t <- J.readJSON v :: J.Result Double
return . TimeAsDoubleJSON . uncurry TOD
$ divMod (round $ t * pico) (pico :: Integer)
where
pico :: (Num a) => a
pico = 10^(12 :: Int)
showJSON (TimeAsDoubleJSON (TOD ss ps)) = J.showJSON
(fromIntegral ss + fromIntegral ps / 10^(12 :: Int) :: Double)
-- Text.JSON from the JSON package only has instances for tuples up to size 4.
-- We use these newtypes so that we don't get a breakage once the 'json'
-- package adds instances for larger tuples (or have to resort to CPP).
newtype Tuple5 a b c d e = Tuple5 { unTuple5 :: (a, b, c, d, e) }
instance (J.JSON a, J.JSON b, J.JSON c, J.JSON d, J.JSON e)
=> J.JSON (Tuple5 a b c d e) where
readJSON (J.JSArray [a,b,c,d,e]) =
Tuple5 <$> ((,,,,) <$> J.readJSON a
<*> J.readJSON b
<*> J.readJSON c
<*> J.readJSON d
<*> J.readJSON e)
readJSON _ = fail "Unable to read Tuple5"
showJSON (Tuple5 (a, b, c, d, e)) =
J.JSArray
[ J.showJSON a
, J.showJSON b
, J.showJSON c
, J.showJSON d
, J.showJSON e
]
-- | Look up a value in a JSON object. Accessing @["a", "b", "c"]@ on an
-- object is equivalent as accessing @myobject.a.b.c@ on a JavaScript object.
--
-- An error is returned if the object doesn't have such an accessor or if
-- any value during the nested access is not an object at all.
nestedAccessByKey :: [String] -> J.JSValue -> J.Result J.JSValue
nestedAccessByKey keys json = case keys of
[] -> return json
k:ks -> case json of
J.JSObject obj -> J.valFromObj k obj >>= nestedAccessByKey ks
_ -> J.Error $ "Cannot access non-object with key '" ++ k ++ "'"
-- | Same as `nestedAccessByKey`, but accessing with a dotted string instead
-- (like @nestedAccessByKeyDotted "a.b.c"@).
nestedAccessByKeyDotted :: String -> J.JSValue -> J.Result J.JSValue
nestedAccessByKeyDotted s =
nestedAccessByKey (map T.unpack . T.splitOn (T.pack ".") . T.pack $ s)
-- | Branch decoding on a field in a JSON object.
branchOnField :: String -- ^ fieldname to branch on
-> (J.JSValue -> J.Result a)
-- ^ decoding function if field is present and @true@; field
-- will already be removed in the input
-> (J.JSValue -> J.Result a)
-- ^ decoding function otherwise
-> J.JSValue -> J.Result a
branchOnField k ifTrue ifFalse (J.JSObject jobj) =
let fields = J.fromJSObject jobj
jobj' = J.JSObject . J.toJSObject $ filter ((/=) k . fst) fields
in if lookup k fields == Just (J.JSBool True)
then ifTrue jobj'
else ifFalse jobj'
branchOnField k _ _ _ = J.Error $ "Need an object to branch on key " ++ k
-- | Add a field to a JSON object; to nothing, if the argument is not an object.
addField :: (String, J.JSValue) -> J.JSValue -> J.JSValue
addField (n,v) (J.JSObject obj) = J.JSObject $ JT.set_field obj n v
addField _ jsval = jsval
|
apyrgio/ganeti
|
src/Ganeti/JSON.hs
|
bsd-2-clause
| 19,912 | 0 | 18 | 4,762 | 4,778 | 2,522 | 2,256 | 329 | 3 |
module Tandoori.Typing.Unify (mgu, fitDeclTy) where
import Tandoori
import Tandoori.Typing
import Tandoori.Typing.Monad
import Tandoori.Typing.Error
import Control.Monad.Error
import Tandoori.Typing.Substitute
mgu :: [(Maybe VarName, TyEq)] -> ErrorT TypingError Typing Subst
mgu eqs = mgu' False eqs
fitDeclTy :: Ty -> Ty -> ErrorT TypingError Typing Subst
fitDeclTy τDecl τ = mgu' True [(Nothing, τ :=: τDecl)]
data Unification = Skip
| Substitute Tv Ty
| Recurse [TyEq]
| Flip Unification
| Incongruent
| OccursFailed
mguEq :: TyEq -> ErrorT TypingError Typing Unification
mguEq (TyCon d :=: TyCon d') = return $ if d == d' then Skip else Incongruent
mguEq (TyVar α :=: TyVar α') | α == α' = return Skip
mguEq (TyVar α :=: τ') | occurs α τ' = return OccursFailed
-- | otherwise = do rigid <- isMonoTv α
-- return $ if rigid then Flip Rigid else Substitute α t'
| otherwise = return $ Substitute α τ'
mguEq (τ :=: TyVar α) = return $ Flip Incongruent
mguEq (TyFun τ μ :=: TyFun τ' μ') = return $ Recurse [τ :=: τ', μ :=: μ']
mguEq (TyApp τ μ :=: TyApp τ' μ') = return $ Recurse [τ :=: τ', μ :=: μ']
mguEq (TyTuple n :=: TyTuple m) | n == m = return Skip
mguEq _ = return $ Incongruent
mgu' :: Bool -> [(Maybe VarName, TyEq)] -> ErrorT TypingError Typing Subst
mgu' leftOnly [] = return emptySubst
mgu' leftOnly ((src, t :=: t'):eqs) = process False =<< mguEq (t :=: t')
where process flipped Skip = mgu' leftOnly eqs
process flipped (Recurse eqs') = mgu' leftOnly (map (\ eq -> (src, eq)) eqs' ++ eqs)
process flipped Incongruent = throwError $ TypingError src $ Unsolvable (t :=: t')
process flipped OccursFailed = throwError $ TypingError src $ InfiniteType (t :=: t')
process flipped (Flip u) = process True =<< if flipped || leftOnly then return u else mguEq (t' :=: t)
process flipped (Substitute x t) = do s <- mgu' leftOnly eqs'
return $ addSubst x t s
where eqs' = map (fmap (\ (t :=: t') -> ((subst t) :=: (subst t')))) eqs
where s = addSubst x t emptySubst
subst t = substTy s t
|
bitemyapp/tandoori
|
src/Tandoori/Typing/Unify.hs
|
bsd-3-clause
| 2,685 | 0 | 17 | 1,024 | 859 | 437 | 422 | 40 | 7 |
module Main where
import Pipes.Cliff.Examples
import qualified Data.ByteString.Char8 as BS8
main :: IO ()
main = standardOutputAndError >>= BS8.putStr
|
rimmington/pipes-cliff
|
tests/standardOutputAndError.hs
|
bsd-3-clause
| 153 | 0 | 6 | 21 | 40 | 25 | 15 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module StarGist where
import qualified GitHub.Data.Name as N
import qualified GitHub.Endpoints.Gists as GH
import qualified Data.Text as T
import qualified Data.Text.IO as T
main :: IO ()
main = do
let gid = "your-gist-id"
result <- GH.starGist (GH.OAuth "your-token") gid
case result of
Left err -> putStrLn $ "Error: " ++ show err
Right () -> T.putStrLn $ T.concat ["Starred: ", N.untagName gid]
|
jwiegley/github
|
samples/Gists/StarGist.hs
|
bsd-3-clause
| 475 | 0 | 14 | 109 | 146 | 81 | 65 | 13 | 2 |
{-# LANGUAGE RankNTypes, NoMonomorphismRestriction, BangPatterns #-}
-- The following are program transformations I would like us to be able to do
-- They might not require many rules
--
-- NOTE: no support for beta, gamma, dirichlet distributions yet, hence
-- some of these examples won't work
module Examples.OptimizationTests where
import Language.Hakaru.Types
import Language.Hakaru.Distribution
import Language.Hakaru.Metropolis
import Data.Dynamic
import Control.Monad
import qualified Data.Map.Strict as M
-- Turn observe into constant
prog1_before = return $ conditioned (normal 0 1)
run1_before = sample prog1_before conds
where conds = [Just (toDyn (Lebesgue 4 :: Density Double))]
prog1_after = return 4
run1_after = sample prog1_after []
-- Conjugacy rewrite
coin2 = True
prog2_before = do bias <- unconditioned (beta 1 1)
coin <- conditioned (bern bias)
return (coin, bias)
run2_before = sample prog2_before [Just (toDyn (Discrete coin2))]
prog2_after = do coin <- conditioned (bern 0.5)
bias <- unconditioned (if coin2
then beta 2 1
else beta 1 2)
return (coin, bias)
run2_after = sample prog2_after [Just (toDyn (Discrete coin2))]
-- Transform Monte Carlo into Sequential Monte Carlo
prog3_before = do coin1 <- unconditioned (bern 0.5)
coin2 <- unconditioned $ if coin1
then bern 0.9
else bern 0.2
return coin2
run3_before = sample prog3_before []
prog3_after1 = do coin1 <- unconditioned (bern 0.5)
return coin1
run3_after1 = sample prog3_after1 []
prog3_after2 prev = do coin1 <- unconditioned $ categorical prev
coin2 <- unconditioned $ if coin1
then bern 0.9
else bern 0.2
return coin2
run3_after2 = do
prev <- run3_after1
sample (prog3_after2 (take 10 prev)) []
-- Transform loop through lifted inference
coin4 = True
flips = 20
prog4_before = do bias <- unconditioned (beta 1 1)
replicateM flips (conditioned (bern bias))
return bias
run4_before = sample prog4_before $ replicate flips (Just (toDyn (Discrete coin4)))
prog4_after = do bias <- unconditioned (if coin4
then beta (1 + flips) 1
else beta 1 (1 + flips))
return bias
run4_after = sample prog4_after []
|
bitemyapp/hakaru
|
Examples/OptimizationTests.hs
|
bsd-3-clause
| 2,693 | 0 | 13 | 925 | 664 | 334 | 330 | 52 | 2 |
-- -*- haskell-hugs-program-args: ("+." "-98") -*-
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
-- An monadic variant of the library from "Adaptive Functional
-- Programming", by Acar, Blelloch and Harper (POPL 2002).
-- Magnus Carlsson, [email protected]
module Control.Monad.Adaptive
( Adaptive
, Changeable
, Modifiable
, readMod
, InM(..)
, change
, propagate
, run
, inCh
, NewMod(..)
, newMod
) where
import Prelude
import Control.Monad(ap,unless)
import Control.Monad.Adaptive.MonadUtil
import Control.Monad.Adaptive.Ref
import qualified Control.Monad.Adaptive.OrderedList as OL
import Control.Monad.Adaptive.OrderedList(OrderedList)
import qualified Control.Monad.Adaptive.PriorityQueue as PQ
import Control.Monad.Adaptive.PriorityQueue(PriorityQueue)
-- Export:
class InM m' where
inM :: Ref m r => m a -> m' m r a
class (Monad (n m r), Ref m r) => NewMod n m r where
newModBy :: (a -> a -> Bool) -> Changeable m r a -> n m r (Modifiable m r a)
newMod :: (Eq a, NewMod n m r) =>
Changeable m r a -> n m r (Modifiable m r a)
change :: Ref m r => Modifiable m r a -> a -> Adaptive m r ()
propagate :: Ref m r => Adaptive m r ()
readMod :: Ref m r => Modifiable m r a -> Changeable m r a
run :: Ref m r => Adaptive m r a -> m a
inCh :: Ref m r => Changeable m r a -> Adaptive m r a
-- Local:
type ReComp m r = (Adaptive m r (), TimeStamp m r, TimeStamp m r)
startTime (_,s,_) = s
type TimeStamp m r = OL.Record m r ()
newtype Adaptive m r a =
Ad ((r (PriorityQueue (ReComp m r)), r (TimeStamp m r)) ->
OrderedList m r () a)
newtype Changeable m r a = Ch (K (Adaptive m r ()) a)
type K b a = (a -> b) -> b
newtype Modifiable m r a = Mo (r a, r (a -> Adaptive m r ()), r [ReComp m r])
cont :: Ref m r =>
((a -> Adaptive m r ()) -> Adaptive m r ()) -> Changeable m r a
cont m = Ch m
deCh (Ch m) = m
deAd (Ad m) = m
inAd :: Ref m r => Adaptive m r a -> Changeable m r a
inAd m = Ch $ (m >>=)
class InOL m' where
inOL :: Ref m r => OrderedList m r () b -> m' m r b
instance InOL Adaptive where
inOL m = Ad $ const m
instance InOL Changeable where
inOL m = inAd (inOL m)
instance Ref m r => Ref (Changeable m r) r where
newRef v = inM $ newRef v
readRef x = inM $ readRef x
writeRef x v = inM $ writeRef x v
instance Ref m r => Monad (Changeable m r) where
return a = Ch $ \k -> k a
Ch m >>= f = Ch $ \k -> m $ \a -> deCh (f a) k
instance Ref m r => Functor (Changeable m r) where
fmap f m = m >>= return . f
instance Ref m r => Ref (Adaptive m r) r where
newRef v = inM $ newRef v
readRef x = inM $ readRef x
writeRef x v = inM $ writeRef x v
instance Ref m r => Monad (Adaptive m r) where
return a = Ad $ \e -> return a
Ad m >>= f = Ad $ \e -> m e >>= \a -> deAd (f a) e
instance Ref m r => Functor (Adaptive m r) where
fmap f m = m >>= return . f
readMod (Mo (r,chg,es)) = do
start <- inAd stepTime
cont $ \k -> do
let reader = do readRef r >>= k
now <- readCurrentTime
mapRef ((reader,start,now):) es
reader
pqRef :: Ref m r => Adaptive m r (r (PriorityQueue (ReComp m r)))
pqRef = Ad $ \ (pq,ct) -> return pq
readPq :: Ref m r => Adaptive m r (PriorityQueue (ReComp m r))
readPq = pqRef >>= readRef
writePq a = pqRef >>= flip writeRef a
ctRef :: Ref m r => Adaptive m r (r (TimeStamp m r))
ctRef = Ad $ \ (pq,ct) -> return ct
readCurrentTime :: Ref m r => Adaptive m r (TimeStamp m r)
readCurrentTime = ctRef >>= readRef
writeCurrentTime a = ctRef >>= flip writeRef a
stepTime :: Ref m r => Adaptive m r (TimeStamp m r)
stepTime = do
readCurrentTime >>= inOL . flip OL.insert () >>= writeCurrentTime
readCurrentTime
instance InM Changeable where
inM m = Ch $ (inM m >>=)
instance InM Adaptive where
inM m = Ad $ const (OL.inM m)
change (Mo (r,changeR,es)) a = do
chg <- readRef changeR
chg a
propagate = do
let prop = do
pq <- readPq
case PQ.min pq of
Nothing -> return ()
Just ((reader,start,stop),pq') -> do
writePq pq'
unlessM (inOL (OL.deleted start)) $ do
inOL (OL.spliceOut start stop)
writeCurrentTime start
reader
prop
now <- readCurrentTime
prop
writeCurrentTime now
run m = OL.run $ do
pq <- newRef PQ.empty
ct <- OL.base >>= newRef
deAd m (pq,ct)
inCh (Ch m) = do
x <- newRef (error "inCh")
m (writeRef x)
readRef x
instance EqRef r => Eq (Modifiable m r a) where
(Mo (r1,_,_)) == (Mo (r2,_,_)) = eqRef r1 r2
newMod = newModBy (==)
instance Ref m r => NewMod Changeable m r where
newModBy c ch = inAd $ newModBy c ch
insertPQ :: Ref m r =>
r [ReComp m r] -> Adaptive m r ()
insertPQ esR = do
es <- readRef esR
pqR <- pqRef
readRef pqR >>= ins es >>= writeRef pqR
where
ins [] pq = return pq
ins (e:es) pq = PQ.insertM (\x y -> inOL $
OL.order (startTime x) (startTime y))
e pq >>= ins es
instance Ref m r => NewMod Adaptive m r where
newModBy cmp c = do
m <- newRef (error "newMod")
changeR <- newRef (error "changeR")
es <- newRef []
let writeFirst v = do
writeRef m v
now <- stepTime
writeRef changeR (writeAgain now)
writeAgain t v = do
v' <- readRef m
unless (cmp v' v) $ do
writeRef m v
insertPQ es
writeRef es []
writeCurrentTime t
writeRef changeR writeFirst
inCh $ do
v <- c
write <- readRef changeR
inAd $ write v
return (Mo (m, changeR, es))
|
Blaisorblade/Haskell-Adaptive
|
Control/Monad/Adaptive.hs
|
bsd-3-clause
| 5,691 | 0 | 23 | 1,666 | 2,626 | 1,303 | 1,323 | -1 | -1 |
module Code.Huffman
( make
)
where
-- $Id$
import Code.Type
import Code.Huffman.LR
import Code.Measure
import Util.Sort
import Data.FiniteMap
import Reporter
import ToDoc
isoptimalprefix :: ( ToDoc [b], ToDoc [a], ToDoc a, Ord a, Eq b )
=> Frequency a
-> Code a b
-> Reporter ()
isoptimalprefix freq code = do
inform $ vcat
[ text "Ist der Code"
, nest 4 $ toDoc code
, text "ein optimaler Präfix-Code für die Verteilung"
, nest 4 $ toDoc freq
, text "?"
]
let mcode = measure freq code
inform $ text "Der Code hat das Gesamtgewicht" <+> toDoc mcode
let huff = make freq
mhuff = measure freq huff
when ( mcode > mhuff ) $ reject
$ text "Das ist zu groß."
inform $ text "Das ist optimal."
-- | construct Huffman code
make :: Ord a
=> Frequency a
-> Code a LR
make xis =
let [ top ] = maker $ do
(x, i) <- fmToList xis
return $ Letter { weight = i, codes = listToFM [(x, [])] }
in codes top
maker :: Ord a
=> [ Letter a ] -> [ Letter a ]
maker xs =
case sortBy weight xs of
x : y : rest -> maker $ combine x y : rest
sonst -> sonst
combine :: Ord a
=> Letter a -> Letter a -> Letter a
combine x y =
Letter { weight = weight x + weight y
, codes = listToFM $ do
( c, it ) <- [ (L, x), (R, y) ]
( z, cs ) <- fmToList $ codes it
return ( z, c : cs )
}
|
Erdwolf/autotool-bonn
|
src/Code/Huffman.hs
|
gpl-2.0
| 1,418 | 16 | 17 | 444 | 549 | 286 | 263 | -1 | -1 |
{-# LANGUAGE CPP, GADTs, TypeFamilies, ScopedTypeVariables, RankNTypes #-}
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Safe #-}
#endif
module Compiler.Hoopl.Block (
-- * Shapes
O, C
, MaybeO(..), MaybeC(..)
, IndexedCO
, Shape(..)
-- * Blocks
, Block(..)
-- ** Predicates on Blocks
, isEmptyBlock
-- ** Constructing blocks
, emptyBlock, blockCons, blockSnoc
, blockJoinHead, blockJoinTail, blockJoin, blockJoinAny
, blockAppend
-- ** Deconstructing blocks
, firstNode, lastNode, endNodes
, blockSplitHead, blockSplitTail, blockSplit, blockSplitAny
-- ** Modifying blocks
, replaceFirstNode, replaceLastNode
-- ** Converting to and from lists
, blockToList, blockFromList
-- ** Maps and folds
, mapBlock, mapBlock', mapBlock3'
, foldBlockNodesF, foldBlockNodesF3
, foldBlockNodesB, foldBlockNodesB3
-- ** Biasing
, frontBiasBlock, backBiasBlock
) where
-- -----------------------------------------------------------------------------
-- Shapes: Open and Closed
-- | Used at the type level to indicate an "open" structure with
-- a unique, unnamed control-flow edge flowing in or out.
-- "Fallthrough" and concatenation are permitted at an open point.
data O
-- | Used at the type level to indicate a "closed" structure which
-- supports control transfer only through the use of named
-- labels---no "fallthrough" is permitted. The number of control-flow
-- edges is unconstrained.
data C
-- | Either type indexed by closed/open using type families
type family IndexedCO ex a b :: *
type instance IndexedCO C a b = a
type instance IndexedCO O a b = b
-- | Maybe type indexed by open/closed
data MaybeO ex t where
JustO :: t -> MaybeO O t
NothingO :: MaybeO C t
-- | Maybe type indexed by closed/open
data MaybeC ex t where
JustC :: t -> MaybeC C t
NothingC :: MaybeC O t
instance Functor (MaybeO ex) where
fmap _ NothingO = NothingO
fmap f (JustO a) = JustO (f a)
instance Functor (MaybeC ex) where
fmap _ NothingC = NothingC
fmap f (JustC a) = JustC (f a)
-- | Dynamic shape value
data Shape ex where
Closed :: Shape C
Open :: Shape O
-- -----------------------------------------------------------------------------
-- The Block type
-- | A sequence of nodes. May be any of four shapes (O/O, O/C, C/O, C/C).
-- Open at the entry means single entry, mutatis mutandis for exit.
-- A closed/closed block is a /basic/ block and can't be extended further.
-- Clients should avoid manipulating blocks and should stick to either nodes
-- or graphs.
data Block n e x where
BlockCO :: n C O -> Block n O O -> Block n C O
BlockCC :: n C O -> Block n O O -> n O C -> Block n C C
BlockOC :: Block n O O -> n O C -> Block n O C
BNil :: Block n O O
BMiddle :: n O O -> Block n O O
BCat :: Block n O O -> Block n O O -> Block n O O
BSnoc :: Block n O O -> n O O -> Block n O O
BCons :: n O O -> Block n O O -> Block n O O
-- -----------------------------------------------------------------------------
-- Simple operations on Blocks
-- Predicates
isEmptyBlock :: Block n e x -> Bool
isEmptyBlock BNil = True
isEmptyBlock (BCat l r) = isEmptyBlock l && isEmptyBlock r
isEmptyBlock _ = False
-- Building
emptyBlock :: Block n O O
emptyBlock = BNil
blockCons :: n O O -> Block n O x -> Block n O x
blockCons n b = case b of
BlockOC b l -> (BlockOC $! (n `blockCons` b)) l
BNil{} -> BMiddle n
BMiddle{} -> n `BCons` b
BCat{} -> n `BCons` b
BSnoc{} -> n `BCons` b
BCons{} -> n `BCons` b
blockSnoc :: Block n e O -> n O O -> Block n e O
blockSnoc b n = case b of
BlockCO f b -> BlockCO f $! (b `blockSnoc` n)
BNil{} -> BMiddle n
BMiddle{} -> b `BSnoc` n
BCat{} -> b `BSnoc` n
BSnoc{} -> b `BSnoc` n
BCons{} -> b `BSnoc` n
blockJoinHead :: n C O -> Block n O x -> Block n C x
blockJoinHead f (BlockOC b l) = BlockCC f b l
blockJoinHead f b = BlockCO f BNil `cat` b
blockJoinTail :: Block n e O -> n O C -> Block n e C
blockJoinTail (BlockCO f b) t = BlockCC f b t
blockJoinTail b t = b `cat` BlockOC BNil t
blockJoin :: n C O -> Block n O O -> n O C -> Block n C C
blockJoin f b t = BlockCC f b t
blockAppend :: Block n e O -> Block n O x -> Block n e x
blockAppend = cat
-- Taking apart
firstNode :: Block n C x -> n C O
firstNode (BlockCO n _) = n
firstNode (BlockCC n _ _) = n
lastNode :: Block n x C -> n O C
lastNode (BlockOC _ n) = n
lastNode (BlockCC _ _ n) = n
endNodes :: Block n C C -> (n C O, n O C)
endNodes (BlockCC f _ l) = (f,l)
blockSplitHead :: Block n C x -> (n C O, Block n O x)
blockSplitHead (BlockCO n b) = (n, b)
blockSplitHead (BlockCC n b t) = (n, BlockOC b t)
blockSplitTail :: Block n e C -> (Block n e O, n O C)
blockSplitTail (BlockOC b n) = (b, n)
blockSplitTail (BlockCC f b t) = (BlockCO f b, t)
-- | Split a closed block into its entry node, open middle block, and
-- exit node.
blockSplit :: Block n C C -> (n C O, Block n O O, n O C)
blockSplit (BlockCC f b t) = (f, b, t)
blockSplitAny :: Block n e x
-> (MaybeC e (n C O), Block n O O, MaybeC x (n O C))
blockSplitAny block = case block of
BlockCO f b -> (JustC f, b, NothingC)
BlockCC f b l -> (JustC f, b, JustC l)
BlockOC b l -> (NothingC, b, JustC l)
b@BNil -> (NothingC, b, NothingC)
b@BMiddle{} -> (NothingC, b, NothingC)
b@BCat{} -> (NothingC, b, NothingC)
b@BCons{} -> (NothingC, b, NothingC)
b@BSnoc{} -> (NothingC, b, NothingC)
blockToList :: Block n O O -> [n O O]
blockToList b = go b []
where go :: Block n O O -> [n O O] -> [n O O]
go BNil r = r
go (BMiddle n) r = n : r
go (BCat b1 b2) r = go b1 $! go b2 r
go (BSnoc b1 n) r = go b1 (n:r)
go (BCons n b1) r = n : go b1 r
blockFromList :: [n O O] -> Block n O O
blockFromList = foldr BCons BNil
-- | Convert a list of nodes to a block. The entry and exit node must
-- or must not be present depending on the shape of the block.
--
blockJoinAny :: (MaybeC e (n C O), Block n O O, MaybeC x (n O C)) -> Block n e x
blockJoinAny (NothingC, m, NothingC) = m
blockJoinAny (NothingC, m, JustC l) = BlockOC m l
blockJoinAny (JustC f, m, NothingC) = BlockCO f m
blockJoinAny (JustC f, m, JustC l) = BlockCC f m l
-- Modifying
replaceFirstNode :: Block n C x -> n C O -> Block n C x
replaceFirstNode (BlockCO _ b) f = BlockCO f b
replaceFirstNode (BlockCC _ b n) f = BlockCC f b n
replaceLastNode :: Block n x C -> n O C -> Block n x C
replaceLastNode (BlockOC b _) n = BlockOC b n
replaceLastNode (BlockCC l b _) n = BlockCC l b n
-- -----------------------------------------------------------------------------
-- General concatenation
cat :: Block n e O -> Block n O x -> Block n e x
cat x y = case x of
BNil -> y
BlockCO l b1 -> case y of
BlockOC b2 n -> (BlockCC l $! (b1 `cat` b2)) n
BNil -> x
BMiddle _ -> BlockCO l $! (b1 `cat` y)
BCat{} -> BlockCO l $! (b1 `cat` y)
BSnoc{} -> BlockCO l $! (b1 `cat` y)
BCons{} -> BlockCO l $! (b1 `cat` y)
BMiddle n -> case y of
BlockOC b2 n2 -> (BlockOC $! (x `cat` b2)) n2
BNil -> x
BMiddle{} -> BCons n y
BCat{} -> BCons n y
BSnoc{} -> BCons n y
BCons{} -> BCons n y
BCat{} -> case y of
BlockOC b3 n2 -> (BlockOC $! (x `cat` b3)) n2
BNil -> x
BMiddle n -> BSnoc x n
BCat{} -> BCat x y
BSnoc{} -> BCat x y
BCons{} -> BCat x y
BSnoc{} -> case y of
BlockOC b2 n2 -> (BlockOC $! (x `cat` b2)) n2
BNil -> x
BMiddle n -> BSnoc x n
BCat{} -> BCat x y
BSnoc{} -> BCat x y
BCons{} -> BCat x y
BCons{} -> case y of
BlockOC b2 n2 -> (BlockOC $! (x `cat` b2)) n2
BNil -> x
BMiddle n -> BSnoc x n
BCat{} -> BCat x y
BSnoc{} -> BCat x y
BCons{} -> BCat x y
-- -----------------------------------------------------------------------------
-- Mapping
-- | map a function over the nodes of a 'Block'
mapBlock :: (forall e x. n e x -> n' e x) -> Block n e x -> Block n' e x
mapBlock f (BlockCO n b ) = BlockCO (f n) (mapBlock f b)
mapBlock f (BlockOC b n) = BlockOC (mapBlock f b) (f n)
mapBlock f (BlockCC n b m) = BlockCC (f n) (mapBlock f b) (f m)
mapBlock _ BNil = BNil
mapBlock f (BMiddle n) = BMiddle (f n)
mapBlock f (BCat b1 b2) = BCat (mapBlock f b1) (mapBlock f b2)
mapBlock f (BSnoc b n) = BSnoc (mapBlock f b) (f n)
mapBlock f (BCons n b) = BCons (f n) (mapBlock f b)
-- | A strict 'mapBlock'
mapBlock' :: (forall e x. n e x -> n' e x) -> (Block n e x -> Block n' e x)
mapBlock' f = mapBlock3' (f, f, f)
-- | map over a block, with different functions to apply to first nodes,
-- middle nodes and last nodes respectively. The map is strict.
--
mapBlock3' :: forall n n' e x .
( n C O -> n' C O
, n O O -> n' O O,
n O C -> n' O C)
-> Block n e x -> Block n' e x
mapBlock3' (f, m, l) b = go b
where go :: forall e x . Block n e x -> Block n' e x
go (BlockOC b y) = (BlockOC $! go b) $! l y
go (BlockCO x b) = (BlockCO $! f x) $! (go b)
go (BlockCC x b y) = ((BlockCC $! f x) $! go b) $! (l y)
go BNil = BNil
go (BMiddle n) = BMiddle $! m n
go (BCat x y) = (BCat $! go x) $! (go y)
go (BSnoc x n) = (BSnoc $! go x) $! (m n)
go (BCons n x) = (BCons $! m n) $! (go x)
-- -----------------------------------------------------------------------------
-- Folding
-- | Fold a function over every node in a block, forward or backward.
-- The fold function must be polymorphic in the shape of the nodes.
foldBlockNodesF3 :: forall n a b c .
( n C O -> a -> b
, n O O -> b -> b
, n O C -> b -> c)
-> (forall e x . Block n e x -> IndexedCO e a b -> IndexedCO x c b)
foldBlockNodesF :: forall n a .
(forall e x . n e x -> a -> a)
-> (forall e x . Block n e x -> IndexedCO e a a -> IndexedCO x a a)
foldBlockNodesB3 :: forall n a b c .
( n C O -> b -> c
, n O O -> b -> b
, n O C -> a -> b)
-> (forall e x . Block n e x -> IndexedCO x a b -> IndexedCO e c b)
foldBlockNodesB :: forall n a .
(forall e x . n e x -> a -> a)
-> (forall e x . Block n e x -> IndexedCO x a a -> IndexedCO e a a)
foldBlockNodesF3 (ff, fm, fl) = block
where block :: forall e x . Block n e x -> IndexedCO e a b -> IndexedCO x c b
block (BlockCO f b ) = ff f `cat` block b
block (BlockCC f b l) = ff f `cat` block b `cat` fl l
block (BlockOC b l) = block b `cat` fl l
block BNil = id
block (BMiddle node) = fm node
block (b1 `BCat` b2) = block b1 `cat` block b2
block (b1 `BSnoc` n) = block b1 `cat` fm n
block (n `BCons` b2) = fm n `cat` block b2
cat :: forall a b c. (a -> b) -> (b -> c) -> a -> c
cat f f' = f' . f
foldBlockNodesF f = foldBlockNodesF3 (f, f, f)
foldBlockNodesB3 (ff, fm, fl) = block
where block :: forall e x . Block n e x -> IndexedCO x a b -> IndexedCO e c b
block (BlockCO f b ) = ff f `cat` block b
block (BlockCC f b l) = ff f `cat` block b `cat` fl l
block (BlockOC b l) = block b `cat` fl l
block BNil = id
block (BMiddle node) = fm node
block (b1 `BCat` b2) = block b1 `cat` block b2
block (b1 `BSnoc` n) = block b1 `cat` fm n
block (n `BCons` b2) = fm n `cat` block b2
cat :: forall a b c. (b -> c) -> (a -> b) -> a -> c
cat f f' = f . f'
foldBlockNodesB f = foldBlockNodesB3 (f, f, f)
----------------------------------------------------------------
-- | A block is "front biased" if the left child of every
-- concatenation operation is a node, not a general block; a
-- front-biased block is analogous to an ordinary list. If a block is
-- front-biased, then its nodes can be traversed from front to back
-- without general recusion; tail recursion suffices. Not all shapes
-- can be front-biased; a closed/open block is inherently back-biased.
frontBiasBlock :: Block n e x -> Block n e x
frontBiasBlock blk = case blk of
BlockCO f b -> BlockCO f (fb b BNil)
BlockOC b n -> BlockOC (fb b BNil) n
BlockCC f b n -> BlockCC f (fb b BNil) n
b@BNil{} -> fb b BNil
b@BMiddle{} -> fb b BNil
b@BCat{} -> fb b BNil
b@BSnoc{} -> fb b BNil
b@BCons{} -> fb b BNil
where
fb :: Block n O O -> Block n O O -> Block n O O
fb BNil rest = rest
fb (BMiddle n) rest = BCons n rest
fb (BCat l r) rest = fb l (fb r rest)
fb (BCons n b) rest = BCons n (fb b rest)
fb (BSnoc b n) rest = fb b (BCons n rest)
-- | A block is "back biased" if the right child of every
-- concatenation operation is a node, not a general block; a
-- back-biased block is analogous to a snoc-list. If a block is
-- back-biased, then its nodes can be traversed from back to back
-- without general recusion; tail recursion suffices. Not all shapes
-- can be back-biased; an open/closed block is inherently front-biased.
backBiasBlock :: Block n e x -> Block n e x
backBiasBlock blk = case blk of
BlockCO f b -> BlockCO f (bb BNil b)
BlockOC b n -> BlockOC (bb BNil b) n
BlockCC f b n -> BlockCC f (bb BNil b) n
b@BNil{} -> bb BNil b
b@BMiddle{} -> bb BNil b
b@BCat{} -> bb BNil b
b@BSnoc{} -> bb BNil b
b@BCons{} -> bb BNil b
where
bb :: Block n O O -> Block n O O -> Block n O O
bb rest BNil = rest
bb rest (BMiddle n) = BSnoc rest n
bb rest (BCat l r) = bb (bb rest l) r
bb rest (BCons n b) = bb (BSnoc rest n) b
bb rest (BSnoc b n) = BSnoc (bb rest b) n
|
hvr/hoopl
|
src/Compiler/Hoopl/Block.hs
|
bsd-3-clause
| 14,669 | 0 | 15 | 4,846 | 5,691 | 2,935 | 2,756 | -1 | -1 |
{-# LANGUAGE GeneralizedNewtypeDeriving, ScopedTypeVariables, RecursiveDo, GADTs,
TypeFamilies, EmptyDataDecls, FlexibleInstances #-}
{-# OPTIONS_GHC -fno-cse -fno-full-laziness #-}
module FRP.Sodium.Plain where
import qualified FRP.Sodium.Context as R
-- Note: the 'full-laziness' optimization messes up finalizers, so we're
-- disabling it. It'd be nice to find a really robust solution to this.
-- -fno-cse just in case, since we're using unsafePerformIO.
import Control.Applicative
import Control.Concurrent.Chan
import Control.Concurrent.MVar (MVar, newEmptyMVar, takeMVar, newMVar, readMVar)
import qualified Control.Concurrent.MVar as MV
import Control.Exception (evaluate)
import Control.Monad
import Control.Monad.State.Strict
import Control.Monad.Trans
import Data.Int
import Data.IORef
import Data.Map (Map)
import qualified Data.Map as M
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as S
import Data.Sequence (Seq, (|>), (><))
import qualified Data.Sequence as Seq
import GHC.Exts
import System.Mem.Weak
import System.IO.Unsafe
import Unsafe.Coerce
modifyMVar :: MVar a -> (a -> IO (a, b)) -> IO b
modifyMVar mv f = MV.modifyMVar mv $ \a -> do
(a', b') <- f a
evaluate a'
return (a', b')
modifyMVar_ :: MVar a -> (a -> IO a) -> IO ()
modifyMVar_ mv f = MV.modifyMVar_ mv $ \a -> do
a' <- f a
evaluate a'
return a'
putMVar :: MVar a -> a -> IO ()
putMVar mv a = do
evaluate a
MV.putMVar mv a
-- Note: the second parameter is a dummy, make it depend
-- on the last function parameter of the caller to make
-- sure that the IORef is freshly created every time
unsafeNewIORef :: a -> b -> IORef a
{-# NOINLINE unsafeNewIORef #-}
unsafeNewIORef v dummy = unsafePerformIO (newIORef v)
-- | Phantom type for use with 'R.Context' type class.
data Plain
partition :: Partition
{-# NOINLINE partition #-}
partition = unsafePerformIO createPartition
where
createPartition :: IO Partition
createPartition = do
lock <- newEmptyMVar
nextNodeIDRef <- newIORef (NodeID 0)
return $ Partition {
paLock = lock,
paNextNodeID = nextNodeIDRef
}
-- | A monad for transactional reactive operations. Execute it from 'IO' using 'sync'.
type Reactive = R.Reactive Plain
-- | A stream of events. The individual firings of events are called \'event occurrences\'.
type Event = R.Event Plain
-- | A time-varying value, American spelling.
type Behavior = R.Behavior Plain
-- | A time-varying value, British spelling.
type Behaviour = R.Behavior Plain
-- Must be data not newtype, because we need to attach finalizers to it
data Sample a = Sample {
unSample :: IO a,
sDep :: Dep,
sampleKeepAlive :: Maybe (IORef ())
}
instance R.Context Plain where
newtype Reactive Plain a = Reactive (StateT ReactiveState IO a)
data Event Plain a = Event { -- Must be data not newtype, because we need to attach finalizers to it
-- | Listen for event occurrences on this event, to be handled by the specified
-- handler. The returned action is used to unregister the listener.
getListenRaw :: Reactive (Listen a),
evCacheRef :: IORef (Maybe (Listen a)),
eDep :: Dep
}
data Behavior Plain a = Behavior {
updates_ :: Event a, -- ^ An event that gives the updates for the behavior. It doesn't do any equality
-- comparison as the name might imply.
-- | Obtain the current value of a behavior.
sampleImpl :: Sample a
}
sync = sync
newEvent = newEvent
listen = listen
never = never
merge = merge
filterJust = filterJust
hold = hold
updates = updates
value = value
snapshot = snapshot
switchE = switchE
switch = switch
execute = execute
sample = sample
coalesce = coalesce
once = once
split = split
-- | An event that gives the updates for the behavior. If the behavior was created
-- with 'hold', then 'updates' gives you an event like to the one that was held
-- but with only the last firing in any single transaction included.
updates :: Behavior a -> Event a
updates = coalesce (flip const) . updates_
-- | Execute the specified 'Reactive' within a new transaction, blocking the caller
-- until all resulting processing is complete and all callbacks have been called.
-- This operation is thread-safe, so it may be called from any thread.
--
-- State changes to 'hold' values occur after processing of the transaction is complete.
sync :: Reactive a -> IO a
sync task = do
let loop :: StateT ReactiveState IO () = do
queue1 <- gets asQueue1
if not $ Seq.null queue1 then do
let Reactive task = Seq.index queue1 0
modify $ \as -> as { asQueue1 = Seq.drop 1 queue1 }
task
loop
else do
queue2 <- gets asQueue2
mTask <- lift $ popPriorityQueue queue2
case mTask of
Just (Reactive task) -> do
task
loop
Nothing -> do
final <- gets asFinal
if not $ Seq.null final then do
let Reactive task = Seq.index final 0
modify $ \as -> as { asFinal = Seq.drop 1 final }
task
loop
else
return ()
post <- gets asPost
unless (Seq.null post) $ do
let Reactive task = post `Seq.index` 0
modify $ \as -> as { asPost = Seq.drop 1 post }
task
loop
outVar <- newIORef undefined
let lock = paLock partition
putMVar lock ()
q <- newPriorityQueue
evalStateT loop $ ReactiveState {
asQueue1 = Seq.singleton (task >>= ioReactive . writeIORef outVar),
asQueue2 = q,
asFinal = Seq.empty,
asPost = Seq.empty
}
takeMVar lock
readIORef outVar
-- | Returns an event, and a push action for pushing a value into the event.
newEvent :: Reactive (Event a, a -> Reactive ())
newEvent = do
(ev, push, _) <- ioReactive $ newEventLinked undefined
return (ev, push)
-- | Listen for firings of this event. The returned @IO ()@ is an IO action
-- that unregisters the listener. This is the observer pattern.
--
-- To listen to a 'Behavior' use @listen (value b) handler@ or
-- @listen (updates b) handler@
--
-- NOTE: The callback is called with the transaction held, so you cannot
-- use 'sync' inside a listener. You can delegate to another thread and have
-- that start the new transaction. If you want to do more processing in
-- the same transction, then you can use 'FRP.Sodium.Internal.listenTrans'
-- but this is discouraged unless you really need to write a new primitive.
listen :: Event a -> (a -> IO ()) -> Reactive (IO ())
listen ev handle = listenTrans ev $ \a -> ioReactive (handle a >> touch ev)
-- | An event that never fires.
never :: Event a
never = Event {
getListenRaw = return $ Listen (\_ _ _ -> return (return ())) undefined,
evCacheRef = unsafeNewIORef Nothing undefined,
eDep = undefined
}
-- | Merge two streams of events of the same type.
--
-- In the case where two event occurrences are simultaneous (i.e. both
-- within the same transaction), both will be delivered in the same
-- transaction. If the event firings are ordered for some reason, then
-- their ordering is retained. In many common cases the ordering will
-- be undefined.
merge :: Event a -> Event a -> Event a
merge ea eb = Event gl cacheRef (dep (ea, eb))
where
cacheRef = unsafeNewIORef Nothing eb
gl = do
(l, push, nodeRef) <- ioReactive newEventImpl
unlistener <- later $ do
u1 <- linkedListen ea (Just nodeRef) False push
u2 <- linkedListen eb (Just nodeRef) False $
schedulePrioritized (Just nodeRef) . push
return (u1 >> u2)
addCleanup_Listen unlistener l
-- | Unwrap Just values, and discard event occurrences with Nothing values.
filterJust :: Event (Maybe a) -> Event a
filterJust ema = Event gl cacheRef (dep ema)
where
cacheRef = unsafeNewIORef Nothing ema
gl = do
(l, push, nodeRef) <- ioReactive newEventImpl
unlistener <- later $ linkedListen ema (Just nodeRef) False $ \ma -> case ma of
Just a -> push a
Nothing -> return ()
addCleanup_Listen unlistener l
-- | Create a behavior with the specified initial value, that gets updated
-- by the values coming through the event. The \'current value\' of the behavior
-- is notionally the value as it was 'at the start of the transaction'.
-- That is, state updates caused by event firings get processed at the end of
-- the transaction.
hold :: a -> Event a -> Reactive (Behavior a)
hold initA ea = do
bsRef <- ioReactive $ newIORef $ initA `seq` BehaviorState initA Nothing
unlistener <- later $ linkedListen ea Nothing False $ \a -> do
bs <- ioReactive $ readIORef bsRef
ioReactive $ writeIORef bsRef $ a `seq` bs { bsUpdate = Just a }
when (isNothing (bsUpdate bs)) $ scheduleLast $ ioReactive $ do
bs <- readIORef bsRef
let newCurrent = fromJust (bsUpdate bs)
writeIORef bsRef $ newCurrent `seq` BehaviorState newCurrent Nothing
keepAliveRef <- ioReactive $ newIORef ()
sample <- ioReactive $ addCleanup_Sample unlistener
(Sample (bsCurrent <$> readIORef bsRef) (dep ea) (Just keepAliveRef))
let beh = sample `seq` Behavior {
updates_ = ea,
sampleImpl = sample
}
return beh
-- | An event that is guaranteed to fire once when you listen to it, giving
-- the current value of the behavior, and thereafter behaves like 'updates',
-- firing for each update to the behavior's value.
value :: Behavior a -> Event a
value ba = sa `seq` ea `seq` eventify (listenValueRaw ba) (dep (sa, ea))
where
sa = sampleImpl ba
ea = updates ba
-- | Sample the behavior at the time of the event firing. Note that the 'current value'
-- of the behavior that's sampled is the value as at the start of the transaction
-- before any state changes of the current transaction are applied through 'hold's.
snapshot :: (a -> b -> c) -> Event a -> Behavior b -> Event c
snapshot f ea bb = sample' `seq` Event gl cacheRef (dep (ea, sample))
where
cacheRef = unsafeNewIORef Nothing bb
sample = sampleImpl bb
sample' = unSample sample
gl = do
(l, push, nodeRef) <- ioReactive newEventImpl
unlistener <- later $ linkedListen ea (Just nodeRef) False $ \a -> do
b <- ioReactive sample'
push (f a b)
addCleanup_Listen unlistener l
-- | Unwrap an event inside a behavior to give a time-varying event implementation.
switchE :: Behavior (Event a) -> Event a
switchE bea = eea `seq` Event gl cacheRef (dep (eea, depRef))
where
eea = updates bea
cacheRef = unsafeNewIORef Nothing bea
depRef = unsafeNewIORef undefined bea
gl = do
(l, push, nodeRef) <- ioReactive newEventImpl
unlisten2Ref <- ioReactive $ newIORef Nothing
let doUnlisten2 = do
mUnlisten2 <- readIORef unlisten2Ref
fromMaybe (return ()) mUnlisten2
unlistener1 <- later $ do
initEa <- sample bea
(ioReactive . writeIORef unlisten2Ref) =<< (Just <$> linkedListen initEa (Just nodeRef) False push)
unlisten1 <- linkedListen eea (Just nodeRef) False $ \ea -> scheduleLast $ do
ioReactive $ do
doUnlisten2
writeIORef depRef ea
(ioReactive . writeIORef unlisten2Ref) =<< (Just <$> linkedListen ea (Just nodeRef) True push)
return $ unlisten1 >> doUnlisten2
addCleanup_Listen unlistener1 l
-- | Unwrap a behavior inside another behavior to give a time-varying behavior implementation.
switch :: Behavior (Behavior a) -> Reactive (Behavior a)
switch bba = do
ba <- sample bba
depRef <- ioReactive $ newIORef ba
za <- sample ba
let eba = updates bba
ioReactive $ evaluate eba
(ev, push, nodeRef) <- ioReactive $ newEventLinked (dep (bba, depRef))
unlisten2Ref <- ioReactive $ newIORef Nothing
let doUnlisten2 = do
mUnlisten2 <- readIORef unlisten2Ref
fromMaybe (return ()) mUnlisten2
unlisten1 <- listenValueRaw bba (Just nodeRef) False $ \ba -> do
ioReactive $ do
doUnlisten2
writeIORef depRef ba
(ioReactive . writeIORef unlisten2Ref . Just) =<< listenValueRaw ba (Just nodeRef) False push
hold za $ finalizeEvent ev (unlisten1 >> doUnlisten2)
-- | Execute the specified 'Reactive' action inside an event.
execute :: Event (Reactive a) -> Event a
execute ev = Event gl cacheRef (dep ev)
where
cacheRef = unsafeNewIORef Nothing ev
gl = do
(l, push, nodeRef) <- ioReactive newEventImpl
unlistener <- later $ linkedListen ev (Just nodeRef) False $ \action -> action >>= push
addCleanup_Listen unlistener l
-- | Obtain the current value of a behavior.
sample :: Behavior a -> Reactive a
{-# NOINLINE sample #-}
sample beh = ioReactive $ do
let sample = sampleImpl beh
maybe (return ())
readIORef
(sampleKeepAlive sample) -- defeat optimizer on ghc-7.8
unSample sample
-- | If there's more than one firing in a single transaction, combine them into
-- one using the specified combining function.
--
-- If the event firings are ordered, then the first will appear at the left
-- input of the combining function. In most common cases it's best not to
-- make any assumptions about the ordering, and the combining function would
-- ideally be commutative.
coalesce :: (a -> a -> a) -> Event a -> Event a
coalesce combine e = Event gl cacheRef (dep e)
where
cacheRef = unsafeNewIORef Nothing e
gl = do
(l, push, nodeRef) <- ioReactive newEventImpl
outRef <- ioReactive $ newIORef Nothing
unlistener <- later $ linkedListen e (Just nodeRef) False $ \a -> do
first <- isNothing <$> ioReactive (readIORef outRef)
ioReactive $ modifyIORef outRef $ \ma -> Just $ case ma of
Just a0 -> a0 `combine` a
Nothing -> a
when first $ schedulePrioritized (Just nodeRef) $ do
Just out <- ioReactive $ readIORef outRef
ioReactive $ writeIORef outRef Nothing
push out
addCleanup_Listen unlistener l
-- | Throw away all event occurrences except for the first one.
once :: Event a -> Event a
once e = Event gl cacheRef (dep e)
where
cacheRef = unsafeNewIORef Nothing e
gl = do
(l, push, nodeRef) <- ioReactive newEventImpl
aliveRef <- ioReactive $ newIORef True
unlistener <- later $ do
rec
unlisten <- linkedListen e (Just nodeRef) False $ \a -> do
alive <- ioReactive $ readIORef aliveRef
when alive $ do
ioReactive $ writeIORef aliveRef False
scheduleLast $ ioReactive unlisten
push a
return unlisten
addCleanup_Listen unlistener l
-- | Take each list item and put it into a new transaction of its own.
--
-- An example use case of this might be a situation where we are splitting
-- a block of input data into frames. We obviously want each frame to have
-- its own transaction so that state is updated separately each frame.
split :: Event [a] -> Event a
split esa = Event gl cacheRef (dep esa)
where
cacheRef = unsafeNewIORef Nothing esa
gl = do
(l, push, nodeRef) <- ioReactive newEventImpl
unlistener <- later $ linkedListen esa (Just nodeRef) False $ \as ->
schedulePost $ map push as
addCleanup_Listen unlistener l
-- | Create a new 'Behavior' along with an action to push changes into it.
-- American spelling.
newBehavior :: a -- ^ Initial behavior value
-> Reactive (Behavior a, a -> Reactive ())
newBehavior = R.newBehavior
-- | Create a new 'Behavior' along with an action to push changes into it.
-- British spelling.
newBehaviour :: a -- ^ Initial behavior value
-> Reactive (Behavior a, a -> Reactive ())
newBehaviour = R.newBehaviour
-- | Merge two streams of events of the same type, combining simultaneous
-- event occurrences.
--
-- In the case where multiple event occurrences are simultaneous (i.e. all
-- within the same transaction), they are combined using the supplied
-- function. The output event is guaranteed not to have more than one
-- event occurrence per transaction.
--
-- The combine function should be commutative, because simultaneous events
-- should be considered to be order-agnostic.
mergeWith :: (a -> a -> a) -> Event a -> Event a -> Event a
mergeWith = R.mergeWith
-- | Only keep event occurrences for which the predicate is true.
filterE :: (a -> Bool) -> Event a -> Event a
filterE = R.filterE
-- | Let event occurrences through only when the behavior's value is True.
-- Note that the behavior's value is as it was at the start of the transaction,
-- that is, no state changes from the current transaction are taken into account.
gate :: Event a -> Behavior Bool -> Event a
gate = R.gate
-- | Transform an event with a generalized state loop (a mealy machine). The function
-- is passed the input and the old state and returns the new state and output value.
collectE :: (a -> s -> (b, s)) -> s -> Event a -> Reactive (Event b)
collectE = R.collectE
-- | Transform a behavior with a generalized state loop (a mealy machine). The function
-- is passed the input and the old state and returns the new state and output value.
collect :: (a -> s -> (b, s)) -> s -> Behavior a -> Reactive (Behavior b)
collect = R.collect
-- | Accumulate state changes given in the input event.
accum :: a -> Event (a -> a) -> Reactive (Behavior a)
accum = R.accum
class PriorityQueueable k where
priorityOf :: k -> IO Int64
newtype Sequence = Sequence Int64 deriving (Eq, Ord, Enum)
data PriorityQueue k v = PriorityQueue {
pqNextSeq :: IORef Sequence,
pqDirty :: IORef Bool,
pqQueue :: IORef (Map (Int64, Sequence) v),
pqData :: IORef (Map Sequence (k, v))
}
newPriorityQueue :: IO (PriorityQueue k v)
newPriorityQueue =
PriorityQueue <$> newIORef (Sequence 0) <*> newIORef False
<*> newIORef M.empty <*> newIORef M.empty
pushPriorityQueue :: PriorityQueueable k => PriorityQueue k v -> k -> v -> IO ()
pushPriorityQueue pq k v = do
prio <- priorityOf k
seq <- readIORef (pqNextSeq pq)
modifyIORef (pqNextSeq pq) succ
modifyIORef (pqQueue pq) (M.insert (prio, seq) v)
modifyIORef (pqData pq) (M.insert seq (k, v))
dirtyPriorityQueue :: PriorityQueue k v -> IO ()
dirtyPriorityQueue pq = writeIORef (pqDirty pq) True
popPriorityQueue :: PriorityQueueable k => PriorityQueue k v -> IO (Maybe v)
popPriorityQueue pq = do
maybeRegen
q <- readIORef (pqQueue pq)
if M.null q
then return Nothing
else do
let (pseq@(prio, seq), v) = M.findMin q
modifyIORef (pqQueue pq) (M.delete pseq)
modifyIORef (pqData pq) (M.delete seq)
return $ Just v
where
maybeRegen = do
dirty <- readIORef (pqDirty pq)
when dirty $ do
writeIORef (pqDirty pq) False
dat <- readIORef (pqData pq)
writeIORef (pqQueue pq) M.empty
forM_ (M.assocs dat) $ \(seq,(k,v)) -> do
prio <- priorityOf k
modifyIORef (pqQueue pq) (M.insert (prio, seq) v)
type ID = Int64
instance PriorityQueueable (Maybe (MVar Node)) where
priorityOf (Just nodeRef) = noRank <$> readMVar nodeRef
priorityOf Nothing = return maxBound
data ReactiveState = ReactiveState {
asQueue1 :: Seq (Reactive ()),
asQueue2 :: PriorityQueue (Maybe (MVar Node)) (Reactive ()),
asFinal :: Seq (Reactive ()),
asPost :: Seq (Reactive ())
}
instance Functor (R.Reactive Plain) where
fmap f rm = Reactive (fmap f (unReactive rm))
unReactive :: Reactive a -> StateT ReactiveState IO a
unReactive (Reactive m) = m
instance Applicative (R.Reactive Plain) where
pure a = Reactive $ return a
rf <*> rm = Reactive $ unReactive rf <*> unReactive rm
instance Monad (R.Reactive Plain) where
return a = Reactive $ return a
rma >>= kmb = Reactive $ do
a <- unReactive rma
unReactive (kmb a)
instance MonadFix (R.Reactive Plain) where
mfix f = Reactive $ mfix $ \a -> unReactive (f a)
ioReactive :: IO a -> Reactive a
ioReactive io = Reactive $ liftIO io
newtype NodeID = NodeID Int deriving (Eq, Ord, Enum)
data Partition = Partition {
paLock :: MVar (),
paNextNodeID :: IORef NodeID
}
-- | Queue the specified atomic to run at the end of the priority 1 queue
scheduleEarly :: Reactive () -> Reactive ()
scheduleEarly task = Reactive $ modify $ \as -> as { asQueue1 = asQueue1 as |> task }
scheduleLast :: Reactive () -> Reactive ()
scheduleLast task = Reactive $ modify $ \as -> as { asFinal = asFinal as |> task }
schedulePost :: [Reactive ()] -> Reactive ()
schedulePost tasks = Reactive $ modify $ \as -> as { asPost = Seq.fromList tasks >< asPost as }
data Listen a = Listen { runListen_ :: Maybe (MVar Node) -> Bool -> (a -> Reactive ()) -> Reactive (IO ())
, listenerKeepAlive :: Weak (IORef ())
}
-- | Unwrap an event's listener machinery.
getListen :: Event a -> Reactive (Listen a)
getListen (Event getLRaw cacheRef _) = do
mL <- ioReactive $ readIORef cacheRef
case mL of
Just l -> return l
Nothing -> do
l <- getLRaw
ioReactive $ writeIORef cacheRef (Just l)
return l
-- | Listen for firings of this event. The returned @IO ()@ is an IO action
-- that unregisters the listener. This is the observer pattern.
linkedListen :: Event a -> Maybe (MVar Node) -> Bool -> (a -> Reactive ()) -> Reactive (IO ())
{-# NOINLINE linkedListen #-}
linkedListen ev mv suppressEarlierFirings handle = do
ioReactive $ evaluate ev
l <- getListen ev
unlisten <- runListen_ l mv suppressEarlierFirings handle
-- ensure l doesn't get cleaned up while runListen_ is running
_ <- ioReactive $ touch l
return unlisten
-- | Variant of 'listen' that allows you to initiate more activity in the current
-- transaction. Useful for implementing new primitives.
listenTrans :: Event a -> (a -> Reactive ()) -> Reactive (IO ())
listenTrans ev handle = linkedListen ev Nothing False handle
data Observer p a = Observer {
obNextID :: ID,
obListeners :: Map ID (a -> Reactive ()),
obFirings :: [a]
}
data Node = Node {
noID :: NodeID,
noRank :: Int64,
noListeners :: Map ID (MVar Node)
}
newNode :: IO (MVar Node)
newNode = do
nodeID <- readIORef (paNextNodeID partition)
modifyIORef (paNextNodeID partition) succ
newMVar (Node nodeID 0 M.empty)
wrap :: (Maybe (MVar Node) -> Bool -> (a -> Reactive ()) -> Reactive (IO ())) -> IO (Listen a)
{-# NOINLINE wrap #-}
wrap l = Listen l <$> newIORef ()
touch :: a -> IO ()
{-# NOINLINE touch #-}
touch a = evaluate a >> return ()
linkNode :: MVar Node -> ID -> MVar Node -> IO Bool
linkNode nodeRef iD mvTarget = do
no <- readMVar nodeRef
modified <- ensureBiggerThan S.empty mvTarget (noRank no)
modifyMVar_ nodeRef $ \no -> return $
let listeners' = M.insert iD mvTarget (noListeners no)
in listeners' `seq` no { noListeners = listeners' }
return modified
ensureBiggerThan :: Set NodeID -> MVar Node -> Int64 -> IO Bool
ensureBiggerThan visited nodeRef limit = do
no <- takeMVar nodeRef
if noRank no > limit || noID no `S.member` visited then do
putMVar nodeRef no
return False
else do
let newSerial = succ limit
--putStrLn $ show (noRank no) ++ " -> " ++ show newSerial
putMVar nodeRef $ newSerial `seq` no { noRank = newSerial }
forM_ (M.elems . noListeners $ no) $ \mvTarget -> do
ensureBiggerThan (S.insert (noID no) visited) mvTarget newSerial
return True
unlinkNode :: MVar Node -> ID -> IO ()
unlinkNode nodeRef iD = do
modifyMVar_ nodeRef $ \no -> do
let listeners' = M.delete iD (noListeners no)
return $ listeners' `seq` no { noListeners = listeners' }
newtype Dep = Dep Any
dep :: a -> Dep
dep = Dep . unsafeCoerce
-- | Returns a 'Listen' for registering listeners, and a push action for pushing
-- a value into the event.
newEventImpl :: forall p a . IO (Listen a, a -> Reactive (), MVar Node)
newEventImpl = do
nodeRef <- newNode
mvObs <- newMVar (Observer 0 M.empty [])
cacheRef <- newIORef Nothing
rec
let l mMvTarget suppressEarlierFirings handle = do
(firings, unlisten, iD) <- ioReactive $ modifyMVar mvObs $ \ob -> do
let iD = obNextID ob
nextID' = succ iD
listeners' = M.insert iD handle (obListeners ob)
ob' = nextID' `seq` listeners' `seq`
ob { obNextID = nextID',
obListeners = listeners' }
unlisten = do
modifyMVar_ mvObs $ \ob -> do
let listeners' = M.delete iD (obListeners ob)
return $ listeners' `seq` ob { obListeners = listeners' }
unlinkNode nodeRef iD
--touch listen
return ()
return (ob', (reverse . obFirings $ ob, unlisten, iD))
modified <- case mMvTarget of
Just mvTarget -> ioReactive $ linkNode nodeRef iD mvTarget
Nothing -> return False
-- If any of our ranks are changed, dirty the priority queue so
-- all the priorities will be re-evaluated
when modified $ dirtyPrioritized
unless suppressEarlierFirings $ mapM_ handle firings
return unlisten
listen <- wrap l -- defeat optimizer on ghc-7.0.4
let push a = do
ioReactive $ evaluate a
ob <- ioReactive $ modifyMVar mvObs $ \ob -> return $
(ob { obFirings = a : obFirings ob }, ob)
-- If this is the first firing...
when (null (obFirings ob)) $ scheduleLast $ ioReactive $ do
modifyMVar_ mvObs $ \ob -> return $ ob { obFirings = [] }
mapM_ ($ a) (M.elems . obListeners $ ob)
return (listen, push, nodeRef)
-- | Returns an event, and a push action for pushing a value into the event.
newEventLinked :: Dep -> IO (Event a, a -> Reactive (), MVar Node)
newEventLinked d = do
(listen, push, nodeRef) <- newEventImpl
cacheRef <- newIORef Nothing
let ev = Event {
getListenRaw = return listen,
evCacheRef = cacheRef,
eDep = d
}
return (ev, push, nodeRef)
instance Functor (R.Event Plain) where
f `fmap` e = Event getListen' cacheRef (dep e)
where
cacheRef = unsafeNewIORef Nothing e
getListen' =
return $ Listen (\mNodeRef suppressEarlierFirings handle -> do
linkedListen e mNodeRef suppressEarlierFirings (handle . f)) undefined
instance Functor (R.Behavior Plain) where
f `fmap` Behavior e s =
fs `seq` fe `seq` Behavior fe fs
where
fe = f `fmap` e
s' = unSample s
fs = s' `seq` Sample (f `fmap` s') (dep s) Nothing
constant :: a -> Behavior a
constant a = Behavior {
updates_ = never,
sampleImpl = Sample (return a) undefined Nothing
}
data BehaviorState a = BehaviorState {
bsCurrent :: a,
bsUpdate :: Maybe a
}
-- | Add a finalizer to an event.
finalizeEvent :: Event a -> IO () -> Event a
{-# NOINLINE finalizeEvent #-}
finalizeEvent ea unlisten = ea { getListenRaw = gl }
where
gl = do
l <- getListen ea
ioReactive $ finalizeListen l unlisten
-- | Add a finalizer to a listener.
finalizeListen :: Listen a -> IO () -> IO (Listen a)
{-# NOINLINE finalizeListen #-}
finalizeListen l unlisten = do
wRef <- mkWeakIORef (listenerKeepAlive l) unlisten
return $ l { listenerKeepAlive = wRef }
-- | Add a finalizer to a Reactive.
finalizeSample :: Sample a -> IO () -> IO (Sample a)
{-# NOINLINE finalizeSample #-}
finalizeSample s unlisten = case sampleKeepAlive s of
Just keepaliveRef -> do
mkWeakIORef keepaliveRef unlisten
return s
Nothing -> error "finalizeSample called on sample with no keepAlive"
newtype Unlistener = Unlistener (MVar (Maybe (IO ())))
-- | Perform a listen later so we can tolerate lazy loops.
-- Returns an 'Unlistener' that can be attached to an event with 'addCleanup_Listen'.
later :: Reactive (IO ()) -> Reactive Unlistener
later doListen = do
unlistener@(Unlistener ref) <- newUnlistener
-- We schedule the actual listen rather than doing it now, so event values get
-- evaluated lazily. Otherwise we get deadlocks when events are used in value loops.
scheduleEarly $ do
mOldUnlisten <- ioReactive $ takeMVar ref
case mOldUnlisten of
Just _ -> do
unlisten <- doListen
ioReactive $ putMVar ref (Just unlisten)
Nothing -> ioReactive $ putMVar ref mOldUnlisten
return unlistener
where
newUnlistener :: Reactive Unlistener
newUnlistener = Unlistener <$> ioReactive (newMVar (Just $ return ()))
-- | Cause the things listened to with 'later' to be unlistened when the
-- specified listener is not referenced any more.
addCleanup_Listen :: Unlistener -> Listen a -> Reactive (Listen a)
addCleanup_Listen (Unlistener ref) l = ioReactive $ finalizeListen l $ do
mUnlisten <- takeMVar ref
fromMaybe (return ()) mUnlisten
putMVar ref Nothing
-- | Cause the things listened to with 'later' to be unlistened when the
-- specified sample is not referenced any more.
addCleanup_Sample :: Unlistener -> Sample a -> IO (Sample a)
addCleanup_Sample (Unlistener ref) s = finalizeSample s $ do
mUnlisten <- takeMVar ref
fromMaybe (return ()) mUnlisten
putMVar ref Nothing
-- | Listen to the value of this behavior with an initial callback giving
-- the current value. Can get multiple values per transaction, the last of
-- which is considered valid. You would normally want to use 'listenValue',
-- which removes the extra unwanted values.
listenValueRaw :: Behavior a -> Maybe (MVar Node) -> Bool -> (a -> Reactive ()) -> Reactive (IO ())
listenValueRaw ba = lastFiringOnly $ \mNodeRef suppressEarlierFirings handle -> do
a <- sample ba
handle a
linkedListen (updates ba) mNodeRef suppressEarlierFirings handle
-- | Queue the specified atomic to run at the end of the priority 2 queue
schedulePrioritized :: Maybe (MVar Node)
-> Reactive ()
-> Reactive ()
schedulePrioritized mNodeRef task = Reactive $ do
q <- gets asQueue2
lift $ pushPriorityQueue q mNodeRef task
dirtyPrioritized :: Reactive ()
dirtyPrioritized = Reactive $ do
q <- gets asQueue2
lift $ dirtyPriorityQueue q
-- Clean up the listener so it gives only one value per transaction, specifically
-- the last one.
lastFiringOnly :: (Maybe (MVar Node) -> Bool -> (a -> Reactive ()) -> Reactive (IO ()))
-> Maybe (MVar Node) -> Bool -> (a -> Reactive ()) -> Reactive (IO ())
lastFiringOnly listen mNodeRef suppressEarlierFirings handle = do
aRef <- ioReactive $ newIORef Nothing
listen mNodeRef suppressEarlierFirings $ \a -> do
ma <- ioReactive $ readIORef aRef
ioReactive $ writeIORef aRef (Just a)
when (isNothing ma) $ schedulePrioritized mNodeRef $ do
Just a <- ioReactive $ readIORef aRef
ioReactive $ writeIORef aRef Nothing
handle a
eventify :: (Maybe (MVar Node) -> Bool -> (a -> Reactive ()) -> Reactive (IO ())) -> Dep -> Event a
eventify listen d = Event gl cacheRef d
where
cacheRef = unsafeNewIORef Nothing listen
gl = do
(l, push, nodeRef) <- ioReactive newEventImpl
unlistener <- later $ listen (Just nodeRef) False push
addCleanup_Listen unlistener l
instance Applicative (R.Behavior Plain) where
pure = constant
b1@(Behavior e1 s1) <*> b2@(Behavior e2 s2) = Behavior u s
where
cacheRef = unsafeNewIORef Nothing s2
keepaliveRef = unsafeNewIORef () s2
u = Event gl cacheRef (dep (e1,e2))
s1' = unSample s1
s2' = unSample s2
gl = do
fRef <- ioReactive $ newIORef =<< unSample s1
aRef <- ioReactive $ newIORef =<< unSample s2
(l, push, nodeRef) <- ioReactive newEventImpl
unlistener <- later $ do
un1 <- linkedListen e1 (Just nodeRef) False $ \f -> do
ioReactive $ writeIORef fRef f
a <- ioReactive $ readIORef aRef
push (f a)
un2 <- linkedListen e2 (Just nodeRef) False $ \a -> do
f <- ioReactive $ readIORef fRef
ioReactive $ writeIORef aRef a
push (f a)
return (un1 >> un2)
addCleanup_Listen unlistener l
s = s1' `seq` s2' `seq` Sample (($) <$> s1' <*> s2') (dep (s1, s2)) (Just keepaliveRef)
{-
-- | Cross the specified event over to a different partition.
crossE :: (Typeable p, Typeable q) => Event a -> Reactive (Event q a)
crossE epa = do
(ev, push) <- ioReactive newEvent
unlisten <- listen epa $ async . push
return $ finalizeEvent ev unlisten
-- | Cross the specified behavior over to a different partition.
cross :: (Typeable p, Typeable q) => Behavior a -> Reactive (Behavior q a)
cross bpa = do
a <- sample bpa
ea <- crossE (updates bpa)
ioReactive $ sync $ 3 a ea
-}
-- | An event that gives the updates for the behavior. If the behavior was created
-- with 'hold', then 'changes' gives you an event equivalent to the one that was held.
changes :: Behavior a -> Event a
{-# DEPRECATED changes "renamed to 'updates'" #-}
changes = updates
-- | An event that is guaranteed to fire once when you listen to it, giving
-- the current value of the behavior, and thereafter behaves like 'changes',
-- firing for each update to the behavior's value.
values :: Behavior a -> Event a
{-# DEPRECATED values "renamed to 'value'" #-}
values = value
-- | Sample the behavior at the time of the event firing. Note that the 'current value'
-- of the behavior that's sampled is the value as at the start of the transaction
-- before any state changes of the current transaction are applied through 'hold's.
snapshotWith :: (a -> b -> c) -> Event a -> Behavior b -> Event c
{-# DEPRECATED snapshotWith "renamed to 'snapshot'" #-}
snapshotWith = snapshot
-- | Count event occurrences, giving a behavior that starts with 0 before the first occurrence.
count :: Event a -> Reactive (Behavior Int)
{-# DEPRECATED count "removing it in the pursuit of minimalism, replace with: accum 0 (const (1+) <$> e)" #-}
count = accum 0 . (const (1+) <$>)
|
kevintvh/sodium
|
haskell/src/FRP/Sodium/Plain.hs
|
bsd-3-clause
| 35,960 | 0 | 33 | 10,099 | 9,387 | 4,686 | 4,701 | -1 | -1 |
module Generate.JavaScript.BuiltIn where
import Control.Arrow (first)
import qualified Language.ECMAScript3.Syntax as JS
import qualified AST.Module.Name as ModuleName
import Generate.JavaScript.Helpers
import qualified Reporting.Region as R
utils :: String -> [JS.Expression ()] -> JS.Expression ()
utils func args =
obj ["_U", func] `call` args
-- LITERALS
character :: Char -> JS.Expression ()
character char =
utils "chr" [ JS.StringLit () [char] ]
string :: String -> JS.Expression ()
string str =
JS.StringLit () str
-- LISTS
list :: [JS.Expression ()] -> JS.Expression ()
list elements =
utils "list" [ JS.ArrayLit () elements ]
range :: JS.Expression () -> JS.Expression () -> JS.Expression ()
range low high =
utils "range" [ low, high ]
-- RECORDS
recordUpdate :: JS.Expression () -> [(String, JS.Expression ())] -> JS.Expression ()
recordUpdate record fields =
utils "update"
[ record
, JS.ObjectLit () (map (first prop) fields)
]
-- COMPARISIONS
eq :: JS.Expression () -> JS.Expression () -> JS.Expression ()
eq left right =
utils "eq" [ left, right ]
cmp :: JS.Expression () -> JS.Expression () -> JS.Expression ()
cmp left right =
utils "cmp" [ left, right ]
-- CRASH
crash :: ModuleName.Canonical -> R.Region -> Maybe (JS.Expression ()) -> JS.Expression ()
crash home region maybeCaseCrashValue =
let
homeString =
JS.StringLit () (ModuleName.canonicalToString home)
in
case maybeCaseCrashValue of
Nothing ->
utils "crash" [ homeString, regionToJs region ]
Just crashValue ->
utils "crashCase" [ homeString, regionToJs region, crashValue ]
regionToJs :: R.Region -> JS.Expression ()
regionToJs (R.Region start end) =
JS.ObjectLit ()
[ ( prop "start", positionToJs start )
, ( prop "end", positionToJs end )
]
positionToJs :: R.Position -> JS.Expression ()
positionToJs (R.Position line column) =
JS.ObjectLit ()
[ ( prop "line", JS.IntLit () line )
, ( prop "column", JS.IntLit () column )
]
|
laszlopandy/elm-compiler
|
src/Generate/JavaScript/BuiltIn.hs
|
bsd-3-clause
| 2,058 | 0 | 12 | 441 | 782 | 403 | 379 | 52 | 2 |
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module Hakyll.Core.Runtime.Tests
( tests
) where
--------------------------------------------------------------------------------
import qualified Data.ByteString as B
import System.FilePath ((</>))
import Test.Framework (Test, testGroup)
import Test.HUnit (Assertion, (@?=))
--------------------------------------------------------------------------------
import Hakyll
import qualified Hakyll.Core.Logger as Logger
import Hakyll.Core.Runtime
import TestSuite.Util
--------------------------------------------------------------------------------
tests :: Test
tests = testGroup "Hakyll.Core.Runtime.Tests" $
fromAssertions "run" [case01, case02]
--------------------------------------------------------------------------------
case01 :: Assertion
case01 = do
_ <- run testConfiguration Logger.Error $ do
match "images/*" $ do
route idRoute
compile copyFileCompiler
match "*.md" $ do
route $ setExtension "html"
compile $ do
getResourceBody
>>= saveSnapshot "raw"
>>= return . renderPandoc
create ["bodies.txt"] $ do
route idRoute
compile $ do
items <- loadAllSnapshots "*.md" "raw"
makeItem $ concat $ map itemBody (items :: [Item String])
favicon <- B.readFile $
providerDirectory testConfiguration </> "images/favicon.ico"
favicon' <- B.readFile $
destinationDirectory testConfiguration </> "images/favicon.ico"
favicon @?= favicon'
example <- readFile $
destinationDirectory testConfiguration </> "example.html"
lines example @?= ["<p>This is an example.</p>"]
bodies <- readFile $ destinationDirectory testConfiguration </> "bodies.txt"
head (lines bodies) @?= "This is an example."
cleanTestEnv
--------------------------------------------------------------------------------
case02 :: Assertion
case02 = do
_ <- run testConfiguration Logger.Error $ do
match "images/favicon.ico" $ do
route $ gsubRoute "images/" (const "")
compile $ makeItem ("Test" :: String)
match "images/**" $ do
route idRoute
compile copyFileCompiler
favicon <- readFile $
destinationDirectory testConfiguration </> "favicon.ico"
favicon @?= "Test"
cleanTestEnv
|
bergmark/hakyll
|
tests/Hakyll/Core/Runtime/Tests.hs
|
bsd-3-clause
| 2,611 | 0 | 21 | 673 | 517 | 255 | 262 | 55 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE ViewPatterns #-}
module Database.Persist.Quasi
( parse
, PersistSettings (..)
, upperCaseSettings
, lowerCaseSettings
, nullable
#if TEST
, Token (..)
, tokenize
, parseFieldType
#endif
) where
import Prelude hiding (lines)
import Control.Arrow ((&&&))
import Control.Monad (msum, mplus)
import Data.Char
import Data.List (find, foldl')
import qualified Data.Map as M
import Data.Maybe (mapMaybe, fromMaybe, maybeToList)
import Data.Monoid (mappend)
import Data.Text (Text)
import qualified Data.Text as T
import Database.Persist.Types
data ParseState a = PSDone | PSFail String | PSSuccess a Text deriving Show
parseFieldType :: Text -> Either String FieldType
parseFieldType t0 =
case parseApplyFT t0 of
PSSuccess ft t'
| T.all isSpace t' -> Right ft
PSFail err -> Left $ "PSFail " ++ err
other -> Left $ show other
where
parseApplyFT t =
case goMany id t of
PSSuccess (ft:fts) t' -> PSSuccess (foldl' FTApp ft fts) t'
PSSuccess [] _ -> PSFail "empty"
PSFail err -> PSFail err
PSDone -> PSDone
parseEnclosed :: Char -> (FieldType -> FieldType) -> Text -> ParseState FieldType
parseEnclosed end ftMod t =
let (a, b) = T.break (== end) t
in case parseApplyFT a of
PSSuccess ft t' -> case (T.dropWhile isSpace t', T.uncons b) of
("", Just (c, t'')) | c == end -> PSSuccess (ftMod ft) (t'' `Data.Monoid.mappend` t')
(x, y) -> PSFail $ show (b, x, y)
x -> PSFail $ show x
parse1 t =
case T.uncons t of
Nothing -> PSDone
Just (c, t')
| isSpace c -> parse1 $ T.dropWhile isSpace t'
| c == '(' -> parseEnclosed ')' id t'
| c == '[' -> parseEnclosed ']' FTList t'
| isUpper c ->
let (a, b) = T.break (\x -> isSpace x || x `elem` ("()[]"::String)) t
in PSSuccess (getCon a) b
| otherwise -> PSFail $ show (c, t')
getCon t =
case T.breakOnEnd "." t of
(_, "") -> FTTypeCon Nothing t
("", _) -> FTTypeCon Nothing t
(a, b) -> FTTypeCon (Just $ T.init a) b
goMany front t =
case parse1 t of
PSSuccess x t' -> goMany (front . (x:)) t'
PSFail err -> PSFail err
PSDone -> PSSuccess (front []) t
-- _ ->
data PersistSettings = PersistSettings
{ psToDBName :: !(Text -> Text)
, psStrictFields :: !Bool
-- ^ Whether fields are by default strict. Default value: @True@.
--
-- @since 1.2
, psIdName :: !Text
-- ^ The name of the id column. Default value: @id@
-- The name of the id column can also be changed on a per-model basis
-- <https://github.com/yesodweb/persistent/wiki/Persistent-entity-syntax>
--
-- @since 2.0
}
defaultPersistSettings, upperCaseSettings, lowerCaseSettings :: PersistSettings
defaultPersistSettings = PersistSettings
{ psToDBName = id
, psStrictFields = True
, psIdName = "id"
}
upperCaseSettings = defaultPersistSettings
lowerCaseSettings = defaultPersistSettings
{ psToDBName =
let go c
| isUpper c = T.pack ['_', toLower c]
| otherwise = T.singleton c
in T.dropWhile (== '_') . T.concatMap go
}
-- | Parses a quasi-quoted syntax into a list of entity definitions.
parse :: PersistSettings -> Text -> [EntityDef]
parse ps = parseLines ps
. removeSpaces
. filter (not . empty)
. map tokenize
. T.lines
-- | A token used by the parser.
data Token = Spaces !Int -- ^ @Spaces n@ are @n@ consecutive spaces.
| Token Text -- ^ @Token tok@ is token @tok@ already unquoted.
deriving (Show, Eq)
-- | Tokenize a string.
tokenize :: Text -> [Token]
tokenize t
| T.null t = []
| "--" `T.isPrefixOf` t = [] -- Comment until the end of the line.
| "#" `T.isPrefixOf` t = [] -- Also comment to the end of the line, needed for a CPP bug (#110)
| T.head t == '"' = quotes (T.tail t) id
| T.head t == '(' = parens 1 (T.tail t) id
| isSpace (T.head t) =
let (spaces, rest) = T.span isSpace t
in Spaces (T.length spaces) : tokenize rest
-- support mid-token quotes and parens
| Just (beforeEquals, afterEquals) <- findMidToken t
, not (T.any isSpace beforeEquals)
, Token next : rest <- tokenize afterEquals =
Token (T.concat [beforeEquals, "=", next]) : rest
| otherwise =
let (token, rest) = T.break isSpace t
in Token token : tokenize rest
where
findMidToken t' =
case T.break (== '=') t' of
(x, T.drop 1 -> y)
| "\"" `T.isPrefixOf` y || "(" `T.isPrefixOf` y -> Just (x, y)
_ -> Nothing
quotes t' front
| T.null t' = error $ T.unpack $ T.concat $
"Unterminated quoted string starting with " : front []
| T.head t' == '"' = Token (T.concat $ front []) : tokenize (T.tail t')
| T.head t' == '\\' && T.length t' > 1 =
quotes (T.drop 2 t') (front . (T.take 1 (T.drop 1 t'):))
| otherwise =
let (x, y) = T.break (`elem` ['\\','\"']) t'
in quotes y (front . (x:))
parens count t' front
| T.null t' = error $ T.unpack $ T.concat $
"Unterminated parens string starting with " : front []
| T.head t' == ')' =
if count == (1 :: Int)
then Token (T.concat $ front []) : tokenize (T.tail t')
else parens (count - 1) (T.tail t') (front . (")":))
| T.head t' == '(' =
parens (count + 1) (T.tail t') (front . ("(":))
| T.head t' == '\\' && T.length t' > 1 =
parens count (T.drop 2 t') (front . (T.take 1 (T.drop 1 t'):))
| otherwise =
let (x, y) = T.break (`elem` ['\\','(',')']) t'
in parens count y (front . (x:))
-- | A string of tokens is empty when it has only spaces. There
-- can't be two consecutive 'Spaces', so this takes /O(1)/ time.
empty :: [Token] -> Bool
empty [] = True
empty [Spaces _] = True
empty _ = False
-- | A line. We don't care about spaces in the middle of the
-- line. Also, we don't care about the ammount of indentation.
data Line = Line { lineIndent :: Int
, tokens :: [Text]
}
-- | Remove leading spaces and remove spaces in the middle of the
-- tokens.
removeSpaces :: [[Token]] -> [Line]
removeSpaces =
map toLine
where
toLine (Spaces i:rest) = toLine' i rest
toLine xs = toLine' 0 xs
toLine' i = Line i . mapMaybe fromToken
fromToken (Token t) = Just t
fromToken Spaces{} = Nothing
-- | Divide lines into blocks and make entity definitions.
parseLines :: PersistSettings -> [Line] -> [EntityDef]
parseLines ps lines =
fixForeignKeysAll $ toEnts lines
where
toEnts (Line indent (name:entattribs) : rest) =
let (x, y) = span ((> indent) . lineIndent) rest
in mkEntityDef ps name entattribs x : toEnts y
toEnts (Line _ []:rest) = toEnts rest
toEnts [] = []
fixForeignKeysAll :: [UnboundEntityDef] -> [EntityDef]
fixForeignKeysAll unEnts = map fixForeignKeys unEnts
where
ents = map unboundEntityDef unEnts
entLookup = M.fromList $ map (\e -> (entityHaskell e, e)) ents
fixForeignKeys :: UnboundEntityDef -> EntityDef
fixForeignKeys (UnboundEntityDef foreigns ent) =
ent { entityForeigns = map (fixForeignKey ent) foreigns }
-- check the count and the sqltypes match and update the foreignFields with the names of the primary columns
fixForeignKey :: EntityDef -> UnboundForeignDef -> ForeignDef
fixForeignKey ent (UnboundForeignDef foreignFieldTexts fdef) =
case M.lookup (foreignRefTableHaskell fdef) entLookup of
Just pent -> case entityPrimary pent of
Just pdef ->
if length foreignFieldTexts /= length (compositeFields pdef)
then lengthError pdef
else let fds_ffs = zipWith (toForeignFields pent)
foreignFieldTexts
(compositeFields pdef)
in fdef { foreignFields = map snd fds_ffs
, foreignNullable = setNull $ map fst fds_ffs
}
Nothing ->
error $ "no explicit primary key fdef="++show fdef++ " ent="++show ent
Nothing ->
error $ "could not find table " ++ show (foreignRefTableHaskell fdef)
++ " fdef=" ++ show fdef ++ " allnames="
++ show (map (unHaskellName . entityHaskell . unboundEntityDef) unEnts)
++ "\n\nents=" ++ show ents
where
setNull :: [FieldDef] -> Bool
setNull [] = error "setNull: impossible!"
setNull (fd:fds) = let nullSetting = isNull fd in
if all ((nullSetting ==) . isNull) fds then nullSetting
else error $ "foreign key columns must all be nullable or non-nullable"
++ show (map (unHaskellName . fieldHaskell) (fd:fds))
isNull = (NotNullable /=) . nullable . fieldAttrs
toForeignFields pent fieldText pfd =
case chktypes fd haskellField (entityFields pent) pfh of
Just err -> error err
Nothing -> (fd, ((haskellField, fieldDB fd), (pfh, pfdb)))
where
fd = getFd (entityFields ent) haskellField
haskellField = HaskellName fieldText
(pfh, pfdb) = (fieldHaskell pfd, fieldDB pfd)
chktypes :: FieldDef -> HaskellName -> [FieldDef] -> HaskellName -> Maybe String
chktypes ffld _fkey pflds pkey =
if fieldType ffld == fieldType pfld then Nothing
else Just $ "fieldType mismatch: " ++ show (fieldType ffld) ++ ", " ++ show (fieldType pfld)
where
pfld = getFd pflds pkey
entName = entityHaskell ent
getFd [] t = error $ "foreign key constraint for: " ++ show (unHaskellName entName)
++ " unknown column: " ++ show t
getFd (f:fs) t
| fieldHaskell f == t = f
| otherwise = getFd fs t
lengthError pdef = error $ "found " ++ show (length foreignFieldTexts) ++ " fkeys and " ++ show (length (compositeFields pdef)) ++ " pkeys: fdef=" ++ show fdef ++ " pdef=" ++ show pdef
data UnboundEntityDef = UnboundEntityDef
{ _unboundForeignDefs :: [UnboundForeignDef]
, unboundEntityDef :: EntityDef
}
lookupKeyVal :: Text -> [Text] -> Maybe Text
lookupKeyVal key = lookupPrefix $ key `mappend` "="
lookupPrefix :: Text -> [Text] -> Maybe Text
lookupPrefix prefix = msum . map (T.stripPrefix prefix)
-- | Construct an entity definition.
mkEntityDef :: PersistSettings
-> Text -- ^ name
-> [Attr] -- ^ entity attributes
-> [Line] -- ^ indented lines
-> UnboundEntityDef
mkEntityDef ps name entattribs lines =
UnboundEntityDef foreigns $
EntityDef
entName
(DBName $ getDbName ps name' entattribs)
-- idField is the user-specified Id
-- otherwise useAutoIdField
-- but, adjust it if the user specified a Primary
(setComposite primaryComposite $ fromMaybe autoIdField idField)
entattribs
cols
uniqs
[]
derives
extras
isSum
comments
where
comments = Nothing
entName = HaskellName name'
(isSum, name') =
case T.uncons name of
Just ('+', x) -> (True, x)
_ -> (False, name)
(attribs, extras) = splitExtras lines
attribPrefix = flip lookupKeyVal entattribs
idName | Just _ <- attribPrefix "id" = error "id= is deprecated, ad a field named 'Id' and use sql="
| otherwise = Nothing
(idField, primaryComposite, uniqs, foreigns) = foldl' (\(mid, mp, us, fs) attr ->
let (i, p, u, f) = takeConstraint ps name' cols attr
squish xs m = xs `mappend` maybeToList m
in (just1 mid i, just1 mp p, squish us u, squish fs f)) (Nothing, Nothing, [],[]) attribs
derives = concat $ mapMaybe takeDerives attribs
cols :: [FieldDef]
cols = mapMaybe (takeColsEx ps) attribs
autoIdField = mkAutoIdField ps entName (DBName `fmap` idName) idSqlType
idSqlType = maybe SqlInt64 (const $ SqlOther "Primary Key") primaryComposite
setComposite Nothing fd = fd
setComposite (Just c) fd = fd { fieldReference = CompositeRef c }
just1 :: (Show x) => Maybe x -> Maybe x -> Maybe x
just1 (Just x) (Just y) = error $ "expected only one of: "
`mappend` show x `mappend` " " `mappend` show y
just1 x y = x `mplus` y
mkAutoIdField :: PersistSettings -> HaskellName -> Maybe DBName -> SqlType -> FieldDef
mkAutoIdField ps entName idName idSqlType = FieldDef
{ fieldHaskell = HaskellName "Id"
-- this should be modeled as a Maybe
-- but that sucks for non-ID field
-- TODO: use a sumtype FieldDef | IdFieldDef
, fieldDB = fromMaybe (DBName $ psIdName ps) idName
, fieldType = FTTypeCon Nothing $ keyConName $ unHaskellName entName
, fieldSqlType = idSqlType
-- the primary field is actually a reference to the entity
, fieldReference = ForeignRef entName defaultReferenceTypeCon
, fieldAttrs = []
, fieldStrict = True
, fieldComments = Nothing
}
defaultReferenceTypeCon :: FieldType
defaultReferenceTypeCon = FTTypeCon (Just "Data.Int") "Int64"
keyConName :: Text -> Text
keyConName entName = entName `mappend` "Id"
splitExtras :: [Line] -> ([[Text]], M.Map Text [[Text]])
splitExtras [] = ([], M.empty)
splitExtras (Line indent [name]:rest)
| not (T.null name) && isUpper (T.head name) =
let (children, rest') = span ((> indent) . lineIndent) rest
(x, y) = splitExtras rest'
in (x, M.insert name (map tokens children) y)
splitExtras (Line _ ts:rest) =
let (x, y) = splitExtras rest
in (ts:x, y)
takeColsEx :: PersistSettings -> [Text] -> Maybe FieldDef
takeColsEx = takeCols (\ft perr -> error $ "Invalid field type " ++ show ft ++ " " ++ perr)
takeCols :: (Text -> String -> Maybe FieldDef) -> PersistSettings -> [Text] -> Maybe FieldDef
takeCols _ _ ("deriving":_) = Nothing
takeCols onErr ps (n':typ:rest)
| not (T.null n) && isLower (T.head n) =
case parseFieldType typ of
Left err -> onErr typ err
Right ft -> Just FieldDef
{ fieldHaskell = HaskellName n
, fieldDB = DBName $ getDbName ps n rest
, fieldType = ft
, fieldSqlType = SqlOther $ "SqlType unset for " `mappend` n
, fieldAttrs = rest
, fieldStrict = fromMaybe (psStrictFields ps) mstrict
, fieldReference = NoReference
, fieldComments = Nothing
}
where
(mstrict, n)
| Just x <- T.stripPrefix "!" n' = (Just True, x)
| Just x <- T.stripPrefix "~" n' = (Just False, x)
| otherwise = (Nothing, n')
takeCols _ _ _ = Nothing
getDbName :: PersistSettings -> Text -> [Text] -> Text
getDbName ps n [] = psToDBName ps n
getDbName ps n (a:as) = fromMaybe (getDbName ps n as) $ T.stripPrefix "sql=" a
takeConstraint :: PersistSettings
-> Text
-> [FieldDef]
-> [Text]
-> (Maybe FieldDef, Maybe CompositeDef, Maybe UniqueDef, Maybe UnboundForeignDef)
takeConstraint ps tableName defs (n:rest) | not (T.null n) && isUpper (T.head n) = takeConstraint'
where
takeConstraint'
| n == "Unique" = (Nothing, Nothing, Just $ takeUniq ps tableName defs rest, Nothing)
| n == "Foreign" = (Nothing, Nothing, Nothing, Just $ takeForeign ps tableName defs rest)
| n == "Primary" = (Nothing, Just $ takeComposite defs rest, Nothing, Nothing)
| n == "Id" = (Just $ takeId ps tableName (n:rest), Nothing, Nothing, Nothing)
| otherwise = (Nothing, Nothing, Just $ takeUniq ps "" defs (n:rest), Nothing) -- retain compatibility with original unique constraint
takeConstraint _ _ _ _ = (Nothing, Nothing, Nothing, Nothing)
-- TODO: this is hacky (the double takeCols, the setFieldDef stuff, and setIdName.
-- need to re-work takeCols function
takeId :: PersistSettings -> Text -> [Text] -> FieldDef
takeId ps tableName (n:rest) = fromMaybe (error "takeId: impossible!") $ setFieldDef $
takeCols (\_ _ -> addDefaultIdType) ps (field:rest `mappend` setIdName)
where
field = case T.uncons n of
Nothing -> error "takeId: empty field"
Just (f, ield) -> toLower f `T.cons` ield
addDefaultIdType = takeColsEx ps (field : keyCon : rest `mappend` setIdName)
setFieldDef = fmap (\fd ->
let refFieldType = if fieldType fd == FTTypeCon Nothing keyCon
then defaultReferenceTypeCon
else fieldType fd
in fd { fieldReference = ForeignRef (HaskellName tableName) $ refFieldType
})
keyCon = keyConName tableName
-- this will be ignored if there is already an existing sql=
-- TODO: I think there is a ! ignore syntax that would screw this up
setIdName = ["sql=" `mappend` psIdName ps]
takeId _ tableName _ = error $ "empty Id field for " `mappend` show tableName
takeComposite :: [FieldDef]
-> [Text]
-> CompositeDef
takeComposite fields pkcols
= CompositeDef
(map (getDef fields) pkcols)
attrs
where
(_, attrs) = break ("!" `T.isPrefixOf`) pkcols
getDef [] t = error $ "Unknown column in primary key constraint: " ++ show t
getDef (d:ds) t
| fieldHaskell d == HaskellName t =
if nullable (fieldAttrs d) /= NotNullable
then error $ "primary key column cannot be nullable: " ++ show t
else d
| otherwise = getDef ds t
-- Unique UppercaseConstraintName list of lowercasefields terminated
-- by ! or sql= such that a unique constraint can look like:
-- `UniqueTestNull fieldA fieldB sql=ConstraintNameInDatabase !force`
-- Here using sql= sets the name of the constraint.
takeUniq :: PersistSettings
-> Text
-> [FieldDef]
-> [Text]
-> UniqueDef
takeUniq ps tableName defs (n:rest)
| not (T.null n) && isUpper (T.head n)
= UniqueDef
(HaskellName n)
dbName
(map (HaskellName &&& getDBName defs) fields)
attrs
where
isAttr a =
"!" `T.isPrefixOf` a
isSqlName a =
"sql=" `T.isPrefixOf` a
isNonField a =
isAttr a
|| isSqlName a
(fields, nonFields) =
break isNonField rest
attrs = filter isAttr nonFields
usualDbName =
DBName $ psToDBName ps (tableName `T.append` n)
sqlName :: Maybe DBName
sqlName =
case find isSqlName nonFields of
Nothing ->
Nothing
(Just t) ->
case drop 1 $ T.splitOn "=" t of
(x : _) -> Just (DBName x)
_ -> Nothing
dbName = fromMaybe usualDbName sqlName
getDBName [] t =
error $ "Unknown column in unique constraint: " ++ show t
++ " " ++ show defs ++ show n ++ " " ++ show attrs
getDBName (d:ds) t
| fieldHaskell d == HaskellName t = fieldDB d
| otherwise = getDBName ds t
takeUniq _ tableName _ xs =
error $ "invalid unique constraint on table["
++ show tableName
++ "] expecting an uppercase constraint name xs="
++ show xs
data UnboundForeignDef = UnboundForeignDef
{ _unboundFields :: [Text] -- ^ fields in other entity
, _unboundForeignDef :: ForeignDef
}
takeForeign :: PersistSettings
-> Text
-> [FieldDef]
-> [Text]
-> UnboundForeignDef
takeForeign ps tableName _defs (refTableName:n:rest)
| not (T.null n) && isLower (T.head n)
= UnboundForeignDef fields $ ForeignDef
(HaskellName refTableName)
(DBName $ psToDBName ps refTableName)
(HaskellName n)
(DBName $ psToDBName ps (tableName `T.append` n))
[]
attrs
False
where
(fields,attrs) = break ("!" `T.isPrefixOf`) rest
takeForeign _ tableName _ xs = error $ "invalid foreign key constraint on table[" ++ show tableName ++ "] expecting a lower case constraint name xs=" ++ show xs
takeDerives :: [Text] -> Maybe [Text]
takeDerives ("deriving":rest) = Just rest
takeDerives _ = Nothing
nullable :: [Text] -> IsNullable
nullable s
| "Maybe" `elem` s = Nullable ByMaybeAttr
| "nullable" `elem` s = Nullable ByNullableAttr
| otherwise = NotNullable
|
gbwey/persistent
|
persistent/Database/Persist/Quasi.hs
|
mit
| 21,105 | 0 | 20 | 6,506 | 6,565 | 3,387 | 3,178 | 431 | 13 |
module FrontEnd.Infix (
buildFixityMap, infixHsModule, FixityMap,size,
infixStatement, restrictFixityMap, dumpFixityMap) where
import Data.Binary
import Data.Monoid
import qualified Data.Map as Map
import FrontEnd.HsSyn
import FrontEnd.Lex.ParseMonad
import FrontEnd.Syn.Traverse
import FrontEnd.Warning
import Name.Names
import Support.MapBinaryInstance
import Util.HasSize
import qualified FrontEnd.Lex.Fixity as F
type FixityInfo = (Int, HsAssoc)
type SymbolMap = Map.Map Name FixityInfo
newtype FixityMap = FixityMap SymbolMap
deriving(Monoid,HasSize)
instance Binary FixityMap where
put (FixityMap ts) = putMap ts
get = fmap FixityMap getMap
restrictFixityMap :: (Name -> Bool) -> FixityMap -> FixityMap
restrictFixityMap f (FixityMap fm) = FixityMap (Map.filterWithKey (\k _ -> f k) fm)
dumpFixityMap :: FixityMap -> IO ()
dumpFixityMap (FixityMap ts) = do
mapM_ print (Map.toList ts)
infixHsModule :: FixityMap -> HsModule -> HsModule
infixHsModule (FixityMap ism) m = domod m where
(expShuntSpec,pexpShuntSpec) = (expShuntSpec,pexpShuntSpec) where
pexpShuntSpec = expShuntSpec {
F.operator = paren_operator, F.trailingOps }
expShuntSpec = F.shuntSpec {
F.lookupToken,
F.application ,
F.operator,
F.lookupUnary }
lookupToken (HsBackTick bt) = backtick bt
lookupToken (HsAsPat x v) = mr (HsAsPat x) v
lookupToken (HsLocatedExp (Located sl v)) = mr (HsLocatedExp . Located sl) v
lookupToken t = return (Left t)
lookupUnary t = return Nothing
application e1 e2 = return $ HsApp e1 (hsParen e2)
operator (HsBackTick t) as = operator t as
operator (HsVar v) [e] | v == v_sub = return $ HsNegApp (hsParen e)
operator t as = return $ foldl HsApp t (map hsParen as)
paren_operator (HsBackTick t) as = paren_operator t as
paren_operator (HsVar v) [e] | v == v_sub = return $ HsNegApp (hsParen e)
paren_operator t [e] = return $ HsRightSection (hsParen e) t
paren_operator t as = operator t as
trailingOps e (HsBackTick t) = trailingOps e t
trailingOps e t = return $ HsLeftSection t (hsParen e)
backtick bt = f bt where
f (HsVar v) = g v
f ~(HsCon v) = g v
g v = return $ case Map.lookup v ism of
Just (n,HsAssocLeft) -> Right (F.L,n)
Just (n,HsAssocRight) -> Right (F.R,n)
Just (n,HsAssocNone) -> Right (F.N,n)
Just (n,HsAssocPrefix) -> Right (F.Prefix,n)
Just (n,HsAssocPrefixy) -> Right (F.Prefixy,n)
Nothing -> Right (F.L,9)
mr x v = do
n <- lookupToken v
case n of
Left v -> return $ Left $ x v
Right {} -> return n
patShuntSpec = F.shuntSpec {
F.lookupToken,
F.application,
F.operator,
F.lookupUnary } where
lookupToken (HsPatBackTick bt) = backtick bt
lookupToken t = return (Left t)
lookupUnary t = return Nothing
application (HsPApp t es) y = return $ HsPApp t (es ++ [y])
application x y = do
parseErrorK $ "weird application: " ++ show (x,y)
return HsPWildCard
operator ~(HsPatBackTick t) as = f t as where
f (HsPVar v) [e] | v == u_Bang = do sl <- getSrcSpan; return $ HsPBangPat (Located sl e)
f (HsPVar v) [e] | v == u_Twiddle = do sl <- getSrcSpan; return $ HsPIrrPat (Located sl e)
f (HsPVar v) [HsPVar ap, e] | v == u_At = do sl <- getSrcSpan; return $ HsPAsPat ap e
f (HsPVar v) [HsPWildCard, e] | v == u_At = do return e
f (HsPVar v) [e] | originalUnqualifiedName v == vu_sub = return $ HsPNeg e
f (HsPApp t xs) y = return $ HsPApp t (xs ++ y)
f x@(HsPVar v) y = do
parseErrorK $ "weird operator: " ++ show (v,originalUnqualifiedName v,x,y)
return HsPWildCard
f x y = do
parseErrorK $ "weird operator: " ++ show (x,y)
return HsPWildCard
backtick bt = f bt where
f (HsPVar v) | v == u_Bang = return (Right (F.Prefix,11))
f (HsPVar v) | v == u_Twiddle = return (Right (F.Prefix,11))
f (HsPVar v) | v == u_At = return (Right (F.R,12))
f (HsPVar v) = g v
f (HsPApp v []) = g v
f z = parseErrorK $ "infix.f: " ++ show z
g v = return $ case Map.lookup v ism of
Just (n,HsAssocLeft) -> Right (F.L,n)
Just (n,HsAssocRight) -> Right (F.R,n)
Just (n,HsAssocNone) -> Right (F.N,n)
Just (n,HsAssocPrefix) -> Right (F.Prefix,n)
Just (n,HsAssocPrefixy) -> Right (F.Prefixy,n)
Nothing -> Right (F.L,9)
domod m = case runP (traverseHsOps ops m) (hsModuleOpt m) of
(ws,~(Just v)) -> if null ws then v else error $ unlines (map show ws)
ops = (hsOpsDefault ops) { opHsExp, opHsPat } where
opHsExp (HsParen (HsWords es)) = F.shunt pexpShuntSpec es >>= applyHsOps ops
opHsExp (HsWords es) = F.shunt expShuntSpec es >>= applyHsOps ops
opHsExp e@(HsApp HsTuple {} _) = do
addWarn UnexpectedType $ "Attempt to apply a tuple like a function in expression"
traverseHsOps ops e
opHsExp e@(HsApp HsUnboxedTuple {} _) = do
addWarn UnexpectedType $ "Attempt to apply an unboxed tuple like a function in expression"
traverseHsOps ops e
opHsExp e@(HsApp HsList {} _) = do
addWarn UnexpectedType $ "Attempt to apply literal list like a function in expression"
traverseHsOps ops e
opHsExp op@HsApp {} | (ce,ps) <- fromHsApp op = do
let cont = do
ps <- mapM opHsExp (ce:ps)
return $ foldl1 HsApp ps
err s = addWarn UnexpectedType s >> cont
case ce of
HsCon c | Just (isBoxed,level,n) <- fromName_Tuple c, level == termLevel -> case length ps of
lps | lps > n -> err "Attempt to apply a tuple like a function in expression"
| lps < n -> cont
| otherwise -> opHsExp $ if isBoxed then HsTuple ps else HsUnboxedTuple ps
HsList {} -> err "Attempt to apply literal list like a function in expression"
HsTuple {} -> err "Attempt to apply a tuple like a function in expression"
HsUnboxedTuple {} -> err "Attempt to apply an unboxed tuple like a function in expression"
_ -> cont
opHsExp (HsBackTick t) = parseErrorK "unexpected binary operator."
opHsExp e = traverseHsOps ops e
opHsPat (HsPatWords ws) = F.shunt patShuntSpec ws >>= opHsPat
opHsPat op@(HsPApp n ps) | Just (isBoxed,level,n) <- fromName_Tuple n, level == termLevel = case length ps of
lps | lps > n -> do
addWarn UnexpectedType $ "Applying tuple to too many arguments in pattern"
traverseHsOps ops op
| lps < n -> do
addWarn UnexpectedType $ "Applying tuple constructor to not enough arguments in pattern"
traverseHsOps ops op
| otherwise -> opHsPat $ if isBoxed then HsPTuple ps else HsPUnboxedTuple ps
opHsPat p = traverseHsOps ops p
fromHsApp t = f t [] where
f (HsApp a b) rs = f a (b:rs)
f t rs = (t,rs)
buildFixityMap :: [HsDecl] -> FixityMap
buildFixityMap ds = FixityMap (Map.unions $ map f ds) where
f (HsInfixDecl _ assoc strength names) = Map.fromList $ zip names $ repeat (strength,assoc)
f _ = Map.empty
-- TODO: interactive
infixStatement :: FixityMap -> HsStmt -> HsStmt
infixStatement (FixityMap ism) m = m
--infixStatement (FixityMap ism) m = processStmt ism m
|
hvr/jhc
|
src/FrontEnd/Infix.hs
|
mit
| 7,994 | 0 | 22 | 2,577 | 2,876 | 1,428 | 1,448 | -1 | -1 |
import System.IO (hFlush, stdout)
import Control.Monad.Except (runExceptT)
import Readline (readline, load_history)
import Types
import Reader (read_str)
import Printer (_pr_str)
-- read
mal_read :: String -> IOThrows MalVal
mal_read str = read_str str
-- eval
eval :: MalVal -> String -> MalVal
eval ast env = ast
-- print
mal_print :: MalVal -> String
mal_print exp = show exp
-- repl
rep :: String -> IOThrows String
rep line = do
ast <- mal_read line
return $ mal_print (eval ast "")
repl_loop :: IO ()
repl_loop = do
line <- readline "user> "
case line of
Nothing -> return ()
Just "" -> repl_loop
Just str -> do
res <- runExceptT $ rep str
out <- case res of
Left (StringError str) -> return $ "Error: " ++ str
Left (MalValError mv) -> return $ "Error: " ++ (show mv)
Right val -> return val
putStrLn out
hFlush stdout
repl_loop
main = do
load_history
repl_loop
|
0gajun/mal
|
haskell/step1_read_print.hs
|
mpl-2.0
| 1,031 | 1 | 18 | 317 | 359 | 174 | 185 | 34 | 5 |
-- train.hs
-- Compiles to executable.
-- We're passed (1) the path to a directory and (2) an integer.
-- Saves a hyperplane (dim = 2nd arg) that is the linear regression
-- of all of the images in the directory to hyperplane.txt in the same
-- directory.
import PCA
import ImageToVector
import System.Directory
import System.IO (hFlush, stdout)
import System.Environment
import Data.Packed.Matrix
import Data.Packed.Vector
main :: IO ()
main = do
(arg1:arg2:rest) <- getArgs
let dir = arg1
numsv = read arg2
takeImgs = case rest of
[] -> id :: [a] -> [a]
arg3:_ -> take (read arg3)
putStr $ concat
[ "Dir: ", dir
, " \tsv: ", show numsv,", \t"]
hFlush stdout
imageFiles <- getDirectoryContents dir
maybeImages <- loadImagesToVectors 20 20
$ map ((dir ++ "/") ++) imageFiles
let rows = takeImgs [a | Just a <- maybeImages]
putStr $ concat
[ show . length $ rows, " images. "]
hFlush stdout
let h = linRegression numsv $ fromRows rows
saveHyperplane (dir++"/hyperplane.txt") h
putStrLn "Done!"
|
IsToomersCornerBeingRolledRightNow/principalComponentAnalysisViaSingularValueDecomposition
|
train.hs
|
mit
| 1,100 | 1 | 15 | 275 | 322 | 163 | 159 | 29 | 2 |
{-# LANGUAGE LambdaCase #-}
module TC.Unify where
import Control.Applicative
import Control.Monad
import Control.Monad.Except
import qualified Data.Map as M
import Data.List (intersect)
import Source
import TC.Util
type Subst = M.Map Name
nullSubst :: Subst t
nullSubst = M.empty
class HasNames t where
named :: Name -> t
occurs :: Name -> t -> Bool
apply :: Subst t -> t -> t
instance HasNames Kind where
named = KVar
occurs n = \case
KVar m -> n == m
Star -> False
KFun l r -> occurs n l || occurs n r
apply s = go
where go (KFun l r) = go l `KFun` go r
go (KVar v) = maybe (KVar v) id $ M.lookup v s
go Star = Star
instance HasNames Type where
named = TVar Nothing
occurs n = \case
TVar _ m -> n == m
TApp l r -> occurs n l || occurs n r
_ -> False
apply s = go
where go (TVar k v) = maybe (TVar k v) id $ M.lookup v s
go (TApp l r) = go l `TApp` go r
go t = t
add :: (HasNames t, Eq t) => Name -> t -> Subst t -> TCM (Subst t)
add n t | named n == t = return . id
| occurs n t = const . throwError $ OccursFail n
| otherwise = return . M.insert n t
mergeApply :: HasNames t => Subst t -> Subst t -> Subst t
mergeApply s1 s2 = M.map (apply s1) s2 `M.union` s1
mergeAgree :: (Eq t, HasNames t) => Subst t -> Subst t -> TCM (Subst t)
mergeAgree s1 s2 = do
checkAgrees (M.keys s1 `intersect` M.keys s2)
return (s1 `M.union` s2)
where checkAgrees nms = forM_ nms $ \n -> do
let t = apply s1 (named n)
t' = apply s2 (named n)
when (t /= t') . throwError $ CannotMerge -- Todo, this should show t
kunify :: Kind -> Kind -> TCM (Subst Kind)
kunify k1 k2 = case (k1, k2) of
(KVar n, t) -> add n t nullSubst
(t, KVar n) -> add n t nullSubst
(KFun l r, KFun l' r') -> mergeApply <$> kunify l r <*> kunify l' r'
(Star, Star) -> return nullSubst
(_, _) -> throwError CannotUnify
tunify :: Type -> Type -> TCM (Subst Type, Subst Kind)
tunify t1 t2 = do
case (t1, t2) of
(TVar _ n, t) -> (,) <$> add n t nullSubst <*> kindCheck t1 t2
(t, TVar _ n) -> (,) <$> add n t nullSubst <*> kindCheck t1 t2
(TApp l r, TApp l' r') -> mergeBoth <$> tunify l r <*> tunify l' r'
(TCon _ n, TCon _ n') ->
if n == n' -- Special case so we don't check kind equality with ==
then (,) nullSubst <$> kindCheck t1 t2
else throwError CannotUnify
(_, _) ->
if t1 == t2
then (,) nullSubst <$> kindCheck t1 t2
else throwError CannotUnify
where kindCheck t1 t2 = kunify (kindOf t1) (kindOf t2)
mergeBoth (l, r) (l', r') = (mergeApply l l', mergeApply r r')
|
jozefg/hi
|
src/TC/Unify.hs
|
mit
| 2,724 | 0 | 16 | 828 | 1,269 | 635 | 634 | 73 | 7 |
module P13 where
import P11(Item(..))
-- | Modified run-length encoding
-- >>> encodeModified "aaaabccaadeeee"
-- [Multiple 4 'a',Single 'b',Multiple 2 'c',Multiple 2 'a',Single 'd',Multiple 4 'e']
encodeModified :: Eq a => [a] -> [Item a]
encodeModified = foldr func [] where
func x [] = [Single x]
func x list@((Single y):xs) =
if x == y then (Multiple 2 x):xs else (Single x):list
func x list@((Multiple n y):xs) =
if x == y then (Multiple (n + 1) x):xs else (Single x):list
|
briancavalier/h99
|
p13.hs
|
mit
| 504 | 0 | 12 | 108 | 205 | 112 | 93 | 9 | 5 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.WebKitCSSRegionRule
(js_getCssRules, getCssRules, WebKitCSSRegionRule,
castToWebKitCSSRegionRule, gTypeWebKitCSSRegionRule)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"cssRules\"]" js_getCssRules
:: WebKitCSSRegionRule -> IO (Nullable CSSRuleList)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSRegionRule.cssRules Mozilla WebKitCSSRegionRule.cssRules documentation>
getCssRules ::
(MonadIO m) => WebKitCSSRegionRule -> m (Maybe CSSRuleList)
getCssRules self
= liftIO (nullableToMaybe <$> (js_getCssRules (self)))
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/WebKitCSSRegionRule.hs
|
mit
| 1,434 | 6 | 10 | 165 | 371 | 236 | 135 | 24 | 1 |
----------------------------------------------------------------
--
-- | aartifact
-- http://www.aartifact.org/
--
-- @src\/Validate.hs@
--
-- Functions for turning a list of statements (a source
-- document) into an output representing its validation
-- status.
--
----------------------------------------------------------------
--
module Validation (rawCxt, validate, validateBasic) where
import IOPrintFormat
import IOSource
import ExpConst (Const(..))
import Exp
import Context
import ValidationComp (Verification(..))
import ValidationSearch (verify)
----------------------------------------------------------------
-- | Process a list of statements while maintaining a context,
-- and validate expressions with respect to this context.
validate :: Context -> [Stmt] -> ([Stmt], Stat)
validate cxtraw ss = (\(ss,(_,_,_,st))->(ss,st)) $ execs cxtraw ss
validateBasic cxtraw ss = (\(ss,(_,_,_,st))->(ss,st)) $ execs (setBasic cxtraw) ss
rawCxt stmts = state0 $ concat $ map (\x->case x of ExpStmt _ (e,_)->[e];_->[]) stmts
exec :: Context -> Stmt -> ([Stmt], Context)
exec state (s@(Text _)) = ([s], state)
exec state (s@(SyntaxError _)) = ([s], state)
exec state (Intro src Variable vs) = ([Intro (SrcOk src) Variable vs], updVars vs state)
exec state (Intro src ty vs) = ([Intro (SrcOk src) ty vs], updConsts vs state)
exec state (ExpStmt Assert (e,src)) = ([ExpStmt Assert (e',src')], state'')
where state'' = updStat stat' $ if isErr src' then considerCxt e' state' else assumeCxt e' state'
stat' = statSrc src'
src' = vArt state' e' src
(e',state') = freshExpVars (normOps e) state
exec state (ExpStmt Assume (e,src)) = ([ExpStmt Assume (e',src')], state'')
where state'' = if isErr src' then considerCxt e' state' else assumeCxt e' state'
src' = vAsu state' e' src
(e',state') = freshExpVars (normOps e) state
exec state (ExpStmt Consider (e,src)) = ([ExpStmt Consider (e',src')], state'')
where state'' = if isErr src' then state' else addLawCxt state' e
src' = vAsu state' e' src
(e',state') = freshExpVars (normOps e) state
exec state (Include n ss) = (map (mkIncludeWrap n) rs, state')
where (rs, state') = execs state ss
exec state stmt = ([stmt],state)
execs :: Context -> [Stmt] -> ([Stmt], Context)
execs state [] = ([], state)
execs state (s:ss) = (vs++vs', state'') where
(vs , state' ) = exec state s
(vs', state'') = execs state' ss
----------------------------------------------------------------
-- | Analysis and verification of expressions with feedback in
-- the form of source annotations/tags.
vAsu :: Context -> Exp -> Src -> Src
vAsu s e (SrcIg [l,src,r]) = SrcIg [l,vAsu s e src,r]
vAsu s (Forall vs (App (C Imp) (T[e1,e2]))) (SrcL ts [s1,s2]) = SrcL ts [vAsu (updVars vs s) e1 s1, vAsu (updVars vs s) e2 s2]
vAsu s (Exists vs (App (C And) (T[e1,e2]))) (SrcL ts [s1,s2]) = SrcL ts [vAsu (updVars vs s) e1 s1, vAsu (updVars vs s) e2 s2]
vAsu s (Bind Considering vs (T[e1,e2])) (SrcL ts [s1,s2]) = SrcL ts [vAsu (updVars vs s) e1 s1, vAsu (updVars vs s) e2 s2]
vAsu s (App (C Not) e) (SrcL ts [src]) = SrcL ts [vAsu s e src]
vAsu s (App (C And) (T[e1,e2])) (SrcL ts [s1,s2]) = SrcL ts [vAsu s e1 s1, vAsu s e2 s2]
vAsu s (App (C Or) (T[e1,e2])) (SrcL ts [s1,s2]) = SrcL ts [vAsu s e1 s1, vAsu s e2 s2]
vAsu s (App (C Imp) (T[e1,e2])) (SrcL ts [s1,s2]) = SrcL ts [vAsu s e1 s1, vAsu s e2 s2]
vAsu s (App (C Iff) (T[e1,e2])) (SrcL ts [s1,s2]) = SrcL ts [vAsu s e1 s1, vAsu s e2 s2]
vAsu s e src = if length fvs == 0 then SrcOk src else SrcErr src (ErrUnbound (map fst fvs))
where fvs = fv (varsCxt s) e
vArt :: Context -> Exp -> Src -> Src
vArt s e (SrcIg [l,src,r]) = SrcIg [l,vArt s e src,r]
vArt s (Forall vs (App (C Imp) (T[e1,e2]))) (SrcL ts [s1,s2]) =
SrcL ts [vAsu (updVars vs s) e1 s1, vArt (assumeCxt e1 (updVars vs s)) e2 s2]
--vArt s (Exists vs (App (C And) (T[e1,e2]))) (SrcL ts [s1,s2]) =
-- SrcL ts [vArt (updVars vs s) e1 s1, vArt (assumeCxt e1 (updVars vs s)) e2 s2]
vArt s (App (C And) (T[e1,e2])) (SrcL ts [s1,s2]) = SrcL ts [vArt s e1 s1, vArt (assumeCxt e1 s) e2 s2]
--vArt s (App (C Or) (T[e1,e2])) (SrcL ts [s1,s2]) = SrcL ts [vArt s e1 s1, vArt s e2 s2]
vArt s (App (C Imp) (T[e1,e2])) (SrcL ts [s1,s2]) = SrcL ts [vAsu s e1 s1, vArt (assumeCxt e1 s) e2 s2]
vArt s (App (C Iff) (T[e1,e2])) (SrcL ts [s1,s2]) = SrcL ts [vArt (assumeCxt e2 s) e1 s1, vArt (assumeCxt e1 s) e2 s2]
vArt s (App (C Not) e) (SrcL ts [src]) = SrcL ts [vArt s e src]
vArt s (App (C MakeReport) (T es)) src = SrcReport (reportCxt es (considerCxt (T es) s)) src
vArt s e src =
let fvs = fv (varsCxt s) e
in if length fvs > 0 then SrcErr src (ErrUnbound (map fst fvs)) else
case verify_or_contra s e of
Verifiable Contradiction -> SrcStat (statCxt s) $ SrcErr src (ErrContra)
Verifiable (B True) -> SrcStat (statCxt s) $ SrcOk src --([R str $ Verifiable s (B True)], assumeCxt e state')
r -> SrcStat (statCxt s) $ SrcErr src (ErrVer "") --([R (str) r], state')
verify_or_contra s e =
case verify (assumeCxt e s) (C Contradiction) of
Verifiable (B True) -> Verifiable Contradiction
_ -> verify s e
-- ++":"++(show (evalExp state e)) -- ++ show (getR state)
-- eof
|
aartifact/aartifact-verifier
|
src/Validation.hs
|
mit
| 5,277 | 0 | 14 | 1,079 | 2,527 | 1,340 | 1,187 | 70 | 4 |
{-# LANGUAGE TypeSynonymInstances #-}
module Oden.Core where
import Oden.Core.Operator
import Oden.Identifier
import Oden.Metadata
import Oden.QualifiedName (QualifiedName(..))
import Oden.SourceInfo
import qualified Oden.Type.Polymorphic as Poly
data NameBinding = NameBinding (Metadata SourceInfo) Identifier
deriving (Show, Eq, Ord)
data FieldInitializer t = FieldInitializer (Metadata SourceInfo) Identifier (Expr t)
deriving (Show, Eq, Ord)
data Expr t = Symbol (Metadata SourceInfo) Identifier t
| Subscript (Metadata SourceInfo) (Expr t) (Expr t) t
| Subslice (Metadata SourceInfo) (Expr t) (Range t) t
| UnaryOp (Metadata SourceInfo) UnaryOperator (Expr t) t
| BinaryOp (Metadata SourceInfo) BinaryOperator (Expr t) (Expr t) t
| Application (Metadata SourceInfo) (Expr t) (Expr t) t
| NoArgApplication (Metadata SourceInfo) (Expr t) t
| ForeignFnApplication (Metadata SourceInfo) (Expr t) [Expr t] t
| Fn (Metadata SourceInfo) NameBinding (Expr t) t
| NoArgFn (Metadata SourceInfo) (Expr t) t
| Let (Metadata SourceInfo) NameBinding (Expr t) (Expr t) t
| Literal (Metadata SourceInfo) Literal t
| Tuple (Metadata SourceInfo) (Expr t) (Expr t) [Expr t] t
| If (Metadata SourceInfo) (Expr t) (Expr t) (Expr t) t
| Slice (Metadata SourceInfo) [Expr t] t
| Block (Metadata SourceInfo) [Expr t] t
| RecordInitializer (Metadata SourceInfo) t [FieldInitializer t]
| RecordFieldAccess (Metadata SourceInfo) (Expr t) Identifier t
| PackageMemberAccess (Metadata SourceInfo) Identifier Identifier t
deriving (Show, Eq, Ord)
instance HasSourceInfo (Expr t) where
getSourceInfo (Symbol (Metadata si) _ _) = si
getSourceInfo (Subscript (Metadata si) _ _ _) = si
getSourceInfo (Subslice (Metadata si) _ _ _) = si
getSourceInfo (UnaryOp (Metadata si) _ _ _) = si
getSourceInfo (BinaryOp (Metadata si) _ _ _ _) = si
getSourceInfo (Application (Metadata si) _ _ _) = si
getSourceInfo (NoArgApplication (Metadata si) _ _) = si
getSourceInfo (ForeignFnApplication (Metadata si) _ _ _) = si
getSourceInfo (Fn (Metadata si) _ _ _) = si
getSourceInfo (NoArgFn (Metadata si) _ _) = si
getSourceInfo (Let (Metadata si) _ _ _ _) = si
getSourceInfo (Literal (Metadata si) _ _) = si
getSourceInfo (If (Metadata si) _ _ _ _) = si
getSourceInfo (Slice (Metadata si) _ _) = si
getSourceInfo (Tuple (Metadata si) _ _ _ _) = si
getSourceInfo (Block (Metadata si) _ _) = si
getSourceInfo (RecordInitializer (Metadata si) _ _) = si
getSourceInfo (RecordFieldAccess (Metadata si) _ _ _) = si
getSourceInfo (PackageMemberAccess (Metadata si) _ _ _) = si
setSourceInfo si (Symbol _ i t) = Symbol (Metadata si) i t
setSourceInfo si (Subscript _ s i t) = Subscript (Metadata si) s i t
setSourceInfo si (Subslice _ s r t) = Subslice (Metadata si) s r t
setSourceInfo si (UnaryOp _ o r t) = UnaryOp (Metadata si) o r t
setSourceInfo si (BinaryOp _ p l r t) = BinaryOp (Metadata si) p l r t
setSourceInfo si (Application _ f a t) = Application (Metadata si) f a t
setSourceInfo si (NoArgApplication _ f t) = NoArgApplication (Metadata si) f t
setSourceInfo si (ForeignFnApplication _ f a t) = ForeignFnApplication (Metadata si) f a t
setSourceInfo si (Fn _ n b t) = Fn (Metadata si) n b t
setSourceInfo si (NoArgFn _ b t) = NoArgFn (Metadata si) b t
setSourceInfo si (Let _ n v b t) = Let (Metadata si) n v b t
setSourceInfo si (Literal _ l t) = Literal (Metadata si) l t
setSourceInfo si (If _ c t e t') = If (Metadata si) c t e t'
setSourceInfo si (Slice _ e t) = Slice (Metadata si) e t
setSourceInfo si (Tuple _ f s r t) = Tuple (Metadata si) f s r t
setSourceInfo si (Block _ e t) = Block (Metadata si) e t
setSourceInfo si (RecordInitializer _ t vs) = RecordInitializer (Metadata si) t vs
setSourceInfo si (RecordFieldAccess _ expr name t) = RecordFieldAccess (Metadata si) expr name t
setSourceInfo si (PackageMemberAccess _ pkgAlias name t) = PackageMemberAccess (Metadata si) pkgAlias name t
typeOf :: Expr t -> t
typeOf (Symbol _ _ t) = t
typeOf (Subscript _ _ _ t) = t
typeOf (Subslice _ _ _ t) = t
typeOf (UnaryOp _ _ _ t) = t
typeOf (BinaryOp _ _ _ _ t) = t
typeOf (Application _ _ _ t) = t
typeOf (NoArgApplication _ _ t) = t
typeOf (ForeignFnApplication _ _ _ t) = t
typeOf (Fn _ _ _ t) = t
typeOf (NoArgFn _ _ t) = t
typeOf (Let _ _ _ _ t) = t
typeOf (Literal _ _ t) = t
typeOf (If _ _ _ _ t) = t
typeOf (Tuple _ _ _ _ t) = t
typeOf (Slice _ _ t) = t
typeOf (Block _ _ t) = t
typeOf (RecordInitializer _ t _) = t
typeOf (RecordFieldAccess _ _ _ t) = t
typeOf (PackageMemberAccess _ _ _ t) = t
data Literal = Int Integer
| Bool Bool
| String String
| Unit
deriving (Show, Eq, Ord)
data Range t = Range (Expr t) (Expr t)
| RangeTo (Expr t)
| RangeFrom (Expr t)
deriving (Show, Eq, Ord)
type CanonicalExpr = (Poly.Scheme, Expr Poly.Type)
data Definition = Definition (Metadata SourceInfo) Identifier CanonicalExpr
| ForeignDefinition (Metadata SourceInfo) Identifier Poly.Scheme
| TypeDefinition (Metadata SourceInfo) QualifiedName [NameBinding] Poly.Type
deriving (Show, Eq, Ord)
type PackageName = [String]
data PackageDeclaration = PackageDeclaration (Metadata SourceInfo) PackageName
deriving (Show, Eq, Ord)
data ImportedPackage = ImportedPackage (Metadata SourceInfo) Identifier Package
deriving (Show, Eq, Ord)
data Package = Package PackageDeclaration [ImportedPackage] [Definition]
deriving (Show, Eq, Ord)
|
AlbinTheander/oden
|
src/Oden/Core.hs
|
mit
| 6,441 | 0 | 10 | 2,052 | 2,495 | 1,274 | 1,221 | 112 | 1 |
setList (a:b) 0 value=
value:b
setList (a:b) n value=
a:setList b (n-1) value
delete :: [a]->Int->[a]
delete xs n =
let (ys,zs) = splitAt n xs in ys ++ (tail zs)
data DoodleTimeSlot timeType = DoodleTimeSlot
{ begin :: timeType
, end :: timeType
, names :: [String]
}
addName::String -> DoodleTimeSlot t -> DoodleTimeSlot t
addName name (DoodleTimeSlot startTime endTime names) = DoodleTimeSlot startTime endTime (name:names)
|
salenaer/functionProject
|
try.hs
|
mit
| 559 | 0 | 9 | 200 | 207 | 109 | 98 | 13 | 1 |
-- SYNTAX TEST "source.haskell"
{-# LANGUAGE GADTs #-}
module Test where
-- it understands GADT syntax
data Term a where
-- ^^^^^ meta.declaration.type.data keyword.other
-- ^ meta.declaration.type.data meta.type-signature variable.other.generic-type
-- ^^^^ meta.declaration.type.data meta.type-signature entity.name.type
-- <- meta.declaration.type.data keyword.other.data
LitI :: Int -> Term Int
-- ^^^ meta.type-signature entity.name.type support.class.prelude.Int
-- ^^^^ meta.type-signature entity.name.type
-- ^^ meta.type-signature keyword.other.arrow
-- ^^^ meta.type-signature entity.name.type support.class.prelude.Int
-- ^^^^ entity.name.tag
LitS :: String -> Term String
-- ^^^^^^ meta.type-signature entity.name.type support.class.prelude.String
-- ^^^^ meta.type-signature entity.name.type
-- ^^ meta.type-signature keyword.other.arrow
-- ^^^^^^ meta.type-signature entity.name.type support.class.prelude.String
-- ^^^^ entity.name.tag
f :: a
f = undefined
-- >> =source.haskell
|
atom-haskell/language-haskell
|
spec/fixture/gadt.hs
|
mit
| 1,155 | 0 | 7 | 262 | 61 | 43 | 18 | 7 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module WaiAppStatic.Types
( -- * Pieces
Piece
, toPiece
, fromPiece
, unsafeToPiece
, Pieces
, toPieces
-- * Caching
, MaxAge (..)
-- * File\/folder serving
, FolderName
, Folder (..)
, File (..)
, LookupResult (..)
, Listing
-- * Settings
, StaticSettings (..)
) where
import Data.Text (Text)
import qualified Network.HTTP.Types as H
import qualified Network.Wai as W
import Data.ByteString (ByteString)
import System.Posix.Types (EpochTime)
import qualified Data.Text as T
import Blaze.ByteString.Builder (Builder)
import Network.Mime (MimeType)
-- | An individual component of a path, or of a filepath.
--
-- This is the core type used by wai-app-static for doing lookups. It provides
-- a smart constructor to avoid the possibility of constructing unsafe path
-- segments (though @unsafeToPiece@ can get around that as necessary).
--
-- Individual file lookup backends must know how to convert from a @Piece@ to
-- their storage system.
newtype Piece = Piece { fromPiece :: Text }
deriving (Show, Eq, Ord)
-- | Smart constructor for a @Piece@. Won\'t allow unsafe components, such as
-- pieces beginning with a period or containing a slash. This /will/, however,
-- allow null pieces.
toPiece :: Text -> Maybe Piece
toPiece t
| T.null t = Just $ Piece t
| T.head t == '.' = Nothing
| T.any (== '/') t = Nothing
| otherwise = Just $ Piece t
-- | Construct a @Piece@ without input validation.
unsafeToPiece :: Text -> Piece
unsafeToPiece = Piece
-- | Call @toPiece@ on a list.
--
-- > toPieces = mapM toPiece
toPieces :: [Text] -> Maybe Pieces
toPieces = mapM toPiece
-- | Request coming from a user. Corresponds to @pathInfo@.
type Pieces = [Piece]
-- | Values for the max-age component of the cache-control response header.
data MaxAge = NoMaxAge -- ^ no cache-control set
| MaxAgeSeconds Int -- ^ set to the given number of seconds
| MaxAgeForever -- ^ essentially infinite caching; in reality, probably one year
-- | Just the name of a folder.
type FolderName = Piece
-- | Represent contents of a single folder, which can be itself either a file
-- or a folder.
data Folder = Folder
{ folderContents :: [Either FolderName File]
}
-- | Information on an individual file.
data File = File
{ -- | Size of file in bytes
fileGetSize :: Int
-- | How to construct a WAI response for this file. Some files are stored
-- on the filesystem and can use @ResponseFile@, while others are stored
-- in memory and should use @ResponseBuilder@.
, fileToResponse :: H.Status -> H.ResponseHeaders -> W.Response
-- | Last component of the filename.
, fileName :: Piece
-- | Calculate a hash of the contents of this file, such as for etag.
, fileGetHash :: IO (Maybe ByteString)
-- | Last modified time, used for both display in listings and if-modified-since.
, fileGetModified :: Maybe EpochTime
}
-- | Result of looking up a file in some storage backend.
--
-- The lookup is either a file or folder, or does not exist.
data LookupResult = LRFile File
| LRFolder Folder
| LRNotFound
-- | How to construct a directory listing page for the given request path and
-- the resulting folder.
type Listing = Pieces -> Folder -> IO Builder
-- | All of the settings available to users for tweaking wai-app-static.
--
-- Note that you should use the settings type approach for modifying values.
-- See <http://www.yesodweb.com/book/settings-types> for more information.
data StaticSettings = StaticSettings
{
-- | Lookup a single file or folder. This is how you can control storage
-- backend (filesystem, embedded, etc) and where to lookup.
ssLookupFile :: Pieces -> IO LookupResult
-- | Determine the mime type of the given file. Note that this function
-- lives in @IO@ in case you want to perform more complicated mimetype
-- analysis, such as via the @file@ utility.
, ssGetMimeType :: File -> IO MimeType
-- | Ordered list of filenames to be used for indices. If the user
-- requests a folder, and a file with the given name is found in that
-- folder, that file is served. This supercedes any directory listing.
, ssIndices :: [Piece]
-- | How to perform a directory listing. Optional. Will be used when the
-- user requested a folder.
, ssListing :: Maybe Listing
-- | Value to provide for max age in the cache-control.
, ssMaxAge :: MaxAge
-- | Given a requested path and a new destination, construct a string
-- that will go there. Default implementation will use relative paths.
, ssMkRedirect :: Pieces -> ByteString -> ByteString
-- | If @True@, send a redirect to the user when a folder is requested
-- and an index page should be displayed. When @False@, display the
-- content immediately.
, ssRedirectToIndex :: Bool
-- | Prefer usage of etag caching to last-modified caching.
, ssUseHash :: Bool
-- | Force a trailing slash at the end of directories
, ssAddTrailingSlash :: Bool
-- | Optional `W.Application` to be used in case of 404 errors
--
-- Since 3.1.3
, ss404Handler :: Maybe W.Application
}
|
rgrinberg/wai
|
wai-app-static/WaiAppStatic/Types.hs
|
mit
| 5,363 | 0 | 11 | 1,291 | 621 | 390 | 231 | 64 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module HolyProject.HolyFiles where
import Paths_holy_haskell_sc
import Data.Data
import Text.Hastache
import Text.Hastache.Context
import System.Directory
import System.FilePath.Posix (takeDirectory, (</>))
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy.Char8 as LZ
-- | Nice little package for our data to be passed around.
data Project = Project {
projectName :: String
, moduleName :: String
, author :: String
, mail :: String
, ghaccout :: String
, synopsis :: String
, year :: String
} deriving (Data, Typeable)
-- | This is the list of files that will be parsed by the Hastache
-- system and saved into the given
-- location with in the project.
-- | The first elem is the path to the template, and the second elem
-- is the destination for the
-- processed file.
genFileList :: Project -> [(FilePath,FilePath)]
genFileList p = [
("gitignore", ".gitignore")
, ("project.cabal", (projectName p) ++ ".cabal")
, ("Setup.hs", "Setup.hs")
, ("src/Main.hs", "src" </> "Main.hs")
]
-- | Creates the actual folder structure and populates it with the
-- files from the genFileList function.
createProject :: Project -> IO ()
createProject p = do
let context = mkGenericContext p
createDirectory $ projectName p -- mkdir
setCurrentDirectory $ projectName p -- cd
mapM_ (\(x,y) -> genFile context x y) $ genFileList p
-- | Using the current context and Hastache, process a file and save
-- the output into the new project directory tree.
genFile :: MuContext IO -> FilePath -> FilePath -> IO ()
genFile context filename outputFilename = do
pkgfileName <- getDataFileName ("scaffold/" ++ filename)
template <- BS.readFile pkgfileName
transformedFile <- hastacheStr defaultConfig template context -- hastache magic here
createDirectoryIfMissing True (takeDirectory outputFilename)
LZ.writeFile outputFilename transformedFile
|
mankyKitty/holy-haskell-project-starter
|
src/HolyProject/HolyFiles.hs
|
mit
| 2,365 | 0 | 11 | 758 | 409 | 232 | 177 | 38 | 1 |
module Six where
data TisAnInteger =
TisAn Integer
instance Eq TisAnInteger where
(==) (TisAn x) (TisAn x') =
x == x'
data TwoIntegers =
Two Integer Integer
instance Eq TwoIntegers where
(==) (Two x y) (Two x' y') =
x == x' && y == y'
data StringOrInt =
TisAnInt Int
| TisAString String
instance Eq StringOrInt where
(==) (TisAnInt x) (TisAnInt x') =
x == x'
(==) (TisAString x) (TisAString x') =
x == x'
(==) _ _ = False
data Pair a =
Pair a a
instance Eq a => Eq (Pair a) where
(==) (Pair x y) (Pair x' y') =
x == x' && y == y'
data Tuple a b =
Tuple a b
instance (Eq a, Eq b) => Eq (Tuple a b) where
(==) (Tuple x y) (Tuple x' y') =
x == x' && y == y'
data Which a =
ThisOne a
| ThatOne a
instance Eq a => Eq (Which a) where
(==) (ThisOne x) (ThisOne x') =
x == x'
(==) (ThatOne x) (ThatOne x') =
x == x'
(==) _ _ = False
data EitherOr a b =
Hello a
| Goodbye b
instance (Eq a, Eq b) => Eq (EitherOr a b) where
(==) (Hello x) (Hello x') =
x == x'
(==) (Goodbye x) (Goodbye x') =
x == x'
(==) _ _ = False
|
mudphone/HaskellBook
|
src/Six.hs
|
mit
| 1,115 | 0 | 8 | 337 | 574 | 309 | 265 | 48 | 0 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
module MLUtil.Roundable
( Roundable (..)
) where
import qualified Data.Vector.Storable as VS
import MLUtil.Imports
class Roundable a where
roundToPrecision :: Int -> a -> a
instance Roundable R where
-- http://stackoverflow.com/questions/12450501/round-number-to-specified-number-of-digits
roundToPrecision n x = (fromInteger $ round $ x * (10 ^ n)) / (10.0 ^^ n)
{-
instance (Roundable a, VS.Storable a) => Roundable (Vector a) where
roundToPrecision n = VS.map (roundToPrecision n)
instance (Roundable a, VS.Storable a, Element a) => Roundable (Matrix a) where
roundToPrecision n = mapMatrixWithIndex (\_ x -> roundToPrecision n x)
-}
instance Roundable Vector where
roundToPrecision n = cmap (roundToPrecision n)
instance Roundable Matrix where
roundToPrecision n = cmap (roundToPrecision n)
instance Roundable a => Roundable [a] where
roundToPrecision n = map (roundToPrecision n)
|
rcook/mlutil
|
mlutil/src/MLUtil/Roundable.hs
|
mit
| 1,016 | 0 | 10 | 187 | 191 | 103 | 88 | 16 | 0 |
mergeSort :: (Ord a) => [a] -> [a]
mergeSort [] = []
mergeSort [x] = [x]
mergeSort xs = merge (mergeSort left) (mergeSort right)
where left = take (length xs `div` 2) xs
right = drop (length xs `div` 2) xs
merge :: (Ord a) => [a] -> [a] -> [a]
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys)
| (x <= y) = x:(merge xs (y:ys))
| otherwise = y:(merge (x:xs) ys)
|
siemiatj/algorithms
|
Coursera/haskell/mergesort.hs
|
mit
| 380 | 0 | 10 | 93 | 261 | 138 | 123 | 12 | 1 |
module Zwerg.Generator.Default
( module EXPORTED
, generateSkeleton
, generatePlayerSkeleton
) where
import Zwerg.Generator as EXPORTED
import Zwerg.UI.GlyphMap
generatePlayerSkeleton :: MonadCompState ()
generatePlayerSkeleton = do
--TODO: check if player already exists and throw error if it does
addComp playerUUID equipment zDefault
addComp playerUUID inventory zDefault
addComp playerUUID stats zDefault
addComp playerUUID glyph $ Glyph '@' (CellColor yellow Nothing)
addComp playerUUID blocksPassage True
addComp playerUUID blocksVision False
generateSkeleton :: EntityType -> MonadCompState UUID
generateSkeleton etype = do
entityUUID <- popUUID
addComp entityUUID entityType etype
generateSkeleton' entityUUID etype
return entityUUID
generateSkeleton' :: UUID -> EntityType -> MonadCompState ()
generateSkeleton' enemyUUID Enemy = do
addComp enemyUUID equipment zDefault
addComp enemyUUID stats zDefault
addComp enemyUUID blocksPassage True
addComp enemyUUID blocksVision False
generateSkeleton' levelUUID Level = do
setComp levelUUID tiles zDefault
setComp levelUUID glyphMap blankGlyphMap
emptyTileMap <- zBuildM $ \pos -> do
tileUUID <- generateSkeleton Tile
addComp tileUUID position pos
addComp tileUUID level levelUUID
modComp levelUUID tiles (zAdd tileUUID)
return tileUUID
setComp levelUUID tileMap emptyTileMap
setComp levelUUID name "Test Square Level"
generateSkeleton' tileUUID Tile = do
addComp tileUUID tileType Void
addComp tileUUID occupants zDefault
addComp tileUUID blocksPassage True
generateSkeleton' itemUUID Item = do
addComp itemUUID blocksPassage False
addComp itemUUID blocksVision False
generateSkeleton' otherUUID otherType = addComp otherUUID entityType otherType
|
zmeadows/zwerg
|
lib/Zwerg/Generator/Default.hs
|
mit
| 1,797 | 0 | 14 | 300 | 447 | 202 | 245 | 45 | 1 |
{-# LANGUAGE TypeOperators #-}
module Document.Phase.Transient where
--
-- Modules
--
import Document.Phase as P
import Document.Phase.Types
import Document.Visitor
import Latex.Parser hiding (contents)
import Logic.Expr
import Logic.Expr.Parser
import UnitB.Syntax as AST
--
-- Libraries
--
import Control.Monad.RWS as RWS ( RWS )
import Control.Precondition
import Control.Lens as L hiding ((|>),(<.>),(<|),indices,Context)
import Data.Either.Validation
import qualified Data.Maybe as MM
import Data.List as L hiding ( union, insert, inits )
import qualified Data.List.NonEmpty as NE
import Data.Map as M hiding ( (\\), (!) )
import Text.Printf.TH
import Utilities.Syntactic
tr_hintV :: HasMachineP2 mch
=> mch
-> Map Name Var
-> NonEmpty EventId
-> LatexDoc
-> Either [Error] TrHint
tr_hintV p2 vs evts doc = validationToEither $ eitherToValidation r <* nonNullError es
where
(r,es) = runM (tr_hint p2 vs (as_label <$> evts) doc) (line_info doc)
nonNullError :: [e] -> Validation [e] ()
nonNullError [] = pure ()
nonNullError es = Failure es
tr_hint :: HasMachineP2 mch
=> mch
-> Map Name Var
-> NonEmpty Label
-> LatexDoc
-> M TrHint
tr_hint p2 vs lbls thint = do
tr@(TrHint wit _) <- toEither $ tr_hint' p2 vs lbls thint empty_hint
evs <- get_events p2 $ NE.toList lbls
let vs = L.map (view pIndices p2 !) evs
err e ind = ( not $ M.null diff
, [s|A witness is needed for %s in event '%s'|]
(intercalate "," $ render <$> keys diff) (pretty e))
where
diff = ind `M.difference` wit
toEither $ error_list
$ zipWith err evs vs
return tr
tr_hint' :: HasMachineP2 mch
=> mch
-> Map Name Var
-> NonEmpty Label
-> LatexDoc
-> TrHint
-> RWS LineInfo [Error] () TrHint
tr_hint' p2 fv lbls = visit_doc []
[ ( "\\index"
, CmdBlock $ \(x, texExpr) (TrHint ys z) -> do
evs <- _unM $ get_events p2 lbls
let inds = p2^.pIndices
vs <- _unM $ bind_all evs
([s|'%s' is not an index of '%s'|] (render x) . pretty)
(\e -> x `M.lookup` (inds ! e))
let Var _ t = NE.head vs
ind = prime $ Var x t
x' = addPrime x
expr <- _unM $ hoistEither $ parse_expr'
((p2^.pMchSynt) `with_vars` insert x' ind fv)
texExpr
return $ TrHint (insert x (t, expr) ys) z)
, ( "\\lt"
, CmdBlock $ \(Identity prog) (TrHint ys z) -> do
let msg = [s|Only one progress property needed for '%s'|]
_unM $ toEither $ error_list
[ ( not $ MM.isNothing z
, msg $ pretty $ NE.toList lbls )
]
return $ TrHint ys (Just prog))
]
|
literate-unitb/literate-unitb
|
src/Document/Phase/Transient.hs
|
mit
| 3,091 | 0 | 19 | 1,130 | 993 | 535 | 458 | -1 | -1 |
{-# htermination maxBound :: Int #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_maxBound_4.hs
|
mit
| 37 | 0 | 2 | 6 | 3 | 2 | 1 | 1 | 0 |
module Deposit where
import qualified Rest
import qualified Rest
import Network.HTTP.Conduit
import Network.HTTP.Types
import qualified Data.ByteString.Char8 as C8
import qualified Data.ByteString.Lazy.Char8 as LC8
import Data.String (fromString)
address :: IO (Response LC8.ByteString)
address = Rest.post "/bitcoin_deposit_address/" []
unconfirmed :: IO (Response LC8.ByteString)
unconfirmed = Rest.post "/unconfirmed_btc/" []
|
GildedHonour/BitstampApi
|
src/Deposit.hs
|
mit
| 432 | 0 | 8 | 49 | 113 | 68 | 45 | 12 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{- |
See the documentation in "Crypto.Sodium.Sign".
-}
module Crypto.Sodium.Sign.Ed25519
( -- * Constants
publicKeyBytes -- | Number of bytes in a 'PublicKey'.
, secretKeyBytes -- | Number of bytes in a 'SecretKey'.
, seedBytes -- | Number of bytes in a 'Seed'.
, signatureBytes -- | Number of bytes in a 'Signature'.
-- * Types
, PublicKey -- | 'PublicKey' for asymmetric signing.
, mkPublicKey -- | Smart constructor for 'PublicKey'. Verifies that
-- the length of the parameter is 'publicKeyBytes'.
, unPublicKey -- | Returns the contents of a 'PublicKey'.
, SecretKey -- | 'SecretKey' for asymmetric signing.
, mkSecretKey -- | Smart constructor for 'SecretKey'. Verifies that
-- the length of the parameter is 'secretKeyBytes'.
, unSecretKey -- | Returns the contents of a 'SecretKey'.
, Seed -- | 'Seed' for deterministic key generation.
, mkSeed -- | Smart constructor for 'Seed'. Verifies that the length of
-- the parameter is 'seedBytes'.
, unSeed -- | Returns the contents of a 'Seed'.
, Signature -- | A 'Signature' of a message.
, mkSignature -- | Smart constructor for 'Signature'. Verifies that
-- the length of the parameter is 'signatureBytes'.
, unSignature -- | Returns the contents of a 'Signature'.
-- * Key Generation
, randomKeypair -- | Randomly generates a 'SecretKey' and the corresponding
-- 'PublicKey'.
, keypairFromSeed -- | Computes a 'SecretKey' and the corresponding
-- 'PublicKey' from a 'Seed'.
, randomSeed -- | Randomly generates a 'Seed'.
-- * Signing/Verifying
, sign -- | Signs a message using a 'SecretKey'. Returns the signed message.
, verify -- | Verifies that a message has been signed by the 'SecretKey'
-- corresponding to the 'PublicKey' given as a parameter.
-- If verification succeeds it returns 'Just' the
-- contents of the message, otherwise it returns 'Nothing'.
, signDetached -- | Signs a message using a 'SecretKey'. Returns a detached
-- 'Signature'.
, verifyDetached -- | Verifies that a message with a detached 'Signature' has
-- been signed by the 'SecretKey' corresponding to the
-- 'PublicKey' given as a parameter.
-- * Key Conversion
, skToSeed -- | Converts a 'SecretKey' to a 'Seed'.
, skToPk -- | Computes the corresponding 'PublicKey' from a 'SecretKey'.
, pkToCurve25519 -- | Converts a 'PublicKey' to a 'Curve25519.PublicKey'
-- for use in asymmetric authenticated encryption.
--
-- WARNING: This function should only be used if
-- you are absolutely sure of what you're doing.
-- Using the same key for different purposes will
-- open up for cross protocol attacks unless you're
-- extremely careful.
, skToCurve25519 -- | Converts a 'SecretKey' to a 'Curve25519.SecretKey'
-- for use in asymmetric authenticated encryption.
--
-- WARNING: This function should only be used if
-- you are absolutely sure of what you're doing.
-- Using the same key for different purposes will
-- open up for cross protocol attacks unless you're
-- extremely careful.
) where
import qualified Crypto.Sodium.Box.Curve25519Xsalsa20Poly1305 as Curve
import Crypto.Sodium.Internal (createWithResult,
mkHelper,
mkSecureHelper)
import Crypto.Sodium.Random (randomSecret)
import Crypto.Sodium.SecureMem (SecureMem)
import qualified Crypto.Sodium.SecureMem as SM
import Control.Arrow ((***))
import Control.Exception (evaluate)
import Control.Monad (unless, void,
(<=<))
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Internal as B
import qualified Data.ByteString.Unsafe as B
import Data.Hashable (Hashable)
import Data.Maybe (fromJust)
import Data.Word (Word8)
import Foreign.C.Types (CChar, CInt (..),
CSize (..),
CULLong (..))
import Foreign.Marshal.Alloc (alloca)
import Foreign.Ptr (Ptr)
import Foreign.Storable (peek)
import System.IO.Unsafe (unsafeDupablePerformIO)
foreign import ccall unsafe "crypto_sign_ed25519_bytes"
c_crypto_sign_ed25519_bytes :: CSize
foreign import ccall unsafe "crypto_sign_ed25519_seedbytes"
c_crypto_sign_ed25519_seedbytes :: CSize
foreign import ccall unsafe "crypto_sign_ed25519_publickeybytes"
c_crypto_sign_ed25519_publickeybytes :: CSize
foreign import ccall unsafe "crypto_sign_ed25519_secretkeybytes"
c_crypto_sign_ed25519_secretkeybytes :: CSize
foreign import ccall unsafe "crypto_sign_ed25519"
c_crypto_sign_ed25519 :: Ptr Word8 -> Ptr CULLong -> Ptr CChar -> CULLong -> Ptr Word8 -> IO CInt
foreign import ccall unsafe "crypto_sign_ed25519_open"
c_crypto_sign_ed25519_open :: Ptr Word8 -> Ptr CULLong -> Ptr CChar -> CULLong -> Ptr CChar -> IO CInt
foreign import ccall unsafe "crypto_sign_ed25519_detached"
c_crypto_sign_ed25519_detached :: Ptr Word8 -> Ptr CULLong -> Ptr CChar -> CULLong -> Ptr Word8 -> IO CInt
foreign import ccall unsafe "crypto_sign_ed25519_verify_detached"
c_crypto_sign_ed25519_verify_detached :: Ptr CChar -> Ptr CChar -> CULLong -> Ptr CChar -> IO CInt
foreign import ccall unsafe "crypto_sign_ed25519_keypair"
c_crypto_sign_ed25519_keypair :: Ptr Word8 -> Ptr Word8 -> IO CInt
foreign import ccall unsafe "crypto_sign_ed25519_seed_keypair"
c_crypto_sign_ed25519_seed_keypair :: Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> IO CInt
foreign import ccall unsafe "crypto_sign_ed25519_pk_to_curve25519"
c_crypto_sign_ed25519_pk_to_curve25519 :: Ptr Word8 -> Ptr CChar -> IO CInt
foreign import ccall unsafe "crypto_sign_ed25519_sk_to_curve25519"
c_crypto_sign_ed25519_sk_to_curve25519 :: Ptr Word8 -> Ptr Word8 -> IO CInt
foreign import ccall unsafe "crypto_sign_ed25519_sk_to_seed"
c_crypto_sign_ed25519_sk_to_seed :: Ptr Word8 -> Ptr Word8 -> IO CInt
foreign import ccall unsafe "crypto_sign_ed25519_sk_to_pk"
c_crypto_sign_ed25519_sk_to_pk :: Ptr Word8 -> Ptr Word8 -> IO CInt
seedBytes :: Int
seedBytes = fromIntegral c_crypto_sign_ed25519_seedbytes
secretKeyBytes :: Int
secretKeyBytes = fromIntegral c_crypto_sign_ed25519_secretkeybytes
publicKeyBytes :: Int
publicKeyBytes = fromIntegral c_crypto_sign_ed25519_publickeybytes
signatureBytes :: Int
signatureBytes = fromIntegral c_crypto_sign_ed25519_bytes
newtype Seed = Seed { unSeed :: SecureMem } deriving (Eq, Show)
mkSeed :: SecureMem -> Maybe Seed
mkSeed = mkSecureHelper seedBytes Seed
newtype SecretKey = SecretKey { unSecretKey :: SecureMem } deriving (Eq, Show)
mkSecretKey :: SecureMem -> Maybe SecretKey
mkSecretKey = mkSecureHelper secretKeyBytes SecretKey
newtype PublicKey = PublicKey { unPublicKey :: ByteString } deriving (Eq, Show, Ord, Hashable)
mkPublicKey :: ByteString -> Maybe PublicKey
mkPublicKey = mkHelper publicKeyBytes PublicKey
newtype Signature = Signature { unSignature :: ByteString } deriving (Eq, Show)
mkSignature :: ByteString -> Maybe Signature
mkSignature = mkHelper signatureBytes Signature
randomSeed :: IO Seed
randomSeed = Seed <$> randomSecret seedBytes
randomKeypair :: IO (PublicKey, SecretKey)
randomKeypair =
fmap (PublicKey *** SecretKey) $
createWithResult publicKeyBytes $ \ppk ->
SM.create secretKeyBytes $ \psk ->
void $ c_crypto_sign_ed25519_keypair ppk psk
keypairFromSeed :: Seed -> (PublicKey, SecretKey)
keypairFromSeed (Seed s) =
(PublicKey *** SecretKey) $
unsafeDupablePerformIO $
createWithResult publicKeyBytes $ \ppk ->
SM.create secretKeyBytes $ \psk ->
SM.withSecureMem s $ \ps ->
void $ c_crypto_sign_ed25519_seed_keypair ppk psk ps
sign :: SecretKey -> ByteString -> ByteString
sign (SecretKey sk) m =
unsafeDupablePerformIO $
B.unsafeUseAsCStringLen m $ \(pm, mLen) ->
alloca $ \psmLen ->
SM.withSecureMem sk $ \psk -> do
sm <- B.create (mLen + signatureBytes) $ \psm ->
void $ c_crypto_sign_ed25519 psm psmLen pm (fromIntegral mLen) psk
(`B.take` sm) . fromIntegral <$> peek psmLen
verify :: PublicKey -> ByteString -> Maybe ByteString
verify (PublicKey pk) sm =
unsafeDupablePerformIO $
B.unsafeUseAsCStringLen sm $ \(psm, smLen) ->
alloca $ \pmLen ->
B.unsafeUseAsCString pk $ \ppk -> do
(m, r) <- createWithResult smLen $ \pm ->
c_crypto_sign_ed25519_open pm pmLen psm (fromIntegral smLen) ppk
if r == 0
then Just . (`B.take` m) . fromIntegral <$> peek pmLen
else return Nothing
signDetached :: SecretKey -> ByteString -> Signature
signDetached (SecretKey sk) m =
Signature $ B.unsafeCreate signatureBytes $ \ps ->
alloca $ \psLen ->
B.unsafeUseAsCStringLen m $ \(pm, mLen) ->
SM.withSecureMem sk $ \psk -> do
void $ c_crypto_sign_ed25519_detached ps psLen pm (fromIntegral mLen) psk
sLen <- fromIntegral <$> peek psLen
unless (sLen == signatureBytes) $
evaluate $ error "signDetached: internal error sLen /= signatureBytes"
verifyDetached :: PublicKey -> ByteString -> Signature -> Bool
verifyDetached (PublicKey pk) m (Signature s) =
unsafeDupablePerformIO $
B.unsafeUseAsCString s $ \ps ->
B.unsafeUseAsCStringLen m $ \(pm, mLen) ->
B.unsafeUseAsCString pk $
return . (==0) <=<
c_crypto_sign_ed25519_verify_detached ps pm (fromIntegral mLen)
pkToCurve25519 :: PublicKey -> Curve.PublicKey
pkToCurve25519 (PublicKey pk) =
fromJust $
Curve.mkPublicKey $
B.unsafeCreate Curve.publicKeyBytes $ \pcpk ->
B.unsafeUseAsCString pk $
void . c_crypto_sign_ed25519_pk_to_curve25519 pcpk
skToCurve25519 :: SecretKey -> Curve.SecretKey
skToCurve25519 (SecretKey sk) =
fromJust $
Curve.mkSecretKey $
unsafeDupablePerformIO $
SM.create Curve.secretKeyBytes $ \pcsk ->
SM.withSecureMem sk $
void . c_crypto_sign_ed25519_sk_to_curve25519 pcsk
skToSeed :: SecretKey -> Seed
skToSeed (SecretKey sk) =
Seed $
unsafeDupablePerformIO $
SM.create seedBytes $ \ps ->
SM.withSecureMem sk $
void . c_crypto_sign_ed25519_sk_to_seed ps
skToPk :: SecretKey -> PublicKey
skToPk (SecretKey sk) =
PublicKey $
B.unsafeCreate publicKeyBytes $ \ppk ->
SM.withSecureMem sk $
void . c_crypto_sign_ed25519_sk_to_pk ppk
|
dnaq/crypto-sodium
|
src/Crypto/Sodium/Sign/Ed25519.hs
|
mit
| 11,660 | 0 | 19 | 3,332 | 2,084 | 1,142 | 942 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html
module Stratosphere.ResourceProperties.CloudFrontDistributionDefaultCacheBehavior where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.CloudFrontDistributionForwardedValues
import Stratosphere.ResourceProperties.CloudFrontDistributionLambdaFunctionAssociation
-- | Full data type definition for CloudFrontDistributionDefaultCacheBehavior.
-- See 'cloudFrontDistributionDefaultCacheBehavior' for a more convenient
-- constructor.
data CloudFrontDistributionDefaultCacheBehavior =
CloudFrontDistributionDefaultCacheBehavior
{ _cloudFrontDistributionDefaultCacheBehaviorAllowedMethods :: Maybe (ValList Text)
, _cloudFrontDistributionDefaultCacheBehaviorCachedMethods :: Maybe (ValList Text)
, _cloudFrontDistributionDefaultCacheBehaviorCompress :: Maybe (Val Bool)
, _cloudFrontDistributionDefaultCacheBehaviorDefaultTTL :: Maybe (Val Double)
, _cloudFrontDistributionDefaultCacheBehaviorFieldLevelEncryptionId :: Maybe (Val Text)
, _cloudFrontDistributionDefaultCacheBehaviorForwardedValues :: CloudFrontDistributionForwardedValues
, _cloudFrontDistributionDefaultCacheBehaviorLambdaFunctionAssociations :: Maybe [CloudFrontDistributionLambdaFunctionAssociation]
, _cloudFrontDistributionDefaultCacheBehaviorMaxTTL :: Maybe (Val Double)
, _cloudFrontDistributionDefaultCacheBehaviorMinTTL :: Maybe (Val Double)
, _cloudFrontDistributionDefaultCacheBehaviorSmoothStreaming :: Maybe (Val Bool)
, _cloudFrontDistributionDefaultCacheBehaviorTargetOriginId :: Val Text
, _cloudFrontDistributionDefaultCacheBehaviorTrustedSigners :: Maybe (ValList Text)
, _cloudFrontDistributionDefaultCacheBehaviorViewerProtocolPolicy :: Val Text
} deriving (Show, Eq)
instance ToJSON CloudFrontDistributionDefaultCacheBehavior where
toJSON CloudFrontDistributionDefaultCacheBehavior{..} =
object $
catMaybes
[ fmap (("AllowedMethods",) . toJSON) _cloudFrontDistributionDefaultCacheBehaviorAllowedMethods
, fmap (("CachedMethods",) . toJSON) _cloudFrontDistributionDefaultCacheBehaviorCachedMethods
, fmap (("Compress",) . toJSON) _cloudFrontDistributionDefaultCacheBehaviorCompress
, fmap (("DefaultTTL",) . toJSON) _cloudFrontDistributionDefaultCacheBehaviorDefaultTTL
, fmap (("FieldLevelEncryptionId",) . toJSON) _cloudFrontDistributionDefaultCacheBehaviorFieldLevelEncryptionId
, (Just . ("ForwardedValues",) . toJSON) _cloudFrontDistributionDefaultCacheBehaviorForwardedValues
, fmap (("LambdaFunctionAssociations",) . toJSON) _cloudFrontDistributionDefaultCacheBehaviorLambdaFunctionAssociations
, fmap (("MaxTTL",) . toJSON) _cloudFrontDistributionDefaultCacheBehaviorMaxTTL
, fmap (("MinTTL",) . toJSON) _cloudFrontDistributionDefaultCacheBehaviorMinTTL
, fmap (("SmoothStreaming",) . toJSON) _cloudFrontDistributionDefaultCacheBehaviorSmoothStreaming
, (Just . ("TargetOriginId",) . toJSON) _cloudFrontDistributionDefaultCacheBehaviorTargetOriginId
, fmap (("TrustedSigners",) . toJSON) _cloudFrontDistributionDefaultCacheBehaviorTrustedSigners
, (Just . ("ViewerProtocolPolicy",) . toJSON) _cloudFrontDistributionDefaultCacheBehaviorViewerProtocolPolicy
]
-- | Constructor for 'CloudFrontDistributionDefaultCacheBehavior' containing
-- required fields as arguments.
cloudFrontDistributionDefaultCacheBehavior
:: CloudFrontDistributionForwardedValues -- ^ 'cfddcbForwardedValues'
-> Val Text -- ^ 'cfddcbTargetOriginId'
-> Val Text -- ^ 'cfddcbViewerProtocolPolicy'
-> CloudFrontDistributionDefaultCacheBehavior
cloudFrontDistributionDefaultCacheBehavior forwardedValuesarg targetOriginIdarg viewerProtocolPolicyarg =
CloudFrontDistributionDefaultCacheBehavior
{ _cloudFrontDistributionDefaultCacheBehaviorAllowedMethods = Nothing
, _cloudFrontDistributionDefaultCacheBehaviorCachedMethods = Nothing
, _cloudFrontDistributionDefaultCacheBehaviorCompress = Nothing
, _cloudFrontDistributionDefaultCacheBehaviorDefaultTTL = Nothing
, _cloudFrontDistributionDefaultCacheBehaviorFieldLevelEncryptionId = Nothing
, _cloudFrontDistributionDefaultCacheBehaviorForwardedValues = forwardedValuesarg
, _cloudFrontDistributionDefaultCacheBehaviorLambdaFunctionAssociations = Nothing
, _cloudFrontDistributionDefaultCacheBehaviorMaxTTL = Nothing
, _cloudFrontDistributionDefaultCacheBehaviorMinTTL = Nothing
, _cloudFrontDistributionDefaultCacheBehaviorSmoothStreaming = Nothing
, _cloudFrontDistributionDefaultCacheBehaviorTargetOriginId = targetOriginIdarg
, _cloudFrontDistributionDefaultCacheBehaviorTrustedSigners = Nothing
, _cloudFrontDistributionDefaultCacheBehaviorViewerProtocolPolicy = viewerProtocolPolicyarg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html#cfn-cloudfront-distribution-defaultcachebehavior-allowedmethods
cfddcbAllowedMethods :: Lens' CloudFrontDistributionDefaultCacheBehavior (Maybe (ValList Text))
cfddcbAllowedMethods = lens _cloudFrontDistributionDefaultCacheBehaviorAllowedMethods (\s a -> s { _cloudFrontDistributionDefaultCacheBehaviorAllowedMethods = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html#cfn-cloudfront-distribution-defaultcachebehavior-cachedmethods
cfddcbCachedMethods :: Lens' CloudFrontDistributionDefaultCacheBehavior (Maybe (ValList Text))
cfddcbCachedMethods = lens _cloudFrontDistributionDefaultCacheBehaviorCachedMethods (\s a -> s { _cloudFrontDistributionDefaultCacheBehaviorCachedMethods = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html#cfn-cloudfront-distribution-defaultcachebehavior-compress
cfddcbCompress :: Lens' CloudFrontDistributionDefaultCacheBehavior (Maybe (Val Bool))
cfddcbCompress = lens _cloudFrontDistributionDefaultCacheBehaviorCompress (\s a -> s { _cloudFrontDistributionDefaultCacheBehaviorCompress = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html#cfn-cloudfront-distribution-defaultcachebehavior-defaultttl
cfddcbDefaultTTL :: Lens' CloudFrontDistributionDefaultCacheBehavior (Maybe (Val Double))
cfddcbDefaultTTL = lens _cloudFrontDistributionDefaultCacheBehaviorDefaultTTL (\s a -> s { _cloudFrontDistributionDefaultCacheBehaviorDefaultTTL = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html#cfn-cloudfront-distribution-defaultcachebehavior-fieldlevelencryptionid
cfddcbFieldLevelEncryptionId :: Lens' CloudFrontDistributionDefaultCacheBehavior (Maybe (Val Text))
cfddcbFieldLevelEncryptionId = lens _cloudFrontDistributionDefaultCacheBehaviorFieldLevelEncryptionId (\s a -> s { _cloudFrontDistributionDefaultCacheBehaviorFieldLevelEncryptionId = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html#cfn-cloudfront-distribution-defaultcachebehavior-forwardedvalues
cfddcbForwardedValues :: Lens' CloudFrontDistributionDefaultCacheBehavior CloudFrontDistributionForwardedValues
cfddcbForwardedValues = lens _cloudFrontDistributionDefaultCacheBehaviorForwardedValues (\s a -> s { _cloudFrontDistributionDefaultCacheBehaviorForwardedValues = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html#cfn-cloudfront-distribution-defaultcachebehavior-lambdafunctionassociations
cfddcbLambdaFunctionAssociations :: Lens' CloudFrontDistributionDefaultCacheBehavior (Maybe [CloudFrontDistributionLambdaFunctionAssociation])
cfddcbLambdaFunctionAssociations = lens _cloudFrontDistributionDefaultCacheBehaviorLambdaFunctionAssociations (\s a -> s { _cloudFrontDistributionDefaultCacheBehaviorLambdaFunctionAssociations = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html#cfn-cloudfront-distribution-defaultcachebehavior-maxttl
cfddcbMaxTTL :: Lens' CloudFrontDistributionDefaultCacheBehavior (Maybe (Val Double))
cfddcbMaxTTL = lens _cloudFrontDistributionDefaultCacheBehaviorMaxTTL (\s a -> s { _cloudFrontDistributionDefaultCacheBehaviorMaxTTL = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html#cfn-cloudfront-distribution-defaultcachebehavior-minttl
cfddcbMinTTL :: Lens' CloudFrontDistributionDefaultCacheBehavior (Maybe (Val Double))
cfddcbMinTTL = lens _cloudFrontDistributionDefaultCacheBehaviorMinTTL (\s a -> s { _cloudFrontDistributionDefaultCacheBehaviorMinTTL = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html#cfn-cloudfront-distribution-defaultcachebehavior-smoothstreaming
cfddcbSmoothStreaming :: Lens' CloudFrontDistributionDefaultCacheBehavior (Maybe (Val Bool))
cfddcbSmoothStreaming = lens _cloudFrontDistributionDefaultCacheBehaviorSmoothStreaming (\s a -> s { _cloudFrontDistributionDefaultCacheBehaviorSmoothStreaming = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html#cfn-cloudfront-distribution-defaultcachebehavior-targetoriginid
cfddcbTargetOriginId :: Lens' CloudFrontDistributionDefaultCacheBehavior (Val Text)
cfddcbTargetOriginId = lens _cloudFrontDistributionDefaultCacheBehaviorTargetOriginId (\s a -> s { _cloudFrontDistributionDefaultCacheBehaviorTargetOriginId = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html#cfn-cloudfront-distribution-defaultcachebehavior-trustedsigners
cfddcbTrustedSigners :: Lens' CloudFrontDistributionDefaultCacheBehavior (Maybe (ValList Text))
cfddcbTrustedSigners = lens _cloudFrontDistributionDefaultCacheBehaviorTrustedSigners (\s a -> s { _cloudFrontDistributionDefaultCacheBehaviorTrustedSigners = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-defaultcachebehavior.html#cfn-cloudfront-distribution-defaultcachebehavior-viewerprotocolpolicy
cfddcbViewerProtocolPolicy :: Lens' CloudFrontDistributionDefaultCacheBehavior (Val Text)
cfddcbViewerProtocolPolicy = lens _cloudFrontDistributionDefaultCacheBehaviorViewerProtocolPolicy (\s a -> s { _cloudFrontDistributionDefaultCacheBehaviorViewerProtocolPolicy = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/CloudFrontDistributionDefaultCacheBehavior.hs
|
mit
| 10,880 | 0 | 13 | 755 | 1,261 | 714 | 547 | 87 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main
where
import Common (loggerName)
import Config (readConfig, ServerType(..))
import Control.Exception (catch, SomeException)
import Control.Concurrent (forkIO)
import Control.Concurrent.Chan (Chan, writeChan, newChan, readChan)
import Control.Concurrent.MVar (newMVar, modifyMVar_, withMVar, MVar)
import Control.Monad (forever, void)
import Control.Monad.IO.Class (MonadIO(liftIO))
import Data.Aeson.Types (Value, object, (.=))
import Data.ByteString.Lazy.Char8 (pack)
import Data.List (delete)
import Data.Time.Clock (getCurrentTime)
import Error (MsgError(..))
import Network.Socket ( getAddrInfo, addrAddress, addrFamily, withSocketsDo
, defaultProtocol, bindSocket, listen, accept
, AddrInfo(..), AddrInfoFlag(AI_PASSIVE), socket
, defaultHints, SocketType(Stream), Socket, close)
import Network.HTTP.Types.Status (statusCode, status500)
import Network.Wai (Middleware, responseLBS)
import Network.Wai.Handler.Warp (defaultSettings, setPort, runSettings)
import Network.Wai.Handler.WarpTLS (tlsSettings, runTLS)
import Nova.Config (confFileName, NovaConfig(..))
import Nova.Web.Version (listVersionsH)
import Nova.Web.Server (createServerH)
import System.IO (stdout)
import System.Log.Formatter (simpleLogFormatter)
import System.Log.Handler (setFormatter)
import System.Log.Handler.Simple (fileHandler, streamHandler)
import System.Log.Logger ( setLevel, updateGlobalLogger, setHandlers
, removeAllHandlers, debugM, noticeM, errorM)
import System.Timeout (timeout)
import Web.Common (ScottyM, ActionM)
import qualified Error as E
import qualified Keystone.Web.Auth as A
import qualified Keystone.Web.Auth.Types as AT
import qualified Web.Scotty.Trans as S
import qualified Nova.Compute as NC
main = do
(config :: NovaConfig) <- readConfig confFileName
let logFormatter = simpleLogFormatter "$utcTime (pid $pid, $tid) $prio: $msg"
stdoutHandler <- streamHandler stdout (logLevel config)
fileHandler <- fileHandler "nova.log" (logLevel config)
removeAllHandlers
updateGlobalLogger loggerName $ setLevel (logLevel config) . setHandlers
[ setFormatter stdoutHandler logFormatter
, setFormatter fileHandler logFormatter
]
-- Add verify database
agentList <- newMVar []
(messageChannel :: Chan NC.Message) <- newChan
forkIO $ computeServer messageChannel agentList
!policy <- A.loadPolicy
-- ^ bang pattern is because we want to know if the policy is correct now
-- ^ we need the evaluation to happen immediatelly
verifyDatabase config
app <- S.scottyAppT id (application policy config agentList)
let settings = tlsSettings
(certificateFile config)
(keyFile config)
let serverSettings = setPort (port config) defaultSettings
noticeM loggerName $ "Starting web server @ port " ++ (show $ port config)
case serverType config of
Tls -> runTLS settings serverSettings app
Plain -> runSettings serverSettings app
computeServer :: Chan NC.Message -> NC.AgentList -> IO ()
computeServer messageChannel agentList = withSocketsDo $ do
addrinfos <- getAddrInfo
(Just (defaultHints {addrFlags = [AI_PASSIVE]}))
Nothing
(Just "13000")
let serveraddr = head addrinfos
sock <- socket (addrFamily serveraddr) Stream defaultProtocol
bindSocket sock (addrAddress serveraddr)
listen sock 5
forkIO $ messagePrinter messageChannel
forever $ do
(clientSocket, clientAddr) <- accept sock
mAgent <- NC.handshake clientSocket
case mAgent of
Just agent -> do
void $ forkIO $ do
modifyMVar_ agentList $ \list -> return $ agent : list
withMVar agentList $ putStrLn . show
(threadReader (NC.socket agent) messageChannel)
`catch` (
\(e :: SomeException) ->
errorM loggerName $ "Caught exception in thread reader: " ++ (show e)
)
close $ NC.socket agent
modifyMVar_ agentList $ \list -> return $ delete agent list
withMVar agentList $ putStrLn . show
Nothing -> do
errorM loggerName $ "Failed to handshake with remote client: " ++ (show clientAddr)
messagePrinter :: Chan NC.Message -> IO ()
messagePrinter chan = do
forever $ do
m <- readChan chan
debugM loggerName $ show m
threadReader :: Socket -> Chan NC.Message -> IO ()
threadReader sock channel = do
m <- timeout (2 * (fromIntegral NC.heartBeatTimeout) * 1000000) $ NC.readMessage sock
case m of
Nothing ->
errorM loggerName $ "Agent didn't respond within specified time."
Just (Left ParseFailure) ->
errorM loggerName $ "Failed to read message."
Just (Left EndOfStream) ->
return ()
Just (Right v) -> do
writeChan channel v
threadReader sock channel
application :: AT.Policy
-> NovaConfig
-> NC.AgentList
-> ScottyM IO ()
application policy config agentList = do
S.middleware exceptionCatchMiddleware
S.middleware logRequestResponse
S.defaultHandler $ \e -> do
S.status $ E.code e
case statusCode $ E.code e of
500 -> do
time <- liftIO $ getCurrentTime
liftIO $ errorM loggerName $ E.message e
S.json $ e {E.message = "Internal error. Server time - " ++ (show time)}
_ -> do
S.json e
S.get "/" $ listVersionsH config
S.get "/v2.1/:tenant_id/os-hypervisors" $ listHypervisorsH config agentList
S.post "/v2.1/:tenant_id/servers" $ createServerH config agentList
listHypervisorsH :: (Functor m, MonadIO m)
=> NovaConfig -> NC.AgentList -> ActionM m ()
listHypervisorsH config varAgentList = do
reply <- liftIO $ withMVar varAgentList $ \agentList ->
return $ object ["hypervisors" .= map agentToJson agentList ]
S.json reply
agentToJson :: NC.ComputeAgent -> Value
agentToJson agent = object [ "hypervisor_hostname" .= NC.agentName agent]
verifyDatabase :: NovaConfig -> IO ()
verifyDatabase NovaConfig{..} = return () -- TODO
exceptionCatchMiddleware :: Middleware
exceptionCatchMiddleware app request responder = do
(app request responder)
`catch`
(\(e :: SomeException) -> do
time <- liftIO $ getCurrentTime
errorM loggerName $ show e
let message = "Internal error. Server time - " ++ (show time) ++ "\n"
responder $ responseLBS status500 [] (pack message)
)
logRequestResponse :: Middleware
logRequestResponse app request responder = do
debugM loggerName $ show request
app request responder
|
VictorDenisov/keystone
|
src/Nova.hs
|
gpl-2.0
| 6,793 | 0 | 24 | 1,508 | 1,942 | 1,000 | 942 | 153 | 4 |
import Control.Monad ( filterM )
import System.Directory ( Permissions(..), getModificationTime, getPermissions)
import System.Time (ClockTime(..))
import System.FilePath ((</>), takeExtension)
import Control.Exception (bracket, handle, IOException )
import System.IO (IOMode(..), hClose, hFileSize, openFile)
import RecursiveContents (getRecursiveContents)
type Predicate = FilePath
-> Permissions
-> Maybe Integer
-> ClockTime
-> Bool
type InfoP a = FilePath
-> Permissions
-> Maybe Integer
-> ClockTime
-> a
pathP :: InfoP FilePath
pathP path _ _ _ = path
sizeP :: InfoP Integer
sizeP _ _ (Just size) _ = size
sizeP _ _ Nothing _ = -1
equalP :: (Eq a) => InfoP a -> a -> InfoP Bool
equalP f k = \w x y z -> f w x y z == k
liftP :: (a -> b -> c) -> InfoP a -> b -> InfoP c
liftP q f k = \w x y z -> f w x y z `q` k
liftP2 :: ( a -> b -> c ) -> InfoP a -> InfoP b -> InfoP c
liftP2 q f g = \w x y z -> f w x y z `q` g w x y z
andP = liftP2 (&&)
orP = liftP2 (||)
greaterP, lesserP :: (Ord a) => InfoP a -> a -> InfoP Bool
greaterP = liftP (>)
lesserP = liftP (<)
betterFind :: Predicate -> FilePath -> IO [FilePath]
betterFind p path = getRecursiveContents path >>= filterM check
where check name = do
perms <- getPermissions name
size <- getFileSize name
modified <- getModificationTime name
return ( p name perms size modified )
getFileSize :: FilePath -> IO (Maybe Integer)
getFileSize path = handle ((\_ -> return Nothing) :: IOException -> IO (Maybe Integer)) $
bracket ( openFile path ReadMode ) hClose getSize
where
getSize h = do
size <- hFileSize h
return (Just size)
myTest path _ (Just size) _ = takeExtension path == ".cpp" && size > 131072
myTest _ _ _ _ = False
liftPath :: (FilePath -> a) -> InfoP a
liftPath f = \w x y z -> f w
myTest2 = (liftPath takeExtension ==? ".cpp") &&? (sizeP >? 131072)
(==?) = equalP
(&&?) = andP
(>?) = greaterP
|
Tr1p0d/realWorldHaskell
|
rwh9/BetterPredicate.hs
|
gpl-2.0
| 1,904 | 25 | 11 | 408 | 871 | 458 | 413 | 54 | 1 |
-- Author: Viacheslav Lotsmanov
-- License: GPLv3 https://raw.githubusercontent.com/unclechu/xmonadrc/master/LICENSE
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import "base" Data.Function ((&), fix)
import "base" Data.List (stripPrefix, find)
import "base" Data.Bool (bool)
import "base" Data.Maybe (isJust)
import "base" Control.Concurrent (threadDelay)
import "base" Control.Exception (finally)
import "base" Control.Monad (unless, forM_)
import "base" System.Environment (getEnvironment)
import "base" System.Exit (ExitCode(ExitSuccess, ExitFailure))
import "base" System.IO (Handle, hGetLine)
import "directory" System.Directory (doesFileExist)
import "unix" System.Posix.Signals ( Signal
, signalProcess
, sigHUP
, sigINT
, sigTERM
, sigPIPE
, sigKILL
)
import "process" System.Process.Internals ( ProcessHandle__ (OpenHandle)
, withProcessHandle
)
import "process" System.Process ( StdStream (NoStream, Inherit, CreatePipe)
, CreateProcess (std_in, std_out, std_err, env)
, ProcessHandle
, createProcess
, readProcess
, proc
, terminateProcess
, waitForProcess
)
import "HUnit" Test.HUnit ( Test (TestList, TestCase)
, runTestTT
, assertEqual
, assertBool
)
import "dbus" DBus ( Address
, BusName
, busName_
, MemberName
, parseAddress
, formatAddress
, signal
, signalBody
, signalDestination
, toVariant
)
import "dbus" DBus.Client ( Client
, connect
, disconnect
, emit
)
import "X11" Graphics.X11.Xlib ( Display
, openDisplay
, closeDisplay
, displayString
)
-- local imports
import Test.Utils (getTmpDBusSocketPath)
main :: IO ()
main = do
successfullyExec "stack" ["clean", "unclechu-xmobar-indicators-cmd"]
successfullyExec "stack" ["build", "unclechu-xmobar-indicators-cmd"]
() <$ runTestTT tests
where successfullyExec :: String -> [String] -> IO ()
successfullyExec app args = do
(Nothing, _, _, pHandle) <-
createProcess (proc app args) { std_in = NoStream
, std_out = Inherit
, std_err = Inherit
}
ExitSuccess <- waitForProcess pHandle
return ()
tests :: Test
tests = TestList [ testTerminating sigHUP
, testTerminating sigINT
, testTerminating sigTERM
, testTerminating sigPIPE
, testKilling
, initialIndicators
, testCombinations
]
initialIndicators :: Test
initialIndicators = TestCase $ withAppAndTerminate $ \_ _ pOut ->
lines <$> hGetLine pOut
>>= (\x -> head x <$ assertEqual "Only single line" 1 (length x))
>>= return . getRidOfActions
>>= assertEqual "Initial indicators is correct" shouldBe
where shouldBe = renderIndicators [ ("#999", "num")
, ("#999", "caps")
, ("#999", "hax")
, ("#999", "[ ]")
]
type CombinationRecord = (MemberName, Bool, (String -> Bool), String)
type Combination = [CombinationRecord]
type IndicatorsState = [(MemberName, Bool)]
testCombinations :: Test
testCombinations = TestCase $ withAppAndTerminate $ \client busName pOut -> do
(getRidOfActions -> parseIndicators -> indicatorsAtStart) <- hGetLine pOut
let changeState :: MemberName -> Bool -> IO ()
changeState member state =
emit client (signal "/" "com.github.unclechu.xmonadrc" member)
{ signalDestination = Just busName
, signalBody = [toVariant state]
}
handle :: [Combination] -> IndicatorsState -> [Indicator] -> IO ()
handle [] _ _ = return ()
handle (x:xs) state indicators = do
(newState, newIndicators) <-
handleRecords (getDiffs state x) state indicators
assertEqual "Combinations count is correct" (length state) (length x)
assertEqual "Indicators count is correct" (length indicators) (length x)
forM_ (zip3 x newState newIndicators) $
\((cMember, cIsOn, cf, cTitle), (sMember, sIsOn), (iColor, iTitle)) -> do
assertEqual "Member matches internal state" cMember sMember
assertEqual "State of indicator matches internal state" cIsOn sIsOn
assertEqual "Title of indicator is correct" cTitle iTitle
assertBool "Color of indicator is correct" $ cf iColor
handle xs newState newIndicators
handleRecords :: [CombinationRecord]
-> IndicatorsState
-> [Indicator]
-> IO (IndicatorsState, [Indicator])
handleRecords [] state indicators = return (state, indicators)
handleRecords ((member, isOn, _, _) : xs) state _ = do
let newState = map f state where f (a, b) | a == member = (a, isOn)
| otherwise = (a, b)
changeState member isOn
lines <$> hGetLine pOut
>>= (\x -> head x <$ assertEqual "Only single line" 1 (length x))
>>= return . parseIndicators . getRidOfActions
>>= (\x -> x <$ assertEqual "Indicators count is correct"
(length newState)
(length x)
)
>>= handleRecords xs newState
in flip (handle combinations) indicatorsAtStart [ ("numlock", False)
, ("capslock", False)
, ("alternative", False)
, ("focuslock", False)
]
where -- All combinations of all possible states
-- to check it one by one.
combinations :: [Combination]
combinations = let cf = bool (== "#999") (/= "#999") in
[
[ ("numlock", num, cf num, "num")
, ("capslock", caps, cf caps, caps ? "CAPS" $ "caps")
, ("alternative", alt, cf alt, alt ? "HAX" $ "hax")
, ("focuslock", focus, cf focus, focus ? "[x]" $ "[ ]")
]
| num <- [True, False]
, caps <- [True, False]
, alt <- [True, False]
, focus <- [True, False]
]
getDiffs :: IndicatorsState -> Combination -> [CombinationRecord]
getDiffs state = filter $ \(ca, cb, _, _) ->
isJust $ find (\(sa, sb) -> ca == sa && cb /= sb) state
testTerminating :: Signal -> Test
testTerminating sig = TestCase $ withApp $ \_ pHandle pOut -> do
withProcessHandle pHandle $ \(OpenHandle cpid) -> do
_ <- hGetLine pOut
signalProcess sig cpid
waitForProcess pHandle
>>= assertEqual
("Application terminates by " ++ show sig ++ " successfully")
ExitSuccess
return ()
testKilling :: Test
testKilling = TestCase $ withApp $ \_ pHandle pOut -> do
withProcessHandle pHandle $ \(OpenHandle cpid) -> do
_ <- hGetLine pOut
signalProcess sigKILL cpid
waitForProcess pHandle
>>= assertEqual
"Application died by killing as expected"
(ExitFailure $ negate $ fromIntegral sigKILL)
return ()
withAppAndTerminate :: (Client -> BusName -> Handle -> IO ()) -> IO ()
withAppAndTerminate m = withApp $ \client pHandle pOut -> do
xDpyName <- do dpy <- openDisplay ""
let name = getXDpyName dpy
name `seq` name <$ closeDisplay dpy
let busName = busName_ $ "com.github.unclechu.xmonadrc." ++ xDpyName
m client busName pOut `finally` do
terminateProcess pHandle
waitForProcess pHandle
>>= assertEqual "Application terminated successfully" ExitSuccess
withApp :: (Client -> ProcessHandle -> Handle -> IO ()) -> IO ()
withApp m = withTmpDBus $ \client addr -> do
envList <- filter ((/= "DBUS_SESSION_BUS_ADDRESS") . fst) <$> getEnvironment
(lines -> head -> (++ "/bin") -> binDir) <-
readProcess "stack" ["path", "--local-install-root"] ""
(Nothing, Just pOut, _, pHandle) <-
createProcess
(proc (binDir ++ "/unclechu-xmobar-indicators-cmd") [])
{ std_in = NoStream
, std_out = CreatePipe
, std_err = Inherit
, env = Just $
("DBUS_SESSION_BUS_ADDRESS", formatAddress addr) : envList
}
m client pHandle pOut
`finally` (terminateProcess pHandle >> waitForProcess pHandle)
withTmpDBus :: (Client -> Address -> IO ()) -> IO ()
withTmpDBus m = do
tmpSocketPath <- getTmpDBusSocketPath
let addrPath = "unix:path=" ++ tmpSocketPath
(Nothing, _, _, pHandle) <-
createProcess
(proc "dbus-daemon" ["--address=" ++ addrPath, "--session", "--nofork"])
{ std_in = NoStream
, std_out = Inherit
, std_err = Inherit
}
-- Wait for DBus socket readiness
fix $ \wait ->
doesFileExist tmpSocketPath
>>= flip unless (threadDelay 100000 >> wait)
let Just addr = parseAddress addrPath
client <- connect addr
m client addr
`finally` (disconnect client >> terminateProcess pHandle)
-- Removes <action> wrappers
getRidOfActions :: String -> String
getRidOfActions s = parse (s, "")
where parse :: (String, String) -> String
parse ("", to) = reverse to
parse ((stripPrefix "<action=" -> Just rest), to) =
let (afterAction, insideAction) = actionOpen rest
in parse (afterAction, (insideAction ++ to))
parse (x:xs, to) = parse (xs, x:to)
actionOpen :: String -> (String, String)
actionOpen "" = actionNotClosedErr
actionOpen ('>':xs) = actionClose (xs, "")
actionOpen (_:xs) = actionOpen xs
actionClose :: (String, String) -> (String, String)
actionClose ("", _) = actionNotClosedErr
actionClose ((stripPrefix "</action>" -> Just rest), to) = (rest, to)
actionClose (x:xs, to) = actionClose (xs, x:to)
actionNotClosedErr = error $
"Parse error (<action> opened but not closed) in: '" ++ s ++ "'"
type Color = String
type Title = String
type Indicator = (Color, Title)
parseIndicators :: String -> [Indicator]
parseIndicators s = parse (' ':s, []) -- Add space before for generic handle
where parse :: (String, [Indicator]) -> [Indicator]
parse ("", to) = reverse $ map (\(a, b) -> (reverse a, reverse b)) to
parse ((stripPrefix " <fc=" -> Just rest), to) =
let (afterFc, indicator) = fcOpen (rest, "")
in parse (afterFc, indicator : to)
parse _ = incorrectIndicatorsErr
fcOpen :: (String, Color) -> (String, Indicator)
fcOpen ("", _) = fcNotClosedErr
fcOpen ('>':xs, color) = fcClose (xs, "") & \(a, to) -> (a, (color, to))
fcOpen (x:xs, color) = fcOpen (xs, x : color)
fcClose :: (String, String) -> (String, String)
fcClose ("", _) = fcNotClosedErr
fcClose ((stripPrefix "</fc>" -> Just rest), to) = (rest, to)
fcClose (x:xs, to) = fcClose (xs, x:to)
incorrectIndicatorsErr = error $
"Incorrect indicators: '" ++ s ++ "'"
fcNotClosedErr = error $
"Parse error (<fc> opened but not closed) in: '" ++ s ++ "'"
renderIndicators :: [Indicator] -> String
renderIndicators = unwords . map pairToStr
where pairToStr (color, title) = "<fc=" ++ color ++ ">" ++ title ++ "</fc>"
getXDpyName :: Display -> String
getXDpyName = map f . displayString
where f ':' = '_'
f '.' = '_'
f x = x
(?) :: Bool -> a -> a -> a
(?) True x _ = x
(?) False _ y = y
infixl 1 ?
|
unclechu/xmonadrc
|
xmobar/indicators-cmd/test/Spec.hs
|
gpl-3.0
| 12,885 | 0 | 26 | 4,640 | 3,460 | 1,890 | 1,570 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Sound.Tidal.Tempo where
import Data.Time (getCurrentTime, UTCTime, diffUTCTime)
import Data.Time.Clock.POSIX
import Control.Monad (forM_, forever, void)
import Control.Monad.IO.Class (liftIO)
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.MVar
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Network.WebSockets as WS
import qualified Control.Exception as E
import qualified System.IO.Error as Error
import GHC.Conc.Sync (ThreadId)
import System.Environment (getEnv)
import Sound.Tidal.Utils
data Tempo = Tempo {at :: UTCTime, beat :: Double, bps :: Double}
type ClientState = [WS.Connection]
instance Eq WS.Connection
instance Show Tempo where
show x = show (at x) ++ "," ++ show (beat x) ++ "," ++ show (bps x)
getClockIp :: IO String
getClockIp = getEnvDefault "127.0.0.1" "TIDAL_TEMPO_IP"
getServerPort :: IO Int
getServerPort = fmap read (getEnvDefault "9160" "TIDAL_TEMPO_PORT")
readTempo :: String -> Tempo
readTempo x = Tempo (read a) (read b) (read c)
where (a:b:c:_) = wordsBy (== ',') x
logicalTime :: Tempo -> Double -> Double
logicalTime t b = changeT + timeDelta
where beatDelta = b - (beat t)
timeDelta = beatDelta / (bps t)
changeT = realToFrac $ utcTimeToPOSIXSeconds $ at t
tempoMVar :: IO (MVar (Tempo))
tempoMVar = do now <- getCurrentTime
mv <- newMVar (Tempo now 0 0.5)
forkIO $ clocked $ f mv
return mv
where f mv change _ = do swapMVar mv change
return ()
beatNow :: Tempo -> IO (Double)
beatNow t = do now <- getCurrentTime
let delta = realToFrac $ diffUTCTime now (at t)
let beatDelta = bps t * delta
return $ beat t + beatDelta
clientApp :: MVar Tempo -> MVar Double -> WS.ClientApp ()
clientApp mTempo mBps conn = do
--sink <- WS.getSink
liftIO $ forkIO $ sendBps conn mBps
forever loop
where
loop = do
msg <- WS.receiveData conn
let tempo = readTempo $ T.unpack msg
liftIO $ tryTakeMVar mTempo
liftIO $ putMVar mTempo tempo
sendBps :: WS.Connection -> MVar Double -> IO ()
sendBps conn mBps = forever $ do
bps <- takeMVar mBps
WS.sendTextData conn (T.pack $ show bps)
connectClient :: Bool -> String -> MVar Tempo -> MVar Double -> IO ()
connectClient secondTry ip mTempo mBps = do
let errMsg = "Failed to connect to tidal server. Try specifying a " ++
"different port (default is 9160) setting the " ++
"environment variable TIDAL_TEMPO_PORT"
serverPort <- getServerPort
WS.runClient ip serverPort "/tempo" (clientApp mTempo mBps) `E.catch`
\(_ :: E.SomeException) -> do
case secondTry of
True -> error errMsg
_ -> do
res <- E.try (void startServer)
case res of
Left (_ :: E.SomeException) -> error errMsg
Right _ -> do
threadDelay 500000
connectClient True ip mTempo mBps
runClient :: IO ((MVar Tempo, MVar Double))
runClient =
do clockip <- getClockIp
mTempo <- newEmptyMVar
mBps <- newEmptyMVar
forkIO $ connectClient False clockip mTempo mBps
return (mTempo, mBps)
bpsUtils :: IO ((Double -> IO (), IO (Rational)))
bpsUtils = do (mTempo, mBps) <- runClient
let bpsSetter b = putMVar mBps b
currentTime = do tempo <- readMVar mTempo
now <- beatNow tempo
return $ toRational now
return (bpsSetter, currentTime)
bpsSetter :: IO (Double -> IO ())
bpsSetter = do (f, _) <- bpsUtils
return f
clocked :: (Tempo -> Int -> IO ()) -> IO ()
clocked callback =
do (mTempo, mBps) <- runClient
t <- readMVar mTempo
now <- getCurrentTime
let delta = realToFrac $ diffUTCTime now (at t)
beatDelta = bps t * delta
nowBeat = beat t + beatDelta
nextBeat = ceiling nowBeat
-- next4 = nextBeat + (4 - (nextBeat `mod` 4))
loop mTempo nextBeat
where loop mTempo b =
do t <- readMVar mTempo
now <- getCurrentTime
let delta = realToFrac $ diffUTCTime now (at t)
actualBeat = (beat t) + ((bps t) * delta)
beatDelta = (fromIntegral b) - actualBeat
delay = beatDelta / (bps t)
threadDelay $ floor (delay * 1000000)
callback t b
loop mTempo $ b + 1
clockedTick :: Int -> (Tempo -> Int -> IO ()) -> IO ()
clockedTick tpb callback =
do (mTempo, mBps) <- runClient
t <- readMVar mTempo
now <- getCurrentTime
let delta = realToFrac $ diffUTCTime now (at t)
beatDelta = bps t * delta
nowBeat = beat t + beatDelta
nextTick = ceiling (nowBeat * (fromIntegral tpb))
-- next4 = nextBeat + (4 - (nextBeat `mod` 4))
loop mTempo nextTick
where loop mTempo tick =
do t <- readMVar mTempo
now <- getCurrentTime
let tps = (fromIntegral tpb) * bps t
delta = realToFrac $ diffUTCTime now (at t)
actualTick = ((fromIntegral tpb) * beat t) + (tps * delta)
tickDelta = (fromIntegral tick) - actualTick
delay = tickDelta / tps
threadDelay $ floor (delay * 1000000)
callback t tick
loop mTempo $ tick + 1
updateTempo :: MVar Tempo -> Maybe Double -> IO ()
updateTempo mt Nothing = return ()
updateTempo mt (Just bps') = do t <- takeMVar mt
now <- getCurrentTime
let delta = realToFrac $ diffUTCTime now (at t)
beat' = (beat t) + ((bps t) * delta)
putMVar mt $ Tempo now beat' bps'
addClient :: WS.Connection -> ClientState -> ClientState
addClient client clients = client : clients
removeClient :: WS.Connection -> ClientState -> ClientState
removeClient client = filter (/= client)
broadcast :: Text -> ClientState -> IO ()
broadcast message clients = do
T.putStrLn message
forM_ clients $ \conn -> WS.sendTextData conn $ message
startServer :: IO (ThreadId)
startServer = do
serverPort <- getServerPort
start <- getCurrentTime
tempoState <- newMVar (Tempo start 0 1)
clientState <- newMVar []
forkIO $ WS.runServer "0.0.0.0" serverPort $ serverApp tempoState clientState
serverApp :: MVar Tempo -> MVar ClientState -> WS.ServerApp
serverApp tempoState clientState pending = do
conn <- WS.acceptRequest pending
tempo <- liftIO $ readMVar tempoState
liftIO $ WS.sendTextData conn $ T.pack $ show tempo
clients <- liftIO $ readMVar clientState
liftIO $ modifyMVar_ clientState $ \s -> return $ addClient conn s
serverLoop conn tempoState clientState
serverLoop :: WS.Connection -> MVar Tempo -> MVar ClientState -> IO ()
serverLoop conn tempoState clientState = E.handle catchDisconnect $
forever $ do
msg <- WS.receiveData conn
liftIO $ updateTempo tempoState $ maybeRead $ T.unpack msg
tempo <- liftIO $ readMVar tempoState
liftIO $ readMVar clientState >>= broadcast (T.pack $ show tempo)
where
catchDisconnect e = case E.fromException e of
Just WS.ConnectionClosed -> liftIO $ modifyMVar_ clientState $ \s -> do
let s' = removeClient conn s
return s'
_ -> return ()
|
lennart/Tidal
|
Sound/Tidal/Tempo.hs
|
gpl-3.0
| 7,582 | 0 | 22 | 2,221 | 2,575 | 1,260 | 1,315 | 177 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
-- |
-- Copyright : (c) 2010-2012 Benedikt Schmidt & Simon Meier
-- License : GPL v3 (see LICENSE)
--
-- Maintainer : Simon Meier <[email protected]>
-- Portability : portable
--
-- Rewriting rules representing protocol execution and intruder deduction. Once
-- modulo the full Diffie-Hellman equational theory and once modulo AC.
module Theory.Model.Rule (
-- * General Rules
Rule(..)
, PremIdx(..)
, ConcIdx(..)
-- ** Accessors
, rInfo
, rPrems
, rConcs
, rActs
, rPrem
, rConc
, rNewVars
, lookupPrem
, lookupConc
, enumPrems
, enumConcs
-- ** Genereal protocol and intruder rules
, RuleInfo(..)
, ruleInfo
-- * Protocol Rule Information
, RuleAttribute(..)
, ProtoRuleName(..)
, ProtoRuleEInfo(..)
, preName
, preAttributes
, ProtoRuleACInfo(..)
, pracName
, pracAttributes
, pracVariants
, pracLoopBreakers
, ProtoRuleACInstInfo(..)
, praciName
, praciAttributes
, praciLoopBreakers
, RuleACConstrs
-- * Intruder Rule Information
, IntrRuleACInfo(..)
-- * Concrete Rules
, ProtoRuleE
, ProtoRuleAC
, IntrRuleAC
, RuleAC
, RuleACInst
-- ** Queries
, HasRuleName(..)
, HasRuleAttributes(..)
, isIntruderRule
, isDestrRule
, isIEqualityRule
, isConstrRule
, isPubConstrRule
, isFreshRule
, isIRecvRule
, isISendRule
, isCoerceRule
, isProtocolRule
, isConstantRule
, isSubtermRule
, containsNewVars
, getRuleName
, getRuleNameDiff
, getRemainingRuleApplications
, setRemainingRuleApplications
, nfRule
, normRule
, isTrivialProtoVariantAC
, getNewVariables
, getSubstitutionsFixingNewVars
, compareRulesUpToNewVars
-- ** Conversion
, ruleACToIntrRuleAC
, ruleACIntrToRuleAC
, ruleACIntrToRuleACInst
, getLeftRule
, getRightRule
, constrRuleToDestrRule
, destrRuleToConstrRule
, destrRuleToDestrRule
-- ** Construction
, someRuleACInst
, someRuleACInstAvoiding
, someRuleACInstAvoidingFixing
, someRuleACInstFixing
, addDiffLabel
, removeDiffLabel
, multRuleInstance
, unionRuleInstance
, xorRuleInstance
-- ** Unification
, unifyRuleACInstEqs
, unifiableRuleACInsts
, equalRuleUpToRenaming
-- * Pretty-Printing
, reservedRuleNames
, showRuleCaseName
, prettyProtoRuleName
, prettyRuleName
, prettyRuleAttribute
, prettyProtoRuleE
, prettyProtoRuleAC
, prettyIntrRuleAC
, prettyIntrRuleACInfo
, prettyRuleAC
, prettyLoopBreakers
, prettyRuleACInst
, prettyProtoRuleACInstInfo
, prettyInstLoopBreakers
) where
import Prelude hiding (id, (.))
import GHC.Generics (Generic)
import Data.Binary
import qualified Data.ByteString.Char8 as BC
-- import Data.Foldable (foldMap)
import Data.Data
import Data.List
import qualified Data.Set as S
import qualified Data.Map as M
import Data.Monoid
-- import Data.Maybe (fromMaybe)
import Data.Color
import Safe
-- import Control.Basics
import Control.Category
import Control.DeepSeq
import Control.Monad.Bind
import Control.Monad.Reader
import Extension.Data.Label hiding (get)
import qualified Extension.Data.Label as L
import Logic.Connectives
import Term.LTerm
import Term.Rewriting.Norm (nf', norm')
import Term.Builtin.Convenience (var)
import Term.Unification
import Theory.Model.Fact
import Theory.Text.Pretty
-- import Debug.Trace
------------------------------------------------------------------------------
-- General Rule
------------------------------------------------------------------------------
-- | Rewriting rules with arbitrary additional information and facts with names
-- and logical variables.
data Rule i = Rule {
_rInfo :: i
, _rPrems :: [LNFact]
, _rConcs :: [LNFact]
, _rActs :: [LNFact]
-- contains initially the new variables, then their instantiations
, _rNewVars :: [LNTerm]
}
deriving(Eq, Ord, Show, Data, Typeable, Generic)
instance NFData i => NFData (Rule i)
instance Binary i => Binary (Rule i)
$(mkLabels [''Rule])
-- | An index of a premise. The first premise has index '0'.
newtype PremIdx = PremIdx { getPremIdx :: Int }
deriving( Eq, Ord, Show, Enum, Data, Typeable, Binary, NFData )
-- | An index of a conclusion. The first conclusion has index '0'.
newtype ConcIdx = ConcIdx { getConcIdx :: Int }
deriving( Eq, Ord, Show, Enum, Data, Typeable, Binary, NFData )
-- | @lookupPrem i ru@ returns the @i@-th premise of rule @ru@, if possible.
lookupPrem :: PremIdx -> Rule i -> Maybe LNFact
lookupPrem i = (`atMay` getPremIdx i) . L.get rPrems
-- | @lookupConc i ru@ returns the @i@-th conclusion of rule @ru@, if possible.
lookupConc :: ConcIdx -> Rule i -> Maybe LNFact
lookupConc i = (`atMay` getConcIdx i) . L.get rConcs
-- | @rPrem i@ is a lens for the @i@-th premise of a rule.
rPrem :: PremIdx -> (Rule i :-> LNFact)
rPrem i = nthL (getPremIdx i) . rPrems
-- | @rConc i@ is a lens for the @i@-th conclusion of a rule.
rConc :: ConcIdx -> (Rule i :-> LNFact)
rConc i = nthL (getConcIdx i) . rConcs
-- | Enumerate all premises of a rule.
enumPrems :: Rule i -> [(PremIdx, LNFact)]
enumPrems = zip [(PremIdx 0)..] . L.get rPrems
-- | Enumerate all conclusions of a rule.
enumConcs :: Rule i -> [(ConcIdx, LNFact)]
enumConcs = zip [(ConcIdx 0)..] . L.get rConcs
-- Instances
------------
-- we need special instances for Eq and Ord to ignore the new variable instantiations when comparing rules
-- instance (Eq t) => Eq (Rule t) where
-- (Rule i0 ps0 cs0 as0 _) == (Rule i1 ps1 cs1 as1 _) =
-- (i0 == i1) && (ps0 == ps1) && (cs0 == cs1) && (as0 == as1)
compareRulesUpToNewVars :: (Ord i) => Rule i -> Rule i -> Ordering
compareRulesUpToNewVars (Rule i0 ps0 cs0 as0 _) (Rule i1 ps1 cs1 as1 _) =
if i0 == i1 then
if ps0 == ps1 then
if cs0 == cs1 then
compare as0 as1
else
compare cs0 cs1
else
compare ps0 ps1
else
compare i0 i1
-- deriving instance (Ord t) => Ord (Rule t)
instance Functor Rule where
fmap f (Rule i ps cs as nvs) = Rule (f i) ps cs as nvs
instance (Show i, HasFrees i) => HasFrees (Rule i) where
foldFrees f (Rule i ps cs as nvs) =
(foldFrees f i `mappend`) $
(foldFrees f ps `mappend`) $
(foldFrees f cs `mappend`) $
(foldFrees f as `mappend`) $
(foldFrees f nvs)
-- We do not include the new variables in the occurrences
foldFreesOcc f c (Rule i ps cs as _) =
foldFreesOcc f ((show i):c) (ps, cs, as)
mapFrees f (Rule i ps cs as nvs) =
Rule <$> mapFrees f i
<*> mapFrees f ps <*> mapFrees f cs <*> mapFrees f as
<*> mapFrees f nvs
instance Apply i => Apply (Rule i) where
apply subst (Rule i ps cs as nvs) =
Rule (apply subst i) (apply subst ps) (apply subst cs) (apply subst as) (apply subst nvs)
instance Sized (Rule i) where
size (Rule _ ps cs as _) = size ps + size cs + size as
------------------------------------------------------------------------------
-- Rule information split into intruder rule and protocol rules
------------------------------------------------------------------------------
-- | Rule information for protocol and intruder rules.
data RuleInfo p i =
ProtoInfo p
| IntrInfo i
deriving( Eq, Ord, Show, Generic)
instance (NFData i, NFData p) => NFData (RuleInfo p i)
instance (Binary i, Binary p) => Binary (RuleInfo p i)
-- | @ruleInfo proto intr@ maps the protocol information with @proto@ and the
-- intruder information with @intr@.
ruleInfo :: (p -> c) -> (i -> c) -> RuleInfo p i -> c
ruleInfo proto _ (ProtoInfo x) = proto x
ruleInfo _ intr (IntrInfo x) = intr x
-- Instances
------------
instance (HasFrees p, HasFrees i) => HasFrees (RuleInfo p i) where
foldFrees f = ruleInfo (foldFrees f) (foldFrees f)
foldFreesOcc _ _ = const mempty
mapFrees f = ruleInfo (fmap ProtoInfo . mapFrees f)
(fmap IntrInfo . mapFrees f)
instance (Apply p, Apply i) => Apply (RuleInfo p i) where
apply subst = ruleInfo (ProtoInfo . apply subst) (IntrInfo . apply subst)
------------------------------------------------------------------------------
-- Protocol Rule Information
------------------------------------------------------------------------------
-- | An attribute for a Rule, which does not affect the semantics.
data RuleAttribute = RuleColor (RGB Rational)
deriving( Eq, Ord, Show, Data, Generic)
instance NFData RuleAttribute
instance Binary RuleAttribute
-- | A name of a protocol rule is either one of the special reserved rules or
-- some standard rule.
data ProtoRuleName =
FreshRule
| StandRule String -- ^ Some standard protocol rule
deriving( Eq, Ord, Show, Data, Typeable, Generic)
instance NFData ProtoRuleName
instance Binary ProtoRuleName
-- | Information for protocol rules modulo E.
data ProtoRuleEInfo = ProtoRuleEInfo
{ _preName :: ProtoRuleName
, _preAttributes :: [RuleAttribute]
}
deriving( Eq, Ord, Show, Data, Generic)
instance NFData ProtoRuleEInfo
instance Binary ProtoRuleEInfo
-- | Information for protocol rules modulo AC. The variants list the possible
-- instantiations of the free variables of the rule. The source is interpreted
-- modulo AC; i.e., its variants were also built.
data ProtoRuleACInfo = ProtoRuleACInfo
{ _pracName :: ProtoRuleName
, _pracAttributes :: [RuleAttribute]
, _pracVariants :: Disj (LNSubstVFresh)
, _pracLoopBreakers :: [PremIdx]
}
deriving(Eq, Ord, Show, Generic)
instance NFData ProtoRuleACInfo
instance Binary ProtoRuleACInfo
-- | Information for instances of protocol rules modulo AC.
data ProtoRuleACInstInfo = ProtoRuleACInstInfo
{ _praciName :: ProtoRuleName
, _praciAttributes :: [RuleAttribute]
, _praciLoopBreakers :: [PremIdx]
}
deriving(Eq, Ord, Show, Generic)
instance NFData ProtoRuleACInstInfo
instance Binary ProtoRuleACInstInfo
$(mkLabels [''ProtoRuleEInfo, ''ProtoRuleACInfo, ''ProtoRuleACInstInfo])
-- Instances
------------
instance Apply RuleAttribute where
apply _ = id
instance HasFrees RuleAttribute where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
instance Apply ProtoRuleName where
apply _ = id
instance HasFrees ProtoRuleName where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
instance Apply PremIdx where
apply _ = id
instance HasFrees PremIdx where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
instance Apply ConcIdx where
apply _ = id
instance HasFrees ConcIdx where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
instance HasFrees ProtoRuleEInfo where
foldFrees f (ProtoRuleEInfo na attr) =
foldFrees f na `mappend` foldFrees f attr
foldFreesOcc _ _ = const mempty
mapFrees f (ProtoRuleEInfo na attr) =
ProtoRuleEInfo na <$> mapFrees f attr
instance Apply ProtoRuleEInfo where
apply _ = id
instance HasFrees ProtoRuleACInfo where
foldFrees f (ProtoRuleACInfo na attr vari breakers) =
foldFrees f na `mappend` foldFrees f attr
`mappend` foldFrees f vari
`mappend` foldFrees f breakers
foldFreesOcc _ _ = const mempty
mapFrees f (ProtoRuleACInfo na attr vari breakers) =
ProtoRuleACInfo na <$> mapFrees f attr
<*> mapFrees f vari
<*> mapFrees f breakers
instance Apply ProtoRuleACInstInfo where
apply subst (ProtoRuleACInstInfo na attr breakers) =
ProtoRuleACInstInfo (apply subst na) attr breakers
instance HasFrees ProtoRuleACInstInfo where
foldFrees f (ProtoRuleACInstInfo na attr breakers) =
foldFrees f na `mappend` foldFrees f attr
`mappend` foldFrees f breakers
foldFreesOcc _ _ = const mempty
mapFrees f (ProtoRuleACInstInfo na attr breakers) =
ProtoRuleACInstInfo na <$> mapFrees f attr <*> mapFrees f breakers
------------------------------------------------------------------------------
-- Intruder Rule Information
------------------------------------------------------------------------------
-- | An intruder rule modulo AC is described by its name.
data IntrRuleACInfo =
ConstrRule BC.ByteString
| DestrRule BC.ByteString Int Bool Bool
-- the number of remaining consecutive applications of this destruction rule, 0 means unbounded, -1 means not yet determined
-- true if the RHS is a true subterm of the LHS
-- true if the RHS is a constant
| CoerceRule
| IRecvRule
| ISendRule
| PubConstrRule
| FreshConstrRule
| IEqualityRule -- Necessary for diff
deriving( Ord, Eq, Show, Data, Typeable, Generic)
instance NFData IntrRuleACInfo
instance Binary IntrRuleACInfo
-- | An intruder rule modulo AC.
type IntrRuleAC = Rule IntrRuleACInfo
-- | Converts between these two types of rules, if possible.
ruleACToIntrRuleAC :: RuleAC -> Maybe IntrRuleAC
ruleACToIntrRuleAC (Rule (IntrInfo i) ps cs as nvs) = Just (Rule i ps cs as nvs)
ruleACToIntrRuleAC _ = Nothing
-- | Converts between these two types of rules.
ruleACIntrToRuleAC :: IntrRuleAC -> RuleAC
ruleACIntrToRuleAC (Rule ri ps cs as nvs) = Rule (IntrInfo ri) ps cs as nvs
-- | Converts between these two types of rules.
ruleACIntrToRuleACInst :: IntrRuleAC -> RuleACInst
ruleACIntrToRuleACInst (Rule ri ps cs as nvs) = Rule (IntrInfo ri) ps cs as nvs
-- | Converts between constructor and destructor rules.
constrRuleToDestrRule :: RuleAC -> Int -> Bool -> Bool -> [RuleAC]
constrRuleToDestrRule (Rule (IntrInfo (ConstrRule name)) ps' cs _ _) i s c
-- we remove the actions and new variables as destructors do not have actions or new variables
= map toRule $ permutations ps'
where
toRule :: [LNFact] -> RuleAC
toRule [] = error "Bug in constrRuleToDestrRule. Please report."
toRule (p:ps) = Rule (IntrInfo (DestrRule name i s c)) ((convertKUtoKD p):ps) (map convertKUtoKD cs) [] []
constrRuleToDestrRule _ _ _ _ = error "Not a destructor rule."
-- | Converts between destructor and constructor rules.
destrRuleToConstrRule :: FunSym -> Int -> RuleAC -> RuleAC
destrRuleToConstrRule f l (Rule (IntrInfo (DestrRule name _ _ _)) ps cs _ _)
= toRule (map convertKDtoKU ps ++ kuFacts) (conclusions cs)
where
-- we add the conclusion as an action as constructors have this action
toRule :: [LNFact] -> [LNFact] -> RuleAC
toRule ps' cs' = Rule (IntrInfo (ConstrRule name)) ps' cs' cs' []
conclusions [] = []
-- KD and KU facts only have one term
conclusions ((Fact KDFact ann (m:ms)):cs') = (Fact KUFact ann ((addTerms m):ms)):(conclusions cs')
conclusions (c:cs') = c:(conclusions cs')
addTerms (FAPP f' t) | f'==f = fApp f (t ++ newvars)
addTerms t = fApp f (t:newvars)
kuFacts = map kuFact newvars
newvars = map (var "z") [1..(toInteger $ l-(length ps))]
destrRuleToConstrRule _ _ _ = error "Not a constructor rule."
-- | Creates variants of a destructor rule, where KD and KU facts are permuted.
destrRuleToDestrRule :: RuleAC -> [RuleAC]
destrRuleToDestrRule (Rule (IntrInfo (DestrRule name i s c)) ps' cs as nv)
= map toRule $ permutations (map convertKDtoKU ps')
where
toRule [] = error "Bug in destrRuleToDestrRule. Please report."
toRule (p:ps) = Rule (IntrInfo (DestrRule name i s c)) ((convertKUtoKD p):ps) cs as nv
destrRuleToDestrRule _ = error "Not a destructor rule."
-- Instances
------------
instance Apply IntrRuleACInfo where
apply _ = id
instance HasFrees IntrRuleACInfo where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
------------------------------------------------------------------------------
-- Concrete rules
------------------------------------------------------------------------------
-- | A rule modulo E is always a protocol rule. Intruder rules are specified
-- abstractly by their operations generating them and are only available once
-- their variants are built.
type ProtoRuleE = Rule ProtoRuleEInfo
-- | A protocol rule modulo AC.
type ProtoRuleAC = Rule ProtoRuleACInfo
-- | A rule modulo AC is either a protocol rule or an intruder rule
type RuleAC = Rule (RuleInfo ProtoRuleACInfo IntrRuleACInfo)
-- | A rule instance module AC is either a protocol rule or an intruder rule.
-- The info identifies the corresponding rule modulo AC that the instance was
-- derived from.
type RuleACInst = Rule (RuleInfo ProtoRuleACInstInfo IntrRuleACInfo)
-- Accessing the rule name
--------------------------
-- | Types that have an associated name.
class HasRuleName t where
ruleName :: t -> RuleInfo ProtoRuleName IntrRuleACInfo
instance HasRuleName ProtoRuleE where
ruleName = ProtoInfo . L.get (preName . rInfo)
instance HasRuleName RuleAC where
ruleName = ruleInfo (ProtoInfo . L.get pracName) IntrInfo . L.get rInfo
instance HasRuleName ProtoRuleAC where
ruleName = ProtoInfo . L.get (pracName . rInfo)
instance HasRuleName IntrRuleAC where
ruleName = IntrInfo . L.get rInfo
instance HasRuleName RuleACInst where
ruleName = ruleInfo (ProtoInfo . L.get praciName) IntrInfo . L.get rInfo
class HasRuleAttributes t where
ruleAttributes :: t -> [RuleAttribute]
instance HasRuleAttributes ProtoRuleE where
ruleAttributes = L.get (preAttributes . rInfo)
instance HasRuleAttributes RuleAC where
ruleAttributes (Rule (ProtoInfo ri) _ _ _ _) = L.get pracAttributes ri
ruleAttributes _ = []
instance HasRuleAttributes ProtoRuleAC where
ruleAttributes = L.get (pracAttributes . rInfo)
instance HasRuleAttributes IntrRuleAC where
ruleAttributes _ = []
instance HasRuleAttributes RuleACInst where
ruleAttributes (Rule (ProtoInfo ri) _ _ _ _) = L.get praciAttributes ri
ruleAttributes _ = []
-- Queries
----------
-- | True iff the rule is a destruction rule.
isDestrRule :: HasRuleName r => r -> Bool
isDestrRule ru = case ruleName ru of
IntrInfo (DestrRule _ _ _ _) -> True
IntrInfo IEqualityRule -> True
_ -> False
-- | True iff the rule is an iequality rule.
isIEqualityRule :: HasRuleName r => r -> Bool
isIEqualityRule ru = case ruleName ru of
IntrInfo IEqualityRule -> True
_ -> False
-- | True iff the rule is a construction rule.
isConstrRule :: HasRuleName r => r -> Bool
isConstrRule ru = case ruleName ru of
IntrInfo (ConstrRule _) -> True
IntrInfo FreshConstrRule -> True
IntrInfo PubConstrRule -> True
IntrInfo CoerceRule -> True
_ -> False
-- | True iff the rule is a construction rule.
isPubConstrRule :: HasRuleName r => r -> Bool
isPubConstrRule ru = case ruleName ru of
IntrInfo PubConstrRule -> True
_ -> False
-- | True iff the rule is the special fresh rule.
isFreshRule :: HasRuleName r => r -> Bool
isFreshRule = (ProtoInfo FreshRule ==) . ruleName
-- | True iff the rule is the special learn rule.
isIRecvRule :: HasRuleName r => r -> Bool
isIRecvRule = (IntrInfo IRecvRule ==) . ruleName
-- | True iff the rule is the special knows rule.
isISendRule :: HasRuleName r => r -> Bool
isISendRule = (IntrInfo ISendRule ==) . ruleName
-- | True iff the rule is the special coerce rule.
isCoerceRule :: HasRuleName r => r -> Bool
isCoerceRule = (IntrInfo CoerceRule ==) . ruleName
-- | True iff the rule is a destruction rule with constant RHS.
isConstantRule :: HasRuleName r => r -> Bool
isConstantRule ru = case ruleName ru of
IntrInfo (DestrRule _ _ _ constant) -> constant
_ -> False
-- | True iff the rule is a destruction rule where the RHS is a true subterm of the LHS.
isSubtermRule :: HasRuleName r => r -> Bool
isSubtermRule ru = case ruleName ru of
IntrInfo (DestrRule _ _ subterm _) -> subterm
IntrInfo IEqualityRule -> True
-- the equality rule is considered a subterm rule, as it has no RHS.
_ -> False
-- | True if the messages in premises and conclusions are in normal form
nfRule :: Rule i -> WithMaude Bool
nfRule (Rule _ ps cs as nvs) = reader $ \hnd ->
all (nfFactList hnd) [ps, cs, as, map termFact nvs]
where
nfFactList hnd xs =
getAll $ foldMap (foldMap (All . (\t -> nf' t `runReader` hnd))) xs
-- | Normalize all terms in premises, actions and conclusions
normRule :: Rule i -> WithMaude (Rule i)
normRule (Rule rn ps cs as nvs) = reader $ \hnd -> (Rule rn (normFacts ps hnd) (normFacts cs hnd) (normFacts as hnd) (normTerms nvs hnd))
where
normFacts fs hnd' = map (\f -> runReader (normFact f) hnd') fs
normTerms fs hnd' = map (\f -> runReader (norm' f) hnd') fs
-- | True iff the rule is an intruder rule
isIntruderRule :: HasRuleName r => r -> Bool
isIntruderRule ru =
case ruleName ru of IntrInfo _ -> True; ProtoInfo _ -> False
-- | True iff the rule is an intruder rule
isProtocolRule :: HasRuleName r => r -> Bool
isProtocolRule ru =
case ruleName ru of IntrInfo _ -> False; ProtoInfo _ -> True
-- | True if the protocol rule has only the trivial variant.
isTrivialProtoVariantAC :: ProtoRuleAC -> ProtoRuleE -> Bool
isTrivialProtoVariantAC (Rule info ps as cs nvs) (Rule _ ps' as' cs' nvs') =
L.get pracVariants info == Disj [emptySubstVFresh]
&& ps == ps' && as == as' && cs == cs' && nvs == nvs'
-- | Returns a rule's name
getRuleName :: HasRuleName (Rule i) => Rule i -> String
getRuleName ru = case ruleName ru of
IntrInfo i -> case i of
ConstrRule x -> "Constr" ++ (prefixIfReserved ('c' : BC.unpack x))
DestrRule x _ _ _ -> "Destr" ++ (prefixIfReserved ('d' : BC.unpack x))
CoerceRule -> "Coerce"
IRecvRule -> "Recv"
ISendRule -> "Send"
PubConstrRule -> "PubConstr"
FreshConstrRule -> "FreshConstr"
IEqualityRule -> "Equality"
ProtoInfo p -> case p of
FreshRule -> "FreshRule"
StandRule s -> s
-- | Returns a protocol rule's name
getRuleNameDiff :: HasRuleName (Rule i) => Rule i -> String
getRuleNameDiff ru = case ruleName ru of
IntrInfo i -> "Intr" ++ case i of
ConstrRule x -> "Constr" ++ (prefixIfReserved ('c' : BC.unpack x))
DestrRule x _ _ _ -> "Destr" ++ (prefixIfReserved ('d' : BC.unpack x))
CoerceRule -> "Coerce"
IRecvRule -> "Recv"
ISendRule -> "Send"
PubConstrRule -> "PubConstr"
FreshConstrRule -> "FreshConstr"
IEqualityRule -> "Equality"
ProtoInfo p -> "Proto" ++ case p of
FreshRule -> "FreshRule"
StandRule s -> s
-- | Returns the remaining rule applications within the deconstruction chain if possible, 0 otherwise
getRemainingRuleApplications :: RuleACInst -> Int
getRemainingRuleApplications ru = case ruleName ru of
IntrInfo (DestrRule _ i _ _) -> i
_ -> 0
-- | Sets the remaining rule applications within the deconstruction chain if possible
setRemainingRuleApplications :: RuleACInst -> Int -> RuleACInst
setRemainingRuleApplications (Rule (IntrInfo (DestrRule name _ subterm constant)) prems concs acts nvs) i
= Rule (IntrInfo (DestrRule name i subterm constant)) prems concs acts nvs
setRemainingRuleApplications rule _
= rule
-- | Converts a protocol rule to its "left" variant
getLeftRule :: ProtoRuleE -> ProtoRuleE
getLeftRule (Rule ri ps cs as nvs) =
(Rule ri (map getLeftFact ps) (map getLeftFact cs) (map getLeftFact as) (map getLeftTerm nvs))
-- | Converts a protocol rule to its "left" variant
getRightRule :: ProtoRuleE -> ProtoRuleE
getRightRule (Rule ri ps cs as nvs) =
(Rule ri (map getRightFact ps) (map getRightFact cs) (map getRightFact as) (map getRightTerm nvs))
-- | Returns a list of all new variables that need to be fixed for mirroring
getNewVariables :: Bool -> RuleACInst -> [LVar]
getNewVariables showPubVars (Rule _ _ _ _ nvs) = case showPubVars of
True -> newvars
False -> filter (\v -> not $ lvarSort v == LSortPub) newvars
where
newvars = toVariables nvs
toVariables [] = []
toVariables (x:xs) = case getVar x of
Just v -> v:(toVariables xs)
-- if the variable is already fixed, no need to fix it again!
Nothing -> toVariables xs
-- | Returns whether a given rule has new variables
containsNewVars :: RuleACInst -> Bool
containsNewVars (Rule _ _ _ _ nvs) = nvs == []
-- | Given a fresh rule instance and the rule instance to mirror, returns a substitution
-- determining how all new variables need to be instantiated if possible.
-- First parameter: original instance to mirror
-- Second parameter: fresh instance
getSubstitutionsFixingNewVars :: RuleACInst -> RuleACInst -> Maybe LNSubst
getSubstitutionsFixingNewVars (Rule (ProtoInfo (ProtoRuleACInstInfo _ _ _)) _ _ _ instancesO)
(Rule (ProtoInfo (ProtoRuleACInstInfo _ _ _)) _ _ _ instancesF)
| all (\(x, y) -> isPubVar x || x == y) $ zip instancesF instancesO
= Just $ Subst $ M.fromList $ substList instancesF instancesO
-- otherwise there is no substitution
| otherwise
= Nothing
where
substList [] [] = []
substList (f:fs) (o:os) = case getVar f of
Nothing -> (substList fs os)
Just v -> (v, o):(substList fs os)
substList _ _ = error "getSubstitutionsFixingNewVars: different number of new variables"
getSubstitutionsFixingNewVars _ _
= error "getSubstitutionsFixingNewVars: not called on a protocol rule" -- FIXME: Nothing?
-- Construction
---------------
-- | Returns a multiplication rule instance of the given size.
multRuleInstance :: Int -> RuleAC
multRuleInstance n = (Rule (IntrInfo (ConstrRule $ BC.pack "_mult")) (map xifact [1..n]) [prod] [prod] [])
where
prod = kuFact (FAPP (AC Mult) (map xi [1..n]))
xi :: Int -> LNTerm
xi k = (LIT $ Var $ LVar "x" LSortMsg (toInteger k))
xifact :: Int -> LNFact
xifact k = kuFact (xi k)
-- | Returns a union rule instance of the given size.
unionRuleInstance :: Int -> RuleAC
unionRuleInstance n = (Rule (IntrInfo (ConstrRule $ BC.pack "_union")) (map xifact [1..n]) [prod] [prod] [])
where
prod = kuFact (FAPP (AC Union) (map xi [1..n]))
xi :: Int -> LNTerm
xi k = (LIT $ Var $ LVar "x" LSortMsg (toInteger k))
xifact :: Int -> LNFact
xifact k = kuFact (xi k)
-- | Returns a xor rule instance of the given size.
xorRuleInstance :: Int -> RuleAC
xorRuleInstance n = (Rule (IntrInfo (ConstrRule $ BC.pack "_xor")) (map xifact [1..n]) [prod] [prod] [])
where
prod = Fact KUFact S.empty [(FAPP (AC Xor) (map xi [1..n]))]
xi :: Int -> LNTerm
xi k = (LIT $ Var $ LVar "x" LSortMsg (toInteger k))
xifact :: Int -> LNFact
xifact k = Fact KUFact S.empty [(xi k)]
type RuleACConstrs = Disj LNSubstVFresh
-- | Compute /some/ rule instance of a rule modulo AC. If the rule is a
-- protocol rule, then the given source and variants also need to be handled.
someRuleACInst :: MonadFresh m
=> RuleAC
-> m (RuleACInst, Maybe RuleACConstrs)
someRuleACInst =
fmap extractInsts . rename
where
extractInsts (Rule (ProtoInfo i) ps cs as nvs) =
( Rule (ProtoInfo i') ps cs as nvs
, Just (L.get pracVariants i)
)
where
i' = ProtoRuleACInstInfo (L.get pracName i)
(L.get pracAttributes i)
(L.get pracLoopBreakers i)
extractInsts (Rule (IntrInfo i) ps cs as nvs) =
( Rule (IntrInfo i) ps cs as nvs, Nothing )
-- | Compute /some/ rule instance of a rule modulo AC. If the rule is a
-- protocol rule, then the given source and variants also need to be handled.
someRuleACInstAvoiding :: HasFrees t
=> RuleAC
-> t
-> (RuleACInst, Maybe RuleACConstrs)
someRuleACInstAvoiding r s =
renameAvoiding (extractInsts r) s
where
extractInsts (Rule (ProtoInfo i) ps cs as nvs) =
( Rule (ProtoInfo i') ps cs as nvs
, Just (L.get pracVariants i)
)
where
i' = ProtoRuleACInstInfo (L.get pracName i)
(L.get pracAttributes i)
(L.get pracLoopBreakers i)
extractInsts (Rule (IntrInfo i) ps cs as nvs) =
( Rule (IntrInfo i) ps cs as nvs, Nothing )
-- | Compute /some/ rule instance of a rule modulo AC. If the rule is a
-- protocol rule, then the given source and variants also need to be handled.
someRuleACInstFixing :: MonadFresh m
=> RuleAC
-> LNSubst
-> m (RuleACInst, Maybe RuleACConstrs)
someRuleACInstFixing r subst =
renameIgnoring (varsRange subst) (extractInsts r)
where
extractInsts (Rule (ProtoInfo i) ps cs as nvs) =
( apply subst (Rule (ProtoInfo i') ps cs as nvs)
, Just (L.get pracVariants i)
)
where
i' = ProtoRuleACInstInfo (L.get pracName i)
(L.get pracAttributes i)
(L.get pracLoopBreakers i)
extractInsts (Rule (IntrInfo i) ps cs as nvs) =
( apply subst (Rule (IntrInfo i) ps cs as nvs), Nothing )
-- | Compute /some/ rule instance of a rule modulo AC. If the rule is a
-- protocol rule, then the given source and variants also need to be handled.
someRuleACInstAvoidingFixing :: HasFrees t
=> RuleAC
-> t
-> LNSubst
-> (RuleACInst, Maybe RuleACConstrs)
someRuleACInstAvoidingFixing r s subst =
renameAvoidingIgnoring (extractInsts r) s (varsRange subst)
where
extractInsts (Rule (ProtoInfo i) ps cs as nvs) =
( apply subst (Rule (ProtoInfo i') ps cs as nvs)
, Just (L.get pracVariants i)
)
where
i' = ProtoRuleACInstInfo (L.get pracName i)
(L.get pracAttributes i)
(L.get pracLoopBreakers i)
extractInsts (Rule (IntrInfo i) ps cs as nvs) =
( apply subst (Rule (IntrInfo i) ps cs as nvs), Nothing )
-- | Add the diff label to a rule
addDiffLabel :: Rule a -> String -> Rule a
addDiffLabel (Rule info prems concs acts nvs) name = Rule info prems concs (acts ++ [Fact {factTag = ProtoFact Linear name 0, factAnnotations = S.empty, factTerms = []}]) nvs
-- | Remove the diff label from a rule
removeDiffLabel :: Rule a -> String -> Rule a
removeDiffLabel (Rule info prems concs acts nvs) name = Rule info prems concs (filter isNotDiffAnnotation acts) nvs
where
isNotDiffAnnotation fa = (fa /= Fact {factTag = ProtoFact Linear name 0, factAnnotations = S.empty, factTerms = []})
-- Unification
--------------
-- | Unify a list of @RuleACInst@ equalities.
unifyRuleACInstEqs :: [Equal RuleACInst] -> WithMaude [LNSubstVFresh]
unifyRuleACInstEqs eqs
| all unifiable eqs = unifyLNFactEqs $ concatMap ruleEqs eqs
| otherwise = return []
where
unifiable (Equal ru1 ru2) =
L.get rInfo ru1 == L.get rInfo ru2
&& length (L.get rPrems ru1) == length (L.get rPrems ru2)
&& length (L.get rConcs ru1) == length (L.get rConcs ru2)
ruleEqs (Equal ru1 ru2) =
zipWith Equal (L.get rPrems ru1) (L.get rPrems ru2) ++
zipWith Equal (L.get rConcs ru1) (L.get rConcs ru2)
-- | Are these two rule instances unifiable?
unifiableRuleACInsts :: RuleACInst -> RuleACInst -> WithMaude Bool
unifiableRuleACInsts ru1 ru2 =
(not . null) <$> unifyRuleACInstEqs [Equal ru1 ru2]
-- | Are these two rule instances equal up to renaming of variables?
equalRuleUpToRenaming :: (Show a, Eq a, HasFrees a) => Rule a -> Rule a -> WithMaude Bool
equalRuleUpToRenaming r1@(Rule rn1 pr1 co1 ac1 nvs1) r2@(Rule rn2 pr2 co2 ac2 nvs2) = reader $ \hnd ->
case eqs of
Nothing -> False
Just eqs' -> (rn1 == rn2) && (any isRenamingPerRule $ unifs eqs' hnd)
where
isRenamingPerRule subst = isRenaming (restrictVFresh (vars r1) subst) && isRenaming (restrictVFresh (vars r2) subst)
vars ru = map fst $ varOccurences ru
unifs eq hnd = unifyLNTerm eq `runReader` hnd
eqs = foldl matchFacts (Just $ zipWith Equal nvs1 nvs2) $ zip (pr1++co1++ac1) (pr2++co2++ac2)
matchFacts Nothing _ = Nothing
matchFacts (Just l) (Fact f1 _ t1, Fact f2 _ t2) | f1 == f2 = Just ((zipWith Equal t1 t2)++l)
| otherwise = Nothing
------------------------------------------------------------------------------
-- Fact analysis
------------------------------------------------------------------------------
-- | Globally unique facts.
--
-- A rule instance removes a fact fa if fa is in the rule's premise but not
-- in the rule's conclusion.
--
-- A fact symbol fa is globally fresh with respect to a dependency graph if
-- there are no two rule instances that remove the same fact built from fa.
--
-- We are looking for sufficient criterion to prove that a fact symbol is
-- globally fresh.
--
-- The Fr symbol is globally fresh by construction.
--
-- We have to track every creation of a globally fresh fact to a Fr fact.
--
-- (And show that the equality of of the created fact implies the equality of
-- the corresponding fresh facts. Ignore this for now by assuming that no
-- duplication happens.)
--
-- (fa(x1), fr(y1)), (fa(x2), fr(y2)) : x2 = x1 ==> y1 == y2
--
-- And ensure that every duplication is non-unifiable.
--
-- A Fr fact is described
--
-- We track which symbols are not globally fresh.
--
-- All persistent facts are not globally fresh.
--
-- Adding a rule ru.
-- All fact symbols that occur twice in the conclusion
--
-- For simplicity: globally fresh fact symbols occur at most once in premise
-- and conclusion of a rule.
--
-- A fact is removed by a rule if it occurs in the rules premise
-- 1. but doesn't occur in the rule's conclusion
-- 2. or does occur but non-unifiable.
--
-- We want a sufficient criterion to prove that a fact is globally unique.
--
--
------------------------------------------------------------------------------
-- Pretty-Printing
------------------------------------------------------------------------------
-- | Prefix the name if it is equal to a reserved name.
--
-- NOTE: We maintain the invariant that a theory does not contain standard
-- rules with a reserved name. This is a last ressort. The pretty-printed
-- theory can then not be parsed anymore.
prefixIfReserved :: String -> String
prefixIfReserved n
| n `elem` reservedRuleNames = "_" ++ n
| "_" `isPrefixOf` n = "_" ++ n
| otherwise = n
-- | List of all reserved rule names.
reservedRuleNames :: [String]
reservedRuleNames = ["Fresh", "irecv", "isend", "coerce", "fresh", "pub", "iequality"]
prettyProtoRuleName :: Document d => ProtoRuleName -> d
prettyProtoRuleName rn = text $ case rn of
FreshRule -> "Fresh"
StandRule n -> prefixIfReserved n
prettyRuleName :: (HighlightDocument d, HasRuleName (Rule i)) => Rule i -> d
prettyRuleName = ruleInfo prettyProtoRuleName prettyIntrRuleACInfo . ruleName
prettyRuleAttribute :: (HighlightDocument d) => RuleAttribute -> d
prettyRuleAttribute attr = case attr of
RuleColor c -> text "color=" <> text (rgbToHex c)
-- | Pretty print the rule name such that it can be used as a case name
showRuleCaseName :: HasRuleName (Rule i) => Rule i -> String
showRuleCaseName =
render . ruleInfo prettyProtoRuleName prettyIntrRuleACInfo . ruleName
prettyIntrRuleACInfo :: Document d => IntrRuleACInfo -> d
prettyIntrRuleACInfo rn = text $ case rn of
IRecvRule -> "irecv"
ISendRule -> "isend"
CoerceRule -> "coerce"
FreshConstrRule -> "fresh"
PubConstrRule -> "pub"
IEqualityRule -> "iequality"
ConstrRule name -> prefixIfReserved ('c' : BC.unpack name)
DestrRule name _ _ _ -> prefixIfReserved ('d' : BC.unpack name)
-- DestrRule name i -> prefixIfReserved ('d' : BC.unpack name ++ "_" ++ show i)
prettyNamedRule :: (HighlightDocument d, HasRuleName (Rule i), HasRuleAttributes (Rule i))
=> d -- ^ Prefix.
-> (i -> d) -- ^ Rule info pretty printing.
-> Rule i -> d
prettyNamedRule prefix ppInfo ru =
prefix <-> prettyRuleName ru <> ppAttributes <> colon $-$
nest 2 (sep [ nest 1 $ ppFactsList rPrems
, if null acts
then operator_ "-->"
else fsep [operator_ "--[", ppFacts' acts, operator_ "]->"]
, nest 1 $ ppFactsList rConcs]) $-$
nest 2 (ppInfo $ L.get rInfo ru) -- $-$
-- Debug:
-- (keyword_ "new variables: ") <> (ppList prettyLNTerm $ L.get rNewVars ru)
where
acts = filter isNotDiffAnnotation (L.get rActs ru)
ppList pp = fsep . punctuate comma . map pp
ppFacts' list = ppList prettyLNFact list
ppFacts proj = ppList prettyLNFact $ L.get proj ru
ppFactsList proj = fsep [operator_ "[", ppFacts proj, operator_ "]"]
isNotDiffAnnotation fa = (fa /= Fact {factTag = ProtoFact Linear ("Diff" ++ getRuleNameDiff ru) 0, factAnnotations = S.empty, factTerms = []})
ppAttributes = case ruleAttributes ru of
[] -> text ""
attrs -> hcat $ [text "[", hsep $ map prettyRuleAttribute attrs, text "]"]
prettyProtoRuleACInfo :: HighlightDocument d => ProtoRuleACInfo -> d
prettyProtoRuleACInfo i =
(ppVariants $ L.get pracVariants i) $-$
prettyLoopBreakers i
where
ppVariants (Disj [subst]) | subst == emptySubstVFresh = emptyDoc
ppVariants substs = kwVariantsModulo "AC" $-$ prettyDisjLNSubstsVFresh substs
prettyProtoRuleACInstInfo :: HighlightDocument d => ProtoRuleACInstInfo -> d
prettyProtoRuleACInstInfo i = prettyInstLoopBreakers i
prettyLoopBreakers :: HighlightDocument d => ProtoRuleACInfo -> d
prettyLoopBreakers i = case breakers of
[] -> emptyDoc
[_] -> lineComment_ $ "loop breaker: " ++ show breakers
_ -> lineComment_ $ "loop breakers: " ++ show breakers
where
breakers = getPremIdx <$> L.get pracLoopBreakers i
prettyInstLoopBreakers :: HighlightDocument d => ProtoRuleACInstInfo -> d
prettyInstLoopBreakers i = case breakers of
[] -> emptyDoc
[_] -> lineComment_ $ "loop breaker: " ++ show breakers
_ -> lineComment_ $ "loop breakers: " ++ show breakers
where
breakers = getPremIdx <$> L.get praciLoopBreakers i
prettyProtoRuleE :: HighlightDocument d => ProtoRuleE -> d
prettyProtoRuleE = prettyNamedRule (kwRuleModulo "E") (const emptyDoc)
prettyRuleAC :: HighlightDocument d => RuleAC -> d
prettyRuleAC =
prettyNamedRule (kwRuleModulo "AC")
(ruleInfo prettyProtoRuleACInfo (const emptyDoc))
prettyIntrRuleAC :: HighlightDocument d => IntrRuleAC -> d
prettyIntrRuleAC = prettyNamedRule (kwRuleModulo "AC") (const emptyDoc)
prettyProtoRuleAC :: HighlightDocument d => ProtoRuleAC -> d
prettyProtoRuleAC = prettyNamedRule (kwRuleModulo "AC") prettyProtoRuleACInfo
prettyRuleACInst :: HighlightDocument d => RuleACInst -> d
prettyRuleACInst = prettyNamedRule (kwInstanceModulo "AC") (const emptyDoc)
|
rsasse/tamarin-prover
|
lib/theory/src/Theory/Model/Rule.hs
|
gpl-3.0
| 41,188 | 0 | 18 | 10,724 | 10,267 | 5,359 | 4,908 | 682 | 10 |
{-|
Module : Setseer.Pixel
Description : Generate pixels
Copyright : Erik Edlund
License : GPL-3
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
-}
module Setseer.Pixel where
import Codec.Picture
import Data.Complex
import Data.Vector
import Data.Word
import Setseer.Color
import Setseer.Glue
escapeColorPixel
:: SetParams
-> Escape
-> PixelRGB8
escapeColorPixel params escs
| n < 256
= colors params ! n
| otherwise
= PixelRGB8 0 0 0
where
cX = realPart $ snd escs
cY = imagPart $ snd escs
sqr = (cX * cX) + (cY * cY)
adj = if sqr > ee
then log ((log sqr) / 2.0) / logFor2
else 0.0
a = (fst escs - truncate adj) * 255
n = abs $ truncate $ (frI a) / (frI (escapeIter params))
rainbowPixel
:: SetParams
-> Escape
-> PixelRGB8
rainbowPixel params escs
| fst escs < escapeIter params
= convertHSVdToPixelRGB8 h s v
| otherwise
= PixelRGB8 0 0 0
where
s = 0.7
v = 1.0
n = fst escs
z = snd escs
a = realPart $ abs z
m = frI n + 1.0 - log (log a) / logFor2
h = frI (escapeIter params - fst escs) / m
-- Escape for `z^(2) + c`; handles Mandelbrot and Julia sets
-- when given appropriate values for `c` and `z`.
escape_ZZ_plus_C
:: SetParams
-> Int
-> Complex''
-> Complex''
-> Escape
escape_ZZ_plus_C params i (cX, cY) (zX, zY)
| i < escapeIter params && m < escapeLimit
= escape_ZZ_plus_C params (i + 1) (cX, cY) (zX', zY')
| otherwise
= (i, (zX :+ zY))
where
m = (zX * zX) + (zY * zY)
zX' = zX * zX - zY * zY + cX
zY' = 2.0 * zX * zY + cY
-- Curry to taste.
pixelRenderer
:: SetParams
-> (SetParams -> Int -> Complex'' -> Complex'' -> Escape)
-> (SetParams -> Int -> Int -> Complex'')
-> (SetParams -> Int -> Int -> Complex'')
-> (SetParams -> Escape -> PixelRGB8)
-> Int
-> Int
-> PixelRGB8
pixelRenderer params esc cC cZ pxl x y
= pxl params escs
where
c = cC params x y
z = cZ params x y
escs = esc params 0 c z
|
edlund/setseer
|
sources/Setseer/Pixel.hs
|
gpl-3.0
| 2,058 | 0 | 13 | 583 | 734 | 380 | 354 | 68 | 2 |
module ModifyingTreeSpec where
import Test.Hspec
import NodeEditor.Data
import NodeEditor.Parser
spec = do
describe "setNodeBody" $ do
it "replaces the node body for the given id" $ do
let tree = treeFromText "node body"
let newTree = setNodeBody tree 0 "fosho"
getNodeBody newTree 0 `shouldBe` "fosho"
|
rickardlindberg/node-editor-2
|
test/ModifyingTreeSpec.hs
|
gpl-3.0
| 330 | 0 | 16 | 72 | 86 | 42 | 44 | 10 | 1 |
-- | Compute a Gram-Schmidt orthogonal basis
module Math.LinearAlgebra.GramSchmidt (
gramSchmidtBasis,
gramSchmidtOrthogonalization
) where
import Prelude hiding ((*>))
import Math.Algebra.LinearAlgebra
-- | Given a basis, return the Gram-Schmidt orhthogonal basis
gramSchmidtBasis :: Fractional a => [[a]] -> [[a]]
gramSchmidtBasis a = fst $ gramSchmidtOrthogonalization a
-- | Given a basis, return the Gram-Schmidt orthogonalization, which is a tuple with the Gram-Schmidt orthogonal basis first, and the
-- $\mu_{i,j} = \langle b_i, b^*_j \rangle / \langle b^*_j, b^*_j \rangle$ triangular matrix second, for $1 \leq j < i < n$.
gramSchmidtOrthogonalization :: Fractional a => [[a]] -> ([[a]], [[a]])
gramSchmidtOrthogonalization (b0:bs) = gs bs [b0] []
-- TODO get rid of the (++) used like this, to make it faster
-- | Perform actual Gram-Schmidt reduction
gs [] b' mu = (b', mu)
gs (b_i:bs) b' mu = gs bs b'' mu'
where
mu_i = mu_row b' b_i
mu' = mu ++ [mu_i]
tosum = zipWith (*>) mu_i b'
offset = foldl1 (<+>) tosum
b'_i = b_i <-> offset
b'' = b' ++ [b'_i]
-- | Compute a (partial) row of the $\mu_{i,j}$ matrix. This is based on the previously orthogonalized vectors $b^*_j$, and the current vector $b_i$.
-- This assumes that 'b_i is of length 'i
mu_row b' b_i = flip map b' $ \b'_j -> (b_i <.> b'_j) / (b'_j <.> b'_j)
|
bcoppens/Lattices
|
src/Math/LinearAlgebra/GramSchmidt.hs
|
gpl-3.0
| 1,453 | 0 | 9 | 348 | 309 | 177 | 132 | 18 | 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.DataFusion.Projects.Locations.Operations.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)
--
-- Deletes a long-running operation. This method indicates that the client
-- is no longer interested in the operation result. It does not cancel the
-- operation. If the server doesn\'t support this method, it returns
-- \`google.rpc.Code.UNIMPLEMENTED\`.
--
-- /See:/ <https://cloud.google.com/data-fusion/docs Cloud Data Fusion API Reference> for @datafusion.projects.locations.operations.delete@.
module Network.Google.Resource.DataFusion.Projects.Locations.Operations.Delete
(
-- * REST Resource
ProjectsLocationsOperationsDeleteResource
-- * Creating a Request
, projectsLocationsOperationsDelete
, ProjectsLocationsOperationsDelete
-- * Request Lenses
, plodXgafv
, plodUploadProtocol
, plodAccessToken
, plodUploadType
, plodName
, plodCallback
) where
import Network.Google.DataFusion.Types
import Network.Google.Prelude
-- | A resource alias for @datafusion.projects.locations.operations.delete@ method which the
-- 'ProjectsLocationsOperationsDelete' request conforms to.
type ProjectsLocationsOperationsDeleteResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Empty
-- | Deletes a long-running operation. This method indicates that the client
-- is no longer interested in the operation result. It does not cancel the
-- operation. If the server doesn\'t support this method, it returns
-- \`google.rpc.Code.UNIMPLEMENTED\`.
--
-- /See:/ 'projectsLocationsOperationsDelete' smart constructor.
data ProjectsLocationsOperationsDelete =
ProjectsLocationsOperationsDelete'
{ _plodXgafv :: !(Maybe Xgafv)
, _plodUploadProtocol :: !(Maybe Text)
, _plodAccessToken :: !(Maybe Text)
, _plodUploadType :: !(Maybe Text)
, _plodName :: !Text
, _plodCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsOperationsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plodXgafv'
--
-- * 'plodUploadProtocol'
--
-- * 'plodAccessToken'
--
-- * 'plodUploadType'
--
-- * 'plodName'
--
-- * 'plodCallback'
projectsLocationsOperationsDelete
:: Text -- ^ 'plodName'
-> ProjectsLocationsOperationsDelete
projectsLocationsOperationsDelete pPlodName_ =
ProjectsLocationsOperationsDelete'
{ _plodXgafv = Nothing
, _plodUploadProtocol = Nothing
, _plodAccessToken = Nothing
, _plodUploadType = Nothing
, _plodName = pPlodName_
, _plodCallback = Nothing
}
-- | V1 error format.
plodXgafv :: Lens' ProjectsLocationsOperationsDelete (Maybe Xgafv)
plodXgafv
= lens _plodXgafv (\ s a -> s{_plodXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plodUploadProtocol :: Lens' ProjectsLocationsOperationsDelete (Maybe Text)
plodUploadProtocol
= lens _plodUploadProtocol
(\ s a -> s{_plodUploadProtocol = a})
-- | OAuth access token.
plodAccessToken :: Lens' ProjectsLocationsOperationsDelete (Maybe Text)
plodAccessToken
= lens _plodAccessToken
(\ s a -> s{_plodAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plodUploadType :: Lens' ProjectsLocationsOperationsDelete (Maybe Text)
plodUploadType
= lens _plodUploadType
(\ s a -> s{_plodUploadType = a})
-- | The name of the operation resource to be deleted.
plodName :: Lens' ProjectsLocationsOperationsDelete Text
plodName = lens _plodName (\ s a -> s{_plodName = a})
-- | JSONP
plodCallback :: Lens' ProjectsLocationsOperationsDelete (Maybe Text)
plodCallback
= lens _plodCallback (\ s a -> s{_plodCallback = a})
instance GoogleRequest
ProjectsLocationsOperationsDelete
where
type Rs ProjectsLocationsOperationsDelete = Empty
type Scopes ProjectsLocationsOperationsDelete =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsLocationsOperationsDelete'{..}
= go _plodName _plodXgafv _plodUploadProtocol
_plodAccessToken
_plodUploadType
_plodCallback
(Just AltJSON)
dataFusionService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsOperationsDeleteResource)
mempty
|
brendanhay/gogol
|
gogol-datafusion/gen/Network/Google/Resource/DataFusion/Projects/Locations/Operations/Delete.hs
|
mpl-2.0
| 5,429 | 0 | 15 | 1,137 | 702 | 413 | 289 | 103 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.