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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
module SPARC.CodeGen.Amode (
getAmode
)
where
import GhcPrelude
import {-# SOURCE #-} SPARC.CodeGen.Gen32
import SPARC.CodeGen.Base
import SPARC.AddrMode
import SPARC.Imm
import SPARC.Instr
import SPARC.Regs
import SPARC.Base
import NCGMonad
import Format
import Cmm
import OrdList
-- | Generate code to reference a memory address.
getAmode
:: CmmExpr -- ^ expr producing an address
-> NatM Amode
getAmode tree@(CmmRegOff _ _)
= do dflags <- getDynFlags
getAmode (mangleIndexTree dflags tree)
getAmode (CmmMachOp (MO_Sub _) [x, CmmLit (CmmInt i _)])
| fits13Bits (-i)
= do
(reg, code) <- getSomeReg x
let
off = ImmInt (-(fromInteger i))
return (Amode (AddrRegImm reg off) code)
getAmode (CmmMachOp (MO_Add _) [x, CmmLit (CmmInt i _)])
| fits13Bits i
= do
(reg, code) <- getSomeReg x
let
off = ImmInt (fromInteger i)
return (Amode (AddrRegImm reg off) code)
getAmode (CmmMachOp (MO_Add _) [x, y])
= do
(regX, codeX) <- getSomeReg x
(regY, codeY) <- getSomeReg y
let
code = codeX `appOL` codeY
return (Amode (AddrRegReg regX regY) code)
getAmode (CmmLit lit)
= do
let imm__2 = litToImm lit
tmp1 <- getNewRegNat II32
tmp2 <- getNewRegNat II32
let code = toOL [ SETHI (HI imm__2) tmp1
, OR False tmp1 (RIImm (LO imm__2)) tmp2]
return (Amode (AddrRegReg tmp2 g0) code)
getAmode other
= do
(reg, code) <- getSomeReg other
let
off = ImmInt 0
return (Amode (AddrRegImm reg off) code)
| ezyang/ghc | compiler/nativeGen/SPARC/CodeGen/Amode.hs | bsd-3-clause | 1,646 | 0 | 16 | 490 | 610 | 303 | 307 | 55 | 1 |
{-# LANGUAGE MagicHash #-}
-- !!! test tryTakeMVar
import Control.Concurrent
import Control.Exception
import GHC.Exts ( fork# )
import GHC.IO ( IO(..) )
import GHC.Conc ( ThreadId(..) )
main = do
m <- newEmptyMVar
r <- timeout 5 (tryTakeMVar m) (putStrLn "timed out!" >> return Nothing)
print (r :: Maybe Int)
m <- newMVar True
r <- timeout 5 (tryTakeMVar m) (putStrLn "timed out!" >> return Nothing)
print r
timeout
:: Int -- secs
-> IO a -- action to run
-> IO a -- action to run on timeout
-> IO a
timeout secs action on_timeout
= do
threadid <- myThreadId
timeout <- forkIO $ do threadDelay (secs * 1000000)
throwTo threadid (ErrorCall "__timeout")
( do result <- action
killThread timeout
return result
)
`Control.Exception.catch`
\exception -> case fromException exception of
Just (ErrorCall "__timeout") -> on_timeout
_other -> do killThread timeout
throw exception
| ezyang/ghc | testsuite/tests/concurrent/should_run/conc022.hs | bsd-3-clause | 1,107 | 0 | 14 | 377 | 325 | 158 | 167 | 31 | 2 |
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
{-# LANGUAGE ConstraintKinds, TemplateHaskell, PolyKinds, TypeFamilies, RankNTypes #-}
module T7021a where
import GHC.Exts
import Language.Haskell.TH
type IOable a = (Show a, Read a)
type family ALittleSilly :: Constraint
data Proxy a = Proxy
foo :: IOable a => a
foo = undefined
baz :: a b => Proxy a -> b
baz = undefined
bar :: ALittleSilly => a
bar = undefined
test :: Q Exp
test = do
Just fooName <- lookupValueName "foo"
Just bazName <- lookupValueName "baz"
Just barName <- lookupValueName "bar"
reify fooName
reify bazName
reify barName
[t| forall a. (Show a, (Read a, Num a)) => a -> a |]
[| \_ -> 0 |]
| ezyang/ghc | testsuite/tests/th/T7021a.hs | bsd-3-clause | 704 | 0 | 8 | 154 | 191 | 99 | 92 | -1 | -1 |
module Main where
import Data.Array.Unboxed
type Lights = UArray (Int,Int) Bool
main :: IO ()
main =
do input <- loadInput
let steps = 100
print $ countLights $ iterate (applyRule life) input !! steps
print $ countLights $ iterate (applyRule (addCorners life)) input !! steps
countLights :: Lights -> Int
countLights = length . filter id . elems
loadInput :: IO Lights
loadInput =
do str <- readFile "input18.txt"
let lights = map (map (=='#')) (lines str)
return $! case lights of
[] -> array ((1,1),(0,0)) []
x:_ -> array ((1,1),(length lights, length x))
[ ((r,c), col)
| (r,row) <- zip [1..] lights
, (c,col) <- zip [1..] row ]
type Rule = Lights -> (Int,Int) -> Bool
applyRule :: Rule -> Lights -> Lights
applyRule f a = array (bounds a) [ (i, f a i) | i <- range (bounds a) ]
life :: Rule
life a i@(x,y) = neighbors == 3 ||
neighbors == 2 && a!i
where
neighbors = length [ () | x' <- [x-1..x+1], y' <- [y-1..y+1]
, let i' = (x',y')
, i /= i'
, inRange (bounds a) i'
, a ! i'
]
addCorners :: Rule -> Rule
addCorners f a i@(x,y)
| x == xlo || x == xhi
, y == ylo || y == yhi = True
| otherwise = f a i
where
((xlo,ylo),(xhi,yhi)) = bounds a
| glguy/advent2015 | Day18.hs | isc | 1,422 | 0 | 16 | 508 | 676 | 356 | 320 | 38 | 2 |
{-
Lab Session Software Testing 2013, Week 6
Tuba Kaya Chomette, Sander Leer, Martijn Stegeman
13 October 2013
-}
module Benchmark where
import Week6
import Criterion.Main
import Criterion.Config
import Data.Bits
{-
To actually run this benchmark, you need to install Criterion by running
cabal install criterion
This has a huge amount of dependencies, so it is not advised to actually
do this.
-}
{-
See the plot in report/plot.pdf
The linear relation of expM's exponent size and its running time is clear
from the right half of the plot. There seems to be a sublinear
(logarithmic) relation between exM's exponent size and its running time.
-}
exMfast :: Integer -> Integer -> Integer -> Integer
exMfast b e m = exM' b e m 1 where
exM' _ 0 _ r = r
exM' b e m r | odd e = exM' (b*b `mod` m) (Data.Bits.shiftR e 1) m (r*b `mod` m)
| otherwise = exM' (b*b `mod` m) (Data.Bits.shiftR e 1) m r
main = defaultMainWith defaultConfig (return ()) [
-- bgroup "exM" [
-- bench "exM 1" $ whnf (\ x -> exM 7919 x 257) 1
-- , bench "exM 10" $ whnf (\ x -> exM 7919 x 257) 10
-- , bench "exM 100" $ whnf (\ x -> exM 7919 x 257) 100
-- , bench "exM 1000" $ whnf (\ x -> exM 7919 x 257) 1000
-- , bench "exM 10000" $ whnf (\ x -> exM 7919 x 257) 10000
-- , bench "exM 100000" $ whnf (\ x -> exM 7919 x 257) 100000
-- , bench "exM 1000000" $ whnf (\ x -> exM 7919 x 257) 1000000
-- , bench "exM 10000000" $ whnf (\ x -> exM 7919 x 257) 10000000
-- , bench "exM 100000000" $ whnf (\ x -> exM 7919 x 257) 100000000
-- ],
-- bgroup "expM" [
-- bench "expM 1" $ whnf (\ x -> expM 7919 x 257) 1
-- , bench "expM 10" $ whnf (\ x -> expM 7919 x 257) 10
-- , bench "expM 100" $ whnf (\ x -> expM 7919 x 257) 100
-- , bench "expM 1000" $ whnf (\ x -> expM 7919 x 257) 1000
-- , bench "expM 10000" $ whnf (\ x -> expM 7919 x 257) 10000
-- , bench "expM 100000" $ whnf (\ x -> expM 7919 x 257) 100000
-- , bench "expM 1000000" $ whnf (\ x -> expM 7919 x 257) 1000000
-- , bench "expM 10000000" $ whnf (\ x -> expM 7919 x 257) 10000000
-- ],
bgroup "exMfast" [
bench "exMfast 1" $ whnf (\ x -> exMfast 7919 x 257) 1
, bench "exMfast 10" $ whnf (\ x -> exMfast 7919 x 257) 10
, bench "exMfast 100" $ whnf (\ x -> exMfast 7919 x 257) 100
, bench "exMfast 1000" $ whnf (\ x -> exMfast 7919 x 257) 1000
, bench "exMfast 10000" $ whnf (\ x -> exMfast 7919 x 257) 10000
, bench "exMfast 100000" $ whnf (\ x -> exMfast 7919 x 257) 100000
, bench "exMfast 1000000" $ whnf (\ x -> exMfast 7919 x 257) 1000000
, bench "exMfast 10000000" $ whnf (\ x -> exMfast 7919 x 257) 10000000
, bench "exMfast 100000000" $ whnf (\ x -> exMfast 7919 x 257) 100000000
]
]
| stgm/prac-testing | week6/Benchmark.hs | mit | 2,998 | 0 | 13 | 944 | 509 | 272 | 237 | 21 | 2 |
module NetHack.Data.BUC
(BUC(..))
where
data BUC = Blessed | Uncursed | Cursed
deriving(Eq, Show)
| Noeda/Megaman | src/NetHack/Data/BUC.hs | mit | 115 | 0 | 6 | 31 | 40 | 25 | 15 | 4 | 0 |
{-# LANGUAGE BangPatterns #-}
module Vec2 where
data Vec2
= Vec2 {-# UNPACK #-}!Double {-# UNPACK #-}!Double
deriving Show
vecZero :: Vec2
vecZero = Vec2 0.0 0.0
vecAdd :: Vec2 -> Vec2 -> Vec2
vecAdd (Vec2 a b) (Vec2 x y)
= Vec2 (a+x) (b+y)
vecSub :: Vec2 -> Vec2 -> Vec2
vecSub (Vec2 a b) (Vec2 x y)
= Vec2 (a-x) (b-y)
vecScale :: Vec2 -> Double -> Vec2
vecScale (Vec2 a b) !s
= Vec2 (a*s) (b*s)
vecDot :: Vec2 -> Vec2 -> Double
vecDot (Vec2 a b) (Vec2 x y)
= (a*x)+(b*y)
vecNorm :: Vec2 -> Double
vecNorm v
= sqrt (vecDot v v)
vecNormalize :: Vec2 -> Vec2
vecNormalize v
= vecScale v (1.0 / (vecNorm v))
vecDimSelect :: Vec2 -> Int -> Double
vecDimSelect (Vec2 a b) n
= case rem n 2 of
0 -> a
1 -> b
vecLessThan :: Vec2 -> Vec2 -> Bool
vecLessThan (Vec2 a b) (Vec2 x y)
= a < x && b < y
vecGreaterThan :: Vec2 -> Vec2 -> Bool
vecGreaterThan (Vec2 a b) (Vec2 x y)
= a > x && b > y
| gscalzo/HaskellTheHardWay | gloss-try/gloss-master/gloss-examples/picture/Boids/Vec2.hs | mit | 999 | 0 | 9 | 306 | 479 | 248 | 231 | 36 | 2 |
-- | This module implements GL_ARB_texture_storage with
-- GL_EXT_direct_state_access in terms of glTexImageX calls.
--
-- The implementation is unlikely to be perfect but it should work for most
-- cases.
{-# LANGUAGE NoImplicitPrelude, MultiWayIf #-}
module Graphics.Caramia.Internal.TexStorage
( fakeTextureStorage1D
, fakeTextureStorage2D
, fakeTextureStorage3D )
where
import Graphics.Caramia.Prelude
import Graphics.Caramia.Internal.OpenGLCApi
import Graphics.Caramia.Texture.Internal
import Graphics.GL.Ext.EXT.DirectStateAccess
import Graphics.GL.Ext.EXT.TextureCompressionS3tc
import Graphics.GL.Ext.EXT.TextureSRGB
import Control.Exception
import Foreign.Ptr
-- | glTextureStorage1D
fakeTextureStorage1D :: GLuint
-> GLenum
-> GLsizei
-> GLenum
-> GLsizei
-> IO ()
fakeTextureStorage1D texture target levels internalformat width =
mask_ $ if gl_EXT_direct_state_access
then dsaFakeTextureStorage1D
else nodsaFakeTextureStorage1D
where
rec fun i w | i < levels = fun i w >>
rec fun (i+1) (max 1 $ w `div` 2)
| otherwise = return ()
dsaFakeTextureStorage1D = do
rec (\i w -> do
glTextureImage1DEXT texture
target
i
(fromIntegral internalformat)
w
0
(formatFromInternalFormat internalformat)
(typeFromInternalFormat internalformat)
nullPtr) 0 width
glTextureParameteriEXT texture target GL_TEXTURE_MAX_LEVEL (levels-1)
nodsaFakeTextureStorage1D = do
old_tex <- gi $ bindingQueryPoint target
glBindTexture target texture
rec (\i w ->
glTexImage1D target
i
(fromIntegral internalformat)
w
0
(formatFromInternalFormat internalformat)
(typeFromInternalFormat internalformat)
nullPtr) 0 width
glTexParameteri target GL_TEXTURE_MAX_LEVEL (levels-1)
glBindTexture target old_tex
-- | glTextureStorage2D
fakeTextureStorage2D :: GLuint
-> GLenum
-> GLsizei
-> GLenum
-> GLsizei
-> GLsizei
-> IO ()
fakeTextureStorage2D texture target levels internalformat width height =
mask_ $ if gl_EXT_direct_state_access
then dsaFakeTextureStorage2D
else nodsaFakeTextureStorage2D
where
rec fun i w h | i < levels = fun i w h >>
rec fun
(i+1)
(max 1 $ w `div` 2)
(max 1 $ h `div` 2)
| otherwise = return ()
dsaFakeTextureStorage2D = do
rec (\i w h ->
if target /= GL_TEXTURE_CUBE_MAP
then glTextureImage2DEXT texture
target
i
(fromIntegral internalformat)
w
h
0
(formatFromInternalFormat internalformat)
(typeFromInternalFormat internalformat)
nullPtr
else for_ cubeSides $ \side ->
glTextureImage2DEXT texture
side
i
(fromIntegral internalformat)
w
h
0
(formatFromInternalFormat internalformat)
(typeFromInternalFormat internalformat)
nullPtr) 0 width height
glTextureParameteriEXT texture target GL_TEXTURE_MAX_LEVEL (levels-1)
nodsaFakeTextureStorage2D = do
old_tex <- gi $ bindingQueryPoint target
glBindTexture target texture
rec (\i w h -> if target /= GL_TEXTURE_CUBE_MAP
then glTexImage2D target
i
(fromIntegral internalformat)
w
h
0
(formatFromInternalFormat internalformat)
(typeFromInternalFormat internalformat)
nullPtr
else for_ cubeSides $ \side ->
glTexImage2D side
i
(fromIntegral internalformat)
w
h
0
(formatFromInternalFormat internalformat)
(typeFromInternalFormat internalformat)
nullPtr)
0 width height
glTexParameteri target GL_TEXTURE_MAX_LEVEL (levels-1)
glBindTexture target old_tex
cubeSides :: [GLenum]
cubeSides = [GL_TEXTURE_CUBE_MAP_POSITIVE_X
,GL_TEXTURE_CUBE_MAP_POSITIVE_Y
,GL_TEXTURE_CUBE_MAP_POSITIVE_Z
,GL_TEXTURE_CUBE_MAP_NEGATIVE_X
,GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
,GL_TEXTURE_CUBE_MAP_NEGATIVE_Z]
-- | glTextureStorage3D
fakeTextureStorage3D :: GLuint
-> GLenum
-> GLsizei
-> GLenum
-> GLsizei
-> GLsizei
-> GLsizei
-> IO ()
fakeTextureStorage3D texture target levels internalformat width height depth =
mask_ $ if gl_EXT_direct_state_access
then dsaFakeTextureStorage3D
else nodsaFakeTextureStorage3D
where
rec fun i w h z | i < levels = fun i w h z >>
rec fun
(i+1)
(max 1 $ w `div` 2)
(max 1 $ h `div` 2)
(max 1 $ z `div` 2)
| otherwise = return ()
dsaFakeTextureStorage3D = do
rec (\i w h z ->
glTextureImage3DEXT texture
target
i
(fromIntegral internalformat)
w
h
z
0
(formatFromInternalFormat internalformat)
(typeFromInternalFormat internalformat)
nullPtr) 0 width height depth
glTextureParameteriEXT texture target GL_TEXTURE_MAX_LEVEL (levels-1)
nodsaFakeTextureStorage3D = do
old_tex <- gi $ bindingQueryPoint target
glBindTexture target texture
rec (\i w h z -> glTexImage3D
target
i
(fromIntegral internalformat)
w
h
z
0
(formatFromInternalFormat internalformat)
(typeFromInternalFormat internalformat)
nullPtr) 0 width height depth
glTexParameteri target GL_TEXTURE_MAX_LEVEL (levels-1)
glBindTexture target old_tex
typeFromInternalFormat :: GLenum -> GLenum
typeFromInternalFormat x =
if | x == GL_R8 -> GL_UNSIGNED_BYTE
| x == GL_R8I -> GL_BYTE
| x == GL_R8UI -> GL_UNSIGNED_BYTE
| x == GL_R16 -> GL_UNSIGNED_SHORT
| x == GL_R16I -> GL_SHORT
| x == GL_R16UI -> GL_UNSIGNED_SHORT
| x == GL_R16F -> GL_FLOAT
| x == GL_R32F -> GL_FLOAT
| x == GL_R32I -> GL_INT
| x == GL_R32UI -> GL_UNSIGNED_INT
| x == GL_RG8 -> GL_UNSIGNED_BYTE
| x == GL_RG8I -> GL_BYTE
| x == GL_RG8UI -> GL_UNSIGNED_BYTE
| x == GL_RG16 -> GL_UNSIGNED_SHORT
| x == GL_RG16I -> GL_SHORT
| x == GL_RG16UI -> GL_UNSIGNED_SHORT
| x == GL_RG16F -> GL_FLOAT
| x == GL_RG32F -> GL_FLOAT
| x == GL_RG32I -> GL_INT
| x == GL_RG32UI -> GL_UNSIGNED_INT
| x == GL_R11F_G11F_B10F -> GL_FLOAT
| x == GL_RGBA32F -> GL_FLOAT
| x == GL_RGBA32I -> GL_INT
| x == GL_RGBA32UI -> GL_UNSIGNED_INT
| x == GL_RGBA16 -> GL_UNSIGNED_SHORT
| x == GL_RGBA16F -> GL_FLOAT
| x == GL_RGBA16I -> GL_SHORT
| x == GL_RGBA16UI -> GL_UNSIGNED_SHORT
| x == GL_RGBA8 -> GL_UNSIGNED_BYTE
| x == GL_RGBA8UI -> GL_UNSIGNED_BYTE
| x == GL_SRGB8_ALPHA8 -> GL_UNSIGNED_BYTE
| x == GL_RGB10_A2 -> GL_FLOAT
| x == GL_RGB32F -> GL_FLOAT
| x == GL_RGB32I -> GL_INT
| x == GL_RGB32UI -> GL_UNSIGNED_INT
| x == GL_RGB16F -> GL_FLOAT
| x == GL_RGB16I -> GL_SHORT
| x == GL_RGB16UI -> GL_UNSIGNED_SHORT
| x == GL_RGB16 -> GL_UNSIGNED_SHORT
| x == GL_RGB8 -> GL_UNSIGNED_BYTE
| x == GL_RGB8I -> GL_BYTE
| x == GL_RGB8UI -> GL_UNSIGNED_BYTE
| x == GL_SRGB8 -> GL_UNSIGNED_BYTE
| x == GL_RGB9_E5 -> GL_FLOAT
| x == GL_COMPRESSED_RG_RGTC2 -> GL_FLOAT
| x == GL_COMPRESSED_SIGNED_RG_RGTC2 -> GL_FLOAT
| x == GL_COMPRESSED_RED_RGTC1 -> GL_FLOAT
| x == GL_COMPRESSED_SIGNED_RED_RGTC1 -> GL_FLOAT
| x == GL_COMPRESSED_RGB_S3TC_DXT1_EXT -> GL_FLOAT
| x == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT -> GL_FLOAT
| x == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT -> GL_FLOAT
| x == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT -> GL_FLOAT
| x == GL_COMPRESSED_SRGB_S3TC_DXT1_EXT -> GL_FLOAT
| x == GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT -> GL_FLOAT
| x == GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT -> GL_FLOAT
| x == GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT -> GL_FLOAT
| x == GL_DEPTH_COMPONENT32 -> GL_FLOAT
| x == GL_DEPTH_COMPONENT32F -> GL_FLOAT
| x == GL_DEPTH_COMPONENT24 -> GL_FLOAT
| x == GL_DEPTH_COMPONENT16 -> GL_FLOAT
| x == GL_DEPTH32F_STENCIL8 -> GL_FLOAT_32_UNSIGNED_INT_24_8_REV
| x == GL_DEPTH24_STENCIL8 -> GL_UNSIGNED_INT_24_8
| otherwise ->
error $ "typeFromInternalFormat: unknown internal format " <>
show x
formatFromInternalFormat :: GLenum -> GLenum
formatFromInternalFormat x =
if | x == GL_R8 -> GL_RED
| x == GL_R8I -> GL_RED_INTEGER
| x == GL_R8UI -> GL_RED_INTEGER
| x == GL_R16 -> GL_RED
| x == GL_R16I -> GL_RED_INTEGER
| x == GL_R16UI -> GL_RED_INTEGER
| x == GL_R16F -> GL_RED
| x == GL_R32F -> GL_RED
| x == GL_R32I -> GL_RED_INTEGER
| x == GL_R32UI -> GL_RED_INTEGER
| x == GL_RG8 -> GL_RG
| x == GL_RG8I -> GL_RG_INTEGER
| x == GL_RG8UI -> GL_RG_INTEGER
| x == GL_RG16 -> GL_RG
| x == GL_RG16I -> GL_RG_INTEGER
| x == GL_RG16UI -> GL_RG_INTEGER
| x == GL_RG16F -> GL_RG
| x == GL_RG32F -> GL_RG
| x == GL_RG32I -> GL_RG_INTEGER
| x == GL_RG32UI -> GL_RG_INTEGER
| x == GL_R11F_G11F_B10F -> GL_RGB
| x == GL_RGBA32F -> GL_RGBA
| x == GL_RGBA32I -> GL_RGBA_INTEGER
| x == GL_RGBA32UI -> GL_RGBA_INTEGER
| x == GL_RGBA16 -> GL_RGBA
| x == GL_RGBA16F -> GL_RGBA
| x == GL_RGBA16I -> GL_RGBA_INTEGER
| x == GL_RGBA16UI -> GL_RGBA_INTEGER
| x == GL_RGBA8 -> GL_RGBA
| x == GL_RGBA8UI -> GL_RGBA_INTEGER
| x == GL_SRGB8_ALPHA8 -> GL_RGBA
| x == GL_RGB10_A2 -> GL_RGBA
| x == GL_RGB32F -> GL_RGB
| x == GL_RGB32I -> GL_RGB_INTEGER
| x == GL_RGB32UI -> GL_RGB_INTEGER
| x == GL_RGB16F -> GL_RGB
| x == GL_RGB16I -> GL_RGB_INTEGER
| x == GL_RGB16UI -> GL_RGB_INTEGER
| x == GL_RGB16 -> GL_RGB
| x == GL_RGB8 -> GL_RGB
| x == GL_RGB8I -> GL_RGB_INTEGER
| x == GL_RGB8UI -> GL_RGB_INTEGER
| x == GL_SRGB8 -> GL_RGB
| x == GL_RGB9_E5 -> GL_RGB
| x == GL_COMPRESSED_RG_RGTC2 -> GL_RG
| x == GL_COMPRESSED_SIGNED_RG_RGTC2 -> GL_RG
| x == GL_COMPRESSED_RED_RGTC1 -> GL_RED
| x == GL_COMPRESSED_SIGNED_RED_RGTC1 -> GL_RED
| x == GL_COMPRESSED_RGB_S3TC_DXT1_EXT -> GL_RGB
| x == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT -> GL_RGBA
| x == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT -> GL_RGBA
| x == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT -> GL_RGBA
| x == GL_COMPRESSED_SRGB_S3TC_DXT1_EXT -> GL_RGB
| x == GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT -> GL_RGBA
| x == GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT -> GL_RGBA
| x == GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT -> GL_RGBA
| x == GL_DEPTH_COMPONENT32 -> GL_DEPTH_COMPONENT
| x == GL_DEPTH_COMPONENT32F -> GL_DEPTH_COMPONENT
| x == GL_DEPTH_COMPONENT24 -> GL_DEPTH_COMPONENT
| x == GL_DEPTH_COMPONENT16 -> GL_DEPTH_COMPONENT
| x == GL_DEPTH32F_STENCIL8 -> GL_DEPTH_STENCIL
| x == GL_DEPTH24_STENCIL8 -> GL_DEPTH_STENCIL
| otherwise ->
error $ "formatFromInternalFormat: unknown internal format " <>
show x
| Noeda/caramia | src/Graphics/Caramia/Internal/TexStorage.hs | mit | 14,120 | 0 | 19 | 5,999 | 3,021 | 1,458 | 1,563 | 310 | 63 |
{-|
Module : Language.Common.Storage
Description : Storage size definition
Copyright : (c) Jacob Errington and Frederic Lafrance, 2016
License : MIT
Maintainer : goto@mail.jerrington.me
Stability : experimental
-}
module Language.Common.Storage where
-- | Types having an associated storage requirement as a number of bytes needed
-- to represent the data.
class StorageSize a where
-- | Compute the number of bytes needed to store a value of this type.
storageSize :: a -> Int | djeik/goto | libgoto/Language/Common/Storage.hs | mit | 501 | 0 | 7 | 97 | 29 | 18 | 11 | 3 | 0 |
{- Author: Jeff Newbern
Maintainer: Jeff Newbern <jnewbern@nomaware.com>
Time-stamp: <Wed Jul 2 16:34:28 2003>
License: GPL
-}
{- DESCRIPTION
Example 11 - Using the Maybe monad
Usage: Compile the code and execute the resulting program
with an argument that is the name or nickname of
a mail user in the system below:
"Bill Gates" "billy"
"Bill Clinton" "slick willy"
"Michael Jackson" "jacko"
That user's email preference will be printed as either
"Just HTML" or "Just Plain". An unrecognized name will generate
output of "Nothing".
Try: ./ex11 "Bill Clinton"
./ex11 jacko
./ex11 Madonna
-}
import Monad
import System
-- this our super-simple email preference system
type EmailAddr = String
data MailPref = HTML | Plain deriving Show
data MailSystem = MS { fullNameDB::[(String,EmailAddr)],
nickNameDB::[(String,EmailAddr)],
prefsDB ::[(EmailAddr,MailPref)] }
-- this is a more convenient way to specify user information
data UserInfo = User { name::String,
nick::String,
email::EmailAddr,
prefs::MailPref }
-- makeMailSystem will make a MailSystem from a list of users
makeMailSystem :: [UserInfo] -> MailSystem
makeMailSystem users = let fullLst = map (\u -> (name u, email u)) users
nickLst = map (\u -> (nick u, email u)) users
prefLst = map (\u -> (email u, prefs u)) users
in MS fullLst nickLst prefLst
-- getMailPrefs returns the email preference for a given user,
-- or Nothing if the user is not in the system.
getMailPrefs :: MailSystem -> String -> Maybe MailPref
getMailPrefs sys name =
do let nameDB = fullNameDB sys
nickDB = nickNameDB sys
prefDB = prefsDB sys
addr <- (lookup name nameDB) `mplus` (lookup name nickDB)
lookup addr prefDB
-- print the email preference of the person named on the command-line
main :: IO ()
main = do let users = [ User "Bill Gates" "billy" "billg@microsoft.com" HTML,
User "Bill Clinton" "slick willy" "bill@hope.ar.us" Plain,
User "Michael Jackson" "jacko" "mj@wonderland.org" HTML ]
mailsys = makeMailSystem users
args <- getArgs
print (getMailPrefs mailsys (args!!0))
-- END OF FILE | maurotrb/hs-exercises | AllAboutMonads/examples/example11.hs | mit | 2,352 | 16 | 13 | 639 | 440 | 242 | 198 | 30 | 1 |
module Text.Noise.Parser.Character
( Location
, Length
, Range
, locationAt
, rangeAt
) where
import Text.Parsec.Pos (SourcePos, updatePosChar, initialPos, sourceName)
import Text.Noise.SourceRange (SourceRange)
import Data.List (elemIndex)
type Location = Int
type Length = Int
type Range = (Location, Length)
locationAt :: String -> SourcePos -> Maybe Location
locationAt source pos = elemIndex pos positions
where positions = scanl updatePosChar firstPos source
firstPos = initialPos (sourceName pos)
rangeAt :: String -> SourceRange -> Maybe Range
rangeAt source (fromPos, toPos) = do
fromLoc <- locationAt source fromPos
toLoc <- locationAt source toPos
return (fromLoc, toLoc - fromLoc)
| brow/noise | src/Text/Noise/Parser/Character.hs | mit | 715 | 0 | 9 | 117 | 221 | 123 | 98 | 21 | 1 |
module Lab2 where
------------------------------------------------------------------------------------------------------------------------------
-- Lab 2: Validating Credit Card Numbers
------------------------------------------------------------------------------------------------------------------------------
-- ===================================
-- Ex. 0
-- ===================================
{-
First we need to find the digits of a number. Define a function
toDigits :: Integer -> [Integer]
that takes a n :: Integer where n >= 0 and returns a list of the digits of n.
More precisely, toDigits should satisfy the following properties,
for all n :: Integer where n >= 0:
* eval (toDigits n) == n
* all (\d -> d >= 0 && d < 10) (toDigits n)
* length (show n) == length (toDigits n)
where eval is defined as follows:
eval xs = foldl (\x y -> y + (10 * x)) 0 xs
Note: toDigits n should error when n < 0.
-}
eval xs = foldl (\x y -> y + (10 * x)) 0 xs
toDigits :: Integer -> [Integer]
toDigits n
| n < 10 = [n]
| n >= 10 = toDigits(new_num) ++ [last_digit]
where
last_digit = n `mod` 10
remainder = n - last_digit
new_num
| remainder < 10 = remainder
| remainder >= 10 = remainder `div` 10
test0 = do
-- Test exercise 1
print("[9,8,7,6,5,4,3,2,1]", toDigits 987654321)
print("[0]", toDigits 0)
print("[1]", toDigits 1)
print(eval (toDigits 19) == 19)
print(all (\d -> d >= 0 && d < 10) (toDigits 1234))
print(length (show 1234) == length (toDigits 1234))
-- ===================================
-- Ex. 1
-- ===================================
{-
Now we need to reverse the digits of a number. Define a function
toDigitsRev :: Integer -> [Integer]
that takes a n :: Integer where n >= 0 and returns a list of the digits of n
in reverse order. More precisely, toDigitsRev should satisfy the following
properties, for all n :: Integer where n >= 0::
n == evalRev (toDigitsRev n)
all (\d -> d >= 0 && d < 10) (toDigitsRev n)
length (toDigitsRev n) == length (show n)
where evalRev is defined as follows:
evalRev xs = foldr (\x y -> x + (10 * y)) 0 xs
Note: toDigitsRev n should error when n < 0.
-}
evalRev xs = foldr (\x y -> x + (10 * y)) 0 xs
toDigitsRev :: Integer -> [Integer]
toDigitsRev n = reverse (toDigits n)
test1 = do
-- Test exercise 1
print("[1,2,3,4,5,6,7,8,9]", toDigitsRev 987654321)
print("[0]", toDigitsRev 0)
print("[3,2,1]", toDigitsRev 123)
print(19 == evalRev (toDigitsRev 19))
print(all (\d -> d >= 0 && d < 10) (toDigitsRev 1234))
print(length (toDigitsRev 1234) == length (show 1234))
-- ===================================
-- Ex. 2
-- ===================================
{-
Once we have the digits in the proper order, we need to double every
other one.
Define the function
doubleSecond :: [Integer] -> [Integer]
that doubles every second number in the input list.
Example: The result of doubleSecond [8, 7, 6, 5] is [8, 14, 6, 10].
-}
doubleSecond :: [Integer] -> [Integer]
-- doubleSecond [] = []
-- doubleSecond (xs)
-- | (length xs) `mod` 2 == 0 = doubleSecond (init xs) ++ [last xs * 2]
-- | otherwise = doubleSecond (init xs) ++ [last xs]
-- Or this is much better:
doubleSecond (xs) = [x * (mod i 2 + 1) | (x, i) <- zip xs [0..]]
test2 = do
print("8,14,6,10", doubleSecond [8,7,6,5])
print("1,4,3", doubleSecond [1,2,3])
print("1", doubleSecond [1])
print("0", doubleSecond [0])
print("1,4", doubleSecond [1,2])
print("1,2,1,2,1,2,1,2", doubleSecond [1,1,1,1,1,1,1,1])
-- ===================================
-- Ex. 3
-- ===================================
{-
The output of doubleSecond has a mix of one-digit and two-digit numbers.
Define a function
sumDigits :: [Integer] -> Integer
to calculate the sum of all individual digits, even if a number in the list
has more than 2 digits.
Example: The result of
sumDigits [8,14,6,10] = 8 + (1 + 4) + 6 + (1 + 0) = 20.
sumDigits [3, 9, 4, 15, 8] = 3 + 9 + 4 + (1 + 5) + 8 = 30
-}
sumDigits :: [Integer] -> Integer
sumDigits [] = 0
sumDigits (x:xs)
| x >= 10 = sumDigits (toDigits x) + sumDigits xs
| otherwise = x + sumDigits xs
test3 = do
print("20", sumDigits [8,14,6,10])
print("30", sumDigits [3,9,4,15,8])
print("1", sumDigits [1])
print("0", sumDigits [0])
print("5", sumDigits [14])
-- ===================================
-- Ex. 4
-- ===================================
{-
Calculate the modulus of the sum divided by 10. If the result equals 0, then
the number is valid. Here is an example of the results of each step on the
number 4012888888881881.
-}
isValid :: Integer -> Bool
isValid n = (sumDigits (doubleSecond (toDigitsRev n))) `mod` 10 == 0
test4 = do
print(isValid 4012888888881881)
print(isValid 4012888888881891)
-- ===================================
-- Ex. 5
-- ===================================
numValid :: [Integer] -> Integer
numValid xs = sum . map (\_ -> 1) $ filter isValid xs
creditcards :: [Integer]
creditcards = [ 4716347184862961,
4532899082537349,
4485429517622493,
4320635998241421,
4929778869082405,
5256283618614517,
5507514403575522,
5191806267524120,
5396452857080331,
5567798501168013,
6011798764103720,
6011970953092861,
6011486447384806,
6011337752144550,
6011442159205994,
4916188093226163,
4916699537435624,
4024607115319476,
4556945538735693,
4532818294886666,
5349308918130507,
5156469512589415,
5210896944802939,
5442782486960998,
5385907818416901,
6011920409800508,
6011978316213975,
6011221666280064,
6011285399268094,
6011111757787451,
4024007106747875,
4916148692391990,
4916918116659358,
4024007109091313,
4716815014741522,
5370975221279675,
5586822747605880,
5446122675080587,
5361718970369004,
5543878863367027,
6011996932510178,
6011475323876084,
6011358905586117,
6011672107152563,
6011660634944997,
4532917110736356,
4485548499291791,
4532098581822262,
4018626753711468,
4454290525773941,
5593710059099297,
5275213041261476,
5244162726358685,
5583726743957726,
5108718020905086,
6011887079002610,
6011119104045333,
6011296087222376,
6011183539053619,
6011067418196187,
4532462702719400,
4420029044272063,
4716494048062261,
4916853817750471,
4327554795485824,
5138477489321723,
5452898762612993,
5246310677063212,
5211257116158320,
5230793016257272,
6011265295282522,
6011034443437754,
6011582769987164,
6011821695998586,
6011420220198992,
4716625186530516,
4485290399115271,
4556449305907296,
4532036228186543,
4916950537496300,
5188481717181072,
5535021441100707,
5331217916806887,
5212754109160056,
5580039541241472,
6011450326200252,
6011141461689343,
6011886911067144,
6011835735645726,
6011063209139742,
379517444387209,
377250784667541,
347171902952673,
379852678889749,
345449316207827,
349968440887576,
347727987370269,
370147776002793,
374465794689268,
340860752032008,
349569393937707,
379610201376008,
346590844560212,
376638943222680,
378753384029375,
348159548355291,
345714137642682,
347556554119626,
370919740116903,
375059255910682,
373129538038460,
346734548488728,
370697814213115,
377968192654740,
379127496780069,
375213257576161,
379055805946370,
345835454524671,
377851536227201,
345763240913232
]
| supermitch/learn-haskell | edx-fp101x/5_lab.hs | mit | 9,109 | 0 | 14 | 3,064 | 1,444 | 813 | 631 | 176 | 1 |
--------------------------------------------------------------------
-- |
-- Module : Data.MessagePack.Put
-- Copyright : (c) Hideyuki Tanaka, 2009-2015
-- License : BSD3
--
-- Maintainer: tanaka.hideyuki@gmail.com
-- Stability : experimental
-- Portability: portable
--
-- MessagePack Serializer using @Data.Binary@
--
--------------------------------------------------------------------
module Data.MessagePack.Put (
putNil, putBool, putInt, putFloat, putDouble,
putStr, putBin, putArray, putMap, putExt,
) where
import Data.Binary
import Data.Binary.IEEE754
import Data.Binary.Put
import Data.Bits
import qualified Data.ByteString as S
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Vector as V
import Prelude hiding (putStr)
putNil :: Put
putNil = putWord8 0xC0
putBool :: Bool -> Put
putBool False = putWord8 0xC2
putBool True = putWord8 0xC3
putInt :: Int -> Put
putInt n
| -32 <= n && n <= 127 =
putWord8 $ fromIntegral n
| 0 <= n && n < 0x100 =
putWord8 0xCC >> putWord8 (fromIntegral n)
| 0 <= n && n < 0x10000 =
putWord8 0xCD >> putWord16be (fromIntegral n)
| 0 <= n && n < 0x100000000 =
putWord8 0xCE >> putWord32be (fromIntegral n)
| 0 <= n =
putWord8 0xCF >> putWord64be (fromIntegral n)
| -0x80 <= n =
putWord8 0xD0 >> putWord8 (fromIntegral n)
| -0x8000 <= n =
putWord8 0xD1 >> putWord16be (fromIntegral n)
| -0x80000000 <= n =
putWord8 0xD2 >> putWord32be (fromIntegral n)
| otherwise =
putWord8 0xD3 >> putWord64be (fromIntegral n)
putFloat :: Float -> Put
putFloat f = do
putWord8 0xCB
putFloat32be f
putDouble :: Double -> Put
putDouble d = do
putWord8 0xCB
putFloat64be d
putStr :: T.Text -> Put
putStr t = do
let bs = T.encodeUtf8 t
case S.length bs of
len | len <= 31 ->
putWord8 $ 0xA0 .|. fromIntegral len
| len < 0x100 ->
putWord8 0xD9 >> putWord8 (fromIntegral len)
| len < 0x10000 ->
putWord8 0xDA >> putWord16be (fromIntegral len)
| otherwise ->
putWord8 0xDB >> putWord32be (fromIntegral len)
putByteString bs
putBin :: S.ByteString -> Put
putBin bs = do
case S.length bs of
len | len < 0x100 ->
putWord8 0xC4 >> putWord8 (fromIntegral len)
| len < 0x10000 ->
putWord8 0xC5 >> putWord16be (fromIntegral len)
| otherwise ->
putWord8 0xC6 >> putWord32be (fromIntegral len)
putByteString bs
putArray :: (a -> Put) -> V.Vector a -> Put
putArray p xs = do
case V.length xs of
len | len <= 15 ->
putWord8 $ 0x90 .|. fromIntegral len
| len < 0x10000 ->
putWord8 0xDC >> putWord16be (fromIntegral len)
| otherwise ->
putWord8 0xDD >> putWord32be (fromIntegral len)
V.mapM_ p xs
putMap :: (a -> Put) -> (b -> Put) -> V.Vector (a, b) -> Put
putMap p q xs = do
case V.length xs of
len | len <= 15 ->
putWord8 $ 0x80 .|. fromIntegral len
| len < 0x10000 ->
putWord8 0xDE >> putWord16be (fromIntegral len)
| otherwise ->
putWord8 0xDF >> putWord32be (fromIntegral len)
V.mapM_ (\(a, b) -> p a >> q b ) xs
putExt :: Word8 -> S.ByteString -> Put
putExt typ dat = do
case S.length dat of
1 -> putWord8 0xD4
2 -> putWord8 0xD5
4 -> putWord8 0xD6
8 -> putWord8 0xD7
16 -> putWord8 0xD8
len | len < 0x100 -> putWord8 0xC7 >> putWord8 (fromIntegral len)
| len < 0x10000 -> putWord8 0xC8 >> putWord16be (fromIntegral len)
| otherwise -> putWord8 0xC9 >> putWord32be (fromIntegral len)
putWord8 typ
putByteString dat
| voidlizard/ntced-tcp-proxy | contrib/msgpack/src/Data/MessagePack/Put.hs | mit | 3,761 | 0 | 14 | 1,043 | 1,304 | 628 | 676 | 101 | 6 |
module Bench
( main
)
where
import Criterion.Main
import Data.Bifunctor
import qualified Data.ByteString as BS
import Data.List
import Data.Text.Encoding (decodeUtf8)
import qualified Javran.MaxFlow.Algorithm.Dinitz as Dinitz
import qualified Javran.MaxFlow.Algorithm.DinitzCherkassky as DinitzCherkassky
import qualified Javran.MaxFlow.Algorithm.EdmondsKarp as EdmondsKarp
import Javran.MaxFlow.Common
import Javran.MaxFlow.Parser
import Javran.MaxFlow.TestData
import Javran.MaxFlow.Types
pSimple, pGenetic, pHandmade, pRandomBest :: [(String, NormalizedNetwork)]
[ pSimple
, pGenetic
, pHandmade
, pRandomBest
] =
fmap
normPack
[ packSimple
, packGenetic
, packHandmade
, packRandomBest
]
where
normPack :: [(FilePath, BS.ByteString)] -> [(FilePath, NormalizedNetwork)]
normPack = sortOn fst . fmap (second norm)
where
norm :: BS.ByteString -> NormalizedNetwork
norm raw = normalize nr
where
Right nr = parseFromRaw $ decodeUtf8 raw
runSolver
:: MaxFlowSolver
-> [(String, NormalizedNetwork)]
-> [(String, (Int, FlowAssignment, CapacityMap))]
runSolver solver =
(fmap . second) (\nn -> let (Right r, _) = solver nn in r)
main :: IO ()
main =
defaultMain
[ maxFlowGroup "Dinitz" (runSolver Dinitz.maxFlow)
, maxFlowGroup "DinitzCherkassky" (runSolver DinitzCherkassky.maxFlow)
, maxFlowGroup "EdmondsKarp" (runSolver EdmondsKarp.maxFlow)
]
where
maxFlowGroup bTag solver =
bgroup
bTag
[ bench "simple" $ nf solver pSimple
, bench "genetic" $ nf solver pGenetic
, bench "handmade" $ nf solver pHandmade
, bench "random-best" $ nf solver pRandomBest
]
| Javran/misc | max-flow/bench/Bench.hs | mit | 1,764 | 0 | 13 | 405 | 479 | 272 | 207 | 50 | 1 |
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ViewPatterns #-}
module Test.Target
( target, targetResult, targetWith, targetResultWith
, targetTH, targetResultTH, targetWithTH, targetResultWithTH
, Result(..), Testable, Targetable(..)
, TargetOpts(..), defaultOpts
, Test(..)
, monomorphic
) where
import Control.Applicative
import Control.Arrow
import Control.Monad
import Control.Monad.Catch
import Control.Monad.State
import qualified Language.Haskell.TH as TH
import System.Process (terminateProcess)
import Test.QuickCheck.All (monomorphic)
import Text.Printf (printf)
import Language.Fixpoint.Types.Names
import Language.Fixpoint.Smt.Interface hiding (verbose)
import Test.Target.Monad
import Test.Target.Targetable (Targetable(..))
import Test.Target.Targetable.Function ()
import Test.Target.Testable
import Test.Target.Types
import Test.Target.Util
-- | Test whether a function inhabits its refinement type by enumerating valid
-- inputs and calling the function.
target :: Testable f
=> f -- ^ the function
-> String -- ^ the name of the function
-> FilePath -- ^ the path to the module that defines the function
-> IO ()
target f name path
= targetWith f name path defaultOpts
targetTH :: TH.Name -> FilePath -> TH.ExpQ
targetTH f m = [| target $(monomorphic f) $(TH.stringE $ show f) m |]
-- targetTH :: TH.ExpQ -- (TH.TExp (Testable f => f -> TH.Name -> IO ()))
-- targetTH = TH.location >>= \TH.Loc {..} ->
-- [| \ f n -> target f (show n) loc_filename |]
-- | Like 'target', but returns the 'Result' instead of printing to standard out.
targetResult :: Testable f => f -> String -> FilePath -> IO Result
targetResult f name path
= targetResultWith f name path defaultOpts
targetResultTH :: TH.Name -> FilePath -> TH.ExpQ
targetResultTH f m = [| targetResult $(monomorphic f) $(TH.stringE $ show f) m |]
-- | Like 'target', but accepts options to control the enumeration depth,
-- solver, and verbosity.
targetWith :: Testable f => f -> String -> FilePath -> TargetOpts -> IO ()
targetWith f name path opts
= do res <- targetResultWith f name path opts
case res of
Passed n -> printf "OK. Passed %d tests\n\n" n
Failed x -> printf "Found counter-example: %s\n\n" x
Errored x -> printf "Error! %s\n\n" x
targetWithTH :: TH.Name -> FilePath -> TargetOpts -> TH.ExpQ
targetWithTH f m opts = [| targetWith $(monomorphic f) $(TH.stringE $ show f) m opts |]
-- | Like 'targetWith', but returns the 'Result' instead of printing to standard out.
targetResultWith :: Testable f => f -> String -> FilePath -> TargetOpts -> IO Result
targetResultWith f name path opts
= do when (verbose opts) $
printf "Testing %s\n" name
sp <- getSpec (ghcOpts opts) path
ctx <- mkContext (solver opts)
do r <- runTarget opts (initState path sp ctx) $ do
ty <- safeFromJust "targetResultWith" . lookup (symbol name) <$> gets sigs
test f ty
_ <- cleanupContext ctx
return r
`onException` terminateProcess (pId ctx)
where
mkContext = if logging opts
then flip (makeContext False) (".target/" ++ name)
else makeContextNoLog False
targetResultWithTH :: TH.Name -> FilePath -> TargetOpts -> TH.ExpQ
targetResultWithTH f m opts = [| targetResultWith $(monomorphic f) $(TH.stringE $ show f) m opts |]
data Test = forall t. Testable t => T t
| gridaphobe/target | src/Test/Target.hs | mit | 3,744 | 0 | 19 | 953 | 821 | 445 | 376 | 69 | 3 |
{-|
Module : TestPrint.Problen.BSP.CNF.Builder
Description : The CNFBuilder module Printer tests
Copyright : (c) Andrew Burnett 2014-2015
Maintainer : andyburnett88@gmail.com
Stability : experimental
Portability : Unknown
The Test Tree Node for the CNFBuilder module Printer Tests
-}
module TestPrint.Problem.BSP.CNF.Builder (
printer -- :: TestTree
) where
import HSat.Problem.BSP.CNF.Builder.Internal
import HSat.Problem.BSP.Common
import TestPrint
name :: String
name = "Builder"
printer :: TestTree
printer =
testGroup name [
printBuilders,
printErrors1,
printErrors2,
printErrors3
]
printBuilders :: TestTree
printBuilders =
printList "CNFBuilder" [
CNFBuilder 234 200 6 clauses clause,
CNFBuilder 234 268 5 clauses emptyClause,
CNFBuilder 10 30 0 emptyClauses emptyClause
]
clauses :: Clauses
clauses = mkClausesFromIntegers [
[-24,-185,63,56,46,32,4,-47,-5,-1],
[134,45,63,67,88,-91,100],
[1,1,1,1,1],
[2,2,2,2,-2],
[44,-44,33]
]
clause :: Clause
clause = mkClauseFromIntegers [
23,-65,11,199,-198]
printErrors1 :: TestTree
printErrors1 =
printTest "Incorrect Clause Number" (
IncorrectClauseNumber 10 8)
printErrors2 :: TestTree
printErrors2 =
printTest "Incorrect Var Range" (
VarOutsideRange 100000 1000023434)
printErrors3 :: TestTree
printErrors3 =
printTest "Initialisation Error" (
Initialisation (-1) (-1))
| aburnett88/HSat | tests-src/TestPrint/Problem/BSP/CNF/Builder.hs | mit | 1,419 | 0 | 9 | 254 | 374 | 223 | 151 | 42 | 1 |
module GHCJS.DOM.VTTRegionList (
) where
| manyoo/ghcjs-dom | ghcjs-dom-webkit/src/GHCJS/DOM/VTTRegionList.hs | mit | 43 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
-- problem 1
-- find the last element of a list
last' :: [a] -> a
last' = head . reverse
-- problem 2
-- find the penultimate element of a list
penult :: [a] -> a
penult = last . init
-- problem 3
-- find the k'th element of a list, 1-based indexing.
elemAt :: [a] -> Int -> a
elemAt x k = x !! (k - 1)
-- problem 4
-- find the number of elements in a list
length' :: (Integral b) => [a] -> b
length' = foldl (\n _ -> n + 1) 0
-- problem 5
-- reverse a list
reverse' :: [a] -> [a]
reverse' = foldl (flip (:)) []
-- problem 6
-- find out whether a list is a palindrome.
ispal :: [a] -> [a]
ispal x = x == reverse(x)
-- problem 7
-- flatten a nested structure
data NestedList a = Elem a | List [NestedList a]
| autocorr/lyah | 99qs/01_lists.hs | mit | 714 | 0 | 8 | 167 | 228 | 133 | 95 | 13 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
module CodeGenerator(
generatePISA,
showPISAProgram
) where
import Data.List
import Control.Arrow
import Control.Monad.Except
import Control.Monad.State
import Debug.Trace (trace, traceShow)
import Text.Pretty.Simple (pPrint)
import AST
import ClassAnalyzer
import PISA
import ScopeAnalyzer
{-# ANN module "HLint: ignore Reduce duplication" #-}
data CGState =
CGState {
labelIndex :: SIdentifier,
registerIndex :: Integer,
labelTable :: [(SIdentifier, Label)],
registerStack :: [(SIdentifier, Register)],
saState :: SAState
} deriving (Show, Eq)
newtype CodeGenerator a = CodeGenerator { runCG :: StateT CGState (Except String) a }
deriving (Functor, Applicative, Monad, MonadState CGState, MonadError String)
initialState :: SAState -> CGState
initialState s = CGState { labelIndex = 0, registerIndex = 6, labelTable = [], registerStack = [], saState = s }
-- | Register containing 0
registerZero :: Register
registerZero = Reg 0
-- | Register containing Stack pointer
registerSP :: Register
registerSP = Reg 1
-- | Register R0
registerRO :: Register
registerRO = Reg 2
-- | Register holding 'this'
registerThis :: Register
registerThis = Reg 3
-- | Register containing Free list pointers
registerFLPs :: Register
registerFLPs = Reg 4
-- | Register containing Heap pointer
registerHP :: Register
registerHP = Reg 5
-- | Pushes a new register to the register stack
pushRegister :: SIdentifier -> CodeGenerator Register
pushRegister i = do ri <- gets registerIndex
modify $ \s -> s { registerIndex = 1 + ri, registerStack = (i, Reg ri) : registerStack s }
return $ Reg ri
-- | Pop a register from the register stack
popRegister :: CodeGenerator ()
popRegister = modify $ \s -> s { registerIndex = (-1) + registerIndex s, registerStack = drop 1 $ registerStack s }
-- | Reserve a tmp register
tempRegister :: CodeGenerator Register
tempRegister =
do ri <- gets registerIndex
modify $ \s -> s { registerIndex = 1 + ri }
return $ Reg ri
-- | Clear reverved tmp register
popTempRegister :: CodeGenerator ()
popTempRegister = modify $ \s -> s { registerIndex = (-1) + registerIndex s }
-- | Lookup register of given identifier
lookupRegister :: SIdentifier -> CodeGenerator Register
lookupRegister i = gets registerStack >>= \rs ->
case lookup i rs of
Nothing -> throwError $ "ICE: No register reserved for index " ++ show i
(Just r) -> return r
-- | Returns the method name of a valid method identifier
getMethodName :: SIdentifier -> CodeGenerator MethodName
getMethodName i = gets (symbolTable . saState) >>= \st ->
case lookup i st of
(Just (Method _ n)) -> return n
_ -> throwError $ "ICE: Invalid method index " ++ show i
-- | Inserts a unique method label in the label table for a given method identifier
insertMethodLabel :: SIdentifier -> CodeGenerator ()
insertMethodLabel m =
do n <- getMethodName m
i <- gets labelIndex
modify $ \s -> s { labelIndex = 1 + i, labelTable = (m, "l_" ++ n ++ "_" ++ show i) : labelTable s }
-- | Returns the Method label for a method identifier
getMethodLabel :: SIdentifier -> CodeGenerator Label
getMethodLabel m = gets labelTable >>= \lt ->
case lookup m lt of
(Just l) -> return l
Nothing -> insertMethodLabel m >> getMethodLabel m
-- | Returns a unique label by appending the label index to a passed label type
getUniqueLabel :: Label -> CodeGenerator Label
getUniqueLabel l =
do i <- gets labelIndex
modify $ \s -> s { labelIndex = 1 + i }
return $ l ++ "_" ++ show i
-- | Returns the address to the variable of a given identifier
loadVariableAddress :: SIdentifier -> CodeGenerator (Register, [(Maybe Label, MInstruction)], CodeGenerator ())
loadVariableAddress n = gets (symbolTable . saState) >>= \st ->
case lookup n st of
(Just (ClassField _ _ _ o)) -> tempRegister >>= \r -> return (r, [(Nothing, ADD r registerThis), (Nothing, ADDI r $ Immediate o)], popTempRegister)
(Just (LocalVariable _ _)) -> lookupRegister n >>= \r -> return (r, [], return ())
(Just (MethodParameter _ _)) -> lookupRegister n >>= \r -> return (r, [], return ())
_ -> throwError $ "ICE: Invalid variable index " ++ show n
-- | Returns the value of a variable of given identifier
loadVariableValue :: SIdentifier -> CodeGenerator (Register, [(Maybe Label, MInstruction)], CodeGenerator ())
loadVariableValue n =
do (ra, la, ua) <- loadVariableAddress n
rv <- tempRegister
return (rv, la ++ [(Nothing, EXCH rv ra)] ++ invertInstructions la, popTempRegister >> ua)
-- | Returns address an array element
loadArrayElementVariableAddress :: SIdentifier -> SExpression -> CodeGenerator (Register, [(Maybe Label, MInstruction)], CodeGenerator ())
loadArrayElementVariableAddress n e =
do (ra, la, ua) <- loadVariableAddress n
(re, le, ue) <- cgExpression e
rv <- tempRegister
rt <- tempRegister
return (rv, la ++ le ++ [(Nothing, EXCH rt ra), (Nothing, XOR rv rt), (Nothing, EXCH rt ra), (Nothing, ADDI rv ArrayElementOffset), (Nothing, ADD rv re)] ++ invertInstructions (la ++ le), popTempRegister >> popTempRegister >> ue >> ua)
-- | Returns the value of an array element
loadArrayElementVariableValue :: SIdentifier -> SExpression -> CodeGenerator (Register, [(Maybe Label, MInstruction)], CodeGenerator ())
loadArrayElementVariableValue n e =
do (ra, la, ua) <- loadArrayElementVariableAddress n e
rv <- tempRegister
return (rv, la ++ [(Nothing, EXCH rv ra)] ++ invertInstructions la , popTempRegister >> ua)
-- | Returns pointer to free list at given index
loadFreeListAddress :: Register -> CodeGenerator (Register, [(Maybe Label, MInstruction)], CodeGenerator ())
loadFreeListAddress index = tempRegister >>= \rt -> return (rt, [(Nothing, XOR rt registerFLPs), (Nothing, ADD rt index)], popTempRegister)
-- | Returns a copy of the pointer to the head of the free list at the given register
loadHeadAtFreeList :: Register -> CodeGenerator (Register, [(Maybe Label, MInstruction)], CodeGenerator ())
loadHeadAtFreeList rFreeList =
do rv <- tempRegister
rt <- tempRegister
let copyAddress = [(Nothing, EXCH rt rFreeList),
(Nothing, XOR rv rt),
(Nothing, EXCH rt rFreeList)]
return (rv, copyAddress, popTempRegister >> popTempRegister)
-- | Code generation for binary operators
cgBinOp :: BinOp -> Register -> Register -> CodeGenerator (Register, [(Maybe Label, MInstruction)], CodeGenerator ())
cgBinOp Add r1 r2 = tempRegister >>= \rt -> return (rt, [(Nothing, XOR rt r1), (Nothing, ADD rt r2)], popTempRegister)
cgBinOp Sub r1 r2 = tempRegister >>= \rt -> return (rt, [(Nothing, XOR rt r1), (Nothing, SUB rt r2)], popTempRegister)
cgBinOp Xor r1 r2 = tempRegister >>= \rt -> return (rt, [(Nothing, XOR rt r1), (Nothing, XOR rt r2)], popTempRegister)
cgBinOp BitAnd r1 r2 = tempRegister >>= \rt -> return (rt, [(Nothing, ANDX rt r1 r2)], popTempRegister)
cgBinOp BitOr r1 r2 = tempRegister >>= \rt -> return (rt, [(Nothing, ORX rt r1 r2)], popTempRegister)
cgBinOp Lt r1 r2 =
do rt <- tempRegister
rc <- tempRegister
l_top <- getUniqueLabel "cmp_top"
l_bot <- getUniqueLabel "cmp_bot"
let cmp = [(Nothing, XOR rt r1),
(Nothing, SUB rt r2),
(Just l_top, BGEZ rt l_bot),
(Nothing, XORI rc $ Immediate 1),
(Just l_bot, BGEZ rt l_top)]
return (rc, cmp, popTempRegister >> popTempRegister)
cgBinOp Gt r1 r2 =
do rt <- tempRegister
rc <- tempRegister
l_top <- getUniqueLabel "cmp_top"
l_bot <- getUniqueLabel "cmp_bot"
let cmp = [(Nothing, XOR rt r1),
(Nothing, SUB rt r2),
(Just l_top, BLEZ rt l_bot),
(Nothing, XORI rc $ Immediate 1),
(Just l_bot, BLEZ rt l_top)]
return (rc, cmp, popTempRegister >> popTempRegister)
cgBinOp Eq r1 r2 =
do rt <- tempRegister
l_top <- getUniqueLabel "cmp_top"
l_bot <- getUniqueLabel "cmp_bot"
let cmp = [(Just l_top, BNE r1 r2 l_bot),
(Nothing, XORI rt $ Immediate 1),
(Just l_bot, BNE r1 r2 l_top)]
return (rt, cmp, popTempRegister)
cgBinOp Neq r1 r2 =
do rt <- tempRegister
l_top <- getUniqueLabel "cmp_top"
l_bot <- getUniqueLabel "cmp_bot"
let cmp = [(Just l_top, BEQ r1 r2 l_bot),
(Nothing, XORI rt $ Immediate 1),
(Just l_bot, BEQ r1 r2 l_top)]
return (rt, cmp, popTempRegister)
cgBinOp Lte r1 r2 =
do rt <- tempRegister
rc <- tempRegister
l_top <- getUniqueLabel "cmp_top"
l_bot <- getUniqueLabel "cmp_bot"
let cmp = [(Nothing, XOR rt r1),
(Nothing, SUB rt r2),
(Just l_top, BGTZ rt l_bot),
(Nothing, XORI rc $ Immediate 1),
(Just l_bot, BGTZ rt l_top)]
return (rc, cmp, popTempRegister >> popTempRegister)
cgBinOp Gte r1 r2 =
do rt <- tempRegister
rc <- tempRegister
l_top <- getUniqueLabel "cmp_top"
l_bot <- getUniqueLabel "cmp_bot"
let cmp = [(Nothing, XOR rt r1),
(Nothing, SUB rt r2),
(Just l_top, BLTZ rt l_bot),
(Nothing, XORI rc $ Immediate 1),
(Just l_bot, BLTZ rt l_top)]
return (rc, cmp, popTempRegister >> popTempRegister)
cgBinOp _ _ _ = throwError "ICE: Binary operator not implemented"
-- | Code generation for expressions
cgExpression :: SExpression -> CodeGenerator (Register, [(Maybe Label, MInstruction)], CodeGenerator ())
cgExpression (Constant 0) = return (registerZero, [], return ())
cgExpression (Constant n) = tempRegister >>= \rt -> return (rt, [(Nothing, XORI rt $ Immediate n)], popTempRegister)
cgExpression (Variable i) = loadVariableValue i
cgExpression (ArrayElement (n, e)) = loadArrayElementVariableValue n e
cgExpression Nil = return (registerZero, [], return ())
cgExpression (Binary op e1 e2) =
do (r1, l1, u1) <- cgExpression e1
(r2, l2, u2) <- cgExpression e2
(ro, lo, uo) <- cgBinOp op r1 r2
return (ro, l1 ++ l2 ++ lo, uo >> u2 >> u1)
-- | Code generation for binary expressions
cgBinaryExpression :: SExpression -> CodeGenerator (Register, [(Maybe Label, MInstruction)], CodeGenerator ())
cgBinaryExpression e =
do (re, le, ue) <- cgExpression e
rt <- tempRegister
l_top <- getUniqueLabel "f_top"
l_bot <- getUniqueLabel "f_bot"
let flatten = [(Just l_top, BEQ re registerZero l_bot),
(Nothing, XORI rt $ Immediate 1),
(Just l_bot, BEQ re registerZero l_top)]
return (rt, le ++ flatten, popTempRegister >> ue)
-- | Code generation for assignments
cgAssign :: SIdentifier -> ModOp -> SExpression -> CodeGenerator [(Maybe Label, MInstruction)]
cgAssign n modop e =
do (rt, lt, ut) <- loadVariableValue n
(re, le, ue) <- cgExpression e
ue >> ut
return $ lt ++ le ++ [(Nothing, cgModOp modop rt re)] ++ invertInstructions (lt ++ le)
where cgModOp ModAdd = ADD
cgModOp ModSub = SUB
cgModOp ModXor = XOR
-- | Code generation for assignments
cgAssignArrElem :: (SIdentifier, SExpression) -> ModOp -> SExpression -> CodeGenerator [(Maybe Label, MInstruction)]
cgAssignArrElem (n, e1) modop e2 =
do (rt, lt, ut) <- loadArrayElementVariableValue n e1
(re, le, ue) <- cgExpression e2
l <- getUniqueLabel "assArrElem"
ue >> ut
return $ lt ++ le ++ [(Just l, cgModOp modop rt re)] ++ invertInstructions (lt ++ le)
where cgModOp ModAdd = ADD
cgModOp ModSub = SUB
cgModOp ModXor = XOR
-- | Ensures correct loads for swapping
loadForSwap :: (SIdentifier, Maybe SExpression) -> CodeGenerator (Register, [(Maybe Label, MInstruction)], CodeGenerator ())
loadForSwap (n, x) = gets (symbolTable . saState) >>= \st ->
case lookup n st of
(Just (ClassField IntegerArrayType _ _ _)) -> case x of
Just x' -> loadArrayElementVariableValue n x'
_ -> loadVariableValue n
(Just (ClassField (ObjectArrayType _) _ _ _)) -> case x of
Just x' -> loadArrayElementVariableValue n x'
_ -> loadVariableValue n
(Just ClassField {}) -> loadVariableValue n
(Just (LocalVariable IntegerType _)) -> loadVariableValue n
(Just (LocalVariable (ObjectType _) _)) -> loadVariableValue n
(Just (LocalVariable (CopyType _) _)) -> loadVariableValue n
(Just (LocalVariable IntegerArrayType _)) -> case x of
Just x' -> loadArrayElementVariableValue n x'
_ -> loadVariableValue n
(Just (LocalVariable (ObjectArrayType _) _)) -> case x of
Just x' -> loadArrayElementVariableValue n x'
_ -> loadVariableValue n
(Just (MethodParameter IntegerType _)) -> loadVariableValue n
(Just (MethodParameter (ObjectType _) _)) -> loadVariableValue n
(Just (MethodParameter (CopyType _) _)) -> loadVariableValue n
(Just (MethodParameter IntegerArrayType _)) -> case x of
Just x' -> loadArrayElementVariableValue n x'
_ -> loadVariableValue n
(Just (MethodParameter (ObjectArrayType _) _)) -> case x of
Just x' -> loadArrayElementVariableValue n x'
_ -> loadVariableValue n
_ -> throwError $ "ICE: Invalid variable index " ++ show n
-- | Code generation for swaps
cgSwap :: (SIdentifier, Maybe SExpression) -> (SIdentifier, Maybe SExpression) -> CodeGenerator [(Maybe Label, MInstruction)]
cgSwap n1 n2 = if n1 == n2 then return [] else
do (r1, l1, u1) <- loadForSwap n1
(r2, l2, u2) <- loadForSwap n2
u2 >> u1
l <- getUniqueLabel "swap"
let swap = [(Just l, XOR r1 r2), (Nothing, XOR r2 r1), (Nothing, XOR r1 r2)]
return $ l1 ++ l2 ++ swap ++ invertInstructions (l1 ++ l2)
-- | Code generation for conditionals
cgConditional :: SExpression -> [SStatement] -> [SStatement] -> SExpression -> CodeGenerator [(Maybe Label, MInstruction)]
cgConditional e1 s1 s2 e2 =
do l_test <- getUniqueLabel "test"
l_assert_t <- getUniqueLabel "assert_true"
l_test_f <- getUniqueLabel "test_false"
l_assert <- getUniqueLabel "assert"
rt <- tempRegister
(re1, le1, ue1) <- cgBinaryExpression e1
ue1
s1' <- concat <$> mapM cgStatement s1
s2' <- concat <$> mapM cgStatement s2
(re2, le2, ue2) <- cgBinaryExpression e2
ue2 >> popTempRegister --rt
return $ le1 ++ [(Nothing, XOR rt re1)] ++ invertInstructions le1 ++
[(Just l_test, BEQ rt registerZero l_test_f), (Nothing, XORI rt $ Immediate 1)] ++
s1' ++ [(Nothing, XORI rt $ Immediate 1), (Just l_assert_t, BRA l_assert), (Just l_test_f, BRA l_test)] ++
s2' ++ [(Just l_assert, BNE rt registerZero l_assert_t)] ++
le2 ++ [(Nothing, XOR rt re2)] ++ invertInstructions le2
-- | Code generation for loops
cgLoop :: SExpression -> [SStatement] -> [SStatement] -> SExpression -> CodeGenerator [(Maybe Label, MInstruction)]
cgLoop e1 s1 s2 e2 =
do l_entry <- getUniqueLabel "entry"
l_test <- getUniqueLabel "test"
l_assert <- getUniqueLabel "assert"
l_exit <- getUniqueLabel "exit"
rt <- tempRegister
(re1, le1, ue1) <- cgBinaryExpression e1
ue1
s1' <- concat <$> mapM cgStatement s1
s2' <- concat <$> mapM cgStatement s2
(re2, le2, ue2) <- cgBinaryExpression e2
ue2 >> popTempRegister --rt
return $ [(Nothing, XORI rt $ Immediate 1), (Just l_entry, BEQ rt registerZero l_assert)] ++
le1 ++ [(Nothing, XOR rt re1)] ++ invertInstructions le1 ++
s1' ++ le2 ++ [(Nothing, XOR rt re2)] ++ invertInstructions le2 ++
[(Just l_test, BNE rt registerZero l_exit)] ++ s2' ++
[(Just l_assert, BRA l_entry), (Just l_exit, BRA l_test), (Nothing, XORI rt $ Immediate 1)]
-- | Code generation for object blocks
cgObjectBlock :: TypeName -> SIdentifier -> [SStatement] -> CodeGenerator [(Maybe Label, MInstruction)]
cgObjectBlock tp n stmt =
do rn <- pushRegister n
let push = [(Nothing, XOR rn registerSP), (Nothing, SUBI registerSP $ Immediate 1)]
malloc <- cgObjectConstruction tp (n, Nothing)
stmt' <- concat <$> mapM cgStatement stmt
free <- cgObjectDestruction tp (n, Nothing)
popRegister
return $ push ++ malloc ++ stmt' ++ free ++ invertInstructions push
-- | Code generation for local blocks
cgLocalBlock :: SIdentifier -> SExpression -> [SStatement] -> SExpression -> CodeGenerator [(Maybe Label, MInstruction)]
cgLocalBlock n e1 stmt e2 =
do rn <- pushRegister n
(re1, le1, ue1) <- cgExpression e1
rt1 <- tempRegister
popTempRegister >> ue1
stmt' <- concat <$> mapM cgStatement stmt
(re2, le2, ue2) <- cgExpression e2
rt2 <- tempRegister
popTempRegister >> ue2
popRegister --rn
l <- getUniqueLabel "localBlock"
let create re rt = [(Just l, XOR rn registerSP),
(Nothing, XOR rt re),
(Nothing, EXCH rt registerSP),
(Nothing, SUBI registerSP $ Immediate 1)]
load = le1 ++ create re1 rt1 ++ invertInstructions le1
clear = le2 ++ invertInstructions (create re2 rt2) ++ invertInstructions le2
return $ load ++ stmt' ++ clear
-- | Code generation for calls
cgCall :: [(SIdentifier, Maybe SExpression)] -> [(Maybe Label, MInstruction)] -> Register -> CodeGenerator [(Maybe Label, MInstruction)]
cgCall args jump this =
do (ra, la, ua) <- unzip3 <$> mapM loadAddr args
sequence_ ua
rs <- gets registerStack
let rr = (registerThis : map snd rs) \\ (this : ra)
store = concatMap push $ rr ++ ra ++ [this]
return $ concat la ++ store ++ jump ++ invertInstructions store ++ invertInstructions (concat la)
where push r = [(Nothing, EXCH r registerSP), (Nothing, SUBI registerSP $ Immediate 1)]
loadAddr (n, e) =
case e of
Nothing -> loadVariableAddress n
Just e' -> loadArrayElementVariableAddress n e'
-- | Code generation for local calling
cgLocalCall :: SIdentifier -> [(SIdentifier, Maybe SExpression)]-> CodeGenerator [(Maybe Label, MInstruction)]
cgLocalCall m args = getMethodLabel m >>= \l_m -> cgCall args [(Nothing, BRA l_m)] registerThis
-- | Code generation for local uncalling
cgLocalUncall :: SIdentifier -> [(SIdentifier, Maybe SExpression)] -> CodeGenerator [(Maybe Label, MInstruction)]
cgLocalUncall m args = getMethodLabel m >>= \l_m -> cgCall args [(Nothing, RBRA l_m)] registerThis
-- | Returns the type associated with a given identifier
getType :: SIdentifier -> CodeGenerator TypeName
getType i = gets (symbolTable . saState) >>= \st ->
case lookup i st of
(Just (LocalVariable (ObjectType tp) _)) -> return tp
(Just (ClassField (ObjectType tp) _ _ _)) -> return tp
(Just (MethodParameter (ObjectType tp) _)) -> return tp
(Just (LocalVariable (ObjectArrayType tp) _)) -> return tp
(Just (ClassField (ObjectArrayType tp) _ _ _)) -> return tp
(Just (MethodParameter (ObjectArrayType tp) _)) -> return tp
_ -> throwError $ "ICE: Invalid object variable index " ++ show i
-- | Load the return offset for methods
loadMethodAddress :: (SIdentifier, Register) -> MethodName -> CodeGenerator (Register, [(Maybe Label, MInstruction)])
loadMethodAddress (o, ro) m =
do rv <- tempRegister
rt <- tempRegister
rtgt <- tempRegister
offsetMacro <- OffsetMacro <$> getType o <*> pure m
l <- getUniqueLabel "loadMetAdd"
let load = [(Just l, EXCH rv ro),
(Nothing, ADDI rv offsetMacro),
(Nothing, EXCH rt rv),
(Nothing, XOR rtgt rt),
(Nothing, EXCH rt rv),
(Nothing, SUBI rv offsetMacro),
(Nothing, EXCH rv ro)]
return (rtgt, load)
-- | Load address or value needed for calls
loadForCall :: (SIdentifier, Maybe SExpression) -> CodeGenerator (Register, [(Maybe Label, MInstruction)], CodeGenerator ())
loadForCall (n, e) = gets (symbolTable . saState) >>= \st ->
case lookup n st of
(Just (ClassField (ObjectArrayType _) _ _ _)) ->
case e of
Just x' -> loadArrayElementVariableValue n x'
_ -> throwError $ "ICE: Invalid variable index " ++ show n
(Just ClassField {}) -> loadVariableValue n
(Just (LocalVariable (ObjectType _) _)) -> loadVariableValue n
(Just (LocalVariable (CopyType _) _)) -> loadVariableValue n
(Just (LocalVariable (ObjectArrayType _) _)) ->
case e of
Just x' -> loadArrayElementVariableValue n x'
_ -> throwError $ "ICE: Invalid variable index " ++ show n
(Just _) -> loadVariableValue n
_ -> throwError $ "ICE: Invalid variable index " ++ show n
-- | Code generation for object calls
cgObjectCall :: (SIdentifier, Maybe SExpression) -> MethodName -> [(SIdentifier, Maybe SExpression)] -> CodeGenerator [(Maybe Label, MInstruction)]
cgObjectCall (o, e) m args =
do (ro, lo, uo) <- loadForCall (o, e)
rt <- tempRegister
(rtgt, loadAddress) <- loadMethodAddress (o, rt) m
l_jmp <- getUniqueLabel "l_jmp"
let jp = [(Nothing, SUBI rtgt $ AddressMacro l_jmp),
(Just l_jmp, SWAPBR rtgt),
(Nothing, NEG rtgt),
(Nothing, ADDI rtgt $ AddressMacro l_jmp)]
call <- cgCall args jp rt
popTempRegister >> popTempRegister >> popTempRegister -- rv, rt & rtgt from loadMethod Addr
popTempRegister >> uo
let load = lo ++ [(Nothing, XOR rt ro)] ++ loadAddress ++ invertInstructions lo
return $ load ++ call ++ invertInstructions load
-- | Code generation for object uncalls
cgObjectUncall :: (SIdentifier, Maybe SExpression) -> MethodName -> [(SIdentifier, Maybe SExpression)] -> CodeGenerator [(Maybe Label, MInstruction)]
cgObjectUncall (o, e) m args =
do (ro, lo, uo) <- loadForCall (o, e)
rt <- tempRegister
(rtgt, loadAddress) <- loadMethodAddress (o, rt) m
l_jmp <- getUniqueLabel "l_jmp"
l_rjmp_top <- getUniqueLabel "l_rjmp_top"
l_rjmp_bot <- getUniqueLabel "l_rjmp_bot"
let jp = [(Nothing, SUBI rtgt $ AddressMacro l_jmp),
(Just l_rjmp_top, RBRA l_rjmp_bot),
(Just l_jmp, SWAPBR rtgt),
(Nothing, NEG rtgt),
(Just l_rjmp_bot, BRA l_rjmp_top),
(Nothing, ADDI rtgt $ AddressMacro l_jmp)]
call <- cgCall args jp rt
popTempRegister >> popTempRegister >> popTempRegister -- rv, rt & rtgt from loadMethod Addr
popTempRegister >> uo
let load = lo ++ [(Nothing, XOR rt ro)] ++ loadAddress ++ invertInstructions lo
return $ load ++ call ++ invertInstructions load
-- | Code generation for object construction
cgObjectConstruction :: TypeName -> (SIdentifier, Maybe SExpression) -> CodeGenerator [(Maybe Label, MInstruction)]
cgObjectConstruction tp (n, e) =
do (rv, lv, uv) <- case e of
Nothing -> loadVariableAddress n
Just e' -> loadArrayElementVariableAddress n e'
rp <- tempRegister
rt <- tempRegister
popTempRegister >> popTempRegister
l <- getUniqueLabel "obj_con"
rs <- gets registerStack
let rr = (registerThis : map snd rs) \\ [rp, rt]
store = concatMap push rr
malloc = [(Just l, ADDI rt $ SizeMacro tp)] ++ push rt ++ push rp
lb = l ++ "_bot"
setVtable = [(Nothing, XORI rt $ AddressMacro $ "l_" ++ tp ++ "_vt"),
(Nothing, EXCH rt rp),
(Nothing, ADDI rp ReferenceCounterIndex),
(Nothing, XORI rt $ Immediate 1),
(Nothing, EXCH rt rp),
(Just lb, SUBI rp ReferenceCounterIndex),
(Nothing, EXCH rp rv)]
uv
return $ store ++ malloc ++ [(Nothing, BRA "l_malloc")] ++ invertInstructions malloc ++ invertInstructions store ++ lv ++ setVtable ++ invertInstructions lv
where push r = [(Nothing, EXCH r registerSP), (Nothing, SUBI registerSP $ Immediate 1)]
-- | Code generation for object destruction
cgObjectDestruction :: TypeName -> (SIdentifier, Maybe SExpression) -> CodeGenerator [(Maybe Label, MInstruction)]
cgObjectDestruction tp (n, e) =
do (rp, la, ua) <- case e of
Nothing -> loadVariableValue n
Just e' -> loadArrayElementVariableValue n e'
rt <- tempRegister
l <- getUniqueLabel "obj_des"
popTempRegister >> ua
rs <- gets registerStack
let removeVtable = [(Just lt, EXCH rt rp),
(Nothing, XORI rt $ AddressMacro $ "l_" ++ tp ++ "_vt"),
(Nothing, ADDI rp ReferenceCounterIndex),
(Nothing, EXCH rt rp),
(Nothing, XORI rt $ Immediate 1),
(Nothing, SUBI rp ReferenceCounterIndex)]
rr = (registerThis : map snd rs) \\ [rp, rt]
store = concatMap push rr
free = [(Just l, ADDI rt $ SizeMacro tp)] ++ push rt ++ push rp
lt = l ++ "_top"
return $ la ++ removeVtable ++ store ++ free ++ [(Nothing, RBRA "l_malloc")] ++ invertInstructions (la ++ store ++ free)
where push r = [(Nothing, EXCH r registerSP), (Nothing, SUBI registerSP $ Immediate 1)]
-- | Code generation for reference construction
cgCopyReference :: (SIdentifier, Maybe SExpression) -> (SIdentifier, Maybe SExpression) -> CodeGenerator [(Maybe Label, MInstruction)]
cgCopyReference (n, e1) (m, e2) =
do (rcp, lp, up) <- case e2 of
Nothing -> loadVariableValue m
Just e2' -> loadArrayElementVariableValue m e2'
(rp, la, ua) <- case e1 of
Nothing -> loadVariableValue n
Just e1' -> loadArrayElementVariableValue n e1'
rt <- tempRegister
up >> ua >> popTempRegister
l <- getUniqueLabel "copy"
let reference = [(Just l, XOR rcp rp),
(Nothing, ADDI rp ReferenceCounterIndex),
(Nothing, EXCH rt rp),
(Nothing, ADDI rt $ Immediate 1),
(Nothing, EXCH rt rp),
(Nothing, SUBI rp ReferenceCounterIndex)]
return $ lp ++ la ++ reference ++ invertInstructions (lp ++ la)
-- | Code generation for reference destruction
cgUnCopyReference :: (SIdentifier, Maybe SExpression) -> (SIdentifier, Maybe SExpression) -> CodeGenerator [(Maybe Label, MInstruction)]
cgUnCopyReference (n, e1) (m, e2) =
do (rcp, la1, ua1) <- case e2 of
Nothing -> loadVariableValue m
Just e2' -> loadArrayElementVariableValue m e2'
(rp, la2, ua2) <- case e1 of
Nothing -> loadVariableValue n
Just e1' -> loadArrayElementVariableValue n e1'
rt <- tempRegister
l <- getUniqueLabel "uncopy"
ua1 >> ua2 >> popTempRegister
let reference = [(Just l, XOR rcp rp),
(Nothing, ADDI rp ReferenceCounterIndex),
(Nothing, EXCH rt rp),
(Nothing, SUBI rt $ Immediate 1),
(Nothing, EXCH rt rp),
(Nothing, SUBI rp ReferenceCounterIndex)]
-- removeRegister (m, rcp)
return $ la1 ++ la2 ++ reference ++ invertInstructions (la1 ++ la2)
-- | Code generation for array construction
cgArrayConstruction :: SExpression -> SIdentifier -> CodeGenerator [(Maybe Label, MInstruction)]
cgArrayConstruction e n =
do (ra, la, ua) <- loadVariableAddress n
(re, le, ue) <- cgExpression e
rp <- tempRegister
rt <- tempRegister
popTempRegister >> popTempRegister
l <- getUniqueLabel "arr_con"
rs <- gets registerStack
let rr = (registerThis : map snd rs) \\ [rp, rt]
store = le ++ [(Just l, ADDI rt ArrayElementOffset), (Nothing, ADD rt re)] ++ invertInstructions le ++ concatMap push rr
malloc = push rt ++ push rp
lb = l ++ "_bot"
initArray = la ++ le ++
[(Nothing, XOR rt re),
(Nothing, EXCH rt rp),
(Nothing, ADDI rp ReferenceCounterIndex),
(Nothing, XORI rt $ Immediate 1),
(Nothing, EXCH rt rp),
(Nothing, SUBI rp ReferenceCounterIndex),
(Just lb, EXCH rp ra)] ++
invertInstructions (la ++ le)
ue >> ua
return $ store ++ malloc ++ [(Nothing, BRA "l_malloc")] ++ invertInstructions (store ++ malloc) ++ initArray
where push r = [(Nothing, EXCH r registerSP), (Nothing, SUBI registerSP $ Immediate 1)]
-- | Code generation for array destruction
cgArrayDestruction :: SExpression -> SIdentifier -> CodeGenerator [(Maybe Label, MInstruction)]
cgArrayDestruction e n =
do (rp, lp, up) <- loadVariableValue n
(re, le, ue) <- cgExpression e
rt <- tempRegister
l <- getUniqueLabel "obj_des"
popTempRegister >> ue >> up
rs <- gets registerStack
let removeArray = [(Just lt, EXCH rt rp),
(Nothing, XOR rt re),
(Nothing, ADDI rp ReferenceCounterIndex),
(Nothing, EXCH rt rp),
(Nothing, XORI rt $ Immediate 1),
(Nothing, SUBI rp ReferenceCounterIndex)]
rr = (registerThis : map snd rs) \\ [rp, rt]
store = concatMap push rr
free = [(Just l, ADDI rt ArrayElementOffset), (Nothing, ADD rt re)] ++ push rt ++ push rp
lt = l ++ "_top"
return $ lp ++ le ++ removeArray ++ store ++ free ++ [(Nothing, RBRA "l_malloc")] ++ invertInstructions (lp ++ le ++ store ++ free)
where push r = [(Nothing, EXCH r registerSP), (Nothing, SUBI registerSP $ Immediate 1)]
-- | Code generation for statements
cgStatement :: SStatement -> CodeGenerator [(Maybe Label, MInstruction)]
cgStatement (Assign n modop e) = cgAssign n modop e
cgStatement (AssignArrElem (n, e1) modop e2) = cgAssignArrElem (n, e1) modop e2
cgStatement (Swap (n1, e1) (n2, e2)) = cgSwap (n1, e1) (n2, e2)
cgStatement (Conditional e1 s1 s2 e2) = cgConditional e1 s1 s2 e2
cgStatement (Loop e1 s1 s2 e2) = cgLoop e1 s1 s2 e2
cgStatement (ObjectBlock tp n stmt) = cgObjectBlock tp n stmt
cgStatement (LocalBlock _ n e1 stmt e2) = cgLocalBlock n e1 stmt e2
cgStatement (LocalCall m args) = cgLocalCall m args
cgStatement (LocalUncall m args) = cgLocalUncall m args
cgStatement (ObjectCall o m args) = cgObjectCall o m args
cgStatement (ObjectUncall o m args) = cgObjectUncall o m args
cgStatement (ObjectConstruction tp n) = cgObjectConstruction tp n
cgStatement (ObjectDestruction tp n) = cgObjectDestruction tp n
cgStatement Skip = return []
cgStatement (CopyReference _ n m) = cgCopyReference n m
cgStatement (UnCopyReference _ n m) = cgUnCopyReference n m
cgStatement (ArrayConstruction (_, e) n) = cgArrayConstruction e n
cgStatement (ArrayDestruction (_, e) n) = cgArrayDestruction e n
-- | Code generation for methods
cgMethod :: (TypeName, SMethodDeclaration) -> CodeGenerator [(Maybe Label, MInstruction)]
cgMethod (_, GMDecl m ps body) =
do l <- getMethodLabel m
rs <- addParameters
body' <- concat <$> mapM cgStatement body
clearParameters
let lt = l ++ "_top"
lb = l ++ "_bot"
mp = [(Just lt, BRA lb),
(Nothing, ADDI registerSP $ Immediate 1),
(Nothing, EXCH registerRO registerSP)]
++ concatMap pushParameter rs ++
[(Nothing, EXCH registerThis registerSP),
(Nothing, SUBI registerSP $ Immediate 1),
(Just l, SWAPBR registerRO),
(Nothing, NEG registerRO),
(Nothing, ADDI registerSP $ Immediate 1),
(Nothing, EXCH registerThis registerSP)]
++ invertInstructions (concatMap pushParameter rs) ++
[(Nothing, EXCH registerRO registerSP),
(Nothing, SUBI registerSP $ Immediate 1)]
return $ mp ++ body' ++ [(Just lb, BRA lt)]
where addParameters = mapM (pushRegister . (\(GDecl _ p) -> p)) ps
clearParameters = replicateM_ (length ps) popRegister
pushParameter r = [(Nothing, EXCH r registerSP), (Nothing, SUBI registerSP $ Immediate 1)]
cgMalloc1 :: CodeGenerator [(Maybe Label, MInstruction)]
cgMalloc1 =
do -- Temp registers needed for malloc
r_p <- tempRegister -- Pointer to new obj
r_object_size <- tempRegister -- Object size
r_counter <- tempRegister -- Free list index
r_csize <- tempRegister -- Current cell size
rt <- tempRegister
rt2 <- tempRegister
r_tmp <- tempRegister
-- Expressions and sub routines
(r_e1_outer, l_e1_outer, u_e1_outer) <- cgBinOp Lt r_csize r_object_size
(r_e2_outer, l_e2_outer, u_e2_outer) <- cgBinOp Lt r_csize r_object_size
(r_fl, l_fl, u_fl) <- loadFreeListAddress r_counter
(r_block, l_block, u_block) <- loadHeadAtFreeList r_fl
(r_e1_inner, l_e1_inner, u_e1_inner) <- cgBinOp Neq r_block registerZero
(r_e2_i1, l_e2_i1, u_e2_i1) <- cgBinOp Neq r_p r_tmp
(r_e2_i2, l_e2_i2, u_e2_i2) <- cgBinOp Eq r_tmp registerZero
(r_e2_i3, l_e2_i3, u_e2_i3) <- cgBinOp BitOr r_e2_i1 r_e2_i2
let tmpRegisterList = [rt, rt2, r_tmp, r_e1_outer, r_e2_outer, r_fl, r_block, r_e1_inner, r_e2_i1, r_e2_i2, r_e2_i3]
-- Update state after evaluating expressions and subroutines
u_e2_i3 >> u_e2_i2 >> u_e2_i1 >> u_e1_inner
u_block >> u_fl >> u_e2_outer >> u_e1_outer
popTempRegister >> popTempRegister >> popTempRegister >> popTempRegister >> popTempRegister >> popTempRegister >> popTempRegister
let l_o_test = "l_o_test"
l_o_assert_t = "l_o_assert_true"
l_o_test_f = "l_o_test_false"
l_o_assert = "l_o_assert"
l_i_test = "l_i_test"
l_i_assert_t = "l_i_assert_true"
l_i_test_f = "l_i_test_false"
l_i_assert = "l_i_assert"
l_m_top = "l_malloc1_top"
l_m_bot = "l_malloc1_bot"
l_m_entry = "l_malloc1"
malloc = [(Just l_m_top, BRA l_m_bot), --
(Nothing, ADDI registerSP $ Immediate 1),
(Nothing, EXCH registerRO registerSP)] -- Pop return offset from stack
++ invertInstructions l_fl ++
[(Just l_m_entry, SWAPBR registerRO), -- Malloc1 entry/exit point
(Nothing, NEG registerRO), -- Restore return offset
(Nothing, EXCH registerRO registerSP), -- Push return offset to stack
(Nothing, SUBI registerSP $ Immediate 1)]
++ l_fl
++ l_block
++ l_e1_outer -- Set r_e1 -> c_size < obj_size
++ [(Nothing, XOR rt r_e1_outer)] -- r_t = r_e1_o
++ invertInstructions l_e1_outer ++ -- Clear r_e1_o
[(Just l_o_test, BEQ rt registerZero l_o_test_f),
(Nothing, XORI rt $ Immediate 1), -- S1_outer start
(Nothing, ADDI r_counter $ Immediate 1)] -- counter++
++ invertInstructions l_block ++
[(Nothing, RL r_csize $ Immediate 1)] -- call double(csize)
++ concatMap pushRegisterToStack tmpRegisterList
++
[(Nothing, BRA l_m_entry)] -- call malloc1()
++ invertInstructions(concatMap pushRegisterToStack tmpRegisterList)
++
[(Nothing, RR r_csize $ Immediate 1), -- uncall double(csize)
(Nothing, SUBI r_counter $ Immediate 1), -- counter++
(Nothing, XORI rt $ Immediate 1), -- S1_outer end
(Just l_o_assert_t, BRA l_o_assert),
(Just l_o_test_f, BRA l_o_test)]
++ l_e1_inner ++ -- Set r_e1_i -> r_block != 0 (S2_OUTER)
[(Nothing, XOR rt2 r_e1_inner)] -- Set rt2 -> r_e1_i
++ invertInstructions l_e1_inner ++ -- Clear r_e1_i
[(Just l_i_test, BEQ rt2 registerZero l_i_test_f),
(Nothing, XORI rt2 $ Immediate 1), -- S1_inner start
(Nothing, ADD r_p r_block), -- Set address of p to said block
(Nothing, SUB r_block r_p), -- Clear r_block
(Nothing, EXCH r_tmp r_p), -- Load address of next block
(Nothing, EXCH r_tmp r_fl), -- Set address of next block as head of current free list
(Nothing, XOR r_tmp r_p), -- Clear address of next block
(Nothing, XORI rt2 $ Immediate 1), -- S1_inner end
(Just l_i_assert_t, BRA l_i_assert),
(Just l_i_test_f, BRA l_i_test),
(Nothing, ADDI r_counter $ Immediate 1), -- S2_inner start
(Nothing, RL r_csize $ Immediate 1)] -- call double(csize)
++ concatMap pushRegisterToStack tmpRegisterList ++
[(Nothing, BRA l_m_entry)] -- call malloc1()
++ invertInstructions(concatMap pushRegisterToStack tmpRegisterList) ++
[(Nothing, RR r_csize $ Immediate 1), -- uncall double(csize)
(Nothing, SUBI r_counter $ Immediate 1), -- counter -= 1
(Nothing, XOR r_tmp r_p), -- Copy current address of p
(Nothing, EXCH r_tmp r_fl), -- Store address in current free list
(Nothing, ADD r_p r_csize), -- Set p to other half of the block we're splitting
(Just l_i_assert, BNE rt2 registerZero l_i_assert_t),
(Nothing, EXCH r_tmp r_fl),
(Nothing, SUB r_p r_csize)]
++ l_e2_i1 -- set r_e2_i1 <- p - csize != free_list[counter]
++ l_e2_i2 -- set r_e2_i2 <- free_list[counter] = 0
++ l_e2_i3 -- set r_e2_i3 <- r_e2_i1 || r_e2_i2
++ [(Nothing, XOR rt2 r_e2_i3)] -- Set rt2 -> r_i_2
++ invertInstructions l_e2_i3 -- Clear r_i_2
++ invertInstructions l_e2_i2
++ invertInstructions l_e2_i1 ++
[(Nothing, ADD r_p r_csize),
(Nothing, EXCH r_tmp r_fl), -- S2_outer end
(Just l_o_assert, BNE rt registerZero l_o_assert_t)]
++ l_e2_outer -- Set r_e2 -> c_size < obj_size
++ [(Nothing, XOR rt r_e2_outer)] -- r_t = r_e1_o
++ invertInstructions l_e2_outer -- Clear r_e1_o
++ [(Just l_m_bot, BRA l_m_top)] -- Go to top
return malloc
where pushRegisterToStack r = [(Nothing, EXCH r registerSP), (Nothing, SUBI registerSP $ Immediate 1)]
cgMalloc :: CodeGenerator [(Maybe Label, MInstruction)]
cgMalloc =
do rp <- tempRegister -- Pointer to new obj
ros <- tempRegister -- Object size
rc <- tempRegister -- Free list index
rs <- tempRegister -- Current cell size
popTempRegister >> popTempRegister >> popTempRegister >> popTempRegister
let malloc = [(Just "l_malloc_top", BRA "l_malloc_bot")]
++
[(Just "l_malloc", SWAPBR registerRO),
(Nothing, NEG registerRO),
(Nothing, ADDI rs $ Immediate 2),
(Nothing, XOR rc registerZero)]
++ concatMap pop [rp, ros]
++ push registerRO ++
[(Nothing, BRA "l_malloc1")]
++ pop registerRO
++ concatMap push [ros, rp] ++
[(Nothing, XOR rc registerZero),
(Nothing, SUBI rs $ Immediate 2),
(Just "l_malloc_bot", BRA "l_malloc_top")]
return malloc
where pop r = [(Nothing, ADDI registerSP $ Immediate 1), (Nothing, EXCH r registerSP)]
push r = invertInstructions (pop r)
-- | Code generation for virtual tables
cgVirtualTables :: CodeGenerator [(Maybe Label, MInstruction)]
cgVirtualTables = concat <$> (gets (virtualTables . saState) >>= mapM vtInstructions)
where vtInstructions (n, ms) = zip (vtLabel n) <$> mapM vtData ms
vtData m = DATA . AddressMacro <$> getMethodLabel m
vtLabel n = (Just $ "l_" ++ n ++ "_vt") : repeat Nothing
-- | Returns the main class label
getMainLabel :: CodeGenerator Label
getMainLabel = gets (mainMethod . saState) >>= getMethodLabel
-- | Fetches the main class from the class analysis state
getMainClass :: CodeGenerator TypeName
getMainClass = gets (mainClass . caState . saState) >>= \mc ->
case mc of
(Just tp) -> return tp
Nothing -> throwError "ICE: No main method defined"
-- | Fetches the field of a given type name
getFields :: TypeName -> CodeGenerator [VariableDeclaration]
getFields tp =
do cs <- gets (classes . caState . saState)
case lookup tp cs of
(Just (GCDecl _ _ fs _)) -> return fs
Nothing -> throwError $ "ICE: Unknown class " ++ tp
-- | Code generation for output
cgOutput :: TypeName -> CodeGenerator ([(Maybe Label, MInstruction)], [(Maybe Label, MInstruction)])
cgOutput tp =
do mfs <- getFields tp
co <- concat <$> mapM cgCopyOutput (zip [1..] mfs)
return (map cgStatic mfs, co)
where cgStatic (GDecl _ n) = (Just $ "l_r_" ++ n, DATA $ Immediate 0)
cgCopyOutput(o, GDecl _ n) =
do rt <- tempRegister
ra <- tempRegister
popTempRegister >> popTempRegister
let copy = [ADDI registerThis ReferenceCounterIndex,
ADDI registerThis $ Immediate o,
EXCH rt registerThis,
XORI ra $ AddressMacro $ "l_r_" ++ n,
EXCH rt ra,
XORI ra $ AddressMacro $ "l_r_" ++ n,
SUBI registerThis $ Immediate o,
SUBI registerThis ReferenceCounterIndex]
return $ zip (repeat Nothing) copy
-- | Generates code for the program entry point
cgProgram :: SProgram -> CodeGenerator PISA.MProgram
cgProgram p =
do vt <- cgVirtualTables
malloc <- cgMalloc
malloc1 <- cgMalloc1
rv <- tempRegister -- V table register
rb <- tempRegister -- Memory block register
popTempRegister >> popTempRegister
ms <- concat <$> mapM cgMethod p
l_main <- getMainLabel
mtp <- getMainClass
(out, co) <- cgOutput mtp
let mvt = "l_" ++ mtp ++ "_vt"
mn = [(Just "start", BRA "top"),
(Nothing, START),
(Nothing, ADDI registerFLPs ProgramSize), -- Init free list pointer list
(Nothing, XOR registerHP registerFLPs), -- Init heap pointer
(Nothing, ADDI registerHP FreeListsSize), -- Init space for FLPs list
(Nothing, XOR rb registerHP), -- Store address of initial memory block in rb
(Nothing, ADDI registerFLPs FreeListsSize), -- Index to end of free lists
(Nothing, SUBI registerFLPs $ Immediate 1), -- Index to last element of free lists
(Nothing, EXCH rb registerFLPs), -- Store address of first block in last element of free lists
(Nothing, ADDI registerFLPs $ Immediate 1), -- Index to end of free lists
(Nothing, SUBI registerFLPs FreeListsSize), -- Index to beginning of free lists
(Nothing, XOR registerSP registerHP), -- Init stack pointer 1/2
(Nothing, ADDI registerSP StackOffset), -- Init stack pointer 2/2
(Nothing, SUBI registerSP $ SizeMacro mtp), -- Allocate space for main on stack
(Nothing, XOR registerThis registerSP), -- Store address of main object
(Nothing, XORI rv $ AddressMacro mvt), -- Store address of vtable in rv
(Nothing, EXCH rv registerThis), -- Add address of vtable to stack
(Nothing, SUBI registerSP $ Immediate 1), -- Add address of vtable to stack
(Nothing, EXCH registerThis registerSP), -- Push 'this' to stack
(Nothing, SUBI registerSP $ Immediate 1), -- Push 'this' to stack
(Nothing, BRA l_main), -- Execute main
(Nothing, ADDI registerSP $ Immediate 1), -- Pop 'this'
(Nothing, EXCH registerThis registerSP)] -- Pop 'this'
++ co ++
[(Nothing, ADDI registerSP $ Immediate 1), -- Pop vtable address
(Nothing, EXCH rv registerThis), -- Pop vtable address
(Nothing, XORI rv $ AddressMacro mvt), -- Clear rv
(Nothing, XOR registerThis registerSP), -- Clear 'this'
(Nothing, ADDI registerSP $ SizeMacro mtp), -- Deallocate space for main
(Nothing, SUBI registerSP StackOffset), -- Clear stack pointer
(Nothing, XOR registerSP registerHP), -- Clear stack pointer
(Nothing, SUBI registerHP FreeListsSize), -- Reset Heap pointer (For pretty output)
(Nothing, XOR registerHP registerFLPs), -- Reset Heap pointer (For pretty output)
(Nothing, SUBI registerFLPs ProgramSize), -- Reset Free lists pointer (For pretty output)
(Just "finish", FINISH)]
return $ PISA.GProg $ [(Just "top", BRA "start")] ++ out ++ vt ++ malloc ++ malloc1 ++ ms ++ mn
-- | Generates code for a program
generatePISA :: (SProgram, SAState) -> Except String (PISA.MProgram, SAState)
generatePISA (p, s) = second saState <$> runStateT (runCG $ cgProgram p) (initialState s)
showPISAProgram :: (Show a, MonadIO m) => (t, a) -> m ()
showPISAProgram (_, s) = pPrint s
| cservenka/ROOPLPPC | src/CodeGenerator.hs | mit | 48,614 | 0 | 47 | 15,509 | 14,532 | 7,548 | 6,984 | 799 | 20 |
{-# LANGUAGE DeriveDataTypeable #-}
-- | This module provides a simple leftist-heap implementation based on Chris
-- Okasaki's book \"Purely Functional Data Structures\", Cambridge University
-- Press, 1998, chapter 3.1.
--
-- A @'HeapT' prio val@ associates a priority @prio@ to a value @val@. A
-- priority-value pair with minimum priority will always be the head of the
-- 'HeapT', so this module implements minimum priority heaps. Note that the value
-- associated to the priority has no influence on the ordering of elements, only
-- the priority does.
module HeapInternal
( -- * A basic heap type
HeapT(..)
-- * Query
, isEmpty, rank, size
-- * Construction
, empty, singleton, union, unions
-- * Deconstruction
, view
-- * Filter
, partition
-- * Subranges
, splitAt, span
-- * Conversion
, fromList, toList
, fromDescList, toAscList
) where
import Control.Exception
import Data.Foldable ( Foldable(..), foldl' )
import Data.List ( groupBy, sortBy )
import Data.Monoid
import Data.Ord
import Data.Typeable
import Prelude hiding ( foldl, span, splitAt )
import Text.Read
-- | The basic heap type. It stores priority-value pairs @(prio, val)@ and
-- always keeps the pair with minimal priority on top. The value associated to
-- the priority does not have any influence on the ordering of elements.
data HeapT prio val
= Empty -- ^ An empty 'HeapT'.
| Tree { _rank :: {-# UNPACK #-} !Int -- ^ Rank of the leftist heap.
, _size :: {-# UNPACK #-} !Int -- ^ Number of elements in the heap.
, _priority :: !prio -- ^ Priority of the entry.
, _value :: val -- ^ Value of the entry.
, _left :: !(HeapT prio val) -- ^ Left subtree.
, _right :: !(HeapT prio val) -- ^ Right subtree.
} -- ^ A tree node of a non-empty 'HeapT'.
deriving (Typeable)
instance (Read prio, Read val, Ord prio) => Read (HeapT prio val) where
readPrec = parens $ prec 10 $ do
Ident "fromList" <- lexP
fmap fromList readPrec
readListPrec = readListPrecDefault
instance (Show prio, Show val) => Show (HeapT prio val) where
showsPrec d heap = showParen (d > 10)
$ showString "fromList " . (showsPrec 11 (toList heap))
instance (Ord prio, Ord val) => Eq (HeapT prio val) where
heap1 == heap2 = size heap1 == size heap2 && EQ == compare heap1 heap2
instance (Ord prio, Ord val) => Ord (HeapT prio val) where
compare = comparing toPairAscList
instance (Ord prio) => Monoid (HeapT prio val) where
mempty = empty
mappend = union
mconcat = unions
instance Functor (HeapT prio) where
fmap _ Empty = Empty
fmap f heap = heap { _value = f (_value heap)
, _left = fmap f (_left heap)
, _right = fmap f (_right heap)
}
instance (Ord prio) => Foldable (HeapT prio) where
foldMap f = foldMap f . fmap snd . toAscList
foldr f z = foldl (flip f) z . fmap snd . reverse . toAscList
foldl f z = foldl f z . fmap snd . toAscList
-- | /O(1)/. Is the 'HeapT' empty?
isEmpty :: HeapT prio val -> Bool
isEmpty Empty = True
isEmpty _ = False
-- | /O(1)/. Find the rank of a 'HeapT' (the length of its right spine).
rank :: HeapT prio val -> Int
rank Empty = 0
rank heap = _rank heap
-- | /O(1)/. The total number of elements in the 'HeapT'.
size :: HeapT prio val -> Int
size Empty = 0
size heap = _size heap
-- | /O(1)/. Construct an empty 'HeapT'.
empty :: HeapT prio val
empty = Empty
-- | /O(1)/. Create a singleton 'HeapT'.
singleton :: prio -> val -> HeapT prio val
singleton p v = Tree { _rank = 1
, _size = 1
, _priority = p
, _value = v
, _left = empty
, _right = empty
}
{-# INLINE singleton #-}
-- | /O(1)/. Insert an priority-value pair into the 'HeapT', whose /priority is
-- less or equal/ to all other priorities on the 'HeapT', i. e. a pair that is a
-- valid head of the 'HeapT'.
--
-- /The precondition is not checked/.
uncheckedCons :: (Ord prio) => prio -> val -> HeapT prio val -> HeapT prio val
uncheckedCons p v heap = assert (maybe True (\(p', _, _) -> p <= p') (view heap))
Tree { _rank = 1
, _size = 1 + size heap
, _priority = p
, _value = v
, _left = heap
, _right = empty
}
{-# INLINE uncheckedCons #-}
-- | /O(log max(n, m))/. Form the union of two 'HeapT's.
union :: (Ord prio) => HeapT prio val -> HeapT prio val -> HeapT prio val
union heap Empty = heap
union Empty heap = heap
union heap1 heap2 = let
p1 = _priority heap1
p2 = _priority heap2
in if p1 < p2
then makeT p1 (_value heap1) (_left heap1) (union (_right heap1) heap2)
else makeT p2 (_value heap2) (_left heap2) (union (_right heap2) heap1)
-- | Build a 'HeapT' from a priority, a value and two more 'HeapT's. Therefore,
-- the /priority has to be less or equal/ than all priorities in both 'HeapT'
-- parameters.
--
-- /The precondition is not checked/.
makeT :: (Ord prio) => prio -> val -> HeapT prio val -> HeapT prio val -> HeapT prio val
makeT p v a b = let
ra = rank a
rb = rank b
s = size a + size b + 1
in assert (checkPrio a && checkPrio b) $ if ra > rb
then Tree (rb + 1) s p v a b
else Tree (ra + 1) s p v b a
where
checkPrio = maybe True (\(p', _, _) -> p <= p') . view
{-# INLINE makeT #-}
-- | Build the union of all given 'HeapT's.
unions :: (Ord prio) => [HeapT prio val] -> HeapT prio val
unions heaps = case tournamentFold' heaps of
[] -> empty
[h] -> h
hs -> unions hs
where
tournamentFold' :: (Monoid m) => [m] -> [m]
tournamentFold' (x1:x2:xs) = (: tournamentFold' xs) $! mappend x1 x2
tournamentFold' xs = xs
-- | /O(log n)/ for the tail, /O(1)/ for the head. Find the priority-value pair
-- with minimal priority and delete it from the 'HeapT' (i. e. find head and tail
-- of the heap) if it is not empty. Otherwise, 'Nothing' is returned.
view :: (Ord prio) => HeapT prio val -> Maybe (prio, val, HeapT prio val)
view Empty = Nothing
view heap = Just (_priority heap, _value heap, union (_left heap) (_right heap))
{-# INLINE view #-}
-- | Partition the 'HeapT' into two. @'partition' p h = (h1, h2)@: All
-- priority-value pairs in @h1@ fulfil the predicate @p@, those in @h2@ don't.
-- @'union' h1 h2 = h@.
partition :: (Ord prio) => ((prio, val) -> Bool) -> HeapT prio val
-> (HeapT prio val, HeapT prio val)
partition _ Empty = (empty, empty)
partition f heap
| f (p, v) = (makeT p v l1 r1, union l2 r2)
| otherwise = (union l1 r1, makeT p v l2 r2)
where
(p, v) = (_priority heap, _value heap)
(l1, l2) = partition f (_left heap)
(r1, r2) = partition f (_right heap)
{-# INLINE partition #-}
-- | @'splitAt' n h@: A list of the lowest @n@ priority-value pairs of @h@, in
-- ascending order of priority, and @h@, with those elements removed.
splitAt :: (Ord prio) => Int -> HeapT prio val -> ([(prio, val)], HeapT prio val)
splitAt n heap
| n > 0 = case view heap of
Nothing -> ([], empty)
Just (p, v, hs) -> let (xs, heap') = splitAt (n-1) hs in ((p, v):xs, heap')
| otherwise = ([], heap)
{-# INLINE splitAt #-}
-- | @'span' p h@: The longest prefix of priority-value pairs of @h@, in
-- ascending order of priority, that satisfy @p@ and @h@, with those elements
-- removed.
span :: (Ord prio) => ((prio, val) -> Bool) -> HeapT prio val
-> ([(prio, val)], HeapT prio val)
span f heap = case view heap of
Nothing -> ([], empty)
Just (p, v, hs) -> let pv = (p, v)
in if f pv
then let (xs, heap') = span f hs in (pv:xs, heap')
else ([], heap)
{-# INLINE span #-}
-- | /O(n log n)/. Build a 'HeapT' from the given priority-value pairs.
fromList :: (Ord prio) => [(prio, val)] -> HeapT prio val
fromList = fromDescList . sortBy (flip (comparing fst))
{-# INLINE fromList #-}
-- | /O(n log n)/. List all priority-value pairs of the 'HeapT' in no specific
-- order.
toList :: HeapT prio val -> [(prio, val)]
toList Empty = []
toList heap = let
left = _left heap
right = _right heap
in
(_priority heap, _value heap) : if (size right) < (size left)
then toList right ++ toList left
else toList left ++ toList right
{-# INLINE toList #-}
-- | /O(n)/. Create a 'HeapT' from a list providing its priority-value pairs in
-- descending order of priority.
--
-- /The precondition is not checked/.
fromDescList :: (Ord prio) => [(prio, val)] -> HeapT prio val
fromDescList = foldl' (\h (p, v) -> uncheckedCons p v h) empty
{-# INLINE fromDescList #-}
-- | /O(n log n)/. List the priority-value pairs of the 'HeapT' in ascending
-- order of priority.
toAscList :: (Ord prio) => HeapT prio val -> [(prio, val)]
toAscList = fst . span (const True)
{-# INLINE toAscList #-}
-- | List the priority-value pairs of the 'HeapT' just like 'toAscList' does,
-- but don't ignore the value @val@ when sorting.
toPairAscList :: (Ord prio, Ord val) => HeapT prio val -> [(prio, val)]
toPairAscList = concat
. fmap (sortBy (comparing snd))
. groupBy (\x y -> fst x == fst y)
. toAscList
| PepeLui17/Proyecto_Lenguajes_De_Programacion_Segundo_Parcial | HeapInternal.hs | gpl-2.0 | 9,423 | 0 | 15 | 2,548 | 2,650 | 1,430 | 1,220 | 167 | 4 |
--
-- Copyright (c) 2013 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
module Vm.Utility ( withMountedDisk, copyFileFromDisk
, tapCreate
, tapCreateVhd
, tapDestroy
, PartitionNum
, manageFrontVifs) where
import qualified Control.Exception as E
import Control.Applicative
import Control.Monad
import Data.Int
import Data.List
import Data.Maybe
import System.IO
import System.IO.Error
import System.FilePath
import Text.Printf
import Directory
import Tools.Misc
import Tools.Process
import Tools.Text
import Tools.Log
import Vm.DmTypes
import Vm.Dm
import Vm.DomainCore
import Vm.Queries
import Vm.Types
import Vm.Uuid
import XenMgr.Connect.Xl as Xl
import XenMgr.Rpc
type PartitionNum = Int
finally' = flip E.finally
mount :: FilePath -> FilePath -> Bool -> IO ()
mount dev dir ro = void $ readProcessOrDie "mount" ["-o", opts, dev, dir] "" where
opts = intercalate "," . filter (not.null) $ [ro_opt]
ro_opt | ro = "ro"
| otherwise = ""
umount :: FilePath -> IO ()
umount dir = void $ readProcessOrDie "umount" [dir] ""
--Updated syntax for new tap-ctl style
tapCreate ty extraEnv ro path = chomp <$> readProcessOrDieWithEnv extraEnv "tap-ctl" ( ["create"] ++ ["-a", ty++":"++path] ) ""
tapCreateVhd = tapCreate "vhd"
tapCreateVdi = tapCreate "vdi"
tapCreateAio = tapCreate "aio"
tapDestroy :: String -> IO ()
tapDestroy path = void $ readProcessOrDie "tap-ctl" ["destroy", "-d", path] ""
withTempDirectory :: FilePath -> (FilePath -> IO a) -> IO a
withTempDirectory root_path action =
do directory <- attempt 1
action directory `E.finally` removeDirectory directory
where
attempt n =
let name = templated_name n in
( do createDirectory name
return name ) `E.catch` create_error n
create_error :: Int -> IOError -> IO FilePath
create_error n e | isAlreadyExistsError e = attempt (n+1)
| otherwise = E.throw e
templated_name magic_num = root_path </> printf "tempdir-%08d" magic_num
withMountedDisk :: [(String,String)] -> DiskType -> Bool -> FilePath -> Maybe PartitionNum -> (FilePath -> IO a) -> IO a
withMountedDisk _ QemuCopyOnWrite _ _ _ _ = error "qcow unsupported"
withMountedDisk extraEnv diskT ro phys_path part action
= withTempDirectory "/tmp" $ \temp_dir ->
do dev <- create_dev diskT
finally' (destroy_dev diskT dev) $
do lo <- locreate dev
finally' (loremove lo) $
do loop <- lopart lo part
settle part
mount loop temp_dir ro
finally' (umount temp_dir) $ action temp_dir
where
create_dev DiskImage = return phys_path
create_dev PhysicalDevice = return phys_path
create_dev VirtualHardDisk = tapCreateVhd extraEnv ro phys_path
create_dev ExternalVdi = tapCreateVdi extraEnv ro phys_path
create_dev Aio = tapCreateAio extraEnv ro phys_path
create_dev _ = error "unsupported"
destroy_dev t dev | t `elem` [VirtualHardDisk, ExternalVdi, Aio] = tapDestroy dev
destroy_dev _ _ = return ()
loremove dev = readProcessOrDie "losetup" ["--detach", dev] ""
locreate dev = chomp <$> readProcessOrDie "losetup" (args ++ [dev]) ""
args = ["--find", "--show" ] ++ partscan part
partscan Nothing = []
partscan (Just pnum) = ["--partscan"]
-- losetup returns without waiting for the the partition device nodes.
-- The kernel creates them fast enough, but they aren't necessarily
-- labeled by by udev, and mount can fail from the incorrect label.
settle :: Maybe PartitionNum -> IO ()
settle Nothing = return ()
settle (Just pmnum) = do
void $ readProcessOrDie "udevadm" ["settle"] ""
lopart :: FilePath -> Maybe PartitionNum -> IO FilePath
lopart lo Nothing = return lo
lopart lo (Just pnum) = do
ex <- doesFileExist path
case ex of
True -> return path
_ -> error $ "partition " ++ show pnum ++ " not found in " ++ show lo
where
path = lo ++ "p" ++ show pnum
deslash ('/':xs) = xs
deslash xs = xs
copyFileFromDisk :: [(String, String)] -> DiskType -> Bool -> FilePath -> (Maybe PartitionNum,FilePath) -> FilePath -> IO ()
copyFileFromDisk extraEnv diskT ro phys_path (part,src_path) dst_path
= withMountedDisk extraEnv diskT ro phys_path part $ \contents ->
void $
readProcessOrDie "cp" [contents </> deslash src_path, dst_path] "" >>
readProcessOrDie "sync" [] "" >> verifyChecksum (contents </> deslash src_path) dst_path
where
verifyChecksum src dst = do
src_sha_raw <- readProcessOrDie "sha256sum" [src] ""
dst_sha_raw <- readProcessOrDie "sha256sum" [dst] ""
let src_sha = head $ split ' ' $ src_sha_raw
let dst_sha = head $ split ' ' $ dst_sha_raw
info $ "copyFile src_sha: " ++ src_sha
info $ "copyFile dst_sha: " ++ dst_sha
if src_sha /= dst_sha
then error "copy file shasums dont match!"
else return ()
manageFrontVifs :: Bool -> Uuid -> Rpc ()
manageFrontVifs connect_action back_uuid =
do
vms <- filter ((/=) back_uuid) <$> (filterM Xl.isRunning =<< getVms)
devs <- mapM getdevs vms
devices <- filterM (uses back_uuid) (concat devs)
mapM_ (manage connect_action) devices
where
getdevs :: Uuid -> Rpc [(Uuid, DmFront)]
getdevs uuid = whenDomainID [] uuid $ \domid -> do
-- TODO: only supporting vif,vwif devices atm
vifs <- liftIO $ getFrontDevices VIF domid
vwifs <- liftIO $ getFrontDevices VWIF domid
return $ zip (repeat uuid) (vifs ++ vwifs)
uses bkuuid (_,d) = do
domid <- liftIO $ Xl.getDomainId bkuuid
if domid /= "" then return $ (read domid :: DomainID) == dmfBackDomid d else return False
manage connect_action (front_uuid, dev) = do
let nid@(XbDeviceID nic_id) = dmfID dev
liftIO $ Xl.connectVif front_uuid nid connect_action
| OpenXT/manager | xenmgr/Vm/Utility.hs | gpl-2.0 | 6,721 | 0 | 18 | 1,633 | 1,892 | 954 | 938 | 129 | 8 |
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
{- |
Module : ./Modal/Logic_Modal.hs
Description : Instance of class Logic for Modal CASL
Copyright : (c) Till Mossakowski, Uni Bremen 2002-2004
License : GPLv2 or higher, see LICENSE.txt
Maintainer : luecke@informatik.uni-bremen.de
Stability : provisional
Portability : portable
Instance of class Logic for modal logic.
-}
module Modal.Logic_Modal where
import Logic.Logic
import Modal.AS_Modal
import Modal.ModalSign
import Modal.ATC_Modal ()
import Modal.Parse_AS
import Modal.Print_AS
import Modal.StatAna
import CASL.Sign
import CASL.Morphism
import CASL.SymbolMapAnalysis
import CASL.AS_Basic_CASL
import CASL.Parse_AS_Basic
import CASL.MapSentence
import CASL.SimplifySen
import CASL.SymbolParser
import CASL.Taxonomy
import CASL.ToDoc
import CASL.Logic_CASL ()
data Modal = Modal deriving Show
instance Language Modal where
description _ = unlines
[ "ModalCASL extends CASL by modal operators. Syntax for ordinary"
, "modalities, multi-modal logics as well as term-modal"
, "logic (also covering dynamic logic) is provided."
, "Specific modal logics can be obtained via restrictions to"
, "sublanguages." ]
type MSign = Sign M_FORMULA ModalSign
type ModalMor = Morphism M_FORMULA ModalSign (DefMorExt ModalSign)
type ModalFORMULA = FORMULA M_FORMULA
instance SignExtension ModalSign where
isSubSignExtension = isSubModalSign
instance Syntax Modal M_BASIC_SPEC Symbol SYMB_ITEMS SYMB_MAP_ITEMS where
parse_basic_spec Modal = Just $ basicSpec modal_reserved_words
parse_symb_items Modal = Just $ symbItems modal_reserved_words
parse_symb_map_items Modal = Just $ symbMapItems modal_reserved_words
-- Modal logic
map_M_FORMULA :: MapSen M_FORMULA ModalSign (DefMorExt ModalSign)
map_M_FORMULA mor (BoxOrDiamond b m f ps) =
let newM = case m of
Simple_mod _ -> m
Term_mod t -> let newT = mapTerm map_M_FORMULA mor t
in Term_mod newT
newF = mapSen map_M_FORMULA mor f
in BoxOrDiamond b newM newF ps
instance Sentences Modal ModalFORMULA MSign ModalMor Symbol where
map_sen Modal m = return . mapSen map_M_FORMULA m
sym_of Modal = symOf
symmap_of Modal = morphismToSymbMap
sym_name Modal = symName
simplify_sen Modal = simplifySen minExpForm simModal
print_sign Modal sig = printSign
(printModalSign $ simplifySen minExpForm simModal sig) sig
print_named Modal = printTheoryFormula
-- simplifySen for ExtFORMULA
simModal :: Sign M_FORMULA ModalSign -> M_FORMULA -> M_FORMULA
simModal sign (BoxOrDiamond b md form pos) =
let mod' = case md of
Term_mod term -> Term_mod $ rmTypesT minExpForm
simModal sign term
t -> t
in BoxOrDiamond b mod'
(simplifySen minExpForm simModal sign form) pos
rmTypesExt :: a -> b -> b
rmTypesExt _ f = f
instance StaticAnalysis Modal M_BASIC_SPEC ModalFORMULA
SYMB_ITEMS SYMB_MAP_ITEMS
MSign
ModalMor
Symbol RawSymbol where
basic_analysis Modal = Just basicModalAnalysis
stat_symb_map_items Modal = statSymbMapItems
stat_symb_items Modal = statSymbItems
symbol_to_raw Modal = symbolToRaw
id_to_raw Modal = idToRaw
matches Modal = CASL.Morphism.matches
empty_signature Modal = emptySign emptyModalSign
signature_union Modal s = return . addSig addModalSign s
intersection Modal s = return . interSig interModalSign s
morphism_union Modal = plainMorphismUnion addModalSign
final_union Modal = finalUnion addModalSign
is_subsig Modal = isSubSig isSubModalSign
subsig_inclusion Modal = sigInclusion emptyMorExt
cogenerated_sign Modal = cogeneratedSign emptyMorExt
generated_sign Modal = generatedSign emptyMorExt
induced_from_morphism Modal = inducedFromMorphism emptyMorExt
induced_from_to_morphism Modal =
inducedFromToMorphism emptyMorExt isSubModalSign diffModalSign
theory_to_taxonomy Modal = convTaxo
instance Logic Modal ()
M_BASIC_SPEC ModalFORMULA SYMB_ITEMS SYMB_MAP_ITEMS
MSign
ModalMor
Symbol RawSymbol () where
stability _ = Unstable
empty_proof_tree _ = ()
| gnn/Hets | Modal/Logic_Modal.hs | gpl-2.0 | 4,510 | 0 | 16 | 1,128 | 891 | 450 | 441 | 95 | 2 |
-- Copyright (C) 2006-2011 Angelos Charalambidis <a.charalambidis@di.uoa.gr>
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2, or (at your option)
-- any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; see the file COPYING. If not, write to
-- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-- Boston, MA 02110-1301, USA.
{-# LANGUAGE
FlexibleContexts
,FlexibleInstances
,FunctionalDependencies
,MultiParamTypeClasses
,TypeSynonymInstances
#-}
module Subst where
-- import Language.Hopl (Expr(..), Clause(..))
-- import Data.Monoid (mconcat)
import CoreLang
import Data.List (union)
type Subst a = [ (a, Expr a) ]
success :: Subst a
success = []
bind :: a -> Expr a -> Subst a
bind v e = [(v, e)]
isTaut :: Eq a => (a, Expr a) -> Bool
isTaut (v, Var v') = v == v'
isTaut _ = False
class (Substitutable a b) | a -> b where
subst :: Substitutable a b => (Subst b) -> a -> a
instance Eq a => (Substitutable (Expr a) a) where
subst theta (App e1 e2) = App (subst theta e1) (subst theta e2)
subst theta (And e1 e2) = And (subst theta e1) (subst theta e2)
subst theta (Or e1 e2) = Or (subst theta e1) (subst theta e2)
subst theta (Eq e1 e2) = Eq (subst theta e1) (subst theta e2)
subst theta (Lambda x e) = maybe (Lambda x (subst theta e)) aux $ lookup x theta
where aux (Var y) = Lambda y (subst theta e)
aux _ = error "Cannot substitute lambda bounds vars with expr"
subst theta (Exists x e) = maybe (Exists x (subst theta e)) aux $ lookup x theta
where aux (Var y) = Exists y (subst theta e)
aux _ = error "Cannot substitute exist bounds vars with expr"
-- subst theta (Forall x e) = maybe (Forall x (subst theta e)) aux $ lookup x theta
-- where aux (Var y) = Forall y (subst theta e)
-- aux _ = error "Cannot substitute lambda bounds vars with expr"
subst theta e@(Var x) = maybe e id $ lookup x theta
subst theta (Not e) = Not (subst theta e)
subst theta (ListCons e1 e2) = ListCons (subst theta e1) (subst theta e2)
subst theta e = e
instance Eq a => (Substitutable (Subst a) a) where
subst theta zeta = [ (v, e') | (v, e) <- theta, let e' = subst zeta e, not (isTaut (v, e')) ]
restrict :: Eq a => [a] -> Subst a -> Subst a
restrict ss xs = [ (v, e) | (v, e) <- xs, v `elem` ss ]
combine theta zeta =
let ss = map fst theta
zeta' = [ (v, e) | (v, e) <- zeta, v `notElem` ss ]
in subst theta zeta ++ zeta'
dom theta = map fst theta
range theta = concatMap fv (map snd theta)
vars theta = dom theta `union` range theta
isRenamingSubst s = all (\(_, x) -> isVar x) s
| acharal/hopes | src/prover/Subst.hs | gpl-2.0 | 3,226 | 18 | 12 | 849 | 963 | 507 | 456 | 46 | 1 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-}
module TestVals
( env
, list
, factorialVal, euler1Val, solveDepressedQuarticVal
, factorsVal
, lambda, lambdaRecord, letItem, recordType
, eLet
, listTypePair, boolTypePair, polyIdTypePair, unsafeCoerceTypePair
, ignoredParamTypePair
, xGetterPair, xGetterPairConstrained
) where
import Prelude.Compat
import Control.Lens.Operators
import qualified Data.ByteString.Char8 as BS8
import qualified Data.Map as Map
import Data.Monoid ((<>))
import qualified Data.Set as Set
import Lamdu.Expr.Constraints (Constraints(..), CompositeVarConstraints(..))
import Lamdu.Expr.Nominal (Nominal(..))
import Lamdu.Expr.Pure (($$), ($$:))
import qualified Lamdu.Expr.Pure as P
import Lamdu.Expr.Scheme (Scheme(..))
import qualified Lamdu.Expr.Scheme as Scheme
import Lamdu.Expr.Type (Type, (~>))
import qualified Lamdu.Expr.Type as T
import qualified Lamdu.Expr.TypeVars as TV
import Lamdu.Expr.Val (Val)
import qualified Lamdu.Expr.Val as V
import Lamdu.Infer (TypeVars(..), Loaded(..))
{-# ANN module ("HLint: ignore Redundant $" :: String) #-}
-- TODO: $$ to be type-classed for TApp vs BApp
-- TODO: TCon "->" instead of TFun
eLet :: V.Var -> Val () -> (Val () -> Val ()) -> Val ()
eLet name val mkBody = P.app (P.abs name body) val
where
body = mkBody $ P.var name
lambda :: V.Var -> (Val () -> Val ()) -> Val ()
lambda varName mkBody = P.abs varName $ mkBody $ P.var varName
lambdaRecord :: [T.Tag] -> ([Val ()] -> Val ()) -> Val ()
lambdaRecord names mkBody =
lambda "paramsRecord" $ \paramsRec ->
mkBody $ map (P.getField paramsRec) names
letItem :: V.Var -> Val () -> (Val () -> Val ()) -> Val ()
letItem name val mkBody = lambda name mkBody $$ val
openRecordType :: T.ProductVar -> [(T.Tag, Type)] -> Type
openRecordType tv = T.TRecord . foldr (uncurry T.CExtend) (T.CVar tv)
recordType :: [(T.Tag, Type)] -> Type
recordType = T.TRecord . foldr (uncurry T.CExtend) T.CEmpty
forAll :: [T.TypeVar] -> ([Type] -> Type) -> Scheme
forAll tvs mkType =
Scheme mempty { typeVars = Set.fromList tvs } mempty $ mkType $ map T.TVar tvs
listTypePair :: (T.NominalId, Nominal)
listTypePair =
( "List"
, Nominal
{ nParams = Map.singleton "elem" tvName
, nScheme =
T.CEmpty
& T.CExtend "[]" (recordType [])
& T.CExtend ":" (recordType [("head", tv), ("tail", listOf tv)])
& T.TSum
& Scheme.mono
}
)
where
tvName = "a"
tv = T.TVar tvName
listOf :: Type -> Type
listOf = T.TInst (fst listTypePair) . Map.singleton "elem"
boolType :: Type
boolType = T.TInst (fst boolTypePair) Map.empty
intType :: Type
intType = T.TPrim "Int"
boolTypePair :: (T.NominalId, Nominal)
boolTypePair =
( "Bool"
, Nominal
{ nParams = Map.empty
, nScheme =
T.CEmpty
& T.CExtend "True" (recordType [])
& T.CExtend "False" (recordType [])
& T.TSum
& Scheme.mono
}
)
tvA :: T.TypeVar
tvA = "a"
tvB :: T.TypeVar
tvB = "b"
ta :: Type
ta = TV.lift tvA
tb :: Type
tb = TV.lift tvB
polyIdTypePair :: (T.NominalId, Nominal)
polyIdTypePair =
( "PolyIdentity"
, Nominal
{ nParams = Map.empty
, nScheme =
Scheme (TV.singleton tvA) mempty $
ta ~> ta
}
)
unsafeCoerceTypePair :: (T.NominalId, Nominal)
unsafeCoerceTypePair =
( "UnsafeCoerce"
, Nominal
{ nParams = Map.empty
, nScheme =
Scheme (TV.singleton tvA <> TV.singleton tvB) mempty $
ta ~> tb
}
)
ignoredParamTypePair :: (T.NominalId, Nominal)
ignoredParamTypePair =
( "IgnoredParam"
, Nominal
{ nParams = Map.singleton "res" tvB
, nScheme =
Scheme (TV.singleton tvA) mempty $
ta ~> tb
}
)
xGetter :: (T.ProductVar -> Constraints) -> Nominal
xGetter constraints =
Nominal
{ nParams = Map.empty
, nScheme =
Scheme (TV.singleton tvA <> TV.singleton tvRest) (constraints tvRest) $
openRecordType tvRest [("x", ta)] ~> ta
}
where
tvRest :: T.ProductVar
tvRest = "rest"
xGetterPair :: (T.NominalId, Nominal)
xGetterPair =
( "XGetter"
, xGetter mempty
)
xGetterPairConstrained :: (T.NominalId, Nominal)
xGetterPairConstrained =
( "XGetterConstrained"
, xGetter $
\tvRest ->
mempty
{ productVarConstraints =
CompositeVarConstraints $ Map.singleton tvRest $
Set.fromList ["x", "y"]
}
)
maybeOf :: Type -> Type
maybeOf t =
T.TSum $
T.CExtend "Nothing" (recordType []) $
T.CExtend "Just" t T.CEmpty
infixType :: Type -> Type -> Type -> Type
infixType a b c = recordType [("l", a), ("r", b)] ~> c
infixArgs :: Val () -> Val () -> Val ()
infixArgs l r = P.record [("l", l), ("r", r)]
env :: Loaded
env =
Loaded
{ loadedGlobalTypes =
Map.fromList
[ ("fix", forAll ["a"] $ \ [a] -> (a ~> a) ~> a)
, ("if", forAll ["a"] $ \ [a] -> recordType [("condition", boolType), ("then", a), ("else", a)] ~> a)
, ("==", forAll ["a"] $ \ [a] -> infixType a a boolType)
, (">", forAll ["a"] $ \ [a] -> infixType a a boolType)
, ("%", forAll ["a"] $ \ [a] -> infixType a a a)
, ("*", forAll ["a"] $ \ [a] -> infixType a a a)
, ("-", forAll ["a"] $ \ [a] -> infixType a a a)
, ("+", forAll ["a"] $ \ [a] -> infixType a a a)
, ("/", forAll ["a"] $ \ [a] -> infixType a a a)
, ("//", forAll [] $ \ [] -> infixType intType intType intType)
, ("sum", forAll ["a"] $ \ [a] -> listOf a ~> a)
, ("filter", forAll ["a"] $ \ [a] -> recordType [("from", listOf a), ("predicate", a ~> boolType)] ~> listOf a)
, (":", forAll ["a"] $ \ [a] -> recordType [("head", a), ("tail", listOf a)] ~> listOf a)
, ("[]", forAll ["a"] $ \ [a] -> listOf a)
, ("concat", forAll ["a"] $ \ [a] -> listOf (listOf a) ~> listOf a)
, ("map", forAll ["a", "b"] $ \ [a, b] -> recordType [("list", listOf a), ("mapping", a ~> b)] ~> listOf b)
, ("..", forAll [] $ \ [] -> infixType intType intType (listOf intType))
, ("||", forAll [] $ \ [] -> infixType boolType boolType boolType)
, ("head", forAll ["a"] $ \ [a] -> listOf a ~> a)
, ("negate", forAll ["a"] $ \ [a] -> a ~> a)
, ("sqrt", forAll ["a"] $ \ [a] -> a ~> a)
, ("id", forAll ["a"] $ \ [a] -> a ~> a)
, ("zipWith",forAll ["a","b","c"] $ \ [a,b,c] ->
(a ~> b ~> c) ~> listOf a ~> listOf b ~> listOf c )
, ("Just", forAll ["a"] $ \ [a] -> a ~> maybeOf a)
, ("Nothing",forAll ["a"] $ \ [a] -> maybeOf a)
, ("maybe", forAll ["a", "b"] $ \ [a, b] -> b ~> (a ~> b) ~> maybeOf a ~> b)
, ("plus1", forAll [] $ \ [] -> intType ~> intType)
, ("True", forAll [] $ \ [] -> boolType)
, ("False", forAll [] $ \ [] -> boolType)
]
, loadedNominals =
Map.fromList
[ listTypePair
, boolTypePair
, polyIdTypePair
, unsafeCoerceTypePair
, ignoredParamTypePair
, xGetterPair
, xGetterPairConstrained
]
}
list :: [Val ()] -> Val ()
list = foldr cons (P.toNom "List" $ P.inject "[]" P.recEmpty)
cons :: Val () -> Val () -> Val ()
cons h t = P.toNom "List" $ P.inject ":" $ P.record [("head", h), ("tail", t)]
litInt :: Integer -> Val ()
litInt = P.lit "Int" . BS8.pack . show
factorialVal :: Val ()
factorialVal =
P.global "fix" $$
lambda "loop"
( \loop ->
lambda "x" $ \x ->
P.global "if" $$:
[ ( "condition", P.global "==" $$
infixArgs x (litInt 0) )
, ( "then", litInt 1 )
, ( "else", P.global "*" $$
infixArgs x (loop $$ (P.global "-" $$ infixArgs x (litInt 1)))
)
]
)
euler1Val :: Val ()
euler1Val =
P.global "sum" $$
( P.global "filter" $$:
[ ("from", P.global ".." $$ infixArgs (litInt 1) (litInt 1000))
, ( "predicate",
lambda "x" $ \x ->
P.global "||" $$ infixArgs
( P.global "==" $$ infixArgs
(litInt 0) (P.global "%" $$ infixArgs x (litInt 3)) )
( P.global "==" $$ infixArgs
(litInt 0) (P.global "%" $$ infixArgs x (litInt 5)) )
)
]
)
solveDepressedQuarticVal :: Val ()
solveDepressedQuarticVal =
lambdaRecord ["e", "d", "c"] $ \[e, d, c] ->
letItem "solvePoly" (P.global "id")
$ \solvePoly ->
letItem "sqrts"
( lambda "x" $ \x ->
letItem "r"
( P.global "sqrt" $$ x
) $ \r ->
list [r, P.global "negate" $$ r]
)
$ \sqrts ->
P.global "if" $$:
[ ("condition", P.global "==" $$ infixArgs d (litInt 0))
, ( "then",
P.global "concat" $$
( P.global "map" $$:
[ ("list", solvePoly $$ list [e, c, litInt 1])
, ("mapping", sqrts)
]
)
)
, ( "else",
P.global "concat" $$
( P.global "map" $$:
[ ( "list", sqrts $$ (P.global "head" $$ (solvePoly $$ list
[ P.global "negate" $$ (d %* d)
, (c %* c) %- (litInt 4 %* e)
, litInt 2 %* c
, litInt 1
]))
)
, ( "mapping",
lambda "x" $ \x ->
solvePoly $$ list
[ (c %+ (x %* x)) %- (d %/ x)
, litInt 2 %* x
, litInt 2
]
)
]
)
)
]
where
(%+) = inf "+"
(%-) = inf "-"
(%*) = inf "*"
(%/) = inf "/"
inf :: V.GlobalId -> Val () -> Val () -> Val ()
inf str x y = P.global str $$ infixArgs x y
factorsVal :: Val ()
factorsVal =
fix_ $ \loop ->
lambdaRecord ["n", "min"] $ \ [n, m] ->
if_ ((m %* m) %> n) (list [n]) $
if_ ((n %% m) %== litInt 0)
(cons m $ loop $$: [("n", n %// m), ("min", m)]) $
loop $$: [ ("n", n), ("min", m %+ litInt 1) ]
where
fix_ f = P.global "fix" $$ lambda "loop" f
if_ b t f =
( nullaryCase "False" f $
nullaryCase "True" t $
P.absurd
) $$ P.fromNom "Bool" b
nullaryCase tag handler = P._case tag (defer handler)
defer = P.lambda "_" . const
(%>) = inf ">"
(%%) = inf "%"
(%*) = inf "*"
(%+) = inf "+"
(%//) = inf "//"
(%==) = inf "=="
| da-x/Algorithm-W-Step-By-Step | src/TestVals.hs | gpl-3.0 | 11,046 | 0 | 29 | 3,823 | 4,256 | 2,333 | 1,923 | 276 | 1 |
{- http://cryptopals.com/sets/1/challenges/1/ -}
module Base64 where
import Hex
import Data.Bits (shift, (.&.))
import Data.List (elemIndex)
import Data.Maybe (fromJust)
import CryptoChallenge
base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
toBase64Char n = base64Chars !! n
fromBase64Char c = fromJust $ elemIndex c base64Chars
tailPad :: String -> String
tailPad s= concat $ replicate ((length s `mod` 6) `div` 2) "="
encodeTriplet :: (Int, Int, Int) -> [Int]
encodeTriplet (a,b,c) = x:y:z:w:[]
where x = shift (a .&. 0xfc) (-2)
y = (shift (a .&. 3) (4)) + (shift (b .&. 0xf0) (-4))
z = (shift (b .&. 0x0f) (2)) + (shift (c .&. 0xc0) (-6))
w = c .&. 0x3f
decodeQuad (c1:c2:c3:c4:cs) =
(shift v1 2) + (shift (v2 .&. 0x30) (-4)) :
(shift (v2 .&. 0x0f) 4) + (shift (v3 .&. 0x3c) (-2)) :
(shift (v3 .&. 0x03) 6) + v4 :
[]
where v1 = fromBase64Char c1
v2 = fromBase64Char c2
v3 = fromBase64Char c3
v4 = fromBase64Char c4
--TODO:: Fix the encode bug here: toTriplets (a:[]) = [(a,0,0)] = ?
toTriplets :: [Int] -> [(Int, Int, Int)]
toTriplets [] = []
toTriplets (a:[]) = [(a,0,0)]
toTriplets (a:b:[]) = [(a,b,0)]
toTriplets (a:b:c:xs) = (a,b,c) : (toTriplets xs)
--base64Encode :: String -> String
base64Encode s = (map toBase64Char
$ concat
[encodeTriplet t
| t <- toTriplets (fromString s)])
++ tailPad s
--base64 = base64Encode
----------------------------------
----- Decoder --------------------
----------------------------------
checkLength s
| length s `mod` 4 == 0 = s
| otherwise = error "Invalid Base64 string"
removeCRs = filter (\c -> c `elem` base64Chars)
base64Decode s = decodeString $ checkLength $ removeCRs s
{-
......|..V....|....V..|......|V
-}
decodeString "" = []
decodeString s = decodeQuad (take 4 s) ++ decodeString (drop 4 s)
| CharlesRandles/cryptoChallenge | base64.hs | gpl-3.0 | 2,065 | 0 | 14 | 561 | 797 | 433 | 364 | 43 | 1 |
--------------------------------------------------------------------------------
-- Copyright (C) 1997, 1998, 2008 Joern Dinkla, www.dinkla.net
--------------------------------------------------------------------------------
module Tests.Polys where
import Point2 (Point2 (..))
import Polygon (Polygon (..), Polygon2, vertices)
p42 = PolygonCCW (map Point2 [(0.0,0.0), (10.0,7.0), (12.0,3.0), (20.0,8.0), (13.0,17.0),
(10.0,12.0), (12.0,14.0), (13.0,11.0), (7.0,11.0), (6.0,14.0), (10.0,15.0), (6.0,18.0),
(-1.0,15.0), (1.0,13.0), (4.0,14.0), (5.0,10.0), (-2.0,9.0), (5.0,5.0)])
p44 = PolygonCCW (map Point2 [(0.0,10.0), (10.0,0.0), (20.0,10.0), (30.0,0.0), (40.0,10.0),
(50.0,0.0), (50.0,10.0), (40.0,20.0), (30.0,10.0), (20.0,20.0), (10.0,10.0), (0.0,20.0)])
p53 = PolygonCCW (map Point2 [(9.0,0.0), (5.0,0.75), (4.5,1.25), (5.75,2.0), (6.0,3.0),
(5.7,3.25), (4.5,3.5), (4.7,4.0), (8.5,4.3), (5.5,4.5), (10.0,5.5), (8.0,5.75), (6.0,6.5),
(4.5,7.0), (4.5,8.0), (5.0,9.0), (1.5,6.25), (4.0,6.0), (4.5,5.5), (4.0,4.5), (3.0,4.0),
(3.5,2.5), (5.5,2.3), (2.5,0.5), (1.0,0.3)])
p59 = PolygonCCW (map Point2 [(10.0,0.0), (13.0,7.0), (14.0,11.0), (17.0,12.0), (13.0,14.0),
(9.0,13.0), (9.0,18.0), (6.0,15.0), (3.0,18.0), (1.0,14.0), (4.0,15.0), (8.0,10.0), (4.0,12.0),
(4.0,7.0), (7.0,9.0)])
p50 = PolygonCCW (map Point2 [(10.0,6.0), (8.0,6.5), (7.5,11.0), (6.0,10.0), (4.0,11.0),
(2.0,10.0), (3.0,8.0), (2.5,5.0), (1.0,7.0), (0.0,3.0), (2.0,0.0), (4.0,2.0), (6.5,0.0),
(6.0,4.0), (9.5,3.0)])
p00 :: (Num a, Eq a) => Polygon2 a
p00 = PolygonCCW (map Point2 [(1,6), (2,2), (8,1), (7,2), (2,3), (3,5), (3,6), (6,5),
(4,5), (6,3), (8,2), (6,7), (4,7), (7,8), (8,5), (10,2), (8,9), (5,10)])
p01 :: (Num a, Eq a) => Polygon2 a
p01 = PolygonCCW (map Point2 [
(6,5), (6,3), (5,6), (5,5), (5,4),
(3,5), (3,4), (3,3), (1,4), (1,1),
(2,1), (2,2), (3,2), (3,1), (4,1),
(4,2), (4,3), (5,3), (5,2), (5,1),
(6,1), (6,2), (7,2), (7,3), (8,3),
(9,1), (10,4), (11,3), (10,2), (11,1),
(12,2), (12,10), (9,10), (7,10), (6,9),
(7,8), (9,9), (11,7), (11,5), (9,6),
(9,8), (7,6), (7,7), (6,7), (4,9),
(4,8), (4,7), (3,8), (3,7), (2,8),
(2,7), (1,8), (1,7), (1,6), (2,5),
(3,6), (5,7), (7,5), (9,4), (7,4) ])
p02 :: (Num a, Eq a) => Polygon2 a
p02 = PolygonCCW (map Point2 [
(1,1), (2,1), (3,1), (3,2), (3,3), (2,3), (1,3), (1,2)])
| smoothdeveloper/GeoAlgLib | src/Tests/Polys.hs | gpl-3.0 | 2,472 | 0 | 10 | 434 | 1,779 | 1,155 | 624 | 38 | 1 |
{-|
Module : Control.Monad.EitherCont
Description : The 'EitherCont' type and API
Copyright : (c) Eitan Chatav, 2015
License : PublicDomain
Maintainer : eitan.chatav@gmail.com
Stability : experimental
The 'EitherCont' type and API provide an idiomatic way to handle errors in
continuation passing style.
-}
module Control.Monad.EitherCont
( EitherCont
, EitherContT()
, eitherCont
, runEitherCont
, liftEither
, fmapL
, bimapEC
, throwEC
, apL
, catchEC
, liftL
, flipEC
, mapEitherCont
, withEitherContL
, withEitherContR
, callCCL
) where
import Control.Monad.Trans.EitherCont
import Data.Functor.Identity
-- |'EitherCont' 'a' 'l' 'r' is a CPS computation that produces an intermediate
-- result of type 'a' within a CPS computation which produces either a success
-- of type 'r' or failure of type 'l'.
type EitherCont a l r = EitherContT a l Identity r
-- |Construct a continuation-passing computation from a function.
eitherCont :: ((l -> a) -> (r -> a) -> a) -> EitherCont a l r
eitherCont ec = EitherContT $ \kl kr -> Identity $
ec (runIdentity . kl) (runIdentity . kr)
-- |The result of running a CPS computation with given failure and success
-- continuations.
--
-- prop> runEitherCont . eitherCont = id
-- prop> eitherCont . runEitherCont = id
runEitherCont :: EitherCont a l r -> (l -> a) -> (r -> a) -> a
runEitherCont ec kl kr = runIdentity $
runEitherContT ec (Identity . kl) (Identity . kr)
-- |'liftEither' embeds 'Either' in 'EitherCont' 'a'.
liftEither :: Either l r -> EitherCont a l r
liftEither e = eitherCont $ \kl kr -> either kl kr e
-- |Apply a function to transform the result of a continuation-passing
-- computation.
mapEitherCont :: (a -> a) -> EitherCont a l r -> EitherCont a l r
mapEitherCont = mapEitherContT . fmap
-- |Apply a function to transform the success continuation passed to a
-- continuation-passing computation.
withEitherContR :: ((r' -> a) -> r -> a)
-> EitherCont a l r
-> EitherCont a l r'
withEitherContR f = withEitherContTR ((Identity .) . f . (runIdentity .))
-- |Apply a function to transform the failure continuation passed to an
-- continuation-passing computation.
withEitherContL :: ((l' -> a) -> l -> a)
-> EitherCont a l r
-> EitherCont a l' r
withEitherContL f = withEitherContTL ((Identity .) . f . (runIdentity .))
| echatav/error-continuations | src/Control/Monad/EitherCont.hs | unlicense | 2,443 | 0 | 10 | 548 | 506 | 285 | 221 | 40 | 1 |
module Main where
import System.Environment
import Options.Applicative
import ServerAPI (OpLimit(..),Problem(..), TrainingResponse(..))
import StringClient as SC (getMyproblems, getStatus, getTrainingProblem, evalProgram, evalProgramById, guessProgram)
import FileClient as FC (getUnsolved, getUnsolvedHS, filterByIds, getMyproblemsHS)
import HsClient as HC (getTrainingProblem, getUnsolved)
import ProgramCounting as PC (expectedComplexity)
import Gen
import Data.List (isInfixOf, intercalate, find, sortBy)
import Data.Ord (comparing)
import Text.Printf
import System.IO
import Solve (solve, isFeasible, solveExact, solveWithTimeout, bonusSolve)
import PP (ppProg)
import Data.Word
import Filter
import Data.Maybe
import Data.Time.Clock
data Cmd = MyProblems
| Status
| Train (Maybe Int) (Maybe OpLimit)
| Eval String [String]
| Guess String String
| Generate Int [String]
| Unsolved String
| FindSolvable String Int
| TrainSolve Int
| TrainBonusSolve Int Int
| Solve Int String String
| Filter String String
| SolveMany Int Int Int Bool Bool
| LowLevelSolve String Int [String]
| SolveExact Int [String] ([Word64], [Word64])
| FilterCached Int [String] Word64
| EstimateComplexity Int [String]
| ReportComplexity String Bool
main = do
hSetBuffering stdout NoBuffering
execParser options >>= run
run MyProblems = putStrLn =<< SC.getMyproblems
run Status = putStrLn =<< getStatus
run (Train length oplimit) = putStrLn =<< SC.getTrainingProblem length oplimit
run (Eval programOrId args) =
if " " `isInfixOf` programOrId
then putStrLn =<< evalProgram programOrId (map read args)
else putStrLn =<< evalProgramById programOrId (map read args)
run (Guess id program) = putStrLn =<< guessProgram id program
run (Generate size ops) = mapM_ (putStrLn . ppProg) $ generateRestrictedUpTo size ops (64, 64) False Nothing
run (Unsolved fname) = putStrLn =<< FC.getUnsolved fname
run (FindSolvable fname tmout) = do
problems <- FC.getUnsolvedHS fname
tryGen $ sortBy (comparing problemSize) problems
where
tryGen [] = return ()
tryGen (p:ps) = do
res <- isFeasible tmout p
_ <- case res of
Nothing -> return () -- putStrLn ("skipping " ++ problemId p ++ " - timed out")
Just () -> pp (p, generateRestricted (problemSize p) (operators p) (64, 64) False Nothing)
tryGen ps
pp (p, exps) = putStrLn $ (printf "%s|%d|%s|%d" (problemId p) (problemSize p) (intercalate " " $ operators p) (length exps))
run (TrainSolve size) = do
p <- HC.getTrainingProblem (Just size) Nothing
let progId = (trainingId p)
print p
solve (trainingId p) size (trainingOps p)
run (TrainBonusSolve size cacheSize) = do
p <- HC.getTrainingProblem (Just size) Nothing
let progId = (trainingId p)
print p
bonusSolve (trainingId p) size cacheSize (trainingOps p)
run (Solve tmout fname id) = do
problems <- FC.getUnsolvedHS fname
case find ((==id).problemId) problems of
Nothing -> error "No unsolved problems with this ID"
Just p -> solveWithTimeout tmout (problemId p) (problemSize p) (operators p)
run (LowLevelSolve id size ops) = solve id size ops
run (SolveExact size ops (ins, outs)) = solveExact size ops ins outs
run (Filter problemsFile idsFile) = FC.filterByIds problemsFile idsFile >>= putStrLn
run (SolveMany offset limit tmout bySize includeBonuses) = do
problemsUnfiltered <- HC.getUnsolved
let problems = if includeBonuses then problemsUnfiltered else filter (not.("bonus" `elem`).operators) problemsUnfiltered
putStrLn $ ">>> " ++ show (length problems) ++ " remaining"
let workload = take limit $ drop offset $ sortProblems problems
trySolve workload
where
sortProblems = if bySize then sortBy (comparing problemSize)
else sortBy (comparing complexity)
complexity p = PC.expectedComplexity (operators p) (problemSize p)
trySolve [] = putStrLn "All done!"
trySolve (p:ps) = do
tm <- getCurrentTime
print tm
putStrLn $ printf ">>> Trying %s, size %d, operations (%s)" (problemId p) (problemSize p) (intercalate " " $ operators p)
solveWithTimeout tmout (problemId p) (problemSize p) (operators p)
trySolve ps
run (FilterCached size ops expected) = mapM_ (putStrLn.ppProg) $ filterByCached expected $ generateRestrictedUpTo size ops (64, 64) False (Just expected)
run (EstimateComplexity size operations) = putStrLn $ show $ PC.expectedComplexity operations size
run (ReportComplexity fname all) = do
problems <- if all then FC.getMyproblemsHS fname else FC.getUnsolvedHS fname
mapM_ report $ sortBy (comparing fst) $ zip (map complexity problems) problems
where
complexity p = PC.expectedComplexity (operators p) (problemSize p)
report :: (Integer,Problem) -> IO ()
report (c,p) = putStrLn $ printf "%s|%s|%d|%s|%0.5f" (maybe "not" (\b -> if b then "yes" else "not") $ solved p)
(problemId p) (problemSize p) (intercalate " " $ operators p) ((log $ fromIntegral c) :: Double)
options = info (clientOptions <**> helper) idm
clientOptions =
subparser
( command "myproblems"
(info (pure MyProblems)
(progDesc "Get our problem set"))
<> command "status"
(info (pure Status)
(progDesc "Get current team status"))
<> command "train"
(info train
(progDesc "Get random task for training"))
<> command "eval"
(info eval
(progDesc "Eval program on given inputs"))
<> command "guess"
(info guess
(progDesc "Provide guess for given program ID"))
<> command "generate"
(info generate
(progDesc "Generate programs of given size with given ops restrictions"))
<> command "unsolved"
(info unsolved
(progDesc "Provide the list of tasks that are still not solved"))
<> command "find-solvable"
(info findSolvable
(progDesc "Find list of problems solvable by brute-force within N seconds (deprecated)"))
<> command "train-solve"
(info trainSolve
(progDesc "Solve the new training task of the given size"))
<> command "train-bonus-solve"
(info trainBonusSolve
(progDesc "Solve the new bonus training task of the given size (new algorithm!)"))
<> command "low-level-solve"
(info lowLevelSolve
(progDesc "Try solving problem supplying its ID, SIZE, OPERATIONS manually"))
<> command "solve-exact"
(info solveExactCmd
(progDesc "Try solving problem supplying its SIZE, OPERATIONS, INPUTS/OUTPUTS manually"))
<> command "production-solve-one"
(info realSolve
(progDesc "Solve the REAL tasks with given ID (deprecated)"))
<> command "production-solve-many"
(info realSolveMany
(progDesc "Solve some unsolved REAL tasks"))
<> command "filter-out"
(info filterProblems
(progDesc "Filter out tasks with given IDs (deprecated)"))
<> command "filter-cached"
(info filterCached
(progDesc "Filter generated expressions by the value they should have on the first test input"))
<> command "estimate-complexity"
(info estimateComplexity
(progDesc "Estimate complexity of a problem, based on its SIZE and OPERATIONS"))
<> command "report-complexity"
(info reportComplexity
(progDesc "Report all problems in the order of their complexity"))
)
train = Train <$> (fmap read <$> ( optional $ strOption (metavar "LENGTH" <> short 'l' <> long "length")))
<*> (fmap read <$> ( optional $ strOption (metavar "NoFold|Fold|TFold" <> short 'o' <> long "ops")))
eval = Eval <$> argument str (metavar "PROGRAM or ID")
<*> arguments1 str (metavar "ARG1 [ARG2 .. ARG_n]")
guess = Guess <$> argument str (metavar "ID")
<*> argument str (metavar "PROGRAM")
generate = Generate <$> (read <$> argument str (metavar "SIZE"))
<*> (words <$> argument str (metavar "OPERATIONS"))
unsolved = Unsolved <$> argument str (metavar "FILE")
findSolvable = FindSolvable <$> argument str (metavar "FILE")
<*> (read <$> argument str (metavar "TIMEOUT"))
trainSolve = TrainSolve <$> (read <$> argument str (metavar "SIZE"))
trainBonusSolve = TrainBonusSolve <$> (read <$> argument str (metavar "SIZE"))
<*> (read <$> strOption (long "cache-size" <> help "cache size; 2000000 is ~30sec of populating the cache" <> value "200000"))
lowLevelSolve = LowLevelSolve <$> argument str (metavar "ID")
<*> (read <$> argument str (metavar "SIZE"))
<*> (words <$> (argument str (metavar "OPERATIONS")))
solveExactCmd = SolveExact <$> (read <$> argument str (metavar "SIZE"))
<*> (words <$> (argument str (metavar "OPERATIONS")))
<*> (read <$> (argument str (metavar "INOUTS")))
filterCached = FilterCached <$> (read <$> argument str (metavar "SIZE"))
<*> (words <$> (argument str (metavar "OPERATIONS")))
<*> (read <$> argument str (metavar "EXPECTED-VALUE"))
realSolve = Solve <$> (read <$> argument str (metavar "TIMEOUT"))
<*> argument str (metavar "FILE")
<*> argument str (metavar "ID")
realSolveMany= SolveMany <$> (read <$> strOption (metavar "OFFSET" <> long "offset"))
<*> (read <$> strOption (metavar "LIMIT" <> long "limit"))
<*> (read <$> strOption (metavar "TIMEOUT" <> long "timeout"))
<*> (switch (long "by-size" <> help "order tasks by size, not by complexity (faster)" <> value False))
<*> (switch (long "include-bonuses" <> help "include bonus tasks" <> value False))
filterProblems = Filter <$> argument str (metavar "MYPROBLEMS-FILE")
<*> argument str (metavar "IDS-FILE")
estimateComplexity = EstimateComplexity <$> (read <$> argument str (metavar "SIZE"))
<*> (words <$> (argument str (metavar "OPERATIONS")))
reportComplexity = ReportComplexity <$> (argument str (metavar "FILE"))
<*> (switch (long "all" <> help "all tasks, not just unsolved" <> value False))
| atemerev/icfpc2013 | src/client/client.hs | apache-2.0 | 10,339 | 1 | 28 | 2,455 | 3,170 | 1,598 | 1,572 | 198 | 10 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module Phaedrus.Text.BetaCode
( betaCode
, fromBeta
, fromBetaIgnore
, normalizeChars
, betanorm
, clean
, BetaCode
, unBeta
, toBeta
) where
import Control.Applicative
import Control.Error
import Data.Attoparsec.Text
import Data.Char
import Data.Hashable
import Data.Maybe
import Data.Monoid
import Data.String
import qualified Data.Text as T
import Data.Text.ICU.Normalize
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Builder
import qualified Data.Text.Lazy.Builder as B
import GHC.Generics (Generic)
-- BetaCode conversion
diacritic :: Parser Char
diacritic = choice [ char' ')' '\x0313' -- ̓ ) Smooth breathing ἐν E)N
, char' '(' '\x0314' -- ̔ ( Rough breathing ὁ, οἱ O(, OI(
, char' '/' '\x0301' -- ́ / Acute accent πρός PRO/S
, char' '=' '\x0342' -- ͂ = Circumflex accent τῶν TW=N
, char' '\\' '\x0300' -- ̀ \ Grave accent πρὸς PRO\S
, char' '+' '\x0308' -- ̈ + Diaeresis προϊέναι PROI+E/NAI
, char' '|' '\x0345' -- ͅ | Iota subscript τῷ TW=|
, char' '&' '\x0304' -- ̄ & Macron μαχαίρᾱς MAXAI/RA&S
-- , char' '\'' '\x0306' -- ̆ ' Breve μάχαιρᾰ MA/XAIRA'
, char' '?' '\x0323' -- combining dot below
]
punct :: Parser Char
punct = choice [ char '.' -- . . Period
, char ',' -- , , Comma
-- , char' ':' '\x00b7' -- · : Colon (Ano Stigme)
, char ':' -- · : Colon (Ano Stigme)
, char ';' -- ; ; Question Mark
, char' '\'' '\x1fbd' -- ’ ' Apostrophe
, char' '-' '\x2010' -- ‐ - Hyphen
, char' '_' '\x2014' -- — _ Dash
]
lowercase :: Parser Char
lowercase = choice [ beta 'A' 'a' '\x03b1' -- Α *A Alpha α A
, beta 'B' 'b' '\x03b2' -- Β *B Beta β B
, beta 'G' 'g' '\x03b3' -- Γ *G Gamma γ G
, beta 'D' 'd' '\x03b4' -- Δ *D Delta δ D
, beta 'E' 'e' '\x03b5' -- Ε *E Epsilon ε E
, beta 'V' 'v' '\x03dd' -- Ϝ *V Digamma ϝ V
, beta 'Z' 'z' '\x03b6' -- Ζ *Z Zeta ζ Z
, beta 'H' 'h' '\x03b7' -- Η *H Eta η H
, beta 'Q' 'q' '\x03b8' -- Θ *Q Theta θ Q
, beta 'I' 'i' '\x03b9' -- Ι *I Iota ι I
, beta 'K' 'k' '\x03ba' -- Κ *K Kappa κ K
, beta 'L' 'l' '\x03bb' -- Λ *L Lambda λ L
, beta 'M' 'm' '\x03bc' -- Μ *M Mu μ M
, beta 'N' 'n' '\x03bd' -- Ν *N Nu ν N
, beta 'C' 'c' '\x03be' -- Ξ *C Xi ξ C
, beta 'O' 'o' '\x03bf' -- Ο *O Omicron ο O
, beta 'P' 'p' '\x03c0' -- Π *P Pi π P
, beta 'R' 'r' '\x03c1' -- Ρ *R Rho ρ R
, beta' "S1" "s1" '\x03c3' -- Σ *S Medial Sigma σ S, S1
, beta' "S2" "s2" '\x03c2' -- Σ *S Final Sigma ς S, S2, J
, beta' "S3" "s3" '\x03f2' -- Ϲ *S (*S3) Lunate Sigma ϲ S (S3)
, beta 'J' 'j' '\x03c2' -- Σ *S Final Sigma ς S, S2, J
, sigma
-- , beta 'S' 's' '\x03c3' -- Σ *S Medial Sigma σ S, S1
-- , beta 'S' 's' '\x03c2' -- Σ *S Final Sigma ς S, S2, J
-- , beta 'S' 's' '\x03f2' -- Ϲ *S (*S3) Lunate Sigma ϲ S (S3)
, beta 'T' 't' '\x03c4' -- Τ *T Tau τ T
, beta 'U' 'u' '\x03c5' -- Υ *U Upsilon υ U
, beta 'F' 'f' '\x03c6' -- Φ *F Phi φ F
, beta 'X' 'x' '\x03c7' -- Χ *X Chi χ X
, beta 'Y' 'y' '\x03c8' -- Ψ *Y Psi ψ Y
, beta 'W' 'w' '\x03c9' -- Ω *W Omega ω W
]
char' :: Char -> Char -> Parser Char
char' c d = char c *> pure d
beta :: Char -> Char -> Char -> Parser Char
beta c d e = (char c <|> char d) *> pure e
beta' :: T.Text -> T.Text -> Char -> Parser Char
beta' c d e = (string c <|> string d) *> pure e
sigma :: Parser Char
sigma = do
char 'S' <|> char 's'
eow <- endOfWord
pure $ if eow
then '\x03c2'
else '\x03c3'
diacritics :: Parser Builder
diacritics = B.fromString <$> many' diacritic
upperseq :: Parser Builder
upperseq = char '*' *> ((<>) <$> (flip (<>) <$> diacritics
<*> (singleton . toUpper <$> lowercase))
<*> diacritics)
lowerseq :: Parser Builder
lowerseq = (<>) <$> (singleton <$> lowercase) <*> diacritics
endOfWord :: Parser Bool
endOfWord = eow . fromMaybe ' ' <$> peekChar
where eow '.' = True
eow ',' = True
eow ':' = True
eow ';' = True
eow '\'' = True
eow '-' = True
eow '_' = True
eow x = isSpace x
remove :: Parser Builder
remove = (char '<' <|> char '>') *> pure mempty
betaCode :: Parser T.Text
betaCode = toStrict . toLazyText . mconcat
<$> (many' (space' <|> digit' <|> upperseq <|> lowerseq <|> punct' <|> remove) <* endOfInput)
where space' = singleton <$> space
punct' = singleton <$> punct
digit' = singleton <$> digit
fromBeta :: T.Text -> Either T.Text T.Text
fromBeta t = fmapL (const errMsg) $ parseOnly betaCode t
where errMsg = "ERROR " <> t
fromBetaIgnore :: T.Text -> T.Text
fromBetaIgnore = either id id . fromBeta
normalizeChars :: T.Text -> T.Text
normalizeChars = normalize NFC
betanorm :: T.Text -> T.Text
betanorm = normalizeChars . fromBetaIgnore
clean :: T.Text -> T.Text
clean = T.filter (\c -> isAscii c && isAlphaNum c) . T.map cchar
cchar :: Char -> Char
cchar '\x03b1' = 'a'
cchar '\x03b2' = 'b'
cchar '\x03b3' = 'g'
cchar '\x03b4' = 'd'
cchar '\x03b5' = 'e'
cchar '\x03b6' = 'z'
cchar '\x03b7' = 'h'
cchar '\x03b8' = 'q'
cchar '\x03b9' = 'i'
cchar '\x03ba' = 'k'
cchar '\x03bb' = 'l'
cchar '\x03bc' = 'm'
cchar '\x03bd' = 'n'
cchar '\x03be' = 'c'
cchar '\x03bf' = 'o'
cchar '\x03c0' = 'p'
cchar '\x03c1' = 'r'
cchar '\x03c2' = 's'
cchar '\x03c3' = 's'
cchar '\x03c4' = 't'
cchar '\x03c5' = 'u'
cchar '\x03c6' = 'f'
cchar '\x03c7' = 'x'
cchar '\x03c8' = 'y'
cchar '\x03c9' = 'w'
cchar '\x03dd' = 'v'
cchar '\x03f2' = 's'
cchar c = c
newtype BetaCode = BC { unBeta :: T.Text }
deriving (Eq, Show, Generic)
instance Hashable BetaCode
toBeta :: T.Text -> BetaCode
toBeta = BC . clean . normalizeChars
instance IsString BetaCode where
fromString = toBeta . T.pack
| erochest/phaedrus | Phaedrus/Text/BetaCode.hs | apache-2.0 | 7,445 | 0 | 14 | 3,001 | 1,642 | 877 | 765 | 160 | 8 |
module DeliveryQueue where
import qualified Data.Set as Set
import qualified Data.PSQueue as PSQueue
import Transaction
import Commutating
import Position
import NonCommutatingTransactionSet
newtype DeliveryQueue = DeliveryQueue (PSQueue.PSQ TransactionID Position)
empty :: DeliveryQueue
empty =
DeliveryQueue PSQueue.empty
getHighestPosition :: DeliveryQueue -> Position
getHighestPosition (DeliveryQueue psq) =
case PSQueue.findMin psq of
Nothing -> 0
Just b -> negate $ PSQueue.prio b
insert :: TransactionID -> Position -> DeliveryQueue -> DeliveryQueue
insert t p (DeliveryQueue dq) =
DeliveryQueue $ PSQueue.insert t p dq | kdkeyser/halvin | src/halvin/DeliveryQueue.hs | apache-2.0 | 652 | 0 | 10 | 102 | 169 | 92 | 77 | 19 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Util.JSONWebToken where
import Control.Applicative
import Control.Monad
import Data.Aeson
import qualified Data.ByteString.Char8 as C
import qualified Data.ByteString.Lazy.Char8 as CL
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified JWT
import qualified JWE
import qualified JWS
import qualified Util.Base64 as B64
import Model.PublicKey
( PublicKey(..)
, rsaKey
)
import Crypto.PubKey.RSA
( PrivateKey
)
------------------------------------------------------------------------------ | Converts value to JWT encoded.
toB64JSON :: ToJSON a => a -> IO C.ByteString
toB64JSON = return . B64.encode . encode
fromB64JSON :: FromJSON a => C.ByteString -> IO (Maybe a)
fromB64JSON = return . decode . B64.decode'
--toCompactJWT :: ToJSON a => a -> IO C.ByteString
--toCompactJWT jwtContents = do
-- myPrivKey <- liftM read $ readFile "../server-common/resources/keys/rsa-key.priv"
-- theirPubKey <- liftM read $ readFile "../server-common/resources/keys/TJDFT/rsa-key.pub"
-- JWT.toCompact myPrivKey theirPubKey jwtContents
--
--fromCompactJWT :: FromJSON a => C.ByteString -> IO (Maybe a)
--fromCompactJWT jwtContents = do
-- myPrivKey <- liftM read $ readFile "../server-common/resources/keys/rsa-key.priv"
-- theirPubKey <- liftM read $ readFile "../server-common/resources/keys/TJDFT/rsa-key.pub"
-- JWT.fromCompact myPrivKey theirPubKey jwtContents
serverPrivKey :: IO PrivateKey
serverPrivKey = liftM read $ readFile "../server-common/resources/keys/rsa-key.priv"
serverPubKey :: IO PublicKey
serverPubKey = liftM (RSAPublicKey . read) $ readFile "../server-common/resources/keys/rsa-key.pub"
-- Returns a value and the message whose signature must be verified.
decrypt :: FromJSON a => PrivateKey -> C.ByteString -> Maybe (a, C.ByteString)
decrypt privKey jweContents =
-- TODO: Handle header properly. I'm ignoring it because we're using
-- only one algorithm.
let (_, jwsContents) = JWE.decryptJWE privKey jweContents
in case C.split '.' jwsContents of
(_:msg:_) -> (,) <$> (decode . B64.decode') msg
<*> pure jwsContents
_ -> Nothing
-- Verifies signature using sender's public key. It must be taken from
-- Server's database using the contract UUID provided (known after
-- decryption).
verify :: PublicKey -> C.ByteString -> Bool
verify pubKey jwsContents =
let eitherMsg = JWS.verifyJWS (rsaKey pubKey) jwsContents
in case eitherMsg of
Right _ -> True
_ -> False
signAndEncrypt :: ToJSON a => PrivateKey -> PublicKey -> a -> IO C.ByteString
signAndEncrypt privKey pubKey = JWT.toCompact privKey (rsaKey pubKey)
| alexandrelucchesi/pfec | server-common/src/Util/JSONWebToken.hs | apache-2.0 | 2,756 | 0 | 15 | 493 | 503 | 280 | 223 | 41 | 2 |
-- -*- coding: utf-8; -*-
module Show where
import Model
import qualified Data.Map as Map
showElements :: Int
-> [Element]
-> String
showElements n (e@(Element name props subelements):es) =
(take (2*n) $ repeat ' ') ++ show (Element name props []) ++ "\n" ++
showElements (n+1) subelements ++
showElements n es
showElements n (e@(Def name subelements):es) =
(take (2*n) $ repeat ' ') ++ show (Def name []) ++ "\n" ++
showElements (n+1) subelements ++
showElements n es
showElements n (e:es) =
(take (2*n) $ repeat ' ') ++ show e ++ "\n" ++
showElements n es
showElements _ []= ""
| grzegorzbalcerek/orgmode | Show.hs | bsd-2-clause | 628 | 0 | 13 | 149 | 293 | 151 | 142 | 18 | 1 |
{-|
Copyright : (C) 2013-2016, University of Twente
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <christiaan.baaij@gmail.com>
-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
module CLaSH.GHC.Evaluator where
import Control.Monad.Trans.Except (runExcept)
import qualified Data.Bifunctor as Bifunctor
import Data.Bits (shiftL,shiftR)
import qualified Data.Either as Either
import qualified Data.HashMap.Strict as HashMap
import qualified Data.List as List
import Data.Text (Text)
import Unbound.Generics.LocallyNameless (runFreshM, bind, embed,
string2Name)
import CLaSH.Core.DataCon (DataCon (..))
import CLaSH.Core.Literal (Literal (..))
import CLaSH.Core.Term (Term (..))
import CLaSH.Core.Type (Type (..), ConstTy (..),
TypeView (..), tyView, mkFunTy,
mkTyConApp, splitFunForallTy)
import CLaSH.Core.TyCon (TyCon, TyConName, tyConDataCons)
import CLaSH.Core.TysPrim (typeNatKind)
import CLaSH.Core.Util (collectArgs,mkApps,mkVec,termType,tyNatSize)
import CLaSH.Core.Var (Var (..))
reduceConstant :: HashMap.HashMap TyConName TyCon -> Bool -> Term -> Term
reduceConstant tcm isSubj e@(collectArgs -> (Prim nm ty, args)) = case nm of
"GHC.Prim.eqChar#" | Just (i,j) <- charLiterals tcm isSubj args
-> boolToIntLiteral (i == j)
"GHC.Prim.neChar#" | Just (i,j) <- charLiterals tcm isSubj args
-> boolToIntLiteral (i /= j)
"GHC.Prim.+#" | Just (i,j) <- intLiterals tcm isSubj args
-> integerToIntLiteral (i+j)
"GHC.Prim.-#" | Just (i,j) <- intLiterals tcm isSubj args
-> integerToIntLiteral (i-j)
"GHC.Prim.*#" | Just (i,j) <- intLiterals tcm isSubj args
-> integerToIntLiteral (i*j)
"GHC.Prim.quotInt#" | Just (i,j) <- intLiterals tcm isSubj args
-> integerToIntLiteral (i `quot` j)
"GHC.Prim.remInt#" | Just (i,j) <- intLiterals tcm isSubj args
-> integerToIntLiteral (i `rem` j)
"GHC.Prim.quotRemInt#" | Just (i,j) <- intLiterals tcm isSubj args
-> let (_,tyView -> TyConApp tupTcNm tyArgs) = splitFunForallTy ty
(Just tupTc) = HashMap.lookup tupTcNm tcm
[tupDc] = tyConDataCons tupTc
(q,r) = quotRem i j
ret = mkApps (Data tupDc) (map Right tyArgs ++
[Left (integerToIntLiteral q), Left (integerToIntLiteral r)])
in ret
"GHC.Prim.negateInt#"
| [Literal (IntLiteral i)] <- reduceTerms tcm isSubj args
-> integerToIntLiteral (negate i)
"GHC.Prim.>#" | Just (i,j) <- intLiterals tcm isSubj args
-> boolToIntLiteral (i > j)
"GHC.Prim.>=#" | Just (i,j) <- intLiterals tcm isSubj args
-> boolToIntLiteral (i >= j)
"GHC.Prim.==#" | Just (i,j) <- intLiterals tcm isSubj args
-> boolToIntLiteral (i == j)
"GHC.Prim./=#" | Just (i,j) <- intLiterals tcm isSubj args
-> boolToIntLiteral (i /= j)
"GHC.Prim.<#" | Just (i,j) <- intLiterals tcm isSubj args
-> boolToIntLiteral (i < j)
"GHC.Prim.<=#" | Just (i,j) <- intLiterals tcm isSubj args
-> boolToIntLiteral (i <= j)
"GHC.Prim.eqWord#" | Just (i,j) <- wordLiterals tcm isSubj args
-> boolToIntLiteral (i == j)
"GHC.Prim.neWord#" | Just (i,j) <- wordLiterals tcm isSubj args
-> boolToIntLiteral (i /= j)
"GHC.Prim.tagToEnum#"
| [Right (ConstTy (TyCon tcN)), Left (Literal (IntLiteral i))] <-
map (Bifunctor.bimap (reduceConstant tcm isSubj) id) args
-> let dc = do { tc <- HashMap.lookup tcN tcm
; let dcs = tyConDataCons tc
; List.find ((== (i+1)) . toInteger . dcTag) dcs
}
in maybe e Data dc
"GHC.Integer.Type.integerToInt"
| [Literal (IntegerLiteral i)] <- reduceTerms tcm isSubj args
-> integerToIntLiteral i
"GHC.Integer.Type.plusInteger" | Just (i,j) <- integerLiterals tcm isSubj args
-> integerToIntegerLiteral (i+j)
"GHC.Integer.Type.minusInteger" | Just (i,j) <- integerLiterals tcm isSubj args
-> integerToIntegerLiteral (i-j)
"GHC.Integer.Type.timesInteger" | Just (i,j) <- integerLiterals tcm isSubj args
-> integerToIntegerLiteral (i*j)
"GHC.Integer.Type.negateInteger#"
| [Literal (IntegerLiteral i)] <- reduceTerms tcm isSubj args
-> integerToIntegerLiteral (negate i)
"GHC.Integer.Type.divInteger" | Just (i,j) <- integerLiterals tcm isSubj args
-> integerToIntegerLiteral (i `div` j)
"GHC.Integer.Type.modInteger" | Just (i,j) <- integerLiterals tcm isSubj args
-> integerToIntegerLiteral (i `mod` j)
"GHC.Integer.Type.quotInteger" | Just (i,j) <- integerLiterals tcm isSubj args
-> integerToIntegerLiteral (i `quot` j)
"GHC.Integer.Type.remInteger" | Just (i,j) <- integerLiterals tcm isSubj args
-> integerToIntegerLiteral (i `rem` j)
"GHC.Integer.Type.gtInteger" | Just (i,j) <- integerLiterals tcm isSubj args
-> boolToBoolLiteral tcm ty (i > j)
"GHC.Integer.Type.geInteger" | Just (i,j) <- integerLiterals tcm isSubj args
-> boolToBoolLiteral tcm ty (i >= j)
"GHC.Integer.Type.eqInteger" | Just (i,j) <- integerLiterals tcm isSubj args
-> boolToBoolLiteral tcm ty (i == j)
"GHC.Integer.Type.neqInteger" | Just (i,j) <- integerLiterals tcm isSubj args
-> boolToBoolLiteral tcm ty (i /= j)
"GHC.Integer.Type.ltInteger" | Just (i,j) <- integerLiterals tcm isSubj args
-> boolToBoolLiteral tcm ty (i < j)
"GHC.Integer.Type.leInteger" | Just (i,j) <- integerLiterals tcm isSubj args
-> boolToBoolLiteral tcm ty (i <= j)
"GHC.Integer.Type.gtInteger#" | Just (i,j) <- integerLiterals tcm isSubj args
-> boolToIntLiteral (i > j)
"GHC.Integer.Type.geInteger#" | Just (i,j) <- integerLiterals tcm isSubj args
-> boolToIntLiteral (i >= j)
"GHC.Integer.Type.eqInteger#" | Just (i,j) <- integerLiterals tcm isSubj args
-> boolToIntLiteral (i == j)
"GHC.Integer.Type.neqInteger#" | Just (i,j) <- integerLiterals tcm isSubj args
-> boolToIntLiteral (i /= j)
"GHC.Integer.Type.ltInteger#" | Just (i,j) <- integerLiterals tcm isSubj args
-> boolToIntLiteral (i < j)
"GHC.Integer.Type.leInteger#" | Just (i,j) <- integerLiterals tcm isSubj args
-> boolToIntLiteral (i <= j)
"GHC.Integer.Type.shiftRInteger"
| [Literal (IntegerLiteral i), Literal (IntLiteral j)] <- reduceTerms tcm isSubj args
-> integerToIntegerLiteral (i `shiftR` fromInteger j)
"GHC.Integer.Type.shiftLInteger"
| [Literal (IntegerLiteral i), Literal (IntLiteral j)] <- reduceTerms tcm isSubj args
-> integerToIntegerLiteral (i `shiftL` fromInteger j)
"GHC.TypeLits.natVal"
| [Literal (IntegerLiteral i), _] <- reduceTerms tcm isSubj args
-> integerToIntegerLiteral i
"GHC.Types.I#"
| isSubj
, [Literal (IntLiteral i)] <- reduceTerms tcm isSubj args
-> let (_,tyView -> TyConApp intTcNm []) = splitFunForallTy ty
(Just intTc) = HashMap.lookup intTcNm tcm
[intDc] = tyConDataCons intTc
in mkApps (Data intDc) [Left (Literal (IntLiteral i))]
"CLaSH.Sized.Internal.BitVector.eq#" | Just (i,j) <- bitVectorLiterals tcm isSubj args
-> boolToBoolLiteral tcm ty (i == j)
"CLaSH.Sized.Internal.BitVector.neq#" | Just (i,j) <- bitVectorLiterals tcm isSubj args
-> boolToBoolLiteral tcm ty (i /= j)
"CLaSH.Sized.Internal.Index.eq#" | Just (i,j) <- indexLiterals tcm isSubj args
-> boolToBoolLiteral tcm ty (i == j)
"CLaSH.Sized.Internal.Index.neq#" | Just (i,j) <- indexLiterals tcm isSubj args
-> boolToBoolLiteral tcm ty (i /= j)
"CLaSH.Sized.Internal.Signed.eq#" | Just (i,j) <- signedLiterals tcm isSubj args
-> boolToBoolLiteral tcm ty (i == j)
"CLaSH.Sized.Internal.Signed.neq#" | Just (i,j) <- signedLiterals tcm isSubj args
-> boolToBoolLiteral tcm ty (i /= j)
"CLaSH.Sized.Internal.Signed.minBound#"
| [litTy,kn@(Left (Literal (IntegerLiteral mb)))] <- args
-> let minB = negate (2 ^ (mb - 1))
in mkApps signedConPrim [litTy,kn,Left (Literal (IntegerLiteral minB))]
"CLaSH.Sized.Internal.Signed.maxBound#"
| [litTy,kn@(Left (Literal (IntegerLiteral mb)))] <- args
-> let maxB = (2 ^ (mb - 1)) - 1
in mkApps signedConPrim [litTy,kn,Left (Literal (IntegerLiteral maxB))]
"CLaSH.Sized.Internal.Signed.toInteger#"
| [collectArgs -> (Prim nm' _,[Right _, Left _, Left (Literal (IntegerLiteral i))])] <-
(map (reduceConstant tcm isSubj) . Either.lefts) args
, nm' == "CLaSH.Sized.Internal.Signed.fromInteger#"
-> integerToIntegerLiteral i
"CLaSH.Sized.Internal.Unsigned.eq#" | Just (i,j) <- unsignedLiterals tcm isSubj args
-> boolToBoolLiteral tcm ty (i == j)
"CLaSH.Sized.Internal.Unsigned.neq#" | Just (i,j) <- unsignedLiterals tcm isSubj args
-> boolToBoolLiteral tcm ty (i /= j)
"CLaSH.Sized.Internal.Unsigned.minBound#"
| [litTy,kn@(Left (Literal (IntegerLiteral _)))] <- args
-> mkApps unsignedConPrim [litTy,kn,Left (Literal (IntegerLiteral 0))]
"CLaSH.Sized.Internal.Unsigned.minBound#"
| [litTy,kn@(Left (Literal (IntegerLiteral mb)))] <- args
-> let maxB = (2 ^ mb) - 1
in mkApps unsignedConPrim [litTy,kn,Left (Literal (IntegerLiteral maxB))]
"CLaSH.Sized.Internal.Unsigned.toInteger#"
| [collectArgs -> (Prim nm' _,[Right _, Left _, Left (Literal (IntegerLiteral i))])] <-
(map (reduceConstant tcm isSubj) . Either.lefts) args
, nm' == "CLaSH.Sized.Internal.Unsigned.fromInteger#"
-> integerToIntegerLiteral i
"CLaSH.Promoted.Nat.SNat"
| [(Literal (IntegerLiteral _),[]), (Data _,_)] <- (map collectArgs . Either.lefts) args
-> mkApps snatCon args
"CLaSH.Sized.Vector.replicate"
| isSubj
, (TyConApp vecTcNm [lenTy,argTy]) <- tyView (runFreshM (termType tcm e))
, Right len <- runExcept (tyNatSize tcm lenTy)
-> let (Just vecTc) = HashMap.lookup vecTcNm tcm
[nilCon,consCon] = tyConDataCons vecTc
in mkVec nilCon consCon argTy len (replicate len (last $ Either.lefts args))
"CLaSH.Sized.Vector.maxIndex"
| isSubj
, [nTy, _] <- Either.rights args
, Right n <- runExcept (tyNatSize tcm nTy)
-> let ty' = runFreshM (termType tcm e)
(TyConApp intTcNm _) = tyView ty'
(Just intTc) = HashMap.lookup intTcNm tcm
[intCon] = tyConDataCons intTc
in mkApps (Data intCon) [Left (Literal (IntegerLiteral (toInteger (n - 1))))]
"CLaSH.Sized.Vector.length"
| isSubj
, [nTy, _] <- Either.rights args
, Right n <-runExcept (tyNatSize tcm nTy)
-> let ty' = runFreshM (termType tcm e)
(TyConApp intTcNm _) = tyView ty'
(Just intTc) = HashMap.lookup intTcNm tcm
[intCon] = tyConDataCons intTc
in mkApps (Data intCon) [Left (Literal (IntegerLiteral (toInteger n)))]
_ -> e
reduceConstant _ _ e = e
reduceTerms :: HashMap.HashMap TyConName TyCon -> Bool -> [Either Term Type] -> [Term]
reduceTerms tcm isSubj = map (reduceConstant tcm isSubj) . Either.lefts
integerLiterals :: HashMap.HashMap TyConName TyCon -> Bool -> [Either Term Type] -> Maybe (Integer,Integer)
integerLiterals tcm isSubj args = case reduceTerms tcm isSubj args of
[Literal (IntegerLiteral i), Literal (IntegerLiteral j)] -> Just (i,j)
_ -> Nothing
intLiterals :: HashMap.HashMap TyConName TyCon -> Bool -> [Either Term Type] -> Maybe (Integer,Integer)
intLiterals tcm isSubj args = case reduceTerms tcm isSubj args of
[Literal (IntLiteral i), Literal (IntLiteral j)] -> Just (i,j)
_ -> Nothing
wordLiterals :: HashMap.HashMap TyConName TyCon -> Bool -> [Either Term Type] -> Maybe (Integer,Integer)
wordLiterals tcm isSubj args = case (map (reduceConstant tcm isSubj) . Either.lefts) args of
[Literal (WordLiteral i), Literal (WordLiteral j)] -> Just (i,j)
_ -> Nothing
charLiterals :: HashMap.HashMap TyConName TyCon -> Bool -> [Either Term Type] -> Maybe (Char,Char)
charLiterals tcm isSubj args = case (map (reduceConstant tcm isSubj) . Either.lefts) args of
[Literal (CharLiteral i), Literal (CharLiteral j)] -> Just (i,j)
_ -> Nothing
sizedLiterals :: Text -> HashMap.HashMap TyConName TyCon -> Bool -> [Either Term Type] -> Maybe (Integer,Integer)
sizedLiterals szCon tcm isSubj args
= case reduceTerms tcm isSubj args of
([ collectArgs -> (Prim nm _,[Right _, Left _, Left (Literal (IntegerLiteral i))])
, collectArgs -> (Prim nm' _,[Right _, Left _, Left (Literal (IntegerLiteral j))])])
| nm == szCon
, nm' == szCon -> Just (i,j)
_ -> Nothing
bitVectorLiterals :: HashMap.HashMap TyConName TyCon -> Bool -> [Either Term Type] -> Maybe (Integer,Integer)
bitVectorLiterals = sizedLiterals "CLaSH.Sized.Internal.BitVector.fromInteger#"
indexLiterals :: HashMap.HashMap TyConName TyCon -> Bool -> [Either Term Type] -> Maybe (Integer,Integer)
indexLiterals = sizedLiterals "CLaSH.Sized.Internal.Index.fromInteger#"
signedLiterals :: HashMap.HashMap TyConName TyCon -> Bool -> [Either Term Type] -> Maybe (Integer,Integer)
signedLiterals = sizedLiterals "CLaSH.Sized.Internal.Signed.fromInteger#"
unsignedLiterals :: HashMap.HashMap TyConName TyCon -> Bool -> [Either Term Type] -> Maybe (Integer,Integer)
unsignedLiterals = sizedLiterals "CLaSH.Sized.Internal.Unsigned.fromInteger#"
boolToIntLiteral :: Bool -> Term
boolToIntLiteral b = if b then Literal (IntLiteral 1) else Literal (IntLiteral 0)
boolToBoolLiteral :: HashMap.HashMap TyConName TyCon -> Type -> Bool -> Term
boolToBoolLiteral tcm ty b =
let (_,tyView -> TyConApp boolTcNm []) = splitFunForallTy ty
(Just boolTc) = HashMap.lookup boolTcNm tcm
[falseDc,trueDc] = tyConDataCons boolTc
retDc = if b then trueDc else falseDc
in Data retDc
integerToIntLiteral :: Integer -> Term
integerToIntLiteral = Literal . IntLiteral . toInteger . (fromInteger :: Integer -> Int) -- for overflow behaviour
integerToIntegerLiteral :: Integer -> Term
integerToIntegerLiteral = Literal . IntegerLiteral
signedConPrim :: Term
signedConPrim = Prim "CLaSH.Sized.Internal.Signed.fromInteger#" (ForAllTy (bind nTV funTy))
where
funTy = foldr1 mkFunTy [intTy,intTy,mkTyConApp signedTcNm [nVar]]
intTy = ConstTy (TyCon (string2Name "GHC.Integer.Type.Integer"))
signedTcNm = string2Name "CLaSH.Sized.Internal.Signed.Signed"
nName = string2Name "n"
nVar = VarTy typeNatKind nName
nTV = TyVar nName (embed typeNatKind)
unsignedConPrim :: Term
unsignedConPrim = Prim "CLaSH.Sized.Internal.Unsigned.fromInteger#" (ForAllTy (bind nTV funTy))
where
funTy = foldr1 mkFunTy [intTy,intTy,mkTyConApp unsignedTcNm [nVar]]
intTy = ConstTy (TyCon (string2Name "GHC.Integer.Type.Integer"))
unsignedTcNm = string2Name "CLaSH.Sized.Internal.Unsigned.Unsigned"
nName = string2Name "n"
nVar = VarTy typeNatKind nName
nTV = TyVar nName (embed typeNatKind)
snatCon :: Term
snatCon = Data (MkData snanNm 1 snatTy [nName] [] argTys)
where
snanNm = string2Name "CLaSH.Promoted.Nat.SNat"
snatTy = ForAllTy (bind nTV funTy)
argTys = [ConstTy (TyCon (string2Name "GHC.Integer.Type.Integer"))
,AppTy (AppTy (ConstTy (TyCon (string2Name "Data.Proxy.Proxy"))) typeNatKind)
nVar
]
funTy = foldr mkFunTy (ConstTy (TyCon (string2Name "CLaSH.Promoted.Nat.SNat"))) argTys
nName = string2Name "n"
nVar = VarTy typeNatKind nName
nTV = TyVar nName (embed typeNatKind)
| ggreif/clash-compiler | clash-ghc/src-ghc/CLaSH/GHC/Evaluator.hs | bsd-2-clause | 15,675 | 0 | 21 | 3,339 | 5,569 | 2,785 | 2,784 | 277 | 62 |
-- {-# LANGUAGE TemplateHaskell #-}
module Main (main) where
import Test.HUnit hiding (Test)
import Test.Framework (Test, defaultMain, testGroup)
import Test.Framework.Providers.HUnit
import MiniSat2
-- should be SAT
case_test1 :: IO ()
case_test1 = do
solver <- newSolver
a <- newVar solver
b <- newVar solver
addClause solver [Pos a, Pos b]
addClause solver [Neg a, Pos b]
addClause solver [Pos a, Neg b]
r <- solve solver
r @?= True
------------------------------------------------------------------------
-- Test harness
main :: IO ()
main = defaultMain [group]
-- $(defaultMainGenerator)
group = testGroup "SomeModule" [testCase "test1" case_test1]
| msakai/haskell-minisat | test/Test.hs | bsd-3-clause | 676 | 0 | 9 | 112 | 209 | 108 | 101 | 18 | 1 |
{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Network.DHT.Kademlia.Workers.Interactive (interactive) where
import Control.Concurrent.STM
import Control.Monad
import Data.Aeson as JSON
import Data.Binary
import Data.Conduit
import Data.Conduit.Network
import Network.DHT.Kademlia.Def
import Network.DHT.Kademlia.Util
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as BL
import qualified Data.Conduit.Binary as CB
import qualified Data.Conduit.List as CL
import qualified Data.Vector as V
-- | Interactive shell to inspect Kademlia
--
-- Example usage
--
-- > echo routes | netcat localhost 6000
interactive :: KademliaEnv -> IO ()
interactive KademliaEnv{..} = forkIO_ $ do
runTCPServer (serverSettings 6000 "!4") app
where
app req = do
bs <- appSource req $$
CB.takeWhile (/= newline) =$ CL.consume >>= return . BL.fromChunks
case bs of
"routes" -> do
routingTable2 <- liftM (V.takeWhile (/= defaultKBucket)) $
atomically $ V.mapM readTVar routingTable
CB.sourceLbs (JSON.encode routingTable2) $$ appSink req
otherwise -> CB.sourceLbs usage $$ appSink req
newline :: Word8
newline = head $ B.unpack $ BC.singleton '\n'
usage :: BL.ByteString
usage = BL.intercalate "\n" [
"USAGE"
, " routes - dump current routing table as json"
, ""
]
| phylake/kademlia | Network/DHT/Kademlia/Workers/Interactive.hs | bsd-3-clause | 1,558 | 0 | 20 | 374 | 363 | 208 | 155 | 37 | 2 |
{-# LANGUAGE MultiParamTypeClasses, OverloadedStrings #-}
module Model.UserProfile
( UserProfile (..)
, Name
, Id
, mkUserProfile
, MachineUsage (..)
, concretize
) where
import qualified Data.Map as M
import qualified Data.Binary as B
import Data.Aeson
import Database.HDBC
import Data.Convertible.Base
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import Control.Applicative
import Control.Monad
import Model.State
import Model.Types
import Model.Machine
type Id = String
type Name = String
data UserProfile = UserProfile
{ userName :: Name
, usages :: M.Map Id MachineUsage }
deriving (Eq, Show)
data MachineUsage = MachineUsage
{ initially :: State
, usage :: [(Second, State)] }
deriving (Eq, Show)
mkUserProfile :: Name -> [(Id, State, [(Second, State)])] -> UserProfile
mkUserProfile name = UserProfile name . M.fromList .
map (\ (n, s, us) -> (n, MachineUsage s us))
instance B.Binary MachineUsage where
put (MachineUsage s us) = do
B.put s
B.put us
get = MachineUsage <$> B.get <*> B.get
instance ToJSON MachineUsage where
toJSON (MachineUsage s us) = toJSON (s, us)
instance FromJSON MachineUsage where
parseJSON v = do
(s, us) <- parseJSON v
return $ MachineUsage s us
instance B.Binary UserProfile where
put (UserProfile un as) = do
B.put un
B.put as
get = UserProfile <$> B.get <*> B.get
instance Convertible UserProfile SqlValue where
safeConvert = Right . SqlByteString . BS.concat . BL.toChunks . B.encode
instance Convertible SqlValue UserProfile where
safeConvert (SqlByteString bs) = Right $ B.decode $ BL.fromChunks [bs]
instance ToJSON UserProfile where
toJSON (UserProfile un xs) = object [ "name" .= un, "data" .= xs]
instance FromJSON UserProfile where
parseJSON (Object v) = UserProfile <$> v .: "name" <*> v .: "data"
parseJSON _ = mzero
concretize :: UserProfile
-> M.Map Id MachineDescription
-> [(MachineDescription, MachineUsage)]
concretize (UserProfile _ uss) mds = M.elems $ M.intersectionWith (,) mds uss
| redelmann/e-zimod-server | Model/UserProfile.hs | bsd-3-clause | 2,168 | 0 | 10 | 485 | 713 | 390 | 323 | 62 | 1 |
import Test.HUnit
import Control.Monad (void)
main :: IO ()
main = void $ runTestTT $ TestList [ TestLabel "test" simpleTest
]
simpleTest = TestCase (assertEqual "1 == 1" 1 1)
| DAHeath/Tetris | test/Spec.hs | bsd-3-clause | 213 | 0 | 8 | 67 | 68 | 35 | 33 | 5 | 1 |
module HipChat where
| mjhopkins/hipchat | src/HipChat.hs | bsd-3-clause | 21 | 0 | 2 | 3 | 4 | 3 | 1 | 1 | 0 |
module Yesod.CoreBot.Bliki.Cache.UpdateHTML where
import Yesod.CoreBot.Bliki.Prelude
import Yesod.CoreBot.Bliki.Config
import Yesod.CoreBot.Bliki.Resources.Base
import Yesod.CoreBot.Bliki.Store
import Yesod.CoreBot.Bliki.DB
import HereDoc
import Control.Monad.Reader
import qualified Data.ByteString.Lazy as B
import Data.FileStore ( Revision(..)
, TimeRange(..)
, Resource
, RevisionId
)
import qualified Data.FileStore as FileStore
import qualified Data.Text as Text
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Text.Blaze.Renderer.String as HTMLRenderer
import Text.Pandoc
import Text.Pandoc.Shared
import System.Directory
pandoc_write_options :: ConfigM master m
=> m WriterOptions
pandoc_write_options = do
return $ defaultWriterOptions
{ writerHtml5 = True
, writerHTMLMathMethod = MathJax "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"
, writerEmailObfuscation = JavascriptObfuscation
, writerStandalone = True
, writerTemplate = [heredoc|
$for(include-before)$
$include-before$
$endfor$
$if(title)$
<header>
<h1 class="title">$title$</h1>
$for(author)$
<h2 class="author">$author$</h2>
$endfor$
$if(date)$
<h3 class="date">$date$</h3>
$endif$
</header>
$endif$
$if(toc)$
<nav id="$idprefix$TOC">
$toc$
</nav>
$endif$
$body$
$for(include-after)$
$include-after$
$endfor$
|]
}
build_blog_HTML :: ( MonadIO m, ConfigM master m )
=> Maybe Bloggable
-> RevisionId
-> String
-> m ()
build_blog_HTML mprev_update rev_ID txt =
if_missingM (asks blog_HTML_path <*> pure rev_ID) $ \out_path -> do
liftIO $ putStrLn $ "build HTML for " ++ rev_ID ++ " log"
let pandoc = readMarkdown defaultParserState txt
write_opts <- pandoc_write_options
let html_string = writeHtmlString write_opts pandoc
liftIO $ cache_str out_path html_string
build_node_HTML :: forall m master . ( MonadIO m, StoreM m, ConfigM master m )
=> Maybe Bloggable
-> RevisionId
-> FilePath
-> m ()
build_node_HTML mprev_update rev_ID node_path = do
if_missingM (asks node_HTML_path <*> pure rev_ID <*> pure node_path) $ \out_path -> do
liftIO $ putStrLn $ "build HTML for " ++ node_path ++ " " ++ show rev_ID
store_data <- data_for_node_rev node_path rev_ID
let markdown_data = FileStore.toByteString store_data
markdown_text = TL.unpack $ TL.decodeUtf8 markdown_data
pandoc = readMarkdown defaultParserState markdown_text
write_opts <- pandoc_write_options
let body_html_str = writeHtmlString write_opts pandoc
let html_builder :: ( Route master -> [(Text, Text)] -> Text ) -> Html = [hamlet|
#{preEscapedToMarkup body_html_str}
|]
html_str <- HTMLRenderer.renderHtml <$> ( pure html_builder <*> asks route_render )
liftIO $ cache_str out_path html_str
if_missingM :: ( MonadIO m )
=> m FilePath
-> ( FilePath -> m () )
-> m ()
if_missingM pM aM = do
path <- pM
exists <- liftIO $ doesFileExist path
case exists of
True -> return ()
False -> aM path
| coreyoconnor/corebot-bliki | src/Yesod/CoreBot/Bliki/Cache/UpdateHTML.hs | bsd-3-clause | 3,452 | 0 | 20 | 912 | 747 | 401 | 346 | -1 | -1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE CPP #-}
-- ----------------------------------------------------------------------------
-- | This module provides scalable event notification for file
-- descriptors and timeouts.
--
-- This module should be considered GHC internal.
--
-- ----------------------------------------------------------------------------
module GHC.Event
#ifdef ghcjs_HOST_OS
( ) where
#else
( -- * Types
EventManager
, TimerManager
-- * Creation
, getSystemEventManager
, new
, getSystemTimerManager
-- * Registering interest in I/O events
, Event
, evtRead
, evtWrite
, IOCallback
, FdKey(keyFd)
, registerFd
, unregisterFd
, unregisterFd_
, closeFd
-- * Registering interest in timeout events
, TimeoutCallback
, TimeoutKey
, registerTimeout
, updateTimeout
, unregisterTimeout
) where
import GHC.Event.Manager
import GHC.Event.TimerManager (TimeoutCallback, TimeoutKey, registerTimeout,
updateTimeout, unregisterTimeout, TimerManager)
import GHC.Event.Thread (getSystemEventManager, getSystemTimerManager)
#endif
| forked-upstream-packages-for-ghcjs/ghc | libraries/base/GHC/Event.hs | bsd-3-clause | 1,218 | 0 | 3 | 269 | 22 | 19 | 3 | 31 | 0 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
import Control.Applicative
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BC
import Data.Monoid
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
import Network.HTTP.QueryString.Internal
instance Arbitrary ByteString where
arbitrary = BC.pack <$> arbitrary
data KeyString = Key { toBS :: ByteString }
instance Arbitrary KeyString where
arbitrary = Key . BC.pack <$> ((:) <$> arbitrary <*> arbitrary)
instance Arbitrary QueryString where
arbitrary = queryString . map unpack <$> arbitrary
unpack :: (KeyString, ByteString) -> (ByteString, ByteString)
unpack (a, b) = (toBS a, b)
instance Show QueryString where
show = show . rawData
main :: IO ()
main = hspec $ do
describe "QueryString" $ do
prop "mappend" prop_mappend
prop "read" prop_read
prop "parse" prop_parse
prop_mappend :: QueryString -> QueryString -> Bool
prop_mappend a b = (a <> b) == queryString (rawData a ++ rawData b)
prop_read :: QueryString -> Bool
prop_read a = read (BC.unpack (toString a)) == a
prop_parse :: QueryString -> Bool
prop_parse a = parseQuery (toString a) == Just a
| worksap-ate/http-querystring | test/Spec.hs | bsd-3-clause | 1,195 | 0 | 11 | 219 | 383 | 204 | 179 | 32 | 1 |
{-|
Module : Data.Boltzmann.System.Utils
Description : Various routines for combinatorial systems.
Copyright : (c) Maciej Bendkowski, 2017-2021
License : BSD3
Maintainer : maciej.bendkowski@tcs.uj.edu.pl
Stability : experimental
The following module implements subroutines for combinatorial systems based
on the excellent paper of Carine Pivoteau, Bruno Salvy, and Michèle Soria:
Algorithms for combinatorial structures: Well-founded systems and Newton iterations.
Journal of Combinatorial Theory, Series A 119 (2012) p. 1711–1773.
-}
module Data.Boltzmann.System.Utils
( isEmptyAtZero
, zeroCoordinates
, wellFoundedAtZero
, polynomial
) where
import Prelude hiding ((<>))
import Data.Map (Map)
import qualified Data.Map.Strict as M
import Numeric.LinearAlgebra hiding (size)
import Data.Boltzmann.System
-- | Non-strict multiplication.
(.*) :: (Num a, Eq a) => a -> a -> a
0 .* _ = 0
_ .* 0 = 0
1 .* x = x
x .* 1 = x
x .* y = x * y
-- | Evaluates the given system Y = H(Z, Y) at coordinates
-- Z = 0 and Y = 0 and checks if the outcome system is empty,
-- i.e. H(0, 0) = 0 or not.
isEmptyAtZero :: (Eq a, Num a) => System a -> Bool
isEmptyAtZero sys = all isZeroType ts
where ts = M.toList $ defs sys
isZeroType (_, consL) = all isZeroCons consL
-- Note: A given constructor can give a non-zero coordinate
-- iff it has no arguments and no positive weight. List
-- arguments are irrelevant as they yield powers of unity.
isZeroCons cons = not $ weight cons == 0 && null (args cons)
evalAtZero :: Num a => Arg -> a
evalAtZero (Type _) = 0
evalAtZero (List _) = 1
evalAtZeroL :: (Eq a, Num a) => [Arg] -> a
evalAtZeroL xs = foldl (.*) 1 $ map evalAtZero xs
derivTypeAtZero :: (Eq a, Eq b, Num a, Num b)
=> String -> [Cons b] -> a
derivTypeAtZero dt consL =
sum $ map (derivConsAtZero dt) consL
derivConsAtZero :: (Eq a, Eq b, Num a, Num b)
=> String -> Cons a -> b
derivConsAtZero dt cons
| weight cons /= 0 = 0
| otherwise = derivConsAtZeroL dt (args cons)
derivConsAtZeroL :: (Eq a, Num a)
=> String -> [Arg] -> a
derivConsAtZeroL _ [] = 1
derivConsAtZeroL dt (x:xs) = lhs + rhs
where lhs = evalAtZero x .* derivConsAtZeroL dt xs
rhs = derivAtZero dt x .* evalAtZeroL xs
derivAtZero :: Num a
=> String -> Arg -> a
derivAtZero dt arg
| argName arg /= dt = 0
| otherwise = 1
-- | Computes the Jacobian matrix of the given system
-- and evaluates it at zero-valued coordinates.
jacobian :: (Eq a, Num a) => System a -> Matrix Double
jacobian sys = (n><n) [idx i j | i <- [0..n-1], j <- [0..n-1]]
where n = size sys
ts = defs sys
idx i j =
let typ = snd $ M.elemAt i ts
dt = fst $ M.elemAt j ts
in derivTypeAtZero dt typ
-- | Checks whether the given matrix is zero or not.
isZero :: Matrix Double -> Bool
isZero mat = all (== 0) $ concat (toLists mat)
-- | Checks whether the given Jacobian matrix nilpotent is or not.
isNilpotent :: Matrix Double -> Bool
isNilpotent mat = isZero $ power mat m
where m = rows mat
-- | Squares the given matrix.
square :: Matrix Double -> Matrix Double
square m = m <> m
-- | Fast matrix exponentiation.
power :: Integral a
=> Matrix Double -> a -> Matrix Double
power m 1 = m
power m n
| odd n = m <> square (power m $ n-1)
| otherwise = square (power m $ n `div` 2)
data Coordinate = Zero | Z deriving (Eq)
-- | Maps coordinates into booleans.
coord :: Coordinate -> Bool
coord Zero = True
coord Z = False
-- | Gives the constructor list of a given type.
constrList :: System a -> String -> [Cons a]
constrList sys = (M.!) (defs sys)
-- | Detects whether the given system, satisfying H(0,0) = 0
-- and having a nilpotent Jacobian matrix, admits zero coordinates
-- in its solution. See also the 0-coord subroutine of Pivoteau et al.
zeroCoordinates :: System a -> Bool
zeroCoordinates sys = zeroCoordinates' sys m f
where f = M.fromSet (const Zero) $ types sys
m = size sys
zeroCoordinates' :: (Eq b, Num b)
=> System a -> b -> Map String Coordinate -> Bool
zeroCoordinates' _ 0 f = elem Zero $ M.elems f
zeroCoordinates' sys m f = zeroCoordinates' sys (m-1) f'
where xs = map (\k -> (k, mapF $ constrList sys k)) (M.keys f)
f' = M.fromAscList xs
mapF consL
| all (coord . mapF') consL = Zero
| otherwise = Z
mapF' cons
| any (coord . mapF'') (args cons) = Zero
| otherwise = Z
mapF'' (List _) = Z
mapF'' (Type t) =
case t `M.lookup` f of
Just Zero -> Zero
_ -> Z
-- | Checks whether the given system is well-founded at zero. Note that
-- the input system is assumed to satisfy H(0,0) = 0. See also the
-- isWellFoundedAt0 subroutine of Pivoteau et al.
wellFoundedAtZero :: (Eq a, Num a)
=> System a -> Bool
wellFoundedAtZero sys
| isNilpotent (jacobian sys) = not $ zeroCoordinates sys
| otherwise = False
-- | Yields an infinite stream of successive evaluation iterations
-- in form of Y[m+1] = H(Z, Y[m]); starting with the given Y[0] and z.
evals :: System Int -> Vector Double -> Double -> [Vector Double]
evals sys ys z = ys : evals sys (eval sys ys z) z
-- | Checks whether the given system, assumed to satisfy H(0,0) = 0
-- and having a nilpotent Jacobian, encodes an implicit polynomial
-- species. See also the isPolynomial subroutine of Pivoteau et al.
polynomial :: System Int -> Bool
polynomial sys = hs !! m == hs !! (m+1)
where m = size sys
hs = evals sys vec 1 -- note: numerical evaluation.
vec = vector $ replicate m 0
| maciej-bendkowski/boltzmann-brain | Data/Boltzmann/System/Utils.hs | bsd-3-clause | 5,979 | 0 | 13 | 1,717 | 1,690 | 862 | 828 | 106 | 3 |
module Data.Sass.Internal
(
) where
| athanclark/shashh | src/Data/Sass/Internal.hs | bsd-3-clause | 44 | 0 | 3 | 13 | 10 | 7 | 3 | 2 | 0 |
{-# LANGUAGE Arrows, FlexibleContexts, TypeOperators, TypeFamilies, ConstraintKinds, ScopedTypeVariables #-}
module BenchTasks.Logistic where
import MixedTypesNumPrelude
-- import qualified Prelude as P
-- import Text.Printf
import Control.Arrow
taskDescription :: Integer -> String
taskDescription n =
"taskLogistic1: " ++ show n ++ " iterations of logistic map with c = "
++ (show (double c)) ++ " and x0 = 0.125"
c :: Rational
c = 3.82 -- not dyadic
x0 :: Rational
x0 = 0.125
type HasLogisticOps r =
(CanMulSameType r,
CanSub Integer r, SubType Integer r ~ r,
CanMulBy r Rational)
taskLogistic :: (HasLogisticOps r) => Integer -> r -> r
taskLogistic n x = r
where
(Just r) = taskLogisticWithHook n (const Just) x
taskLogisticWithHook ::
(HasLogisticOps r)
=>
Integer -> (Integer -> r -> Maybe r) -> r -> Maybe r
taskLogisticWithHook = taskLogisticWithHookA
taskLogisticWithHookA ::
(ArrowChoice to, HasLogisticOps r)
=>
Integer -> (Integer -> r `to` Maybe r) -> (r `to` Maybe r)
taskLogisticWithHookA n hookA =
proc r ->
logisticWithHookA hookA c n -< (Just r)
logisticWithHook ::
(HasLogisticOps r)
=>
(Integer -> r -> Maybe r) -> Rational -> Integer -> Maybe r -> Maybe r
logisticWithHook = logisticWithHookA
logisticWithHookA ::
(ArrowChoice to, HasLogisticOps r)
=>
(Integer -> r `to` Maybe r) -> Rational -> Integer -> (Maybe r `to` Maybe r)
logisticWithHookA hookA c n =
foldl1 (<<<) (take n (map step [1..]))
where
step i = proc mx ->
do
case mx of
Just x ->
hookA i -< c*x*(1-x)
Nothing ->
returnA -< Nothing
| michalkonecny/aern2 | aern2-real/attic/bench/BenchTasks/Logistic.hs | bsd-3-clause | 1,637 | 6 | 16 | 368 | 524 | 278 | 246 | 45 | 2 |
-- | Quasi quoters to make it easier to enter some values that are
-- tedious to express in Haskell source.
module Penny.Quasi where
import Data.Data (Data)
import qualified Data.Text as X
import qualified Language.Haskell.TH as T
import qualified Language.Haskell.TH.Quote as TQ
import Text.Read (readMaybe)
import Penny.Copper (parseProduction)
import Penny.Copper.Decopperize (dDate, dTime, dNilOrBrimRadPer, dBrimRadPer)
import Penny.Copper.Productions
import Penny.NonNegative.Internal
liftData :: Data a => a -> T.Q T.Exp
liftData = TQ.dataToExpQ (const Nothing)
expOnly :: (String -> T.Q T.Exp) -> TQ.QuasiQuoter
expOnly q = TQ.QuasiQuoter
{ TQ.quoteExp = q
, TQ.quotePat = undefined
, TQ.quoteType = undefined
, TQ.quoteDec = undefined
}
-- | Quasi quoter for non-negative numbers. The resulting expression
-- has type 'NonNegative'.
qNonNeg :: TQ.QuasiQuoter
qNonNeg = expOnly $ \s ->
case readMaybe s of
Nothing -> fail $ "invalid number: " ++ s
Just n
| n < 0 -> fail $ "number is negative: " ++ s
| otherwise -> liftData (NonNegative n)
-- | Quasi quoter for dates. Enter as YYYY-MM-DD. The resulting
-- expression has type 'Data.Time.Day'.
qDay :: TQ.QuasiQuoter
qDay = expOnly $ \s ->
case parseProduction a'Date (X.strip . X.pack $ s) of
Left _ -> fail $ "invalid date: " ++ s
Right d -> liftData . dDate $ d
-- | Quasi quoter for time of day. Enter as HH:MM:SS, where the
-- seconds are optional. The resulting expression has type
-- 'Data.Time.TimeOfDay'.
qTime :: TQ.QuasiQuoter
qTime = expOnly $ \s ->
case parseProduction a'Time (X.strip . X.pack $ s) of
Left _ -> fail $ "invalid time of day: " ++ s
Right d -> liftData . dTime $ d
-- | Quasi quoter for unsigned decimal numbers. The resulting
-- expression has type 'Penny.Decimal.DecUnsigned'. The string can
-- have grouping characters, but the radix point mus always be a
-- period.
qUnsigned :: TQ.QuasiQuoter
qUnsigned = expOnly $ \s ->
case parseProduction a'NilOrBrimRadPer (X.strip . X.pack $ s) of
Left _ -> fail $ "invalid unsigned number: " ++ s
Right d -> liftData . dNilOrBrimRadPer $ d
-- | Quasi quoter for positive decimal numbers. The resulting
-- expression has type 'Penny.Decimal.DecPositive'. The string can
-- have grouping characters, but the radix point must always be a
-- period.
qDecPos :: TQ.QuasiQuoter
qDecPos = expOnly $ \s ->
case parseProduction a'BrimRadPer (X.strip . X.pack $ s) of
Left _ -> fail $ "invalid positive number: " ++ s
Right d -> liftData . dBrimRadPer $ d
| massysett/penny | penny/lib/Penny/Quasi.hs | bsd-3-clause | 2,569 | 0 | 13 | 501 | 623 | 341 | 282 | 45 | 2 |
-- | The assembler
module Assembler where
import Control.Monad
import Data.Bits
import Data.List
import Data.Maybe (isJust, fromJust, mapMaybe)
import System.IO
import Text.Parsec
import qualified Text.Parsec.Token as Token
import Text.Parsec.Language
import Text.Groom
import Assembly
-- * The parser
-- | The parser type
type AssemblyParser u a = Parsec String u a
-- | Running the parser
runAssemblyParser :: Parsec String u a
-> u
-> FilePath
-> IO (Either ParseError a)
runAssemblyParser parser state path =
do c <- withFile path ReadMode $ \h ->
do c <- hGetContents h
when (length c == 0) (fail "empty file")
return c
return (runParser parser state path c)
-- | Parses an assembly file
parseAssemblyFile :: FilePath -> IO (Either ParseError [CodeWord])
parseAssemblyFile path = runAssemblyParser parser () path
where parser =
do whiteSpace
ws <- many1 parseCodeWord
eof
return ws
-- | Prints an assembly file
printAssemblyFile :: FilePath -> IO ()
printAssemblyFile path = parseAssemblyFile path >>= putStrLn . groom
-- | Assembles a file
assembleFile :: FilePath -> IO (Either ParseError [Assembled])
assembleFile path =
do e <- parseAssemblyFile path
case e of
Left err -> return $ Left err
Right cws -> return $ Right $ assembleListing $ assignAddresses cws
-- ** Basic definitions of the language style
-- | The language style
assemblyStyle :: LanguageDef st
assemblyStyle = emptyDef
{ Token.commentStart = ""
, Token.commentEnd = ""
, Token.commentLine = ";"
, Token.nestedComments = False
, Token.identStart = letter <|> oneOf "._"
, Token.identLetter = alphaNum <|> oneOf "._"
, Token.opStart = Token.opLetter assemblyStyle
, Token.opLetter = oneOf "+-:"
, Token.reservedOpNames = ["++", "--", ":"]
, Token.reservedNames = [ "r0", "r1", "r2", "r3"
, "r4", "r5", "r6", "r7"
, "ip"
, ".lit"
, "eq"
, "mov", "imov", "rot"
, "not", "nor", "and.n2", "clr"
, "nand", "copy.n1", "xor", "and.n1"
, "or.n2", "xnor", "copy", "and"
, "set", "or.n1", "or", "tst"
]
++ mathReserved
++ map ("if." ++ ) mathReserved
, Token.caseSensitive = False
}
where mathReserved = [ "jmp"
, "add", "sub", "nsub"
, "dec", "inc", "neg"
, "u.lt", "s.lt"
, "iadd", "isub", "ior", "iand"
]
-- | The tokenizer
assembly :: Token.TokenParser st
assembly = Token.makeTokenParser assemblyStyle
-- ** Primitive parsers
-- | Parses whitespace
whiteSpace :: AssemblyParser u ()
whiteSpace = Token.whiteSpace assembly
-- | Parse an identifier
identifier :: AssemblyParser u String
identifier = Token.identifier assembly
-- | Parse a reserved word
reserved :: String -> AssemblyParser u ()
reserved = Token.reserved assembly
-- | Parse a reserved operator
reservedOp :: String -> AssemblyParser u ()
reservedOp = Token.reservedOp assembly
-- | Parse a natural number
natural :: AssemblyParser u Integer
natural = Token.natural assembly
-- | Parses something enclosed in parenthesis
parens :: AssemblyParser u a -> AssemblyParser u a
parens = Token.parens assembly
-- | Parses a colon
colon :: AssemblyParser u String
colon = Token.colon assembly
-- | Parses a comma
comma :: AssemblyParser u String
comma = Token.comma assembly
-- ** Parsing registers and address modes
-- | Parse a register
parseRegister :: AssemblyParser u Register
parseRegister = foldl1 (<|>) (map pr' regs)
where pr' (s, r) = reserved s >>= const (return r)
regs = [ ("ip", R0)
, ("r0", R0), ("r1", R1), ("r2", R2), ("r3", R3)
, ("r4", R4), ("r5", R5), ("r6", R6), ("r7", R7)
]
-- | Parse a register mode
parseRegisterMode :: AssemblyParser u RegisterMode
parseRegisterMode =
(parseRegister >>= return . Direct) <|>
parens parseIndirectRegisterMode
where parseIndirectRegisterMode =
(do r <- parseRegister
m <- optionMaybe (reservedOp "++")
if isJust m
then return (IndirectInc r)
else return (Indirect r)) <|>
(do reservedOp "--"
r <- parseRegister
return (IndirectDec r))
-- ** Parsing instructions
-- | Parses a math operation
parseMath :: AssemblyParser u Instruction
parseMath = parseJmp <|>
parseBinary "add" Add <|>
parseBinary "sub" Sub <|>
parseBinary "nsub" Nsub <|>
parseUnary "dec" Dec <|>
parseUnary "inc" Inc <|>
parseUnary "neg" Neg <|>
parseBinary "s.lt" SLt <|>
parseBinary "u.lt" ULt <|>
parseImm "iadd" IAdd <|>
parseImm "insub" INSub <|>
parseImm "ior" IOr <|>
parseImm "iand" IAnd <|>
parseEq
where parseUnary :: String
-> (Conditional -> Register -> Instruction)
-> AssemblyParser u Instruction
parseUnary opcode f =
do c <- try ((reserved ("if." ++ opcode) >>= const (return True)) <|>
(reserved opcode >>= const (return False)))
r <- parseRegister
return (f c r)
parseBinary :: String
-> (Conditional -> Register -> Register -> Instruction)
-> AssemblyParser u Instruction
parseBinary opcode f =
do c <- try ((reserved ("if." ++ opcode) >>= const (return True)) <|>
(reserved opcode >>= const (return False)))
r1 <- parseRegister
_ <- comma
r2 <- parseRegister
return (f c r1 r2)
parseJmp =
do c <- try ((reserved ("if.jmp") >>= const (return True)) <|>
(reserved "jmp" >>= const (return False)))
l <- identifier
return (Jmp c l)
parseImm opcode f =
do c <- try ((reserved ("if." ++ opcode) >>= const (return True)) <|>
(reserved opcode >>= const (return False)))
i <- (identifier >>= return . Right) <|> (natural >>= return . Left)
_ <- comma
r <- parseRegister
return (f c i r)
parseEq =
do _ <- try (reserved "eq")
r1 <- parseRegister
_ <- comma
r2 <- parseRegister
return (Eq r1 r2)
-- | Parses a logic operation
parseLogic :: AssemblyParser u Instruction
parseLogic = parseUnary "not" Not <|>
parseBinary "nor" Nor <|>
parseBinary "and.n2" AndN2 <|>
parseUnary "clr" Clr <|>
parseBinary "nand" Nand <|>
parseBinary "copy.n1" CopyN1 <|>
parseBinary "xor" Xor <|>
parseBinary "and.n1" AndN1 <|>
parseBinary "or.n2" OrN2 <|>
parseBinary "xnor" Xnor <|>
parseBinary "copy" Copy <|>
parseBinary "and" And <|>
parseUnary "set" Set <|>
parseBinary "or.n1" OrN1 <|>
parseBinary "or" Or <|>
parseUnary "tst" Tst
where parseUnary :: String
-> (Register -> Instruction)
-> AssemblyParser u Instruction
parseUnary opcode f =
do try (reserved opcode)
r <- parseRegister
return (f r)
parseBinary :: String
-> (Register -> Register -> Instruction)
-> AssemblyParser u Instruction
parseBinary opcode f =
do try (reserved opcode)
r1 <- parseRegister
_ <- comma
r2 <- parseRegister
return (f r1 r2)
-- | Parses a move instruction
parseMov :: AssemblyParser u Instruction
parseMov = parseMov1 <|> parseMov2
where parseMov1 =
do try (reserved "imov")
(do i <- natural
_ <- comma
r <- parseRegisterMode
return (Movi i r)) <|>
(do l <- identifier
_ <- comma
r <- parseRegisterMode
return (Movil l r))
parseMov2 =
do try (reserved "mov")
r1 <- parseRegisterMode
_ <- comma
r2 <- parseRegisterMode
return (Mov r1 r2)
-- | Parses a rotate instruction
parseRot :: AssemblyParser u Instruction
parseRot =
do try (reserved "rot")
i <- natural
_ <- comma
r <- parseRegister
return (Rot i r)
-- | Parses a literal instruction
parseLit :: AssemblyParser u Instruction
parseLit =
do try (reserved ".lit")
(natural >>= return . Liti) <|> (identifier >>= return . Litl)
-- | Parses a code word
parseCodeWord :: AssemblyParser u CodeWord
parseCodeWord = (parseMath >>= return . Instr) <|>
(parseLogic >>= return . Instr) <|>
(parseMov >>= return . Instr) <|>
(parseRot >>= return . Instr) <|>
(parseLit >>= return . Instr) <|>
(do i <- identifier
_ <- colon
return (Label i))
-- * The assembler
-- | Assigns addresses to a list of 'CodeWord's. This function is wise enough
-- to only increment the address counter on 'Instr's, and not on 'Label's.
-- All counting is done relative to 0, making this function compatible with
-- relative addressing.
--
-- The pairs in the output are arranged to be compatible with using 'lookup'
-- to determine the address of a label definition.
assignAddresses :: [CodeWord] -> [(CodeWord, Address)]
assignAddresses = snd . mapAccumL assignAddress 0
where assignAddress a x = (a + codeSize x, (x, a))
codeSize :: CodeWord -> Address
codeSize (Label _) = 0
codeSize (Instr (Jmp _ _)) = 2
codeSize (Instr (Movi _ _)) = 2
codeSize (Instr (Movil _ _)) = 2
codeSize (Instr (IAdd _ _ _)) = 2
codeSize (Instr (INSub _ _ _)) = 2
codeSize (Instr (IOr _ _ _)) = 2
codeSize (Instr (IAnd _ _ _)) = 2
codeSize _ = 1
-- | Assembled code
type Assembled = (Address, (CodeWord, [AssembledWord]))
-- | Assembles a program listing
assembleListing :: [(CodeWord, Address)] -> [Assembled]
assembleListing cws = mapMaybe (assemble cws) cws
-- | Assembles a single line of code
assemble :: [(CodeWord, Address)]
-> (CodeWord, Address)
-> Maybe Assembled
assemble _ (Label _, _) = Nothing
assemble cws (cw@(Instr instr), addr) = Just $ assemble' instr
where encodeRegister = fromIntegral . fromEnum
encodeRegisterMode (Direct r) = (0, encodeRegister r)
encodeRegisterMode (Indirect r) = (1, encodeRegister r)
encodeRegisterMode (IndirectInc r) = (2, encodeRegister r)
encodeRegisterMode (IndirectDec r) = (3, encodeRegister r)
-- Instruction encoders
unaryMath c i r = binaryMath c i R7 r
binaryMath c i r1 r2 = AssembledInstr $
0 `shiftL` 10 .|.
(if c then 1 else 0) `shiftL` 9 .|.
i `shiftL` 6 .|.
encodeRegister r1 `shiftL` 3 .|.
encodeRegister r2
immMath c f r = AssembledInstr $
27 `shiftL` 7 .|.
(if c then 1 else 0) `shiftL` 6 .|.
f `shiftL` 3 .|.
encodeRegister r
unaryLogic i r = binaryLogic i R7 r
binaryLogic i r1 r2 = AssembledInstr $
1 `shiftL` 10 .|.
i `shiftL` 6 .|.
encodeRegister r1 `shiftL` 3 .|.
encodeRegister r2
encodeMov r1 r2 =
let (p, a) = encodeRegisterMode r1
(r, b) = encodeRegisterMode r2
in AssembledInstr $
2 `shiftL` 10 .|.
p `shiftL` 8 .|.
r `shiftL` 6 .|.
a `shiftL` 3 .|.
b
-- Math
assemble' :: Instruction -> (Address, (CodeWord, [AssembledWord]))
assemble' (Add c r1 r2) = (addr, (cw, [binaryMath c 0 r1 r2]))
assemble' (Jmp False lbl) = assemble' (Movil lbl $ Direct R0)
-- TODO: the address encoding for Jmp requires us to know if
-- ip is incremented before or after execution. Will
-- need to revisit this.
assemble' (Jmp True lbl) = let i = fromJust $ lookup (Label lbl) cws
i' = i - addr - 2
in (addr, (cw, [ immMath True 0 R0
, AssembledLiter i'
]))
assemble' (Sub c r1 r2) = (addr, (cw, [binaryMath c 1 r1 r2]))
assemble' (Nsub c r1 r2) = (addr, (cw, [binaryMath c 2 r1 r2]))
assemble' (Dec c r) = (addr, (cw, [unaryMath c 3 r]))
assemble' (Inc c r) = (addr, (cw, [unaryMath c 4 r]))
assemble' (Neg c r) = (addr, (cw, [unaryMath c 5 r]))
assemble' (SLt c r1 r2) = (addr, (cw, [binaryMath c 6 r1 r2]))
assemble' (ULt c r1 r2) = (addr, (cw, [binaryMath c 7 r1 r2]))
assemble' (Eq r1 r2) = let eq = AssembledInstr $
50 `shiftL` 6 .|.
encodeRegister r1 `shiftL` 3 .|.
encodeRegister r2
in (addr, (cw, [eq]))
-- Immediate math
assemble' (IAdd c eil r) = let i = case eil of
Left i' -> i'
Right lbl -> fromJust $ lookup (Label lbl) cws
in (addr, (cw, [ immMath c 0 r
, AssembledLiter i
]))
assemble' (INSub c eil r) = let i = case eil of
Left i' -> i'
Right lbl -> fromJust $ lookup (Label lbl) cws
in (addr, (cw, [ immMath c 1 r
, AssembledLiter i
]))
-- Logic
assemble' (Not r) = (addr, (cw, [unaryLogic 0 r]))
assemble' (Nor r1 r2) = (addr, (cw, [binaryLogic 1 r1 r2]))
assemble' (AndN2 r1 r2) = (addr, (cw, [binaryLogic 2 r1 r2]))
assemble' (Clr r) = (addr, (cw, [unaryLogic 3 r]))
assemble' (Nand r1 r2) = (addr, (cw, [binaryLogic 4 r1 r2]))
assemble' (CopyN1 r1 r2) = (addr, (cw, [binaryLogic 5 r1 r2]))
assemble' (Xor r1 r2) = (addr, (cw, [binaryLogic 6 r1 r2]))
assemble' (AndN1 r1 r2) = (addr, (cw, [binaryLogic 7 r1 r2]))
assemble' (OrN2 r1 r2) = (addr, (cw, [binaryLogic 8 r1 r2]))
assemble' (Xnor r1 r2) = (addr, (cw, [binaryLogic 9 r1 r2]))
assemble' (Copy r1 r2) = (addr, (cw, [binaryLogic 10 r1 r2]))
assemble' (And r1 r2) = (addr, (cw, [binaryLogic 11 r1 r2]))
assemble' (Set r) = (addr, (cw, [unaryLogic 12 r]))
assemble' (OrN1 r1 r2) = (addr, (cw, [binaryLogic 13 r1 r2]))
assemble' (Or r1 r2) = (addr, (cw, [binaryLogic 14 r1 r2]))
assemble' (Tst r) = (addr, (cw, [unaryLogic 15 r]))
-- Loads
assemble' (Mov r1 r2) = (addr, (cw, [encodeMov r1 r2]))
assemble' (Movi i r) = (addr, (cw, [ encodeMov (IndirectInc R0) r
, AssembledLiter i
]))
assemble' (Movil lbl r) = let i = fromJust $ lookup (Label lbl) cws
in (addr, (cw, [ encodeMov (IndirectInc R0) r
, AssembledLiter i
]))
-- Rotations
assemble' (Rot i r) = let ror = AssembledInstr $
26 `shiftL` 7 .|.
i `shiftL` 3 .|.
encodeRegister r
in (addr, (cw, [ror]))
-- Literals
assemble' (Liti i) = (addr, (cw, [AssembledLiter i]))
assemble' (Litl s) = let i = fromJust $ lookup (Label s) cws
in (addr, (cw, [AssembledLiter i]))
| Shadytel/Computer | Emulator/Assembler.hs | bsd-3-clause | 17,374 | 0 | 20 | 7,023 | 5,056 | 2,655 | 2,401 | 337 | 42 |
module CustomCodes
( customChr
, customDecrypt
) where
import FastDegree
import RSA
customDecrypt :: PrivateKey -> Integer -> String
customDecrypt (n, d) code = go (deg n code d) ""
where
go 0 word = word
go x word = go (x `div` 100) ((customChr $ mod x 100):word)
customChr :: Integer -> Char
customChr 16 = 'А'
customChr 17 = 'Б'
customChr 18 = 'В'
customChr 19 = 'Г'
customChr 20 = 'Д'
customChr 21 = 'Е'
customChr 22 = 'Ж'
customChr 23 = 'З'
customChr 24 = 'И'
customChr 25 = 'Й'
customChr 26 = 'К'
customChr 27 = 'Л'
customChr 28 = 'М'
customChr 29 = 'Н'
customChr 30 = 'О'
customChr 31 = 'П'
customChr 32 = 'Р'
customChr 33 = 'С'
customChr 34 = 'Т'
customChr 35 = 'У'
customChr 36 = 'Ф'
customChr 37 = 'Х'
customChr 38 = 'Ц'
customChr 39 = 'Ч'
customChr 40 = 'Ш'
customChr 41 = 'Щ'
customChr 42 = 'Ъ'
customChr 43 = 'Ы'
customChr 44 = 'Ь'
customChr 45 = 'Э'
customChr 46 = 'Ю'
customChr 47 = 'Я'
customChr 48 = 'а'
customChr 49 = 'б'
customChr 50 = 'в'
customChr 51 = 'г'
customChr 52 = 'д'
customChr 53 = 'е'
customChr 54 = 'ж'
customChr 55 = 'з'
customChr 56 = 'и'
customChr 57 = 'й'
customChr 58 = 'к'
customChr 59 = 'л'
customChr 60 = 'м'
customChr 61 = 'н'
customChr 62 = 'о'
customChr 63 = 'п'
customChr 64 = 'р'
customChr 65 = 'с'
customChr 66 = 'т'
customChr 67 = 'у'
customChr 68 = 'ф'
customChr 69 = 'х'
customChr 70 = 'ц'
customChr 71 = 'ч'
customChr 72 = 'ш'
customChr 73 = 'щ'
customChr 74 = 'ъ'
customChr 75 = 'ы'
customChr 76 = 'ь'
customChr 77 = 'э'
customChr 78 = 'ю'
customChr 79 = 'я'
customChr _ = '.'
| GOGEN/rsa | app/CustomCodes.hs | bsd-3-clause | 1,617 | 0 | 12 | 339 | 646 | 329 | 317 | 75 | 2 |
module Graphics.X11.HLock(xLocker, hlock) where
import Data.Maybe(fromMaybe)
import Control.Arrow(second)
import Data.Bits((.|.))
import Control.Monad.State
import Control.Concurrent(threadDelay)
import System.Exit(exitFailure)
import System.Posix.User.Password
import HLock hiding (hlock)
import qualified HLock(hlock)
import qualified Graphics.X11.Xlib as X
import qualified Graphics.X11.Xrandr as X
import qualified Graphics.X11.Xlib.Extras as X
xLocker :: LockerT LoopBodyT X.Display [LockT]
xLocker = Locker
{ grabResource = liftIO $ X.openDisplay ""
, lockResource = \display ->
liftIO $ forAllScreen display $ lockScreen display
, unlockResource = \dpy _ -> liftIO $ X.closeDisplay dpy
, authenticationTry = keyboardEventHandler
}
hlock :: MonadIO io => io ()
hlock = runLoopBody $ HLock.hlock xLocker
runLoopBody :: MonadIO io => LoopBodyT a -> io a
runLoopBody loopBody = liftIO $ X.allocaXEvent $ \xevent ->
evalStateT (unLoopBody loopBody) (xevent, "")
lockScreen :: X.Display -> X.ScreenNumber -> IO LockT
lockScreen dpy scr = do
rootWindow' <- X.rootWindow dpy scr
newWindow <- createBlackWindow dpy scr rootWindow'
X.xrrSelectInput dpy newWindow X.rrScreenChangeNotifyMask
grabPointer dpy rootWindow'
grabKeyboard dpy rootWindow'
return Lock { screen = scr
, rootWindow = rootWindow'
, window = newWindow
}
data LockT = Lock
{ screen :: X.ScreenNumber
, rootWindow, window :: X.Window
}
grabPointer :: X.Display -> X.Window -> IO ()
grabPointer dpy rootWindow' = void $
X.grabPointer dpy rootWindow' False (X.buttonPressMask .|. X.buttonReleaseMask .|. X.pointerMotionMask)
X.grabModeAsync X.grabModeAsync 0 0 X.currentTime
grabKeyboard :: X.Display -> X.Window -> IO ()
grabKeyboard dpy rw = do
grabKeyboard' 100
X.selectInput dpy rw X.substructureNotifyMask
where
grabKeyboard' :: Int -> IO ()
grabKeyboard' tries | tries > 0 = do
result<- X.grabKeyboard dpy rw True X.grabModeAsync X.grabModeAsync X.currentTime
unless (result == X.grabSuccess) $ do
threadDelay 100
grabKeyboard' (tries - 1)
grabKeyboard' _ = exitFailure
createBlackWindow :: X.Display -> X.ScreenNumber -> X.Window -> IO X.Window
createBlackWindow dpy scr rootWindow' = X.allocaSetWindowAttributes $ \windowattributes -> do
X.set_background_pixel windowattributes $
X.blackPixel dpy scr
X.set_override_redirect windowattributes True
newWindow <- X.createWindow
dpy
rootWindow'
0
0
(fromIntegral $ X.displayWidth dpy scr)
(fromIntegral $ X.displayHeight dpy scr)
0
(X.defaultDepth dpy scr)
X.copyFromParent
(X.defaultVisual dpy scr)
(X.cWOverrideRedirect .|. X.cWBackPixel)
windowattributes
X.mapWindow dpy newWindow
X.raiseWindow dpy newWindow
return newWindow
forAllScreen :: X.Display -> (X.ScreenNumber -> IO b) -> IO [b]
forAllScreen dpy = forM [0..screenCount' - 1]
where screenCount' = fromIntegral $ X.screenCount dpy
newtype LoopBodyT a = LoopBody
{ unLoopBody :: StateT (X.XEventPtr, String) IO a}
deriving(Functor, Applicative, Monad, MonadIO)
keyboardEventHandler :: X.Display -> [LockT] -> LoopBodyT AuthorizedT
keyboardEventHandler dpy locks = do
xEventPointer <- getEvent
event <- liftIO $ X.getEvent xEventPointer
case event of
X.KeyEvent {} -> do
(mayKsym, str) <- liftIO $ X.lookupString $ X.asKeyEvent xEventPointer
let ksym = fromMaybe X.xK_F1 mayKsym
if ksym == X.xK_KP_Enter || ksym == X.xK_Return
then do
text <- getCharacters
resetCharacters
a <- liftIO $ checkPassword text
return $ if a
then Authorized
else UnAuthorized
else do
unless ( X.ev_event_type event == X.keyRelease
|| X.isFunctionKey ksym
|| X.isKeypadKey ksym
|| X.isMiscFunctionKey ksym
|| X.isPFKey ksym
|| X.isPrivateKeypadKey ksym) $
append str
return UnAuthorized
_otherwise -> liftIO $ do
forM_ locks $ \lock ->
X.raiseWindow dpy $ window lock
return UnAuthorized
where
getEvent :: LoopBodyT X.XEventPtr
getEvent = LoopBody $ fst <$> get >>= \xe -> liftIO $ X.nextEvent dpy xe >> return xe
getCharacters :: LoopBodyT String
getCharacters = LoopBody ( reverse.snd <$> get)
append :: String -> LoopBodyT ()
append str = LoopBody (modify $ second (reverse str++))
resetCharacters = LoopBody (modify $ second (const ""))
| zsedem/hlock | src/Graphics/X11/HLock.hs | bsd-3-clause | 5,011 | 0 | 25 | 1,467 | 1,457 | 737 | 720 | 116 | 4 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
Monadic type operations
This module contains monadic operations over types that contain
mutable type variables
-}
{-# LANGUAGE CPP, TupleSections, MultiWayIf #-}
module TcMType (
TcTyVar, TcKind, TcType, TcTauType, TcThetaType, TcTyVarSet,
--------------------------------
-- Creating new mutable type variables
newFlexiTyVar,
newFlexiTyVarTy, -- Kind -> TcM TcType
newFlexiTyVarTys, -- Int -> Kind -> TcM [TcType]
newOpenFlexiTyVarTy,
newMetaKindVar, newMetaKindVars,
cloneMetaTyVar,
newFmvTyVar, newFskTyVar,
readMetaTyVar, writeMetaTyVar, writeMetaTyVarRef,
newMetaDetails, isFilledMetaTyVar, isUnfilledMetaTyVar,
--------------------------------
-- Expected types
ExpType(..), ExpSigmaType, ExpRhoType,
mkCheckExpType, newOpenInferExpType, readExpType, readExpType_maybe,
writeExpType, expTypeToType, checkingExpType_maybe, checkingExpType,
tauifyExpType,
--------------------------------
-- Creating fresh type variables for pm checking
genInstSkolTyVarsX,
--------------------------------
-- Creating new evidence variables
newEvVar, newEvVars, newDict,
newWanted, newWanteds,
emitWanted, emitWantedEq, emitWantedEvVar, emitWantedEvVars,
newTcEvBinds, addTcEvBind,
newCoercionHole, fillCoercionHole, isFilledCoercionHole,
unpackCoercionHole, unpackCoercionHole_maybe,
checkCoercionHole,
--------------------------------
-- Instantiation
newMetaTyVars, newMetaTyVarX, newMetaSigTyVars,
newSigTyVar,
tcInstType,
tcInstSkolTyVars, tcInstSkolTyVarsLoc, tcInstSuperSkolTyVarsX,
tcInstSigTyVarsLoc, tcInstSigTyVars,
tcInstSkolType,
tcSkolDFunType, tcSuperSkolTyVars,
instSkolTyCoVars, freshenTyVarBndrs, freshenCoVarBndrsX,
--------------------------------
-- Zonking and tidying
zonkTidyTcType, zonkTidyOrigin,
mkTypeErrorThing, mkTypeErrorThingArgs,
tidyEvVar, tidyCt, tidySkolemInfo,
skolemiseUnboundMetaTyVar,
zonkTcTyVar, zonkTcTyVars, zonkTyCoVarsAndFV, zonkTcTypeAndFV,
zonkQuantifiedTyVar, zonkQuantifiedTyVarOrType, quantifyTyVars,
defaultKindVar,
zonkTcTyCoVarBndr, zonkTcTyBinder, zonkTcType, zonkTcTypes, zonkCo,
zonkTyCoVarKind, zonkTcTypeMapper,
zonkEvVar, zonkWC, zonkSimples, zonkId, zonkCt, zonkSkolemInfo,
tcGetGlobalTyCoVars
) where
#include "HsVersions.h"
-- friends:
import TyCoRep
import TcType
import Type
import Kind
import Coercion
import Class
import Var
-- others:
import TcRnMonad -- TcType, amongst others
import TcEvidence
import Id
import Name
import VarSet
import TysWiredIn
import TysPrim
import VarEnv
import PrelNames
import Util
import Outputable
import FastString
import SrcLoc
import Bag
import Pair
import qualified GHC.LanguageExtensions as LangExt
import Control.Monad
import Maybes
import Data.List ( mapAccumL, partition )
import Control.Arrow ( second )
{-
************************************************************************
* *
Kind variables
* *
************************************************************************
-}
mkKindName :: Unique -> Name
mkKindName unique = mkSystemName unique kind_var_occ
kind_var_occ :: OccName -- Just one for all MetaKindVars
-- They may be jiggled by tidying
kind_var_occ = mkOccName tvName "k"
newMetaKindVar :: TcM TcKind
newMetaKindVar = do { uniq <- newUnique
; details <- newMetaDetails TauTv
; let kv = mkTcTyVar (mkKindName uniq) liftedTypeKind details
; return (mkTyVarTy kv) }
newMetaKindVars :: Int -> TcM [TcKind]
newMetaKindVars n = mapM (\ _ -> newMetaKindVar) (nOfThem n ())
{-
************************************************************************
* *
Evidence variables; range over constraints we can abstract over
* *
************************************************************************
-}
newEvVars :: TcThetaType -> TcM [EvVar]
newEvVars theta = mapM newEvVar theta
--------------
newEvVar :: TcPredType -> TcRnIf gbl lcl EvVar
-- Creates new *rigid* variables for predicates
newEvVar ty = do { name <- newSysName (predTypeOccName ty)
; return (mkLocalIdOrCoVar name ty) }
newWanted :: CtOrigin -> Maybe TypeOrKind -> PredType -> TcM CtEvidence
-- Deals with both equality and non-equality predicates
newWanted orig t_or_k pty
= do loc <- getCtLocM orig t_or_k
d <- if isEqPred pty then HoleDest <$> newCoercionHole
else EvVarDest <$> newEvVar pty
return $ CtWanted { ctev_dest = d
, ctev_pred = pty
, ctev_loc = loc }
newWanteds :: CtOrigin -> ThetaType -> TcM [CtEvidence]
newWanteds orig = mapM (newWanted orig Nothing)
-- | Emits a new Wanted. Deals with both equalities and non-equalities.
emitWanted :: CtOrigin -> TcPredType -> TcM EvTerm
emitWanted origin pty
= do { ev <- newWanted origin Nothing pty
; emitSimple $ mkNonCanonical ev
; return $ ctEvTerm ev }
-- | Emits a new equality constraint
emitWantedEq :: CtOrigin -> TypeOrKind -> Role -> TcType -> TcType -> TcM Coercion
emitWantedEq origin t_or_k role ty1 ty2
= do { hole <- newCoercionHole
; loc <- getCtLocM origin (Just t_or_k)
; emitSimple $ mkNonCanonical $
CtWanted { ctev_pred = pty, ctev_dest = HoleDest hole, ctev_loc = loc }
; return (mkHoleCo hole role ty1 ty2) }
where
pty = mkPrimEqPredRole role ty1 ty2
-- | Creates a new EvVar and immediately emits it as a Wanted.
-- No equality predicates here.
emitWantedEvVar :: CtOrigin -> TcPredType -> TcM EvVar
emitWantedEvVar origin ty
= do { new_cv <- newEvVar ty
; loc <- getCtLocM origin Nothing
; let ctev = CtWanted { ctev_dest = EvVarDest new_cv
, ctev_pred = ty
, ctev_loc = loc }
; emitSimple $ mkNonCanonical ctev
; return new_cv }
emitWantedEvVars :: CtOrigin -> [TcPredType] -> TcM [EvVar]
emitWantedEvVars orig = mapM (emitWantedEvVar orig)
newDict :: Class -> [TcType] -> TcM DictId
newDict cls tys
= do { name <- newSysName (mkDictOcc (getOccName cls))
; return (mkLocalId name (mkClassPred cls tys)) }
predTypeOccName :: PredType -> OccName
predTypeOccName ty = case classifyPredType ty of
ClassPred cls _ -> mkDictOcc (getOccName cls)
EqPred _ _ _ -> mkVarOccFS (fsLit "cobox")
IrredPred _ -> mkVarOccFS (fsLit "irred")
{-
************************************************************************
* *
Coercion holes
* *
************************************************************************
-}
newCoercionHole :: TcM CoercionHole
newCoercionHole
= do { u <- newUnique
; traceTc "New coercion hole:" (ppr u)
; ref <- newMutVar Nothing
; return $ CoercionHole u ref }
-- | Put a value in a coercion hole
fillCoercionHole :: CoercionHole -> Coercion -> TcM ()
fillCoercionHole (CoercionHole u ref) co
= do {
#ifdef DEBUG
; cts <- readTcRef ref
; whenIsJust cts $ \old_co ->
pprPanic "Filling a filled coercion hole" (ppr u $$ ppr co $$ ppr old_co)
#endif
; traceTc "Filling coercion hole" (ppr u <+> text ":=" <+> ppr co)
; writeTcRef ref (Just co) }
-- | Is a coercion hole filled in?
isFilledCoercionHole :: CoercionHole -> TcM Bool
isFilledCoercionHole (CoercionHole _ ref) = isJust <$> readTcRef ref
-- | Retrieve the contents of a coercion hole. Panics if the hole
-- is unfilled
unpackCoercionHole :: CoercionHole -> TcM Coercion
unpackCoercionHole hole
= do { contents <- unpackCoercionHole_maybe hole
; case contents of
Just co -> return co
Nothing -> pprPanic "Unfilled coercion hole" (ppr hole) }
-- | Retrieve the contents of a coercion hole, if it is filled
unpackCoercionHole_maybe :: CoercionHole -> TcM (Maybe Coercion)
unpackCoercionHole_maybe (CoercionHole _ ref) = readTcRef ref
-- | Check that a coercion is appropriate for filling a hole. (The hole
-- itself is needed only for printing. NB: This must be /lazy/ in the coercion,
-- as it's used in TcHsSyn in the presence of knots.
-- Always returns the checked coercion, but this return value is necessary
-- so that the input coercion is forced only when the output is forced.
checkCoercionHole :: Coercion -> CoercionHole -> Role -> Type -> Type -> TcM Coercion
checkCoercionHole co h r t1 t2
-- co is already zonked, but t1 and t2 might not be
| debugIsOn
= do { t1 <- zonkTcType t1
; t2 <- zonkTcType t2
; let (Pair _t1 _t2, _role) = coercionKindRole co
; return $
ASSERT2( t1 `eqType` _t1 && t2 `eqType` _t2 && r == _role
, (text "Bad coercion hole" <+>
ppr h <> colon <+> vcat [ ppr _t1, ppr _t2, ppr _role
, ppr co, ppr t1, ppr t2
, ppr r ]) )
co }
| otherwise
= return co
{-
************************************************************************
*
Expected types
*
************************************************************************
Note [ExpType]
~~~~~~~~~~~~~~
An ExpType is used as the "expected type" when type-checking an expression.
An ExpType can hold a "hole" that can be filled in by the type-checker.
This allows us to have one tcExpr that works in both checking mode and
synthesis mode (that is, bidirectional type-checking). Previously, this
was achieved by using ordinary unification variables, but we don't need
or want that generality. (For example, #11397 was caused by doing the
wrong thing with unification variables.) Instead, we observe that these
holes should
1. never be nested
2. never appear as the type of a variable
3. be used linearly (never be duplicated)
By defining ExpType, separately from Type, we can achieve goals 1 and 2
statically.
See also [wiki:Typechecking]
Note [TcLevel of ExpType]
~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data G a where
MkG :: G Bool
foo MkG = True
This is a classic untouchable-variable / ambiguous GADT return type
scenario. But, with ExpTypes, we'll be inferring the type of the RHS.
And, because there is only one branch of the case, we won't trigger
Note [Case branches must never infer a non-tau type] of TcMatches.
We thus must track a TcLevel in an Inferring ExpType. If we try to
fill the ExpType and find that the TcLevels don't work out, we
fill the ExpType with a tau-tv at the low TcLevel, hopefully to
be worked out later by some means. This is triggered in
test gadt/gadt-escape1.
-}
-- actual data definition is in TcType
-- | Make an 'ExpType' suitable for inferring a type of kind * or #.
newOpenInferExpType :: TcM ExpType
newOpenInferExpType
= do { rr <- newFlexiTyVarTy runtimeRepTy
; u <- newUnique
; tclvl <- getTcLevel
; let ki = tYPE rr
; traceTc "newOpenInferExpType" (ppr u <+> dcolon <+> ppr ki)
; ref <- newMutVar Nothing
; return (Infer u tclvl ki ref) }
-- | Extract a type out of an ExpType, if one exists. But one should always
-- exist. Unless you're quite sure you know what you're doing.
readExpType_maybe :: ExpType -> TcM (Maybe TcType)
readExpType_maybe (Check ty) = return (Just ty)
readExpType_maybe (Infer _ _ _ ref) = readMutVar ref
-- | Extract a type out of an ExpType. Otherwise, panics.
readExpType :: ExpType -> TcM TcType
readExpType exp_ty
= do { mb_ty <- readExpType_maybe exp_ty
; case mb_ty of
Just ty -> return ty
Nothing -> pprPanic "Unknown expected type" (ppr exp_ty) }
-- | Write into an 'ExpType'. It must be an 'Infer'.
writeExpType :: ExpType -> TcType -> TcM ()
writeExpType (Infer u tc_lvl ki ref) ty
| debugIsOn
= do { ki1 <- zonkTcType (typeKind ty)
; ki2 <- zonkTcType ki
; MASSERT2( ki1 `eqType` ki2, ppr ki1 $$ ppr ki2 $$ ppr u )
; lvl_now <- getTcLevel
; MASSERT2( tc_lvl == lvl_now, ppr u $$ ppr tc_lvl $$ ppr lvl_now )
; cts <- readTcRef ref
; case cts of
Just already_there -> pprPanic "writeExpType"
(vcat [ ppr u
, ppr ty
, ppr already_there ])
Nothing -> write }
| otherwise
= write
where
write = do { traceTc "Filling ExpType" $
ppr u <+> text ":=" <+> ppr ty
; writeTcRef ref (Just ty) }
writeExpType (Check ty1) ty2 = pprPanic "writeExpType" (ppr ty1 $$ ppr ty2)
-- | Returns the expected type when in checking mode.
checkingExpType_maybe :: ExpType -> Maybe TcType
checkingExpType_maybe (Check ty) = Just ty
checkingExpType_maybe _ = Nothing
-- | Returns the expected type when in checking mode. Panics if in inference
-- mode.
checkingExpType :: String -> ExpType -> TcType
checkingExpType _ (Check ty) = ty
checkingExpType err et = pprPanic "checkingExpType" (text err $$ ppr et)
tauifyExpType :: ExpType -> TcM ExpType
-- ^ Turn a (Infer hole) type into a (Check alpha),
-- where alpha is a fresh unificaiton variable
tauifyExpType exp_ty = do { ty <- expTypeToType exp_ty
; return (Check ty) }
-- | Extracts the expected type if there is one, or generates a new
-- TauTv if there isn't.
expTypeToType :: ExpType -> TcM TcType
expTypeToType (Check ty) = return ty
expTypeToType (Infer u tc_lvl ki ref)
= do { uniq <- newUnique
; tv_ref <- newMutVar Flexi
; let details = MetaTv { mtv_info = TauTv
, mtv_ref = tv_ref
, mtv_tclvl = tc_lvl }
name = mkMetaTyVarName uniq (fsLit "t")
tau_tv = mkTcTyVar name ki details
tau = mkTyVarTy tau_tv
-- can't use newFlexiTyVarTy because we need to set the tc_lvl
-- See also Note [TcLevel of ExpType]
; writeMutVar ref (Just tau)
; traceTc "Forcing ExpType to be monomorphic:"
(ppr u <+> dcolon <+> ppr ki <+> text ":=" <+> ppr tau)
; return tau }
{-
************************************************************************
* *
SkolemTvs (immutable)
* *
************************************************************************
-}
tcInstType :: ([TyVar] -> TcM (TCvSubst, [TcTyVar]))
-- ^ How to instantiate the type variables
-> TcType -- ^ Type to instantiate
-> TcM ([TcTyVar], TcThetaType, TcType) -- ^ Result
-- (type vars, preds (incl equalities), rho)
tcInstType inst_tyvars ty
= case tcSplitForAllTys ty of
([], rho) -> let -- There may be overloading despite no type variables;
-- (?x :: Int) => Int -> Int
(theta, tau) = tcSplitPhiTy rho
in
return ([], theta, tau)
(tyvars, rho) -> do { (subst, tyvars') <- inst_tyvars tyvars
; let (theta, tau) = tcSplitPhiTy (substTyUnchecked subst rho)
; return (tyvars', theta, tau) }
tcSkolDFunType :: Type -> TcM ([TcTyVar], TcThetaType, TcType)
-- Instantiate a type signature with skolem constants.
-- We could give them fresh names, but no need to do so
tcSkolDFunType ty = tcInstType tcInstSuperSkolTyVars ty
tcSuperSkolTyVars :: [TyVar] -> (TCvSubst, [TcTyVar])
-- Make skolem constants, but do *not* give them new names, as above
-- Moreover, make them "super skolems"; see comments with superSkolemTv
-- see Note [Kind substitution when instantiating]
-- Precondition: tyvars should be ordered by scoping
tcSuperSkolTyVars = mapAccumL tcSuperSkolTyVar emptyTCvSubst
tcSuperSkolTyVar :: TCvSubst -> TyVar -> (TCvSubst, TcTyVar)
tcSuperSkolTyVar subst tv
= (extendTvSubstWithClone subst tv new_tv, new_tv)
where
kind = substTyUnchecked subst (tyVarKind tv)
new_tv = mkTcTyVar (tyVarName tv) kind superSkolemTv
-- Wrappers
-- we need to be able to do this from outside the TcM monad:
tcInstSkolTyVarsLoc :: SrcSpan -> [TyVar] -> TcRnIf gbl lcl (TCvSubst, [TcTyVar])
tcInstSkolTyVarsLoc loc = instSkolTyCoVars (mkTcSkolTyVar loc False)
tcInstSkolTyVars :: [TyVar] -> TcM (TCvSubst, [TcTyVar])
tcInstSkolTyVars = tcInstSkolTyVars' False emptyTCvSubst
tcInstSuperSkolTyVars :: [TyVar] -> TcM (TCvSubst, [TcTyVar])
tcInstSuperSkolTyVars = tcInstSuperSkolTyVarsX emptyTCvSubst
tcInstSuperSkolTyVarsX :: TCvSubst -> [TyVar] -> TcM (TCvSubst, [TcTyVar])
tcInstSuperSkolTyVarsX subst = tcInstSkolTyVars' True subst
tcInstSkolTyVars' :: Bool -> TCvSubst -> [TyVar] -> TcM (TCvSubst, [TcTyVar])
-- Precondition: tyvars should be ordered (kind vars first)
-- see Note [Kind substitution when instantiating]
-- Get the location from the monad; this is a complete freshening operation
tcInstSkolTyVars' overlappable subst tvs
= do { loc <- getSrcSpanM
; instSkolTyCoVarsX (mkTcSkolTyVar loc overlappable) subst tvs }
mkTcSkolTyVar :: SrcSpan -> Bool -> Unique -> Name -> Kind -> TcTyVar
mkTcSkolTyVar loc overlappable uniq old_name kind
= mkTcTyVar (mkInternalName uniq (getOccName old_name) loc)
kind
(SkolemTv overlappable)
tcInstSigTyVarsLoc :: SrcSpan -> [TyVar]
-> TcRnIf gbl lcl (TCvSubst, [TcTyVar])
-- We specify the location
tcInstSigTyVarsLoc loc = instSkolTyCoVars (mkTcSkolTyVar loc False)
tcInstSigTyVars :: [TyVar] -> TcRnIf gbl lcl (TCvSubst, [TcTyVar])
-- Get the location from the TyVar itself, not the monad
tcInstSigTyVars
= instSkolTyCoVars mk_tv
where
mk_tv uniq old_name kind
= mkTcTyVar (setNameUnique old_name uniq) kind (SkolemTv False)
tcInstSkolType :: TcType -> TcM ([TcTyVar], TcThetaType, TcType)
-- Instantiate a type with fresh skolem constants
-- Binding location comes from the monad
tcInstSkolType ty = tcInstType tcInstSkolTyVars ty
------------------
freshenTyVarBndrs :: [TyVar] -> TcRnIf gbl lcl (TCvSubst, [TyVar])
-- ^ Give fresh uniques to a bunch of TyVars, but they stay
-- as TyVars, rather than becoming TcTyVars
-- Used in FamInst.newFamInst, and Inst.newClsInst
freshenTyVarBndrs = instSkolTyCoVars mk_tv
where
mk_tv uniq old_name kind = mkTyVar (setNameUnique old_name uniq) kind
freshenCoVarBndrsX :: TCvSubst -> [CoVar] -> TcRnIf gbl lcl (TCvSubst, [CoVar])
-- ^ Give fresh uniques to a bunch of CoVars
-- Used in FamInst.newFamInst
freshenCoVarBndrsX subst = instSkolTyCoVarsX mk_cv subst
where
mk_cv uniq old_name kind = mkCoVar (setNameUnique old_name uniq) kind
------------------
instSkolTyCoVars :: (Unique -> Name -> Kind -> TyCoVar)
-> [TyVar] -> TcRnIf gbl lcl (TCvSubst, [TyCoVar])
instSkolTyCoVars mk_tcv = instSkolTyCoVarsX mk_tcv emptyTCvSubst
instSkolTyCoVarsX :: (Unique -> Name -> Kind -> TyCoVar)
-> TCvSubst -> [TyCoVar] -> TcRnIf gbl lcl (TCvSubst, [TyCoVar])
instSkolTyCoVarsX mk_tcv = mapAccumLM (instSkolTyCoVarX mk_tcv)
instSkolTyCoVarX :: (Unique -> Name -> Kind -> TyCoVar)
-> TCvSubst -> TyCoVar -> TcRnIf gbl lcl (TCvSubst, TyCoVar)
instSkolTyCoVarX mk_tcv subst tycovar
= do { uniq <- newUnique -- using a new unique is critical. See
-- Note [Skolems in zonkSyntaxExpr] in TcHsSyn
; let new_tcv = mk_tcv uniq old_name kind
subst1 | isTyVar new_tcv
= extendTvSubstWithClone subst tycovar new_tcv
| otherwise
= extendCvSubstWithClone subst tycovar new_tcv
; return (subst1, new_tcv) }
where
old_name = tyVarName tycovar
kind = substTyUnchecked subst (tyVarKind tycovar)
newFskTyVar :: TcType -> TcM TcTyVar
newFskTyVar fam_ty
= do { uniq <- newUnique
; let name = mkSysTvName uniq (fsLit "fsk")
; return (mkTcTyVar name (typeKind fam_ty) (FlatSkol fam_ty)) }
{-
Note [Kind substitution when instantiating]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we instantiate a bunch of kind and type variables, first we
expect them to be topologically sorted.
Then we have to instantiate the kind variables, build a substitution
from old variables to the new variables, then instantiate the type
variables substituting the original kind.
Exemple: If we want to instantiate
[(k1 :: *), (k2 :: *), (a :: k1 -> k2), (b :: k1)]
we want
[(?k1 :: *), (?k2 :: *), (?a :: ?k1 -> ?k2), (?b :: ?k1)]
instead of the buggous
[(?k1 :: *), (?k2 :: *), (?a :: k1 -> k2), (?b :: k1)]
************************************************************************
* *
MetaTvs (meta type variables; mutable)
* *
************************************************************************
-}
mkMetaTyVarName :: Unique -> FastString -> Name
-- Makes a /System/ Name, which is eagerly eliminated by
-- the unifier; see TcUnify.nicer_to_update_tv1, and
-- TcCanonical.canEqTyVarTyVar (nicer_to_update_tv2)
mkMetaTyVarName uniq str = mkSysTvName uniq str
newSigTyVar :: Name -> Kind -> TcM TcTyVar
newSigTyVar name kind
= do { details <- newMetaDetails SigTv
; return (mkTcTyVar name kind details) }
newFmvTyVar :: TcType -> TcM TcTyVar
-- Very like newMetaTyVar, except sets mtv_tclvl to one less
-- so that the fmv is untouchable.
newFmvTyVar fam_ty
= do { uniq <- newUnique
; ref <- newMutVar Flexi
; cur_lvl <- getTcLevel
; let details = MetaTv { mtv_info = FlatMetaTv
, mtv_ref = ref
, mtv_tclvl = fmvTcLevel cur_lvl }
name = mkMetaTyVarName uniq (fsLit "s")
; return (mkTcTyVar name (typeKind fam_ty) details) }
newMetaDetails :: MetaInfo -> TcM TcTyVarDetails
newMetaDetails info
= do { ref <- newMutVar Flexi
; tclvl <- getTcLevel
; return (MetaTv { mtv_info = info
, mtv_ref = ref
, mtv_tclvl = tclvl }) }
cloneMetaTyVar :: TcTyVar -> TcM TcTyVar
cloneMetaTyVar tv
= ASSERT( isTcTyVar tv )
do { uniq <- newUnique
; ref <- newMutVar Flexi
; let name' = setNameUnique (tyVarName tv) uniq
details' = case tcTyVarDetails tv of
details@(MetaTv {}) -> details { mtv_ref = ref }
_ -> pprPanic "cloneMetaTyVar" (ppr tv)
; return (mkTcTyVar name' (tyVarKind tv) details') }
-- Works for both type and kind variables
readMetaTyVar :: TyVar -> TcM MetaDetails
readMetaTyVar tyvar = ASSERT2( isMetaTyVar tyvar, ppr tyvar )
readMutVar (metaTvRef tyvar)
isFilledMetaTyVar :: TyVar -> TcM Bool
-- True of a filled-in (Indirect) meta type variable
isFilledMetaTyVar tv
| MetaTv { mtv_ref = ref } <- tcTyVarDetails tv
= do { details <- readMutVar ref
; return (isIndirect details) }
| otherwise = return False
isUnfilledMetaTyVar :: TyVar -> TcM Bool
-- True of a un-filled-in (Flexi) meta type variable
isUnfilledMetaTyVar tv
| MetaTv { mtv_ref = ref } <- tcTyVarDetails tv
= do { details <- readMutVar ref
; return (isFlexi details) }
| otherwise = return False
--------------------
-- Works with both type and kind variables
writeMetaTyVar :: TcTyVar -> TcType -> TcM ()
-- Write into a currently-empty MetaTyVar
writeMetaTyVar tyvar ty
| not debugIsOn
= writeMetaTyVarRef tyvar (metaTvRef tyvar) ty
-- Everything from here on only happens if DEBUG is on
| not (isTcTyVar tyvar)
= WARN( True, text "Writing to non-tc tyvar" <+> ppr tyvar )
return ()
| MetaTv { mtv_ref = ref } <- tcTyVarDetails tyvar
= writeMetaTyVarRef tyvar ref ty
| otherwise
= WARN( True, text "Writing to non-meta tyvar" <+> ppr tyvar )
return ()
--------------------
writeMetaTyVarRef :: TcTyVar -> TcRef MetaDetails -> TcType -> TcM ()
-- Here the tyvar is for error checking only;
-- the ref cell must be for the same tyvar
writeMetaTyVarRef tyvar ref ty
| not debugIsOn
= do { traceTc "writeMetaTyVar" (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)
<+> text ":=" <+> ppr ty)
; writeTcRef ref (Indirect ty) }
-- Everything from here on only happens if DEBUG is on
| otherwise
= do { meta_details <- readMutVar ref;
-- Zonk kinds to allow the error check to work
; zonked_tv_kind <- zonkTcType tv_kind
; zonked_ty_kind <- zonkTcType ty_kind
-- Check for double updates
; ASSERT2( isFlexi meta_details,
hang (text "Double update of meta tyvar")
2 (ppr tyvar $$ ppr meta_details) )
traceTc "writeMetaTyVar" (ppr tyvar <+> text ":=" <+> ppr ty)
; writeMutVar ref (Indirect ty)
; when ( not (isPredTy tv_kind)
-- Don't check kinds for updates to coercion variables
&& not (zonked_ty_kind `tcEqKind` zonked_tv_kind))
$ WARN( True, hang (text "Ill-kinded update to meta tyvar")
2 ( ppr tyvar <+> text "::" <+> (ppr tv_kind $$ ppr zonked_tv_kind)
<+> text ":="
<+> ppr ty <+> text "::" <+> (ppr ty_kind $$ ppr zonked_ty_kind) ) )
(return ()) }
where
tv_kind = tyVarKind tyvar
ty_kind = typeKind ty
{-
% Generating fresh variables for pattern match check
-}
-- UNINSTANTIATED VERSION OF tcInstSkolTyCoVars
genInstSkolTyVarsX :: SrcSpan -> TCvSubst -> [TyVar]
-> TcRnIf gbl lcl (TCvSubst, [TcTyVar])
-- Precondition: tyvars should be scoping-ordered
-- see Note [Kind substitution when instantiating]
-- Get the location from the monad; this is a complete freshening operation
genInstSkolTyVarsX loc subst tvs = instSkolTyCoVarsX (mkTcSkolTyVar loc False) subst tvs
{-
************************************************************************
* *
MetaTvs: TauTvs
* *
************************************************************************
Note [Never need to instantiate coercion variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
With coercion variables sloshing around in types, it might seem that we
sometimes need to instantiate coercion variables. This would be problematic,
because coercion variables inhabit unboxed equality (~#), and the constraint
solver thinks in terms only of boxed equality (~). The solution is that
we never need to instantiate coercion variables in the first place.
The tyvars that we need to instantiate come from the types of functions,
data constructors, and patterns. These will never be quantified over
coercion variables, except for the special case of the promoted Eq#. But,
that can't ever appear in user code, so we're safe!
-}
newAnonMetaTyVar :: MetaInfo -> Kind -> TcM TcTyVar
-- Make a new meta tyvar out of thin air
newAnonMetaTyVar meta_info kind
= do { uniq <- newUnique
; let name = mkMetaTyVarName uniq s
s = case meta_info of
TauTv -> fsLit "t"
FlatMetaTv -> fsLit "fmv"
SigTv -> fsLit "a"
; details <- newMetaDetails meta_info
; return (mkTcTyVar name kind details) }
newFlexiTyVar :: Kind -> TcM TcTyVar
newFlexiTyVar kind = newAnonMetaTyVar TauTv kind
newFlexiTyVarTy :: Kind -> TcM TcType
newFlexiTyVarTy kind = do
tc_tyvar <- newFlexiTyVar kind
return (mkTyVarTy tc_tyvar)
newFlexiTyVarTys :: Int -> Kind -> TcM [TcType]
newFlexiTyVarTys n kind = mapM newFlexiTyVarTy (nOfThem n kind)
-- | Create a tyvar that can be a lifted or unlifted type.
newOpenFlexiTyVarTy :: TcM TcType
newOpenFlexiTyVarTy
= do { rr <- newFlexiTyVarTy runtimeRepTy
; newFlexiTyVarTy (tYPE rr) }
newMetaSigTyVars :: [TyVar] -> TcM (TCvSubst, [TcTyVar])
newMetaSigTyVars = mapAccumLM newMetaSigTyVarX emptyTCvSubst
newMetaTyVars :: [TyVar] -> TcM (TCvSubst, [TcTyVar])
-- Instantiate with META type variables
-- Note that this works for a sequence of kind, type, and coercion variables
-- variables. Eg [ (k:*), (a:k->k) ]
-- Gives [ (k7:*), (a8:k7->k7) ]
newMetaTyVars = mapAccumLM newMetaTyVarX emptyTCvSubst
-- emptyTCvSubst has an empty in-scope set, but that's fine here
-- Since the tyvars are freshly made, they cannot possibly be
-- captured by any existing for-alls.
newMetaTyVarX :: TCvSubst -> TyVar -> TcM (TCvSubst, TcTyVar)
-- Make a new unification variable tyvar whose Name and Kind come from
-- an existing TyVar. We substitute kind variables in the kind.
newMetaTyVarX subst tyvar = new_meta_tv_x TauTv subst tyvar
newMetaSigTyVarX :: TCvSubst -> TyVar -> TcM (TCvSubst, TcTyVar)
-- Just like newMetaTyVarX, but make a SigTv
newMetaSigTyVarX subst tyvar = new_meta_tv_x SigTv subst tyvar
new_meta_tv_x :: MetaInfo -> TCvSubst -> TyVar -> TcM (TCvSubst, TcTyVar)
new_meta_tv_x info subst tyvar
= do { uniq <- newUnique
; details <- newMetaDetails info
; let name = mkSystemName uniq (getOccName tyvar)
-- See Note [Name of an instantiated type variable]
kind = substTyUnchecked subst (tyVarKind tyvar)
new_tv = mkTcTyVar name kind details
subst1 = extendTvSubstWithClone subst tyvar new_tv
; return (subst1, new_tv) }
{- Note [Name of an instantiated type variable]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
At the moment we give a unification variable a System Name, which
influences the way it is tidied; see TypeRep.tidyTyVarBndr.
************************************************************************
* *
Quantification
* *
************************************************************************
Note [quantifyTyVars]
~~~~~~~~~~~~~~~~~~~~~
quantifyTyVars is given the free vars of a type that we
are about to wrap in a forall.
It takes these free type/kind variables (partitioned into dependent and
non-dependent variables) and
1. Zonks them and remove globals and covars
2. Extends kvs1 with free kind vars in the kinds of tvs (removing globals)
3. Calls zonkQuantifiedTyVar on each
Step (2) is often unimportant, because the kind variable is often
also free in the type. Eg
Typeable k (a::k)
has free vars {k,a}. But the type (see Trac #7916)
(f::k->*) (a::k)
has free vars {f,a}, but we must add 'k' as well! Hence step (3).
This function bothers to distinguish between dependent and non-dependent
variables only to keep correct defaulting behavior with -XNoPolyKinds.
With -XPolyKinds, it treats both classes of variables identically.
Note that this function can accept covars, but will never return them.
This is because we never want to infer a quantified covar!
-}
quantifyTyVars :: TcTyCoVarSet -- global tvs
-> Pair TcTyCoVarSet -- dependent tvs We only distinguish
-- nondependent tvs between these for
-- -XNoPolyKinds
-> TcM [TcTyVar]
-- See Note [quantifyTyVars]
-- Can be given a mixture of TcTyVars and TyVars, in the case of
-- associated type declarations. Also accepts covars, but *never* returns any.
quantifyTyVars gbl_tvs (Pair dep_tkvs nondep_tkvs)
= do { dep_tkvs <- zonkTyCoVarsAndFV dep_tkvs
; nondep_tkvs <- (`minusVarSet` dep_tkvs) <$>
zonkTyCoVarsAndFV nondep_tkvs
; gbl_tvs <- zonkTyCoVarsAndFV gbl_tvs
; let all_cvs = filterVarSet isCoVar $
dep_tkvs `unionVarSet` nondep_tkvs `minusVarSet` gbl_tvs
dep_kvs = varSetElemsWellScoped $
dep_tkvs `minusVarSet` gbl_tvs
`minusVarSet` (closeOverKinds all_cvs)
-- remove any tvs that a covar depends on
nondep_tvs = varSetElemsWellScoped $
nondep_tkvs `minusVarSet` gbl_tvs
-- no worry about dependent cvs here, as these vars
-- are non-dependent
-- NB kinds of tvs are zonked by zonkTyCoVarsAndFV
-- In the non-PolyKinds case, default the kind variables
-- to *, and zonk the tyvars as usual. Notice that this
-- may make quantifyTyVars return a shorter list
-- than it was passed, but that's ok
; poly_kinds <- xoptM LangExt.PolyKinds
; dep_vars2 <- if poly_kinds
then return dep_kvs
else do { let (meta_kvs, skolem_kvs) = partition is_meta dep_kvs
is_meta kv = isTcTyVar kv && isMetaTyVar kv
; mapM_ defaultKindVar meta_kvs
; return skolem_kvs } -- should be empty
; let quant_vars = dep_vars2 ++ nondep_tvs
; traceTc "quantifyTyVars"
(vcat [ text "globals:" <+> ppr gbl_tvs
, text "nondep:" <+> ppr nondep_tvs
, text "dep:" <+> ppr dep_kvs
, text "dep2:" <+> ppr dep_vars2
, text "quant_vars:" <+> ppr quant_vars ])
; mapMaybeM zonk_quant quant_vars }
-- Because of the order, any kind variables
-- mentioned in the kinds of the type variables refer to
-- the now-quantified versions
where
zonk_quant tkv
| isTcTyVar tkv = zonkQuantifiedTyVar tkv
| otherwise = return $ Just tkv
-- For associated types, we have the class variables
-- in scope, and they are TyVars not TcTyVars
zonkQuantifiedTyVar :: TcTyVar -> TcM (Maybe TcTyVar)
-- The quantified type variables often include meta type variables
-- we want to freeze them into ordinary type variables, and
-- default their kind (e.g. from TYPE v to TYPE Lifted)
-- The meta tyvar is updated to point to the new skolem TyVar. Now any
-- bound occurrences of the original type variable will get zonked to
-- the immutable version.
--
-- We leave skolem TyVars alone; they are immutable.
--
-- This function is called on both kind and type variables,
-- but kind variables *only* if PolyKinds is on.
--
-- This returns a tyvar if it should be quantified over; otherwise,
-- it returns Nothing. Nothing is
-- returned only if zonkQuantifiedTyVar is passed a RuntimeRep meta-tyvar,
-- in order to default to PtrRepLifted.
zonkQuantifiedTyVar tv = left_only `liftM` zonkQuantifiedTyVarOrType tv
where left_only :: Either a b -> Maybe a
left_only (Left x) = Just x
left_only (Right _) = Nothing
-- | Like zonkQuantifiedTyVar, but if zonking reveals that the tyvar
-- should become a type (when defaulting a RuntimeRep var to PtrRepLifted), it
-- returns the type instead.
zonkQuantifiedTyVarOrType :: TcTyVar -> TcM (Either TcTyVar TcType)
zonkQuantifiedTyVarOrType tv
= case tcTyVarDetails tv of
SkolemTv {} -> do { kind <- zonkTcType (tyVarKind tv)
; return $ Left $ setTyVarKind tv kind }
-- It might be a skolem type variable,
-- for example from a user type signature
MetaTv { mtv_ref = ref } ->
do when debugIsOn $ do
-- [Sept 04] Check for non-empty.
-- See note [Silly Type Synonym]
cts <- readMutVar ref
case cts of
Flexi -> return ()
Indirect ty -> WARN( True, ppr tv $$ ppr ty )
return ()
if isRuntimeRepVar tv
then do { writeMetaTyVar tv ptrRepLiftedTy
; return (Right ptrRepLiftedTy) }
else Left `liftM` skolemiseUnboundMetaTyVar tv vanillaSkolemTv
_other -> pprPanic "zonkQuantifiedTyVar" (ppr tv) -- FlatSkol, RuntimeUnk
-- | Take an (unconstrained) meta tyvar and default it. Works only on
-- vars of type RuntimeRep and of type *. For other kinds, it issues
-- an error. See Note [Defaulting with -XNoPolyKinds]
defaultKindVar :: TcTyVar -> TcM Kind
defaultKindVar kv
| ASSERT( isMetaTyVar kv )
isRuntimeRepVar kv
= writeMetaTyVar kv ptrRepLiftedTy >> return ptrRepLiftedTy
| isStarKind (tyVarKind kv)
= writeMetaTyVar kv liftedTypeKind >> return liftedTypeKind
| otherwise
= do { addErr (vcat [ text "Cannot default kind variable" <+> quotes (ppr kv')
, text "of kind:" <+> ppr (tyVarKind kv')
, text "Perhaps enable PolyKinds or add a kind signature" ])
; return (mkTyVarTy kv) }
where
(_, kv') = tidyOpenTyCoVar emptyTidyEnv kv
skolemiseUnboundMetaTyVar :: TcTyVar -> TcTyVarDetails -> TcM TyVar
-- We have a Meta tyvar with a ref-cell inside it
-- Skolemise it, so that
-- we are totally out of Meta-tyvar-land
-- We create a skolem TyVar, not a regular TyVar
-- See Note [Zonking to Skolem]
skolemiseUnboundMetaTyVar tv details
= ASSERT2( isMetaTyVar tv, ppr tv )
do { span <- getSrcSpanM -- Get the location from "here"
-- ie where we are generalising
; kind <- zonkTcType (tyVarKind tv)
; let uniq = getUnique tv
-- NB: Use same Unique as original tyvar. This is
-- important for TcHsType.splitTelescopeTvs to work properly
tv_name = getOccName tv
final_name = mkInternalName uniq tv_name span
final_tv = mkTcTyVar final_name kind details
; traceTc "Skolemising" (ppr tv <+> text ":=" <+> ppr final_tv)
; writeMetaTyVar tv (mkTyVarTy final_tv)
; return final_tv }
{-
Note [Defaulting with -XNoPolyKinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data Compose f g a = Mk (f (g a))
We infer
Compose :: forall k1 k2. (k2 -> *) -> (k1 -> k2) -> k1 -> *
Mk :: forall k1 k2 (f :: k2 -> *) (g :: k1 -> k2) (a :: k1).
f (g a) -> Compose k1 k2 f g a
Now, in another module, we have -XNoPolyKinds -XDataKinds in effect.
What does 'Mk mean? Pre GHC-8.0 with -XNoPolyKinds,
we just defaulted all kind variables to *. But that's no good here,
because the kind variables in 'Mk aren't of kind *, so defaulting to *
is ill-kinded.
After some debate on #11334, we decided to issue an error in this case.
The code is in defaultKindVar.
Note [What is a meta variable?]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A "meta type-variable", also know as a "unification variable" is a placeholder
introduced by the typechecker for an as-yet-unknown monotype.
For example, when we see a call `reverse (f xs)`, we know that we calling
reverse :: forall a. [a] -> [a]
So we know that the argument `f xs` must be a "list of something". But what is
the "something"? We don't know until we explore the `f xs` a bit more. So we set
out what we do know at the call of `reverse` by instantiate its type with a fresh
meta tyvar, `alpha` say. So now the type of the argument `f xs`, and of the
result, is `[alpha]`. The unification variable `alpha` stands for the
as-yet-unknown type of the elements of the list.
As type inference progresses we may learn more about `alpha`. For example, suppose
`f` has the type
f :: forall b. b -> [Maybe b]
Then we instantiate `f`'s type with another fresh unification variable, say
`beta`; and equate `f`'s result type with reverse's argument type, thus
`[alpha] ~ [Maybe beta]`.
Now we can solve this equality to learn that `alpha ~ Maybe beta`, so we've
refined our knowledge about `alpha`. And so on.
If you found this Note useful, you may also want to have a look at
Section 5 of "Practical type inference for higher rank types" (Peyton Jones,
Vytiniotis, Weirich and Shields. J. Functional Programming. 2011).
Note [What is zonking?]
~~~~~~~~~~~~~~~~~~~~~~~
GHC relies heavily on mutability in the typechecker for efficient operation.
For this reason, throughout much of the type checking process meta type
variables (the MetaTv constructor of TcTyVarDetails) are represented by mutable
variables (known as TcRefs).
Zonking is the process of ripping out these mutable variables and replacing them
with a real TcType. This involves traversing the entire type expression, but the
interesting part of replacing the mutable variables occurs in zonkTyVarOcc.
There are two ways to zonk a Type:
* zonkTcTypeToType, which is intended to be used at the end of type-checking
for the final zonk. It has to deal with unfilled metavars, either by filling
it with a value like Any or failing (determined by the UnboundTyVarZonker
used).
* zonkTcType, which will happily ignore unfilled metavars. This is the
appropriate function to use while in the middle of type-checking.
Note [Zonking to Skolem]
~~~~~~~~~~~~~~~~~~~~~~~~
We used to zonk quantified type variables to regular TyVars. However, this
leads to problems. Consider this program from the regression test suite:
eval :: Int -> String -> String -> String
eval 0 root actual = evalRHS 0 root actual
evalRHS :: Int -> a
evalRHS 0 root actual = eval 0 root actual
It leads to the deferral of an equality (wrapped in an implication constraint)
forall a. () => ((String -> String -> String) ~ a)
which is propagated up to the toplevel (see TcSimplify.tcSimplifyInferCheck).
In the meantime `a' is zonked and quantified to form `evalRHS's signature.
This has the *side effect* of also zonking the `a' in the deferred equality
(which at this point is being handed around wrapped in an implication
constraint).
Finally, the equality (with the zonked `a') will be handed back to the
simplifier by TcRnDriver.tcRnSrcDecls calling TcSimplify.tcSimplifyTop.
If we zonk `a' with a regular type variable, we will have this regular type
variable now floating around in the simplifier, which in many places assumes to
only see proper TcTyVars.
We can avoid this problem by zonking with a skolem. The skolem is rigid
(which we require for a quantified variable), but is still a TcTyVar that the
simplifier knows how to deal with.
Note [Silly Type Synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this:
type C u a = u -- Note 'a' unused
foo :: (forall a. C u a -> C u a) -> u
foo x = ...
bar :: Num u => u
bar = foo (\t -> t + t)
* From the (\t -> t+t) we get type {Num d} => d -> d
where d is fresh.
* Now unify with type of foo's arg, and we get:
{Num (C d a)} => C d a -> C d a
where a is fresh.
* Now abstract over the 'a', but float out the Num (C d a) constraint
because it does not 'really' mention a. (see exactTyVarsOfType)
The arg to foo becomes
\/\a -> \t -> t+t
* So we get a dict binding for Num (C d a), which is zonked to give
a = ()
[Note Sept 04: now that we are zonking quantified type variables
on construction, the 'a' will be frozen as a regular tyvar on
quantification, so the floated dict will still have type (C d a).
Which renders this whole note moot; happily!]
* Then the \/\a abstraction has a zonked 'a' in it.
All very silly. I think its harmless to ignore the problem. We'll end up with
a \/\a in the final result but all the occurrences of a will be zonked to ()
************************************************************************
* *
Zonking types
* *
************************************************************************
-}
-- | @tcGetGlobalTyCoVars@ returns a fully-zonked set of *scoped* tyvars free in
-- the environment. To improve subsequent calls to the same function it writes
-- the zonked set back into the environment. Note that this returns all
-- variables free in anything (term-level or type-level) in scope. We thus
-- don't have to worry about clashes with things that are not in scope, because
-- if they are reachable, then they'll be returned here.
tcGetGlobalTyCoVars :: TcM TcTyVarSet
tcGetGlobalTyCoVars
= do { (TcLclEnv {tcl_tyvars = gtv_var}) <- getLclEnv
; gbl_tvs <- readMutVar gtv_var
; gbl_tvs' <- zonkTyCoVarsAndFV gbl_tvs
; writeMutVar gtv_var gbl_tvs'
; return gbl_tvs' }
zonkTcTypeAndFV :: TcType -> TcM TyCoVarSet
-- Zonk a type and take its free variables
-- With kind polymorphism it can be essential to zonk *first*
-- so that we find the right set of free variables. Eg
-- forall k1. forall (a:k2). a
-- where k2:=k1 is in the substitution. We don't want
-- k2 to look free in this type!
-- NB: This might be called from within the knot, so don't use
-- smart constructors. See Note [Zonking within the knot] in TcHsType
zonkTcTypeAndFV ty
= tyCoVarsOfType <$> mapType (zonkTcTypeMapper { tcm_smart = False }) () ty
zonkTyCoVar :: TyCoVar -> TcM TcType
-- Works on TyVars and TcTyVars
zonkTyCoVar tv | isTcTyVar tv = zonkTcTyVar tv
| isTyVar tv = mkTyVarTy <$> zonkTyCoVarKind tv
| otherwise = ASSERT2( isCoVar tv, ppr tv )
mkCoercionTy . mkCoVarCo <$> zonkTyCoVarKind tv
-- Hackily, when typechecking type and class decls
-- we have TyVars in scopeadded (only) in
-- TcHsType.tcTyClTyVars, but it seems
-- painful to make them into TcTyVars there
zonkTyCoVarsAndFV :: TyCoVarSet -> TcM TyCoVarSet
zonkTyCoVarsAndFV tycovars = tyCoVarsOfTypes <$> mapM zonkTyCoVar (varSetElems tycovars)
zonkTcTyVars :: [TcTyVar] -> TcM [TcType]
zonkTcTyVars tyvars = mapM zonkTcTyVar tyvars
----------------- Types
zonkTyCoVarKind :: TyCoVar -> TcM TyCoVar
zonkTyCoVarKind tv = do { kind' <- zonkTcType (tyVarKind tv)
; return (setTyVarKind tv kind') }
zonkTcTypes :: [TcType] -> TcM [TcType]
zonkTcTypes tys = mapM zonkTcType tys
{-
************************************************************************
* *
Zonking constraints
* *
************************************************************************
-}
zonkImplication :: Implication -> TcM Implication
zonkImplication implic@(Implic { ic_skols = skols
, ic_given = given
, ic_wanted = wanted
, ic_info = info })
= do { skols' <- mapM zonkTcTyCoVarBndr skols -- Need to zonk their kinds!
-- as Trac #7230 showed
; given' <- mapM zonkEvVar given
; info' <- zonkSkolemInfo info
; wanted' <- zonkWCRec wanted
; return (implic { ic_skols = skols'
, ic_given = given'
, ic_wanted = wanted'
, ic_info = info' }) }
zonkEvVar :: EvVar -> TcM EvVar
zonkEvVar var = do { ty' <- zonkTcType (varType var)
; return (setVarType var ty') }
zonkWC :: WantedConstraints -> TcM WantedConstraints
zonkWC wc = zonkWCRec wc
zonkWCRec :: WantedConstraints -> TcM WantedConstraints
zonkWCRec (WC { wc_simple = simple, wc_impl = implic, wc_insol = insol })
= do { simple' <- zonkSimples simple
; implic' <- mapBagM zonkImplication implic
; insol' <- zonkSimples insol
; return (WC { wc_simple = simple', wc_impl = implic', wc_insol = insol' }) }
zonkSimples :: Cts -> TcM Cts
zonkSimples cts = do { cts' <- mapBagM zonkCt' cts
; traceTc "zonkSimples done:" (ppr cts')
; return cts' }
zonkCt' :: Ct -> TcM Ct
zonkCt' ct = zonkCt ct
zonkCt :: Ct -> TcM Ct
zonkCt ct@(CHoleCan { cc_ev = ev })
= do { ev' <- zonkCtEvidence ev
; return $ ct { cc_ev = ev' } }
zonkCt ct
= do { fl' <- zonkCtEvidence (cc_ev ct)
; return (mkNonCanonical fl') }
zonkCtEvidence :: CtEvidence -> TcM CtEvidence
zonkCtEvidence ctev@(CtGiven { ctev_pred = pred })
= do { pred' <- zonkTcType pred
; return (ctev { ctev_pred = pred'}) }
zonkCtEvidence ctev@(CtWanted { ctev_pred = pred, ctev_dest = dest })
= do { pred' <- zonkTcType pred
; let dest' = case dest of
EvVarDest ev -> EvVarDest $ setVarType ev pred'
-- necessary in simplifyInfer
HoleDest h -> HoleDest h
; return (ctev { ctev_pred = pred', ctev_dest = dest' }) }
zonkCtEvidence ctev@(CtDerived { ctev_pred = pred })
= do { pred' <- zonkTcType pred
; return (ctev { ctev_pred = pred' }) }
zonkSkolemInfo :: SkolemInfo -> TcM SkolemInfo
zonkSkolemInfo (SigSkol cx ty) = do { ty <- readExpType ty
; ty' <- zonkTcType ty
; return (SigSkol cx (mkCheckExpType ty')) }
zonkSkolemInfo (InferSkol ntys) = do { ntys' <- mapM do_one ntys
; return (InferSkol ntys') }
where
do_one (n, ty) = do { ty' <- zonkTcType ty; return (n, ty') }
zonkSkolemInfo skol_info = return skol_info
{-
%************************************************************************
%* *
\subsection{Zonking -- the main work-horses: zonkTcType, zonkTcTyVar}
* *
* For internal use only! *
* *
************************************************************************
-}
-- zonkId is used *during* typechecking just to zonk the Id's type
zonkId :: TcId -> TcM TcId
zonkId id
= do { ty' <- zonkTcType (idType id)
; return (Id.setIdType id ty') }
-- | A suitable TyCoMapper for zonking a type inside the knot, and
-- before all metavars are filled in.
zonkTcTypeMapper :: TyCoMapper () TcM
zonkTcTypeMapper = TyCoMapper
{ tcm_smart = True
, tcm_tyvar = const zonkTcTyVar
, tcm_covar = const (\cv -> mkCoVarCo <$> zonkTyCoVarKind cv)
, tcm_hole = hole
, tcm_tybinder = \_env tv _vis -> ((), ) <$> zonkTcTyCoVarBndr tv }
where
hole :: () -> CoercionHole -> Role -> Type -> Type
-> TcM Coercion
hole _ h r t1 t2
= do { contents <- unpackCoercionHole_maybe h
; case contents of
Just co -> do { co <- zonkCo co
; checkCoercionHole co h r t1 t2 }
Nothing -> do { t1 <- zonkTcType t1
; t2 <- zonkTcType t2
; return $ mkHoleCo h r t1 t2 } }
-- For unbound, mutable tyvars, zonkType uses the function given to it
-- For tyvars bound at a for-all, zonkType zonks them to an immutable
-- type variable and zonks the kind too
zonkTcType :: TcType -> TcM TcType
zonkTcType = mapType zonkTcTypeMapper ()
-- | "Zonk" a coercion -- really, just zonk any types in the coercion
zonkCo :: Coercion -> TcM Coercion
zonkCo = mapCoercion zonkTcTypeMapper ()
zonkTcTyCoVarBndr :: TcTyCoVar -> TcM TcTyCoVar
-- A tyvar binder is never a unification variable (MetaTv),
-- rather it is always a skolems. BUT it may have a kind
-- that has not yet been zonked, and may include kind
-- unification variables.
zonkTcTyCoVarBndr tyvar
-- can't use isCoVar, because it looks at a TyCon. Argh.
= ASSERT2( isImmutableTyVar tyvar || (not $ isTyVar tyvar), pprTvBndr tyvar )
updateTyVarKindM zonkTcType tyvar
-- | Zonk a TyBinder
zonkTcTyBinder :: TcTyBinder -> TcM TcTyBinder
zonkTcTyBinder (Anon ty) = Anon <$> zonkTcType ty
zonkTcTyBinder (Named tv vis) = Named <$> zonkTcTyCoVarBndr tv <*> pure vis
zonkTcTyVar :: TcTyVar -> TcM TcType
-- Simply look through all Flexis
zonkTcTyVar tv
| isTcTyVar tv
= case tcTyVarDetails tv of
SkolemTv {} -> zonk_kind_and_return
RuntimeUnk {} -> zonk_kind_and_return
FlatSkol ty -> zonkTcType ty
MetaTv { mtv_ref = ref }
-> do { cts <- readMutVar ref
; case cts of
Flexi -> zonk_kind_and_return
Indirect ty -> zonkTcType ty }
| otherwise -- coercion variable
= zonk_kind_and_return
where
zonk_kind_and_return = do { z_tv <- zonkTyCoVarKind tv
; return (mkTyVarTy z_tv) }
{-
%************************************************************************
%* *
Tidying
* *
************************************************************************
-}
zonkTidyTcType :: TidyEnv -> TcType -> TcM (TidyEnv, TcType)
zonkTidyTcType env ty = do { ty' <- zonkTcType ty
; return (tidyOpenType env ty') }
-- | Make an 'ErrorThing' storing a type.
mkTypeErrorThing :: TcType -> ErrorThing
mkTypeErrorThing ty = ErrorThing ty (Just $ length $ snd $ repSplitAppTys ty)
zonkTidyTcType
-- NB: Use *rep*splitAppTys, else we get #11313
-- | Make an 'ErrorThing' storing a type, with some extra args known about
mkTypeErrorThingArgs :: TcType -> Int -> ErrorThing
mkTypeErrorThingArgs ty num_args
= ErrorThing ty (Just $ (length $ snd $ repSplitAppTys ty) + num_args)
zonkTidyTcType
zonkTidyOrigin :: TidyEnv -> CtOrigin -> TcM (TidyEnv, CtOrigin)
zonkTidyOrigin env (GivenOrigin skol_info)
= do { skol_info1 <- zonkSkolemInfo skol_info
; let skol_info2 = tidySkolemInfo env skol_info1
; return (env, GivenOrigin skol_info2) }
zonkTidyOrigin env orig@(TypeEqOrigin { uo_actual = act
, uo_expected = exp
, uo_thing = m_thing })
= do { (env1, act') <- zonkTidyTcType env act
; mb_exp <- readExpType_maybe exp -- it really should be filled in.
-- unless we're debugging.
; (env2, exp') <- case mb_exp of
Just ty -> second mkCheckExpType <$> zonkTidyTcType env1 ty
Nothing -> return (env1, exp)
; (env3, m_thing') <- zonkTidyErrorThing env2 m_thing
; return ( env3, orig { uo_actual = act'
, uo_expected = exp'
, uo_thing = m_thing' }) }
zonkTidyOrigin env (KindEqOrigin ty1 m_ty2 orig t_or_k)
= do { (env1, ty1') <- zonkTidyTcType env ty1
; (env2, m_ty2') <- case m_ty2 of
Just ty2 -> second Just <$> zonkTidyTcType env1 ty2
Nothing -> return (env1, Nothing)
; (env3, orig') <- zonkTidyOrigin env2 orig
; return (env3, KindEqOrigin ty1' m_ty2' orig' t_or_k) }
zonkTidyOrigin env (FunDepOrigin1 p1 l1 p2 l2)
= do { (env1, p1') <- zonkTidyTcType env p1
; (env2, p2') <- zonkTidyTcType env1 p2
; return (env2, FunDepOrigin1 p1' l1 p2' l2) }
zonkTidyOrigin env (FunDepOrigin2 p1 o1 p2 l2)
= do { (env1, p1') <- zonkTidyTcType env p1
; (env2, p2') <- zonkTidyTcType env1 p2
; (env3, o1') <- zonkTidyOrigin env2 o1
; return (env3, FunDepOrigin2 p1' o1' p2' l2) }
zonkTidyOrigin env orig = return (env, orig)
zonkTidyErrorThing :: TidyEnv -> Maybe ErrorThing
-> TcM (TidyEnv, Maybe ErrorThing)
zonkTidyErrorThing env (Just (ErrorThing thing n_args zonker))
= do { (env', thing') <- zonker env thing
; return (env', Just $ ErrorThing thing' n_args zonker) }
zonkTidyErrorThing env Nothing
= return (env, Nothing)
----------------
tidyCt :: TidyEnv -> Ct -> Ct
-- Used only in error reporting
-- Also converts it to non-canonical
tidyCt env ct
= case ct of
CHoleCan { cc_ev = ev }
-> ct { cc_ev = tidy_ev env ev }
_ -> mkNonCanonical (tidy_ev env (ctEvidence ct))
where
tidy_ev :: TidyEnv -> CtEvidence -> CtEvidence
-- NB: we do not tidy the ctev_evar field because we don't
-- show it in error messages
tidy_ev env ctev@(CtGiven { ctev_pred = pred })
= ctev { ctev_pred = tidyType env pred }
tidy_ev env ctev@(CtWanted { ctev_pred = pred })
= ctev { ctev_pred = tidyType env pred }
tidy_ev env ctev@(CtDerived { ctev_pred = pred })
= ctev { ctev_pred = tidyType env pred }
----------------
tidyEvVar :: TidyEnv -> EvVar -> EvVar
tidyEvVar env var = setVarType var (tidyType env (varType var))
----------------
tidySkolemInfo :: TidyEnv -> SkolemInfo -> SkolemInfo
tidySkolemInfo env (DerivSkol ty) = DerivSkol (tidyType env ty)
tidySkolemInfo env (SigSkol cx ty) = SigSkol cx (mkCheckExpType $
tidyType env $
checkingExpType "tidySkolemInfo" ty)
tidySkolemInfo env (InferSkol ids) = InferSkol (mapSnd (tidyType env) ids)
tidySkolemInfo env (UnifyForAllSkol ty) = UnifyForAllSkol (tidyType env ty)
tidySkolemInfo _ info = info
| mcschroeder/ghc | compiler/typecheck/TcMType.hs | bsd-3-clause | 57,998 | 7 | 21 | 15,974 | 10,245 | 5,326 | 4,919 | -1 | -1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.AmountOfMoney.RU.Tests
( tests ) where
import Data.String
import Prelude
import Test.Tasty
import Duckling.AmountOfMoney.RU.Corpus
import Duckling.Dimensions.Types
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "RU Tests"
[ makeCorpusTest [Seal AmountOfMoney] corpus
]
| facebookincubator/duckling | tests/Duckling/AmountOfMoney/RU/Tests.hs | bsd-3-clause | 522 | 0 | 9 | 78 | 79 | 50 | 29 | 11 | 1 |
module Trace.Haptics.ShowTix (showtix_plugin) where
import qualified Data.Set as Set
import Trace.Haptics.Flags
import Trace.Haptics.Mix
import Trace.Haptics.Tix
showtix_options :: FlagOptSeq
showtix_options =
excludeOpt
. includeOpt
. srcDirOpt
. hpcDirOpt
. resetHpcDirsOpt
. outputOpt
. verbosityOpt
showtix_plugin :: Plugin
showtix_plugin =
Plugin
{ name = "show"
, usage = "[OPTION] .. <TIX_FILE> [<MODULE> [<MODULE> ..]]"
, options = showtix_options
, summary = "Show .tix file in readable, verbose format"
, implementation = showtix_main
, init_flags = default_flags
, final_flags = default_final_flags
}
showtix_main :: Flags -> [String] -> IO ()
showtix_main _ [] = hpcError showtix_plugin $ "no .tix file or executable name specified"
showtix_main flags (prog : modNames) = do
let hpcflags1 =
flags
{ includeMods =
Set.fromList modNames
`Set.union` includeMods flags
}
optTixs <- readTix (getTixFileName prog)
case optTixs of
Nothing -> hpcError showtix_plugin $ "could not read .tix file : " ++ prog
Just (Tix tixs) -> do
tixs_mixs <-
sequence
[ do
mix <- readMixWithFlags hpcflags1 (Right tix)
return $ (tix, mix)
| tix <- tixs
, allowModule hpcflags1 (tixModuleName tix)
]
let rjust n str = take (n - length str) (repeat ' ') ++ str
let ljust n str = str ++ take (n - length str) (repeat ' ')
sequence_
[ sequence_
[ putStrLn
(rjust 5 (show ix) ++ " "
++ rjust 10 (show count)
++ " "
++ ljust 20 modName
++ " "
++ rjust 20 (show pos)
++ " "
++ show lab)
| (count, ix, (pos, lab)) <- zip3 tixs' [(0 :: Int) ..] entries
]
| ( TixModule modName _hash1 _ tixs'
, Mix _file _timestamp _hash2 _tab entries
) <-
tixs_mixs
]
return ()
| Javran/haptics | src/Trace/Haptics/ShowTix.hs | bsd-3-clause | 2,089 | 0 | 28 | 724 | 592 | 306 | 286 | 61 | 2 |
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE QuantifiedConstraints #-}
-- | NamedStructure definition for sequences of bits.
--
-- This module provides the core data types and functions for
-- conversion of finite bit sequences from an to conventional (Haskell) data types.
--
-- Non-compressed, non-random finite bit sequences generated by programs are
-- usually compositions of bytes and multi byte words, and a ton of Haskell libraries
-- exist for the serialization and deserialization of ByteStrings.
--
-- This module allows the definition of a __structure__ i.e. a very simple grammar,
-- which allows functions in this library to read and write single bytes, words and bits.
--
-- Also complete bit sequence may be constructed or destructed from and to Haskell types.
--
-- Further more, the structures may contain dependent sub-sequences, for example to
-- express structures that precede a /length/ field before a repetitive block data.
--
-- Antother example for dependent sequences is /fields/ whose presence depends on
-- /flags/ preceding them.
--
-- This library is also designed with /zero copying/ in mind.
--
-- It should be emphasized that binary deserialization __is not__
-- to be confused with binary destructuring. While the former usually involves copying
-- all regular sub sequences from the input to a value of a certain type, the later
-- merely requires to peek into the sequeuence at a certain position and deserializing
-- a sub sequence. The starting position and the interpretation are governed by the
-- strucuture applied to the sequence.
module Data.Type.BitRecords.Core where
import Data.Int
import Data.Kind ( Type )
import Data.Kind.Extra
import Data.Proxy
import Data.Type.Pretty
import Data.Word
import Data.Bits
import GHC.TypeLits
import Text.Printf
import Data.Type.BitRecords.Builder.LazyByteStringBuilder
import Data.FunctionBuilder
import Data.Type.BitRecords.Builder.BitBuffer64
import Control.Category
import Prelude hiding ((.), id)
-- * Bit-Records
-- ** Bit-Record Type
-- data BitRec where
-- BRFields :: [(Symbol, Extends (BitRecordField t))] -> BitRec
-- | 'BitRecordField's assembly
data BitRecord where
EmptyBitRecord :: BitRecord
BRMemberT :: Symbol -> Extends (BitRecordField t) -> BitRecord
BitRecordMember :: Extends (BitRecordField t) -> BitRecord
MkRecordField :: Extends (BitField rt st size) -> BitRecord
BitRecordAppend :: BitRecord -> BitRecord -> BitRecord
-- TODO MissingBitRecord :: ErrorMessage -> BitRecord
-- | A conditional 'BitRecord'
type family WhenR (b :: Bool) (x :: BitRecord) :: BitRecord where
WhenR 'False r = 'EmptyBitRecord
WhenR 'True r = r
-- *** Basic Accessor
-- | Get the number of bits in a 'BitRecord'
type family SizeInBits (x :: k) :: Nat where
SizeInBits 'EmptyBitRecord = 0
SizeInBits ('BitRecordMember f) = FieldWidth f
SizeInBits ('MkRecordField f) = BitFieldSize (From f)
SizeInBits ('BitRecordAppend l r) = SizeInBits l + SizeInBits r
-- | For something to be augmented by a size field there must be an instance of
-- this family to generate the value of the size field, e.g. by counting the
-- elements.
type family SizeInBytes (c :: k) :: Nat
type instance SizeInBytes (f := v) = SizeInBytes v
type instance SizeInBytes (LabelF l f) = SizeInBytes f
type instance SizeInBytes (MkField (t :: BitField (rt:: Type) (st::k) (size::Nat))) = SizeInBytes t
type instance SizeInBytes (b :: BitRecord) = Bits2Bytes (SizeInBits b)
type Bits2Bytes (bitSize :: Nat) =
Bits2Bytes2 (Div bitSize 8) (Mod bitSize 8)
type family Bits2Bytes2 (bitSizeDiv8 :: Nat) (bitSizeMod8 :: Nat) :: Nat where
Bits2Bytes2 bytes 0 = bytes
Bits2Bytes2 bytes n = bytes + 1
type instance SizeInBytes (f :=. v) = SizeInBytes v
type instance SizeInBytes (Labelled l f) = SizeInBytes f
type instance SizeInBytes (t :: BitField (rt:: Type) (st::k) (size::Nat)) = size
-- | Get the total number of members in a record.
type family BitRecordMemberCount (b :: BitRecord) :: Nat where
BitRecordMemberCount 'EmptyBitRecord = 0
BitRecordMemberCount ('BitRecordMember f) = 1
BitRecordMemberCount ('MkRecordField f) = 1
BitRecordMemberCount ('BitRecordAppend l r) = BitRecordMemberCount l + BitRecordMemberCount r
-- | Get the size of the record.
getRecordSizeFromProxy
:: forall px (rec :: BitRecord)
. KnownNat (SizeInBits rec)
=> px rec
-> Integer
getRecordSizeFromProxy _ = natVal (Proxy :: Proxy (SizeInBits rec))
-- | Either use the value from @Just@ or return a 'EmptyBitRecord' value(types(kinds))
type OptionalRecordOf (f :: Extends (s -> Extends BitRecord)) (x :: Maybe s)
= (Optional (Konst 'EmptyBitRecord) f $ x :: Extends BitRecord)
-- ** Record composition
-- | Combine two 'BitRecord's to form a new 'BitRecord'. If the parameters are
-- not of type 'BitRecord' they will be converted.
type (:+:) (l :: BitRecord) (r :: BitRecord) = ((l `Append` r) :: BitRecord)
infixl 3 :+:
type family Append (l :: BitRecord) (r :: BitRecord) :: BitRecord where
Append l 'EmptyBitRecord = l
Append 'EmptyBitRecord r = r
Append l r = 'BitRecordAppend l r
-- | Append a 'BitRecord' and a 'BitRecordField'
type (:+.) (r :: BitRecord) (f :: Extends (BitRecordField t1))
= Append r ( 'BitRecordMember f)
infixl 6 :+.
-- | Append a 'BitRecordField' and a 'BitRecord'
type (.+:) (f :: Extends (BitRecordField t1)) (r :: BitRecord)
= Append ( 'BitRecordMember f) r
infixr 6 .+:
-- | Append a 'BitRecordField' and a 'BitRecordField' forming a 'BitRecord' with
-- two members.
type (.+.) (l :: Extends (BitRecordField t1)) (r :: Extends (BitRecordField t2))
= Append ( 'BitRecordMember l) ( 'BitRecordMember r)
infixr 6 .+.
-- | Set a field to either a static value or a runtime value.
type family (:~)
(field :: Extends (BitRecordField (t :: BitField (rt :: Type) (st :: k) (len :: Nat))))
(value :: Extends (FieldValue (label :: Symbol) st))
:: Extends (BitRecordField t) where
fld :~ StaticFieldValue l v = (l @: fld) := v
fld :~ RuntimeFieldValue l = l @: fld
infixl 7 :~
-- -- | Like ':~' but for a 'Maybe' parameter. In case of 'Just' it behaves like ':~'
-- -- in case of 'Nothing' it return an 'EmptyBitRecord'.
-- type family (:~?)
-- (fld :: Extends (BitRecordField (t :: BitField (rt :: Type) (st :: k) (len :: Nat))))
-- (value :: Maybe (Extends (FieldValue (label :: Symbol) st)))
-- :: Extends BitRecord where
-- fld :~? ('Just v) = RecordField (fld :~ v)
-- fld :~? 'Nothing = Konst 'EmptyBitRecord
-- infixl 7 :~?
-- | Like ':~' but for a 'Maybe' parameter. In case of 'Just' it behaves like ':~'
-- in case of 'Nothing' it return an 'EmptyBitRecord'.
type family (:+?)
(fld :: Extends (BitRecordField (t :: BitField (rt :: Type) (st :: k) (len :: Nat))))
(value :: Maybe (Extends (FieldValue (label :: Symbol) st)))
:: BitRecord where
fld :+? ('Just v) = 'BitRecordMember (fld :~ v)
fld :+? 'Nothing = 'EmptyBitRecord
infixl 7 :+?
-- | The field value parameter for ':~', either a static, compile time, value or
-- a dynamic, runtime value.
data FieldValue :: Symbol -> staticRep -> Type
data StaticFieldValue (label :: Symbol) :: staticRep -> Extends (FieldValue label staticRep)
data RuntimeFieldValue (label :: Symbol) :: Extends (FieldValue label staticRep)
-- *** Record Arrays and Repitition
-- | An array of records with a fixed number of elements, NOTE: this type is
-- actually not really necessary since 'ReplicateRecord' exists, but this allows
-- to have a different 'showRecord' output.
data RecArray :: BitRecord -> Nat -> Extends BitRecord
type r ^^ n = RecArray r n
infixl 5 ^^
type instance From (RecArray (r :: BitRecord) n ) = RecArrayToBitRecord r n
-- | Repeat a bit record @n@ times.
type family RecArrayToBitRecord (r :: BitRecord) (n :: Nat) :: BitRecord where
RecArrayToBitRecord r 0 = 'EmptyBitRecord
RecArrayToBitRecord r 1 = r
RecArrayToBitRecord r n = Append r (RecArrayToBitRecord r (n - 1))
-- *** Lists of Records
-- | Let type level lists also be records
data
BitRecordOfList
(f :: Extends (foo -> BitRecord))
(xs :: [foo])
:: Extends BitRecord
type instance From (BitRecordOfList f xs) =
FoldMap BitRecordAppendFun 'EmptyBitRecord f xs
type BitRecordAppendFun = Fun1 BitRecordAppendFun_
data BitRecordAppendFun_ :: BitRecord -> Extends (BitRecord -> BitRecord)
type instance Apply (BitRecordAppendFun_ l) r = Append l r
-- *** Maybe Record
-- | Either use the value from @Just@ or return a 'EmptyBitRecord' value(types(kinds))
data OptionalRecord :: Maybe BitRecord -> Extends BitRecord
type instance From (OptionalRecord ('Just t)) = t
type instance From (OptionalRecord 'Nothing) = 'EmptyBitRecord
-- ** Field ADT
-- | A family of bit fields.
--
-- A bit field always has a size, i.e. the number of bits it uses, as well as a
-- term level value type and a type level value type. It also has an optional
-- label, and an optional value assigned to it.
data BitRecordField :: BitField rt st len -> Type
-- | A bit record field with a number of bits
data MkField (t :: BitField rt st len) :: Extends (BitRecordField t)
-- **** Setting a Label
-- | A bit record field with a number of bits
data LabelF :: Symbol -> Extends (BitRecordField t) -> Extends (BitRecordField t)
-- | A field with a label assigned to it.
type (l :: Symbol) @: (f :: Extends
(BitRecordField (t :: BitField rt (st :: stk) size)))
= (LabelF l f :: Extends (BitRecordField t))
infixr 8 @:
-- | A field with a label assigned to it.
type (l :: Symbol) @:: (f :: Extends a) = Labelled l f
infixr 8 @::
-- **** Assignment
-- | A field with a value set at compile time.
data (:=) :: forall rt st size (t :: BitField rt st size) .
Extends (BitRecordField t)
-> st
-> Extends (BitRecordField t)
infixl 7 :=
-- | A field with a value set at compile time.
data (:=.) :: Extends (BitField rt st size)
-> st
-> Extends (BitField rt st size)
infixl 7 :=.
-- | Types of this kind define the basic type of a 'BitRecordField'. Sure, this
-- could have been an open type, but really, how many actual useful field types
-- exist? Well, from a global perspective, uncountable infinite, but the focus
-- of this library is to blast out bits over the network, using usual Haskell
-- libraries, and hence, there is actually only very little reason to
-- differentiate types of record fields, other than what low-level library
-- function to apply and how to pretty print the field.
data BitField
(runtimeRep :: Type)
(staticRep :: k)
(bitCount :: Nat)
where
MkFieldFlag ::BitField Bool Bool 1
MkFieldBits :: (forall (n :: Nat) . BitField (B n) Nat n)
MkFieldBitsXXL :: (forall (n :: Nat) . BitField Integer Nat n)
MkFieldU8 ::BitField Word8 Nat 8
MkFieldU16 ::BitField Word16 Nat 16
MkFieldU32 ::BitField Word32 Nat 32
MkFieldU64 ::BitField Word64 Nat 64
MkFieldI8 ::BitField Int8 SignedNat 8
MkFieldI16 ::BitField Int16 SignedNat 16
MkFieldI32 ::BitField Int32 SignedNat 32
MkFieldI64 ::BitField Int64 SignedNat 64
-- TODO refactor this MkFieldCustom, it caused a lot of trouble!
MkFieldCustom ::BitField rt st n
type family BitFieldSize (b :: BitField rt st size) :: Nat where
BitFieldSize (b :: BitField rt st size) = size
type Flag = MkField 'MkFieldFlag
type Field n = MkField ( 'MkFieldBits :: BitField (B n) Nat n)
type FieldU8 = MkField 'MkFieldU8
type FieldU16 = MkField 'MkFieldU16
type FieldU32 = MkField 'MkFieldU32
type FieldU64 = MkField 'MkFieldU64
type FieldI8 = MkField 'MkFieldI8
type FieldI16 = MkField 'MkFieldI16
type FieldI32 = MkField 'MkFieldI32
type FieldI64 = MkField 'MkFieldI64
-- | A data type for 'Field' and 'MkFieldBits', that is internally a 'Word64'.
-- It carries the number of relevant bits in its type.
newtype B (size :: Nat) = B {unB :: Word64}
deriving (Read,Show,Num,Integral,Bits,FiniteBits,Eq,Ord,Bounded,Enum,Real)
instance (PrintfArg Word64, n <= 64) => PrintfArg (B n) where
formatArg (B x) = formatArg x
parseFormat (B x) = parseFormat x
-- | A signed field value.
data SignedNat where
PositiveNat ::Nat -> SignedNat
NegativeNat ::Nat -> SignedNat
-- *** Composed Fields
-- | A Flag (1-bit) that is true if the type level maybe is 'Just'.
type family FlagJust (a :: Maybe (v :: Type)) :: Extends (BitRecordField 'MkFieldFlag) where
FlagJust ('Just x) = Flag := 'True
FlagJust 'Nothing = Flag := 'False
-- | A Flag (1-bit) that is true if the type level maybe is 'Nothing'.
type family FlagNothing (a :: Maybe (v :: Type)) :: Extends (BitRecordField 'MkFieldFlag) where
FlagNothing ('Just x) = Flag := 'False
FlagNothing 'Nothing = Flag := 'True
-- | A 'BitRecordField' can be used as 'BitRecordMember'
data RecordField :: Extends (BitRecordField t) -> Extends BitRecord
type instance From (RecordField f) = 'BitRecordMember f
-- | Calculate the size as a number of bits from a 'BitRecordField'
type family FieldWidth (x :: Extends (BitRecordField t)) where
FieldWidth (x :: Extends (BitRecordField (t :: BitField rt st size))) = size
-- * Field and Record PrettyType Instances
-- | Render @rec@ to a pretty, human readable form. Internally this is a wrapper
-- around 'ptShow' using 'PrettyRecord'.
showARecord
:: forall proxy (rec :: Extends BitRecord)
. PrettyTypeShow (PrettyRecord (From rec))
=> proxy rec
-> String
showARecord _ = showPretty (Proxy :: Proxy (PrettyRecord (From rec)))
-- | Render @rec@ to a pretty, human readable form. Internally this is a wrapper
-- around 'ptShow' using 'PrettyRecord'.
showRecord
:: forall proxy (rec :: BitRecord)
. PrettyTypeShow (PrettyRecord rec)
=> proxy rec
-> String
showRecord _ = showPretty (Proxy :: Proxy (PrettyRecord rec))
type instance ToPretty (rec :: BitRecord) = PrettyRecord rec
type family PrettyRecord (rec :: BitRecord) :: PrettyType where
PrettyRecord ('BitRecordMember m) = PrettyField m
PrettyRecord ('MkRecordField m) = PrettyRecordField m
PrettyRecord ' EmptyBitRecord = 'PrettyNewline
PrettyRecord ('BitRecordAppend l r) = PrettyRecord l <$$> PrettyRecord r
type instance ToPretty (f :: Extends (BitRecordField t)) = PrettyField f
type family PrettyRecordField (f :: Extends (BitField (rt :: Type) (st :: Type) (size :: Nat))) :: PrettyType where
PrettyRecordField (Konst t) = PrettyFieldType t
PrettyRecordField (f :=. v) =
PrettyRecordField f <+> PutStr ":=" <+> PrettyFieldValue (From f) v
PrettyRecordField (Labelled l f) = l <:> PrettyRecordField f
type family PrettyField (f :: Extends (BitRecordField (t :: BitField (rt :: Type) (st :: Type) (size :: Nat)))) :: PrettyType where
PrettyField (MkField t) = PrettyFieldType t
PrettyField ((f :: Extends (BitRecordField t)) := v) =
PrettyField f <+> PutStr ":=" <+> PrettyFieldValue t v
PrettyField (LabelF l f) = l <:> PrettyField f
type family PrettyFieldType (t :: BitField (rt :: Type) (st :: Type) (size :: Nat)) :: PrettyType where
PrettyFieldType 'MkFieldFlag = PutStr "boolean"
PrettyFieldType ('MkFieldBits :: BitField (B (s :: Nat)) Nat s) = PutStr "bits" <++> PrettyParens (PutNat s)
PrettyFieldType ('MkFieldBitsXXL :: BitField Integer Nat (s :: Nat)) = PutStr "bits-XXL" <++> PrettyParens (PutNat s)
PrettyFieldType 'MkFieldU64 = PutStr "U64"
PrettyFieldType 'MkFieldU32 = PutStr "U32"
PrettyFieldType 'MkFieldU16 = PutStr "U16"
PrettyFieldType 'MkFieldU8 = PutStr "U8"
PrettyFieldType 'MkFieldI64 = PutStr "I64"
PrettyFieldType 'MkFieldI32 = PutStr "I32"
PrettyFieldType 'MkFieldI16 = PutStr "I16"
PrettyFieldType 'MkFieldI8 = PutStr "I8"
PrettyFieldType ('MkFieldCustom :: BitField rt ct size) = ToPretty rt <++> PrettyParens (PutNat size)
type family PrettyFieldValue (t :: BitField (rt :: Type) (st :: Type) (size :: Nat)) (v :: st) :: PrettyType where
PrettyFieldValue 'MkFieldFlag 'True = PutStr "yes"
PrettyFieldValue 'MkFieldFlag 'False = PutStr "no"
PrettyFieldValue ('MkFieldBits :: BitField (B (s :: Nat)) Nat s) v =
'PrettyNat 'PrettyUnpadded ('PrettyPrecision s) 'PrettyBit v <+> PrettyParens (("hex" <:> PutHex v) <+> ("dec" <:> PutNat v))
PrettyFieldValue 'MkFieldU8 v = ("hex" <:> PutHex8 v) <+> PrettyParens ("dec" <:> PutNat v)
PrettyFieldValue 'MkFieldU16 v = ("hex" <:> PutHex16 v) <+> PrettyParens ("dec" <:> PutNat v)
PrettyFieldValue 'MkFieldU32 v = ("hex" <:> PutHex32 v) <+> PrettyParens ("dec" <:> PutNat v)
PrettyFieldValue 'MkFieldU64 v = ("hex" <:> PutHex64 v) <+> PrettyParens ("dec" <:> PutNat v)
PrettyFieldValue 'MkFieldI8 ('PositiveNat v) = ("hex" <:> (PutStr "+" <++> PutHex8 v)) <+> PrettyParens ("dec" <:> (PutStr "+" <++> PutNat v))
PrettyFieldValue 'MkFieldI16 ('PositiveNat v) = ("hex" <:> (PutStr "+" <++> PutHex16 v)) <+> PrettyParens ("dec" <:> (PutStr "+" <++> PutNat v))
PrettyFieldValue 'MkFieldI32 ('PositiveNat v) = ("hex" <:> (PutStr "+" <++> PutHex32 v)) <+> PrettyParens ("dec" <:> (PutStr "+" <++> PutNat v))
PrettyFieldValue 'MkFieldI64 ('PositiveNat v) = ("hex" <:> (PutStr "+" <++> PutHex64 v)) <+> PrettyParens ("dec" <:> (PutStr "+" <++> PutNat v))
PrettyFieldValue 'MkFieldI8 ('NegativeNat v) = ("hex" <:> (PutStr "-" <++> PutHex8 v)) <+> PrettyParens ("dec" <:> (PutStr "-" <++> PutNat v))
PrettyFieldValue 'MkFieldI16 ('NegativeNat v) = ("hex" <:> (PutStr "-" <++> PutHex16 v)) <+> PrettyParens ("dec" <:> (PutStr "-" <++> PutNat v))
PrettyFieldValue 'MkFieldI32 ('NegativeNat v) = ("hex" <:> (PutStr "-" <++> PutHex32 v)) <+> PrettyParens ("dec" <:> (PutStr "-" <++> PutNat v))
PrettyFieldValue 'MkFieldI64 ('NegativeNat v) = ("hex" <:> (PutStr "-" <++> PutHex64 v)) <+> PrettyParens ("dec" <:> (PutStr "-" <++> PutNat v))
PrettyFieldValue ('MkFieldCustom :: BitField rt ct size) v = PrettyCustomFieldValue rt ct size v
type family PrettyCustomFieldValue (rt :: Type) (st :: Type) (size :: Nat) (v :: st) :: PrettyType
type family PrintHexIfPossible t (s :: Nat) :: PrettyType where
PrintHexIfPossible Word64 s = PutHex64 s
PrintHexIfPossible Word32 s = PutHex32 s
PrintHexIfPossible Word16 s = PutHex16 s
PrintHexIfPossible Word8 s = PutHex8 s
PrintHexIfPossible x s = TypeError ('Text "Invalid size field type: " ':<>: 'ShowType x)
-- * Binary serialization
-- *** BitFields
instance
forall rt st s (nested :: BitField rt st s) .
( HasFunctionBuilder BitBuilder (Proxy nested) )
=> HasFunctionBuilder BitBuilder (Proxy (Konst nested)) where
type ToFunction BitBuilder (Proxy (Konst nested)) a =
ToFunction BitBuilder (Proxy nested) a
toFunctionBuilder _ = toFunctionBuilder (Proxy @nested)
instance
forall rt st s (nested :: BitField rt st s) .
( DynamicContent BitBuilder (Proxy nested) rt )
=> DynamicContent BitBuilder (Proxy (Konst nested)) rt where
addParameter _ = addParameter (Proxy @nested)
-- -- *** Labbeled Fields
instance
forall nested l .
( HasFunctionBuilder BitBuilder (Proxy nested) )
=> HasFunctionBuilder BitBuilder (Proxy (LabelF l nested)) where
type ToFunction BitBuilder (Proxy (LabelF l nested)) a =
ToFunction BitBuilder (Proxy nested) a
toFunctionBuilder _ = toFunctionBuilder (Proxy @nested)
instance ( DynamicContent BitBuilder (Proxy nested) b )
=> DynamicContent BitBuilder (Proxy (LabelF l nested)) b where
addParameter _ = addParameter (Proxy @nested)
instance
forall rt st s (nested :: Extends (BitField rt st s)) l .
( HasFunctionBuilder BitBuilder (Proxy nested) )
=> HasFunctionBuilder BitBuilder (Proxy (Labelled l nested)) where
type ToFunction BitBuilder (Proxy (Labelled l nested)) a =
ToFunction BitBuilder (Proxy nested) a
toFunctionBuilder _ = toFunctionBuilder (Proxy @nested)
instance
forall rt st s (nested :: Extends (BitField rt st s)) (l :: Symbol) .
( DynamicContent BitBuilder (Proxy nested) rt )
=> DynamicContent BitBuilder (Proxy (Labelled l nested)) rt where
addParameter _ = addParameter (Proxy @nested)
-- -- **** Bool
instance forall f . (FieldWidth f ~ 1) =>
HasFunctionBuilder BitBuilder (Proxy (f := 'True)) where
toFunctionBuilder _ = immediate (appendBitBuffer64 (bitBuffer64 1 1))
instance forall f . (FieldWidth f ~ 1) =>
HasFunctionBuilder BitBuilder (Proxy (f := 'False)) where
toFunctionBuilder _ = immediate (appendBitBuffer64 (bitBuffer64 1 0))
instance HasFunctionBuilder BitBuilder (Proxy (MkField 'MkFieldFlag)) where
type ToFunction BitBuilder (Proxy (MkField 'MkFieldFlag)) a = Bool -> a
toFunctionBuilder _ =
deferred (appendBitBuffer64 . bitBuffer64 1 . (\ !t -> if t then 1 else 0))
-- -- new:
instance forall f . (BitFieldSize (From f) ~ 1) =>
HasFunctionBuilder BitBuilder (Proxy (f :=. 'True)) where
toFunctionBuilder _ = immediate (appendBitBuffer64 (bitBuffer64 1 1))
instance forall f . (BitFieldSize (From f) ~ 1) =>
HasFunctionBuilder BitBuilder (Proxy (f :=. 'False)) where
toFunctionBuilder _ = immediate (appendBitBuffer64 (bitBuffer64 1 0))
instance HasFunctionBuilder BitBuilder (Proxy 'MkFieldFlag) where
type ToFunction BitBuilder (Proxy 'MkFieldFlag) a = Bool -> a
toFunctionBuilder _ =
deferred (appendBitBuffer64 . bitBuffer64 1 . (\ !t -> if t then 1 else 0))
instance DynamicContent BitBuilder (Proxy 'MkFieldFlag) Bool where
addParameter = toFunctionBuilder
-- -- **** Bits
instance forall (s :: Nat) . (KnownBufferSize s) =>
HasFunctionBuilder BitBuilder (Proxy (MkField ('MkFieldBits :: BitField (B s) Nat s))) where
type ToFunction BitBuilder (Proxy (MkField ('MkFieldBits :: BitField (B s) Nat s))) a = B s -> a
toFunctionBuilder _ = deferred (appendBitBuffer64 . bitBuffer64ProxyLength (Proxy @s) . unB)
instance forall (s :: Nat) . (KnownBufferSize s) =>
DynamicContent BitBuilder (Proxy (MkField ('MkFieldBits :: BitField (B s) Nat s))) (B s) where
addParameter = toFunctionBuilder
-- -- **** Naturals
instance
HasFunctionBuilder BitBuilder (Proxy (MkField 'MkFieldU64)) where
type ToFunction BitBuilder (Proxy (MkField 'MkFieldU64)) a = Word64 -> a
toFunctionBuilder _ = deferred (appendBitBuffer64 . bitBuffer64 64)
instance
DynamicContent BitBuilder (Proxy (MkField 'MkFieldU64)) Word64 where
addParameter = toFunctionBuilder
instance
HasFunctionBuilder BitBuilder (Proxy (MkField 'MkFieldU32)) where
type ToFunction BitBuilder (Proxy (MkField 'MkFieldU32)) a = Word32 -> a
toFunctionBuilder _ = deferred (appendBitBuffer64 . bitBuffer64 32 . fromIntegral)
instance
DynamicContent BitBuilder (Proxy (MkField ('MkFieldU32:: BitField Word32 Nat 32))) Word32 where
addParameter = toFunctionBuilder
instance
HasFunctionBuilder BitBuilder (Proxy 'MkFieldU32) where
type ToFunction BitBuilder (Proxy 'MkFieldU32) a = Word32 -> a
toFunctionBuilder _ = deferred (appendBitBuffer64 . bitBuffer64 32 . fromIntegral)
instance
DynamicContent BitBuilder (Proxy 'MkFieldU32) Word32 where
addParameter = toFunctionBuilder
instance
HasFunctionBuilder BitBuilder (Proxy (MkField 'MkFieldU16)) where
type ToFunction BitBuilder (Proxy (MkField 'MkFieldU16)) a = Word16 -> a
toFunctionBuilder _ = deferred (appendBitBuffer64 . bitBuffer64 16 . fromIntegral)
instance
DynamicContent BitBuilder (Proxy (MkField 'MkFieldU16)) Word16 where
addParameter = toFunctionBuilder
instance
HasFunctionBuilder BitBuilder (Proxy (MkField 'MkFieldU8)) where
type ToFunction BitBuilder (Proxy (MkField 'MkFieldU8)) a = Word8 -> a
toFunctionBuilder _ = deferred (appendBitBuffer64 . bitBuffer64 8 . fromIntegral)
instance
DynamicContent BitBuilder (Proxy (MkField 'MkFieldU8)) Word8 where
addParameter = toFunctionBuilder
-- -- **** Signed
instance
HasFunctionBuilder BitBuilder (Proxy (MkField 'MkFieldI64)) where
type ToFunction BitBuilder (Proxy (MkField 'MkFieldI64)) a = Int64 -> a
toFunctionBuilder _ = deferred (appendBitBuffer64 . bitBuffer64 64 . fromIntegral @Int64 @Word64)
instance
DynamicContent BitBuilder (Proxy (MkField 'MkFieldI64)) Int64 where
addParameter = toFunctionBuilder
instance
HasFunctionBuilder BitBuilder (Proxy (MkField 'MkFieldI32)) where
type ToFunction BitBuilder (Proxy (MkField 'MkFieldI32)) a = Int32 -> a
toFunctionBuilder _ = deferred (appendBitBuffer64 . bitBuffer64 32 . fromIntegral . fromIntegral @Int32 @Word32)
instance
DynamicContent BitBuilder (Proxy (MkField 'MkFieldI32)) Int32 where
addParameter = toFunctionBuilder
instance
HasFunctionBuilder BitBuilder (Proxy (MkField 'MkFieldI16)) where
type ToFunction BitBuilder (Proxy (MkField 'MkFieldI16)) a = Int16 -> a
toFunctionBuilder _ = deferred (appendBitBuffer64 . bitBuffer64 16 . fromIntegral . fromIntegral @Int16 @Word16)
instance
DynamicContent BitBuilder (Proxy (MkField 'MkFieldI16)) Int16 where
addParameter = toFunctionBuilder
instance
HasFunctionBuilder BitBuilder (Proxy (MkField 'MkFieldI8)) where
type ToFunction BitBuilder (Proxy (MkField 'MkFieldI8)) a = Int8 -> a
toFunctionBuilder _ = deferred (appendBitBuffer64 . bitBuffer64 8 . fromIntegral . fromIntegral @Int8 @Word8)
instance
DynamicContent BitBuilder (Proxy (MkField 'MkFieldI8)) Int8 where
addParameter = toFunctionBuilder
-- *** Assign static values
instance
forall
rt
(len :: Nat)
(t :: BitField rt Nat len)
(f :: Extends (BitRecordField t))
(v :: Nat)
.
( KnownNat v
, DynamicContent BitBuilder (Proxy f) rt
, Num rt
)
=> HasFunctionBuilder BitBuilder (Proxy (f := v)) where
toFunctionBuilder _ =
fillParameter (addParameter (Proxy @f)) (fromIntegral (natVal (Proxy @v)))
instance forall v f x . (KnownNat v, DynamicContent BitBuilder (Proxy f) x, Num x) =>
HasFunctionBuilder BitBuilder (Proxy (f := 'PositiveNat v)) where
toFunctionBuilder _ =
fillParameter (addParameter (Proxy @f)) (fromIntegral (natVal (Proxy @v)))
instance forall v f x . (KnownNat v, DynamicContent BitBuilder (Proxy f) x, Num x) =>
HasFunctionBuilder BitBuilder (Proxy (f := 'NegativeNat v)) where
toFunctionBuilder _ = fillParameter (addParameter (Proxy @f)) (fromIntegral (-1 * natVal (Proxy @v)))
-- new:
instance
forall rt (len :: Nat) (f :: Extends (BitField rt Nat len)) (v :: Nat) .
( KnownNat v
, DynamicContent BitBuilder (Proxy f) rt
, Num rt)
=>
HasFunctionBuilder BitBuilder (Proxy (f :=. v)) where
toFunctionBuilder _ =
fillParameter
(addParameter (Proxy @f))
(fromIntegral (natVal (Proxy @v)))
-- -- instance forall v f a x . (KnownNat v, HasFunctionBuilder BitBuilder (Proxy f) a, ToFunction BitBuilder (Proxy f) a ~ (x -> a), Num x) =>
-- -- HasFunctionBuilder BitBuilder (Proxy (f := ('PositiveNat v))) a where
-- -- toFunctionBuilder _ = fillParameter (toFunctionBuilder (Proxy @f)) (fromIntegral (natVal (Proxy @v)))
--
--
-- -- instance forall v f a x . (KnownNat v, HasFunctionBuilder BitBuilder (Proxy f) a, ToFunction BitBuilder (Proxy f) a ~ (x -> a), Num x) =>
-- -- HasFunctionBuilder BitBuilder (Proxy (f := ('NegativeNat v))) a where
-- -- toFunctionBuilder _ = fillParameter (toFunctionBuilder (Proxy @f)) (fromIntegral (-1 * (natVal (Proxy @v))))
-- ** 'BitRecord' instances
instance forall (r :: Extends BitRecord) . HasFunctionBuilder BitBuilder (Proxy (From r)) =>
HasFunctionBuilder BitBuilder (Proxy r) where
type ToFunction BitBuilder (Proxy r) a =
ToFunction BitBuilder (Proxy (From r)) a
toFunctionBuilder _ = toFunctionBuilder (Proxy @(From r))
-- *** 'BitRecordMember'
instance forall f . HasFunctionBuilder BitBuilder (Proxy f) => HasFunctionBuilder BitBuilder (Proxy ('BitRecordMember f)) where
type ToFunction BitBuilder (Proxy ('BitRecordMember f)) a = ToFunction BitBuilder (Proxy f) a
toFunctionBuilder _ = toFunctionBuilder (Proxy @f)
-- *** 'RecordField'
instance forall f . HasFunctionBuilder BitBuilder (Proxy f)
=> HasFunctionBuilder BitBuilder (Proxy ('MkRecordField f)) where
type ToFunction BitBuilder (Proxy ('MkRecordField f)) a =
ToFunction BitBuilder (Proxy f) a
toFunctionBuilder _ = toFunctionBuilder (Proxy @f)
-- *** 'AppendedBitRecords'
instance forall l r .
(HasFunctionBuilder BitBuilder (Proxy l), HasFunctionBuilder BitBuilder (Proxy r))
=> HasFunctionBuilder BitBuilder (Proxy ('BitRecordAppend l r)) where
type ToFunction BitBuilder (Proxy ('BitRecordAppend l r)) a =
ToFunction BitBuilder (Proxy l) (ToFunction BitBuilder (Proxy r) a)
toFunctionBuilder _ = toFunctionBuilder (Proxy @l) . toFunctionBuilder (Proxy @r)
-- *** 'EmptyBitRecord' and '...Pretty'
instance HasFunctionBuilder BitBuilder (Proxy 'EmptyBitRecord) where
toFunctionBuilder _ = id
| sheyll/isobmff-builder | src/Data/Type/BitRecords/Core.hs | bsd-3-clause | 28,864 | 16 | 14 | 5,338 | 8,238 | 4,409 | 3,829 | -1 | -1 |
module Pos.Core.NetworkAddress
( NetworkAddress
, localhost
, addrParser
, addrParserNoWildcard
) where
import Universum
import qualified Data.ByteString.Char8 as BS8
import qualified Serokell.Util.Parse as P
-- We should really be using Megaparsec here instead of Parsec, but that
-- requires 'Serokell.Util.Parse' to be modified to use Parsec and then
-- have that dependency bubble up.
import Text.Megaparsec (ParsecT)
import qualified Text.Megaparsec as P
import qualified Text.Megaparsec.Char as P
-- | @"127.0.0.1"@.
localhost :: ByteString
localhost = "127.0.0.1"
-- | Full node address.
type NetworkAddress = (ByteString, Word16)
-- | Parsed for network address in format @host:port@.
addrParser :: ParsecT () String m NetworkAddress
addrParser = (,) <$> (encodeUtf8 <$> P.host) <*> (P.char ':' *> P.port) <* P.eof
-- | Parses an IPv4 NetworkAddress where the host is not 0.0.0.0.
addrParserNoWildcard :: ParsecT () String m NetworkAddress
addrParserNoWildcard = do
(host, port) <- addrParser
if host == BS8.pack "0.0.0.0" then empty
else return (host, port)
| input-output-hk/pos-haskell-prototype | core/src/Pos/Core/NetworkAddress.hs | mit | 1,141 | 0 | 10 | 227 | 222 | 135 | 87 | 21 | 2 |
{-# LANGUAGE DeriveAnyClass #-}
module Commands.Plugins.Spiros.Act.Types where
import Commands.Plugins.Spiros.Extra.Types
import Commands.Plugins.Spiros.Edit
import Commands.Backends.Workflow (KeySequence)
data Acts
= ActsRW Int Act -- ^ repeated read/write actions
deriving (Show,Read,Eq,Ord,Generic,Data,NFData)
data Act
= KeyRiff_ KeySequence
--TODO | Click_ Click
| Edit_ Edit
| Move_ Move
deriving (Show,Read,Eq,Ord,Generic,Data,NFData)
{-old
data Acts
= ActRW Int Act -- ^ actions can be chained (RW means read/write)
| ActRO Act -- ^ idempotent(ish) actions don't need immediate repetition (RO means read-in only) .
-}
| sboosali/commands-spiros | config/Commands/Plugins/Spiros/Act/Types.hs | gpl-2.0 | 671 | 0 | 6 | 122 | 131 | 78 | 53 | 13 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.SWF.CountPendingDecisionTasks
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Returns the estimated number of decision tasks in the specified task list.
-- The count returned is an approximation and is not guaranteed to be exact. If
-- you specify a task list that no decision task was ever scheduled in then 0
-- will be returned.
--
-- Access Control
--
-- You can use IAM policies to control this action's access to Amazon SWF
-- resources as follows:
--
-- Use a 'Resource' element with the domain name to limit the action to only
-- specified domains. Use an 'Action' element to allow or deny permission to call
-- this action. Constrain the 'taskList.name' parameter by using a Condition
-- element with the 'swf:taskList.name' key to allow the action to access only
-- certain task lists. If the caller does not have sufficient permissions to
-- invoke the action, or the parameter values fall outside the specified
-- constraints, the action fails. The associated event attribute's cause
-- parameter will be set to OPERATION_NOT_PERMITTED. For details and example IAM
-- policies, see <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to Amazon SWF Workflows>.
--
-- <http://docs.aws.amazon.com/amazonswf/latest/apireference/API_CountPendingDecisionTasks.html>
module Network.AWS.SWF.CountPendingDecisionTasks
(
-- * Request
CountPendingDecisionTasks
-- ** Request constructor
, countPendingDecisionTasks
-- ** Request lenses
, cpdtDomain
, cpdtTaskList
-- * Response
, CountPendingDecisionTasksResponse
-- ** Response constructor
, countPendingDecisionTasksResponse
-- ** Response lenses
, cpdtrCount
, cpdtrTruncated
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.SWF.Types
import qualified GHC.Exts
data CountPendingDecisionTasks = CountPendingDecisionTasks
{ _cpdtDomain :: Text
, _cpdtTaskList :: TaskList
} deriving (Eq, Read, Show)
-- | 'CountPendingDecisionTasks' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'cpdtDomain' @::@ 'Text'
--
-- * 'cpdtTaskList' @::@ 'TaskList'
--
countPendingDecisionTasks :: Text -- ^ 'cpdtDomain'
-> TaskList -- ^ 'cpdtTaskList'
-> CountPendingDecisionTasks
countPendingDecisionTasks p1 p2 = CountPendingDecisionTasks
{ _cpdtDomain = p1
, _cpdtTaskList = p2
}
-- | The name of the domain that contains the task list.
cpdtDomain :: Lens' CountPendingDecisionTasks Text
cpdtDomain = lens _cpdtDomain (\s a -> s { _cpdtDomain = a })
-- | The name of the task list.
cpdtTaskList :: Lens' CountPendingDecisionTasks TaskList
cpdtTaskList = lens _cpdtTaskList (\s a -> s { _cpdtTaskList = a })
data CountPendingDecisionTasksResponse = CountPendingDecisionTasksResponse
{ _cpdtrCount :: Nat
, _cpdtrTruncated :: Maybe Bool
} deriving (Eq, Ord, Read, Show)
-- | 'CountPendingDecisionTasksResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'cpdtrCount' @::@ 'Natural'
--
-- * 'cpdtrTruncated' @::@ 'Maybe' 'Bool'
--
countPendingDecisionTasksResponse :: Natural -- ^ 'cpdtrCount'
-> CountPendingDecisionTasksResponse
countPendingDecisionTasksResponse p1 = CountPendingDecisionTasksResponse
{ _cpdtrCount = withIso _Nat (const id) p1
, _cpdtrTruncated = Nothing
}
-- | The number of tasks in the task list.
cpdtrCount :: Lens' CountPendingDecisionTasksResponse Natural
cpdtrCount = lens _cpdtrCount (\s a -> s { _cpdtrCount = a }) . _Nat
-- | If set to true, indicates that the actual count was more than the maximum
-- supported by this API and the count returned is the truncated value.
cpdtrTruncated :: Lens' CountPendingDecisionTasksResponse (Maybe Bool)
cpdtrTruncated = lens _cpdtrTruncated (\s a -> s { _cpdtrTruncated = a })
instance ToPath CountPendingDecisionTasks where
toPath = const "/"
instance ToQuery CountPendingDecisionTasks where
toQuery = const mempty
instance ToHeaders CountPendingDecisionTasks
instance ToJSON CountPendingDecisionTasks where
toJSON CountPendingDecisionTasks{..} = object
[ "domain" .= _cpdtDomain
, "taskList" .= _cpdtTaskList
]
instance AWSRequest CountPendingDecisionTasks where
type Sv CountPendingDecisionTasks = SWF
type Rs CountPendingDecisionTasks = CountPendingDecisionTasksResponse
request = post "CountPendingDecisionTasks"
response = jsonResponse
instance FromJSON CountPendingDecisionTasksResponse where
parseJSON = withObject "CountPendingDecisionTasksResponse" $ \o -> CountPendingDecisionTasksResponse
<$> o .: "count"
<*> o .:? "truncated"
| romanb/amazonka | amazonka-swf/gen/Network/AWS/SWF/CountPendingDecisionTasks.hs | mpl-2.0 | 5,814 | 0 | 11 | 1,187 | 623 | 380 | 243 | 70 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- Module : Test.AWS.DirectoryService
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
module Test.AWS.DirectoryService
( tests
, fixtures
) where
import Network.AWS.DirectoryService
import Test.AWS.Gen.DirectoryService
import Test.Tasty
tests :: [TestTree]
tests = []
fixtures :: [TestTree]
fixtures = []
| fmapfmapfmap/amazonka | amazonka-ds/test/Test/AWS/DirectoryService.hs | mpl-2.0 | 776 | 0 | 5 | 201 | 73 | 50 | 23 | 11 | 1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="tr-TR">
<title>Özelleştirilebilir HTML Raporu</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>İçindekiler</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>İçerik</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Arama</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favoriler</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/customreport/src/main/javahelp/org/zaproxy/zap/extension/customreport/resources/help_tr_TR/helpset_tr_TR.hs | apache-2.0 | 985 | 79 | 66 | 158 | 419 | 211 | 208 | -1 | -1 |
module Music.Time.Aligned (
-- * Alignable class
Alignable(..),
-- * Aligned values
Aligned,
aligned,
realign,
renderAligned,
renderAlignedVoice,
renderAlignedNote,
renderAlignedDuration,
) where
import qualified Data.Aeson as JSON
import Music.Time.Internal.Preliminaries
import Music.Dynamics.Literal
import Music.Pitch.Literal
import Music.Time.Event
import Music.Time.Juxtapose
import Music.Time.Note
import Music.Time.Score
import Music.Time.Voice
-- TODO should this be a Setter or a Lens instead?
class Alignable a where
align :: Alignment -> a -> a
instance Alignable a => Alignable [a] where
align l = fmap (align l)
instance Alignable (Aligned a) where
align l (Aligned ((t, _), a)) = Aligned ((t, l), a)
-- type AlignedVoice a = Aligned (Voice a)
-- | 'Aligned' places a vector-like object in space, by fixing a local duration interpolating
-- the vector to a specific point in time. The aligned value must be an instance of
-- 'HasDuration', with @'view' 'duration'@ providing the size of the vector.
--
-- This is analogous to alignment in a graphical program. To align something at onset, midpoint
-- or offset, use 0, 0.5 or 1 as the local duration value.
newtype Aligned v = Aligned { getAligned :: ((Time, Alignment), v) }
deriving (Functor, Eq, Ord, Foldable, Traversable)
instance Wrapped (Aligned v) where
type Unwrapped (Aligned v) = ((Time, Alignment), v)
_Wrapped' = iso getAligned Aligned
instance Rewrapped (Aligned a) (Aligned b)
-- | Align the given value so that its local duration occurs at the given time.
aligned :: Time -> Alignment -> v -> Aligned v
aligned t d a = Aligned ((t, d), a)
instance Show a => Show (Aligned a) where
show (Aligned ((t,d),v)) = "aligned ("++show t++") ("++show d++") ("++ show v++")"
instance ToJSON a => ToJSON (Aligned a) where
toJSON (Aligned ((t,d),v)) = JSON.object [ ("alignment", toJSON d), ("origin", toJSON t), ("value", toJSON v) ]
instance Transformable v => Transformable (Aligned v) where
transform s (Aligned ((t, d), v)) = Aligned ((transform s t, d), transform s v)
instance (HasDuration v, Transformable v) => HasDuration (Aligned v) where
_duration (Aligned (_, v)) = v^.duration
instance (HasDuration v, Transformable v) => HasPosition (Aligned v) where
-- _position (Aligned (position, alignment, v)) = alerp (position .-^ (size * alignment)) (position .+^ (size * (1-alignment)))
_era (Aligned ((position, alignment), v)) =
(position .-^ (size * alignment)) <-> (position .+^ (size * (1-alignment)))
where
size = v^.duration
-- | Change the alignment of a value without moving it.
--
-- @
-- x^.'era' = ('realign' l x)^.'era'
-- @
realign :: (HasDuration a, Transformable a) => Alignment -> Aligned a -> Aligned a
realign l a@(Aligned ((t,_),x)) = Aligned ((a^.position l,l),x)
-- | Render an aligned value. The given span represents the actual span of the aligned value.
renderAligned :: (HasDuration a, Transformable a) => (Span -> a -> b) -> Aligned a -> b
renderAligned f a@(Aligned (_, v)) = f (_era a) v
-- Somewhat suspect, see below for clarity...
voiceToScoreInEra :: Span -> Voice a -> Score a
voiceToScoreInEra e = set era e . scat . map (uncurry stretch) . view pairs . fmap pure
noteToEventInEra :: Span -> Note a -> Event a
noteToEventInEra e = set era e . view notee . fmap pure
durationToSpanInEra :: Span -> Duration -> Span
durationToSpanInEra = const
-- TODO compare placeAt etc.
-- | Convert an aligned voice to a score.
renderAlignedVoice :: Aligned (Voice a) -> Score a
renderAlignedVoice = renderAligned voiceToScoreInEra
-- | Convert an aligned note to an event.
renderAlignedNote :: Aligned (Note a) -> Event a
renderAlignedNote = renderAligned noteToEventInEra
-- | Convert an aligned duration to a span.
renderAlignedDuration :: Aligned Duration -> Span
renderAlignedDuration = renderAligned durationToSpanInEra
| music-suite/music-score | src/Music/Time/Aligned.hs | bsd-3-clause | 4,034 | 0 | 12 | 815 | 1,170 | 640 | 530 | -1 | -1 |
-- Both these functions should successfully simplify
-- using the combine-identical-alternatives optimisation
module T7360 where
import GHC.List as L
data Foo = Foo1 | Foo2 | Foo3 !Int
fun1 :: Foo -> ()
{-# NOINLINE fun1 #-}
fun1 x = case x of
Foo1 -> ()
Foo2 -> ()
Foo3 {} -> ()
fun2 x = (fun1 Foo1, -- Keep -ddump-simpl output
-- in a predictable order
case x of
[] -> L.length x
(_:_) -> L.length x)
| sdiehl/ghc | testsuite/tests/simplCore/should_compile/T7360.hs | bsd-3-clause | 510 | 0 | 10 | 185 | 135 | 74 | 61 | 15 | 3 |
-- |
-- Module : Data.ByteString.Lazy.Search
-- Copyright : Daniel Fischer
-- Chris Kuklewicz
-- Licence : BSD3
-- Maintainer : Daniel Fischer <daniel.is.fischer@googlemail.com>
-- Stability : Provisional
-- Portability : non-portable (BangPatterns)
--
-- Fast overlapping Boyer-Moore search of lazy
-- 'L.ByteString' values. Breaking, splitting and replacing
-- using the Boyer-Moore algorithm.
--
-- Descriptions of the algorithm can be found at
-- <http://www-igm.univ-mlv.fr/~lecroq/string/node14.html#SECTION00140>
-- and
-- <http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm>
--
-- Original authors: Daniel Fischer (daniel.is.fischer at googlemail.com) and
-- Chris Kuklewicz (haskell at list.mightyreason.com).
module Data.ByteString.Lazy.Search( -- * Overview
-- $overview
-- ** Performance
-- $performance
-- ** Caution
-- $caution
-- ** Complexity
-- $complexity
-- ** Partial application
-- $partial
-- ** Integer overflow
-- $overflow
-- * Finding substrings
indices
, nonOverlappingIndices
-- * Breaking on substrings
, breakOn
, breakAfter
, breakFindAfter
-- * Replacing
, replace
-- * Splitting
, split
, splitKeepEnd
, splitKeepFront
-- * Convenience
, strictify
) where
import qualified Data.ByteString.Lazy.Search.Internal.BoyerMoore as BM
import Data.ByteString.Search.Substitution
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.Int (Int64)
-- $overview
--
-- This module provides functions related to searching a substring within
-- a string, using the Boyer-Moore algorithm with minor modifications
-- to improve the overall performance and ameliorate the worst case
-- performance degradation of the original Boyer-Moore algorithm for
-- periodic patterns.
--
-- Efficiency demands that the pattern be a strict 'S.ByteString',
-- to work with a lazy pattern, convert it to a strict 'S.ByteString'
-- first via 'strictify' (provided it is not too long).
-- If support for long lazy patterns is needed, mail a feature-request.
--
-- When searching a pattern in a UTF-8-encoded 'S.ByteString', be aware that
-- these functions work on bytes, not characters, so the indices are
-- byte-offsets, not character offsets.
-- $performance
--
-- In general, the Boyer-Moore algorithm is the most efficient method to
-- search for a pattern inside a string. The advantage over other algorithms
-- (e.g. Naïve, Knuth-Morris-Pratt, Horspool, Sunday) can be made
-- arbitrarily large for specially selected patterns and targets, but
-- usually, it's a factor of 2–3 versus Knuth-Morris-Pratt and of
-- 6–10 versus the naïve algorithm. The Horspool and Sunday
-- algorithms, which are simplified variants of the Boyer-Moore algorithm,
-- typically have performance between Boyer-Moore and Knuth-Morris-Pratt,
-- mostly closer to Boyer-Moore. The advantage of the Boyer-moore variants
-- over other algorithms generally becomes larger for longer patterns. For
-- very short patterns (or patterns with a very short period), other
-- algorithms, e.g. "Data.ByteString.Lazy.Search.DFA" can be faster (my
-- tests suggest that \"very short\" means two, maybe three bytes).
--
-- In general, searching in a strict 'S.ByteString' is slightly faster
-- than searching in a lazy 'L.ByteString', but for long targets the
-- smaller memory footprint of lazy 'L.ByteString's can make searching
-- those (sometimes much) faster. On the other hand, there are cases
-- where searching in a strict target is much faster, even for long targets.
--
-- On 32-bit systems, 'Int'-arithmetic is much faster than 'Int64'-arithmetic,
-- so when there are many matches, that can make a significant difference.
--
-- Also, the modification to ameliorate the case of periodic patterns
-- is defeated by chunk-boundaries, so long patterns with a short period
-- and many matches exhibit poor behaviour (consider using @indices@ from
-- "Data.ByteString.Lazy.Search.DFA" or "Data.ByteString.Lazy.Search.KMP"
-- in those cases, the former for medium-length patterns, the latter for
-- long patterns; none of the functions except 'indices' suffer from
-- this problem, though).
-- $caution
--
-- When working with a lazy target string, the relation between the pattern
-- length and the chunk size can play a big rôle.
-- Crossing chunk boundaries is relatively expensive, so when that becomes
-- a frequent occurrence, as may happen when the pattern length is close
-- to or larger than the chunk size, performance is likely to degrade.
-- If it is needed, steps can be taken to ameliorate that effect, but unless
-- entirely separate functions are introduced, that would hurt the
-- performance for the more common case of patterns much shorter than
-- the default chunk size.
-- $complexity
--
-- Preprocessing the pattern is /O/(@patternLength@ + σ) in time and
-- space (σ is the alphabet size, 256 here) for all functions.
-- The time complexity of the searching phase for 'indices'
-- is /O/(@targetLength@ \/ @patternLength@) in the best case.
-- For non-periodic patterns, the worst case complexity is
-- /O/(@targetLength@), but for periodic patterns, the worst case complexity
-- is /O/(@targetLength@ * @patternLength@) for the original Boyer-Moore
-- algorithm.
--
-- The searching functions in this module contain a modification which
-- drastically improves the performance for periodic patterns, although
-- less for lazy targets than for strict ones.
-- If I'm not mistaken, the worst case complexity for periodic patterns
-- is /O/(@targetLength@ * (1 + @patternLength@ \/ @chunkSize@)).
--
-- The other functions don't have to deal with possible overlapping
-- patterns, hence the worst case complexity for the processing phase
-- is /O/(@targetLength@) (respectively /O/(@firstIndex + patternLength@)
-- for the breaking functions if the pattern occurs).
-- $partial
--
-- All functions can usefully be partially applied. Given only a pattern,
-- the pattern is preprocessed only once, allowing efficient re-use.
-- $overflow
--
-- The current code uses @Int@ to keep track of the locations in the
-- target string. If the length of the pattern plus the length of any
-- strict chunk of the target string is greater or equal to
-- @'maxBound' :: 'Int'@ then this will overflow causing an error. We try
-- to detect this and call 'error' before a segfault occurs.
------------------------------------------------------------------------------
-- Exported Functions --
------------------------------------------------------------------------------
-- | @'indices'@ finds the starting indices of all possibly overlapping
-- occurrences of the pattern in the target string.
-- If the pattern is empty, the result is @[0 .. 'length' target]@.
{-# INLINE indices #-}
indices :: S.ByteString -- ^ Strict pattern to find
-> L.ByteString -- ^ Lazy string to search
-> [Int64] -- ^ Offsets of matches
indices = BM.matchSL
-- | @'nonOverlappingIndices'@ finds the starting indices of all
-- non-overlapping occurrences of the pattern in the target string.
-- It is more efficient than removing indices from the list produced
-- by 'indices'.
{-# INLINE nonOverlappingIndices #-}
nonOverlappingIndices :: S.ByteString -- ^ Strict pattern to find
-> L.ByteString -- ^ Lazy string to search
-> [Int64] -- ^ Offsets of matches
nonOverlappingIndices = BM.matchNOL
-- | @'breakOn' pattern target@ splits @target@ at the first occurrence
-- of @pattern@. If the pattern does not occur in the target, the
-- second component of the result is empty, otherwise it starts with
-- @pattern@. If the pattern is empty, the first component is empty.
-- For a non-empty pattern, the first component is generated lazily,
-- thus the first parts of it can be available before the pattern has
-- been found or determined to be absent.
--
-- @
-- 'uncurry' 'L.append' . 'breakOn' pattern = 'id'
-- @
{-# INLINE breakOn #-}
breakOn :: S.ByteString -- ^ Strict pattern to search for
-> L.ByteString -- ^ Lazy string to search in
-> (L.ByteString, L.ByteString)
-- ^ Head and tail of string broken at substring
breakOn = BM.breakSubstringL
-- | @'breakAfter' pattern target@ splits @target@ behind the first occurrence
-- of @pattern@. An empty second component means that either the pattern
-- does not occur in the target or the first occurrence of pattern is at
-- the very end of target. If you need to discriminate between those cases,
-- use breakFindAfter.
-- If the pattern is empty, the first component is empty.
-- For a non-empty pattern, the first component is generated lazily,
-- thus the first parts of it can be available before the pattern has
-- been found or determined to be absent.
--
-- @
-- 'uncurry' 'L.append' . 'breakAfter' pattern = 'id'
-- @
{-# INLINE breakAfter #-}
breakAfter :: S.ByteString -- ^ Strict pattern to search for
-> L.ByteString -- ^ Lazy string to search in
-> (L.ByteString, L.ByteString)
-- ^ Head and tail of string broken after substring
breakAfter = BM.breakAfterL
-- | @'breakFindAfter'@ does the same as 'breakAfter' but additionally indicates
-- whether the pattern is present in the target.
--
-- @
-- 'fst' . 'breakFindAfter' pat = 'breakAfter' pat
-- @
{-# INLINE breakFindAfter #-}
breakFindAfter :: S.ByteString -- ^ Strict pattern to search for
-> L.ByteString -- ^ Lazy string to search in
-> ((L.ByteString, L.ByteString), Bool)
-- ^ Head and tail of string broken after substring
-- and presence of pattern
breakFindAfter = BM.breakFindAfterL
-- | @'replace' pat sub text@ replaces all (non-overlapping) occurrences of
-- @pat@ in @text@ with @sub@. If occurrences of @pat@ overlap, the first
-- occurrence that does not overlap with a replaced previous occurrence
-- is substituted. Occurrences of @pat@ arising from a substitution
-- will not be substituted. For example:
--
-- @
-- 'replace' \"ana\" \"olog\" \"banana\" = \"bologna\"
-- 'replace' \"ana\" \"o\" \"bananana\" = \"bono\"
-- 'replace' \"aab\" \"abaa\" \"aaabb\" = \"aabaab\"
-- @
--
-- The result is a lazy 'L.ByteString',
-- which is lazily produced, without copying.
-- Equality of pattern and substitution is not checked, but
--
-- @
-- 'replace' pat pat text == text
-- @
--
-- holds (the internal structure is generally different).
-- If the pattern is empty but not the substitution, the result
-- is equivalent to (were they 'String's) @cycle sub@.
--
-- For non-empty @pat@ and @sub@ a lazy 'L.ByteString',
--
-- @
-- 'L.concat' . 'Data.List.intersperse' sub . 'split' pat = 'replace' pat sub
-- @
--
-- and analogous relations hold for other types of @sub@.
{-# INLINE replace #-}
replace :: Substitution rep
=> S.ByteString -- ^ Strict pattern to replace
-> rep -- ^ Replacement string
-> L.ByteString -- ^ Lazy string to modify
-> L.ByteString -- ^ Lazy result
replace = BM.replaceAllL
-- | @'split' pattern target@ splits @target@ at each (non-overlapping)
-- occurrence of @pattern@, removing @pattern@. If @pattern@ is empty,
-- the result is an infinite list of empty 'L.ByteString's, if @target@
-- is empty but not @pattern@, the result is an empty list, otherwise
-- the following relations hold (where @patL@ is the lazy 'L.ByteString'
-- corresponding to @pat@):
--
-- @
-- 'L.concat' . 'Data.List.intersperse' patL . 'split' pat = 'id',
-- 'length' ('split' pattern target) ==
-- 'length' ('nonOverlappingIndices' pattern target) + 1,
-- @
--
-- no fragment in the result contains an occurrence of @pattern@.
{-# INLINE split #-}
split :: S.ByteString -- ^ Strict pattern to split on
-> L.ByteString -- ^ Lazy string to split
-> [L.ByteString] -- ^ Fragments of string
split = BM.splitDropL
-- | @'splitKeepEnd' pattern target@ splits @target@ after each (non-overlapping)
-- occurrence of @pattern@. If @pattern@ is empty, the result is an
-- infinite list of empty 'L.ByteString's, otherwise the following
-- relations hold:
--
-- @
-- 'L.concat' . 'splitKeepEnd' pattern = 'id',
-- @
--
-- all fragments in the result except possibly the last end with
-- @pattern@, no fragment contains more than one occurrence of @pattern@.
{-# INLINE splitKeepEnd #-}
splitKeepEnd :: S.ByteString -- ^ Strict pattern to split on
-> L.ByteString -- ^ Lazy string to split
-> [L.ByteString] -- ^ Fragments of string
splitKeepEnd = BM.splitKeepEndL
-- | @'splitKeepFront'@ is like 'splitKeepEnd', except that @target@ is split
-- before each occurrence of @pattern@ and hence all fragments
-- with the possible exception of the first begin with @pattern@.
-- No fragment contains more than one non-overlapping occurrence
-- of @pattern@.
{-# INLINE splitKeepFront #-}
splitKeepFront :: S.ByteString -- ^ Strict pattern to split on
-> L.ByteString -- ^ Lazy string to split
-> [L.ByteString] -- ^ Fragments of string
splitKeepFront = BM.splitKeepFrontL
-- | @'strictify'@ converts a lazy 'L.ByteString' to a strict 'S.ByteString'
-- to make it a suitable pattern.
strictify :: L.ByteString -> S.ByteString
strictify = S.concat . L.toChunks
| seereason/stringsearch | Data/ByteString/Lazy/Search.hs | bsd-3-clause | 14,566 | 0 | 9 | 3,641 | 667 | 502 | 165 | 65 | 1 |
module Package05 where
import GHC.Hs.Types
import GHC.Hs.MyTypes
import GHC.Hs.Utils
| sdiehl/ghc | testsuite/tests/package/package05.hs | bsd-3-clause | 85 | 0 | 4 | 9 | 22 | 15 | 7 | 4 | 0 |
{-|
Module : Idris.REPL
Description : Main function to decide Idris' mode of use.
License : BSD3
Maintainer : The Idris Community.
-}
module Idris.Main
( idrisMain
, idris
, runMain
, runClient -- taken from Idris.REPL.
, loadInputs -- taken from Idris.ModeCommon
) where
import Idris.AbsSyntax
import Idris.Core.Execute (execute)
import Idris.Core.TT
import Idris.Elab.Term
import Idris.Elab.Value
import Idris.ElabDecls
import Idris.Error
import Idris.IBC
import Idris.Info
import Idris.ModeCommon
import Idris.Options
import Idris.Output
import Idris.Parser hiding (indent)
import Idris.REPL
import Idris.REPL.Commands
import Idris.REPL.Parser
import IRTS.CodegenCommon
import Util.System
import Control.Category
import Control.DeepSeq
import Control.Monad
import Control.Monad.Trans (lift)
import Control.Monad.Trans.Except (runExceptT)
import Control.Monad.Trans.State.Strict (execStateT)
import Data.List
import Data.Maybe
import Prelude hiding (id, (.), (<$>))
import System.Console.Haskeline as H
import System.Directory
import System.Exit
import System.FilePath
import System.IO
import System.IO.CodePage (withCP65001)
import Text.Trifecta.Result (ErrInfo(..), Result(..))
-- | How to run Idris programs.
runMain :: Idris () -> IO ()
runMain prog = withCP65001 $ do
-- Run in codepage 65001 on Windows so that UTF-8 characters can
-- be displayed properly. See #3000.
res <- runExceptT $ execStateT prog idrisInit
case res of
Left err -> do
putStrLn $ "Uncaught error: " ++ show err
exitFailure
Right _ -> return ()
-- | The main function of Idris that when given a set of Options will
-- launch Idris into the desired interaction mode either: REPL;
-- Compiler; Script execution; or IDE Mode.
idrisMain :: [Opt] -> Idris ()
idrisMain opts =
do mapM_ setWidth (opt getConsoleWidth opts)
let inputs = opt getFile opts
let quiet = Quiet `elem` opts
let nobanner = NoBanner `elem` opts
let idesl = Idemode `elem` opts || IdemodeSocket `elem` opts
let runrepl = not (NoREPL `elem` opts)
let output = opt getOutput opts
let ibcsubdir = opt getIBCSubDir opts
let importdirs = opt getImportDir opts
let sourcedirs = opt getSourceDir opts
setSourceDirs sourcedirs
let bcs = opt getBC opts
let pkgdirs = opt getPkgDir opts
-- Set default optimisations
let optimise = case opt getOptLevel opts of
[] -> 1
xs -> last xs
setOptLevel optimise
let outty = case opt getOutputTy opts of
[] -> if Interface `elem` opts then
Object else Executable
xs -> last xs
let cgn = case opt getCodegen opts of
[] -> Via IBCFormat "c"
xs -> last xs
let cgFlags = opt getCodegenArgs opts
-- Now set/unset specifically chosen optimisations
let os = opt getOptimisation opts
mapM_ processOptimisation os
script <- case opt getExecScript opts of
[] -> return Nothing
x:y:xs -> do iputStrLn "More than one interpreter expression found."
runIO $ exitWith (ExitFailure 1)
[expr] -> return (Just expr)
let immediate = opt getEvalExpr opts
let port = case getPort opts of
Nothing -> ListenPort defaultPort
Just p -> p
when (DefaultTotal `elem` opts) $ do i <- getIState
putIState (i { default_total = DefaultCheckingTotal })
tty <- runIO isATTY
setColourise $ not quiet && last (tty : opt getColour opts)
mapM_ addLangExt (opt getLanguageExt opts)
setREPL runrepl
setQuiet (quiet || isJust script || not (null immediate))
setCmdLine opts
setOutputTy outty
setNoBanner nobanner
setCodegen cgn
mapM_ (addFlag cgn) cgFlags
mapM_ makeOption opts
vlevel <- verbose
when (runrepl && vlevel == 0) $ setVerbose 1
-- if we have the --bytecode flag, drop into the bytecode assembler
case bcs of
[] -> return ()
xs -> return () -- runIO $ mapM_ bcAsm xs
case ibcsubdir of
[] -> setIBCSubDir ""
(d:_) -> setIBCSubDir d
setImportDirs importdirs
setNoBanner nobanner
-- Check if listed packages are actually installed
idrisCatch (do ipkgs <- runIO $ getIdrisInstalledPackages
let diff_pkgs = (\\) pkgdirs ipkgs
when (not $ null diff_pkgs) $ do
iputStrLn "The following packages were specified but cannot be found:"
iputStr $ unlines $ map (\x -> unwords ["-", x]) diff_pkgs
runIO $ exitWith (ExitFailure 1))
(\e -> return ())
when (not (NoBasePkgs `elem` opts)) $ do
addPkgDir "prelude"
addPkgDir "base"
mapM_ addPkgDir pkgdirs
elabPrims
when (not (NoBuiltins `elem` opts)) $ do x <- loadModule "Builtins" (IBC_REPL True)
addAutoImport "Builtins"
return ()
when (not (NoPrelude `elem` opts)) $ do x <- loadModule "Prelude" (IBC_REPL True)
addAutoImport "Prelude"
return ()
when (runrepl && not idesl) initScript
nobanner <- getNoBanner
when (runrepl &&
not quiet &&
not idesl &&
not (isJust script) &&
not nobanner &&
null immediate) $
iputStrLn banner
orig <- getIState
mods <- if idesl then return [] else loadInputs inputs Nothing
let efile = case inputs of
[] -> ""
(f:_) -> f
runIO $ hSetBuffering stdout LineBuffering
ok <- noErrors
when ok $ case output of
[] -> return ()
(o:_) -> idrisCatch (process "" (Compile cgn o))
(\e -> do ist <- getIState ; iputStrLn $ pshow ist e)
case immediate of
[] -> return ()
exprs -> do setWidth InfinitelyWide
mapM_ (\str -> do ist <- getIState
c <- colourise
case parseExpr ist str of
Failure (ErrInfo err _) -> do iputStrLn $ show (fixColour c err)
runIO $ exitWith (ExitFailure 1)
Success e -> process "" (Eval e))
exprs
runIO exitSuccess
case script of
Nothing -> return ()
Just expr -> execScript expr
-- Create Idris data dir + repl history and config dir
idrisCatch (do dir <- runIO $ getIdrisUserDataDir
exists <- runIO $ doesDirectoryExist dir
unless exists $ logLvl 1 ("Creating " ++ dir)
runIO $ createDirectoryIfMissing True (dir </> "repl"))
(\e -> return ())
historyFile <- runIO $ getIdrisHistoryFile
when ok $ case opt getPkgIndex opts of
(f : _) -> writePkgIndex f
_ -> return ()
when (runrepl && not idesl) $ do
-- clearOrigPats
case port of
DontListen -> return ()
ListenPort port' -> startServer port' orig mods
runInputT (replSettings (Just historyFile)) $ repl (force orig) mods efile
let idesock = IdemodeSocket `elem` opts
when (idesl) $ idemodeStart idesock orig inputs
ok <- noErrors
when (not ok) $ runIO (exitWith (ExitFailure 1))
where
makeOption (OLogging i) = setLogLevel i
makeOption (OLogCats cs) = setLogCats cs
makeOption (Verbose v) = setVerbose v
makeOption TypeCase = setTypeCase True
makeOption TypeInType = setTypeInType True
makeOption NoCoverage = setCoverage False
makeOption ErrContext = setErrContext True
makeOption (IndentWith n) = setIndentWith n
makeOption (IndentClause n) = setIndentClause n
makeOption _ = return ()
processOptimisation :: (Bool,Optimisation) -> Idris ()
processOptimisation (True, p) = addOptimise p
processOptimisation (False, p) = removeOptimise p
addPkgDir :: String -> Idris ()
addPkgDir p = do ddir <- runIO getIdrisLibDir
addImportDir (ddir </> p)
addIBC (IBCImportDir (ddir </> p))
-- | Invoke as if from command line. It is an error if there are
-- unresolved totality problems.
idris :: [Opt] -> IO (Maybe IState)
idris opts = do res <- runExceptT $ execStateT totalMain idrisInit
case res of
Left err -> do putStrLn $ pshow idrisInit err
return Nothing
Right ist -> return (Just ist)
where totalMain = do idrisMain opts
ist <- getIState
case idris_totcheckfail ist of
((fc, msg):_) -> ierror . At fc . Msg $ "Could not build: "++ msg
[] -> return ()
-- | Execute the provided Idris expression.
execScript :: String -> Idris ()
execScript expr = do i <- getIState
c <- colourise
case parseExpr i expr of
Failure (ErrInfo err _) -> do iputStrLn $ show (fixColour c err)
runIO $ exitWith (ExitFailure 1)
Success term -> do ctxt <- getContext
(tm, _) <- elabVal (recinfo (fileFC "toplevel")) ERHS term
res <- execute tm
runIO $ exitSuccess
-- | Run the initialisation script
initScript :: Idris ()
initScript = do script <- runIO $ getIdrisInitScript
idrisCatch (do go <- runIO $ doesFileExist script
when go $ do
h <- runIO $ openFile script ReadMode
runInit h
runIO $ hClose h)
(\e -> iPrintError $ "Error reading init file: " ++ show e)
where runInit :: Handle -> Idris ()
runInit h = do eof <- lift . lift $ hIsEOF h
ist <- getIState
unless eof $ do
line <- runIO $ hGetLine h
script <- runIO $ getIdrisInitScript
c <- colourise
processLine ist line script c
runInit h
processLine i cmd input clr =
case parseCmd i input cmd of
Failure (ErrInfo err _) -> runIO $ print (fixColour clr err)
Success (Right Reload) -> iPrintError "Init scripts cannot reload the file"
Success (Right (Load f _)) -> iPrintError "Init scripts cannot load files"
Success (Right (ModImport f)) -> iPrintError "Init scripts cannot import modules"
Success (Right Edit) -> iPrintError "Init scripts cannot invoke the editor"
Success (Right Proofs) -> proofs i
Success (Right Quit) -> iPrintError "Init scripts cannot quit Idris"
Success (Right cmd ) -> process [] cmd
Success (Left err) -> runIO $ print err
| mpkh/Idris-dev | src/Idris/Main.hs | bsd-3-clause | 12,005 | 0 | 25 | 4,657 | 3,270 | 1,561 | 1,709 | 245 | 28 |
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.IO.Class
-- Copyright : (c) Andy Gill 2001,
-- (c) Oregon Graduate Institute of Science and Technology, 2001
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : ross@soi.city.ac.uk
-- Stability : experimental
-- Portability : portable
--
-- Class of monads based on @IO@.
-----------------------------------------------------------------------------
module Control.Monad.IO.Class (
MonadIO(..)
) where
import System.IO (IO)
-- | Monads in which 'IO' computations may be embedded.
-- Any monad built by applying a sequence of monad transformers to the
-- 'IO' monad will be an instance of this class.
--
-- Instances should satisfy the following laws, which state that 'liftIO'
-- is a transformer of monads:
--
-- * @'liftIO' . 'return' = 'return'@
--
-- * @'liftIO' (m >>= f) = 'liftIO' m >>= ('liftIO' . f)@
class (Monad m) => MonadIO m where
-- | Lift a computation from the 'IO' monad.
liftIO :: IO a -> m a
instance MonadIO IO where
liftIO = id
| jwiegley/ghc-release | libraries/transformers/Control/Monad/IO/Class.hs | gpl-3.0 | 1,130 | 0 | 8 | 224 | 97 | 65 | 32 | 7 | 0 |
{-# LANGUAGE FlexibleContexts #-}
-- | Users end point handling
-- <http://instagram.com/developer/endpoints/users/#>
module Instagram.Users (
getUser
, SelfFeedParams(..)
, getSelfFeed
, RecentParams(..)
, getRecent
, SelfLikedParams(..)
, getSelfLiked
, UserSearchParams(..)
, searchUsers
) where
import Instagram.Monad
import Instagram.Types
import Data.Time.Clock.POSIX (POSIXTime)
import Data.Typeable (Typeable)
import qualified Network.HTTP.Types as HT
import Data.Maybe (isJust)
import qualified Data.Text as T (Text)
import Data.Default
-- | Get basic information about a user.
getUser :: (MonadBaseControl IO m, MonadResource m)
=> UserID
-> Maybe OAuthToken
-> InstagramT m (Envelope (Maybe User))
getUser uid token = getGetEnvelopeM ["/v1/users/",uid] token ([]::HT.Query)
-- | Parameters for call to self feed
data SelfFeedParams = SelfFeedParams {
sfpCount :: Maybe Integer,
sfpMaxID :: Maybe T.Text,
sfpMinId :: Maybe T.Text
}
deriving (Show,Typeable)
instance Default SelfFeedParams where
def = SelfFeedParams Nothing Nothing Nothing
instance HT.QueryLike SelfFeedParams where
toQuery (SelfFeedParams c maxI minI) = filter (isJust .snd)
[ "count" ?+ c
, "max_id" ?+ maxI
, "min_id" ?+ minI
]
-- | See the authenticated user's feed.
getSelfFeed :: (MonadBaseControl IO m, MonadResource m)
=> OAuthToken
-> SelfFeedParams
-> InstagramT m (Envelope [Media])
getSelfFeed = getGetEnvelope ["/v1/users/self/feed/"]
-- | Parameters for call to recent media
data RecentParams = RecentParams {
rpCount :: Maybe Integer,
rpMaxTimestamp :: Maybe POSIXTime,
rpMinTimestamp :: Maybe POSIXTime,
rpMaxID :: Maybe T.Text,
rpMinId :: Maybe T.Text
}
deriving (Show,Typeable)
instance Default RecentParams where
def = RecentParams Nothing Nothing Nothing Nothing Nothing
instance HT.QueryLike RecentParams where
toQuery (RecentParams c maxT minT maxI minI) = filter (isJust .snd)
[ "count" ?+ c
, "max_timestamp" ?+ maxT
, "min_timestamp" ?+ minT
, "max_id" ?+ maxI
, "min_id" ?+ minI
]
-- | Get the most recent media published by a user.
getRecent :: (MonadBaseControl IO m, MonadResource m)
=> UserID
-> Maybe OAuthToken
-> RecentParams
-> InstagramT m (Envelope [Media])
getRecent uid = getGetEnvelopeM ["/v1/users/",uid,"/media/recent/"]
-- | parameters for self liked call
data SelfLikedParams = SelfLikedParams {
slpCount :: Maybe Integer,
slpMaxLikeID :: Maybe T.Text
}
deriving (Show,Typeable)
instance Default SelfLikedParams where
def = SelfLikedParams Nothing Nothing
instance HT.QueryLike SelfLikedParams where
toQuery (SelfLikedParams c maxI) = filter (isJust .snd)
[ "count" ?+ c
, "max_like_id" ?+ maxI
]
-- | See the authenticated user's list of media they've liked.
getSelfLiked :: (MonadBaseControl IO m, MonadResource m)
=> OAuthToken
-> SelfLikedParams
-> InstagramT m (Envelope [Media])
getSelfLiked = getGetEnvelope ["/v1/users/self/media/liked"]
-- | parameters for self liked call
data UserSearchParams = UserSearchParams {
uspQuery :: T.Text,
uspCount :: Maybe Integer
}
deriving (Show,Typeable)
instance HT.QueryLike UserSearchParams where
toQuery (UserSearchParams q c ) = filter (isJust .snd)
[ "count" ?+ c -- does not seem to be taken into account...
, "q" ?+ q
]
-- | Search for a user by name.
searchUsers :: (MonadBaseControl IO m, MonadResource m)
=> Maybe OAuthToken
-> UserSearchParams
-> InstagramT m (Envelope [User])
searchUsers = getGetEnvelopeM ["/v1/users/search"]
| BeautifulDestinations/ig | src/Instagram/Users.hs | bsd-3-clause | 3,765 | 4 | 12 | 831 | 962 | 529 | 433 | 91 | 1 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- | Functions to make tagsoup suck less.
module TagSoup where
import Control.Applicative
import Control.Monad.Except
import Control.Monad.State
import Data.Char
import Data.List
import Data.Maybe
import Data.Time
import Text.HTML.TagSoup
import Text.HTML.TagSoup.Match
newtype Soup a = Soup { unSoup :: StateT [Tag String] (Either String) a }
deriving (Monad,Functor,MonadError String,MonadState [Tag String],Alternative,Applicative)
runSoup :: [Tag String] -> Soup a -> Either String a
runSoup xs m = evalStateT (unSoup m) xs
getAttrib :: String -> Tag String -> Soup String
getAttrib att (TagOpen _ atts) = return (fromMaybe empty $ lookup att atts)
getAttrib _ x = throwError ("(" ++ show x ++ ") is not a TagOpen")
gotoTagByNameAttrs :: String -> ([Attribute String] -> Bool) -> Soup (Tag String)
gotoTagByNameAttrs name attrs = do
xs <- get
case dropWhile (not . tagOpen (==name) attrs) xs of
[] -> throwError $ "Unable to find tag " ++ name ++ "."
(x:xs') -> do put xs'
return x
gotoTagByName :: String -> Soup (Tag String)
gotoTagByName name = do
xs <- get
case dropWhile (not . tagOpen (==name) (const True)) xs of
[] -> throwError $ "Unable to find tag " ++ name ++ "."
(x:xs') -> do put xs'
return x
skipTagByName :: String -> Soup ()
skipTagByName name = void $ gotoTagByName name
skipTagByNameAttrs :: String -> ([Attribute String] -> Bool) -> Soup ()
skipTagByNameAttrs name attrs = void $ gotoTagByNameAttrs name attrs
nextText :: Soup String
nextText = do
xs <- get
case xs of
(TagText x:xs') -> do put xs'
return x
_ -> throwError $ "Expected tag content but got something else: " ++ show (take 1 xs)
parseGithubTime :: (ParseTime a) => String -> Soup a
parseGithubTime str =
case (parseTimeM True) defaultTimeLocale "%Y-%m-%dT%T%z" str of
Nothing -> throwError $ "Unable to parse datetime: " ++ str
Just t -> return t
parseDate :: (ParseTime a) => String -> Soup a
parseDate str =
case (parseTimeM True) defaultTimeLocale "%Y-%m-%d" str of
Nothing -> throwError $ "Unable to parse date: " ++ str
Just t -> return t
parseEpoch :: (ParseTime a) => String -> Soup a
parseEpoch str =
case (parseTimeM True) defaultTimeLocale "%s" str of
Nothing -> throwError $ "Unable to parse epoch seconds to date: " ++ str
Just t -> return t
-- | Extract all text content from tags (similar to Verbatim found in HaXml)
tagsText :: [Tag String] -> String
tagsText = intercalate " " . map trim' . mapMaybe maybeTagText
-- | Extract all text content from tags.
tagsTxt :: [Tag String] -> String
tagsTxt = concat . mapMaybe maybeTagText
trim' :: String -> String
trim' = dropWhile isSpace . reverse . dropWhile isSpace . reverse
skipTagByNameClass :: String -> String -> Soup()
skipTagByNameClass name cls =
skipTagByNameAttrs name
(any (\(key,value) -> key == "class" && any (==cls) (words value)))
gotoTagByNameClass :: String -> String -> Soup (Tag String)
gotoTagByNameClass name cls =
gotoTagByNameAttrs name
(any (\(key,value) -> key == "class" && any (==cls) (words value)))
meither :: MonadError e m => e -> Maybe a -> m a
meither e Nothing = throwError e
meither _ (Just x) = return x
| lwm/haskellnews | src/TagSoup.hs | bsd-3-clause | 3,380 | 0 | 13 | 742 | 1,183 | 594 | 589 | 76 | 2 |
module Aws
( -- * Logging
LogLevel(..)
, Logger
, defaultLog
-- * Configuration
, Configuration(..)
, baseConfiguration
, dbgConfiguration
-- * Transaction runners
-- ** Safe runners
, aws
, awsRef
, pureAws
, simpleAws
-- ** Unsafe runners
, unsafeAws
, unsafeAwsRef
-- ** URI runners
, awsUri
-- ** Iterated runners
--, awsIteratedAll
, awsIteratedSource
, awsIteratedList
-- * Response
-- ** Full HTTP response
, HTTPResponseConsumer
-- ** Metadata in responses
, Response(..)
, readResponse
, readResponseIO
, ResponseMetadata
-- ** Memory responses
, AsMemoryResponse(..)
-- ** Exception types
, XmlException(..)
, HeaderException(..)
, FormException(..)
-- * Query
-- ** Service configuration
, ServiceConfiguration
, DefaultServiceConfiguration(..)
, NormalQuery
, UriOnlyQuery
-- ** Expiration
, TimeInfo(..)
-- * Transactions
, Transaction
, IteratedTransaction
-- * Credentials
, Credentials(..)
, makeCredentials
, credentialsDefaultFile
, credentialsDefaultKey
, loadCredentialsFromFile
, loadCredentialsFromEnv
, loadCredentialsFromInstanceMetadata
, loadCredentialsFromEnvOrFile
, loadCredentialsFromEnvOrFileOrInstanceMetadata
, loadCredentialsDefault
)
where
import Aws.Aws
import Aws.Core
| frms-/aws | Aws.hs | bsd-3-clause | 1,241 | 0 | 5 | 190 | 197 | 140 | 57 | 45 | 0 |
----------------------------------------------------------------------------
-- |
-- Module : XMonad.Hooks.WorkspaceByPos
-- Copyright : (c) Jan Vornberger 2009
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : jan.vornberger@informatik.uni-oldenburg.de
-- Stability : unstable
-- Portability : not portable
--
-- Useful in a dual-head setup: Looks at the requested geometry of
-- new windows and moves them to the workspace of the non-focused
-- screen if necessary.
--
-----------------------------------------------------------------------------
module XMonad.Hooks.WorkspaceByPos (
-- * Usage
-- $usage
workspaceByPos
) where
import XMonad
import qualified XMonad.StackSet as W
import XMonad.Util.XUtils (fi)
import Data.Maybe
import Control.Applicative((<$>))
import Control.Monad.Error ((<=<),guard,lift,runErrorT,throwError)
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Hooks.WorkspaceByPos
-- >
-- > myManageHook = workspaceByPos <+> manageHook defaultConfig
-- >
-- > main = xmonad defaultConfig { manageHook = myManageHook }
workspaceByPos :: ManageHook
workspaceByPos = (maybe idHook doShift <=< liftX . needsMoving) =<< ask
needsMoving :: Window -> X (Maybe WorkspaceId)
needsMoving w = withDisplay $ \d -> do
-- only relocate windows with non-zero position
wa <- io $ getWindowAttributes d w
fmap (const Nothing `either` Just) . runErrorT $ do
guard $ wa_x wa /= 0 || wa_y wa /= 0
ws <- gets windowset
sc <- lift $ fromMaybe (W.current ws)
<$> pointScreen (fi $ wa_x wa) (fi $ wa_y wa)
Just wkspc <- lift $ screenWorkspace (W.screen sc)
guard $ W.currentTag ws /= wkspc
return wkspc `asTypeOf` throwError ""
| markus1189/xmonad-contrib-710 | XMonad/Hooks/WorkspaceByPos.hs | bsd-3-clause | 1,812 | 0 | 18 | 356 | 351 | 195 | 156 | -1 | -1 |
-- !!! ds008 -- free tyvars on RHSs
--
-- these tests involve way-cool TyApps
module ShouldCompile where
f x = []
g x = (f [],[],[],[])
h x = g (1::Int)
| shlevy/ghc | testsuite/tests/deSugar/should_compile/ds008.hs | bsd-3-clause | 157 | 0 | 7 | 36 | 65 | 37 | 28 | 4 | 1 |
module System.Console.Xterm.ColorsSpec (
spec
) where
import Test.Hspec
import System.Console.Xterm.Colors
spec :: Spec
spec = do
-- compare results with table in
-- http://www.calmar.ws/vim/256-xterm-24bit-rgb-color-chart.html
describe "getXtermColor" $ do
it "0 is #000000" $ do
getXtermColor 0 `shouldBe` mkRGB 0x0 0x0 0x0
it "15 is #ffffff" $ do
getXtermColor 15 `shouldBe` mkRGB 0xFF 0xFF 0xFF
it "121 is #87ffaf" $ do
getXtermColor 121 `shouldBe` mkRGB 0x87 0xFF 0xAF
it "236 is #303030" $ do
getXtermColor 236 `shouldBe` mkRGB 0x30 0x30 0x30
it "255 is #eeeeee" $ do
getXtermColor 255 `shouldBe` mkRGB 0xEE 0xEE 0xEE
| bacher09/xterm-colors | tests/System/Console/Xterm/ColorsSpec.hs | mit | 748 | 0 | 14 | 217 | 192 | 94 | 98 | 17 | 1 |
import System.Process
import System.Exit
import Control.Applicative
import Data.Maybe
import BranchParse
import StatusParse
{- Type aliases -}
type Hash = String
type Numbers = [String]
{- Combining branch and status parsing -}
processBranch :: String -> BranchInfo
processBranch = either (const noBranchInfo) id . branchInfo . drop 3
processGitStatus :: [String] -> (BranchInfo, StatusT Int)
processGitStatus [] = undefined
processGitStatus (b:s) = (processBranch b, processStatus s)
allInfo :: (BranchInfo, StatusT Int) -> (Maybe Branch, Numbers)
allInfo (((branch, _), behead), StatusC s x c t) = (branch , fmap show [ahead, behind, s, x, c, t])
where
(ahead, behind) = fromMaybe (0,0) behead
makeHash :: Maybe Hash -> String
makeHash = (':' :) . maybe "" init
{- Git commands -}
maybeResult :: (ExitCode, a, b) -> Maybe a
maybeResult (ex, out, _) =
if ex == ExitSuccess then Just out else Nothing
safeRun :: String -> [String] -> IO (Maybe String)
safeRun command arguments = maybeResult <$> readProcessWithExitCode command arguments ""
gitstatus :: IO (Maybe String)
gitstatus = safeRun "git" ["status", "--porcelain", "--branch"]
gitrevparse :: IO (Maybe Hash)
gitrevparse = safeRun "git" ["rev-parse", "--short", "HEAD"]
{- IO -}
printHash :: IO ()
printHash = putStrLn . makeHash =<< gitrevparse
printBranch :: Maybe Branch -> IO ()
printBranch branch =
case branch of
Nothing -> printHash
Just bn -> putStrLn bn
printNumbers :: Numbers -> IO ()
printNumbers = mapM_ putStrLn
printAll :: Maybe String -> IO ()
printAll status =
case fmap (allInfo . processGitStatus . lines) status of
Nothing -> return ()
Just (b,n) -> printBranch b >> printNumbers n
-- maybe (return ()) (\(b,n) -> printBranch b >> printNumbers n) $ fmap (allInfo . processGitStatus . lines) status
-- main
main :: IO ()
main = gitstatus >>= printAll
| TheAtomicGoose/zsh-git-prompt | src/Main.hs | mit | 1,869 | 6 | 9 | 331 | 651 | 350 | 301 | 43 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{- |
Module : Language.Egison.Primitives
Licence : MIT
This module provides primitive functions in Egison.
-}
module Language.Egison.Primitives
( primitiveEnv
, primitiveEnvNoIO
) where
import Control.Monad.Except
import Data.IORef
import qualified Data.Sequence as Sq
import qualified Data.Vector as V
{-- -- for 'egison-sqlite'
import qualified Database.SQLite3 as SQLite
--} -- for 'egison-sqlite'
import Language.Egison.Data
import Language.Egison.Data.Collection (makeICollection)
import Language.Egison.IExpr (Index (..), stringToVar)
import Language.Egison.Math
import Language.Egison.Primitives.Arith
import Language.Egison.Primitives.IO
import Language.Egison.Primitives.String
import Language.Egison.Primitives.Types
import Language.Egison.Primitives.Utils
primitiveEnv :: IO Env
primitiveEnv = do
bindings <- forM (constants ++ primitives ++ ioPrimitives) $ \(name, op) -> do
ref <- newIORef . WHNF $ Value op
return (stringToVar name, ref)
return $ extendEnv nullEnv bindings
primitiveEnvNoIO :: IO Env
primitiveEnvNoIO = do
bindings <- forM (constants ++ primitives) $ \(name, op) -> do
ref <- newIORef . WHNF $ Value op
return (stringToVar name, ref)
return $ extendEnv nullEnv bindings
--
-- Constants
--
constants :: [(String, EgisonValue)]
constants = [ ("f.pi", Float 3.141592653589793)
, ("f.e" , Float 2.718281828459045)
]
--
-- Primitives
--
primitives :: [(String, EgisonValue)]
primitives =
map (\(name, fn) -> (name, PrimitiveFunc (fn name))) strictPrimitives
++ map (\(name, fn) -> (name, LazyPrimitiveFunc (fn name))) lazyPrimitives
++ primitiveArithFunctions
++ primitiveStringFunctions
++ primitiveTypeFunctions
where
strictPrimitives =
[ ("addSubscript", addSubscript)
, ("addSuperscript", addSuperscript)
, ("assert", assert)
, ("assertEqual", assertEqual)
]
lazyPrimitives =
[ ("tensorShape", tensorShape')
, ("tensorToList", tensorToList')
, ("dfOrder", dfOrder')
]
--
-- Miscellaneous primitive functions
--
tensorShape' :: String -> LazyPrimitiveFunc
tensorShape' = lazyOneArg tensorShape''
where
tensorShape'' (Value (TensorData (Tensor ns _ _))) =
return . Value . Collection . Sq.fromList $ map toEgison ns
tensorShape'' (ITensor (Tensor ns _ _)) =
return . Value . Collection . Sq.fromList $ map toEgison ns
tensorShape'' _ = return . Value . Collection $ Sq.fromList []
tensorToList' :: String -> LazyPrimitiveFunc
tensorToList' = lazyOneArg tensorToList''
where
tensorToList'' (Value (TensorData (Tensor _ xs _))) =
return . Value . Collection . Sq.fromList $ V.toList xs
tensorToList'' (ITensor (Tensor _ xs _)) = do
inners <- liftIO . newIORef $ Sq.fromList (map IElement (V.toList xs))
return (ICollection inners)
tensorToList'' x = makeICollection [x]
dfOrder' :: String -> LazyPrimitiveFunc
dfOrder' = lazyOneArg dfOrder''
where
dfOrder'' (Value (TensorData (Tensor ns _ is))) =
return $ Value (toEgison (fromIntegral (length ns - length is) :: Integer))
dfOrder'' (ITensor (Tensor ns _ is)) =
return $ Value (toEgison (fromIntegral (length ns - length is) :: Integer))
dfOrder'' _ = return $ Value (toEgison (0 :: Integer))
addSubscript :: String -> PrimitiveFunc
addSubscript = twoArgs $ \fn sub ->
case (fn, sub) of
(ScalarData (SingleSymbol (Symbol id name is)), ScalarData s@(SingleSymbol (Symbol _ _ []))) ->
return (ScalarData (SingleSymbol (Symbol id name (is ++ [Sub s]))))
(ScalarData (SingleSymbol (Symbol id name is)), ScalarData s@(SingleTerm _ [])) ->
return (ScalarData (SingleSymbol (Symbol id name (is ++ [Sub s]))))
_ -> throwErrorWithTrace (TypeMismatch "symbol or integer" (Value fn))
addSuperscript :: String -> PrimitiveFunc
addSuperscript = twoArgs $ \fn sub ->
case (fn, sub) of
(ScalarData (SingleSymbol (Symbol id name is)), ScalarData s@(SingleSymbol (Symbol _ _ []))) ->
return (ScalarData (SingleSymbol (Symbol id name (is ++ [Sup s]))))
(ScalarData (SingleSymbol (Symbol id name is)), ScalarData s@(SingleTerm _ [])) ->
return (ScalarData (SingleSymbol (Symbol id name (is ++ [Sup s]))))
_ -> throwErrorWithTrace (TypeMismatch "symbol" (Value fn))
assert :: String -> PrimitiveFunc
assert = twoArgs' $ \label test -> do
test <- fromEgison test
if test
then return $ Bool True
else throwErrorWithTrace (Assertion (show label))
assertEqual :: String -> PrimitiveFunc
assertEqual = threeArgs' $ \label actual expected ->
if actual == expected
then return $ Bool True
else throwErrorWithTrace (Assertion
(show label ++ "\n expected: " ++ show expected ++ "\n but found: " ++ show actual))
{-- -- for 'egison-sqlite'
sqlite :: PrimitiveFunc
sqlite = twoArgs' $ \val val' -> do
dbName <- fromEgison val
qStr <- fromEgison val'
ret <- liftIO $ query' (T.pack dbName) $ T.pack qStr
return $ makeIO $ return $ Collection $ Sq.fromList $ map (\r -> Tuple (map toEgison r)) ret
where
query' :: T.Text -> T.Text -> IO [[String]]
query' dbName q = do
db <- SQLite.open dbName
rowsRef <- newIORef []
SQLite.execWithCallback db q (\_ _ mcs -> do
row <- forM mcs (\mcol -> case mcol of
Just col -> return $ T.unpack col
Nothing -> return "null")
rows <- readIORef rowsRef
writeIORef rowsRef (row:rows))
SQLite.close db
ret <- readIORef rowsRef
return $ reverse ret
--} -- for 'egison-sqlite'
| egison/egison | hs-src/Language/Egison/Primitives.hs | mit | 5,956 | 0 | 20 | 1,510 | 1,636 | 872 | 764 | 98 | 3 |
module MaitreD where
import Data.Time (ZonedTime (..))
data Reservation =
Reservation { date :: ZonedTime, quantity :: Int, isAccepted :: Bool }
deriving (Show)
instance Eq Reservation where
x == y =
zonedTimeZone (date x) == zonedTimeZone (date y)
&& zonedTimeToLocalTime (date x) == zonedTimeToLocalTime (date y)
&& quantity x == quantity y
&& isAccepted x == isAccepted y
tryAccept :: Int -> [Reservation] -> Reservation -> Maybe Reservation
tryAccept capacity reservations reservation =
let reservedSeats = sum $ map quantity reservations
in if reservedSeats + quantity reservation <= capacity
then Just $ reservation { isAccepted = True }
else Nothing
| ploeh/dependency-rejection-samples | Haskell/MaitreD.hs | mit | 787 | 0 | 15 | 231 | 233 | 120 | 113 | 17 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Spell.Test where
import Control.Arrow (second)
import Data.Function (on)
import Data.List (groupBy, sortBy)
import qualified Data.Text as T
import qualified Data.Text.IO as TI
import Data.Trie
import Spell.Confusion (confusionPenalties)
import Spell.Edit
import System.IO
import System.IO.Unsafe (unsafePerformIO)
import Test.Hspec
import Test.QuickCheck
{-# NOINLINE corpus #-}
corpus :: Trie Char ()
corpus = unsafePerformIO $ do
h <- openFile "corpus.txt" ReadMode
c <- TI.hGetContents h
return . skeleton $ T.words c
spellTest :: Spec
spellTest = describe "Spell.Edit" $ do
context "with defaultPenalties" (test defaultPenalties)
context "with confusionPenalties" (test confusionPenalties)
test :: Penalties Char Double -> Spec
test p = do
describe "searchBestEdits" $ do
it "returns 100 first optimal elements in correct order" $ property $ \w ->
let trie = shrinkMatrices $ populate (calculateEdit p $ T.pack w) corpus
left = searchBestEdits Nothing $ expandPaths trie
right = sortBy (compare `on` snd) . map (second fst) $ toList trie
f = (==) `on` (map (sortBy (compare `on` fst)) . groupBy ((==) `on` snd))
in f left right
it "corrects “purlpe” to “purple” with costs ≤ 1.0 (checks reversals)" $
let check ("purple", x) = x <= 1.0
check _ = False
in check . head $ bestEdits p Nothing "purlpe" corpus
| fgrsnau/spell | test/Spell/Test.hs | mit | 1,574 | 0 | 23 | 416 | 464 | 244 | 220 | 37 | 2 |
-- Multiple choice
-- 1. A value of type [a] is
-- a) a list of alphabetic characters
-- b) a list of lists
-- c) a list whose elements are all of some type 𝑎 ***
-- d) a list whose elements are all of different types
-- 2. A function of type [[a]] -> [a] could
-- a) take a list of strings as an argument ***
-- b) transform a character into a string
-- c) transform a string in to a list of strings
-- d) take two arguments
-- 3. A function of type [a] -> Int -> a
-- a) takes one argument
-- b) returns one element of type 𝑎 from a list ***
-- c) must return an Int value
-- d) is completely fictional
-- 4. A function of type (a, b) -> a
-- a) takes a list argument and returns a Char value
-- b) has zero arguments
-- c) takes a tuple argument and returns the first value ***
-- d) requires that 𝑎 and 𝑏 be of different types Determine the type
-- For the following functions, determine the type of the specified value. Note:
-- you can type them into a file and load the contents of the file in GHCi. You
-- can then query the types a er you’ve loaded them.
-- 1. All function applications return a value. Determine the value returned by
-- these function applications and the type of that value.
-- a) (* 9) 6
-- 54
-- b) head [(0,"doge"),(1,"kitteh")]
--(0, "doge")
-- c) head [(0 :: Integer ,"doge"),(1,"kitteh")]
-- (0, "doge")
-- d) if False then True else False
-- False
-- e) length [1, 2, 3, 4, 5]
-- 5
-- f) (length [1, 2, 3, 4]) > (length "TACOCAT")
-- Bool
-- 2. Given
-- x=5 y=x+5 w = y * 10
-- What is the type of w?
-- Num
-- 3. Given
-- x=5 y=x+5
-- z y = y * 10
-- What is the type of z?
-- z :: (Num a) => a -> a
-- 4. Given
-- x=5 y=x+5 f=4/y
-- What is the type of f?
-- f :: (Fractional a) => a
-- 5. Given
-- x = "Julie"
-- y = " <3 "
-- z = "Haskell"
-- f = x ++ y ++ z
-- What is the type of f?
-- f :: String
-- Does it compile?
-- Yes???
-- For each set of expressions, figure out which expression, if any, causes the
-- compiler to squawk at you (n.b. we do not mean literal squawking) and why.
-- Fix it if you can.
-- 1.
-- bigNum = (^) 5
-- wahoo = bigNum $ 10
-- 2.
-- x' = print
-- y' = print "woohoo!"
-- z' = x' "hello world"
-- 3.
-- a' = (+)
-- b' = a'
-- c' = b' 10
-- d' = c' 200
-- 4.
-- a'' = 12 + b''
-- b'' = 10000 * c''
-- c'' = 3
-- Type variable or specific type constructor?
-- 1. You will be shown a type declaration, and you should categorize each type.
-- The choices are a fully polymorphic type variable, constrained polymorphic
-- type variable, or concrete type constructor.
-- f :: Num a => a -> b -> Int -> Int
-- [0] [1] [2] [3]
-- Here, the answer would be: constrained polymorphic (Num) ([0]), fully
-- polymorphic ([1]), and concrete ([2] and [3]).
-- 2. Categorize each component of the type signature as described in the previous example.
-- f :: zed -> Zed -> Blah
-- zed is fully polymorphic
-- Zed is concrete type constructor
-- Blah is concrete type constructor
-- 3. Categorize each component of the type signature
-- f :: Enum b => a -> b -> C
-- a is fully polymorphic type variable
-- b is constrained polymorphic type variable
-- C is a concrete type constructor.
-- 4. Categorize each component of the type signature
-- f :: f -> g -> C Write a type signature
-- f and g are fully polymorphic type variables
-- C is a concrete type constructor.
-- For the following expressions, please add a type signature. You should be
-- able to rely on GHCi type inference to check your work, although you might
-- not have precisely the same answer as GHCi gives (due to polymorphism, etc).
-- 1. While we haven’t fully explained this syntax yet, you’ve seen it in
-- Chapter 2 and as a solution to an exercise in Chapter 4. This syntax is a way
-- of destructuring a single element of a list.
functionH :: [x] -> x
functionH (x:_) = x
-- 2.
functionC :: (Ord x) => x -> x -> Bool
functionC x y = if (x > y) then True else False
-- 3.
functionS :: (a, b) -> b
functionS (x, y) = y
-- Given a type, write the function
-- You will be shown a type and a function that needs to be written. Use the
-- information the type provides to determine what the function should do. We’ll
-- also tell you how many ways there are to write the function. (Syntactically
-- different but semantically equivalent implementations are not counted as
-- being different).
-- 1. There is only one implementation that typechecks.
i :: a -> a
i a = a
-- 2. There is only one version that works.
c :: a -> b -> a
c a b = a
-- 3. Given alpha equivalence are c” and c (see above) the same thing?
c'' :: b -> a -> b
c'' a b = a
-- 4. Only one version that works.
c' :: a -> b -> b
c' a b = b
-- 5. There are multiple possibilities, at least two of which you’ve seen in
-- previous chapters.
r :: [a] -> [a]
r a = a
-- 6. Only one version that will typecheck.
--co :: (b -> c) -> (a -> b) -> (a -> c)
-- Having trouble with this one, I know it has to be the composition of the
-- second function with the first, but I can't get it to work???
-- 7. One version will typecheck.
a :: (a -> c) -> a -> a
a x y = y
-- 8. One version will typecheck.
a' :: (a -> b) -> a -> b
a' x y = x y
-- Fix it
-- Won’t someone take pity on this poor broken code and fix it up? Be sure to
-- check carefully for things like capitalization, parentheses, and indentation.
-- 1. module sing where
fstString :: [Char] -> [Char]
fstString x = x ++ " in the rain"
sndString :: [Char] -> [Char]
sndString x = x ++ " over the rainbow"
sing = if (x > y)
then fstString x
else sndString y
where x = "Singing"
y = "Somewhere"
-- 2. Now that it’s fixed, make a minor change and make it sing the other song.
-- If you’re lucky, you’ll end up with both songs stuck in your head!
-- The change would just be to swap the values of x and y.
-- 3. -- arith3broken.hs
-- module Arith3Broken where
main :: IO ()
main = do
print (1 + 2)
putStrLn "10"
print (negate (-1))
print ((+) 0 blah)
where blah = negate 1
-- Type-Kwon-Do
-- The name is courtesy Phillip Wright3, thank you for the idea!
-- The focus here is on manipulating terms in order to get the types to fit.
-- This sort of exercise is something you’ll encounter in writing real Haskell
-- code, so the practice will make it easier to deal with when you get there.
-- Practicing this will make you better at writing ordinary code as well.
-- We provide the types and bottomed out (declared as “undefined”) terms. Bottom
-- and undefined will be explained in more detail later. The contents of the
-- terms are irrelevant here. You’ll use only the declarations provided and what
-- the Prelude provides by default unless otherwise specified. Your goal is to
-- make the ???’d declaration pass the typechecker by modifying it alone.
-- Here’s a worked example for how we present these exercises and how you are
-- expected to solve them. Given the following:
data Woot
data Blah
f :: Woot -> Blah
f = undefined
g :: (Blah, Woot) -> (Blah, Blah)
g (b, w) = (b, b)
-- Here it’s 𝑔 that you’re supposed to implement; however, you can’t evaluate
-- anything. You’re to only use type-checking and type-inference to validate
-- your answers. Also note that we’re using a trick for defining datatypes which
-- can be named in a type signature, but have no values. Here’s an example of a
-- valid solution:
-- g :: (Blah, Woot) -> (Blah, Blah) g (b, w) = (b, f w)
-- The idea is to only fill in what we’ve marked with ???.
-- Not all terms will always be used in the intended solution for a problem.
-- 1.
f' :: Int -> String
f' = undefined
g' :: String -> Char
g' = undefined
h :: Int -> Char
h x = g' $ f' x
-- 2.
data A
data B
data C
q :: A -> B
q = undefined
w :: B -> C
w = undefined
e :: A -> C
e x = w $ q x
-- 3.
data X
data Y
data Z
xz :: X -> Z
xz = undefined
yz :: Y -> Z
yz = undefined
xform :: (X, Y) -> (Z, Z)
xform (a, b) = ((xz a), (yz b))
-- 4.
munge :: (x -> y) -> (y -> (w, z)) -> x -> w
munge a b c = fst $ b $ a c
| diminishedprime/.org | reading-list/haskell_programming_from_first_principles/05_09.hs | mit | 8,043 | 0 | 11 | 1,786 | 930 | 582 | 348 | -1 | -1 |
{-|
Module : Prelude.Betahaxx.Unicode
Re-export some basic base-unicode-symbols and add two of my own.
-}
module Prelude.Unicode.Betahaxx ( (≡), (≢), (≠), (≤), (≥), π, (⋅), ℤ, ℚ, (×), (§) ) where
import Prelude.Unicode ((≡), (≢), (≠), (≤), (≥), π, (⋅), ℤ, ℚ)
-- |Multiplication sign for multiplication.
-- I still think it's more readable and nicer than asterisk or center dot.
-- Although mathematically this is usually cross product or something
-- more complicated, so I'm not going to try to get it into some big library.
(×) :: Num a => a -> a -> a
(×) = (*)
infixl 7 ×
{-# INLINE (×) #-}
-- |(§) = @fmap@
--
-- U+00A7, SECTION SYMBOL
(§) :: Functor f => (a -> b) -> f a -> f b
(§) = fmap
infixl 4 §
{-# INLINE (§) #-}
| betaveros/betahaxx | Prelude/Unicode/Betahaxx.hs | mit | 778 | 0 | 8 | 149 | 197 | 136 | 61 | 10 | 1 |
import Eval
import Data
import Parser
import System( getArgs )
main = do
-- The name of the file to load is the first arg.
[f_name] <- getArgs
-- Parse the file.
maybe_parsed <- parseProgramFile f_name
-- Check if it parsed correctly.
case maybe_parsed of
Left err -> print err
Right parsed -> do
-- Set up the environment.
env <- init_env parsed
-- Call the main function.
result <- eval_exp env (Call "main" [])
-- Discard the result.
return ()
-- Initialise an environment with a parse tree.
init_env parsed = do
env <- newEnv
pushStack env
-- Add some constants.
sequence $ [setGlobalVar env word (IntegerVar num)
| (num, word) <- zip [0..10] $ words "zero one two three four five six seven eight nine ten"]
-- Comparison functions.
setGlobalVar env "equal" $ BuiltinMethod $ return . BoolVar . (\xs-> all (equal $ head xs) $ tail xs)
setGlobalVar env "greater" $ BuiltinMethod $ return . BoolVar . and . (\xs-> zipWith greater xs $ tail xs)
setGlobalVar env "nonep" $ BuiltinMethod $ return . BoolVar . (\xs-> all (equal NoneVar) $ xs)
setGlobalVar env "none" $ NoneVar
-- Load the methods from the parse tree.
load_env env parsed
return env
-- Load methods and blocks from a parse tree into an environment.
load_env env (part:rest) = do
case part of
Method name args stmts -> setGlobalVar env name $ MethodVar args stmts
Block name stmts -> setGlobalVar env name $ BlockVar stmts
load_env env rest
load_env env [] = return ()
| tomjnixon/buzzlang | src/Main.hs | mit | 1,500 | 0 | 16 | 322 | 465 | 223 | 242 | 30 | 2 |
module AppTest where
import System.Process
import System.Directory
import System.Exit
import System.FilePath
import System.IO
import Data.String.Utils
build_dir = "./dist/build"
test_dir = "./test"
type ProgName = String
type TestName = String
runTestCase :: ProgName -> TestName -> String -> IO ExitCode
runTestCase pname tname args = do
let prog = build_dir `combine` pname `combine` pname
let ftname = join "_" [pname, tname]
let obtained = test_dir `combine` (ftname ++ ".out")
let expected = test_dir `combine` (ftname ++ ".exp")
exitCode <- runProgram prog args obtained
case exitCode of
ExitFailure val -> exitWith exitCode
ExitSuccess -> compareOutputs obtained expected
-- Allows to bind (as in >>=) tests together, propagating failure should it
-- happen.
thenTestCase :: ProgName -> TestName -> String -> ExitCode -> IO ExitCode
thenTestCase pname tname args exit = case exit of
ExitFailure val -> return exit
ExitSuccess -> runTestCase pname tname args
-- Run program (1st arg), passes arg to it via 2nd arg (space-sparated
-- arguments), 3rd arg is name of output file. This assumes that the program to
-- test send output to stdout.
runProgram :: FilePath -> String -> FilePath -> IO ExitCode
runProgram prog args obt = do
let progCmd = join " " [prog, args, ">", obt]
let progProcess = shell progCmd
(i,o,e,h) <- createProcess progProcess
waitForProcess h
-- Compare obtained with expected outputs, using diff(1).
--
compareOutputs :: FilePath -> FilePath -> IO ExitCode
compareOutputs a b = do
let diffCmd = join " " ["diff", "-sq", a, b]
let diffProcess = shell diffCmd
(i,o,e,h) <- createProcess diffProcess
waitForProcess h
| tjunier/mlgsc | test/AppTest.hs | mit | 1,685 | 2 | 12 | 298 | 484 | 252 | 232 | 37 | 2 |
{-# LANGUAGE ViewPatterns #-}
module Y2021.M04.D28.Solution where
{--
This is interesting
>>> Nothing > Just 70
False
>>> Nothing < Just 70
True
... huh. So Nothing is ... Just 0? That, for me, isn't good. I don't want
something to succeed when I have only partial data.
Pesky me.
So, we have some functions that take two values, dependent on both, and
some other functions, that, to conform to the interface, takes two values,
but only depends on the first value.
Why would I do that?
Trending data and analytics. Some analytics depend on a trend, established
over a time series, and some analytics are realized from current data (only).
Take indicators from the stock market, for example. Some indicators, like the
SMA50/200 (Simple Moving Averages 50 (days) and 200 (days)) require a cross-
over from the previous period to this period:
buy = yesterday (sma50 < sma200) && today (sma50 > sma200)
Whereas the Relative Strength Index has a buy or sell signal dependent only
on a cross-over in this period
buy = today (rsi14 < 30)
sell = today (rsi14 > 70)
But you may not always have trending data, for example: from a new security.
Let's do this.
You have a Time-series of trending data.
--}
import Control.Arrow (second)
import Control.Monad (liftM2)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (listToMaybe, mapMaybe)
import Data.Set (Set)
import qualified Data.Set as Set
import Control.Map (snarf) -- lol
data Trend = Trend { sma50, sma200, rsi14 :: Maybe Double }
deriving (Eq, Ord, Show)
-- note: you may have some, or all, trending data.
-- And you have function-type that takes trending data and returns a buy/sell
-- recommendation
data Call = BUY | SELL
deriving (Eq, Ord, Show)
data Basis = GoldenCross | DeathCross | RSI70 | RSI30
deriving (Eq, Ord, Show)
data Recommendation = Rec Call Basis
deriving (Eq, Ord, Show)
type RunRec = Trend -> Trend -> Maybe Recommendation
{--
Today's Haskell problem is a two-layered cake (with icing, of course):
First, the sma functions need both today's and yesterday's trends (as described
above). The RSI functions need only today's trends.
ANY function will fail if the indicator in the trend is not present.
From a time-series of trends, collect and return buy/sell recommendations.
DISCLAIMER! Please note, all data provided are FAKE, MADE UP, INACCURATE.
A BUY or SELL recommendation here is NOT financial advice in any way, shape,
or form, so ... THERE!
OKAY!
So, let's pretend we have three companies. One that has one set of trending
data, and the other two that have a series of trending data, complete or
incomplete.
The timeseries goes into the past: the first element is today's trends, the
second element is yesterday's trends, third, day before's, ... etc.
--}
abc, xyz, pqr :: [Trend]
abc = [Trend (Just 7.4) Nothing (Just 55)]
xyz = [Trend (Just 10) (Just 20) (Just 27), Trend (Just 11) Nothing (Just 12)]
pqr = [Trend (Just 7) (Just 15) (Just 45), Trend (Just 17) (Just 14) (Just 59)]
-- Now we have recommendation functions
-- to set up, we need functions that compare data in the monadic domain
lt, gt :: Maybe Double -> Maybe Double -> Maybe Bool
lt = liftM2 (<)
gt = liftM2 (>)
nd :: Maybe Bool -> Maybe Bool -> Maybe Bool
nd = liftM2 (&&)
-- now, define implication:
(-|) :: Bool -> a -> Maybe a
True -| q = Just q
False -| _ = Nothing
-- now: using (-|) create (=|)
(=|) :: Maybe Bool -> a -> Maybe a
p =| q = p >>= (-| q)
-- the 'Golden Cross' says SMA50 crosses above the SMA200 from yesterday to
-- today.
goldenCross :: RunRec
goldenCross today yesterday =
(sma50 today `gt` sma200 today)
`nd` (sma50 yesterday `lt` sma200 yesterday) =| Rec BUY GoldenCross
-- The 'Death Cross' says the dual
deathCross :: RunRec
deathCross today yesterday =
(sma50 today `lt` sma200 today)
`nd` (sma50 yesterday `gt` sma200 yesterday) =| Rec SELL DeathCross
-- The RSI 14 cases:
rsi70, rsi30 :: RunRec
rsi70 today _ = rsi14 today `gt` Just 70 =| Rec SELL RSI70
rsi30 today _ = rsi14 today `lt` Just 30 =| Rec BUY RSI30
-- now the rsi-functions can be run straight off, but the cross-functions
-- need to be lifted:
type RunRec' = Trend -> Maybe Trend -> Maybe Recommendation
-- write a function to convert an RunRec-function to a RunRec' one.
toRunRec' :: RunRec -> RunRec'
toRunRec' f t0 mbt1 = mbt1 >>= f t0
-- run the functions against the companies and return a set of recommendations
-- (if any) for each company
type Company = String
runRecs :: [RunRec] -> [(Company, [Trend])] -> Map Company (Set Recommendation)
runRecs (map toRunRec' -> recs) =
Map.fromList
. filter (not . (== Set.empty) . snd)
. map (second (flip runRec recs))
runRec :: [Trend] -> [RunRec'] -> Set Recommendation
runRec (t0:ts) = Set.fromList . mapMaybe (flip uncurry (t0, listToMaybe ts))
recs :: [RunRec]
recs = [goldenCross, deathCross, rsi70, rsi30]
-- what are the Buy or Sell recommendations for abc, xyz, and pqr?
{--
>>> runRecs recs (zip (words "abc xyz pqr") [abc, xyz, pqr])
fromList [("pqr",fromList [Rec SELL DeathCross]),("xyz",fromList [Rec BUY RSI30])]
--}
| geophf/1HaskellADay | exercises/HAD/Y2021/M04/D28/Solution.hs | mit | 5,142 | 0 | 12 | 978 | 994 | 550 | 444 | 57 | 1 |
{-
Number letter counts
Problem 17
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.
-}
units = [ "zero"
, "one"
, "two"
, "three"
, "four"
, "five"
, "six"
, "seven"
, "eight"
, "nine"
, "ten"
, "eleven"
, "twelve"
, "thirteen"
, "fourteen"
, "fifteen"
, "sixteen"
, "seventeen"
, "eighteen"
, "nineteen"
]
tens = [ "unit"
, "ten"
, "twenty"
, "thirty"
, "forty"
, "fifty"
, "sixty"
, "seventy"
, "eighty"
, "ninety"
]
number2Text n
| n == 0 = ""
| n < 20 = units !! n
| n < 100 = tens !! (n `div` 10) ++ number2Text (n `mod` 10)
| n < 1000 = hundreds (n `div` 100) ++ hundredsTens (n `mod` 100)
| n < 1000000 = number2Text (n `div` 1000) ++ "thousand" ++ number2Text (n `mod` 1000)
where
hundreds h = (units !! h) ++ "hundred"
hundredsTens 0 = ""
hundredsTens t = "and" ++ number2Text t
euler17 = length (concat (map number2Text [1..1000]))
| feliposz/project-euler-solutions | haskell/euler17.hs | mit | 1,559 | 0 | 10 | 528 | 336 | 188 | 148 | 40 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Haskmon.Types.Internals where
import Data.Aeson
import Data.Aeson.Types
import Data.Time.Format
import Data.Time.Clock
import Control.Monad(mzero)
import Haskmon.Resource(getResource)
-- {{{ MetaData
-- | Metadata that all resources (except Pokedex) have in common
data MetaData = MetaData {
resourceUri :: String,
created :: UTCTime,
modified :: UTCTime
} deriving Show
getMetadata :: Object -> Parser MetaData
getMetadata v = MetaData <$>
v .: "resource_uri" <*>
convert (v .: "created") <*>
convert (v .: "modified")
where convert :: Parser String -> Parser UTCTime
convert ps = readTime' defaultTimeLocale formatStr <$> ps
readTime' = parseTimeOrError True
formatStr = "%FT%R:%S%Q"
-- Alias for withObject
withO :: Value -> (Object -> Parser a) -> Parser a
withO o f = withObject "object" f o
-- }}}
-- Pokedex {{{
data Pokedex = Pokedex {
pokedexName :: String,
pokedexPokemons :: [MetaPokemon]
}
instance Show Pokedex where
show p = "<Pokedex - " ++ pokedexName p ++ ">"
instance FromJSON MetaPokemon where
parseJSON v = withO v $
\o -> MetaPokemon <$> o .: "name" <*> (getResource <$> o .: "resource_uri")
instance FromJSON Pokedex where
parseJSON (Object o) = Pokedex <$> o .: "name" <*> o .: "pokemon"
parseJSON _ = mzero
-- }}}
-- Pokemon {{{
data MetaPokemon = MetaPokemon { mPokemonName :: String, getPokemon :: IO Pokemon }
instance Show MetaPokemon where
show p = "<MetaPokemon - " ++ mPokemonName p ++ ">"
data Pokemon = Pokemon {
pokemonName :: String,
pokemonNationalId :: Word,
pokemonAbilities :: [MetaAbility],
pokemonMoves :: [MetaMove],
pokemonTypes :: [MetaType],
pokemonEggCycle :: Word,
pokemonEggGroups :: [MetaEggGroup],
pokemonCatchRate :: Word,
pokemonHp :: Word,
pokemonAttack :: Word,
pokemonDefense :: Word,
pokemonSpAtk :: Word,
pokemonSpDef :: Word,
pokemonSpeed :: Word,
pokemonEvolutions :: [Evolution],
pokemonSprites :: [MetaSprite],
pokemonDescriptions :: [MetaDescription],
pokemonMetadata :: MetaData
} deriving Show
instance FromJSON Pokemon where
parseJSON o = withO o go
where go v = Pokemon <$>
v .: "name" <*>
v .: "national_id" <*>
v .: "abilities" <*>
v .: "moves" <*>
v .: "types" <*>
v .: "egg_cycles" <*>
v .: "egg_groups" <*>
v .: "catch_rate" <*>
v .: "hp" <*>
v .: "attack" <*>
v .: "defense" <*>
v .: "sp_atk" <*>
v .: "sp_def" <*>
v .: "speed" <*>
v .: "evolutions" <*>
v .: "sprites" <*>
v .: "descriptions" <*>
getMetadata v
--- }}}
-- Evolution {{{
data Evolution = Evolution {
evolutionName :: String,
evolutionMethod :: EvolutionMethod,
evolutionPokemon :: IO Pokemon
}
instance Show Evolution where
show e = "<Evolution - " ++ evolutionName e ++ ">"
data EvolutionMethod = EvolutionLevelUp LevelUpDetail
| EvolutionFriendship
| EvolutionStone
| EvolutionHappiness
| EvolutionTrade
| EvolutionOther -- Plain other...no info whatsoever
deriving Show
data LevelUpDetail = Level Word
| LevelSpecial
deriving Show
instance FromJSON EvolutionMethod where
parseJSON o = withO o $ \v ->
do method <- v .: "method" :: Parser String
case method of
"trade" -> return EvolutionTrade
"stone" -> return EvolutionStone
"level_up" -> EvolutionLevelUp <$> maybe LevelSpecial Level <$> v .:? "level"
"other" -> go $ v .:? "detail"
els -> fail $ "Expected an Evolution type. Got " ++ els
where go pt = do str <- pt
case str of
Nothing -> return EvolutionOther
Just "happiness" -> return EvolutionHappiness
Just "friendship" -> return EvolutionFriendship
Just l -> fail $ "Expected happiness or friendship, got " ++ l
instance FromJSON Evolution where
parseJSON o = withO o $ \v -> Evolution <$>
v .: "to" <*>
parseJSON o <*>
(getResource <$> v .: "resource_uri")
-- }}}
-- Ability {{{
data MetaAbility = MetaAbility { mAbilityName :: String, getAbility :: IO Ability}
instance Show MetaAbility where
show p = "<MetaAbility - " ++ mAbilityName p ++ ">"
data Ability = Ability { abilityName :: String,
abilityDescription :: String,
abilityMetadata :: MetaData
} deriving Show
instance FromJSON Ability where
parseJSON o = withO o $ \v -> Ability <$>
v .: "name" <*>
v .: "description" <*>
getMetadata v
instance FromJSON MetaAbility where
parseJSON v = withO v $ \o -> MetaAbility <$> o .: "name" <*>
(getResource <$> o .: "resource_uri")
-- }}}
-- Types {{{
data MetaType = MetaType { mTypeName :: String, getType :: IO Type }
instance Show MetaType where
show p = "<MetaType - " ++ mTypeName p ++ ">"
data Type = Type {
typeName :: String,
typeIneffective :: [Type],
typeNoEffect :: [Type],
typeResistance :: [Type],
typeSuperEffective :: [Type],
typeWeakness :: [Type],
typeMetadata :: MetaData
} deriving Show
instance FromJSON Type where
parseJSON v = withO v $ \o -> Type <$>
o .: "name" <*>
o .: "ineffective" <*>
o .: "no_effect" <*>
o .: "resistance" <*>
o .: "super_effective" <*>
o .: "weakness" <*>
getMetadata o
instance FromJSON MetaType where
parseJSON v = withO v $ \o -> MetaType <$> o .: "name" <*>
(getResource <$> o .: "resource_uri")
-- }}}
-- Moves {{{
data MetaMoveLearnType = MoveLearnLevelUp Word
| MoveLearnMachine
| MoveLearnTutor
| MoveLearnEggMove
| MoveLearnOther deriving Show
data MetaMove = MetaMove { mMoveName :: String,
mMoveLearnType :: MetaMoveLearnType,
getMove :: IO Move}
instance Show MetaMove where
show p = "<MetaMove - " ++ mMoveName p ++ ">"
data Move = Move {
moveName :: String,
movePower :: Word,
movePp :: Word,
moveAccuracy :: Word,
moveMetadata :: MetaData
} deriving Show
instance FromJSON Move where
parseJSON v = withO v $ \o -> Move <$>
o .: "name" <*>
o .: "power" <*>
o .: "pp" <*>
o .: "accuracy" <*>
getMetadata o
instance FromJSON MetaMove where
parseJSON v = withO v go
where go o = MetaMove <$> o .: "name" <*>
mmLearnType <*>
(getResource <$> o .: "resource_uri")
where mmLearnType :: Parser MetaMoveLearnType
mmLearnType = do
learnType <- o .: "learn_type" :: Parser String
case learnType of
"level up" -> MoveLearnLevelUp <$> (o .: "level")
"machine" -> return MoveLearnMachine
"tutor" -> return MoveLearnTutor
"egg move" -> return MoveLearnEggMove
"other" -> return MoveLearnOther
err -> fail $ "expected level_up, machine, tutor, egg_move or other. Got " ++ err
-- }}}
-- EGGS!!! {{{
data MetaEggGroup = MetaEggGroup {
mEggGroupName :: String,
getEggGroup :: IO EggGroup
}
instance Show MetaEggGroup where
show p = "<MetaEggGroup - " ++ mEggGroupName p ++ ">"
data EggGroup = EggGroup { eggGroupName :: String,
eggGroupPokemons :: [MetaPokemon],
eggGroupMetadata :: MetaData
} deriving Show
instance FromJSON EggGroup where
parseJSON v = withO v $ \o -> EggGroup <$>
o .: "name" <*>
o .: "pokemon" <*>
getMetadata o
instance FromJSON MetaEggGroup where
parseJSON v = withO v $ \o -> MetaEggGroup <$>
o .: "name" <*>
(getResource <$> o .: "resource_uri")
--- }}}
-- Description {{{
data MetaDescription = MetaDescription {
mDescriptionName :: String,
getDescriptions :: IO Description
}
data Description = Description {
descriptionName :: String,
descriptionText :: String,
descriptionGames :: [MetaGame],
descriptionPokemon :: MetaPokemon,
descriptionMetadata :: MetaData
} deriving Show
instance Show MetaDescription where
show set = "<MetaDescription - " ++ mDescriptionName set ++ ">"
instance FromJSON Description where
parseJSON v = withO v $ \o -> Description <$>
o .: "name" <*>
o .: "description" <*>
o .: "games" <*>
o .: "pokemon" <*>
getMetadata o
instance FromJSON MetaDescription where
parseJSON v = withO v $ \o -> MetaDescription <$>
o .: "name" <*>
(getResource <$> o .: "resource_uri")
-- }}}
-- Game {{{
data MetaGame = MetaGame { mGameName :: String, getGame :: IO Game }
instance Show MetaGame where
show set = "<MetaGame - " ++ mGameName set ++ ">"
data Game = Game {
gameName :: String,
gameGeneration :: Word,
gameReleaseYear :: Word,
gameMetadata :: MetaData
} deriving Show
instance FromJSON MetaGame where
parseJSON v = withO v $ \o -> MetaGame <$>
o .: "name" <*> (getResource <$> o .: "resource_uri")
instance FromJSON Game where
parseJSON v = withO v $ \o -> Game <$>
o .: "name"<*>
o .: "generation" <*>
o .: "release_year" <*>
getMetadata o
-- }}}
-- Sprite {{{
data MetaSprite = MetaSprite { mSpriteName :: String, getSprite :: IO Sprite }
instance Show MetaSprite where
show set = "<MetaSprite - " ++ mSpriteName set ++ ">"
data Sprite = Sprite {
spriteName :: String,
spritePokemon :: MetaPokemon,
spriteImage :: String -- Just a plain URI
} deriving Show
instance FromJSON MetaSprite where
parseJSON v = withO v $ \o -> MetaSprite <$>
o .: "name" <*>
(getResource <$> o .: "resource_uri")
instance FromJSON Sprite where
parseJSON v = withO v $ \o -> Sprite <$>
o .: "name" <*>
o .: "pokemon" <*>
o .: "image"
-- }}}
| bitemyapp/Haskmon | src/Haskmon/Types/Internals.hs | mit | 13,316 | 5 | 42 | 6,112 | 2,696 | 1,449 | 1,247 | 269 | 1 |
-----------------------------------------------------------------------------
--
-- Module : Drool.VisualConfig
-- Copyright : 2012, Tobias Fuchs
-- License : MIT
--
-- Maintainer : twh.fuchs@gmail.com
-- Stability : experimental
-- Portability : POSIX
--
-- |
--
-----------------------------------------------------------------------------
module Drool.VisualConfig (
VisualConfig
) where
data VisualConfig = VisualConfig { incRotation :: RotationVector, -- Incremental rotation step size
incRotationAccum :: RotationVector, -- Incremental rotation accumulated value (sum of step sizes)
fixedRotation :: RotationVector, -- Fixed rotation vector
rotationUseGlobal :: Bool,
-- Light:
light0 :: LightConfig,
light1 :: LightConfig,
lightUseGlobal :: Bool,
-- Colors:
gridMaterial :: MaterialConfig,
surfaceMaterial :: MaterialConfig,
gridOpacity :: GLfloat,
surfaceOpacity :: GLfloat,
-- Perspective:
renderPerspective :: RenderPerspective,
autoPerspectiveSwitch :: Bool,
autoPerspectiveSwitchInterval :: Int,
perspectiveUseGlobal :: Bool,
-- View:
viewAngle :: GLfloat,
viewDistance :: GLfloat,
-- Blending:
blendModeSourceIdx :: Int,
blendModeFrameBufferIdx :: Int }
| fuchsto/drool | src/Drool/VisualConfig.hs | mit | 2,024 | 0 | 8 | 988 | 155 | 109 | 46 | 21 | 0 |
-- | Git utilities.
module Stackage.View.Git where
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Resource
import Data.Conduit
import qualified Data.Conduit.List as CL
import Data.Conduit.Process
import qualified Data.Conduit.Text as CT
import Data.List
import Data.Set (Set)
import qualified Data.Set as S
import qualified Data.Text as T
import Filesystem.Path (FilePath)
import qualified Filesystem.Path.CurrentOS as FP
import Prelude hiding (FilePath)
-- | Get files in the Git repo.
getGitFiles :: (MonadThrow m,MonadIO m)
=> m (Set FilePath)
getGitFiles =
do (_,ps) <- sourceProcessWithConsumer
(proc "git" ["ls-files"])
(CT.decodeUtf8 $= CT.lines $= CL.consume)
return (S.fromList
(map (FP.decodeString . T.unpack)
(T.words (T.unlines ps))))
| fpco/stackage-view | server/Stackage/View/Git.hs | mit | 960 | 0 | 16 | 275 | 245 | 147 | 98 | 24 | 1 |
--
-- riot/Riot/Locale.hs
--
-- Copyright (c) Tuomo Valkonen 2004-2006.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
module Riot.Locale(
to_locale,
from_locale
) where
import Foreign.C.String(withCString, peekCString)
import Ginsu.CWString(withLCString, peekLCString)
#ifdef CF_CHARSET_SUPPORT
to_locale str = withLCString str (\s -> peekCString s)
from_locale str = withCString str (\s -> peekLCString s)
#else
to_locale str = return str
from_locale str = return str
#endif
| opqdonut/riot | Riot/Locale.hs | gpl-2.0 | 706 | 0 | 8 | 119 | 102 | 63 | 39 | 7 | 1 |
module H33 where
myGCD :: (Integral i) => i -> i -> i
myGCD 0 y = y
myGCD x y
| x < 0 = myGCD (-x) y
| y < 0 = myGCD x (-y)
| x > y = myGCD y x
| otherwise = myGCD (y `mod` x) x
coprime :: (Integral i) => i -> i -> Bool
coprime a b = myGCD a b == 1
| hsinhuang/codebase | h99/H33.hs | gpl-2.0 | 269 | 0 | 8 | 92 | 171 | 86 | 85 | 10 | 1 |
import Data.Numbers.Primes
import qualified Data.Map as M
import Data.List
-- 2: {2}
-- 3: {3}
-- 4: {2^2}
-- 5: {5}
-- 6: {2, 3}
-- 7: {7}
-- 8: {2^3}
-- 9: {3^2}
-- 10: {2, 5}
-- 11: {11}
-- 12: {2, 3}
-- 13: {13}
-- 14: {2^2, 7}
-- 15: {3, 5}
-- 16: {2^4}
-- 17: {17}
-- 18: {2, 3^2}
-- 19: {19}
-- 20: {2^2, 5}
-- ==>
-- x: {2^4, 3^2, 5, 7, 11, 13, 17, 19} =
-- 16*9*5*7*11*13*17*19 = ?
factorLists :: Integer -> [[Integer]]
factorLists n = map primeFactors [2..n]
factorMaps :: Integer -> [M.Map Integer Int]
factorMaps n = map toFactorMap $ factorLists n
toFactorMap :: [Integer] -> M.Map Integer Int
toFactorMap xs = let groups = group xs
assocs = map toAssoc groups
in M.fromList assocs
toAssoc :: [Integer] -> (Integer,Int)
toAssoc xs = (head xs, length xs)
finalMap n = M.unionsWith max $ factorMaps n
mult n = product $ map f $ M.toList $ finalMap n
where f (x,y) = x ^ y
| AntoineSavage/haskell | project_euler/p1-50/p5/main.hs | gpl-2.0 | 955 | 0 | 9 | 250 | 274 | 152 | 122 | 16 | 1 |
-- |
-- Module : Language.Go.Parser.Parser
-- Copyright : (c) 2011 Andrew Robbins
-- License : GPLv3 (see COPYING)
--
-- This module provides parsers for the various Go language elements.
{- LANGUAGE CPP -}
module Language.Go.Parser.Parser (
-- * All-in-one parsers
goParse,
goParseFileWith,
goParseTestWith,
-- * Tokenizing and parsing a token stream
goTokenize,
goParseTokens,
-- * Parsers for main language elements
goSource,
goImportDecl,
goTopLevelDecl,
goType,
goBlock,
goExpression,
goStatement,
) where
import Language.Go.Parser.Operators
import Language.Go.Parser.Tokens
import Language.Go.Parser.Lexer (alexScanTokens)
import Language.Go.Syntax.AST
import Control.Monad
import Data.Maybe (isJust, catMaybes)
import Text.Parsec.Prim hiding (token)
import Text.Parsec.Error (ParseError)
import Text.Parsec.Combinator
-- | Tokenize Go language source code
--
-- This is where semicolons are inserted into the token stream.
-- We also filter out comments here, so any comment processing
-- must occur before this stage.
--
-- See also: 4.3. Semicolons
goTokenize :: String -> [GoTokenPos]
goTokenize = insertSemi . stripComments . alexScanTokens
-- | Parse Go Language source code into AST
goParse :: String -> String -> Either ParseError GoSource
goParse filename s = goParseTokens filename $ goTokenize s
-- | Parse Go Language token list into AST
goParseTokens :: String -> [GoTokenPos] -> Either ParseError GoSource
goParseTokens filename toks = runGoParser goSource filename toks
goParseFileWith :: GoParser a -> String -> String -> Either ParseError a
goParseFileWith start filename s = runGoParser start filename (goTokenize s)
goParseTestWith :: GoParser a -> String -> Either ParseError a
goParseTestWith start s = runGoParser start "" (goTokenize s)
--
-- Begin specification grammar
--
-- | Standard @Type@
--
-- See also: SS. 6. Types
goType :: GoParser GoType
goType = goTypeName
<|> goTypeLit
<|> goParen goType
-- | Standard @TypeName@
--
-- See also: SS. 6. Types
goTypeName :: GoParser GoType
goTypeName = do
(GoQual q n) <- goQualifiedIdent
return $ GoTypeName q n
-- | Standard @TypeLit@
--
-- See also: SS. 6. Types
goTypeLit :: GoParser GoType
goTypeLit = (try goSliceType)
<|> goArrayType
<|> goStructType
<|> goPointerType
<|> goFunctionType
<|> goInterfaceType
<|> goMapType
<|> goChannelType
-- See also: SS. 6.1. Boolean types
-- See also: SS. 6.2. Numeric types
-- See also: SS. 6.3. String types
-- | Standard @ArrayType@
--
-- See also: SS. 6.4. Array types
goArrayType :: GoParser GoType
goArrayType = do
l <- goBracket goExpression -- Go @ArrayLength@
t <- goType -- Go @ElementType@
return $ GoArrayType l t
-- | Standard @SliceType@
--
-- See also: SS. 6.5. Slice types
goSliceType :: GoParser GoType
goSliceType = do
goTokLBracket
goTokRBracket
liftM GoSliceType goType
-- | Standard @StructType@
--
-- See also: SS. 6.6. Struct types
goStructType :: GoParser GoType
goStructType = do
goTokStruct
liftM GoStructType $ goBlockish goFieldDecl
-- | Standard @FieldDecl@
--
-- See also: SS. 6.6. Struct types
goFieldDecl :: GoParser GoFieldType
goFieldDecl = (try field) <|> anonymous where
parseTag = do
let strlit = token (GoTokStr Nothing "")
GoTokStr (Just lit) s <- try strlit
return $ GoLitStr lit s
field = do -- Go @FieldDecl@
ids <- goIdentifierList
t <- goType
tag <- optionMaybe parseTag
return $ GoFieldType tag ids t
anonymous = do -- Go @AnonymousField@
a <- optionMaybe goTokAsterisk -- "*"
t <- goTypeName -- TypeName
tag <- optionMaybe parseTag
return $ GoFieldAnon tag (isJust a) t
-- | Standard @PointerType@
--
-- See also: SS. 6.7. Pointer types
goPointerType :: GoParser GoType
goPointerType = do
goTokAsterisk
liftM GoPointerType goType -- Go @BaseType@
-- | Standard @FunctionType@
--
-- See also: SS. 6.8. Function types
goFunctionType :: GoParser GoType
goFunctionType = do
goTokFunc
liftM GoFunctionType goSignature
-- | Standard @Signature@
--
-- See also: SS. 6.8. Function types
goSignature :: GoParser GoSig
goSignature = do
par <- goParameters
res <- option [] goResult
return $ GoSig par res
-- | Standard @Result@
--
-- See also: SS. 6.8. Function types
goResult :: GoParser [GoParam]
goResult = goParameters
<|> do ty <- goType ; return [GoParam [] ty]
-- | Standard @Parameters@
--
-- See also: SS. 6.8. Function types
goParameters :: GoParser [GoParam]
goParameters = do
goTokLParen
params <- option [] $ do
ps <- goParameterList
optional goTokComma
return ps
goTokRParen
return params
-- | Standard @ParameterList@
--
-- See also: SS. 6.8. Function types
goParameterList :: GoParser [GoParam]
goParameterList = sepBy goParameterDecl goTokComma
-- | Standard @ParameterDecl@
--
-- See also: SS. 6.8. Function types
goParameterDecl :: GoParser GoParam
goParameterDecl = (try goParameterDecl') <|> goParameterDecl'' where
goParameterDecl' :: GoParser GoParam
goParameterDecl' = do
is <- option [] goIdentifierList
t <- try goVariadicType <|> goType
return $ GoParam is t
goParameterDecl'' :: GoParser GoParam
goParameterDecl'' = do
t <- try goVariadicType <|> goType
return $ GoParam [] t
-- | Standard @InterfaceType@
--
-- See also: SS. 6.9. Interface types
goInterfaceType :: GoParser GoType
goInterfaceType = do
goTokInterface
xs <- goBlockish goMethodSpec
return $ GoInterfaceType xs
-- | Standard @MethodSpec@
--
-- See also: SS. 6.9. Interface types
goMethodSpec :: GoParser GoMethSpec
goMethodSpec = try goMethodSpec' <|> goMethodSpec'' where
goMethodSpec'' = do
GoQual pkg id <- goQualifiedIdent -- Go @InterfaceTypeName@
return $ GoIfaceName pkg id
goMethodSpec' = do
n <- goIdentifier -- Go @MethodName@
s <- goSignature
return $ GoMethSpec n s
-- | Standard @MapType@
--
-- See also: SS. 6.10. Map types
goMapType :: GoParser GoType
goMapType = do
goTokMap
kt <- goBracket goType -- Go @KeyType@
et <- goType -- Go @ElementType@
return $ GoMapType kt et
-- | Standard @ChannelType@
--
-- See also: SS. 6.11. Channel types
goChannelType :: GoParser GoType
goChannelType = do
qi <- goChannelQuip
ty <- goType
return $ GoChannelType qi ty
-- | Nonstandard
goChannelQuip :: GoParser GoChanKind
goChannelQuip = do goTokArrow ; goTokChan ; return GoIChan -- 1=RecvDir
<|> (try $ do goTokChan ; goTokArrow ; return GoOChan) -- 2=SendDir
<|> (try $ do goTokChan ; return GoIOChan) -- 3=BothDir
-- See also: SS. 7.1. Type identity
-- See also: SS. 7.2. Assignability
-- | Standard @Block@
--
-- See also: SS. 8. Blocks
goBlock :: GoParser GoBlock
goBlock = do liftM GoBlock $ goBlockish goStatement
-- | Nonstandard
goBlockish :: GoParser a -> GoParser [a]
goBlockish p = goBrace $ do
lines <- sepEndBy (optionMaybe p) goTokSemicolon
return $ catMaybes lines
-- | Standard @Declaration@
--
-- See also: SS. 9. Declarations and scope
goDeclaration :: GoParser GoDecl
goDeclaration = goConstDecl
<|> goTypeDecl
<|> goVarDecl
-- <?> "declaration"
-- | Standard @TopLevelDecl@
--
-- See also: SS. 9. Declarations and scope
goTopLevelDecl :: GoParser GoDecl
goTopLevelDecl = goDeclaration
<|> try goFunctionDecl
<|> try goMethodDecl
-- <?> "top-level declaration"
-- | Standard @ConstDecl@
--
-- See also: SS. 9.5. Constant declarations
goConstDecl :: GoParser GoDecl
goConstDecl = goTokConst >> liftM GoConst (goParenish $ try goConstSpec)
-- | Standard @ConstSpec@
goConstSpec :: GoParser GoCVSpec
goConstSpec = do
id <- goIdentifierList
option (GoCVSpec id Nothing []) (try (goConstSpec' id) <|> goConstSpec'' id) where
goConstSpec' :: [GoId] -> GoParser GoCVSpec
goConstSpec' ids = do
goTokEqual
exs <- goExpressionList
return $ GoCVSpec ids Nothing exs
goConstSpec'' :: [GoId] -> GoParser GoCVSpec
goConstSpec'' ids = do
typ <- goType
goTokEqual
exs <- goExpressionList
return $ GoCVSpec ids (Just typ) exs
goIdentifier :: GoParser GoId
goIdentifier = do
GoTokId name <- token $ GoTokId ""
return $ GoId name
-- | Standard @IdentifierList@
--
-- See also: SS. 9.5. Constant declarations
goIdentifierList :: GoParser [GoId]
goIdentifierList = sepBy1 goIdentifier goTokComma
-- | Standard @ExpressionList@
--
-- See also: SS. 9.5. Constant declarations
goExpressionList :: GoParser [GoExpr]
goExpressionList = try exprs <|> return []
where exprs = do
-- custom implementation of sepBy that doesn't
-- fail on [x0 comma ... xn comma y]
x <- goExpression
xs <- many $ try (goTokComma >> goExpression)
return (x:xs)
-- | Nonstandard, includes @ConstSpec@, @VarSpec@
--
-- See also: SS. 9.5. Constant declarations
--goCVSpecs :: GoParser [GoCVSpec]
--goCVSpecs = try goCVSpecs' <|> goCVSpecs'' where
--
-- goCVSpecs' = liftM (replicate 1) goCVSpec
-- goCVSpecs'' = goParen $ many $ goSemi goCVSpec
--
-- goCVSpec :: GoParser GoCVSpec
-- goCVSpec = do
-- ids <- goIdentifierList
-- try (goCVSpec' ids) <|> goCVSpec'' ids where
-- See also: SS. 9.6. Iota
-- | Standard @TypeDecl@
--
-- See also: SS. 9.7. Type declarations
goTypeDecl :: GoParser GoDecl
goTypeDecl = goTokType >> liftM GoType (goParenish goTypeSpec)
-- | Standard @TypeSpec@
--
-- See also: SS. 9.7. Type declarations
goTypeSpec :: GoParser GoTypeSpec
goTypeSpec = do
id <- goIdentifier
ty <- goType
return $ GoTypeSpec id ty
-- | Standard @VarDecl@
--
-- See also: SS. 9.8. Variable declarations
goVarDecl :: GoParser GoDecl
goVarDecl = goTokVar >> liftM GoVar (goParenish goVarSpec)
goVarSpec :: GoParser GoCVSpec
goVarSpec = do
id <- goIdentifierList
(try (goVarSpec' id) <|> try (goVarSpec'' id) <|> goVarSpec''' id) where
goVarSpec' :: [GoId] -> GoParser GoCVSpec
goVarSpec' ids = do
goTokEqual
exs <- goExpressionList
return $ GoCVSpec ids Nothing exs
goVarSpec'' :: [GoId] -> GoParser GoCVSpec
goVarSpec'' ids = do
typ <- goType
goTokEqual
exs <- goExpressionList
return $ GoCVSpec ids (Just typ) exs
goVarSpec''' :: [GoId] -> GoParser GoCVSpec
goVarSpec''' ids = do
typ <- goType
return $ GoCVSpec ids (Just typ) []
-- | Standard @ShortVarDecl@
--
-- See also: SS. 9.9. Short variable declarations
goShortVarDecl :: GoParser GoSimp
goShortVarDecl = do
ids <- goIdentifierList
goTokColonEq
exs <- optionMaybe goExpressionList
case exs of
Just ex -> return (GoSimpVar ids ex)
Nothing -> fail "short var"
-- return (GoSimpVar ids exs)
-- <?> "short variable declaration"
-- | Standard @FunctionDecl@
--
-- See also: SS. 9.10. Function declarations
goFunctionDecl :: GoParser GoDecl
goFunctionDecl = do
goTokFunc
id <- goIdentifier
sg <- goSignature
bk <- option GoNoBlock goBlock -- Go @Body@
return $ GoFunc $ GoFuncDecl id sg bk
-- | Standard @MethodDecl@
--
-- See also: SS. 9.11. Method declarations
goMethodDecl :: GoParser GoDecl
goMethodDecl = do
goTokFunc
rc <- goReceiver
id <- goIdentifier
sg <- goSignature
bk <- option GoNoBlock goBlock
return $ GoMeth $ GoMethDecl rc id sg bk
-- | Standard @Receiver@
--
-- See also: SS. 9.11. Method declarations
goReceiver :: GoParser GoRec
goReceiver = between goTokLParen goTokRParen (try namedrec <|> anonrec)
where namedrec = do
-- Named receiver
id <- goIdentifier
pt <- optionMaybe goTokAsterisk
ty <- goTypeName -- Go @BaseTypeName@
return $ GoRec (isJust pt) (Just id) ty
anonrec = do
pt <- optionMaybe goTokAsterisk
ty <- goTypeName -- Go @BaseTypeName@
return $ GoRec (isJust pt) Nothing ty
-- | Standard @Operand@
--
-- See also: SS. 10.1. Operands
goOperand :: GoParser GoPrim
goOperand = (try $ liftM GoLiteral goLiteral)
<|> try goQualifiedIdent
<|> try goMethodExpr
<|> liftM GoParen (goParen goExpression)
-- | Standard @Literal@
--
-- See also: SS. 10.1. Operands
goLiteral :: GoParser GoLit
goLiteral = goBasicLit
<|> goCompositeLit
<|> goFunctionLit
<?> "literal"
-- | Standard @BasicLit@
--
-- See also: SS. 10.1. Operands
goBasicLit :: GoParser GoLit
goBasicLit = try $ do
(GoTokenPos _ tok) <- lookAhead anyToken
case tok of
(GoTokInt (Just s) t) -> do anyToken; return $ GoLitInt s t
(GoTokReal (Just s) t) -> do anyToken; return $ GoLitReal s t
(GoTokImag (Just s) t) -> do anyToken; return $ GoLitImag s t
(GoTokChar (Just s) t) -> do anyToken; return $ GoLitChar s t
(GoTokStr (Just s) t) -> do anyToken; return $ GoLitStr s t
x -> fail (show x)
-- | Standard @QualifiedIdent@
--
-- See also: SS. 10.2. Qualified identifiers
goQualifiedIdent :: GoParser GoPrim
goQualifiedIdent = try qualified <|> liftM (GoQual Nothing) goIdentifier
where qualified = do
qual <- goIdentifier
goTokFullStop
name <- goIdentifier
return $ GoQual (Just qual) name
-- | Standard @CompositeLit@
--
-- See also: SS. 10.3. Composite literals
goCompositeLit :: GoParser GoLit
goCompositeLit = do
st <- getState
ty <- goLiteralType
case ty of
GoTypeName _ _ -> if noComposite st && parenDepth st == 0 then fail "no T{} in condition" else return ()
_ -> return ()
va <- goLiteralValue
return $ GoLitComp ty va
-- | Nonstandard
--
-- This production represents the third part of the @LiteralType@ production.
--
-- See also: SS. 10.3. Composite literals
goArrayEllipsisType :: GoParser GoType
goArrayEllipsisType = do
goBracket goTokEllipsis
t <- goType
return $ GoEllipsisType t
goVariadicType :: GoParser GoType
goVariadicType = do
goTokEllipsis
t <- goType
return (GoVariadicType t)
-- | Standard @LiteralType@
--
-- See also: SS. 10.3. Composite literals
goLiteralType :: GoParser GoType
goLiteralType = (try goArrayType)
<|> (try goArrayEllipsisType)
<|> goSliceType
<|> goStructType
<|> goMapType
<|> goTypeName
-- | Standard @LiteralValue@
-- Standard @ElementList@
--
-- See also: SS. 10.3. Composite literals
goLiteralValue :: GoParser GoComp
goLiteralValue = do
goTokLBrace
elements <- sepEndBy (try goElement) goTokComma
goTokRBrace
return $ GoComp elements
-- | Standard @Element@
--
-- See also: SS. 10.3. Composite literals
goElement :: GoParser GoElement
goElement = do
key <- option GoKeyNone goKey
val <- goValue
return $ GoElement key val
-- | Standard @Key@
-- followed by colon.
--
-- See also: SS. 10.3. Composite literals
goKey :: GoParser GoKey
goKey = try fieldcolon -- Go @FieldName@
<|> try keycolon -- Go @ElementIndex@
<?> "literal key"
where fieldcolon = do { key <- goIdentifier; goTokColon; return $ GoKeyField key }
keycolon = do { expr <- goExpression; goTokColon; return $ GoKeyIndex expr }
-- | Standard @Value@
--
-- See also: SS. 10.3. Composite literals
goValue :: GoParser GoValue
goValue = liftM GoValueExpr goExpression
<|> liftM GoValueComp goLiteralValue
<?> "literal value"
-- | Standard @FunctionLit@
--
-- See also: SS. 10.4. Function literals
goFunctionLit :: GoParser GoLit
goFunctionLit = liftM GoLitFunc goFuncLambda
-- | Nonstandard function literals (self-contained)
goFuncLambda :: GoParser GoFuncExpr
goFuncLambda = do
goTokFunc
sg <- goSignature
bk <- goBlock
return $ GoFuncExpr sg bk
-- | Standard @PrimaryExpr@
--
-- @PrimaryExpr@ is occurs in many places:
--
-- * @Expression@,
--
-- * @TypeSwitchGuard@,
--
-- * and in its own definition.
--
-- Therefore, it is useful to have a separate datatype for it,
-- since otherwise we would have to repeat ourselves. This is
-- the responsibility @goPrimary@ below. The only thing we do
-- here is convert the AST one level, so it's an expression.
--
-- See also: SS. 10.5. Primary expressions
-- | Nonstandard primary expressions (self-contained)
goPrimaryExpr :: GoParser GoExpr
goPrimaryExpr = do
-- Try builtin call first because the prefix looks like an
-- identifier.
-- goConversion only matches for unnamed types (names match
-- goOperand).
ex <- (try goBuiltinCall) <|> (try goOperand) <|> (try goConversion)
let complex prefix = (try $ goIndex prefix)
<|> (try $ goSlice prefix)
<|> try (goTypeAssertion prefix)
<|> goCall prefix
<|> goSelector prefix
let veryComplex prefix = try (do
vex <- complex prefix
veryComplex vex) <|> return prefix
pr <- veryComplex ex
return $ GoPrim pr
-- | Standard @Selector@
--
-- See also: SS. 10.5. Primary expressions, 10.6. Selectors
goSelector :: GoPrim -> GoParser GoPrim
goSelector ex = do
goTokFullStop
id <- goIdentifier
return $ GoSelect ex id
-- | Standard @Index@
--
-- See also: SS. 10.5. Primary expressions, 10.7. Indexes
goIndex :: GoPrim -> GoParser GoPrim
goIndex ex = do
goTokLBracket
enterParen
ix <- goExpression
exitParen
goTokRBracket
return $ GoIndex ex ix
-- | Standard @Slice@
--
-- See also: SS. 10.5. Primary expressions, 10.8. Slices
goSlice :: GoPrim -> GoParser GoPrim
goSlice ex = do
goTokLBracket
x <- optionMaybe goExpression
goTokColon
y <- optionMaybe goExpression
goTokRBracket
return $ GoSlice ex x y
-- | Standard @TypeAssertion@
--
-- See also: SS. 10.5. Primary expressions, 10.9. Type assertions
goTypeAssertion :: GoPrim -> GoParser GoPrim
goTypeAssertion ex = do
goTokFullStop
goTokLParen
ty <- goType
goTokRParen
return $ GoTA ex ty
-- | Standard @Call@
--
-- See also: SS. 10.5. Primary expressions, 10.10. Calls
goCall :: GoPrim -> GoParser GoPrim
goCall ex = goParen $ do
ar <- goExpressionList
rs <- optionMaybe goTokEllipsis
optional goTokComma
return $ GoCall ex ar (isJust rs)
-- | Standard @Expression@
--
-- Technically, the Go spec says
--
-- * @Expression@ = @UnaryExpr@ | @Expression@ @binary_op@ @UnaryExpr@ .
--
-- * @UnaryExpr@ = @PrimaryExpr@ | @unary_op@ @UnaryExpr@ .
--
-- but we combine these into one production here.
--
-- See also: SS. 10.12. Operators
goExpression :: GoParser GoExpr
goExpression = goOpExpr goUnaryExpr
<?> "expression"
goUnaryExpr :: GoParser GoExpr
goUnaryExpr = unaryExpr
where unaryExpr = try unaryOpExpr <|> goPrimaryExpr
unaryOpExpr = do
op <- goUnaryOp
expr <- unaryExpr
return $ Go1Op op expr
-- | Standard @MethodExpr@
--
-- See also: SS. 10.13. Method expressions
goMethodExpr :: GoParser GoPrim
goMethodExpr = do
rc <- goReceiverType
goTokFullStop
id <- goMethodName
return $ GoMethod rc id
-- | Nonstandard
goMethodName = goIdentifier
-- | Standard @ReceiverType@
--
-- See also: SS. 10.13. Method expressions
goReceiverType :: GoParser GoRec
goReceiverType = try goReceiverType' <|> goReceiverType'' where
goReceiverType'' = do
ty <- goParen (goTokAsterisk >> goTypeName)
return $ GoRec True Nothing ty
goReceiverType' = do
ty <- goTypeName
return $ GoRec False Nothing ty
-- | Standard @Conversion@
--
-- See also: SS. 10.14. Conversions
goConversion :: GoParser GoPrim
goConversion = do
ty <- goType
ex <- goParen goExpression
return $ GoCast ty ex
-- | Standard @Statement@
--
-- See also: SS. 11. Statements
goStatement :: GoParser GoStmt
goStatement = (liftM GoStmtDecl goDeclaration) -- 'Statement/Declaration'
<|> try goLabeledStmt -- label and identifier are the same token
<|> (liftM GoStmtSimple goSimple) -- 'Statement/SimpleStmt'
<|> goGoStmt
<|> goReturnStmt
<|> goBreakStmt
<|> goContinueStmt
<|> goGotoStmt
<|> goFallthroughStmt
<|> liftM GoStmtBlock goBlock
<|> goIfStmt
<|> goSwitchStmt
<|> goSelectStmt
<|> goForStmt
<|> goDeferStmt
<?> "statement"
-- | Nonstandard simple statements (self-contained)
--
-- This is to wrap simple statements in a self-contained datatype.
goSimple :: GoParser GoSimp
goSimple = (try goSendStmt) -- 'SimpleStmt/SendStmt'
<|> (try goIncDecStmt) -- 'SimpleStmt/IncDecStmt'
<|> (try goShortVarDecl) -- 'SimpleStmt/ShortVarDecl'
<|> (try goAssignment) -- 'SimpleStmt/Assignment'
<|> (liftM GoSimpExpr goExpression) -- 'SimpleStmt/ExpressionStmt'
-- | Standard @LabeledStmt@
--
-- See also: SS. 11.2. Labeled statements
goLabeledStmt :: GoParser GoStmt
goLabeledStmt = do
id <- goIdentifier -- Go @Label@
goTokColon
st <- option (GoStmtSimple GoSimpEmpty) goStatement
return $ GoStmtLabeled id st
-- | Standard @SendStmt@
--
-- See also: SS. 11.4. Send statements
goSendStmt :: GoParser GoSimp
goSendStmt = do
ch <- goExpression -- Go @Channel@
goTokArrow
ex <- goExpression
return $ GoSimpSend ch ex
-- | Standard @IncDecStmt@
--
-- See also: SS. 11.5. IncDec statements
goIncDecStmt :: GoParser GoSimp
goIncDecStmt = try $ do
ex <- goUnaryExpr -- goExpression
(GoTokenPos _ op) <- anyToken
case op of
GoTokInc -> return $ GoSimpInc ex
GoTokDec -> return $ GoSimpDec ex
_ -> fail "IncDecStmt What?"
-- | Standard @Assignment@
--
-- See also: SS. 11.6. Assignments
goAssignment :: GoParser GoSimp
goAssignment = do
lv <- goExpressionList
op <- goAssignOp
rv <- goExpressionList
return $ GoSimpAsn lv op rv
goNoComposite :: GoParser a -> GoParser a
goNoComposite p = do
st <- getState -- save state
putState $ GoParserState { noComposite = True, parenDepth = 0 }
x <- p
putState st -- restore state
return x
goCond :: GoParser GoCond
goCond = goNoComposite $ do
st <- optionMaybe (goSemi goSimple)
ex <- optionMaybe goExpression
return $ GoCond st ex
-- | Standard @IfStmt@
--
-- See also: SS. 11.7. If statements
goIfStmt :: GoParser GoStmt
goIfStmt = do
goTokIf
cond <- goCond
case cond of
GoCond _ Nothing -> fail "missing condition in if"
_ -> return ()
b <- goBlock
e <- optionMaybe (goTokElse >> goStatement)
return $ GoStmtIf cond b e
-- | Standard @IfStmt@
--
-- See also: SS. 11.8. Switch statements
goSwitchStmt :: GoParser GoStmt
goSwitchStmt = try goExprSwitchStmt
<|> goTypeSwitchStmt
-- | Standard @ExprSwitchStmt@
--
-- See also: SS. 11.8. Switch statements
goExprSwitchStmt :: GoParser GoStmt
goExprSwitchStmt = do
goTokSwitch
cond <- goCond
cl <- goBrace $ many goExprCaseClause
return $ GoStmtSwitch cond cl
-- | Standard @ExprCaseClause@
--
-- See also: SS. 11.8. Switch statements
goExprCaseClause :: GoParser (GoCase GoExpr)
goExprCaseClause = do
fn <- goAfter goTokColon goExprSwitchCase
st <- many $ goSemi goStatement
return $ fn st
-- | Standard @ExprSwitchCase@
--
-- See also: SS. 11.8. Switch statements
goExprSwitchCase :: GoParser ([GoStmt] -> GoCase GoExpr)
goExprSwitchCase = goExprSwitchCase' <|> goExprSwitchCase''
where goExprSwitchCase' = do goTokCase; el <- goExpressionList; return $ GoCase el
goExprSwitchCase'' = do goTokDefault; return GoDefault
-- | Standard @TypeSwitchStmt@
goTypeSwitchStmt :: GoParser GoStmt
goTypeSwitchStmt = do
goTokSwitch
st <- optionMaybe $ goSemi goSimple
id <- optionMaybe $ goAfter goTokColonEq goIdentifier
ga <- goTypeSwitchGuard st
cl <- goBrace $ many goTypeCaseClause
return $ GoStmtTypeSwitch ga cl id
-- | Standard @TypeSwitchGuard@
goTypeSwitchGuard :: (Maybe GoSimp) -> GoParser GoCond
goTypeSwitchGuard st = do
ex <- goExpression
goTokFullStop
goParen goTokType
return $ GoCond st (Just ex)
-- | Standard @TypeSwitchCase@
goTypeCaseClause :: GoParser (GoCase GoType)
goTypeCaseClause = do
fn <- goAfter goTokColon goTypeSwitchCase
st <- many $ goSemi goStatement
return $ fn st
-- | Standard @TypeSwitchCase@
goTypeSwitchCase :: GoParser ([GoStmt] -> GoCase GoType)
goTypeSwitchCase = goTypeSwitchCase' <|> goTypeSwitchCase''
where goTypeSwitchCase' = do goTokCase; tl <- goTypeList; return $ GoCase tl
goTypeSwitchCase'' = do goTokDefault; return GoDefault
-- | Standard @TypeList@
goTypeList :: GoParser [GoType]
goTypeList = sepBy1 goType goTokComma
-- | Standard @ForStmt@
--
-- See also: SS. 11.9. For statements
goForStmt :: GoParser GoStmt
goForStmt = do
goTokFor
h <- goNoComposite (try goForClause <|> try goRangeClause <|> goCondition)
b <- goBlock
return $ GoStmtFor h b
-- | Standard @Condition@
goCondition :: GoParser GoForClause
goCondition = liftM GoForWhile (optionMaybe goExpression)
-- | Standard @ForClause@
goForClause :: GoParser GoForClause
goForClause = do
i <- option GoSimpEmpty goSimple -- Go @InitStmt@
goTokSemicolon
c <- optionMaybe goExpression
goTokSemicolon
p <- option GoSimpEmpty goSimple -- Go @PostStmt@
return $ GoForThree i c p
-- | Standard @RangeClause@
goRangeClause :: GoParser GoForClause
goRangeClause = do
k <- goExpression
v <- optionMaybe (goTokComma >> goUnaryExpr)
p <- goAnyEqual
goTokRange
e <- goExpression
let lhs = case v of { Nothing -> [k]; Just v -> [k,v] }
return $ GoForRange lhs e (p == GoOp ":=")
-- Nonstandard
goAnyEqual :: GoParser GoOp
goAnyEqual = do goTokEqual; return $ GoOp "="
<|> do goTokColonEq; return $ GoOp ":="
-- | Standard @GoStmt@
--
-- See also: SS. 11.10. Go statements
goGoStmt :: GoParser GoStmt
goGoStmt = do goTokGo; liftM GoStmtGo goExpression
-- | Standard @SelectStmt@
--
-- See also: SS. 11.11. Select statements
goSelectStmt :: GoParser GoStmt
goSelectStmt = do
goTokSelect
cl <- goBrace $ many goCommClause
return $ GoStmtSelect cl
-- | Standard @CommClause@
--
-- See also: SS. 11.11. Select statements
goCommClause :: GoParser (GoCase GoChan)
goCommClause = do
fn <- goAfter goTokColon goCommCase
st <- many $ goSemi goStatement
return $ fn st
-- | Standard @CommCase@
--
-- See also: SS. 11.11. Select statements
goCommCase :: GoParser ([GoStmt] -> GoCase GoChan)
goCommCase = goCommCase' <|> goCommCase''
where goCommCase' = do goTokCase; ch <- goChanStmt; return $ GoCase [ch]
goCommCase'' = do goTokDefault; return GoDefault
-- | Nonstandard
goChanStmt :: GoParser GoChan
goChanStmt = try (goSendStmt >>= convert) <|> goRecvStmt
where convert (GoSimpSend x y) = return (GoChanSend x y)
convert _ = error "impossible"
-- | Standard @RecvStmt@
--
-- See also: SS. 11.11. Select statements
goRecvStmt :: GoParser GoChan
goRecvStmt = do
as <- optionMaybe $ try (do
ex <- goExpression
ex2 <- optionMaybe (goTokComma >> goExpression)
op <- goAnyEqual
return (ex, ex2, op))
re <- goRecvExpr
return $ GoChanRecv as re
-- | Standard @RecvExpr@
--
-- See also: SS. 11.11. Select statements
goRecvExpr :: GoParser GoExpr
goRecvExpr = try goRecvExpr'
<|> goParen goRecvExpr where
goRecvExpr' = do
goTokArrow
ex <- goExpression
return $ Go1Op (GoOp "<-") ex
-- | Standard @ReturnStmt@
--
-- See also: SS. 11.12. Return statements
goReturnStmt :: GoParser GoStmt
goReturnStmt = do goTokReturn; liftM GoStmtReturn $ option [] goExpressionList
-- | Standard @BreakStmt@
--
-- See also: SS. 11.13. Break statements
goBreakStmt :: GoParser GoStmt
goBreakStmt = do goTokBreak; liftM GoStmtBreak $ optionMaybe goIdentifier
-- | Standard @ContinueStmt@
--
-- See also: SS. 11.14. Continue statementss
goContinueStmt :: GoParser GoStmt
goContinueStmt = do goTokContinue; liftM GoStmtContinue $ optionMaybe goIdentifier
-- | Standard @GotoStmt@
--
-- See also: SS. 11.15. Goto statements
goGotoStmt :: GoParser GoStmt
goGotoStmt = do goTokGoto; liftM GoStmtGoto $ goIdentifier
-- | Standard @FallthroughStmt@
--
-- See also: SS. 11.16. Fallthrough statements
goFallthroughStmt :: GoParser GoStmt
goFallthroughStmt = goTokFallthrough >> return GoStmtFallthrough
-- | Standard @DeferStmt@
--
-- See also: SS. 11.17. Defer statements
goDeferStmt :: GoParser GoStmt
goDeferStmt = goTokDefer >> liftM GoStmtDefer goExpression
-- | Standard @BuiltinCall@
--
-- See also: SS. 12. Built-in functions, 12.3. Allocation
goBuiltinCall :: GoParser GoPrim
goBuiltinCall = do
id <- goIdentifier
goTokLParen
tj <- optionMaybe goType
ar <- option [] goBuiltinArgs
goTokRParen
case (id, tj) of
(GoId "new", Just ty) -> return $ GoNew ty
(GoId "make", Just ty) -> return $ GoMake ty ar
_ -> fail "BuiltinCall what?"
-- | Standard @BuiltinArgs@
--
-- See also: SS. 12. Built-in functions
goBuiltinArgs :: GoParser [GoExpr]
goBuiltinArgs = goTokComma >> goExpressionList
-- | Standard @SourceFile@
--
-- See also: SS. 13.1. Source file organization
goSource :: GoParser GoSource
goSource = do
pkg <- goSemi goPackageClause
imp <- many $ goSemi goImportDecl
top <- many $ goSemi goTopLevelDecl
eof
return $ GoSource pkg imp top
-- | Standard @PackageClase@
--
-- See also: SS. 13.2. Package clause
goPackageClause :: GoParser GoId
goPackageClause = do
goTokPackage
goIdentifier
-- | Standard @ImportDecl@
--
-- See also: SS. 13.3. Import declarations
goImportDecl :: GoParser GoPrel
goImportDecl = goTokImport >> liftM GoImportDecl goImportSpec
-- | List of specs separated by semicolons, in parentheses.
-- See also goBlockish.
goParenish :: GoParser a -> GoParser [a]
goParenish x = goParen xs <|> one
where one = do { t <- x; return [t] }
xs = do
lines <- sepEndBy (optionMaybe x) goTokSemicolon
return $ catMaybes lines
-- | Standard @ImportSpec@
--
-- See also: SS. 13.3. Import declarations
goImportSpec :: GoParser [GoImpSpec]
goImportSpec = goImpSpecs'' <|> goImpSpecs' where
goImpSpecs' = liftM (replicate 1) goImpSpec
goImpSpecs'' = goParen $ many $ goSemi goImpSpec
goImpSpec :: GoParser GoImpSpec
goImpSpec = do
ty <- try goImpType
ip <- goString -- Go @ImportPath@
return $ GoImpSpec ty ip
goImpType :: GoParser GoImpType
goImpType = try dot <|> try qual <|> return GoImp
where dot = do { goTokFullStop; return GoImpDot }
qual = do { id <- goIdentifier; return $ GoImpQual id }
--
-- End specification grammar
--
-- combinators
goAfter :: GoParser b -> GoParser a -> GoParser a
goAfter y x = try (do z <- x ; y ; return z)
goSemi :: GoParser a -> GoParser a
goSemi = goAfter goTokSemicolon
-- literals
goString :: GoParser String
goString = do
GoTokStr _ uni <- token (GoTokStr Nothing "")
return uni
goParen :: GoParser a -> GoParser a
goParen p = do
goTokLParen
enterParen
x <- p
exitParen
goTokRParen
return x
goBrace :: GoParser a -> GoParser a
goBrace = between goTokLBrace goTokRBrace
goBracket :: GoParser a -> GoParser a
goBracket = between goTokLBracket goTokRBracket
-- parsers
-- only in TypeLit:
-- Pointer
-- InterfaceType
-- ChannelType
-- FunctionType (available as FunctionLit)
-- only in LiteralType:
-- goArrayEllipsisType
| remyoudompheng/hs-language-go | Language/Go/Parser/Parser.hs | gpl-3.0 | 31,307 | 0 | 21 | 6,829 | 7,117 | 3,577 | 3,540 | -1 | -1 |
{-|
Module : Main
Description : So that it can work as an executable.
Copyright : (c)
License : GPL-3
Maintainer : njagi@urbanslug.com
Stability : experimental
Portability : POSIX
-}
module Main where
import Devel
import Devel.Args
import Options.Applicative
import System.Process (rawSystem)
import System.Exit (ExitCode(ExitSuccess))
import System.Environment (setEnv)
main :: IO ()
main = do
cmdArgs <- execParser opts
_ <- case interfaceFile cmdArgs of
Just path -> rawSystem "ghc" $ ["--show-iface "] ++ [show path]
_ -> return ExitSuccess
reverseProxy' <- return $ reverseProxy cmdArgs
buildFile' <- return $ case buildFile cmdArgs of
Just path' -> path'
_ -> "Application.hs"
runFunction' <- return $ case runFunction cmdArgs of
Just function' -> function'
_ -> "develMain"
buildAndRun buildFile' runFunction' reverseProxy'
where opts :: ParserInfo CmdArgs
opts = info (helper <*> cmdArgs)
(fullDesc
<> progDesc "For WAI complaint haskell web applications"
<> header "wai-devel: development server for haskell web applications." )
| bitemyapp/wai-devel | src/Main.hs | gpl-3.0 | 1,279 | 0 | 13 | 391 | 263 | 131 | 132 | 26 | 4 |
module Classwork where
import Data.Monoid
newtype Endom a = Endom { appEndom :: a -> a };
instance Monoid (Endom a) where
mempty = Endom id
Endom f `mappend` Endom g = Endom $ f . g
fn = mconcat $ map Endom [(+5), (*3), (^2)]
fn' = mconcat $ map (Dual . Endom) [(+5), (*3), (^2)]
{-
instance (Monoid a) => Monoid (Maybe a) where
mempty = Nothing
Nothing `mappend` Nothing = Nothing
(Just x) `mappend` Nothing = Just x
Nothing `mappend` Just y = Just y
Just x `mappend` Just y = Just (x `mappend` y)
-}
f :: [String] -> String
f = foldr1 (\x y -> x ++ "," ++ y)
or' :: [Bool] -> Bool
or' = foldr (\x y -> x || y) False
length' :: [a] -> Int
length' = foldr (\_ y -> y + 1) 0
head' :: [a] -> a
head' = foldl1 (\x _ -> x)
last' :: [a] -> a
last' = foldr1 (\_ y -> y)
filter' :: (a -> Bool) -> [a] -> [a]
filter' p = foldr (\x tail -> if p x then x:tail else tail) []
map' :: (a -> b) -> [a] -> [b]
map' f = foldr (\x tail -> (f x):tail) []
take' :: Int -> [a] -> [a]
take' n xs = foldr step ini xs n
where
step :: a -> (Int -> [a]) -> Int -> [a]
step x g 0 = []
step x g n = x : (g (n - 1))
ini :: Int -> [a]
ini = const []
| ItsLastDay/academic_university_2016-2018 | subjects/Haskell/7/classwork.hs | gpl-3.0 | 1,195 | 0 | 11 | 340 | 587 | 328 | 259 | 29 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Test.QuickCheck
import Test.QuickCheck.Property
import Test.QuickCheck.All
import Control.Monad
import Test.Utils.GeometryArbitraries
import Test.Utils.GeometryData
import GameLogic.Base.Geometry
prop_inSegmentBounded _ = inSegment (minBound :: Int, maxBound :: Int)
prop_inSegmentSwap (x1, x2) y = inSegment (x1, x2) y == inSegment (x2, x1) y
prop_inBoundsEmpty p = not (inBounds p [])
prop_inBoundsSelf1 p _ = inBounds p [pointBound p]
prop_inBoundsSelf2 p bs = inBounds p $ pointBound p : bs
prop_inBoundsNoBounds p bs = inBounds p $ noBound : bs
prop_rectBound1 = rectBound point1 point2 == Rectangled point1 point2
prop_rectBound2 = rectBound point3 point4 == Rectangled point5 point6
prop_rectInRect = inRect rect1 rect2
prop_validateDirections = all (==zeroPoint) mappedDirPairs
where
mappedDirPairs = map (\(a, b) -> addPoint (toVector a) (toVector b)) oppositeDirections
prop_updateRectBound ps = rect1 `inRect` newRect
where
newRect = foldr updateRectBound rect1 ps
prop_occupiedArea1 p ps = occupiedArea (p:ps) == foldr updateRectBound (rectBound p p) ps
prop_occupiedArea2 ps = let
area = occupiedArea ps
in all (\p -> inBounds p [area]) ps
prop_movePoint1 n p dir = classify isTrivial "trivial" res
where moved1 = moveStraight n p dir
moved2 = moveStraight n moved1 (opposite dir)
isTrivial = n == 0
res = if isTrivial then (moved1 == p) && (moved2 == p)
else (moved1 /= p) && (moved2 == p)
prop_movePoint2 n p dir = classify isTrivial "trivial" res
where moved1 = moveStraight n p dir
moved2 = moveStraight (negate n) moved1 dir
isTrivial = n == 0
res = if isTrivial then (moved1 == p) && (moved2 == p)
else (moved1 /= p) && (moved2 == p)
prop_neighbours1 p1 dir = testNeighbours dir && testNeighbours (opposite dir)
where
testNeighbours d = advance p1 d `elem` neighbours p1
prop_neighbours2 p1 dir (NonZero dist) = ( classify far "not neighbours"
. classify near "neighbours") (far || near)
where
far = (abs dist > 1) && not test
near = (abs dist <= 1) && test
test = testNeighbours dir && testNeighbours (opposite dir)
testNeighbours d = moveStraight (abs dist) p1 d `elem` neighbours p1
prop_areNeighbours p1 p2 = ( classify (not ns) "not neighbours"
. classify ns "neighbours"
. classify same "same point") (not ns || ns || same)
where
same = p1 == p2
ns = areNeighbours p1 p2
tests :: IO Bool
tests = $quickCheckAll
runTests = tests >>= \passed -> putStrLn $
if passed then "All tests passed."
else "Some tests failed."
main :: IO ()
main = runTests | graninas/The-Amoeba-World | src/Amoeba/Test/GeometryTest.hs | gpl-3.0 | 2,846 | 0 | 12 | 721 | 954 | 494 | 460 | 58 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.KMS.DisableKeyRotation
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Disables rotation of the specified key.
--
-- <http://docs.aws.amazon.com/kms/latest/APIReference/API_DisableKeyRotation.html>
module Network.AWS.KMS.DisableKeyRotation
(
-- * Request
DisableKeyRotation
-- ** Request constructor
, disableKeyRotation
-- ** Request lenses
, dkrKeyId
-- * Response
, DisableKeyRotationResponse
-- ** Response constructor
, disableKeyRotationResponse
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.KMS.Types
import qualified GHC.Exts
newtype DisableKeyRotation = DisableKeyRotation
{ _dkrKeyId :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DisableKeyRotation' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dkrKeyId' @::@ 'Text'
--
disableKeyRotation :: Text -- ^ 'dkrKeyId'
-> DisableKeyRotation
disableKeyRotation p1 = DisableKeyRotation
{ _dkrKeyId = p1
}
-- | A unique identifier for the customer master key. This value can be a globally
-- unique identifier or the fully specified ARN to a key. Key ARN Example -
-- arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012 Globally Unique Key ID Example - 12345678-1234-1234-1234-123456789012
--
dkrKeyId :: Lens' DisableKeyRotation Text
dkrKeyId = lens _dkrKeyId (\s a -> s { _dkrKeyId = a })
data DisableKeyRotationResponse = DisableKeyRotationResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DisableKeyRotationResponse' constructor.
disableKeyRotationResponse :: DisableKeyRotationResponse
disableKeyRotationResponse = DisableKeyRotationResponse
instance ToPath DisableKeyRotation where
toPath = const "/"
instance ToQuery DisableKeyRotation where
toQuery = const mempty
instance ToHeaders DisableKeyRotation
instance ToJSON DisableKeyRotation where
toJSON DisableKeyRotation{..} = object
[ "KeyId" .= _dkrKeyId
]
instance AWSRequest DisableKeyRotation where
type Sv DisableKeyRotation = KMS
type Rs DisableKeyRotation = DisableKeyRotationResponse
request = post "DisableKeyRotation"
response = nullResponse DisableKeyRotationResponse
| romanb/amazonka | amazonka-kms/gen/Network/AWS/KMS/DisableKeyRotation.hs | mpl-2.0 | 3,264 | 0 | 9 | 675 | 359 | 220 | 139 | 48 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.AppState.Types.Sum
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.AppState.Types.Sum where
import Network.Google.Prelude
| rueshyna/gogol | gogol-appstate/gen/Network/Google/AppState/Types/Sum.hs | mpl-2.0 | 600 | 0 | 4 | 109 | 29 | 25 | 4 | 8 | 0 |
{-# 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.DialogFlow.Projects.Agent.Intents.Patch
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates the specified intent.
--
-- /See:/ <https://cloud.google.com/dialogflow-enterprise/ Dialogflow API Reference> for @dialogflow.projects.agent.intents.patch@.
module Network.Google.Resource.DialogFlow.Projects.Agent.Intents.Patch
(
-- * REST Resource
ProjectsAgentIntentsPatchResource
-- * Creating a Request
, projectsAgentIntentsPatch
, ProjectsAgentIntentsPatch
-- * Request Lenses
, paipXgafv
, paipLanguageCode
, paipUploadProtocol
, paipUpdateMask
, paipAccessToken
, paipUploadType
, paipPayload
, paipIntentView
, paipName
, paipCallback
) where
import Network.Google.DialogFlow.Types
import Network.Google.Prelude
-- | A resource alias for @dialogflow.projects.agent.intents.patch@ method which the
-- 'ProjectsAgentIntentsPatch' request conforms to.
type ProjectsAgentIntentsPatchResource =
"v2" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "languageCode" Text :>
QueryParam "upload_protocol" Text :>
QueryParam "updateMask" GFieldMask :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "intentView" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] GoogleCloudDialogflowV2Intent :>
Patch '[JSON] GoogleCloudDialogflowV2Intent
-- | Updates the specified intent.
--
-- /See:/ 'projectsAgentIntentsPatch' smart constructor.
data ProjectsAgentIntentsPatch =
ProjectsAgentIntentsPatch'
{ _paipXgafv :: !(Maybe Xgafv)
, _paipLanguageCode :: !(Maybe Text)
, _paipUploadProtocol :: !(Maybe Text)
, _paipUpdateMask :: !(Maybe GFieldMask)
, _paipAccessToken :: !(Maybe Text)
, _paipUploadType :: !(Maybe Text)
, _paipPayload :: !GoogleCloudDialogflowV2Intent
, _paipIntentView :: !(Maybe Text)
, _paipName :: !Text
, _paipCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsAgentIntentsPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'paipXgafv'
--
-- * 'paipLanguageCode'
--
-- * 'paipUploadProtocol'
--
-- * 'paipUpdateMask'
--
-- * 'paipAccessToken'
--
-- * 'paipUploadType'
--
-- * 'paipPayload'
--
-- * 'paipIntentView'
--
-- * 'paipName'
--
-- * 'paipCallback'
projectsAgentIntentsPatch
:: GoogleCloudDialogflowV2Intent -- ^ 'paipPayload'
-> Text -- ^ 'paipName'
-> ProjectsAgentIntentsPatch
projectsAgentIntentsPatch pPaipPayload_ pPaipName_ =
ProjectsAgentIntentsPatch'
{ _paipXgafv = Nothing
, _paipLanguageCode = Nothing
, _paipUploadProtocol = Nothing
, _paipUpdateMask = Nothing
, _paipAccessToken = Nothing
, _paipUploadType = Nothing
, _paipPayload = pPaipPayload_
, _paipIntentView = Nothing
, _paipName = pPaipName_
, _paipCallback = Nothing
}
-- | V1 error format.
paipXgafv :: Lens' ProjectsAgentIntentsPatch (Maybe Xgafv)
paipXgafv
= lens _paipXgafv (\ s a -> s{_paipXgafv = a})
-- | Optional. The language of training phrases, parameters and rich messages
-- defined in \`intent\`. If not specified, the agent\'s default language
-- is used. [Many
-- languages](https:\/\/cloud.google.com\/dialogflow-enterprise\/docs\/reference\/language)
-- are supported. Note: languages must be enabled in the agent before they
-- can be used.
paipLanguageCode :: Lens' ProjectsAgentIntentsPatch (Maybe Text)
paipLanguageCode
= lens _paipLanguageCode
(\ s a -> s{_paipLanguageCode = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
paipUploadProtocol :: Lens' ProjectsAgentIntentsPatch (Maybe Text)
paipUploadProtocol
= lens _paipUploadProtocol
(\ s a -> s{_paipUploadProtocol = a})
-- | Optional. The mask to control which fields get updated.
paipUpdateMask :: Lens' ProjectsAgentIntentsPatch (Maybe GFieldMask)
paipUpdateMask
= lens _paipUpdateMask
(\ s a -> s{_paipUpdateMask = a})
-- | OAuth access token.
paipAccessToken :: Lens' ProjectsAgentIntentsPatch (Maybe Text)
paipAccessToken
= lens _paipAccessToken
(\ s a -> s{_paipAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
paipUploadType :: Lens' ProjectsAgentIntentsPatch (Maybe Text)
paipUploadType
= lens _paipUploadType
(\ s a -> s{_paipUploadType = a})
-- | Multipart request metadata.
paipPayload :: Lens' ProjectsAgentIntentsPatch GoogleCloudDialogflowV2Intent
paipPayload
= lens _paipPayload (\ s a -> s{_paipPayload = a})
-- | Optional. The resource view to apply to the returned intent.
paipIntentView :: Lens' ProjectsAgentIntentsPatch (Maybe Text)
paipIntentView
= lens _paipIntentView
(\ s a -> s{_paipIntentView = a})
-- | The unique identifier of this intent. Required for Intents.UpdateIntent
-- and Intents.BatchUpdateIntents methods. Format:
-- \`projects\/\/agent\/intents\/\`.
paipName :: Lens' ProjectsAgentIntentsPatch Text
paipName = lens _paipName (\ s a -> s{_paipName = a})
-- | JSONP
paipCallback :: Lens' ProjectsAgentIntentsPatch (Maybe Text)
paipCallback
= lens _paipCallback (\ s a -> s{_paipCallback = a})
instance GoogleRequest ProjectsAgentIntentsPatch
where
type Rs ProjectsAgentIntentsPatch =
GoogleCloudDialogflowV2Intent
type Scopes ProjectsAgentIntentsPatch =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/dialogflow"]
requestClient ProjectsAgentIntentsPatch'{..}
= go _paipName _paipXgafv _paipLanguageCode
_paipUploadProtocol
_paipUpdateMask
_paipAccessToken
_paipUploadType
_paipIntentView
_paipCallback
(Just AltJSON)
_paipPayload
dialogFlowService
where go
= buildClient
(Proxy :: Proxy ProjectsAgentIntentsPatchResource)
mempty
| brendanhay/gogol | gogol-dialogflow/gen/Network/Google/Resource/DialogFlow/Projects/Agent/Intents/Patch.hs | mpl-2.0 | 7,082 | 0 | 19 | 1,627 | 1,026 | 597 | 429 | 148 | 1 |
module Codewars.Kata.DNA where
import Codewars.Kata.DNA.Types
-- data Base = A | T | G | C
type DNA = [Base]
change :: Base -> Base
change A = T
change T = A
change G = C
change C = G
dnaStrand :: DNA -> DNA
dnaStrand = (change <$>)
| ice1000/OI-codes | codewars/1-100/complementary-dna.hs | agpl-3.0 | 236 | 0 | 5 | 53 | 83 | 49 | 34 | 10 | 1 |
--Syntax of Nominal Terms extended with atom substitutions
module TrmX
(Trm(..)
, FreshAtms
, Rule
, Prm
, Atm
, Var
, Fun
, Ctx
, Ctxs
, CtxD
, Asb
, VSub
, TrmCtx
, anAtmTrm
, aVarTrm
, anAbsTrm
, anAppTrm
, aTplTrm
, aTrmCtx
, aFC
, showCtx
, showCtxs
, showVSub
) where
----------------PREAMBLE
--containers
import qualified Data.List as L
import Data.Map(Map)
import qualified Data.Map as M
import Data.Set(Set)
import qualified Data.Set as S
--base
--import Control.Arrow
------------------------------------ DATA STRUCTURES
--Type aliases for nominal structures
type Atm = String --type of atom symbol
type Var = String --type of variable symbol
type Fun = String --type of term formers
type Ctx = Set (Atm,Var) --type of freshness context
type Ctxs = Set Ctx --type of collection of contexts
type CtxD = (Ctx, Set Atm) -- apair of a frhness context and a set of atoms; used to generate primitive constraints using new atoms from the set of atoms
--type aliases for permutations and substitutions
type Prm = [(Atm, Atm)] --type of permutations: list of atom swappings
type Asb = Map Atm Trm --type of atom substitutions
type VSub = Map Var Trm --type of variable substitutions
type TrmCtx = (Ctx, Trm) --type of terms-in-context
--to keep record of atoms: fst for atms in system, snd for available atoms
type FreshAtms = (Set Atm,Set Atm)
{-| Nominal terms with primitive atom substituion can be:
Atom terms, Moderated variables where the permutations are suspended first
and then the atom substitutions, Abstraction terms, Function applications and
Tuple terms.-}
data Trm = AtmTrm Atm
| VarTrm Asb Prm Var
| AbsTrm Atm Trm
| AppTrm Fun Trm
| TplTrm [Trm] deriving (Eq, Ord)
--Nominal term constructors
anAtmTrm:: Atm -> Trm
anAtmTrm = AtmTrm
aVarTrm:: Asb -> Prm -> Var -> Trm
aVarTrm = VarTrm
anAbsTrm:: Atm -> Trm -> Trm
anAbsTrm = AbsTrm
anAppTrm:: Fun -> Trm -> Trm
anAppTrm = AppTrm
aTplTrm:: [Trm] -> Trm
aTplTrm = TplTrm
--term-in-context constructor
aTrmCtx :: Ctx -> Trm -> TrmCtx
aTrmCtx = (\x y -> (x,y))
--freshness context constructor
aFC:: Atm -> Var -> Ctx
aFC a v = S.singleton (a,v)
{-RULES-}
{- | An extended nominal rewrite rule consists of a freshness context \Delta,
a left term t and a right term s. It is denoted as \Delta |- t -> s and
represented as type (Ctx, Trm, Trm) where Ctx is the type of \Delta and Trm
is the type of both terms t,s. Term t is placed in the middle position and
s in the last position. -}
type Rule = (Ctx, Trm, Trm)
------------------------------{- PRETTY PRINTING-}
--printing permutations
showPrm:: Prm -> String
showPrm [] = ""
showPrm ((a, b) : xs)| a==b = showPrm xs --discards Identity swaps
showPrm ((a,b) : xs) = showPrm xs ++ "(" ++ a ++ " " ++ b ++ ")"
--printing a freshness context
showCtx:: Ctx -> String
showCtx ctx =
if S.null ctx
then "{}"
else "{" ++ L.intercalate "," (map (\(a,v) -> a ++ "#" ++ v) (S.toList ctx)) ++ "}"
showCtxs :: Ctxs -> String
showCtxs ctxs = "{" ++ L.intercalate ", " (map showCtx $ S.toList ctxs) ++ "}"
--printing a nominal term
showTrm :: Trm -> String
showTrm (AtmTrm a) = a
showTrm (VarTrm asb p v) = showAsb asb ++ (if null p || M.null asb then "" else "^" ) ++ showPrm p ++ (if null p && M.null asb then "" else "+") ++ v
showTrm (AbsTrm a t) = "[" ++ a ++ "]" ++ " " ++ showTrm t
showTrm (AppTrm f t) = f ++ " " ++ showTrm t
showTrm (TplTrm []) = ""
showTrm (TplTrm xs) = "("++ L.intercalate ", " (map showTrm xs) ++ ")"
--print atom subs
showAsb :: Asb -> String
showAsb = M.foldrWithKey (\k t acc -> acc ++ f k t) ""
where f k t = "[" ++ k ++ " -> " ++ showTrm t ++ "]"
--prints a set of variable mappings
showVSub:: VSub -> String
showVSub vsub = if M.null vsub
then "Id"
else M.foldrWithKey (\k t acc -> acc ++ f k t) "" vsub
where f k t = "[" ++ k ++ " -> " ++ showTrm t ++ "]"
--prints a term-in-context
showTrmCtx:: TrmCtx -> String
showTrmCtx (c, t) = showCtx c ++ " |- " ++ show t
instance Show Trm where show = showTrm
--instance Show Ctx where show = showCtx
--instance Show TrmCtx where show = showTrmCtx
--prints a nominal rewrite rule
showRule :: Rule -> String
showRule (fc,l,r) = showCtx fc ++ " |- " ++ showTrm l ++ " --> " ++ showTrm r
--prints a sequence of nominal reduction steps
showSteps :: Ctx -> [Trm] -> String
showSteps fc ts = showCtx fc ++ " |- " ++ L.intercalate " --> " (map showTrm ts) ++ "."
| susoDominguez/eNominalTerms-Alpha | TrmX.hs | unlicense | 4,751 | 0 | 14 | 1,235 | 1,279 | 713 | 566 | 93 | 3 |
d::Int->Double
d 1 = 1.0
d k = d (k-1) * sqrt (1 / (2*(1+cos(pi/3/(2^^(k-1))))))
s::Int->Double
s 1 = 2*d 1
s k = (2^(k)) * (d k) --s (k-1) - d (k-1) + 2 * (d k)
phi = (1.0+sqrt(5))/2.0 | Crazycolorz5/Haskell-Code | Delaunay Fractal.hs | unlicense | 187 | 3 | 19 | 42 | 189 | 90 | 99 | 7 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Kubernetes.V1.EmptyDirVolumeSource where
import GHC.Generics
import Data.Text
import qualified Data.Aeson
-- | EmptyDirVolumeSource is temporary directory that shares a pod's lifetime.
data EmptyDirVolumeSource = EmptyDirVolumeSource
{ medium :: Maybe Text -- ^ What type of storage medium should back this directory. The default is \"\" which means to use the node's default medium. Must be an empty string (default) or Memory. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#emptydir
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON EmptyDirVolumeSource
instance Data.Aeson.ToJSON EmptyDirVolumeSource
| minhdoboi/deprecated-openshift-haskell-api | kubernetes/lib/Kubernetes/V1/EmptyDirVolumeSource.hs | apache-2.0 | 821 | 0 | 9 | 108 | 83 | 50 | 33 | 14 | 0 |
{-# LANGUAGE DeriveDataTypeable, DeriveFunctor, DeriveFoldable, DeriveTraversable, StandaloneDeriving, TypeFamilies, RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.Types
-- Copyright : (c) Simon Marlow 2003-2006,
-- David Waern 2006-2009,
-- Mateusz Kowalczyk 2013
-- License : BSD-like
--
-- Maintainer : haddock@projects.haskellorg
-- Stability : experimental
-- Portability : portable
--
-- Types that are commonly used through-out Haddock. Some of the most
-- important types are defined here, like 'Interface' and 'DocName'.
-----------------------------------------------------------------------------
module Haddock.Types (
module Haddock.Types
, HsDocString, LHsDocString
, Fixity(..)
, module Documentation.Haddock.Types
) where
import Control.Exception
import Control.Arrow hiding ((<+>))
import Control.DeepSeq
import Data.Typeable
import Data.Map (Map)
import Data.Data (Data)
import qualified Data.Map as Map
import Documentation.Haddock.Types
import BasicTypes (Fixity(..))
import GHC hiding (NoLink)
import DynFlags (Language)
import qualified GHC.LanguageExtensions as LangExt
import Coercion
import NameSet
import OccName
import Outputable
import Control.Applicative (Applicative(..))
import Control.Monad (ap)
import Haddock.Backends.Hyperlinker.Types
-----------------------------------------------------------------------------
-- * Convenient synonyms
-----------------------------------------------------------------------------
type IfaceMap = Map Module Interface
type InstIfaceMap = Map Module InstalledInterface -- TODO: rename
type DocMap a = Map Name (MDoc a)
type ArgMap a = Map Name (Map Int (MDoc a))
type SubMap = Map Name [Name]
type DeclMap = Map Name [LHsDecl Name]
type InstMap = Map SrcSpan Name
type FixMap = Map Name Fixity
type DocPaths = (FilePath, Maybe FilePath) -- paths to HTML and sources
-----------------------------------------------------------------------------
-- * Interface
-----------------------------------------------------------------------------
-- | 'Interface' holds all information used to render a single Haddock page.
-- It represents the /interface/ of a module. The core business of Haddock
-- lies in creating this structure. Note that the record contains some fields
-- that are only used to create the final record, and that are not used by the
-- backends.
data Interface = Interface
{
-- | The module behind this interface.
ifaceMod :: !Module
-- | Original file name of the module.
, ifaceOrigFilename :: !FilePath
-- | Textual information about the module.
, ifaceInfo :: !(HaddockModInfo Name)
-- | Documentation header.
, ifaceDoc :: !(Documentation Name)
-- | Documentation header with cross-reference information.
, ifaceRnDoc :: !(Documentation DocName)
-- | Haddock options for this module (prune, ignore-exports, etc).
, ifaceOptions :: ![DocOption]
-- | Declarations originating from the module. Excludes declarations without
-- names (instances and stand-alone documentation comments). Includes
-- names of subordinate declarations mapped to their parent declarations.
, ifaceDeclMap :: !(Map Name [LHsDecl Name])
-- | Documentation of declarations originating from the module (including
-- subordinates).
, ifaceDocMap :: !(DocMap Name)
, ifaceArgMap :: !(ArgMap Name)
-- | Documentation of declarations originating from the module (including
-- subordinates).
, ifaceRnDocMap :: !(DocMap DocName)
, ifaceRnArgMap :: !(ArgMap DocName)
, ifaceSubMap :: !(Map Name [Name])
, ifaceFixMap :: !(Map Name Fixity)
, ifaceExportItems :: ![ExportItem Name]
, ifaceRnExportItems :: ![ExportItem DocName]
-- | All names exported by the module.
, ifaceExports :: ![Name]
-- | All \"visible\" names exported by the module.
-- A visible name is a name that will show up in the documentation of the
-- module.
, ifaceVisibleExports :: ![Name]
-- | Aliases of module imports as in @import A.B.C as C@.
, ifaceModuleAliases :: !AliasMap
-- | Instances exported by the module.
, ifaceInstances :: ![ClsInst]
, ifaceFamInstances :: ![FamInst]
-- | Orphan instances
, ifaceOrphanInstances :: ![DocInstance Name]
, ifaceRnOrphanInstances :: ![DocInstance DocName]
-- | The number of haddockable and haddocked items in the module, as a
-- tuple. Haddockable items are the exports and the module itself.
, ifaceHaddockCoverage :: !(Int, Int)
-- | Warnings for things defined in this module.
, ifaceWarningMap :: !WarningMap
-- | Tokenized source code of module (avaliable if Haddock is invoked with
-- source generation flag).
, ifaceTokenizedSrc :: !(Maybe [RichToken])
}
type WarningMap = Map Name (Doc Name)
-- | A subset of the fields of 'Interface' that we store in the interface
-- files.
data InstalledInterface = InstalledInterface
{
-- | The module represented by this interface.
instMod :: Module
-- | Textual information about the module.
, instInfo :: HaddockModInfo Name
-- | Documentation of declarations originating from the module (including
-- subordinates).
, instDocMap :: DocMap Name
, instArgMap :: ArgMap Name
-- | All names exported by this module.
, instExports :: [Name]
-- | All \"visible\" names exported by the module.
-- A visible name is a name that will show up in the documentation of the
-- module.
, instVisibleExports :: [Name]
-- | Haddock options for this module (prune, ignore-exports, etc).
, instOptions :: [DocOption]
, instSubMap :: Map Name [Name]
, instFixMap :: Map Name Fixity
}
-- | Convert an 'Interface' to an 'InstalledInterface'
toInstalledIface :: Interface -> InstalledInterface
toInstalledIface interface = InstalledInterface
{ instMod = ifaceMod interface
, instInfo = ifaceInfo interface
, instDocMap = ifaceDocMap interface
, instArgMap = ifaceArgMap interface
, instExports = ifaceExports interface
, instVisibleExports = ifaceVisibleExports interface
, instOptions = ifaceOptions interface
, instSubMap = ifaceSubMap interface
, instFixMap = ifaceFixMap interface
}
-----------------------------------------------------------------------------
-- * Export items & declarations
-----------------------------------------------------------------------------
data ExportItem name
-- | An exported declaration.
= ExportDecl
{
-- | A declaration.
expItemDecl :: !(LHsDecl name)
-- | Maybe a doc comment, and possibly docs for arguments (if this
-- decl is a function or type-synonym).
, expItemMbDoc :: !(DocForDecl name)
-- | Subordinate names, possibly with documentation.
, expItemSubDocs :: ![(name, DocForDecl name)]
-- | Instances relevant to this declaration, possibly with
-- documentation.
, expItemInstances :: ![DocInstance name]
-- | Fixity decls relevant to this declaration (including subordinates).
, expItemFixities :: ![(name, Fixity)]
-- | Whether the ExportItem is from a TH splice or not, for generating
-- the appropriate type of Source link.
, expItemSpliced :: !Bool
}
-- | An exported entity for which we have no documentation (perhaps because it
-- resides in another package).
| ExportNoDecl
{ expItemName :: !name
-- | Subordinate names.
, expItemSubs :: ![name]
}
-- | A section heading.
| ExportGroup
{
-- | Section level (1, 2, 3, ...).
expItemSectionLevel :: !Int
-- | Section id (for hyperlinks).
, expItemSectionId :: !String
-- | Section heading text.
, expItemSectionText :: !(Doc name)
}
-- | Some documentation.
| ExportDoc !(MDoc name)
-- | A cross-reference to another module.
| ExportModule !Module
data Documentation name = Documentation
{ documentationDoc :: Maybe (MDoc name)
, documentationWarning :: !(Maybe (Doc name))
} deriving Functor
-- | Arguments and result are indexed by Int, zero-based from the left,
-- because that's the easiest to use when recursing over types.
type FnArgsDoc name = Map Int (MDoc name)
type DocForDecl name = (Documentation name, FnArgsDoc name)
noDocForDecl :: DocForDecl name
noDocForDecl = (Documentation Nothing Nothing, Map.empty)
unrenameDocForDecl :: DocForDecl DocName -> DocForDecl Name
unrenameDocForDecl (doc, fnArgsDoc) =
(fmap getName doc, (fmap . fmap) getName fnArgsDoc)
-----------------------------------------------------------------------------
-- * Cross-referencing
-----------------------------------------------------------------------------
-- | Type of environment used to cross-reference identifiers in the syntax.
type LinkEnv = Map Name Module
-- | Extends 'Name' with cross-reference information.
data DocName
= Documented Name Module
-- ^ This thing is part of the (existing or resulting)
-- documentation. The 'Module' is the preferred place
-- in the documentation to refer to.
| Undocumented Name
-- ^ This thing is not part of the (existing or resulting)
-- documentation, as far as Haddock knows.
deriving (Eq, Data)
type instance PostRn DocName NameSet = PlaceHolder
type instance PostRn DocName Fixity = PlaceHolder
type instance PostRn DocName Bool = PlaceHolder
type instance PostRn DocName [Name] = PlaceHolder
type instance PostTc DocName Kind = PlaceHolder
type instance PostTc DocName Type = PlaceHolder
type instance PostTc DocName Coercion = PlaceHolder
instance NamedThing DocName where
getName (Documented name _) = name
getName (Undocumented name) = name
-- | Useful for debugging
instance Outputable DocName where
ppr = ppr . getName
instance OutputableBndr DocName where
pprBndr _ = ppr . getName
pprPrefixOcc = pprPrefixOcc . getName
pprInfixOcc = pprInfixOcc . getName
class NamedThing name => SetName name where
setName :: Name -> name -> name
instance SetName Name where
setName name' _ = name'
instance SetName DocName where
setName name' (Documented _ mdl) = Documented name' mdl
setName name' (Undocumented _) = Undocumented name'
-----------------------------------------------------------------------------
-- * Instances
-----------------------------------------------------------------------------
-- | The three types of instances
data InstType name
= ClassInst
{ clsiCtx :: [HsType name]
, clsiTyVars :: LHsQTyVars name
, clsiSigs :: [Sig name]
, clsiAssocTys :: [PseudoFamilyDecl name]
}
| TypeInst (Maybe (HsType name)) -- ^ Body (right-hand side)
| DataInst (TyClDecl name) -- ^ Data constructors
instance OutputableBndr a => Outputable (InstType a) where
ppr (ClassInst { .. }) = text "ClassInst"
<+> ppr clsiCtx
<+> ppr clsiTyVars
<+> ppr clsiSigs
ppr (TypeInst a) = text "TypeInst" <+> ppr a
ppr (DataInst a) = text "DataInst" <+> ppr a
-- | Almost the same as 'FamilyDecl' except for type binders.
--
-- In order to perform type specialization for class instances, we need to
-- substitute class variables to appropriate type. However, type variables in
-- associated type are specified using 'LHsTyVarBndrs' instead of 'HsType'.
-- This makes type substitution impossible and to overcome this issue,
-- 'PseudoFamilyDecl' type is introduced.
data PseudoFamilyDecl name = PseudoFamilyDecl
{ pfdInfo :: FamilyInfo name
, pfdLName :: Located name
, pfdTyVars :: [LHsType name]
, pfdKindSig :: LFamilyResultSig name
}
mkPseudoFamilyDecl :: FamilyDecl name -> PseudoFamilyDecl name
mkPseudoFamilyDecl (FamilyDecl { .. }) = PseudoFamilyDecl
{ pfdInfo = fdInfo
, pfdLName = fdLName
, pfdTyVars = [ L loc (mkType bndr) | L loc bndr <- hsq_explicit fdTyVars ]
, pfdKindSig = fdResultSig
}
where
mkType (KindedTyVar (L loc name) lkind) =
HsKindSig tvar lkind
where
tvar = L loc (HsTyVar (L loc name))
mkType (UserTyVar name) = HsTyVar name
-- | An instance head that may have documentation and a source location.
type DocInstance name = (InstHead name, Maybe (MDoc name), Located name)
-- | The head of an instance. Consists of a class name, a list of kind
-- parameters, a list of type parameters and an instance type
data InstHead name = InstHead
{ ihdClsName :: name
, ihdKinds :: [HsType name]
, ihdTypes :: [HsType name]
, ihdInstType :: InstType name
}
-- | An instance origin information.
--
-- This is used primarily in HTML backend to generate unique instance
-- identifiers (for expandable sections).
data InstOrigin name
= OriginClass name
| OriginData name
| OriginFamily name
instance NamedThing name => NamedThing (InstOrigin name) where
getName (OriginClass name) = getName name
getName (OriginData name) = getName name
getName (OriginFamily name) = getName name
-----------------------------------------------------------------------------
-- * Documentation comments
-----------------------------------------------------------------------------
type LDoc id = Located (Doc id)
type Doc id = DocH (ModuleName, OccName) id
type MDoc id = MetaDoc (ModuleName, OccName) id
instance (NFData a, NFData mod)
=> NFData (DocH mod a) where
rnf doc = case doc of
DocEmpty -> ()
DocAppend a b -> a `deepseq` b `deepseq` ()
DocString a -> a `deepseq` ()
DocParagraph a -> a `deepseq` ()
DocIdentifier a -> a `deepseq` ()
DocIdentifierUnchecked a -> a `deepseq` ()
DocModule a -> a `deepseq` ()
DocWarning a -> a `deepseq` ()
DocEmphasis a -> a `deepseq` ()
DocBold a -> a `deepseq` ()
DocMonospaced a -> a `deepseq` ()
DocUnorderedList a -> a `deepseq` ()
DocOrderedList a -> a `deepseq` ()
DocDefList a -> a `deepseq` ()
DocCodeBlock a -> a `deepseq` ()
DocHyperlink a -> a `deepseq` ()
DocPic a -> a `deepseq` ()
DocMathInline a -> a `deepseq` ()
DocMathDisplay a -> a `deepseq` ()
DocAName a -> a `deepseq` ()
DocProperty a -> a `deepseq` ()
DocExamples a -> a `deepseq` ()
DocHeader a -> a `deepseq` ()
instance NFData Name where rnf x = seq x ()
instance NFData OccName where rnf x = seq x ()
instance NFData ModuleName where rnf x = seq x ()
instance NFData id => NFData (Header id) where
rnf (Header a b) = a `deepseq` b `deepseq` ()
instance NFData Hyperlink where
rnf (Hyperlink a b) = a `deepseq` b `deepseq` ()
instance NFData Picture where
rnf (Picture a b) = a `deepseq` b `deepseq` ()
instance NFData Example where
rnf (Example a b) = a `deepseq` b `deepseq` ()
exampleToString :: Example -> String
exampleToString (Example expression result) =
">>> " ++ expression ++ "\n" ++ unlines result
data DocMarkup id a = Markup
{ markupEmpty :: a
, markupString :: String -> a
, markupParagraph :: a -> a
, markupAppend :: a -> a -> a
, markupIdentifier :: id -> a
, markupIdentifierUnchecked :: (ModuleName, OccName) -> a
, markupModule :: String -> a
, markupWarning :: a -> a
, markupEmphasis :: a -> a
, markupBold :: a -> a
, markupMonospaced :: a -> a
, markupUnorderedList :: [a] -> a
, markupOrderedList :: [a] -> a
, markupDefList :: [(a,a)] -> a
, markupCodeBlock :: a -> a
, markupHyperlink :: Hyperlink -> a
, markupAName :: String -> a
, markupPic :: Picture -> a
, markupMathInline :: String -> a
, markupMathDisplay :: String -> a
, markupProperty :: String -> a
, markupExample :: [Example] -> a
, markupHeader :: Header a -> a
}
data HaddockModInfo name = HaddockModInfo
{ hmi_description :: Maybe (Doc name)
, hmi_copyright :: Maybe String
, hmi_license :: Maybe String
, hmi_maintainer :: Maybe String
, hmi_stability :: Maybe String
, hmi_portability :: Maybe String
, hmi_safety :: Maybe String
, hmi_language :: Maybe Language
, hmi_extensions :: [LangExt.Extension]
}
emptyHaddockModInfo :: HaddockModInfo a
emptyHaddockModInfo = HaddockModInfo
{ hmi_description = Nothing
, hmi_copyright = Nothing
, hmi_license = Nothing
, hmi_maintainer = Nothing
, hmi_stability = Nothing
, hmi_portability = Nothing
, hmi_safety = Nothing
, hmi_language = Nothing
, hmi_extensions = []
}
-----------------------------------------------------------------------------
-- * Options
-----------------------------------------------------------------------------
-- | Source-level options for controlling the documentation.
data DocOption
= OptHide -- ^ This module should not appear in the docs.
| OptPrune
| OptIgnoreExports -- ^ Pretend everything is exported.
| OptNotHome -- ^ Not the best place to get docs for things
-- exported by this module.
| OptShowExtensions -- ^ Render enabled extensions for this module.
deriving (Eq, Show)
-- | Option controlling how to qualify names
data QualOption
= OptNoQual -- ^ Never qualify any names.
| OptFullQual -- ^ Qualify all names fully.
| OptLocalQual -- ^ Qualify all imported names fully.
| OptRelativeQual -- ^ Like local, but strip module prefix
-- from modules in the same hierarchy.
| OptAliasedQual -- ^ Uses aliases of module names
-- as suggested by module import renamings.
-- However, we are unfortunately not able
-- to maintain the original qualifications.
-- Image a re-export of a whole module,
-- how could the re-exported identifiers be qualified?
type AliasMap = Map Module ModuleName
data Qualification
= NoQual
| FullQual
| LocalQual Module
| RelativeQual Module
| AliasedQual AliasMap Module
-- ^ @Module@ contains the current module.
-- This way we can distinguish imported and local identifiers.
makeContentsQual :: QualOption -> Qualification
makeContentsQual qual =
case qual of
OptNoQual -> NoQual
_ -> FullQual
makeModuleQual :: QualOption -> AliasMap -> Module -> Qualification
makeModuleQual qual aliases mdl =
case qual of
OptLocalQual -> LocalQual mdl
OptRelativeQual -> RelativeQual mdl
OptAliasedQual -> AliasedQual aliases mdl
OptFullQual -> FullQual
OptNoQual -> NoQual
-----------------------------------------------------------------------------
-- * Error handling
-----------------------------------------------------------------------------
-- A monad which collects error messages, locally defined to avoid a dep on mtl
type ErrMsg = String
newtype ErrMsgM a = Writer { runWriter :: (a, [ErrMsg]) }
instance Functor ErrMsgM where
fmap f (Writer (a, msgs)) = Writer (f a, msgs)
instance Applicative ErrMsgM where
pure a = Writer (a, [])
(<*>) = ap
instance Monad ErrMsgM where
return = pure
m >>= k = Writer $ let
(a, w) = runWriter m
(b, w') = runWriter (k a)
in (b, w ++ w')
tell :: [ErrMsg] -> ErrMsgM ()
tell w = Writer ((), w)
-- Exceptions
-- | Haddock's own exception type.
data HaddockException = HaddockException String deriving Typeable
instance Show HaddockException where
show (HaddockException str) = str
throwE :: String -> a
instance Exception HaddockException
throwE str = throw (HaddockException str)
-- In "Haddock.Interface.Create", we need to gather
-- @Haddock.Types.ErrMsg@s a lot, like @ErrMsgM@ does,
-- but we can't just use @GhcT ErrMsgM@ because GhcT requires the
-- transformed monad to be MonadIO.
newtype ErrMsgGhc a = WriterGhc { runWriterGhc :: Ghc (a, [ErrMsg]) }
--instance MonadIO ErrMsgGhc where
-- liftIO = WriterGhc . fmap (\a->(a,[])) liftIO
--er, implementing GhcMonad involves annoying ExceptionMonad and
--WarnLogMonad classes, so don't bother.
liftGhcToErrMsgGhc :: Ghc a -> ErrMsgGhc a
liftGhcToErrMsgGhc = WriterGhc . fmap (\a->(a,[]))
liftErrMsg :: ErrMsgM a -> ErrMsgGhc a
liftErrMsg = WriterGhc . return . runWriter
-- for now, use (liftErrMsg . tell) for this
--tell :: [ErrMsg] -> ErrMsgGhc ()
--tell msgs = WriterGhc $ return ( (), msgs )
instance Functor ErrMsgGhc where
fmap f (WriterGhc x) = WriterGhc (fmap (first f) x)
instance Applicative ErrMsgGhc where
pure a = WriterGhc (return (a, []))
(<*>) = ap
instance Monad ErrMsgGhc where
return = pure
m >>= k = WriterGhc $ runWriterGhc m >>= \ (a, msgs1) ->
fmap (second (msgs1 ++)) (runWriterGhc (k a))
-----------------------------------------------------------------------------
-- * Pass sensitive types
-----------------------------------------------------------------------------
type instance PostRn DocName NameSet = PlaceHolder
type instance PostRn DocName Fixity = PlaceHolder
type instance PostRn DocName Bool = PlaceHolder
type instance PostRn DocName Name = DocName
type instance PostRn DocName (Located Name) = Located DocName
type instance PostRn DocName [Name] = PlaceHolder
type instance PostRn DocName DocName = DocName
type instance PostTc DocName Kind = PlaceHolder
type instance PostTc DocName Type = PlaceHolder
type instance PostTc DocName Coercion = PlaceHolder
| randen/haddock | haddock-api/src/Haddock/Types.hs | bsd-2-clause | 22,504 | 0 | 13 | 5,579 | 4,280 | 2,436 | 1,844 | 427 | 5 |
maxp [] = (Nothing, Nothing)
maxp (x:[]) = (Just x, Nothing)
maxp (x:y:[])
| x > y = (Just x, Just y)
| otherwise = (Just y, Just y)
maxp (x:xs) = case maxp xs of
(Just a, Just b) -> let x' = x + b; y' = a in
if x' > y' then (Just x', Just y') else (Just y', Just y')
rob = uncurry max . maxp
| wangbj/leet | 198.hs | bsd-2-clause | 306 | 0 | 12 | 84 | 216 | 110 | 106 | 9 | 2 |
upd (r, g, y, b) 'R' = (succ r, g, y, b)
upd (r, g, y, b) 'G' = (r, succ g, y, b)
upd (r, g, y, b) 'Y' = (r, g, succ y, b)
upd (r, g, y, b) 'B' = (r, g, y, succ b)
slv (r, g, y, b) [] = r == g && y == b
slv (r, g, y, b) (c : cs) =
if abs (r' - g') > 1 || abs (y' - b') > 1
then False
else slv acc cs
where
acc@(r', g', y', b') = upd (r, g, y, b) c
tst = do
cs <- getLine
putStrLn $ show $ slv (0, 0, 0, 0) cs
main = do
tstr <- getLine
mapM_ (const tst) [1 .. read tstr]
| pbl64k/HackerRank-Contests | 2014-10-10-FP/SequenceFullOfColors/sfoc.accepted.hs | bsd-2-clause | 522 | 0 | 11 | 184 | 374 | 210 | 164 | 16 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS -fno-warn-orphans #-}
module Dixi.Forms where
import Servant.API
import Text.Read
#ifdef OLDBASE
import Control.Applicative
#endif
import qualified Data.Text as T
import Dixi.API
instance FromFormUrlEncoded NewBody where
fromFormUrlEncoded x = NB <$> maybe (Left "error") Right (lookup "content" x) <*> pure (lookup "comment" x)
instance ToFormUrlEncoded NewBody where
toFormUrlEncoded (NB t c) = ("content", T.pack $ show t) : maybe [] (pure . ("comment",)) c
instance ToFormUrlEncoded RevReq where
toFormUrlEncoded (DR v1 v2 c) = [("from", T.pack $ show v1), ("to", T.pack $ show v2)] ++ maybe [] (pure . ("comment",)) c
instance FromFormUrlEncoded RevReq where
fromFormUrlEncoded x = DR <$> maybe (Left "error") Right (lookup "from" x >>= readMaybe . T.unpack)
<*> maybe (Left "error") Right (lookup "to" x >>= readMaybe . T.unpack)
<*> pure (lookup "comment" x)
| liamoc/dixi | Dixi/Forms.hs | bsd-3-clause | 1,055 | 0 | 13 | 231 | 346 | 183 | 163 | 19 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.