code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE FlexibleContexts #-}
module Persistent where
import Control.Monad.State (MonadState)
import Control.Monad.State (StateT)
import Control.Monad.State (execStateT)
import Control.Monad.State (get)
import Control.Monad.State (gets)
import Control.Monad.State (modify)
import Control.Monad.Trans (liftIO)
data Doc =
Doc
{ items :: [Item]
, nextItemID :: ItemID }
deriving (Show, Read, Eq, Ord)
data Item =
Item
{ itemID :: ItemID
, itemTitle :: Title
, itemBody :: Body
} deriving (Show, Read, Eq, Ord)
type ItemID = Int
type Title = String
type Body = String
main :: IO ()
main = do
putStrLn "Started."
doc <- execStateT cmdLoop newDoc
putStrLn "Doc:"
print doc
putStrLn "Terminated."
return ()
cmdLoop :: StateT Doc IO ()
cmdLoop = do
liftIO $ putStr "cmd> "
cmd <- liftIO getLine
case cmd of
"quit" -> return ()
"show" -> do doc <- get
liftIO $ print doc
cmdLoop
"add" -> do liftIO $ putStr "Title: "
title <- liftIO $ getLine
liftIO $ putStr "Body: "
body <- liftIO $ getLine
addItem title body
cmdLoop
'@' : _ -> do liftIO $ putStrLn cmd
cmdLoop
"help" -> do { liftIO putHelp; cmdLoop }
_ -> do liftIO $ putStrLn "Invalid command."
cmdLoop
cmds :: [String]
cmds = ["quit", "show", "add", "help"]
putHelp :: IO ()
putHelp = do
putStrLn "Available commands:"
flip mapM_ cmds $ \cmd -> putStrLn (" " ++ cmd)
-- TBD: connect to persitent store
newDoc :: Doc
newDoc = Doc { items = [], nextItemID = 0 }
addItem :: MonadState Doc m => Title -> Body -> m ()
addItem title body = do
iid <- gets nextItemID
modify $ \doc -> Doc { items = Item iid title body : items doc,
nextItemID = iid + 1 }
-- TBD: showItem
-- TBD: updateItem
-- TBD: deleteItem
| notae/haskell-exercise | io/Persistent.hs | bsd-3-clause | 1,897 | 0 | 13 | 537 | 644 | 334 | 310 | 64 | 6 |
import System.Environment (getArgs)
import Data.List (isInfixOf)
import Data.List.Split (splitOn)
count :: (Eq a) => a -> [a] -> Int
count x ys = length (filter (== x) ys)
details :: [String] -> Int
details [] = 10
details (x:xs) | isInfixOf "XY" x = 0
| otherwise = min (count '.' x) (details xs)
main :: IO ()
main = do
[inpFile] <- getArgs
input <- readFile inpFile
putStr . unlines . map (show . details . splitOn ",") $ lines input
| nikai3d/ce-challenges | easy/details.hs | bsd-3-clause | 484 | 0 | 12 | 129 | 228 | 116 | 112 | 14 | 1 |
{-# language CPP #-}
-- | = Name
--
-- VK_EXT_validation_flags - instance extension
--
-- == VK_EXT_validation_flags
--
-- [__Name String__]
-- @VK_EXT_validation_flags@
--
-- [__Extension Type__]
-- Instance extension
--
-- [__Registered Extension Number__]
-- 62
--
-- [__Revision__]
-- 2
--
-- [__Extension and Version Dependencies__]
--
-- - Requires Vulkan 1.0
--
-- [__Deprecation state__]
--
-- - /Deprecated/ by @VK_EXT_validation_features@ extension
--
-- [__Special Use__]
--
-- - <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#extendingvulkan-compatibility-specialuse Debugging tools>
--
-- [__Contact__]
--
-- - Tobin Ehlis
-- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_validation_flags] @tobine%0A<<Here describe the issue or question you have about the VK_EXT_validation_flags extension>> >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
-- 2019-08-19
--
-- [__IP Status__]
-- No known IP claims.
--
-- [__Contributors__]
--
-- - Tobin Ehlis, Google
--
-- - Courtney Goeltzenleuchter, Google
--
-- == Description
--
-- This extension provides the 'ValidationFlagsEXT' struct that can be
-- included in the @pNext@ chain of the
-- 'Vulkan.Core10.DeviceInitialization.InstanceCreateInfo' structure passed
-- as the @pCreateInfo@ parameter of
-- 'Vulkan.Core10.DeviceInitialization.createInstance'. The structure
-- contains an array of 'ValidationCheckEXT' values that will be disabled
-- by the validation layers.
--
-- == Deprecation by @VK_EXT_validation_features@
--
-- Functionality in this extension is subsumed into the
-- @VK_EXT_validation_features@ extension.
--
-- == New Structures
--
-- - Extending 'Vulkan.Core10.DeviceInitialization.InstanceCreateInfo':
--
-- - 'ValidationFlagsEXT'
--
-- == New Enums
--
-- - 'ValidationCheckEXT'
--
-- == New Enum Constants
--
-- - 'EXT_VALIDATION_FLAGS_EXTENSION_NAME'
--
-- - 'EXT_VALIDATION_FLAGS_SPEC_VERSION'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_VALIDATION_FLAGS_EXT'
--
-- == Version History
--
-- - Revision 2, 2019-08-19 (Mark Lobodzinski)
--
-- - Marked as deprecated
--
-- - Revision 1, 2016-08-26 (Courtney Goeltzenleuchter)
--
-- - Initial draft
--
-- == See Also
--
-- 'ValidationCheckEXT', 'ValidationFlagsEXT'
--
-- == Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_EXT_validation_flags Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_EXT_validation_flags ( ValidationFlagsEXT(..)
, ValidationCheckEXT( VALIDATION_CHECK_ALL_EXT
, VALIDATION_CHECK_SHADERS_EXT
, ..
)
, EXT_VALIDATION_FLAGS_SPEC_VERSION
, pattern EXT_VALIDATION_FLAGS_SPEC_VERSION
, EXT_VALIDATION_FLAGS_EXTENSION_NAME
, pattern EXT_VALIDATION_FLAGS_EXTENSION_NAME
) where
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import GHC.Show (showsPrec)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (evalContT)
import Data.Vector (generateM)
import qualified Data.Vector (imapM_)
import qualified Data.Vector (length)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero)
import Vulkan.Zero (Zero(..))
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import GHC.Generics (Generic)
import Data.Int (Int32)
import Foreign.Ptr (Ptr)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import Data.Word (Word32)
import Data.Kind (Type)
import Control.Monad.Trans.Cont (ContT(..))
import Data.Vector (Vector)
import Vulkan.CStruct.Utils (advancePtrBytes)
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_VALIDATION_FLAGS_EXT))
-- | VkValidationFlagsEXT - Specify validation checks to disable for a Vulkan
-- instance
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_validation_flags VK_EXT_validation_flags>,
-- 'Vulkan.Core10.Enums.StructureType.StructureType', 'ValidationCheckEXT'
data ValidationFlagsEXT = ValidationFlagsEXT
{ -- | @pDisabledValidationChecks@ is a pointer to an array of
-- 'ValidationCheckEXT' values specifying the validation checks to be
-- disabled.
--
-- #VUID-VkValidationFlagsEXT-pDisabledValidationChecks-parameter#
-- @pDisabledValidationChecks@ /must/ be a valid pointer to an array of
-- @disabledValidationCheckCount@ valid 'ValidationCheckEXT' values
disabledValidationChecks :: Vector ValidationCheckEXT }
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (ValidationFlagsEXT)
#endif
deriving instance Show ValidationFlagsEXT
instance ToCStruct ValidationFlagsEXT where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p ValidationFlagsEXT{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_VALIDATION_FLAGS_EXT)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
lift $ poke ((p `plusPtr` 16 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (disabledValidationChecks)) :: Word32))
pPDisabledValidationChecks' <- ContT $ allocaBytes @ValidationCheckEXT ((Data.Vector.length (disabledValidationChecks)) * 4)
lift $ Data.Vector.imapM_ (\i e -> poke (pPDisabledValidationChecks' `plusPtr` (4 * (i)) :: Ptr ValidationCheckEXT) (e)) (disabledValidationChecks)
lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr ValidationCheckEXT))) (pPDisabledValidationChecks')
lift $ f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_VALIDATION_FLAGS_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
f
instance FromCStruct ValidationFlagsEXT where
peekCStruct p = do
disabledValidationCheckCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32))
pDisabledValidationChecks <- peek @(Ptr ValidationCheckEXT) ((p `plusPtr` 24 :: Ptr (Ptr ValidationCheckEXT)))
pDisabledValidationChecks' <- generateM (fromIntegral disabledValidationCheckCount) (\i -> peek @ValidationCheckEXT ((pDisabledValidationChecks `advancePtrBytes` (4 * (i)) :: Ptr ValidationCheckEXT)))
pure $ ValidationFlagsEXT
pDisabledValidationChecks'
instance Zero ValidationFlagsEXT where
zero = ValidationFlagsEXT
mempty
-- | VkValidationCheckEXT - Specify validation checks to disable
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_validation_flags VK_EXT_validation_flags>,
-- 'ValidationFlagsEXT'
newtype ValidationCheckEXT = ValidationCheckEXT Int32
deriving newtype (Eq, Ord, Storable, Zero)
-- | 'VALIDATION_CHECK_ALL_EXT' specifies that all validation checks are
-- disabled.
pattern VALIDATION_CHECK_ALL_EXT = ValidationCheckEXT 0
-- | 'VALIDATION_CHECK_SHADERS_EXT' specifies that shader validation is
-- disabled.
pattern VALIDATION_CHECK_SHADERS_EXT = ValidationCheckEXT 1
{-# complete VALIDATION_CHECK_ALL_EXT,
VALIDATION_CHECK_SHADERS_EXT :: ValidationCheckEXT #-}
conNameValidationCheckEXT :: String
conNameValidationCheckEXT = "ValidationCheckEXT"
enumPrefixValidationCheckEXT :: String
enumPrefixValidationCheckEXT = "VALIDATION_CHECK_"
showTableValidationCheckEXT :: [(ValidationCheckEXT, String)]
showTableValidationCheckEXT = [(VALIDATION_CHECK_ALL_EXT, "ALL_EXT"), (VALIDATION_CHECK_SHADERS_EXT, "SHADERS_EXT")]
instance Show ValidationCheckEXT where
showsPrec = enumShowsPrec enumPrefixValidationCheckEXT
showTableValidationCheckEXT
conNameValidationCheckEXT
(\(ValidationCheckEXT x) -> x)
(showsPrec 11)
instance Read ValidationCheckEXT where
readPrec =
enumReadPrec enumPrefixValidationCheckEXT showTableValidationCheckEXT conNameValidationCheckEXT ValidationCheckEXT
type EXT_VALIDATION_FLAGS_SPEC_VERSION = 2
-- No documentation found for TopLevel "VK_EXT_VALIDATION_FLAGS_SPEC_VERSION"
pattern EXT_VALIDATION_FLAGS_SPEC_VERSION :: forall a . Integral a => a
pattern EXT_VALIDATION_FLAGS_SPEC_VERSION = 2
type EXT_VALIDATION_FLAGS_EXTENSION_NAME = "VK_EXT_validation_flags"
-- No documentation found for TopLevel "VK_EXT_VALIDATION_FLAGS_EXTENSION_NAME"
pattern EXT_VALIDATION_FLAGS_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern EXT_VALIDATION_FLAGS_EXTENSION_NAME = "VK_EXT_validation_flags"
| expipiplus1/vulkan | src/Vulkan/Extensions/VK_EXT_validation_flags.hs | bsd-3-clause | 9,655 | 1 | 18 | 1,817 | 1,471 | 896 | 575 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
module Facebook.Gen.Types
where
import Data.Text hiding (length)
import Data.Csv
import Data.Coerce
import Control.Monad
import Control.Applicative
newtype Entity = Entity Text deriving (Show, Ord, Eq)
data InteractionMode =
Reading
| Creating
| Updating
| Deleting
| Types -- Used only for Types.hs
deriving (Show, Ord, Eq)
newtype Boolean = Boolean Bool deriving Show
data FieldInfo = FieldInfo {
name :: !Text
, type_ :: !Text
, desc :: !Text -- TODO: Can contain enum definitions --> change CSV files?
, required :: Boolean
, inResp :: Boolean -- when response does not contain requested field
} deriving Show
isRequired :: FieldInfo -> Bool
isRequired (FieldInfo _ _ _ (Boolean True) _) = True
isRequired _ = False
instance Eq FieldInfo where
-- in order to find duplicate field names for a single entity
(==) (FieldInfo n1 _ _ _ _)
(FieldInfo n2 _ _ _ _) = n1 == n2
instance Ord FieldInfo where -- order by type string in order to choose type when they mismatch... ugly hack
compare (FieldInfo _ t1 _ _ _)
(FieldInfo _ t2 _ _ _) = cmp t1 t2
where
cmp "Int" "Text" = GT -- FIXME!!!!
cmp "AdCreativeADT" "Text" = GT -- FIXME!!!!
cmp a b = compare a b
instance FromField Boolean where
parseField s
| s == "Y" || s == "y" = pure $ Boolean True
| otherwise = pure $ Boolean False
instance FromField InteractionMode where
parseField "Reading" = pure Reading
parseField "Creating" = pure Creating
parseField "Deleting" = pure Deleting
parseField "Updating" = pure Updating
parseField x = error $ "Don't know what to do with InteractionMode \"" ++ show x ++ "\""
| BeautifulDestinations/fb | gen/src/Facebook/Gen/Types.hs | bsd-3-clause | 1,829 | 0 | 11 | 517 | 476 | 253 | 223 | 51 | 1 |
{-# LANGUAGE UnicodeSyntax #-}
module LineCount.Select
( selectProfile
) where
import Control.Arrow
import Control.Monad
import Data.Foldable
import Data.Function
import Data.Function.JAExtra
import Data.Tuple.JAExtra
import LineCount.Base
import LineCount.Profile.Base
import Prelude.Unicode
import System.FilePath
{-|
Represents a step int the 'Profile' selection process. Results are 'mplus' chained,
ergo from left to right the function to first return a 'Just' value selects the profile.
-}
newtype Selector = Selector { unSelector ∷ MainOptions → [Profile] → FilePath → Maybe Profile }
instance Monoid Selector where
mempty = Selector (const3 mzero)
mappend (Selector s1) (Selector s2) = Selector newfunc
where
newfunc = curry3 (uncurry mplus ∘ ((&&&) `on` uncurry3) s1 s2)
defaultSelector ∷ Selector
defaultSelector = Selector (const func)
where
func profiles path = lookup (takeExtension path) $ prfsToAssocList profiles
selectorChain ∷ [Selector]
selectorChain =
[ defaultSelector
]
selector ∷ Selector
selector = fold selectorChain
selectProfile ∷ MainOptions → [Profile] → FilePath → Maybe Profile
selectProfile = unSelector selector
| JustusAdam/hlinecount | src/LineCount/Select.hs | bsd-3-clause | 1,314 | 0 | 13 | 298 | 287 | 159 | 128 | 28 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Control.Concurrent.MVar
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : non-portable (concurrency)
--
-- Synchronising variables
--
-----------------------------------------------------------------------------
module Control.Concurrent.MVar
(
-- * @MVar@s
MVar -- abstract
, newEmptyMVar -- :: IO (MVar a)
, newMVar -- :: a -> IO (MVar a)
, takeMVar -- :: MVar a -> IO a
, putMVar -- :: MVar a -> a -> IO ()
, readMVar -- :: MVar a -> IO a
, swapMVar -- :: MVar a -> a -> IO a
, tryTakeMVar -- :: MVar a -> IO (Maybe a)
, tryPutMVar -- :: MVar a -> a -> IO Bool
, isEmptyMVar -- :: MVar a -> IO Bool
, withMVar -- :: MVar a -> (a -> IO b) -> IO b
, modifyMVar_ -- :: MVar a -> (a -> IO a) -> IO ()
, modifyMVar -- :: MVar a -> (a -> IO (a,b)) -> IO b
) where
import Hugs.ConcBase ( MVar, newEmptyMVar, newMVar, takeMVar, putMVar,
tryTakeMVar, tryPutMVar, isEmptyMVar,
)
import Prelude
import Control.Exception as Exception
{-|
This is a combination of 'takeMVar' and 'putMVar'; ie. it takes the value
from the 'MVar', puts it back, and also returns it.
-}
readMVar :: MVar a -> IO a
readMVar m =
block $ do
a <- takeMVar m
putMVar m a
return a
-- |Swap the contents of an 'MVar' for a new value.
swapMVar :: MVar a -> a -> IO a
swapMVar mvar new =
block $ do
old <- takeMVar mvar
putMVar mvar new
return old
{-|
'withMVar' is a safe wrapper for operating on the contents of an
'MVar'. This operation is exception-safe: it will replace the
original contents of the 'MVar' if an exception is raised (see
"Control.Exception").
-}
withMVar :: MVar a -> (a -> IO b) -> IO b
withMVar m io =
block $ do
a <- takeMVar m
b <- Exception.catch (unblock (io a))
(\e -> do putMVar m a; throw e)
putMVar m a
return b
{-|
A safe wrapper for modifying the contents of an 'MVar'. Like 'withMVar',
'modifyMVar' will replace the original contents of the 'MVar' if an
exception is raised during the operation.
-}
modifyMVar_ :: MVar a -> (a -> IO a) -> IO ()
modifyMVar_ m io =
block $ do
a <- takeMVar m
a' <- Exception.catch (unblock (io a))
(\e -> do putMVar m a; throw e)
putMVar m a'
{-|
A slight variation on 'modifyMVar_' that allows a value to be
returned (@b@) in addition to the modified value of the 'MVar'.
-}
modifyMVar :: MVar a -> (a -> IO (a,b)) -> IO b
modifyMVar m io =
block $ do
a <- takeMVar m
(a',b) <- Exception.catch (unblock (io a))
(\e -> do putMVar m a; throw e)
putMVar m a'
return b
| OS2World/DEV-UTIL-HUGS | libraries/Control/Concurrent/MVar.hs | bsd-3-clause | 2,864 | 14 | 14 | 726 | 600 | 312 | 288 | 54 | 1 |
module Language.Haskell.Generate.Expression
( Expression(..)
, app
) where
import Language.Haskell.Exts.Syntax
newtype Expression t = Expression { runExpression :: Exp }
app :: Expression (a -> b) -> Expression a -> Expression b
app (Expression a) (Expression b) = Expression $ App a b
| bennofs/haskell-generate | src/Language/Haskell/Generate/Expression.hs | bsd-3-clause | 297 | 0 | 8 | 54 | 101 | 58 | 43 | 7 | 1 |
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import BGFX
import Control.Lens ((&), (.~))
import Data.Bits
import Data.Distributive
import Data.Foldable (for_)
import Data.Word
import Foreign
import Foreign.Ptr
import GHC.Stack
import Linear
import System.Clock
import Unsafe.Coerce
import qualified Data.ByteString as BS
import qualified SDL
foreign import ccall unsafe
"bgfx_sdl_set_window" bgfxSdlSetWindow :: Ptr a -> IO ()
main :: IO ()
main =
do let width = 1280
let height = 720
let debug = BGFX_DEBUG_TEXT
let reset = BGFX_RESET_VSYNC
SDL.initializeAll
w <-
SDL.createWindow
"bgfx with SDL2"
SDL.defaultWindow {SDL.windowInitialSize =
fromIntegral <$> V2 width height}
bgfxSdlSetWindow (unsafeCoerce w :: Ptr ())
bgfxRenderFrame
bgfxInit BGFX_RENDERER_TYPE_COUNT BGFX_PCI_ID_NONE 0 nullPtr nullPtr
bgfxReset width height reset
bgfxSetDebug debug
bgfxSetViewClear 0
(BGFX_CLEAR_COLOR .|. BGFX_CLEAR_DEPTH)
808464639
1.0
0
posColorVertexDecl <- declarePosColorVertex
vbh <-
do ref <-
withArrayLen
cubeVertices
(\len ptr ->
bgfxCopy ptr (fromIntegral (len * sizeOf (head cubeVertices))))
bgfxCreateVertexBuffer ref posColorVertexDecl BGFX_BUFFER_NONE
ibh <-
do ptr <- newArray cubeIndices
ref <-
bgfxMakeRef
ptr
(fromIntegral (length cubeIndices * sizeOf (head cubeIndices)))
bgfxCreateIndexBuffer ref BGFX_BUFFER_NONE
program <- loadProgram "vs_cubes.bin" "fs_cubes.bin"
timeOffset <- getTime Monotonic
let loop =
do _ <- SDL.pollEvents
done <- return False
if done
then return ()
else do tick
loop
tick =
do now <- getTime Monotonic
let time =
fromIntegral (timeSpecAsNanoSecs (diffTimeSpec now timeOffset)) *
1.0e-9
with (distribute
(lookAt (V3 0 0 (-35))
0
(V3 0 1 0) :: M44 Float))
(\viewPtr ->
with (distribute
(perspective
1.047
(fromIntegral width / fromIntegral height :: Float)
0.1
100))
(\projPtr -> bgfxSetViewTransform 0 viewPtr projPtr))
bgfxSetViewRect 0
0
0
(fromIntegral width)
(fromIntegral height)
bgfxTouch 0
for_ [0 .. 11] $
\yy ->
do for_ [0 .. 11] $
\xx ->
do with (distribute
(((m33_to_m44 . fromQuaternion)
(axisAngle (V3 1 0 0)
(time +
fromIntegral xx * 0.21) *
axisAngle (V3 0 1 0)
(time +
fromIntegral yy * 0.37)) :: M44 Float) &
translation .~
V3 (-15 + fromIntegral xx * 3)
(-15 + fromIntegral yy * 3)
0))
(flip bgfxSetTransform 1)
bgfxSetVertexBuffer vbh 0 maxBound
bgfxSetIndexBuffer ibh 0 maxBound
bgfxSetState BGFX_STATE_DEFAULT 0
bgfxSubmit 0 program 0
bgfxFrame
loop
bgfxShutdown
loadProgram
:: FilePath -> FilePath -> IO BgfxProgramHandle
loadProgram vsName fsName =
do vs <- loadShader vsName
fs <- loadShader fsName
bgfxCreateProgram vs fs True
where loadShader path =
do bytes <- BS.readFile path
mem <-
BS.useAsCStringLen (BS.snoc bytes 0) $
\(ptr,len) -> bgfxCopy ptr (fromIntegral len)
bgfxCreateShader mem
declarePosColorVertex :: IO (Ptr BgfxVertexDecl)
declarePosColorVertex =
do vertexDecl <- malloc
bgfxVertexDeclBegin vertexDecl BGFX_RENDERER_TYPE_NULL
bgfxVertexDeclAdd vertexDecl BGFX_ATTRIB_POSITION 3 BGFX_ATTRIB_TYPE_FLOAT False False
bgfxVertexDeclAdd vertexDecl BGFX_ATTRIB_COLOR0 4 BGFX_ATTRIB_TYPE_UINT8 True False
bgfxVertexDeclEnd vertexDecl
return vertexDecl
data PosColorVertex =
PosColorVertex (V3 Float)
Word32
instance Storable PosColorVertex where
sizeOf ~(PosColorVertex a b) = sizeOf a + sizeOf b
peek ptr =
do PosColorVertex <$> peek (castPtr ptr) <*>
peek (castPtr (ptr `plusPtr`
fromIntegral (sizeOf (undefined :: V3 Float))))
poke ptr (PosColorVertex a b) =
do poke (castPtr ptr) a
poke (castPtr (ptr `plusPtr`
fromIntegral (sizeOf (undefined :: V3 Float))))
b
alignment _ = 0
cubeVertices :: [PosColorVertex]
cubeVertices =
[PosColorVertex
(V3 (-1.0)
(1.0)
(1.0))
4278190080
,PosColorVertex
(V3 (1.0)
(1.0)
(1.0))
4278190335
,PosColorVertex
(V3 (-1.0)
(-1.0)
(1.0))
4278255360
,PosColorVertex
(V3 (1.0)
(-1.0)
(1.0))
4278255615
,PosColorVertex
(V3 (-1.0)
(1.0)
(-1.0))
4294901760
,PosColorVertex
(V3 (1.0)
(1.0)
(-1.0))
4294902015
,PosColorVertex
(V3 (-1.0)
(-1.0)
(-1.0))
4294967040
,PosColorVertex
(V3 (1.0)
(-1.0)
(-1.0))
4294967295]
cubeIndices :: [Word16]
cubeIndices =
[0,1,2,1,3,2,4,6,5,5,6,7,0,2,4,4,2,6,1,5,3,5,7,3,0,4,1,4,5,1,2,3,6,6,3,7]
| haskell-game/bgfx | Cubes.hs | bsd-3-clause | 6,439 | 0 | 35 | 2,788 | 1,709 | 863 | 846 | 193 | 2 |
module Abstract.Counter.Get (
module Abstract.Interfaces.Counter.Get,
mkCounter'Get
) where
import Abstract.Counter
import Abstract.Interfaces.Counter
import Abstract.Interfaces.Counter.Get
mkCounter'Get url = do
c <- mkCounter url
return $ counterToGet c
| adarqui/Abstract | src/Abstract/Counter/Get.hs | bsd-3-clause | 263 | 0 | 8 | 33 | 66 | 38 | 28 | 9 | 1 |
-- | Debug Options
module Graphics.QML.Debug (
setDebugLogLevel
) where
import Graphics.QML.Internal.Engine
-- | Sets the global debug log level. At level zero, no logging information
-- will be printed. Higher levels will increase debug verbosity.
setDebugLogLevel :: Int -> IO ()
setDebugLogLevel = hsqmlSetDebugLoglevel
| drhodes/HsQML | src/Graphics/QML/Debug.hs | bsd-3-clause | 329 | 0 | 7 | 51 | 41 | 26 | 15 | 5 | 1 |
module JavaScript.AceAjax.Raw.Annotation where
import qualified GHCJS.Types as GHCJS
import qualified GHCJS.Marshal as GHCJS
import qualified Data.Typeable
import GHCJS.FFI.TypeScript
import GHCJS.DOM.Types (HTMLElement)
import JavaScript.AceAjax.Raw.Types
foreign import javascript "$1.row" row :: Annotation -> IO (GHCJS.JSNumber)
foreign import javascript "$1.column" column :: Annotation -> IO (GHCJS.JSNumber)
foreign import javascript "$1.text" text :: Annotation -> IO (GHCJS.JSString)
foreign import javascript "$1.type" type_ :: Annotation -> IO (GHCJS.JSString)
| fpco/ghcjs-from-typescript | ghcjs-ace/JavaScript/AceAjax/Raw/Annotation.hs | bsd-3-clause | 573 | 6 | 7 | 64 | 145 | 87 | 58 | 11 | 0 |
{-# LANGUAGE MultiParamTypeClasses, TypeFamilies, FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS -Wall #-}
module FiniteStateMachine.Machine (
FSM(FSM), FSM1
) where
import Basic.Types
import Basic.Memory
import Basic.Features
import Basic.Operations
import FiniteStateMachine.State
--import FiniteStateMachine.Defn (atEnd)
import Control.Lens (makeLenses)
--------------------------------------------------------------------------
---------------------------- Finite State Machine
--------------------------------------------------------------------------
data FSM s f i =
FSM { _sta :: s
, _finalstates :: f
, _trans :: Trans (f, i) s
, _inpt :: i }
makeLenses ''FSM
-- The following is close to being automatable
instance HasState (FSM s f i) where
type State (FSM s f i) = s
state = sta
instance HasTransition (FSM s f i) where
transition = trans
instance HasInput (FSM s f i) where
type Input (FSM s f i) = i
input = inpt
instance HasFinal (FSM s f i) where
type Final (FSM s f i) = f
final = finalstates
instance HasStatic (FSM s f i) where
type Static (FSM s f i) = (f, i)
static g (FSM s f tr i) = fmap (\(a,b) -> FSM s a tr b) (g (f,i))
--------------------------------------------------------------------------
---------------------------------machine operations
---------------------------------------------------------------------------
instance (Eq v, SetLike l, AtEnd a i) => EndCond (FSM (FSMState v a) (l v) i) where
endcond m = isInputEnd m
-- convenient abbreviation
type FSM1 v a i c = FSM (FSMState v a) (c v) (c i)
| davidzhulijun/TAM | FiniteStateMachine/Machine.hs | bsd-3-clause | 1,667 | 0 | 10 | 304 | 478 | 267 | 211 | 38 | 0 |
{-# LANGUAGE TemplateHaskell #-}
module Dampf.Docker.Args.Network where
import Dampf.Docker.Args.Class
import Data.Text (Text)
import Control.Lens
import Data.Monoid ((<>))
import qualified Data.Text as T
data Driver = Bridge
instance Show Driver where
show Bridge = "bridge"
data CreateArgs = CreateArgs {
_driver :: Driver
, _createNet :: Text
}
data ConnectArgs = ConnectArgs {
_alias :: Maybe Text
, _ip :: Maybe Text
, _link :: Maybe [Text]
, _connectToNet :: Text
, _containerName :: Text
}
defCreateArg :: Text -> CreateArgs
defCreateArg = CreateArgs Bridge
defConnectArg :: Text -> Text -> ConnectArgs
defConnectArg net container = ConnectArgs Nothing Nothing Nothing net container
makeClassy ''ConnectArgs
makeClassy ''CreateArgs
instance ToArgs CreateArgs where
toArgs s = ["network", "create"]
<> s ^. driver . to (namedArg "driver")
<> [s ^. createNet . to T.unpack]
instance ToArgs ConnectArgs where
toArgs s = ["network", "connect"]
<> s ^. alias . _Just . to (namedTextArg "alias")
<> s ^. ip . _Just . to (namedTextArg "ip")
<> ["--link"] <> toListOf (link . _Just . traverse . to T.unpack) s
<> [s ^. connectToNet . to T.unpack]
<> [s ^. containerName . to T.unpack]
| filopodia/open | dampf/lib/Dampf/Docker/Args/Network.hs | mit | 1,254 | 2 | 18 | 255 | 423 | 229 | 194 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : $Header$
Description : Abstract syntax for common logic
Copyright : (c) Karl Luc, DFKI Bremen 2010, Eugen Kuksa and Uni Bremen 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer : eugenk@informatik.uni-bremen.de
Stability : provisional
Portability : portable
Definition of abstract syntax for common logic
-}
{-
Ref.
ISO/IEC IS 24707:2007(E)
-}
module CommonLogic.AS_CommonLogic where
import Common.Id as Id
import Common.IRI
import Common.Doc
import Common.DocUtils
import Common.Keywords
import qualified Common.AS_Annotation as AS_Anno
import Data.Data
import Data.Set (Set)
-- DrIFT command
{-! global: GetRange !-}
newtype BASIC_SPEC = Basic_spec [AS_Anno.Annoted BASIC_ITEMS]
deriving (Show, Ord, Eq, Typeable)
data BASIC_ITEMS = Axiom_items [AS_Anno.Annoted TEXT_META]
deriving (Show, Ord, Eq, Typeable)
type PrefixMapping = (String, IRI)
emptyTextMeta :: TEXT_META
emptyTextMeta = Text_meta { getText = Text [] nullRange
, textIri = Nothing
, nondiscourseNames = Nothing
, prefix_map = [] }
data TEXT_META = Text_meta { getText :: TEXT
, textIri :: Maybe IRI
, nondiscourseNames :: Maybe (Set NAME)
, prefix_map :: [PrefixMapping]
} deriving (Show, Eq, Ord, Typeable, Data)
{- TODO: check static analysis and other features on discourse names,
as soon as parsers of segregated dialects are implemented -}
-- Common Logic Syntax
data TEXT = Text [PHRASE] Id.Range
| Named_text NAME TEXT Id.Range
deriving (Show, Ord, Eq, Typeable, Data)
data PHRASE = Module MODULE
| Sentence SENTENCE
| Importation IMPORTATION
| Comment_text COMMENT TEXT Id.Range
deriving (Show, Ord, Eq, Typeable, Data)
data COMMENT = Comment String Id.Range
deriving (Show, Ord, Eq, Typeable, Data)
data MODULE = Mod NAME TEXT Id.Range
| Mod_ex NAME [NAME] TEXT Id.Range
deriving (Show, Ord, Eq, Typeable, Data)
data IMPORTATION = Imp_name NAME
deriving (Show, Ord, Eq, Typeable, Data)
data SENTENCE = Quant_sent QUANT [NAME_OR_SEQMARK] SENTENCE Id.Range
| Bool_sent BOOL_SENT Id.Range
| Atom_sent ATOM Id.Range
| Comment_sent COMMENT SENTENCE Id.Range
| Irregular_sent SENTENCE Id.Range
deriving (Show, Ord, Eq, Typeable, Data)
data QUANT = Universal | Existential
deriving (Show, Ord, Eq, Typeable, Data)
data BOOL_SENT = Junction AndOr [SENTENCE]
| Negation SENTENCE
| BinOp ImplEq SENTENCE SENTENCE
deriving (Show, Ord, Eq, Typeable, Data)
data AndOr = Conjunction | Disjunction
deriving (Show, Ord, Eq, Typeable, Data)
data ImplEq = Implication | Biconditional
deriving (Show, Ord, Eq, Typeable, Data)
data ATOM = Equation TERM TERM
| Atom TERM [TERM_SEQ]
deriving (Show, Ord, Eq, Typeable, Data)
data TERM = Name_term NAME
| Funct_term TERM [TERM_SEQ] Id.Range
| Comment_term TERM COMMENT Id.Range
| That_term SENTENCE Id.Range
deriving (Show, Ord, Eq, Typeable, Data)
data TERM_SEQ = Term_seq TERM
| Seq_marks SEQ_MARK
deriving (Show, Ord, Eq, Typeable, Data)
type NAME = Id.Token
type SEQ_MARK = Id.Token
-- binding seq
data NAME_OR_SEQMARK = Name NAME
| SeqMark SEQ_MARK
deriving (Show, Eq, Ord, Typeable, Data)
data SYMB_MAP_ITEMS = Symb_map_items [SYMB_OR_MAP] Id.Range
deriving (Show, Ord, Eq, Typeable, Data)
data SYMB_OR_MAP = Symb NAME_OR_SEQMARK
| Symb_mapN NAME NAME Id.Range
| Symb_mapS SEQ_MARK SEQ_MARK Id.Range
deriving (Show, Ord, Eq, Typeable, Data)
data SYMB_ITEMS = Symb_items [NAME_OR_SEQMARK] Id.Range
-- pos: SYMB_KIND, commas
deriving (Show, Ord, Eq, Typeable, Data)
-- pretty printing using CLIF
instance Pretty BASIC_SPEC where
pretty = printBasicSpec
instance Pretty BASIC_ITEMS where
pretty = printBasicItems
instance Pretty TEXT_META where
pretty = printTextMeta
instance Pretty TEXT where
pretty = printText
instance Pretty PHRASE where
pretty = printPhrase
instance Pretty MODULE where
pretty = printModule
instance Pretty IMPORTATION where
pretty = printImportation
instance Pretty SENTENCE where
pretty = printSentence
instance Pretty BOOL_SENT where
pretty = printBoolSent
instance Pretty AndOr where
pretty = printAndOr
instance Pretty ImplEq where
pretty = printImplEq
instance Pretty QUANT where
pretty = printQuant
instance Pretty ATOM where
pretty = printAtom
instance Pretty TERM where
pretty = printTerm
instance Pretty TERM_SEQ where
pretty = printTermSeq
instance Pretty COMMENT where
pretty = printComment
instance Pretty NAME_OR_SEQMARK where
pretty = printNameOrSeqMark
instance Pretty SYMB_OR_MAP where
pretty = printSymbOrMap
instance Pretty SYMB_MAP_ITEMS where
pretty = printSymbMapItems
instance Pretty SYMB_ITEMS where
pretty = printSymbItems
printBasicSpec :: BASIC_SPEC -> Doc
printBasicSpec (Basic_spec xs) = vcat $ map pretty xs
printBasicItems :: BASIC_ITEMS -> Doc
printBasicItems (Axiom_items xs) = vcat $ map pretty xs
printTextMeta :: TEXT_META -> Doc
printTextMeta tm = pretty $ getText tm
-- print basic spec as pure clif-texts, without any annotations
exportCLIF :: [AS_Anno.Named TEXT_META] -> Doc
exportCLIF xs = vsep $ map (exportTextMeta . AS_Anno.sentence) xs
exportBasicSpec :: BASIC_SPEC -> Doc
exportBasicSpec (Basic_spec xs) =
vsep $ map (exportBasicItems . AS_Anno.item) xs
exportBasicItems :: BASIC_ITEMS -> Doc
exportBasicItems (Axiom_items xs) =
vsep $ map (exportTextMeta . AS_Anno.item) xs
exportTextMeta :: TEXT_META -> Doc
exportTextMeta = pretty . getText
-- using pure clif syntax from here
printText :: TEXT -> Doc
printText s = case s of
Text x _ -> fsep $ map pretty x
Named_text x y _ -> parens $ text clTextS <+> pretty x <+> pretty y
printPhrase :: PHRASE -> Doc
printPhrase s = case s of
Module x -> parens $ text clModuleS <+> pretty x
Sentence x -> pretty x
Importation x -> parens $ text clImportS <+> pretty x
Comment_text x y _ -> parens $ text clCommentS <+> pretty x <+> pretty y
printModule :: MODULE -> Doc
printModule (Mod x z _) = pretty x <+> pretty z
printModule (Mod_ex x y z _) =
pretty x <+> parens (text clExcludeS <+> fsep (map pretty y)) <+> pretty z
printImportation :: IMPORTATION -> Doc
printImportation (Imp_name x) = pretty x
printSentence :: SENTENCE -> Doc
printSentence s = case s of
Quant_sent q vs is _ ->
parens $ pretty q <+> parens (sep $ map pretty vs) <+> pretty is
Bool_sent xs _ -> parens $ pretty xs
Atom_sent xs _ -> pretty xs
Comment_sent x y _ -> parens $ text clCommentS <+> pretty x <+> pretty y
Irregular_sent xs _ -> parens $ pretty xs
printComment :: COMMENT -> Doc
printComment s = case s of
Comment x _ -> text x
printQuant :: QUANT -> Doc
printQuant s = case s of
Universal -> text forallS
Existential -> text existsS
printBoolSent :: BOOL_SENT -> Doc
printBoolSent s = case s of
Junction q xs -> pretty q <+> fsep (map pretty xs)
Negation xs -> text notS <+> pretty xs
BinOp q x y -> pretty q <+> pretty x <+> pretty y
printAndOr :: AndOr -> Doc
printAndOr s = case s of
Conjunction -> text andS
Disjunction -> text orS
printImplEq :: ImplEq -> Doc
printImplEq s = case s of
Implication -> text ifS
Biconditional -> text iffS
printAtom :: ATOM -> Doc
printAtom s = case s of
Equation a b -> parens $ equals <+> pretty a <+> pretty b
Atom t ts -> parens $ pretty t <+> sep (map pretty ts)
printTerm :: TERM -> Doc
printTerm s = case s of
Name_term a -> pretty a
Funct_term t ts _ -> parens $ pretty t <+> fsep (map pretty ts)
Comment_term t c _ -> parens $ text clCommentS <+> pretty c <+> pretty t
That_term sent _ -> parens $ text "that" <+> pretty sent
printTermSeq :: TERM_SEQ -> Doc
printTermSeq s = case s of
Term_seq t -> pretty t
Seq_marks m -> pretty m
-- Binding Seq
printNameOrSeqMark :: NAME_OR_SEQMARK -> Doc
printNameOrSeqMark s = case s of
Name x -> pretty x
SeqMark x -> pretty x
-- Alt x y -> pretty x <+> pretty y
printSymbOrMap :: SYMB_OR_MAP -> Doc
printSymbOrMap (Symb nos) = pretty nos
printSymbOrMap (Symb_mapN source dest _) =
pretty source <+> mapsto <+> pretty dest <> space
printSymbOrMap (Symb_mapS source dest _) =
pretty source <+> mapsto <+> pretty dest <> space
{- space needed. without space the comma (from printSymbMapItems)
would be part of the name @dest@ -}
printSymbMapItems :: SYMB_MAP_ITEMS -> Doc
printSymbMapItems (Symb_map_items xs _) = ppWithCommas xs
printSymbItems :: SYMB_ITEMS -> Doc
printSymbItems (Symb_items xs _) = fsep $ map pretty xs
-- keywords, reservednames in CLIF
orS :: String
orS = "or"
iffS :: String
iffS = "iff"
clCommentS :: String
clCommentS = "cl-comment"
clTextS :: String
clTextS = "cl-text"
clImportS :: String
clImportS = "cl-imports"
clModuleS :: String
clModuleS = "cl-module"
clExcludeS :: String
clExcludeS = "cl-excludes"
| mariefarrell/Hets | CommonLogic/AS_CommonLogic.der.hs | gpl-2.0 | 9,494 | 0 | 13 | 2,372 | 2,793 | 1,443 | 1,350 | 222 | 5 |
{-# LANGUAGE DeriveDataTypeable #-}
module Common where
import Control.Exception
import Data.Typeable
import Data.Data
-- A EndUserFailure corresponds to user error; anything other exceptions
-- are our fault
data EndUserFailure = UpdateFailure | ParseFailure
deriving (Typeable, Show, Data)
instance Exception EndUserFailure
| diflying/logitext | Common.hs | bsd-3-clause | 333 | 0 | 6 | 47 | 54 | 32 | 22 | 8 | 0 |
{-# LANGUAGE Haskell2010 #-}
{-# LINE 1 "System/FilePath.hs" #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE Safe #-}
{- |
Module : System.FilePath
Copyright : (c) Neil Mitchell 2005-2014
License : BSD3
Maintainer : ndmitchell@gmail.com
Stability : stable
Portability : portable
A library for 'FilePath' manipulations, using Posix or Windows filepaths
depending on the platform.
Both "System.FilePath.Posix" and "System.FilePath.Windows" provide the
same interface. See either for examples and a list of the available
functions.
-}
module System.FilePath(module System.FilePath.Posix) where
import System.FilePath.Posix
| phischu/fragnix | tests/packages/scotty/System.FilePath.hs | bsd-3-clause | 681 | 0 | 5 | 151 | 26 | 19 | 7 | 6 | 0 |
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | orphan instances
module Instances where
import Control.Monad.State.Strict
import Network.MPD.Core
instance MonadMPD (StateT a MPD) where
getVersion = lift getVersion
open = lift open
close = lift close
send = lift . send
setPassword = lift . setPassword
getPassword = lift getPassword
| haasn/vimus | src/Instances.hs | mit | 426 | 5 | 8 | 114 | 90 | 49 | 41 | 12 | 0 |
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Pack
-- Copyright : (c) The University of Glasgow 1997-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : cvs-ghc@haskell.org
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- This module provides a small set of low-level functions for packing
-- and unpacking a chunk of bytes. Used by code emitted by the compiler
-- plus the prelude libraries.
--
-- The programmer level view of packed strings is provided by a GHC
-- system library PackedString.
--
-----------------------------------------------------------------------------
module GHC.Pack
(
-- (**) - emitted by compiler.
packCString#,
unpackCString,
unpackCString#,
unpackNBytes#,
unpackFoldrCString#, -- (**)
unpackAppendCString#, -- (**)
)
where
import GHC.Base
import GHC.List ( length )
import GHC.ST
import GHC.Ptr
data ByteArray ix = ByteArray ix ix ByteArray#
data MutableByteArray s ix = MutableByteArray ix ix (MutableByteArray# s)
unpackCString :: JString -> [Char]
unpackCString (JS# s) = unpackCString# s
-- unpackCString :: Ptr a -> [Char]
-- unpackCString a@(Ptr addr)
-- | a == nullPtr = []
-- | otherwise = undefined -- TODO: unpackCString# addr
packCString# :: [Char] -> ByteArray#
packCString# str = case (packString str) of { ByteArray _ _ bytes -> bytes }
packString :: [Char] -> ByteArray Int
packString str = runST (packStringST str)
packStringST :: [Char] -> ST s (ByteArray Int)
packStringST str =
let len = length str in
packNBytesST len str
packNBytesST :: Int -> [Char] -> ST s (ByteArray Int)
packNBytesST (I# length#) str =
{-
allocate an array that will hold the string
(not forgetting the NUL byte at the end)
-}
new_ps_array (length# +# 1#) >>= \ ch_array ->
-- fill in packed string from "str"
fill_in ch_array 0# str >>
-- freeze the puppy:
freeze_ps_array ch_array length#
where
fill_in :: MutableByteArray s Int -> Int# -> [Char] -> ST s ()
fill_in arr_in# idx [] =
write_ps_array arr_in# idx (chr# 0#) >>
return ()
fill_in arr_in# idx (C# c : cs) =
write_ps_array arr_in# idx c >>
fill_in arr_in# (idx +# 1#) cs
-- (Very :-) ``Specialised'' versions of some CharArray things...
new_ps_array :: Int# -> ST s (MutableByteArray s Int)
write_ps_array :: MutableByteArray s Int -> Int# -> Char# -> ST s ()
freeze_ps_array :: MutableByteArray s Int -> Int# -> ST s (ByteArray Int)
new_ps_array size = ST $ \ s ->
case (newByteArray# size s) of { (# s2#, barr# #) ->
(# s2#, MutableByteArray bot bot barr# #) }
where
bot = error "new_ps_array"
write_ps_array (MutableByteArray _ _ barr#) n ch = ST $ \ s# ->
case writeCharArray# barr# n ch s# of { s2# ->
(# s2#, () #) }
-- same as unsafeFreezeByteArray
freeze_ps_array (MutableByteArray _ _ arr#) len# = ST $ \ s# ->
case unsafeFreezeByteArray# arr# s# of { (# s2#, frozen# #) ->
(# s2#, ByteArray 0 (I# len#) frozen# #) }
| alexander-at-github/eta | libraries/base/GHC/Pack.hs | bsd-3-clause | 3,267 | 0 | 13 | 738 | 743 | 401 | 342 | 52 | 2 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
Type checking of type signatures in interface files
-}
{-# LANGUAGE CPP #-}
module TcIface (
tcLookupImported_maybe,
importDecl, checkWiredInTyCon, tcHiBootIface, typecheckIface,
tcIfaceDecl, tcIfaceInst, tcIfaceFamInst, tcIfaceRules,
tcIfaceVectInfo, tcIfaceAnnotations,
tcIfaceExpr, -- Desired by HERMIT (Trac #7683)
tcIfaceGlobal
) where
#include "HsVersions.h"
import TcTypeNats(typeNatCoAxiomRules)
import IfaceSyn
import LoadIface
import IfaceEnv
import BuildTyCl
import TcRnMonad
import TcType
import Type
import Coercion hiding (substTy)
import TypeRep
import HscTypes
import Annotations
import InstEnv
import FamInstEnv
import CoreSyn
import CoreUtils
import CoreUnfold
import CoreLint
import MkCore
import Id
import MkId
import IdInfo
import Class
import TyCon
import CoAxiom
import ConLike
import DataCon
import PrelNames
import TysWiredIn
import TysPrim ( superKindTyConName )
import BasicTypes ( strongLoopBreaker, Arity, TupleSort(..)
, Boxity(..), pprRuleName )
import Literal
import qualified Var
import VarEnv
import VarSet
import Name
import NameEnv
import NameSet
import OccurAnal ( occurAnalyseExpr )
import Demand
import Module
import UniqFM
import UniqSupply
import Outputable
import Maybes
import SrcLoc
import DynFlags
import Util
import FastString
import Control.Monad
import qualified Data.Map as Map
#if __GLASGOW_HASKELL__ < 709
import Data.Traversable ( traverse )
#endif
{-
This module takes
IfaceDecl -> TyThing
IfaceType -> Type
etc
An IfaceDecl is populated with RdrNames, and these are not renamed to
Names before typechecking, because there should be no scope errors etc.
-- For (b) consider: f = \$(...h....)
-- where h is imported, and calls f via an hi-boot file.
-- This is bad! But it is not seen as a staging error, because h
-- is indeed imported. We don't want the type-checker to black-hole
-- when simplifying and compiling the splice!
--
-- Simple solution: discard any unfolding that mentions a variable
-- bound in this module (and hence not yet processed).
-- The discarding happens when forkM finds a type error.
************************************************************************
* *
Type-checking a complete interface
* *
************************************************************************
Suppose we discover we don't need to recompile. Then we must type
check the old interface file. This is a bit different to the
incremental type checking we do as we suck in interface files. Instead
we do things similarly as when we are typechecking source decls: we
bring into scope the type envt for the interface all at once, using a
knot. Remember, the decls aren't necessarily in dependency order --
and even if they were, the type decls might be mutually recursive.
-}
typecheckIface :: ModIface -- Get the decls from here
-> TcRnIf gbl lcl ModDetails
typecheckIface iface
= initIfaceTc iface $ \ tc_env_var -> do
-- The tc_env_var is freshly allocated, private to
-- type-checking this particular interface
{ -- Get the right set of decls and rules. If we are compiling without -O
-- we discard pragmas before typechecking, so that we don't "see"
-- information that we shouldn't. From a versioning point of view
-- It's not actually *wrong* to do so, but in fact GHCi is unable
-- to handle unboxed tuples, so it must not see unfoldings.
ignore_prags <- goptM Opt_IgnoreInterfacePragmas
-- Typecheck the decls. This is done lazily, so that the knot-tying
-- within this single module work out right. In the If monad there is
-- no global envt for the current interface; instead, the knot is tied
-- through the if_rec_types field of IfGblEnv
; names_w_things <- loadDecls ignore_prags (mi_decls iface)
; let type_env = mkNameEnv names_w_things
; writeMutVar tc_env_var type_env
-- Now do those rules, instances and annotations
; insts <- mapM tcIfaceInst (mi_insts iface)
; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
; rules <- tcIfaceRules ignore_prags (mi_rules iface)
; anns <- tcIfaceAnnotations (mi_anns iface)
-- Vectorisation information
; vect_info <- tcIfaceVectInfo (mi_module iface) type_env (mi_vect_info iface)
-- Exports
; exports <- ifaceExportNames (mi_exports iface)
-- Finished
; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
text "Type envt:" <+> ppr type_env])
; return $ ModDetails { md_types = type_env
, md_insts = insts
, md_fam_insts = fam_insts
, md_rules = rules
, md_anns = anns
, md_vect_info = vect_info
, md_exports = exports
}
}
{-
************************************************************************
* *
Type and class declarations
* *
************************************************************************
-}
tcHiBootIface :: HscSource -> Module -> TcRn SelfBootInfo
-- Load the hi-boot iface for the module being compiled,
-- if it indeed exists in the transitive closure of imports
-- Return the ModDetails; Nothing if no hi-boot iface
tcHiBootIface hsc_src mod
| HsBootFile <- hsc_src -- Already compiling a hs-boot file
= return NoSelfBoot
| otherwise
= do { traceIf (text "loadHiBootInterface" <+> ppr mod)
; mode <- getGhcMode
; if not (isOneShot mode)
-- In --make and interactive mode, if this module has an hs-boot file
-- we'll have compiled it already, and it'll be in the HPT
--
-- We check wheher the interface is a *boot* interface.
-- It can happen (when using GHC from Visual Studio) that we
-- compile a module in TypecheckOnly mode, with a stable,
-- fully-populated HPT. In that case the boot interface isn't there
-- (it's been replaced by the mother module) so we can't check it.
-- And that's fine, because if M's ModInfo is in the HPT, then
-- it's been compiled once, and we don't need to check the boot iface
then do { hpt <- getHpt
; case lookupUFM hpt (moduleName mod) of
Just info | mi_boot (hm_iface info)
-> return (mkSelfBootInfo (hm_details info))
_ -> return NoSelfBoot }
else do
-- OK, so we're in one-shot mode.
-- Re #9245, we always check if there is an hi-boot interface
-- to check consistency against, rather than just when we notice
-- that an hi-boot is necessary due to a circular import.
{ read_result <- findAndReadIface
need mod
True -- Hi-boot file
; case read_result of {
Succeeded (iface, _path) -> do { tc_iface <- typecheckIface iface
; return (mkSelfBootInfo tc_iface) } ;
Failed err ->
-- There was no hi-boot file. But if there is circularity in
-- the module graph, there really should have been one.
-- Since we've read all the direct imports by now,
-- eps_is_boot will record if any of our imports mention the
-- current module, which either means a module loop (not
-- a SOURCE import) or that our hi-boot file has mysteriously
-- disappeared.
do { eps <- getEps
; case lookupUFM (eps_is_boot eps) (moduleName mod) of
Nothing -> return NoSelfBoot -- The typical case
Just (_, False) -> failWithTc moduleLoop
-- Someone below us imported us!
-- This is a loop with no hi-boot in the way
Just (_mod, True) -> failWithTc (elaborate err)
-- The hi-boot file has mysteriously disappeared.
}}}}
where
need = ptext (sLit "Need the hi-boot interface for") <+> ppr mod
<+> ptext (sLit "to compare against the Real Thing")
moduleLoop = ptext (sLit "Circular imports: module") <+> quotes (ppr mod)
<+> ptext (sLit "depends on itself")
elaborate err = hang (ptext (sLit "Could not find hi-boot interface for") <+>
quotes (ppr mod) <> colon) 4 err
mkSelfBootInfo :: ModDetails -> SelfBootInfo
mkSelfBootInfo mds
= SelfBoot { sb_mds = mds
, sb_tcs = mkNameSet (map tyConName (typeEnvTyCons iface_env))
, sb_ids = mkNameSet (map idName (typeEnvIds iface_env)) }
where
iface_env = md_types mds
{-
************************************************************************
* *
Type and class declarations
* *
************************************************************************
When typechecking a data type decl, we *lazily* (via forkM) typecheck
the constructor argument types. This is in the hope that we may never
poke on those argument types, and hence may never need to load the
interface files for types mentioned in the arg types.
E.g.
data Foo.S = MkS Baz.T
Mabye we can get away without even loading the interface for Baz!
This is not just a performance thing. Suppose we have
data Foo.S = MkS Baz.T
data Baz.T = MkT Foo.S
(in different interface files, of course).
Now, first we load and typecheck Foo.S, and add it to the type envt.
If we do explore MkS's argument, we'll load and typecheck Baz.T.
If we explore MkT's argument we'll find Foo.S already in the envt.
If we typechecked constructor args eagerly, when loading Foo.S we'd try to
typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
which isn't done yet.
All very cunning. However, there is a rather subtle gotcha which bit
me when developing this stuff. When we typecheck the decl for S, we
extend the type envt with S, MkS, and all its implicit Ids. Suppose
(a bug, but it happened) that the list of implicit Ids depended in
turn on the constructor arg types. Then the following sequence of
events takes place:
* we build a thunk <t> for the constructor arg tys
* we build a thunk for the extended type environment (depends on <t>)
* we write the extended type envt into the global EPS mutvar
Now we look something up in the type envt
* that pulls on <t>
* which reads the global type envt out of the global EPS mutvar
* but that depends in turn on <t>
It's subtle, because, it'd work fine if we typechecked the constructor args
eagerly -- they don't need the extended type envt. They just get the extended
type envt by accident, because they look at it later.
What this means is that the implicitTyThings MUST NOT DEPEND on any of
the forkM stuff.
-}
tcIfaceDecl :: Bool -- True <=> discard IdInfo on IfaceId bindings
-> IfaceDecl
-> IfL TyThing
tcIfaceDecl = tc_iface_decl NoParentTyCon
tc_iface_decl :: TyConParent -- For nested declarations
-> Bool -- True <=> discard IdInfo on IfaceId bindings
-> IfaceDecl
-> IfL TyThing
tc_iface_decl _ ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type,
ifIdDetails = details, ifIdInfo = info})
= do { name <- lookupIfaceTop occ_name
; ty <- tcIfaceType iface_type
; details <- tcIdDetails ty details
; info <- tcIdInfo ignore_prags name ty info
; return (AnId (mkGlobalId details name ty info)) }
tc_iface_decl parent _ (IfaceData {ifName = occ_name,
ifCType = cType,
ifTyVars = tv_bndrs,
ifRoles = roles,
ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
ifCons = rdr_cons,
ifRec = is_rec, ifPromotable = is_prom,
ifParent = mb_parent })
= bindIfaceTyVars_AT tv_bndrs $ \ tyvars -> do
{ tc_name <- lookupIfaceTop occ_name
; tycon <- fixM $ \ tycon -> do
{ stupid_theta <- tcIfaceCtxt ctxt
; parent' <- tc_parent mb_parent
; cons <- tcIfaceDataCons tc_name tycon tyvars rdr_cons
; return (buildAlgTyCon tc_name tyvars roles cType stupid_theta
cons is_rec is_prom gadt_syn parent') }
; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
; return (ATyCon tycon) }
where
tc_parent :: IfaceTyConParent -> IfL TyConParent
tc_parent IfNoParent = return parent
tc_parent (IfDataInstance ax_name _ arg_tys)
= ASSERT( isNoParent parent )
do { ax <- tcIfaceCoAxiom ax_name
; let fam_tc = coAxiomTyCon ax
ax_unbr = toUnbranchedAxiom ax
; lhs_tys <- tcIfaceTcArgs arg_tys
; return (FamInstTyCon ax_unbr fam_tc lhs_tys) }
tc_iface_decl _ _ (IfaceSynonym {ifName = occ_name, ifTyVars = tv_bndrs,
ifRoles = roles,
ifSynRhs = rhs_ty,
ifSynKind = kind })
= bindIfaceTyVars_AT tv_bndrs $ \ tyvars -> do
{ tc_name <- lookupIfaceTop occ_name
; rhs_kind <- tcIfaceKind kind -- Note [Synonym kind loop]
; rhs <- forkM (mk_doc tc_name) $
tcIfaceType rhs_ty
; let tycon = buildSynonymTyCon tc_name tyvars roles rhs rhs_kind
; return (ATyCon tycon) }
where
mk_doc n = ptext (sLit "Type synonym") <+> ppr n
tc_iface_decl parent _ (IfaceFamily {ifName = occ_name, ifTyVars = tv_bndrs,
ifFamFlav = fam_flav,
ifFamKind = kind,
ifResVar = res, ifFamInj = inj })
= bindIfaceTyVars_AT tv_bndrs $ \ tyvars -> do
{ tc_name <- lookupIfaceTop occ_name
; rhs_kind <- tcIfaceKind kind -- Note [Synonym kind loop]
; rhs <- forkM (mk_doc tc_name) $
tc_fam_flav fam_flav
; res_name <- traverse (newIfaceName . mkTyVarOccFS) res
; let tycon = buildFamilyTyCon tc_name tyvars res_name rhs rhs_kind
parent inj
; return (ATyCon tycon) }
where
mk_doc n = ptext (sLit "Type synonym") <+> ppr n
tc_fam_flav IfaceOpenSynFamilyTyCon = return OpenSynFamilyTyCon
tc_fam_flav (IfaceClosedSynFamilyTyCon mb_ax_name_branches)
= do { ax <- traverse (tcIfaceCoAxiom . fst) mb_ax_name_branches
; return (ClosedSynFamilyTyCon ax) }
tc_fam_flav IfaceAbstractClosedSynFamilyTyCon
= return AbstractClosedSynFamilyTyCon
tc_fam_flav IfaceBuiltInSynFamTyCon
= pprPanic "tc_iface_decl"
(text "IfaceBuiltInSynFamTyCon in interface file")
tc_iface_decl _parent ignore_prags
(IfaceClass {ifCtxt = rdr_ctxt, ifName = tc_occ,
ifTyVars = tv_bndrs, ifRoles = roles, ifFDs = rdr_fds,
ifATs = rdr_ats, ifSigs = rdr_sigs,
ifMinDef = mindef_occ, ifRec = tc_isrec })
-- ToDo: in hs-boot files we should really treat abstract classes specially,
-- as we do abstract tycons
= bindIfaceTyVars tv_bndrs $ \ tyvars -> do
{ tc_name <- lookupIfaceTop tc_occ
; traceIf (text "tc-iface-class1" <+> ppr tc_occ)
; ctxt <- mapM tc_sc rdr_ctxt
; traceIf (text "tc-iface-class2" <+> ppr tc_occ)
; sigs <- mapM tc_sig rdr_sigs
; fds <- mapM tc_fd rdr_fds
; traceIf (text "tc-iface-class3" <+> ppr tc_occ)
; mindef <- traverse (lookupIfaceTop . mkVarOccFS) mindef_occ
; cls <- fixM $ \ cls -> do
{ ats <- mapM (tc_at cls) rdr_ats
; traceIf (text "tc-iface-class4" <+> ppr tc_occ)
; buildClass tc_name tyvars roles ctxt fds ats sigs mindef tc_isrec }
; return (ATyCon (classTyCon cls)) }
where
tc_sc pred = forkM (mk_sc_doc pred) (tcIfaceType pred)
-- The *length* of the superclasses is used by buildClass, and hence must
-- not be inside the thunk. But the *content* maybe recursive and hence
-- must be lazy (via forkM). Example:
-- class C (T a) => D a where
-- data T a
-- Here the associated type T is knot-tied with the class, and
-- so we must not pull on T too eagerly. See Trac #5970
tc_sig (IfaceClassOp occ dm rdr_ty)
= do { op_name <- lookupIfaceTop occ
; op_ty <- forkM (mk_op_doc op_name rdr_ty) (tcIfaceType rdr_ty)
-- Must be done lazily for just the same reason as the
-- type of a data con; to avoid sucking in types that
-- it mentions unless it's necessary to do so
; return (op_name, dm, op_ty) }
tc_at cls (IfaceAT tc_decl if_def)
= do ATyCon tc <- tc_iface_decl (AssocFamilyTyCon cls) ignore_prags tc_decl
mb_def <- case if_def of
Nothing -> return Nothing
Just def -> forkM (mk_at_doc tc) $
extendIfaceTyVarEnv (tyConTyVars tc) $
do { tc_def <- tcIfaceType def
; return (Just tc_def) }
-- Must be done lazily in case the RHS of the defaults mention
-- the type constructor being defined here
-- e.g. type AT a; type AT b = AT [b] Trac #8002
return (ATI tc mb_def)
mk_sc_doc pred = ptext (sLit "Superclass") <+> ppr pred
mk_at_doc tc = ptext (sLit "Associated type") <+> ppr tc
mk_op_doc op_name op_ty = ptext (sLit "Class op") <+> sep [ppr op_name, ppr op_ty]
tc_fd (tvs1, tvs2) = do { tvs1' <- mapM tcIfaceTyVar tvs1
; tvs2' <- mapM tcIfaceTyVar tvs2
; return (tvs1', tvs2') }
tc_iface_decl _ _ (IfaceAxiom { ifName = ax_occ, ifTyCon = tc
, ifAxBranches = branches, ifRole = role })
= do { tc_name <- lookupIfaceTop ax_occ
; tc_tycon <- tcIfaceTyCon tc
; tc_branches <- tc_ax_branches branches
; let axiom = CoAxiom { co_ax_unique = nameUnique tc_name
, co_ax_name = tc_name
, co_ax_tc = tc_tycon
, co_ax_role = role
, co_ax_branches = toBranchList tc_branches
, co_ax_implicit = False }
; return (ACoAxiom axiom) }
tc_iface_decl _ _ (IfacePatSyn{ ifName = occ_name
, ifPatMatcher = if_matcher
, ifPatBuilder = if_builder
, ifPatIsInfix = is_infix
, ifPatUnivTvs = univ_tvs
, ifPatExTvs = ex_tvs
, ifPatProvCtxt = prov_ctxt
, ifPatReqCtxt = req_ctxt
, ifPatArgs = args
, ifPatTy = pat_ty })
= do { name <- lookupIfaceTop occ_name
; traceIf (ptext (sLit "tc_iface_decl") <+> ppr name)
; matcher <- tc_pr if_matcher
; builder <- fmapMaybeM tc_pr if_builder
; bindIfaceTyVars univ_tvs $ \univ_tvs -> do
{ bindIfaceTyVars ex_tvs $ \ex_tvs -> do
{ patsyn <- forkM (mk_doc name) $
do { prov_theta <- tcIfaceCtxt prov_ctxt
; req_theta <- tcIfaceCtxt req_ctxt
; pat_ty <- tcIfaceType pat_ty
; arg_tys <- mapM tcIfaceType args
; return $ buildPatSyn name is_infix matcher builder
(univ_tvs, req_theta) (ex_tvs, prov_theta)
arg_tys pat_ty }
; return $ AConLike . PatSynCon $ patsyn }}}
where
mk_doc n = ptext (sLit "Pattern synonym") <+> ppr n
tc_pr :: (IfExtName, Bool) -> IfL (Id, Bool)
tc_pr (nm, b) = do { id <- forkM (ppr nm) (tcIfaceExtId nm)
; return (id, b) }
tc_ax_branches :: [IfaceAxBranch] -> IfL [CoAxBranch]
tc_ax_branches if_branches = foldlM tc_ax_branch [] if_branches
tc_ax_branch :: [CoAxBranch] -> IfaceAxBranch -> IfL [CoAxBranch]
tc_ax_branch prev_branches
(IfaceAxBranch { ifaxbTyVars = tv_bndrs, ifaxbLHS = lhs, ifaxbRHS = rhs
, ifaxbRoles = roles, ifaxbIncomps = incomps })
= bindIfaceTyVars_AT tv_bndrs $ \ tvs -> do
-- The _AT variant is needed here; see Note [CoAxBranch type variables] in CoAxiom
{ tc_lhs <- tcIfaceTcArgs lhs -- See Note [Checking IfaceTypes vs IfaceKinds]
; tc_rhs <- tcIfaceType rhs
; let br = CoAxBranch { cab_loc = noSrcSpan
, cab_tvs = tvs
, cab_lhs = tc_lhs
, cab_roles = roles
, cab_rhs = tc_rhs
, cab_incomps = map (prev_branches !!) incomps }
; return (prev_branches ++ [br]) }
tcIfaceDataCons :: Name -> TyCon -> [TyVar] -> IfaceConDecls -> IfL AlgTyConRhs
tcIfaceDataCons tycon_name tycon tc_tyvars if_cons
= case if_cons of
IfAbstractTyCon dis -> return (AbstractTyCon dis)
IfDataFamTyCon -> return DataFamilyTyCon
IfDataTyCon cons -> do { data_cons <- mapM tc_con_decl cons
; return (mkDataTyConRhs data_cons) }
IfNewTyCon con -> do { data_con <- tc_con_decl con
; mkNewTyConRhs tycon_name tycon data_con }
where
tc_con_decl (IfCon { ifConInfix = is_infix,
ifConExTvs = ex_tvs,
ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
ifConArgTys = args, ifConFields = field_lbls,
ifConStricts = if_stricts,
ifConSrcStricts = if_src_stricts})
= -- Universally-quantified tyvars are shared with
-- parent TyCon, and are alrady in scope
bindIfaceTyVars ex_tvs $ \ ex_tyvars -> do
{ traceIf (text "Start interface-file tc_con_decl" <+> ppr occ)
; name <- lookupIfaceTop occ
-- Read the context and argument types, but lazily for two reasons
-- (a) to avoid looking tugging on a recursive use of
-- the type itself, which is knot-tied
-- (b) to avoid faulting in the component types unless
-- they are really needed
; ~(eq_spec, theta, arg_tys, stricts) <- forkM (mk_doc name) $
do { eq_spec <- tcIfaceEqSpec spec
; theta <- tcIfaceCtxt ctxt
; arg_tys <- mapM tcIfaceType args
; stricts <- mapM tc_strict if_stricts
-- The IfBang field can mention
-- the type itself; hence inside forkM
; return (eq_spec, theta, arg_tys, stricts) }
; lbl_names <- mapM lookupIfaceTop field_lbls
-- Remember, tycon is the representation tycon
; let orig_res_ty = mkFamilyTyConApp tycon
(substTyVars (mkTopTvSubst eq_spec) tc_tyvars)
; con <- buildDataCon (pprPanic "tcIfaceDataCons: FamInstEnvs" (ppr name))
name is_infix
(map src_strict if_src_stricts)
(Just stricts)
-- Pass the HsImplBangs (i.e. final
-- decisions) to buildDataCon; it'll use
-- these to guide the construction of a
-- worker.
-- See Note [Bangs on imported data constructors] in MkId
lbl_names
tc_tyvars ex_tyvars
eq_spec theta
arg_tys orig_res_ty tycon
; traceIf (text "Done interface-file tc_con_decl" <+> ppr name)
; return con }
mk_doc con_name = ptext (sLit "Constructor") <+> ppr con_name
tc_strict :: IfaceBang -> IfL HsImplBang
tc_strict IfNoBang = return (HsLazy)
tc_strict IfStrict = return (HsStrict)
tc_strict IfUnpack = return (HsUnpack Nothing)
tc_strict (IfUnpackCo if_co) = do { co <- tcIfaceCo if_co
; return (HsUnpack (Just co)) }
src_strict :: IfaceSrcBang -> HsSrcBang
src_strict (IfSrcBang unpk bang) = HsSrcBang Nothing unpk bang
tcIfaceEqSpec :: IfaceEqSpec -> IfL [(TyVar, Type)]
tcIfaceEqSpec spec
= mapM do_item spec
where
do_item (occ, if_ty) = do { tv <- tcIfaceTyVar occ
; ty <- tcIfaceType if_ty
; return (tv,ty) }
{-
Note [Synonym kind loop]
~~~~~~~~~~~~~~~~~~~~~~~~
Notice that we eagerly grab the *kind* from the interface file, but
build a forkM thunk for the *rhs* (and family stuff). To see why,
consider this (Trac #2412)
M.hs: module M where { import X; data T = MkT S }
X.hs: module X where { import {-# SOURCE #-} M; type S = T }
M.hs-boot: module M where { data T }
When kind-checking M.hs we need S's kind. But we do not want to
find S's kind from (typeKind S-rhs), because we don't want to look at
S-rhs yet! Since S is imported from X.hi, S gets just one chance to
be defined, and we must not do that until we've finished with M.T.
Solution: record S's kind in the interface file; now we can safely
look at it.
************************************************************************
* *
Instances
* *
************************************************************************
-}
tcIfaceInst :: IfaceClsInst -> IfL ClsInst
tcIfaceInst (IfaceClsInst { ifDFun = dfun_occ, ifOFlag = oflag
, ifInstCls = cls, ifInstTys = mb_tcs
, ifInstOrph = orph })
= do { dfun <- forkM (ptext (sLit "Dict fun") <+> ppr dfun_occ) $
tcIfaceExtId dfun_occ
; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
; return (mkImportedInstance cls mb_tcs' dfun oflag orph) }
tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
tcIfaceFamInst (IfaceFamInst { ifFamInstFam = fam, ifFamInstTys = mb_tcs
, ifFamInstAxiom = axiom_name } )
= do { axiom' <- forkM (ptext (sLit "Axiom") <+> ppr axiom_name) $
tcIfaceCoAxiom axiom_name
-- will panic if branched, but that's OK
; let axiom'' = toUnbranchedAxiom axiom'
mb_tcs' = map (fmap ifaceTyConName) mb_tcs
; return (mkImportedFamInst fam mb_tcs' axiom'') }
{-
************************************************************************
* *
Rules
* *
************************************************************************
We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
are in the type environment. However, remember that typechecking a Rule may
(as a side effect) augment the type envt, and so we may need to iterate the process.
-}
tcIfaceRules :: Bool -- True <=> ignore rules
-> [IfaceRule]
-> IfL [CoreRule]
tcIfaceRules ignore_prags if_rules
| ignore_prags = return []
| otherwise = mapM tcIfaceRule if_rules
tcIfaceRule :: IfaceRule -> IfL CoreRule
tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
ifRuleAuto = auto, ifRuleOrph = orph })
= do { ~(bndrs', args', rhs') <-
-- Typecheck the payload lazily, in the hope it'll never be looked at
forkM (ptext (sLit "Rule") <+> pprRuleName name) $
bindIfaceBndrs bndrs $ \ bndrs' ->
do { args' <- mapM tcIfaceExpr args
; rhs' <- tcIfaceExpr rhs
; return (bndrs', args', rhs') }
; let mb_tcs = map ifTopFreeName args
; this_mod <- getIfModule
; return (Rule { ru_name = name, ru_fn = fn, ru_act = act,
ru_bndrs = bndrs', ru_args = args',
ru_rhs = occurAnalyseExpr rhs',
ru_rough = mb_tcs,
ru_origin = this_mod,
ru_orphan = orph,
ru_auto = auto,
ru_local = False }) } -- An imported RULE is never for a local Id
-- or, even if it is (module loop, perhaps)
-- we'll just leave it in the non-local set
where
-- This function *must* mirror exactly what Rules.roughTopNames does
-- We could have stored the ru_rough field in the iface file
-- but that would be redundant, I think.
-- The only wrinkle is that we must not be deceived by
-- type synonyms at the top of a type arg. Since
-- we can't tell at this point, we are careful not
-- to write them out in coreRuleToIfaceRule
ifTopFreeName :: IfaceExpr -> Maybe Name
ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
ifTopFreeName (IfaceType (IfaceTupleTy s _ ts)) = Just (tupleTyConName s (length (tcArgsIfaceTypes ts)))
ifTopFreeName (IfaceApp f _) = ifTopFreeName f
ifTopFreeName (IfaceExt n) = Just n
ifTopFreeName _ = Nothing
{-
************************************************************************
* *
Annotations
* *
************************************************************************
-}
tcIfaceAnnotations :: [IfaceAnnotation] -> IfL [Annotation]
tcIfaceAnnotations = mapM tcIfaceAnnotation
tcIfaceAnnotation :: IfaceAnnotation -> IfL Annotation
tcIfaceAnnotation (IfaceAnnotation target serialized) = do
target' <- tcIfaceAnnTarget target
return $ Annotation {
ann_target = target',
ann_value = serialized
}
tcIfaceAnnTarget :: IfaceAnnTarget -> IfL (AnnTarget Name)
tcIfaceAnnTarget (NamedTarget occ) = do
name <- lookupIfaceTop occ
return $ NamedTarget name
tcIfaceAnnTarget (ModuleTarget mod) = do
return $ ModuleTarget mod
{-
************************************************************************
* *
Vectorisation information
* *
************************************************************************
-}
-- We need access to the type environment as we need to look up information about type constructors
-- (i.e., their data constructors and whether they are class type constructors). If a vectorised
-- type constructor or class is defined in the same module as where it is vectorised, we cannot
-- look that information up from the type constructor that we obtained via a 'forkM'ed
-- 'tcIfaceTyCon' without recursively loading the interface that we are already type checking again
-- and again and again...
--
tcIfaceVectInfo :: Module -> TypeEnv -> IfaceVectInfo -> IfL VectInfo
tcIfaceVectInfo mod typeEnv (IfaceVectInfo
{ ifaceVectInfoVar = vars
, ifaceVectInfoTyCon = tycons
, ifaceVectInfoTyConReuse = tyconsReuse
, ifaceVectInfoParallelVars = parallelVars
, ifaceVectInfoParallelTyCons = parallelTyCons
})
= do { let parallelTyConsSet = mkNameSet parallelTyCons
; vVars <- mapM vectVarMapping vars
; let varsSet = mkVarSet (map fst vVars)
; tyConRes1 <- mapM (vectTyConVectMapping varsSet) tycons
; tyConRes2 <- mapM (vectTyConReuseMapping varsSet) tyconsReuse
; vParallelVars <- mapM vectVar parallelVars
; let (vTyCons, vDataCons, vScSels) = unzip3 (tyConRes1 ++ tyConRes2)
; return $ VectInfo
{ vectInfoVar = mkVarEnv vVars `extendVarEnvList` concat vScSels
, vectInfoTyCon = mkNameEnv vTyCons
, vectInfoDataCon = mkNameEnv (concat vDataCons)
, vectInfoParallelVars = mkVarSet vParallelVars
, vectInfoParallelTyCons = parallelTyConsSet
}
}
where
vectVarMapping name
= do { vName <- lookupIfaceTop (mkLocalisedOccName mod mkVectOcc name)
; var <- forkM (ptext (sLit "vect var") <+> ppr name) $
tcIfaceExtId name
; vVar <- forkM (ptext (sLit "vect vVar [mod =") <+>
ppr mod <> ptext (sLit "; nameModule =") <+>
ppr (nameModule name) <> ptext (sLit "]") <+> ppr vName) $
tcIfaceExtId vName
; return (var, (var, vVar))
}
-- where
-- lookupLocalOrExternalId name
-- = do { let mb_id = lookupTypeEnv typeEnv name
-- ; case mb_id of
-- -- id is local
-- Just (AnId id) -> return id
-- -- name is not an Id => internal inconsistency
-- Just _ -> notAnIdErr
-- -- Id is external
-- Nothing -> tcIfaceExtId name
-- }
--
-- notAnIdErr = pprPanic "TcIface.tcIfaceVectInfo: not an id" (ppr name)
vectVar name
= forkM (ptext (sLit "vect scalar var") <+> ppr name) $
tcIfaceExtId name
vectTyConVectMapping vars name
= do { vName <- lookupIfaceTop (mkLocalisedOccName mod mkVectTyConOcc name)
; vectTyConMapping vars name vName
}
vectTyConReuseMapping vars name
= vectTyConMapping vars name name
vectTyConMapping vars name vName
= do { tycon <- lookupLocalOrExternalTyCon name
; vTycon <- forkM (ptext (sLit "vTycon of") <+> ppr vName) $
lookupLocalOrExternalTyCon vName
-- Map the data constructors of the original type constructor to those of the
-- vectorised type constructor /unless/ the type constructor was vectorised
-- abstractly; if it was vectorised abstractly, the workers of its data constructors
-- do not appear in the set of vectorised variables.
--
-- NB: This is lazy! We don't pull at the type constructors before we actually use
-- the data constructor mapping.
; let isAbstract | isClassTyCon tycon = False
| datacon:_ <- tyConDataCons tycon
= not $ dataConWrapId datacon `elemVarSet` vars
| otherwise = True
vDataCons | isAbstract = []
| otherwise = [ (dataConName datacon, (datacon, vDatacon))
| (datacon, vDatacon) <- zip (tyConDataCons tycon)
(tyConDataCons vTycon)
]
-- Map the (implicit) superclass and methods selectors as they don't occur in
-- the var map.
vScSels | Just cls <- tyConClass_maybe tycon
, Just vCls <- tyConClass_maybe vTycon
= [ (sel, (sel, vSel))
| (sel, vSel) <- zip (classAllSelIds cls) (classAllSelIds vCls)
]
| otherwise
= []
; return ( (name, (tycon, vTycon)) -- (T, T_v)
, vDataCons -- list of (Ci, Ci_v)
, vScSels -- list of (seli, seli_v)
)
}
where
-- we need a fully defined version of the type constructor to be able to extract
-- its data constructors etc.
lookupLocalOrExternalTyCon name
= do { let mb_tycon = lookupTypeEnv typeEnv name
; case mb_tycon of
-- tycon is local
Just (ATyCon tycon) -> return tycon
-- name is not a tycon => internal inconsistency
Just _ -> notATyConErr
-- tycon is external
Nothing -> tcIfaceTyConByName name
}
notATyConErr = pprPanic "TcIface.tcIfaceVectInfo: not a tycon" (ppr name)
{-
************************************************************************
* *
Types
* *
************************************************************************
-}
tcIfaceType :: IfaceType -> IfL Type
tcIfaceType (IfaceTyVar n) = do { tv <- tcIfaceTyVar n; return (TyVarTy tv) }
tcIfaceType (IfaceAppTy t1 t2) = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (AppTy t1' t2') }
tcIfaceType (IfaceLitTy l) = do { l1 <- tcIfaceTyLit l; return (LitTy l1) }
tcIfaceType (IfaceFunTy t1 t2) = tcIfaceTypeFun t1 t2
tcIfaceType (IfaceDFunTy t1 t2) = tcIfaceTypeFun t1 t2
tcIfaceType (IfaceTupleTy s i tks) = tcIfaceTupleTy s i tks
tcIfaceType (IfaceTyConApp tc tks) = do { tc' <- tcIfaceTyCon tc
; tks' <- tcIfaceTcArgs tks
; return (mkTyConApp tc' tks') }
tcIfaceType (IfaceForAllTy tv t) = bindIfaceTyVar tv $ \ tv' -> do { t' <- tcIfaceType t; return (ForAllTy tv' t') }
tcIfaceTypeFun :: IfaceType -> IfaceType -> IfL Type
tcIfaceTypeFun t1 t2 = do { t1' <- tcIfaceType t1; t2' <- tcIfaceType t2; return (FunTy t1' t2') }
tcIfaceKind :: IfaceKind -> IfL Type
tcIfaceKind (IfaceAppTy t1 t2) = do { t1' <- tcIfaceKind t1; t2' <- tcIfaceKind t2; return (AppTy t1' t2') }
tcIfaceKind (IfaceFunTy t1 t2) = tcIfaceKindFun t1 t2
tcIfaceKind (IfaceDFunTy t1 t2) = tcIfaceKindFun t1 t2
tcIfaceKind (IfaceLitTy l) = pprPanic "tcIfaceKind" (ppr l)
tcIfaceKind k = tcIfaceType k
tcIfaceKindFun :: IfaceKind -> IfaceKind -> IfL Type
tcIfaceKindFun t1 t2 = do { t1' <- tcIfaceKind t1; t2' <- tcIfaceKind t2; return (FunTy t1' t2') }
tcIfaceTupleTy :: TupleSort -> IfaceTyConInfo -> IfaceTcArgs -> IfL Type
tcIfaceTupleTy sort info args
= do { args' <- tcIfaceTcArgs args
; let arity = length args'
; base_tc <- tcTupleTyCon sort arity
; case info of
NoIfaceTyConInfo
-> return (mkTyConApp base_tc args')
IfacePromotedTyCon
| Just tc <- promotableTyCon_maybe base_tc
-> return (mkTyConApp tc args')
| otherwise
-> panic "tcIfaceTupleTy" (ppr base_tc)
IfacePromotedDataCon
-> do { let tc = promoteDataCon (tyConSingleDataCon base_tc)
kind_args = map typeKind args'
; return (mkTyConApp tc (kind_args ++ args')) } }
tcTupleTyCon :: TupleSort -> Arity -> IfL TyCon
tcTupleTyCon sort arity
= case sort of
ConstraintTuple -> do { thing <- tcIfaceGlobal (cTupleTyConName arity)
; return (tyThingTyCon thing) }
BoxedTuple -> return (tupleTyCon Boxed arity)
UnboxedTuple -> return (tupleTyCon Unboxed arity)
tcIfaceTcArgs :: IfaceTcArgs -> IfL [Type]
tcIfaceTcArgs args
= case args of
ITC_Type t ts ->
do { t' <- tcIfaceType t
; ts' <- tcIfaceTcArgs ts
; return (t':ts') }
ITC_Kind k ks ->
do { k' <- tcIfaceKind k
; ks' <- tcIfaceTcArgs ks
; return (k':ks') }
ITC_Nil -> return []
-----------------------------------------
tcIfaceCtxt :: IfaceContext -> IfL ThetaType
tcIfaceCtxt sts = mapM tcIfaceType sts
-----------------------------------------
tcIfaceTyLit :: IfaceTyLit -> IfL TyLit
tcIfaceTyLit (IfaceNumTyLit n) = return (NumTyLit n)
tcIfaceTyLit (IfaceStrTyLit n) = return (StrTyLit n)
{-
************************************************************************
* *
Coercions
* *
************************************************************************
-}
tcIfaceCo :: IfaceCoercion -> IfL Coercion
tcIfaceCo (IfaceReflCo r t) = mkReflCo r <$> tcIfaceType t
tcIfaceCo (IfaceFunCo r c1 c2) = mkFunCo r <$> tcIfaceCo c1 <*> tcIfaceCo c2
tcIfaceCo (IfaceTyConAppCo r tc cs) = mkTyConAppCo r <$> tcIfaceTyCon tc
<*> mapM tcIfaceCo cs
tcIfaceCo (IfaceAppCo c1 c2) = mkAppCo <$> tcIfaceCo c1
<*> tcIfaceCo c2
tcIfaceCo (IfaceForAllCo tv c) = bindIfaceTyVar tv $ \ tv' ->
mkForAllCo tv' <$> tcIfaceCo c
tcIfaceCo (IfaceCoVarCo n) = mkCoVarCo <$> tcIfaceCoVar n
tcIfaceCo (IfaceAxiomInstCo n i cs) = AxiomInstCo <$> tcIfaceCoAxiom n
<*> pure i
<*> mapM tcIfaceCo cs
tcIfaceCo (IfaceUnivCo s r t1 t2) = UnivCo s r <$> tcIfaceType t1
<*> tcIfaceType t2
tcIfaceCo (IfaceSymCo c) = SymCo <$> tcIfaceCo c
tcIfaceCo (IfaceTransCo c1 c2) = TransCo <$> tcIfaceCo c1
<*> tcIfaceCo c2
tcIfaceCo (IfaceInstCo c1 t2) = InstCo <$> tcIfaceCo c1
<*> tcIfaceType t2
tcIfaceCo (IfaceNthCo d c) = NthCo d <$> tcIfaceCo c
tcIfaceCo (IfaceLRCo lr c) = LRCo lr <$> tcIfaceCo c
tcIfaceCo (IfaceSubCo c) = SubCo <$> tcIfaceCo c
tcIfaceCo (IfaceAxiomRuleCo ax tys cos) = AxiomRuleCo
<$> tcIfaceCoAxiomRule ax
<*> mapM tcIfaceType tys
<*> mapM tcIfaceCo cos
tcIfaceCoVar :: FastString -> IfL CoVar
tcIfaceCoVar = tcIfaceLclId
tcIfaceCoAxiomRule :: FastString -> IfL CoAxiomRule
tcIfaceCoAxiomRule n =
case Map.lookup n typeNatCoAxiomRules of
Just ax -> return ax
_ -> pprPanic "tcIfaceCoAxiomRule" (ppr n)
{-
************************************************************************
* *
Core
* *
************************************************************************
-}
tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
tcIfaceExpr (IfaceType ty)
= Type <$> tcIfaceType ty
tcIfaceExpr (IfaceCo co)
= Coercion <$> tcIfaceCo co
tcIfaceExpr (IfaceCast expr co)
= Cast <$> tcIfaceExpr expr <*> tcIfaceCo co
tcIfaceExpr (IfaceLcl name)
= Var <$> tcIfaceLclId name
tcIfaceExpr (IfaceExt gbl)
= Var <$> tcIfaceExtId gbl
tcIfaceExpr (IfaceLit lit)
= do lit' <- tcIfaceLit lit
return (Lit lit')
tcIfaceExpr (IfaceFCall cc ty) = do
ty' <- tcIfaceType ty
u <- newUnique
dflags <- getDynFlags
return (Var (mkFCallId dflags u cc ty'))
tcIfaceExpr (IfaceTuple sort args)
= do { args' <- mapM tcIfaceExpr args
; tc <- tcTupleTyCon sort arity
; let con_args = map (Type . exprType) args' ++ args'
-- Put the missing type arguments back in
con_id = dataConWorkId (tyConSingleDataCon tc)
; return (mkApps (Var con_id) con_args) }
where
arity = length args
tcIfaceExpr (IfaceLam (bndr, os) body)
= bindIfaceBndr bndr $ \bndr' ->
Lam (tcIfaceOneShot os bndr') <$> tcIfaceExpr body
where
tcIfaceOneShot IfaceOneShot b = setOneShotLambda b
tcIfaceOneShot _ b = b
tcIfaceExpr (IfaceApp fun arg)
= tcIfaceApps fun arg
tcIfaceExpr (IfaceECase scrut ty)
= do { scrut' <- tcIfaceExpr scrut
; ty' <- tcIfaceType ty
; return (castBottomExpr scrut' ty') }
tcIfaceExpr (IfaceCase scrut case_bndr alts) = do
scrut' <- tcIfaceExpr scrut
case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
let
scrut_ty = exprType scrut'
case_bndr' = mkLocalId case_bndr_name scrut_ty
tc_app = splitTyConApp scrut_ty
-- NB: Won't always succeed (polymorphic case)
-- but won't be demanded in those cases
-- NB: not tcSplitTyConApp; we are looking at Core here
-- look through non-rec newtypes to find the tycon that
-- corresponds to the datacon in this case alternative
extendIfaceIdEnv [case_bndr'] $ do
alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
return (Case scrut' case_bndr' (coreAltsType alts') alts')
tcIfaceExpr (IfaceLet (IfaceNonRec (IfLetBndr fs ty info) rhs) body)
= do { name <- newIfaceName (mkVarOccFS fs)
; ty' <- tcIfaceType ty
; id_info <- tcIdInfo False {- Don't ignore prags; we are inside one! -}
name ty' info
; let id = mkLocalIdWithInfo name ty' id_info
; rhs' <- tcIfaceExpr rhs
; body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
; return (Let (NonRec id rhs') body') }
tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
= do { ids <- mapM tc_rec_bndr (map fst pairs)
; extendIfaceIdEnv ids $ do
{ pairs' <- zipWithM tc_pair pairs ids
; body' <- tcIfaceExpr body
; return (Let (Rec pairs') body') } }
where
tc_rec_bndr (IfLetBndr fs ty _)
= do { name <- newIfaceName (mkVarOccFS fs)
; ty' <- tcIfaceType ty
; return (mkLocalId name ty') }
tc_pair (IfLetBndr _ _ info, rhs) id
= do { rhs' <- tcIfaceExpr rhs
; id_info <- tcIdInfo False {- Don't ignore prags; we are inside one! -}
(idName id) (idType id) info
; return (setIdInfo id id_info, rhs') }
tcIfaceExpr (IfaceTick tickish expr) = do
expr' <- tcIfaceExpr expr
-- If debug flag is not set: Ignore source notes
dbgFlag <- fmap (gopt Opt_Debug) getDynFlags
case tickish of
IfaceSource{} | not dbgFlag
-> return expr'
_otherwise -> do
tickish' <- tcIfaceTickish tickish
return (Tick tickish' expr')
-------------------------
tcIfaceApps :: IfaceExpr -> IfaceExpr -> IfL CoreExpr
-- See Note [Checking IfaceTypes vs IfaceKinds]
tcIfaceApps fun arg
= go_down fun [arg]
where
go_down (IfaceApp fun arg) args = go_down fun (arg:args)
go_down fun args = do { fun' <- tcIfaceExpr fun
; go_up fun' (exprType fun') args }
go_up :: CoreExpr -> Type -> [IfaceExpr] -> IfL CoreExpr
go_up fun _ [] = return fun
go_up fun fun_ty (IfaceType t : args)
| Just (tv,body_ty) <- splitForAllTy_maybe fun_ty
= do { t' <- if isKindVar tv
then tcIfaceKind t
else tcIfaceType t
; let fun_ty' = substTyWith [tv] [t'] body_ty
; go_up (App fun (Type t')) fun_ty' args }
go_up fun fun_ty (arg : args)
| Just (_, fun_ty') <- splitFunTy_maybe fun_ty
= do { arg' <- tcIfaceExpr arg
; go_up (App fun arg') fun_ty' args }
go_up fun fun_ty args = pprPanic "tcIfaceApps" (ppr fun $$ ppr fun_ty $$ ppr args)
-------------------------
tcIfaceTickish :: IfaceTickish -> IfM lcl (Tickish Id)
tcIfaceTickish (IfaceHpcTick modl ix) = return (HpcTick modl ix)
tcIfaceTickish (IfaceSCC cc tick push) = return (ProfNote cc tick push)
tcIfaceTickish (IfaceSource src name) = return (SourceNote src name)
-------------------------
tcIfaceLit :: Literal -> IfL Literal
-- Integer literals deserialise to (LitInteger i <error thunk>)
-- so tcIfaceLit just fills in the type.
-- See Note [Integer literals] in Literal
tcIfaceLit (LitInteger i _)
= do t <- tcIfaceTyConByName integerTyConName
return (mkLitInteger i (mkTyConTy t))
tcIfaceLit lit = return lit
-------------------------
tcIfaceAlt :: CoreExpr -> (TyCon, [Type])
-> (IfaceConAlt, [FastString], IfaceExpr)
-> IfL (AltCon, [TyVar], CoreExpr)
tcIfaceAlt _ _ (IfaceDefault, names, rhs)
= ASSERT( null names ) do
rhs' <- tcIfaceExpr rhs
return (DEFAULT, [], rhs')
tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
= ASSERT( null names ) do
lit' <- tcIfaceLit lit
rhs' <- tcIfaceExpr rhs
return (LitAlt lit', [], rhs')
-- A case alternative is made quite a bit more complicated
-- by the fact that we omit type annotations because we can
-- work them out. True enough, but its not that easy!
tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
= do { con <- tcIfaceDataCon data_occ
; when (debugIsOn && not (con `elem` tyConDataCons tycon))
(failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
; tcIfaceDataAlt con inst_tys arg_strs rhs }
tcIfaceDataAlt :: DataCon -> [Type] -> [FastString] -> IfaceExpr
-> IfL (AltCon, [TyVar], CoreExpr)
tcIfaceDataAlt con inst_tys arg_strs rhs
= do { us <- newUniqueSupply
; let uniqs = uniqsFromSupply us
; let (ex_tvs, arg_ids)
= dataConRepFSInstPat arg_strs uniqs con inst_tys
; rhs' <- extendIfaceTyVarEnv ex_tvs $
extendIfaceIdEnv arg_ids $
tcIfaceExpr rhs
; return (DataAlt con, ex_tvs ++ arg_ids, rhs') }
{-
************************************************************************
* *
IdInfo
* *
************************************************************************
-}
tcIdDetails :: Type -> IfaceIdDetails -> IfL IdDetails
tcIdDetails _ IfVanillaId = return VanillaId
tcIdDetails ty IfDFunId
= return (DFunId (isNewTyCon (classTyCon cls)))
where
(_, _, cls, _) = tcSplitDFunTy ty
tcIdDetails _ (IfRecSelId tc naughty)
= do { tc' <- tcIfaceTyCon tc
; return (RecSelId { sel_tycon = tc', sel_naughty = naughty }) }
tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
tcIdInfo ignore_prags name ty info
| ignore_prags = return vanillaIdInfo
| otherwise = case info of
NoInfo -> return vanillaIdInfo
HasInfo info -> foldlM tcPrag init_info info
where
-- Set the CgInfo to something sensible but uninformative before
-- we start; default assumption is that it has CAFs
init_info = vanillaIdInfo
tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo
tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs)
tcPrag info (HsArity arity) = return (info `setArityInfo` arity)
tcPrag info (HsStrictness str) = return (info `setStrictnessInfo` str)
tcPrag info (HsInline prag) = return (info `setInlinePragInfo` prag)
-- The next two are lazy, so they don't transitively suck stuff in
tcPrag info (HsUnfold lb if_unf)
= do { unf <- tcUnfolding name ty info if_unf
; let info1 | lb = info `setOccInfo` strongLoopBreaker
| otherwise = info
; return (info1 `setUnfoldingInfoLazily` unf) }
tcUnfolding :: Name -> Type -> IdInfo -> IfaceUnfolding -> IfL Unfolding
tcUnfolding name _ info (IfCoreUnfold stable if_expr)
= do { dflags <- getDynFlags
; mb_expr <- tcPragExpr name if_expr
; let unf_src | stable = InlineStable
| otherwise = InlineRhs
; return $ case mb_expr of
Nothing -> NoUnfolding
Just expr -> mkUnfolding dflags unf_src
True {- Top level -}
(isBottomingSig strict_sig)
expr
}
where
-- Strictness should occur before unfolding!
strict_sig = strictnessInfo info
tcUnfolding name _ _ (IfCompulsory if_expr)
= do { mb_expr <- tcPragExpr name if_expr
; return (case mb_expr of
Nothing -> NoUnfolding
Just expr -> mkCompulsoryUnfolding expr) }
tcUnfolding name _ _ (IfInlineRule arity unsat_ok boring_ok if_expr)
= do { mb_expr <- tcPragExpr name if_expr
; return (case mb_expr of
Nothing -> NoUnfolding
Just expr -> mkCoreUnfolding InlineStable True expr guidance )}
where
guidance = UnfWhen { ug_arity = arity, ug_unsat_ok = unsat_ok, ug_boring_ok = boring_ok }
tcUnfolding name dfun_ty _ (IfDFunUnfold bs ops)
= bindIfaceBndrs bs $ \ bs' ->
do { mb_ops1 <- forkM_maybe doc $ mapM tcIfaceExpr ops
; return (case mb_ops1 of
Nothing -> noUnfolding
Just ops1 -> mkDFunUnfolding bs' (classDataCon cls) ops1) }
where
doc = text "Class ops for dfun" <+> ppr name
(_, _, cls, _) = tcSplitDFunTy dfun_ty
{-
For unfoldings we try to do the job lazily, so that we never type check
an unfolding that isn't going to be looked at.
-}
tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
tcPragExpr name expr
= forkM_maybe doc $ do
core_expr' <- tcIfaceExpr expr
-- Check for type consistency in the unfolding
whenGOptM Opt_DoCoreLinting $ do
in_scope <- get_in_scope
dflags <- getDynFlags
case lintUnfolding dflags noSrcLoc in_scope core_expr' of
Nothing -> return ()
Just fail_msg -> do { mod <- getIfModule
; pprPanic "Iface Lint failure"
(vcat [ ptext (sLit "In interface for") <+> ppr mod
, hang doc 2 fail_msg
, ppr name <+> equals <+> ppr core_expr'
, ptext (sLit "Iface expr =") <+> ppr expr ]) }
return core_expr'
where
doc = text "Unfolding of" <+> ppr name
get_in_scope :: IfL [Var] -- Totally disgusting; but just for linting
get_in_scope
= do { (gbl_env, lcl_env) <- getEnvs
; rec_ids <- case if_rec_types gbl_env of
Nothing -> return []
Just (_, get_env) -> do
{ type_env <- setLclEnv () get_env
; return (typeEnvIds type_env) }
; return (varEnvElts (if_tv_env lcl_env) ++
varEnvElts (if_id_env lcl_env) ++
rec_ids) }
{-
************************************************************************
* *
Getting from Names to TyThings
* *
************************************************************************
-}
tcIfaceGlobal :: Name -> IfL TyThing
tcIfaceGlobal name
| Just thing <- wiredInNameTyThing_maybe name
-- Wired-in things include TyCons, DataCons, and Ids
-- Even though we are in an interface file, we want to make
-- sure the instances and RULES of this thing (particularly TyCon) are loaded
-- Imagine: f :: Double -> Double
= do { ifCheckWiredInThing thing; return thing }
| otherwise
= do { env <- getGblEnv
; case if_rec_types env of { -- Note [Tying the knot]
Just (mod, get_type_env)
| nameIsLocalOrFrom mod name
-> do -- It's defined in the module being compiled
{ type_env <- setLclEnv () get_type_env -- yuk
; case lookupNameEnv type_env name of
Just thing -> return thing
Nothing -> pprPanic "tcIfaceGlobal (local): not found:"
(ppr name $$ ppr type_env) }
; _ -> do
{ hsc_env <- getTopEnv
; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
; case mb_thing of {
Just thing -> return thing ;
Nothing -> do
{ mb_thing <- importDecl name -- It's imported; go get it
; case mb_thing of
Failed err -> failIfM err
Succeeded thing -> return thing
}}}}}
-- Note [Tying the knot]
-- ~~~~~~~~~~~~~~~~~~~~~
-- The if_rec_types field is used in two situations:
--
-- a) Compiling M.hs, which indiretly imports Foo.hi, which mentions M.T
-- Then we look up M.T in M's type environment, which is splatted into if_rec_types
-- after we've built M's type envt.
--
-- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
-- is up to date. So we call typecheckIface on M.hi. This splats M.T into
-- if_rec_types so that the (lazily typechecked) decls see all the other decls
--
-- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
-- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
-- emasculated form (e.g. lacking data constructors).
tcIfaceTyConByName :: IfExtName -> IfL TyCon
tcIfaceTyConByName name
= do { thing <- tcIfaceGlobal name
; return (tyThingTyCon thing) }
tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
tcIfaceTyCon (IfaceTyCon name info)
= do { thing <- tcIfaceGlobal name
; case info of
NoIfaceTyConInfo -> return (tyThingTyCon thing)
IfacePromotedDataCon -> return (promoteDataCon (tyThingDataCon thing))
-- Same Name as its underlying DataCon
IfacePromotedTyCon -> return (promote_tc (tyThingTyCon thing)) }
-- Same Name as its underlying TyCon
where
promote_tc tc
| Just prom_tc <- promotableTyCon_maybe tc = prom_tc
| isSuperKind (tyConKind tc) = tc
| otherwise = pprPanic "tcIfaceTyCon" (ppr name $$ ppr tc)
tcIfaceCoAxiom :: Name -> IfL (CoAxiom Branched)
tcIfaceCoAxiom name = do { thing <- tcIfaceGlobal name
; return (tyThingCoAxiom thing) }
tcIfaceDataCon :: Name -> IfL DataCon
tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
; case thing of
AConLike (RealDataCon dc) -> return dc
_ -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
tcIfaceExtId :: Name -> IfL Id
tcIfaceExtId name = do { thing <- tcIfaceGlobal name
; case thing of
AnId id -> return id
_ -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
{-
************************************************************************
* *
Bindings
* *
************************************************************************
-}
bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
bindIfaceBndr (IfaceIdBndr (fs, ty)) thing_inside
= do { name <- newIfaceName (mkVarOccFS fs)
; ty' <- tcIfaceType ty
; let id = mkLocalId name ty'
; extendIfaceIdEnv [id] (thing_inside id) }
bindIfaceBndr (IfaceTvBndr bndr) thing_inside
= bindIfaceTyVar bndr thing_inside
bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
bindIfaceBndrs [] thing_inside = thing_inside []
bindIfaceBndrs (b:bs) thing_inside
= bindIfaceBndr b $ \ b' ->
bindIfaceBndrs bs $ \ bs' ->
thing_inside (b':bs')
-----------------------
bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
bindIfaceTyVar (occ,kind) thing_inside
= do { name <- newIfaceName (mkTyVarOccFS occ)
; tyvar <- mk_iface_tyvar name kind
; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
bindIfaceTyVars bndrs thing_inside
= do { names <- newIfaceNames (map mkTyVarOccFS occs)
; let (kis_kind, tys_kind) = span isSuperIfaceKind kinds
(kis_name, tys_name) = splitAt (length kis_kind) names
-- We need to bring the kind variables in scope since type
-- variables may mention them.
; kvs <- zipWithM mk_iface_tyvar kis_name kis_kind
; extendIfaceTyVarEnv kvs $ do
{ tvs <- zipWithM mk_iface_tyvar tys_name tys_kind
; extendIfaceTyVarEnv tvs (thing_inside (kvs ++ tvs)) } }
where
(occs,kinds) = unzip bndrs
isSuperIfaceKind :: IfaceKind -> Bool
isSuperIfaceKind (IfaceTyConApp tc ITC_Nil) = ifaceTyConName tc == superKindTyConName
isSuperIfaceKind _ = False
mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
mk_iface_tyvar name ifKind
= do { kind <- tcIfaceKind ifKind
; return (Var.mkTyVar name kind) }
bindIfaceTyVars_AT :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
-- Used for type variable in nested associated data/type declarations
-- where some of the type variables are already in scope
-- class C a where { data T a b }
-- Here 'a' is in scope when we look at the 'data T'
bindIfaceTyVars_AT [] thing_inside
= thing_inside []
bindIfaceTyVars_AT (b@(tv_occ,_) : bs) thing_inside
= do { mb_tv <- lookupIfaceTyVar tv_occ
; let bind_b :: (TyVar -> IfL a) -> IfL a
bind_b = case mb_tv of
Just b' -> \k -> k b'
Nothing -> bindIfaceTyVar b
; bind_b $ \b' ->
bindIfaceTyVars_AT bs $ \bs' ->
thing_inside (b':bs') }
| wxwxwwxxx/ghc | compiler/iface/TcIface.hs | bsd-3-clause | 63,828 | 879 | 49 | 22,069 | 9,262 | 5,593 | 3,669 | -1 | -1 |
{-# LANGUAGE FlexibleContexts, ParallelListComp #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
module Validate (Similar(..), validate, validate') where
import Data.Int
import Data.Word
import Data.Array.IArray
import Foreign.C.Types
import Foreign.Storable
import Control.Exception (assert)
import Unsafe.Coerce
class Similar a where
sim :: a -> a -> Bool
instance Similar Int where sim = (==)
instance Similar Int8 where sim = (==)
instance Similar Int16 where sim = (==)
instance Similar Int32 where sim = (==)
instance Similar Int64 where sim = (==)
instance Similar Word where sim = (==)
instance Similar Word8 where sim = (==)
instance Similar Word16 where sim = (==)
instance Similar Word32 where sim = (==)
instance Similar Word64 where sim = (==)
instance Similar CShort where sim = (==)
instance Similar CUShort where sim = (==)
instance Similar CInt where sim = (==)
instance Similar CUInt where sim = (==)
instance Similar CLong where sim = (==)
instance Similar CULong where sim = (==)
instance Similar CLLong where sim = (==)
instance Similar CULLong where sim = (==)
instance Similar Bool where sim = (==)
instance Similar Char where sim = (==)
instance Similar CChar where sim = (==)
instance Similar CSChar where sim = (==)
instance Similar CUChar where sim = (==)
instance Similar Float where sim = absoluteOrRelative
instance Similar CFloat where sim = absoluteOrRelative
instance Similar Double where sim = absoluteOrRelative
instance Similar CDouble where sim = absoluteOrRelative
instance (Similar a, Similar b) => Similar (a,b) where
(x,y) `sim` (u,v) = x `sim` u && y `sim` v
--
-- http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
--
absoluteOrRelative :: (Fractional a, Ord a) => a -> a -> Bool
absoluteOrRelative u v
| abs (u-v) < epsilonAbs = True
| abs u > abs v = abs ((u-v) / u) < epsilonRel
| otherwise = abs ((v-u) / v) < epsilonRel
where
epsilonRel = 0.001
epsilonAbs = 0.00001
-- Comparisons using lexicographically ordered floating-point numbers
-- reinterpreted as twos-complement integers.
--
lexicographic32 :: (Num a, Storable a) => Int -> a -> a -> Bool
lexicographic32 maxUlps a b
= assert (sizeOf a == 4 && maxUlps > 0 && maxUlps < 4 * 1024 * 1024)
$ intDiff < fromIntegral maxUlps
where
intDiff = abs (toInt a - toInt b)
toInt x | x' < 0 = 0x80000000 - x'
| otherwise = x'
where x' = unsafeCoerce x :: Int32
lexicographic64 :: (Num a, Storable a) => Int -> a -> a -> Bool
lexicographic64 maxUlps a b
= assert (sizeOf a == 8 && maxUlps > 0 && maxUlps < 8 * 1024 * 1024)
$ intDiff < fromIntegral maxUlps
where
intDiff = abs (toInt a - toInt b)
toInt x | x' < 0 = 0x8000000000000000 - x'
| otherwise = x'
where x' = unsafeCoerce x :: Int64
-- Compare two vectors element-wise for equality, for a given measure of
-- similarity. The index and values are returned for pairs that fail.
--
validate
:: (IArray array e, Ix ix, Similar e)
=> array ix e
-> array ix e
-> [(ix,(e,e))]
validate ref arr = validate' (assocs ref) (elems arr)
validate' :: (Ix ix, Similar e) => [(ix,e)] -> [e] -> [(ix,(e,e))]
validate' ref arr =
filter (not . uncurry sim . snd) [ (i,(x,y)) | (i,x) <- ref | y <- arr ]
| blambo/accelerate-examples | src/Validate.hs | bsd-3-clause | 3,372 | 4 | 20 | 764 | 1,258 | 678 | 580 | 73 | 1 |
import Sudoku
import Control.Exception
import System.Environment
import Control.Parallel.Strategies hiding (parMap)
import Data.Maybe
-- <<main
main :: IO ()
main = do
[f] <- getArgs
file <- readFile f
let puzzles = lines file
solutions = runEval (parMap solve puzzles)
evaluate (length puzzles)
print (length (filter isJust solutions))
-- >>
parMap :: (a -> b) -> [a] -> Eval [b]
parMap f [] = return []
parMap f (a:as) = do
b <- rpar (f a)
bs <- parMap f as
return (b:bs)
| lywaterman/parconc-examples | sudoku4.hs | bsd-3-clause | 505 | 0 | 12 | 113 | 232 | 116 | 116 | 19 | 1 |
{-# LANGUAGE FlexibleInstances, UndecidableInstances, OverlappingInstances, OverloadedStrings, TypeFamilies, RankNTypes, DeriveDataTypeable, StandaloneDeriving, FlexibleContexts, TypeSynonymInstances, ScopedTypeVariables, GADTs, GeneralizedNewtypeDeriving, BangPatterns, DeriveGeneric #-}
-----------------------------------------------------------------------------
{- |
Module : Language.Javascript.JMacro.Base
Copyright : (c) Gershom Bazerman, 2009
License : BSD 3 Clause
Maintainer : gershomb@gmail.com
Stability : experimental
Simple DSL for lightweight (untyped) programmatic generation of Javascript.
-}
-----------------------------------------------------------------------------
module Compiler.JMacro.Base (
-- * ADT
JStat(..), JExpr(..), JVal(..), JOp(..), JUOp(..),
Ident(..), IdentSupply(..), JsLabel,
-- * Generic traversal (via compos)
JMacro(..), JMGadt(..), Compos(..),
composOp, composOpM, composOpM_, composOpFold,
-- * Hygienic transformation
withHygiene, scopify,
-- * Display/Output
renderJs, renderJs',
renderPrefixJs, renderPrefixJs',
JsToDoc(..), defaultRenderJs, RenderJs(..), jsToDoc,
-- * Ad-hoc data marshalling
ToJExpr(..),
-- * Literals
jsv,
-- * Occasionally helpful combinators
jLam, jVar, jVarTy, jFor, jForIn, jForEachIn, jTryCatchFinally,
expr2stat, ToStat(..), nullStat,
-- * Hash combinators
jhEmpty, jhSingle, jhAdd, jhFromList,
-- * Utility
jsSaturate, SaneDouble(..)
) where
import Prelude hiding (tail, init, head, last, minimum, maximum, foldr1, foldl1, (!!), read)
import Control.Applicative hiding (empty)
import Control.Arrow (second, (***))
import Control.DeepSeq
import Control.Monad.State.Strict
import Control.Monad.Identity
import Data.Function
import Data.Bits ((.&.), shiftR)
import Data.Binary (Binary)
import Data.Char (toLower, isControl, ord)
import qualified Data.Map as M
import qualified Data.Text.Lazy as TL
import Data.Text (Text)
import qualified Data.Text as T
import Data.Data
import Data.Hashable (Hashable)
import Data.Monoid (Monoid, mappend, mempty)
import Data.Text.Binary ()
import GHC.Generics
import Numeric(showHex)
import Safe
import Data.Aeson
import qualified Data.Vector as V
import qualified Data.HashMap.Strict as HM
import Text.PrettyPrint.Leijen.Text hiding ((<$>))
import qualified Text.PrettyPrint.Leijen.Text as PP
-- wl-pprint-text compatibility with pretty
infixl 5 $$, $+$
($+$), ($$), ($$$) :: Doc -> Doc -> Doc
x $+$ y = x PP.<$> y
x $$ y = align (x $+$ y)
x $$$ y = align (nest 2 $ x $+$ y)
{--------------------------------------------------------------------
ADTs
--------------------------------------------------------------------}
newtype IdentSupply a = IS {runIdentSupply :: State [Ident] a} deriving Typeable
instance NFData (IdentSupply a) where rnf (IS{}) = ()
inIdentSupply :: (State [Ident] a -> State [Ident] b) -> IdentSupply a -> IdentSupply b
inIdentSupply f x = IS $ f (runIdentSupply x)
instance Data a => Data (IdentSupply a) where
gunfold _ _ _ = error "gunfold IdentSupply"
toConstr _ = error "toConstr IdentSupply"
dataTypeOf _ = mkNoRepType "IdentSupply"
instance Functor IdentSupply where
fmap f x = inIdentSupply (fmap f) x
takeOne :: State [Ident] Ident
takeOne = do
(x:xs) <- get
put xs
return x
newIdentSupply :: Maybe Text -> [Ident]
newIdentSupply Nothing = newIdentSupply (Just "jmId")
newIdentSupply (Just pfx') = [TxtI (pfx `mappend` T.pack (show x)) | x <- [(0::Integer)..]]
where pfx = pfx' `mappend` "_"
sat_ :: IdentSupply a -> a
sat_ x = evalState (runIdentSupply x) $ newIdentSupply (Just "<<unsatId>>")
instance Eq a => Eq (IdentSupply a) where
(==) = (==) `on` sat_
instance Ord a => Ord (IdentSupply a) where
compare = compare `on` sat_
instance Show a => Show (IdentSupply a) where
show x = "(" ++ show (sat_ x) ++ ")"
-- array comprehensions/generators?
-- | Statements
data JStat = DeclStat Ident
| ReturnStat JExpr
| IfStat JExpr JStat JStat
| WhileStat Bool JExpr JStat -- bool is "do"
| ForInStat Bool Ident JExpr JStat -- bool is "each"
| SwitchStat JExpr [(JExpr, JStat)] JStat
| TryStat JStat Ident JStat JStat
| BlockStat [JStat]
| ApplStat JExpr [JExpr]
| UOpStat JUOp JExpr
| AssignStat JExpr JExpr
| UnsatBlock (IdentSupply JStat)
| AntiStat Text
| LabelStat JsLabel JStat
| BreakStat (Maybe JsLabel)
| ContinueStat (Maybe JsLabel)
deriving (Eq, Ord, Show, Data, Typeable, Generic)
instance NFData JStat
type JsLabel = Text
instance Monoid JStat where
mempty = BlockStat []
mappend (BlockStat xs) (BlockStat ys) = BlockStat $ xs ++ ys
mappend (BlockStat xs) ys = BlockStat $ xs ++ [ys]
mappend xs (BlockStat ys) = BlockStat $ xs : ys
mappend xs ys = BlockStat [xs,ys]
-- TODO: annotate expressions with type
-- | Expressions
data JExpr = ValExpr JVal
| SelExpr JExpr Ident
| IdxExpr JExpr JExpr
| InfixExpr JOp JExpr JExpr
| UOpExpr JUOp JExpr
| IfExpr JExpr JExpr JExpr
| ApplExpr JExpr [JExpr]
| UnsatExpr (IdentSupply JExpr)
| AntiExpr Text
deriving (Eq, Ord, Show, Data, Typeable, Generic)
instance NFData JExpr
-- | Values
data JVal = JVar Ident
| JList [JExpr]
| JDouble SaneDouble
| JInt Integer
| JStr Text
| JRegEx Text
| JHash (M.Map Text JExpr)
| JFunc [Ident] JStat
| UnsatVal (IdentSupply JVal)
deriving (Eq, Ord, Show, Data, Typeable, Generic)
instance NFData JVal
data JOp =
EqOp -- ==
| StrictEqOp -- ===
| NeqOp -- !=
| StrictNeqOp -- !==
| GtOp -- >
| GeOp -- >=
| LtOp -- <
| LeOp -- <=
| AddOp -- +
| SubOp -- -
| MulOp -- "*"
| DivOp -- /
| ModOp -- %
| LeftShiftOp -- <<
| RightShiftOp -- >>
| ZRightShiftOp -- >>>
| BAndOp -- &
| BOrOp -- |
| BXorOp -- ^
| LAndOp -- &&
| LOrOp -- ||
| InstanceofOp -- instanceof
| InOp -- in
deriving (Show, Eq, Ord, Enum, Data, Typeable, Generic)
instance NFData JOp
opText :: JOp -> TL.Text
opText EqOp = "=="
opText StrictEqOp = "==="
opText NeqOp = "!="
opText StrictNeqOp = "!=="
opText GtOp = ">"
opText GeOp = ">="
opText LtOp = "<"
opText LeOp = "<="
opText AddOp = "+"
opText SubOp = "-"
opText MulOp = "*"
opText DivOp = "/"
opText ModOp = "%"
opText LeftShiftOp = "<<"
opText RightShiftOp = ">>"
opText ZRightShiftOp = ">>>"
opText BAndOp = "&"
opText BOrOp = "|"
opText BXorOp = "^"
opText LAndOp = "&&"
opText LOrOp = "||"
opText InstanceofOp = "instanceof"
opText InOp = "in"
data JUOp =
NotOp -- !
| BNotOp -- ~
| NegOp -- -
| PlusOp -- +x
| NewOp -- new x
| TypeofOp -- typeof x
| DeleteOp -- delete x
| YieldOp -- yield x
| VoidOp -- void x
| PreInc -- ++x
| PostInc -- x++
| PreDec -- --x
| PostDec -- x--
deriving (Show, Eq, Ord, Enum, Data, Typeable, Generic)
instance NFData JUOp
isPre :: JUOp -> Bool
isPre PostInc = False
isPre PostDec = False
isPre _ = True
isAlphaOp :: JUOp -> Bool
isAlphaOp NewOp = True
isAlphaOp TypeofOp = True
isAlphaOp DeleteOp = True
isAlphaOp YieldOp = True
isAlphaOp VoidOp = True
isAlphaOp _ = False
uOpText :: JUOp -> TL.Text
uOpText NotOp = "!"
uOpText BNotOp = "~"
uOpText NegOp = "-"
uOpText PlusOp = "+"
uOpText NewOp = "new"
uOpText TypeofOp = "typeof"
uOpText DeleteOp = "delete"
uOpText YieldOp = "yield"
uOpText VoidOp = "void"
uOpText PreInc = "++"
uOpText PostInc = "++"
uOpText PreDec = "--"
uOpText PostDec = "--"
newtype SaneDouble = SaneDouble { unSaneDouble :: Double }
deriving (Data, Typeable, Fractional, Num, Generic, NFData)
instance Eq SaneDouble where
(SaneDouble x) == (SaneDouble y) = x == y || (isNaN x && isNaN y)
instance Ord SaneDouble where
compare (SaneDouble x) (SaneDouble y) = compare (fromNaN x) (fromNaN y)
where fromNaN z | isNaN z = Nothing
| otherwise = Just z
instance Show SaneDouble where
show (SaneDouble x) = show x
-- | Identifiers
newtype Ident = TxtI Text
deriving (Show, Data, Typeable, Hashable, Eq, Ord, Binary, Generic, NFData)
expr2stat :: JExpr -> JStat
expr2stat (ApplExpr x y) = (ApplStat x y)
expr2stat (IfExpr x y z) = IfStat x (expr2stat y) (expr2stat z)
expr2stat (UOpExpr o x) = UOpStat o x
expr2stat (AntiExpr x) = AntiStat x
expr2stat _ = nullStat
{--------------------------------------------------------------------
Compos
--------------------------------------------------------------------}
-- | Compos and ops for generic traversal as defined over
-- the JMacro ADT.
-- | Utility class to coerce the ADT into a regular structure.
class JMacro a where
jtoGADT :: a -> JMGadt a
jfromGADT :: JMGadt a -> a
instance JMacro Ident where
jtoGADT = JMGId
jfromGADT (JMGId x) = x
jfromGADT _ = error "impossible"
instance JMacro JStat where
jtoGADT = JMGStat
jfromGADT (JMGStat x) = x
jfromGADT _ = error "impossible"
instance JMacro JExpr where
jtoGADT = JMGExpr
jfromGADT (JMGExpr x) = x
jfromGADT _ = error "impossible"
instance JMacro JVal where
jtoGADT = JMGVal
jfromGADT (JMGVal x) = x
jfromGADT _ = error "impossible"
-- | Union type to allow regular traversal by compos.
data JMGadt a where
JMGId :: Ident -> JMGadt Ident
JMGStat :: JStat -> JMGadt JStat
JMGExpr :: JExpr -> JMGadt JExpr
JMGVal :: JVal -> JMGadt JVal
composOp :: Compos t => (forall a. t a -> t a) -> t b -> t b
composOp f = runIdentity . composOpM (Identity . f)
composOpM :: (Compos t, Monad m) => (forall a. t a -> m (t a)) -> t b -> m (t b)
composOpM = compos return ap
composOpM_ :: (Compos t, Monad m) => (forall a. t a -> m ()) -> t b -> m ()
composOpM_ = composOpFold (return ()) (>>)
composOpFold :: Compos t => b -> (b -> b -> b) -> (forall a. t a -> b) -> t c -> b
composOpFold z c f = unC . compos (\_ -> C z) (\(C x) (C y) -> C (c x y)) (C . f)
newtype C b a = C { unC :: b }
class Compos t where
compos :: (forall a. a -> m a) -> (forall a b. m (a -> b) -> m a -> m b)
-> (forall a. t a -> m (t a)) -> t c -> m (t c)
instance Compos JMGadt where
compos = jmcompos
jmcompos :: forall m c. (forall a. a -> m a) -> (forall a b. m (a -> b) -> m a -> m b) -> (forall a. JMGadt a -> m (JMGadt a)) -> JMGadt c -> m (JMGadt c)
jmcompos ret app f' v =
case v of
JMGId _ -> ret v
JMGStat v' -> ret JMGStat `app` case v' of
DeclStat i -> ret DeclStat `app` f i
ReturnStat i -> ret ReturnStat `app` f i
IfStat e s s' -> ret IfStat `app` f e `app` f s `app` f s'
WhileStat b e s -> ret (WhileStat b) `app` f e `app` f s
ForInStat b i e s -> ret (ForInStat b) `app` f i `app` f e `app` f s
SwitchStat e l d -> ret SwitchStat `app` f e `app` l' `app` f d
where l' = mapM' (\(c,s) -> ret (,) `app` f c `app` f s) l
BlockStat xs -> ret BlockStat `app` mapM' f xs
ApplStat e xs -> ret ApplStat `app` f e `app` mapM' f xs
TryStat s i s1 s2 -> ret TryStat `app` f s `app` f i `app` f s1 `app` f s2
UOpStat o e -> ret (UOpStat o) `app` f e
AssignStat e e' -> ret AssignStat `app` f e `app` f e'
UnsatBlock _ -> ret v'
AntiStat _ -> ret v'
ContinueStat l -> ret (ContinueStat l)
BreakStat l -> ret (BreakStat l)
LabelStat l s -> ret (LabelStat l) `app` f s
JMGExpr v' -> ret JMGExpr `app` case v' of
ValExpr e -> ret ValExpr `app` f e
SelExpr e e' -> ret SelExpr `app` f e `app` f e'
IdxExpr e e' -> ret IdxExpr `app` f e `app` f e'
InfixExpr o e e' -> ret (InfixExpr o) `app` f e `app` f e'
UOpExpr o e -> ret (UOpExpr o) `app` f e
IfExpr e e' e'' -> ret IfExpr `app` f e `app` f e' `app` f e''
ApplExpr e xs -> ret ApplExpr `app` f e `app` mapM' f xs
UnsatExpr _ -> ret v'
AntiExpr _ -> ret v'
JMGVal v' -> ret JMGVal `app` case v' of
JVar i -> ret JVar `app` f i
JList xs -> ret JList `app` mapM' f xs
JDouble _ -> ret v'
JInt _ -> ret v'
JStr _ -> ret v'
JRegEx _ -> ret v'
JHash m -> ret JHash `app` m'
where (ls, vs) = unzip (M.toList m)
m' = ret (M.fromAscList . zip ls) `app` mapM' f vs
JFunc xs s -> ret JFunc `app` mapM' f xs `app` f s
UnsatVal _ -> ret v'
where
mapM' :: forall a. (a -> m a) -> [a] -> m [a]
mapM' g = foldr (app . app (ret (:)) . g) (ret [])
f :: forall b. JMacro b => b -> m b
f x = ret jfromGADT `app` f' (jtoGADT x)
{--------------------------------------------------------------------
New Identifiers
--------------------------------------------------------------------}
class ToSat a where
toSat_ :: a -> [Ident] -> IdentSupply (JStat, [Ident])
instance ToSat [JStat] where
toSat_ f vs = IS $ return $ (BlockStat f, reverse vs)
instance ToSat JStat where
toSat_ f vs = IS $ return $ (f, reverse vs)
instance ToSat JExpr where
toSat_ f vs = IS $ return $ (expr2stat f, reverse vs)
instance ToSat [JExpr] where
toSat_ f vs = IS $ return $ (BlockStat $ map expr2stat f, reverse vs)
instance (ToSat a, b ~ JExpr) => ToSat (b -> a) where
toSat_ f vs = IS $ do
x <- takeOne
runIdentSupply $ toSat_ (f (ValExpr $ JVar x)) (x:vs)
{-
splitIdentSupply :: ([Ident] -> ([Ident], [Ident]))
splitIdentSupply is = (takeAlt is, takeAlt (drop 1 is))
where takeAlt (x:_:xs) = x : takeAlt xs
takeAlt _ = error "splitIdentSupply: stream is not infinite"
-}
{--------------------------------------------------------------------
Saturation
--------------------------------------------------------------------}
-- | Given an optional prefix, fills in all free variable names with a supply
-- of names generated by the prefix.
jsSaturate :: (JMacro a) => Maybe Text -> a -> a
jsSaturate str x = evalState (runIdentSupply $ jsSaturate_ x) (newIdentSupply str)
jsSaturate_ :: (JMacro a) => a -> IdentSupply a
jsSaturate_ e = IS $ jfromGADT <$> go (jtoGADT e)
where
go :: forall a. JMGadt a -> State [Ident] (JMGadt a)
go v = case v of
JMGStat (UnsatBlock us) -> go =<< (JMGStat <$> runIdentSupply us)
JMGExpr (UnsatExpr us) -> go =<< (JMGExpr <$> runIdentSupply us)
JMGVal (UnsatVal us) -> go =<< (JMGVal <$> runIdentSupply us)
_ -> composOpM go v
{--------------------------------------------------------------------
Transformation
--------------------------------------------------------------------}
-- doesn't apply to unsaturated bits
jsReplace_ :: JMacro a => [(Ident, Ident)] -> a -> a
jsReplace_ xs e = jfromGADT $ go (jtoGADT e)
where
go :: forall a. JMGadt a -> JMGadt a
go v = case v of
JMGId i -> maybe v JMGId (M.lookup i mp)
_ -> composOp go v
mp = M.fromList xs
-- only works on fully saturated things
jsUnsat_ :: JMacro a => [Ident] -> a -> IdentSupply a
jsUnsat_ xs e = IS $ do
(idents,is') <- splitAt (length xs) <$> get
put is'
return $ jsReplace_ (zip xs idents) e
-- | Apply a transformation to a fully saturated syntax tree,
-- taking care to return any free variables back to their free state
-- following the transformation. As the transformation preserves
-- free variables, it is hygienic.
withHygiene :: JMacro a => (a -> a) -> a -> a
withHygiene f x = jfromGADT $ case jtoGADT x of
JMGExpr z -> JMGExpr $ UnsatExpr $ inScope z
JMGStat z -> JMGStat $ UnsatBlock $ inScope z
JMGVal z -> JMGVal $ UnsatVal $ inScope z
JMGId _ -> jtoGADT $ f x
where
inScope z = IS $ do
([TxtI a], b) <- splitAt 1 `fmap` get
put b
return $ withHygiene_ a f z
withHygiene_ :: JMacro a => Text -> (a -> a) -> a -> a
withHygiene_ un f x = jfromGADT $ case jtoGADT x of
JMGStat _ -> jtoGADT $ UnsatBlock (jsUnsat_ is' x'')
JMGExpr _ -> jtoGADT $ UnsatExpr (jsUnsat_ is' x'')
JMGVal _ -> jtoGADT $ UnsatVal (jsUnsat_ is' x'')
JMGId _ -> jtoGADT $ f x
where
(x', (TxtI l : _)) = runState (runIdentSupply $ jsSaturate_ x) is
is' = take lastVal is
x'' = f x'
lastVal = readNote ("inSat" ++ T.unpack un) (reverse . takeWhile (/= '_') . reverse $ T.unpack l) :: Int
is = newIdentSupply $ Just ("inSat" `mappend` un)
-- | Takes a fully saturated expression and transforms it to use unique variables that respect scope.
scopify :: JStat -> JStat
scopify x = evalState (jfromGADT <$> go (jtoGADT x)) (newIdentSupply Nothing)
where go :: forall a. JMGadt a -> State [Ident] (JMGadt a)
go v = case v of
(JMGStat (BlockStat ss)) -> JMGStat . BlockStat <$>
blocks ss
where blocks [] = return []
blocks (DeclStat (TxtI i) : xs)
| "!!" `T.isPrefixOf` i = (DeclStat (TxtI (T.drop 2 i)):) <$> blocks xs
| "!" `T.isPrefixOf` i = (DeclStat (TxtI $ T.tail i):) <$> blocks xs
| otherwise = do
(newI:st) <- get
put st
rest <- blocks xs
return $ [DeclStat newI `mappend` jsReplace_ [(TxtI i, newI)] (BlockStat rest)]
blocks (x':xs) = (jfromGADT <$> go (jtoGADT x')) <:> blocks xs
(<:>) = liftM2 (:)
(JMGStat (TryStat s (TxtI i) s1 s2)) -> do
(newI:st) <- get
put st
t <- jfromGADT <$> go (jtoGADT s)
c <- jfromGADT <$> go (jtoGADT s1)
f <- jfromGADT <$> go (jtoGADT s2)
return . JMGStat . TryStat t newI (jsReplace_ [(TxtI i, newI)] c) $ f
(JMGExpr (ValExpr (JFunc is s))) -> do
st <- get
let (newIs,newSt) = splitAt (length is) st
put (newSt)
rest <- jfromGADT <$> go (jtoGADT s)
return . JMGExpr . ValExpr $ JFunc newIs $ (jsReplace_ $ zip is newIs) rest
_ -> composOpM go v
{--------------------------------------------------------------------
Pretty Printing
--------------------------------------------------------------------}
-- | Render a syntax tree as a pretty-printable document
-- (simply showing the resultant doc produces a nice,
-- well formatted String).
renderJs :: (JsToDoc a, JMacro a) => a -> Doc
renderJs = renderJs' defaultRenderJs
renderJs' :: (JsToDoc a, JMacro a) => RenderJs -> a -> Doc
renderJs' r = jsToDocR r . jsSaturate Nothing
data RenderJs = RenderJs { renderJsS :: RenderJs -> JStat -> Doc
, renderJsE :: RenderJs -> JExpr -> Doc
, renderJsV :: RenderJs -> JVal -> Doc
, renderJsI :: RenderJs -> Ident -> Doc
}
defaultRenderJs :: RenderJs
defaultRenderJs = RenderJs defRenderJsS defRenderJsE defRenderJsV defRenderJsI
jsToDoc :: JsToDoc a => a -> Doc
jsToDoc = jsToDocR defaultRenderJs
-- | Render a syntax tree as a pretty-printable document, using a given prefix to all generated names. Use this with distinct prefixes to ensure distinct generated names between independent calls to render(Prefix)Js.
renderPrefixJs :: (JsToDoc a, JMacro a) => Text -> a -> Doc
renderPrefixJs pfx = renderPrefixJs' defaultRenderJs pfx
renderPrefixJs' :: (JsToDoc a, JMacro a) => RenderJs -> Text -> a -> Doc
renderPrefixJs' r pfx = jsToDocR r . jsSaturate (Just $ "jmId_" `mappend` pfx)
braceNest :: Doc -> Doc
braceNest x = char '{' <+> nest 2 x $$ char '}'
braceNest' :: Doc -> Doc
braceNest' x = nest 2 (char '{' $+$ x) $$ char '}'
class JsToDoc a where jsToDocR :: RenderJs -> a -> Doc
instance JsToDoc JStat where jsToDocR r = renderJsS r r
instance JsToDoc JExpr where jsToDocR r = renderJsE r r
instance JsToDoc JVal where jsToDocR r = renderJsV r r
instance JsToDoc Ident where jsToDocR r = renderJsI r r
instance JsToDoc [JExpr] where
jsToDocR r = vcat . map ((<> semi) . jsToDocR r)
instance JsToDoc [JStat] where
jsToDocR r = vcat . map ((<> semi) . jsToDocR r)
defRenderJsS :: RenderJs -> JStat -> Doc
defRenderJsS r (IfStat cond x y) = text "if" <> parens (jsToDocR r cond) $$ braceNest' (jsToDocR r x) $$ mbElse
where mbElse | y == BlockStat [] = PP.empty
| otherwise = text "else" $$ braceNest' (jsToDocR r y)
defRenderJsS r (DeclStat x) = text "var" <+> jsToDocR r x
defRenderJsS r (WhileStat False p b) = text "while" <> parens (jsToDocR r p) $$ braceNest' (jsToDocR r b)
defRenderJsS r (WhileStat True p b) = (text "do" $$ braceNest' (jsToDocR r b)) $+$ text "while" <+> parens (jsToDocR r p)
defRenderJsS r (UnsatBlock e) = jsToDocR r $ sat_ e
defRenderJsS _ (BreakStat l) = maybe (text "break") (((<+>) `on` text) "break" . TL.fromStrict) l
defRenderJsS _ (ContinueStat l) = maybe (text "continue") (((<+>) `on` text) "continue" . TL.fromStrict) l
defRenderJsS r (LabelStat l s) = text (TL.fromStrict l) <> char ':' $$ printBS s
where
printBS (BlockStat ss) = vcat $ interSemi $ flattenBlocks ss
printBS x = jsToDocR r x
interSemi [x] = [jsToDocR r x]
interSemi [] = []
interSemi (x:xs) = (jsToDocR r x <> semi) : interSemi xs
defRenderJsS r (ForInStat each i e b) = text txt <> parens (jsToDocR r i <+> text "in" <+> jsToDocR r e) $$ braceNest' (jsToDocR r b)
where txt | each = "for each"
| otherwise = "for"
defRenderJsS r (SwitchStat e l d) = text "switch" <+> parens (jsToDocR r e) $$ braceNest' cases
where l' = map (\(c,s) -> (text "case" <+> parens (jsToDocR r c) <> char ':') $$$ (jsToDocR r s)) l ++ [text "default:" $$$ (jsToDocR r d)]
cases = vcat l'
defRenderJsS r (ReturnStat e) = text "return" <+> jsToDocR r e
defRenderJsS r (ApplStat e es) = jsToDocR r e <> (parens . fillSep . punctuate comma $ map (jsToDocR r) es)
defRenderJsS r (TryStat s i s1 s2) = text "try" $$ braceNest' (jsToDocR r s) $$ mbCatch $$ mbFinally
where mbCatch | s1 == BlockStat [] = PP.empty
| otherwise = text "catch" <> parens (jsToDocR r i) $$ braceNest' (jsToDocR r s1)
mbFinally | s2 == BlockStat [] = PP.empty
| otherwise = text "finally" $$ braceNest' (jsToDocR r s2)
defRenderJsS r (AssignStat i x) = jsToDocR r i <+> char '=' <+> jsToDocR r x
defRenderJsS r (UOpStat op x)
| isPre op && isAlphaOp op = text (uOpText op) <+> optParens r x
| isPre op = text (uOpText op) <> optParens r x
| otherwise = optParens r x <> text (uOpText op)
defRenderJsS _ (AntiStat{}) = error "defRenderJsS: AntiStat"
defRenderJsS r (BlockStat xs) = jsToDocR r (flattenBlocks xs)
flattenBlocks :: [JStat] -> [JStat]
flattenBlocks (BlockStat y:ys) = flattenBlocks y ++ flattenBlocks ys
flattenBlocks (y:ys) = y : flattenBlocks ys
flattenBlocks [] = []
optParens :: RenderJs -> JExpr -> Doc
optParens r x = case x of
(UOpExpr _ _) -> parens (jsToDocR r x)
_ -> jsToDocR r x
defRenderJsE :: RenderJs -> JExpr -> Doc
defRenderJsE r (ValExpr x) = jsToDocR r x
defRenderJsE r (SelExpr x y) = cat [jsToDocR r x <> char '.', jsToDocR r y]
defRenderJsE r (IdxExpr x y) = jsToDocR r x <> brackets (jsToDocR r y)
defRenderJsE r (IfExpr x y z) = parens (jsToDocR r x <+> char '?' <+> jsToDocR r y <+> char ':' <+> jsToDocR r z)
defRenderJsE r (InfixExpr op x y) = parens $ hsep [jsToDocR r x, text (opText op), jsToDocR r y]
defRenderJsE r (UOpExpr op x)
| isPre op && isAlphaOp op = text (uOpText op) <+> optParens r x
| isPre op = text (uOpText op) <> optParens r x
| otherwise = optParens r x <> text (uOpText op)
defRenderJsE r (ApplExpr je xs) = jsToDocR r je <> (parens . fillSep . punctuate comma $ map (jsToDocR r) xs)
defRenderJsE _ (AntiExpr{}) = error "defRenderJsE: AntiExpr" -- text . TL.fromChunks $ ["`(", s, ")`"]
defRenderJsE r (UnsatExpr e) = jsToDocR r $ sat_ e
defRenderJsV :: RenderJs -> JVal -> Doc
defRenderJsV r (JVar i) = jsToDocR r i
defRenderJsV r (JList xs) = brackets . fillSep . punctuate comma $ map (jsToDocR r) xs
defRenderJsV _ (JDouble (SaneDouble d))
| d < 0 || isNegativeZero d = parens (double d)
| otherwise = double d
defRenderJsV _ (JInt i) | i < 0 = parens (integer i)
| otherwise = integer i
defRenderJsV _ (JStr s) = text . TL.fromChunks $ ["\"",encodeJson s,"\""]
defRenderJsV _ (JRegEx s) = text . TL.fromChunks $ ["/",s,"/"]
defRenderJsV r (JHash m)
| M.null m = text "{}"
| otherwise = braceNest . fillSep . punctuate comma .
map (\(x,y) -> squotes (text (TL.fromStrict x)) <> colon <+> jsToDocR r y) $ M.toList m
defRenderJsV r (JFunc is b) = parens $ text "function" <> parens (fillSep . punctuate comma . map (jsToDocR r) $ is) $$ braceNest' (jsToDocR r b)
defRenderJsV r (UnsatVal f) = jsToDocR r $ sat_ f
defRenderJsI :: RenderJs -> Ident -> Doc
defRenderJsI _ (TxtI t) = text (TL.fromStrict t)
{--------------------------------------------------------------------
ToJExpr Class
--------------------------------------------------------------------}
-- | Things that can be marshalled into javascript values.
-- Instantiate for any necessary data structures.
class ToJExpr a where
toJExpr :: a -> JExpr
toJExprFromList :: [a] -> JExpr
toJExprFromList = ValExpr . JList . map toJExpr
instance ToJExpr a => ToJExpr [a] where
toJExpr = toJExprFromList
instance ToJExpr JExpr where
toJExpr = id
instance ToJExpr () where
toJExpr _ = ValExpr $ JList []
instance ToJExpr Bool where
toJExpr True = jsv "true"
toJExpr False = jsv "false"
instance ToJExpr JVal where
toJExpr = ValExpr
instance ToJExpr a => ToJExpr (M.Map Text a) where
toJExpr = ValExpr . JHash . M.map toJExpr
instance ToJExpr a => ToJExpr (M.Map String a) where
toJExpr = ValExpr . JHash . M.fromList . map (T.pack *** toJExpr) . M.toList
instance ToJExpr Double where
toJExpr = ValExpr . JDouble . SaneDouble
instance ToJExpr Int where
toJExpr = ValExpr . JInt . fromIntegral
instance ToJExpr Integer where
toJExpr = ValExpr . JInt
instance ToJExpr Char where
toJExpr = ValExpr . JStr . T.pack . (:[])
toJExprFromList = ValExpr . JStr . T.pack
-- where escQuotes = tailDef "" . initDef "" . show
instance ToJExpr Ident where
toJExpr = ValExpr . JVar
instance ToJExpr T.Text where
toJExpr = ValExpr . JStr
instance ToJExpr TL.Text where
toJExpr = ValExpr . JStr . TL.toStrict
instance (ToJExpr a, ToJExpr b) => ToJExpr (a,b) where
toJExpr (a,b) = ValExpr . JList $ [toJExpr a, toJExpr b]
instance (ToJExpr a, ToJExpr b, ToJExpr c) => ToJExpr (a,b,c) where
toJExpr (a,b,c) = ValExpr . JList $ [toJExpr a, toJExpr b, toJExpr c]
instance (ToJExpr a, ToJExpr b, ToJExpr c, ToJExpr d) => ToJExpr (a,b,c,d) where
toJExpr (a,b,c,d) = ValExpr . JList $ [toJExpr a, toJExpr b, toJExpr c, toJExpr d]
instance (ToJExpr a, ToJExpr b, ToJExpr c, ToJExpr d, ToJExpr e) => ToJExpr (a,b,c,d,e) where
toJExpr (a,b,c,d,e) = ValExpr . JList $ [toJExpr a, toJExpr b, toJExpr c, toJExpr d, toJExpr e]
instance (ToJExpr a, ToJExpr b, ToJExpr c, ToJExpr d, ToJExpr e, ToJExpr f) => ToJExpr (a,b,c,d,e,f) where
toJExpr (a,b,c,d,e,f) = ValExpr . JList $ [toJExpr a, toJExpr b, toJExpr c, toJExpr d, toJExpr e, toJExpr f]
instance Num JExpr where
fromInteger = ValExpr . JInt . fromIntegral
x + y = InfixExpr AddOp x y
x - y = InfixExpr SubOp x y
x * y = InfixExpr MulOp x y
abs x = ApplExpr (jsv "Math.abs") [x]
signum x = IfExpr (InfixExpr GtOp x 0) 1 (IfExpr (InfixExpr EqOp x 0) 0 (-1))
{--------------------------------------------------------------------
Block Sugar
--------------------------------------------------------------------}
class ToStat a where
toStat :: a -> JStat
instance ToStat JStat where
toStat = id
instance ToStat [JStat] where
toStat = BlockStat
instance ToStat JExpr where
toStat = expr2stat
instance ToStat [JExpr] where
toStat = BlockStat . map expr2stat
{--------------------------------------------------------------------
Combinators
--------------------------------------------------------------------}
-- | Create a new anonymous function. The result is an expression.
-- Usage:
-- @jLam $ \ x y -> {JExpr involving x and y}@
jLam :: ToSat a => a -> JExpr
jLam f = ValExpr . UnsatVal . IS $ do
(block,is) <- runIdentSupply $ toSat_ f []
return $ JFunc is block
-- | Introduce a new variable into scope for the duration
-- of the enclosed expression. The result is a block statement.
-- Usage:
-- @jVar $ \ x y -> {JExpr involving x and y}@
jVar :: ToSat a => a -> JStat
jVar f = UnsatBlock . IS $ do
(block, is) <- runIdentSupply $ toSat_ f []
let addDecls (BlockStat ss) =
BlockStat $ map (\x -> DeclStat x) is ++ ss
addDecls x = x
return $ addDecls block
-- | Introduce a new variable with optional type into scope for the duration
-- of the enclosed expression. The result is a block statement.
-- Usage:
-- @jVar $ \ x y -> {JExpr involving x and y}@
jVarTy :: ToSat a => a -> {- Maybe JLocalType -> -} JStat
jVarTy f {- t -} = UnsatBlock . IS $ do
(block, is) <- runIdentSupply $ toSat_ f []
let addDecls (BlockStat ss) =
BlockStat $ map (\x -> DeclStat x {- t -}) is ++ ss
addDecls x = x
return $ addDecls block
-- | Create a for in statement.
-- Usage:
-- @jForIn {expression} $ \x -> {block involving x}@
jForIn :: ToSat a => JExpr -> (JExpr -> a) -> JStat
jForIn e f = UnsatBlock . IS $ do
(block, is) <- runIdentSupply $ toSat_ f []
let i = headNote "jForIn" is
return $ DeclStat i `mappend` ForInStat False i e block
-- | As with "jForIn" but creating a \"for each in\" statement.
jForEachIn :: ToSat a => JExpr -> (JExpr -> a) -> JStat
jForEachIn e f = UnsatBlock . IS $ do
(block, is) <- runIdentSupply $ toSat_ f []
let i = headNote "jForEachIn" is
return $ DeclStat i `mappend` ForInStat True i e block
jTryCatchFinally :: (ToSat a) => JStat -> a -> JStat -> JStat
jTryCatchFinally s f s2 = UnsatBlock . IS $ do
(block, is) <- runIdentSupply $ toSat_ f []
let i = headNote "jTryCatchFinally" is
return $ TryStat s i block s2
jsv :: Text -> JExpr
jsv = ValExpr . JVar . TxtI
jFor :: (ToJExpr a, ToStat b) => JStat -> a -> JStat -> b -> JStat
jFor before p after b = BlockStat [before, WhileStat False (toJExpr p) b']
where b' = case toStat b of
BlockStat xs -> BlockStat $ xs ++ [after]
x -> BlockStat [x,after]
jhEmpty :: M.Map Text JExpr
jhEmpty = M.empty
jhSingle :: ToJExpr a => Text -> a -> M.Map Text JExpr
jhSingle k v = jhAdd k v $ jhEmpty
jhAdd :: ToJExpr a => Text -> a -> M.Map Text JExpr -> M.Map Text JExpr
jhAdd k v m = M.insert k (toJExpr v) m
jhFromList :: [(Text, JExpr)] -> JVal
jhFromList = JHash . M.fromList
nullStat :: JStat
nullStat = BlockStat []
-- Aeson instance
instance ToJExpr Value where
toJExpr Null = ValExpr $ JVar $ TxtI "null"
toJExpr (Bool b) = ValExpr $ JVar $ TxtI $ T.pack $ map toLower (show b)
toJExpr (Number n) = ValExpr $ JDouble $ realToFrac n
toJExpr (String s) = ValExpr $ JStr $ s
toJExpr (Array vs) = ValExpr $ JList $ map toJExpr $ V.toList vs
toJExpr (Object obj) = ValExpr $ JHash $ M.fromList $ map (second toJExpr) $ HM.toList obj
encodeJson :: Text -> Text
encodeJson = T.concatMap encodeJsonChar
encodeJsonChar :: Char -> Text
encodeJsonChar '/' = "\\/"
encodeJsonChar '\b' = "\\b"
encodeJsonChar '\f' = "\\f"
encodeJsonChar '\n' = "\\n"
encodeJsonChar '\r' = "\\r"
encodeJsonChar '\t' = "\\t"
encodeJsonChar '"' = "\\\""
encodeJsonChar '\\' = "\\\\"
encodeJsonChar c
| not (isControl c) && ord c <= 127 = T.singleton c
| ord c <= 0xff = hexxs "\\x" 2 (ord c)
| ord c <= 0xffff = hexxs "\\u" 4 (ord c)
| otherwise = let cp0 = ord c - 0x10000 -- output surrogate pair
in hexxs "\\u" 4 ((cp0 `shiftR` 10) + 0xd800) `mappend`
hexxs "\\u" 4 ((cp0 .&. 0x3ff) + 0xdc00)
where hexxs prefix pad cp =
let h = showHex cp ""
in T.pack (prefix ++ replicate (pad - length h) '0' ++ h)
| philderbeast/ghcjs | src/Compiler/JMacro/Base.hs | mit | 34,012 | 0 | 21 | 9,648 | 12,066 | 6,181 | 5,885 | 647 | 35 |
{-# LANGUAGE UnboxedTuples #-}
module T9404 where
foo _ = case seq () (# #) of (# #) -> ()
foo2 _ = case () `seq` (# #) of (# #) -> ()
| siddhanathan/ghc | testsuite/tests/typecheck/should_compile/T9404.hs | bsd-3-clause | 137 | 0 | 8 | 35 | 60 | 32 | 28 | 4 | 1 |
{-# OPTIONS_GHC -fwarn-missing-signatures #-}
module Main (main, c_type_default, c_unused_bind) where
import A (a)
import B (b)
main :: IO ()
main = print (a + b)
c_type_default :: Int
c_type_default = 2 ^ 2
c_unused_bind :: Int -> Int
c_unused_bind x = 2
| urbanslug/ghc | testsuite/tests/driver/dynamic_flags_001/C.hs | bsd-3-clause | 263 | 0 | 7 | 50 | 88 | 51 | 37 | 10 | 1 |
module Anagrams where
import Data.List (sort, intercalate)
import qualified Data.Map.Lazy as Map
type Word = String
extractN :: Int -> [Word] -> [Word]
extractN n =
filter lengthN
where
lengthN :: String -> Bool
lengthN word = length word == n
anagram :: Word -> Word
anagram = sort
anagramList :: [Word] -> [(Word, Word)]
anagramList = map (\w -> (anagram w, w))
anagramMap :: [(Word, Word)] -> Map.Map Word [Word]
anagramMap = Map.fromListWith (++) . map toList
where
toList :: (Word, Word) -> (Word, [Word])
toList (label, w) = (label, [w])
anagrams :: Int -> [Word] -> String
anagrams n ws = foldl printer "" $ (Map.toList . anagramMap . anagramList . extractN n) ws
where
printer :: String -> (Word, [Word]) -> String
printer s (w, ws) = s ++ "\n" ++ w ++ ": " ++ (intercalate ", " (sort ws))
| dirkz/Thinking_Functionally_With_Haskell | 1/Anagrams.hs | isc | 843 | 0 | 11 | 189 | 372 | 209 | 163 | 21 | 1 |
-- Where my anagrams at?
-- http://www.codewars.com/kata/523a86aa4230ebb5420001e1/
module Anagram where
import Data.List (sort)
anagrams :: String -> [String] -> [String]
anagrams w = filter $ (sort w ==) . sort
| gafiatulin/codewars | src/5 kyu/Anagram.hs | mit | 215 | 0 | 8 | 33 | 58 | 34 | 24 | 4 | 1 |
{-# OPTIONS_HADDOCK show-extensions #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
#if __GLASGOW_HASKELL__ > 805
{-# LANGUAGE NoStarIsType #-}
#endif
{-|
Module : Data.ExactPi.TypeLevel
Description : Exact non-negative rational multiples of powers of pi at the type level
License : MIT
Maintainer : douglas.mcclean@gmail.com
Stability : experimental
This kind is sufficient to exactly express the closure of Q⁺ ∪ {π} under multiplication and division.
As a result it is useful for representing conversion factors between physical units.
-}
module Data.ExactPi.TypeLevel
(
-- * Type Level ExactPi Values
type ExactPi'(..),
KnownExactPi(..),
-- * Arithmetic
type (*), type (/), type Recip,
type ExactNatural,
type One, type Pi,
-- * Conversion to Term Level
type MinCtxt, type MinCtxt',
injMin
)
where
import Data.ExactPi
import Data.Maybe (fromJust)
import Data.Proxy
import Data.Ratio
import GHC.TypeLits hiding (type (*), type (^))
import qualified GHC.TypeLits as N
import Numeric.NumType.DK.Integers hiding (type (*), type (/))
import qualified Numeric.NumType.DK.Integers as Z
-- | A type-level representation of a non-negative rational multiple of an integer power of pi.
--
-- Each type in this kind can be exactly represented at the term level by a value of type 'ExactPi',
-- provided that its denominator is non-zero.
--
-- Note that there are many representations of zero, and many representations of dividing by zero.
-- These are not excluded because doing so introduces a lot of extra machinery. Play nice! Future
-- versions may not include a representation for zero.
--
-- Of course there are also many representations of every value, because the numerator need not be
-- comprime to the denominator. For many purposes it is not necessary to maintain the types in reduced
-- form, they will be appropriately reduced when converted to terms.
data ExactPi' = ExactPi' TypeInt -- Exponent of pi
Nat -- Numerator
Nat -- Denominator
-- | A KnownDimension is one for which we can construct a term-level representation.
--
-- Each validly constructed type of kind 'ExactPi'' has a 'KnownExactPi' instance, provided that
-- its denominator is non-zero.
class KnownExactPi (v :: ExactPi') where
-- | Converts an 'ExactPi'' type to an 'ExactPi' value.
exactPiVal :: Proxy v -> ExactPi
-- | Determines the minimum context required for a numeric type to hold the value
-- associated with a specific 'ExactPi'' type.
type family MinCtxt' (v :: ExactPi') where
MinCtxt' ('ExactPi' 'Zero p 1) = Num
MinCtxt' ('ExactPi' 'Zero p q) = Fractional
MinCtxt' ('ExactPi' z p q) = Floating
type MinCtxt v a = (KnownExactPi v, MinCtxt' v a, KnownMinCtxt (MinCtxt' v))
-- | A KnownMinCtxt is a contraint on values sufficient to allow us to inject certain
-- 'ExactPi' values into types that satisfy the constraint.
class KnownMinCtxt c where
-- | Injects an 'ExactPi' value into a specified type satisfying this constraint.
--
-- The injection is permitted to fail if type constraint does not entail the 'MinCtxt'
-- required by the 'ExactPi'' representation of the supplied 'ExactPi' value.
inj :: c a => Proxy c -- ^ A proxy for identifying the required constraint.
-> ExactPi -- ^ The value to inject.
-> a -- ^ A value of the constrained type corresponding to the supplied 'ExactPi' value.
instance KnownMinCtxt Num where
inj _ = fromInteger . fromJust . toExactInteger
instance KnownMinCtxt Fractional where
inj _ = fromRational . fromJust . toExactRational
instance KnownMinCtxt Floating where
inj _ = approximateValue
-- | Converts an 'ExactPi'' type to a numeric value with the minimum required context.
--
-- When the value is known to be an integer, it can be returned as any instance of 'Num'. Similarly,
-- rationals require 'Fractional', and values that involve 'pi' require 'Floating'.
injMin :: forall v a.(MinCtxt v a) => Proxy v -> a
injMin = inj (Proxy :: Proxy (MinCtxt' v)) . exactPiVal
instance (KnownTypeInt z, KnownNat p, KnownNat q, 1 <= q) => KnownExactPi ('ExactPi' z p q) where
exactPiVal _ = Exact z' (p' % q')
where
z' = toNum (Proxy :: Proxy z)
p' = natVal (Proxy :: Proxy p)
q' = natVal (Proxy :: Proxy q)
-- | Forms the product of 'ExactPi'' types (in the arithmetic sense).
type family (a :: ExactPi') * (b :: ExactPi') :: ExactPi' where
('ExactPi' z p q) * ('ExactPi' z' p' q') = 'ExactPi' (z Z.+ z') (p N.* p') (q N.* q')
-- | Forms the quotient of 'ExactPi'' types (in the arithmetic sense).
type family (a :: ExactPi') / (b :: ExactPi') :: ExactPi' where
('ExactPi' z p q) / ('ExactPi' z' p' q') = 'ExactPi' (z Z.- z') (p N.* q') (q N.* p')
-- | Forms the reciprocal of an 'ExactPi'' type.
type family Recip (a :: ExactPi') :: ExactPi' where
Recip ('ExactPi' z p q) = 'ExactPi' (Negate z) q p
-- | Converts a type-level natural to an 'ExactPi'' type.
type ExactNatural n = 'ExactPi' 'Zero n 1
-- | The 'ExactPi'' type representing the number 1.
type One = ExactNatural 1
-- | The 'ExactPi'' type representing the number 'pi'.
type Pi = 'ExactPi' 'Pos1 1 1
| dmcclean/exact-pi | src/Data/ExactPi/TypeLevel.hs | mit | 5,423 | 13 | 10 | 1,066 | 903 | 535 | 368 | -1 | -1 |
module Console (execute, executeInLoop) where
import Data.List.Split
import MyHttp (
Context(..)
, ServerPart
, Request(..)
, RequestType(..)
, Response(..)
)
execute :: Context -> ServerPart -> IO ()
execute inputContext serverpart =
case serverpart inputContext of
Just ctxt -> putStrLn $ show (response ctxt)
Nothing -> print "Error"
parseRequest :: String -> Request
parseRequest input =
case rawType of
"GET" -> Request {reqtype = Get, route = reqRoute}
"POST" -> Request {reqtype = Post, route = reqRoute}
_ -> error "Foo"
where
parts = splitOn ";" input
rawType = head parts
reqRoute = head $ tail parts
executeInLoop :: ServerPart -> IO()
executeInLoop serverpart =
do
putStrLn "Enter Input Route: "
input <- getLine
if input == "exit"
then return ()
else
do
let res = Response {content = "", statusCode = 500}
let ctxt = Context {request = parseRequest input, response = res}
execute ctxt serverpart
executeInLoop serverpart
| nicolocodev/learnhappstack | 5_UsingMsum/Console.hs | mit | 1,137 | 0 | 15 | 352 | 340 | 181 | 159 | 34 | 3 |
{-# htermination isNothing :: Maybe a -> Bool #-}
import Maybe
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Maybe_isNothing_1.hs | mit | 63 | 0 | 3 | 11 | 5 | 3 | 2 | 1 | 0 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
module Models.Url
( Url(..)
, isDetailUrl
) where
import BasicPrelude
import Data.Aeson (FromJSON(..), ToJSON(..), genericParseJSON, genericToJSON)
import Data.Aeson.Types (defaultOptions, fieldLabelModifier)
import GHC.Generics (Generic)
data Url = Url
{ _type :: Text
, _url :: Text
} deriving (Show, Generic)
instance ToJSON Url where
toJSON = genericToJSON defaultOptions {
fieldLabelModifier = drop 1 }
instance FromJSON Url where
parseJSON = genericParseJSON defaultOptions {
fieldLabelModifier = drop 1 }
isDetailUrl :: Url -> Bool
isDetailUrl url = _type url == "detail"
| nicolashery/example-marvel-haskell | Models/Url.hs | mit | 732 | 0 | 9 | 143 | 185 | 109 | 76 | 22 | 1 |
{-# htermination intersectFM_C :: Ord a => (b1 -> b2 -> b3) -> FiniteMap a b1 -> FiniteMap a b2 -> FiniteMap a b3 #-}
import FiniteMap
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/FiniteMap_intersectFM_C_1.hs | mit | 135 | 0 | 3 | 27 | 5 | 3 | 2 | 1 | 0 |
module Q07 where
data NestedList a = Elem a | List [NestedList a]
flatten :: NestedList a -> [a]
flatten x =
let
flatten' :: NestedList a -> [a] -> [a]
flatten' (Elem x) = \y -> x:y
flatten' (List y) = foldr (.) (\x -> x) $ map flatten' y
in
(flatten' x) [] | cshung/MiscLab | Haskell99/q07.hs | mit | 283 | 0 | 12 | 80 | 148 | 78 | 70 | 9 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module QPX.API.Response.Currency where
import Control.Lens (makeLenses)
import Control.Monad (mzero)
import Data.Aeson (FromJSON, Value (String), parseJSON)
import Data.Char (isLetter)
import Data.String.Conversions (cs)
data Currency = Currency { _currency :: String
, _amount :: Float
}
makeLenses ''Currency
instance Show Currency where
show (Currency c a) = c ++ " " ++ show a
instance FromJSON Currency where
parseJSON (String s) = return $ Currency currency' amount'
where currency' = takeWhile isLetter $ cs s
amount' = read $ dropWhile isLetter $ cs s
parseJSON _ = mzero
| timbodeit/qpx-api | src/QPX/API/Response/Currency.hs | mit | 836 | 0 | 10 | 282 | 210 | 115 | 95 | 18 | 0 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
module Game where
import Control.Monad.Random
import Utils (maximumByKey, iterateN)
type Heuristic a s = s -> a -> Double
class Game a s | s -> a where
agent :: s -> a
actions :: s -> [s]
terminal :: s -> Bool
evaluate :: Heuristic a s
lookAheadEval :: Game a s => Heuristic a s -> Heuristic a s
lookAheadEval heuristic state =
if terminal state then heuristic state else
maximumByKey ($ (agent state)) (map heuristic (actions state))
lookAheadEvalDepth :: Game a s => Int -> Heuristic a s -> Heuristic a s
lookAheadEvalDepth n = iterateN n lookAheadEval
lookAheadPlay :: Game a s => Heuristic a s -> s -> s
lookAheadPlay heuristic state =
maximumByKey ((flip heuristic) (agent state)) (actions state)
lookAheadPlayDepth :: Game a s => Int -> Heuristic a s -> s -> s
lookAheadPlayDepth n heuristic = lookAheadPlay (lookAheadEvalDepth (n - 1) heuristic)
playOut :: Game a s => (s -> s) -> s -> [s]
playOut play state =
if terminal state then [state]
else state : playOut play (play state)
finalState :: Game a s => (s -> s) -> s -> s
finalState = until terminal
playOutEval :: Game a s => (s -> s) -> Heuristic a s
playOutEval play state = evaluate (finalState play state)
playOutM :: (Monad m, Game a s) => (s -> m s) -> s -> m [s]
playOutM play state =
if terminal state then return [state]
else do
next <- play state
rest <- playOutM play next
return $ state : rest
playOutEvalM :: (Monad m, Game a s) => (s -> m s) -> s -> m (a -> Double)
playOutEvalM play state = do
game <- playOutM play state
let final = last game
return $ evaluate final
randomPlayer :: (MonadRandom m, Game a s) => s -> m s
randomPlayer state = do
let states = actions state
index <- getRandomR (0, length states - 1)
return $ states !! index
playOutEvalR :: (MonadRandom m, Game a s) => s -> m (a -> Double)
playOutEvalR = playOutEvalM randomPlayer
playOutEvalPR :: (Game a s) => (s -> Int) -> s -> a -> Double
playOutEvalPR hash state = evalRand (playOutEvalR state) (mkStdGen $ hash state)
| vladfi1/game-ai | lib/Game.hs | mit | 2,122 | 0 | 11 | 459 | 899 | 454 | 445 | 51 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Slack
( OAuthAccessResponse(..)
, Token(..)
, TeamId
, issueSlackToken
) where
import Data.Aeson
import Data.Aeson.Types (typeMismatch)
import Data.List (intercalate)
import Network.HTTP.Simple (httpJSON, getResponseBody, parseRequest)
import System.Environment (getEnv)
issueSlackToken :: String -> String -> IO OAuthAccessResponse
issueSlackToken redirectUri code = do
clientId <- getEnv "YUMMY_CLIENT_ID"
clientSecret <- getEnv "YUMMY_CLIENT_SECRET"
let url = mkURL "GET" "https://slack.com/api/oauth.access"
[ ( "client_id" , clientId )
, ( "client_secret", clientSecret )
, ( "code" , code )
, ( "redirect_uri" , redirectUri )
]
r <- parseRequest url
getResponseBody <$> httpJSON r
type URL = String
type Parameters = [Parameter]
type Parameter = (String, String)
mkURL :: String -> URL -> Parameters -> URL
mkURL verb u = mkUrl (verb ++ " " ++ u)
mkUrl :: URL -> Parameters -> URL
mkUrl url [] = url
mkUrl url parameters = url ++ "?" ++ toParameters parameters
toParameters :: Parameters -> String
toParameters = intercalate "&" . map toParameter
toParameter :: Parameter -> String
toParameter (a, b) = a ++ "=" ++ b
type TeamId = String
data Token = Unknown | Token String deriving (Show)
data OAuthAccessResponse = OAuthAccessResponse Token TeamId URL URL deriving Show
instance FromJSON OAuthAccessResponse where
parseJSON (Object o) = do
incomingWebhook <- o .: "incoming_webhook"
OAuthAccessResponse <$> parseJSON (Object o)
<*> o .: "team_id"
<*> incomingWebhook .: "url"
<*> incomingWebhook .: "configuration_url"
parseJSON invalid = typeMismatch "OAuthAccessResponse" invalid
instance FromJSON Token where
parseJSON (Object o) = maybe Unknown Token <$> o .:? "access_token"
parseJSON invalid = typeMismatch "Token" invalid
| Kercoin/yummy | src/Slack.hs | mit | 2,049 | 0 | 17 | 523 | 544 | 292 | 252 | 48 | 1 |
import Prelude hiding (Left, Right)
import Control.Applicative
import Control.Monad (join)
import Data.Monoid hiding (Sum, First)
import Test.QuickCheck hiding (Success)
import Test.QuickCheck.Checkers
import Test.QuickCheck.Classes
-- Write Monad instances for the following types. Use the QuickCheck properties
-- we showed you to validate your instances.
-- 1. Welcome to the Nope Monad, where nothing happens and nobody cares.
data Nope a = NopeDotJpg
deriving (Eq, Show)
instance Functor Nope where
fmap _ _ = NopeDotJpg
instance Applicative Nope where
pure _ = NopeDotJpg
_ <*> _ = NopeDotJpg
instance Monad Nope where
return = pure
_ >>= _ = NopeDotJpg
instance Arbitrary (Nope a) where
arbitrary = elements [NopeDotJpg]
instance (Eq a) => EqProp (Nope a) where
(=-=) = eq
-- 2.
data PhhhbbtttEither b a =
Left a
| Right b
deriving (Eq, Show)
instance Functor (PhhhbbtttEither b) where
fmap _ (Right b) = Right b
fmap f (Left a) = Left $ f a
instance Applicative (PhhhbbtttEither b) where
pure = Left
Right f <*> _ = Right f
Left f <*> fa = fmap f fa
instance Monad (PhhhbbtttEither b) where
return = pure
(Right a) >>= _ = Right a
(Left a) >>= f = f a
instance (Arbitrary a, Arbitrary b) => Arbitrary (PhhhbbtttEither b a) where
arbitrary = genPhEither
where genPhEither = do
a <- arbitrary
b <- arbitrary
elements [Left a, Right b]
instance (Eq a, Eq b) => EqProp (PhhhbbtttEither b a) where
(=-=) = eq
-- 3. Write a Monad instance for Identity.
newtype Identity a = Identity a
deriving (Eq, Ord, Show)
instance Functor Identity where
fmap f (Identity a) = Identity $ f a
instance Applicative Identity where
pure = Identity
(<*>) (Identity f) a = fmap f a
instance Monad Identity where
return = pure
Identity a' >>= f = f a'
instance (Arbitrary a) => Arbitrary (Identity a) where
arbitrary = genIdentity
where genIdentity = do
a <- arbitrary
return $ Identity a
instance (Eq a) => EqProp (Identity a) where
(=-=) = eq
-- 4. This one should be easier than the Applicative instance was. Remember to
-- use the Functor that Monad requires, then see where the chips fall.
data List a =
Nil
| Cons a (List a)
deriving (Eq, Show)
take' :: Int -> List a -> List a
take' 0 _ = Nil
take' _ Nil = Nil
take' n (Cons x xs) = Cons x (take' (n - 1) xs)
instance Monoid (List a) where
mempty = Nil
mappend a Nil = a
mappend Nil a = a
mappend (Cons x xs) ys = Cons x $ xs `mappend` ys
instance Functor List where
fmap _ Nil = Nil
fmap f (Cons a la) = Cons (f a) (fmap f la)
instance Applicative List where
pure x = Cons x Nil
Nil <*> _ = Nil
_ <*> Nil = Nil
(Cons f fs) <*> as = (f <$> as) <> (fs <*> as)
instance Monad List where
return = pure
Nil >>= _ = Nil
(Cons x xs) >>= f = f x <> (xs >>= f)
instance Arbitrary a => Arbitrary (List a) where
-- this breaks
-- arbitrary = Cons <$> arbitrary <*> arbitrary
arbitrary = do
x <- arbitrary
y <- arbitrary
frequency [(1, return Nil),
(10, return (Cons x y))]
instance Eq a => EqProp (List a) where
xs =-= ys = xs' `eq` ys'
where xs' = take' 3000 xs
ys' = take' 3000 ys
main :: IO ()
main = do putStrLn "Testing Nope"
quickBatch $ monad (undefined :: Nope (Int, Int, Int))
putStrLn "Testing PhhhbbtttEither"
quickBatch $ monad (undefined :: PhhhbbtttEither String (Int, Int, Int))
putStrLn "Testing Identity"
quickBatch $ monad (undefined :: Identity (Int, Int, Int))
putStrLn "Testing List"
quickBatch $ monad (undefined :: List (Int, String, Int))
-- Write the following functions using the methods provided by Monad and
-- Functor. Using stuff like identity and composition are fine, but it has to
-- typecheck with types provided.
-- 1.
j :: Monad m => m (m a) -> m a
j a = a >>= id
-- 2.
l1 :: Monad m => (a -> b) -> m a -> m b
l1 f m1 = f <$> m1
--3.
l2 :: Monad m => (a -> b -> c) -> m a -> m b -> m c
l2 f m1 m2 = do m1' <- m1
m2' <- m2
return $ f m1' m2'
-- 4.
a :: Monad m => m a -> m (a -> b) -> m b
a = flip (<*>)
-- 5. You’ll need recursion for this one.
meh :: Monad m => [a] -> (a -> m b) -> m [b]
meh [] _ = return []
meh (x:xs) f = (++) <$> (fmap pure $ f x) <*> (meh xs f)
-- 6. Hint: reuse “meh”
flipType :: (Monad m) => [m a] -> m [a]
flipType a = meh a (join . pure)
| diminishedprime/.org | reading-list/haskell_programming_from_first_principles/18_07.hs | mit | 4,484 | 0 | 13 | 1,179 | 1,770 | 907 | 863 | 120 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Y2020.M11.D17.Exercise where
{--
So.
Okay.
I was going to go all: map countries and their airbases to a KML-file, but
to do that, I need a lat-long of the country, and where best to do that,
other than the country's capital. But we don't have country capitals, so
it's back to wikidata to get those data.
The PROBLEM with wikidata, see: is that it's wikidata, or messy as all get-out.
So, today, we're going to get these wikidata, then clean them up and transform
them to enhanced information on countries that we can use.
Here we go.
First, here is the query that gets us these data. There are some weirditudes.
# Countries and capitals
SELECT ?country ?countryLabel ?capital ?capitalLabel ?latlongLabel
WHERE
{
?capital wdt:P31 wd:Q5119.
?capital wdt:P1376 ?country.
?capital wdt:P625 ?latlong.
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
n.b.: we do not constrain countries, because, if we do, we lose countries,
like Belgium. Let's sieve these data through the lens of the countries we
already have.
--}
import Data.Aeson
import Data.Aeson.WikiDatum
import Data.ByteString.Lazy.Char8 (ByteString)
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Map (Map)
import Data.Set (Set)
import Data.Relation
import Graph.Query
import Y2020.M10.D12.Exercise hiding (LongLat) -- WAAY back when for countries
data CountryInfo = CI { country :: WikiDatum,
capital :: WikiDatum,
latLong :: LongLat }
deriving (Eq, Show)
instance FromJSON CountryInfo where
parseJSON = undefined
samp :: ByteString
samp = BL.concat ["{\"country\":\"http://www.wikidata.org/entity/Q31\"",
",\"countryLabel\":\"Belgium\",\"capital\":\"http://www.wikidata.org/",
"entity/Q239\",\"capitalLabel\":\"Brussels\",\"latlongLabel\":\"Point",
"(4.351666666 50.846666666)\"}"]
{--
>>> (decode samp) :: Maybe CountryInfo
Just (CI {country = WD {qid = "http://www.wikidata.org/entity/Q31",
name = "Belgium"},
capital = WD {qid = "http://www.wikidata.org/entity/Q239",
name = "Brussels"},
latLong = point({ latitude: 50.846666666, longitude: 4.351666666 })})
WOOT!
With this instance declaration, read in the file of ... "countries" and their
capitals.
--}
capitalDir :: FilePath
capitalDir = "Y2020/M11/D17/"
capitalsJSON :: FilePath
capitalsJSON = "things-capitals.json"
type CountryInfoMap = Map Country CountryInfo
readCapitals :: FilePath -> IO CountryInfoMap
readCapitals = undefined
-- How many country-infos thingies are there?
{--
2. Now, load the airbase map and `capitalize` it. But we don't want to do that.
What we want to do is filter out the `countries` that don't have airbases.
Let's do that, instead.
>>> loadBases (workingDir ++ file)
>>> let bases = it
>>> let mappedBases = byICAO bases
--}
countrySet :: Map Icao AirBase -> Set Country
countrySet = undefined
{--
Now we have a set of countries-that-are-countries by which we may identify
the things in the `CountryInfoMap` that are countries and not just things.
--}
{-- BONUS -------------------------------------------------------
3. Upload Countries' Q-id's, their capitals (with their q-id's), and their
lattness-longness to the graph data store. That means, of course, you must
model these relations as ... well: ... relations.
--}
data CC = Cntry WikiDatum | Capitol WikiDatum LongLat
deriving Eq -- finally I spell Capitol ... correctly
instance Node CC where
asNode = undefined
data CapAt = CAPITOL | AT
deriving (Eq, Ord, Show)
instance Edge CapAt where
asEdge = undefined
countryCapitalCoordinates :: CountryInfo -> Relation CC CapAt CC
countryCapitalCoordinates = undefined
-- with `countryCapitalCoordinates` you can cyph your data to the graph.
-- I recommend doing an update to countries to add their Q-id's first.
| geophf/1HaskellADay | exercises/HAD/Y2020/M11/D17/Exercise.hs | mit | 3,997 | 0 | 8 | 771 | 334 | 201 | 133 | 41 | 1 |
module Text.Highlighting.Color.QQ (str) where
import Language.Haskell.TH
import Language.Haskell.TH.Quote
str = QuasiQuoter
{ quoteExp = stringE
, quotePat = undefined
, quoteType = undefined
, quoteDec = undefined
}
| dmalikov/highlighting-colors | src/Text/Highlighting/Color/QQ.hs | mit | 229 | 0 | 6 | 40 | 57 | 38 | 19 | 8 | 1 |
{-# LANGUAGE TemplateHaskell, RankNTypes, ScopedTypeVariables #-}
module Language.Meta.C99.Quote (
c,
ce,
cs
) where
import Language.Haskell.TH
import Language.Haskell.TH.Lib
import Language.Haskell.TH.Quote
import Language.Haskell.TH.Lift
import Language.Haskell.TH.Syntax
import qualified Language.Haskell.Meta.Parse as MH (parseExp)
import qualified Language.Meta.C.Quote as CT
import qualified Language.Meta.C.AST as CA
import qualified Language.Meta.C.Literal as CL
import qualified Language.Meta.C.Parser as CP
import qualified Language.Meta.C99.AST as C99A
import Language.Meta.C99.Data
import Language.Meta.C99.Parser
import qualified Language.Meta.SExpr as S
import Data.Maybe (catMaybes)
import Data.Data
import Data.Generics
import Control.Monad (liftM)
import qualified Control.Monad.Trans as MT
import Control.Monad.Trans.State
import Text.Parsec (ParseError)
$(deriveLiftMany [
''C99A.TranslationUnit,
''C99A.ExternalDecl,
''C99A.DeclSpec,
''C99A.FunctionSpec,
''C99A.Decl,
''C99A.TypeSpec,
''C99A.TypeQualifier,
''C99A.InitDeclarator,
''C99A.StructDecl,
''C99A.SpecQualifierList,
''C99A.StructDeclarator,
''C99A.Enumerator,
''C99A.Declarator,
''C99A.DirectDeclarator,
''C99A.ArrayDeclarator,
''C99A.Pointer,
''C99A.ParamTypeList,
''C99A.ParamDecl,
''C99A.InitializerList,
''C99A.Initializer,
''C99A.Designation,
''C99A.DesignatorList,
''C99A.Designator,
''C99A.TypeName,
''C99A.AbstractDeclarator,
''C99A.DirectAbstractDeclarator,
''C99A.Stat,
''C99A.Compound,
''C99A.BlockItemList,
''C99A.BlockItem,
''C99A.Exp,
''C99A.AssignmentExp,
''C99A.ConditionalExp,
''C99A.ConstExp,
''C99A.LogicalOrExp,
''C99A.CastExp,
''C99A.UnaryExp,
''C99A.TerminalExp,
''C99A.PostExp])
c :: QuasiQuoter
c = QuasiQuoter {
quoteExp = strToExp fromString,
quotePat = strToPat fromString,
quoteType = undefined,
quoteDec = undefined
}
ce :: QuasiQuoter
ce = QuasiQuoter {
quoteExp = strToExp expFromString,
quotePat = strToPat expFromString,
quoteType = undefined,
quoteDec = undefined
}
cs :: QuasiQuoter
cs = QuasiQuoter {
quoteExp = strToExp statFromString,
quotePat = strToPat statFromString,
quoteType = undefined,
quoteDec = undefined
}
type QState = StateT [Name] Q
strToExp :: forall a. Data a => (FilePath -> String -> Either ParseError a) -> String -> Q Exp
strToExp p input = case p "c99expExpr" input of
Left err -> error $ show err
Right result -> do
(exp, names) <- rs result
lamE (map varP (reverse names)) exp
rs :: forall a. Data a => a -> Q (Q Exp, [Name])
rs result = runStateT (dataToExpQM ((\_ -> return Nothing)
`extQ` antiId -- TODO: hey, what the hell is this?
`extQ` antiExp
`extQ` antiBlockItemList
`extQ` antiTranslationUnit
`extQ` antiStringLiteral) result) []
antiId (CA.WildId (S.SList items)) =
MT.lift (mapM S.toExpM items) >>= return . unzip >>= \(names, exps) ->
modify (reverse (catMaybes names) ++) >>
MT.lift location >>= \loc ->
return (Just [| CT.quoteId "antiId" loc ($(foldr appE [|""|] exps)) |])
antiId _ = return Nothing
antiBlockItemList (C99A.WildBlockItemList command) =
MT.lift (S.toCommandM command) >>= \(name, exp) ->
maybe (return ()) (modify . (:)) name >>
MT.lift location >>= \loc ->
return (Just [| quoteBlockItems "antiBlockItemList" loc ($(exp)) |])
antiBlockItemList _ = return Nothing
-- DRY
antiExp (C99A.WildExp command) =
MT.lift (S.toCommandM command) >>= \(name, exp) ->
maybe (return ()) (modify . (:)) name >>
MT.lift location >>= \loc ->
return (Just [| quoteCExp "antiExp" loc ($(exp)) |])
antiExp _ = return Nothing
antiTranslationUnit (C99A.WildTranslationUnit command) =
MT.lift (S.toCommandM command) >>= \(name, exp) ->
maybe (return ()) (modify . (:)) name >>
MT.lift location >>= \loc ->
return (Just [| quoteTranslationUnit "antiTranslationUnit" loc ($(exp)) |])
antiTranslationUnit _ = return Nothing
antiStringLiteral (CL.StringLiteral (S.SList items)) =
MT.lift (mapM S.toExpM items) >>= return . unzip >>= \(names, exps) ->
modify (reverse (catMaybes names) ++) >>
return (Just [| CL.StringLiteral (S.SList [S.SString ($(foldr appE [|""|] exps))]) |])
antiStringLiteral (CL.WideStringLiteral (S.SList items)) =
MT.lift (mapM S.toExpM items) >>= return . unzip >>= \(names, exps) ->
modify (reverse (catMaybes names) ++) >>
return (Just [| CL.WideStringLiteral (S.SList [S.SString ($(foldr appE [|""|] exps))]) |])
quoteBlockItems ctx = CT.quoteParser ctx blockItemListP
quoteCExp ctx = CT.quoteParser ctx castExpP
quoteTranslationUnit ctx = CT.quoteParser ctx translationUnitP
strToPat p input = case p "c99Pat" input of
Left err -> error $ show err
Right result -> dataToPatQ (const Nothing) result
-- TODO: Refactor out dataToXxxM utilities
dataToQaM :: forall a k q m. (Data a, Monad m)
=> (Name -> k)
-> (Lit -> Q q)
-> (k -> [Q q] -> Q q)
-> (forall b. Data b => b -> m (Maybe (Q q)))
-> a
-> m (Q q)
dataToQaM mkCon mkLit appCon antiQ t =
antiQ t >>= \antiResult ->
case antiResult of
Nothing ->
case constrRep constr of
AlgConstr _ ->
conArgs >>= \args ->
return (appCon (mkCon conName) args)
where
conName :: Name
conName =
case showConstr constr of
"(:)" -> Name (mkOccName ":") (NameG DataName (mkPkgName "ghc-prim") (mkModName "GHC.Types"))
con@"[]" -> Name (mkOccName con) (NameG DataName (mkPkgName "ghc-prim") (mkModName "GHC.Types"))
con@('(':_) -> Name (mkOccName con) (NameG DataName (mkPkgName "ghc-prim") (mkModName "GHC.Tuple"))
con -> mkNameG_d (tyConPackage tycon)
(tyConModule tycon)
con
where
tycon :: TyCon
tycon = (typeRepTyCon . typeOf) t
conArgs :: m [Q q]
conArgs = sequence (gmapQ (dataToQaM mkCon mkLit appCon antiQ) t)
IntConstr n ->
return $ mkLit $ integerL n
FloatConstr n ->
return $ mkLit $ rationalL n
CharConstr c ->
return $ mkLit $ charL c
where
constr :: Constr
constr = toConstr t
Just y -> return y
dataToExpQM :: (Data a, Monad m)
=> (forall b. Data b => b -> m (Maybe (Q Exp)))
-> a
-> m (Q Exp)
dataToExpQM = dataToQaM conE litE (foldl appE)
| ykst/MetaC | Language/Meta/C99/Quote.hs | mit | 6,857 | 3 | 22 | 1,783 | 2,231 | 1,209 | 1,022 | 178 | 8 |
module CabalSpec (main, spec) where
import Helper
import Cabal
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "format" $ do
it "creates a cabal file" $ do
format "foo" [
package "base-4.6.0.1"
, package "bytestring-0.10.0.2"
] [
package "base-4.6.0.1"
, package "bytestring-0.10.0.2"
, package "hspec-1.7.3"
, package "QuickCheck-2.6"
]
`shouldBe` unlines [
"-- NOTE:"
, "--"
, "-- This file was generated from dependencies.yaml. To regenerate it run"
, "-- `depends`."
, "--"
, "name: foo"
, "version: 0.0.0"
, "build-type: Simple"
, "cabal-version: >= 1.8"
, ""
, "executable foo"
, " ghc-options: -Wall"
, " hs-source-dirs: src"
, " main-is: Main.hs"
, " build-depends:"
, " base == 4.6.0.1"
, " , bytestring == 0.10.0.2"
, ""
, "test-suite test"
, " type: exitcode-stdio-1.0"
, " ghc-options: -Wall -Werror"
, " hs-source-dirs: test, src"
, " main-is: Main.hs"
, " build-depends:"
, " base == 4.6.0.1"
, " , bytestring == 0.10.0.2"
, " , hspec == 1.7.3"
, " , QuickCheck == 2.6"
]
| sol/depends | test/CabalSpec.hs | mit | 1,380 | 0 | 16 | 552 | 205 | 118 | 87 | 46 | 1 |
{-# LANGUAGE GADTs, CPP, Trustworthy, TemplateHaskell, TupleSections, ViewPatterns, DeriveDataTypeable, ScopedTypeVariables #-}
module Main where
import JavaScript.Web.Worker.Extras
import qualified Tarefa6_li1g147 as G147
main :: IO ()
main = runSyncWorker $ \(inp::[String],player::Int,ticks::Int) -> G147.bot inp player ticks
| hpacheco/HAAP | examples/gameworker/Worker3.hs | mit | 341 | 0 | 9 | 47 | 75 | 45 | 30 | 6 | 1 |
module Three where
main :: IO ()
main = do
putStrLn greeting
printSecond
where greeting = "Yarrrrr"
printSecond :: IO ()
printSecond = do
putStrLn greeting
| mudphone/HaskellBook | src/Three.hs | mit | 189 | 0 | 9 | 59 | 56 | 28 | 28 | 9 | 1 |
-- Copyright (c) 2016-present, SoundCloud Ltd.
-- All rights reserved.
--
-- This source code is distributed under the terms of a MIT license,
-- found in the LICENSE file.
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
module Kubernetes.Model.V1.ISCSIVolumeSource
( ISCSIVolumeSource (..)
, targetPortal
, iqn
, lun
, iscsiInterface
, fsType
, readOnly
, mkISCSIVolumeSource
) where
import Control.Lens.TH (makeLenses)
import Data.Aeson.TH (defaultOptions, deriveJSON,
fieldLabelModifier)
import Data.Text (Text)
import GHC.Generics (Generic)
import Prelude hiding (drop, error, max, min)
import qualified Prelude as P
import Test.QuickCheck (Arbitrary, arbitrary)
import Test.QuickCheck.Instances ()
-- | Represents an ISCSI disk. ISCSI volumes can only be mounted as read/write once. ISCSI volumes support ownership management and SELinux relabeling.
data ISCSIVolumeSource = ISCSIVolumeSource
{ _targetPortal :: !(Text)
, _iqn :: !(Text)
, _lun :: !(Integer)
, _iscsiInterface :: !(Maybe Text)
, _fsType :: !(Text)
, _readOnly :: !(Maybe Bool)
} deriving (Show, Eq, Generic)
makeLenses ''ISCSIVolumeSource
$(deriveJSON defaultOptions{fieldLabelModifier = (\n -> if n == "_type_" then "type" else P.drop 1 n)} ''ISCSIVolumeSource)
instance Arbitrary ISCSIVolumeSource where
arbitrary = ISCSIVolumeSource <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
-- | Use this method to build a ISCSIVolumeSource
mkISCSIVolumeSource :: Text -> Text -> Integer -> Text -> ISCSIVolumeSource
mkISCSIVolumeSource xtargetPortalx xiqnx xlunx xfsTypex = ISCSIVolumeSource xtargetPortalx xiqnx xlunx Nothing xfsTypex Nothing
| soundcloud/haskell-kubernetes | lib/Kubernetes/Model/V1/ISCSIVolumeSource.hs | mit | 2,055 | 0 | 14 | 573 | 374 | 220 | 154 | 47 | 1 |
{-# LANGUAGE DeriveDataTypeable, ViewPatterns #-}
import Control.Monad (when, unless)
import Data.List (delete)
import System.Console.CmdArgs
import System.Directory (doesFileExist, removeFile)
import System.Environment (getEnvironment)
import System.IO.Error (catchIOError)
data Options = Options
{ filename :: String
, number :: Int
, show_ :: Bool
, clean :: Bool
, line :: [String]
}
deriving (Show, Data, Typeable)
getDefaultFile :: IO [Char]
getDefaultFile = do
found <- lookup "HOME" `fmap` getEnvironment
case found of
Nothing -> error "There is no $HOME environment variable"
Just home -> return (home ++ "/.linecache")
getOptions :: IO Options
getOptions = do
defaultFile <- getDefaultFile
let defaultCapacity = 10
return $ Options
{ filename = defaultFile &= typFile &= help ("Cache file path (default=" ++ defaultFile ++ ")")
, number = defaultCapacity &= typ "NUM" &= help ("Cache capacity (default=" ++ show defaultCapacity++ ")")
, show_ = False &= help "Show line cache"
, clean = False &= help "Clean line cache"
, line = def &= args &= typ "NEW-LINE" }
&= summary "Line Cache Manager v 0.1.1, (c) Dmitry Antonyuk 2010-2011"
&= program "linecache"
lru :: (Eq a) => a -> [a] -> [a]
lru x xs = x : (x `delete` xs)
force :: [a] -> IO ()
force = mapM_ (ret ())
ret :: a -> b -> IO a
ret = const . return
main :: IO ()
main = do
Options _file _capacity _list _delete (unwords -> _line) <- getOptions >>= cmdArgs
when _delete $ do
exists <- doesFileExist _file
when exists (removeFile _file)
cache <- fmap lines (readFile _file `catchIOError` ret "")
force cache
unless (null _line) $ do
let newCache = take _capacity $ lru _line cache
writeFile _file (unlines newCache)
when _list $ putStr $ unlines cache
| lomeo/linecache | Main.hs | mit | 1,937 | 0 | 17 | 505 | 634 | 326 | 308 | 50 | 2 |
module Roman (numerals) where
import Control.Monad (liftM2, liftM)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
import Debug.Trace
base = [(1, Just "I"),
(5, Just "V"),
(10, Just "X"),
(50, Just "L"),
(100, Just "C"),
(500, Just "D"),
(1000, Just "M")]
baseMap = Map.fromList base
stickM = liftM2 (++)
minusType n = or [Map.member (n + i) baseMap | i <- map fst base]
numerals :: Integer -> Maybe String
numerals n
| n < 1 || n > 5000 = Nothing
| Map.member n baseMap = Map.findWithDefault Nothing n baseMap
| minusType n = letter `stickM` Map.findWithDefault Nothing (n + i) baseMap
| multi > 0 && remainder == 0 = concat <$> (replicate (fromInteger multi) <$> numerals pivot)
| multi == 1 && pivot < m = (++) <$> numerals m <*> (Just $ fromMaybe "" $ numerals (n - m))
| otherwise =(++) <$> numerals (n - remainder) <*> (Just $ fromMaybe "" $ numerals remainder)
where pivot = head $ dropWhile (n <) $ reverse $ map fst base
multi = n `div` pivot
remainder = n - multi * pivot
(i, letter) = head $ filter (\(i, _) -> Map.member (n + i) baseMap) base
m = head [i - j | i <- reverse $ map fst base, j <- map fst base, n > i - j, i - j > 0]
| c19/Exercism-Haskell | roman-numerals/src/Roman.hs | mit | 1,275 | 0 | 13 | 339 | 614 | 323 | 291 | 28 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE PackageImports #-}
import "terrelln-me" Application (getApplicationDev)
import Network.Wai.Handler.Warp
(runSettings, defaultSettings, setPort)
import Control.Concurrent (forkIO)
import System.Directory (doesFileExist, removeFile)
import System.Exit (exitSuccess)
import Control.Concurrent (threadDelay)
#ifndef mingw32_HOST_OS
import System.Posix.Signals (installHandler, sigINT, Handler(Catch))
#endif
main :: IO ()
main = do
#ifndef mingw32_HOST_OS
_ <- installHandler sigINT (Catch $ return ()) Nothing
#endif
putStrLn "Starting devel application"
(port, app) <- getApplicationDev
forkIO $ runSettings (setPort port defaultSettings) app
loop
loop :: IO ()
loop = do
threadDelay 100000
e <- doesFileExist "yesod-devel/devel-terminate"
if e then terminateDevel else loop
terminateDevel :: IO ()
terminateDevel = exitSuccess
| terrelln/terrelln.me | devel.hs | mit | 895 | 0 | 12 | 134 | 238 | 131 | 107 | 24 | 2 |
module Network.Skype.Protocol.ChatMember where
import Data.Typeable (Typeable)
import Network.Skype.Protocol.Chat
import Network.Skype.Protocol.Types
data ChatMemberProperty = ChatMemberChatName ChatID
| ChatMemberIdentity UserID
| ChatMemberRole ChatRole
| ChatMemberIsActive Bool
deriving (Eq, Show, Typeable)
| emonkak/skype4hs | src/Network/Skype/Protocol/ChatMember.hs | mit | 388 | 0 | 6 | 104 | 71 | 44 | 27 | 9 | 0 |
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
module Robots2.Quiz where
import Inter.Types
import Autolib.ToDoc
import Autolib.Reader
import Data.Typeable
data RC = RC { width :: Integer -- ^ feld geht von (-w.-w) .. (w,w)
, num_robots :: Int
, num_targets :: Int
, at_least :: Int -- ^ req length of solution
, search_width :: Int -- ^ at most that many nodes per level
}
deriving ( Typeable )
$(derives [makeReader, makeToDoc] [''RC])
rc :: RC
rc = RC { width = 3
, num_robots = 5
, num_targets = 2
, at_least = 5
, search_width = 1000
}
-- Local Variables:
-- mode: haskell
-- End:
| Erdwolf/autotool-bonn | src/Robots2/Quiz.hs | gpl-2.0 | 643 | 4 | 9 | 158 | 148 | 93 | 55 | 19 | 1 |
-- We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
--
-- What is the largest n-digit pandigital prime that exists?
import Data.List
import Prime
main :: IO ()
main = print answer
-- Pull out the largest prime; I think that the last will always be the largest, but you could do maximum
-- if I am wrong here
answer :: Integer
answer = last perms
-- Go through all the permutations of all lists of numbers [1..n] where n is prime and > 2
-- pull out the prime permutations
-- Slow but tolerable, just
perms :: [Integer]
perms =
[c | a <- ['3','5'..'9']
, b <- permute ['1'..a]
, let c = read b::Integer
, prime c
]
where
permute "" = [""]
permute str = [(x:xs)| x <- str, xs <- permute (delete x str)]
| ciderpunx/project_euler_in_haskell | euler041.hs | gpl-2.0 | 861 | 0 | 12 | 207 | 177 | 97 | 80 | 14 | 2 |
module Utils (zipK) where
zipK :: [a] -> [a] -> a -> [(a, a)]
zipK (x:xs) (y:ys) k = (x, y) : zipK xs ys k
zipK (x:xs) _ k = (x, k) : zipK xs [] k
zipK _ (y:ys) k = (k, y) : zipK [] ys k
zipK _ _ k = []
| aauger/HaskellCoreUtils | HaskellCoreUtils/src/Utils.hs | gpl-3.0 | 224 | 0 | 9 | 77 | 174 | 95 | 79 | 6 | 1 |
{-# LANGUAGE CPP #-}
module Main (main) where
import Control.Applicative ((<|>))
import Control.Monad (forM_, unless, (>=>))
import Data.Char (toLower)
import Data.List (nub, partition, sort)
import Data.Maybe (catMaybes, fromMaybe, mapMaybe,
maybeToList)
import Data.Version (showVersion)
import qualified Paths_jammittools as Paths
import Sound.Jammit.Base
import Sound.Jammit.Export
import qualified System.Console.GetOpt as Opt
import System.Directory (createDirectoryIfMissing)
import qualified System.Environment as Env
import System.Exit (exitFailure)
import System.FilePath (makeValid, takeDirectory, (<.>), (</>))
import Text.PrettyPrint.Boxes (hsep, left, render, text, top, vcat,
(/+/))
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>))
#endif
printUsage :: IO ()
printUsage = do
prog <- Env.getProgName
putStrLn $ "jammittools v" ++ showVersion Paths.version
putStrLn ""
let header = "Usage: " ++ prog ++ " -t <title> -r <artist> [options]"
putStr $ Opt.usageInfo header argOpts
putStrLn ""
putStrLn "Instrument parts:"
putStr showCharPartMap
putStrLn "For sheet music, GRBA are tab instead of notation."
putStrLn "For audio, GBDKV are the backing tracks for each instrument."
putStrLn ""
putStrLn "Example usage:"
putStrLn " # Export all sheet music and audio to a new folder"
putStrLn $ " mkdir export; " ++ prog ++ " -t title -r artist -x export"
putStrLn " # Make a sheet music PDF with Guitar 1's notation and tab"
putStrLn $ " " ++ prog ++ " -t title -r artist -y gG -s gtr1.pdf"
putStrLn " # Make an audio track with no drums and no vocals"
putStrLn $ " " ++ prog ++ " -t title -r artist -y D -n vx -a nodrumsvox.wav"
main :: IO ()
main = do
(opts, nonopts, errs) <- Opt.getOpt Opt.Permute argOpts <$> Env.getArgs
unless (null $ nonopts ++ errs) $ do
forM_ nonopts $ \nonopt -> putStrLn $ "unrecognized argument `" ++ nonopt ++ "'"
forM_ errs putStr
printUsage
exitFailure
let args = foldr ($) defaultArgs opts
exportBoth matches dout = do
let sheets = getSheetParts matches
audios = getAudioParts matches
backingOrder = [Drums, Guitar, Keyboard, Bass, Vocal]
isGuitar p = elem (partToInstrument p) [Guitar, Bass]
(gtrs, nongtrs) = partition isGuitar [minBound .. maxBound]
backingTracks = flip mapMaybe backingOrder $ \i ->
case getOneResult (Without i) audios of
Left _ -> Nothing
Right fp -> Just (i, fp)
forM_ gtrs $ \p ->
case (getOneResult (Notation p) sheets, getOneResult (Tab p) sheets) of
(Right note, Right tab) -> let
parts = [note, tab]
systemHeight = sum $ map snd parts
fout = dout </> drop 4 (map toLower $ show p) <.> "pdf"
in do
putStrLn $ "Exporting notation & tab for " ++ show p
runSheet [note, tab] (getPageLines systemHeight args) fout
_ -> return ()
forM_ nongtrs $ \p ->
case getOneResult (Notation p) sheets of
Left _ -> return ()
Right note -> let
fout = dout </> drop 4 (map toLower $ show p) <.> "pdf"
in do
putStrLn $ "Exporting notation for " ++ show p
runSheet [note] (getPageLines (snd note) args) fout
forM_ [minBound .. maxBound] $ \p ->
case getOneResult (Only p) audios of
Left _ -> return ()
Right fp -> let
fout = dout </> drop 4 (map toLower $ show p) <.> "wav"
in do
putStrLn $ "Exporting audio for " ++ show p
runAudio [fp] [] fout
if rawBackings args
then forM_ backingTracks $ \(inst, fback) -> do
putStrLn $ "Exporting backing track for " ++ show inst
let fout = dout </> "backing-" ++ map toLower (show inst) <.> "wav"
runAudio [fback] [] fout
else case backingTracks of
[] -> return ()
(inst, fback) : _ -> let
others = [ fp | (Only p, fp) <- audios, partToInstrument p /= inst ]
fout = dout </> "backing.wav"
in do
putStrLn "Exporting backing audio (could take a while)"
runAudio [fback] others fout
clickTracks <- mapM loadBeats $ map (\(fp, _, _) -> fp) matches
case catMaybes clickTracks of
[] -> return ()
beats : _ -> do
putStrLn "Exporting metronome click track"
writeMetronomeTrack (dout </> "click.wav") beats
case function args of
PrintUsage -> printUsage
ShowDatabase -> do
matches <- searchResults args
putStr $ showLibrary matches
ExportAudio fout -> do
matches <- getAudioParts <$> searchResultsChecked args
let f = mapM (`getOneResult` matches) . mapMaybe charToAudioPart
case (f $ selectParts args, f $ rejectParts args) of
(Left err , _ ) -> error err
(_ , Left err ) -> error err
(Right yaifcs, Right naifcs) -> runAudio yaifcs naifcs fout
ExportClick fout -> do
matches <- map (\(fp, _, _) -> fp) <$> searchResultsChecked args
clickTracks <- mapM loadBeats matches
case catMaybes clickTracks of
[] -> do
putStrLn $ "Couldn't load beats.plist from any of these folders: " ++ show matches
exitFailure
beats : _ -> writeMetronomeTrack fout beats
CheckPresence -> do
matches <- getAudioParts <$> searchResultsChecked args
let f = mapM (`getOneResult` matches) . mapMaybe charToAudioPart
case (f $ selectParts args, f $ rejectParts args) of
(Left err , _ ) -> error err
(_ , Left err ) -> error err
(Right _ , Right _ ) -> return ()
ExportSheet fout -> do
matches <- getSheetParts <$> searchResultsChecked args
let f = mapM (`getOneResult` matches) . mapMaybe charToSheetPart
case f $ selectParts args of
Left err -> error err
Right parts -> let
systemHeight = sum $ map snd parts
in runSheet parts (getPageLines systemHeight args) fout
ExportAll dout -> do
matches <- searchResultsChecked args
exportBoth matches dout
ExportLib dout -> do
matches <- searchResults args
let titleArtists = nub [ (title info, artist info) | (_, info, _) <- matches ]
forM_ titleArtists $ \ta@(t, a) -> do
putStrLn $ "# SONG: " ++ a ++ " - " ++ t
let entries = filter (\(_, info, _) -> ta == (title info, artist info)) matches
songDir = dout </> makeValid (removeSlashes $ a ++ " - " ++ t)
removeSlashes = map $ \c -> case c of '/' -> '_'; '\\' -> '_'; _ -> c
createDirectoryIfMissing False songDir
exportBoth entries songDir
getPageLines :: Integer -> Args -> Int
getPageLines systemHeight args = let
pageHeight = sheetWidth / 8.5 * 11 :: Double
defaultLines = round $ pageHeight / fromIntegral systemHeight
in max 1 $ fromMaybe defaultLines $ pageLines args
-- | If there is exactly one pair with the given first element, returns its
-- second element. Otherwise (for 0 or >1 elements) returns an error.
getOneResult :: (Eq a, Show a) => a -> [(a, b)] -> Either String b
getOneResult x xys = case [ b | (a, b) <- xys, a == x ] of
[y] -> Right y
[] -> Left $ "Couldn't find the part " ++ show x
ys -> Left $ unwords
[ "Found"
, show $ length ys
, "different parts for"
, show x ++ ";"
, "this is probably a bug?"
]
-- | Displays a table of the library, possibly filtered by search terms.
showLibrary :: Library -> String
showLibrary lib = let
titleArtists = sort $ nub [ (title info, artist info) | (_, info, _) <- lib ]
partsFor ttl art = map partToChar $ sort $ concat
[ mapMaybe (trackTitle >=> titleToPart) trks
| (_, info, trks) <- lib
, (ttl, art) == (title info, artist info) ]
makeColumn h col = text h /+/ vcat left (map text col)
titleColumn = makeColumn "Title" $ map fst titleArtists
artistColumn = makeColumn "Artist" $ map snd titleArtists
partsColumn = makeColumn "Parts" $ map (uncurry partsFor) titleArtists
in render $ hsep 1 top [titleColumn, artistColumn, partsColumn]
-- | Loads the Jammit library, and applies the search terms from the arguments
-- to filter it.
searchResults :: Args -> IO Library
searchResults args = do
exeDir <- takeDirectory <$> Env.getExecutablePath
jmt <- case jammitDir args of
Just j -> return [j]
Nothing -> Env.lookupEnv "JAMMIT" >>= \mv -> case mv of
Just j -> return [j]
Nothing -> maybeToList <$> findJammitDir
db <- concat <$> mapM loadLibrary (exeDir : jmt)
return $ filterLibrary args db
-- | Checks that the search actually narrowed down the library to a single song.
searchResultsChecked :: Args -> IO Library
searchResultsChecked args = do
lib <- searchResults args
case [ info | (_, info, _) <- lib ] of
[] -> do
putStrLn "No songs matched your search."
exitFailure
x : xs -> if all (\y -> title y == title x && artist y == artist x) xs
then return lib
else do
putStrLn "Multiple songs matched your search:"
putStr $ showLibrary lib
exitFailure
argOpts :: [Opt.OptDescr (Args -> Args)]
argOpts =
[ Opt.Option ['t'] ["title"]
(Opt.ReqArg
(\s a -> a { filterLibrary = fuzzySearchBy title s . filterLibrary a })
"str")
"search by song title (fuzzy)"
, Opt.Option ['r'] ["artist"]
(Opt.ReqArg
(\s a -> a { filterLibrary = fuzzySearchBy artist s . filterLibrary a })
"str")
"search by song artist (fuzzy)"
, Opt.Option ['T'] ["title-exact"]
(Opt.ReqArg
(\s a -> a { filterLibrary = exactSearchBy title s . filterLibrary a })
"str")
"search by song title (exact)"
, Opt.Option ['R'] ["artist-exact"]
(Opt.ReqArg
(\s a -> a { filterLibrary = exactSearchBy artist s . filterLibrary a })
"str")
"search by song artist (exact)"
, Opt.Option ['y'] ["yes-parts"]
(Opt.ReqArg (\s a -> a { selectParts = s }) "parts")
"parts to appear in sheet music or audio"
, Opt.Option ['n'] ["no-parts"]
(Opt.ReqArg (\s a -> a { rejectParts = s }) "parts")
"parts to subtract (add inverted) from audio"
, Opt.Option ['l'] ["lines"]
(Opt.ReqArg (\s a -> a { pageLines = Just $ read s }) "int")
"number of systems per page"
, Opt.Option ['j'] ["jammit"]
(Opt.ReqArg (\s a -> a { jammitDir = Just s }) "directory")
"location of Jammit library"
, Opt.Option ['?', 'h'] ["help"]
(Opt.NoArg $ \a -> a { function = PrintUsage })
"function: print usage info"
, Opt.Option ['d'] ["database"]
(Opt.NoArg $ \a -> a { function = ShowDatabase })
"function: display all songs in db"
, Opt.Option ['s'] ["sheet"]
(Opt.ReqArg (\s a -> a { function = ExportSheet s }) "file")
"function: export sheet music"
, Opt.Option ['a'] ["audio"]
(Opt.ReqArg (\s a -> a { function = ExportAudio s }) "file")
"function: export audio"
, Opt.Option ['m'] ["metronome"]
(Opt.ReqArg (\s a -> a { function = ExportClick s }) "file")
"function: export metronome audio"
, Opt.Option ['x'] ["export"]
(Opt.ReqArg (\s a -> a { function = ExportAll s }) "dir")
"function: export song to dir"
, Opt.Option ['b'] ["backup"]
(Opt.ReqArg (\s a -> a { function = ExportLib s }) "dir")
"function: export library to dir"
, Opt.Option ['c'] ["check"]
(Opt.NoArg $ \a -> a { function = CheckPresence })
"function: check presence of audio parts"
, Opt.Option [] ["raw"]
(Opt.NoArg $ \a -> a { rawBackings = True })
"when exporting song/library, extract all individual backing tracks"
]
data Args = Args
{ filterLibrary :: Library -> Library
, selectParts :: String
, rejectParts :: String
, pageLines :: Maybe Int
, jammitDir :: Maybe FilePath
, function :: Function
, rawBackings :: Bool
}
data Function
= PrintUsage
| ShowDatabase
| ExportSheet FilePath
| ExportAudio FilePath
| ExportClick FilePath
| ExportAll FilePath
| ExportLib FilePath
| CheckPresence
deriving (Eq, Ord, Show, Read)
defaultArgs :: Args
defaultArgs = Args
{ filterLibrary = id
, selectParts = ""
, rejectParts = ""
, pageLines = Nothing
, jammitDir = Nothing
, function = PrintUsage
, rawBackings = False
}
partToChar :: Part -> Char
partToChar p = case p of
PartGuitar1 -> 'g'
PartGuitar2 -> 'r'
PartBass1 -> 'b'
PartBass2 -> 'a'
PartDrums1 -> 'd'
PartDrums2 -> 'm'
PartKeys1 -> 'k'
PartKeys2 -> 'y'
PartPiano -> 'p'
PartSynth -> 's'
PartOrgan -> 'o'
PartVocal -> 'v'
PartBVocals -> 'x'
charPartMap :: [(Char, Part)]
charPartMap = [ (partToChar p, p) | p <- [minBound .. maxBound] ]
showCharPartMap :: String
showCharPartMap = let
len = ceiling (fromIntegral (length charPartMap) / 2 :: Double)
(map1, map2) = splitAt len charPartMap
col1 = vcat left [ text $ [c] ++ ": " ++ drop 4 (show p) | (c, p) <- map1 ]
col2 = vcat left [ text $ [c] ++ ": " ++ drop 4 (show p) | (c, p) <- map2 ]
in render $ hsep 2 top [text "", col1, col2]
charToSheetPart :: Char -> Maybe SheetPart
charToSheetPart c = let
notation = Notation <$> lookup c charPartMap
tab = Tab <$> lookup (toLower c) charPartMap
in notation <|> tab
charToAudioPart :: Char -> Maybe AudioPart
charToAudioPart c = let
only = Only <$> lookup c charPartMap
without = Without . partToInstrument <$> lookup (toLower c) charPartMap
in only <|> without
| mtolly/jammittools | Main.hs | gpl-3.0 | 14,153 | 0 | 26 | 4,188 | 4,516 | 2,321 | 2,195 | 324 | 23 |
{-# LANGUAGE OverloadedStrings #-}
module XMonad.Hooks.DynamicLog.Status.DZen2.Fancy where
import XMonad.Hooks.DynamicLog.Status.System
import XMonad.Hooks.DynamicLog.Status.StatusText
import XMonad.Hooks.DynamicLog.Status.DZen2.Universal
import Control.Monad.IO.Class
colorBattery :: Int -> (String -> StatusText)
colorBattery x
| (x < 15) = fg "red"
| (x < 50) = fg "yellow"
| (x < 90) = fg "green"
| otherwise = fg "blue"
coloredBattery :: (MonadIO m) => m StatusText
coloredBattery = do
batST <- battery
return $ do
batText <- batST
(colorBattery $ read batText) batText
| Fizzixnerd/xmonad-config | site-haskell/src/XMonad/Hooks/DynamicLog/Status/DZen2/Fancy.hs | gpl-3.0 | 605 | 0 | 13 | 104 | 192 | 104 | 88 | 18 | 1 |
module Nucleic.FlatColor (
lightGrey, mediumGrey,
torquoise, emerald, peterriver, amethyst, wetasphalt,
greensea, nephritis, belizehole, wisteria, midnightblue,
sunflower, carrot, alizarin, clouds, concrete,
orange, pumpkin, pomegranate, silver, asbestos
) where
import Nucleic.Color (RGB (..))
-- accent0 = RGB 90 99 120 -- #5A6378 dark grey/blue
-- accent1 = RGB 96 181 204 -- #60B5CC blue
-- accent2 = RGB 240 173 0 -- #F0AD00 yellow
-- accent3 = RGB 234 21 122 -- #EA157A pink
-- accent4 = RGB 127 209 59 -- #7FD13B green
lightGrey, mediumGrey :: RGB
lightGrey = RGB 245 245 245 -- #F5F5F5
mediumGrey = RGB 216 221 225 -- #D8DDE1
-- Flat colors
torquoise, emerald, peterriver, amethyst, wetasphalt :: RGB
torquoise = RGB 26 188 156 -- #1abc9c
emerald = RGB 46 204 113 -- #1abc9c
peterriver = RGB 52 152 219 -- #3498db
amethyst = RGB 155 89 182 -- #9b59b6
wetasphalt = RGB 52 73 94 -- #34495e
greensea, nephritis, belizehole, wisteria, midnightblue :: RGB
greensea = RGB 22 160 133 -- #16a085
nephritis = RGB 39 174 96 -- #27ae60
belizehole = RGB 41 128 185 -- #2980b9
wisteria = RGB 142 68 173 -- #8e44ad
midnightblue = RGB 44 62 80 -- #2c3e50
sunflower, carrot, alizarin, clouds, concrete :: RGB
sunflower = RGB 241 196 15 -- #f1c40f
carrot = RGB 230 126 34 -- #e67e22
alizarin = RGB 231 76 60 -- #e74c3c
clouds = RGB 236 240 241 -- #ecf0f1
concrete = RGB 149 165 166 -- #95a5a6
orange, pumpkin, pomegranate, silver, asbestos :: RGB
orange = RGB 243 156 18 -- #f39c12
pumpkin = RGB 211 84 0 -- #d35400
pomegranate = RGB 192 57 43 -- #c0392b
silver = RGB 189 195 199 -- #bdc3c7
asbestos = RGB 127 140 141 -- #7f8c8d
| RayRacine/nucleic | Nucleic/FlatColor.hs | gpl-3.0 | 1,788 | 0 | 6 | 461 | 439 | 267 | 172 | 34 | 1 |
module Hadolint.Rule.DL3033 (rule) where
import qualified Data.Text as Text
import Hadolint.Rule
import qualified Hadolint.Shell as Shell
import Language.Docker.Syntax
rule :: Rule Shell.ParsedShell
rule = simpleRule code severity message check
where
code = "DL3033"
severity = DLWarningC
message = "Specify version with `yum install -y <package>-<version>`."
check (Run (RunArgs args _)) = foldArguments (all versionFixed . yumPackages) args
check _ = True
versionFixed package =
"-" `Text.isInfixOf` package
|| ".rpm" `Text.isSuffixOf` package
{-# INLINEABLE rule #-}
yumPackages :: Shell.ParsedShell -> [Text.Text]
yumPackages args =
[ arg | cmd <- Shell.presentCommands args, Shell.cmdHasArgs "yum" ["install"] cmd, arg <- Shell.getArgsNoFlags cmd, arg /= "install"
]
| lukasmartinelli/hadolint | src/Hadolint/Rule/DL3033.hs | gpl-3.0 | 821 | 0 | 11 | 151 | 231 | 127 | 104 | 18 | 2 |
{-# 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.DoubleClickBidManager.Sdf.Download
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves entities in SDF format.
--
-- /See:/ <https://developers.google.com/bid-manager/ DoubleClick Bid Manager API Reference> for @doubleclickbidmanager.sdf.download@.
module Network.Google.Resource.DoubleClickBidManager.Sdf.Download
(
-- * REST Resource
SdfDownloadResource
-- * Creating a Request
, sdfDownload
, SdfDownload
-- * Request Lenses
, sdXgafv
, sdUploadProtocol
, sdAccessToken
, sdUploadType
, sdPayload
, sdCallback
) where
import Network.Google.DoubleClickBids.Types
import Network.Google.Prelude
-- | A resource alias for @doubleclickbidmanager.sdf.download@ method which the
-- 'SdfDownload' request conforms to.
type SdfDownloadResource =
"doubleclickbidmanager" :>
"v1.1" :>
"sdf" :>
"download" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] DownloadRequest :>
Post '[JSON] DownloadResponse
-- | Retrieves entities in SDF format.
--
-- /See:/ 'sdfDownload' smart constructor.
data SdfDownload =
SdfDownload'
{ _sdXgafv :: !(Maybe Xgafv)
, _sdUploadProtocol :: !(Maybe Text)
, _sdAccessToken :: !(Maybe Text)
, _sdUploadType :: !(Maybe Text)
, _sdPayload :: !DownloadRequest
, _sdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SdfDownload' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sdXgafv'
--
-- * 'sdUploadProtocol'
--
-- * 'sdAccessToken'
--
-- * 'sdUploadType'
--
-- * 'sdPayload'
--
-- * 'sdCallback'
sdfDownload
:: DownloadRequest -- ^ 'sdPayload'
-> SdfDownload
sdfDownload pSdPayload_ =
SdfDownload'
{ _sdXgafv = Nothing
, _sdUploadProtocol = Nothing
, _sdAccessToken = Nothing
, _sdUploadType = Nothing
, _sdPayload = pSdPayload_
, _sdCallback = Nothing
}
-- | V1 error format.
sdXgafv :: Lens' SdfDownload (Maybe Xgafv)
sdXgafv = lens _sdXgafv (\ s a -> s{_sdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
sdUploadProtocol :: Lens' SdfDownload (Maybe Text)
sdUploadProtocol
= lens _sdUploadProtocol
(\ s a -> s{_sdUploadProtocol = a})
-- | OAuth access token.
sdAccessToken :: Lens' SdfDownload (Maybe Text)
sdAccessToken
= lens _sdAccessToken
(\ s a -> s{_sdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
sdUploadType :: Lens' SdfDownload (Maybe Text)
sdUploadType
= lens _sdUploadType (\ s a -> s{_sdUploadType = a})
-- | Multipart request metadata.
sdPayload :: Lens' SdfDownload DownloadRequest
sdPayload
= lens _sdPayload (\ s a -> s{_sdPayload = a})
-- | JSONP
sdCallback :: Lens' SdfDownload (Maybe Text)
sdCallback
= lens _sdCallback (\ s a -> s{_sdCallback = a})
instance GoogleRequest SdfDownload where
type Rs SdfDownload = DownloadResponse
type Scopes SdfDownload =
'["https://www.googleapis.com/auth/doubleclickbidmanager"]
requestClient SdfDownload'{..}
= go _sdXgafv _sdUploadProtocol _sdAccessToken
_sdUploadType
_sdCallback
(Just AltJSON)
_sdPayload
doubleClickBidsService
where go
= buildClient (Proxy :: Proxy SdfDownloadResource)
mempty
| brendanhay/gogol | gogol-doubleclick-bids/gen/Network/Google/Resource/DoubleClickBidManager/Sdf/Download.hs | mpl-2.0 | 4,473 | 0 | 18 | 1,096 | 711 | 414 | 297 | 103 | 1 |
{-
This file is part of Tractor.
Tractor is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Tractor 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Tractor. If not, see <http://www.gnu.org/licenses/>.
-}
{- |
Module : SBIsecCoJp.Broker
Description : broker
Copyright : (c) 2016 Akihiro Yamamoto
License : AGPLv3
Maintainer : https://github.com/ak1211
Stability : unstable
Portability : POSIX
証券会社とやり取りするモジュールです。
-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TypeFamilies #-}
module SBIsecCoJp.Broker
( siteConn
, noticeOfBrokerageAnnouncement
, noticeOfCurrentAssets
, fetchUpdatedPriceAndStore
) where
import Control.Exception.Safe
import qualified Control.Monad.IO.Class as M
import qualified Control.Monad.Logger as Logger
import qualified Control.Monad.Reader as M
import Control.Monad.Trans.Maybe (MaybeT (..))
import qualified Control.Monad.Trans.Resource as MR
import qualified Data.Conduit as C
import qualified Data.Conduit.List as CL
import qualified Data.Maybe as Maybe
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import Data.Time (UTCTime, ZonedTime (..))
import qualified Data.Time as Time
import Database.Persist ((<.), (==.))
import qualified Database.Persist as DB
import qualified Database.Persist.MySQL as MySQL
import qualified Database.Persist.Sql as DB
import qualified Network.HTTP.Conduit as N
import Network.URI (URI)
import qualified Network.URI as URI
import qualified Safe
import qualified BrokerBackend as BB
import qualified Conf
import qualified GenScraper as GS
import Lib (tzAsiaTokyo)
import qualified Lib
import SBIsecCoJp.Model
import qualified SBIsecCoJp.Scraper as S
import qualified SinkSlack as Slack
-- |
-- runResourceTと組み合わせて証券会社のサイトにログイン/ログアウトする
siteConn :: (Monad m, M.MonadTrans t, MR.MonadResource (t m))
=> Conf.InfoSBIsecCoJp
-> Conf.UserAgent
-> (BB.HTTPSession -> m b)
-> t m b
siteConn conf userAgent f =
MR.allocate (login conf userAgent url) logout
>>= (\(_,session) -> M.lift $ f session)
where
url = "https://k.sbisec.co.jp/bsite/visitor/top.do"
-- |
-- Slackへお知らせを送るついでに現在資産評価をDBへ
noticeOfBrokerageAnnouncement :: M.MonadIO m
=> Conf.InfoSBIsecCoJp
-> MySQL.ConnectInfo
-> Conf.UserAgent
-> C.ConduitT () TL.Text m ()
noticeOfBrokerageAnnouncement conf _ userAgent = do
r <- M.liftIO . MR.runResourceT . siteConn conf userAgent $ go
C.yield r
where
go :: BB.HTTPSession -> IO TL.Text
go sess =
TL.pack . maybe "マーケット情報の取得に失敗しました。" show
<$> runMaybeT (goMarketInfoPage sess)
-- |
-- トップ -> マーケット情報を見に行く関数
goMarketInfoPage :: BB.HTTPSession -> MaybeT IO S.MarketInfoPage
goMarketInfoPage sess =
MaybeT . return . S.marketInfoPage =<< fetchLinkPage noWaitFetch sess "マーケット情報"
-- |
-- DBから最新の資産評価を取り出してSlackへレポートを送る
noticeOfCurrentAssets :: M.MonadIO m
=> MySQL.ConnectInfo
-> C.ConduitT () Slack.Report m ()
noticeOfCurrentAssets connInfo = do
-- 今日の前場開始時間
openingTime <- todayOpeningTime <$> M.liftIO Time.getCurrentTime
-- データーベースの内容からレポートを作る
rpt <- M.liftIO
. Logger.runNoLoggingT . MR.runResourceT
. MySQL.withMySQLConn connInfo . MySQL.runSqlConn $ do
DB.runMigration migrateSBIsecCoJp
--
yesterday <- takeBeforeAsset openingTime
latest <- takeLatestAsset
report <- M.mapM
(makeReport yesterday)
(latest :: Maybe (DB.Entity SbiseccojpAsset))
return $ Maybe.maybeToList (report :: Maybe Slack.Report)
-- Slackへレポートを送る
CL.sourceList rpt
where
-- |
-- 今日の前場開始時間
todayOpeningTime :: UTCTime -> UTCTime
todayOpeningTime =
Time.zonedTimeToUTC
. (\(ZonedTime t z) -> ZonedTime
(t { Time.localTimeOfDay = Time.TimeOfDay 9 00 00}) z)
. Time.utcToZonedTime Lib.tzAsiaTokyo
-- |
-- レポートを作る関数
makeReport yesterday (DB.Entity key asset) = do
-- 保有株式を取り出す
stocks <- takeStocks key
--
return Slack.Report
{ Slack.reportAt = sbiseccojpAssetAt asset
, Slack.reportAllAsset = allAsset asset
-- 現在値 - 前営業日値
, Slack.reportGrowthToday = (\y -> allAsset asset - allAsset y) <$> yesterday
, Slack.reportAllProfit = sbiseccojpAssetProfit asset
, Slack.reportStockDigests =
[Slack.StockDigest (sbiseccojpStockAt s) (sbiseccojpStockGain s) (sbiseccojpStockDigest s) | s<-stocks]
}
-- |
-- DBから最新の資産評価を取り出す
takeLatestAsset =
DB.selectFirst [] [DB.Desc SbiseccojpAssetAt]
-- |
-- DBから保有株式を取り出す
takeStocks key =
fmap DB.entityVal
<$>
DB.selectList
[SbiseccojpStockAsset ==. key]
[DB.Asc SbiseccojpStockTicker]
-- |
-- DBから前場開始直前の資産評価を取り出す
takeBeforeAsset openingTime =
fmap DB.entityVal
<$>
DB.selectFirst
[SbiseccojpAssetAt <. openingTime]
[DB.Desc SbiseccojpAssetAt]
-- |
-- 全財産(現金換算)を返す関数
-- 株式資産評価合計 + 使用可能現金
allAsset :: SbiseccojpAsset -> Double
allAsset a =
sbiseccojpAssetEvaluation a + realToFrac (sbiseccojpAssetCashBalance a)
-- |
-- 現在資産評価を証券会社のサイトから取得してDBへ
fetchUpdatedPriceAndStore :: MySQL.ConnectInfo
-> BB.HTTPSession
-> IO ()
fetchUpdatedPriceAndStore connInfo sess@BB.HTTPSession{..} = do
let mbfn a b = maybe (throwString a) return =<< runMaybeT b
-- トップ -> 買付余力を見に行く
pmlPages <- mbfn "買付余力ページの取得に失敗しました"goPurchaseMarginListPage
-- 先頭の買付余力しかいらないので
let pmlist = S.PurchaseMarginListPage
. (\(S.PurchaseMarginListPage xs) -> take 1 xs) $ pmlPages
-- トップ -> 買付余力 -> 詳細を見に行く関数
pmdPages <- mbfn "買付余力 -> 詳細ページの取得に失敗しました" $ goPurchaseMarginDetailPage pmlist
let pmdPage = Safe.headNote "買付余力/詳細の数が不足" pmdPages
-- サーバーに対して過度なアクセスを控えるための時間待ち
BB.waitMS 600
-- トップ -> 保有証券一覧を見に行く
hslPage <- mbfn "保有証券一覧ページの取得に失敗しました" goHoldStockListPage
-- トップ -> 保有証券一覧 -> 保有証券詳細ページを見に行く
stocks <- mbfn "保有証券詳細ページの取得に失敗しました" $ goHoldStockDetailPage hslPage
-- 受信時間
tm <- Time.getCurrentTime
let (year,_,_) = Time.toGregorian (Time.utctDay tm)
-- 全てをデーターベースへ
Logger.runStderrLoggingT . MR.runResourceT . MySQL.withMySQLConn connInfo . MySQL.runSqlConn $ do
DB.runMigration migrateSBIsecCoJp
-- 資産テーブルへ格納する
key <- DB.insert $ asset tm hslPage pmdPage
-- 保有株式テーブルへ格納する(寄っている場合のみ)
M.mapM_ DB.insert . Maybe.mapMaybe (stock year key) $ stocks
where
-- |
-- 資産テーブル情報を組み立てる
asset :: UTCTime -> S.HoldStockListPage -> S.PurchaseMarginDetailPage -> SbiseccojpAsset
asset at hslp pmdp = SbiseccojpAsset
{ sbiseccojpAssetAt = at
, sbiseccojpAssetEvaluation = S.hslEvaluation hslp
, sbiseccojpAssetProfit = S.hslProfit hslp
--
, sbiseccojpAssetMoneySpare = S.pmdMoneyToSpare pmdp
, sbiseccojpAssetCashBalance= S.pmdCashBalance pmdp
}
-- |
-- 保有株式テーブル情報を組み立てる
-- まだ寄っていない値を元に作らない
stock :: Integer -> DB.Key SbiseccojpAsset -> S.HoldStockDetailPage -> Maybe SbiseccojpStock
stock year key S.HoldStockDetailPage{..} = do
(month, day, hour, minute) <- hsdMDHourMin
d <- Time.fromGregorianValid year month day
t <- Time.makeTimeOfDayValid hour minute 0
let lt = Time.LocalTime {Time.localDay = d, Time.localTimeOfDay = t}
Just SbiseccojpStock
{ sbiseccojpStockAsset = key
, sbiseccojpStockAt = Time.localTimeToUTC tzAsiaTokyo lt
, sbiseccojpStockTicker = hsdTicker
, sbiseccojpStockCaption = T.unpack hsdCaption
, sbiseccojpStockCount = hsdCount
, sbiseccojpStockPurchase = hsdPurchasePrice
, sbiseccojpStockPrice = hsdPrice
}
-- |
-- トップ / 保有証券一覧を見に行く関数
goHoldStockListPage :: MaybeT IO S.HoldStockListPage
goHoldStockListPage =
MaybeT . return . S.holdStockListPage =<< fetchLinkPage slowlyFetch sess "保有証券一覧"
-- |
-- トップ -> 保有証券一覧 -> 保有証券詳細ページを見に行く関数
goHoldStockDetailPage :: S.HoldStockListPage
-> MaybeT IO [S.HoldStockDetailPage]
goHoldStockDetailPage page =
-- 詳細ページをスクレイピングする
MaybeT . return . M.mapM S.holdStockDetailPage
-- 詳細ページへアクセスする
=<< M.mapM (slowlyFetch sess) . mapAbsUri . S.unHoldStockDetailLink . S.hslLinks
=<< pure page
-- |
-- トップ -> 買付余力を見に行く関数
goPurchaseMarginListPage :: MaybeT IO S.PurchaseMarginListPage
goPurchaseMarginListPage =
S.purchaseMarginListPage <$> fetchLinkPage slowlyFetch sess "買付余力"
-- |
-- トップ -> 買付余力 -> 詳細を見に行く関数
goPurchaseMarginDetailPage :: S.PurchaseMarginListPage
-> MaybeT IO [S.PurchaseMarginDetailPage]
goPurchaseMarginDetailPage page =
-- 詳細ページをスクレイピングする
MaybeT . return . M.mapM S.purchaseMarginDetailPage
-- 詳細ページへアクセスする
=<< M.mapM (slowlyFetch sess) . mapAbsUri . unpack =<< pure page
where
unpack (S.PurchaseMarginListPage x) = x
-- |
-- リンク情報からURIに写す
mapAbsUri :: [GS.AnchorTag] -> [URI]
mapAbsUri =
Maybe.mapMaybe (BB.toAbsoluteURI sLoginPageURI . T.unpack . GS.aHref)
-- |
-- リンクのページへアクセスする関数
fetchLinkPage :: (BB.HTTPSession -> URI -> MaybeT IO TL.Text)
-> BB.HTTPSession -> T.Text -> MaybeT IO TL.Text
fetchLinkPage fetcher sess t =
fetcher sess =<< MaybeT . return . lookupLinkOnTopPage sess =<< pure t
-- |
-- トップページ上のリンクテキストに対応したURIを返す
lookupLinkOnTopPage :: BB.HTTPSession -> T.Text -> Maybe URI
lookupLinkOnTopPage BB.HTTPSession{..} linktext =
BB.toAbsoluteURI sLoginPageURI . T.unpack
=<< lookup linktext [(GS.aText a, GS.aHref a) | a<-S.unTopPage $ S.topPage sTopPageHTML]
-- |
-- 通常のfetch
noWaitFetch :: M.MonadIO m => BB.HTTPSession -> URI -> m TL.Text
noWaitFetch =
BB.fetchPageWithSession
-- |
-- 時間待ち付きfetch
slowlyFetch :: M.MonadIO m => BB.HTTPSession -> URI -> m TL.Text
slowlyFetch x y = noWaitFetch x y <* M.liftIO (BB.waitMS 300)
-- |
-- ログインページからログインしてHTTPセッション情報を返す関数
login :: Conf.InfoSBIsecCoJp -> Conf.UserAgent -> String -> IO BB.HTTPSession
login conf userAgent loginPageURL = do
loginURI <- maybe errInvalidUrl return (URI.parseURI loginPageURL)
-- HTTPS接続ですよ
manager <- N.newManager N.tlsManagerSettings
-- ログインページへアクセスする
loginPage <- BB.takeBodyFromResponse <$>
BB.fetchHTTP manager reqHeader Nothing [] loginURI
-- ログインページをスクレイピングする
loginForm <- S.formLoginPage loginPage
-- IDとパスワードを入力する
let postMsg = BB.mkCustomPostReq
(map GS.toPairNV $ GS.formInputTag loginForm)
[ ("username", Conf.loginID $ Conf.unInfoSBIsecCoJp conf)
, ("password", Conf.loginPassword $ Conf.unInfoSBIsecCoJp conf)
]
-- フォームのaction属性ページ
let formAction = T.unpack $ GS.formAction loginForm
postto <- maybe loginFail return $ BB.toAbsoluteURI loginURI formAction
-- 提出
resp <- BB.fetchHTTP manager reqHeader Nothing postMsg postto
-- 受け取ったセッションクッキーとトップページを返却する
return BB.HTTPSession
{ BB.sLoginPageURI = loginURI
, BB.sManager = manager
, BB.sReqHeaders = reqHeader
, BB.sRespCookies = N.responseCookieJar resp
, BB.sTopPageHTML = BB.takeBodyFromResponse resp
}
where
-- |
-- HTTPリクエストヘッダ
reqHeader = Lib.httpRequestHeader userAgent
--
--
errInvalidUrl =
throwString $ loginPageURL ++ " は有効なURLではありません"
--
--
loginFail =
throwString $ loginPageURL ++ " にログインできませんでした"
-- |
-- ログアウトする関数
logout :: BB.HTTPSession -> IO ()
logout sess@BB.HTTPSession{..} =
let topPageLinks = S.topPage sTopPageHTML
logoutLink = lookup "ログアウト" [(GS.aText a, GS.aHref a) | a<-S.unTopPage topPageLinks]
toLogoutURI = BB.toAbsoluteURI sLoginPageURI . T.unpack
in
case toLogoutURI =<< logoutLink of
Nothing -> logoutFail
Just uri ->
-- ログアウトページへアクセスする
M.void $ BB.fetchPageWithSession sess uri
where
--
--
logoutFail =
throwString "ログアウトリンクがわかりませんでした"
| ak1211/tractor | src/SBIsecCoJp/Broker.hs | agpl-3.0 | 15,718 | 0 | 17 | 3,922 | 2,920 | 1,551 | 1,369 | 225 | 2 |
module Codewars.Kata.FactorialTail where
import Data.List (group)
import Control.Arrow ((&&&))
zeroes :: Integral a => a -> a -> a
zeroes base n = minimum . ((f . (head &&& length)) <$>) . group . pd $ base
where f (a, b) = (`div` fromIntegral b) . sum . ((n `div`) <$>) $ [a ^ i | i <- [1 .. floor (fromIntegral a `logBase` fromIntegral n)]]
pd x | x == 1 = [ ]
| null d = [x]
| True = head d : pd (div x $ head d)
where d = filter ((== 0) . (x `mod`)) [2 .. floor $ sqrt $ fromIntegral $ x]
--
| ice1000/OI-codes | codewars/301-400/factorial-tail.hs | agpl-3.0 | 560 | 0 | 15 | 175 | 294 | 162 | 132 | 10 | 1 |
module Main where
import Prelude as P hiding ((.), id)
import System.Console.GetOpt
import System.Environment
import System.FilePath.Posix
import Control.Applicative
import Control.Category
import qualified Data.ByteString as B
import Text.CSV
import Types
import Conduits
--Run main program, either encoding or decoding
run (Config end typs enc outFile) inFile =
coding end typs inFile outFile where
coding = case enc of
CSV -> csvToBinary
Binary -> binaryToCSV
options :: [OptDescr (Config -> IO Config)]
options =
[
Option ['c'] ["configFile"]
(ReqArg (\ arg option -> do
contents <- parseCSVFromFile arg
case contents of
Left err -> error $ show err
Right (typeNames:rest) -> do
let typs = map read typeNames
return $ option {types = typs})
"FILE")
"configuration file",
Option ['l'] ["little"]
(NoArg (\ option -> return $ option {endianess = LE}))
"uses little endian encoding instead of big endian",
Option ['o'] ["output"]
(ReqArg (\ arg option -> return $ option {outputFile = arg})
"FILE")
"output file name",
Option ['d'] ["coding"]
(NoArg (\ option -> return $ option {coding = Binary}))
"encode or decode"
]
main = do
args <- getArgs
case getOpt Permute options args of
--Arguments correctly parsed
(opts, inFile:[], []) -> do
--Make changes to default configuration
config <- foldl (>>=) (return defaultConfig) opts
--run program
run config inFile
--Arguments not valid
(_, nonOpts, []) -> error $
"Unrecognized arguments: " ++ unwords nonOpts
--Other errors
(_, _, msgs) -> error $
concat msgs ++ usageInfo "" options
| nsmryan/BIC | Main.hs | unlicense | 1,866 | 0 | 21 | 570 | 540 | 295 | 245 | 49 | 3 |
module Algo.List (
splitAts,
interswap,
interswapInRange,
slice,
inRange,
rangeSize,
shrinkRange,
splits
) where
import Control.Monad (MonadPlus(..))
tuple2ToList tpl = case tpl of
(p,r) -> [p,r]
splitAts :: [Int] -> [a] -> [[a]]
splitAts ids lst = go ids lst 0
where go [i] lst n = tuple2ToList $ splitAt (i-n) lst
go (i:is) lst n = case (splitAt (i-n) lst) of
(p,r) -> p:(go is r i)
interswap :: [a] -> Int -> [a]
interswap xs i = interswapInRange xs (0, length xs - 1) i
interswapInRange :: [a] -> (Int,Int) -> Int -> [a]
interswapInRange [] (p,r) i = []
interswapInRange xs (p,r) i = case splitAts [p,i,r+1] xs of
[xs1, xs2, xs3, xs4] -> xs1 ++ xs3 ++ xs2 ++ xs4
isOrdered:: (Ord a) => [a] -> Bool
isOrdered [] = True
isOrdered [a] = True
isOrdered (x:y:xs) = if (x <= y) then isSucc xs else isPrev xs
isSucc [] = True
isSucc [a] = True
isSucc (x:y:xs) = if (x<=y) then isSucc xs else False
isPrev [] = True
isPrev [a] = True
isPrev (x:y:xs) = if (x>=y) then isPrev xs else False
slice :: [a] -> (Int, Int) -> [a]
slice xs (p,r) = take (r-p+1) (drop p xs)
inRange :: Int -> (Int,Int) -> Bool
inRange x (p,r) = p <= x && x <= r
rangeSize (p,r) = (r-p+1)
shrinkRange (p,r) i = (p+i,r-i)
splits :: MonadPlus m => [a] -> m (a, [a])
splits [] = mzero
splits (a:x) = return (a,x) `mplus`
do (b,x') <- splits x
return (b, a:x')
| seckcoder/lang-learn | haskell/algo/src/Algo/List.hs | unlicense | 1,469 | 0 | 12 | 403 | 853 | 469 | 384 | 44 | 2 |
-----------------------------------------------------------------------------
-- Copyright 2019, Ideas project team. This file is distributed under the
-- terms of the Apache License 2.0. For more information, see the files
-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution.
-----------------------------------------------------------------------------
-- |
-- Maintainer : bastiaan.heeren@ou.nl
-- Stability : provisional
-- Portability : portable (depends on ghc)
--
-- Converting a strategy to XML, and the other way around.
--
-----------------------------------------------------------------------------
module Ideas.Encoding.StrategyInfo (strategyToXML) where
import Data.Monoid
import Ideas.Common.Id
import Ideas.Common.Strategy.Abstract
import Ideas.Common.Strategy.Configuration
import Ideas.Common.Strategy.CyclicTree
import Ideas.Common.Strategy.StrategyTree (StrategyTree)
import Ideas.Text.XML
-----------------------------------------------------------------------
-- Strategy to XML
strategyToXML :: IsStrategy f => f a -> XML
strategyToXML = strategyTreeToXML . toStrategyTree
nameAttr :: Id -> XMLBuilder
nameAttr info = "name" .=. showId info
strategyTreeToXML :: StrategyTree a -> XML
strategyTreeToXML tree = makeXML "label" $
case isLabel tree of
Just (l, a) -> nameAttr l <> strategyTreeBuilder a
_ -> strategyTreeBuilder tree
strategyTreeBuilder :: StrategyTree a -> XMLBuilder
strategyTreeBuilder = builder . fold emptyAlg
{ fNode = \def xs ->
case xs of
[x] | isConfigId def
-> addProperty (show def) x
_ -> makeXML (show def) (mconcat (map builder xs))
, fLeaf = \r ->
makeXML "rule" ("name" .=. show r)
, fLabel = \l a ->
makeXML "label" (nameAttr l <> builder a)
, fRec = \n a ->
makeXML "rec" (("var" .=. show n) <> builder a)
, fVar = \n ->
makeXML "var" ("var" .=. show n)
}
addProperty :: String -> XML -> XML
addProperty s a =
if name a `elem` ["label", "rule"]
then a { attributes = attributes a ++ [s := "true"] }
else a
-----------------------------------------------------------------------
-- XML to strategy
{-
xmlToStrategy :: Monad m => (String -> Maybe (Rule a)) -> XML -> m (Strategy a)
xmlToStrategy f = liftM fromCore . readStrategy xmlToInfo g
where
g info = case f (showId info) of
Just r -> return r
Nothing -> fail $ "Unknown rule: " ++ showId info
xmlToInfo :: Monad m => XML -> m Id
xmlToInfo xml = do
n <- findAttribute "name" xml
-- let boolAttr s = fromMaybe False (findBool s xml)
return (newId n)
findBool :: Monad m => String -> XML -> m Bool
findBool attr xml = do
s <- findAttribute attr xml
case map toLower s of
"true" -> return True
"false" -> return False
_ -> fail "not a boolean"
readStrategy :: Monad m => (XML -> m Id) -> (Id -> m (Rule a)) -> XML -> m (Core a)
readStrategy toLabel findRule xml = error "not implemented" do
xs <- mapM (readStrategy toLabel findRule) (children xml)
let s = name xml
case lookup s table of
Just f -> f s xs
Nothing ->
fail $ "Unknown strategy combinator " ++ show s
where
buildSequence _ xs
| null xs = return Succeed
| otherwise = return (foldr1 (:*:) xs)
buildChoice _ xs
| null xs = return Fail
| otherwise = return (foldr1 (:|:) xs)
buildOrElse _ xs
| null xs = return Fail
| otherwise = return (foldr1 (:|>:) xs)
buildInterleave _ xs
| null xs = return succeedCore
| otherwise = return (foldr1 (:%:) xs)
buildLabel x = do
info <- toLabel xml
return (Label info x)
buildRule = do
info <- toLabel xml
r <- findRule info
return (Label info (Sym r))
buildVar = do
s <- findAttribute "var" xml
i <- maybe (fail "var: not an int") return (readInt s)
return (Var i)
comb0 a _ [] = return a
comb0 _ s _ = fail $ "Strategy combinator " ++ s ++ "expects 0 args"
comb1 f _ [x] = return (f x)
comb1 _ s _ = fail $ "Strategy combinator " ++ s ++ "expects 1 arg"
join2 f g a b = join (f g a b)
table =
[ ("sequence", buildSequence)
, ("choice", buildChoice)
, ("orelse", buildOrElse)
, ("interleave", buildInterleave)
, ("label", join2 comb1 buildLabel)
-- , ("atomic", comb1 Atomic)
, ("rule", join2 comb0 buildRule)
, ("var", join2 comb0 buildVar)
-- , ("succeed", comb0 Succeed)
--, ("fail", comb0 Fail)
]
-} | ideas-edu/ideas | src/Ideas/Encoding/StrategyInfo.hs | apache-2.0 | 4,771 | 0 | 17 | 1,320 | 492 | 271 | 221 | 37 | 2 |
{-# LANGUAGE RebindableSyntax #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ViewPatterns #-}
{-
Copyright 2018 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Internal.Color where
import qualified "codeworld-api" CodeWorld as CW
import Internal.Num
import Internal.Truth
import qualified "base" Prelude as P
import "base" Prelude ((.))
newtype Color =
RGBA (Number, Number, Number, Number)
deriving (P.Eq)
type Colour = Color
{-# RULES
"equality/color" forall (x :: Color) . (==) x = (P.==) x
#-}
pattern RGB :: (Number, Number, Number) -> Color
pattern RGB components <- (toRGB -> P.Just components)
where RGB components
= let (r, g, b) = components in RGBA (r, g, b, 1)
-- Utility function for RGB pattern synonym.
toRGB :: Color -> P.Maybe (Number, Number, Number)
toRGB (RGBA (r, g, b, 1)) = P.Just (r, g, b)
toRGB _ = P.Nothing
pattern HSL :: (Number, Number, Number) -> Color
pattern HSL components <- (toHSL -> P.Just components)
where HSL components = fromHSL components
-- Utility functions for HSL pattern synonym.
toHSL :: Color -> P.Maybe (Number, Number, Number)
toHSL c@(RGBA (_, _, _, 1)) = P.Just (hue c, saturation c, luminosity c)
toHSL _ = P.Nothing
fromHSL :: (Number, Number, Number) -> Color
fromHSL (h, s, l) =
fromCWColor (CW.HSL (toDouble (pi * h / 180)) (toDouble s) (toDouble l))
{-# WARNING
fromHSL "Please use HSL instead of fromHSL."
#-}
toCWColor :: Color -> CW.Color
toCWColor (RGBA (r, g, b, a)) =
CW.RGBA (toDouble r) (toDouble g) (toDouble b) (toDouble a)
fromCWColor :: CW.Color -> Color
fromCWColor (CW.RGBA r g b a) =
RGBA (fromDouble r, fromDouble g, fromDouble b, fromDouble a)
white, black :: Color
white = fromCWColor CW.white
black = fromCWColor CW.black
-- Primary and secondary colors
red, green, blue, cyan, magenta, yellow :: Color
red = fromCWColor CW.red
yellow = fromCWColor CW.yellow
green = fromCWColor CW.green
cyan = fromCWColor CW.cyan
blue = fromCWColor CW.blue
magenta = fromCWColor CW.magenta
-- Tertiary colors
orange, rose, chartreuse, aquamarine, violet, azure :: Color
orange = fromCWColor CW.orange
chartreuse = fromCWColor CW.chartreuse
aquamarine = fromCWColor CW.aquamarine
azure = fromCWColor CW.azure
violet = fromCWColor CW.violet
rose = fromCWColor CW.rose
-- Other common colors and color names
brown = fromCWColor CW.brown
purple = fromCWColor CW.purple
pink = fromCWColor CW.pink
mixed :: (Color, Color) -> Color
mixed (a, b) = fromCWColor (CW.mixed (toCWColor a) (toCWColor b))
lighter :: (Color, Number) -> Color
lighter (c, d) = fromCWColor (CW.lighter (toDouble d) (toCWColor c))
light :: Color -> Color
light = fromCWColor . CW.light . toCWColor
darker :: (Color, Number) -> Color
darker (c, d) = fromCWColor (CW.darker (toDouble d) (toCWColor c))
dark :: Color -> Color
dark = fromCWColor . CW.dark . toCWColor
brighter :: (Color, Number) -> Color
brighter (c, d) = fromCWColor (CW.brighter (toDouble d) (toCWColor c))
bright :: Color -> Color
bright = fromCWColor . CW.bright . toCWColor
duller :: (Color, Number) -> Color
duller (c, d) = fromCWColor (CW.duller (toDouble d) (toCWColor c))
dull :: Color -> Color
dull = fromCWColor . CW.dull . toCWColor
translucent :: Color -> Color
translucent = fromCWColor . CW.translucent . toCWColor
gray, grey :: Number -> Color
gray = fromCWColor . CW.gray . toDouble
grey = gray
assortedColors :: [Color]
assortedColors = P.map fromCWColor CW.assortedColors
hue, saturation, luminosity, alpha :: Color -> Number
hue = (180 *) . (/ pi) . fromDouble . CW.hue . toCWColor
saturation = fromDouble . CW.saturation . toCWColor
luminosity = fromDouble . CW.luminosity . toCWColor
alpha = fromDouble . CW.alpha . toCWColor
| tgdavies/codeworld | codeworld-base/src/Internal/Color.hs | apache-2.0 | 4,344 | 0 | 12 | 773 | 1,342 | 749 | 593 | 91 | 1 |
module {-# REL #-} BottomHidden (
HiddenType(..)
) where
-- This is hidden only at the package level, but we're not using packages...
newtype HiddenType = Hide String deriving Show
| dimitri-xyz/relative-imports-test-bottom | BottomHidden.hs | apache-2.0 | 188 | 0 | 5 | 37 | 26 | 18 | 8 | 3 | 0 |
module Main where
import Data.List (genericLength)
import Data.Maybe (catMaybes)
import System.Console.ANSI
import System.Exit (exitFailure, exitSuccess)
import System.Process (readProcessWithExitCode)
import Text.Regex (matchRegex, mkRegex)
average :: (Fractional a, Real b) => [b] -> a
average xs = realToFrac (sum xs) / genericLength xs
expected :: Fractional a => a
expected = 5
main :: IO ()
main = do
(_, sout, serr) <- readProcessWithExitCode "stack" ["haddock", "--no-haddock-deps"] ""
let
output = sout ++ serr
printDocCoverage output
if (average (match output) :: Double) >= expected
then do
setSGR [SetColor Foreground Dull Green]
putStrLn "Documentation coverage OK"
setSGR []
exitSuccess
else do
setSGR [SetColor Foreground Dull Red]
putStrLn "Documentation coverage FAIL"
setSGR []
exitFailure
where
printDocCoverage output = do
setSGR [SetColor Foreground Dull Yellow]
putStrLn "--- BEGIN Documentation coverage ---"
setSGR []
putStr . unlines . map (" "++) $ lines output
setSGR [SetColor Foreground Dull Yellow]
putStrLn "--- END Documentation coverage ---"
setSGR []
match :: String -> [Int]
match = fmap read . concat . catMaybes . fmap f . lines
where
f = matchRegex $ mkRegex "^ *([0-9]*)% "
| listx/miro | test/doc-coverage.hs | bsd-2-clause | 1,325 | 0 | 12 | 290 | 441 | 218 | 223 | 39 | 2 |
{-# LANGUAGE BangPatterns #-}
module Network.Wai.Handler.Warp.MultiMap (
MultiMap
, isEmpty
, empty
, singleton
, insert
, Network.Wai.Handler.Warp.MultiMap.lookup
, pruneWith
, toList
, merge
) where
import Data.Hashable (hash)
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as I
import Data.Semigroup
import Prelude -- Silence redundant import warnings
----------------------------------------------------------------
-- | 'MultiMap' is used for cache of file descriptors.
-- Since multiple threads would open file descriptors for
-- the same file simultaneously, multiple entries must
-- be contained for the file.
-- Since hash values of file pathes are used as outer keys,
-- collison would happen for multiple file pathes.
-- Becase only positive entries are contained,
-- a bad guy cannot be cause the hash collision intentinally.
-- So, lists are good enough.
newtype MultiMap v = MultiMap (IntMap [(FilePath,v)])
----------------------------------------------------------------
-- | O(1)
empty :: MultiMap v
empty = MultiMap $ I.empty
-- | O(1)
isEmpty :: MultiMap v -> Bool
isEmpty (MultiMap mm) = I.null mm
----------------------------------------------------------------
-- | O(1)
singleton :: FilePath -> v -> MultiMap v
singleton path v = MultiMap mm
where
!h = hash path
!mm = I.singleton h [(path,v)]
----------------------------------------------------------------
-- | O(N)
lookup :: FilePath -> MultiMap v -> Maybe v
lookup path (MultiMap mm) = case I.lookup h mm of
Nothing -> Nothing
Just s -> Prelude.lookup path s
where
!h = hash path
----------------------------------------------------------------
-- | O(log n)
insert :: FilePath -> v -> MultiMap v -> MultiMap v
insert path v (MultiMap mm) = MultiMap mm'
where
!h = hash path
!mm' = I.insertWith (<>) h [(path,v)] mm
----------------------------------------------------------------
-- | O(n)
toList :: MultiMap v -> [(FilePath,v)]
toList (MultiMap mm) = concatMap snd $ I.toAscList mm
----------------------------------------------------------------
-- | O(n)
pruneWith :: MultiMap v
-> ((FilePath,v) -> IO Bool)
-> IO (MultiMap v)
pruneWith (MultiMap mm) action = MultiMap <$> mm'
where
!mm' = I.fromAscList <$> go (I.toDescList mm) []
go [] !acc = return acc
go ((h,s):kss) !acc = do
rs <- prune action s
case rs of
[] -> go kss acc
_ -> go kss ((h,rs) : acc)
----------------------------------------------------------------
-- O(n + m) where N is the size of the second argument
merge :: MultiMap v -> MultiMap v -> MultiMap v
merge (MultiMap m1) (MultiMap m2) = MultiMap mm
where
!mm = I.unionWith (<>) m1 m2
----------------------------------------------------------------
prune :: ((FilePath,v) -> IO Bool) -> [(FilePath,v)] -> IO [(FilePath,v)]
prune action xs0 = go xs0
where
go [] = return []
go (x:xs) = do
keep <- action x
rs <- go xs
return $ if keep then x:rs else rs
| sordina/wai | warp/Network/Wai/Handler/Warp/MultiMap.hs | bsd-2-clause | 3,104 | 0 | 15 | 649 | 848 | 451 | 397 | 57 | 3 |
{-# LANGUAGE CPP, FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Common helper functions and instances for all Ganeti tests.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Test.Ganeti.TestCommon
( maxMem
, maxDsk
, maxCpu
, maxSpindles
, maxVcpuRatio
, maxSpindleRatio
, maxNodes
, maxOpCodes
, (==?)
, (/=?)
, failTest
, passTest
, stableCover
, pythonCmd
, runPython
, checkPythonResult
, DNSChar(..)
, genPrintableAsciiChar
, genPrintableAsciiString
, genPrintableAsciiStringNE
, genPrintableByteString
, genName
, genFQDN
, genUUID
, genMaybe
, genSublist
, genMap
, genTags
, genFields
, genUniquesList
, SmallRatio(..)
, genSetHelper
, genSet
, genListSet
, genAndRestArguments
, genIPv4Address
, genIPv4Network
, genIp6Addr
, genIp6Net
, genOpCodesTagName
, genLuxiTagName
, netmask2NumHosts
, testSerialisation
, testArraySerialisation
, testDeserialisationFail
, resultProp
, readTestData
, genSample
, testParser
, genPropParser
, genNonNegative
, relativeError
, getTempFileName
, listOfUniqueBy
, counterexample
, cover'
) where
import Control.Exception (catchJust)
import Control.Monad
import Control.Monad.Fail (MonadFail, fail)
import Data.Attoparsec.Text (Parser, parseOnly)
import Data.List
import qualified Data.Map as M
import Data.Text (pack)
import Data.Word
import qualified Data.ByteString as BS
import qualified Data.ByteString.UTF8 as UTF8
#if !MIN_VERSION_QuickCheck(2,10,0)
import Data.Char (isPrint)
#endif
import qualified Data.Set as Set
import System.Directory (getTemporaryDirectory, removeFile)
import System.Environment (getEnv)
import System.Exit (ExitCode(..))
import System.IO (hClose, openTempFile)
import System.IO.Error (isDoesNotExistError)
import System.Process (readProcessWithExitCode)
import qualified Test.HUnit as HUnit
import Test.QuickCheck
import Test.QuickCheck.Monadic
import qualified Text.JSON as J
import Numeric
import qualified Ganeti.BasicTypes as BasicTypes
import Ganeti.JSON (ArrayObject(..))
import Ganeti.Objects (TagSet(..))
import Ganeti.Types
import Ganeti.Utils.Monad (unfoldrM)
-- * Compatibility instances
instance MonadFail Gen where
fail = error "No monadfail instance"
instance MonadFail (Either String) where
fail x = Left x
-- * Arbitrary orphan instances
instance Arbitrary TagSet where
arbitrary = (TagSet . Set.fromList) <$> genTags
-- * Constants
-- | Maximum memory (1TiB, somewhat random value).
maxMem :: Int
maxMem = 1024 * 1024
-- | Maximum disk (8TiB, somewhat random value).
maxDsk :: Int
maxDsk = 1024 * 1024 * 8
-- | Max CPUs (1024, somewhat random value).
maxCpu :: Int
maxCpu = 1024
-- | Max spindles (1024, somewhat random value).
maxSpindles :: Int
maxSpindles = 1024
-- | Max vcpu ratio (random value).
maxVcpuRatio :: Double
maxVcpuRatio = 1024.0
-- | Max spindle ratio (random value).
maxSpindleRatio :: Double
maxSpindleRatio = 1024.0
-- | Max nodes, used just to limit arbitrary instances for smaller
-- opcode definitions (e.g. list of nodes in OpTestDelay).
maxNodes :: Int
maxNodes = 32
-- | Max opcodes or jobs in a submit job and submit many jobs.
maxOpCodes :: Int
maxOpCodes = 16
-- * Helper functions
-- | Checks for equality with proper annotation. The first argument is
-- the computed value, the second one the expected value.
(==?) :: (Show a, Eq a) => a -> a -> Property
(==?) x y = counterexample
("Expected equality, but got mismatch\nexpected: " ++
show y ++ "\n but got: " ++ show x) (x == y)
infix 3 ==?
-- | Checks for inequality with proper annotation. The first argument
-- is the computed value, the second one the expected (not equal)
-- value.
(/=?) :: (Show a, Eq a) => a -> a -> Property
(/=?) x y = counterexample
("Expected inequality, but got equality: '" ++
show x ++ "'.") (x /= y)
infix 3 /=?
-- | Show a message and fail the test.
failTest :: String -> Property
failTest msg = counterexample msg False
-- | A 'True' property.
passTest :: Property
passTest = property True
-- | QuickCheck 2.12 swapped the order of the first two arguments, so provide a
-- compatibility function here
cover' :: Testable prop => Double -> Bool -> String -> prop -> Property
#if MIN_VERSION_QuickCheck(2, 12, 0)
cover' = cover
#else
cover' p x = cover x (round p)
#endif
-- | A stable version of QuickCheck's `cover`. In its current implementation,
-- cover will not detect insufficient coverage if the actual coverage in the
-- sample is 0. Work around this by lifting the probability to at least
-- 10 percent.
-- The underlying issue is tracked at
-- https://github.com/nick8325/quickcheck/issues/26
stableCover :: Testable prop => Bool -> Double -> String -> prop -> Property
stableCover p percent s prop =
let newlabel = "(stabilized to at least 10%) " ++ s
in forAll (frequency [(1, return True), (9, return False)]) $ \ basechance ->
cover' (10 + (percent * 9 / 10)) (basechance || p) newlabel prop
-- | Return the python binary to use. If the PYTHON environment
-- variable is defined, use its value, otherwise use just \"python3\".
pythonCmd :: IO String
pythonCmd = catchJust (guard . isDoesNotExistError)
(getEnv "PYTHON") (const (return "python3"))
-- | Run Python with an expression, returning the exit code, standard
-- output and error.
runPython :: String -> String -> IO (ExitCode, String, String)
runPython expr stdin = do
py_binary <- pythonCmd
readProcessWithExitCode py_binary ["-c", expr] stdin
-- | Check python exit code, and fail via HUnit assertions if
-- non-zero. Otherwise, return the standard output.
checkPythonResult :: (ExitCode, String, String) -> IO String
checkPythonResult (py_code, py_stdout, py_stderr) = do
HUnit.assertEqual ("python exited with error: " ++ py_stderr)
ExitSuccess py_code
return py_stdout
-- * Arbitrary instances
-- | Defines a DNS name.
newtype DNSChar = DNSChar { dnsGetChar::Char }
instance Arbitrary DNSChar where
arbitrary = liftM DNSChar $ elements (['a'..'z'] ++ ['0'..'9'] ++ "_-")
instance Show DNSChar where
show = show . dnsGetChar
-- * Generators
-- | Generates printable ASCII characters (from ' ' to '~').
genPrintableAsciiChar :: Gen Char
genPrintableAsciiChar = choose ('\x20', '\x7e')
-- | Generates a short string (0 <= n <= 40 chars) from printable ASCII.
genPrintableAsciiString :: Gen String
genPrintableAsciiString = do
n <- choose (0, 40)
vectorOf n genPrintableAsciiChar
-- | Generates a short string (1 <= n <= 40 chars) from printable ASCII.
genPrintableAsciiStringNE :: Gen NonEmptyString
genPrintableAsciiStringNE = do
n <- choose (1, 40)
vectorOf n genPrintableAsciiChar >>= mkNonEmpty
-- | Generates a printable Unicode ByteString
genPrintableByteString :: Gen BS.ByteString
#if MIN_VERSION_QuickCheck(2, 10, 0)
genPrintableByteString = fmap (UTF8.fromString . getPrintableString) arbitrary
#else
genPrintableByteString =
fmap UTF8.fromString $ listOf (arbitrary `suchThat` isPrint)
#endif
-- | Generates a single name component.
genName :: Gen String
genName = do
n <- choose (1, 16)
dn <- vector n
return (map dnsGetChar dn)
-- | Generates an entire FQDN.
genFQDN :: Gen String
genFQDN = do
ncomps <- choose (1, 4)
names <- vectorOf ncomps genName
return $ intercalate "." names
-- | Generates a UUID-like string.
--
-- Only to be used for QuickCheck testing. For obtaining actual UUIDs use
-- the newUUID function in Ganeti.Utils
genUUID :: Gen String
genUUID = do
c1 <- vector 6
c2 <- vector 4
c3 <- vector 4
c4 <- vector 4
c5 <- vector 4
c6 <- vector 4
c7 <- vector 6
return $ map dnsGetChar c1 ++ "-" ++ map dnsGetChar c2 ++ "-" ++
map dnsGetChar c3 ++ "-" ++ map dnsGetChar c4 ++ "-" ++
map dnsGetChar c5 ++ "-" ++ map dnsGetChar c6 ++ "-" ++
map dnsGetChar c7
-- | Combinator that generates a 'Maybe' using a sub-combinator.
genMaybe :: Gen a -> Gen (Maybe a)
genMaybe subgen = frequency [ (1, pure Nothing), (3, Just <$> subgen) ]
-- | Generates a sublist of a given list, keeping the ordering.
-- The generated elements are always a subset of the list.
--
-- In order to better support corner cases, the size of the sublist is
-- chosen to have the uniform distribution.
genSublist :: [a] -> Gen [a]
genSublist xs = choose (0, l) >>= g xs l
where
l = length xs
g _ _ 0 = return []
g [] _ _ = return []
g ys n k | k == n = return ys
g (y:ys) n k = frequency [ (k, liftM (y :) (g ys (n - 1) (k - 1)))
, (n - k, g ys (n - 1) k)
]
-- | Generates a map given generators for keys and values.
genMap :: (Ord k, Ord v) => Gen k -> Gen v -> Gen (M.Map k v)
genMap kg vg = M.fromList <$> listOf ((,) <$> kg <*> vg)
-- | Defines a tag type.
newtype TagChar = TagChar { tagGetChar :: Char }
-- | All valid tag chars. This doesn't need to match _exactly_
-- Ganeti's own tag regex, just enough for it to be close.
tagChar :: String
tagChar = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ".+*/:@-"
instance Arbitrary TagChar where
arbitrary = liftM TagChar $ elements tagChar
-- | Generates a tag
genTag :: Gen [TagChar]
genTag = do
-- the correct value would be C.maxTagLen, but that's way too
-- verbose in unittests, and at the moment I don't see any possible
-- bugs with longer tags and the way we use tags in htools
n <- choose (1, 10)
vector n
-- | Generates a list of tags (correctly upper bounded).
genTags :: Gen [String]
genTags = do
-- the correct value would be C.maxTagsPerObj, but per the comment
-- in genTag, we don't use tags enough in htools to warrant testing
-- such big values
n <- choose (0, 10::Int)
tags <- mapM (const genTag) [1..n]
return $ map (map tagGetChar) tags
-- | Generates a fields list. This uses the same character set as a
-- DNS name (just for simplicity).
genFields :: Gen [String]
genFields = do
n <- choose (1, 32)
vectorOf n genName
-- | Generates a list of a given size with non-duplicate elements.
genUniquesList :: (Eq a, Arbitrary a, Ord a) => Int -> Gen a -> Gen [a]
genUniquesList cnt generator = do
set <- foldM (\set _ -> do
newelem <- generator `suchThat` (`Set.notMember` set)
return (Set.insert newelem set)) Set.empty [1..cnt]
return $ Set.toList set
newtype SmallRatio = SmallRatio Double deriving Show
instance Arbitrary SmallRatio where
arbitrary = liftM SmallRatio $ choose (0, 1)
-- | Helper for 'genSet', declared separately due to type constraints.
genSetHelper :: (Ord a) => [a] -> Maybe Int -> Gen (Set.Set a)
genSetHelper candidates size = do
size' <- case size of
Nothing -> choose (0, length candidates)
Just s | s > length candidates ->
error $ "Invalid size " ++ show s ++ ", maximum is " ++
show (length candidates)
| otherwise -> return s
foldM (\set _ -> do
newelem <- elements candidates `suchThat` (`Set.notMember` set)
return (Set.insert newelem set)) Set.empty [1..size']
-- | Generates a 'Set' of arbitrary elements.
genSet :: (Ord a, Bounded a, Enum a) => Maybe Int -> Gen (Set.Set a)
genSet = genSetHelper [minBound..maxBound]
-- | Generates a 'Set' of arbitrary elements wrapped in a 'ListSet'
genListSet :: (Ord a, Bounded a, Enum a) => Maybe Int
-> Gen (BasicTypes.ListSet a)
genListSet is = BasicTypes.ListSet <$> genSet is
-- | Generate an arbitrary element of and AndRestArguments field.
genAndRestArguments :: Gen (M.Map String J.JSValue)
genAndRestArguments = do
n <- choose (0::Int, 10)
let oneParam _ = do
name <- choose (15 ::Int, 25)
>>= flip vectorOf (elements tagChar)
intvalue <- arbitrary
value <- oneof [ J.JSString . J.toJSString <$> genName
, return $ J.showJSON (intvalue :: Int)
]
return (name, value)
M.fromList `liftM` mapM oneParam [1..n]
-- | Generate an arbitrary IPv4 address in textual form.
genIPv4 :: Gen String
genIPv4 = do
a <- choose (1::Int, 255)
b <- choose (0::Int, 255)
c <- choose (0::Int, 255)
d <- choose (0::Int, 255)
return . intercalate "." $ map show [a, b, c, d]
genIPv4Address :: Gen IPv4Address
genIPv4Address = mkIPv4Address =<< genIPv4
-- | Generate an arbitrary IPv4 network in textual form.
genIPv4AddrRange :: Gen String
genIPv4AddrRange = do
pfxLen <- choose (8::Int, 30)
-- Generate a number that fits in pfxLen bits
addr <- choose(1::Int, 2^pfxLen-1)
let hostLen = 32 - pfxLen
-- ...and shift it left until it becomes a 32-bit number
-- with the low hostLen bits unset
net = addr * 2^hostLen
netBytes = [(net `div` 2^x) `mod` 256 | x <- [24::Int, 16, 8, 0]]
return $ intercalate "." (map show netBytes) ++ "/" ++ show pfxLen
genIPv4Network :: Gen IPv4Network
genIPv4Network = mkIPv4Network =<< genIPv4AddrRange
-- | Helper function to compute the number of hosts in a network
-- given the netmask. (For IPv4 only.)
netmask2NumHosts :: Word8 -> Int
netmask2NumHosts n = 2^(32-n)
-- | Generates an arbitrary IPv6 network address in textual form.
-- The generated address is not simpflified, e. g. an address like
-- "2607:f0d0:1002:0051:0000:0000:0000:0004" does not become
-- "2607:f0d0:1002:51::4"
genIp6Addr :: Gen String
genIp6Addr = do
rawIp <- vectorOf 8 $ choose (0::Integer, 65535)
return $ intercalate ":" (map (`showHex` "") rawIp)
-- | Helper function to convert an integer in to an IPv6 address in textual
-- form
ip6AddressFromNumber :: Integer -> [Char]
ip6AddressFromNumber ipInt =
-- chunksOf splits a sequence in chunks of n elements length each
-- chunksOf 4 "20010db80000" = ["2001", "0db8", "0000"]
let chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf n lst = take n lst : (chunksOf n $ drop n lst)
-- Left-pad a sequence with a fixed element if it's shorter than n
-- elements, or trim it to the first n elements otherwise
-- e.g. lPadTrim 6 '0' "abcd" = "00abcd"
lPadTrim :: Int -> a -> [a] -> [a]
lPadTrim n p lst
| length lst < n = lPadTrim n p $ p : lst
| otherwise = take n lst
rawIp = lPadTrim 32 '0' $ (`showHex` "") ipInt
in intercalate ":" $ chunksOf 4 rawIp
-- | Generates an arbitrary IPv6 network in textual form.
genIp6Net :: Gen String
genIp6Net = do
netmask <- choose (8::Int, 126)
raw_ip <- (* 2^(128-netmask)) <$> choose(1::Integer, 2^netmask-1)
return $ ip6AddressFromNumber raw_ip ++ "/" ++ show netmask
-- | Generates a valid, arbitrary tag name with respect to the given
-- 'TagKind' for opcodes.
genOpCodesTagName :: TagKind -> Gen (Maybe String)
genOpCodesTagName TagKindCluster = return Nothing
genOpCodesTagName _ = Just <$> genFQDN
-- | Generates a valid, arbitrary tag name with respect to the given
-- 'TagKind' for Luxi.
genLuxiTagName :: TagKind -> Gen String
genLuxiTagName TagKindCluster = return ""
genLuxiTagName _ = genFQDN
-- * Helper functions
-- | Checks for serialisation idempotence.
testSerialisation :: (Eq a, Show a, J.JSON a) => a -> Property
testSerialisation a =
case J.readJSON (J.showJSON a) of
J.Error msg -> failTest $ "Failed to deserialise: " ++ msg
J.Ok a' -> a ==? a'
-- | Checks for array serialisation idempotence.
testArraySerialisation :: (Eq a, Show a, ArrayObject a) => a -> Property
testArraySerialisation a =
case fromJSArray (toJSArray a) of
J.Error msg -> failTest $ "Failed to deserialise: " ++ msg
J.Ok a' -> a ==? a'
-- | Checks if the deserializer doesn't accept forbidden values.
-- The first argument is ignored, it just enforces the correct type.
testDeserialisationFail :: (Eq a, Show a, J.JSON a)
=> a -> J.JSValue -> Property
testDeserialisationFail a val =
case liftM (`asTypeOf` a) $ J.readJSON val of
J.Error _ -> passTest
J.Ok x -> failTest $ "Parsed invalid value " ++ show val ++
" to: " ++ show x
-- | Result to PropertyM IO.
resultProp :: (Show a) => BasicTypes.GenericResult a b -> PropertyM IO b
resultProp (BasicTypes.Bad err) = stop . failTest $ show err
resultProp (BasicTypes.Ok val) = return val
-- | Return the source directory of Ganeti.
getSourceDir :: IO FilePath
getSourceDir = catchJust (guard . isDoesNotExistError)
(getEnv "TOP_SRCDIR")
(const (return "."))
-- | Returns the path of a file in the test data directory, given its name.
testDataFilename :: String -> String -> IO FilePath
testDataFilename datadir name = do
src <- getSourceDir
return $ src ++ datadir ++ name
-- | Returns the content of the specified haskell test data file.
readTestData :: String -> IO String
readTestData filename = do
name <- testDataFilename "/test/data/" filename
readFile name
-- | Generate arbitrary values in the IO monad. This is a simple
-- wrapper over 'sample''.
genSample :: Gen a -> IO a
genSample gen = do
values <- sample' gen
case values of
[] -> error "sample' returned an empty list of values??"
x:_ -> return x
-- | Function for testing whether a file is parsed correctly.
testParser :: (Show a, Eq a) => Parser a -> String -> a -> HUnit.Assertion
testParser parser fileName expectedContent = do
fileContent <- readTestData fileName
case parseOnly parser $ pack fileContent of
Left msg -> HUnit.assertFailure $ "Parsing failed: " ++ msg
Right obtained -> HUnit.assertEqual fileName expectedContent obtained
-- | Generate a property test for parsers.
genPropParser :: (Show a, Eq a) => Parser a -> String -> a -> Property
genPropParser parser s expected =
case parseOnly parser $ pack s of
Left msg -> failTest $ "Parsing failed: " ++ msg
Right obtained -> expected ==? obtained
-- | Generate an arbitrary non negative integer number
genNonNegative :: Gen Int
genNonNegative =
fmap fromEnum (arbitrary::Gen (Test.QuickCheck.NonNegative Int))
-- | Computes the relative error of two 'Double' numbers.
--
-- This is the \"relative error\" algorithm in
-- http:\/\/randomascii.wordpress.com\/2012\/02\/25\/
-- comparing-floating-point-numbers-2012-edition (URL split due to too
-- long line).
relativeError :: Double -> Double -> Double
relativeError d1 d2 =
let delta = abs $ d1 - d2
a1 = abs d1
a2 = abs d2
greatest = max a1 a2
in if delta == 0
then 0
else delta / greatest
-- | Helper to a get a temporary file name.
getTempFileName :: String -> IO FilePath
getTempFileName filename = do
tempdir <- getTemporaryDirectory
(fpath, handle) <- openTempFile tempdir filename
_ <- hClose handle
removeFile fpath
return fpath
-- | @listOfUniqueBy gen keyFun forbidden@: Generates a list of random length,
-- where all generated elements will be unique by the keying function
-- @keyFun@. They will also be distinct from all elements in @forbidden@ by
-- the keying function.
--
-- As for 'listOf', the maximum output length depends on the size parameter.
--
-- Example:
--
-- > listOfUniqueBy (arbitrary :: Gen String) (length) ["hey"]
-- > -- Generates a list of strings of different length, but not of length 3.
--
-- The passed @gen@ should not make key collisions too likely, since the
-- implementation uses `suchThat`, looping until enough unique elements
-- have been generated. If the @gen@ makes collisions likely, this function
-- will consequently be slow, or not terminate if it is not possible to
-- generate enough elements, like in:
--
-- > listOfUniqueBy (arbitrary :: Gen Int) (`mod` 2) []
-- > -- May not terminate depending on the size parameter of the Gen,
-- > -- since there are only 2 unique keys (0 and 1).
listOfUniqueBy :: (Ord b) => Gen a -> (a -> b) -> [a] -> Gen [a]
listOfUniqueBy gen keyFun forbidden = do
let keysOf = Set.fromList . map keyFun
k <- sized $ \n -> choose (0, n)
flip unfoldrM (0, keysOf forbidden) $ \(i, usedKeys) ->
if i == k
then return Nothing
else do
x <- gen `suchThat` ((`Set.notMember` usedKeys) . keyFun)
return $ Just (x, (i + 1, Set.insert (keyFun x) usedKeys))
| ganeti/ganeti | test/hs/Test/Ganeti/TestCommon.hs | bsd-2-clause | 21,600 | 0 | 20 | 4,628 | 4,955 | 2,653 | 2,302 | 374 | 4 |
module Transformer.JustUnfold where
import qualified ConsPD.Unfold
import qualified Transformer.ConsPD
transform l = Transformer.ConsPD.transform "test/out/consPD" Nothing (ConsPD.Unfold.justUnfold l)
| kajigor/uKanren_transformations | src/Transformer/JustUnfold.hs | bsd-3-clause | 203 | 0 | 8 | 19 | 45 | 26 | 19 | 4 | 1 |
-- | Simple-config is a parser generator for simple configuration file.
--
-- To use this library, one needs import a module and set extensions.
--
-- > {-# LANGUAGE TemplateHaskell, QuasiQuotes #-}
-- > import Text.Config
--
-- The following is quick example.
--
-- > mkConfig "configParser" [config|
-- > TestConfig
-- > uri URI
-- > text String
-- > list [String]
-- > val Int
-- > vals [Int]
-- > bs ByteString
-- > |]
--
-- The example generates following codes.
--
-- > data TestConfig = TestConfig
-- > { uri :: String
-- > , text :: String
-- > , list :: [String]
-- > , val :: Int
-- > , vals :: [Int]
-- > , bs :: ByteString
-- > }
-- > deriving (Show)
-- >
-- > instance Default TestConfig where
-- > def = TestConfig
-- > { uri = "http://localhost/"
-- > , text = ""
-- > , list = []
-- > , val = 0
-- > , vals = []
-- > , bs = ""
-- > }
-- >
-- > configParser :: Parser TestConfig
-- > configParser = ...
--
-- Its parser is able to parse following string.
--
-- > uri: http://example.com/content.html
-- > text: wakaruwa
-- > list: kaede, kirari, momoka
-- > val: 28
-- > vals: 25, 17, 12
-- > bs: chihiro
--
module Text.Config
( -- * Types
module Text.Config.Types
, module Text.Config.TH
) where
import Text.Config.Types
import Text.Config.TH
| yunomu/simple-config | Text/Config.hs | bsd-3-clause | 1,398 | 0 | 5 | 398 | 88 | 77 | 11 | 6 | 0 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
module Snap.Snaplet.Mandrill
( initMandrill
, runMandrill
, MandrillState (..)
, HasMandrill (..)
) where
import Control.Applicative
import Control.Monad.State
import Control.Monad.Trans.Reader
import Data.Configurator
import qualified Network.API.Mandrill as M
import Paths_snaplet_mandrill
import Snap.Snaplet
-------------------------------------------------------------------------------
newtype MandrillState = MandrillState { token :: M.MandrillKey }
-------------------------------------------------------------------------------
class MonadIO m => HasMandrill m where
getMandrill :: m M.MandrillKey
instance HasMandrill (Handler b MandrillState) where
getMandrill = gets token
instance MonadIO m => HasMandrill (ReaderT M.MandrillKey m) where
getMandrill = ask
-- | Initialize the Mandrill Snaplet.
initMandrill :: SnapletInit b MandrillState
initMandrill = makeSnaplet "mandrill" description datadir $ do
conf <- getSnapletUserConfig
return =<< MandrillState <$> (liftIO $ require conf "token")
where
description = "Snaplet for Mandrill library"
datadir = Just $ liftM (++"/resources/mandrill") getDataDir
-------------------------------------------------------------------------------
-- | Runs an Mandrill action in any monad with a HasAmqpConn instance.
runMandrill :: (HasMandrill m) => M.MandrillT m a -> m a
runMandrill action = do
tk <- getMandrill
return =<< M.runMandrill tk action
| ixmatus/snaplet-mandrill | src/Snap/Snaplet/Mandrill.hs | bsd-3-clause | 1,596 | 0 | 11 | 291 | 309 | 171 | 138 | 31 | 1 |
-- |Read data from stdin, print FNV-1a hash to stdout
import Text.Printf (printf)
import qualified Data.ByteString.Lazy as L
import Data.Digest.Pure.FNV1a
main :: IO ()
main = do
c <- L.getContents
let hsh = fnv1a c
putStrLn $ show hsh
| zdavkeos/pureFNV1a | Test/fnv1a.hs | bsd-3-clause | 259 | 0 | 10 | 62 | 74 | 40 | 34 | 8 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module TestAux where
import Ciel
-- import Debug.Trace (trace)
sumup :: [Int] -> CielWF Int
sumup is = return $ sum is
add5 :: Int -> CielWF Int
add5 i = return (i+5)
add1 :: Int -> CielWF Int
add1 i = return (i+1)
$(remotable ['sumup,'add5,'add1])
| jepst/Cielhs | TestAux.hs | bsd-3-clause | 288 | 0 | 8 | 56 | 121 | 65 | 56 | 10 | 1 |
module Data.Metagraph.Builder(
-- * Types
MetaGraphM
-- * Basic API
, buildMetaGraph
, newMetaGraph
, newNode
, newEdge
, addNode
, addEdge
-- * Helpers
, lookupGraph
, lookupEdge
, lookupNode
) where
import Data.Metagraph.Strict
import Data.IntMap (IntMap)
import qualified Data.IntMap.Strict as M
import Control.Monad.State.Strict
import Data.Metagraph.Internal.Types
import Data.Maybe
-- | Build environment for 'MetaGraphM'
data BuildEnv edge node = BuildEnv {
-- | Next id for edge
_buildNextEdge :: !Int
-- | Next id for node
, _buildNextNode :: !Int
-- | Next id for graph
, _buildNextGraph :: !Int
-- | Cache of all edges
, _buildEdges :: !(IntMap (MetaEdge edge node))
-- | Cache of all nodes
, _buildNodes :: !(IntMap (MetaNode edge node))
-- | Cache of all graphs
, _buildGraphs :: !(IntMap (MetaGraph edge node))
}
-- | Construct new building environment
newBuildEnv :: BuildEnv edge node
newBuildEnv = BuildEnv 0 0 0 mempty mempty mempty
-- | Increment edge id counter and return old value
genNextEdgeId :: MetaGraphId -> (EdgeId -> MetaEdge edge node) -> BuildEnv edge node -> (EdgeId, BuildEnv edge node)
genNextEdgeId !gi !e !be = be' `seq` i `seq` (EdgeId i, be')
where
i = _buildNextEdge be
edge = e $! EdgeId i
be' = be {
_buildNextEdge = _buildNextEdge be + 1
, _buildEdges = M.insert i edge $! _buildEdges be
, _buildGraphs = M.adjust (insertEdge edge) (unMetaGraphId gi) $! _buildGraphs be
}
-- | Increment node id counter and return old value
genNextNodeId :: MetaGraphId -> (NodeId -> MetaNode edge node) -> BuildEnv edge node -> (NodeId, BuildEnv edge node)
genNextNodeId !gi !n !be = be' `seq` i `seq` (NodeId i, be')
where
i = _buildNextNode be
node = n $! NodeId i
be' = be {
_buildNextNode = _buildNextNode be + 1
, _buildNodes = M.insert i node $! _buildNodes be
, _buildGraphs = M.adjust (insertNode node) (unMetaGraphId gi) $! _buildGraphs be
}
-- | Increment node id counter and return old value
genNextGraphId :: (MetaGraphId -> MetaGraph edge node) -> BuildEnv edge node -> (MetaGraphId, BuildEnv edge node)
genNextGraphId !g !be = be' `seq` i `seq` (MetaGraphId i, be')
where
i = _buildNextGraph be
be' = be {
_buildNextGraph = _buildNextGraph be + 1
, _buildGraphs = M.insert i (g $ MetaGraphId i) $! _buildGraphs be
}
-- | Find edge in build environment
envLookupEdge :: EdgeId -> BuildEnv edge node -> Maybe (MetaEdge edge node)
envLookupEdge !i !be = M.lookup (unEdgeId i) $! _buildEdges be
-- | Find node in build environment
envLookupNode :: NodeId -> BuildEnv edge node -> Maybe (MetaNode edge node)
envLookupNode !i !be = M.lookup (unNodeId i) $! _buildNodes be
-- | Find edge in build environment
envLookupGraph :: MetaGraphId -> BuildEnv edge node -> Maybe (MetaGraph edge node)
envLookupGraph !i !be = M.lookup (unMetaGraphId i) $! _buildGraphs be
-- | Adjusting value of edge by id in build environment
envModifyEdges :: EdgeId -> (MetaEdge edge node -> MetaEdge edge node) -> BuildEnv edge node -> BuildEnv edge node
envModifyEdges !i !f !be = be { _buildEdges = M.adjust f (unEdgeId i) $! _buildEdges be }
-- | Adjusting value of node by id in build environment
envModifyNodes :: NodeId -> (MetaNode edge node -> MetaNode edge node) -> BuildEnv edge node -> BuildEnv edge node
envModifyNodes !i !f !be = be { _buildNodes = M.adjust f (unNodeId i) $! _buildNodes be }
-- | Adjusting value of metagraph by id in build environment
envModifyGraphs :: MetaGraphId -> (MetaGraph edge node -> MetaGraph edge node) -> BuildEnv edge node -> BuildEnv edge node
envModifyGraphs !i !f !be = be { _buildGraphs = M.adjust f (unMetaGraphId i) $! _buildGraphs be }
-- | Remove edge from build environment
envDeleteEdge :: EdgeId -> BuildEnv edge node -> BuildEnv edge node
envDeleteEdge !i !be = be { _buildEdges = M.delete (unEdgeId i) $! _buildEdges be }
-- | Remove node from build environment
envDeleteNode :: NodeId -> BuildEnv edge node -> BuildEnv edge node
envDeleteNode !i !be = be { _buildNodes = M.delete (unNodeId i) $! _buildNodes be }
-- | Remove graph from build environment
envDeleteGraph :: MetaGraphId -> BuildEnv edge node -> BuildEnv edge node
envDeleteGraph !i !be = be { _buildGraphs = M.delete (unMetaGraphId i) $! _buildGraphs be }
-- | A special monad where creation of meta graph is efficient
newtype MetaGraphM edge node a = MetaGraphM { unMetaGraphM :: State (BuildEnv edge node) a }
deriving (Functor, Applicative, Monad)
-- | Execute monadic action that builds metagraph efficiently. Return value in the monadic
-- builder is resulted metagraph that is extracted from build environment.
buildMetaGraph :: MetaGraphM edge node MetaGraphId -> MetaGraph edge node
buildMetaGraph ma = fromMaybe
(error "buildMetaGraph: resulting graph is not in environment!")
(M.lookup (unMetaGraphId i) $ _buildGraphs env)
where
(i, env) = runState (unMetaGraphM ma) newBuildEnv
-- | Creation of new metagraph in monadic action
newMetaGraph :: MetaGraphM edge node MetaGraphId
newMetaGraph = MetaGraphM . state $ genNextGraphId empty
-- | Creation of new node in monadic action
newNode :: MetaGraphId -- ^ Metagraph the node belongs to
-> Maybe MetaGraphId -- ^ Subgraph
-> node -- ^ Payload
-> MetaGraphM edge node NodeId
newNode gi msubi payload = do
mgr <- join <$> traverse lookupGraph msubi
MetaGraphM . state $ genNextNodeId gi $ \i -> MetaNode {
_nodeId = i
, _nodePayload = payload
, _nodeGraph = mgr
}
-- | Add given node to metagraph
addNode :: MetaGraphId -- ^ Target metagraph
-> NodeId -- ^ Existing node
-> MetaGraphM edge node ()
addNode gi ni = do
mn <- lookupNode ni
case mn of
Nothing -> fail "addNode: cannot find node with such id"
Just n -> MetaGraphM . modify' $ envModifyGraphs gi $ \g -> g {
_metagraphNodes = M.insert (unNodeId ni) n $! _metagraphNodes g
}
-- | Add given edge to metagraph
addEdge :: MetaGraphId -- ^ Target metagraph
-> EdgeId -- ^ Existing edge
-> MetaGraphM edge node ()
addEdge gi ei = do
mn <- lookupEdge ei
case mn of
Nothing -> fail "addEdge: cannot find edge with such id"
Just e -> MetaGraphM . modify' $ envModifyGraphs gi $ \g -> g {
_metagraphEdges = M.insert (unEdgeId ei) e $! _metagraphEdges g
}
-- | Create new edge in build environment
newEdge :: MetaGraphId -- ^ Metagraph the edge belongs to
-> Directed -- ^ Is the edge directed
-> NodeId -- ^ Start node
-> NodeId -- ^ End node
-> Maybe MetaGraphId -- ^ Subgraph
-> edge -- ^ Paload
-> MetaGraphM edge node EdgeId
newEdge gi dir starti endi msubi payload = do
mgr <- join <$> traverse lookupGraph msubi
from <- maybe (fail $ "Cannot find from node " ++ show starti) return =<< lookupNode starti
to <- maybe (fail $ "Cannot find to node " ++ show starti) return =<< lookupNode endi
MetaGraphM . state $ genNextEdgeId gi $ \i -> MetaEdge {
_edgeId = i
, _edgeDirected = dir
, _edgeFrom = from
, _edgeTo = to
, _edgePayload = payload
, _edgeGraph = mgr
}
-- | Find metagraph in build environment
lookupGraph :: MetaGraphId -> MetaGraphM edge node (Maybe (MetaGraph edge node))
lookupGraph i = MetaGraphM $ envLookupGraph i <$> get
-- | Find metagraph in build environment
lookupEdge :: EdgeId -> MetaGraphM edge node (Maybe (MetaEdge edge node))
lookupEdge i = MetaGraphM $ envLookupEdge i <$> get
-- | Find metagraph in build environment
lookupNode :: NodeId -> MetaGraphM edge node (Maybe (MetaNode edge node))
lookupNode i = MetaGraphM $ envLookupNode i <$> get
| Teaspot-Studio/metagraph | src/Data/Metagraph/Builder.hs | bsd-3-clause | 7,694 | 0 | 17 | 1,630 | 2,191 | 1,125 | 1,066 | -1 | -1 |
module Rad.QL.Define.Util where
import Data.Monoid ((<>))
import Unsafe.Coerce
import Rad.QL.Internal.Builders
import Rad.QL.Internal.Types
import Rad.QL.AST
import Rad.QL.Types
unit :: (Applicative m) => m ()
unit = pure ()
-- The describeable class, allows use to use the `describe` method to append a description
class (Monad m) => Describable m where
describe :: Description -> m ()
infixr 8 $..
($..) :: (Description -> a) -> Description -> a
($..) = ($)
infixr 9 |.., |--
(|..) :: Description -> Description -> Description
d1 |.. d2 = d1 <> "\n" <> d2
(|--) :: Description -> Description -> Description
d1 |-- d2 = d1 <> "\n\n" <> d2
-- The deprecateable class, allows use of the `deprecate` method to append a description
class (Monad m) => Deprecatable m where
deprecate :: Deprecation -> m ()
-- undefined object, useful for stubbing out methods
data UNDEFINED = UNDEFINED
instance GraphQLScalar UNDEFINED where
serialize _ = buildString "UNDEFINED"
deserialize _ = Nothing
instance (Monad m) => GraphQLValue m UNDEFINED
instance (Monad m) => GraphQLType SCALAR m UNDEFINED where
def = emptyDef
| jqyu/bustle-chi | src/Rad/QL/Define/Util.hs | bsd-3-clause | 1,128 | 0 | 9 | 201 | 337 | 189 | 148 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, PackageImports #-}
import "GLFW-b" Graphics.UI.GLFW as GLFW
import Binary.Fast
import Codec.Image.STB
import Control.Applicative
import Control.Monad
import Data.Bitmap.Pure
import Data.Vect
import FRP.Elerea.Param
import GLBackend
import GraphicsPipeline
import Utils
import qualified Data.ByteString.Char8 as SB
import Graphics.Rendering.OpenGL.Raw.Core32
setupProgram :: IO GLProgram
setupProgram = do
vsrc <- SB.readFile "simple/simple.vert"
fsrc <- SB.readFile "simple/simple.frag"
Just p <- compileProgram $ Program
{ attributes = [("position",AT_Vec3)
,("normal",AT_Vec3)
,("UVTex",AT_Vec2)]
, uniforms = [("cameraMatrix",UT_Mat4)
,("projectionMatrix",UT_Mat4)
,("time",UT_Float)]
, samplers = [("diffuseTexture",ST_Sampler2D)]
, outputs = []
, vertexShader = [vsrc]
, geometryShader = []
, fragmentShader = [fsrc]
}
return p
type Scene = [(Mat4,GLMesh)]
main :: IO ()
main = do
windowSize <- initCommon "Graphics Pipeline Demo"
(mousePosition,mousePositionSink) <- external (0,0)
(_mousePress,mousePressSink) <- external False
(buttonPress,buttonPressSink) <- external False
(fblrPress,fblrPressSink) <- external (False,False,False,False,False)
printGLVersion
glProgram <- setupProgram
--glCube <- compileMesh cube
--glCube <- compileMesh =<< remoteMesh "Cube"
--glCube <- compileMesh =<< remoteMesh "Monkey"
glScene <- compileMesh =<< loadMesh "Scene.lcmesh"
glCube <- compileMesh =<< loadMesh "Monkey.lcmesh"
glPlane <- compileMesh =<< loadMesh "Plane.lcmesh"
glSphere <- compileMesh =<< loadMesh "Icosphere.lcmesh"
let scn = [(idmtx,glSphere),(idmtx,glCube),(idmtx,glPlane),(idmtx,glScene)]
Right b <- loadImage "textures/Panels_Diffuse.png"
diffuseTex <- compileColorTexture2D b
renderTex <- compileColorTexture2D $ emptyBitmap (512,512) 3 Nothing
fb <- newGLFramebuffer
bloom <- initBloom
vsm <- initVSM
ssao <- initSSAO
s <- fpsState
sc <- start $ scene ssao vsm bloom fb renderTex diffuseTex glProgram scn windowSize mousePosition fblrPress buttonPress
driveNetwork sc (readInput s mousePositionSink mousePressSink fblrPressSink buttonPressSink)
closeWindow
scene :: SSAO -> VSM -> Bloom -> GLFramebuffer -> GLColorTexture2D -> GLColorTexture2D -> GLProgram -> Scene -> Signal (Int, Int)
-> Signal (Float, Float)
-> Signal (Bool, Bool, Bool, Bool, Bool)
-> Signal (Bool)
-> SignalGen Float (Signal (IO ()))
scene ssao vsm bloom fb rtex tex p scn windowSize mousePosition fblrPress buttonPress = do
re1 <- integral 0 1.5
re2 <- integral 10 (-1.0)
re3 <- integral 110 0.8
time <- stateful 0 (+)
last2 <- transfer ((0,0),(0,0)) (\_ n (_,b) -> (b,n)) mousePosition
let mouseMove = (\((ox,oy),(nx,ny)) -> (nx-ox,ny-oy)) <$> last2
--let mouseMove = mousePosition
cam <- userCamera (Vec3 (-4) 0 0) mouseMove fblrPress
return $ drawGLScene ssao vsm bloom fb rtex tex p scn <$> windowSize <*> re1 <*> re2 <*> re3 <*> cam <*> time <*> buttonPress
drawGLScene :: SSAO -> VSM -> Bloom -> GLFramebuffer -> GLColorTexture2D -> GLColorTexture2D -> GLProgram -> Scene -> (Int, Int)
-> Float
-> Float
-> Float
-> (Vec3, Vec3, Vec3, t1)
-> Float
-> Bool
-> IO ()
drawGLScene _ssao vsm _bloom _fb _rtex _tex p objs (w,h) _re1 _re2 _re3 (cam,dir,up,_) time _buttonPress = do
let cm = fromProjective (lookat cam (cam + dir) up)
pm = perspective 0.1 50 90 (fromIntegral w / fromIntegral h)
{-
render t = withDepth $ do
clearGLFramebuffer
l <- forM objs $ \(worldMat,mesh) -> renderGLMesh' p mesh $ and <$> sequence
-- setup uniforms
[ setUniform p "cameraMatrix" $ U_Mat4 cm
, setUniform p "projectionMatrix" $ U_Mat4 pm
, setUniform p "time" $ U_Float time
, setSampler p "diffuseTexture" t
]
let b = and l
unless b $ putStrLn "render fail"
return b
-}
--withFramebuffer fb Nothing Nothing [rtex] $ render tex
--render rtex
--render tex
--renderBloom bloom rtex
--VSM
renderVSM (w,h) time vsm objs cm pm
{-
--glViewport 0 0 (fromIntegral w) (fromIntegral h)
-- SSAO
if buttonPress then render tex else do
withFramebuffer fb (Just $ ssaoDepthTexture ssao) Nothing [ssaoRenderTexture ssao] $ render tex
renderSSAO ssao
-}
swapBuffers
readInput :: State
-> ((Float, Float) -> IO a)
-> (Bool -> IO b)
-> ((Bool, Bool, Bool, Bool, Bool) -> IO c)
-> (Bool -> IO b)
-> IO (Maybe Float)
readInput s mousePos mouseBut fblrPress buttonPress = do
t <- getTime
resetTime
(x,y) <- getMousePosition
mousePos (fromIntegral x,fromIntegral y)
mouseBut =<< mouseButtonIsPressed MouseButton0
fblrPress =<< ((,,,,) <$> keyIsPressed KeyLeft <*> keyIsPressed KeyUp <*> keyIsPressed KeyDown <*> keyIsPressed KeyRight <*> keyIsPressed KeyRightShift)
buttonPress =<< keyIsPressed KeySpace
updateFPS s t
k <- keyIsPressed KeyEsc
return $ if k then Nothing else Just (realToFrac t)
program :: Program
program = Program [] [] [] [] [] [] []
loadProgram :: FilePath -> FilePath -> Program -> IO GLProgram
loadProgram v f p = do
vsrc <- SB.readFile v
fsrc <- SB.readFile f
SB.putStr "Loading shaders: "
print (v,f)
Just glp <- compileProgram $ p {vertexShader = [vsrc], fragmentShader = [fsrc]}
return glp
-- Variance Shadow Map Effect
data VSM
= VSM
{ vsmDepthTexture :: GLColorTexture2D
, vsmBlurTexture :: GLColorTexture2D
, vsmFramebuffer :: GLFramebuffer
, vsmStoreProgram :: GLProgram
, vsmBlurProgram :: GLProgram
, vsmShadowProgram :: GLProgram
, vsmShadowMapSize :: Size
, vsmTmpDepth :: GLDepthTexture2D
}
initVSM :: IO VSM
initVSM = do
storeProgram <- loadProgram "vsm/StoreDepth.vert" "vsm/StoreDepth.frag" $ program
{ attributes = [("position", AT_Vec3)]
, uniforms = [("worldProjection", UT_Mat4)]
}
blurProgram <- loadProgram "vsm/Blur.vert" "vsm/Blur.frag" $ program
{ attributes = [("position", AT_Vec3)
,("uv", AT_Vec2)]
, uniforms = [("worldProjection", UT_Mat4)
,("scaleU", UT_Vec2)]
, samplers = [("textureSource", ST_Sampler2D)]
}
shadowProgram <- loadProgram "vsm/Final.vert" "vsm/Final.frag" $ program
{ attributes = [("position", AT_Vec3)]
, uniforms = [("worldProjection", UT_Mat4)
,("lightProjection", UT_Mat4)]
, samplers = [("shadowMap", ST_Sampler2D)]
}
let smSize = (512,512)
--blurW = shadowMapH * coeff
--blurH = shadowMapW * coeff
--coeff = 0.25
blurTexture = undefined
framebuffer <- newGLFramebuffer
depthTexture <- compileColorTexture2D $ emptyBitmap smSize 3 Nothing
--blurTexture <- compileColorTexture2D $ emptyBitmap (floor blurW,floor blurH) 3 Nothing
tmpDepth <- newGLDepthTexture2D smSize
return $ VSM depthTexture blurTexture framebuffer storeProgram blurProgram shadowProgram smSize tmpDepth
renderVSM :: Size -> Float -> VSM -> Scene -> Mat4 -> Mat4 -> IO Bool
renderVSM (w,h) time vsm ((_,o):(_,m):ox) camMat projMat = do
let fb = vsmFramebuffer vsm
dtex = vsmDepthTexture vsm
btex = vsmBlurTexture vsm
stp = vsmStoreProgram vsm
bp = vsmBlurProgram vsm
shp = vsmShadowProgram vsm
lpos = Vec3 0.1 2 0.1
lat = (Vec3 0 (-100) 0)
up = Vec3 0 1 0
objs = (fromProjective $ (rotationEuler (Vec3 (time*0.1) (time*0.3) 0) .*. translation lpos),o):
(fromProjective $ rotationEuler (Vec3 time (time/pi) 0),m):ox -- (fromProjective $ translation lat,o):ox
lmat = fromProjective (lookat lpos lat up)
scale a b s = a + (b-a)*(s/2+0.5)
frontclip = scale (0.00001) 0.8 $ sin (time*0.6)
frontclip' = 0.4
pmat = perspective frontclip' 5 90 (fromIntegral w / fromIntegral h)
(sw,sh) = vsmShadowMapSize vsm
{-
bias = Mat4 (Vec4 0.5 0.0 0.0 0.0)
(Vec4 0.0 0.5 0.0 0.0)
(Vec4 0.0 0.0 0.5 0.0)
(Vec4 0.5 0.5 0.5 1.0)
-}
--print frontclip
-- render from light view, store depth map
oks1 <- withFramebuffer fb (Just $ vsmTmpDepth vsm) Nothing [dtex] $ withDepth $ do
glViewport 0 0 (fromIntegral sw) (fromIntegral sh)
clearGLFramebuffer
l <- forM objs $ \(worldMat,mesh) ->
renderGLMesh' stp mesh $ setUniform stp "worldProjection" $ U_Mat4 $ worldMat .*. lmat .*. pmat
-- renderGLMesh' stp mesh $ setUniform stp "worldProjection" $ U_Mat4 $ worldMat .*. camMat .*. projMat
return $ and l
-- blur depth map
-- blurH
-- blurV
{-
oks2 <- withFramebuffer fb Nothing Nothing [btex] $ do
clearGLFramebuffer
l <- forM objs $ \(worldMat,mesh) ->
renderGLMesh' strp mesh $ setUniform strp "worldProjection" $ U_Mat4 worldMat -- TODO: set proper matrix
return $ and l
-}
-- render from camera view
oks3 <- withDepth $ do
glViewport 0 0 (fromIntegral w) (fromIntegral h)
clearGLFramebuffer
l <- forM objs $ \(worldMat,mesh) -> renderGLMesh' shp mesh $ and <$> sequence
-- setup uniforms
--[ setUniform shp "worldProjection" $ U_Mat4 $ worldMat .*. lmat .*. pmat
[ setUniform shp "worldProjection" $ U_Mat4 $ worldMat .*. camMat .*. projMat
, setUniform shp "lightProjection" $ U_Mat4 $ worldMat .*. lmat .*. pmat
--, setUniform shp "lightProjection" $ U_Mat4 $ worldMat .*. camMat .*. projMat
, setSampler shp "shadowMap" dtex
]
return $ and l
return False
-- Bloom Effect
data Bloom
= Bloom
{ glmProgram :: GLProgram
, glmQuad :: GLMesh
}
initBloom :: IO Bloom
initBloom = do
bloomProgram <- loadProgram "bloom/bloom.vert" "bloom/bloom.frag" $ program
{ attributes = [("position", AT_Vec2)]
, samplers = [("renderedTexture", ST_Sampler2D)]
}
quad <- compileMesh quad2D
return $ Bloom bloomProgram quad
renderBloom :: Bloom -> GLColorTexture2D -> IO Bool
renderBloom (Bloom p m) tex = do
clearGLFramebuffer
b <- renderGLMesh' p m $ setSampler p "renderedTexture" tex
unless b $ putStrLn "render fail"
return b
{-
{ vsmDepthTexture :: GLColorTexture2D
, vsmBlurTexture :: GLColorTexture2D
, vsmFramebuffer :: GLFramebuffer
, vsmStoreProgram :: GLProgram
, vsmBlurProgram :: GLProgram
, vsmShadowProgram :: GLProgram
, vsmShadowMapSize :: Size
, vsmTmpDepth :: GLDepthTexture2D
}
-}
-- SSAO Effect
data SSAO
= SSAO
{ ssaoProgram :: GLProgram
, ssaoQuad :: GLMesh
, ssaoDepthTexture :: GLDepthTexture2D
, ssaoLuminanceTexture :: GLColorTexture2D
, ssaoRenderTexture :: GLColorTexture2D
, ssaoRenderSize :: Size
}
initSSAO :: IO SSAO
initSSAO = do
ssaoProgram <- loadProgram "ssao/ssao.vert" "ssao/ssao.frag" $ program
{ attributes = [("position", AT_Vec2)]
, uniforms = [("bgl_RenderedTextureHeight", UT_Float)
,("bgl_RenderedTextureWidth", UT_Float)]
, samplers = [("bgl_DepthTexture", ST_Sampler2D)
,("bgl_LuminanceTexture", ST_Sampler2D)
,("bgl_RenderedTexture", ST_Sampler2D)]
}
quad <- compileMesh quad2D
let size = (1280,720)
depthTexture <- newGLDepthTexture2D size
luminanceTexture <- compileColorTexture2D $ emptyBitmap size 3 Nothing
renderTexture <- compileColorTexture2D $ emptyBitmap size 3 Nothing
return $ SSAO ssaoProgram quad depthTexture luminanceTexture renderTexture size
--renderSSAO :: SSAO -> Size -> GLDepthTexture2D -> GLColorTexture2D -> GLColorTexture2D -> IO Bool
--renderSSAO ssao (w,h) dt rt lt = do
renderSSAO ssao = do
clearGLFramebuffer
let p = ssaoProgram ssao
lt = ssaoLuminanceTexture ssao
(w,h) = ssaoRenderSize ssao
rt = ssaoRenderTexture ssao
dt = ssaoDepthTexture ssao
b <- renderGLMesh' p (ssaoQuad ssao) $ and <$> sequence
-- setup uniforms
[ setUniform p "bgl_RenderedTextureHeight" $ U_Float $ fromIntegral h
, setUniform p "bgl_RenderedTextureWidth" $ U_Float $ fromIntegral w
, setSampler p "bgl_DepthTexture" dt
, setSampler p "bgl_LuminanceTexture" lt
, setSampler p "bgl_RenderedTexture" rt
]
unless b $ putStrLn "render fail"
return b
| csabahruska/GFXDemo | Main.hs | bsd-3-clause | 13,343 | 0 | 22 | 3,841 | 3,322 | 1,751 | 1,571 | 232 | 2 |
{-# LANGUAGE LambdaCase, RecordWildCards, Strict #-}
module AbstractInterpretation.BinaryIR (encodeAbstractProgram) where
import Control.Monad.State
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.ByteString.Lazy as LBS
import Data.ByteString.Builder
import AbstractInterpretation.IR
data Env
= Env
{ envTagMap :: Map (Set Tag) Int32
, envBlockCount :: !Int
, envBuilder :: !Builder
, envBuilderMap :: Map Int (Int, Builder) -- block size, data
, envInstCount :: !Int
}
emptyEnv = Env
{ envTagMap = mempty
, envBlockCount = 0
, envBuilder = mempty
, envBuilderMap = mempty
, envInstCount = 0
}
type W = State Env
emit :: Builder -> W ()
emit b = modify' $ \env@Env{..} -> env {envBuilder = envBuilder <> b}
writeI32 :: Int32 -> W ()
writeI32 i = emit $ int32LE i
writeW32 :: Word32 -> W ()
writeW32 w = emit $ word32LE w
writeReg :: Reg -> W ()
writeReg (Reg r) = writeW32 r
writeMem :: Mem -> W ()
writeMem (Mem m) = writeW32 m
writeTagSet :: Set Tag -> W ()
writeTagSet s = do
tm <- gets envTagMap
let size = fromIntegral $ Map.size tm
case Map.lookup s tm of
Just idx -> writeI32 idx
Nothing -> do
modify' $ \env@Env{..} -> env {envTagMap = Map.insert s size envTagMap}
writeI32 size
writeBlock :: [Instruction] -> W ()
writeBlock il = do
let size = length il
blockIndex <- gets envBlockCount
modify' $ \env@Env{..} -> env {envInstCount = envInstCount + size, envBlockCount = succ blockIndex}
writeI32 $ fromIntegral blockIndex
savedBuilder <- gets envBuilder
modify' $ \env@Env{..} -> env {envBuilder = mempty}
mapM_ writeInstruction il
blockBuilder <- gets envBuilder
modify' $ \env@Env{..} -> env {envBuilder = savedBuilder, envBuilderMap = Map.insert blockIndex (size, blockBuilder) envBuilderMap}
-----------------------------------
writeRange :: Range -> W ()
writeRange Range{..} = do
writeI32 from
writeI32 to
writeType :: Int32 -> W ()
writeType = writeI32
writeTag :: Tag -> W ()
writeTag (Tag w) = writeW32 w
writePredicate :: Predicate -> W ()
writePredicate = \case
TagIn s -> do
writeType 100
writeTagSet s
TagNotIn s -> do
writeType 101
writeTagSet s
ValueIn r -> do
writeType 102
writeRange r
ValueNotIn r -> do
writeType 103
writeRange r
writeCondition :: Condition -> W ()
writeCondition = \case
NodeTypeExists t -> do
writeType 200
writeTag t
SimpleTypeExists st -> do
writeType 201
writeI32 st
AnyNotIn s -> do
writeType 202
writeTagSet s
Any p -> do
writeType 203
writePredicate p
writeSelector :: Selector -> W ()
writeSelector = \case
NodeItem t i -> do
writeType 300
writeTag t
writeI32 $ fromIntegral i
ConditionAsSelector c -> do
writeType 301
writeCondition c
AllFields -> do
writeType 302
writeConstant :: Constant -> W ()
writeConstant = \case
CSimpleType st -> do
writeType 400
writeI32 st
CHeapLocation m -> do
writeType 401
writeMem m
CNodeType t a -> do
writeType 402
writeTag t
writeI32 $ fromIntegral a
CNodeItem t i v -> do
writeType 403
writeTag t
writeI32 $ fromIntegral i
writeI32 v
writeInstruction :: Instruction -> W ()
writeInstruction = \case
If {..} -> do
writeType 500
writeCondition condition
writeReg srcReg
writeBlock instructions
Project {..} -> do
writeType 501
writeSelector srcSelector
writeReg srcReg
writeReg dstReg
Extend {..} -> do
writeType 502
writeReg srcReg
writeSelector dstSelector
writeReg dstReg
Move {..} -> do
writeType 503
writeReg srcReg
writeReg dstReg
RestrictedMove {..} -> do
writeType 504
writeReg srcReg
writeReg dstReg
ConditionalMove {..} -> do
writeType 505
writeReg srcReg
writePredicate predicate
writeReg dstReg
Fetch {..} -> do
writeType 506
writeReg addressReg
writeReg dstReg
Store {..} -> do
writeType 507
writeReg srcReg
writeMem address
Update {..} -> do
writeType 508
writeReg srcReg
writeReg addressReg
RestrictedUpdate {..} -> do
writeType 509
writeReg srcReg
writeReg addressReg
ConditionalUpdate {..} -> do
writeType 510
writeReg srcReg
writePredicate predicate
writeReg addressReg
Set {..} -> do
writeType 511
writeReg dstReg
writeConstant constant
{-
memory count i32
register count i32
start block id i32
cmd count i32
cmds ...
block count i32
blocks (ranges) ...
intset count i32
set size i32
set elems ... [i32]
-}
writeBlockItem :: Int32 -> Int -> W Int32
writeBlockItem offset size = do
let nextOffset = offset + fromIntegral size
writeI32 $ offset
writeI32 $ nextOffset
pure nextOffset
encodeAbstractProgram :: AbstractProgram -> LBS.ByteString
encodeAbstractProgram AbstractProgram {..} = toLazyByteString (envBuilder env) where
env = flip execState emptyEnv $ do
writeW32 _absMemoryCounter
writeW32 _absRegisterCounter
-- start block id
writeBlock _absInstructions
-- commands
cmdCount <- gets envInstCount
writeI32 $ fromIntegral cmdCount
(blockSizes, blocks) <- gets $ unzip . Map.elems . envBuilderMap
mapM emit blocks
-- bocks
blkCount <- gets envBlockCount
writeI32 $ fromIntegral blkCount
foldM_ writeBlockItem 0 blockSizes
-- intsets
{-
setCount <- gets envTagSetCount
writeI32 $ fromIntegral setCount
sets <- gets envTagSets
-}
tagMap <- gets envTagMap
writeI32 $ fromIntegral $ Map.size tagMap
let sets = Map.elems $ Map.fromList [(i, s) | (s, i) <- Map.toList tagMap]
forM_ sets $ \s -> do
writeI32 $ fromIntegral $ Set.size s
forM_ (Set.toList s) (\(Tag t) -> writeI32 $ fromIntegral t)
| andorp/grin | grin/src/AbstractInterpretation/BinaryIR.hs | bsd-3-clause | 5,955 | 0 | 19 | 1,493 | 1,991 | 924 | 1,067 | 204 | 12 |
module Machine.Gates (nand
,not
,and
,or
,xor
,mux
,dmux
,notN
,andN
,orN
,muxN
,orNWay
,mux4WayN
,mux8WayN
,dmux4Way
,dmux8Way
,Mpin) where
import Prelude hiding (and, not, or)
-- The goal is to define a nand gate, and to use the nand for all further logic and
-- not use built in Haskell language features that serve the same purpose beyond the
-- nand gate, at least as much as possible. In the future, to improve performance
-- this may change.
nand :: Bool -> Bool -> Bool
nand a b | a && b = False
| otherwise = True
not :: Bool -> Bool
not a = nand a a
and :: Bool -> Bool -> Bool
and a b = not (nand a b)
or :: Bool -> Bool -> Bool
or a b = nand (not a) (not b)
xor :: Bool -> Bool -> Bool
xor a b = nand (nand a (nand a b)) (nand b (nand a b))
-- if sel is False a is output, else b is output
mux :: Bool -> Bool -> Bool -> Bool
mux a b sel = or (and (not sel) a) (and sel b)
-- Returning information on two pins required something like the let construct.
dmux :: Bool -> Bool -> (Bool, Bool)
dmux sel input = let
a = and (not sel) input
b = and sel input
in ((a, b))
-- Haskell doesn't have fixed width arrays, just tuples which doesn't help much. Using
-- built in arrays as a compromise. This should be a not16, but it's just a notN. This
-- breaks the hardware simulation constraints I wanted to achieve in this instance. You
-- can't have an endless hardware bus in real life. An Mpin is basically a pin array.
type Mpin = [Bool]
notN :: Mpin -> Mpin
notN input = fmap not input
andN :: Mpin -> Mpin -> Mpin
andN a b = fmap (\(a', b') -> and a' b') $ zip a b
orN :: Mpin -> Mpin -> Mpin
orN a b = fmap (\(a', b') -> or a' b') $ zip a b
-- The previous defined boolean gates don't allow any way to return anything other than a Bool
-- A separate mechanism was needed, so falling back to Haskell. In chip designs the chip definition
-- allows the designer mechanisms for defining imperative logic for outs not possible here.
muxN :: Bool -> Mpin -> Mpin -> Mpin
muxN sel a b | sel = b
| otherwise = a
orNWay :: Mpin -> Bool
orNWay input = foldl or False input
-- Again I just don't yet see anyway to just use previously defined functions to achieve this chip.
mux4WayN :: Mpin -> Mpin -> Mpin -> Mpin -> (Bool, Bool) -> Mpin
mux4WayN a b c d (sel1, sel2) | and (not sel1) (not sel2) = a -- 00
| and (not sel1) sel2 = b -- 01
| and sel1 (not sel2) = c -- 10
| and sel1 sel2 = d -- 11
mux8WayN :: Mpin -> Mpin -> Mpin -> Mpin -> Mpin -> Mpin -> Mpin -> Mpin -> (Bool, Bool, Bool) -> Mpin
mux8WayN a b c d e f g h (sel1, sel2, sel3) | and (and (not sel1) (not sel2)) (not sel3) = a -- 000
| and (and (not sel1) (not sel2)) sel3 = b -- 001
| and (and (not sel1) sel2 ) (not sel3) = c -- 010
| and (and (not sel1) sel2 ) sel3 = d -- 011
| and (and sel1 (not sel2)) (not sel3) = e -- 100
| and (and sel1 (not sel2)) sel3 = f -- 101
| and (and sel1 sel2 ) (not sel3) = g -- 110
| and (and sel1 sel2 ) sel3 = h -- 111
dmux4Way :: Bool -> (Bool, Bool) -> (Bool, Bool, Bool, Bool)
dmux4Way input (sel1, sel2) = let
a = and (and (not sel1) (not sel2)) input -- 00
b = and (and (not sel1) sel2) input -- 01
c = and (and sel1 (not sel2)) input -- 10
d = and (and sel1 sel2) input -- 11
in ((a, b, c, d))
dmux8Way :: Bool -> (Bool, Bool, Bool) -> (Bool, Bool, Bool, Bool, Bool, Bool, Bool, Bool)
dmux8Way input (sel1, sel2, sel3) = let
a = and (and (and (not sel1) (not sel2)) (not sel3)) input -- 000
b = and (and (and (not sel1) (not sel2)) sel3 ) input -- 001
c = and (and (and (not sel1) sel2 ) (not sel3)) input -- 010
d = and (and (and (not sel1) sel2 ) sel3 ) input -- 011
e = and (and (and sel1 (not sel2)) (not sel3)) input -- 100
f = and (and (and sel1 (not sel2)) sel3 ) input -- 101
g = and (and (and sel1 sel2 ) (not sel3)) input -- 110
h = and (and (and sel1 sel2 ) sel3 ) input -- 111
in ((a, b, c, d, e, f, g, h))
| btipling/machine-vm | src/Machine/Gates.hs | bsd-3-clause | 4,869 | 0 | 15 | 1,888 | 1,643 | 866 | 777 | 80 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Language.ECMAScript5.Parser
import Language.ECMAScript5.Syntax
import Data.ByteString
import Data.String
import Prelude hiding (getContents, putStr)
main :: IO ()
main = do src <- getContents
case parse program "" src of
Left err -> putStr $ "Error: " `append` (fromString $ show err)
Right js -> putStr $ fromString $ show js
| achudnov/language-ecmascript-console | Main.hs | bsd-3-clause | 433 | 0 | 13 | 103 | 124 | 67 | 57 | 12 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Test.Tasty
import Test.Tasty.HUnit
import Language.Haskell.TH
import Language.Haskell.TH.Alpha
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Tests" [unitTests]
unitTests :: TestTree
unitTests = testGroup "Unit tests"
[ testCase "Lambda expressions with different bound variables" $
do
b <- areExpAEq [| \x -> x|] [| \y -> y|]
assertBool "Expressions not considered equal!" b
, testCase "Nested lambda expressions with different bound variables" $
do
b <- areExpAEq [| \f -> \a -> \b -> f a b |] [| \g -> \x -> \y -> g x y|]
assertBool "Expressions not considered equal!" b
, testCase "Equal literals" $
do
b <- areExpAEq [| 5 |] [| 5 |]
assertBool "Expressions not considered equal!" b
, testCase "Different constructors" $
do
b <- areExpAEq [| Left 5 |] [| Right 5 |]
assertBool "Expressions considered equal!" (not b)
, testCase "Let bindings" $
do
b <- areExpAEq [| let x = 5 in x |] [| let y = 5 in y |]
assertBool "Expressions not considered equal!" b
, testCase "Different open terms" $
do
b <- areExpAEq [| tail |] [| head |]
assertBool "Expressions considered equal!" (not b)
, testCase "Same open terms" $
do
b <- areExpAEq [| tail |] [| tail |]
assertBool "Expressions not considered equal!" b
, testCase "Same lambda'd terms" $
do
b <- areExpAEq [| \x -> tail x |] [| \y -> tail y |]
assertBool "Expressions not considered equal!" b
, testCase "@=" $
do
let x = mkName "x"
let y = mkName "y"
b <- runQ $ (LamE [VarP x] (VarE x)) @= (LamE [VarP y] (VarE y))
assertBool "Expressions not considered equal!" b
]
| jkarni/th-alpha | tests/tests.hs | bsd-3-clause | 1,817 | 0 | 16 | 501 | 477 | 250 | 227 | 50 | 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.Ordinal.HR.Tests
( tests ) where
import Data.String
import Prelude
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Ordinal.HR.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "HR Tests"
[ makeCorpusTest [Seal Ordinal] corpus
]
| facebookincubator/duckling | tests/Duckling/Ordinal/HR/Tests.hs | bsd-3-clause | 503 | 0 | 9 | 77 | 79 | 50 | 29 | 11 | 1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
Utilities for desugaring
This module exports some utility functions of no great interest.
-}
{-# LANGUAGE CPP #-}
-- | Utility functions for constructing Core syntax, principally for desugaring
module DsUtils (
EquationInfo(..),
firstPat, shiftEqns,
MatchResult(..), CanItFail(..), CaseAlt(..),
cantFailMatchResult, alwaysFailMatchResult,
extractMatchResult, combineMatchResults,
adjustMatchResult, adjustMatchResultDs,
mkCoLetMatchResult, mkViewMatchResult, mkGuardedMatchResult,
matchCanFail, mkEvalMatchResult,
mkCoPrimCaseMatchResult, mkCoAlgCaseMatchResult, mkCoSynCaseMatchResult,
wrapBind, wrapBinds,
mkErrorAppDs, mkCoreAppDs, mkCoreAppsDs, mkCastDs,
seqVar,
-- LHs tuples
mkLHsVarPatTup, mkLHsPatTup, mkVanillaTuplePat,
mkBigLHsVarTupId, mkBigLHsTupId, mkBigLHsVarPatTupId, mkBigLHsPatTupId,
mkSelectorBinds,
selectSimpleMatchVarL, selectMatchVars, selectMatchVar,
mkOptTickBox, mkBinaryTickBox, getUnBangedLPat
) where
#include "HsVersions.h"
import {-# SOURCE #-} Match ( matchSimply )
import HsSyn
import TcHsSyn
import Coercion( Coercion, isReflCo )
import TcType( tcSplitTyConApp )
import CoreSyn
import DsMonad
import {-# SOURCE #-} DsExpr ( dsLExpr )
import CoreUtils
import MkCore
import MkId
import Id
import Literal
import TyCon
import ConLike
import DataCon
import PatSyn
import Type
import TysPrim
import TysWiredIn
import BasicTypes
import UniqSet
import UniqSupply
import Module
import PrelNames
import Outputable
import SrcLoc
import Util
import DynFlags
import FastString
import TcEvidence
import Control.Monad ( zipWithM )
{-
************************************************************************
* *
\subsection{ Selecting match variables}
* *
************************************************************************
We're about to match against some patterns. We want to make some
@Ids@ to use as match variables. If a pattern has an @Id@ readily at
hand, which should indeed be bound to the pattern as a whole, then use it;
otherwise, make one up.
-}
selectSimpleMatchVarL :: LPat Id -> DsM Id
selectSimpleMatchVarL pat = selectMatchVar (unLoc pat)
-- (selectMatchVars ps tys) chooses variables of type tys
-- to use for matching ps against. If the pattern is a variable,
-- we try to use that, to save inventing lots of fresh variables.
--
-- OLD, but interesting note:
-- But even if it is a variable, its type might not match. Consider
-- data T a where
-- T1 :: Int -> T Int
-- T2 :: a -> T a
--
-- f :: T a -> a -> Int
-- f (T1 i) (x::Int) = x
-- f (T2 i) (y::a) = 0
-- Then we must not choose (x::Int) as the matching variable!
-- And nowadays we won't, because the (x::Int) will be wrapped in a CoPat
selectMatchVars :: [Pat Id] -> DsM [Id]
selectMatchVars ps = mapM selectMatchVar ps
selectMatchVar :: Pat Id -> DsM Id
selectMatchVar (BangPat pat) = selectMatchVar (unLoc pat)
selectMatchVar (LazyPat pat) = selectMatchVar (unLoc pat)
selectMatchVar (ParPat pat) = selectMatchVar (unLoc pat)
selectMatchVar (VarPat var) = return (localiseId var) -- Note [Localise pattern binders]
selectMatchVar (AsPat var _) = return (unLoc var)
selectMatchVar other_pat = newSysLocalDs (hsPatType other_pat)
-- OK, better make up one...
{-
Note [Localise pattern binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider module M where
[Just a] = e
After renaming it looks like
module M where
[Just M.a] = e
We don't generalise, since it's a pattern binding, monomorphic, etc,
so after desugaring we may get something like
M.a = case e of (v:_) ->
case v of Just M.a -> M.a
Notice the "M.a" in the pattern; after all, it was in the original
pattern. However, after optimisation those pattern binders can become
let-binders, and then end up floated to top level. They have a
different *unique* by then (the simplifier is good about maintaining
proper scoping), but it's BAD to have two top-level bindings with the
External Name M.a, because that turns into two linker symbols for M.a.
It's quite rare for this to actually *happen* -- the only case I know
of is tc003 compiled with the 'hpc' way -- but that only makes it
all the more annoying.
To avoid this, we craftily call 'localiseId' in the desugarer, which
simply turns the External Name for the Id into an Internal one, but
doesn't change the unique. So the desugarer produces this:
M.a{r8} = case e of (v:_) ->
case v of Just a{r8} -> M.a{r8}
The unique is still 'r8', but the binding site in the pattern
is now an Internal Name. Now the simplifier's usual mechanisms
will propagate that Name to all the occurrence sites, as well as
un-shadowing it, so we'll get
M.a{r8} = case e of (v:_) ->
case v of Just a{s77} -> a{s77}
In fact, even CoreSubst.simplOptExpr will do this, and simpleOptExpr
runs on the output of the desugarer, so all is well by the end of
the desugaring pass.
************************************************************************
* *
* type synonym EquationInfo and access functions for its pieces *
* *
************************************************************************
\subsection[EquationInfo-synonym]{@EquationInfo@: a useful synonym}
The ``equation info'' used by @match@ is relatively complicated and
worthy of a type synonym and a few handy functions.
-}
firstPat :: EquationInfo -> Pat Id
firstPat eqn = ASSERT( notNull (eqn_pats eqn) ) head (eqn_pats eqn)
shiftEqns :: [EquationInfo] -> [EquationInfo]
-- Drop the first pattern in each equation
shiftEqns eqns = [ eqn { eqn_pats = tail (eqn_pats eqn) } | eqn <- eqns ]
-- Functions on MatchResults
matchCanFail :: MatchResult -> Bool
matchCanFail (MatchResult CanFail _) = True
matchCanFail (MatchResult CantFail _) = False
alwaysFailMatchResult :: MatchResult
alwaysFailMatchResult = MatchResult CanFail (\fail -> return fail)
cantFailMatchResult :: CoreExpr -> MatchResult
cantFailMatchResult expr = MatchResult CantFail (\_ -> return expr)
extractMatchResult :: MatchResult -> CoreExpr -> DsM CoreExpr
extractMatchResult (MatchResult CantFail match_fn) _
= match_fn (error "It can't fail!")
extractMatchResult (MatchResult CanFail match_fn) fail_expr = do
(fail_bind, if_it_fails) <- mkFailurePair fail_expr
body <- match_fn if_it_fails
return (mkCoreLet fail_bind body)
combineMatchResults :: MatchResult -> MatchResult -> MatchResult
combineMatchResults (MatchResult CanFail body_fn1)
(MatchResult can_it_fail2 body_fn2)
= MatchResult can_it_fail2 body_fn
where
body_fn fail = do body2 <- body_fn2 fail
(fail_bind, duplicatable_expr) <- mkFailurePair body2
body1 <- body_fn1 duplicatable_expr
return (Let fail_bind body1)
combineMatchResults match_result1@(MatchResult CantFail _) _
= match_result1
adjustMatchResult :: DsWrapper -> MatchResult -> MatchResult
adjustMatchResult encl_fn (MatchResult can_it_fail body_fn)
= MatchResult can_it_fail (\fail -> encl_fn <$> body_fn fail)
adjustMatchResultDs :: (CoreExpr -> DsM CoreExpr) -> MatchResult -> MatchResult
adjustMatchResultDs encl_fn (MatchResult can_it_fail body_fn)
= MatchResult can_it_fail (\fail -> encl_fn =<< body_fn fail)
wrapBinds :: [(Var,Var)] -> CoreExpr -> CoreExpr
wrapBinds [] e = e
wrapBinds ((new,old):prs) e = wrapBind new old (wrapBinds prs e)
wrapBind :: Var -> Var -> CoreExpr -> CoreExpr
wrapBind new old body -- NB: this function must deal with term
| new==old = body -- variables, type variables or coercion variables
| otherwise = Let (NonRec new (varToCoreExpr old)) body
seqVar :: Var -> CoreExpr -> CoreExpr
seqVar var body = Case (Var var) var (exprType body)
[(DEFAULT, [], body)]
mkCoLetMatchResult :: CoreBind -> MatchResult -> MatchResult
mkCoLetMatchResult bind = adjustMatchResult (mkCoreLet bind)
-- (mkViewMatchResult var' viewExpr var mr) makes the expression
-- let var' = viewExpr var in mr
mkViewMatchResult :: Id -> CoreExpr -> Id -> MatchResult -> MatchResult
mkViewMatchResult var' viewExpr var =
adjustMatchResult (mkCoreLet (NonRec var' (mkCoreAppDs (text "mkView" <+> ppr var') viewExpr (Var var))))
mkEvalMatchResult :: Id -> Type -> MatchResult -> MatchResult
mkEvalMatchResult var ty
= adjustMatchResult (\e -> Case (Var var) var ty [(DEFAULT, [], e)])
mkGuardedMatchResult :: CoreExpr -> MatchResult -> MatchResult
mkGuardedMatchResult pred_expr (MatchResult _ body_fn)
= MatchResult CanFail (\fail -> do body <- body_fn fail
return (mkIfThenElse pred_expr body fail))
mkCoPrimCaseMatchResult :: Id -- Scrutinee
-> Type -- Type of the case
-> [(Literal, MatchResult)] -- Alternatives
-> MatchResult -- Literals are all unlifted
mkCoPrimCaseMatchResult var ty match_alts
= MatchResult CanFail mk_case
where
mk_case fail = do
alts <- mapM (mk_alt fail) sorted_alts
return (Case (Var var) var ty ((DEFAULT, [], fail) : alts))
sorted_alts = sortWith fst match_alts -- Right order for a Case
mk_alt fail (lit, MatchResult _ body_fn)
= ASSERT( not (litIsLifted lit) )
do body <- body_fn fail
return (LitAlt lit, [], body)
data CaseAlt a = MkCaseAlt{ alt_pat :: a,
alt_bndrs :: [CoreBndr],
alt_wrapper :: HsWrapper,
alt_result :: MatchResult }
mkCoAlgCaseMatchResult
:: DynFlags
-> Id -- Scrutinee
-> Type -- Type of exp
-> [CaseAlt DataCon] -- Alternatives (bndrs *include* tyvars, dicts)
-> MatchResult
mkCoAlgCaseMatchResult dflags var ty match_alts
| isNewtype -- Newtype case; use a let
= ASSERT( null (tail match_alts) && null (tail arg_ids1) )
mkCoLetMatchResult (NonRec arg_id1 newtype_rhs) match_result1
| isPArrFakeAlts match_alts
= MatchResult CanFail $ mkPArrCase dflags var ty (sort_alts match_alts)
| otherwise
= mkDataConCase var ty match_alts
where
isNewtype = isNewTyCon (dataConTyCon (alt_pat alt1))
-- [Interesting: because of GADTs, we can't rely on the type of
-- the scrutinised Id to be sufficiently refined to have a TyCon in it]
alt1@MkCaseAlt{ alt_bndrs = arg_ids1, alt_result = match_result1 }
= ASSERT( notNull match_alts ) head match_alts
-- Stuff for newtype
arg_id1 = ASSERT( notNull arg_ids1 ) head arg_ids1
var_ty = idType var
(tc, ty_args) = tcSplitTyConApp var_ty -- Don't look through newtypes
-- (not that splitTyConApp does, these days)
newtype_rhs = unwrapNewTypeBody tc ty_args (Var var)
--- Stuff for parallel arrays
--
-- Concerning `isPArrFakeAlts':
--
-- * it is *not* sufficient to just check the type of the type
-- constructor, as we have to be careful not to confuse the real
-- representation of parallel arrays with the fake constructors;
-- moreover, a list of alternatives must not mix fake and real
-- constructors (this is checked earlier on)
--
-- FIXME: We actually go through the whole list and make sure that
-- either all or none of the constructors are fake parallel
-- array constructors. This is to spot equations that mix fake
-- constructors with the real representation defined in
-- `PrelPArr'. It would be nicer to spot this situation
-- earlier and raise a proper error message, but it can really
-- only happen in `PrelPArr' anyway.
--
isPArrFakeAlts :: [CaseAlt DataCon] -> Bool
isPArrFakeAlts [alt] = isPArrFakeCon (alt_pat alt)
isPArrFakeAlts (alt:alts) =
case (isPArrFakeCon (alt_pat alt), isPArrFakeAlts alts) of
(True , True ) -> True
(False, False) -> False
_ -> panic "DsUtils: you may not mix `[:...:]' with `PArr' patterns"
isPArrFakeAlts [] = panic "DsUtils: unexpectedly found an empty list of PArr fake alternatives"
mkCoSynCaseMatchResult :: Id -> Type -> CaseAlt PatSyn -> MatchResult
mkCoSynCaseMatchResult var ty alt = MatchResult CanFail $ mkPatSynCase var ty alt
sort_alts :: [CaseAlt DataCon] -> [CaseAlt DataCon]
sort_alts = sortWith (dataConTag . alt_pat)
mkPatSynCase :: Id -> Type -> CaseAlt PatSyn -> CoreExpr -> DsM CoreExpr
mkPatSynCase var ty alt fail = do
matcher <- dsLExpr $ mkLHsWrap wrapper $ nlHsTyApp matcher [ty]
let MatchResult _ mkCont = match_result
cont <- mkCoreLams bndrs <$> mkCont fail
return $ mkCoreAppsDs (text "patsyn" <+> ppr var) matcher [Var var, ensure_unstrict cont, Lam voidArgId fail]
where
MkCaseAlt{ alt_pat = psyn,
alt_bndrs = bndrs,
alt_wrapper = wrapper,
alt_result = match_result} = alt
(matcher, needs_void_lam) = patSynMatcher psyn
-- See Note [Matchers and builders for pattern synonyms] in PatSyns
-- on these extra Void# arguments
ensure_unstrict cont | needs_void_lam = Lam voidArgId cont
| otherwise = cont
mkDataConCase :: Id -> Type -> [CaseAlt DataCon] -> MatchResult
mkDataConCase _ _ [] = panic "mkDataConCase: no alternatives"
mkDataConCase var ty alts@(alt1:_) = MatchResult fail_flag mk_case
where
con1 = alt_pat alt1
tycon = dataConTyCon con1
data_cons = tyConDataCons tycon
match_results = map alt_result alts
sorted_alts :: [CaseAlt DataCon]
sorted_alts = sort_alts alts
var_ty = idType var
(_, ty_args) = tcSplitTyConApp var_ty -- Don't look through newtypes
-- (not that splitTyConApp does, these days)
mk_case :: CoreExpr -> DsM CoreExpr
mk_case fail = do
alts <- mapM (mk_alt fail) sorted_alts
return $ mkWildCase (Var var) (idType var) ty (mk_default fail ++ alts)
mk_alt :: CoreExpr -> CaseAlt DataCon -> DsM CoreAlt
mk_alt fail MkCaseAlt{ alt_pat = con,
alt_bndrs = args,
alt_result = MatchResult _ body_fn }
= do { body <- body_fn fail
; case dataConBoxer con of {
Nothing -> return (DataAlt con, args, body) ;
Just (DCB boxer) ->
do { us <- newUniqueSupply
; let (rep_ids, binds) = initUs_ us (boxer ty_args args)
; return (DataAlt con, rep_ids, mkLets binds body) } } }
mk_default :: CoreExpr -> [CoreAlt]
mk_default fail | exhaustive_case = []
| otherwise = [(DEFAULT, [], fail)]
fail_flag :: CanItFail
fail_flag | exhaustive_case
= foldr orFail CantFail [can_it_fail | MatchResult can_it_fail _ <- match_results]
| otherwise
= CanFail
mentioned_constructors = mkUniqSet $ map alt_pat alts
un_mentioned_constructors
= mkUniqSet data_cons `minusUniqSet` mentioned_constructors
exhaustive_case = isEmptyUniqSet un_mentioned_constructors
--- Stuff for parallel arrays
--
-- * the following is to desugar cases over fake constructors for
-- parallel arrays, which are introduced by `tidy1' in the `PArrPat'
-- case
--
mkPArrCase :: DynFlags -> Id -> Type -> [CaseAlt DataCon] -> CoreExpr -> DsM CoreExpr
mkPArrCase dflags var ty sorted_alts fail = do
lengthP <- dsDPHBuiltin lengthPVar
alt <- unboxAlt
return (mkWildCase (len lengthP) intTy ty [alt])
where
elemTy = case splitTyConApp (idType var) of
(_, [elemTy]) -> elemTy
_ -> panic panicMsg
panicMsg = "DsUtils.mkCoAlgCaseMatchResult: not a parallel array?"
len lengthP = mkApps (Var lengthP) [Type elemTy, Var var]
--
unboxAlt = do
l <- newSysLocalDs intPrimTy
indexP <- dsDPHBuiltin indexPVar
alts <- mapM (mkAlt indexP) sorted_alts
return (DataAlt intDataCon, [l], mkWildCase (Var l) intPrimTy ty (dft : alts))
where
dft = (DEFAULT, [], fail)
--
-- each alternative matches one array length (corresponding to one
-- fake array constructor), so the match is on a literal; each
-- alternative's body is extended by a local binding for each
-- constructor argument, which are bound to array elements starting
-- with the first
--
mkAlt indexP alt@MkCaseAlt{alt_result = MatchResult _ bodyFun} = do
body <- bodyFun fail
return (LitAlt lit, [], mkCoreLets binds body)
where
lit = MachInt $ toInteger (dataConSourceArity (alt_pat alt))
binds = [NonRec arg (indexExpr i) | (i, arg) <- zip [1..] (alt_bndrs alt)]
--
indexExpr i = mkApps (Var indexP) [Type elemTy, Var var, mkIntExpr dflags i]
{-
************************************************************************
* *
\subsection{Desugarer's versions of some Core functions}
* *
************************************************************************
-}
mkErrorAppDs :: Id -- The error function
-> Type -- Type to which it should be applied
-> SDoc -- The error message string to pass
-> DsM CoreExpr
mkErrorAppDs err_id ty msg = do
src_loc <- getSrcSpanDs
dflags <- getDynFlags
let
full_msg = showSDoc dflags (hcat [ppr src_loc, vbar, msg])
core_msg = Lit (mkMachString full_msg)
-- mkMachString returns a result of type String#
return (mkApps (Var err_id) [Type ty, core_msg])
{-
'mkCoreAppDs' and 'mkCoreAppsDs' hand the special-case desugaring of 'seq'.
Note [Desugaring seq (1)] cf Trac #1031
~~~~~~~~~~~~~~~~~~~~~~~~~
f x y = x `seq` (y `seq` (# x,y #))
The [CoreSyn let/app invariant] means that, other things being equal, because
the argument to the outer 'seq' has an unlifted type, we'll use call-by-value thus:
f x y = case (y `seq` (# x,y #)) of v -> x `seq` v
But that is bad for two reasons:
(a) we now evaluate y before x, and
(b) we can't bind v to an unboxed pair
Seq is very, very special! So we recognise it right here, and desugar to
case x of _ -> case y of _ -> (# x,y #)
Note [Desugaring seq (2)] cf Trac #2273
~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
let chp = case b of { True -> fst x; False -> 0 }
in chp `seq` ...chp...
Here the seq is designed to plug the space leak of retaining (snd x)
for too long.
If we rely on the ordinary inlining of seq, we'll get
let chp = case b of { True -> fst x; False -> 0 }
case chp of _ { I# -> ...chp... }
But since chp is cheap, and the case is an alluring contet, we'll
inline chp into the case scrutinee. Now there is only one use of chp,
so we'll inline a second copy. Alas, we've now ruined the purpose of
the seq, by re-introducing the space leak:
case (case b of {True -> fst x; False -> 0}) of
I# _ -> ...case b of {True -> fst x; False -> 0}...
We can try to avoid doing this by ensuring that the binder-swap in the
case happens, so we get his at an early stage:
case chp of chp2 { I# -> ...chp2... }
But this is fragile. The real culprit is the source program. Perhaps we
should have said explicitly
let !chp2 = chp in ...chp2...
But that's painful. So the code here does a little hack to make seq
more robust: a saturated application of 'seq' is turned *directly* into
the case expression, thus:
x `seq` e2 ==> case x of x -> e2 -- Note shadowing!
e1 `seq` e2 ==> case x of _ -> e2
So we desugar our example to:
let chp = case b of { True -> fst x; False -> 0 }
case chp of chp { I# -> ...chp... }
And now all is well.
The reason it's a hack is because if you define mySeq=seq, the hack
won't work on mySeq.
Note [Desugaring seq (3)] cf Trac #2409
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The isLocalId ensures that we don't turn
True `seq` e
into
case True of True { ... }
which stupidly tries to bind the datacon 'True'.
-}
mkCoreAppDs :: SDoc -> CoreExpr -> CoreExpr -> CoreExpr
mkCoreAppDs _ (Var f `App` Type ty1 `App` Type ty2 `App` arg1) arg2
| f `hasKey` seqIdKey -- Note [Desugaring seq (1), (2)]
= Case arg1 case_bndr ty2 [(DEFAULT,[],arg2)]
where
case_bndr = case arg1 of
Var v1 | isLocalId v1 -> v1 -- Note [Desugaring seq (2) and (3)]
_ -> mkWildValBinder ty1
mkCoreAppDs s fun arg = mkCoreApp s fun arg -- The rest is done in MkCore
mkCoreAppsDs :: SDoc -> CoreExpr -> [CoreExpr] -> CoreExpr
mkCoreAppsDs s fun args = foldl (mkCoreAppDs s) fun args
mkCastDs :: CoreExpr -> Coercion -> CoreExpr
-- We define a desugarer-specific verison of CoreUtils.mkCast,
-- because in the immediate output of the desugarer, we can have
-- apparently-mis-matched coercions: E.g.
-- let a = b
-- in (x :: a) |> (co :: b ~ Int)
-- Lint know about type-bindings for let and does not complain
-- So here we do not make the assertion checks that we make in
-- CoreUtils.mkCast; and we do less peephole optimisation too
mkCastDs e co | isReflCo co = e
| otherwise = Cast e co
{-
************************************************************************
* *
Tuples and selector bindings
* *
************************************************************************
This is used in various places to do with lazy patterns.
For each binder $b$ in the pattern, we create a binding:
\begin{verbatim}
b = case v of pat' -> b'
\end{verbatim}
where @pat'@ is @pat@ with each binder @b@ cloned into @b'@.
ToDo: making these bindings should really depend on whether there's
much work to be done per binding. If the pattern is complex, it
should be de-mangled once, into a tuple (and then selected from).
Otherwise the demangling can be in-line in the bindings (as here).
Boring! Boring! One error message per binder. The above ToDo is
even more helpful. Something very similar happens for pattern-bound
expressions.
Note [mkSelectorBinds]
~~~~~~~~~~~~~~~~~~~~~~
Given p = e, where p binds x,y
we are going to make EITHER
EITHER (A) v = e (where v is fresh)
x = case v of p -> x
y = case v of p -> y
OR (B) t = case e of p -> (x,y)
x = case t of (x,_) -> x
y = case t of (_,y) -> y
We do (A) when
* Matching the pattern is cheap so we don't mind
doing it twice.
* Or if the pattern binds only one variable (so we'll only
match once)
* AND the pattern can't fail (else we tiresomely get two inexhaustive
pattern warning messages)
Otherwise we do (B). Really (A) is just an optimisation for very common
cases like
Just x = e
(p,q) = e
-}
mkSelectorBinds :: Bool -- ^ is strict
-> [[Tickish Id]] -- ^ ticks to add, possibly
-> LPat Id -- ^ The pattern
-> CoreExpr -- ^ Expression to which the pattern is bound
-> DsM (Maybe Id,[(Id,CoreExpr)])
-- ^ Id the rhs is bound to, for desugaring strict
-- binds (see Note [Desugar Strict binds] in DsBinds)
-- and all the desugared binds
mkSelectorBinds _ ticks (L _ (VarPat v)) val_expr
= return (Just v
,[(v, case ticks of
[t] -> mkOptTickBox t val_expr
_ -> val_expr)])
mkSelectorBinds is_strict ticks pat val_expr
| null binders, not is_strict
= return (Nothing, [])
| isSingleton binders || is_simple_lpat pat
-- See Note [mkSelectorBinds]
= do { val_var <- newSysLocalDs (hsLPatType pat)
-- Make up 'v' in Note [mkSelectorBinds]
-- NB: give it the type of *pattern* p, not the type of the *rhs* e.
-- This does not matter after desugaring, but there's a subtle
-- issue with implicit parameters. Consider
-- (x,y) = ?i
-- Then, ?i is given type {?i :: Int}, a PredType, which is opaque
-- to the desugarer. (Why opaque? Because newtypes have to be. Why
-- does it get that type? So that when we abstract over it we get the
-- right top-level type (?i::Int) => ...)
--
-- So to get the type of 'v', use the pattern not the rhs. Often more
-- efficient too.
-- For the error message we make one error-app, to avoid duplication.
-- But we need it at different types, so we make it polymorphic:
-- err_var = /\a. iRREFUT_PAT_ERR a "blah blah blah"
; err_app <- mkErrorAppDs iRREFUT_PAT_ERROR_ID alphaTy (ppr pat)
; err_var <- newSysLocalDs (mkForAllTy alphaTyVar alphaTy)
; binds <- zipWithM (mk_bind val_var err_var) ticks' binders
; return (Just val_var
,(val_var, val_expr) :
(err_var, Lam alphaTyVar err_app) :
binds) }
| otherwise
= do { val_var <- newSysLocalDs (hsLPatType pat)
; error_expr <- mkErrorAppDs iRREFUT_PAT_ERROR_ID tuple_ty (ppr pat)
; tuple_expr
<- matchSimply (Var val_var) PatBindRhs pat local_tuple error_expr
; tuple_var <- newSysLocalDs tuple_ty
; let mk_tup_bind tick binder
= (binder, mkOptTickBox tick $
mkTupleSelector local_binders binder
tuple_var (Var tuple_var))
-- if strict and no binders we want to force the case
-- expression to force an error if the pattern match
-- failed. See Note [Desugar Strict binds] in DsBinds.
; let force_var = if null binders && is_strict
then tuple_var
else val_var
; return (Just force_var
,(val_var,val_expr) :
(tuple_var, tuple_expr) :
zipWith mk_tup_bind ticks' binders) }
where
binders = collectPatBinders pat
ticks' = ticks ++ repeat []
local_binders = map localiseId binders -- See Note [Localise pattern binders]
local_tuple = mkBigCoreVarTup binders
tuple_ty = exprType local_tuple
mk_bind scrut_var err_var tick bndr_var = do
-- (mk_bind sv err_var) generates
-- bv = case sv of { pat -> bv; other -> err_var @ type-of-bv }
-- Remember, pat binds bv
rhs_expr <- matchSimply (Var scrut_var) PatBindRhs pat
(Var bndr_var) error_expr
return (bndr_var, mkOptTickBox tick rhs_expr)
where
error_expr = Var err_var `App` Type (idType bndr_var)
is_simple_lpat p = is_simple_pat (unLoc p)
is_simple_pat (TuplePat ps Boxed _) = all is_triv_lpat ps
is_simple_pat pat@(ConPatOut{}) = case unLoc (pat_con pat) of
RealDataCon con -> isProductTyCon (dataConTyCon con)
&& all is_triv_lpat (hsConPatArgs (pat_args pat))
PatSynCon _ -> False
is_simple_pat (VarPat _) = True
is_simple_pat (ParPat p) = is_simple_lpat p
is_simple_pat _ = False
is_triv_lpat p = is_triv_pat (unLoc p)
is_triv_pat (VarPat _) = True
is_triv_pat (WildPat _) = True
is_triv_pat (ParPat p) = is_triv_lpat p
is_triv_pat _ = False
{-
Creating big tuples and their types for full Haskell expressions.
They work over *Ids*, and create tuples replete with their types,
which is whey they are not in HsUtils.
-}
mkLHsPatTup :: [LPat Id] -> LPat Id
mkLHsPatTup [] = noLoc $ mkVanillaTuplePat [] Boxed
mkLHsPatTup [lpat] = lpat
mkLHsPatTup lpats = L (getLoc (head lpats)) $
mkVanillaTuplePat lpats Boxed
mkLHsVarPatTup :: [Id] -> LPat Id
mkLHsVarPatTup bs = mkLHsPatTup (map nlVarPat bs)
mkVanillaTuplePat :: [OutPat Id] -> Boxity -> Pat Id
-- A vanilla tuple pattern simply gets its type from its sub-patterns
mkVanillaTuplePat pats box = TuplePat pats box (map hsLPatType pats)
-- The Big equivalents for the source tuple expressions
mkBigLHsVarTupId :: [Id] -> LHsExpr Id
mkBigLHsVarTupId ids = mkBigLHsTupId (map nlHsVar ids)
mkBigLHsTupId :: [LHsExpr Id] -> LHsExpr Id
mkBigLHsTupId = mkChunkified mkLHsTupleExpr
-- The Big equivalents for the source tuple patterns
mkBigLHsVarPatTupId :: [Id] -> LPat Id
mkBigLHsVarPatTupId bs = mkBigLHsPatTupId (map nlVarPat bs)
mkBigLHsPatTupId :: [LPat Id] -> LPat Id
mkBigLHsPatTupId = mkChunkified mkLHsPatTup
{-
************************************************************************
* *
Code for pattern-matching and other failures
* *
************************************************************************
Generally, we handle pattern matching failure like this: let-bind a
fail-variable, and use that variable if the thing fails:
\begin{verbatim}
let fail.33 = error "Help"
in
case x of
p1 -> ...
p2 -> fail.33
p3 -> fail.33
p4 -> ...
\end{verbatim}
Then
\begin{itemize}
\item
If the case can't fail, then there'll be no mention of @fail.33@, and the
simplifier will later discard it.
\item
If it can fail in only one way, then the simplifier will inline it.
\item
Only if it is used more than once will the let-binding remain.
\end{itemize}
There's a problem when the result of the case expression is of
unboxed type. Then the type of @fail.33@ is unboxed too, and
there is every chance that someone will change the let into a case:
\begin{verbatim}
case error "Help" of
fail.33 -> case ....
\end{verbatim}
which is of course utterly wrong. Rather than drop the condition that
only boxed types can be let-bound, we just turn the fail into a function
for the primitive case:
\begin{verbatim}
let fail.33 :: Void -> Int#
fail.33 = \_ -> error "Help"
in
case x of
p1 -> ...
p2 -> fail.33 void
p3 -> fail.33 void
p4 -> ...
\end{verbatim}
Now @fail.33@ is a function, so it can be let-bound.
-}
mkFailurePair :: CoreExpr -- Result type of the whole case expression
-> DsM (CoreBind, -- Binds the newly-created fail variable
-- to \ _ -> expression
CoreExpr) -- Fail variable applied to realWorld#
-- See Note [Failure thunks and CPR]
mkFailurePair expr
= do { fail_fun_var <- newFailLocalDs (voidPrimTy `mkFunTy` ty)
; fail_fun_arg <- newSysLocalDs voidPrimTy
; let real_arg = setOneShotLambda fail_fun_arg
; return (NonRec fail_fun_var (Lam real_arg expr),
App (Var fail_fun_var) (Var voidPrimId)) }
where
ty = exprType expr
{-
Note [Failure thunks and CPR]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we make a failure point we ensure that it
does not look like a thunk. Example:
let fail = \rw -> error "urk"
in case x of
[] -> fail realWorld#
(y:ys) -> case ys of
[] -> fail realWorld#
(z:zs) -> (y,z)
Reason: we know that a failure point is always a "join point" and is
entered at most once. Adding a dummy 'realWorld' token argument makes
it clear that sharing is not an issue. And that in turn makes it more
CPR-friendly. This matters a lot: if you don't get it right, you lose
the tail call property. For example, see Trac #3403.
************************************************************************
* *
Ticks
* *
********************************************************************* -}
mkOptTickBox :: [Tickish Id] -> CoreExpr -> CoreExpr
mkOptTickBox = flip (foldr Tick)
mkBinaryTickBox :: Int -> Int -> CoreExpr -> DsM CoreExpr
mkBinaryTickBox ixT ixF e = do
uq <- newUnique
this_mod <- getModule
let bndr1 = mkSysLocal (fsLit "t1") uq boolTy
let
falseBox = Tick (HpcTick this_mod ixF) (Var falseDataConId)
trueBox = Tick (HpcTick this_mod ixT) (Var trueDataConId)
--
return $ Case e bndr1 boolTy
[ (DataAlt falseDataCon, [], falseBox)
, (DataAlt trueDataCon, [], trueBox)
]
-- *******************************************************************
-- | Remove any bang from a pattern and say if it is a strict bind,
-- also make irrefutable patterns ordinary patterns if -XStrict.
--
-- Example:
-- ~pat => False, pat -- when -XStrict
-- ~pat => False, ~pat -- without -XStrict
-- ~(~pat) => False, ~pat -- when -XStrict
-- pat => True, pat -- when -XStrict
-- !pat => True, pat -- always
getUnBangedLPat :: DynFlags
-> LPat id -- ^ Original pattern
-> (Bool, LPat id) -- is bind strict?, pattern without bangs
getUnBangedLPat dflags (L l (ParPat p))
= let (is_strict, p') = getUnBangedLPat dflags p
in (is_strict, L l (ParPat p'))
getUnBangedLPat _ (L _ (BangPat p))
= (True,p)
getUnBangedLPat dflags (L _ (LazyPat p))
| xopt Opt_Strict dflags
= (False,p)
getUnBangedLPat dflags p
= (xopt Opt_Strict dflags,p)
| elieux/ghc | compiler/deSugar/DsUtils.hs | bsd-3-clause | 34,479 | 0 | 19 | 9,741 | 5,537 | 2,889 | 2,648 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : Language.VHDL.Error
-- Copyright : (c) SAM Group, KTH/ICT/ECS 2007-2008
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : christiaan.baaij@gmail.com
-- Stability : experimental
-- Portability : portable
--
-- ForSyDe error-related types and functions.
--
-----------------------------------------------------------------------------
module Language.VHDL.Error
(VHDLErr(..),
EProne,
module Control.Monad.Error,
module Debug.Trace) where
import Debug.Trace
import Control.Monad.Error
-------------
-- VHDLErr
-------------
-- | All Errors thrown or displayed in ForSyDe
data VHDLErr =
-- Used in ForSyDe.Backend.VHDL.*
-- | Empty VHDL identifier
EmptyVHDLId |
-- | Incorrect Basic VHDL Identifier
IncVHDLBasId String |
-- | Incorrect Extended VHDL Identifier
IncVHDLExtId String |
-- | Other Errors
Other String
-- | Show errors
instance Show VHDLErr where
show EmptyVHDLId = "Empty VHDL identifier"
show (IncVHDLBasId id) = "Incorrect VHDL basic identifier " ++
"`" ++ id ++ "'"
show (IncVHDLExtId id) = "Incorrect VHDL extended identifier " ++
"`" ++ id ++ "'"
--------------
-- Error Monad
--------------
-- | We make CLasHErr an instance of the Error class to be able to throw it
-- as an exception.
instance Error VHDLErr where
noMsg = Other "An Error has ocurred"
strMsg = Other
-- | 'EProne' represents failure using Left CLasHErr or a successful
-- result of type a using Right a
--
-- 'EProne' is implicitly an instance of
-- ['MonadError'] (@Error e => MonadError e (Either e)@)
-- ['Monad'] (@Error e => Monad (Either e)@)
type EProne = Either VHDLErr
-- FIXME: Rethink Eprone so that it takes contexts in account
| christiaanb/vhdl | Language/VHDL/Error.hs | bsd-3-clause | 1,948 | 0 | 8 | 468 | 198 | 127 | 71 | 22 | 0 |
module Main where
import System.IO
import Control.Applicative
import Control.Monad.Trans.Reader
import qualified Data.Map as Map
import Parser
import TypeInferencer
import Interpreter
import Ast
main :: IO ()
main = withFile
"test/lambda.js"
ReadMode
(\handle -> do
source <- hGetContents handle
-- putStrLn $ show $ jsparse source
putStrLn $ interpreter source
)
-- Some glue code
interpreter :: String -> String
interpreter source = case jsparse source of
Right ts -> (case interp ts of Right s -> s
Left e -> e)
Left error -> show error
where interp t = do ty <- typeInference t
let result = interpreate t
return $ show result ++ " : " ++ show ty
| fiigii/fJS | Main.hs | mit | 998 | 0 | 12 | 459 | 219 | 111 | 108 | 24 | 3 |
module PCProblem.Generator
( generator
)
where
import PCProblem.Type
import PCProblem.Param
import PCProblem.Solver
import Autolib.Util.Zufall
import Autolib.Letters
import Data.Maybe
import Data.List ( nub )
import Autolib.Set
import Inter.Quiz
gen :: Param -> IO PCP
gen p = do
{- hier kamen noch doppelte paare und/oder paare mit identischen strings vor
uvs <- sequence $ do
k <- [ 1 .. paare p ]
return $ do
l <- randomRIO (1, breite p)
[u, v] <- sequence $ replicate 2 $ someIO ( alpha g ) l
return ( u, v )
-}
uvs <- ( sequence $ replicate ( paare p ) $ pair p )
`repeat_until`
\ uvs -> and [ -- alle paare verschieden
uvs == nub uvs
-- alle buchstaben kommen vor
, let (l,r) = unzip uvs
in length ( nub $ concat $ l ++ r )
==
length ( alpha p )
-- es gibt mindestens ein wort mit
-- (mindestens) der geforderten breite
, any ( \ (u,v) -> or [ length u >= breite p
, length v >= breite p
]
) uvs
]
let (u1, v1) : (u2, v2) : rest = uvs
-- hackerei für anfang und ende
let uvs' = ( v1 ++ u1, v1 ) : ( u2 , v2 ++ u2 ) : rest
xys <- permutation uvs'
return $ PCP xys
pair :: Param -> IO (String,String)
pair p = ( do l <- randomRIO (1,breite p)
[u,v] <- sequence $ replicate 2 $ someIO ( alpha p ) l
return (u,v)
) `repeat_until` ( uncurry (/=) )
-- | nur eine kürzeste lösung
sol :: Param -> IO ( PCP, Maybe Folge )
sol p = do
i <- gen p -- Instanz
let fs = solutions ( viel p ) ( fern p ) i
return ( i, listToMaybe $ take 1 $ fs )
-- | falls ein buchstabe nur einseitige differenzen hat,
-- dann nützt er in der lösung nicht viel (?? - check)
triviale_instanz :: PCP -> Bool
triviale_instanz i @ ( PCP uvs ) = or $ do
x <- setToList $ letters i
let diffs = do
( u, v ) <- uvs
return ( count x u - count x v )
return $ all ( >= 0 ) diffs || all ( <= 0 ) diffs
count :: Eq a => a -> [a] -> Int
count x = length . filter ( == x )
instance Generator PCProblem Param ( PCP, Folge ) where
generator _ conf key = do
( i, Just f ) <- sol conf `repeat_until` \ ( i, mf ) ->
not ( triviale_instanz i ) &&
case mf of
Nothing -> False
Just f -> and [ nah conf <= length f
, length f <= fern conf
-- alle paare sollen in der lösung vorkommen
, length (nub f) == paare conf
]
return ( i, f )
instance Project PCProblem ( PCP, Folge ) PCP where
project p ( i, f ) = i
| florianpilz/autotool | src/PCProblem/Generator.hs | gpl-2.0 | 2,708 | 20 | 20 | 950 | 911 | 470 | 441 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : $Header$
Description : definition of the datatype describing
the abstract FreeCAD terms and and a few tools describing simple
mathematical operations on those building-blocks (3d vectors,
rotation matrices, rotation quaternions)
Copyright : (c) Robert Savu and Uni Bremen 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Robert.Savu@dfki.de
Stability : experimental
Portability : portable
Declaration of the abstract datatypes of FreeCAD terms
-}
module FreeCAD.As where
import Data.Data
import qualified Data.Set as Set
data Vector3 =
Vector3 { x :: Double, y :: Double, z :: Double }
deriving (Show, Eq, Ord, Typeable, Data)
data Matrix33 = Matrix33 { a11 :: Double , a12 :: Double , a13 :: Double
, a21 :: Double , a22 :: Double , a23 :: Double
, a31 :: Double , a32 :: Double , a33 :: Double
} deriving (Show, Eq, Ord, Typeable, Data)
-- used as a rotation matrix
data Vector4 = Vector4 { q0 :: Double, q1 :: Double, q2 :: Double, q3 :: Double}
deriving (Show, Eq, Ord, Typeable, Data)
-- quaternion rotational representation
data Placement = Placement { position :: Vector3, orientation :: Vector4 }
deriving (Show, Eq, Ord, Typeable, Data)
{-
-- the placement is determined by 2 vectors:
-- the first one points to the 'center' of the objet in the space
-- the second one determines the orientation of the object in the given space
data Edgelist = []
| 1:Edgelist
| 0:Edgelist
reference from compound objects to 'building-blocks'
objects made through strings or containment of the other
objects
-}
data BaseObject = Box Double Double Double -- Height, Width, Length
| Cylinder Double Double Double -- Angle, Height, Radius
| Sphere Double Double Double Double -- Angle1,Angle2,Angle3,Radius
| Cone Double Double Double Double -- Angle,Radius1,Radius2,Height
| Torus Double Double Double Double Double
-- Angle1, Angle2, Angle3, Radius1, Radius2
| Line Double -- length
| Circle Double Double Double -- StartAngle, EndAngle, Radius
| Rectangle Double Double -- Height, Length
deriving (Show, Eq, Ord, Typeable, Data)
-- TODO: Plane, Vertex, etc..
data Object = BaseObject BaseObject
| Cut ExtendedObject ExtendedObject
| Common ExtendedObject ExtendedObject
| Fusion ExtendedObject ExtendedObject
| Extrusion ExtendedObject Vector3
| Section ExtendedObject ExtendedObject
deriving (Show, Eq, Ord, Typeable, Data)
{- --| Fillet, (Base::String, Edges::Edgelist, Radius::Double)),
--not enough data in the xml
--| Chamfer, (Base::String, Edges::Edgelist, Amount::Double)),
--not enough data in the xml
--| Mirror, (Base::String, Position2::Vector))
--mirroring of an object
-}
data ExtendedObject = Placed PlacedObject | Ref String
deriving (Show, Eq, Ord, Typeable, Data)
data PlacedObject =
PlacedObject {p :: Placement, o :: Object}
deriving (Show, Eq, Ord, Typeable, Data)
data NamedObject = NamedObject { name :: String
, object :: PlacedObject}
| EmptyObject -- for objects that are WIP
deriving (Show, Eq, Ord, Typeable, Data)
{- the first parameter is the name of the object as it is stored in the
FreeCAD document. the second parameter determines the placement of the object
(a pair of vectors) the third parameter contains the type of the object and
a list of doubles (numbers) describing the characteristics
of the object (e.g. dimensions, angles, etc) -}
type Document = [NamedObject]
{- | Datatype for FreeCAD Signatures
Signatures are just sets of named objects -}
data Sign = Sign { objects :: Set.Set NamedObject }
deriving (Show, Eq, Ord, Typeable, Data)
| mariefarrell/Hets | FreeCAD/As.hs | gpl-2.0 | 4,093 | 0 | 10 | 1,111 | 621 | 364 | 257 | 43 | 0 |
module Aar.Parser.Numeric.Int where
import Control.Monad
import Text.Parsec.Prim (ParsecT)
import Text.ParserCombinators.Parsec
import Aar.Lexer.Token
sourcePos :: Monad m => ParsecT s u m SourcePos
sourcePos = statePos `liftM` getParserState
parseOctNum :: Parser String
parseOctNum = do
string "0" <|> string "o" <|> string "O"
octStr <- many1 octDigit
return ('0':'o':octStr)
parseHexNum :: Parser String
parseHexNum = do
try (string "0x") <|> string "0X"
hexStr <- many1 hexDigit
return ('0':'x':hexStr)
parseDecNum :: Parser String
parseDecNum = many1 digit
parseInt :: Parser Token
parseInt = do
pos <- sourcePos
numStr <- try parseOctNum <|>
try parseHexNum <|>
parseDecNum
return $ TokInt pos (read numStr)
| aar-lang/aar | lib/Aar/Parser/Numeric/Int.hs | gpl-3.0 | 820 | 0 | 10 | 205 | 262 | 130 | 132 | 26 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE TupleSections #-}
module Fusion
(
-- * Step
Step(..)
-- * StepList
, StepList(..)
-- * Stream
, Stream(..), yield, await, stateful
, map, filter, drop, take, concat, linesUnbounded, lines
, runStream, runStream', bindStream, applyStream, stepStream
, foldlStream, foldlStreamM
, foldrStream, foldrStreamM, lazyFoldrStreamIO
, fromList, fromListM, toListM, lazyToListIO
, emptyStream, next
-- * Streaming with files
, bracketS, readFile, writeFile
-- * ListT
, ListT(..), concatL
-- * Pipes workalike functions
, Producer, Pipe, Consumer {-, pipe-}
, each
, (>->), (>&>)
)
where
import Control.Applicative
import Control.Concurrent.Async.Lifted
import Control.Concurrent.STM
import Control.Monad
import Control.Monad.Catch
import Control.Monad.Fix
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Control
import Control.Monad.Trans.Free
import Control.Monad.Trans.State
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.Foldable as F
import Data.Function
import Data.Functor.Identity
import Data.Text (Text)
import qualified Data.Text as T
--import qualified Data.Text.Encoding as T
import Data.Void
import GHC.Exts hiding (fromList, toList)
import Pipes.Safe (SafeT, MonadSafe(..))
import Prelude hiding (map, concat, filter, take, drop, lines,
readFile, writeFile)
import qualified Prelude
import System.IO hiding (readFile, writeFile)
import System.IO.Unsafe
#if DOCTESTS
import Control.Lens ((^.))
#endif
#define PHASE_FUSED [1]
#define PHASE_INNER [0]
#define INLINE_FUSED INLINE PHASE_FUSED
#define INLINE_INNER INLINE PHASE_INNER
-- Step
-- | A simple stepper, as suggested by Duncan Coutts in his Thesis paper,
-- "Stream Fusion: Practical shortcut fusion for coinductive sequence types".
-- This version adds a result type.
data Step s a r = Done r | Skip s | Yield s a deriving Functor
-- StepList
newtype StepList s r a = StepList { getStepList :: Step s a r }
instance Functor (StepList s r) where
fmap _ (StepList (Done r)) = StepList $ Done r
fmap _ (StepList (Skip s)) = StepList $ Skip s
fmap f (StepList (Yield s a)) = StepList $ Yield s (f a)
{-# INLINE fmap #-}
-- Stream
data Stream a m r = forall s. Stream (s -> m (Step s a r)) s
instance Show a => Show (Stream a Identity r) where
show xs = "Stream " ++ show (runIdentity (toListM xs))
instance Functor m => Functor (Stream a m) where
{-# SPECIALIZE instance Functor (Stream a IO) #-}
{-# SPECIALIZE instance Functor m => Functor (Stream a (StateT s m)) #-}
{-# SPECIALIZE instance Functor (Stream a (StateT s IO)) #-}
fmap f (Stream k m) = Stream (fmap (fmap f) . k) m
{-# INLINE_FUSED fmap #-}
instance (Monad m, Applicative m) => Applicative (Stream a m) where
{-# SPECIALIZE instance Applicative (Stream a IO) #-}
{-# SPECIALIZE instance Applicative (Stream a (StateT s IO)) #-}
pure = return
{-# INLINE pure #-}
(<*>) = ap
{-# INLINE (<*>) #-}
instance (Monad m, Applicative m) => Monad (Stream a m) where
{-# SPECIALIZE instance Monad (Stream a IO) #-}
{-# SPECIALIZE instance Monad (Stream a (StateT s IO)) #-}
return = Stream (return . Done)
{-# INLINE_FUSED return #-}
Stream step i >>= f = Stream step' (Left i)
where
{-# INLINE_INNER step' #-}
step' (Left s) = step s >>= \case
Done r -> switchStream (f r)
Skip s' -> return $ Skip (Left s')
Yield s' a -> return $ Yield (Left s') a
step' (Right s) = switchStream s
{-# INLINE_FUSED (>>=) #-}
switchStream :: Functor m
=> Stream a m r -> m (Step (Either s (Stream a m r)) a r)
switchStream (Stream step i) = step i <&> \case
Done r -> Done r
Skip s' -> Skip (Right (Stream step s'))
Yield s' a -> Yield (Right (Stream step s')) a
{-# INLINE_INNER switchStream #-}
instance MonadThrow m => MonadThrow (Stream a m) where
throwM e = Stream (\_ -> throwM e) ()
{-# INLINE_FUSED throwM #-}
instance MonadCatch m => MonadCatch (Stream a m) where
catch (Stream step i) c = Stream step' (i, Nothing)
where
{-# INLINE_INNER step' #-}
step' (s, Nothing) = go `catch` \e -> step' (s, Just (c e))
where
{-# INLINE_INNER go #-}
go = step s <&> \case
Done r -> Done r
Skip s' -> Skip (s', Nothing)
Yield s' a -> Yield (s', Nothing) a
step' (old, Just (Stream step'' s)) = step'' s <&> \case
Done r -> Done r
Skip s' -> Skip (old, Just (Stream step'' s'))
Yield s' a -> Yield (old, Just (Stream step'' s')) a
{-# INLINE_FUSED catch #-}
instance MonadMask m => MonadMask (Stream a m) where
mask action = Stream step' Nothing
where
step' Nothing = mask $ \unmask ->
step' $ Just $ action $ \(Stream step s) -> Stream (unmask . step) s
step' (Just (Stream step'' i'')) = step'' i'' <&> \case
Done r -> Done r
Skip s' -> Skip (Just (Stream step'' s'))
Yield s' a -> Yield (Just (Stream step'' s')) a
{-# INLINE mask #-}
uninterruptibleMask action = Stream step' Nothing
where
step' Nothing = mask $ \unmask ->
step' $ Just $ action $ \(Stream step s) -> Stream (unmask . step) s
step' (Just (Stream step'' i'')) = step'' i'' <&> \case
Done r -> Done r
Skip s' -> Skip (Just (Stream step'' s'))
Yield s' a -> Yield (Just (Stream step'' s')) a
{-# INLINEABLE uninterruptibleMask #-}
instance MonadTrans (Stream a) where
lift = Stream (Done `liftM`)
{-# INLINE_FUSED lift #-}
(<&>) :: Functor f => f a -> (a -> b) -> f b
x <&> f = fmap f x
{-# INLINE (<&>) #-}
-- | Helper function for more easily writing step functions. Be aware that
-- this can degrade performance over writing the step function directly as an
-- inlined, inner function. The same applies for 'applyStream', 'stepStream',
-- 'foldlStream', etc.
bindStream :: Monad m => (forall s. Step s a r -> m r) -> Stream a m r -> m r
bindStream f (Stream step i) = step i >>= f
{-# INLINE_INNER bindStream #-}
applyStream :: Functor m => (forall s. Step s a r -> r) -> Stream a m r -> m r
applyStream f (Stream step i) = f <$> step i
{-# INLINE_INNER applyStream #-}
stepStream :: Functor m
=> (forall s. Step s a r -> Step s b r) -> Stream a m r
-> Stream b m r
stepStream f (Stream step i) = Stream (fmap f . step) i
{-# INLINE_INNER stepStream #-}
yield :: Applicative m => a -> Stream a m ()
yield a = Stream (pure . step') True
where
{-# INLINE_INNER step' #-}
step' True = Yield False a
step' False = Done ()
{-# INLINE_FUSED yield #-}
-- | Map over the values produced by a stream.
--
-- >>> map (+1) (fromList [1..3]) :: Stream Int Identity ()
-- Stream [2,3,4]
map :: Functor m => (a -> b) -> Stream a m r -> Stream b m r
map f (Stream step i) = Stream step' i
where
{-# INLINE_INNER step' #-}
step' s = step s <&> \case
Done r -> Done r
Skip s' -> Skip s'
Yield s' a -> Yield s' (f a)
{-# INLINE_FUSED map #-}
filter :: Functor m => (a -> Bool) -> Stream a m r -> Stream a m r
filter p (Stream step i) = Stream step' i
where
{-# INLINE_INNER step' #-}
step' s = step s <&> \case
Done r -> Done r
Skip s' -> Skip s'
Yield s' a | p a -> Yield s' a
| otherwise -> Skip s'
{-# INLINE_FUSED filter #-}
data Split = Pass !Int# | Keep
drop :: Applicative m => Int -> Stream a m r -> Stream a m r
drop (I# n) (Stream step i) = Stream step' (i, Pass n)
where
{-# INLINE_INNER step' #-}
step' (s, Pass 0#) = pure $ Skip (s, Keep)
step' (s, Pass n') = step s <&> \case
Yield s' _ -> Skip (s', Pass (n' -# 1#))
Skip s' -> Skip (s', Pass n')
Done r -> Done r
step' (s, Keep) = step s <&> \case
Yield s' x -> Yield (s', Keep) x
Skip s' -> Skip (s', Keep)
Done r -> Done r
{-# INLINE_FUSED drop #-}
take :: Applicative m => Int -> Stream a m r -> Stream a m ()
take n (Stream step i) = Stream step' (i, n)
where
{-# INLINE_INNER step' #-}
step' (_, 0) = pure $ Done ()
step' (s, n') = step s <&> \case
Yield s' a -> Yield (s', n' - 1) a
Skip s' -> Skip (s', n')
Done _ -> Done ()
{-# INLINE_FUSED take #-}
concat :: Monad m => Stream (Stream a m r) m r -> Stream a m r
concat (Stream step i) = Stream step' (Left i)
where
{-# INLINE_INNER step' #-}
step' (Left s) = step s >>= \case
Done r -> return $ Done r
Skip s' -> return $ Skip (Left s')
Yield s' a -> step' (Right (s',a))
step' (Right (s, Stream inner j)) = liftM (\case
Done _ -> Skip (Left s)
Skip j' -> Skip (Right (s, Stream inner j'))
Yield j' a -> Yield (Right (s, Stream inner j')) a) (inner j)
{-# INLINE_FUSED concat #-}
-- decodeUtf8 :: Applicative m => Stream ByteString m r -> Stream Text m ()
-- decodeUtf8 = Stream step' (i, Pass n)
-- | Break the stream of input 'Text' chunks into a stream of lines. This is
-- called 'linesUnbounded' because memory utilization is not bounded, and will
-- take up as many bytes as the longest line. For static space usage, please
-- use 'lines'.
--
-- >>> toListM $ yield (T.pack "Hello, world!\nGoodbye") >-> linesUnbounded
-- ["Hello, world!","Goodbye"]
linesUnbounded :: Applicative m => Stream Text m r -> Stream Text m r
linesUnbounded (Stream step i) = Stream step' (Left (i, id))
where
-- Right means we have pending lines to emit, followed by either the next
-- state, or the end.
step' (Right (n, x:xs)) = pure $ Yield (Right (n, xs)) x
step' (Right (Left n, [])) = step' (Left n)
step' (Right (Right r, [])) = pure $ Done r
-- Left means we want to read more lines, gathering up the ends in case
-- they form a line with the next chunk
step' (Left (s, prev)) = step s <&> \case
Done r -> case prev [] of
[] -> Done r
(x:xs) -> Yield (Right (Right r, xs)) x
Skip s' -> Skip (Left (s', prev))
Yield s' a -> case T.lines a of
[] -> Skip (Left (s', prev))
[x] -> Skip (Left (s', prev . (x:)))
-- This case is particularly complicated because we need to:
-- 1. Emit the known line 'x' now, prepending any remainder
-- from previous reads (prev)
-- 2. Queue remaining known lines (init xs) for yielding after
-- 3. Preserve the remainder for the next read (last xs)
-- 4. Indicate the next state to read from after we've flushed
-- everything that was queued (s')
(x:xs) -> Yield (Right (Left (s', (last xs:)), init xs))
(T.concat (prev [x]))
{-# INLINE_FUSED linesUnbounded #-}
-- | A perfect streaming approach to breaking up input into lines, using the
-- 'FreeT' monad transformer to produce a stream of streams. (Do not use
-- 'retractT' in production code, since this results in the same behavior as
-- 'linesUnbounded').
--
-- >>> toListM $ retractT (yield (T.pack "Hello, world!\nGoodbye") ^. lines)
-- ["Hello, world!","Goodbye"]
lines :: (Monad m, Functor f)
=> (FreeT (Stream Text m) m r -> f (FreeT (Stream Text m) m r))
-> Stream Text m r -> f (Stream Text m r)
lines k p = fmap _unlines (k (_lines p))
{-# INLINE lines #-}
_lines :: Monad m => Stream Text m r -> FreeT (Stream Text m) m r
_lines (Stream step i) = FreeT (go (step i))
where
go p = p >>= \case
Done r -> return $ Pure r
Skip s' -> go (step s')
Yield s' a ->
if T.null a
then go (step s')
else return $ Free $ Stream step' (s', Right a)
step' (s, Left a) =
return $ Done $ FreeT $ return $ Free $ Stream step' (s, Right a)
step' (s, Right "") = step s >>= \case
Done r -> return $ Done $ FreeT $ return $ Pure r
Skip s' -> return $ Skip (s', Right "")
Yield s' a -> step' (s', Right a)
step' (s, Right a) = do
let (a',b') = T.break (== '\n') a
if T.null b'
then return $ Yield (s, Right b') a'
else return $ Yield (s, Left (T.drop 1 b')) a'
{-# INLINABLE _lines #-}
_unlines :: Monad m => FreeT (Stream Text m) m r -> Stream Text m r
-- _unlines = concat . map (<* return (T.singleton '\n'))
_unlines = undefined
{-# INLINABLE _unlines #-}
-- takeFree :: (Functor f, Monad m) => Int -> FreeT f m () -> FreeT f m ()
fromList :: (Applicative m, F.Foldable f) => f a -> Stream a m ()
fromList = Stream (pure . step) . F.toList
where
{-# INLINE_INNER step #-}
step [] = Done ()
step (x:xs) = Yield xs x
{-# INLINE_FUSED fromList #-}
fromListM :: (Applicative m, F.Foldable f) => m (f a) -> Stream a m ()
fromListM = Stream (step `fmap`) . fmap F.toList
where
{-# INLINE_INNER step #-}
step [] = Done ()
step (y:ys) = Yield (pure ys) y
{-# INLINE_FUSED fromListM #-}
runStream :: Monad m => Stream a m r -> m r
runStream (Stream step i) = step' i
where
{-# INLINE_INNER step' #-}
step' s = step s >>= \case
Done r -> return r
Skip s' -> step' s'
Yield s' _ -> step' s'
{-# INLINE runStream #-}
runStream' :: Monad m => Stream Void m r -> m r
runStream' (Stream step i) = step' i
where
{-# INLINE_INNER step' #-}
step' s = step s >>= \case
Done r -> return r
Skip s' -> step' s'
Yield _ a -> absurd a
{-# INLINE runStream' #-}
foldlStream :: Monad m
=> (b -> a -> b) -> (b -> r -> s) -> b -> Stream a m r -> m s
foldlStream f w z (Stream step i) = step' i z
where
{-# INLINE_INNER step' #-}
step' s !acc = step s >>= \case
Done r -> return $ w acc r
Skip s' -> step' s' acc
Yield s' a -> step' s' (f acc a)
{-# INLINE_FUSED foldlStream #-}
foldlStreamM :: Monad m
=> (m b -> a -> m b) -> (m b -> r -> m s) -> m b -> Stream a m r
-> m s
foldlStreamM f w z (Stream step i) = step' i z
where
{-# INLINE_INNER step' #-}
step' s acc = step s >>= \case
Done r -> w acc r
Skip s' -> step' s' acc
Yield s' a -> step' s' (f acc a)
{-# INLINE_FUSED foldlStreamM #-}
foldrStream :: Monad m => (a -> b -> b) -> (r -> b) -> Stream a m r -> m b
foldrStream f w (Stream step i) = step' i
where
{-# INLINE_INNER step' #-}
step' s = step s >>= \case
Done r -> return $ w r
Skip s' -> step' s'
Yield s' a -> liftM (f a) (step' s')
{-# INLINE_FUSED foldrStream #-}
foldrStreamM :: Monad m
=> (a -> m b -> m b) -> (r -> m b) -> Stream a m r -> m b
foldrStreamM f w (Stream step i) = step' i
where
{-# INLINE_INNER step' #-}
step' s = step s >>= \case
Done r -> w r
Skip s' -> step' s'
Yield s' a -> f a (step' s')
{-# INLINE_FUSED foldrStreamM #-}
lazyFoldrStreamIO :: (a -> IO b -> IO b) -> (r -> IO b) -> Stream a IO r -> IO b
lazyFoldrStreamIO f w (Stream step i) = step' i
where
{-# INLINE_INNER step' #-}
step' s = step s >>= \case
Done r -> w r
Skip s' -> step' s'
Yield s' a -> f a (unsafeInterleaveIO (step' s'))
{-# INLINE_FUSED lazyFoldrStreamIO #-}
toListM :: Monad m => Stream a m r -> m [a]
toListM (Stream step i) = step' i id
where
{-# INLINE_INNER step' #-}
step' s acc = step s >>= \case
Done _ -> return $ acc []
Skip s' -> step' s' acc
Yield s' a -> step' s' (acc . (a:))
{-# INLINE [1] toListM #-}
lazyToListIO :: Stream a IO r -> IO [a]
lazyToListIO (Stream step i) = step' i
where
{-# INLINE_INNER step' #-}
step' s = step s >>= \case
Done _ -> return []
Skip s' -> step' s'
Yield s' a -> liftM (a:) (unsafeInterleaveIO (step' s'))
{-# INLINE lazyToListIO #-}
emptyStream :: (Monad m, Applicative m) => Stream Void m ()
emptyStream = pure ()
{-# INLINE CONLIKE emptyStream #-}
bracketS :: (Monad m, MonadMask (Base m), MonadSafe m)
=> Base m s
-> (s -> Base m ())
-> (forall t. s -> (s -> a -> m t) -> (s -> m t) -> (r -> m t) -> m t)
-> Stream a m r
bracketS i f step = Stream step' $ mask $ \unmask -> do
s <- unmask $ liftBase i
key <- register (f s)
return (s, key)
where
{-# INLINE_INNER step' #-}
step' mx = mx >>= \(s, key) -> step s
(\s' a -> return $ Yield (return (s', key)) a)
(\s' -> return $ Skip (return (s', key)))
(\r -> mask $ \unmask -> do
unmask $ liftBase $ f s
release key
return $ Done r)
{-# INLINE_FUSED bracketS #-}
readFile :: (MonadIO m, MonadMask (Base m), MonadSafe m)
=> FilePath -> Stream ByteString m ()
readFile path = bracketS
(liftIO $ openFile path ReadMode)
(liftIO . hClose)
(\h yield' _skip done -> do
b <- liftIO $ hIsEOF h
if b
then done ()
else yield' h =<< liftIO (B.hGetSome h 8192))
{-# SPECIALIZE readFile :: FilePath -> Stream ByteString (SafeT IO) () #-}
writeFile :: (MonadIO m, MonadMask (Base m), MonadSafe m)
=> FilePath -> Stream ByteString m () -> m ()
writeFile path s = mask $ \unmask -> do
h <- unmask $ liftIO $ openFile path WriteMode
key <- register (liftIO $ hClose h)
unmask $ foldrStreamM (\a _ -> liftIO $ B.hPut h a) (\() -> return ()) s
liftIO $ hClose h
release key
{-# SPECIALIZE writeFile
:: FilePath -> Stream ByteString (SafeT IO) () -> SafeT IO () #-}
next :: Monad m => Stream a m r -> m (Either r (a, Stream a m r))
next (Stream step i) = step' i
where
{-# INLINE_INNER step' #-}
step' s = step s >>= \case
Done r -> return $ Left r
Skip s' -> step' s'
Yield s' a -> return $ Right (a, Stream step s')
{-# INLINE next #-}
-- ListT
newtype ListT m a = ListT { getListT :: Stream a m () }
instance Functor m => Functor (ListT m) where
{-# SPECIALIZE instance Functor (ListT IO) #-}
fmap f = ListT . map f . getListT
{-# INLINE fmap #-}
instance (Monad m, Applicative m) => Applicative (ListT m) where
{-# SPECIALIZE instance Applicative (ListT IO) #-}
pure = return
{-# INLINE pure #-}
(<*>) = ap
{-# INLINE (<*>) #-}
instance (Monad m, Applicative m) => Monad (ListT m) where
{-# SPECIALIZE instance Monad (ListT IO) #-}
return = ListT . fromList . (:[])
{-# INLINE return #-}
(>>=) = (concatL .) . flip fmap
{-# INLINE (>>=) #-}
concatL :: (Monad m, Applicative m) => ListT m (ListT m a) -> ListT m a
concatL = ListT . concat . getListT . liftM getListT
{-# INLINE concatL #-}
-- Pipes
type Producer b m r = Stream b m r
type Pipe a b m r = forall s. Stream a m s -> Stream b m r
type Consumer a m r = forall s. Stream a m s -> m r
each :: (Applicative m, F.Foldable f) => f a -> Producer a m ()
each = fromList
{-# INLINE_FUSED each #-}
(>->) :: Stream a m s -> (Stream a m s -> Stream b m r) -> Stream b m r
f >-> g = g f
{-# INLINE (>->) #-}
stateful :: MonadFix m
=> Stream a (StateT (Stream a m s) m) r -> Stream a m s -> Stream a m r
stateful (Stream inner x) outer = Stream step' (x, outer)
where
{-# INLINE_INNER step' #-}
step' (t, str) = mdo
(r, str') <- runStateT (go str') str
return r
where
{-# INLINE_INNER go #-}
go str' = inner t <&> \case
Done r -> Done r
Skip t' -> Skip (t', str')
Yield t' a -> Yield (t', str') a
{-# INLINE_FUSED stateful #-}
await :: Monad m => Stream a (StateT (Stream a m s) m) (Maybe a)
await = Stream step' ()
where
{-# INLINEABLE [0] step' #-}
step' () = get >>= \case
Stream step s -> lift (step s) >>= \case
Done _ -> return $ Done Nothing
Skip s' -> do
put (Stream step s')
return $ Skip ()
Yield s' a -> do
put (Stream step s')
return $ Done (Just a)
{-# INLINE_FUSED await #-}
-- | Connect two streams, but gather elements from upstream in a separate
-- thread. Exceptions raised in that thread are propagated back to the main
-- thread. A bounded buffer is used of 16 elements.
--
-- Note that monadic effects from upstream are discarded. This is acceptable
-- if effects propagate beyond the thread, such as in 'IO', but does prevent
-- 'StateT' changes from being seen downstream, for example.
(>&>) :: (MonadBaseControl IO m, MonadIO m, MonadMask m)
=> Stream a m r -> (Stream a m r -> Stream b m r) -> Stream b m r
Stream step i >&> k = k $ Stream step' $ do
q <- liftIO $ newTBQueueIO 16
mask $ \unmask -> do
a <- unmask $ async $ flip fix i $ \loop s -> step s >>= \case
Done r -> liftIO $ atomically $ writeTBQueue q (Left r)
Skip s' -> loop s'
Yield s' a -> do
liftIO $ atomically $ writeTBQueue q (Right a)
loop s'
link a
return q
where
{-# INLINE_INNER step' #-}
step' s = s >>= \q -> liftIO (atomically (readTBQueue q)) <&> \case
Left r -> Done r
Right a -> Yield (return q) a
{-# INLINEABLE [1] (>&>) #-}
{-# RULES "fusion: drop/map" forall f n xs.
drop n (map f xs) = map f (drop n xs) #-}
{-# RULES "fusion: map/map" forall f g xs.
map f (map g xs) = map (f . g) xs #-}
{-
These four rules together, on a simple pipline, improve speed dramatically.
But if the fourth doesn't fire (which it won't, except for trivial examples),
then it makes the pipeline twice as slow.
{-# RULES "fusion: map/each" forall f xs.
map f (each xs) = each (Prelude.map f xs) #-}
{-# RULES "fusion: filter/each" forall f xs.
filter f (each xs) = each (Prelude.filter f xs) #-}
{-# RULES "fusion: drop/each" forall n xs.
drop n (each xs) = each (Prelude.drop n xs) #-}
{-# RULES "fusion: toListM/each" forall xs.
toListM (each xs) = return xs #-}
-}
| bitemyapp/fusion | Fusion.hs | bsd-3-clause | 23,019 | 0 | 24 | 6,974 | 7,765 | 3,946 | 3,819 | -1 | -1 |
{-
Teak synthesiser for the Balsa language
Copyright (C) 2007-2010 The University of Manchester
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Andrew Bardsley <bardsley@cs.man.ac.uk> (and others, see AUTHORS)
School of Computer Science, The University of Manchester
Oxford Road, MANCHESTER, M13 9PL, UK
-}
module BalsaLexer (
BalsaToken (..),
tokensToString,
balsaLexer
) where
import Parser
import Report
import Misc
import Lexer
import Data.Char (isDigit, toLower, isHexDigit, isOctDigit, digitToInt)
import Data.List
import Control.Monad
import Data.Bits
data BalsaToken =
BalsaName { tokenPos :: Pos, tokenRaw :: String }
| BalsaKeyword { tokenPos :: Pos, tokenRaw :: String }
| BalsaLabel { tokenPos :: Pos, tokenLabel :: String, tokenRaw :: String }
| BalsaInt { tokenPos :: Pos, tokenRaw :: String, tokenValInt :: Integer }
| BalsaImplicant { tokenPos :: Pos, tokenRaw :: String,
tokenValInt :: Integer, tokenDCInt :: Integer }
| BalsaString { tokenPos :: Pos, tokenRaw :: String, tokenValStr :: String }
| BalsaErrorToken { tokenPos :: Pos, tokenRaw :: String,
tokenReport :: Maybe Report }
deriving (Show)
balsaSymbols :: [String]
balsaSymbols = ["^", "<", "=", ">", "|", "-", ",", ";", ":", "?", "/", ".", "(", ")",
"[", "]", "{", "}", "@", "*", "#", "%", "+", "'", "!", "\"", "<=", "<-", ">=",
"||", "->", ":=", "/=", "..", "(*", "*)"]
balsaKeywords :: [String]
balsaKeywords = ["and", "arbitrate", "array", "as",
"begin", "bits", "builtin",
"case", "channel", "constant", "continue",
"else", "end", "enumeration",
"for", "function",
"if", "in", "import", "input", "is",
"local", "log", "loop",
"not",
"of", "or", "output", "over",
"parameter", "print", "procedure",
"record",
"select", "shared", "signed", "sink", "sizeof",
"then", "type",
"variable",
"while",
"xor"]
keywordMatches :: MatchTree String
keywordMatches = makeMatchTree balsaKeywords
symbolMatches :: MatchTree String
symbolMatches = makeMatchTree balsaSymbols
anyButQuote :: Lexer (Pos, Char)
anyButQuote = makeCharParser "`\"'" (/= '"')
tokenString :: Lexer (Maybe BalsaToken)
tokenString = do
(pos, _) <- char '"'
(_, s) <- repChar anyButQuote
char '"'
return $ Just $ BalsaString pos ("\"" ++ escapeString "" s ++ "\"") s
tokenName :: Lexer (Maybe BalsaToken)
tokenName = do
(pos, c) <- firstId
(_, s) <- repChar nameChar
let str = c:s
isLabel <- optional False (char ':' >> return True)
case (matchInMatchTree keywordMatches str, isLabel) of
(True, True) -> parserFail $ Report pos "label must not be a keyword"
(True, False) -> return $ Just $ BalsaKeyword pos str
(False, True) -> return $ Just $ BalsaLabel pos str (str ++ ":")
(False, False) -> return $ Just $ BalsaName pos str
isDontCare :: Char -> Bool
isDontCare = (`elem` "xX?")
isDigitSep :: Char -> Bool
isDigitSep = (== '_')
decDigit :: Lexer (Pos, Char)
decDigit = makeCharParser "decimal digit" (\c -> isDigit c || isDigitSep c)
binDigit :: Lexer (Pos, Char)
binDigit = makeCharParser "binary digit" (\c -> c `elem` "01" || isDontCare c || isDigitSep c)
hexDigit :: Lexer (Pos, Char)
hexDigit = makeCharParser "hexadecimal digit" (\c -> isHexDigit c || isDontCare c || isDigitSep c)
octDigit :: Lexer (Pos, Char)
octDigit = makeCharParser "octal digit" (\c -> isOctDigit c || isDontCare c || isDigitSep c)
oneToNine :: Lexer (Pos, Char)
oneToNine = makeCharParser "non-zero decimal digit" (\c -> c >= '1' && c <= '9')
digitValue :: Int -> Char -> (Integer, Integer)
digitValue digitBits digit
| isHexDigit digit = (toInteger (digitToInt digit), 0)
| isDontCare digit = (0, bit digitBits - 1)
| otherwise = (0, 0)
parseNumber :: String -> Pos -> Int -> String -> BalsaToken
parseNumber prefix pos radix str =
if dc == 0 then BalsaInt pos rawToken value else BalsaImplicant pos rawToken value dc
where
(value, dc) = foldl' step (0, 0) str
step v '_' = v
step v chr = addDigits (digitValue digitBits (toLower chr)) v
digitBits = case radix of { 2 -> 1; 8 -> 3; _ -> 4 }
addDigits (v1, m1) (v2, m2) = (v2 * toInteger radix + v1, m2 * toInteger radix + m1)
rawToken = prefix ++ str
tokenInt :: Lexer (Maybe BalsaToken)
tokenInt = anyOneOfStr "integer" [
do
(pos, _) <- char '0'
anyOneOfStr "radix indicator or decimal digit" [
do
(_, c) <- ichar 'x'
(_, d) <- obligatory hexDigit
(_, ds) <- repChar hexDigit
return $ Just $ parseNumber ['0', c] pos 16 (d:ds),
do
(_, c) <- ichar 'b'
(_, d) <- obligatory binDigit
(_, ds) <- repChar binDigit
return $ Just $ parseNumber ['0', c] pos 2 (d:ds),
do
(_, c) <- ichar 'o'
(_, d) <- obligatory octDigit
(_, ds) <- repChar octDigit
return $ Just $ parseNumber ['0', c] pos 8 (d:ds),
do
(_, ds) <- repChar decDigit
return $ Just $ parseNumber "0" pos 10 ds ],
do
(pos, d) <- oneToNine
(_, ds) <- repChar decDigit
return $ Just $ parseNumber "" pos 10 (d:ds) ]
tokenSymbol :: Lexer (Maybe BalsaToken)
tokenSymbol = do
(pos:_, s) <- liftM unzip $ parseMatchTree (expecting "symbol") (mapM char) symbolMatches
return $ Just $ BalsaKeyword pos s
getToken :: Lexer (Maybe BalsaToken)
getToken = anyOneOfStr "a valid token" [
do
ws
return Nothing,
tokenString,
tokenName,
tokenInt,
do
comment (string "--") (string "(--") (string "--)")
return Nothing,
tokenSymbol, -- Must be after comment to avoid "(" match
do
(pos, chr) <- anyChar
return $ Just $ BalsaErrorToken pos [chr] (Just (Report pos ("bad character `" ++ [chr] ++ "'")))]
balsaLexer :: Pos -> String -> [BalsaToken]
balsaLexer = lexer (BalsaErrorToken NoPos "") getToken
tokensToString :: Pos -> [BalsaToken] -> String
tokensToString startingPos tokens =
ret
where
(_, ret) = foldl' doToken (startingPos, "") tokens
doToken (position, returnString) token =
(finalPos, returnString ++ posFillBetween position nextPos ++ raw)
where
raw = tokenRaw token
nextPos = tokenPos token
finalPos = posMoveToRight (length raw) nextPos
| balangs/eTeak | src/BalsaLexer.hs | bsd-3-clause | 7,791 | 0 | 18 | 2,493 | 2,233 | 1,221 | 1,012 | 152 | 5 |
{-# LANGUAGE CPP, MagicHash, NondecreasingIndentation, UnboxedTuples,
RecordWildCards, BangPatterns #-}
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2005-2007
--
-- Running statements interactively
--
-- -----------------------------------------------------------------------------
module InteractiveEval (
Resume(..), History(..),
execStmt, ExecOptions(..), execOptions, ExecResult(..), resumeExec,
runDecls, runDeclsWithLocation,
isStmt, hasImport, isImport, isDecl,
parseImportDecl, SingleStep(..),
resume,
abandon, abandonAll,
getResumeContext,
getHistorySpan,
getModBreaks,
getHistoryModule,
back, forward,
setContext, getContext,
availsToGlobalRdrEnv,
getNamesInScope,
getRdrNamesInScope,
moduleIsInterpreted,
getInfo,
exprType,
typeKind,
parseName,
showModule,
isModuleInterpreted,
parseExpr, compileParsedExpr,
compileExpr, dynCompileExpr,
compileExprRemote, compileParsedExprRemote,
Term(..), obtainTermFromId, obtainTermFromVal, reconstructType,
-- * Depcreated API (remove in GHC 7.14)
RunResult(..), runStmt, runStmtWithLocation,
) where
#include "HsVersions.h"
import InteractiveEvalTypes
import GHCi
import GHCi.Message
import GHCi.RemoteTypes
import GhcMonad
import HscMain
import HsSyn
import HscTypes
import InstEnv
import IfaceEnv ( newInteractiveBinder )
import FamInstEnv ( FamInst )
import CoreFVs ( orphNamesOfFamInst )
import TyCon
import Type hiding( typeKind )
import RepType
import TcType hiding( typeKind )
import Var
import Id
import Name hiding ( varName )
import NameSet
import Avail
import RdrName
import VarSet
import VarEnv
import ByteCodeTypes
import Linker
import DynFlags
import Unique
import UniqSupply
import MonadUtils
import Module
import PrelNames ( toDynName, pretendNameIsInScope )
import Panic
import Maybes
import ErrUtils
import SrcLoc
import RtClosureInspect
import Outputable
import FastString
import Bag
import qualified Lexer (P (..), ParseResult(..), unP, mkPState)
import qualified Parser (parseStmt, parseModule, parseDeclaration, parseImport)
import System.Directory
import Data.Dynamic
import Data.Either
import qualified Data.IntMap as IntMap
import Data.List (find,intercalate)
import StringBuffer (stringToStringBuffer)
import Control.Monad
import GHC.Exts
import Data.Array
import Exception
import Control.Concurrent
-- -----------------------------------------------------------------------------
-- running a statement interactively
getResumeContext :: GhcMonad m => m [Resume]
getResumeContext = withSession (return . ic_resume . hsc_IC)
mkHistory :: HscEnv -> ForeignHValue -> BreakInfo -> History
mkHistory hsc_env hval bi = History hval bi (findEnclosingDecls hsc_env bi)
getHistoryModule :: History -> Module
getHistoryModule = breakInfo_module . historyBreakInfo
getHistorySpan :: HscEnv -> History -> SrcSpan
getHistorySpan hsc_env History{..} =
let BreakInfo{..} = historyBreakInfo in
case lookupHpt (hsc_HPT hsc_env) (moduleName breakInfo_module) of
Just hmi -> modBreaks_locs (getModBreaks hmi) ! breakInfo_number
_ -> panic "getHistorySpan"
getModBreaks :: HomeModInfo -> ModBreaks
getModBreaks hmi
| Just linkable <- hm_linkable hmi,
[BCOs cbc] <- linkableUnlinked linkable
= fromMaybe emptyModBreaks (bc_breaks cbc)
| otherwise
= emptyModBreaks -- probably object code
{- | Finds the enclosing top level function name -}
-- ToDo: a better way to do this would be to keep hold of the decl_path computed
-- by the coverage pass, which gives the list of lexically-enclosing bindings
-- for each tick.
findEnclosingDecls :: HscEnv -> BreakInfo -> [String]
findEnclosingDecls hsc_env (BreakInfo modl ix) =
let hmi = expectJust "findEnclosingDecls" $
lookupHpt (hsc_HPT hsc_env) (moduleName modl)
mb = getModBreaks hmi
in modBreaks_decls mb ! ix
-- | Update fixity environment in the current interactive context.
updateFixityEnv :: GhcMonad m => FixityEnv -> m ()
updateFixityEnv fix_env = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
setSession $ hsc_env { hsc_IC = ic { ic_fix_env = fix_env } }
-- -----------------------------------------------------------------------------
-- execStmt
-- | default ExecOptions
execOptions :: ExecOptions
execOptions = ExecOptions
{ execSingleStep = RunToCompletion
, execSourceFile = "<interactive>"
, execLineNumber = 1
, execWrap = EvalThis -- just run the statement, don't wrap it in anything
}
-- | Run a statement in the current interactive context.
execStmt
:: GhcMonad m
=> String -- ^ a statement (bind or expression)
-> ExecOptions
-> m ExecResult
execStmt stmt ExecOptions{..} = do
hsc_env <- getSession
-- Turn off -fwarn-unused-local-binds when running a statement, to hide
-- warnings about the implicit bindings we introduce.
let ic = hsc_IC hsc_env -- use the interactive dflags
idflags' = ic_dflags ic `wopt_unset` Opt_WarnUnusedLocalBinds
hsc_env' = hsc_env{ hsc_IC = ic{ ic_dflags = idflags' } }
-- compile to value (IO [HValue]), don't run
r <- liftIO $ hscStmtWithLocation hsc_env' stmt
execSourceFile execLineNumber
case r of
-- empty statement / comment
Nothing -> return (ExecComplete (Right []) 0)
Just (ids, hval, fix_env) -> do
updateFixityEnv fix_env
status <-
withVirtualCWD $
liftIO $
evalStmt hsc_env' (isStep execSingleStep) (execWrap hval)
let ic = hsc_IC hsc_env
bindings = (ic_tythings ic, ic_rn_gbl_env ic)
size = ghciHistSize idflags'
handleRunStatus execSingleStep stmt bindings ids
status (emptyHistory size)
-- | The type returned by the deprecated 'runStmt' and
-- 'runStmtWithLocation' API
data RunResult
= RunOk [Name] -- ^ names bound by this evaluation
| RunException SomeException -- ^ statement raised an exception
| RunBreak ThreadId [Name] (Maybe BreakInfo)
-- | Conver the old result type to the new result type
execResultToRunResult :: ExecResult -> RunResult
execResultToRunResult r =
case r of
ExecComplete{ execResult = Left ex } -> RunException ex
ExecComplete{ execResult = Right names } -> RunOk names
ExecBreak{..} -> RunBreak (error "no breakThreadId") breakNames breakInfo
-- Remove in GHC 7.14
{-# DEPRECATED runStmt "use execStmt" #-}
-- | Run a statement in the current interactive context. Statement
-- may bind multple values.
runStmt :: GhcMonad m => String -> SingleStep -> m RunResult
runStmt stmt step =
execResultToRunResult <$> execStmt stmt execOptions { execSingleStep = step }
-- Remove in GHC 7.14
{-# DEPRECATED runStmtWithLocation "use execStmtWithLocation" #-}
runStmtWithLocation :: GhcMonad m => String -> Int ->
String -> SingleStep -> m RunResult
runStmtWithLocation source linenumber expr step = do
execResultToRunResult <$>
execStmt expr execOptions { execSingleStep = step
, execSourceFile = source
, execLineNumber = linenumber }
runDecls :: GhcMonad m => String -> m [Name]
runDecls = runDeclsWithLocation "<interactive>" 1
-- | Run some declarations and return any user-visible names that were brought
-- into scope.
runDeclsWithLocation :: GhcMonad m => String -> Int -> String -> m [Name]
runDeclsWithLocation source linenumber expr =
do
hsc_env <- getSession
(tyThings, ic) <- liftIO $ hscDeclsWithLocation hsc_env expr source linenumber
setSession $ hsc_env { hsc_IC = ic }
hsc_env <- getSession
hsc_env' <- liftIO $ rttiEnvironment hsc_env
setSession hsc_env'
return $ filter (not . isDerivedOccName . nameOccName)
-- For this filter, see Note [What to show to users]
$ map getName tyThings
{- Note [What to show to users]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We don't want to display internally-generated bindings to users.
Things like the coercion axiom for newtypes. These bindings all get
OccNames that users can't write, to avoid the possiblity of name
clashes (in linker symbols). That gives a convenient way to suppress
them. The relevant predicate is OccName.isDerivedOccName.
See Trac #11051 for more background and examples.
-}
withVirtualCWD :: GhcMonad m => m a -> m a
withVirtualCWD m = do
hsc_env <- getSession
-- a virtual CWD is only necessary when we're running interpreted code in
-- the same process as the compiler.
if gopt Opt_ExternalInterpreter (hsc_dflags hsc_env) then m else do
let ic = hsc_IC hsc_env
let set_cwd = do
dir <- liftIO $ getCurrentDirectory
case ic_cwd ic of
Just dir -> liftIO $ setCurrentDirectory dir
Nothing -> return ()
return dir
reset_cwd orig_dir = do
virt_dir <- liftIO $ getCurrentDirectory
hsc_env <- getSession
let old_IC = hsc_IC hsc_env
setSession hsc_env{ hsc_IC = old_IC{ ic_cwd = Just virt_dir } }
liftIO $ setCurrentDirectory orig_dir
gbracket set_cwd reset_cwd $ \_ -> m
parseImportDecl :: GhcMonad m => String -> m (ImportDecl RdrName)
parseImportDecl expr = withSession $ \hsc_env -> liftIO $ hscImport hsc_env expr
emptyHistory :: Int -> BoundedList History
emptyHistory size = nilBL size
handleRunStatus :: GhcMonad m
=> SingleStep -> String-> ([TyThing],GlobalRdrEnv) -> [Id]
-> EvalStatus_ [ForeignHValue] [HValueRef]
-> BoundedList History
-> m ExecResult
handleRunStatus step expr bindings final_ids status history
| RunAndLogSteps <- step = tracing
| otherwise = not_tracing
where
tracing
| EvalBreak is_exception apStack_ref ix mod_uniq resume_ctxt _ccs <- status
, not is_exception
= do
hsc_env <- getSession
let hmi = expectJust "handleRunStatus" $
lookupHptDirectly (hsc_HPT hsc_env)
(mkUniqueGrimily mod_uniq)
modl = mi_module (hm_iface hmi)
breaks = getModBreaks hmi
b <- liftIO $
breakpointStatus hsc_env (modBreaks_flags breaks) ix
if b
then not_tracing
-- This breakpoint is explicitly enabled; we want to stop
-- instead of just logging it.
else do
apStack_fhv <- liftIO $ mkFinalizedHValue hsc_env apStack_ref
let bi = BreakInfo modl ix
!history' = mkHistory hsc_env apStack_fhv bi `consBL` history
-- history is strict, otherwise our BoundedList is pointless.
fhv <- liftIO $ mkFinalizedHValue hsc_env resume_ctxt
status <- liftIO $ GHCi.resumeStmt hsc_env True fhv
handleRunStatus RunAndLogSteps expr bindings final_ids
status history'
| otherwise
= not_tracing
not_tracing
-- Hit a breakpoint
| EvalBreak is_exception apStack_ref ix mod_uniq resume_ctxt ccs <- status
= do
hsc_env <- getSession
resume_ctxt_fhv <- liftIO $ mkFinalizedHValue hsc_env resume_ctxt
apStack_fhv <- liftIO $ mkFinalizedHValue hsc_env apStack_ref
let hmi = expectJust "handleRunStatus" $
lookupHptDirectly (hsc_HPT hsc_env)
(mkUniqueGrimily mod_uniq)
modl = mi_module (hm_iface hmi)
bp | is_exception = Nothing
| otherwise = Just (BreakInfo modl ix)
(hsc_env1, names, span, decl) <- liftIO $
bindLocalsAtBreakpoint hsc_env apStack_fhv bp
let
resume = Resume
{ resumeStmt = expr, resumeContext = resume_ctxt_fhv
, resumeBindings = bindings, resumeFinalIds = final_ids
, resumeApStack = apStack_fhv
, resumeBreakInfo = bp
, resumeSpan = span, resumeHistory = toListBL history
, resumeDecl = decl
, resumeCCS = ccs
, resumeHistoryIx = 0 }
hsc_env2 = pushResume hsc_env1 resume
setSession hsc_env2
return (ExecBreak names bp)
-- Completed successfully
| EvalComplete allocs (EvalSuccess hvals) <- status
= do hsc_env <- getSession
let final_ic = extendInteractiveContextWithIds (hsc_IC hsc_env) final_ids
final_names = map getName final_ids
liftIO $ Linker.extendLinkEnv (zip final_names hvals)
hsc_env' <- liftIO $ rttiEnvironment hsc_env{hsc_IC=final_ic}
setSession hsc_env'
return (ExecComplete (Right final_names) allocs)
-- Completed with an exception
| EvalComplete alloc (EvalException e) <- status
= return (ExecComplete (Left (fromSerializableException e)) alloc)
| otherwise
= panic "not_tracing" -- actually exhaustive, but GHC can't tell
resume :: GhcMonad m => (SrcSpan->Bool) -> SingleStep -> m RunResult
resume canLogSpan step = execResultToRunResult <$> resumeExec canLogSpan step
resumeExec :: GhcMonad m => (SrcSpan->Bool) -> SingleStep -> m ExecResult
resumeExec canLogSpan step
= do
hsc_env <- getSession
let ic = hsc_IC hsc_env
resume = ic_resume ic
case resume of
[] -> liftIO $
throwGhcExceptionIO (ProgramError "not stopped at a breakpoint")
(r:rs) -> do
-- unbind the temporary locals by restoring the TypeEnv from
-- before the breakpoint, and drop this Resume from the
-- InteractiveContext.
let (resume_tmp_te,resume_rdr_env) = resumeBindings r
ic' = ic { ic_tythings = resume_tmp_te,
ic_rn_gbl_env = resume_rdr_env,
ic_resume = rs }
setSession hsc_env{ hsc_IC = ic' }
-- remove any bindings created since the breakpoint from the
-- linker's environment
let old_names = map getName resume_tmp_te
new_names = [ n | thing <- ic_tythings ic
, let n = getName thing
, not (n `elem` old_names) ]
liftIO $ Linker.deleteFromLinkEnv new_names
case r of
Resume { resumeStmt = expr, resumeContext = fhv
, resumeBindings = bindings, resumeFinalIds = final_ids
, resumeApStack = apStack, resumeBreakInfo = mb_brkpt
, resumeSpan = span
, resumeHistory = hist } -> do
withVirtualCWD $ do
status <- liftIO $ GHCi.resumeStmt hsc_env (isStep step) fhv
let prevHistoryLst = fromListBL 50 hist
hist' = case mb_brkpt of
Nothing -> prevHistoryLst
Just bi
| not $canLogSpan span -> prevHistoryLst
| otherwise -> mkHistory hsc_env apStack bi `consBL`
fromListBL 50 hist
handleRunStatus step expr bindings final_ids status hist'
back :: GhcMonad m => Int -> m ([Name], Int, SrcSpan, String)
back n = moveHist (+n)
forward :: GhcMonad m => Int -> m ([Name], Int, SrcSpan, String)
forward n = moveHist (subtract n)
moveHist :: GhcMonad m => (Int -> Int) -> m ([Name], Int, SrcSpan, String)
moveHist fn = do
hsc_env <- getSession
case ic_resume (hsc_IC hsc_env) of
[] -> liftIO $
throwGhcExceptionIO (ProgramError "not stopped at a breakpoint")
(r:rs) -> do
let ix = resumeHistoryIx r
history = resumeHistory r
new_ix = fn ix
--
when (new_ix > length history) $ liftIO $
throwGhcExceptionIO (ProgramError "no more logged breakpoints")
when (new_ix < 0) $ liftIO $
throwGhcExceptionIO (ProgramError "already at the beginning of the history")
let
update_ic apStack mb_info = do
(hsc_env1, names, span, decl) <-
liftIO $ bindLocalsAtBreakpoint hsc_env apStack mb_info
let ic = hsc_IC hsc_env1
r' = r { resumeHistoryIx = new_ix }
ic' = ic { ic_resume = r':rs }
setSession hsc_env1{ hsc_IC = ic' }
return (names, new_ix, span, decl)
-- careful: we want apStack to be the AP_STACK itself, not a thunk
-- around it, hence the cases are carefully constructed below to
-- make this the case. ToDo: this is v. fragile, do something better.
if new_ix == 0
then case r of
Resume { resumeApStack = apStack,
resumeBreakInfo = mb_brkpt } ->
update_ic apStack mb_brkpt
else case history !! (new_ix - 1) of
History{..} ->
update_ic historyApStack (Just historyBreakInfo)
-- -----------------------------------------------------------------------------
-- After stopping at a breakpoint, add free variables to the environment
result_fs :: FastString
result_fs = fsLit "_result"
bindLocalsAtBreakpoint
:: HscEnv
-> ForeignHValue
-> Maybe BreakInfo
-> IO (HscEnv, [Name], SrcSpan, String)
-- Nothing case: we stopped when an exception was raised, not at a
-- breakpoint. We have no location information or local variables to
-- bind, all we can do is bind a local variable to the exception
-- value.
bindLocalsAtBreakpoint hsc_env apStack Nothing = do
let exn_occ = mkVarOccFS (fsLit "_exception")
span = mkGeneralSrcSpan (fsLit "<unknown>")
exn_name <- newInteractiveBinder hsc_env exn_occ span
let e_fs = fsLit "e"
e_name = mkInternalName (getUnique e_fs) (mkTyVarOccFS e_fs) span
e_tyvar = mkRuntimeUnkTyVar e_name liftedTypeKind
exn_id = Id.mkVanillaGlobal exn_name (mkTyVarTy e_tyvar)
ictxt0 = hsc_IC hsc_env
ictxt1 = extendInteractiveContextWithIds ictxt0 [exn_id]
--
Linker.extendLinkEnv [(exn_name, apStack)]
return (hsc_env{ hsc_IC = ictxt1 }, [exn_name], span, "<exception thrown>")
-- Just case: we stopped at a breakpoint, we have information about the location
-- of the breakpoint and the free variables of the expression.
bindLocalsAtBreakpoint hsc_env apStack_fhv (Just BreakInfo{..}) = do
let
hmi = expectJust "bindLocalsAtBreakpoint" $
lookupHpt (hsc_HPT hsc_env) (moduleName breakInfo_module)
breaks = getModBreaks hmi
info = expectJust "bindLocalsAtBreakpoint2" $
IntMap.lookup breakInfo_number (modBreaks_breakInfo breaks)
vars = cgb_vars info
result_ty = cgb_resty info
occs = modBreaks_vars breaks ! breakInfo_number
span = modBreaks_locs breaks ! breakInfo_number
decl = intercalate "." $ modBreaks_decls breaks ! breakInfo_number
-- Filter out any unboxed ids;
-- we can't bind these at the prompt
pointers = filter (\(id,_) -> isPointer id) vars
isPointer id | UnaryRep ty <- repType (idType id)
, PtrRep <- typePrimRep ty = True
| otherwise = False
(ids, offsets) = unzip pointers
free_tvs = tyCoVarsOfTypesList (result_ty:map idType ids)
-- It might be that getIdValFromApStack fails, because the AP_STACK
-- has been accidentally evaluated, or something else has gone wrong.
-- So that we don't fall over in a heap when this happens, just don't
-- bind any free variables instead, and we emit a warning.
mb_hValues <-
mapM (getBreakpointVar hsc_env apStack_fhv . fromIntegral) offsets
when (any isNothing mb_hValues) $
debugTraceMsg (hsc_dflags hsc_env) 1 $
text "Warning: _result has been evaluated, some bindings have been lost"
us <- mkSplitUniqSupply 'I' -- Dodgy; will give the same uniques every time
let tv_subst = newTyVars us free_tvs
filtered_ids = [ id | (id, Just _hv) <- zip ids mb_hValues ]
(_,tidy_tys) = tidyOpenTypes emptyTidyEnv $
map (substTy tv_subst . idType) filtered_ids
new_ids <- zipWith3M mkNewId occs tidy_tys filtered_ids
result_name <- newInteractiveBinder hsc_env (mkVarOccFS result_fs) span
let result_id = Id.mkVanillaGlobal result_name
(substTy tv_subst result_ty)
result_ok = isPointer result_id
final_ids | result_ok = result_id : new_ids
| otherwise = new_ids
ictxt0 = hsc_IC hsc_env
ictxt1 = extendInteractiveContextWithIds ictxt0 final_ids
names = map idName new_ids
let fhvs = catMaybes mb_hValues
Linker.extendLinkEnv (zip names fhvs)
when result_ok $ Linker.extendLinkEnv [(result_name, apStack_fhv)]
hsc_env1 <- rttiEnvironment hsc_env{ hsc_IC = ictxt1 }
return (hsc_env1, if result_ok then result_name:names else names, span, decl)
where
-- We need a fresh Unique for each Id we bind, because the linker
-- state is single-threaded and otherwise we'd spam old bindings
-- whenever we stop at a breakpoint. The InteractveContext is properly
-- saved/restored, but not the linker state. See #1743, test break026.
mkNewId :: OccName -> Type -> Id -> IO Id
mkNewId occ ty old_id
= do { name <- newInteractiveBinder hsc_env occ (getSrcSpan old_id)
; return (Id.mkVanillaGlobalWithInfo name ty (idInfo old_id)) }
newTyVars :: UniqSupply -> [TcTyVar] -> TCvSubst
-- Similarly, clone the type variables mentioned in the types
-- we have here, *and* make them all RuntimeUnk tyvars
newTyVars us tvs
= mkTvSubstPrs [ (tv, mkTyVarTy (mkRuntimeUnkTyVar name (tyVarKind tv)))
| (tv, uniq) <- tvs `zip` uniqsFromSupply us
, let name = setNameUnique (tyVarName tv) uniq ]
rttiEnvironment :: HscEnv -> IO HscEnv
rttiEnvironment hsc_env@HscEnv{hsc_IC=ic} = do
let tmp_ids = [id | AnId id <- ic_tythings ic]
incompletelyTypedIds =
[id | id <- tmp_ids
, not $ noSkolems id
, (occNameFS.nameOccName.idName) id /= result_fs]
hsc_env' <- foldM improveTypes hsc_env (map idName incompletelyTypedIds)
return hsc_env'
where
noSkolems = isEmptyVarSet . tyCoVarsOfType . idType
improveTypes hsc_env@HscEnv{hsc_IC=ic} name = do
let tmp_ids = [id | AnId id <- ic_tythings ic]
Just id = find (\i -> idName i == name) tmp_ids
if noSkolems id
then return hsc_env
else do
mb_new_ty <- reconstructType hsc_env 10 id
let old_ty = idType id
case mb_new_ty of
Nothing -> return hsc_env
Just new_ty -> do
case improveRTTIType hsc_env old_ty new_ty of
Nothing -> return $
WARN(True, text (":print failed to calculate the "
++ "improvement for a type")) hsc_env
Just subst -> do
let dflags = hsc_dflags hsc_env
when (dopt Opt_D_dump_rtti dflags) $
printInfoForUser dflags alwaysQualify $
fsep [text "RTTI Improvement for", ppr id, equals, ppr subst]
let ic' = substInteractiveContext ic subst
return hsc_env{hsc_IC=ic'}
pushResume :: HscEnv -> Resume -> HscEnv
pushResume hsc_env resume = hsc_env { hsc_IC = ictxt1 }
where
ictxt0 = hsc_IC hsc_env
ictxt1 = ictxt0 { ic_resume = resume : ic_resume ictxt0 }
-- -----------------------------------------------------------------------------
-- Abandoning a resume context
abandon :: GhcMonad m => m Bool
abandon = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
resume = ic_resume ic
case resume of
[] -> return False
r:rs -> do
setSession hsc_env{ hsc_IC = ic { ic_resume = rs } }
liftIO $ abandonStmt hsc_env (resumeContext r)
return True
abandonAll :: GhcMonad m => m Bool
abandonAll = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
resume = ic_resume ic
case resume of
[] -> return False
rs -> do
setSession hsc_env{ hsc_IC = ic { ic_resume = [] } }
liftIO $ mapM_ (abandonStmt hsc_env. resumeContext) rs
return True
-- -----------------------------------------------------------------------------
-- Bounded list, optimised for repeated cons
data BoundedList a = BL
{-# UNPACK #-} !Int -- length
{-# UNPACK #-} !Int -- bound
[a] -- left
[a] -- right, list is (left ++ reverse right)
nilBL :: Int -> BoundedList a
nilBL bound = BL 0 bound [] []
consBL :: a -> BoundedList a -> BoundedList a
consBL a (BL len bound left right)
| len < bound = BL (len+1) bound (a:left) right
| null right = BL len bound [a] $! tail (reverse left)
| otherwise = BL len bound (a:left) $! tail right
toListBL :: BoundedList a -> [a]
toListBL (BL _ _ left right) = left ++ reverse right
fromListBL :: Int -> [a] -> BoundedList a
fromListBL bound l = BL (length l) bound l []
-- lenBL (BL len _ _ _) = len
-- -----------------------------------------------------------------------------
-- | Set the interactive evaluation context.
--
-- (setContext imports) sets the ic_imports field (which in turn
-- determines what is in scope at the prompt) to 'imports', and
-- constructs the ic_rn_glb_env environment to reflect it.
--
-- We retain in scope all the things defined at the prompt, and kept
-- in ic_tythings. (Indeed, they shadow stuff from ic_imports.)
setContext :: GhcMonad m => [InteractiveImport] -> m ()
setContext imports
= do { hsc_env <- getSession
; let dflags = hsc_dflags hsc_env
; all_env_err <- liftIO $ findGlobalRdrEnv hsc_env imports
; case all_env_err of
Left (mod, err) ->
liftIO $ throwGhcExceptionIO (formatError dflags mod err)
Right all_env -> do {
; let old_ic = hsc_IC hsc_env
!final_rdr_env = all_env `icExtendGblRdrEnv` ic_tythings old_ic
; setSession
hsc_env{ hsc_IC = old_ic { ic_imports = imports
, ic_rn_gbl_env = final_rdr_env }}}}
where
formatError dflags mod err = ProgramError . showSDoc dflags $
text "Cannot add module" <+> ppr mod <+>
text "to context:" <+> text err
findGlobalRdrEnv :: HscEnv -> [InteractiveImport]
-> IO (Either (ModuleName, String) GlobalRdrEnv)
-- Compute the GlobalRdrEnv for the interactive context
findGlobalRdrEnv hsc_env imports
= do { idecls_env <- hscRnImportDecls hsc_env idecls
-- This call also loads any orphan modules
; return $ case partitionEithers (map mkEnv imods) of
([], imods_env) -> Right (foldr plusGlobalRdrEnv idecls_env imods_env)
(err : _, _) -> Left err }
where
idecls :: [LImportDecl RdrName]
idecls = [noLoc d | IIDecl d <- imports]
imods :: [ModuleName]
imods = [m | IIModule m <- imports]
mkEnv mod = case mkTopLevEnv (hsc_HPT hsc_env) mod of
Left err -> Left (mod, err)
Right env -> Right env
availsToGlobalRdrEnv :: ModuleName -> [AvailInfo] -> GlobalRdrEnv
availsToGlobalRdrEnv mod_name avails
= mkGlobalRdrEnv (gresFromAvails (Just imp_spec) avails)
where
-- We're building a GlobalRdrEnv as if the user imported
-- all the specified modules into the global interactive module
imp_spec = ImpSpec { is_decl = decl, is_item = ImpAll}
decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
is_qual = False,
is_dloc = srcLocSpan interactiveSrcLoc }
mkTopLevEnv :: HomePackageTable -> ModuleName -> Either String GlobalRdrEnv
mkTopLevEnv hpt modl
= case lookupHpt hpt modl of
Nothing -> Left "not a home module"
Just details ->
case mi_globals (hm_iface details) of
Nothing -> Left "not interpreted"
Just env -> Right env
-- | Get the interactive evaluation context, consisting of a pair of the
-- set of modules from which we take the full top-level scope, and the set
-- of modules from which we take just the exports respectively.
getContext :: GhcMonad m => m [InteractiveImport]
getContext = withSession $ \HscEnv{ hsc_IC=ic } ->
return (ic_imports ic)
-- | Returns @True@ if the specified module is interpreted, and hence has
-- its full top-level scope available.
moduleIsInterpreted :: GhcMonad m => Module -> m Bool
moduleIsInterpreted modl = withSession $ \h ->
if moduleUnitId modl /= thisPackage (hsc_dflags h)
then return False
else case lookupHpt (hsc_HPT h) (moduleName modl) of
Just details -> return (isJust (mi_globals (hm_iface details)))
_not_a_home_module -> return False
-- | Looks up an identifier in the current interactive context (for :info)
-- Filter the instances by the ones whose tycons (or clases resp)
-- are in scope (qualified or otherwise). Otherwise we list a whole lot too many!
-- The exact choice of which ones to show, and which to hide, is a judgement call.
-- (see Trac #1581)
getInfo :: GhcMonad m => Bool -> Name -> m (Maybe (TyThing,Fixity,[ClsInst],[FamInst]))
getInfo allInfo name
= withSession $ \hsc_env ->
do mb_stuff <- liftIO $ hscTcRnGetInfo hsc_env name
case mb_stuff of
Nothing -> return Nothing
Just (thing, fixity, cls_insts, fam_insts) -> do
let rdr_env = ic_rn_gbl_env (hsc_IC hsc_env)
-- Filter the instances based on whether the constituent names of their
-- instance heads are all in scope.
let cls_insts' = filter (plausible rdr_env . orphNamesOfClsInst) cls_insts
fam_insts' = filter (plausible rdr_env . orphNamesOfFamInst) fam_insts
return (Just (thing, fixity, cls_insts', fam_insts'))
where
plausible rdr_env names
-- Dfun involving only names that are in ic_rn_glb_env
= allInfo
|| nameSetAll ok names
where -- A name is ok if it's in the rdr_env,
-- whether qualified or not
ok n | n == name = True
-- The one we looked for in the first place!
| pretendNameIsInScope n = True
| isBuiltInSyntax n = True
| isExternalName n = isJust (lookupGRE_Name rdr_env n)
| otherwise = True
-- | Returns all names in scope in the current interactive context
getNamesInScope :: GhcMonad m => m [Name]
getNamesInScope = withSession $ \hsc_env -> do
return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
-- | Returns all 'RdrName's in scope in the current interactive
-- context, excluding any that are internally-generated.
getRdrNamesInScope :: GhcMonad m => m [RdrName]
getRdrNamesInScope = withSession $ \hsc_env -> do
let
ic = hsc_IC hsc_env
gbl_rdrenv = ic_rn_gbl_env ic
gbl_names = concatMap greRdrNames $ globalRdrEnvElts gbl_rdrenv
-- Exclude internally generated names; see e.g. Trac #11328
return (filter (not . isDerivedOccName . rdrNameOcc) gbl_names)
-- | Parses a string as an identifier, and returns the list of 'Name's that
-- the identifier can refer to in the current interactive context.
parseName :: GhcMonad m => String -> m [Name]
parseName str = withSession $ \hsc_env -> liftIO $
do { lrdr_name <- hscParseIdentifier hsc_env str
; hscTcRnLookupRdrName hsc_env lrdr_name }
-- | Returns @True@ if passed string is a statement.
isStmt :: DynFlags -> String -> Bool
isStmt dflags stmt =
case parseThing Parser.parseStmt dflags stmt of
Lexer.POk _ _ -> True
Lexer.PFailed _ _ -> False
-- | Returns @True@ if passed string has an import declaration.
hasImport :: DynFlags -> String -> Bool
hasImport dflags stmt =
case parseThing Parser.parseModule dflags stmt of
Lexer.POk _ thing -> hasImports thing
Lexer.PFailed _ _ -> False
where
hasImports = not . null . hsmodImports . unLoc
-- | Returns @True@ if passed string is an import declaration.
isImport :: DynFlags -> String -> Bool
isImport dflags stmt =
case parseThing Parser.parseImport dflags stmt of
Lexer.POk _ _ -> True
Lexer.PFailed _ _ -> False
-- | Returns @True@ if passed string is a declaration but __/not a splice/__.
isDecl :: DynFlags -> String -> Bool
isDecl dflags stmt = do
case parseThing Parser.parseDeclaration dflags stmt of
Lexer.POk _ thing ->
case unLoc thing of
SpliceD _ -> False
_ -> True
Lexer.PFailed _ _ -> False
parseThing :: Lexer.P thing -> DynFlags -> String -> Lexer.ParseResult thing
parseThing parser dflags stmt = do
let buf = stringToStringBuffer stmt
loc = mkRealSrcLoc (fsLit "<interactive>") 1 1
Lexer.unP parser (Lexer.mkPState dflags buf loc)
-- -----------------------------------------------------------------------------
-- Getting the type of an expression
-- | Get the type of an expression
-- Returns the type as described by 'TcRnExprMode'
exprType :: GhcMonad m => TcRnExprMode -> String -> m Type
exprType mode expr = withSession $ \hsc_env -> do
ty <- liftIO $ hscTcExpr hsc_env mode expr
return $ tidyType emptyTidyEnv ty
-- -----------------------------------------------------------------------------
-- Getting the kind of a type
-- | Get the kind of a type
typeKind :: GhcMonad m => Bool -> String -> m (Type, Kind)
typeKind normalise str = withSession $ \hsc_env -> do
liftIO $ hscKcType hsc_env normalise str
-----------------------------------------------------------------------------
-- Compile an expression, run it and deliver the result
-- | Parse an expression, the parsed expression can be further processed and
-- passed to compileParsedExpr.
parseExpr :: GhcMonad m => String -> m (LHsExpr RdrName)
parseExpr expr = withSession $ \hsc_env -> do
liftIO $ runInteractiveHsc hsc_env $ hscParseExpr expr
-- | Compile an expression, run it and deliver the resulting HValue.
compileExpr :: GhcMonad m => String -> m HValue
compileExpr expr = do
parsed_expr <- parseExpr expr
compileParsedExpr parsed_expr
-- | Compile an expression, run it and deliver the resulting HValue.
compileExprRemote :: GhcMonad m => String -> m ForeignHValue
compileExprRemote expr = do
parsed_expr <- parseExpr expr
compileParsedExprRemote parsed_expr
-- | Compile an parsed expression (before renaming), run it and deliver
-- the resulting HValue.
compileParsedExprRemote :: GhcMonad m => LHsExpr RdrName -> m ForeignHValue
compileParsedExprRemote expr@(L loc _) = withSession $ \hsc_env -> do
-- > let _compileParsedExpr = expr
-- Create let stmt from expr to make hscParsedStmt happy.
-- We will ignore the returned [Id], namely [expr_id], and not really
-- create a new binding.
let expr_fs = fsLit "_compileParsedExpr"
expr_name = mkInternalName (getUnique expr_fs) (mkTyVarOccFS expr_fs) loc
let_stmt = L loc . LetStmt . L loc . HsValBinds $
ValBindsIn (unitBag $ mkHsVarBind loc (getRdrName expr_name) expr) []
Just ([_id], hvals_io, fix_env) <- liftIO $ hscParsedStmt hsc_env let_stmt
updateFixityEnv fix_env
status <- liftIO $ evalStmt hsc_env False (EvalThis hvals_io)
case status of
EvalComplete _ (EvalSuccess [hval]) -> return hval
EvalComplete _ (EvalException e) ->
liftIO $ throwIO (fromSerializableException e)
_ -> panic "compileParsedExpr"
compileParsedExpr :: GhcMonad m => LHsExpr RdrName -> m HValue
compileParsedExpr expr = do
fhv <- compileParsedExprRemote expr
dflags <- getDynFlags
liftIO $ wormhole dflags fhv
-- | Compile an expression, run it and return the result as a Dynamic.
dynCompileExpr :: GhcMonad m => String -> m Dynamic
dynCompileExpr expr = do
parsed_expr <- parseExpr expr
-- > Data.Dynamic.toDyn expr
let loc = getLoc parsed_expr
to_dyn_expr = mkHsApp (L loc . HsVar . L loc $ getRdrName toDynName)
parsed_expr
hval <- compileParsedExpr to_dyn_expr
return (unsafeCoerce# hval :: Dynamic)
-----------------------------------------------------------------------------
-- show a module and it's source/object filenames
showModule :: GhcMonad m => ModSummary -> m String
showModule mod_summary =
withSession $ \hsc_env -> do
interpreted <- isModuleInterpreted mod_summary
let dflags = hsc_dflags hsc_env
return (showModMsg dflags (hscTarget dflags) interpreted mod_summary)
isModuleInterpreted :: GhcMonad m => ModSummary -> m Bool
isModuleInterpreted mod_summary = withSession $ \hsc_env ->
case lookupHpt (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
Nothing -> panic "missing linkable"
Just mod_info -> return (not obj_linkable)
where
obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
----------------------------------------------------------------------------
-- RTTI primitives
obtainTermFromVal :: HscEnv -> Int -> Bool -> Type -> a -> IO Term
obtainTermFromVal hsc_env bound force ty x =
cvObtainTerm hsc_env bound force ty (unsafeCoerce# x)
obtainTermFromId :: HscEnv -> Int -> Bool -> Id -> IO Term
obtainTermFromId hsc_env bound force id = do
let dflags = hsc_dflags hsc_env
hv <- Linker.getHValue hsc_env (varName id) >>= wormhole dflags
cvObtainTerm hsc_env bound force (idType id) hv
-- Uses RTTI to reconstruct the type of an Id, making it less polymorphic
reconstructType :: HscEnv -> Int -> Id -> IO (Maybe Type)
reconstructType hsc_env bound id = do
let dflags = hsc_dflags hsc_env
hv <- Linker.getHValue hsc_env (varName id) >>= wormhole dflags
cvReconstructType hsc_env bound (idType id) hv
mkRuntimeUnkTyVar :: Name -> Kind -> TyVar
mkRuntimeUnkTyVar name kind = mkTcTyVar name kind RuntimeUnk
| olsner/ghc | compiler/main/InteractiveEval.hs | bsd-3-clause | 38,399 | 13 | 30 | 10,053 | 8,705 | 4,438 | 4,267 | 681 | 4 |
module Main (main) where
import qualified System.FilePath.Glob as Glob
import qualified Test.DocTest as DocTest
includeDirs :: [String]
includeDirs = []
doctestWithIncludeDirs :: [String] -> IO ()
doctestWithIncludeDirs fs = DocTest.doctest (map ("-I" ++) includeDirs ++ fs)
main :: IO ()
main = Glob.glob "src/**/*.hs" >>= doctestWithIncludeDirs | rcook/sudoku-solver | test/Main.hs | bsd-3-clause | 350 | 0 | 9 | 49 | 111 | 64 | 47 | 9 | 1 |
string1 = "hello"
string2 = "world"
greeting = string1 ++ " " ++ string2 | keshavbashyal/playground-notes | unfinished-courses/haskell-fundamentals/hello.hs | mit | 73 | 0 | 6 | 14 | 24 | 13 | 11 | 3 | 1 |
{-# language ScopedTypeVariables, OverloadedStrings #-}
module Base.Renderable.Header (header, headerHeight) where
import Data.Abelian
import Graphics.Qt
import Utils
import Base.Types
import Base.Constants
import Base.Prose
import Base.Font
import Base.Pixmap
import Base.Renderable.HBox
import Base.Renderable.Centered
headerHeight :: Double = 44
-- | implements menu headers
header :: Application -> Prose -> RenderableInstance
header app =
colorizeProse headerFontColor >>>
capitalizeProse >>>
proseToGlyphs (standardFont app) >>>
fmap (glyphToHeaderCube app) >>>
addStartAndEndCube app >>>
hBox >>>
renderable
data HeaderCube
= StartCube
| StandardCube Glyph
| SpaceCube
| EndCube
deriving Show
-- | converts a glyph into a renderable cube for headers
glyphToHeaderCube :: Application -> Glyph -> HeaderCube
glyphToHeaderCube app glyph =
if equalsSpace glyph then SpaceCube else StandardCube glyph
equalsSpace :: Glyph -> Bool
equalsSpace (Glyph c _) = " " == c
equalsSpace ErrorGlyph{} = False
-- | Adds one cube before and one cube after the header.
addStartAndEndCube :: Application -> [HeaderCube] -> [HeaderCube]
addStartAndEndCube app inner =
StartCube :
inner ++
EndCube :
[]
where
pixmaps = headerCubePixmaps $ applicationPixmaps app
instance Renderable HeaderCube where
label = const "HeaderCube"
render ptr app config size cube = case pixmapCube cube of
Left getter -> render ptr app config size $ getter pixmaps
Right glyph -> do
(childSize, background) <- render ptr app config size $ standardCube pixmaps
return $ tuple childSize $ do
recoverMatrix ptr background
snd =<< render ptr app config (childSize -~ Size (fromUber 1) 0)
(centered [glyph])
where
pixmaps = headerCubePixmaps $ applicationPixmaps app
-- | Returns (Left getter) if the cube should be rendered by just one pixmap,
-- (Right glyph) otherwise.
pixmapCube :: HeaderCube -> Either (HeaderCubePixmaps -> Pixmap) Glyph
pixmapCube cube = case cube of
StartCube -> Left startCube
SpaceCube -> Left spaceCube
EndCube -> Left endCube
StandardCube x -> Right x
| geocurnoff/nikki | src/Base/Renderable/Header.hs | lgpl-3.0 | 2,265 | 0 | 20 | 519 | 561 | 288 | 273 | 58 | 4 |
-------------------------------------------------------------------------------
-- |
-- Module : System.Hardware.Haskino.SamplePrograms.Deep.ScheduledBlinkE
-- Copyright : (c) University of Kansas
-- License : BSD3
-- Stability : experimental
--
-- The /hello world/ of the arduino world, blinking the led.
-- This version is done by creating a scheduled task on the Arduino which
-- blinks the LED on and off without host intervention.
-------------------------------------------------------------------------------
module System.Hardware.Haskino.SamplePrograms.Deep.ScheduledBlinkE where
import Control.Concurrent (threadDelay)
import Control.Monad.Trans (liftIO)
import Data.Boolean.Numbers
import Data.Word
import System.Hardware.Haskino
blinkDelay :: Expr Word32
blinkDelay = lit 1000
startDelay :: Expr Word32
startDelay = blinkDelay * lit 5
progDelay :: Int
progDelay = 10500
-- Task which will execute on Arduino, blink on a second, off a second and
-- repeat
myTask :: Expr Word8 -> Arduino ()
myTask led =
loopE $ do
digitalWriteE led (lit True)
delayMillisE blinkDelay
digitalWriteE led (lit False)
delayMillisE blinkDelay
scheduledBlinkE :: IO ()
scheduledBlinkE = withArduino True "/dev/cu.usbmodem1421" $ do
let led = 13
let tid = 1
setPinModeE led OUTPUT
-- Create the task which blinks with a 2 second period
createTaskE tid (myTask led)
-- Schedule the task to start in 5 seconds
scheduleTaskE tid startDelay
tasks <- queryAllTasksE
liftIO $ print tasks
-- Query to confirm task creation
task <- queryTaskE tid
liftIO $ print task
-- Wait 10.5 seconds and delete the task
-- Note, delayMillis cannot be used here, as it would prevent scheduled
-- task from running on target.
liftIO $ print "Delaying 10500 milliseconds"
liftIO $ threadDelay (progDelay * 1000)
deleteTaskE tid
tasks <- queryAllTasksE
liftIO $ print tasks
| ku-fpg/kansas-amber | legacy/Deep/ScheduledBlinkE.hs | bsd-3-clause | 1,986 | 0 | 11 | 404 | 341 | 173 | 168 | 35 | 1 |
-- GSoC 2013 - Communicating with mobile devices.
-- | This library defines an API for communicating with Android powered devices, sending Push Notifications through Google Cloud Messaging (HTTP connection).
module Network.PushNotify.Gcm
(
-- * GCM Service
sendGCM
-- * GCM Settings
, GCMHttpConfig(..)
, RegId
-- * GCM Messages
, GCMmessage(..)
-- * GCM Result
, GCMresult(..)
) where
import Network.PushNotify.Gcm.Types
import Network.PushNotify.Gcm.Send
| MarcosPividori/GSoC-Communicating-with-mobile-devices | push-notify/Network/PushNotify/Gcm.hs | mit | 506 | 0 | 5 | 113 | 56 | 41 | 15 | 9 | 0 |
{-# LANGUAGE TypeFamilies, DataKinds, PolyKinds, ExplicitForAll, GADTs,
UndecidableInstances, RankNTypes, ScopedTypeVariables #-}
module T14066a where
import Data.Proxy
import Data.Kind
import Data.Type.Bool
type family Bar x y where
Bar (x :: a) (y :: b) = Int
Bar (x :: c) (y :: d) = Bool -- a,b,c,d should be TyVarTvs and unify appropriately
-- the two k's, even though they have different scopes, should unify in the
-- kind-check and then work in the type-check because Prox3 has been generalized
data Prox3 a where
MkProx3a :: Prox3 (a :: k1)
MkProx3b :: Prox3 (a :: k2)
-- This probably should be rejected, as it's polymorphic recursion without a CUSK.
-- But GHC accepts it because the polymorphic occurrence is at a type variable.
data T0 a = forall k (b :: k). MkT0 (T0 b) Int
-- k and j should unify
type family G x a where
G Int (b :: k) = Int
G Bool (c :: j) = Bool
-- this last example just checks that GADT pattern-matching on kinds still works.
-- nothing new here.
data T (a :: k) where
MkT :: T (a :: Type -> Type)
data S (a :: Type -> Type) where
MkS :: S a
f :: forall k (a :: k). Proxy a -> T a -> ()
f _ MkT = let y :: S a
y = MkS
in ()
-- This is questionable. Should we use the RHS to determine dependency? It works
-- now, but if it stops working in the future, that's not a deal-breaker.
type P k a = Proxy (a :: k)
-- This is a challenge. It should be accepted, but only because c's kind is learned
-- to be Proxy True, allowing b to be assigned kind `a`. If we don't know c's kind,
-- then GHC would need to be convinced that If (c's kind) b d always has kind `a`.
-- Naively, we don't know about c's kind early enough.
data SameKind :: forall k. k -> k -> Type
type family IfK (e :: Proxy (j :: Bool)) (f :: m) (g :: n) :: If j m n where
IfK (_ :: Proxy True) f _ = f
IfK (_ :: Proxy False) _ g = g
x :: forall c. (forall a b (d :: a). SameKind (IfK c b d) d) -> (Proxy (c :: Proxy True))
x _ = Proxy
f2 :: forall b. b -> Proxy Maybe
f2 x = fstOf3 y :: Proxy Maybe
where
y :: (Proxy a, Proxy c, b)
y = (Proxy, Proxy, x)
fstOf3 (x, _, _) = x
f3 :: forall b. b -> Proxy Maybe
f3 x = fst y :: Proxy Maybe
where
y :: (Proxy a, b)
y = (Proxy, x)
-- cf. dependent/should_fail/T14066h. Here, y's type does *not* capture any variables,
-- so it is generalized, even with MonoLocalBinds.
f4 x = (fst y :: Proxy Int, fst y :: Proxy Maybe)
where
y :: (Proxy a, Int)
y = (Proxy, x)
| sdiehl/ghc | testsuite/tests/dependent/should_compile/T14066a.hs | bsd-3-clause | 2,522 | 0 | 11 | 632 | 707 | 413 | 294 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : Main (hlint)
-- Copyright : (C) 2013-2015 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : provisional
-- Portability : portable
--
-- This module runs HLint on the lens source tree.
-----------------------------------------------------------------------------
module Main where
import Control.Monad
import Language.Haskell.HLint
import System.Environment
import System.Exit
main :: IO ()
main = do
args <- getArgs
hints <- hlint $ ["src", "--cpp-define=HLINT", "--cpp-ansi"] ++ args
unless (null hints) exitFailure
| ekmett/concurrent | tests/hlint.hs | bsd-2-clause | 718 | 0 | 10 | 117 | 96 | 57 | 39 | 10 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveTraversable #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Complex
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Complex numbers.
--
-----------------------------------------------------------------------------
module Data.Complex
(
-- * Rectangular form
Complex((:+))
, realPart
, imagPart
-- * Polar form
, mkPolar
, cis
, polar
, magnitude
, phase
-- * Conjugate
, conjugate
) where
import GHC.Generics (Generic, Generic1)
import GHC.Float (Floating(..))
import Data.Data (Data)
import Foreign (Storable, castPtr, peek, poke, pokeElemOff, peekElemOff, sizeOf,
alignment)
infix 6 :+
-- -----------------------------------------------------------------------------
-- The Complex type
-- | Complex numbers are an algebraic type.
--
-- For a complex number @z@, @'abs' z@ is a number with the magnitude of @z@,
-- but oriented in the positive real direction, whereas @'signum' z@
-- has the phase of @z@, but unit magnitude.
--
-- The 'Foldable' and 'Traversable' instances traverse the real part first.
data Complex a
= !a :+ !a -- ^ forms a complex number from its real and imaginary
-- rectangular components.
deriving (Eq, Show, Read, Data, Generic, Generic1
, Functor, Foldable, Traversable)
-- -----------------------------------------------------------------------------
-- Functions over Complex
-- | Extracts the real part of a complex number.
realPart :: Complex a -> a
realPart (x :+ _) = x
-- | Extracts the imaginary part of a complex number.
imagPart :: Complex a -> a
imagPart (_ :+ y) = y
-- | The conjugate of a complex number.
{-# SPECIALISE conjugate :: Complex Double -> Complex Double #-}
conjugate :: Num a => Complex a -> Complex a
conjugate (x:+y) = x :+ (-y)
-- | Form a complex number from polar components of magnitude and phase.
{-# SPECIALISE mkPolar :: Double -> Double -> Complex Double #-}
mkPolar :: Floating a => a -> a -> Complex a
mkPolar r theta = r * cos theta :+ r * sin theta
-- | @'cis' t@ is a complex value with magnitude @1@
-- and phase @t@ (modulo @2*'pi'@).
{-# SPECIALISE cis :: Double -> Complex Double #-}
cis :: Floating a => a -> Complex a
cis theta = cos theta :+ sin theta
-- | The function 'polar' takes a complex number and
-- returns a (magnitude, phase) pair in canonical form:
-- the magnitude is nonnegative, and the phase in the range @(-'pi', 'pi']@;
-- if the magnitude is zero, then so is the phase.
{-# SPECIALISE polar :: Complex Double -> (Double,Double) #-}
polar :: (RealFloat a) => Complex a -> (a,a)
polar z = (magnitude z, phase z)
-- | The nonnegative magnitude of a complex number.
{-# SPECIALISE magnitude :: Complex Double -> Double #-}
magnitude :: (RealFloat a) => Complex a -> a
magnitude (x:+y) = scaleFloat k
(sqrt (sqr (scaleFloat mk x) + sqr (scaleFloat mk y)))
where k = max (exponent x) (exponent y)
mk = - k
sqr z = z * z
-- | The phase of a complex number, in the range @(-'pi', 'pi']@.
-- If the magnitude is zero, then so is the phase.
{-# SPECIALISE phase :: Complex Double -> Double #-}
phase :: (RealFloat a) => Complex a -> a
phase (0 :+ 0) = 0 -- SLPJ July 97 from John Peterson
phase (x:+y) = atan2 y x
-- -----------------------------------------------------------------------------
-- Instances of Complex
instance (RealFloat a) => Num (Complex a) where
{-# SPECIALISE instance Num (Complex Float) #-}
{-# SPECIALISE instance Num (Complex Double) #-}
(x:+y) + (x':+y') = (x+x') :+ (y+y')
(x:+y) - (x':+y') = (x-x') :+ (y-y')
(x:+y) * (x':+y') = (x*x'-y*y') :+ (x*y'+y*x')
negate (x:+y) = negate x :+ negate y
abs z = magnitude z :+ 0
signum (0:+0) = 0
signum z@(x:+y) = x/r :+ y/r where r = magnitude z
fromInteger n = fromInteger n :+ 0
instance (RealFloat a) => Fractional (Complex a) where
{-# SPECIALISE instance Fractional (Complex Float) #-}
{-# SPECIALISE instance Fractional (Complex Double) #-}
(x:+y) / (x':+y') = (x*x''+y*y'') / d :+ (y*x''-x*y'') / d
where x'' = scaleFloat k x'
y'' = scaleFloat k y'
k = - max (exponent x') (exponent y')
d = x'*x'' + y'*y''
fromRational a = fromRational a :+ 0
instance (RealFloat a) => Floating (Complex a) where
{-# SPECIALISE instance Floating (Complex Float) #-}
{-# SPECIALISE instance Floating (Complex Double) #-}
pi = pi :+ 0
exp (x:+y) = expx * cos y :+ expx * sin y
where expx = exp x
log z = log (magnitude z) :+ phase z
x ** y = case (x,y) of
(_ , (0:+0)) -> 1 :+ 0
((0:+0), (exp_re:+_)) -> case compare exp_re 0 of
GT -> 0 :+ 0
LT -> inf :+ 0
EQ -> nan :+ nan
((re:+im), (exp_re:+_))
| (isInfinite re || isInfinite im) -> case compare exp_re 0 of
GT -> inf :+ 0
LT -> 0 :+ 0
EQ -> nan :+ nan
| otherwise -> exp (log x * y)
where
inf = 1/0
nan = 0/0
sqrt (0:+0) = 0
sqrt z@(x:+y) = u :+ (if y < 0 then -v else v)
where (u,v) = if x < 0 then (v',u') else (u',v')
v' = abs y / (u'*2)
u' = sqrt ((magnitude z + abs x) / 2)
sin (x:+y) = sin x * cosh y :+ cos x * sinh y
cos (x:+y) = cos x * cosh y :+ (- sin x * sinh y)
tan (x:+y) = (sinx*coshy:+cosx*sinhy)/(cosx*coshy:+(-sinx*sinhy))
where sinx = sin x
cosx = cos x
sinhy = sinh y
coshy = cosh y
sinh (x:+y) = cos y * sinh x :+ sin y * cosh x
cosh (x:+y) = cos y * cosh x :+ sin y * sinh x
tanh (x:+y) = (cosy*sinhx:+siny*coshx)/(cosy*coshx:+siny*sinhx)
where siny = sin y
cosy = cos y
sinhx = sinh x
coshx = cosh x
asin z@(x:+y) = y':+(-x')
where (x':+y') = log (((-y):+x) + sqrt (1 - z*z))
acos z = y'':+(-x'')
where (x'':+y'') = log (z + ((-y'):+x'))
(x':+y') = sqrt (1 - z*z)
atan z@(x:+y) = y':+(-x')
where (x':+y') = log (((1-y):+x) / sqrt (1+z*z))
asinh z = log (z + sqrt (1+z*z))
acosh z = log (z + (z+1) * sqrt ((z-1)/(z+1)))
atanh z = 0.5 * log ((1.0+z) / (1.0-z))
log1p x@(a :+ b)
| abs a < 0.5 && abs b < 0.5
, u <- 2*a + a*a + b*b = log1p (u/(1 + sqrt(u+1))) :+ atan2 (1 + a) b
| otherwise = log (1 + x)
{-# INLINE log1p #-}
expm1 x@(a :+ b)
| a*a + b*b < 1
, u <- expm1 a
, v <- sin (b/2)
, w <- -2*v*v = (u*w + u + w) :+ (u+1)*sin b
| otherwise = exp x - 1
{-# INLINE expm1 #-}
instance Storable a => Storable (Complex a) where
sizeOf a = 2 * sizeOf (realPart a)
alignment a = alignment (realPart a)
peek p = do
q <- return $ castPtr p
r <- peek q
i <- peekElemOff q 1
return (r :+ i)
poke p (r :+ i) = do
q <-return $ (castPtr p)
poke q r
pokeElemOff q 1 i
instance Applicative Complex where
pure a = a :+ a
f :+ g <*> a :+ b = f a :+ g b
instance Monad Complex where
a :+ b >>= f = realPart (f a) :+ imagPart (f b)
| tolysz/prepare-ghcjs | spec-lts8/base/Data/Complex.hs | bsd-3-clause | 8,399 | 2 | 15 | 2,957 | 2,779 | 1,455 | 1,324 | -1 | -1 |
module Test18 where
f = 45
| kmate/HaRe | old/testing/refacSlicing/Test18_TokOut.hs | bsd-3-clause | 30 | 0 | 4 | 9 | 9 | 6 | 3 | 2 | 1 |
{-# LANGUAGE TemplateHaskell, FlexibleInstances #-}
module TH_overlaps where
import Language.Haskell.TH
class C1 a where c1 :: a
class C2 a where c2 :: a
class C3 a where c3 :: a
[d|
instance {-# OVERLAPPABLE #-} C1 [a] where c1 = []
instance C1 [Int] where c1 = [1]
instance C2 [a] where c2 = []
instance {-# OVERLAPPING #-} C2 [Int] where c2 = [1]
instance C3 [a] where c3 = []
instance {-# OVERLAPS #-} C3 [[a]] where c3 = [[]]
instance C3 [[Int]] where c3 = [[1]]
|]
test1 :: ([Char],[Int])
test1 = (c1,c1)
test2 :: ([Char],[Int])
test2 = (c2,c2)
test3 :: ([Char],[[Char]],[[Int]])
test3 = (c3,c3,c3)
| olsner/ghc | testsuite/tests/th/TH_overlaps.hs | bsd-3-clause | 743 | 0 | 7 | 247 | 159 | 98 | 61 | 20 | 1 |
{-# LANGUAGE ForeignFunctionInterface #-}
module Shared001 where
-- Test for building DLLs with ghc -shared, see #2745
f :: Int -> Int
f x = x+1
foreign export ccall f :: Int -> Int
| ezyang/ghc | testsuite/tests/driver/Shared001.hs | bsd-3-clause | 185 | 0 | 6 | 37 | 41 | 24 | 17 | 5 | 1 |
module Spring where
import Data.Array.Unboxed
step :: UArray Int Double -> [Double]
step y = [y!1 + y!0]
| urbanslug/ghc | testsuite/tests/codeGen/should_compile/T3132.hs | bsd-3-clause | 107 | 0 | 8 | 20 | 50 | 28 | 22 | 4 | 1 |
{-
collatz computes the number of Collatz chains from one to the maximum
starting number where the length of the chain is greater than bound.
-}
module Main where
start = 100000
bound = 40
chain :: Integer -> [Integer]
chain 1 = [1]
chain x
| even x = x: chain (div x 2)
| odd x = x : chain (3 * x + 1)
numLongChains :: Int
numLongChains = length $ filter (\xs -> length xs > bound)
(map chain [1..start])
main :: IO ()
main = print numLongChains
| kisom/collatz | collatz.hs | isc | 490 | 0 | 10 | 135 | 165 | 85 | 80 | 13 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.