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 MultiWayIf #-}
{-# LANGUAGE ParallelListComp #-}
module Data.YamlDir ( -- * Only YAML files
-- $yaml
decodeYamlPath
, decodeYamlPathEither
-- * Only Text files
-- $text
, decodeTextPath
, decodeTextPathEither
-- * Files Based On Extension
-- $extension
, decodeExtnPath
, decodeExtnPathEither
) where
import Data.Either (either)
import Data.HashMap.Strict (fromList)
import Data.List (isSuffixOf)
import Data.Text (pack)
import qualified Data.Text.IO as T
import Data.Yaml
import System.Directory ( doesDirectoryExist
, getDirectoryContents
)
import System.FilePath ((</>), takeBaseName)
filterDir :: IO [String] -> IO [String]
filterDir = fmap (filter go)
where go d = d /= "." && d /= ".."
toMaybe :: Either a b -> Maybe b
toMaybe (Left _) = Nothing
toMaybe (Right x) = Just x
decodePath :: FromJSON t => FileFunc -> FilePath -> IO (Maybe t)
decodePath func path = fmap toMaybe (decodeEitherPath func path)
decodeEitherPath :: FromJSON t => FileFunc -> FilePath -> IO (Either String t)
decodeEitherPath func path = do
val <- parsePath func path
return (val >>= parseEither parseJSON)
-- as-yaml functions
{- $yaml
These functions read in a directory as a YAML object and assume that
each file within the directory itself contains a YAML value. For example,
if we create the directory
> $ mkdir mydir
> $ cat >mydir/foo <<EOF
> > [1,2,3]
> > EOF
> $ cat >mydir/bar <<EOF
> > baz: true
> > quux: false
> > EOF
then @decodeYamlPath "mydir"@ will return
> Just (Object (fromList [ ("foo", Array (fromList [ Number 1.0
> , Number 2.0
> , Number 3.0
> ]))
> , ("bar", Object (fromList [ ("baz", Bool True)
> , ("quux", Bool False)
> ]))
> ]))
-}
decodeYamlPath :: FromJSON t => FilePath -> IO (Maybe t)
decodeYamlPath = fmap toMaybe . decodeYamlPathEither
decodeYamlPathEither :: FromJSON t => FilePath -> IO (Either String t)
decodeYamlPathEither = decodeEitherPath go
where go = fmap (either (Left . show) (Right)) . decodeFileEither
-- as-text functions
{- $text
These functions read in a directory as a YAML object and treat each
file in the directory as containing a YAML string value. For example,
if we create the directory
> $ mkdir mydir
> $ cat >mydir/foo <<EOF
> > [1,2,3]
> > EOF
> $ cat >mydir/bar <<EOF
> > baz: true
> > quux: false
> > EOF
then @decodeTextPath "mydir"@ will return
> Just (Object (fromList [ ("foo", String "[1,2,3]\n")
> , ("bar", String "baz: true\nquux: false\n")
> ]))
-}
decodeTextPath :: FromJSON t => FilePath -> IO (Maybe t)
decodeTextPath = fmap toMaybe . decodeTextPathEither
decodeTextPathEither :: FromJSON t => FilePath -> IO (Either String t)
decodeTextPathEither = decodeEitherPath go
where go path = fmap (Right . String) (T.readFile path)
-- extension functions
{- $extension
These functions read in a directory as a YAML object and relies on
the extension of a file to determine whether it is YAML or non-YAML.
For example, if we create the directory
> $ mkdir mydir
> $ cat >mydir/foo.yaml <<EOF
> > [1,2,3]
> > EOF
> $ cat >mydir/bar.text <<EOF
> > baz: true
> > quux: false
> > EOF
then @decodeExtnPath "mydir"@ will return
> Just (Object (fromList [ ("foo.yaml", Array (fromList [ Number 1.0
> , Number 2.0
> , Number 3.0
> ]))
> , ("bar.text", String "baz: true\nquux: false\n")
> ]))
-}
decodeExtnPath :: FromJSON t => FilePath -> IO (Maybe t)
decodeExtnPath = fmap toMaybe . decodeExtnPathEither
decodeExtnPathEither :: FromJSON t => FilePath -> IO (Either String t)
decodeExtnPathEither = decodeEitherPath go
where go p | ".yaml" `isSuffixOf` p
= fmap (either (Left . show) Right) (decodeFileEither p)
| otherwise
= fmap (Right . String) (T.readFile p)
-- implementations
type FileFunc = FilePath -> IO (Either String Value)
parsePath :: FileFunc -> FilePath -> IO (Either String Value)
parsePath withFile path = do
isDir <- doesDirectoryExist path
if | isDir -> parseDir withFile path
| otherwise -> withFile path
parseDir :: FileFunc -> FilePath -> IO (Either String Value)
parseDir withFile path = do
ks <- filterDir (getDirectoryContents path)
vs <- fmap sequence (mapM (parsePath withFile) [path </> k | k <- ks])
case vs of
Left s -> return (Left s)
Right vs' ->
return (Right (Object (fromList [ (pack (takeBaseName k), v)
| k <- ks
| v <- vs'
])))
|
aisamanra/yaml-dir
|
Data/Yaml/Dir.hs
|
bsd-3-clause
| 5,408 | 1 | 21 | 1,902 | 979 | 500 | 479 | 64 | 2 |
{-# LANGUAGE ViewPatterns #-}
module Calcs (forwardBackward, forward, forwardBackwardSim) where
import Common
import Trans
import Emission
import Control.Monad.Reader
import Control.Monad.Random hiding (fromList)
import Control.Monad.State.Strict
import Data.Traversable (traverse)
import Numeric.LinearAlgebra hiding ((|>))
import Data.Function (on)
import Data.List.Stream (findIndex)
import Data.Maybe (fromMaybe)
import qualified Data.Vector as DV
forwardBackward :: ModelInfo -> Dist -> DV.Vector ModelNode -> DV.Vector Dist
forwardBackward info init theData = flip runReader info $ do
forwardProbs <- evalStateT (traverse forward theData) init
ones <- constant 1 `fmap` asks (length . states)
backwardProbs <- evalStateT (traverse backward theData) ones
return . DV.tail $ DV.zipWith reWeight (DV.cons ones forwardProbs) (DV.snoc backwardProbs ones)
forwardBackwardSim :: DV.Vector ModelNode -> ModelSimR (DV.Vector Int)
forwardBackwardSim the_vec = do
init <- asks marginal
forwardProbs <- lift $ evalStateT (traverse forward the_vec) init
ones <- constant 1 `fmap` asks (length . states)
DV.reverse `fmap` evalStateT (traverse backwardSim (DV.reverse (DV.zip the_vec forwardProbs)) ) ones
forward :: ModelNode -> StateT Dist ModelR Dist
forward rn = do
dist <- get
theTMat <- lift $ makeTransMat rn
ep <- lift $ makeEmissionVec rn
put . normalize $ mul (trans theTMat <> dist) ep
get
backward :: ModelNode -> StateT Dist ModelR Dist
backward rn = do
dist <- get
theTMat <- lift $ makeTransMat rn
ep <- lift $ makeEmissionVec rn
put . normalize $ theTMat <> (ep `mul` dist)
get
backwardSim :: (ModelNode, Dist) -> StateT Dist ModelSimR Int
backwardSim (mn, fwd) = do
inDist <- get
ri <- lift $ randIndex (fwd * inDist)
outDist <- lift $ ((!!ri) . toColumns) `fmap` lift (makeTransMat mn)
put outDist
return ri
randIndex :: Vector Double -> ModelSimR Int
randIndex weights = do
rand <- getRandomR (0::Double,1)
rand `seq` return . findDouble rand . normalize $ weights
findDouble :: Double -> Vector Double -> Int
findDouble t v = go 0.0 0
where go t' i | new > t || i == (n-1) = i
| otherwise = go new (i+1)
where new = t' + v@>i
n = dim v
cumSum = scanl1 (+)
|
cglazner/ibd_stitch
|
src/Calcs.hs
|
bsd-3-clause
| 2,449 | 0 | 15 | 617 | 878 | 445 | 433 | 58 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Instrument.Tests.Types
( tests,
)
where
-------------------------------------------------------------------------------
import qualified Data.Map as M
-------------------------------------------------------------------------------
import Instrument.Types
import Path
import Test.HUnit.SafeCopy
import Test.Tasty
import Test.Tasty.HUnit
-------------------------------------------------------------------------------
--TODO: test parse of .serialize files
tests :: TestTree
tests =
testGroup
"Instrument.Types"
[ testCase "Stats SafeCopy" $
testSafeCopy FailMissingFiles $(mkRelFile "test/data/Instrument/Types/Stats.safecopy") stats,
testCase "Payload SafeCopy" $
testSafeCopy FailMissingFiles $(mkRelFile "test/data/Instrument/Types/Payload.safecopy") payload,
testCase "SubmissionPacket SafeCopy" $
testSafeCopy FailMissingFiles $(mkRelFile "test/data/Instrument/Types/SubmissionPacket.safecopy") submissionPacket,
testCase "Aggregated SafeCopy" $
testSafeCopy FailMissingFiles $(mkRelFile "test/data/Instrument/Types/Aggregated.safecopy") aggregated
]
where
stats = Stats 1 2 3 4 5 6 7 8 9 (M.singleton 10 11)
payload = Samples [1.2, 2.3, 4.5]
submissionPacket = SP 3.4 "metric" payload (M.singleton hostDimension "example.org")
aggregated = Aggregated 3.4 "metric" (AggStats stats) mempty
|
Soostone/instrument
|
instrument/test/src/Instrument/Tests/Types.hs
|
bsd-3-clause
| 1,459 | 0 | 11 | 213 | 262 | 140 | 122 | 26 | 1 |
{-# LANGUAGE MultiParamTypeClasses, ScopedTypeVariables, TypeFamilies #-}
{-# OPTIONS_GHC -Wall #-}
----------------------------------------------------------------------
-- |
-- Module : Interface.TV.GtkGL2
-- Copyright : (c) Conal Elliott 2009
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Gtk-based GUIs in the TV (tangible value) framework
--
-- This variation eliminates mdo by having MkI' produce a consumer of
-- refresh actions rather than taking a refresh action as argument.
----------------------------------------------------------------------
module Interface.TV.Gtk.GL2
( module Interface.TV.Gtk2
, renderOut, emptyTexture, textureIsEmpty, textureIn
) where
import Control.Applicative ((<$>))
import Data.IORef
import Graphics.UI.Gtk hiding (Action)
import Graphics.UI.Gtk.OpenGL
import qualified Graphics.Rendering.OpenGL as G
import Graphics.Rendering.OpenGL hiding (Sink,get)
-- For textures
import Data.Bitmap.OpenGL
import Codec.Image.STB
import Interface.TV.Gtk2
mkCanvas :: IO GLDrawingArea
mkCanvas =
glConfigNew [ GLModeRGBA, GLModeDepth , GLModeDouble, GLModeAlpha ]
>>= glDrawingAreaNew
-- | Render output, given a rendering action. Handles all set-up.
-- Intended as an implementation substrate for functional graphics.
renderOut :: Out Action
renderOut = primMkO $
do forget initGL
canvas <- mkCanvas
widgetSetSizeRequest canvas 300 300
-- Initialise some GL setting just before the canvas first gets shown
-- (We can't initialise these things earlier since the GL resources that
-- we are using wouldn't have been set up yet)
-- TODO experiment with moving some of these steps.
forget $ onRealize canvas $ withGLDrawingArea canvas $ const $
do -- setupMatrices -- do elsewhere, e.g., runSurface
depthFunc $= Just Less
drawBuffer $= BackBuffers
clearColor $= Color4 0 0 0.2 1
-- Stash the latest draw action for use in onExpose
drawRef <- newIORef (return ())
let display draw =
-- Draw in context
withGLDrawingArea canvas $ \ glwindow ->
do clear [DepthBuffer, ColorBuffer]
flipY
draw
flipY
-- glWaitVSync
finish
glDrawableSwapBuffers glwindow
writeIORef drawRef draw
-- Sync canvas size with and use draw action
forget $ onExpose canvas $ \_ ->
do (w',h') <- widgetGetSize canvas
let w = fromIntegral w' :: GLsizei
h = fromIntegral h'
maxWH = w `max` h
start s = fromIntegral ((s - maxWH) `div` 2)
viewport $= (Position (start w) (start h), Size maxWH maxWH) -- square
readIORef drawRef >>= display
return True
return (toWidget canvas, display, return ())
flipY :: Action
flipY = scale 1 (-1 :: GLfloat) 1
-- Is there another way to flip Y?
-- | An empty texture. Test with 'textureIsEmpty'
emptyTexture :: TextureObject
emptyTexture = TextureObject bogusTO
bogusTO :: G.GLuint
bogusTO = -1
-- | Is a texture empty?
textureIsEmpty :: TextureObject -> Bool
textureIsEmpty (TextureObject i) = i == bogusTO
loadTexture :: FilePath -> IO (Either String TextureObject)
loadTexture path =
do e <- loadImage path
case e of
Left err -> return (Left err)
Right im -> Right <$> makeSimpleBitmapTexture im
-- Is there a more elegant formulation of loadTex? It's close to
-- being fmap on Either. I can almost get there as follows:
--
-- foo :: FilePath -> IO (Either String (IO TextureObject))
-- foo = (result.fmap.fmap) makeSimpleBitmapTexture loadImage
-- loadImage :: FilePath -> IO (Either String Image)
-- makeSimpleBitmapTexture :: Image -> IO TextureObject
textureIn :: In TextureObject
textureIn = fileMungeIn loadTexture deleteTexture emptyTexture
deleteTexture :: Sink TextureObject
deleteTexture tex | textureIsEmpty tex = return ()
| otherwise =
do -- putStrLn $ "deleteTexture " ++ show tex
deleteObjectNames [tex]
fileMungeIn :: -- Show a => -- for debugging
(FilePath -> IO (Either String a)) -> Sink a -> a -> In a
fileMungeIn munge free start = primMkI $
do w <- fileChooserButtonNew "Select file" FileChooserActionOpen
current <- newIORef start
-- onCurrentFolderChanged w $ putStrLn "onCurrentFolderChanged"
-- onFileActivated w $ putStrLn "onFileActivated"
-- I'm changing the value on preview. TODO: change back if the
-- user cancels.
let install refresh =
forget2 onUpdatePreview w $
do -- putStrLn "onUpdatePreview"
mb <- fileChooserGetFilename w
case mb of
Nothing -> return ()
Just path ->
do e <- munge path
case e of
Left _ -> return ()
-- Left err -> putStrLn $ "fileMungeIn error: " ++ err
Right a -> do readIORef current >>= free
writeIORef current a
-- putStrLn $ "fileMungeIn: new value " ++ show a
refresh
return (toWidget w, readIORef current, return (), install)
|
conal/GtkGLTV
|
src/Interface/TV/Gtk/GL2.hs
|
bsd-3-clause
| 5,456 | 0 | 25 | 1,584 | 988 | 511 | 477 | 88 | 3 |
{-# LANGUAGE CPP
, DeriveDataTypeable
, FlexibleContexts
, GeneralizedNewtypeDeriving
, NoImplicitPrelude
, PatternGuards
, ScopedTypeVariables
, UnicodeSyntax
#-}
module System.FTDI.Internal where
-------------------------------------------------------------------------------
-- Imports
-------------------------------------------------------------------------------
-- from base:
import Control.Applicative ( Applicative, (<$>), Alternative )
import Control.Exception ( Exception, bracket, throwIO )
import Control.Monad ( Functor
, Monad, (>>=), (>>), (=<<), return, fail
, liftM
, MonadPlus
)
import Control.Monad.Fix ( MonadFix )
import Data.Bool ( Bool, otherwise )
#ifdef __HADDOCK__
import Data.Bool ( Bool(False, True) )
#endif
import Data.Bits ( Bits, (.|.)
, setBit, shiftL, shiftR, testBit
)
import Data.Data ( Data )
import Data.Eq ( Eq, (==) )
import Data.Function ( ($), on )
import Data.Int ( Int )
import Data.List ( foldr, head, minimumBy, partition, zip )
import Data.Maybe ( Maybe(Just, Nothing), maybe )
import Data.Ord ( Ord, (<), (>), compare )
import Data.Tuple ( fst, snd )
import Data.Typeable ( Typeable )
import Data.Word ( Word8, Word16 )
import Prelude ( Enum, succ
, Bounded, minBound, maxBound
, Num, (+), (-), Integral, (^)
, Fractional, Real, RealFrac
, Double, Integer
, fromEnum, fromInteger, fromIntegral
, realToFrac, floor, ceiling
, div, error
)
import System.IO ( IO )
import Text.Read ( Read )
import Text.Show ( Show )
-- from base-unicode-symbols:
import Data.Eq.Unicode ( (β‘) )
import Data.Function.Unicode ( (β) )
import Data.Monoid.Unicode ( (β) )
import Prelude.Unicode ( (β
), (Γ·) )
-- from bytestring:
import qualified Data.ByteString as BS ( empty, drop, length
, null, splitAt, unpack
)
import Data.ByteString ( ByteString )
-- from ftdi:
import System.FTDI.Utils ( divRndUp, clamp, genFromEnum, orBits )
-- from safe:
import Safe ( atMay, headMay )
-- from transformers:
import Control.Monad.Trans.State ( StateT, get, put, runStateT )
import Control.Monad.Trans.Class ( MonadTrans, lift )
import Control.Monad.IO.Class ( MonadIO, liftIO )
-- from usb:
import qualified System.USB as USB
-------------------------------------------------------------------------------
-- Exceptions
-------------------------------------------------------------------------------
data FTDIException = InterfaceNotFound deriving (Show, Data, Typeable)
instance Exception FTDIException
-------------------------------------------------------------------------------
-- Request codes and values
-------------------------------------------------------------------------------
type RequestCode = Word8
type RequestValue = Word16
reqReset β· RequestCode
reqSetModemCtrl β· RequestCode
reqSetFlowCtrl β· RequestCode
reqSetBaudRate β· RequestCode
reqSetData β· RequestCode
reqPollModemStatus β· RequestCode
reqSetEventChar β· RequestCode
reqSetErrorChar β· RequestCode
reqSetLatencyTimer β· RequestCode
reqGetLatencyTimer β· RequestCode
reqSetBitMode β· RequestCode
reqReadPins β· RequestCode
reqReadEEPROM β· RequestCode
reqWriteEEPROM β· RequestCode
reqEraseEEPROM β· RequestCode
reqReset = 0x00
reqSetModemCtrl = 0x01
reqSetFlowCtrl = 0x02
reqSetBaudRate = 0x03
reqSetData = 0x04
reqPollModemStatus = 0x05
reqSetEventChar = 0x06
reqSetErrorChar = 0x07
reqSetLatencyTimer = 0x09
reqGetLatencyTimer = 0x0A
reqSetBitMode = 0x0B
reqReadPins = 0x0C
reqReadEEPROM = 0x90
reqWriteEEPROM = 0x91
reqEraseEEPROM = 0x92
valResetSIO β· RequestValue
valPurgeReadBuffer β· RequestValue
valPurgeWriteBuffer β· RequestValue
valResetSIO = 0
valPurgeReadBuffer = 1
valPurgeWriteBuffer = 2
valSetDTRHigh β· RequestValue
valSetDTRLow β· RequestValue
valSetRTSHigh β· RequestValue
valSetRTSLow β· RequestValue
valSetDTRHigh = 0x0101
valSetDTRLow = 0x0100
valSetRTSHigh = 0x0202
valSetRTSLow = 0x0200
-------------------------------------------------------------------------------
-- Defaults
-------------------------------------------------------------------------------
-- |Default USB timeout. The timeout can be set per device handle with
-- the 'setTimeout' function.
defaultTimeout β· Int
defaultTimeout = 5000
-------------------------------------------------------------------------------
-- Devices
-------------------------------------------------------------------------------
-- |A representation of an FTDI device.
data Device = Device
{ devUSB β· USB.Device
, devUSBConf β· USB.ConfigDesc
, devChipType β· ChipType
}
-- |The type of FTDI chip in a 'Device'. The capabilities of a device
-- depend on its chip type.
data ChipType = ChipType_AM
| ChipType_BM
| ChipType_2232C
| ChipType_R
| ChipType_2232H
| ChipType_4232H
deriving (Enum, Eq, Ord, Show, Data, Typeable)
getChipType β· Device β ChipType
getChipType = devChipType
setChipType β· Device β ChipType β Device
setChipType dev ct = dev {devChipType = ct}
-- |Promote a USB device to an FTDI device. You are responsible for
-- supplying the correct USB device and specifying the correct chip
-- type. There is no failsafe way to automatically determine whether a
-- random USB device is an actual FTDI device.
fromUSBDevice β· USB.Device -- ^ USB device
β ChipType
β Device -- ^ FTDI device
fromUSBDevice dev chip =
Device { devUSB = dev
, devUSBConf = head β USB.deviceConfigs $ USB.deviceDesc dev
, devChipType = chip
}
-- |Tries to guess the type of the FTDI chip by looking at the USB
-- device release number of a device's descriptor. Each FTDI chip uses
-- a specific release number to indicate its type.
guessChipType β· USB.DeviceDesc β Maybe ChipType
guessChipType desc = case USB.deviceReleaseNumber desc of
-- Workaround for bug in BM type chips
(0,2,0,0) | USB.deviceSerialNumberStrIx desc β‘ 0
β Just ChipType_BM
| otherwise β Just ChipType_AM
(0,4,0,0) β Just ChipType_BM
(0,5,0,0) β Just ChipType_2232C
(0,6,0,0) β Just ChipType_R
(0,7,0,0) β Just ChipType_2232H
(0,8,0,0) β Just ChipType_4232H
_ β Nothing
-------------------------------------------------------------------------------
-- Interfaces
-------------------------------------------------------------------------------
-- |A device interface. You can imagine an interface as a port or a
-- communication channel. Some devices support communication over
-- multiple interfaces at the same time.
data Interface = Interface_A
| Interface_B
| Interface_C
| Interface_D
deriving (Enum, Eq, Ord, Show, Data, Typeable)
interfaceIndex β· Interface β Word16
interfaceIndex = succ β genFromEnum
interfaceToUSB β· Interface β USB.InterfaceNumber
interfaceToUSB = genFromEnum
interfaceEndPointIn β· Interface β USB.EndpointAddress
interfaceEndPointIn i =
USB.EndpointAddress { USB.endpointNumber = 1 + 2 β
genFromEnum i
, USB.transferDirection = USB.In
}
interfaceEndPointOut β· Interface β USB.EndpointAddress
interfaceEndPointOut i =
USB.EndpointAddress { USB.endpointNumber = 2 + 2 β
genFromEnum i
, USB.transferDirection = USB.Out
}
-------------------------------------------------------------------------------
-- Device Handles
-------------------------------------------------------------------------------
-- |You need a handle in order to communicate with a 'Device'.
data DeviceHandle = DeviceHandle
{ devHndUSB β· USB.DeviceHandle
, devHndDev β· Device
, devHndTimeout β· Int
}
-- |Perform a USB device reset.
resetUSB β· DeviceHandle β IO ()
resetUSB = USB.resetDevice β devHndUSB
-- |Returns the USB timeout associated with a handle.
getTimeout β· DeviceHandle β Int
getTimeout = devHndTimeout
-- |Modifies the USB timeout associated with a handle.
setTimeout β· DeviceHandle β Int β DeviceHandle
setTimeout devHnd timeout = devHnd {devHndTimeout = timeout}
-- |Open a device handle to enable communication. Only use this if you
-- can't use 'withDeviceHandle' for some reason.
openDevice β· Device β IO DeviceHandle
openDevice dev = do
handle β USB.openDevice $ devUSB dev
USB.setConfig handle $ USB.configValue $ devUSBConf dev
return DeviceHandle { devHndUSB = handle
, devHndDev = dev
, devHndTimeout = defaultTimeout
}
-- |Release a device handle.
closeDevice β· DeviceHandle β IO ()
closeDevice = USB.closeDevice β devHndUSB
-- |The recommended way to acquire a handle. Ensures that the handle
-- is released when the monadic computation is completed. Even, or
-- especially, when an exception is thrown.
withDeviceHandle β· Device β (DeviceHandle β IO Ξ±) β IO Ξ±
withDeviceHandle dev = bracket (openDevice dev) closeDevice
-------------------------------------------------------------------------------
-- Interface Handles
-------------------------------------------------------------------------------
data InterfaceHandle = InterfaceHandle
{ ifHndDevHnd β· DeviceHandle
, ifHndInterface β· Interface
, ifHndInEPDesc β· USB.EndpointDesc
, ifHndOutEPDesc β· USB.EndpointDesc
}
getDeviceHandle β· InterfaceHandle β DeviceHandle
getDeviceHandle = ifHndDevHnd
getInterface β· InterfaceHandle β Interface
getInterface = ifHndInterface
openInterface β· DeviceHandle β Interface β IO InterfaceHandle
openInterface devHnd i =
let conf = devUSBConf $ devHndDev devHnd
ifIx = fromEnum i
mIfDesc = headMay =<< USB.configInterfaces conf `atMay` ifIx
mInOutEps = partition ((USB.In β‘) β USB.transferDirection β USB.endpointAddress)
β USB.interfaceEndpoints
<$> mIfDesc
mInEp = headMay β fst =<< mInOutEps
mOutEp = headMay β snd =<< mInOutEps
in maybe (throwIO InterfaceNotFound)
( \ifHnd β do USB.claimInterface (devHndUSB devHnd) (interfaceToUSB i)
return ifHnd
)
$ do inEp β mInEp
outEp β mOutEp
return InterfaceHandle
{ ifHndDevHnd = devHnd
, ifHndInterface = i
, ifHndInEPDesc = inEp
, ifHndOutEPDesc = outEp
}
closeInterface β· InterfaceHandle β IO ()
closeInterface ifHnd =
USB.releaseInterface (devHndUSB $ ifHndDevHnd ifHnd)
(interfaceToUSB $ ifHndInterface ifHnd)
withInterfaceHandle β· DeviceHandle β Interface β (InterfaceHandle β IO Ξ±) β IO Ξ±
withInterfaceHandle h i = bracket (openInterface h i) closeInterface
-------------------------------------------------------------------------------
-- Data transfer
-------------------------------------------------------------------------------
newtype ChunkedReaderT m Ξ± = ChunkedReaderT {unCR β· StateT ByteString m Ξ±}
deriving ( Functor
, Applicative
, Alternative
, Monad
, MonadPlus
, MonadTrans
, MonadIO
, MonadFix
)
{-| Run the ChunkedReaderT given an initial state.
The initial state represents excess bytes carried over from a previous
run. When invoking runChunkedReaderT for the first time you can safely pass the
'BS.empty' bytestring as the initial state.
A contrived example showing how you can manually thread the excess bytes
through subsequent invocations of runChunkedReaderT:
@
example ∷ 'InterfaceHandle' → IO ()
example ifHnd = do
(packets1, rest1) ← runChunkedReaderT ('readData' ifHnd (return 'False') 400) 'BS.empty'
print $ 'BS.concat' packets1
(packets2, rest2) ← runChunkedReaderT ('readData' ifHnd (return 'False') 200) rest1
print $ 'BS.concat' packets2
@
However, it is much easier to let 'ChunkedReaderT's monad instance handle the
plumbing:
@
example ∷ 'InterfaceHandle' → IO ()
example ifHnd =
let reader = do packets1 ← 'readData' ifHnd (return 'False') 400
liftIO $ print $ 'BS.concat' packets1
packets2 ← 'readData' ifHnd (return 'False') 200
liftIO $ print $ 'BS.concat' packets1
in runChunkedReaderT reader 'BS.empty'
@
-}
runChunkedReaderT β· ChunkedReaderT m Ξ± β ByteString β m (Ξ±, ByteString)
runChunkedReaderT = runStateT β unCR
{-| Reads data from the given FTDI interface by performing bulk reads.
This function produces an action in the @ChunkedReaderT@ monad that
will read exactly the requested number of bytes unless it is
explicitly asked to stop early. Executing the @readData@ action will
block until either:
* All data are read
* The given checkStop action returns 'True'
The result value is a list of chunks, represented as
@ByteString@s. This representation was choosen for efficiency reasons.
Data are read in packets. The function may choose to request more than
needed in order to get the highest possible bandwidth. The excess of
bytes is kept as the state of the @ChunkedReaderT@ monad. A subsequent
invocation of @readData@ will first return bytes from the stored state
before requesting more from the device itself. A consequence of this
behaviour is that even when you request 100 bytes the function will
actually request 512 bytes (depending on the packet size) and /block/
until all 512 bytes are read! There is no workaround since requesting
less bytes than the packet size is an error.
USB timeouts will not interrupt @readData@. In case of a timeout
@readData@ will simply resume reading data. A small USB timeout can
degrade performance.
The FTDI latency timer can cause poor performance. If the FTDI chip can't fill
a packet before the latency timer fires it is forced to send an incomplete
packet. This will cause a stream of tiny packets instead of a few large
packets. Performance will suffer horribly, but the request will still be
completed.
If you need to make a lot of small requests then a small latency can actually
improve performance.
Modem status bytes are filtered from the result. Every packet send by the FTDI
chip contains 2 modem status bytes. They are not part of the data and do not
count for the number of bytes read. They will not appear in the result.
Example:
@
-- Read 100 data bytes from ifHnd
(packets, rest) ← 'runChunkedReaderT' ('readData' ifHnd (return 'False') 100) 'BS.empty'
@
-}
readData β· β m. MonadIO m
β InterfaceHandle
β m Bool -- ^ Check stop action
β Int -- ^ Number of bytes to read
β ChunkedReaderT m [ByteString]
readData ifHnd checkStop numBytes = ChunkedReaderT $
do prevRest β get
let readNumBytes = numBytes - BS.length prevRest
if readNumBytes > 0
then do chunks β readLoop readNumBytes
return $ if BS.null prevRest
then chunks
else prevRest : chunks
else let (bs, newRest) = BS.splitAt numBytes prevRest
in put newRest >> return [bs]
where
readLoop β· Int β StateT ByteString m [ByteString]
readLoop readNumBytes = do
-- Amount of bytes we need to request in order to get atleast
-- 'readNumBytes' bytes of data.
let reqSize = packetSize β
reqPackets
reqPackets = readNumBytes `divRndUp` packetDataSize
-- Timeout is ignored; the number of bytes that was read contains
-- enough information.
(bytes, _) β liftIO $ readBulk ifHnd reqSize
let receivedDataBytes = receivedBytes - receivedHeaderBytes
receivedBytes = BS.length bytes
receivedHeaderBytes = packetHeaderSize β
receivedPackets
receivedPackets = receivedBytes `divRndUp` packetSize
-- The reason for not actually getting the requested amount of bytes
-- could be either a USB timeout or the FTDI latency timer firing.
--
-- In case of a USB timeout:
-- β (n : Nat). receivedBytes β‘ n β
packetSize
--
-- In case of FTDI latency timer:
-- receivedBytes < packetSize
if receivedDataBytes < readNumBytes
then let xs = splitPackets bytes
in lift checkStop >>= \stop β
if stop
then put BS.empty >> return xs
else liftM (xs β)
(readLoop $ readNumBytes - receivedDataBytes)
else -- We might have received too much data, since we can only
-- request multiples of 'packetSize' bytes. Split the byte
-- string at such an index that the first part contains
-- readNumBytes of data. The rest is kept for future usage.
let (bs, newRest) = BS.splitAt (splitIndex readNumBytes) bytes
in put newRest >> return (splitPackets bs)
splitIndex n = p β
packetSize + packetHeaderSize
+ (n - p β
packetDataSize)
where p = n `div` packetDataSize
packetDataSize = packetSize - packetHeaderSize
packetHeaderSize = 2
packetSize = USB.maxPacketSize
β USB.endpointMaxPacketSize
$ ifHndInEPDesc ifHnd
-- |Split a stream of bytes into packets. The first 2 bytes of each
-- packet are the modem status bytes and are dropped.
splitPackets xs | BS.null xs = []
| otherwise = case BS.splitAt packetSize xs of
(a, b) β BS.drop 2 a : splitPackets b
-- |Perform a bulk read.
--
-- Returns the bytes that where read (in the form of a 'ByteString') and a flag
-- which indicates whether a timeout occured during the request.
readBulk β· InterfaceHandle
β Int -- ^Number of bytes to read
β IO (ByteString, Bool)
readBulk ifHnd numBytes =
USB.readBulk (devHndUSB $ ifHndDevHnd ifHnd)
(interfaceEndPointIn $ ifHndInterface ifHnd)
(devHndTimeout $ ifHndDevHnd ifHnd)
numBytes
-- |Perform a bulk write.
--
-- Returns the number of bytes that where written and a flag which indicates
-- whether a timeout occured during the request.
writeBulk β· InterfaceHandle
β ByteString -- ^Data to be written
β IO (Int, Bool)
writeBulk ifHnd bs =
USB.writeBulk (devHndUSB $ ifHndDevHnd ifHnd)
(interfaceEndPointOut $ ifHndInterface ifHnd)
(devHndTimeout $ ifHndDevHnd ifHnd)
bs
-------------------------------------------------------------------------------
-- Control Requests
-------------------------------------------------------------------------------
-- |The type of a USB control request.
type USBControl Ξ± = USB.DeviceHandle
β USB.RequestType
β USB.Recipient
β RequestCode
β RequestValue
β Word16
β USB.Timeout
β Ξ±
-- |Generic FTDI control request with explicit index
genControl β· USBControl Ξ±
β Word16 -- ^Index
β InterfaceHandle
β RequestCode
β RequestValue
β Ξ±
genControl usbCtrl index ifHnd request value =
usbCtrl usbHnd
USB.Vendor
USB.ToDevice
request
value
(index .|. (interfaceIndex $ ifHndInterface ifHnd))
(devHndTimeout devHnd)
where devHnd = ifHndDevHnd ifHnd
usbHnd = devHndUSB devHnd
control β· InterfaceHandle β RequestCode β Word16 β IO ()
control = genControl USB.control 0
readControl β· InterfaceHandle β RequestCode β Word16 β USB.Size β IO (ByteString, Bool)
readControl = genControl USB.readControl 0
writeControl β· InterfaceHandle β RequestCode β Word16 β ByteString β IO (USB.Size, Bool)
writeControl = genControl USB.writeControl 0
-------------------------------------------------------------------------------
-- |Reset the FTDI device.
reset β· InterfaceHandle β IO ()
reset ifHnd = control ifHnd reqReset valResetSIO
-- |Clear the on-chip read buffer.
purgeReadBuffer β· InterfaceHandle β IO ()
purgeReadBuffer ifHnd = control ifHnd reqReset valPurgeReadBuffer
-- |Clear the on-chip write buffer.
purgeWriteBuffer β· InterfaceHandle β IO ()
purgeWriteBuffer ifHnd = control ifHnd reqReset valPurgeWriteBuffer
-------------------------------------------------------------------------------
-- |Returns the current value of the FTDI latency timer.
getLatencyTimer β· InterfaceHandle β IO Word8
getLatencyTimer ifHnd = do
(bs, _) β readControl ifHnd reqGetLatencyTimer 0 1
case BS.unpack bs of
[b] β return b
_ β error "System.FTDI.getLatencyTimer: failed"
-- |Set the FTDI latency timer. The latency is the amount of
-- milliseconds after which the FTDI chip will send a packet
-- regardless of the number of bytes in the packet.
setLatencyTimer β· InterfaceHandle β Word8 β IO ()
setLatencyTimer ifHnd latency = control ifHnd reqSetLatencyTimer
$ fromIntegral latency
-- |MPSSE bitbang modes
data BitMode = -- |Switch off bitbang mode, back to regular serial/FIFO.
BitMode_Reset
-- |Classical asynchronous bitbang mode, introduced with B-type
-- chips.
| BitMode_BitBang
-- |Multi-Protocol Synchronous Serial Engine, available on 2232x
-- chips.
| BitMode_MPSSE
-- |Synchronous Bit-Bang Mode, available on 2232x and R-type
-- chips.
| BitMode_SyncBitBang
-- |MCU Host Bus Emulation Mode, available on 2232x
-- chips. CPU-style fifo mode gets set via EEPROM.
| BitMode_MCU
-- |Fast Opto-Isolated Serial Interface Mode, available on 2232x
-- chips.
| BitMode_Opto
-- |Bit-Bang on CBus pins of R-type chips, configure in EEPROM
-- before use.
| BitMode_CBus
-- |Single Channel Synchronous FIFO Mode, available on 2232H
-- chips.
| BitMode_SyncFIFO
deriving (Eq, Ord, Show, Data, Typeable)
marshalBitMode β· BitMode β Word8
marshalBitMode bm = case bm of
BitMode_Reset β 0x00
BitMode_BitBang β 0x01
BitMode_MPSSE β 0x02
BitMode_SyncBitBang β 0x04
BitMode_MCU β 0x08
BitMode_Opto β 0x10
BitMode_CBus β 0x20
BitMode_SyncFIFO β 0x40
-- |The bitmode controls the method of communication.
setBitMode β· InterfaceHandle β Word8 β BitMode β IO ()
setBitMode ifHnd bitMask bitMode = control ifHnd reqSetBitMode value
where bitMask' = fromIntegral bitMask
bitMode' = fromIntegral $ marshalBitMode bitMode
value = bitMask' .|. shiftL bitMode' 8
-- |Sets the baud rate. Internally the baud rate is represented as a
-- fraction. The maximum baudrate is the numerator and a special
-- /divisor/ is used as the denominator. The maximum baud rate is
-- given by the 'BaudRate' instance for 'Bounded'. The divisor
-- consists of an integral part and a fractional part. Both parts are
-- limited in range. As a result not all baud rates can be accurately
-- represented. This function returns the nearest representable baud
-- rate relative to the requested baud rate. According to FTDI
-- documentation the maximum allowed error is 3%. The nearest
-- representable baud rate can be calculated with the
-- 'nearestBaudRate' function.
setBaudRate β· RealFrac Ξ± β InterfaceHandle β BaudRate Ξ± β IO (BaudRate Ξ±)
setBaudRate ifHnd baudRate =
do genControl USB.control ix ifHnd reqSetBaudRate val
return b
where
(val, ix) = encodeBaudRateDivisors chip d s
(d, s, b) = calcBaudRateDivisors chip baudRate
chip = devChipType $ devHndDev $ ifHndDevHnd ifHnd
data Parity = -- |The parity bit is set to one if the number of ones in a given
-- set of bits is even (making the total number of ones, including
-- the parity bit, odd).
Parity_Odd
-- |The parity bit is set to one if the number of ones in a given
-- set of bits is odd (making the total number of ones, including
-- the parity bit, even).
| Parity_Even
| Parity_Mark -- ^The parity bit is always 1.
| Parity_Space -- ^The parity bit is always 0.
deriving (Enum, Eq, Ord, Show, Data, Typeable)
data BitDataFormat = Bits_7
| Bits_8
data StopBits = StopBit_1
| StopBit_15
| StopBit_2
deriving (Enum)
-- |Set RS232 line characteristics
setLineProperty β· InterfaceHandle
β BitDataFormat -- ^Number of bits
β StopBits -- ^Number of stop bits
β Maybe Parity -- ^Optional parity mode
β Bool -- ^Break
β IO ()
setLineProperty ifHnd bitDataFormat stopBits parity break' =
control ifHnd
reqSetData
$ orBits [ case bitDataFormat of
Bits_7 β 7
Bits_8 β 8
, maybe 0 (\p β (1 + genFromEnum p) `shiftL` 8) parity
, genFromEnum stopBits `shiftL` 11
, genFromEnum break' `shiftL` 14
]
-------------------------------------------------------------------------------
-- Modem status
-------------------------------------------------------------------------------
-- |Modem status information. The modem status is send as a header for
-- each read access. In the absence of data the FTDI chip will
-- generate the status every 40 ms.
--
-- The modem status can be explicitely requested with the
-- 'pollModemStatus' function.
data ModemStatus = ModemStatus
{ -- |Clear to send (CTS)
msClearToSend β· Bool
-- |Data set ready (DTS)
, msDataSetReady β· Bool
-- |Ring indicator (RI)
, msRingIndicator β· Bool
-- |Receive line signal detect (RLSD)
, msReceiveLineSignalDetect β· Bool
-- | Data ready (DR)
, msDataReady β· Bool
-- |Overrun error (OE)
, msOverrunError β· Bool
-- |Parity error (PE)
, msParityError β· Bool
-- |Framing error (FE)
, msFramingError β· Bool
-- |Break interrupt (BI)
, msBreakInterrupt β· Bool
-- |Transmitter holding register (THRE)
, msTransmitterHoldingRegister β· Bool
-- |Transmitter empty (TEMT)
, msTransmitterEmpty β· Bool
-- |Error in RCVR FIFO
, msErrorInReceiverFIFO β· Bool
} deriving (Eq, Ord, Show, Data, Typeable)
marshalModemStatus β· ModemStatus β (Word8, Word8)
marshalModemStatus ms = (a, b)
where
a = mkByte $ zip [4..]
[ msClearToSend
, msDataSetReady
, msRingIndicator
, msReceiveLineSignalDetect
]
b = mkByte $ zip [0..]
[ msDataReady
, msOverrunError
, msParityError
, msFramingError
, msBreakInterrupt
, msTransmitterHoldingRegister
, msTransmitterEmpty
, msErrorInReceiverFIFO
]
mkByte β· [(Int, ModemStatus β Bool)] β Word8
mkByte ts = foldr (\(n, f) x β if f ms then setBit x n else x)
0
ts
unmarshalModemStatus β· Word8 β Word8 β ModemStatus
unmarshalModemStatus a b =
ModemStatus { msClearToSend = testBit a 4
, msDataSetReady = testBit a 5
, msRingIndicator = testBit a 6
, msReceiveLineSignalDetect = testBit a 7
, msDataReady = testBit b 0
, msOverrunError = testBit b 1
, msParityError = testBit b 2
, msFramingError = testBit b 3
, msBreakInterrupt = testBit b 4
, msTransmitterHoldingRegister = testBit b 5
, msTransmitterEmpty = testBit b 6
, msErrorInReceiverFIFO = testBit b 7
}
-- |Manually request the modem status.
pollModemStatus β· InterfaceHandle β IO ModemStatus
pollModemStatus ifHnd = do
(bs, _) β readControl ifHnd reqPollModemStatus 0 2
case BS.unpack bs of
[x,y] β return $ unmarshalModemStatus x y
_ β error "System.FTDI.pollModemStatus: failed"
-------------------------------------------------------------------------------
-- Flow control
-------------------------------------------------------------------------------
data FlowCtrl = RTS_CTS -- ^Request-To-Send \/ Clear-To-Send
| DTR_DSR -- ^Data-Terminal-Ready \/ Data-Set-Ready
| XOnXOff -- ^Transmitter on \/ Transmitter off
marshalFlowControl β· FlowCtrl β Word16
marshalFlowControl f = case f of
RTS_CTS β 0x0100
DTR_DSR β 0x0200
XOnXOff β 0x0400
-- |Set the flow control for the FTDI chip. Use 'Nothing' to disable flow
-- control.
setFlowControl β· InterfaceHandle β Maybe FlowCtrl β IO ()
setFlowControl ifHnd mFC = genControl USB.control
(maybe 0 marshalFlowControl mFC)
ifHnd
reqSetFlowCtrl
0
-- |Set DTR line.
setDTR β· InterfaceHandle β Bool β IO ()
setDTR ifHnd b = control ifHnd reqSetModemCtrl
$ if b then valSetDTRHigh else valSetDTRLow
-- |Set RTS line.
setRTS β· InterfaceHandle β Bool β IO ()
setRTS ifHnd b = control ifHnd reqSetModemCtrl
$ if b then valSetRTSHigh else valSetRTSLow
genSetCharacter β· RequestCode β InterfaceHandle β Maybe Word8 β IO ()
genSetCharacter req ifHnd mEC =
control ifHnd req $ maybe 0 (\c β setBit (fromIntegral c) 8) mEC
-- |Set the special event character. Use 'Nothing' to disable the event
-- character.
setEventCharacter β· InterfaceHandle β Maybe Word8 β IO ()
setEventCharacter = genSetCharacter reqSetEventChar
-- |Set the error character. Use 'Nothing' to disable the error character.
setErrorCharacter β· InterfaceHandle β Maybe Word8 β IO ()
setErrorCharacter = genSetCharacter reqSetErrorChar
-------------------------------------------------------------------------------
-- Baud rate
-------------------------------------------------------------------------------
newtype BRDiv Ξ± = BRDiv {unBRDiv β· Ξ±}
deriving ( Eq, Ord, Show, Read, Enum, Num, Integral
, Real, Fractional, RealFrac
)
instance Num Ξ± β Bounded (BRDiv Ξ±) where
minBound = 0
maxBound = 2 ^ (14 β· Int) - 1
newtype BRSubDiv Ξ± = BRSubDiv {unBRSubDiv β· Ξ±}
deriving ( Eq, Ord, Show, Read, Enum, Num, Integral
, Real, Fractional, RealFrac
)
instance Num Ξ± β Bounded (BRSubDiv Ξ±) where
minBound = 0
maxBound = 7
-- |Representation of a baud rate. The most interesting part is the
-- instance for 'Bounded'.
newtype BaudRate Ξ± = BaudRate {unBaudRate β· Ξ±}
deriving ( Eq, Ord, Show, Read, Enum, Num, Integral
, Real, Fractional, RealFrac
)
instance Num Ξ± β Bounded (BaudRate Ξ±) where
-- Minimum baud rate is the maximum baudrate divided by the
-- largest possible divider.
minBound = fromIntegral
$ (ceiling β· BaudRate Double β BaudRate Integer)
$ calcBaudRate maxBound maxBound
maxBound = BaudRate 3000000
-- http://www.ftdichip.com/Documents/AppNotes/AN232B-05_BaudRates.pdf
encodeBaudRateDivisors β· ChipType β BRDiv Int β BRSubDiv Int β (Word16, Word16)
encodeBaudRateDivisors chip d s = (v, i)
where
v = fromIntegral d .|. shiftL s' 14
i | ChipType_2232C β chip = shiftL (shiftR s' 2) 8
| otherwise = shiftR s' 2
s' = fromIntegral $ encodeSubDiv s β· Word16
encodeSubDiv β· BRSubDiv Int β Int
encodeSubDiv n =
case n of
0 β 0 -- 000 ==> 0/8 = 0
4 β 1 -- 001 ==> 4/8 = 0.5
2 β 2 -- 010 ==> 2/8 = 0.25
1 β 3 -- 011 ==> 1/8 = 0.125
3 β 4 -- 100 ==> 3/8 = 0.375
5 β 5 -- 101 ==> 5/8 = 0.625
6 β 6 -- 110 ==> 6/8 = 0.75
7 β 7 -- 111 ==> 7/8 = 0.875
_ β error "Illegal subdivisor"
-- |Calculates the nearest representable baud rate.
nearestBaudRate β· RealFrac Ξ± β ChipType β BaudRate Ξ± β BaudRate Ξ±
nearestBaudRate chip baudRate = b
where (_, _, b) = calcBaudRateDivisors chip baudRate
-- |Finds the divisors that most closely represent the requested baud rate.
calcBaudRateDivisors β· β Ξ±. RealFrac Ξ±
β ChipType
β BaudRate Ξ±
β (BRDiv Int, BRSubDiv Int, BaudRate Ξ±)
calcBaudRateDivisors _ 3000000 = (0, 0, 0)
calcBaudRateDivisors _ 2000000 = (1, 0, 0)
calcBaudRateDivisors chip baudRate =
minimumBy (compare `on` (\(_,_,x) β x))
[ (d, s, b')
| s β chipSubDivisors chip
, let s' = fromIntegral s Γ· 8
d = divisor baudRate s'
-- Baud rate calculated from found divisors.
b' = calcBaudRate d s'
]
where
-- |Calculates the divisor from a baud rate and a subdivisor.
divisor β· Integral Ξ² β BaudRate Ξ± β BRSubDiv Ξ± β BRDiv Ξ²
divisor br s = clamp $ floor $ (maxBound - br β
s') Γ· br
where s' = BaudRate $ unBRSubDiv s
chipSubDivisors β· ChipType β [BRSubDiv Int]
chipSubDivisors ChipType_AM = [0, 1, 2, 4]
chipSubDivisors _ = [0..7]
-- |Calculates the baud rate from a divisor and a subdivisor.
calcBaudRate β· Fractional Ξ± β BRDiv Int β BRSubDiv Ξ± β BaudRate Ξ±
calcBaudRate 0 0 = maxBound
calcBaudRate 1 0 = 2000000
calcBaudRate d s = maxBound Γ· BaudRate (realToFrac d + unBRSubDiv s)
|
roelvandijk/ftdi
|
System/FTDI/Internal.hs
|
bsd-3-clause
| 36,474 | 0 | 18 | 10,855 | 5,882 | 3,275 | 2,607 | 529 | 9 |
--
-- >>> Hub.System <<<
--
-- This module contains all of the O/S-specific utilities. It should currently
-- work for Posix systems. Getting a Windows hub port should be a matter of
-- porting this module.
--
-- (c) 2011-2012 Chris Dornan
module Hub.System
( systemMachine
, homeDir
, tmpFile
, setEnv
, fileExists
, fileDirExists
, removeR
, removeRF
, cpFileDir
, mvFileDir
, symLink
, inc
, tidyDir
, ExecEnv(..)
, RedirectStream(..)
, exec
, readAFile
, writeAFile
, lockFileDir
) where
import System.IO
import System.Exit
import Control.Monad
import qualified Control.Exception as E
import System.Directory
import System.Posix.Unistd
import System.Posix.Env
import System.Posix.Files
import System.Posix.Process
import System.Posix.IO
import Text.Printf
import qualified Data.ByteString.UTF8 as U
import qualified Data.ByteString as B
import qualified Data.Map as Map
import Data.Char
import System.Process
import Hub.Oops
dev_null :: FilePath
dev_null = "/dev/null"
systemMachine :: IO (String,String)
systemMachine = f `fmap` getSystemID
where
f si = (map toLower $ systemName si, machine si)
homeDir :: IO (Maybe FilePath)
homeDir = getEnv "HOME"
tmpFile :: FilePath -> IO FilePath
tmpFile fn =
do pid <- getProcessID
return $ printf "/tmp/hub-%d-%s" (fromIntegral pid :: Int) fn
fileExists :: FilePath -> IO Bool
fileExists fp = flip E.catch (hdl_ioe False) $
do st <- getFileStatus fp
return $ isRegularFile st
fileDirExists :: FilePath -> IO Bool
fileDirExists fp = flip E.catch (hdl_ioe False) $
do st <- getFileStatus fp
return $ isRegularFile st || isDirectory st
removeR :: FilePath -> IO ()
removeR fp =
do ec <- rawSystem "rm" ["-r",fp]
case ec of
ExitSuccess -> return ()
ExitFailure n -> oops PrgO $
printf "rm failure (return code=%d)" n
removeRF :: FilePath -> IO ()
removeRF fp =
do ec <- rawSystem "rm" ["-rf",fp]
case ec of
ExitSuccess -> return ()
ExitFailure n -> oops PrgO $
printf "rm failure (return code=%d)" n
cpFileDir :: FilePath -> FilePath -> IO ()
cpFileDir fp fp' =
do ec <- rawSystem "cp" ["-a",fp,fp']
case ec of
ExitSuccess -> return ()
ExitFailure n -> oops PrgO $
printf "cp failure (return code=%d)" n
mvFileDir :: FilePath -> FilePath -> IO ()
mvFileDir fp fp' =
do ec <- rawSystem "mv" [fp,fp']
case ec of
ExitSuccess -> return ()
ExitFailure n -> oops PrgO $
printf "mv failure (return code=%d)" n
symLink :: FilePath -> FilePath -> IO ()
symLink = createSymbolicLink
inc :: FilePath -> IO Int
inc fp =
do fd <- openFd fp ReadWrite (Just stdFileMode) defaultFileFlags
-- putStrLn "acquiring lock"
waitToSetLock fd (WriteLock,AbsoluteSeek,0,0)
--putStrLn "lock acquired"
i <- rd_i fd
_ <- fdSeek fd AbsoluteSeek 0
_ <- fdWrite fd $ show $ i+1
closeFd fd
return i
where
rd_i fd =
do (s,_) <- E.catch (fdRead fd 64) (hdl_ioe ("",0))
return $ maybe 0 id $ readMB s
tidyDir :: FilePath -> IO ()
tidyDir dp = flip E.catch (hdl_ioe ()) $
do e <- all dots `fmap` getDirectoryContents dp
when e $ removeDirectory dp
where
dots "." = True
dots ".." = True
dots _ = False
readMB :: Read a => String -> Maybe a
readMB str =
case [ x | (x,t)<-reads str, ("","")<-lex t ] of
[x] -> Just x
_ -> Nothing
lockFileDir :: Bool -> Bool -> FilePath -> IO ()
lockFileDir dir lck fp = setFileMode fp m
where
m = case lck of
True ->
case dir of
True -> u [r ,x]
False -> r
False ->
case dir of
True -> u [r,w,x]
False -> u [r,w ]
r = u [ownerReadMode ,groupReadMode ,otherReadMode ]
w = u [ownerWriteMode ]
x = u [ownerExecuteMode,groupExecuteMode,otherExecuteMode]
u = foldr unionFileModes nullFileMode
hdl_ioe :: a -> IOError -> IO a
hdl_ioe x _ = return x
data ExecEnv = EE
{ redirctOutEE :: RedirectStream
, redirctErrEE :: RedirectStream
, extendEnvtEE :: [(String,String)]
} deriving (Show)
data RedirectStream
= InheritRS
| DiscardRS
| RedirctRS FilePath
deriving (Show)
exec :: ExecEnv -> FilePath -> [String] -> IO ExitCode
exec ee pr as =
do so <- get_ss $ redirctOutEE ee
se <- get_ss $ redirctErrEE ee
ev <- get_ev $ extendEnvtEE ee
let cp = (proc pr as) { std_out = so, std_err = se, env=ev }
(_,_,_,ph) <- createProcess cp
ex <- waitForProcess ph
clse so
clse se
return ex
where
get_ss InheritRS = return Inherit
get_ss DiscardRS = get_ss (RedirctRS dev_null)
get_ss (RedirctRS fp) = UseHandle `fmap` openFile fp WriteMode
clse (UseHandle h) = hClose h
clse _ = return ()
get_ev [] = return Nothing
get_ev bs =
do bs0 <- getEnvironment
let st = Map.fromList bs
f (nm,_) = not $ Map.member nm st
--putStrLn $ printf "---\n%s\n---\n\n" $ show (bs ++ filter f bs0)
return $ Just $ bs ++ filter f bs0
readAFile :: FilePath -> IO String
readAFile fp = U.toString `fmap` B.readFile fp
writeAFile :: FilePath -> String -> IO ()
writeAFile fp = B.writeFile fp . U.fromString
|
Lainepress/hub-src
|
Hub/System.hs
|
bsd-3-clause
| 6,121 | 0 | 14 | 2,231 | 1,851 | 947 | 904 | 163 | 5 |
{-# LANGUAGE OverloadedStrings #-}
module ElementaryStreamDescriptorSpec (spec) where
import Data.ByteString.IsoBaseFileFormat.ReExports
import Data.ByteString.IsoBaseFileFormat.Util.BoxContent
import Data.ByteString.Mp4.Boxes.AudioSpecificConfig
import Data.ByteString.Mp4.Boxes.DecoderConfigDescriptor
import Data.ByteString.Mp4.Boxes.DecoderSpecificInfo
import Data.ByteString.Mp4.Boxes.ElementaryStreamDescriptor
import Test.Hspec
import Util
spec :: Spec
spec = do
#ifndef COMPLEXTESTS
return ()
#else
describe "EsdBox" $ do
let eb = esdBox (Proxy @TestEsDescriptor) False 0 0 0
it "has the correct size" $
boxSize eb `shouldBe` 39
it "generates the expected bits" $
printBuilder (boxBuilder eb)
`shouldBe` "<< 00 00 00 27 65 73 64 73 00 00 00 00 03 19 00 01 00 04 11 40 15 00 00 00 00 00 00 00 00 00 00 00 05 02 11 98 06 01 02 >>"
type TestEsDescriptor =
ESDescriptorMp4File
(StaticFieldValue "esId" 1)
TestConfigDescriptor
type TestConfigDescriptor =
DecoderConfigDescriptor
'AudioIso14496_3
'AudioStream
'[AudioConfigAacMinimal
'AacLc
DefaultGASpecificConfig
(SetEnum "samplingFreq" SamplingFreq 'SF48000)
(SetEnum "channelConfig" ChannelConfig 'SinglePair)]
'[]
#endif
|
sheyll/isobmff-builder
|
spec/ElementaryStreamDescriptorSpec.hs
|
bsd-3-clause
| 1,258 | 0 | 8 | 217 | 86 | 59 | 27 | 13 | 1 |
module Atom where
import CheckList
import Control.Lens
import Data.List
import Data.Maybe
import Data.Text.Lazy.Lens (utf8)
import Network.URL
import Network.Wreq
import Text.Atom.Feed (feedEntries, txtToString, entryTitle, linkHref, entryLinks)
import Text.Feed.Import (parseFeedSource)
import Text.Feed.Types (Feed (AtomFeed))
generateCheckList :: String -> IO CheckList
generateCheckList atom =
do articles <- articlesFromAtom atom
let Just url = importURL atom
Absolute host = url_type url
root = exportHost host
relativeUrl = fromJust . stripPrefix root
atomPage = Page { url = relativeUrl atom, name = "Atom file", lookupName = False}
pages = map (\(name, link) -> Page { url = relativeUrl link, name = name, lookupName = True}) articles
return (CheckList { root = root, pages = atomPage : pages})
articlesFromAtom :: String -> IO [(String, String)]
articlesFromAtom atom = do r <- get atom
let Just (AtomFeed feed) = parseFeedSource (r ^. responseBody . utf8)
entries = feedEntries feed
return (map extractEntry entries)
where extractEntry = do name <- txtToString . entryTitle
link <- linkHref . head . entryLinks
return (name, link)
|
madjar/permalink-checker
|
src/Atom.hs
|
bsd-3-clause
| 1,342 | 0 | 15 | 365 | 412 | 222 | 190 | -1 | -1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
-----------------------------------------------------------------
-- Auto-generated by regenClassifiers
--
-- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
-- @generated
-----------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Ranking.Classifiers.CS_XX (classifiers) where
import Data.String
import Prelude
import qualified Data.HashMap.Strict as HashMap
import Duckling.Ranking.Types
classifiers :: Classifiers
classifiers = HashMap.fromList []
|
facebookincubator/duckling
|
Duckling/Ranking/Classifiers/CS_XX.hs
|
bsd-3-clause
| 828 | 0 | 6 | 105 | 66 | 47 | 19 | 8 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
------------------------------------------------------------------------------
-- |
-- Module : Keeper.CheckAuthorizedKeys
-- License : BSD-style
-- Maintainer : Nicolas DI PRIMA <[email protected]>
-- Stability : experimental
-- Portability : unix
------------------------------------------------------------------------------
import System.Keeper
import System.Keeper.Backend.Dummy
------------------------------------------------------------------------------
main = defaultMain getFlatDB
|
NicolasDP/keeper
|
Keeper/CheckAuthorizedKeys.hs
|
bsd-3-clause
| 580 | 1 | 5 | 60 | 35 | 23 | 12 | 5 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.ByteString.Parser
-- Copyright : Lennart Kolmodin, George Giorgidze
-- License : BSD3
--
-- Maintainer : George Giorgidze <http://cs.nott.ac.uk/~ggg/>
-- Stability : experimental
-- Portability : Portable
--
-- A monad for efficiently building structures from
-- encoded lazy ByteStrings.
--
-----------------------------------------------------------------------------
module Codec.ByteString.Parser (
-- * The Parser type
Parser
, runParser
, runParserState
-- * Parsing
, choice
, expect
, skip
, lookAhead
, lookAheadM
, lookAheadE
-- * Utility
, bytesRead
, getBytes
, remaining
, isEmpty
-- * Parsing particular types
, satisfy
, getString
, getStringNul
, string
, getWord8
, getInt8
, word8
, int8
-- ** ByteStrings
, getByteString
, getLazyByteString
, getLazyByteStringNul
, getRemainingLazyByteString
-- ** Big-endian reads
, getWord16be
, word16be
, getWord24be
, word24be
, getWord32be
, word32be
, getWord64be
, word64be
, getInt16be
, int16be
, getInt32be
, int32be
, getInt64be
, int64be
-- ** Little-endian reads
, getWord16le
, word16le
, getWord24le
, word24le
, getWord32le
, word32le
, getWord64le
, word64le
, getInt16le
, int16le
, getInt32le
, int32le
, getInt64le
, int64le
-- ** Host-endian, unaligned reads
, getWordHost
, wordHost
, getWord16host
, word16host
, getWord32host
, word32host
, getWord64host
, word64host
-- Variable length reads
, getVarLenBe
, varLenBe
, getVarLenLe
, varLenLe
) where
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Internal as B
import qualified Data.ByteString.Lazy.Internal as L
import Foreign.Storable (Storable, peek, sizeOf)
import Foreign.Ptr (plusPtr, castPtr)
import Foreign.ForeignPtr (withForeignPtr)
import Control.Monad.ST (runST)
import Control.Monad.ST.Unsafe (unsafeInterleaveST)
import Control.Monad
import Control.Applicative
import Data.STRef
import Data.Word
import Data.Int
import Data.Bits
import Data.Maybe
-- | The parse state
data S = S {-# UNPACK #-} !B.ByteString -- current chunk
L.ByteString -- the rest of the input
{-# UNPACK #-} !Int64 -- bytes read
-- | The Get monad is just a State monad carrying around the input ByteString
newtype Parser a = Parser { unParser :: S -> Either String (a, S) }
instance Functor Parser where
fmap f m = Parser $ \s -> case unParser m s of
Left e -> Left e
Right (a, s') -> Right (f a, s')
instance Monad Parser where
return a = Parser (\s -> Right (a, s))
m >>= k = Parser $ \s -> case (unParser m) s of
Left e -> Left e
Right (a, s') -> (unParser (k a)) s'
fail err = Parser $ \(S _ _ bytes) ->
Left (err ++ ". Failed reading at byte position " ++ show bytes)
instance MonadPlus Parser where
mzero = Parser $ \_ -> Left []
mplus p1 p2 = Parser $ \s -> case (unParser p1 s) of
Left e1 -> case (unParser p2 s) of
Left e2 -> Left (e1 ++ "\n" ++ e2)
ok -> ok
ok -> ok
instance Applicative Parser where
pure = return
(<*>) = ap
instance Alternative Parser where
empty = mzero
(<|>) = mplus
------------------------------------------------------------------------
get :: Parser S
get = Parser $ \s -> Right (s, s)
put :: S -> Parser ()
put s = Parser $ \_ -> Right ((), s)
------------------------------------------------------------------------
initState :: L.ByteString -> S
initState xs = mkState xs 0
mkState :: L.ByteString -> Int64 -> S
mkState l = case l of
L.Empty -> S B.empty L.empty
L.Chunk x xs -> S x xs
-- | Run the Get monad applies a 'get'-based parser on the input ByteString
runParser :: Parser a -> L.ByteString -> Either String a
runParser m str = case unParser m (initState str) of
Left e -> Left e
Right (a, _) -> Right a
-- | Run the Get monad applies a 'get'-based parser on the input
-- ByteString. Additional to the result of get it returns the number of
-- consumed bytes and the rest of the input.
runParserState :: Parser a -> L.ByteString -> Int64 -> Either String (a, L.ByteString, Int64)
runParserState m str off =
case unParser m (mkState str off) of
Left e -> Left e
Right (a, ~(S s ss newOff)) -> Right (a, s `bsJoin` ss, newOff)
------------------------------------------------------------------------
choice :: [Parser a] -> Parser a
choice = foldl (<|>) mzero
-- | Skip ahead @n@ bytes. Fails if fewer than @n@ bytes are available.
skip :: Word64 -> Parser ()
skip n = readN (fromIntegral n) (const ())
-- | Run @ga@, but return without consuming its input.
-- Fails if @ga@ fails.
lookAhead :: Parser a -> Parser a
lookAhead ga = do
s <- get
a <- ga
put s
return a
-- | Like 'lookAhead', but consume the input if @gma@ returns 'Just _'.
-- Fails if @gma@ fails.
lookAheadM :: Parser (Maybe a) -> Parser (Maybe a)
lookAheadM gma = do
s <- get
ma <- gma
when (isNothing ma) $ put s
return ma
-- | Like 'lookAhead', but consume the input if @gea@ returns 'Right _'.
-- Fails if @gea@ fails.
lookAheadE :: Parser (Either a b) -> Parser (Either a b)
lookAheadE gea = do
s <- get
ea <- gea
case ea of
Left _ -> put s
_ -> return ()
return ea
expect :: (Show a, Eq a) => (a -> Bool) -> Parser a -> Parser a
expect f p = do
v <- p
when (not $ f v) $ fail $ show v ++ " was not expected."
return v
getString :: Int -> Parser String
getString l = do
bs <- getLazyByteString (fromIntegral l)
return $! map B.w2c (L.unpack bs)
getStringNul :: Parser String
getStringNul = do
bs <- getLazyByteStringNul
return $! map B.w2c (L.unpack bs)
string :: String -> Parser String
string s = expect (s ==) (getString $ length s)
-- Utility
-- | Get the total number of bytes read to this point.
bytesRead :: Parser Int64
bytesRead = do
S _ _ b <- get
return b
-- | Get the number of remaining unparsed bytes.
-- Useful for checking whether all input has been consumed.
-- Note that this forces the rest of the input.
remaining :: Parser Int64
remaining = do
S s ss _ <- get
return $! (fromIntegral (B.length s) + L.length ss)
-- | Test whether all input has been consumed,
-- i.e. there are no remaining unparsed bytes.
isEmpty :: Parser Bool
isEmpty = do
S s ss _ <- get
return $! (B.null s && L.null ss)
------------------------------------------------------------------------
-- Utility with ByteStrings
-- | An efficient 'get' method for strict ByteStrings. Fails if fewer
-- than @n@ bytes are left in the input.
getByteString :: Int -> Parser B.ByteString
getByteString n = readN n id
-- | An efficient 'get' method for lazy ByteStrings. Does not fail if fewer than
-- @n@ bytes are left in the input.
getLazyByteString :: Int64 -> Parser L.ByteString
getLazyByteString n = do
S s ss bytes <- get
let big = s `bsJoin` ss
case splitAtST n big of
(consume, rest) -> do put $ mkState rest (bytes + n)
return consume
-- | Get a lazy ByteString that is terminated with a NUL byte. Fails
-- if it reaches the end of input without hitting a NUL.
getLazyByteStringNul :: Parser L.ByteString
getLazyByteStringNul = do
S s ss bytes <- get
let big = s `bsJoin` ss
(consume, t) = L.break (== 0) big
(h, rest) = L.splitAt 1 t
when (L.null h) $ fail "too few bytes"
put $ mkState rest (bytes + L.length consume + 1)
return consume
-- | Get the remaining bytes as a lazy ByteString
getRemainingLazyByteString :: Parser L.ByteString
getRemainingLazyByteString = do
S s ss _ <- get
return $! (s `bsJoin` ss)
------------------------------------------------------------------------
-- Helpers
-- | Pull @n@ bytes from the input, as a strict ByteString.
getBytes :: Int -> Parser B.ByteString
getBytes n = do
S s ss bytes <- get
if n <= B.length s
then do let (consume,rest) = B.splitAt n s
put $! S rest ss (bytes + fromIntegral n)
return $! consume
else
case L.splitAt (fromIntegral n) (s `bsJoin` ss) of
(consuming, rest) ->
do let now = B.concat . L.toChunks $ consuming
put $! mkState rest (bytes + fromIntegral n)
-- forces the next chunk before this one is returned
when (B.length now < n) $ fail "too few bytes"
return now
bsJoin :: B.ByteString -> L.ByteString -> L.ByteString
bsJoin bb lb
| B.null bb = lb
| otherwise = L.Chunk bb lb
-- | Split a ByteString. If the first result is consumed before the --
-- second, this runs in constant heap space.
--
-- You must force the returned tuple for that to work, e.g.
--
-- > case splitAtST n xs of
-- > (ys,zs) -> consume ys ... consume zs
--
splitAtST :: Int64 -> L.ByteString -> (L.ByteString, L.ByteString)
splitAtST i ps | i <= 0 = (L.empty, ps)
splitAtST i ps = runST (
do r <- newSTRef undefined
xs <- first r i ps
ys <- unsafeInterleaveST (readSTRef r)
return (xs, ys))
where
first r 0 xs@(L.Chunk _ _) = writeSTRef r xs >> return L.Empty
first r _ L.Empty = writeSTRef r L.Empty >> return L.Empty
first r n (L.Chunk x xs)
| n < l = do writeSTRef r (L.Chunk (B.drop (fromIntegral n) x) xs)
return $! L.Chunk (B.take (fromIntegral n) x) L.Empty
| otherwise = do writeSTRef r (L.drop (n - l) xs)
liftM (L.Chunk x) $ unsafeInterleaveST (first r (n - l) xs)
where l = fromIntegral (B.length x)
-- Pull n bytes from the input, and apply a parser to those bytes,
-- yielding a value. If less than @n@ bytes are available, fail with an
-- error. This wraps @getBytes@.
readN :: Int -> (B.ByteString -> a) -> Parser a
readN n f = fmap f $ getBytes n
------------------------------------------------------------------------
-- Primtives
-- helper, get a raw Ptr onto a strict ByteString copied out of the
-- underlying lazy byteString. So many indirections from the raw parser
-- state that my head hurts...
getPtr :: Storable a => Int -> Parser a
getPtr n = do
(fp,o,_) <- readN n B.toForeignPtr
return . B.inlinePerformIO $ withForeignPtr fp $ \p -> peek (castPtr $ p `plusPtr` o)
------------------------------------------------------------------------
satisfy :: (Word8 -> Bool) -> Parser Word8
satisfy f = do
w <- getWord8
guard (f w)
return w
-- | Read a Word8 from the monad state
getWord8 :: Parser Word8
getWord8 = getPtr (sizeOf (undefined :: Word8))
word8 :: Word8 -> Parser Word8
word8 w = expect (w ==) getWord8
-- | Read a Word16 in big endian format
getWord16be :: Parser Word16
getWord16be = do
s <- readN 2 id
return $! (fromIntegral (s `B.index` 0) `shiftL` 8) .|.
(fromIntegral (s `B.index` 1))
word16be :: Word16 -> Parser Word16
word16be w = expect (w ==) getWord16be
-- | Read a Word16 in little endian format
getWord16le :: Parser Word16
getWord16le = do
s <- readN 2 id
return $! (fromIntegral (s `B.index` 1) `shiftL` 8) .|.
(fromIntegral (s `B.index` 0) )
word16le :: Word16 -> Parser Word16
word16le w = expect (w ==) getWord16le
-- | Read a 24 bit word into Word32 in big endian format
getWord24be :: Parser Word32
getWord24be = do
s <- readN 3 id
return $! (fromIntegral (s `B.index` 0) `shiftL` 16) .|.
(fromIntegral (s `B.index` 1) `shiftL` 8) .|.
(fromIntegral (s `B.index` 2) )
word24be :: Word32 -> Parser Word32
word24be w = expect (w ==) getWord24be
getWord24le :: Parser Word32
getWord24le = do
s <- readN 3 id
return $! (fromIntegral (s `B.index` 2) `shiftL` 16) .|.
(fromIntegral (s `B.index` 1) `shiftL` 8) .|.
(fromIntegral (s `B.index` 0) )
word24le :: Word32 -> Parser Word32
word24le w = expect (w ==) getWord24le
-- | Read a Word32 in big endian format
getWord32be :: Parser Word32
getWord32be = do
s <- readN 4 id
return $! (fromIntegral (s `B.index` 0) `shiftL` 24) .|.
(fromIntegral (s `B.index` 1) `shiftL` 16) .|.
(fromIntegral (s `B.index` 2) `shiftL` 8) .|.
(fromIntegral (s `B.index` 3) )
word32be :: Word32 -> Parser Word32
word32be w = expect (w ==) getWord32be
-- | Read a Word32 in little endian format
getWord32le :: Parser Word32
getWord32le = do
s <- readN 4 id
return $! (fromIntegral (s `B.index` 3) `shiftL` 24) .|.
(fromIntegral (s `B.index` 2) `shiftL` 16) .|.
(fromIntegral (s `B.index` 1) `shiftL` 8) .|.
(fromIntegral (s `B.index` 0) )
word32le :: Word32 -> Parser Word32
word32le w = expect (w ==) getWord32le
-- | Read a Word64 in big endian format
getWord64be :: Parser Word64
getWord64be = do
s <- readN 8 id
return $! (fromIntegral (s `B.index` 0) `shiftL` 56) .|.
(fromIntegral (s `B.index` 1) `shiftL` 48) .|.
(fromIntegral (s `B.index` 2) `shiftL` 40) .|.
(fromIntegral (s `B.index` 3) `shiftL` 32) .|.
(fromIntegral (s `B.index` 4) `shiftL` 24) .|.
(fromIntegral (s `B.index` 5) `shiftL` 16) .|.
(fromIntegral (s `B.index` 6) `shiftL` 8) .|.
(fromIntegral (s `B.index` 7) )
word64be :: Word64 -> Parser Word64
word64be w = expect (w ==) getWord64be
-- | Read a Word64 in little endian format
getWord64le :: Parser Word64
getWord64le = do
s <- readN 8 id
return $! (fromIntegral (s `B.index` 7) `shiftL` 56) .|.
(fromIntegral (s `B.index` 6) `shiftL` 48) .|.
(fromIntegral (s `B.index` 5) `shiftL` 40) .|.
(fromIntegral (s `B.index` 4) `shiftL` 32) .|.
(fromIntegral (s `B.index` 3) `shiftL` 24) .|.
(fromIntegral (s `B.index` 2) `shiftL` 16) .|.
(fromIntegral (s `B.index` 1) `shiftL` 8) .|.
(fromIntegral (s `B.index` 0) )
word64le :: Word64 -> Parser Word64
word64le w = expect (w ==) getWord64le
------------------------------------------------------------------------
getInt8 :: Parser Int8
getInt8 = getWord8 >>= return . fromIntegral
int8 :: Int8 -> Parser Int8
int8 i = expect (i ==) getInt8
getInt16le :: Parser Int16
getInt16le = getWord16le >>= return . fromIntegral
int16le :: Int16 -> Parser Int16
int16le i = expect (i ==) getInt16le
getInt16be :: Parser Int16
getInt16be = getWord16be >>= return . fromIntegral
int16be :: Int16 -> Parser Int16
int16be i = expect (i ==) getInt16be
getInt32le :: Parser Int32
getInt32le = getWord32le >>= return . fromIntegral
int32le :: Int32 -> Parser Int32
int32le i = expect (i ==) getInt32le
getInt32be :: Parser Int32
getInt32be = getWord32be >>= return . fromIntegral
int32be :: Int32 -> Parser Int32
int32be i = expect (i ==) getInt32be
getInt64le :: Parser Int64
getInt64le = getWord64le >>= return . fromIntegral
int64le :: Int64 -> Parser Int64
int64le i = expect (i ==) getInt64le
getInt64be :: Parser Int64
getInt64be = getWord64be >>= return . fromIntegral
int64be :: Int64 -> Parser Int64
int64be i = expect (i ==) getInt64be
------------------------------------------------------------------------
-- Host-endian reads
-- | /O(1)./ Read a single native machine word. The word is read in
-- host order, host endian form, for the machine you're on. On a 64 bit
-- machine the Word is an 8 byte value, on a 32 bit machine, 4 bytes.
getWordHost :: Parser Word
getWordHost = getPtr (sizeOf (undefined :: Word))
wordHost :: Word -> Parser Word
wordHost w = expect (w ==) getWordHost
-- | /O(1)./ Read a 2 byte Word16 in native host order and host endianness.
getWord16host :: Parser Word16
getWord16host = getPtr (sizeOf (undefined :: Word16))
word16host :: Word16 -> Parser Word16
word16host w = expect (w ==) getWord16host
-- | /O(1)./ Read a Word32 in native host order and host endianness.
getWord32host :: Parser Word32
getWord32host = getPtr (sizeOf (undefined :: Word32))
word32host :: Word32 -> Parser Word32
word32host w = expect (w ==) getWord32host
-- | /O(1)./ Read a Word64 in native host order and host endianess.
getWord64host :: Parser Word64
getWord64host = getPtr (sizeOf (undefined :: Word64))
word64host :: Word64 -> Parser Word64
word64host w = expect (w ==) getWord64host
-- Variable length numbers
getVarLenBe :: Parser Word64
getVarLenBe = f 0
where
f :: Word64 -> Parser Word64
f acc = do
w <- getWord8 >>= return . fromIntegral
if testBit w 7
then f $! (shiftL acc 7) .|. (clearBit w 7)
else return $! (shiftL acc 7) .|. w
varLenBe :: Word64 -> Parser Word64
varLenBe a = expect (a ==) getVarLenBe
getVarLenLe :: Parser Word64
getVarLenLe = do
w <- getWord8 >>= return . fromIntegral
if testBit w 7
then do
w' <- getVarLenLe
return $! (clearBit w 7) .|. (shiftL w' 7)
else return $! w
varLenLe :: Word64 -> Parser Word64
varLenLe a = expect (a ==) getVarLenLe
|
giorgidze/HCodecs
|
src/Codec/ByteString/Parser.hs
|
bsd-3-clause
| 17,498 | 0 | 19 | 4,458 | 5,255 | 2,785 | 2,470 | 387 | 3 |
module Network.EasyBitcoin.Internal.Script
where
import Data.Word
import qualified Data.ByteString as BS
import Data.List (nub) -- not to use nub!! TODO
import Data.Binary (Binary, get, put)
import Data.Binary.Get ( getWord64be
, getWord32be
, getWord8
, getWord16le
, getWord32le
, getByteString
, Get
, isEmpty
)
import Data.Binary.Put( putWord64be
, putWord32be
, putWord32le
, putWord16le
, putWord8
, putByteString
)
import Control.Monad (unless, guard,replicateM,forM_,liftM2)
import Control.Applicative((<$>))
newtype Script = Script{scriptOps::[ScriptOp]}
deriving (Eq, Show, Ord,Read)
-- | Data type representing all of the operators allowed inside a 'Script'.
data ScriptOp = OP_PUSHDATA { pushContent :: !BS.ByteString
, pushOpCode :: !PushDataType
}
-- OP__ 0
| OP_1NEGATE
| OP_RESERVED
| OP__ Word8 -- from 0 to 16 inclusive
-- ^ Flow control
| OP_NOP
| OP_VER -- reserved
| OP_IF
| OP_NOTIF
| OP_VERIF -- resreved
| OP_VERNOTIF -- reserved
| OP_ELSE
| OP_ENDIF
| OP_VERIFY
| OP_RETURN
-- ^Stack operations
| OP_TOALTSTACK
| OP_FROMALTSTACK
| OP_IFDUP
| OP_DEPTH
| OP_DROP
| OP_DUP
| OP_NIP
| OP_OVER
| OP_PICK
| OP_ROLL
| OP_ROT
| OP_SWAP
| OP_TUCK
| OP_2DROP
| OP_2DUP
| OP_3DUP
| OP_2OVER
| OP_2ROT
| OP_2SWAP
-- ^ Splice
| OP_CAT
| OP_SUBSTR
| OP_LEFT
| OP_RIGHT
| OP_SIZE
-- ^ Bitwise logic
| OP_INVERT
| OP_AND
| OP_OR
| OP_XOR
| OP_EQUAL
| OP_EQUALVERIFY
| OP_RESERVED1
| OP_RESERVED2
-- ^ Arithmetic
| OP_1ADD
| OP_1SUB
| OP_2MUL
| OP_2DIV
| OP_NEGATE
| OP_ABS
| OP_NOT
| OP_0NOTEQUAL
| OP_ADD
| OP_SUB
| OP_MUL
| OP_DIV
| OP_MOD
| OP_LSHIFT
| OP_RSHIFT
| OP_BOOLAND
| OP_BOOLOR
| OP_NUMEQUAL
| OP_NUMEQUALVERIFY
| OP_NUMNOTEQUAL
| OP_LESSTHAN
| OP_GREATERTHAN
| OP_LESSTHANOREQUAL
| OP_GREATERTHANOREQUAL
| OP_MIN
| OP_MAX
| OP_WITHIN
-- ^ Crypto
| OP_RIPEMD160
| OP_SHA1
| OP_SHA256
| OP_HASH160
| OP_HASH256
| OP_CODESEPARATOR
| OP_CHECKSIG
| OP_CHECKSIGVERIFY
| OP_CHECKMULTISIG
| OP_CHECKMULTISIGVERIFY
-- ^ Expansion
| OP_NOP1 | OP_NOP2 | OP_NOP3 | OP_NOP4 | OP_NOP5
| OP_NOP6 | OP_NOP7 | OP_NOP8 | OP_NOP9 | OP_NOP10
-- ^ Other
| OP_PUBKEYHASH
| OP_PUBKEY
| OP_INVALIDOPCODE !Word8
deriving (Show, Read, Ord,Eq)
-- | Data type representing the type of an OP_PUSHDATA opcode.
data PushDataType = OPCODE -- ^ The next opcode bytes is data to be pushed onto the stack
-- | The next byte contains the number of bytes to be pushed onto
-- the stack
| OPDATA1
-- | The next two bytes contains the number of bytes to be pushed onto
-- the stack
| OPDATA2
-- | The next four bytes contains the number of bytes to be pushed onto
-- the stack
| OPDATA4
deriving (Show, Ord,Read, Eq)
----------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------
op:: Int -> ScriptOp
op n = let n_ = min 16 (max 0 n)
in OP__ (fromIntegral n)
opPushData :: BS.ByteString -> ScriptOp
opPushData bs = case BS.length bs of
len | len <= 0x4b -> OP_PUSHDATA bs OPCODE
| len <= 0xff -> OP_PUSHDATA bs OPDATA1
| len <= 0xffff -> OP_PUSHDATA bs OPDATA2
| len <= 0xffffffff -> OP_PUSHDATA bs OPDATA4
| otherwise -> error "opPushData: payload size too big"
opNumber :: ScriptOp -> Maybe Int
opNumber (OP__ n) = Just (fromIntegral n)
opNumber _ = Nothing
opContent :: ScriptOp -> Maybe BS.ByteString
opContent (OP_PUSHDATA content _) = Just content
opContent _ = Nothing
---------------------------------------------------------------------------------------------------
instance Binary Script where
get = Script <$> getScriptOps
where
getScriptOps = do empty <- isEmpty
if empty
then return []
else liftM2 (:) get getScriptOps
put (Script ops) = forM_ ops put
instance Binary ScriptOp where
get = do op <- getWord8
case op of
0x00 -> return $ OP__ 0
_ | op <= 0x4b -> do payload <- getByteString (fromIntegral op)
return $ OP_PUSHDATA payload OPCODE
0x4c -> do len <- getWord8
payload <- getByteString (fromIntegral len)
return $ OP_PUSHDATA payload OPDATA1
0x4d -> do len <- getWord16le
payload <- getByteString (fromIntegral len)
return $ OP_PUSHDATA payload OPDATA2
0x4e -> do len <- getWord32le
payload <- getByteString (fromIntegral len)
return $ OP_PUSHDATA payload OPDATA4
0x4f -> return $ OP_1NEGATE
0x50 -> return $ OP_RESERVED
_ | op < 0x61 -> return $ OP__ (op - 0x50)
-- Flow control
0x61 -> return $ OP_NOP
0x62 -> return $ OP_VER -- reserved
0x63 -> return $ OP_IF
0x64 -> return $ OP_NOTIF
0x65 -> return $ OP_VERIF -- reserved
0x66 -> return $ OP_VERNOTIF -- reserved
0x67 -> return $ OP_ELSE
0x68 -> return $ OP_ENDIF
0x69 -> return $ OP_VERIFY
0x6a -> return $ OP_RETURN
-- Stack
0x6b -> return $ OP_TOALTSTACK
0x6c -> return $ OP_FROMALTSTACK
0x6d -> return $ OP_2DROP
0x6e -> return $ OP_2DUP
0x6f -> return $ OP_3DUP
0x70 -> return $ OP_2OVER
0x71 -> return $ OP_2ROT
0x72 -> return $ OP_2SWAP
0x73 -> return $ OP_IFDUP
0x74 -> return $ OP_DEPTH
0x75 -> return $ OP_DROP
0x76 -> return $ OP_DUP
0x77 -> return $ OP_NIP
0x78 -> return $ OP_OVER
0x79 -> return $ OP_PICK
0x7a -> return $ OP_ROLL
0x7b -> return $ OP_ROT
0x7c -> return $ OP_SWAP
0x7d -> return $ OP_TUCK
-- Splice
0x7e -> return $ OP_CAT
0x7f -> return $ OP_SUBSTR
0x80 -> return $ OP_LEFT
0x81 -> return $ OP_RIGHT
0x82 -> return $ OP_SIZE
-- Bitwise logic
0x83 -> return $ OP_INVERT
0x84 -> return $ OP_AND
0x85 -> return $ OP_OR
0x86 -> return $ OP_XOR
0x87 -> return $ OP_EQUAL
0x88 -> return $ OP_EQUALVERIFY
0x89 -> return $ OP_RESERVED1
0x8a -> return $ OP_RESERVED2
-- Arithmetic
0x8b -> return $ OP_1ADD
0x8c -> return $ OP_1SUB
0x8d -> return $ OP_2MUL
0x8e -> return $ OP_2DIV
0x8f -> return $ OP_NEGATE
0x90 -> return $ OP_ABS
0x91 -> return $ OP_NOT
0x92 -> return $ OP_0NOTEQUAL
0x93 -> return $ OP_ADD
0x94 -> return $ OP_SUB
0x95 -> return $ OP_MUL
0x96 -> return $ OP_DIV
0x97 -> return $ OP_MOD
0x98 -> return $ OP_LSHIFT
0x99 -> return $ OP_RSHIFT
0x9a -> return $ OP_BOOLAND
0x9b -> return $ OP_BOOLOR
0x9c -> return $ OP_NUMEQUAL
0x9d -> return $ OP_NUMEQUALVERIFY
0x9e -> return $ OP_NUMNOTEQUAL
0x9f -> return $ OP_LESSTHAN
0xa0 -> return $ OP_GREATERTHAN
0xa1 -> return $ OP_LESSTHANOREQUAL
0xa2 -> return $ OP_GREATERTHANOREQUAL
0xa3 -> return $ OP_MIN
0xa4 -> return $ OP_MAX
0xa5 -> return $ OP_WITHIN
-- Crypto
0xa6 -> return $ OP_RIPEMD160
0xa7 -> return $ OP_SHA1
0xa8 -> return $ OP_SHA256
0xa9 -> return $ OP_HASH160
0xaa -> return $ OP_HASH256
0xab -> return $ OP_CODESEPARATOR
0xac -> return $ OP_CHECKSIG
0xad -> return $ OP_CHECKSIGVERIFY
0xae -> return $ OP_CHECKMULTISIG
0xaf -> return $ OP_CHECKMULTISIGVERIFY
-- More NOPs
0xb0 -> return $ OP_NOP1
0xb1 -> return $ OP_NOP2
0xb2 -> return $ OP_NOP3
0xb3 -> return $ OP_NOP4
0xb4 -> return $ OP_NOP5
0xb5 -> return $ OP_NOP6
0xb6 -> return $ OP_NOP7
0xb7 -> return $ OP_NOP8
0xb8 -> return $ OP_NOP9
0xb9 -> return $ OP_NOP10
-- Constants
0xfd -> return $ OP_PUBKEYHASH
0xfe -> return $ OP_PUBKEY
_ -> return $ OP_INVALIDOPCODE op
put op = case op of
(OP_PUSHDATA payload optype)-> do let len = BS.length payload
case optype of
OPCODE -> do unless (len <= 0x4b) $ fail "OP_PUSHDATA OPCODE: Payload size too big"
putWord8 $ fromIntegral len
OPDATA1 -> do unless (len <= 0xff) $ fail "OP_PUSHDATA OPDATA1: Payload size too big"
putWord8 0x4c
putWord8 $ fromIntegral len
OPDATA2 -> do unless (len <= 0xffff) $ fail "OP_PUSHDATA OPDATA2: Payload size too big"
putWord8 0x4d
putWord16le $ fromIntegral len
OPDATA4 -> do unless (len <= 0x7fffffff) $ fail "OP_PUSHDATA OPDATA4: Payload size too big"
putWord8 0x4e
putWord32le $ fromIntegral len
putByteString payload
-- Constants
OP__ 0 -> putWord8 0x00
OP_1NEGATE -> putWord8 0x4f
OP_RESERVED -> putWord8 0x50
OP__ n -> putWord8 (0x50+n) -- n should be between 1 and 16 inclusive
-- Crypto Constants
OP_PUBKEY -> putWord8 0xfe
OP_PUBKEYHASH -> putWord8 0xfd
-- Invalid Opcodes
(OP_INVALIDOPCODE x) -> putWord8 x
-- Flow Control
OP_NOP -> putWord8 0x61
OP_VER -> putWord8 0x62
OP_IF -> putWord8 0x63
OP_NOTIF -> putWord8 0x64
OP_VERIF -> putWord8 0x65
OP_VERNOTIF -> putWord8 0x66
OP_ELSE -> putWord8 0x67
OP_ENDIF -> putWord8 0x68
OP_VERIFY -> putWord8 0x69
OP_RETURN -> putWord8 0x6a
-- Stack Operations
OP_TOALTSTACK -> putWord8 0x6b
OP_FROMALTSTACK -> putWord8 0x6c
OP_2DROP -> putWord8 0x6d
OP_2DUP -> putWord8 0x6e
OP_3DUP -> putWord8 0x6f
OP_2OVER -> putWord8 0x70
OP_2ROT -> putWord8 0x71
OP_2SWAP -> putWord8 0x72
OP_IFDUP -> putWord8 0x73
OP_DEPTH -> putWord8 0x74
OP_DROP -> putWord8 0x75
OP_DUP -> putWord8 0x76
OP_NIP -> putWord8 0x77
OP_OVER -> putWord8 0x78
OP_PICK -> putWord8 0x79
OP_ROLL -> putWord8 0x7a
OP_ROT -> putWord8 0x7b
OP_SWAP -> putWord8 0x7c
OP_TUCK -> putWord8 0x7d
-- Splice
OP_CAT -> putWord8 0x7e
OP_SUBSTR -> putWord8 0x7f
OP_LEFT -> putWord8 0x80
OP_RIGHT -> putWord8 0x81
OP_SIZE -> putWord8 0x82
-- Bitwise Logic
OP_INVERT -> putWord8 0x83
OP_AND -> putWord8 0x84
OP_OR -> putWord8 0x85
OP_XOR -> putWord8 0x86
OP_EQUAL -> putWord8 0x87
OP_EQUALVERIFY -> putWord8 0x88
OP_RESERVED1 -> putWord8 0x89
OP_RESERVED2 -> putWord8 0x8a
-- Arithmetic
OP_1ADD -> putWord8 0x8b
OP_1SUB -> putWord8 0x8c
OP_2MUL -> putWord8 0x8d
OP_2DIV -> putWord8 0x8e
OP_NEGATE -> putWord8 0x8f
OP_ABS -> putWord8 0x90
OP_NOT -> putWord8 0x91
OP_0NOTEQUAL -> putWord8 0x92
OP_ADD -> putWord8 0x93
OP_SUB -> putWord8 0x94
OP_MUL -> putWord8 0x95
OP_DIV -> putWord8 0x96
OP_MOD -> putWord8 0x97
OP_LSHIFT -> putWord8 0x98
OP_RSHIFT -> putWord8 0x99
OP_BOOLAND -> putWord8 0x9a
OP_BOOLOR -> putWord8 0x9b
OP_NUMEQUAL -> putWord8 0x9c
OP_NUMEQUALVERIFY -> putWord8 0x9d
OP_NUMNOTEQUAL -> putWord8 0x9e
OP_LESSTHAN -> putWord8 0x9f
OP_GREATERTHAN -> putWord8 0xa0
OP_LESSTHANOREQUAL -> putWord8 0xa1
OP_GREATERTHANOREQUAL-> putWord8 0xa2
OP_MIN -> putWord8 0xa3
OP_MAX -> putWord8 0xa4
OP_WITHIN -> putWord8 0xa5
-- Crypto
OP_RIPEMD160 -> putWord8 0xa6
OP_SHA1 -> putWord8 0xa7
OP_SHA256 -> putWord8 0xa8
OP_HASH160 -> putWord8 0xa9
OP_HASH256 -> putWord8 0xaa
OP_CODESEPARATOR -> putWord8 0xab
OP_CHECKSIG -> putWord8 0xac
OP_CHECKSIGVERIFY -> putWord8 0xad
OP_CHECKMULTISIG -> putWord8 0xae
OP_CHECKMULTISIGVERIFY -> putWord8 0xaf
-- More NOPs
OP_NOP1 -> putWord8 0xb0
OP_NOP2 -> putWord8 0xb1
OP_NOP3 -> putWord8 0xb2
OP_NOP4 -> putWord8 0xb3
OP_NOP5 -> putWord8 0xb4
OP_NOP6 -> putWord8 0xb5
OP_NOP7 -> putWord8 0xb6
OP_NOP8 -> putWord8 0xb7
OP_NOP9 -> putWord8 0xb8
OP_NOP10 -> putWord8 0xb9
|
vwwv/easy-bitcoin
|
Network/EasyBitcoin/Internal/Script.hs
|
bsd-3-clause
| 19,044 | 0 | 19 | 10,367 | 3,193 | 1,615 | 1,578 | 368 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE Trustworthy #-}
-- GHC warns about splitRec, but a "fix" yield unreachable code and won't compile.
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
module Math.Rec
( Rec(..)
, appendRec
, mapRec
, splitRec
, takeRec
, dropRec
, foldrRec
, traverseRec
-- * Type Lists
, type (++)
, appendNilAxiom
, appendAssocAxiom
-- * Dict1
, Dict1(..)
-- * All
, All(..)
, reproof
) where
import Control.Applicative
import Data.Constraint
import Data.Type.Equality
import Math.Functor
import Prelude (($), fst, snd)
import Unsafe.Coerce
type family (++) (a :: [k]) (b :: [k]) :: [k]
type instance '[] ++ bs = bs
type instance (a ': as) ++ bs = a ': (as ++ bs)
-- | Proof provided by every single class on theorem proving in the last 20 years.
appendNilAxiom :: forall as. Dict (as ~ (as ++ '[]))
appendNilAxiom = unsafeCoerce (Dict :: Dict (as ~ as))
-- | Proof provided by every single class on theorem proving in the last 20 years.
appendAssocAxiom :: forall p q r as bs cs. p as -> q bs -> r cs -> Dict ((as ++ (bs ++ cs)) ~ ((as ++ bs) ++ cs))
appendAssocAxiom _ _ _ = unsafeCoerce (Dict :: Dict (as ~ as))
data Rec f as where
RNil :: Rec f '[]
(:&) :: !(f i) -> !(Rec f is) -> Rec f (i ': is)
instance Functor (Rec f) where
type Dom (Rec f) = (:~:)
type Cod (Rec f) = (->)
fmap Refl as = as
instance Functor Rec where
type Dom Rec = Nat (:~:) (->)
type Cod Rec = Nat (:~:) (->)
fmap f = Nat $ mapRec (runNat f)
-- | Append two records
appendRec :: Rec f as -> Rec f bs -> Rec f (as ++ bs)
appendRec RNil bs = bs
appendRec (a :& as) bs = a :& appendRec as bs
-- | Map over a record
mapRec :: (forall a. f a -> g a) -> Rec f as -> Rec g as
mapRec _ RNil = RNil
mapRec f (a :& as) = f a :& mapRec f as
-- | Split a record
splitRec :: Rec f is -> Rec g (is ++ js) -> (Rec g is, Rec g js)
splitRec (_ :& is) (a :& as) = case splitRec is as of
(l,r) -> (a :& l, r)
splitRec RNil as = (RNil, as)
-- splitRec (_ :& _) RNil = error "splitRec: the impossible happened"
takeRec :: forall f g h is js. Rec f is -> Rec g js -> Rec h (is ++ js) -> Rec h is
takeRec is _ ijs = fst $ (splitRec is ijs :: (Rec h is, Rec h js))
dropRec :: Rec f is -> Rec g (is ++ js) -> Rec g js
dropRec is ijs = snd $ splitRec is ijs
foldrRec :: (forall j js. f j -> r js -> r (j ': js)) -> r '[] -> Rec f is -> r is
foldrRec _ z RNil = z
foldrRec f z (a :& as) = f a (foldrRec f z as)
traverseRec :: Applicative m => (forall i. f i -> m (g i)) -> Rec f is -> m (Rec g is)
traverseRec f (a :& as) = (:&) <$> f a <*> traverseRec f as
traverseRec _ RNil = pure RNil
data Dict1 p a where
Dict1 :: p a => Dict1 p a
class All (p :: i -> Constraint) (is :: [i]) where
proofs :: Rec (Dict1 p) is
instance All p '[] where
proofs = RNil
instance (p i, All p is) => All p (i ': is) where
proofs = Dict1 :& proofs
reproof :: Rec (Dict1 p) is -> Dict (All p is)
reproof RNil = Dict
reproof (Dict1 :& as) = case reproof as of
Dict -> Dict
|
ekmett/categories
|
src/Math/Rec.hs
|
bsd-3-clause
| 3,374 | 4 | 15 | 791 | 1,405 | 763 | 642 | -1 | -1 |
module Superscripts
( superScript
, superScriptNum
, desuperScript
, desuperScriptNum
) where
import qualified Data.Map as Map
normalNums = "0123456789"
superScriptNums = "β°ΒΉΒ²Β³β΄β΅βΆβ·βΈβΉ"
superScripts :: Map.Map Char Char
superScripts = Map.fromList $ zip normalNums superScriptNums
desuperScripts :: Map.Map Char Char
desuperScripts = Map.fromList $ zip superScriptNums normalNums
lookupOrSelf :: Char -> Map.Map Char Char -> Char
lookupOrSelf c m = case Map.lookup c m of
Just r -> r
_ -> c
superScriptChar :: Char -> Char
superScriptChar c = lookupOrSelf c superScripts
superScript = map superScriptChar
desuperScriptChar :: Char -> Char
desuperScriptChar c = lookupOrSelf c desuperScripts
desuperScript = map desuperScriptChar
superScriptNum :: Int -> String
superScriptNum = superScript . show
desuperScriptNum :: Int -> String
desuperScriptNum = desuperScript . show
|
benizi/dotfiles
|
.xmonad/lib/Superscripts.hs
|
mit
| 900 | 0 | 8 | 136 | 244 | 129 | 115 | 26 | 2 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
{- |
Module : ./CSL/Print_AS.hs
Description : Printer for abstract syntax of CSL
Copyright : (c) Dominik Dietrich, Ewaryst Schulz, DFKI Bremen 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
Pretty printing the abstract syntax of CSL.
-}
module CSL.Print_AS
( printExpression
, printCMD
, printAssDefinition
, printConstantName
, ExpressionPrinter (..)
) where
import Common.Id as Id
import Common.Doc
import Common.DocUtils
import Control.Monad
import Control.Monad.Reader
import Numeric
import CSL.AS_BASIC_CSL
import CSL.TreePO
-- * Pretty Printing
instance Pretty InfInt where
pretty = printInfInt
instance Pretty GroundConstant where
pretty = printGC
instance (Ord a, Pretty a) => Pretty (SetOrInterval a) where
pretty = printDomain
instance Pretty a => Pretty (ClosedInterval a) where
pretty = printClosedInterval
instance Pretty OpDecl where
pretty = head . printOpDecl
instance Pretty VarDecl where
pretty = printVarDecl
instance Pretty EPVal where
pretty = printEPVal
instance Pretty EPDecl where
pretty = printEPDecl
instance Pretty OP_ITEM where
pretty = printOpItem
instance Pretty VAR_ITEM where
pretty = printVarItem
instance Pretty BASIC_SPEC where
pretty = printBasicSpec
instance Pretty BASIC_ITEM where
pretty = printBasicItems
instance Pretty EXTPARAM where
pretty = printExtparam
instance Pretty EXPRESSION where
pretty = head . printExpression
instance Pretty SYMB_ITEMS where
pretty = printSymbItems
instance Pretty SYMB where
pretty = printSymbol
instance Pretty SYMB_MAP_ITEMS where
pretty = printSymbMapItems
instance Pretty SYMB_OR_MAP where
pretty = printSymbOrMap
instance Pretty CMD where
pretty = head . printCMD
instance Pretty ConstantName where
pretty = printConstantName
instance Pretty AssDefinition where
pretty = head . printAssDefinition
instance Pretty OPID where
pretty = head . printOPID
{- | A monad for printing of constants. This turns the pretty printing facility
more flexible w.r.t. the output of 'ConstantName'. -}
class Monad m => ExpressionPrinter m where
getOINM :: m OpInfoNameMap
getOINM = return operatorInfoNameMap
printConstant :: ConstantName -> m Doc
printConstant = return . printConstantName
printOpname :: OPNAME -> m Doc
printOpname = return . text . showOPNAME
prefixMode :: m Bool
prefixMode = return False
printArgs :: [Doc] -> m Doc
printArgs = return . parens . sepByCommas
printArgPattern :: String -> m Doc
printArgPattern = return . text
printInterval :: Double -> Double -> m Doc
printInterval l r =
return $ brackets $ sepByCommas $ map (text . show) [l, r]
printRational :: APFloat -> m Doc
printRational r = return $ text $ showFloat (fromRat r :: Double) ""
-- | The default ConstantName printer
printConstantName :: ConstantName -> Doc
printConstantName (SimpleConstant s) = text s
printConstantName (ElimConstant s i) =
text $ if i > 0 then s ++ "__" ++ show i else s
printAssDefinition :: ExpressionPrinter m => AssDefinition -> m Doc
printAssDefinition (ConstDef e) = liftM (text "=" <+>) $ printExpression e
printAssDefinition (FunDef l e) = do
ed <- printExpression e
l' <- mapM printArgPattern l
args <- printArgs l'
return $ args <+> text "=" <+> ed
printOPID :: ExpressionPrinter m => OPID -> m Doc
printOPID (OpUser c) = printConstant c
printOPID (OpId oi) = printOpname oi
-- a dummy instance, we take the simplest monad
instance ExpressionPrinter []
-- | An 'OpInfoNameMap' can be interpreted as an 'ExpressionPrinter'
instance ExpressionPrinter (Reader OpInfoNameMap) where
getOINM = ask
printCMD :: ExpressionPrinter m => CMD -> m Doc
printCMD (Ass c def) = do
def' <- printExpression def
c' <- printOpDecl c
return $ c' <+> text ":=" <+> def'
printCMD c@(Cmd s exps) -- TODO: remove the case := later
| s == ":=" = error $ "printCMD: use Ass for assignment representation! "
++ show c
| s == "constraint" = printExpression (head exps)
| otherwise = let f l = text s <> parens (sepByCommas l)
in liftM f $ mapM printExpression exps
printCMD (Repeat e stms) = do
e' <- printExpression e
let f l = text "re" <>
(text "peat" $+$ vcat (map (text "." <+>) l))
$+$ text "until" <+> e'
liftM f $ mapM printCMD stms
printCMD (Sequence stms) =
let f l = text "se" <> (text "quence" $+$ vcat (map (text "." <+>) l))
$+$ text "end"
in liftM f $ mapM printCMD stms
printCMD (Cond l) = let f l' = vcat l' $+$ text "end"
in liftM f $ mapM (uncurry printCase) l
printCase :: ExpressionPrinter m => EXPRESSION -> [CMD] -> m Doc
printCase e l = do
e' <- printExpression e
let f l' = text "ca" <> (text "se" <+> e' <> text ":"
$+$ vcat (map (text "." <+>) l'))
liftM f $ mapM printCMD l
getPrec :: OpInfoNameMap -> EXPRESSION -> Int
getPrec oinm (Op s _ exps _)
| null exps = maxPrecedence + 1
| otherwise =
case lookupOpInfo oinm s $ length exps of
Right oi -> prec oi
Left True -> error $
concat [ "getPrec: registered operator ", show s, " used "
, "with non-registered arity ", show $ length exps ]
_ -> maxPrecedence {- this is probably a user-defined prefix function
, binds strongly -}
getPrec _ _ = maxPrecedence
getOp :: EXPRESSION -> Maybe OPID
getOp (Op s _ _ _) = Just s
getOp _ = Nothing
printExtparam :: EXTPARAM -> Doc
printExtparam (EP p op i) =
pretty p <> text op <> (if op == "-|" then empty else text $ show i)
printExtparams :: [EXTPARAM] -> Doc
printExtparams [] = empty
printExtparams l = brackets $ sepByCommas $ map printExtparam l
printInfix :: ExpressionPrinter m => EXPRESSION -> m Doc
printInfix e@(Op s _ exps@[e1, e2] _) = do
{- we mustn't omit the space between the operator and its arguments for text-
operators such as "and", "or", but it would be good to omit it for "+-*/" -}
oi <- printOPID s
oinm <- getOINM
let outerprec = getPrec oinm e
f cmp e' ed = if cmp outerprec $ getPrec oinm e' then ed else parens ed
g [ed1, ed2] = let cmp = case getOp e1 of
Just op1 | op1 == s -> (<=)
| otherwise -> (<)
_ -> (<)
in sep [f cmp e1 ed1, oi <+> f (<) e2 ed2]
g _ = error "printInfix: Inner impossible case"
liftM g $ mapM printExpression exps
printInfix _ = error "printInfix: Impossible case"
printExpression :: ExpressionPrinter m => EXPRESSION -> m Doc
printExpression (Var token) = return $ text $ tokStr token
printExpression e@(Op s epl exps _)
| null exps = liftM (<> printExtparams epl) $ printOPID s
| otherwise = do
let asPrfx pexps = do
oid <- printOPID s
args <- printArgs pexps
return $ oid <> printExtparams epl <> args
asPrfx' = mapM printExpression exps >>= asPrfx
oinm <- getOINM
pfxMode <- prefixMode
if pfxMode then asPrfx' else
case lookupOpInfo oinm s $ length exps of
Right oi
| infx oi -> printInfix e
| otherwise -> asPrfx'
_ -> asPrfx'
printExpression (List exps _) = liftM sepByCommas (mapM printExpression exps)
printExpression (Int i _) = return $ text (show i)
printExpression (Rat r _) = printRational r
printExpression (Interval l r _) = printInterval l r
printOpItem :: OP_ITEM -> Doc
printOpItem (Op_item tokens _) =
text "operator" <+> sepByCommas (map pretty tokens)
printVarItem :: VAR_ITEM -> Doc
printVarItem (Var_item vars dom _) =
hsep [sepByCommas $ map pretty vars, text "in", pretty dom]
instance Pretty Ordering where
pretty LT = text "<"
pretty GT = text ">"
pretty EQ = text "="
printVarDecl :: VarDecl -> Doc
printVarDecl (VarDecl n (Just dom)) = pretty n <+> text "in" <+> printDomain dom
printVarDecl (VarDecl n Nothing) = pretty n
printOpDecl :: ExpressionPrinter m => OpDecl -> m Doc
printOpDecl (OpDecl n epl vdl _)
| null vdl = liftM (<> printExtparams epl) $ printConstant n
| otherwise = do
oid <- printConstant n
args <- printArgs $ map printVarDecl vdl
return $ oid <> printExtparams epl <> args
printEPVal :: EPVal -> Doc
printEPVal (EPVal i) = pretty i
printEPVal (EPConstRef r) = pretty r
printEPDecl :: EPDecl -> Doc
printEPDecl (EPDecl tk dom mDef) =
let tkD = pretty tk
domD = printInfixWith True "in" (tk, dom)
in case mDef of
Just def -> vcat [domD, hsep [ text "set", text "default"
, hcat [tkD, text "=", pretty def]]]
_ -> domD
printClosedInterval :: Pretty a => ClosedInterval a -> Doc
printClosedInterval (ClosedInterval l r) =
hcat [ lbrack, sepByCommas $ map pretty [l, r], rbrack ]
printDomain :: (Ord a, Pretty a) => SetOrInterval a -> Doc
printDomain (Set s) = pretty s
printDomain (IntVal (c1, b1) (c2, b2)) =
hcat [ getIBorder True b1, sepByCommas $ map pretty [c1, c2]
, getIBorder False b2]
getIBorder :: Bool -> Bool -> Doc
getIBorder False False = lbrack
getIBorder True True = lbrack
getIBorder _ _ = rbrack
printGC :: GroundConstant -> Doc
printGC (GCI i) = text (show i)
printGC (GCR d) = text (show d)
printInfInt :: InfInt -> Doc
printInfInt NegInf = text "-oo"
printInfInt PosInf = text "oo"
printInfInt (FinInt x) = text $ show x
printBasicSpec :: BASIC_SPEC -> Doc
printBasicSpec (Basic_spec xs) = vcat $ map pretty xs
printBasicItems :: BASIC_ITEM -> Doc
printBasicItems (Axiom_item x) = pretty x
printBasicItems (Op_decl x) = pretty x
printBasicItems (Var_decls x) = text "vars" <+> sepBySemis (map pretty x)
printBasicItems (EP_decl x) = text "eps" <+> sepBySemis
(map (printInfixWith True "in") x)
printBasicItems (EP_domdecl x) =
text "set" <+> sepBySemis (map (printInfixWith False "=") x)
printBasicItems (EP_defval x) = text "set" <+> text "default" <+>
sepBySemis (map (printInfixWith False "=") x)
printInfixWith :: (Pretty a, Pretty b) => Bool -> String -> (a, b) -> Doc
printInfixWith b s (x, y) = sep' [pretty x, text s, pretty y]
where sep' = if b then hsep else hcat
printSymbol :: SYMB -> Doc
printSymbol (Symb_id sym) = pretty sym
printSymbItems :: SYMB_ITEMS -> Doc
printSymbItems (Symb_items xs _) = fsep $ map pretty xs
printSymbOrMap :: SYMB_OR_MAP -> Doc
printSymbOrMap (Symb sym) = pretty sym
printSymbOrMap (Symb_map source dest _) =
pretty source <+> mapsto <+> pretty dest
printSymbMapItems :: SYMB_MAP_ITEMS -> Doc
printSymbMapItems (Symb_map_items xs _) = fsep $ map pretty xs
-- Instances for GetRange
instance GetRange OP_ITEM where
getRange = Range . rangeSpan
rangeSpan x = case x of
Op_item a b -> joinRanges [rangeSpan a, rangeSpan b]
instance GetRange VAR_ITEM where
getRange = Range . rangeSpan
rangeSpan x = case x of
Var_item a _ b -> joinRanges [rangeSpan a, rangeSpan b]
instance GetRange BASIC_SPEC where
getRange = Range . rangeSpan
rangeSpan x = case x of
Basic_spec a -> joinRanges [rangeSpan a]
instance GetRange BASIC_ITEM where
getRange = Range . rangeSpan
rangeSpan x = case x of
Op_decl a -> joinRanges [rangeSpan a]
Var_decls a -> joinRanges [rangeSpan a]
Axiom_item a -> joinRanges [rangeSpan a]
EP_decl a -> joinRanges [rangeSpan $ map fst a]
EP_domdecl a -> joinRanges [rangeSpan $ map fst a]
EP_defval a -> joinRanges [rangeSpan $ map fst a]
instance GetRange CMD where
getRange = Range . rangeSpan
rangeSpan (Ass _ def) = rangeSpan def
rangeSpan (Cmd _ exps) = joinRanges (map rangeSpan exps)
-- parsing guruantees l <> null
rangeSpan (Repeat c l) = joinRanges [rangeSpan c, rangeSpan $ head l]
-- parsing guruantees l <> null
rangeSpan (Sequence l) = rangeSpan $ head l
rangeSpan (Cond l) = rangeSpan $ head l
instance GetRange SYMB_ITEMS where
getRange = Range . rangeSpan
rangeSpan (Symb_items a b) = joinRanges [rangeSpan a, rangeSpan b]
instance GetRange SYMB where
getRange = Range . rangeSpan
rangeSpan (Symb_id a) = joinRanges [rangeSpan a]
instance GetRange SYMB_MAP_ITEMS where
getRange = Range . rangeSpan
rangeSpan (Symb_map_items a b) = joinRanges [rangeSpan a, rangeSpan b]
instance GetRange SYMB_OR_MAP where
getRange = Range . rangeSpan
rangeSpan x = case x of
Symb a -> joinRanges [rangeSpan a]
Symb_map a b c -> joinRanges [rangeSpan a, rangeSpan b, rangeSpan c]
instance GetRange EXPRESSION where
getRange = Range . rangeSpan
rangeSpan x = case x of
Var token -> joinRanges [rangeSpan token]
Op _ _ exps a -> joinRanges $ rangeSpan a : map rangeSpan exps
List exps a -> joinRanges $ rangeSpan a : map rangeSpan exps
Int _ a -> joinRanges [rangeSpan a]
Rat _ a -> joinRanges [rangeSpan a]
Interval _ _ a -> joinRanges [rangeSpan a]
instance Pretty InstantiatedConstant where
pretty (InstantiatedConstant { constName = cn, instantiation = el }) =
if null el then pretty cn
else pretty cn <> parens (sepByCommas $ map pretty el)
|
spechub/Hets
|
CSL/Print_AS.hs
|
gpl-2.0
| 13,531 | 0 | 20 | 3,376 | 4,555 | 2,234 | 2,321 | 309 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module Response.Draw
(drawResponse) where
import Text.Blaze ((!))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import qualified Data.Text as T
import Control.Monad (forM_, mapM_)
import Happstack.Server
import MasterTemplate
import Scripts
drawResponse :: ServerPart Response
drawResponse =
ok $ toResponse $
masterTemplate "Courseography - Draw!"
[]
(do
header "draw"
drawContent
modePanel
)
drawScripts
drawContent :: H.Html
drawContent = H.div ! A.id "about-div" $ "Draw a Graph"
modePanel :: H.Html
modePanel = H.div ! A.id "side-panel-wrap" $ do
H.div ! A.id "node-mode" ! A.class_ "mode clicked" $ "NODE (n)"
H.input ! A.id "course-code"
! A.class_ "course-code"
! A.name "course-code"
! A.placeholder "Course Code"
! A.autocomplete "off"
! A.type_ "text"
! A.size "10"
H.div ! A.id "add-text" ! A.class_ "button" $ "ADD"
H.div ! A.id "path-mode" ! A.class_ "mode" $ "PATH (p)"
H.div ! A.id "region-mode" ! A.class_ "mode" $ "REGION (r)"
H.div ! A.id "finish-region" ! A.class_ "button" $ "finish (f)"
H.div ! A.id "change-mode" ! A.class_ "mode" $ "SELECT/MOVE (m)"
H.div ! A.id "erase-mode" ! A.class_ "mode" $ "ERASE (e)"
H.input ! A.id "select-colour"
! A.class_ "jscolor"
! A.value "ab2567"
! A.size "15"
H.table !A.id "colour-table" $ forM_ (replicate 2 $ replicate 5 "" :: [[H.Html]])
(H.tr . mapM_ (H.td . H.toHtml))
H.div ! A.id "save-graph" ! A.class_ "button" $ "SAVE"
H.input ! A.id "area-of-study"
! A.class_ "course-code"
! A.name "course-code"
! A.placeholder "Enter area of study."
! A.autocomplete "off"
! A.type_ "text"
! A.size "30"
H.div ! A.id "submit-graph-name" ! A.class_ "button" $ "Submit"
H.div ! A.id "json-data" ! A.class_ "json-data" $ ""
|
alexbaluta/courseography
|
app/Response/Draw.hs
|
gpl-3.0
| 2,181 | 0 | 16 | 686 | 695 | 336 | 359 | 55 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.PackageIndex
-- Copyright : (c) David Himmelstrup 2005,
-- Bjorn Bringert 2007,
-- Duncan Coutts 2008
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- An index of packages.
--
module Distribution.Client.PackageIndex (
-- * Package index data type
PackageIndex,
-- * Creating an index
fromList,
-- * Updates
merge,
insert,
deletePackageName,
deletePackageId,
deleteDependency,
-- * Queries
-- ** Precise lookups
elemByPackageId,
elemByPackageName,
lookupPackageName,
lookupPackageId,
lookupDependency,
-- ** Case-insensitive searches
searchByName,
SearchResult(..),
searchByNameSubstring,
-- ** Bulk queries
allPackages,
allPackagesByName,
-- ** Special queries
brokenPackages,
dependencyClosure,
reverseDependencyClosure,
topologicalOrder,
reverseTopologicalOrder,
dependencyInconsistencies,
dependencyCycles,
dependencyGraph,
) where
import Prelude hiding (lookup)
import Control.Exception (assert)
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Tree as Tree
import qualified Data.Graph as Graph
import qualified Data.Array as Array
import Data.Array ((!))
import Data.List (groupBy, sortBy, nub, isInfixOf)
import Data.Monoid (Monoid(..))
import Data.Maybe (isJust, isNothing, fromMaybe, catMaybes)
import Distribution.Package
( PackageName(..), PackageIdentifier(..)
, Package(..), packageName, packageVersion
, Dependency(Dependency), PackageFixedDeps(..) )
import Distribution.Version
( Version, withinRange )
import Distribution.Simple.Utils (lowercase, equating, comparing)
-- | The collection of information about packages from one or more 'PackageDB's.
--
-- It can be searched effeciently by package name and version.
--
newtype PackageIndex pkg = PackageIndex
-- This index package names to all the package records matching that package
-- name case-sensitively. It includes all versions.
--
-- This allows us to find all versions satisfying a dependency.
-- Most queries are a map lookup followed by a linear scan of the bucket.
--
(Map PackageName [pkg])
deriving (Show, Read)
instance Package pkg => Monoid (PackageIndex pkg) where
mempty = PackageIndex Map.empty
mappend = merge
--save one mappend with empty in the common case:
mconcat [] = mempty
mconcat xs = foldr1 mappend xs
invariant :: Package pkg => PackageIndex pkg -> Bool
invariant (PackageIndex m) = all (uncurry goodBucket) (Map.toList m)
where
goodBucket _ [] = False
goodBucket name (pkg0:pkgs0) = check (packageId pkg0) pkgs0
where
check pkgid [] = packageName pkgid == name
check pkgid (pkg':pkgs) = packageName pkgid == name
&& pkgid < pkgid'
&& check pkgid' pkgs
where pkgid' = packageId pkg'
--
-- * Internal helpers
--
mkPackageIndex :: Package pkg => Map PackageName [pkg] -> PackageIndex pkg
mkPackageIndex index = assert (invariant (PackageIndex index))
(PackageIndex index)
internalError :: String -> a
internalError name = error ("PackageIndex." ++ name ++ ": internal error")
-- | Lookup a name in the index to get all packages that match that name
-- case-sensitively.
--
lookup :: Package pkg => PackageIndex pkg -> PackageName -> [pkg]
lookup (PackageIndex m) name = fromMaybe [] $ Map.lookup name m
--
-- * Construction
--
-- | Build an index out of a bunch of packages.
--
-- If there are duplicates, later ones mask earlier ones.
--
fromList :: Package pkg => [pkg] -> PackageIndex pkg
fromList pkgs = mkPackageIndex
. Map.map fixBucket
. Map.fromListWith (++)
$ [ (packageName pkg, [pkg])
| pkg <- pkgs ]
where
fixBucket = -- out of groups of duplicates, later ones mask earlier ones
-- but Map.fromListWith (++) constructs groups in reverse order
map head
-- Eq instance for PackageIdentifier is wrong, so use Ord:
. groupBy (\a b -> EQ == comparing packageId a b)
-- relies on sortBy being a stable sort so we
-- can pick consistently among duplicates
. sortBy (comparing packageId)
--
-- * Updates
--
-- | Merge two indexes.
--
-- Packages from the second mask packages of the same exact name
-- (case-sensitively) from the first.
--
merge :: Package pkg => PackageIndex pkg -> PackageIndex pkg -> PackageIndex pkg
merge i1@(PackageIndex m1) i2@(PackageIndex m2) =
assert (invariant i1 && invariant i2) $
mkPackageIndex (Map.unionWith mergeBuckets m1 m2)
-- | Elements in the second list mask those in the first.
mergeBuckets :: Package pkg => [pkg] -> [pkg] -> [pkg]
mergeBuckets [] ys = ys
mergeBuckets xs [] = xs
mergeBuckets xs@(x:xs') ys@(y:ys') =
case packageId x `compare` packageId y of
GT -> y : mergeBuckets xs ys'
EQ -> y : mergeBuckets xs' ys'
LT -> x : mergeBuckets xs' ys
-- | Inserts a single package into the index.
--
-- This is equivalent to (but slightly quicker than) using 'mappend' or
-- 'merge' with a singleton index.
--
insert :: Package pkg => pkg -> PackageIndex pkg -> PackageIndex pkg
insert pkg (PackageIndex index) = mkPackageIndex $
Map.insertWith (\_ -> insertNoDup) (packageName pkg) [pkg] index
where
pkgid = packageId pkg
insertNoDup [] = [pkg]
insertNoDup pkgs@(pkg':pkgs') = case compare pkgid (packageId pkg') of
LT -> pkg : pkgs
EQ -> pkg : pkgs'
GT -> pkg' : insertNoDup pkgs'
-- | Internal delete helper.
--
delete :: Package pkg => PackageName -> (pkg -> Bool) -> PackageIndex pkg -> PackageIndex pkg
delete name p (PackageIndex index) = mkPackageIndex $
Map.update filterBucket name index
where
filterBucket = deleteEmptyBucket
. filter (not . p)
deleteEmptyBucket [] = Nothing
deleteEmptyBucket remaining = Just remaining
-- | Removes a single package from the index.
--
deletePackageId :: Package pkg => PackageIdentifier -> PackageIndex pkg -> PackageIndex pkg
deletePackageId pkgid =
delete (packageName pkgid) (\pkg -> packageId pkg == pkgid)
-- | Removes all packages with this (case-sensitive) name from the index.
--
deletePackageName :: Package pkg => PackageName -> PackageIndex pkg -> PackageIndex pkg
deletePackageName name =
delete name (\pkg -> packageName pkg == name)
-- | Removes all packages satisfying this dependency from the index.
--
deleteDependency :: Package pkg => Dependency -> PackageIndex pkg -> PackageIndex pkg
deleteDependency (Dependency name verstionRange) =
delete name (\pkg -> packageVersion pkg `withinRange` verstionRange)
--
-- * Bulk queries
--
-- | Get all the packages from the index.
--
allPackages :: Package pkg => PackageIndex pkg -> [pkg]
allPackages (PackageIndex m) = concat (Map.elems m)
-- | Get all the packages from the index.
--
-- They are grouped by package name, case-sensitively.
--
allPackagesByName :: Package pkg => PackageIndex pkg -> [[pkg]]
allPackagesByName (PackageIndex m) = Map.elems m
--
-- * Lookups
--
elemByPackageId :: Package pkg => PackageIndex pkg -> PackageIdentifier -> Bool
elemByPackageId index = isJust . lookupPackageId index
elemByPackageName :: Package pkg => PackageIndex pkg -> PackageName -> Bool
elemByPackageName index = not . null . lookupPackageName index
-- | Does a lookup by package id (name & version).
--
-- Since multiple package DBs mask each other case-sensitively by package name,
-- then we get back at most one package.
--
lookupPackageId :: Package pkg => PackageIndex pkg -> PackageIdentifier -> Maybe pkg
lookupPackageId index pkgid =
case [ pkg | pkg <- lookup index (packageName pkgid)
, packageId pkg == pkgid ] of
[] -> Nothing
[pkg] -> Just pkg
_ -> internalError "lookupPackageIdentifier"
-- | Does a case-sensitive search by package name.
--
lookupPackageName :: Package pkg => PackageIndex pkg -> PackageName -> [pkg]
lookupPackageName index name =
[ pkg | pkg <- lookup index name
, packageName pkg == name ]
-- | Does a case-sensitive search by package name and a range of versions.
--
-- We get back any number of versions of the specified package name, all
-- satisfying the version range constraint.
--
lookupDependency :: Package pkg => PackageIndex pkg -> Dependency -> [pkg]
lookupDependency index (Dependency name versionRange) =
[ pkg | pkg <- lookup index name
, packageName pkg == name
, packageVersion pkg `withinRange` versionRange ]
--
-- * Case insensitive name lookups
--
-- | Does a case-insensitive search by package name.
--
-- If there is only one package that compares case-insentiviely to this name
-- then the search is unambiguous and we get back all versions of that package.
-- If several match case-insentiviely but one matches exactly then it is also
-- unambiguous.
--
-- If however several match case-insentiviely and none match exactly then we
-- have an ambiguous result, and we get back all the versions of all the
-- packages. The list of ambiguous results is split by exact package name. So
-- it is a non-empty list of non-empty lists.
--
searchByName :: Package pkg => PackageIndex pkg
-> String -> [(PackageName, [pkg])]
searchByName (PackageIndex m) name =
[ pkgs
| pkgs@(PackageName name',_) <- Map.toList m
, lowercase name' == lname ]
where
lname = lowercase name
data SearchResult a = None | Unambiguous a | Ambiguous [a]
-- | Does a case-insensitive substring search by package name.
--
-- That is, all packages that contain the given string in their name.
--
searchByNameSubstring :: Package pkg => PackageIndex pkg
-> String -> [(PackageName, [pkg])]
searchByNameSubstring (PackageIndex m) searchterm =
[ pkgs
| pkgs@(PackageName name, _) <- Map.toList m
, lsearchterm `isInfixOf` lowercase name ]
where
lsearchterm = lowercase searchterm
--
-- * Special queries
--
-- | All packages that have dependencies that are not in the index.
--
-- Returns such packages along with the dependencies that they're missing.
--
brokenPackages :: PackageFixedDeps pkg
=> PackageIndex pkg
-> [(pkg, [PackageIdentifier])]
brokenPackages index =
[ (pkg, missing)
| pkg <- allPackages index
, let missing = [ pkg' | pkg' <- depends pkg
, isNothing (lookupPackageId index pkg') ]
, not (null missing) ]
-- | Tries to take the transitive closure of the package dependencies.
--
-- If the transitive closure is complete then it returns that subset of the
-- index. Otherwise it returns the broken packages as in 'brokenPackages'.
--
-- * Note that if the result is @Right []@ it is because at least one of
-- the original given 'PackageIdentifier's do not occur in the index.
--
dependencyClosure :: PackageFixedDeps pkg
=> PackageIndex pkg
-> [PackageIdentifier]
-> Either (PackageIndex pkg)
[(pkg, [PackageIdentifier])]
dependencyClosure index pkgids0 = case closure mempty [] pkgids0 of
(completed, []) -> Left completed
(completed, _) -> Right (brokenPackages completed)
where
closure completed failed [] = (completed, failed)
closure completed failed (pkgid:pkgids) = case lookupPackageId index pkgid of
Nothing -> closure completed (pkgid:failed) pkgids
Just pkg -> case lookupPackageId completed (packageId pkg) of
Just _ -> closure completed failed pkgids
Nothing -> closure completed' failed pkgids'
where completed' = insert pkg completed
pkgids' = depends pkg ++ pkgids
-- | Takes the transitive closure of the packages reverse dependencies.
--
-- * The given 'PackageIdentifier's must be in the index.
--
reverseDependencyClosure :: PackageFixedDeps pkg
=> PackageIndex pkg
-> [PackageIdentifier]
-> [pkg]
reverseDependencyClosure index =
map vertexToPkg
. concatMap Tree.flatten
. Graph.dfs reverseDepGraph
. map (fromMaybe noSuchPkgId . pkgIdToVertex)
where
(depGraph, vertexToPkg, pkgIdToVertex) = dependencyGraph index
reverseDepGraph = Graph.transposeG depGraph
noSuchPkgId = error "reverseDependencyClosure: package is not in the graph"
topologicalOrder :: PackageFixedDeps pkg => PackageIndex pkg -> [pkg]
topologicalOrder index = map toPkgId
. Graph.topSort
$ graph
where (graph, toPkgId, _) = dependencyGraph index
reverseTopologicalOrder :: PackageFixedDeps pkg => PackageIndex pkg -> [pkg]
reverseTopologicalOrder index = map toPkgId
. Graph.topSort
. Graph.transposeG
$ graph
where (graph, toPkgId, _) = dependencyGraph index
-- | Given a package index where we assume we want to use all the packages
-- (use 'dependencyClosure' if you need to get such a index subset) find out
-- if the dependencies within it use consistent versions of each package.
-- Return all cases where multiple packages depend on different versions of
-- some other package.
--
-- Each element in the result is a package name along with the packages that
-- depend on it and the versions they require. These are guaranteed to be
-- distinct.
--
dependencyInconsistencies :: PackageFixedDeps pkg
=> PackageIndex pkg
-> [(PackageName, [(PackageIdentifier, Version)])]
dependencyInconsistencies index =
[ (name, inconsistencies)
| (name, uses) <- Map.toList inverseIndex
, let inconsistencies = duplicatesBy uses
versions = map snd inconsistencies
, reallyIsInconsistent name (nub versions) ]
where inverseIndex = Map.fromListWith (++)
[ (packageName dep, [(packageId pkg, packageVersion dep)])
| pkg <- allPackages index
, dep <- depends pkg ]
duplicatesBy = (\groups -> if length groups == 1
then []
else concat groups)
. groupBy (equating snd)
. sortBy (comparing snd)
reallyIsInconsistent :: PackageName -> [Version] -> Bool
reallyIsInconsistent _ [] = False
reallyIsInconsistent name [v1, v2] =
case (mpkg1, mpkg2) of
(Just pkg1, Just pkg2) -> pkgid1 `notElem` depends pkg2
&& pkgid2 `notElem` depends pkg1
_ -> True
where
pkgid1 = PackageIdentifier name v1
pkgid2 = PackageIdentifier name v2
mpkg1 = lookupPackageId index pkgid1
mpkg2 = lookupPackageId index pkgid2
reallyIsInconsistent _ _ = True
-- | Find if there are any cycles in the dependency graph. If there are no
-- cycles the result is @[]@.
--
-- This actually computes the strongly connected components. So it gives us a
-- list of groups of packages where within each group they all depend on each
-- other, directly or indirectly.
--
dependencyCycles :: PackageFixedDeps pkg
=> PackageIndex pkg
-> [[pkg]]
dependencyCycles index =
[ vs | Graph.CyclicSCC vs <- Graph.stronglyConnComp adjacencyList ]
where
adjacencyList = [ (pkg, packageId pkg, depends pkg)
| pkg <- allPackages index ]
-- | Builds a graph of the package dependencies.
--
-- Dependencies on other packages that are not in the index are discarded.
-- You can check if there are any such dependencies with 'brokenPackages'.
--
dependencyGraph :: PackageFixedDeps pkg
=> PackageIndex pkg
-> (Graph.Graph,
Graph.Vertex -> pkg,
PackageIdentifier -> Maybe Graph.Vertex)
dependencyGraph index = (graph, vertexToPkg, pkgIdToVertex)
where
graph = Array.listArray bounds $
map (catMaybes . map pkgIdToVertex . depends) pkgs
vertexToPkg vertex = pkgTable ! vertex
pkgIdToVertex = binarySearch 0 topBound
pkgTable = Array.listArray bounds pkgs
pkgIdTable = Array.listArray bounds (map packageId pkgs)
pkgs = sortBy (comparing packageId) (allPackages index)
topBound = length pkgs - 1
bounds = (0, topBound)
binarySearch a b key
| a > b = Nothing
| otherwise = case compare key (pkgIdTable ! mid) of
LT -> binarySearch a (mid-1) key
EQ -> Just mid
GT -> binarySearch (mid+1) b key
where mid = (a + b) `div` 2
|
jwiegley/ghc-release
|
libraries/Cabal/cabal-install/Distribution/Client/PackageIndex.hs
|
gpl-3.0
| 16,943 | 0 | 16 | 4,259 | 3,710 | 1,997 | 1,713 | 261 | 5 |
module Abstract.Constraint
( AtomicConstraint (..)
, buildNamedAtomicConstraint
, satisfiesAtomicConstraint
, satisfiesAllAtomicConstraints
, Constraint (..)
, satisfiesConstraint
, satisfiesAllConstraints
) where
import Abstract.Category
import Abstract.Category.FindMorphism
import Base.Valid
data AtomicConstraint morph = AtomicConstraint {
name :: String,
morphism :: morph,
positive :: Bool
} deriving (Show)
instance Valid morph => Valid (AtomicConstraint morph) where
validate = validate . morphism
buildNamedAtomicConstraint :: String -> morph -> Bool -> AtomicConstraint morph
buildNamedAtomicConstraint = AtomicConstraint
premise :: (Category morph) => AtomicConstraint morph -> Obj morph
premise = domain . morphism
conclusion :: (Category morph) => AtomicConstraint morph -> Obj morph
conclusion = codomain . morphism
-- | Given an object @G@ and a AtomicConstraint @a : P -> C@, check whether @G@ satisfies the AtomicConstraint @a@
satisfiesAtomicConstraint :: (FindMorphism morph) => Obj morph -> AtomicConstraint morph -> Bool
satisfiesAtomicConstraint object constraint = Prelude.null ps || allPremisesAreSatisfied
where
ps = findMonomorphisms (premise constraint) object
qs = findMonomorphisms (conclusion constraint) object
a = morphism constraint
positiveSatisfaction = all (\p -> any (\q -> q <&> a == p) qs) ps
negativeSatisfaction = all (\p -> not $ any (\q -> q <&> a == p) qs) ps
allPremisesAreSatisfied = if positive constraint then positiveSatisfaction else negativeSatisfaction
-- | Given an object @G@ and a list of AtomicConstraints @a : P -> C@, check whether @G@ satisfies the all them
satisfiesAllAtomicConstraints :: (FindMorphism morph) => Obj morph -> [AtomicConstraint morph] -> Bool
satisfiesAllAtomicConstraints object = all (satisfiesAtomicConstraint object)
data Constraint morph =
Atomic (AtomicConstraint morph)
| And (Constraint morph) (Constraint morph)
| Or (Constraint morph) (Constraint morph)
| Not (Constraint morph)
deriving (Show)
instance Valid morph => Valid (Constraint morph) where
validate cons = case cons of
Atomic a -> validate a
Not b -> validate b
And a b -> mconcat [validate a, validate b]
Or a b -> mconcat [validate a, validate b]
-- | Given an object @G@ and a Constraint @c@ (a Boolean formula over atomic constraints), check whether @G@ satisfies @c@
satisfiesConstraint :: (FindMorphism morph) => Obj morph -> Constraint morph -> Bool
satisfiesConstraint object constraint =
case constraint of
Atomic atomic -> satisfiesAtomicConstraint object atomic
Not nc -> not $ satisfiesConstraint object nc
And lc rc -> satisfiesConstraint object lc && satisfiesConstraint object rc
Or lc rc -> satisfiesConstraint object lc || satisfiesConstraint object rc
-- | Given an object @G@ and a list of Constraints (Boolean formulas over atomic constraints), check whether @G@ satisfies the all them
satisfiesAllConstraints :: (FindMorphism morph) => Obj morph -> [Constraint morph] -> Bool
satisfiesAllConstraints object = all (satisfiesConstraint object)
|
rodrigo-machado/verigraph
|
src/library/Abstract/Constraint.hs
|
gpl-3.0
| 3,201 | 0 | 15 | 615 | 801 | 414 | 387 | 55 | 4 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="el-GR">
<title>Export Report | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/exportreport/src/main/javahelp/org/zaproxy/zap/extension/exportreport/resources/help_el_GR/helpset_el_GR.hs
|
apache-2.0
| 975 | 89 | 29 | 160 | 398 | 213 | 185 | -1 | -1 |
-- These types follow the format of Twitter search results, as can be
-- found in the benchmarks/json-data directory.
--
-- For uses of these types, see the Twitter subdirectory.
--
-- There is one deviation for the sake of convenience: the Geo field
-- named "type_" is really named "type" in Twitter's real feed. I
-- renamed "type" to "type_" in the *.json files, to avoid overlap
-- with a Haskell reserved keyword.
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Twitter
(
Metadata(..)
, Geo(..)
, Story(..)
, Result(..)
) where
import Prelude.Compat
import Control.DeepSeq
import Data.Data (Typeable, Data)
import Data.Int (Int64)
import Data.Text (Text)
import GHC.Generics (Generic)
newtype Metadata = Metadata {
result_type :: Text
} deriving (Eq, Show, Typeable, Data, Generic)
instance NFData Metadata
data Geo = Geo {
type_ :: Text
, coordinates :: (Double, Double)
} deriving (Eq, Show, Typeable, Data, Generic)
instance NFData Geo
data Story = Story {
from_user_id_str :: Text
, profile_image_url :: Text
, created_at :: Text -- ZonedTime
, from_user :: Text
, id_str :: Text
, metadata :: Metadata
, to_user_id :: Maybe Int64
, text :: Text
, id_ :: Int64
, from_user_id :: Int64
, geo :: Maybe Geo
, iso_language_code :: Text
, to_user_id_str :: Maybe Text
, source :: Text
} deriving (Show, Typeable, Data, Generic)
instance NFData Story
data Result = Result {
results :: [Story]
, max_id :: Int64
, since_id :: Int64
, refresh_url :: Text
, next_page :: Text
, results_per_page :: Int
, page :: Int
, completed_in :: Double
, since_id_str :: Text
, max_id_str :: Text
, query :: Text
} deriving (Show, Typeable, Data, Generic)
instance NFData Result
|
dmjio/aeson
|
examples/src/Twitter.hs
|
bsd-3-clause
| 2,025 | 0 | 9 | 583 | 432 | 266 | 166 | 55 | 0 |
{-# OPTIONS_GHC -Wall #-}
module Canonicalize.Body (flatten) where
import qualified Data.Maybe as Maybe
import qualified AST.Declaration as Decl
import qualified AST.Effects as Effects
import qualified AST.Expression.General as E
import qualified AST.Expression.Canonical as Canonical
import qualified AST.Module.Name as ModuleName
import qualified AST.Pattern as P
import qualified AST.Type as Type
import qualified AST.Variable as Var
import qualified Canonicalize.Sort as Sort
import qualified Reporting.Annotation as A
import qualified Reporting.Region as R
flatten :: ModuleName.Canonical -> Decl.Canonical -> Effects.Canonical -> Canonical.Expr
flatten moduleName (Decl.Decls defs unions aliases _) effects =
let
allDefs =
concat
[ concatMap (unionToDefs moduleName) unions
, Maybe.mapMaybe (aliasToDefs moduleName) aliases
, effectsToDefs moduleName effects
, map A.drop defs
]
loc =
A.A (error "this annotation should never be needed")
in
Sort.definitions $ loc $
E.Let allDefs (loc $ E.SaveEnv moduleName effects)
-- TYPES TO DEFS
unionToDefs :: ModuleName.Canonical -> A.Commented (Decl.Union Type.Canonical) -> [Canonical.Def]
unionToDefs moduleName (A.A (region,_) (Decl.Type name tvars constructors)) =
let
tagToDef (tag, tipes) =
let
vars =
take (length tipes) infiniteArgs
tbody =
Type.App
(Type.Type (Var.fromModule moduleName name))
(map Type.Var tvars)
body =
A.A region $
E.Data tag (map (A.A region . E.localVar) vars)
in
definition tag (buildFunction vars body) region (foldr Type.Lambda tbody tipes)
in
map tagToDef constructors
aliasToDefs :: ModuleName.Canonical -> A.Commented (Decl.Alias Type.Canonical) -> Maybe Canonical.Def
aliasToDefs moduleName (A.A (region,_) (Decl.Type name tvars tipe)) =
case tipe of
Type.Record fields Nothing ->
let
resultType =
Type.Aliased
(Var.fromModule moduleName name)
(zip tvars (map Type.Var tvars))
(Type.Holey tipe)
args =
map snd fields
vars =
take (length args) infiniteArgs
record =
A.A region $
E.Record (zip (map fst fields) (map (A.A region . E.localVar) vars))
in
Just $ definition name (buildFunction vars record) region (foldr Type.Lambda resultType args)
_ ->
Nothing
infiniteArgs :: [String]
infiniteArgs =
map (:[]) ['a'..'z'] ++ map (\n -> "_" ++ show (n :: Int)) [1..]
buildFunction :: [String] -> Canonical.Expr -> Canonical.Expr
buildFunction vars body@(A.A ann _) =
foldr
(\pattern expr -> A.A ann (E.Lambda pattern expr))
body
(map (A.A ann . P.Var) vars)
definition :: String -> Canonical.Expr -> R.Region -> Type.Canonical -> Canonical.Def
definition name expr@(A.A ann _) region tipe =
Canonical.Def
Canonical.dummyFacts
(A.A ann (P.Var name))
expr
(Just (A.A region tipe))
-- EFFECTS
effectsToDefs :: ModuleName.Canonical -> Effects.Canonical -> [Canonical.Def]
effectsToDefs moduleName effects =
case effects of
Effects.None ->
[]
Effects.Port ports ->
map portToDef ports
Effects.Manager _ info ->
let
cmdToDef (A.A region name) =
definition
"command"
(A.A region (E.Cmd moduleName))
region
(Type.cmd moduleName name)
subToDef (A.A region name) =
definition
"subscription"
(A.A region (E.Sub moduleName))
region
(Type.sub moduleName name)
in
case Effects._managerType info of
Effects.CmdManager cmd ->
[ cmdToDef cmd
]
Effects.SubManager sub ->
[ subToDef sub
]
Effects.FxManager cmd sub ->
[ cmdToDef cmd
, subToDef sub
]
portToDef :: A.Commented Effects.PortCanonical -> Canonical.Def
portToDef (A.A (region, _) (Effects.PortCanonical name kind tipe)) =
definition name (A.A region (toPortExpr name kind)) region tipe
toPortExpr :: String -> Effects.Kind -> Canonical.Expr'
toPortExpr name kind =
case kind of
Effects.Outgoing tipe ->
E.OutgoingPort name tipe
Effects.Incoming tipe ->
E.IncomingPort name tipe
|
mgold/Elm
|
src/Canonicalize/Body.hs
|
bsd-3-clause
| 4,443 | 0 | 21 | 1,247 | 1,444 | 747 | 697 | 118 | 5 |
module Main where
import Data.Time
showTZ :: TimeZone -> String
showTZ tz = (formatTime defaultTimeLocale "%Z %z" tz) ++ (if timeZoneSummerOnly tz then " DST" else "")
main :: IO ()
main = mapM_ (\tz -> putStrLn (showTZ tz)) (knownTimeZones defaultTimeLocale)
|
bergmark/time
|
test/ShowDefaultTZAbbreviations.hs
|
bsd-3-clause
| 263 | 0 | 10 | 44 | 97 | 52 | 45 | 6 | 2 |
{-# LANGUAGE NoMonomorphismRestriction #-}
import System.Posix
import Control.Monad
import Foreign
import Control.Concurrent
import Data.Char
import System.Exit
size = 10000
block = 512
main = do
(rd,wr) <- createPipe
let bytes = take size (map (fromIntegral.ord) (cycle ['a'..'z']))
allocaBytes size $ \p -> do
pokeArray p bytes
forkIO $ do r <- fdWriteBuf wr p (fromIntegral size)
when (fromIntegral r /= size) $ error "fdWriteBuf failed"
allocaBytes block $ \p -> do
let loop text = do
r <- fdReadBuf rd p block
let (chunk,rest) = splitAt (fromIntegral r) text
chars <- peekArray (fromIntegral r) p
when (chars /= chunk) $ error "mismatch"
when (null rest) $ exitWith ExitSuccess
loop rest
loop bytes
|
jimenezrick/unix
|
tests/fdReadBuf001.hs
|
bsd-3-clause
| 813 | 0 | 21 | 221 | 306 | 145 | 161 | 25 | 1 |
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
-- This one foxed the constraint solver (Lint error)
-- See Trac #1494
module ShouldCompile where
import Control.Monad.State
newtype L m r = L (StateT Int m r)
instance Functor (L m) where
fmap = undefined
instance Applicative (L m) where
pure = undefined
(<*>) = undefined
instance Monad m => Monad (L m) where
(>>=) = undefined
return = undefined
zork :: (Monad m) => a -> L m ()
zork = undefined
mumble e = do { modify id; zork e }
|
urbanslug/ghc
|
testsuite/tests/typecheck/should_compile/tc232.hs
|
bsd-3-clause
| 509 | 0 | 8 | 110 | 164 | 92 | 72 | 15 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE RankNTypes #-}
{-# OPTIONS_GHC -Wall #-}
module T10931 ( BugC(..) ) where
data IdT f a = IdC (f a)
class ( m ~ Outer m (Inner m) ) => BugC (m :: * -> *) where
type Inner m :: * -> *
type Outer m :: (* -> *) -> * -> *
bug :: ( forall n. ( n ~ Outer n (Inner n)
, Outer n ~ Outer m
)
=> Inner n a)
-> m a
instance BugC (IdT m) where
type Inner (IdT m) = m
type Outer (IdT m) = IdT
bug f = IdC f
|
ezyang/ghc
|
testsuite/tests/indexed-types/should_compile/T10931.hs
|
bsd-3-clause
| 567 | 0 | 15 | 210 | 224 | 122 | 102 | 17 | 0 |
{-# LANGUAGE ScopedTypeVariables, RankNTypes #-}
-- Helper for simpl009.hs (see comments there)
module Simpl009Help where
import Control.Applicative (Applicative(..), Alternative(empty, (<|>)))
import Control.Monad
newtype Parser s a
= Parser (forall res . (a -> [String] -> P s res) -> [String] -> P s res)
data P s res
= Symbol (s -> P s res)
| Fail [String] [String]
| Result res (P s res)
instance Functor (Parser s) where
fmap = liftM
instance Applicative (Parser s) where
pure = return
(<*>) = ap
instance Monad (Parser s) where
return a = Parser (\fut -> fut a)
Parser f >>= k =
Parser (\fut -> f (\a -> let Parser g = k a in g fut))
fail s =
Parser (\fut exp -> Fail exp [s])
instance Alternative (Parser s) where
empty = mzero
(<|>) = mplus
instance MonadPlus (Parser s) where
mplus = error "urk"
mzero = Parser (\fut exp -> Fail exp [])
lookAhead :: forall s. Parser s s
lookAhead =
Parser (\fut exp -> Symbol (\c ->
feed c (fut c [])
))
where
feed :: forall res. s -> P s res -> P s res
feed c (Symbol sym) = sym c
feed c (Result res fut) = Result res (feed c fut)
feed c p@(Fail _ _) = p
|
siddhanathan/ghc
|
testsuite/tests/simplCore/prog002/Simpl009Help.hs
|
bsd-3-clause
| 1,188 | 0 | 16 | 305 | 540 | 289 | 251 | 35 | 3 |
module Mod157_B (T(..)) where
import Mod157_A(T(A))
|
urbanslug/ghc
|
testsuite/tests/module/Mod157_B.hs
|
bsd-3-clause
| 53 | 0 | 6 | 7 | 25 | 17 | 8 | 2 | 0 |
{-# htermination (numerator :: Ratio MyInt -> MyInt) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data MyInt = Pos Nat | Neg Nat ;
data Nat = Succ Nat | Zero ;
data Ratio a = CnPc a a;
numerator (CnPc x y) = x;
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/basic_haskell/numerator_1.hs
|
mit
| 273 | 0 | 8 | 69 | 95 | 56 | 39 | 7 | 1 |
module Main (main) where
import QuickCheckProperties ( bddTests )
import TestSuite ( runTestWith )
import Test.QuickCheck ( Args, stdArgs, maxSize, maxSuccess, maxDiscard )
import System.Environment ( getArgs, getProgName )
import System.Exit ( exitFailure )
import System.IO ( stderr )
import Text.Printf ( hPrintf )
main :: IO ()
main = do
numQCTests <- parseArgs
let qcArgs = stdArgs { maxSize = 250
, maxSuccess = numQCTests
, maxDiscard = numQCTests
}
runTestWith qcArgs bddTests
parseArgs :: IO Int
parseArgs = do
args <- getArgs
case args of
[] -> return 100
[nt] -> case reads nt of
[(i, "")] -> return i
_ -> usage
_ -> usage
usage :: IO a
usage = do
pName <- getProgName
_ <- hPrintf stderr "usage: %s NUM_TESTS\n" pName
exitFailure
|
bradlarsen/bdd
|
hs-bdd-test/Test.hs
|
mit
| 918 | 0 | 14 | 302 | 270 | 146 | 124 | 29 | 4 |
module Cycles.Reap where
import Cycles.Aux (trim, orientGraph)
import Cycles.IO
--import Data.GList
import Control.Monad (mapM_, unless, liftM2, when)
import Data.Foldable (foldlM)
import Data.List (reverse)
import Data.ByteString (hGetContents, readFile, writeFile, init, tail, ByteString)--(readFile, null, ByteString, read, init, tail, split, first, last)
import qualified Data.ByteString.Char8 as C8
import System.Directory (renameFile, getDirectoryContents)
import System.IO
import Debug.Trace (traceShow) -- debug lines marked DEBUG
--import qualified Prelude as P
-- Here are the functions for reaping the results of computing the maximally cyclic orientations of various graphs.
-- This includes functions for:
-- trimming all results in a directory
-- checking all results in a directory
-- collecing all results, given a list (GList) of names associated with each graph
-- Since the outlines are fixed length, I could just detect the length of one and then easily filter/parse the rest...
-- How about read/write where I get the second line, detect length -> find range in which there's a solution, skip to last result and get bestval
-- then iterate through lines replacing the non-best lines with all 0's (except the '\n's). next, collect all chars, skipping 0's or '\n's that are
-- two in a row.
trimAllResults :: String -> IO ()
trimAllResults dir = do
files <- getDirectoryContents dir
let resultFiles = Prelude.filter isresult files
mapM_ trimResult resultFiles
where
isresult name = isgraph name && istxt name
isgraph name = Prelude.take 8 name == "graphNum"
istxt name = Prelude.take 3 (Data.List.reverse name) == "txt"
-- | This function trims a single result (removes all non-optimal values and saves the file)
trimResult :: FilePath -> IO ()
trimResult filename = do
--filestr <- catch (readFile filename) handler -- <- openFile filename ReadWriteMode
-- file <- Data.ByteString.readFile filename :: IO ByteString
handle <- openFile filename ReadMode
file <- Data.ByteString.hGetContents handle
Data.ByteString.writeFile tempFileName $ trimByteStringResult file
removeIfExists filename
renameFile tempFileName filename
where
tempFileName = filename ++ "_temp"
-- where
-- handler :: SomeException -> IO String
-- handler _ = error "The results have disappeared under my nose."
trimBS = Data.ByteString.init . Data.ByteString.tail
justThat (Just x) = x
justThat Nothing = error "some Int I was supposed to read was nothing"
trimSpaces :: ByteString -> ByteString
trimSpaces = C8.filter (/= ' ')
trimNulls = C8.filter (/= '\NUL')
cutAfterComma :: ByteString -> ByteString
cutAfterComma bstr
| C8.null bstr = C8.empty
| C8.head bstr == ',' = C8.tail bstr
| otherwise = cutAfterComma $ C8.tail bstr
parseSolution :: ByteString -> Int
parseSolution solution
| C8.null solution = 0
| otherwise = fst $ justThat $ C8.readInt $ trimSpaces $ C8.init $ cutAfterComma solution
-- | otherwise = readSoln $ C8.unpack $ C8.init $ cutAfterComma solution
where
-- readSoln bstr = read bstr :: Int
trimByteStringResult :: ByteString -> ByteString
trimByteStringResult results = if finished then trimNulls $ C8.unlines (graph ++ filtered ++ [C8.pack "FINISHED."]) else results
where
filtered = Prelude.filter (\s ->parseSolution s == best) solutions
rlines = C8.lines results :: [ByteString]
graph = [Prelude.head rlines]
finished = Prelude.last rlines == C8.pack "\NULFINISHED." --error "somehow not read as finished"
solutions = if finished then Prelude.tail $ Prelude.init rlines else [] :: [ByteString]
best = parseSolution $ Prelude.last solutions
-- Here are the functions for collecting several outputs into one, consolidating, matching with something from GList,
-- converting binary orientations into digraphs, and outputting into a single file
-- justPosition :: Eq a => a -> [a] -> Int
-- justPosition e list
-- | Prelude.null list = error "none of these lists should be empty"
-- | Prelude.head list == e = 0
-- | otherwise = 1 + justPosition e (Prelude.tail list)
-- splitAt :: Char -> String -> [String]
-- splitAt c str
-- | c `notElem` str = [str]
-- | otherwise = fst splitted : Cycles.Reap.splitAt c (snd splitted)
-- where
-- splitted = Prelude.splitAt (1 + justPosition c str) str
cutUntilChar :: Char -> String -> String
cutUntilChar c str
| c `notElem` str = error "splitAt will only call this function if c is in the string, and now there is no c in the string"
| Prelude.head str == c = []
| otherwise = Prelude.head str : cutUntilChar c (Prelude.tail str)
cutAfterChar :: Char -> String -> String
cutAfterChar c str
| c `notElem` str = error "see error for cutUntilChar"
| Prelude.head str == c = Prelude.tail str
| otherwise = cutAfterChar c (Prelude.tail str)
splitAt :: Char -> String -> [String]
splitAt c str
| c `notElem` str = [str]
| otherwise = cutUntilChar c str : Cycles.Reap.splitAt c (cutAfterChar c str)
-- | 'collectBy' takes a checking function and a list and returns ([x | f x], [x | not f x])
collectBy :: (a -> Bool) -> [a] -> ([a],[a])
collectBy f = foldl collector ([],[])
where
-- collector :: ([a],[a]) -> a -> ([a],[a])
collector sofar next = if f next
then (next : fst sofar, snd sofar)
else (fst sofar, next : snd sofar)
onlyJustFst Nothing = error "failed to read number from graph result"
onlyJustFst (Just x) = fst x
-- | This function takes a maxcy filename and a list of files and outputs (matching graphs, non-matching graphs)
-- Note: This function throws out files that are part of an incomplete series.
-- For example, if we input graphNum_..._0_2_out.txt but don't have graphNum_..._1_2_out.txt,
-- the output will be of the form: ([], [leftovers])
collectMatchingGraphs :: FilePath -> [FilePath] -> ([FilePath], [FilePath])
collectMatchingGraphs graphname filelist = checkMatches collected
where
graphnum = splitname graphname !! 2 :: String
checkMatches (matches, leftover) = if length matches == onlyJustFst (C8.readInt (C8.pack (splitname graphname !! 4)))
then (matches, leftover)
else ([], leftover)
collected = collectBy (\l -> (splitname l !! 2) == graphnum) filelist :: ([String], [String])
-- splitname filename = Prelude.init $ splitAt_ (drop 9 filename) :: [String]-- [number of edges, graph number, nth, out of m]
splitname = splitAt_
splitAt_ = Cycles.Reap.splitAt '_'
-- | This will group results into a lists of matching results
groupMatchingGraphs :: [FilePath] -> [[FilePath]]
groupMatchingGraphs filelist
| null filelist = []
| otherwise = fst headCollected : groupMatchingGraphs (snd headCollected)
where
headCollected = collectMatchingGraphs (Prelude.head filelist) filelist
-- headCollected = collectMatchingGraphs (Prelude.head filelist) (Prelude.tail filelist)
-- The above wrong line caused a lot of pain debugging, as it resulted in no groups with more than one element,
-- while being a simple typo and collectMatchingGraphs working fine.
checkAllFinished :: [FilePath] -> IO Bool
checkAllFinished filelist = do
checks <- mapM checkOneFinished filelist
foldlM (\x y ->return $ x && y) True checks
where
checkOneFinished :: FilePath -> IO Bool
checkOneFinished file = do
handle <- openFile file ReadMode
contents <- Data.ByteString.hGetContents handle
let lastLine = Prelude.last $ C8.lines contents
return $ C8.elem 'F' lastLine && C8.elem 'D' lastLine
allEq :: Eq a => [a] -> Bool
allEq list
| length list < 2 = True
| head list == list !! 1 = allEq (Prelude.tail list)
| head list /= list !! 1 = False
checkAllMatching :: [FilePath] -> IO Bool
checkAllMatching filelist = do
checks <- mapM getHeader filelist
return $ allEq checks
where
getHeader :: FilePath -> IO ByteString
getHeader file = do
handle <- openFile file ReadMode
contents <- Data.ByteString.hGetContents handle
return $ Prelude.head $ C8.lines contents
-- | "xyMap f list" is equivalent to "zip (map f list) list".
-- Example: "xyMap (*2) [1,2,3] = [(1,2),(2,4),(3,6)]"
xyMap :: (a -> b) -> [a] -> [(a,b)]
xyMap f = map (\x ->(x, f x))
reapResult :: [FilePath] -> IO [ByteString]
reapResult [] = return [C8.empty]
reapResult filelist = do --when allGood (do
allFinished <- checkAllFinished filelist -- :: IO Bool
allMatching <- checkAllMatching filelist -- :: IO Bool
let allGood = allFinished && allMatching
-- unless allGood (error "somehow a bad solution file got in. (error passed from reapResult in Cycles.Reap)")
files <- mapM C8.readFile filelist :: IO [ByteString]
let graph = Prelude.head $ C8.lines $ Prelude.head files :: ByteString
let results = concatMap (trim . C8.lines) files :: [ByteString]
let parsedTuples = xyMap parseSolution results :: [(ByteString, Int)]
when (null (map snd parsedTuples)) (error "line 205")
let best = maximum $ map snd parsedTuples :: Int
let bestTuples = filter (\b ->snd b == best) parsedTuples :: [(ByteString, Int)]
let bests = map fst bestTuples :: [ByteString]
(sluiceByteStrings allGood) (graph : bests)
-- Here, convert graphs to digraphs
readBinList :: ByteString -> [Int]
readBinList bstr
| C8.null bstr = []
| C8.head bstr == '0' = 0 : readBinList (C8.tail bstr)
| C8.head bstr == '1' = 1 : readBinList (C8.tail bstr)
| otherwise = error "Attempted to read a binary list of form "0101010010" from a ByteString that contains characters other than '0' and '1'."
onlyJust Nothing = error "Input a ByteString without a proper number result into Cycles.Reap.processResult."
onlyJust (Just x) = fst x
processResult :: ByteString -> ([Int],Int)
processResult result = (list, number)
where
list = readBinList listBStr
listBStr = Prelude.head resultPair
number = onlyJust $ C8.readInt $ Prelude.head $ Prelude.tail resultPair
resultPair = C8.split ',' resultTrimmed
resultTrimmed = trimBS $ trimSpaces result
processGraph :: ByteString -> [[Int]]
processGraph bstr = read (C8.unpack bstr)
sluiceByteStrings :: Bool -> [ByteString] -> IO [ByteString]
sluiceByteStrings open bstr = if open then return bstr else return [C8.empty]
sluiceByteString :: Bool -> ByteString -> IO ByteString
sluiceByteString open bstr = if open then return bstr else return C8.empty
polishResult :: [ByteString] -> IO ByteString
polishResult resultList = do
when (Prelude.null resultList) (error "polishResult")
let rawGraph = Prelude.head resultList :: ByteString
let graph = processGraph rawGraph :: [[Int]]
let rawResults = Prelude.tail resultList :: [ByteString]
let processedResults = map processResult rawResults :: [([Int],Int)]
let digraphResults = map (\tup ->(orientGraph (fst tup) graph, snd tup)) processedResults :: [([[Int]],Int)]
checks <- mapM checkResult digraphResults
allGood <- foldlM (\x y ->return $ x && y) True checks
let finalResults = C8.unlines [rawGraph, showResults digraphResults]
sluiceByteString allGood finalResults
where
showResults :: [([[Int]],Int)] -> ByteString
showResults results = C8.unlines (map (C8.pack . show) results)
checkResult :: ([[Int]],Int) -> IO Bool
-- checkResult result = liftM2 (==) (graphToNumCycles (traceShow result (fst result)) True) (return (snd result))
checkResult result = liftM2 (==) (graphToNumCycles (fst result) True) (return (snd result))
-- DEBUG
reapAndPolishResult :: [FilePath] -> IO ByteString
reapAndPolishResult [] = return C8.empty
reapAndPolishResult fileList = do
when (length fileList < 1) (error "reapAndPolishResult1")
when (length (Prelude.head fileList) < 1) (error "reapAndPolishResult2")
let graphNum = read (Prelude.head $ Prelude.tail $ splitname (Prelude.head fileList)) :: Int
let graphName = fst $ gList !! graphNum
reapedResult <- reapResult fileList
polishedResult <- polishResult reapedResult
return $ C8.concat [C8.pack "[\"", C8.pack graphName, C8.pack "\",", polishedResult, C8.pack "]"]
where
splitname filename = Prelude.init $ splitAt_ (drop 9 filename) :: [String]-- [number of edges, graph number, nth, out of m]
splitAt_ = Cycles.Reap.splitAt '_'
reapAllResults :: FilePath -> FilePath -> IO ()
reapAllResults dir outFileName = do
files <- getDirectoryContents dir
let resultFiles = Prelude.filter isresult files
let graphGroups = groupMatchingGraphs resultFiles
-- putStrLn $ show $ map Prelude.length graphGroups
polishedResultsList <- mapM reapAndPolishResult graphGroups
let polishedResults = C8.unlines polishedResultsList
C8.writeFile outFileName polishedResults
where
isresult name = isgraph name && istxt name
isgraph name = Prelude.take 8 name == "graphNum"
istxt name = Prelude.take 3 (Data.List.reverse name) == "txt"
gList :: [(String, [[Int]])]
gList = map (\s -> (s, [[1]])) $ map show [0..]
|
michaeljklein/HCy2C
|
Cycles/Reap.hs
|
mit
| 13,037 | 0 | 16 | 2,519 | 3,428 | 1,754 | 1,674 | 188 | 3 |
module VideoCore.EGL where
import Foreign
import qualified VideoCore.Raw.EGL as EGLC
import qualified VideoCore.Raw.EGL.Platform as EGLCP
import Data.Array.Storable
type ClientVersion = EGLC.EGLint
getConfigs :: EGLC.Display -> EGLC.EGLint -> IO (EGLC.Boolean, EGLC.Config, EGLC.EGLint)
getConfigs display count = do
case count of
0 -> do
(r, c) <- getConfigCount display
return (r, nullPtr, c)
_ -> do
allocaBytes ((fromIntegral count) * 4) $ \configsP ->
alloca $ \countP -> do
r <- EGLC.getConfigs display configsP count countP
configsR <- peek configsP
countR <- peek countP
return (r, configsR, countR)
where
getConfigCount display = do
alloca $ \countP -> do
r <- EGLC.getConfigs display nullPtr 0 countP
countR <- peek countP
return (r, countR)
getConfigAttrib :: EGLC.Display -> EGLC.Config -> EGLC.EGLint -> IO (EGLC.Boolean, EGLC.EGLint)
getConfigAttrib disp cfg attr = do
alloca $ \valP -> do
r <- EGLC.getConfigAttrib disp cfg attr valP
valR <- peek valP
return (r, valR)
chooseConfig :: EGLC.Display -> [EGLC.EGLint] -> IO (EGLC.Boolean, EGLC.Config, EGLC.EGLint)
chooseConfig disp attrs = do
withArray attrs $ \attrsP ->
alloca $ \configP ->
alloca $ \countP -> do
r <- EGLC.chooseConfig disp attrsP configP 1 countP
configR <- peek configP
countR <- peek countP
return (r, configR, countR)
createContext :: EGLC.Display -> EGLC.Config -> EGLC.Context -> ClientVersion -> IO EGLC.Context
createContext d cfg ctx version =
withArray [ EGLC.contextClientVersion, version, EGLC.none ] $ \attrs ->
EGLC.createContext d cfg ctx attrs
createWindowSurface :: EGLC.Display -> EGLC.Config -> EGLCP.DispmanxWindow -> [EGLC.EGLint] -> IO EGLC.Surface
createWindowSurface d cfg w attrs =
with w $ \windowP -> do
r <- case null attrs of
True -> EGLC.createWindowSurface d cfg windowP nullPtr
False -> withArray attrs $ \attrsP ->
EGLC.createWindowSurface d cfg windowP attrsP
return r
|
Wollw/VideoCore-Haskell
|
src/VideoCore/EGL.hs
|
mit
| 2,284 | 0 | 20 | 676 | 736 | 372 | 364 | 51 | 2 |
module Exercise where
type Item a = (a, Int)
type Bag a = [Item a]
|
tcoenraad/functioneel-programmeren
|
2013/opg1a.hs
|
mit
| 68 | 0 | 6 | 16 | 30 | 20 | 10 | 3 | 0 |
module KleisliCategory where
import Data.Char (toUpper)
import Data.String (words)
-- Writer category
type Writer a = (a, String)
(>=>) :: (a -> Writer b) -> (b -> Writer c) -> (a -> Writer c)
m1 >=> m2 = \x ->
let (y, s1) = m1 x
(z, s2) = m2 y
in (z, s1 ++ s2)
return :: a -> Writer a
return x = (x, "")
upCase :: String -> Writer String
upCase s = (map toUpper s, "upCase ")
toWords :: String -> Writer [String]
toWords s = (words s, "toWords ")
process :: String -> Writer [String]
process = upCase >=> toWords
|
rockdragon/julia-programming
|
code/haskell/KleisliCategory.hs
|
mit
| 555 | 0 | 10 | 146 | 258 | 141 | 117 | 17 | 1 |
module Wobsurv.Util.OpenServer.Connection where
import BasePrelude hiding (Interrupted)
import Pipes
import Pipes.Safe hiding (handle)
import Control.Monad.Trans.Except
import Control.Monad.Trans.State
import Control.Monad.Trans.Maybe
import qualified Data.ByteString as ByteString
import qualified Network.Socket as Socket
import qualified Pipes.Network.TCP as PipesNetwork
type Timeout =
Int
type BS =
ByteString.ByteString
type Interactor =
Producer BS (SafeT IO) () -> Producer BS (SafeT IO) (Maybe Word)
session :: Timeout -> Interactor -> Socket.Socket -> IO ()
session initTimeout interactor socket =
handlingExceptions $ runSafeT $ runEffect $ loop initTimeout
where
loop timeout =
do
nextTimeout <- interactor request >-> response
traverse_ (loop . fromIntegral) nextTimeout
where
request =
PipesNetwork.fromSocketTimeout timeout socket 4096
response =
PipesNetwork.toSocketTimeout timeout socket
type Rejector =
Producer BS (SafeT IO) ()
rejection :: Timeout -> Rejector -> Socket.Socket -> IO ()
rejection timeout rejector socket =
handlingExceptions $ runSafeT $ runEffect $ do
-- Consume something to keep linux clients happy:
next $ PipesNetwork.fromSocketTimeout 500000 socket 512
rejector >-> PipesNetwork.toSocketTimeout timeout socket
handlingExceptions :: IO () -> IO ()
handlingExceptions =
handle $ \e ->
case ioeGetErrorType e of
ResourceVanished -> return ()
TimeExpired -> return ()
_ -> error $ "Wobsurv.Util.OpenServer.Connection.handlingExceptions: Unexpected IOException: " <> show e
|
nikita-volkov/wobsurv
|
library/Wobsurv/Util/OpenServer/Connection.hs
|
mit
| 1,650 | 0 | 11 | 331 | 432 | 230 | 202 | 41 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : Parser.Location
-- Description : Source location and span information
-- Maintainer : [email protected]
-- Stability : experimental
-----------------------------------------------------------------------------
module Parser.Location
(
-- * Source location
SrcLoc
, makeSrcLoc
, srcFile, srcAbs, srcLine, srcCol
-- * Source span
, SrcSpan
, makeSrcSpan
, srcLocSpan
, makeSrcSpanLength, makeSrcSpanLengthEnd
, mergeSrcSpan
, spanFile, spanSLine, spanSCol, spanELine, spanECol
-- * Types with location information
, Located (..)
, mergeLocated
, Loc
, makeLoc, unLoc
) where
import Text.PrettyPrint
import Text.PrettyPrint.HughesPJClass (Pretty (..), prettyShow)
-- | Represents a single point within a file. Refer to 'locInvariant'.
data SrcLoc = SrcLoc
{ srcFile :: !FilePath -- ^ path to the source file
, srcAbs :: !Int -- ^ absolute character offset
, srcLine :: !Int -- ^ line number, counting from 1
, srcCol :: !Int -- ^ column number, counting from 1
}
deriving (Eq, Ord)
-- | Construct a 'SrcLoc' given the file, absolute character offset,
-- line number, and column number
makeSrcLoc :: FilePath -> Int -> Int -> Int -> SrcLoc
makeSrcLoc = SrcLoc
locInvariant :: SrcLoc -> Bool
locInvariant s = srcAbs s > 0 && srcLine s > 0 && srcCol s > 0
-- | Delimits a portion of a text file. The end position is defined
-- to be the column /after/ the end of the span. That is, a span of
-- (1,1)-(1,2) is one character long, and a span of (1,1)-(1,1) is
-- zero characters long.
data SrcSpan = SrcSpan
{ spanFile :: !FilePath
, spanSLine :: !Int
, spanSCol :: !Int
, spanELine :: !Int
, spanECol :: !Int
}
deriving (Eq, Ord)
-- | Construct a span using a start location and an end location.
-- Both locations need to have the same source file. Also note
-- 'spanInvariant'.
makeSrcSpan :: SrcLoc -> SrcLoc -> SrcSpan
makeSrcSpan start end = SrcSpan
{ spanFile = srcFile start
, spanSLine = srcLine start
, spanSCol = srcCol start
, spanELine = srcLine end
, spanECol = srcCol end
}
-- | Construct a span using a start location and the number of characters
-- in the span. The span will start and end on the same line.
makeSrcSpanLength :: SrcLoc -> Int -> SrcSpan
makeSrcSpanLength s l = makeSrcSpan s s{ srcCol = l + srcCol s }
-- | Construct a span using an end location and the number of characters
-- in the span. The span will start and end on the same line. The given
-- length /must/ be less than the current position on the line.
makeSrcSpanLengthEnd :: SrcLoc -> Int -> SrcSpan
makeSrcSpanLengthEnd e l = makeSrcSpan e{ srcCol = srcCol e - l } e
-- | Create a 'SrcSpan' corresponding to a single point
srcLocSpan :: SrcLoc -> SrcSpan
srcLocSpan loc = makeSrcSpan loc loc
-- All 'SrcSpan' instances should satisfy this invariant
spanInvariant :: SrcSpan -> Bool
spanInvariant s = spanSLine s <= spanELine s && spanSCol s <= spanECol s
{--------------------------------------------------------------------------
Operations
--------------------------------------------------------------------------}
-- | Fuse two spans together. Both spans need to be in the same file.
mergeSrcSpan :: SrcSpan -> SrcSpan -> SrcSpan
mergeSrcSpan s1 s2 | s1 > s2 = mergeSrcSpan s2 s1
mergeSrcSpan s1 s2 = SrcSpan
{ spanFile = spanFile s1
, spanSLine = spanSLine s1
, spanSCol = spanSCol s1
, spanELine = spanELine s2
, spanECol = spanECol s2
}
{--------------------------------------------------------------------------
Located class
--------------------------------------------------------------------------}
-- | An object with an attached 'SrcSpan'
class Located t where
location :: t -> SrcSpan
instance Located SrcSpan where
location = id
instance Located (Loc a) where
location (Loc s _) = s
-- | Marge the 'SrcSpan's of two Located objects
mergeLocated :: (Located t1, Located t2) => t1 -> t2 -> SrcSpan
mergeLocated t1 t2 = mergeSrcSpan (location t1) (location t2)
-- | Default way to attach location information
data Loc a = Loc SrcSpan a
makeLoc :: SrcSpan -> a -> Loc a
makeLoc = Loc
-- | Get the data out of a 'Loc'
unLoc :: Loc a -> a
unLoc (Loc _ a) = a
{--------------------------------------------------------------------------
Printing
--------------------------------------------------------------------------}
instance Pretty SrcLoc where
pPrint (SrcLoc f _ l c) = text f <> colon <> pPrint l <> comma <> pPrint c
instance Pretty SrcSpan where
pPrint s = text (spanFile s) <> colon <> start <> text "-" <> end
where
SrcSpan { spanSLine = sl, spanSCol = sc
, spanELine = el, spanECol = ec } = s
start :: Doc
start = pPrint sl <> comma <> pPrint sc
end :: Doc
end | sl == el = pPrint ec
| otherwise = pPrint el <> comma <> pPrint ec
instance Pretty e => Pretty (Loc e) where
pPrint l = pPrint (unLoc l) <+> parens (text "at" <+> pPrint (location l))
instance Show SrcLoc where
show = prettyShow
instance Show SrcSpan where
show = prettyShow
instance Show e => Show (Loc e) where
show l = show (unLoc l) ++ " (at " ++ show (location l) ++ ")"
|
cacay/bibdb
|
src/Parser/Location.hs
|
mit
| 5,292 | 0 | 12 | 1,088 | 1,157 | 624 | 533 | 107 | 1 |
module Tach.Wavelet.Core.Internal
(
) where
|
smurphy8/tach
|
core-libs/tach-wavelet-core/src/Tach/Wavelet/Core/Internal.hs
|
mit
| 52 | 0 | 3 | 13 | 11 | 8 | 3 | 2 | 0 |
module Stackage.CLI.Sandbox (
-- TODO
) where
-- TODO: move functionality from main/Sandbox.hs
|
fpco/stackage-sandbox
|
src/Stackage/CLI/Sandbox.hs
|
mit
| 101 | 0 | 3 | 19 | 12 | 9 | 3 | 1 | 0 |
-- | <http://strava.github.io/api/v3/segments/>
module Strive.Actions.Segments
( getSegment
, getStarredSegments
, getSegmentEfforts
, getSegmentLeaderboard
, exploreSegments
) where
import Data.List (intercalate)
import Network.HTTP.Types (Query, toQuery)
import Strive.Aliases (Latitude, Longitude, Result, SegmentId)
import Strive.Client (Client)
import Strive.Internal.HTTP (get)
import Strive.Options
( ExploreSegmentsOptions
, GetSegmentEffortsOptions
, GetSegmentLeaderboardOptions
, GetStarredSegmentsOptions
)
import Strive.Types
( EffortDetailed
, SegmentDetailed
, SegmentExplorerResponse
, SegmentLeaderboardResponse
, SegmentSummary
)
-- | <http://strava.github.io/api/v3/segments/#retrieve>
getSegment :: Client -> SegmentId -> IO (Result SegmentDetailed)
getSegment client segmentId = get client resource query
where
resource = "api/v3/segments/" <> show segmentId
query = [] :: Query
-- | <http://strava.github.io/api/v3/segments/#starred>
getStarredSegments
:: Client -> GetStarredSegmentsOptions -> IO (Result [SegmentSummary])
getStarredSegments client options = get client resource query
where
resource = "api/v3/segments/starred"
query = toQuery options
-- | <http://strava.github.io/api/v3/segments/#efforts>
getSegmentEfforts
:: Client
-> SegmentId
-> GetSegmentEffortsOptions
-> IO (Result [EffortDetailed])
getSegmentEfforts client segmentId options = get client resource query
where
resource = "api/v3/segments/" <> show segmentId <> "/all_efforts"
query = toQuery options
-- | <http://strava.github.io/api/v3/segments/#leaderboard>
getSegmentLeaderboard
:: Client
-> SegmentId
-> GetSegmentLeaderboardOptions
-> IO (Result SegmentLeaderboardResponse)
getSegmentLeaderboard client segmentId options = get client resource query
where
resource = "api/v3/segments/" <> show segmentId <> "/leaderboard"
query = toQuery options
-- | <http://strava.github.io/api/v3/segments/#explore>
exploreSegments
:: Client
-> (Latitude, Longitude, Latitude, Longitude)
-> ExploreSegmentsOptions
-> IO (Result SegmentExplorerResponse)
exploreSegments client (south, west, north, east) options = get
client
resource
query
where
resource = "api/v3/segments/explore"
query =
toQuery
[("bounds", intercalate "," (fmap show [south, west, north, east]))]
<> toQuery options
|
tfausak/strive
|
source/library/Strive/Actions/Segments.hs
|
mit
| 2,390 | 0 | 14 | 355 | 525 | 290 | 235 | 61 | 1 |
module Carbon.DataStructures.Graphs.AdjacencyList.Tests (tests) where
import Test.QuickCheck
import qualified Test.HUnit as HUnit
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import Test.Framework.Providers.HUnit
import Data.List (foldl')
import qualified Carbon.DataStructures.Graphs.AdjacencyList as AdjacencyList
tests :: [Test]
tests = [
testCase "hi" testc
, testCase "hi2" testa
, testCase "hi3" add_nodes
]
add_nodes :: HUnit.Assertion
add_nodes
= let
(AdjacencyList.AdjacencyList nodes) = foldl' (\ aggregate x -> AdjacencyList.add_node aggregate x) AdjacencyList.create [1..3]
in HUnit.assertEqual "AdjacencyList add node" (map (\ x -> AdjacencyList.Node x []) [1..3]) nodes
stub :: a -> Maybe Int
stub _ = Nothing
testc = 1 HUnit.@?= 1
testa = do
a <- return (return (5))
b <- a
HUnit.assertEqual "hi" Nothing (stub 3)
|
Raekye/Carbon
|
haskell/testsuite/tests/Carbon/DataStructures/Graphs/AdjacencyList/Tests.hs
|
mit
| 870 | 6 | 13 | 127 | 292 | 160 | 132 | 25 | 1 |
module Antemodulum.Text.Strict (
module Export
) where
--------------------------------------------------------------------------------
import Data.Text as Export
import Data.Text.IO as Export
|
docmunch/antemodulum
|
src/Antemodulum/Text/Strict.hs
|
mit
| 197 | 0 | 4 | 20 | 29 | 21 | 8 | 4 | 0 |
{-# LANGUAGE NoImplicitPrelude #-}
module System.Etc.Internal.Resolver.Cli
( PlainConfigSpec
-- , resolveCommandCli
-- , resolveCommandCliPure
, resolvePlainCli
, resolvePlainCliPure
) where
-- import System.Etc.Internal.Resolver.Cli.Command (resolveCommandCli, resolveCommandCliPure)
import System.Etc.Internal.Resolver.Cli.Plain
(PlainConfigSpec, resolvePlainCli, resolvePlainCliPure)
|
roman/Haskell-etc
|
etc/src/System/Etc/Internal/Resolver/Cli.hs
|
mit
| 405 | 0 | 5 | 48 | 44 | 32 | 12 | 7 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-recordcolumn.html
module Stratosphere.ResourceProperties.KinesisAnalyticsV2ApplicationRecordColumn where
import Stratosphere.ResourceImports
-- | Full data type definition for KinesisAnalyticsV2ApplicationRecordColumn.
-- See 'kinesisAnalyticsV2ApplicationRecordColumn' for a more convenient
-- constructor.
data KinesisAnalyticsV2ApplicationRecordColumn =
KinesisAnalyticsV2ApplicationRecordColumn
{ _kinesisAnalyticsV2ApplicationRecordColumnMapping :: Maybe (Val Text)
, _kinesisAnalyticsV2ApplicationRecordColumnName :: Val Text
, _kinesisAnalyticsV2ApplicationRecordColumnSqlType :: Val Text
} deriving (Show, Eq)
instance ToJSON KinesisAnalyticsV2ApplicationRecordColumn where
toJSON KinesisAnalyticsV2ApplicationRecordColumn{..} =
object $
catMaybes
[ fmap (("Mapping",) . toJSON) _kinesisAnalyticsV2ApplicationRecordColumnMapping
, (Just . ("Name",) . toJSON) _kinesisAnalyticsV2ApplicationRecordColumnName
, (Just . ("SqlType",) . toJSON) _kinesisAnalyticsV2ApplicationRecordColumnSqlType
]
-- | Constructor for 'KinesisAnalyticsV2ApplicationRecordColumn' containing
-- required fields as arguments.
kinesisAnalyticsV2ApplicationRecordColumn
:: Val Text -- ^ 'kavarcName'
-> Val Text -- ^ 'kavarcSqlType'
-> KinesisAnalyticsV2ApplicationRecordColumn
kinesisAnalyticsV2ApplicationRecordColumn namearg sqlTypearg =
KinesisAnalyticsV2ApplicationRecordColumn
{ _kinesisAnalyticsV2ApplicationRecordColumnMapping = Nothing
, _kinesisAnalyticsV2ApplicationRecordColumnName = namearg
, _kinesisAnalyticsV2ApplicationRecordColumnSqlType = sqlTypearg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-recordcolumn.html#cfn-kinesisanalyticsv2-application-recordcolumn-mapping
kavarcMapping :: Lens' KinesisAnalyticsV2ApplicationRecordColumn (Maybe (Val Text))
kavarcMapping = lens _kinesisAnalyticsV2ApplicationRecordColumnMapping (\s a -> s { _kinesisAnalyticsV2ApplicationRecordColumnMapping = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-recordcolumn.html#cfn-kinesisanalyticsv2-application-recordcolumn-name
kavarcName :: Lens' KinesisAnalyticsV2ApplicationRecordColumn (Val Text)
kavarcName = lens _kinesisAnalyticsV2ApplicationRecordColumnName (\s a -> s { _kinesisAnalyticsV2ApplicationRecordColumnName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-application-recordcolumn.html#cfn-kinesisanalyticsv2-application-recordcolumn-sqltype
kavarcSqlType :: Lens' KinesisAnalyticsV2ApplicationRecordColumn (Val Text)
kavarcSqlType = lens _kinesisAnalyticsV2ApplicationRecordColumnSqlType (\s a -> s { _kinesisAnalyticsV2ApplicationRecordColumnSqlType = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/KinesisAnalyticsV2ApplicationRecordColumn.hs
|
mit
| 3,058 | 0 | 13 | 269 | 357 | 203 | 154 | 34 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module Sortier.Netz.Type
( Netz
, mkNetz, comps, low, high
, State, States
, Comp, Comps
)
where
import Sortier.Netz.Xml
import Autolib.ToDoc
import Autolib.Reader
import Autolib.Size
import Data.Typeable
type Comp = (Int, Int)
type Comps = [ Comp ]
type State = [ Int ]
type States = [ State ]
data Netz = Netz
{ low :: Int
, high :: Int
, comps :: Comps
}
deriving ( Eq, Ord, Typeable )
mkNetz :: [(Int, Int)] -> Netz
mkNetz xys =
let all = do (x,y) <- xys ; [x,y]
in Netz { low = minimum all, high = maximum all
, comps = xys
}
instance Size Netz where
size = length . comps
instance Reader Netz where
atomic_readerPrec p = do
guard $ p < 9
my_reserved "mkNetz"
xys <- reader
return $ mkNetz xys
instance ToDoc Netz where
toDoc n = text "mkNetz" <+> toDoc (comps n)
|
Erdwolf/autotool-bonn
|
src/Sortier/Netz/Type.hs
|
gpl-2.0
| 897 | 6 | 12 | 247 | 335 | 189 | 146 | 35 | 1 |
{-# LANGUAGE CPP, ForeignFunctionInterface #-}
module Darcs.UI.External
( sendEmail
, generateEmail
, sendEmailDoc
, resendEmail
, signString
, verifyPS
, execDocPipe
, execPipeIgnoreError
, pipeDoc
, pipeDocSSH
, maybeURLCmd
, viewDoc
, viewDocWith
, haveSendmail
, sendmailPath
, diffProgram
, darcsProgram
, editText
, editFile
, catchall
-- * Locales
, setDarcsEncodings
, getSystemEncoding
, isUTF8Locale
) where
import Prelude hiding ( catch )
import Data.Maybe ( isJust, isNothing, maybeToList )
import Control.Monad ( unless, when, filterM, liftM2, void )
import GHC.MVar ( MVar )
import System.Exit ( ExitCode(..) )
import System.Environment
( getEnv
#if __GLASGOW_HASKELL__ >= 706
, getExecutablePath
#else
, getProgName
#endif
)
import System.IO ( hPutStr, hPutStrLn, hClose,
hIsTerminalDevice, stdout, stderr, Handle )
import System.Directory ( doesFileExist,
findExecutable )
import System.FilePath.Posix ( (</>) )
import System.Process ( createProcess, proc, CreateProcess(..), runInteractiveProcess, waitForProcess, StdStream(..) )
import System.Process.Internals ( ProcessHandle )
import GHC.IO.Encoding ( setFileSystemEncoding, setForeignEncoding, char8 )
import Foreign.C.String ( CString, peekCString )
import Control.Concurrent ( forkIO, newEmptyMVar, putMVar, takeMVar )
import Control.Exception
( try, finally, catch, IOException )
import System.IO.Error ( ioeGetErrorType )
import GHC.IO.Exception ( IOErrorType(ResourceVanished) )
import Data.Char ( toUpper, toLower )
import Text.Regex
#if defined (HAVE_MAPI)
import Foreign.C ( withCString )
#endif
#ifdef HAVE_MAPI
import Foreign.Ptr ( nullPtr )
import Darcs.Repository.Lock ( canonFilename, writeDocBinFile )
#endif
import Darcs.Util.SignalHandler ( catchNonSignal )
import Darcs.UI.Options.All ( Sign(..), Verify(..), Compression(..) )
import Darcs.Util.Path
( AbsolutePath
, toFilePath
, FilePathLike
)
import Darcs.Util.Progress ( withoutProgress, debugMessage )
import Darcs.Util.ByteString (linesPS, unlinesPS)
import qualified Data.ByteString as B (ByteString, empty, null, readFile
,hGetContents, writeFile, hPut, length
,take, concat, drop, isPrefixOf, singleton, append)
import qualified Data.ByteString.Char8 as BC (unpack, pack)
import Darcs.Repository.Lock
( withTemp
, withNamedTemp
, withOpenTemp
)
import Darcs.Repository.Ssh ( getSSH, SSHCmd(..) )
import Darcs.Util.CommandLine ( parseCmd, addUrlencoded )
import Darcs.Util.Exec ( execInteractive, exec, Redirect(..), withoutNonBlock )
import Darcs.Util.URL ( SshFilePath, sshUhost )
import Darcs.Util.Printer ( Doc, Printers, hPutDocLnWith, hPutDoc, hPutDocLn, hPutDocWith, ($$), renderPS,
simplePrinters,
hPutDocCompr,
text, empty, packedString, vcat, renderString, RenderMode(..) )
import qualified Darcs.Util.Ratified as Ratified
import Darcs.UI.Email ( formatHeader )
sendmailPath :: IO String
sendmailPath = do
l <- filterM doesFileExist $ liftM2 (</>)
[ "/usr/sbin", "/sbin", "/usr/lib" ]
[ "sendmail" ]
ex <- findExecutable "sendmail"
when (isNothing ex && null l) $ fail "Cannot find the \"sendmail\" program."
return $ head $ maybeToList ex ++ l
diffProgram :: IO String
diffProgram = do
l <- filterM (fmap isJust . findExecutable) [ "gdiff", "gnudiff", "diff" ]
when (null l) $ fail "Cannot find the \"diff\" program."
return $ head l
-- |Get the name of the darcs executable (as supplied by @getExecutablePath@)
darcsProgram :: IO String
#if __GLASGOW_HASKELL__ >= 706
darcsProgram = getExecutablePath
#else
darcsProgram = getProgName
#endif
maybeURLCmd :: String -> String -> IO (Maybe String)
maybeURLCmd what url =
do let prot = map toUpper $ takeWhile (/= ':') url
fmap Just (getEnv ("DARCS_" ++ what ++ "_" ++ prot))
`catch` \(_ :: IOException) -> return Nothing
pipeDoc :: RenderMode -> String -> [String] -> Doc -> IO ExitCode
pipeDoc = pipeDocInternal (PipeToOther simplePrinters)
data WhereToPipe = PipeToSsh Compression -- ^ if pipe to ssh, can choose to compress or not
| PipeToOther Printers -- ^ otherwise, can specify printers
pipeDocInternal :: WhereToPipe -> RenderMode -> String -> [String] -> Doc -> IO ExitCode
pipeDocInternal whereToPipe target c args inp = withoutNonBlock $ withoutProgress $
do debugMessage $ unwords (c:args)
(Just i,_,_,pid) <- createProcess (proc c args){ std_in = CreatePipe
{- , delegate_ctlc = True -- requires process 1.2.2.0 -} }
debugMessage "Start transferring data"
case whereToPipe of
PipeToSsh GzipCompression -> hPutDocCompr target i inp
PipeToSsh NoCompression -> hPutDoc target i inp
PipeToOther printers -> hPutDocWith printers target i inp
hClose i
rval <- waitForProcess pid
debugMessage "Finished transferring data"
when (rval == ExitFailure 127) $
putStrLn $ "Command not found:\n "++ show (c:args)
return rval
pipeDocSSH :: Compression -> RenderMode -> SshFilePath -> [String] -> Doc -> IO ExitCode
pipeDocSSH compress target remoteAddr args input = do
(ssh, ssh_args) <- getSSH SSH
pipeDocInternal (PipeToSsh compress) target ssh (ssh_args++ (sshUhost remoteAddr:args)) input
sendEmail :: String -> String -> String -> String -> String -> String -> IO ()
sendEmail f t s cc scmd body =
sendEmailDoc f t s cc scmd Nothing (text body)
generateEmail
:: Handle -- ^ handle to write email to
-> String -- ^ From
-> String -- ^ To
-> String -- ^ Subject
-> String -- ^ CC
-> Doc -- ^ body
-> IO ()
generateEmail h f t s cc body = do
putHeader "To" t
putHeader "From" f
putHeader "Subject" s
unless (null cc) $ putHeader "Cc" cc
putHeader "X-Mail-Originator" "Darcs Version Control System"
hPutDocLn Standard h body
where putHeader field value
= B.hPut h (B.append (formatHeader field value) newline)
newline = B.singleton 10
haveSendmail :: IO Bool
haveSendmail = (sendmailPath >> return True) `catch` (\(_ :: IOException) -> return False)
-- | Send an email, optionally containing a patch bundle
-- (more precisely, its description and the bundle itself)
sendEmailDoc
:: String -- ^ from
-> String -- ^ to
-> String -- ^ subject
-> String -- ^ cc
-> String -- ^ send command
-> Maybe (Doc, Doc) -- ^ (content,bundle)
-> Doc -- ^ body
-> IO ()
sendEmailDoc _ "" _ "" _ _ _ = return ()
sendEmailDoc f "" s cc scmd mbundle body =
sendEmailDoc f cc s "" scmd mbundle body
sendEmailDoc f t s cc scmd mbundle body = do
use_sendmail <- haveSendmail
if use_sendmail || scmd /= "" then
withOpenTemp $ \(h,fn) -> do
generateEmail h f t s cc body
hClose h
withOpenTemp $ \(hat,at) -> do
ftable' <- case mbundle of
Just (content,bundle) -> do
hPutDocLn Standard hat bundle
return [ ('b', renderString Standard content) , ('a', at) ]
Nothing ->
return [ ('b', renderString Standard body) ]
hClose hat
let ftable = [ ('t',addressOnly t),('c',cc),('f',f),('s',s) ] ++ ftable'
r <- execSendmail ftable scmd fn
when (r /= ExitSuccess) $ fail ("failed to send mail to: "
++ t ++ cc_list cc
++ "\nPerhaps sendmail is not configured.")
#ifdef HAVE_MAPI
else do
r <- withCString t $ \tp ->
withCString f $ \fp ->
withCString cc $ \ccp ->
withCString s $ \sp ->
withOpenTemp $ \(h,fn) -> do
hPutDoc Standard h body
hClose h
writeDocBinFile "mailed_patch" body
cfn <- canonFilename fn
withCString cfn $ \pcfn ->
c_send_email fp tp ccp sp nullPtr pcfn
when (r /= 0) $ fail ("failed to send mail to: " ++ t)
#else
else fail "no mail facility (sendmail or mapi) located at configure time!"
#endif
where addressOnly a =
case dropWhile (/= '<') a of
('<':a2) -> takeWhile (/= '>') a2
_ -> a
cc_list [] = []
cc_list c = " and cc'ed " ++ c
resendEmail :: String -> String -> B.ByteString -> IO ()
resendEmail "" _ _ = return ()
resendEmail t scmd body = do
use_sendmail <- haveSendmail
if use_sendmail || scmd /= ""
then
withOpenTemp $ \(h,fn) -> do
hPutStrLn h $ "To: "++ t
hPutStrLn h $ find_from (linesPS body)
hPutStrLn h $ find_subject (linesPS body)
hPutDocLn Standard h $ fixit $ linesPS body
hClose h
let ftable = [('t',t)]
r <- execSendmail ftable scmd fn
when (r /= ExitSuccess) $ fail ("failed to send mail to: " ++ t)
else
#ifdef HAVE_MAPI
fail "Don't know how to resend email with MAPI"
#else
fail "no mail facility (sendmail or mapi) located at configure time (use the sendmail-command option)!"
#endif
where br = BC.pack "\r"
darcsurl = BC.pack "DarcsURL:"
content = BC.pack "Content-"
from_start = BC.pack "From:"
subject_start = BC.pack "Subject:"
fixit (l:ls)
| B.null l = packedString B.empty $$ vcat (map packedString ls)
| l == br = packedString B.empty $$ vcat (map packedString ls)
| B.take 9 l == darcsurl || B.take 8 l == content
= packedString l $$ fixit ls
| otherwise = fixit ls
fixit [] = empty
find_from (l:ls) | B.take 5 l == from_start = BC.unpack l
| otherwise = find_from ls
find_from [] = "From: unknown"
find_subject (l:ls) | B.take 8 l == subject_start = BC.unpack l
| otherwise = find_subject ls
find_subject [] = "Subject: (no subject)"
execSendmail :: [(Char,String)] -> String -> String -> IO ExitCode
execSendmail ftable scmd fn =
if scmd == "" then do
cmd <- sendmailPath
exec cmd ["-i", "-t"] (File fn, Null, AsIs)
else case parseCmd (addUrlencoded ftable) scmd of
Right (arg0:opts, wantstdin) ->
do let stdin = if wantstdin then File fn else Null
exec arg0 opts (stdin, Null, AsIs)
Left e -> fail $ "failed to send mail, invalid sendmail-command: "++show e
_ -> fail "failed to send mail, invalid sendmail-command"
#ifdef HAVE_MAPI
foreign import ccall "win32/send_email.h send_email" c_send_email
:: CString -> {- sender -}
CString -> {- recipient -}
CString -> {- cc -}
CString -> {- subject -}
CString -> {- body -}
CString -> {- path -}
IO Int
#endif
execPSPipe :: String -> [String] -> B.ByteString -> IO B.ByteString
execPSPipe c args ps = fmap (renderPS Standard)
$ execDocPipe Standard c args
$ packedString ps
execAndGetOutput :: RenderMode -> FilePath -> [String] -> Doc
-> IO (ProcessHandle, MVar (), B.ByteString)
execAndGetOutput target c args instr = do
(i,o,e,pid) <- runInteractiveProcess c args Nothing Nothing
_ <- forkIO $ hPutDoc target i instr >> hClose i
mvare <- newEmptyMVar
_ <- forkIO ((Ratified.hGetContents e >>= -- ratify: immediately consumed
hPutStr stderr)
`finally` putMVar mvare ())
out <- B.hGetContents o
return (pid, mvare, out)
execDocPipe :: RenderMode -> String -> [String] -> Doc -> IO Doc
execDocPipe target c args instr = withoutProgress $ do
(pid, mvare, out) <- execAndGetOutput target c args instr
rval <- waitForProcess pid
takeMVar mvare
case rval of
ExitFailure ec ->fail $ "External program '"++c++
"' failed with exit code "++ show ec
ExitSuccess -> return $ packedString out
-- The following is needed for diff, which returns non-zero whenever
-- the files differ.
execPipeIgnoreError :: RenderMode -> String -> [String] -> Doc -> IO Doc
execPipeIgnoreError target c args instr = withoutProgress $ do
(pid, mvare, out) <- execAndGetOutput target c args instr
_ <- waitForProcess pid
takeMVar mvare
return $ if B.null out then empty else packedString out
signString :: Sign -> Doc -> IO Doc
signString NoSign d = return d
signString Sign d = signPGP [] d
signString (SignAs keyid) d = signPGP ["--local-user", keyid] d
signString (SignSSL idf) d = signSSL idf d
signPGP :: [String] -> Doc -> IO Doc
signPGP args = execDocPipe Standard "gpg" ("--clearsign":args)
signSSL :: String -> Doc -> IO Doc
signSSL idfile t =
withTemp $ \cert -> do
opensslPS ["req", "-new", "-key", idfile,
"-outform", "PEM", "-days", "365"]
(BC.pack "\n\n\n\n\n\n\n\n\n\n\n")
>>= opensslPS ["x509", "-req", "-extensions",
"v3_ca", "-signkey", idfile,
"-outform", "PEM", "-days", "365"]
>>= opensslPS ["x509", "-outform", "PEM"]
>>= B.writeFile cert
opensslDoc ["smime", "-sign", "-signer", cert,
"-inkey", idfile, "-noattr", "-text"] t
where opensslDoc = execDocPipe Standard "openssl"
opensslPS = execPSPipe "openssl"
verifyPS :: Verify -> B.ByteString -> IO (Maybe B.ByteString)
verifyPS NoVerify ps = return $ Just ps
verifyPS (VerifyKeyring pks) ps = verifyGPG pks ps
verifyPS (VerifySSL auks) ps = verifySSL auks ps
verifyGPG :: AbsolutePath -> B.ByteString -> IO (Maybe B.ByteString)
verifyGPG goodkeys s =
withOpenTemp $ \(th,tn) -> do
B.hPut th s
hClose th
rval <- exec "gpg" ["--batch","--no-default-keyring",
"--keyring",fix_path $ toFilePath goodkeys, "--verify"]
(File tn, Null, Null)
case rval of
ExitSuccess -> return $ Just gpg_fixed_s
_ -> return Nothing
where gpg_fixed_s = let
not_begin_signature x =
x /= BC.pack "-----BEGIN PGP SIGNED MESSAGE-----"
&&
x /= BC.pack "-----BEGIN PGP SIGNED MESSAGE-----\r"
in unlinesPS $ map fix_line $ tail $ dropWhile not_begin_signature $ linesPS s
fix_line x | B.length x < 3 = x
| BC.pack "- -" `B.isPrefixOf` x = B.drop 2 x
| otherwise = x
#if defined(WIN32)
fix_sep c | c=='/' = '\\' | otherwise = c
fix_path p = map fix_sep p
#else
fix_path p = p
#endif
verifySSL :: AbsolutePath -> B.ByteString -> IO (Maybe B.ByteString)
verifySSL goodkeys s = do
certdata <- opensslPS ["smime", "-pk7out"] s
>>= opensslPS ["pkcs7", "-print_certs"]
cruddy_pk <- opensslPS ["x509", "-pubkey"] certdata
let key_used = B.concat $ tail $
takeWhile (/= BC.pack"-----END PUBLIC KEY-----")
$ linesPS cruddy_pk
in do allowed_keys <- linesPS `fmap` B.readFile (toFilePath goodkeys)
if key_used `notElem` allowed_keys
then return Nothing -- Not an allowed key!
else withTemp $ \cert ->
withTemp $ \on ->
withOpenTemp $ \(th,tn) -> do
B.hPut th s
hClose th
B.writeFile cert certdata
rval <- exec "openssl" ["smime", "-verify", "-CAfile",
cert, "-certfile", cert]
(File tn, File on, Null)
case rval of
ExitSuccess -> Just `fmap` B.readFile on
_ -> return Nothing
where opensslPS = execPSPipe "openssl"
viewDoc :: Doc -> IO ()
viewDoc = viewDocWith simplePrinters Encode
viewDocWith :: Printers -> RenderMode -> Doc -> IO ()
viewDocWith pr mode msg = do
isTerminal <- hIsTerminalDevice stdout
void $ if isTerminal && lengthGreaterThan (20 :: Int) (lines $ renderString mode msg)
then do mbViewerPlusArgs <- getViewer
case mbViewerPlusArgs of
Just viewerPlusArgs -> do
let (viewer : args) = words viewerPlusArgs
pipeDocToPager viewer args pr mode msg
Nothing -> return $ ExitFailure 127 -- No such command
-- TEMPORARY passing the -K option should be removed as soon as
-- we can use the delegate_ctrl_c feature in process
`ortryrunning` pipeDocToPager "less" ["-RK"] pr mode msg
`ortryrunning` pipeDocToPager "more" [] pr mode msg
#ifdef WIN32
`ortryrunning` pipeDocToPager "more.com" [] pr mode msg
#endif
`ortryrunning` pipeDocToPager "" [] pr mode msg
else pipeDocToPager "" [] pr mode msg
where lengthGreaterThan n _ | n <= 0 = True
lengthGreaterThan _ [] = False
lengthGreaterThan n (_:xs) = lengthGreaterThan (n-1) xs
getViewer :: IO (Maybe String)
getViewer = Just `fmap` (getEnv "DARCS_PAGER" `catchall` getEnv "PAGER")
`catchall`
return Nothing
pipeDocToPager :: String -> [String] -> Printers -> RenderMode -> Doc -> IO ExitCode
pipeDocToPager "" _ pr mode inp = do
hPutDocLnWith pr mode stdout inp
return ExitSuccess
pipeDocToPager c args pr mode inp = pipeDocInternal (PipeToOther pr) mode c args inp
-- | Given two shell commands as arguments, execute the former. The
-- latter is then executed if the former failed because the executable
-- wasn't found (code 127), wasn't executable (code 126) or some other
-- exception occurred (save from a resource vanished/broken pipe error).
-- Other failures (such as the user holding ^C)
-- do not cause the second command to be tried.
ortryrunning :: IO ExitCode
-> IO ExitCode
-> IO ExitCode
a `ortryrunning` b = do
ret <- try a
case ret of
(Right (ExitFailure 126)) -> b -- command not executable
(Right (ExitFailure 127)) -> b -- command not found
#ifdef WIN32
(Right (ExitFailure 9009)) -> b -- command not found by cmd.exe on Windows
#endif
(Right x) -> return x -- legitimate success/failure
(Left (e :: IOException)) -> case ioeGetErrorType e of
-- case where pager is quit before darcs has fed it entirely:
ResourceVanished -> return ExitSuccess
-- other exception:
_ -> b
editText :: String -> B.ByteString -> IO B.ByteString
editText desc txt = withNamedTemp desc $ \f -> do
B.writeFile f txt
_ <- runEditor f
B.readFile f
-- | @editFile f@ lets the user edit a file which could but does not need to
-- already exist. This function returns the exit code from the text editor and a
-- flag indicating if the user made any changes.
editFile :: FilePathLike p
=> p
-> IO (ExitCode, Bool)
editFile ff = do
old_content <- file_content
ec <- runEditor f
new_content <- file_content
return (ec, new_content /= old_content)
where
f = toFilePath ff
file_content = do
exists <- doesFileExist f
if exists then do content <- B.readFile f
return $ Just content
else return Nothing
runEditor :: FilePath
-> IO ExitCode
runEditor f = do
ed <- getEditor
execInteractive ed f
`ortryrunning` execInteractive "vi" f
`ortryrunning` execInteractive "emacs" f
`ortryrunning` execInteractive "emacs -nw" f
#ifdef WIN32
`ortryrunning` execInteractive "edit" f
#endif
getEditor :: IO String
getEditor = getEnv "DARCS_EDITOR" `catchall`
getEnv "DARCSEDITOR" `catchall`
getEnv "VISUAL" `catchall`
getEnv "EDITOR" `catchall` return "nano"
catchall :: IO a
-> IO a
-> IO a
a `catchall` b = a `catchNonSignal` (\_ -> b)
-- | In some environments, darcs requires that certain global GHC library variables that
-- control the encoding used in internal translations are set to specific values.
--
-- @setDarcsEncoding@ enforces those settings, and should be called before the
-- first time any darcs operation is run, and again if anything else might have
-- set those encodings to different values.
--
-- Note that it isn't thread-safe and has a global effect on your program.
--
-- The current behaviour of this function is as follows, though this may
-- change in future:
--
-- Encodings are only set on GHC 7.4 and up, on any non-Windows platform.
--
-- Two encodings are set, both to @GHC.IO.Encoding.char8@:
-- @GHC.IO.Encoding.setFileSystemEncoding@ and @GHC.IO.Encoding.setForeignEncoding@.
--
-- Prevent HLint from warning us about a redundant do if the macro isn't
-- defined:
setDarcsEncodings :: IO ()
setDarcsEncodings = do
-- This is needed for appropriate behaviour from getArgs and from general
-- filesystem calls (e.g. getDirectoryContents, readFile, ...)
setFileSystemEncoding char8
-- This ensures that foreign calls made by hashed-storage to stat
-- filenames returned from getDirectoryContents are translated appropriately
setForeignEncoding char8
return ()
-- The following functions are copied from the encoding package (BSD3
-- licence, by Henning GΓΌnther).
-- | @getSystemEncoding@ fetches the current encoding from locale
foreign import ccall "system_encoding.h get_system_encoding"
get_system_encoding :: IO CString
getSystemEncoding :: IO String
getSystemEncoding = do
enc <- get_system_encoding
peekCString enc
-- | @isUTF8@ checks if an encoding is UTF-8 (or ascii, since it is a
-- subset of UTF-8).
isUTF8Locale :: String -> Bool
isUTF8Locale codeName = case normalizeEncoding codeName of
-- ASCII
"ascii" -> True
"646" -> True
"ansi_x3_4_1968" -> True
"ansi_x3.4_1986" -> True
"cp367" -> True
"csascii" -> True
"ibm367" -> True
"iso646_us" -> True
"iso_646.irv_1991" -> True
"iso_ir_6" -> True
"us" -> True
"us_ascii" -> True
-- UTF-8
"utf_8" -> True
"u8" -> True
"utf" -> True
"utf8" -> True
"utf8_ucs2" -> True
"utf8_ucs4" -> True
-- Everything else
_ -> False
where
normalizeEncoding s = map toLower $ subRegex sep s "_"
sep = mkRegex "[^0-9A-Za-z]+"
|
DavidAlphaFox/darcs
|
src/Darcs/UI/External.hs
|
gpl-2.0
| 23,151 | 0 | 25 | 6,872 | 6,039 | 3,142 | 2,897 | -1 | -1 |
module Equ.PreExpr.Eval where
import Equ.Syntax
import Equ.Theories.AbsName
import Equ.PreExpr.Symbols
import Equ.PreExpr.Internal
import Control.Applicative
-- | Funcion para internalizar numerales.
intToCon :: Int -> PreExpr
intToCon 0 = Con $ natZero
intToCon n = UnOp (natSucc) $ intToCon (n-1)
semNBinOp :: Operator -> Maybe (Int -> Int -> Int)
semNBinOp op = case opName op of
Sum -> Just (+)
Prod -> Just (*)
Div -> Just div
Dif -> Just (-)
Mod -> Just mod
_ -> Nothing
semNUnOp :: Operator -> Maybe (Int -> Int)
semNUnOp op = case opName op of
Succ -> Just (1+)
Pred -> Just (\i -> i-1)
_ -> Nothing
semNConst :: Constant -> Maybe Int
semNConst c = case conName c of
Zero -> Just 0
_ -> Nothing
-- | VersiΓ³n para pretty-printing.
evalNat :: PreExpr -> Maybe Int
evalNat (Con c) = semNConst c
evalNat (UnOp op e) = semNUnOp op <*> evalNat e
evalNat _ = Nothing
evalN :: PreExpr -> Maybe Int
evalN (Con c) = semNConst c
evalN (UnOp op e) = semNUnOp op <*> evalN e
evalN (BinOp op e e') = semNBinOp op <*> evalN e <*> evalN e'
evalN _ = Nothing
evalExpr :: PreExpr -> PreExpr
evalExpr (Var v) = Var v
evalExpr (Con c) = Con c
evalExpr (PrExHole h) = PrExHole h
evalExpr e@(UnOp op e') = maybe (UnOp op (evalExpr e')) intToCon $ evalN e
evalExpr e@(BinOp op e1 e2) = maybe e' intToCon $ evalN e
where e' = case (evalN e1, evalN e2) of
(Nothing,Nothing) -> BinOp op (evalExpr e1) (evalExpr e2)
(Just m, Nothing) -> BinOp op (intToCon m) (evalExpr e2)
(Nothing, Just n) -> BinOp op (evalExpr e1) (intToCon n)
(Just m,Just n) -> BinOp op (intToCon m) (intToCon n)
evalExpr (App e e') = App (evalExpr e) (evalExpr e')
evalExpr (Quant q v r t) = Quant q v (evalExpr r) (evalExpr t)
evalExpr (Paren e) = Paren (evalExpr e)
evalExpr (If b t f) = If (evalExpr b) (evalExpr t) (evalExpr f)
evalExpr (Case e cs) = Case e cs
|
miguelpagano/equ
|
Equ/PreExpr/Eval.hs
|
gpl-3.0
| 2,079 | 0 | 12 | 605 | 916 | 457 | 459 | 51 | 6 |
{- $Id$
Find the sum of the digits in the number 100!
Solution to http://projecteuler.net/index.php?section=problems&id=20
Copyright 2007 Victor Engmark
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/>.
-}
module Main( main ) where
import System ( getArgs, getProgName )
factorial :: Int -> Integer
factorial number = map (* [1..number])
digitSum :: Integer -> Integer
digitSum number = 1
usageAndExit :: IO ()
usageAndExit = do
progName <- getProgName
putStrLn $ "Usage: runghc " ++ progName ++ " [positive integer]"
main :: IO ()
main = do
args <- getArgs
case args of
[integer] -> print $ digitSum $ factorial $ read integer
_ -> usageAndExit
|
l0b0/Project-Euler
|
20 - Find the sum of digits in N factorial.hs
|
gpl-3.0
| 1,327 | 0 | 12 | 320 | 163 | 86 | 77 | 16 | 2 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 [email protected]
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module LevelTools.EditWorld.Make
(
makeEditWorldNew,
makeEditWorldLoad,
makeEditWorldIO,
) where
import MyPrelude
import Game.Grid.GridWorld
import Game.Grid.Helpers
import Game.Grid.GridWorld.Make
import Game.LevelPuzzleMode.LevelPuzzleWorld
import Game.LevelPuzzleMode.Iteration
import LevelTools.EditWorld
import LevelTools.Make
import Game.MEnv
import File.Binary
import LevelTools.File
makeEditWorldNew = do
let cnt = makeSemiContentEmpty
grid <- makeGridWorldEmpty
lvl <- makeLevelPuzzleWorldEmpty
return EditWorld
{
editLevel = makeLevel "" False 0,
editSemiContent = cnt,
editLevelPuzzleEmpty = True,
editLevelPuzzleWorld = lvl,
editLevelPuzzleStack = [iterationBeginPlay],
editFileOutput = "",
editGrid = setCamera grid,
editNode = mempty,
editPushedNodes = [],
editEditType = TypeDotPlain,
editEvents = [],
editCameraNode = mempty,
editMessage = mempty,
editDotPlain = makeDotPlain mempty 1 1 0,
editDotBonus = makeDotBonus mempty 1 1 1,
editDotTele = makeDotTele mempty 1 1 mempty,
editDotFinish = makeDotFinish mempty,
editWall = makeWall False mempty (Node 1 0 0) (Node 0 1 0)
}
makeEditWorldLoad path = do
(level, srooms) <- io $ readBinary' rLevelFile path
let cnt = makeSemiContent srooms
grid <- makeGridWorldEmpty
lvl <- makeLevelPuzzleWorldEmpty
return EditWorld
{
editLevel = level,
editSemiContent = cnt,
editLevelPuzzleEmpty = True,
editLevelPuzzleWorld = lvl,
editLevelPuzzleStack = [iterationBeginPlay],
editFileOutput = "",
editGrid = setCamera grid,
editNode = mempty,
editPushedNodes = [],
editEditType = TypeDotPlain,
editEvents = [],
editCameraNode = mempty,
editMessage = mempty,
editDotPlain = makeDotPlain mempty 1 1 0,
editDotBonus = makeDotBonus mempty 1 1 1,
editDotTele = makeDotTele mempty 1 1 mempty,
editDotFinish = makeDotFinish mempty,
editWall = makeWall False mempty (Node 1 0 0) (Node 0 1 0)
}
setCamera grid =
gridModifyCamera grid $ \cam -> cameraSetView cam $ View 0.0 0.4 8.0
makeEditWorldIO path = do
(level, srooms) <- io $ readBinary' rLevelFile path
let cnt = makeSemiContent srooms
grid = error "no GridWordl in EditWorld"
lvl = error "no LevelWorld in EditWorld"
return EditWorld
{
editLevel = level,
editSemiContent = cnt,
editLevelPuzzleEmpty = True,
editLevelPuzzleWorld = lvl,
editLevelPuzzleStack = [iterationBeginPlay],
editFileOutput = "",
editGrid = setCamera grid,
editNode = mempty,
editPushedNodes = [],
editEditType = TypeDotPlain,
editEvents = [],
editCameraNode = mempty,
editMessage = mempty,
editDotPlain = makeDotPlain mempty 1 1 0,
editDotBonus = makeDotBonus mempty 1 1 1,
editDotTele = makeDotTele mempty 1 1 mempty,
editDotFinish = makeDotFinish mempty,
editWall = makeWall False mempty (Node 1 0 0) (Node 0 1 0)
}
|
karamellpelle/grid
|
designer/source/LevelTools/EditWorld/Make.hs
|
gpl-3.0
| 4,257 | 0 | 12 | 1,315 | 834 | 476 | 358 | 89 | 1 |
module BabyRays.Shape where
import Core.Constants
import Core.Geometry
import BabyRays.Material
import BabyRays.Types
makeBox :: (Point -> Material) -> Point -> Vector -> Vector -> Vector -> [Shape]
makeBox mat p0 u v w = tris
where p1 = p0 .+^ w
p2 = p1 .+^ u
p3 = p0 .+^ u
p4 = p0 .+^ v
p5 = p1 .+^ v
p6 = p2 .+^ v
p7 = p3 .+^ v
makeTri (a,b,c) = Triangle a b c mat
tris = map makeTri [(p2,p1,p0),
(p3,p2,p0),
(p4,p5,p6),
(p4,p6,p7),
(p5,p4,p0),
(p0,p1,p5),
(p2,p6,p7),
(p7,p3,p2),
(p7,p3,p0),
(p0,p4,p7),
(p1,p5,p6),
(p6,p2,p1)]
finitePlane :: (Point -> Material) -> Point -> Vector -> Vector -> [Shape]
finitePlane mat p0 u v = map (\(a,b,c) -> Triangle a b c mat) [(p0,p1,p2), (p0,p2,p3)]
where p1 = p0 .+^ v
p2 = p1 .+^ u
p3 = p0 .+^ u
|
dsj36/dropray
|
src/BabyRays/Shape.hs
|
gpl-3.0
| 1,142 | 0 | 10 | 539 | 451 | 267 | 184 | 32 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Dataproc.Projects.Regions.WorkflowTemplates.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes a workflow template. It does not cancel in-progress workflows.
--
-- /See:/ <https://cloud.google.com/dataproc/ Cloud Dataproc API Reference> for @dataproc.projects.regions.workflowTemplates.delete@.
module Network.Google.Resource.Dataproc.Projects.Regions.WorkflowTemplates.Delete
(
-- * REST Resource
ProjectsRegionsWorkflowTemplatesDeleteResource
-- * Creating a Request
, projectsRegionsWorkflowTemplatesDelete
, ProjectsRegionsWorkflowTemplatesDelete
-- * Request Lenses
, prwtdXgafv
, prwtdUploadProtocol
, prwtdAccessToken
, prwtdUploadType
, prwtdName
, prwtdVersion
, prwtdCallback
) where
import Network.Google.Dataproc.Types
import Network.Google.Prelude
-- | A resource alias for @dataproc.projects.regions.workflowTemplates.delete@ method which the
-- 'ProjectsRegionsWorkflowTemplatesDelete' request conforms to.
type ProjectsRegionsWorkflowTemplatesDeleteResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "version" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Empty
-- | Deletes a workflow template. It does not cancel in-progress workflows.
--
-- /See:/ 'projectsRegionsWorkflowTemplatesDelete' smart constructor.
data ProjectsRegionsWorkflowTemplatesDelete =
ProjectsRegionsWorkflowTemplatesDelete'
{ _prwtdXgafv :: !(Maybe Xgafv)
, _prwtdUploadProtocol :: !(Maybe Text)
, _prwtdAccessToken :: !(Maybe Text)
, _prwtdUploadType :: !(Maybe Text)
, _prwtdName :: !Text
, _prwtdVersion :: !(Maybe (Textual Int32))
, _prwtdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsRegionsWorkflowTemplatesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'prwtdXgafv'
--
-- * 'prwtdUploadProtocol'
--
-- * 'prwtdAccessToken'
--
-- * 'prwtdUploadType'
--
-- * 'prwtdName'
--
-- * 'prwtdVersion'
--
-- * 'prwtdCallback'
projectsRegionsWorkflowTemplatesDelete
:: Text -- ^ 'prwtdName'
-> ProjectsRegionsWorkflowTemplatesDelete
projectsRegionsWorkflowTemplatesDelete pPrwtdName_ =
ProjectsRegionsWorkflowTemplatesDelete'
{ _prwtdXgafv = Nothing
, _prwtdUploadProtocol = Nothing
, _prwtdAccessToken = Nothing
, _prwtdUploadType = Nothing
, _prwtdName = pPrwtdName_
, _prwtdVersion = Nothing
, _prwtdCallback = Nothing
}
-- | V1 error format.
prwtdXgafv :: Lens' ProjectsRegionsWorkflowTemplatesDelete (Maybe Xgafv)
prwtdXgafv
= lens _prwtdXgafv (\ s a -> s{_prwtdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
prwtdUploadProtocol :: Lens' ProjectsRegionsWorkflowTemplatesDelete (Maybe Text)
prwtdUploadProtocol
= lens _prwtdUploadProtocol
(\ s a -> s{_prwtdUploadProtocol = a})
-- | OAuth access token.
prwtdAccessToken :: Lens' ProjectsRegionsWorkflowTemplatesDelete (Maybe Text)
prwtdAccessToken
= lens _prwtdAccessToken
(\ s a -> s{_prwtdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
prwtdUploadType :: Lens' ProjectsRegionsWorkflowTemplatesDelete (Maybe Text)
prwtdUploadType
= lens _prwtdUploadType
(\ s a -> s{_prwtdUploadType = a})
-- | Required. The resource name of the workflow template, as described in
-- https:\/\/cloud.google.com\/apis\/design\/resource_names. For
-- projects.regions.workflowTemplates.delete, the resource name of the
-- template has the following format:
-- projects\/{project_id}\/regions\/{region}\/workflowTemplates\/{template_id}
-- For projects.locations.workflowTemplates.instantiate, the resource name
-- of the template has the following format:
-- projects\/{project_id}\/locations\/{location}\/workflowTemplates\/{template_id}
prwtdName :: Lens' ProjectsRegionsWorkflowTemplatesDelete Text
prwtdName
= lens _prwtdName (\ s a -> s{_prwtdName = a})
-- | Optional. The version of workflow template to delete. If specified, will
-- only delete the template if the current server version matches specified
-- version.
prwtdVersion :: Lens' ProjectsRegionsWorkflowTemplatesDelete (Maybe Int32)
prwtdVersion
= lens _prwtdVersion (\ s a -> s{_prwtdVersion = a})
. mapping _Coerce
-- | JSONP
prwtdCallback :: Lens' ProjectsRegionsWorkflowTemplatesDelete (Maybe Text)
prwtdCallback
= lens _prwtdCallback
(\ s a -> s{_prwtdCallback = a})
instance GoogleRequest
ProjectsRegionsWorkflowTemplatesDelete
where
type Rs ProjectsRegionsWorkflowTemplatesDelete =
Empty
type Scopes ProjectsRegionsWorkflowTemplatesDelete =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsRegionsWorkflowTemplatesDelete'{..}
= go _prwtdName _prwtdXgafv _prwtdUploadProtocol
_prwtdAccessToken
_prwtdUploadType
_prwtdVersion
_prwtdCallback
(Just AltJSON)
dataprocService
where go
= buildClient
(Proxy ::
Proxy ProjectsRegionsWorkflowTemplatesDeleteResource)
mempty
|
brendanhay/gogol
|
gogol-dataproc/gen/Network/Google/Resource/Dataproc/Projects/Regions/WorkflowTemplates/Delete.hs
|
mpl-2.0
| 6,288 | 0 | 16 | 1,274 | 804 | 470 | 334 | 118 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.AdExchangeSeller.Types
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.AdExchangeSeller.Types
(
-- * Service Configuration
adExchangeSellerService
-- * OAuth Scopes
, adExchangeSellerReadOnlyScope
, adExchangeSellerScope
-- * AdClients
, AdClients
, adClients
, acEtag
, acNextPageToken
, acKind
, acItems
-- * ReportingMetadataEntry
, ReportingMetadataEntry
, reportingMetadataEntry
, rmeKind
, rmeRequiredMetrics
, rmeCompatibleMetrics
, rmeRequiredDimensions
, rmeId
, rmeCompatibleDimensions
, rmeSupportedProducts
-- * Accounts
, Accounts
, accounts
, aEtag
, aNextPageToken
, aKind
, aItems
-- * Alerts
, Alerts
, alerts
, aleKind
, aleItems
-- * SavedReports
, SavedReports
, savedReports
, srEtag
, srNextPageToken
, srKind
, srItems
-- * SavedReport
, SavedReport
, savedReport
, sKind
, sName
, sId
-- * URLChannels
, URLChannels
, urlChannels
, ucEtag
, ucNextPageToken
, ucKind
, ucItems
-- * CustomChannels
, CustomChannels
, customChannels
, ccEtag
, ccNextPageToken
, ccKind
, ccItems
-- * Report
, Report
, report
, rKind
, rAverages
, rWarnings
, rRows
, rTotals
, rHeaders
, rTotalMatchedRows
-- * Alert
, Alert
, alert
, aaKind
, aaSeverity
, aaId
, aaType
, aaMessage
-- * Account
, Account
, account
, accKind
, accName
, accId
-- * AdClient
, AdClient
, adClient
, adKind
, adArcOptIn
, adSupportsReporting
, adId
, adProductCode
-- * ReportHeadersItem
, ReportHeadersItem
, reportHeadersItem
, rhiName
, rhiCurrency
, rhiType
-- * CustomChannelTargetingInfo
, CustomChannelTargetingInfo
, customChannelTargetingInfo
, cctiLocation
, cctiSiteLanguage
, cctiAdsAppearOn
, cctiDescription
-- * PreferredDeals
, PreferredDeals
, preferredDeals
, pdKind
, pdItems
-- * Metadata
, Metadata
, metadata
, mKind
, mItems
-- * CustomChannel
, CustomChannel
, customChannel
, cTargetingInfo
, cKind
, cName
, cCode
, cId
-- * URLChannel
, URLChannel
, urlChannel
, urlcKind
, urlcId
, urlcURLPattern
-- * PreferredDeal
, PreferredDeal
, preferredDeal
, pAdvertiserName
, pCurrencyCode
, pStartTime
, pKind
, pBuyerNetworkName
, pEndTime
, pId
, pFixedCpm
) where
import Network.Google.AdExchangeSeller.Types.Product
import Network.Google.AdExchangeSeller.Types.Sum
import Network.Google.Prelude
-- | Default request referring to version 'v2.0' of the Ad Exchange Seller API. This contains the host and root path used as a starting point for constructing service requests.
adExchangeSellerService :: ServiceConfig
adExchangeSellerService
= defaultService (ServiceId "adexchangeseller:v2.0")
"www.googleapis.com"
-- | View your Ad Exchange data
adExchangeSellerReadOnlyScope :: Proxy '["https://www.googleapis.com/auth/adexchange.seller.readonly"]
adExchangeSellerReadOnlyScope = Proxy;
-- | View and manage your Ad Exchange data
adExchangeSellerScope :: Proxy '["https://www.googleapis.com/auth/adexchange.seller"]
adExchangeSellerScope = Proxy;
|
rueshyna/gogol
|
gogol-adexchange-seller/gen/Network/Google/AdExchangeSeller/Types.hs
|
mpl-2.0
| 3,960 | 0 | 7 | 1,114 | 489 | 334 | 155 | 139 | 1 |
module Hands where
import Data.Function (on)
import Data.List (groupBy, sortBy)
import Data.Ord (comparing)
import Types
checkGroups :: [Card] -> (HandRank, [Card])
checkGroups h = (hr, cs)
where groupedByRank = sortByLength $ groupBy ((==) `on` rank) $ sort h
topFive = take 5 $ concat groupedByRank
handRank = case map length groupedByRank of
(4:_) -> Quads
(3:2:_) -> FullHouse
(3:_) -> Trips
(2:2:_) -> TwoPair
(2:_) -> Pair
_ -> HighCard
sortByLength :: Ord a => [[a]] -> [[a]]
sortByLength = reverse . sortBy (comparing length)
|
SPbAU-ProgrammingParadigms/materials
|
haskell_2/poker/Hands.hs
|
unlicense
| 682 | 0 | 12 | 233 | 261 | 145 | 116 | 18 | 6 |
module Git.Command.SendPack (run) where
run :: [String] -> IO ()
run args = return ()
|
wereHamster/yag
|
Git/Command/SendPack.hs
|
unlicense
| 86 | 0 | 7 | 15 | 42 | 23 | 19 | 3 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module HsCocoa where
import Foreign.C
import Data.ByteString.Char8 (unpack)
import Data.Either
import Control.Exception
import System.Log.Logger
import qualified Oauth as O
import Sync
import Http
import Error
foreign export ccall hsInitSync :: IO CString
foreign export ccall hsAuthUrl :: CString -> IO CString
foreign export ccall hsAccessToken :: CString -> CString -> IO CInt
foreign export ccall hsSync :: IO CInt
foreign export ccall hsLogout :: IO ()
foreign export ccall hsLoggedIn :: IO Bool
foreign export ccall hsLocalChanges :: IO Bool
foreign export ccall hsRemoteChanges :: IO CInt
hsInitSync :: IO CString
hsInitSync = do
res <- tryAny (initLogging >> getOrCreateSyncDir)
case res of
Right dir -> newCAString dir
Left e -> warningM "HsCocoa.hsInitSync" (show e) >> newCString ""
hsAuthUrl :: CString -> IO CString
hsAuthUrl s = do
state <- peekCString s
newCString $ unpack $ O.loginUrl (O.State state)
hsAccessToken :: CString -> CString -> IO CInt
hsAccessToken s c = do
state <- peekCString s
code <- peekCString c
result <- tryAny $ withHttp $ O.accessToken (O.State state) (O.AuthCode code)
case result of
Right token -> O.storeAccessToken token >> return 0
Left NotAuthenticated -> return 1
Left e -> warningM "HsCocoa.hsAccessToken" (show e) >> return 99
hsSync :: IO CInt
hsSync = do
res <- tryAny sync
case res of
Right _ -> return 0
Left NotAuthenticated -> return 1
Left e -> warningM "HsCocoa.hsSync" (show e) >> return 99
hsLogout :: IO ()
hsLogout = O.removeAccessToken
hsLoggedIn :: IO Bool
hsLoggedIn = fmap isRight (try O.loadAccessToken :: IO (Either SyncError Http.AccessToken))
hsLocalChanges :: IO Bool
hsLocalChanges = checkLocalChange
hsRemoteChanges :: IO CInt
hsRemoteChanges = do
res <- tryAny checkRemoteChange
case res of
Right True -> return 0
Right False -> return (-1)
Left NotAuthenticated -> return 1
Left e -> warningM "HsCocoa.hsRemoteChanges" (show e) >> return 99
tryAny :: IO a -> IO (Either SyncError a)
tryAny action = do
result <- try action
case result of
Right x -> return $ Right x
Left e -> case fromException e of
Just (se :: SyncError) -> return $ Left se
Nothing -> return $ Left (Unhandled e)
|
froden/digipostarkiv
|
src/HsCocoa.hs
|
apache-2.0
| 2,604 | 0 | 16 | 763 | 824 | 399 | 425 | 67 | 4 |
module PolygonSizes.A328793 (a328793) where
import Data.List (findIndices)
import Data.Set (Set)
import qualified Data.Set as Set
import Helpers.PolygonSizes (triangleSizes)
import HelperSequences.A003136 (a003136)
-- This could be a little faster by using the fact that
-- A328793(A024610(n) + k) > n + 1 for all n > 0, k >= 0.
a328793 :: Int -> Int
a328793 n = 2 + head (findIndices (a003136 n `Set.member`) triangleSizes)
a328793_list :: [Int]
a328793_list = map a328793 [2..]
|
peterokagey/haskellOEIS
|
src/PolygonSizes/A328793.hs
|
apache-2.0
| 482 | 0 | 10 | 75 | 125 | 74 | 51 | 10 | 1 |
import Control.Applicative
import Control.Monad hiding (join)
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Function (on)
import Data.List
import Data.Maybe
import Data.String.Utils (replace, join)
import System.Directory
import System.FilePath.Find
import System.Environment
import System.IO.Unsafe
data TZFile
= Reg String FilePath
| Link String String
deriving (Eq, Show)
data TZDesc
= RegD { _name :: String, _label :: String, _desc :: BL.ByteString }
| LinkD { _name :: String, _target :: String }
deriving (Eq,Show)
-- TODO(klao): remove when/if https://github.com/bos/filemanip/pull/4
-- is merged and released.
canonicalPath' :: FindClause FilePath
canonicalPath' = (unsafePerformIO . canonicalizePath) `liftM` filePath
collect :: FilePath -> IO [TZFile]
collect dir0 = do
dir <- (++ "/") <$> canonicalizePath dir0
let
relname = fromJust . stripPrefix dir
add :: [TZFile] -> FileInfo -> [TZFile]
add l = evalClause $ do
ftype <- fileType
fp <- filePath
let name = relname fp
case ftype of
RegularFile -> return $ Reg name fp : l
SymbolicLink -> do
target <- canonicalPath'
return $ Link name (relname target) : l
_ -> return l
fold always add [] dir
toDesc :: TZFile -> IO TZDesc
toDesc (Link name target)
= return $ LinkD name target
toDesc (Reg name file) = do
desc <- BL.readFile file
return $ RegD name (nameToLabel name) desc
nameToLabel :: String -> String
nameToLabel = replace "-" "_" . replace "+" "" . replace "/" "__"
labelDecl :: [TZDesc] -> String
labelDecl zones = "= " ++ join "\n | " (go zones)
where
go [] = []
go (RegD _ label _ : zs) = label : go zs
go (LinkD _ _ : zs) = go zs
descriptionList :: [TZDesc] -> String
descriptionList = join ",\n " . map f
where
f (LinkD name target) = "l " ++ show name ++ " " ++ show target
f (RegD name label desc) = "p " ++ show name ++ " " ++ label ++ " " ++ show (BL.unpack desc)
genCode :: FilePath -> FilePath -> [TZDesc] -> IO ()
genCode templatePath outputPath zones = do
template <- readFile templatePath
let
code = replace "TZ_DESCRIPTIONS" (descriptionList zones)
$ replace "TZ_LABEL_DECL" (labelDecl zones) template
writeFile outputPath code
sumSize :: [TZDesc] -> Int
sumSize = sum . map s
where
s (LinkD name target) = length name + length target
s (RegD name label desc) = length name + length label + fromIntegral (BL.length desc)
main :: IO ()
main = do
args <- getArgs
case args of
[dir, template, output] -> do
zones0 <- collect dir
zones <- sortBy (compare `on` _name) <$> mapM toDesc zones0
putStrLn $ "Approximate size of the data: " ++ show (sumSize zones)
genCode template output zones
_ -> putStrLn "usage: getZones <zoneinfo-dir> <template> <output>"
|
k0001/haskell-tzdata
|
tools/genZones.hs
|
apache-2.0
| 2,866 | 0 | 22 | 663 | 1,041 | 526 | 515 | 76 | 3 |
module Eval (runEval) where
import Control.Monad.Except
import Control.Monad.Reader
import qualified Data.Map as M
import Data.Monoid ((<>))
import BuiltIn
import EvalState
import LitCust
import Syntax
import Types
eval :: TermEnv -> Expr -> Interpreter EvalError Value
eval env (Expr _ expr) = case expr of
Lit (LNum k) -> return $ VNum k
Lit (LBool k) -> return $ VBool k
Lit (LDate k) -> return $ VDate k
Lit (LText k) -> return $ VText k
Lit (LTimUn k) -> return $ VTimUn k
Lit (LWkSt k) -> return $ VWkSt k
List as -> fmap VList $ mapM (eval env) as
Field k Nothing _ -> throwError $ EvFieldNoValue k
Field _ (Just e) _ -> eval env e
Var x -> case M.lookup x env of
Just v -> return v
Nothing -> case M.lookup x builtIns of
Just _ -> evalBuiltIn $ VBltIn x []
Nothing -> throwError $ EvVarNotFound x
Op op a b -> do
a' <- eval env a
b' <- eval env b
return $ binop op a' b'
Lam x body -> return $ VClosure x body env
App fun arg -> do
argv <- eval env arg
fun' <- eval env fun
case fun' of
VClosure x body clo -> do
let nenv = M.insert x argv clo
eval nenv body
VBltIn x as -> evalBuiltIn $ VBltIn x (argv:as)
_ -> error "Expression applied to a non-function. Something \
\went terribly wrong."
Let x e body -> do
e' <- eval env e
let nenv = M.insert x e' env
eval nenv body
If cond tr fl -> do
VBool br <- eval env cond
if br then eval env tr else eval env fl
-- | Evaluate operators
binop :: Binop -> Value -> Value -> Value
binop Add (VNum a) (VNum b) = VNum $ a + b
binop Mul (VNum a) (VNum b) = VNum $ a * b
binop Sub (VNum a) (VNum b) = VNum $ a - b
binop Div (VNum a) (VNum b) = VNum $ a / b
binop Exp (VNum a) (VNum b) = VNum $ a ** b
binop Eql (VNum a) (VNum b) = VBool $ a == b
binop Eql (VText a) (VText b) = VBool $ a == b
binop Eql (VDate a) (VDate b) = VBool $ a == b
binop Eql (VBool a) (VBool b) = VBool $ a == b
binop Neq (VNum a) (VNum b) = VBool $ a /= b
binop Neq (VText a) (VText b) = VBool $ a /= b
binop Neq (VDate a) (VDate b) = VBool $ a /= b
binop Neq (VBool a) (VBool b) = VBool $ a /= b
binop Gt (VNum a) (VNum b) = VBool $ a > b
binop Gt (VText a) (VText b) = VBool $ a > b
binop Gt (VDate a) (VDate b) = VBool $ a > b
binop Gt (VBool a) (VBool b) = VBool $ a > b
binop Gte (VNum a) (VNum b) = VBool $ a >= b
binop Gte (VText a) (VText b) = VBool $ a >= b
binop Gte (VDate a) (VDate b) = VBool $ a >= b
binop Gte (VBool a) (VBool b) = VBool $ a >= b
binop Lt (VNum a) (VNum b) = VBool $ a < b
binop Lt (VText a) (VText b) = VBool $ a < b
binop Lt (VDate a) (VDate b) = VBool $ a < b
binop Lt (VBool a) (VBool b) = VBool $ a < b
binop Lte (VNum a) (VNum b) = VBool $ a <= b
binop Lte (VText a) (VText b) = VBool $ a <= b
binop Lte (VDate a) (VDate b) = VBool $ a <= b
binop Lte (VBool a) (VBool b) = VBool $ a <= b
binop Cat (VText a) (VText b) = VText $ a <> b
binop And (VBool a) (VBool b) = VBool $ a && b
binop Or (VBool a) (VBool b) = VBool $ a || b
binop _ _ _ = error "Either an operator was added without an eval strategy, or\
\type inference didn't work :-("
runEval :: Est -> TermEnv -> String -> Expr -> IO (Either EvalError (Value, TermEnv))
runEval st env nm ex = flip runReaderT st $ runExceptT $ do
-- runEval :: TermEnv -> String -> Expr -> Either EvalError (Value, TermEnv)
-- runEval env nm ex = runIdentity $ runExceptT $ do
res <- eval env ex
return (res, M.insert nm res env)
|
ahodgen/archer-calc
|
src/Eval.hs
|
bsd-2-clause
| 3,793 | 0 | 19 | 1,229 | 1,828 | 894 | 934 | 85 | 20 |
-- Haskell Torrent
-- Copyright (c) 2009, Jesper Louis Andersen,
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are
-- met:
--
-- * Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- * 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 OWNER 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.
-- | Add a module description here
-- also add descriptions to each function.
module BCode
(
BCode,
Path(..),
encode,
-- encodeBS,
decode,
search,
announce,
comment,
creationDate,
info,
hashInfoDict,
infoLength,
infoName,
infoPieceLength,
infoPieces,
numberPieces,
infoFiles,
prettyPrint,
trackerComplete,
trackerIncomplete,
trackerInterval,
trackerMinInterval,
trackerPeers,
trackerWarning,
trackerError,
toBS,
fromBS )
where
import Control.Monad
import Control.Applicative hiding (many)
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString as B
import Data.Char
import Data.Word
import Data.Int
import Data.Digest.Pure.SHA
import Data.List
import Data.Maybe
import qualified Data.Map as M
import Text.PrettyPrint.HughesPJ hiding (char)
import Data.Serialize
import Data.Serialize.Put
import Data.Serialize.Get
-- | BCode represents the structure of a bencoded file
data BCode = BInt Integer -- ^ An integer
| BString B.ByteString -- ^ A string of bytes
| BArray [BCode] -- ^ An array
| BDict (M.Map B.ByteString BCode) -- ^ A key, value map
deriving (Show, Eq)
data Path = PString B.ByteString
| PInt Int
toW8 :: Char -> Word8
toW8 = fromIntegral . ord
fromW8 :: Word8 -> Char
fromW8 = chr . fromIntegral
toBS :: String -> B.ByteString
toBS = B.pack . map toW8
fromBS :: B.ByteString -> String
fromBS = map fromW8 . B.unpack
instance Serialize BCode where
put (BInt i) = wrap 'i' 'e' $ putShow i
put (BArray arr) = wrap 'l' 'e' . mapM_ put $ arr
put (BDict mp) = wrap 'd' 'e' dict
where dict = mapM_ encPair . M.toList $ mp
encPair (k, v) = put (BString k) >> put v
put (BString s) = do
putShow (B.length s)
putWord8 (toW8 ':')
putByteString s
get = getBInt <|> getBArray <|> getBDict <|> getBString
-- | Get something wrapped in two Chars
getWrapped :: Char -> Char -> Get a -> Get a
getWrapped a b p = char a *> p <* char b
-- | Parses a BInt
getBInt :: Get BCode
getBInt = BInt . read <$> getWrapped 'i' 'e' intP
where intP = ((:) <$> char '-' <*> getDigits) <|> getDigits
-- | Parses a BArray
getBArray :: Get BCode
getBArray = BArray <$> getWrapped 'l' 'e' (many get)
-- | Parses a BDict
getBDict :: Get BCode
getBDict = BDict . M.fromList <$> getWrapped 'd' 'e' (many getPairs)
where getPairs = do
(BString s) <- getBString
x <- get
return (s,x)
-- | Parses a BString
getBString :: Get BCode
getBString = do
count <- getDigits
BString <$> ( char ':' *> getStr (read count :: Integer))
where maxInt = fromIntegral (maxBound :: Int) :: Integer
getStr n | n >= 0 = B.concat <$> (sequence $ getStr' n)
| otherwise = fail $ "read a negative length string, length: " ++ show n
getStr' n | n > maxInt = getByteString maxBound : getStr' (n-maxInt)
| otherwise = [getByteString . fromIntegral $ n]
-- | Get one or more digit characters
getDigits :: Get String
getDigits = many1 digit
-- | Returns a character if it is a digit, fails otherwise. uses isDigit.
digit :: Get Char
digit = do
x <- getCharG
if isDigit x
then return x
else fail $ "Expected digit, got: " ++ show x
-- * Put helper functions
-- | Put an element, wrapped by two characters
wrap :: Char -> Char -> Put -> Put
wrap a b m = do
putWord8 (toW8 a)
m
putWord8 (toW8 b)
-- | Put something as it is shown using @show@
putShow :: Show a => a -> Put
putShow = mapM_ put . show
-- * Get Helper functions
-- | Parse zero or items using a given parser
many :: Get a -> Get [a]
many p = many1 p `mplus` return []
-- | Parse one or more items using a given parser
many1 :: Get a -> Get [a]
many1 p = (:) <$> p <*> many p
-- | Parse a given character
char :: Char -> Get Char
char c = do
x <- getCharG
if x == c
then return c
else fail $ "Expected char: '" ++ c:"' got: '" ++ [x,'\'']
-- | Get a Char. Only works with single byte characters
getCharG :: Get Char
getCharG = fromW8 <$> getWord8
-- BCode helper functions
-- | Return the hash of the info-dict in a torrent file
hashInfoDict :: BCode -> Maybe L.ByteString
hashInfoDict bc =
do ih <- info bc
let encoded = encode ih
return . bytestringDigest . sha1 . L.fromChunks $ [encoded]
toPS :: String -> Path
toPS = PString . toBS
{- Simple search function over BCoded data structures, general case. In practice, we
will prefer some simpler mnemonics -}
search :: [Path] -> BCode -> Maybe BCode
search [] bc = Just bc
search (PInt i : rest) (BArray bs) | i < 0 || i > length bs = Nothing
| otherwise = search rest (bs!!i)
search (PString s : rest) (BDict mp) = M.lookup s mp >>= search rest
search _ _ = Nothing
search' :: String -> BCode -> Maybe B.ByteString
search' str b = case search [toPS str] b of
Nothing -> Nothing
Just (BString s) -> Just s
_ -> Nothing
searchStr :: String -> BCode -> Maybe B.ByteString
searchStr = search'
searchInt :: String -> BCode -> Maybe Integer
searchInt str b = case search [toPS str] b of
Just (BInt i) -> Just i
_ -> Nothing
searchInfo :: String -> BCode -> Maybe BCode
searchInfo str = search [toPS "info", toPS str]
{- Various accessors -}
announce, comment, creationDate :: BCode -> Maybe B.ByteString
announce = search' "announce"
comment = search' "comment"
creationDate = search' "creation date"
{- Tracker accessors -}
trackerComplete, trackerIncomplete, trackerInterval :: BCode -> Maybe Integer
trackerMinInterval :: BCode -> Maybe Integer
trackerComplete = searchInt "complete"
trackerIncomplete = searchInt "incomplete"
trackerInterval = searchInt "interval"
trackerMinInterval = searchInt "min interval"
trackerError, trackerWarning :: BCode -> Maybe B.ByteString
trackerError = searchStr "failure reason"
trackerWarning = searchStr "warning mesage"
trackerPeers :: BCode -> Maybe B.ByteString
trackerPeers = searchStr "peers"
info :: BCode -> Maybe BCode
info = search [toPS "info"]
infoName :: BCode -> Maybe B.ByteString
infoName bc = case search [toPS "info", toPS "name"] bc of
Just (BString s) -> Just s
_ -> Nothing
infoPieceLength ::BCode -> Maybe Integer
infoPieceLength bc = do BInt i <- search [toPS "info", toPS "piece length"] bc
return i
infoLength :: BCode -> Maybe Integer
infoLength bc = maybe length2 Just length1
where
-- |info/length key for single-file torrent
length1 = do BInt i <- search [toPS "info", toPS "length"] bc
return i
-- |length summed from files of multi-file torrent
length2 = sum `fmap`
map snd `fmap`
infoFiles bc
infoPieces :: BCode -> Maybe [B.ByteString]
infoPieces b = do t <- searchInfo "pieces" b
case t of
BString str -> return $ sha1Split str
_ -> mzero
where sha1Split r | r == B.empty = []
| otherwise = block : sha1Split rest
where (block, rest) = B.splitAt 20 r
numberPieces :: BCode -> Maybe Int
numberPieces = fmap length . infoPieces
infoFiles :: BCode -> Maybe [([String], Integer)] -- ^[(filePath, fileLength)]
infoFiles bc = let mbFpath = fromBS `fmap` infoName bc
mbLength = infoLength bc
mbFiles = do BArray fileList <- searchInfo "files" bc
return $ do fileDict@(BDict _) <- fileList
let Just (BInt length) = search [toPS "length"] fileDict
Just (BArray path) = search [toPS "path"] fileDict
path' = map (\(BString s) -> fromBS s) path
return (path', length)
in case (mbFpath, mbLength, mbFiles) of
(Just fpath, _, Just files) ->
Just $
map (\(path, length) ->
(fpath:path, length)
) files
(Just fpath, Just length, _) ->
Just [([fpath], length)]
(_, _, Just files) ->
Just files
_ ->
Nothing
pp :: BCode -> Doc
pp bc =
case bc of
BInt i -> integer i
BString s -> text (show s)
BArray arr -> text "[" <+> (cat $ intersperse comma al) <+> text "]"
where al = map pp arr
BDict mp -> text "{" <+> cat (intersperse comma mpl) <+> text "}"
where mpl = map (\(s, bc') -> text (fromBS s) <+> text "->" <+> pp bc') $ M.toList mp
prettyPrint :: BCode -> String
prettyPrint = render . pp
testDecodeEncodeProp1 :: BCode -> Bool
testDecodeEncodeProp1 m =
let encoded = encode m
decoded = decode encoded
in case decoded of
Left _ -> False
Right m' -> m == m'
testData = [BInt 123,
BInt (-123),
BString (toBS "Hello"),
BString (toBS ['\NUL'..'\255']),
BArray [BInt 1234567890
,toBString "a longer string with eieldei stuff to mess things up"
],
toBDict [
("hello",BInt 3)
,("a key",toBString "and a value")
,("a sub dict",toBDict [
("some stuff",BInt 1)
,("some more stuff", toBString "with a string")
])
]
]
toBDict :: [(String,BCode)] -> BCode
toBDict = BDict . M.fromList . map (\(k,v) -> ((toBS k),v))
toBString :: String -> BCode
toBString = BString . toBS
|
astro/haskell-torrent
|
src/BCode.hs
|
bsd-2-clause
| 11,919 | 0 | 21 | 3,932 | 3,088 | 1,603 | 1,485 | 240 | 4 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module Network.S3.Types
( S3Method (..)
, S3Request (..)
, S3SignedRequest (..)
, S3Header
, getS3Header
, s3Header
, s3HeaderBuilder
) where
import Data.ByteString.UTF8 (ByteString)
import GHC.Generics (Generic)
import Data.Char (isSpace)
import Network.HTTP.Types (Query)
import Data.Time.Clock (UTCTime)
import Blaze.ByteString.Builder (Builder, fromByteString)
import Data.Monoid (mconcat)
import qualified Data.ByteString.Char8 as BS
import qualified Data.CaseInsensitive as CI
newtype S3Header = S3Header { getS3Header :: (ByteString, ByteString) }
deriving (Generic, Show)
data S3Method = S3GET -- ^ GET Request
| S3PUT -- ^ PUT Request
| S3HEAD -- ^ HEAD Request
| S3DELETE -- ^ DELETE Request
deriving (Generic, Show)
data S3Request = S3Request {
s3method :: S3Method -- ^ Type of HTTP Method
, mimeType :: Maybe ByteString -- ^ MIME Type
, bucketName :: ByteString -- ^ Name of Amazon S3 Bucket
, objectName :: ByteString -- ^ Name of Amazon S3 File
, regionName :: ByteString -- ^ Name of Amazon S3 Region
, queryString :: Query -- ^ Optional query string items
, requestTime :: UTCTime -- ^ Requests are valid within a 15 minute window of this timestamp
, payloadHash :: Maybe ByteString -- ^ SHA256 hash string of the payload
, s3headers :: [S3Header] -- ^ Headers
} deriving (Generic, Show)
data S3SignedRequest = S3SignedRequest {
sigHeaders :: [S3Header] -- ^ The headers included in the signed request
, sigDate :: ByteString -- ^ The date you used in creating the signing key.
, sigCredential :: ByteString -- ^ <your-access-key-id>/<date>/<aws-region>/<aws-service>/aws4_request
, sigPolicy :: ByteString -- ^ The Base64-encoded security policy that describes what is permitted in the request
, sigSignature :: ByteString -- ^ (AWS Signature Version 4) The HMAC-SHA256 hash of the security policy.
, sigAlgorithm :: ByteString -- ^ The signing algorithm used. For AWS Signature Version 4, the value is AWS4-HMAC-SHA256.
} deriving (Generic, Show)
trim :: ByteString -> ByteString
trim = BS.dropWhile isSpace . fst . BS.spanEnd isSpace
s3Header :: ByteString -> ByteString -> S3Header
s3Header header value = S3Header (lower, trimmed)
where
lower = CI.foldCase header
trimmed = trim value
s3HeaderBuilder :: S3Header -> Builder
s3HeaderBuilder (S3Header (header,value)) =
mconcat [fromByteString header, ":", fromByteString value, "\n"]
|
dmjio/s3-signer
|
src/Network/S3/Types.hs
|
bsd-2-clause
| 2,818 | 0 | 9 | 757 | 490 | 304 | 186 | 54 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ParallelListComp #-}
module Data.Time.Series where
import Data.Time.Series.Literal
import Data.Time.Series.Periodicity
data Search a where
LookBack :: Int -> Periodicity -> Search a -> Search a
LookForward :: Int -> Periodicity -> Search a -> Search a
LookNear :: Int -> Periodicity -> Search a -> Search a
OrElse :: a -> Search a
data F :: (Timing -> * -> *) -> Timing -> * -> * where
Var :: Lit a => s t a -> F s t a
EMA :: Double -> F s (P u) Double -> F s (P u) Double
PrefixSum :: Num a => F s (P u) a -> F s (P u) a
Sliding :: Int -> (forall s'. F s' (P u) a -> F s' (P Always) a) -> F s (P u) a -> F s (P u) a
Delay :: Int -> F s t a -> F s t a
Step :: F s (P u) a -> F s (P u) Int
Sample :: Search a -> F s t' a -> F s (P u) a
Variant :: F s (P u) a -> F s V a
(:+) :: Num a => F s (P u) a -> F s (P u) a -> F s (P u) a
(:-) :: Num a => F s (P u) a -> F s (P u) a -> F s (P u) a
(:*) :: Num a => F s (P u) a -> F s (P u) a -> F s (P u) a
(:/) :: Fractional a => F s (P u) a -> F s (P u) a -> F s (P u) a
Negate :: Num a => F s t a -> F s t a
Abs :: Num a => F s t a -> F s t a
Signum :: Num a => F s t a -> F s t a
Recip :: Fractional a => F s t a -> F s t a
Filter :: F s (P u) Bool -> F s (P u) a -> F s V a
(:==) :: Eq a => F s (P u) a -> F s (P u) a -> F s (P u) Bool
(:/=) :: Eq a => F s (P u) a -> F s (P u) a -> F s (P u) Bool
(:<=) :: Ord a => F s (P u) a -> F s (P u) a -> F s (P u) Bool
(:<) :: Ord a => F s (P u) a -> F s (P u) a -> F s (P u) Bool
(:>=) :: Ord a => F s (P u) a -> F s (P u) a -> F s (P u) Bool
(:>) :: Ord a => F s (P u) a -> F s (P u) a -> F s (P u) Bool
(:&&) :: F s (P u) Bool -> F s (P u) Bool -> F s (P u) Bool
(:||) :: F s (P u) Bool -> F s (P u) Bool -> F s (P u) Bool
Not :: F s t Bool -> F s t Bool
-- * Passes
Sum :: Num a => F s (P u) a -> F s t a
Median :: Num a => F s (P u) a -> F s t a
First :: F s (P u) a -> F s t a
Last :: F s (P u) a -> F s t a
Min :: Ord a => F s (P u) a -> F s t a
Max :: Ord a => F s (P u) a -> F s t a
ArgMin :: Ord a => F s (P u) a -> F s (P u) b -> F s t b
ArgMax :: Ord a => F s (P u) a -> F s (P u) b -> F s t b
-- need Count
By :: F s (P u) a -> (forall s'. F s' (P ub) a -> F s' (P u) b -> F s' (P Always) c) -> F s (P u) b -> F s (P u) c
-- Sorting :: [(F t a, Dir)] -> (forall s. Sorted s => F s bs -> F s c) -> F t bs -> F t c
class Periodic t where
ema :: Double -> F s t Double -> F s t Double
instance Periodic (P u) where
ema = EMA
{-
mean x = sum x / (last step + 1)
mad f = median (abs (f - median f))
-}
|
ekmett/time-series
|
src/Data/Time/Series.hs
|
bsd-3-clause
| 3,070 | 0 | 14 | 1,091 | 1,849 | 912 | 937 | 58 | 0 |
import Control.Monad
import Data.Maybe
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import System.Console.GetOpt
import System.Environment
import System.Exit
import Command
import Types
import Game hiding (id)
import qualified Game
import Play
import Util
data Options
= Options
{ optPhrases :: [String]
, optDisplayMode :: DisplayMode
, optWaitSec :: Double
, optHelp :: Bool
}
defaultOptions :: Options
defaultOptions
= Options
{ optPhrases = []
, optDisplayMode = DisplayAll
, optWaitSec = 0
, optHelp = False
}
options :: [OptDescr (Options -> Options)]
options =
[ Option "p" [] (ReqArg (\val opt -> opt{ optPhrases = val : optPhrases opt }) "STRING") "Phrase of power"
, Option [] ["all-phrases"] (NoArg (\opt -> opt{ optPhrases = phrases ++ optPhrases opt }) ) "Enable all phrases"
, Option [] ["display-mode"] (ReqArg (\val opt -> opt{ optDisplayMode = parseDisplayMode val }) "str") "display mode: all, locked, none"
, Option [] ["wait"] (ReqArg (\val opt -> opt{ optWaitSec = read val }) "double") "wait (in sec)"
, Option "h" ["help"] (NoArg (\opt -> opt{ optHelp = True }) ) "Print help message"
]
where
parseDisplayMode "all" = DisplayAll
parseDisplayMode "locked" = DisplayLocked
parseDisplayMode "none" = DisplayNone
parseDisplayMode s = error $ "unknown display mode: " ++ s
main :: IO ()
main = do
args <- getArgs
case getOpt Permute options args of
(_,_,errs@(_:_)) -> do
mapM_ putStrLn errs
exitFailure
(o,args2,[]) -> do
let opt = foldl (flip id) defaultOptions o
forM_ args2 $ \fname -> do
Just output <- readOutput fname
forM_ output $ \o -> do
let probId = Game.problemId o
Just input <- Util.readProblem $ "problems/problem_" ++ show (Game.problemId o) ++ ".json"
let gm = initGameState input (optPhrases opt) (Game.seed o)
let player = replayPlayer $ stringToCommands $ (Game.solution o)
_ <- autoPlay3 (optDisplayMode opt) (optWaitSec opt) player gm
return ()
_ -> help
help :: IO ()
help = putStrLn $ usageInfo "USAGE: replay [OPTIONS] -p STRING -p STRING .. -f FILENAME -f FILENAME .. FILENAME .." options
|
msakai/icfpc2015
|
tools/replay.hs
|
bsd-3-clause
| 2,273 | 0 | 26 | 545 | 755 | 401 | 354 | 58 | 4 |
{-# LANGUAGE CPP, BangPatterns, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_HADDOCK hide #-}
{- | Copyright : (c) 2010-2011 Simon Meier
License : BSD3-style (see LICENSE)
Maintainer : Simon Meier <[email protected]>
Stability : experimental
Portability : GHC
An /encoding/ is a conversion function of Haskell values to sequences of bytes.
A /fixed(-size) encoding/ is an encoding that always results in sequence of bytes
of a pre-determined, fixed length.
An example for a fixed encoding is the big-endian encoding of a 'Word64',
which always results in exactly 8 bytes.
A /bounded(-size) encoding/ is an encoding that always results in sequence
of bytes that is no larger than a pre-determined bound.
An example for a bounded encoding is the UTF-8 encoding of a 'Char',
which results always in less or equal to 4 bytes.
Note that every fixed encoding is also a bounded encoding.
We explicitly identify fixed encodings because they allow some optimizations
that are impossible with bounded encodings.
In the following,
we first motivate the use of bounded encodings
and then give examples of optimizations
that are only possible with fixed encodings.
Typicall, encodings are implemented efficiently by allocating a buffer
(a mutable array of bytes)
and repeatedly executing the following two steps:
(1) writing to the buffer until it is full and
(2) handing over the filled part to the consumer of the encoded value.
Step (1) is where bounded encodings are used.
We must use a bounded encoding,
as we must check that there is enough free space
/before/ actually writing to the buffer.
In term of expressivity,
it would be sufficient to construct all encodings
from the single fixed encoding that encodes a 'Word8' as-is.
However,
this is not sufficient in terms of efficiency.
It results in unnecessary buffer-full checks and
it complicates the program-flow for writing to the buffer,
as buffer-full checks are interleaved with analyzing the value to be
encoded (e.g., think about the program-flow for UTF-8 encoding).
This has a significant effect on overall encoding performance,
as encoding primitive Haskell values such as 'Word8's or 'Char's
lies at the heart of every encoding implementation.
The 'BoundedPrim's provided by this module remove this performance problem.
Intuitively,
they consist of a tuple of the bound on the maximal number of bytes written
and the actual implementation of the encoding as
a function that modifies a mutable buffer.
Hence when executing a 'BoundedPrim',
the buffer-full check can be done once before the actual writing to the buffer.
The provided 'BoundedPrim's also take care to implement the
actual writing to the buffer efficiently.
Moreover, combinators are provided to construct new bounded encodings
from the provided ones.
The result of an encoding can be consumed efficiently,
if it is represented as a sequence of large enough
/chunks/ of consecutive memory (i.e., C @char@ arrays).
The precise meaning of /large enough/ is application dependent.
Typically, an average chunk size between 4kb and 32kb is suitable
for writing the result to disk or sending it over the network.
We desire large enough chunk sizes because each chunk boundary
incurs extra work that we must be able to amortize.
The need for fixed-size encodings arises when considering
the efficient implementation of encodings that require the encoding of a
value to be prefixed with the size of the resulting sequence of bytes.
An efficient implementation avoids unnecessary buffer
We can implement this efficiently as follows.
We first reserve the space for the encoding of the size.
Then, we encode the value.
Finally, we encode the size of the resulting sequence of bytes into
the reserved space.
For this to work
This works only if the encoding resulting size fits
by first, reserving the space for the encoding
of the size, then performing the
For efficiency,
we want to avoid unnecessary copying.
For example, the HTTP/1.0 requires the size of the body to be given in
the Content-Length field.
chunked-transfer encoding requires each chunk to
be prefixed with the hexadecimal encoding of the chunk size.
-}
{-
--
--
-- A /bounded encoding/ is an encoding that never results in a sequence
-- longer than some fixed number of bytes. This number of bytes must be
-- independent of the value being encoded. Typical examples of bounded
-- encodings are the big-endian encoding of a 'Word64', which results always
-- in exactly 8 bytes, or the UTF-8 encoding of a 'Char', which results always
-- in less or equal to 4 bytes.
--
-- Typically, encodings are implemented efficiently by allocating a buffer (an
-- array of bytes) and repeatedly executing the following two steps: (1)
-- writing to the buffer until it is full and (2) handing over the filled part
-- to the consumer of the encoded value. Step (1) is where bounded encodings
-- are used. We must use a bounded encoding, as we must check that there is
-- enough free space /before/ actually writing to the buffer.
--
-- In term of expressivity, it would be sufficient to construct all encodings
-- from the single bounded encoding that encodes a 'Word8' as-is. However,
-- this is not sufficient in terms of efficiency. It results in unnecessary
-- buffer-full checks and it complicates the program-flow for writing to the
-- buffer, as buffer-full checks are interleaved with analyzing the value to be
-- encoded (e.g., think about the program-flow for UTF-8 encoding). This has a
-- significant effect on overall encoding performance, as encoding primitive
-- Haskell values such as 'Word8's or 'Char's lies at the heart of every
-- encoding implementation.
--
-- The bounded 'Encoding's provided by this module remove this performance
-- problem. Intuitively, they consist of a tuple of the bound on the maximal
-- number of bytes written and the actual implementation of the encoding as a
-- function that modifies a mutable buffer. Hence when executing a bounded
-- 'Encoding', the buffer-full check can be done once before the actual writing
-- to the buffer. The provided 'Encoding's also take care to implement the
-- actual writing to the buffer efficiently. Moreover, combinators are
-- provided to construct new bounded encodings from the provided ones.
--
-- A typical example for using the combinators is a bounded 'Encoding' that
-- combines escaping the ' and \\ characters with UTF-8 encoding. More
-- precisely, the escaping to be done is the one implemented by the following
-- @escape@ function.
--
-- > escape :: Char -> [Char]
-- > escape '\'' = "\\'"
-- > escape '\\' = "\\\\"
-- > escape c = [c]
--
-- The bounded 'Encoding' that combines this escaping with UTF-8 encoding is
-- the following.
--
-- > import Data.ByteString.Builder.Prim.Utf8 (char)
-- >
-- > {-# INLINE escapeChar #-}
-- > escapeUtf8 :: BoundedPrim Char
-- > escapeUtf8 =
-- > encodeIf ('\'' ==) (char <#> char #. const ('\\','\'')) $
-- > encodeIf ('\\' ==) (char <#> char #. const ('\\','\\')) $
-- > char
--
-- The definition of 'escapeUtf8' is more complicated than 'escape', because
-- the combinators ('encodeIf', 'encodePair', '#.', and 'char') used in
-- 'escapeChar' compute both the bound on the maximal number of bytes written
-- (8 for 'escapeUtf8') as well as the low-level buffer manipulation required
-- to implement the encoding. Bounded 'Encoding's should always be inlined.
-- Otherwise, the compiler cannot compute the bound on the maximal number of
-- bytes written at compile-time. Without inlinining, it would also fail to
-- optimize the constant encoding of the escape characters in the above
-- example. Functions that execute bounded 'Encoding's also perform
-- suboptimally, if the definition of the bounded 'Encoding' is not inlined.
-- Therefore we add an 'INLINE' pragma to 'escapeUtf8'.
--
-- Currently, the only library that executes bounded 'Encoding's is the
-- 'bytestring' library (<http://hackage.haskell.org/package/bytestring>). It
-- uses bounded 'Encoding's to implement most of its lazy bytestring builders.
-- Executing a bounded encoding should be done using the corresponding
-- functions in the lazy bytestring builder 'Extras' module.
--
-- TODO: Merge with explanation/example below
--
-- Bounded 'E.Encoding's abstract encodings of Haskell values that can be implemented by
-- writing a bounded-size sequence of bytes directly to memory. They are
-- lifted to conversions from Haskell values to 'Builder's by wrapping them
-- with a bound-check. The compiler can implement this bound-check very
-- efficiently (i.e, a single comparison of the difference of two pointers to a
-- constant), because the bound of a 'E.Encoding' is always independent of the
-- value being encoded and, in most cases, a literal constant.
--
-- 'E.Encoding's are the primary means for defining conversion functions from
-- primitive Haskell values to 'Builder's. Most 'Builder' constructors
-- provided by this library are implemented that way.
-- 'E.Encoding's are also used to construct conversions that exploit the internal
-- representation of data-structures.
--
-- For example, 'encodeByteStringWith' works directly on the underlying byte
-- array and uses some tricks to reduce the number of variables in its inner
-- loop. Its efficiency is exploited for implementing the @filter@ and @map@
-- functions in "Data.ByteString.Lazy" as
--
-- > import qualified Data.ByteString.Builder.Prim as P
-- >
-- > filter :: (Word8 -> Bool) -> ByteString -> ByteString
-- > filter p = toLazyByteString . encodeLazyByteStringWithB write
-- > where
-- > write = P.condB p P.word8 P.emptyB
-- >
-- > map :: (Word8 -> Word8) -> ByteString -> ByteString
-- > map f = toLazyByteString . encodeLazyByteStringWithB (E.word8 E.#. f)
--
-- Compared to earlier versions of @filter@ and @map@ on lazy 'L.ByteString's,
-- these versions use a more efficient inner loop and have the additional
-- advantage that they always result in well-chunked 'L.ByteString's; i.e, they
-- also perform automatic defragmentation.
--
-- We can also use 'E.Encoding's to improve the efficiency of the following
-- 'renderString' function from our UTF-8 CSV table encoding example in
-- "Data.ByteString.Builder".
--
-- > renderString :: String -> Builder
-- > renderString cs = charUtf8 '"' <> foldMap escape cs <> charUtf8 '"'
-- > where
-- > escape '\\' = charUtf8 '\\' <> charUtf8 '\\'
-- > escape '\"' = charUtf8 '\\' <> charUtf8 '\"'
-- > escape c = charUtf8 c
--
-- The idea is to save on 'mappend's by implementing a 'E.Encoding' that escapes
-- characters and using 'encodeListWith', which implements writing a list of
-- values with a tighter inner loop and no 'mappend'.
--
-- > import Data.ByteString.Builder.Extra -- assume these
-- > import Data.ByteString.Builder.Prim -- imports are present
-- > ( BoundedPrim, encodeIf, (<#>), (#.) )
-- > import Data.ByteString.Builder.Prim.Utf8 (char)
-- >
-- > renderString :: String -> Builder
-- > renderString cs =
-- > charUtf8 '"' <> encodeListWithB escapedUtf8 cs <> charUtf8 '"'
-- > where
-- > escapedUtf8 :: BoundedPrim Char
-- > escapedUtf8 =
-- > encodeIf (== '\\') (char <#> char #. const ('\\', '\\')) $
-- > encodeIf (== '\"') (char <#> char #. const ('\\', '\"')) $
-- > char
--
-- This 'Builder' considers a buffer with less than 8 free bytes as full. As
-- all functions are inlined, the compiler is able to optimize the constant
-- 'E.Encoding's as two sequential 'poke's. Compared to the first implementation of
-- 'renderString' this implementation is 1.7x faster.
--
-}
{-
Internally, 'Builder's are buffer-fill operations that are
given a continuation buffer-fill operation and a buffer-range to be filled.
A 'Builder' first checks if the buffer-range is large enough. If that's
the case, the 'Builder' writes the sequences of bytes to the buffer and
calls its continuation. Otherwise, it returns a signal that it requires a
new buffer together with a continuation to be called on this new buffer.
Ignoring the rare case of a full buffer-range, the execution cost of a
'Builder' consists of three parts:
1. The time taken to read the parameters; i.e., the buffer-fill
operation to call after the 'Builder' is done and the buffer-range to
fill.
2. The time taken to check for the size of the buffer-range.
3. The time taken for the actual encoding.
We can reduce cost (1) by ensuring that fewer buffer-fill function calls are
required. We can reduce cost (2) by fusing buffer-size checks of sequential
writes. For example, when escaping a 'String' using 'renderString', it would
be sufficient to check before encoding a character that at least 8 bytes are
free. We can reduce cost (3) by implementing better primitive 'Builder's.
For example, 'renderCell' builds an intermediate list containing the decimal
representation of an 'Int'. Implementing a direct decimal encoding of 'Int's
to memory would be more efficient, as it requires fewer buffer-size checks
and less allocation. It is also a planned extension of this library.
The first two cost reductions are supported for user code through functions
in "Data.ByteString.Builder.Extra". There, we continue the above example
and drop the generation time to 0.8ms by implementing 'renderString' more
cleverly. The third reduction requires meddling with the internals of
'Builder's and is not recomended in code outside of this library. However,
patches to this library are very welcome.
-}
module Data.ByteString.Builder.Prim.Extra (
-- * Base-128, variable-length binary encodings
{- |
There are many options for implementing a base-128 (i.e, 7-bit),
variable-length encoding. The encoding implemented here is the one used by
Google's protocol buffer library
<http://code.google.com/apis/protocolbuffers/docs/encoding.html#varints>. This
encoding can be implemented efficiently and provides the desired property that
small positive integers result in short sequences of bytes. It is intended to
be used for the new default binary serialization format of the differently
sized 'Word' types. It works as follows.
The most-significant bit (MSB) of each output byte indicates whether
there is a following byte (MSB set to 1) or it is the last byte (MSB set to 0).
The remaining 7-bits are used to encode the input starting with the least
significant 7-bit group of the input (i.e., a little-endian ordering of the
7-bit groups is used).
For example, the value @1 :: Int@ is encoded as @[0x01]@. The value
@128 :: Int@, whose binary representation is @1000 0000@, is encoded as
@[0x80, 0x01]@; i.e., the first byte has its MSB set and the least significant
7-bit group is @000 0000@, the second byte has its MSB not set (it is the last
byte) and its 7-bit group is @000 0001@.
-}
word8Var
, word16Var
, word32Var
, word64Var
, wordVar
{- |
The following encodings work by casting the signed integer to the equally sized
unsigned integer. This works well for positive integers, but for negative
integers it always results in the longest possible sequence of bytes,
as their MSB is (by definition) always set.
-}
, int8Var
, int16Var
, int32Var
, int64Var
, intVar
{- |
Positive and negative integers of small magnitude can be encoded compactly
using the so-called ZigZag encoding
(<http://code.google.com/apis/protocolbuffers/docs/encoding.html#types>).
The /ZigZag encoding/ uses
even numbers to encode the postive integers and
odd numbers to encode the negative integers.
For example,
@0@ is encoded as @0@, @-1@ as @1@, @1@ as @2@, @-2@ as @3@, @2@ as @4@, and
so on.
Its efficient implementation uses some bit-level magic.
For example
@
zigZag32 :: 'Int32' -> 'Word32'
zigZag32 n = fromIntegral ((n \`shiftL\` 1) \`xor\` (n \`shiftR\` 31))
@
Note that the 'shiftR' is an arithmetic shift that performs sign extension.
The ZigZag encoding essentially swaps the LSB with the MSB and additionally
inverts all bits if the MSB is set.
The following encodings implement the combintion of ZigZag encoding
together with the above base-128, variable length encodings.
They are intended to become the the new default binary serialization format of
the differently sized 'Int' types.
-}
, int8VarSigned
, int16VarSigned
, int32VarSigned
, int64VarSigned
, intVarSigned
-- * Chunked / size-prefixed encodings
{- |
Some encodings like ASN.1 BER <http://en.wikipedia.org/wiki/Basic_Encoding_Rules>
or Google's protocol buffers <http://code.google.com/p/protobuf/> require
encoded data to be prefixed with its length. The simple method to achieve this
is to encode the data first into a separate buffer, compute the length of the
encoded data, write it to the current output buffer, and append the separate
buffers. The drawback of this method is that it requires a ...
-}
, size
, sizeBound
-- , withSizeFB
-- , withSizeBB
, encodeWithSize
, encodeChunked
, wordVarFixedBound
, wordHexFixedBound
, wordDecFixedBound
, word64VarFixedBound
, word64HexFixedBound
, word64DecFixedBound
) where
import Data.ByteString.Builder.Internal
import Data.ByteString.Builder.Prim.Internal.UncheckedShifts
import Data.ByteString.Builder.Prim.Internal.Base16 (lowerTable, encode4_as_8)
import qualified Data.ByteString as S
import qualified Data.ByteString.Internal as S
import qualified Data.ByteString.Lazy.Internal as L
import Data.Monoid
import Data.List (unfoldr) -- HADDOCK ONLY
import Data.Char (chr, ord)
import Control.Monad ((<=<), unless)
import Data.ByteString.Builder.Prim.Internal hiding (size, sizeBound)
import qualified Data.ByteString.Builder.Prim.Internal as I (size, sizeBound)
import Data.ByteString.Builder.Prim.Binary
import Data.ByteString.Builder.Prim.ASCII
import Data.ByteString.Builder.Prim
import Foreign
------------------------------------------------------------------------------
-- Adapting 'size' for the public interface.
------------------------------------------------------------------------------
-- | The size of the sequence of bytes generated by this 'FixedPrim'.
size :: FixedPrim a -> Word
size = fromIntegral . I.size
-- | The bound on the size of the sequence of bytes generated by this
-- 'BoundedPrim'.
sizeBound :: BoundedPrim a -> Word
sizeBound = fromIntegral . I.sizeBound
------------------------------------------------------------------------------
-- Base-128 Variable-Length Encodings
------------------------------------------------------------------------------
{-# INLINE encodeBase128 #-}
encodeBase128
:: forall a b. (Integral a, Bits a, Storable b, Integral b, Num b)
=> (a -> Int -> a) -> BoundedPrim b
encodeBase128 shiftr =
-- We add 6 because we require the result of (`div` 7) to be rounded up.
boundedEncoding ((8 * sizeOf (undefined :: b) + 6) `div` 7) (io . fromIntegral)
where
io !x !op
| x' == 0 = do poke8 (x .&. 0x7f)
return $! op `plusPtr` 1
| otherwise = do poke8 ((x .&. 0x7f) .|. 0x80)
io x' (op `plusPtr` 1)
where
x' = x `shiftr` 7
poke8 = poke op . fromIntegral
-- | Base-128, variable length encoding of a 'Word8'.
{-# INLINE word8Var #-}
word8Var :: BoundedPrim Word8
word8Var = encodeBase128 shiftr_w
-- | Base-128, variable length encoding of a 'Word16'.
{-# INLINE word16Var #-}
word16Var :: BoundedPrim Word16
word16Var = encodeBase128 shiftr_w
-- | Base-128, variable length encoding of a 'Word32'.
{-# INLINE word32Var #-}
word32Var :: BoundedPrim Word32
word32Var = encodeBase128 shiftr_w32
-- | Base-128, variable length encoding of a 'Word64'.
{-# INLINE word64Var #-}
word64Var :: BoundedPrim Word64
word64Var = encodeBase128 shiftr_w64
-- | Base-128, variable length encoding of a 'Word'.
{-# INLINE wordVar #-}
wordVar :: BoundedPrim Word
wordVar = encodeBase128 shiftr_w
-- | Base-128, variable length encoding of an 'Int8'.
-- Use 'int8VarSigned' for encoding negative numbers.
{-# INLINE int8Var #-}
int8Var :: BoundedPrim Int8
int8Var = fromIntegral >$< word8Var
-- | Base-128, variable length encoding of an 'Int16'.
-- Use 'int16VarSigned' for encoding negative numbers.
{-# INLINE int16Var #-}
int16Var :: BoundedPrim Int16
int16Var = fromIntegral >$< word16Var
-- | Base-128, variable length encoding of an 'Int32'.
-- Use 'int32VarSigned' for encoding negative numbers.
{-# INLINE int32Var #-}
int32Var :: BoundedPrim Int32
int32Var = fromIntegral >$< word32Var
-- | Base-128, variable length encoding of an 'Int64'.
-- Use 'int64VarSigned' for encoding negative numbers.
{-# INLINE int64Var #-}
int64Var :: BoundedPrim Int64
int64Var = fromIntegral >$< word64Var
-- | Base-128, variable length encoding of an 'Int'.
-- Use 'intVarSigned' for encoding negative numbers.
{-# INLINE intVar #-}
intVar :: BoundedPrim Int
intVar = fromIntegral >$< wordVar
{-# INLINE zigZag #-}
zigZag :: (Storable a, Bits a) => a -> a
zigZag x = (x `shiftL` 1) `xor` (x `shiftR` (8 * sizeOf x - 1))
-- | Base-128, variable length, ZigZag encoding of an 'Int'.
{-# INLINE int8VarSigned #-}
int8VarSigned :: BoundedPrim Int8
int8VarSigned = zigZag >$< int8Var
-- | Base-128, variable length, ZigZag encoding of an 'Int16'.
{-# INLINE int16VarSigned #-}
int16VarSigned :: BoundedPrim Int16
int16VarSigned = zigZag >$< int16Var
-- | Base-128, variable length, ZigZag encoding of an 'Int32'.
{-# INLINE int32VarSigned #-}
int32VarSigned :: BoundedPrim Int32
int32VarSigned = zigZag >$< int32Var
-- | Base-128, variable length, ZigZag encoding of an 'Int64'.
{-# INLINE int64VarSigned #-}
int64VarSigned :: BoundedPrim Int64
int64VarSigned = zigZag >$< int64Var
-- | Base-128, variable length, ZigZag encoding of an 'Int'.
{-# INLINE intVarSigned #-}
intVarSigned :: BoundedPrim Int
intVarSigned = zigZag >$< intVar
------------------------------------------------------------------------------
-- Chunked Encoding Transformer
------------------------------------------------------------------------------
-- | /Heavy inlining./
{-# INLINE encodeChunked #-}
encodeChunked
:: Word -- ^ Minimal free-size
-> (Word64 -> FixedPrim Word64)
-- ^ Given a sizeBound on the maximal encodable size this function must return
-- a fixed-size encoding for encoding all smaller size.
-> (BoundedPrim Word64)
-- ^ An encoding for terminating a chunk of the given size.
-> Builder
-- ^ Inner Builder to transform
-> Builder
-- ^ 'Put' with chunked encoding.
encodeChunked minFree mkBeforeFE afterBE =
fromPut . putChunked minFree mkBeforeFE afterBE . putBuilder
-- | /Heavy inlining./
{-# INLINE putChunked #-}
putChunked
:: Word -- ^ Minimal free-size
-> (Word64 -> FixedPrim Word64)
-- ^ Given a sizeBound on the maximal encodable size this function must return
-- a fixed-size encoding for encoding all smaller size.
-> (BoundedPrim Word64)
-- ^ Encoding a directly inserted chunk.
-> Put a
-- ^ Inner Put to transform
-> Put a
-- ^ 'Put' with chunked encoding.
putChunked minFree0 mkBeforeFE afterBE p =
put encodingStep
where
minFree, reservedAfter, maxReserved, minBufferSize :: Int
minFree = fromIntegral $ max 1 minFree0 -- sanitize and convert to Int
-- reserved space must be computed for maximum buffer size to cover for all
-- sizes of the actually returned buffer.
reservedAfter = I.sizeBound afterBE
maxReserved = I.size (mkBeforeFE maxBound) + reservedAfter
minBufferSize = minFree + maxReserved
encodingStep k =
fill (runPut p)
where
fill innerStep !(BufferRange op ope)
| outRemaining < minBufferSize =
return $! bufferFull minBufferSize op (fill innerStep)
| otherwise = do
fillWithBuildStep innerStep doneH fullH insertChunksH brInner
where
outRemaining = ope `minusPtr` op
beforeFE = mkBeforeFE $ fromIntegral outRemaining
reservedBefore = I.size beforeFE
opInner = op `plusPtr` reservedBefore
opeInner = ope `plusPtr` (-reservedAfter)
brInner = BufferRange opInner opeInner
wrapChunk :: Ptr Word8 -> IO (Ptr Word8)
wrapChunk !opInner'
| innerSize == 0 = return op -- no data written => no chunk to wrap
| otherwise = do
runF beforeFE innerSize op
runB afterBE innerSize opInner'
where
innerSize = fromIntegral $ opInner' `minusPtr` opInner
doneH opInner' x = do
op' <- wrapChunk opInner'
let !br' = BufferRange op' ope
k x br'
fullH opInner' minSize nextInnerStep = do
op' <- wrapChunk opInner'
return $! bufferFull
(max minBufferSize (minSize + maxReserved))
op'
(fill nextInnerStep)
insertChunksH opInner' n lbsC nextInnerStep
| n == 0 = do -- flush
op' <- wrapChunk opInner'
return $! insertChunks op' 0 id (fill nextInnerStep)
| otherwise = do -- insert non-empty bytestring
op' <- wrapChunk opInner'
let !br' = BufferRange op' ope
runBuilderWith chunkB (fill nextInnerStep) br'
where
nU = fromIntegral n
chunkB =
primFixed (mkBeforeFE nU) nU `mappend`
lazyByteStringC n lbsC `mappend`
primBounded afterBE nU
-- | /Heavy inlining./ Prefix a 'Builder' with the size of the
-- sequence of bytes that it denotes.
--
-- This function is optimized for streaming use. It tries to prefix the size
-- without copying the output. This is achieved by reserving space for the
-- maximum size to be encoded. This succeeds if the output is smaller than
-- the current free buffer size, which is guaranteed to be at least @8kb@.
--
-- If the output does not fit into the current free buffer size,
-- the method falls back to encoding the data to a separate lazy bytestring,
-- computing the size, and encoding the size before inserting the chunks of
-- the separate lazy bytestring.
{-# INLINE encodeWithSize #-}
encodeWithSize
::
Word
-- ^ Inner buffer-size.
-> (Word64 -> FixedPrim Word64)
-- ^ Given a bound on the maximal size to encode, this function must return
-- a fixed-size encoding for all smaller sizes.
-> Builder
-- ^ 'Put' to prefix with the length of its sequence of bytes.
-> Builder
encodeWithSize innerBufSize mkSizeFE =
fromPut . putWithSize innerBufSize mkSizeFE . putBuilder
-- | Prefix a 'Put' with the size of its written data.
{-# INLINE putWithSize #-}
putWithSize
:: forall a.
Word
-- ^ Buffer-size for inner driver.
-> (Word64 -> FixedPrim Word64)
-- ^ Encoding the size for the fallback case.
-> Put a
-- ^ 'Put' to prefix with the length of its sequence of bytes.
-> Put a
putWithSize innerBufSize mkSizeFE innerP =
put $ encodingStep
where
-- | The minimal free size is such that we can encode any size.
minFree = I.size $ mkSizeFE maxBound
encodingStep :: (forall r. (a -> BuildStep r) -> BuildStep r)
encodingStep k =
fill (runPut innerP)
where
fill :: BuildStep a -> BufferRange -> IO (BuildSignal r)
fill innerStep !(BufferRange op ope)
| outRemaining < minFree =
return $! bufferFull minFree op (fill innerStep)
| otherwise = do
fillWithBuildStep innerStep doneH fullH insertChunksH brInner
where
outRemaining = ope `minusPtr` op
sizeFE = mkSizeFE $ fromIntegral outRemaining
reservedBefore = I.size sizeFE
reservedAfter = minFree - reservedBefore
-- leave enough free space such that all sizes can be encodded.
startInner = op `plusPtr` reservedBefore
opeInner = ope `plusPtr` (negate reservedAfter)
brInner = BufferRange startInner opeInner
fastPrefixSize :: Ptr Word8 -> IO (Ptr Word8)
fastPrefixSize !opInner'
| innerSize == 0 = do runB (toB $ mkSizeFE 0) 0 op
| otherwise = do runF (sizeFE) innerSize op
return opInner'
where
innerSize = fromIntegral $ opInner' `minusPtr` startInner
slowPrefixSize :: Ptr Word8 -> Builder -> BuildStep a -> IO (BuildSignal r)
slowPrefixSize opInner' bInner nextStep = do
(x, chunks, payLenChunks) <- toLBS $ runBuilderWith bInner nextStep
let -- length of payload data in current buffer
payLenCur = opInner' `minusPtr` startInner
-- length of whole payload
payLen = fromIntegral payLenCur + fromIntegral payLenChunks
-- encoder for payload length
sizeFE' = mkSizeFE payLen
-- start of payload in current buffer with the payload
-- length encoded before
startInner' = op `plusPtr` I.size sizeFE'
-- move data in current buffer out of the way, if required
unless (startInner == startInner') $
moveBytes startInner' startInner payLenCur
-- encode payload length at start of the buffer
runF sizeFE' payLen op
-- TODO: If we were to change the CIOS definition such that it also
-- returns the last buffer for writing, we could also fill the
-- last buffer with 'k' and return the signal, once it is
-- filled, therefore avoiding unfilled space.
return $ insertChunks (startInner' `plusPtr` payLenCur)
payLenChunks
chunks
(k x)
where
toLBS = runCIOSWithLength <=<
buildStepToCIOSUntrimmedWith (fromIntegral innerBufSize)
doneH :: Ptr Word8 -> a -> IO (BuildSignal r)
doneH opInner' x = do
op' <- fastPrefixSize opInner'
let !br' = BufferRange op' ope
k x br'
fullH :: Ptr Word8 -> Int -> BuildStep a -> IO (BuildSignal r)
fullH opInner' minSize nextInnerStep =
slowPrefixSize opInner' (ensureFree minSize) nextInnerStep
insertChunksH :: Ptr Word8 -> Int64 -> LazyByteStringC
-> BuildStep a -> IO (BuildSignal r)
insertChunksH opInner' n lbsC nextInnerStep =
slowPrefixSize opInner' (lazyByteStringC n lbsC) nextInnerStep
-- | Run a 'ChunkIOStream' and gather its results and their length.
runCIOSWithLength :: ChunkIOStream a -> IO (a, LazyByteStringC, Int64)
runCIOSWithLength =
go 0 id
where
go !l lbsC (Finished x) = return (x, lbsC, l)
go !l lbsC (YieldC n lbsC' io) = io >>= go (l + n) (lbsC . lbsC')
go !l lbsC (Yield1 bs io) =
io >>= go (l + fromIntegral (S.length bs)) (lbsC . L.Chunk bs)
-- | Run a 'BuildStep' using the untrimmed strategy.
buildStepToCIOSUntrimmedWith :: Int -> BuildStep a -> IO (ChunkIOStream a)
buildStepToCIOSUntrimmedWith bufSize =
buildStepToCIOS (untrimmedStrategy bufSize bufSize)
(return . Finished)
----------------------------------------------------------------------
-- Padded versions of encodings for streamed prefixing of output sizes
----------------------------------------------------------------------
{-# INLINE appsUntilZero #-}
appsUntilZero :: (Eq a, Num a) => (a -> a) -> a -> Int
appsUntilZero f x0 =
count 0 x0
where
count !n 0 = n
count !n x = count (succ n) (f x)
{-# INLINE genericVarFixedBound #-}
genericVarFixedBound :: (Eq b, Show b, Bits b, Num a, Integral b)
=> (b -> a -> b) -> b -> FixedPrim b
genericVarFixedBound shiftRight bound =
fixedEncoding n0 io
where
n0 = max 1 $ appsUntilZero (`shiftRight` 7) bound
io !x0 !op
| x0 > bound = error err
| otherwise = loop 0 x0
where
err = "genericVarFixedBound: value " ++ show x0 ++ " > bound " ++ show bound
loop !n !x
| n0 <= n + 1 = do poke8 (x .&. 0x7f)
| otherwise = do poke8 ((x .&. 0x7f) .|. 0x80)
loop (n + 1) (x `shiftRight` 7)
where
poke8 = pokeElemOff op n . fromIntegral
{-# INLINE wordVarFixedBound #-}
wordVarFixedBound :: Word -> FixedPrim Word
wordVarFixedBound = genericVarFixedBound shiftr_w
{-# INLINE word64VarFixedBound #-}
word64VarFixedBound :: Word64 -> FixedPrim Word64
word64VarFixedBound = genericVarFixedBound shiftr_w64
-- Somehow this function doesn't really make sense, as the bound must be
-- greater when interpreted as an unsigned integer. These conversions and
-- decisions should be left to the user.
--
--{-# INLINE intVarFixed #-}
--intVarFixed :: Size -> FixedPrim Size
--intVarFixed bound = fromIntegral >$< wordVarFixed (fromIntegral bound)
{-# INLINE genHexFixedBound #-}
genHexFixedBound :: (Num a, Bits a, Integral a)
=> (a -> Int -> a) -> Char -> a -> FixedPrim a
genHexFixedBound shiftr padding0 bound =
fixedEncoding n0 io
where
n0 = max 1 $ appsUntilZero (`shiftr` 4) bound
padding = fromIntegral (ord padding0) :: Word8
io !x0 !op0 =
loop (op0 `plusPtr` n0) x0
where
loop !op !x = do
let !op' = op `plusPtr` (-1)
poke op' =<< encode4_as_8 lowerTable (fromIntegral $ x .&. 0xf)
let !x' = x `shiftr` 4
unless (op' <= op0) $
if x' == 0
then pad (op' `plusPtr` (-1))
else loop op' x'
pad !op
| op < op0 = return ()
| otherwise = poke op padding >> pad (op `plusPtr` (-1))
{-# INLINE wordHexFixedBound #-}
wordHexFixedBound :: Char -> Word -> FixedPrim Word
wordHexFixedBound = genHexFixedBound shiftr_w
{-# INLINE word64HexFixedBound #-}
word64HexFixedBound :: Char -> Word64 -> FixedPrim Word64
word64HexFixedBound = genHexFixedBound shiftr_w64
-- | Note: Works only for positive numbers.
{-# INLINE genDecFixedBound #-}
genDecFixedBound :: (Num a, Bits a, Integral a)
=> Char -> a -> FixedPrim a
genDecFixedBound padding0 bound =
fixedEncoding n0 io
where
n0 = max 1 $ appsUntilZero (`div` 10) bound
padding = fromIntegral (ord padding0) :: Word8
io !x0 !op0 =
loop (op0 `plusPtr` n0) x0
where
loop !op !x = do
let !op' = op `plusPtr` (-1)
!x' = x `div` 10
poke op' ((fromIntegral $ (x - x' * 10) + 48) :: Word8)
unless (op' <= op0) $
if x' == 0
then pad (op' `plusPtr` (-1))
else loop op' x'
pad !op
| op < op0 = return ()
| otherwise = poke op padding >> pad (op `plusPtr` (-1))
{-# INLINE wordDecFixedBound #-}
wordDecFixedBound :: Char -> Word -> FixedPrim Word
wordDecFixedBound = genDecFixedBound
{-# INLINE word64DecFixedBound #-}
word64DecFixedBound :: Char -> Word64 -> FixedPrim Word64
word64DecFixedBound = genDecFixedBound
|
markflorisson/hpack
|
testrepo/bytestring-0.10.2.0/Data/ByteString/Builder/Prim/Extra.hs
|
bsd-3-clause
| 35,943 | 0 | 18 | 8,456 | 3,898 | 2,063 | 1,835 | 335 | 3 |
module Text.HTML.Moe2.DSL.HTML5 where
import Text.HTML.Moe2.Element
import Text.HTML.Moe2.Type
article :: MoeCombinator
aside :: MoeCombinator
audio :: MoeCombinator
canvas :: MoeCombinator
command :: MoeCombinator
datagrid :: MoeCombinator
datalist :: MoeCombinator
datatemplate :: MoeCombinator
details :: MoeCombinator
dialog :: MoeCombinator
event_source :: MoeCombinator
figure :: MoeCombinator
footer :: MoeCombinator
header :: MoeCombinator
mark :: MoeCombinator
meter :: MoeCombinator
nav :: MoeCombinator
nest :: MoeCombinator
output :: MoeCombinator
progress :: MoeCombinator
rule :: MoeCombinator
section :: MoeCombinator
source :: MoeCombinator
time :: MoeCombinator
video :: MoeCombinator
article = element "article"
aside = element "aside"
audio = element "audio"
canvas = element "canvas"
command = element "command"
datagrid = element "datagrid"
datalist = element "datalist"
datatemplate = element "datatemplate"
details = element "details"
dialog = element "dialog"
event_source = element "event_source"
figure = element "figure"
footer = element "footer"
header = element "header"
mark = element "mark"
meter = element "meter"
nav = element "nav"
nest = element "nest"
output = element "output"
progress = element "progress"
rule = element "rule"
section = element "section"
source = element "source"
time = element "time"
video = element "video"
|
nfjinjing/moe
|
src/Text/HTML/Moe2/DSL/HTML5.hs
|
bsd-3-clause
| 1,729 | 0 | 5 | 545 | 348 | 192 | 156 | 53 | 1 |
import Data.Pipe
import Data.Pipe.ByteString
import System.IO
main :: IO ()
main = do
_ <- runPipe $ fromFileLn "test/sample.txt" =$= toHandleLn stdout
return ()
|
YoshikuniJujo/simple-pipe
|
test/testEOF.hs
|
bsd-3-clause
| 165 | 0 | 10 | 27 | 61 | 30 | 31 | 7 | 1 |
module Elm.Package.Constraint
( Constraint
, fromString
, toString
, untilNextMajor
, untilNextMinor
, expand
, defaultElmVersion
, isSatisfied
, errorMessage
) where
import qualified Data.Aeson as Json
import qualified Data.Text as Text
import qualified Elm.Package as Package
import qualified Elm.Compiler as Compiler
-- CONSTRAINTS
data Constraint
= Range Package.Version Op Op Package.Version
data Op = Less | LessOrEqual
-- CREATE CONSTRAINTS
untilNextMajor :: Package.Version -> Constraint
untilNextMajor version =
Range version LessOrEqual Less (Package.bumpMajor version)
untilNextMinor :: Package.Version -> Constraint
untilNextMinor version =
Range version LessOrEqual Less (Package.bumpMinor version)
expand :: Constraint -> Package.Version -> Constraint
expand constraint@(Range lower lowerOp upperOp upper) version
| version < lower =
Range version LessOrEqual upperOp upper
| version > upper =
Range lower lowerOp Less (Package.bumpMajor version)
| otherwise =
constraint
-- ELM CONSTRAINT
defaultElmVersion :: Constraint
defaultElmVersion =
if Package._major Compiler.version > 0
then untilNextMajor Compiler.version
else untilNextMinor Compiler.version
-- CHECK IF SATISFIED
isSatisfied :: Constraint -> Package.Version -> Bool
isSatisfied constraint version =
case constraint of
Range lower lowerOp upperOp upper ->
isLess lowerOp lower version
&&
isLess upperOp version upper
isLess :: (Ord a) => Op -> (a -> a -> Bool)
isLess op =
case op of
Less -> (<)
LessOrEqual -> (<=)
-- STRING CONVERSION
toString :: Constraint -> String
toString constraint =
case constraint of
Range lower lowerOp upperOp upper ->
unwords
[ Package.versionToString lower
, opToString lowerOp
, "v"
, opToString upperOp
, Package.versionToString upper
]
opToString :: Op -> String
opToString op =
case op of
Less -> "<"
LessOrEqual -> "<="
fromString :: String -> Maybe Constraint
fromString str =
do let (lowerString, rest) = break (==' ') str
lower <- Package.versionFromString lowerString
(lowerOp, rest1) <- takeOp (eatSpace rest)
rest2 <- eatV (eatSpace rest1)
(upperOp, rest3) <- takeOp (eatSpace rest2)
upper <- Package.versionFromString (eatSpace rest3)
return (Range lower lowerOp upperOp upper)
eatSpace :: String -> String
eatSpace str =
case str of
' ' : rest -> rest
_ -> str
takeOp :: String -> Maybe (Op, String)
takeOp str =
case str of
'<' : '=' : rest -> Just (LessOrEqual, rest)
'<' : rest -> Just (Less, rest)
_ -> Nothing
eatV :: String -> Maybe String
eatV str =
case str of
'v' : rest -> Just rest
_ -> Nothing
-- JSON CONVERSION
instance Json.ToJSON Constraint where
toJSON constraint =
Json.toJSON (toString constraint)
instance Json.FromJSON Constraint where
parseJSON (Json.String text) =
let rawConstraint = Text.unpack text in
case fromString rawConstraint of
Just constraint ->
return constraint
Nothing ->
fail $ errorMessage rawConstraint
parseJSON _ =
fail "constraint must be a string that looks something like \"1.2.1 <= v < 2.0.0\"."
errorMessage :: String -> String
errorMessage rawConstraint =
"Invalid constraint \"" ++ rawConstraint ++ "\"\n\n"
++ " It should look something like \"1.2.1 <= v < 2.0.0\", with no extra or\n"
++ " missing spaces. The middle letter needs to be a 'v' as well.\n\n"
++ " Upper and lower bounds are required so that bounds represent the maximum range\n"
++ " known to work. You do not want to promise users your library will work with\n"
++ " 4.0.0 that version has not been tested!"
|
laszlopandy/elm-package
|
src/Elm/Package/Constraint.hs
|
bsd-3-clause
| 3,890 | 0 | 12 | 971 | 1,004 | 517 | 487 | 109 | 3 |
{-# LANGUAGE RankNTypes #-}
module Content (content) where
import qualified Message
import Text.XML.HXT.Core
import WordProcessing
fieldText::ArrowXml a =>String->a XmlTree XmlTree
fieldText name =
getChildren
>>> isElem
>>> hasName name
>>> getChildren
>>> isText
fieldVal::ArrowXml a =>String->a XmlTree String
fieldVal name = fieldText name >>> getText
normal, bold::ArrowXml a=>a b XmlTree->a b XmlTree
normal = paragraph "Normal"
bold = paragraph "Bold"
descr, params, handling, exposure, static, methodHeading, methods, clifHeading, clifDocu::ArrowXml a=>a XmlTree XmlTree
descr = normal $ fieldText "description"
eqA::(ArrowList a, Eq b)=>b->a b b
eqA = isA . (==)
p::ArrowXml a=>String->a b String->a b XmlTree
p name = paragraph name . (>>> mkText)
content::ArrowXml a=>a XmlTree XmlTree->a XmlTree XmlTree
content styles = top where
top = getChildren
>>> isElem
>>> hasName "types"
>>> wordDocument sections
sections = styles <+> body
body = we "body" (getChildren >>> clifDocu)
clifDocu =
isElem >>>
(hasName "class" <+> hasName "interface") >>>
clifHeading <+> descr <+> methods
clifHeading = paragraph "Heading1" text where
text = kind >>> mkText
name = getAttrValue "name"
kind = kindClass <+> kindInterface
kindClass = hasName "class" >>> name >>^ Message.className
kindInterface = hasName "interface" >>> name >>^ Message.intfName
methods =
getChildren >>>
isElem >>>
hasName "method" >>>
methodHeading
<+> static
<+> exposure
<+> handling
<+> descr
<+> params
methodHeading = p "Heading2" name where
name = getAttrValue "name" >>^ Message.mtdName
static = p "Bold" text where
text = hasAttr "static" >>> constA Message.static
exposure = getAttrValue "exposure" >>> exposures where
exposures = public <+> protected <+> private
expTxt val style text = eqA val >>> p style (constA text)
public = expTxt "public" "Green" Message.public
protected = expTxt "protected" "Yellow" Message.protected
private = expTxt "private" "Red" Message.private
handling = hasAttr "event_handler" >>> p "Italic" text where
text = evtCls >>> arr2 Message.eventHandler
evtCls = fieldVal "refName" &&& fieldVal "refClass"
params = wtbl "TableNormal" borders rows where
borders = wtblBorders 4
rows =
getChildren
>>> isElem
>>> hasName "param"
>>> we "tr" cells
cells = catA $ map (we "tc") [name, kind, descr]
name = bold $ getAttrValue "name" >>> mkText
kind = normal $
fieldVal "kind" >>>
Message.paramKind ^>>
mkText
|
Odomontois/abapdocu
|
src/Content.hs
|
bsd-3-clause
| 2,658 | 0 | 12 | 597 | 835 | 429 | 406 | 77 | 1 |
-- | Memoize IO actions, performing them at most once,
-- but recalling their result for subsequent invocations.
-- This library provides two sequencing strategies:
-- lazy ('once'), and concurrent ('eagerlyOnce').
--
-- The following property holds: @join . once === id@.
-- The same is true for @eagerlyOnce@.
--
-- The memory allocated for a memoized result will obviously not
-- be available for garbage collection until the corresponding
-- memoized action is also available for garbage collection.
module System.IO.Memoize (
once
, eagerlyOnce
, ioMemo
, ioMemo'
, ioMemoPar
) where
import Control.Concurrent.Async (async, wait)
import Control.Concurrent.Cache (newCache, fetch)
-- | Memoize an IO action. The action will be performed
-- the first time that it its value is demanded;
-- all subsequent invocations will simply recall the value acquired
-- from the first call. If the value is never demanded,
-- then the action will never be performed.
--
-- This is basically a safe version of 'System.IO.Unsafe.unsafeInterleaveIO'.
-- Exceptions will be propagated to the caller, and the action will be retried
-- at each invocation, only until it has successfully completed once.
--
-- Example usage:
--
-- >>> getLine' <- once getLine
--
-- >>> replicateM 3 getLine'
-- Hello
-- ["Hello", "Hello", "Hello"]
once :: IO a -> IO (IO a)
once action = do
cache <- newCache
return (fetch cache action)
-- | Memoize an IO action.
-- The action will be started immediately in a new thread.
-- Attempts to access the result will block until the action is finished.
-- If the action produces an error, then attempts to access its value
-- will re-raise the same error each time.
eagerlyOnce :: IO a -> IO (IO a)
eagerlyOnce action = do
thread <- async action
return (wait thread)
{-# DEPRECATED ioMemo' "Please just call the action directly." #-}
-- | Memoize an IO action.
-- The action will be performed immediately;
-- all subsequent invocations
-- will recall the value acquired.
ioMemo' :: IO a -> IO (IO a)
ioMemo' action = do
v <- action
return (return v)
{-# DEPRECATED ioMemo "Please use 'once'." #-}
ioMemo :: IO a -> IO (IO a)
ioMemo = once
{-# DEPRECATED ioMemoPar "Please use 'eagerlyOnce'." #-}
ioMemoPar :: IO a -> IO (IO a)
ioMemoPar = eagerlyOnce
|
DanBurton/io-memoize
|
src/System/IO/Memoize.hs
|
bsd-3-clause
| 2,302 | 0 | 9 | 424 | 293 | 168 | 125 | 27 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Build-specific types.
module Stack.Types.Build
(StackBuildException(..)
,FlagSource(..)
,UnusedFlags(..)
,InstallLocation(..)
,Installed(..)
,psVersion
,Task(..)
,taskIsTarget
,taskLocation
,taskTargetIsMutable
,LocalPackage(..)
,BaseConfigOpts(..)
,Plan(..)
,TestOpts(..)
,BenchmarkOpts(..)
,FileWatchOpts(..)
,BuildOpts(..)
,BuildSubset(..)
,defaultBuildOpts
,TaskType(..)
,IsMutable(..)
,installLocationIsMutable
,TaskConfigOpts(..)
,BuildCache(..)
,ConfigCache(..)
,configureOpts
,CachePkgSrc (..)
,toCachePkgSrc
,isStackOpt
,wantedLocalPackages
,FileCacheInfo (..)
,ConfigureOpts (..)
,PrecompiledCache (..)
)
where
import Stack.Prelude
import Data.Aeson (ToJSON, FromJSON)
import qualified Data.ByteString as S
import Data.Char (isSpace)
import Data.List.Extra
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import Database.Persist.Sql (PersistField(..)
,PersistFieldSql(..)
,PersistValue(PersistText)
,SqlType(SqlString))
import Distribution.PackageDescription (TestSuiteInterface)
import Distribution.System (Arch)
import qualified Distribution.Text as C
import Distribution.Version (mkVersion)
import Path (parseRelDir, (</>), parent)
import Path.Extra (toFilePathNoTrailingSep)
import Stack.Constants
import Stack.Types.Compiler
import Stack.Types.CompilerBuild
import Stack.Types.Config
import Stack.Types.GhcPkgId
import Stack.Types.NamedComponent
import Stack.Types.Package
import Stack.Types.Version
import System.FilePath (pathSeparator)
import RIO.Process (showProcessArgDebug)
----------------------------------------------
-- Exceptions
data StackBuildException
= Couldn'tFindPkgId PackageName
| CompilerVersionMismatch
(Maybe (ActualCompiler, Arch)) -- found
(WantedCompiler, Arch) -- expected
GHCVariant -- expected
CompilerBuild -- expected
VersionCheck
(Maybe (Path Abs File)) -- Path to the stack.yaml file
Text -- recommended resolution
| Couldn'tParseTargets [Text]
| UnknownTargets
(Set PackageName) -- no known version
(Map PackageName Version) -- not in snapshot, here's the most recent version in the index
(Path Abs File) -- stack.yaml
| TestSuiteFailure PackageIdentifier (Map Text (Maybe ExitCode)) (Maybe (Path Abs File)) S.ByteString
| TestSuiteTypeUnsupported TestSuiteInterface
| ConstructPlanFailed String
| CabalExitedUnsuccessfully
ExitCode
PackageIdentifier
(Path Abs File) -- cabal Executable
[String] -- cabal arguments
(Maybe (Path Abs File)) -- logfiles location
[Text] -- log contents
| SetupHsBuildFailure
ExitCode
(Maybe PackageIdentifier) -- which package's custom setup, is simple setup if Nothing
(Path Abs File) -- ghc Executable
[String] -- ghc arguments
(Maybe (Path Abs File)) -- logfiles location
[Text] -- log contents
| ExecutionFailure [SomeException]
| LocalPackageDoesn'tMatchTarget
PackageName
Version -- local version
Version -- version specified on command line
| NoSetupHsFound (Path Abs Dir)
| InvalidFlagSpecification (Set UnusedFlags)
| InvalidGhcOptionsSpecification [PackageName]
| TargetParseException [Text]
| SomeTargetsNotBuildable [(PackageName, NamedComponent)]
| TestSuiteExeMissing Bool String String String
| CabalCopyFailed Bool String
| LocalPackagesPresent [PackageIdentifier]
| CouldNotLockDistDir !(Path Abs File)
deriving Typeable
data FlagSource = FSCommandLine | FSStackYaml
deriving (Show, Eq, Ord)
data UnusedFlags = UFNoPackage FlagSource PackageName
| UFFlagsNotDefined
FlagSource
PackageName
(Set FlagName) -- defined in package
(Set FlagName) -- not defined
| UFSnapshot PackageName
deriving (Show, Eq, Ord)
instance Show StackBuildException where
show (Couldn'tFindPkgId name) =
"After installing " <> packageNameString name <>
", the package id couldn't be found " <> "(via ghc-pkg describe " <>
packageNameString name <> "). This shouldn't happen, " <>
"please report as a bug"
show (CompilerVersionMismatch mactual (expected, earch) ghcVariant ghcBuild check mstack resolution) = concat
[ case mactual of
Nothing -> "No compiler found, expected "
Just (actual, arch) -> concat
[ "Compiler version mismatched, found "
, compilerVersionString actual
, " ("
, C.display arch
, ")"
, ", but expected "
]
, case check of
MatchMinor -> "minor version match with "
MatchExact -> "exact version "
NewerMinor -> "minor version match or newer with "
, T.unpack $ utf8BuilderToText $ display expected
, " ("
, C.display earch
, ghcVariantSuffix ghcVariant
, compilerBuildSuffix ghcBuild
, ") (based on "
, case mstack of
Nothing -> "command line arguments"
Just stack -> "resolver setting in " ++ toFilePath stack
, ").\n"
, T.unpack resolution
]
show (Couldn'tParseTargets targets) = unlines
$ "The following targets could not be parsed as package names or directories:"
: map T.unpack targets
show (UnknownTargets noKnown notInSnapshot stackYaml) =
unlines $ noKnown' ++ notInSnapshot'
where
noKnown'
| Set.null noKnown = []
| otherwise = return $
"The following target packages were not found: " ++
intercalate ", " (map packageNameString $ Set.toList noKnown) ++
"\nSee https://docs.haskellstack.org/en/stable/build_command/#target-syntax for details."
notInSnapshot'
| Map.null notInSnapshot = []
| otherwise =
"The following packages are not in your snapshot, but exist"
: "in your package index. Recommended action: add them to your"
: ("extra-deps in " ++ toFilePath stackYaml)
: "(Note: these are the most recent versions,"
: "but there's no guarantee that they'll build together)."
: ""
: map
(\(name, version') -> "- " ++ packageIdentifierString
(PackageIdentifier name version'))
(Map.toList notInSnapshot)
show (TestSuiteFailure ident codes mlogFile bs) = unlines $ concat
[ ["Test suite failure for package " ++ packageIdentifierString ident]
, flip map (Map.toList codes) $ \(name, mcode) -> concat
[ " "
, T.unpack name
, ": "
, case mcode of
Nothing -> " executable not found"
Just ec -> " exited with: " ++ show ec
]
, return $ case mlogFile of
Nothing -> "Logs printed to console"
-- TODO Should we load up the full error output and print it here?
Just logFile -> "Full log available at " ++ toFilePath logFile
, if S.null bs
then []
else ["", "", doubleIndent $ T.unpack $ decodeUtf8With lenientDecode bs]
]
where
indent = dropWhileEnd isSpace . unlines . fmap (\line -> " " ++ line) . lines
doubleIndent = indent . indent
show (TestSuiteTypeUnsupported interface) =
"Unsupported test suite type: " <> show interface
-- Supressing duplicate output
show (CabalExitedUnsuccessfully exitCode taskProvides' execName fullArgs logFiles bss) =
showBuildError False exitCode (Just taskProvides') execName fullArgs logFiles bss
show (SetupHsBuildFailure exitCode mtaskProvides execName fullArgs logFiles bss) =
showBuildError True exitCode mtaskProvides execName fullArgs logFiles bss
show (ExecutionFailure es) = intercalate "\n\n" $ map show es
show (LocalPackageDoesn'tMatchTarget name localV requestedV) = concat
[ "Version for local package "
, packageNameString name
, " is "
, versionString localV
, ", but you asked for "
, versionString requestedV
, " on the command line"
]
show (NoSetupHsFound dir) =
"No Setup.hs or Setup.lhs file found in " ++ toFilePath dir
show (InvalidFlagSpecification unused) = unlines
$ "Invalid flag specification:"
: map go (Set.toList unused)
where
showFlagSrc :: FlagSource -> String
showFlagSrc FSCommandLine = " (specified on command line)"
showFlagSrc FSStackYaml = " (specified in stack.yaml)"
go :: UnusedFlags -> String
go (UFNoPackage src name) = concat
[ "- Package '"
, packageNameString name
, "' not found"
, showFlagSrc src
]
go (UFFlagsNotDefined src pname pkgFlags flags) = concat
[ "- Package '"
, name
, "' does not define the following flags"
, showFlagSrc src
, ":\n"
, intercalate "\n"
(map (\flag -> " " ++ flagNameString flag)
(Set.toList flags))
, "\n- Flags defined by package '" ++ name ++ "':\n"
, intercalate "\n"
(map (\flag -> " " ++ name ++ ":" ++ flagNameString flag)
(Set.toList pkgFlags))
]
where name = packageNameString pname
go (UFSnapshot name) = concat
[ "- Attempted to set flag on snapshot package "
, packageNameString name
, ", please add to extra-deps"
]
show (InvalidGhcOptionsSpecification unused) = unlines
$ "Invalid GHC options specification:"
: map showGhcOptionSrc unused
where
showGhcOptionSrc name = concat
[ "- Package '"
, packageNameString name
, "' not found"
]
show (TargetParseException [err]) = "Error parsing targets: " ++ T.unpack err
show (TargetParseException errs) = unlines
$ "The following errors occurred while parsing the build targets:"
: map (("- " ++) . T.unpack) errs
show (SomeTargetsNotBuildable xs) =
"The following components have 'buildable: False' set in the cabal configuration, and so cannot be targets:\n " ++
T.unpack (renderPkgComponents xs) ++
"\nTo resolve this, either provide flags such that these components are buildable, or only specify buildable targets."
show (TestSuiteExeMissing isSimpleBuildType exeName pkgName' testName) =
missingExeError isSimpleBuildType $ concat
[ "Test suite executable \""
, exeName
, " not found for "
, pkgName'
, ":test:"
, testName
]
show (CabalCopyFailed isSimpleBuildType innerMsg) =
missingExeError isSimpleBuildType $ concat
[ "'cabal copy' failed. Error message:\n"
, innerMsg
, "\n"
]
show (ConstructPlanFailed msg) = msg
show (LocalPackagesPresent locals) = unlines
$ "Local packages are not allowed when using the script command. Packages found:"
: map (\ident -> "- " ++ packageIdentifierString ident) locals
show (CouldNotLockDistDir lockFile) = unlines
[ "Locking the dist directory failed, try to lock file:"
, " " ++ toFilePath lockFile
, "Maybe you're running another copy of Stack?"
]
missingExeError :: Bool -> String -> String
missingExeError isSimpleBuildType msg =
unlines $ msg :
case possibleCauses of
[] -> []
[cause] -> ["One possible cause of this issue is:\n* " <> cause]
_ -> "Possible causes of this issue:" : map ("* " <>) possibleCauses
where
possibleCauses =
"No module named \"Main\". The 'main-is' source file should usually have a header indicating that it's a 'Main' module." :
"A cabal file that refers to nonexistent other files (e.g. a license-file that doesn't exist). Running 'cabal check' may point out these issues." :
if isSimpleBuildType
then []
else ["The Setup.hs file is changing the installation target dir."]
showBuildError
:: Bool
-> ExitCode
-> Maybe PackageIdentifier
-> Path Abs File
-> [String]
-> Maybe (Path Abs File)
-> [Text]
-> String
showBuildError isBuildingSetup exitCode mtaskProvides execName fullArgs logFiles bss =
let fullCmd = unwords
$ dropQuotes (toFilePath execName)
: map (T.unpack . showProcessArgDebug) fullArgs
logLocations = maybe "" (\fp -> "\n Logs have been written to: " ++ toFilePath fp) logFiles
in "\n-- While building " ++
(case (isBuildingSetup, mtaskProvides) of
(False, Nothing) -> error "Invariant violated: unexpected case in showBuildError"
(False, Just taskProvides') -> "package " ++ dropQuotes (packageIdentifierString taskProvides')
(True, Nothing) -> "simple Setup.hs"
(True, Just taskProvides') -> "custom Setup.hs for package " ++ dropQuotes (packageIdentifierString taskProvides')
) ++
" (scroll up to its section to see the error) using:\n " ++ fullCmd ++ "\n" ++
" Process exited with code: " ++ show exitCode ++
(if exitCode == ExitFailure (-9)
then " (THIS MAY INDICATE OUT OF MEMORY)"
else "") ++
logLocations ++
(if null bss
then ""
else "\n\n" ++ doubleIndent (map T.unpack bss))
where
doubleIndent = dropWhileEnd isSpace . unlines . fmap (\line -> " " ++ line)
dropQuotes = filter ('\"' /=)
instance Exception StackBuildException
----------------------------------------------
-- | Package dependency oracle.
newtype PkgDepsOracle =
PkgDeps PackageName
deriving (Show,Typeable,Eq,NFData)
-- | Stored on disk to know whether the files have changed.
newtype BuildCache = BuildCache
{ buildCacheTimes :: Map FilePath FileCacheInfo
-- ^ Modification times of files.
}
deriving (Generic, Eq, Show, Typeable, ToJSON, FromJSON)
instance NFData BuildCache
-- | Stored on disk to know whether the flags have changed.
data ConfigCache = ConfigCache
{ configCacheOpts :: !ConfigureOpts
-- ^ All options used for this package.
, configCacheDeps :: !(Set GhcPkgId)
-- ^ The GhcPkgIds of all of the dependencies. Since Cabal doesn't take
-- the complete GhcPkgId (only a PackageIdentifier) in the configure
-- options, just using the previous value is insufficient to know if
-- dependencies have changed.
, configCacheComponents :: !(Set S.ByteString)
-- ^ The components to be built. It's a bit of a hack to include this in
-- here, as it's not a configure option (just a build option), but this
-- is a convenient way to force compilation when the components change.
, configCacheHaddock :: !Bool
-- ^ Are haddocks to be built?
, configCachePkgSrc :: !CachePkgSrc
, configCachePathEnvVar :: !Text
-- ^ Value of the PATH env var, see <https://github.com/commercialhaskell/stack/issues/3138>
}
deriving (Generic, Eq, Show, Data, Typeable)
instance NFData ConfigCache
data CachePkgSrc = CacheSrcUpstream | CacheSrcLocal FilePath
deriving (Generic, Eq, Read, Show, Data, Typeable)
instance NFData CachePkgSrc
instance PersistField CachePkgSrc where
toPersistValue CacheSrcUpstream = PersistText "upstream"
toPersistValue (CacheSrcLocal fp) = PersistText ("local:" <> T.pack fp)
fromPersistValue (PersistText t) = do
if t == "upstream"
then Right CacheSrcUpstream
else case T.stripPrefix "local:" t of
Just fp -> Right $ CacheSrcLocal (T.unpack fp)
Nothing -> Left $ "Unexpected CachePkgSrc value: " <> t
fromPersistValue _ = Left "Unexpected CachePkgSrc type"
instance PersistFieldSql CachePkgSrc where
sqlType _ = SqlString
toCachePkgSrc :: PackageSource -> CachePkgSrc
toCachePkgSrc (PSFilePath lp) = CacheSrcLocal (toFilePath (parent (lpCabalFile lp)))
toCachePkgSrc PSRemote{} = CacheSrcUpstream
-- | A task to perform when building
data Task = Task
{ taskProvides :: !PackageIdentifier -- FIXME turn this into a function on taskType?
-- ^ the package/version to be built
, taskType :: !TaskType
-- ^ the task type, telling us how to build this
, taskConfigOpts :: !TaskConfigOpts
, taskBuildHaddock :: !Bool
, taskPresent :: !(Map PackageIdentifier GhcPkgId)
-- ^ GhcPkgIds of already-installed dependencies
, taskAllInOne :: !Bool
-- ^ indicates that the package can be built in one step
, taskCachePkgSrc :: !CachePkgSrc
, taskAnyMissing :: !Bool
-- ^ Were any of the dependencies missing? The reason this is
-- necessary is... hairy. And as you may expect, a bug in
-- Cabal. See:
-- <https://github.com/haskell/cabal/issues/4728#issuecomment-337937673>. The
-- problem is that Cabal may end up generating the same package ID
-- for a dependency, even if the ABI has changed. As a result,
-- without this field, Stack would think that a reconfigure is
-- unnecessary, when in fact we _do_ need to reconfigure. The
-- details here suck. We really need proper hashes for package
-- identifiers.
, taskBuildTypeConfig :: !Bool
-- ^ Is the build type of this package Configure. Check out
-- ensureConfigureScript in Stack.Build.Execute for the motivation
}
deriving Show
-- | Given the IDs of any missing packages, produce the configure options
data TaskConfigOpts = TaskConfigOpts
{ tcoMissing :: !(Set PackageIdentifier)
-- ^ Dependencies for which we don't yet have an GhcPkgId
, tcoOpts :: !(Map PackageIdentifier GhcPkgId -> ConfigureOpts)
-- ^ Produce the list of options given the missing @GhcPkgId@s
}
instance Show TaskConfigOpts where
show (TaskConfigOpts missing f) = concat
[ "Missing: "
, show missing
, ". Without those: "
, show $ f Map.empty
]
-- | The type of a task, either building local code or something from the
-- package index (upstream)
data TaskType
= TTLocalMutable LocalPackage
| TTRemotePackage IsMutable Package PackageLocationImmutable
deriving Show
data IsMutable
= Mutable
| Immutable
deriving (Eq, Show)
instance Semigroup IsMutable where
Mutable <> _ = Mutable
_ <> Mutable = Mutable
Immutable <> Immutable = Immutable
instance Monoid IsMutable where
mempty = Immutable
mappend = (<>)
taskIsTarget :: Task -> Bool
taskIsTarget t =
case taskType t of
TTLocalMutable lp -> lpWanted lp
_ -> False
taskLocation :: Task -> InstallLocation
taskLocation task =
case taskType task of
TTLocalMutable _ -> Local
TTRemotePackage Mutable _ _ -> Local
TTRemotePackage Immutable _ _ -> Snap
taskTargetIsMutable :: Task -> IsMutable
taskTargetIsMutable task =
case taskType task of
TTLocalMutable _ -> Mutable
TTRemotePackage mutable _ _ -> mutable
installLocationIsMutable :: InstallLocation -> IsMutable
installLocationIsMutable Snap = Immutable
installLocationIsMutable Local = Mutable
-- | A complete plan of what needs to be built and how to do it
data Plan = Plan
{ planTasks :: !(Map PackageName Task)
, planFinals :: !(Map PackageName Task)
-- ^ Final actions to be taken (test, benchmark, etc)
, planUnregisterLocal :: !(Map GhcPkgId (PackageIdentifier, Text))
-- ^ Text is reason we're unregistering, for display only
, planInstallExes :: !(Map Text InstallLocation)
-- ^ Executables that should be installed after successful building
}
deriving Show
-- | Basic information used to calculate what the configure options are
data BaseConfigOpts = BaseConfigOpts
{ bcoSnapDB :: !(Path Abs Dir)
, bcoLocalDB :: !(Path Abs Dir)
, bcoSnapInstallRoot :: !(Path Abs Dir)
, bcoLocalInstallRoot :: !(Path Abs Dir)
, bcoBuildOpts :: !BuildOpts
, bcoBuildOptsCLI :: !BuildOptsCLI
, bcoExtraDBs :: ![Path Abs Dir]
}
deriving Show
-- | Render a @BaseConfigOpts@ to an actual list of options
configureOpts :: EnvConfig
-> BaseConfigOpts
-> Map PackageIdentifier GhcPkgId -- ^ dependencies
-> Bool -- ^ local non-extra-dep?
-> IsMutable
-> Package
-> ConfigureOpts
configureOpts econfig bco deps isLocal isMutable package = ConfigureOpts
{ coDirs = configureOptsDirs bco isMutable package
, coNoDirs = configureOptsNoDir econfig bco deps isLocal package
}
-- options set by stack
isStackOpt :: Text -> Bool
isStackOpt t = any (`T.isPrefixOf` t)
[ "--dependency="
, "--constraint="
, "--package-db="
, "--libdir="
, "--bindir="
, "--datadir="
, "--libexecdir="
, "--sysconfdir"
, "--docdir="
, "--htmldir="
, "--haddockdir="
, "--enable-tests"
, "--enable-benchmarks"
, "--exact-configuration"
-- Treat these as causing dirtiness, to resolve
-- https://github.com/commercialhaskell/stack/issues/2984
--
-- , "--enable-library-profiling"
-- , "--enable-executable-profiling"
-- , "--enable-profiling"
] || t == "--user"
configureOptsDirs :: BaseConfigOpts
-> IsMutable
-> Package
-> [String]
configureOptsDirs bco isMutable package = concat
[ ["--user", "--package-db=clear", "--package-db=global"]
, map (("--package-db=" ++) . toFilePathNoTrailingSep) $ case isMutable of
Immutable -> bcoExtraDBs bco ++ [bcoSnapDB bco]
Mutable -> bcoExtraDBs bco ++ [bcoSnapDB bco] ++ [bcoLocalDB bco]
, [ "--libdir=" ++ toFilePathNoTrailingSep (installRoot </> relDirLib)
, "--bindir=" ++ toFilePathNoTrailingSep (installRoot </> bindirSuffix)
, "--datadir=" ++ toFilePathNoTrailingSep (installRoot </> relDirShare)
, "--libexecdir=" ++ toFilePathNoTrailingSep (installRoot </> relDirLibexec)
, "--sysconfdir=" ++ toFilePathNoTrailingSep (installRoot </> relDirEtc)
, "--docdir=" ++ toFilePathNoTrailingSep docDir
, "--htmldir=" ++ toFilePathNoTrailingSep docDir
, "--haddockdir=" ++ toFilePathNoTrailingSep docDir]
]
where
installRoot =
case isMutable of
Immutable -> bcoSnapInstallRoot bco
Mutable -> bcoLocalInstallRoot bco
docDir =
case pkgVerDir of
Nothing -> installRoot </> docDirSuffix
Just dir -> installRoot </> docDirSuffix </> dir
pkgVerDir =
parseRelDir (packageIdentifierString (PackageIdentifier (packageName package)
(packageVersion package)) ++
[pathSeparator])
-- | Same as 'configureOpts', but does not include directory path options
configureOptsNoDir :: EnvConfig
-> BaseConfigOpts
-> Map PackageIdentifier GhcPkgId -- ^ dependencies
-> Bool -- ^ is this a local, non-extra-dep?
-> Package
-> [String]
configureOptsNoDir econfig bco deps isLocal package = concat
[ depOptions
, ["--enable-library-profiling" | boptsLibProfile bopts || boptsExeProfile bopts]
-- Cabal < 1.21.1 does not support --enable-profiling, use --enable-executable-profiling instead
, let profFlag = "--enable-" <> concat ["executable-" | not newerCabal] <> "profiling"
in [ profFlag | boptsExeProfile bopts && isLocal]
, ["--enable-split-objs" | boptsSplitObjs bopts]
, ["--disable-library-stripping" | not $ boptsLibStrip bopts || boptsExeStrip bopts]
, ["--disable-executable-stripping" | not (boptsExeStrip bopts) && isLocal]
, map (\(name,enabled) ->
"-f" <>
(if enabled
then ""
else "-") <>
flagNameString name)
(Map.toList flags)
, map T.unpack $ packageCabalConfigOpts package
, concatMap (\x -> [compilerOptionsCabalFlag wc, T.unpack x]) (packageGhcOptions package)
, map ("--extra-include-dirs=" ++) (configExtraIncludeDirs config)
, map ("--extra-lib-dirs=" ++) (configExtraLibDirs config)
, maybe [] (\customGcc -> ["--with-gcc=" ++ toFilePath customGcc]) (configOverrideGccPath config)
, ["--exact-configuration"]
, ["--ghc-option=-fhide-source-paths" | hideSourcePaths cv]
]
where
wc = view (actualCompilerVersionL.to whichCompiler) econfig
cv = view (actualCompilerVersionL.to getGhcVersion) econfig
hideSourcePaths ghcVersion = ghcVersion >= mkVersion [8, 2] && configHideSourcePaths config
config = view configL econfig
bopts = bcoBuildOpts bco
newerCabal = view cabalVersionL econfig >= mkVersion [1, 22]
-- Unioning atop defaults is needed so that all flags are specified
-- with --exact-configuration.
flags = packageFlags package `Map.union` packageDefaultFlags package
depOptions = map (uncurry toDepOption) $ Map.toList deps
where
toDepOption = if newerCabal then toDepOption1_22 else toDepOption1_18
toDepOption1_22 (PackageIdentifier name _) gid = concat
[ "--dependency="
, packageNameString name
, "="
, ghcPkgIdString gid
]
toDepOption1_18 ident _gid = concat
[ "--constraint="
, packageNameString name
, "=="
, versionString version'
]
where
PackageIdentifier name version' = ident
-- | Get set of wanted package names from locals.
wantedLocalPackages :: [LocalPackage] -> Set PackageName
wantedLocalPackages = Set.fromList . map (packageName . lpPackage) . filter lpWanted
-- | Configure options to be sent to Setup.hs configure
data ConfigureOpts = ConfigureOpts
{ coDirs :: ![String]
-- ^ Options related to various paths. We separate these out since they do
-- not have an impact on the contents of the compiled binary for checking
-- if we can use an existing precompiled cache.
, coNoDirs :: ![String]
}
deriving (Show, Eq, Generic, Data, Typeable)
instance NFData ConfigureOpts
-- | Information on a compiled package: the library conf file (if relevant),
-- the sublibraries (if present) and all of the executable paths.
data PrecompiledCache base = PrecompiledCache
{ pcLibrary :: !(Maybe (Path base File))
-- ^ .conf file inside the package database
, pcSubLibs :: ![Path base File]
-- ^ .conf file inside the package database, for each of the sublibraries
, pcExes :: ![Path base File]
-- ^ Full paths to executables
}
deriving (Show, Eq, Generic, Typeable)
instance NFData (PrecompiledCache Abs)
instance NFData (PrecompiledCache Rel)
|
juhp/stack
|
src/Stack/Types/Build.hs
|
bsd-3-clause
| 28,596 | 0 | 23 | 8,456 | 5,386 | 2,918 | 2,468 | 616 | 6 |
--
-- MaterialTypes.hs
-- Copyright (C) 2017 jragonfyre <jragonfyre@jragonfyre>
--
-- Distributed under terms of the MIT license.
--
module Game.MaterialTypes where
-- (
-- ) where
import qualified Data.HashMap.Lazy as M
import qualified Data.Yaml as Y
import Data.Yaml (FromJSON (..), (.:), (.!=), (.:?), (.=), ToJSON (..))
import Control.Applicative ((<$>),(<*>),(<|>))
import qualified Data.Maybe as May
import qualified Data.List as L
import qualified Data.Text as T
import Data.Text (Text)
import Data.Aeson.Types (typeMismatch)
import Data.Vector (toList)
import Game.BaseTypes
import ParseUtilities
type Material = MaterialSt Identifier
data MaterialSt a = MaterialSt
{ materialName :: Identifier
, materialParents :: [a]
, materialDescriptions :: [String]
, materialProperties :: [MaterialProperty]
}
deriving (Show, Eq, Read)
instance (ToJSON a) => ToJSON (MaterialSt a) where
toJSON mat = Y.object
[ "material" .= materialName mat
, "parents" .= toJSONList (materialParents mat)
, "descriptions" .= toJSONList (materialDescriptions mat)
, "properties" .= toJSONList (materialProperties mat)
]
-- that way we can parse to Material Identifier, then later go to Material Material
instance (FromJSON a) => FromJSON (MaterialSt a) where
parseJSON (Y.Object v) = MaterialSt
<$> v .: "material"
<*> v .:? "parents" .!= []
<*> v .:? "descriptions" .!= []
<*> v .:? "properties" .!= []
parseJSON invalid = typeMismatch "Material" invalid
data MaterialProperty
= Flammable
| Metallic
| Wooden
| Carvable
| Durability Integer
| Value Integer
deriving (Show, Read, Eq)
instance ToJSON MaterialProperty where
toJSON Flammable = Y.String "flammable"
toJSON Metallic = Y.String "metallic"
toJSON Wooden = Y.String "wooden"
toJSON Carvable = Y.String "carvable"
toJSON (Durability dur) = Y.object ["durability" .= (toJSON dur)]
toJSON (Value val) = Y.object ["value" .= (toJSON val)]
instance FromJSON MaterialProperty where
parseJSON (Y.String "flammable") = return Flammable
parseJSON (Y.String "metallic") = return Metallic
parseJSON (Y.String "wooden") = return Wooden
parseJSON (Y.String "carvable") = return Carvable
parseJSON (Y.Object v)
= isKVPair v "durability" Durability
<|> isKVPair v "value" Value
<|> typeMismatch "MaterialProperty" (Y.Object v)
parseJSON invalid = typeMismatch "MaterialProperty" invalid
parseJSONList = parseAMAP parseJSON
|
jragonfyre/TRPG
|
src/Game/MaterialTypes.hs
|
bsd-3-clause
| 2,482 | 0 | 16 | 450 | 742 | 411 | 331 | 59 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
module Universe
( Universe
, Properties
, empty
, attributes
, contains
, insertTrait
, insertTheorem
, lookup
, relevantTheorems
, moveTheorem
, table
, fromPairs
, toPairs
) where
import Prelude hiding (lookup)
import Models.Types
import Formula (Implication(..), implicationProperties)
import Util (encodeText, fromSqlKey)
import Control.Monad.State (State, modify, gets)
import Data.Aeson
import Data.Int (Int64)
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import qualified Data.Set as S
import qualified Data.Text as T
type Properties = M.Map PropertyId TValueId
data Universe = Universe
{ uspaces :: M.Map SpaceId Properties
, utheorems :: M.Map TheoremId (Implication PropertyId)
, urelTheorems :: M.Map PropertyId [TheoremId]
} deriving Show
instance ToJSON Universe where
toJSON u = object . map fmtSpace . M.toList $ uspaces u
where
ts :: Int64 -> T.Text
ts = T.pack . show
fmtSpace (sid, props) = (ts $ fromSqlKey sid, object . map fmtProp $ M.toList props)
fmtProp (pid, vid) = (ts $ fromSqlKey pid, Bool $ toBool vid)
toBool :: TValueId -> Bool
toBool v -- FIXME! this clearly isn't the place for this
| fromSqlKey v == 1 = True
| fromSqlKey v == 2 = False
| otherwise = error "no mapping to boolean"
empty :: Universe
empty = Universe M.empty M.empty M.empty
lookup :: SpaceId -> PropertyId -> Universe -> Maybe TValueId
lookup s p = M.lookup p . attributes s
contains :: SpaceId -> PropertyId -> Universe -> Bool
contains sid pid = M.member pid . attributes sid
attributes :: SpaceId -> Universe -> Properties
attributes sid = fromMaybe M.empty . M.lookup sid . uspaces
relevantTheorems :: PropertyId -> Universe -> [(TheoremId, Implication PropertyId)]
relevantTheorems pid u = z $ map withImplication theoremIds
where
theoremIds = M.findWithDefault [] pid $ urelTheorems u
withImplication tid = (tid, M.lookup tid $ utheorems u)
z [] = []
z ((x, Just y) : zs) = (x,y) : z zs
z ( _ : zs) = z zs
-- TODO: refactor vvv
insertTrait :: SpaceId -> PropertyId -> TValueId -> State Universe ()
insertTrait s key t = modify $ \u -> u { uspaces = M.alter add s $ uspaces u }
where
add :: Maybe Properties -> Maybe Properties
add mps = Just $ case mps of
Nothing -> M.fromList [(key,t)]
Just ps -> M.insert key t ps
insertTheorem :: TheoremId -> Implication PropertyId -> State Universe ()
insertTheorem tid i = do
thrmLk <- gets utheorems
propLk <- gets urelTheorems
-- TODO: verify id isn't already present (esp. for `provisional`)
let theorems = M.insert tid i thrmLk
relThrms = foldl addTid propLk $ S.toList $ implicationProperties i
modify $ \u -> u { utheorems = theorems, urelTheorems = relThrms }
where
addTid :: M.Map PropertyId [TheoremId] -> PropertyId -> M.Map PropertyId [TheoremId]
addTid m p = M.insertWith (++) p [tid] m
replace :: Eq a => a -> a -> [a] -> [a]
replace old new = map f
where f x = if x == old then new else x
moveTheorem :: TheoremId -> TheoremId -> Universe -> Universe
moveTheorem old new u = u { utheorems = uts, urelTheorems = urs }
where
m = utheorems u
mv = M.lookup old m
uts = case mv of
Just val -> M.insert new val $ M.delete old m
Nothing -> M.delete old m
urs = M.map (replace old new) (urelTheorems u)
table :: Universe -> String
table Universe{..} = "Implications\n===\n" ++ implications
where
implications = unlines . map (T.unpack . encodeText) $ M.assocs utheorems
fromPairs :: [(SpaceId, Properties)] -> Universe
fromPairs ps = empty { uspaces = M.fromList ps }
toPairs :: Universe -> [(SpaceId, Properties)]
toPairs = M.toList . uspaces
|
jamesdabbs/pi-base-2
|
src/Universe.hs
|
bsd-3-clause
| 3,816 | 0 | 13 | 850 | 1,378 | 726 | 652 | 92 | 3 |
{-# LANGUAGE ForeignFunctionInterface #-}
-- | Low-level IO operations
-- These operations are either missing from the GHC run-time library,
-- or implemented suboptimally or heavy-handedly
--
module System.LowLevelIO (myfdRead, myfdSeek, Errno(..), select'read'pending)
where
import Foreign.C
import Foreign.Ptr
import System.Posix
import System.IO (SeekMode(..))
import Data.Bits -- for select
import Foreign.Marshal.Array -- for select
-- | Alas, GHC provides no function to read from Fd to an allocated buffer.
-- The library function fdRead is not appropriate as it returns a string
-- already. I'd rather get data from a buffer.
-- Furthermore, fdRead (at least in GHC) allocates a new buffer each
-- time it is called. This is a waste. Yet another problem with fdRead
-- is in raising an exception on any IOError or even EOF. I'd rather
-- avoid exceptions altogether.
--
myfdRead :: Fd -> Ptr CChar -> ByteCount -> IO (Either Errno ByteCount)
myfdRead (Fd fd) ptr n = do
n' <- cRead fd ptr n
if n' == -1 then getErrno >>= return . Left
else return . Right . fromIntegral $ n'
foreign import ccall unsafe "unistd.h read" cRead
:: CInt -> Ptr CChar -> CSize -> IO CInt
foreign import ccall unsafe "string.h" strerror :: Errno -> IO (Ptr CChar)
-- | The following fseek procedure throws no exceptions.
myfdSeek:: Fd -> SeekMode -> FileOffset -> IO (Either Errno FileOffset)
myfdSeek (Fd fd) mode off = do
n' <- cLSeek fd off (mode2Int mode)
if n' == -1 then getErrno >>= return . Left
else return . Right $ n'
where mode2Int :: SeekMode -> CInt -- From GHC source
mode2Int AbsoluteSeek = (0)
mode2Int RelativeSeek = (1)
mode2Int SeekFromEnd = (2)
foreign import ccall unsafe "unistd.h lseek" cLSeek
:: CInt -> FileOffset -> CInt -> IO FileOffset
-- | Darn! GHC doesn't provide the real select over several descriptors!
-- We have to implement it ourselves
--
type FDSET = CUInt
type TIMEVAL = CLong -- Two longs
foreign import ccall "unistd.h select" c_select
:: CInt -> Ptr FDSET -> Ptr FDSET -> Ptr FDSET -> Ptr TIMEVAL -> IO CInt
-- | Convert a file descriptor to an FDSet (for use with select)
-- essentially encode a file descriptor in a big-endian notation
fd2fds :: CInt -> [FDSET]
fd2fds fd = (replicate nb 0) ++ [setBit 0 off]
where
(nb,off) = quotRem (fromIntegral fd) (bitSize (undefined::FDSET))
fds2mfd :: [FDSET] -> [CInt]
fds2mfd fds = [fromIntegral (j+i*bitsize) |
(afds,i) <- zip fds [0..], j <- [0..bitsize],
testBit afds j]
where bitsize = bitSize (undefined::FDSET)
test_fd_conv = and $ map (\e -> [e] == (fds2mfd $ fd2fds e)) lst
where
lst = [0,1,5,7,8,9,16,17,63,64,65]
test_fd_conv' = mfd == fds2mfd fds
where
mfd = [0,1,5,7,8,9,16,17,63,64,65]
fds :: [FDSET]
fds = foldr ormax [] (map fd2fds mfd)
fdmax = maximum $ map fromIntegral mfd
ormax [] x = x
ormax x [] = x
ormax (a:ar) (b:br) = (a .|. b) : ormax ar br
unFd :: Fd -> CInt
unFd (Fd x) = x
-- | poll if file descriptors have something to read
-- Return the list of read-pending descriptors
select'read'pending :: [Fd] -> IO (Either Errno [Fd])
select'read'pending mfd =
withArray ([0,1]::[TIMEVAL]) ( -- holdover...
\timeout ->
withArray fds (
\readfs ->
do
rc <- c_select (fdmax+1) readfs nullPtr nullPtr nullPtr
if rc == -1 then getErrno >>= return . Left
-- because the wait was indefinite, rc must be positive!
else peekArray (length fds) readfs >>=
return . Right . map Fd . fds2mfd))
where
fds :: [FDSET]
fds = foldr ormax [] (map (fd2fds . unFd) mfd)
fdmax = maximum $ map fromIntegral mfd
ormax [] x = x
ormax x [] = x
ormax (a:ar) (b:br) = (a .|. b) : ormax ar br
foreign import ccall "fcntl.h fcntl" fcntl
:: CInt -> CInt -> CInt -> IO CInt
-- | use it as cleanup'fd [5..6] to clean up the sockets left hanging...
cleanup'fd = mapM_ (closeFd . Fd)
|
suhailshergill/liboleg
|
System/LowLevelIO.hs
|
bsd-3-clause
| 4,002 | 4 | 20 | 918 | 1,239 | 674 | 565 | 71 | 4 |
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Module : Game.Rendering
-- Description : Exposes the renderGame function and is the
-- entry point into the main rendering path for the game
-- Copyright : (c) 2016 Caitlin Wilks
-- License : BSD3
-- Maintainer : Caitlin Wilks <[email protected]>
--
--
module Game.Rendering
( renderGame
)
where
import ImGui
import Control.Lens
import System.Random
import Game.Data
import Game.Simulation.Camera.Camera
import Game.Terrain
import Game.Terrain.Rendering
import Data.Aeson
import Data.IORef
import Linear
import Graphics.Rendering.FTGL
import Graphics.GL.Compatibility33
import qualified SDL
import qualified Codec.Picture as Juicy
import qualified LambdaCube.GL as LC
import qualified LambdaCube.GL.Mesh as LC
import qualified LambdaCube.GL.Type as LC
import qualified LambdaCube.Linear as LC
import qualified Data.Map as Map
import qualified Data.Vector as V
import qualified Data.ByteString as BS
-- | Render the game based on its current state
renderGame :: IO (Game -> IO ())
renderGame = do
-- Set up lambdacube
let inputSchema = LC.makeSchema $ do
LC.defObjectArray "objects" LC.Triangles $ do
"position" LC.@: LC.Attribute_V3F
"uv" LC.@: LC.Attribute_V2F
"normal" LC.@: LC.Attribute_V3F
LC.defUniforms $ do
"projection" LC.@: LC.M44F
"time" LC.@: LC.Float
"diffuseTexture" LC.@: LC.FTexture2D
-- Allocate storage
storage <- LC.allocStorage inputSchema
-- Load texture
Right img <- Juicy.readImage "data/textures/grass_block.png"
textureData <- LC.uploadTexture2DToGPU img
-- Load pipeline and generate renderer
Just pipelineDesc <- decodeStrict <$> BS.readFile "data/pipelines/blocks.json"
renderer <- LC.allocRenderer pipelineDesc
-- Generate some random terrain
terrain <- randomChunk (10, 1, 10)
let terrainMesh = genChunkMesh terrain
LC.uploadMeshToGPU terrainMesh >>=
LC.addMeshToObjectArray storage "objects" []
-- Set storage
LC.setStorage renderer storage
-- Load font
font <- createTextureFont "data/fonts/droidsans.ttf"
setFontFaceSize font 22 72
-- Get start ticks
start <- SDL.ticks
-- An IORef for storing the ticks value
lastFPSUpdateRef <- newIORef start
lastFPSAvgRef <- newIORef (60 :: Int) -- ^ the initial value is a lie :)
lastFPSFrameCount <- newIORef (0 :: Int)
-- The render handler to return
return $ \game -> do
-- Get camera matrix and convert it to LC matrix
let projection = convertMatrix $ game ^. gameCamera ^. camMVPMat
let viewRot = (game ^. gameCamera ^. camViewMat) & translation .~ (V3 0 0 0)
let camForward = (V4 0 0 (-1) 0) *! viewRot
let cameraPos = game ^. gameCamera ^. camPosition
let cameraFov = game ^. gameCamera ^. camFov
igBegin "Status"
igText $ "Camera pos: " ++ show cameraPos
igText $ "Camera fov: " ++ show cameraFov
igText $ "Camera forward: " ++ show camForward
igEnd
-- Update timer
ticks <- SDL.ticks
-- Update fps counter
modifyIORef lastFPSFrameCount (+1)
lastFPSUpdate <- readIORef lastFPSUpdateRef
if (ticks - lastFPSUpdate) >= 1000
then do avgFps <- readIORef lastFPSFrameCount
writeIORef lastFPSAvgRef avgFps
writeIORef lastFPSUpdateRef ticks
writeIORef lastFPSFrameCount 0
else return ()
-- Read average fps
fps <- readIORef lastFPSAvgRef
-- Calculate time for unions
let diff = (fromIntegral (ticks - start)) / 100
let time = (fromIntegral ticks / 1000)
-- Update uniforms
LC.setScreenSize storage 800 600
LC.updateUniforms storage $ do
"projection" LC.@= return projection
"diffuseTexture" LC.@= return textureData
"time" LC.@= return (time :: Float)
-- Render a frame
LC.renderFrame renderer
-- | Render stats
-- Unused in favor of imgui, but might need it again
renderStats :: Font -> Int -> IO ()
renderStats font fps = do
-- Clean up opengl state (after lc render)
glUseProgram 0
glColor3f 1 1 1
glLoadIdentity
glOrtho 0 800 0 600 0 10
-- Disable depth test so we can draw on top of lc render
glDisable GL_DEPTH_TEST
-- Draw text
glPushMatrix
glTranslatef 50 50 0
renderFont font ("FPS: " ++ show fps ++ "hz") All
glPopMatrix
-- Restore depth test it's probably important
glEnable GL_DEPTH_TEST
-- | Convert a linear matrix to a lambacube one..
convertMatrix :: M44 Float -> LC.M44F
convertMatrix mat = let V4 (V4 a b c d)
(V4 e f g h)
(V4 i j k l)
(V4 m n o p) = mat
in LC.V4 (LC.V4 a e i m)
(LC.V4 b f j n)
(LC.V4 c g k o)
(LC.V4 d h l p)
|
Catchouli/tyke
|
src/Game/Rendering.hs
|
bsd-3-clause
| 5,081 | 0 | 18 | 1,474 | 1,194 | 598 | 596 | 101 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Lib
import Generator
import View
import Model
import Web.Scotty
import Data.List (intercalate)
import qualified Data.Text.Lazy as T
import Control.Monad.IO.Class (liftIO)
import Network.Wai.Middleware.Static
import System.Environment (getArgs)
import Text.Blaze.Html.Renderer.Text (renderHtml)
import qualified Data.Map.Strict as M
main :: IO ()
main = do
(port,maxPeople) <- args
scotty port $ do
middleware $ staticPolicy (noDots >-> addBase "static")
get "/run-model" $ do
-- rescue block sets sensible default if the parameter is missing
ex' <- param "ex" `rescue` (\_ -> return 200)
pm <- param "pm" `rescue` (\_ -> return 100.0)
ps <- param "ps" `rescue` (\_ -> return 15.0)
cm <- param "cm" `rescue` (\_ -> return 100.0)
cs <- param "cs" `rescue` (\_ -> return 15.0)
pp' <- (param "pp" :: ActionM Float) `rescue` (\_ -> return 50)
let pp = floor pp'
let ex = if ex' > maxPeople then 200 else ex'
rels <- liftIO $ createRels ex pp (pm,ps,cm,cs)
let res = reverse $ runExamples rels
let plKns = getKnowledges plKn rels
let chKns = getKnowledges chKn rels
let minK = floor $ minimum (plKns ++ chKns)
let maxK = ceiling $ maximum (plKns ++ chKns)
let pls = createHisto plKns minK maxK
let chs = createHisto chKns minK maxK
let maxC = yAxisMax pls chs
let (_,s1,s2,s3) = tuplesToArrs res
html $ renderHtml $ graphPage pm ps cm cs ex pp s1 s2 s3 pls chs maxC maxPeople
get "/run-model" $
-- if previous section fails (e.g. nr examples can't be parsed to an Int,
-- then we fall through to this section
redirect "/"
get "/" $
redirect "/run-model?ex=200&pm=100&ps=15&cm=100&cs=15&pp=50"
tuplesToArrs :: [(Int,Double,Double,Double)] -> ([Int],[Double],[Double],[Double])
tuplesToArrs res =
let ids = map (\(x,_,_,_) -> x) res
thought = map (\(_,x,_,_) -> x) res
best = map (\(_,_,x,_) -> x) res
got = map (\(_,_,_,x) -> x) res
in (ids,thought,best,got)
yAxisMax :: M.Map Int Int -> M.Map Int Int -> Int
yAxisMax m1 m2 =
let v = maximum $ M.elems m1 ++ M.elems m2
v' = (1.05 :: Float) * fromIntegral v
in ceiling v'
args :: IO (Int,Int)
args = do
(a1:a2:_) <- getArgs
let port = read a1
let a2' = read a2
let maxPeople = if a2' < 200 then 200 else a2'
return (port,maxPeople)
--printRes :: [(Int,Double,Double,Double)] -> T.Text
--printRes rs = T.pack $ intercalate "\n" $ "Count,Thought,Best,Actual" : map csvFormatter rs
--csvFormatter :: (Int,Double,Double,Double) -> String
--csvFormatter (a,b,c,d) = show a ++ "," ++ show b ++ "," ++
-- show c ++ "," ++ show d
|
alanbuxton/planck-chauffeur
|
app/Main.hs
|
bsd-3-clause
| 2,776 | 0 | 19 | 674 | 1,002 | 532 | 470 | 62 | 2 |
{-# LANGUAGE PatternGuards, ViewPatterns, CPP, ScopedTypeVariables #-}
module General.Util(
URL,
pretty, parseMode, tyApps, fromName, fromQName, fromTyVarBind, declNames,
tarballReadFiles,
isUpper1, isAlpha1,
splitPair, joinPair,
testing, timed,
showUTCTime,
list', strict,
withs,
escapeHTML, unescapeHTML, innerTextHTML, tag, tag_,
noinline,
takeSortOn,
Average, toAverage, fromAverage,
inRanges,
readMaybe,
exitFail,
general_util_test
) where
import Control.Monad.IO.Class
import Language.Haskell.Exts
import Control.Applicative
import Data.List.Extra
import Data.Char
import Data.Either.Extra
import Data.Monoid
import Control.Monad
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Map as Map
import Data.Ix
import Codec.Compression.GZip as GZip
import Codec.Archive.Tar as Tar
import Data.Time.Clock
import Data.Time.Format
import Control.DeepSeq
import Control.Exception.Extra
import Test.QuickCheck
import Foreign.Storable
import Data.Int
import System.IO
import System.Exit
import System.Time.Extra
#if __GLASGOW_HASKELL__< 710
import System.Locale
#endif
import Prelude
type URL = String
exitFail :: String -> IO ()
exitFail msg = do
hPutStrLn stderr msg
exitFailure
pretty :: Pretty a => a -> String
pretty = trim . unwords . words . prettyPrint
parseMode :: ParseMode
parseMode = defaultParseMode{extensions=map EnableExtension es}
where es = [ConstraintKinds,EmptyDataDecls,TypeOperators,ExplicitForAll,GADTs,KindSignatures,MultiParamTypeClasses
,TypeFamilies,FlexibleContexts,FunctionalDependencies,ImplicitParams,MagicHash,UnboxedTuples
,ParallelArrays,UnicodeSyntax,DataKinds,PolyKinds]
tyApps :: Type -> [Type] -> Type
tyApps x (t:ts) = tyApps (TyApp x t) ts
tyApps x [] = x
fromName :: Name -> String
fromName (Ident x) = x
fromName (Symbol x) = x
fromQName :: QName -> String
fromQName (Qual _ x) = fromName x
fromQName (UnQual x) = fromName x
fromQName (Special UnitCon) = "()"
fromQName (Special ListCon) = "[]"
fromQName (Special FunCon) = "->"
fromQName (Special (TupleCon box n)) = "(" ++ h ++ replicate n ',' ++ h ++ ")"
where h = ['#' | box == Unboxed]
fromQName (Special UnboxedSingleCon) = "(##)"
fromQName (Special Cons) = ":"
fromTyVarBind :: TyVarBind -> Name
fromTyVarBind (KindedVar x _) = x
fromTyVarBind (UnkindedVar x) = x
declNames :: Decl -> [String]
declNames x = map fromName $ case x of
TypeDecl _ name _ _ -> [name]
DataDecl _ _ _ name _ _ _ -> [name]
GDataDecl _ _ _ name _ _ _ _ -> [name]
TypeFamDecl _ name _ _ -> [name]
DataFamDecl _ _ name _ _ -> [name]
ClassDecl _ _ name _ _ _ -> [name]
TypeSig _ names _ -> names
_ -> []
tarballReadFiles :: FilePath -> IO [(FilePath, LBS.ByteString)]
tarballReadFiles file = f . Tar.read . GZip.decompress <$> LBS.readFile file
where
f (Next e rest) | NormalFile body _ <- entryContent e = (entryPath e, body) : f rest
f (Next _ rest) = f rest
f Done = []
f (Fail e) = error $ "tarballReadFiles on " ++ file ++ ", " ++ show e
-- | Take a piece of text and escape all the HTML special bits
escapeHTML :: String -> String
escapeHTML = concatMap f
where
f '<' = "<"
f '>' = ">"
f '&' = "&"
f '\"' = """
f x = [x]
-- | Only guarantees to be the inverse of escapeHTML
unescapeHTML :: String -> String
unescapeHTML ('&':xs)
| Just xs <- stripPrefix "lt;" xs = '<' : unescapeHTML xs
| Just xs <- stripPrefix "gt;" xs = '>' : unescapeHTML xs
| Just xs <- stripPrefix "amp;" xs = '&' : unescapeHTML xs
| Just xs <- stripPrefix "quot;" xs = '\"' : unescapeHTML xs
unescapeHTML (x:xs) = x : unescapeHTML xs
unescapeHTML [] = []
innerTextHTML :: String -> String
innerTextHTML ('<':xs) = innerTextHTML $ drop 1 $ dropWhile (/= '>') xs
innerTextHTML (x:xs) = x : innerTextHTML xs
innerTextHTML [] = []
isUpper1 (x:xs) = isUpper x
isUpper1 _ = False
isAlpha1 (x:xs) = isAlpha x
isAlpha1 [] = False
splitPair :: String -> String -> (String, String)
splitPair x y | (a,stripPrefix x -> Just b) <- breakOn x y = (a,b)
| otherwise = error $ "splitPair does not contain separator " ++ show x ++ " in " ++ show y
joinPair :: [a] -> ([a], [a]) -> [a]
joinPair sep (a,b) = a ++ sep ++ b
testing_, testing :: String -> IO () -> IO ()
testing_ name act = do putStr $ "Test " ++ name ++ " "; act
testing name act = do testing_ name act; putStrLn ""
timed :: MonadIO m => String -> m a -> m a
timed msg act = do
liftIO $ putStr (msg ++ "... ") >> hFlush stdout
time <- liftIO offsetTime
res <- act
time <- liftIO time
liftIO $ putStrLn $ showDuration time
return res
showUTCTime :: String -> UTCTime -> String
showUTCTime = formatTime defaultTimeLocale
list' :: NFData a => [a] -> [a]
list' (x:xs) = rnf x `seq` (x : list' xs)
list' [] = []
withs :: [(a -> r) -> r] -> ([a] -> r) -> r
withs [] act = act []
withs (f:fs) act = f $ \a -> withs fs $ \as -> act $ a:as
tag :: String -> [String] -> String -> String
tag name attr inner = "<" ++ unwords (name : map f attr) ++ ">" ++ inner ++ "</" ++ name ++ ">"
where f (break (== '=') -> (a,'=':b)) = a ++ "=\"" ++ escapeHTML b ++ "\""
f x = x
tag_ :: String -> String -> String
tag_ name inner = tag name [] inner
{-# NOINLINE noinline #-}
noinline :: a -> a
noinline a = a
-- ensure that no value escapes in a thunk from the value
strict :: NFData a => IO a -> IO a
strict act = do
res <- try_ act
case res of
Left e -> do msg <- showException e; evaluate $ rnf msg; error msg
Right v -> do evaluate $ rnf v; return v
-- I would like to use the storable-tuple package, but it's not in Stackage
instance Storable () where
sizeOf _ = 0
alignment _ = 1
peek _ = return ()
poke _ _ = return ()
instance forall a b . (Storable a, Storable b) => Storable (a,b) where
sizeOf x = sizeOf (fst x) + sizeOf (snd x)
alignment x = alignment (fst x) `max` alignment (snd x) -- dodgy, but enough for my purposes
peekByteOff ptr pos = liftM2 (,) (peekByteOff ptr pos) (peekByteOff ptr $ pos + sizeOf (undefined :: a))
pokeByteOff ptr pos (a,b) = pokeByteOff ptr pos a >> pokeByteOff ptr (pos + sizeOf (undefined :: a)) b
data Average a = Average !a !Int deriving Show -- a / b
toAverage :: a -> Average a
toAverage x = Average x 1
fromAverage :: Fractional a => Average a -> a
fromAverage (Average a b) = a / fromIntegral b
instance Num a => Monoid (Average a) where
mempty = Average 0 0
mappend (Average x1 x2) (Average y1 y2) = Average (x1+y1) (x2+y2)
readMaybe :: Read a => String -> Maybe a
readMaybe s | [x] <- [x | (x,t) <- reads s, ("","") <- lex t] = Just x
| otherwise = Nothing
data TakeSort k v = More !Int !(Map.Map k [v])
| Full !k !(Map.Map k [v])
-- | @takeSortOn n op == take n . sortOn op@
takeSortOn :: Ord k => (a -> k) -> Int -> [a] -> [a]
takeSortOn op n xs
| n <= 0 = []
| otherwise = concatMap reverse $ Map.elems $ getMap $ foldl' add (More n Map.empty) xs
where
getMap (More _ mp) = mp
getMap (Full _ mp) = mp
add (More n mp) x = (if n <= 1 then full else More (n-1)) $ Map.insertWith (++) (op x) [x] mp
add o@(Full mx mp) x = let k = op x in if k >= mx then o else full $ Map.insertWith (++) k [x] $ delMax mp
full mp = Full (fst $ Map.findMax mp) mp
delMax mp | Just ((k,_:vs), mp) <- Map.maxViewWithKey mp = if null vs then mp else Map.insert k vs mp
-- | Equivalent to any (`inRange` x) xs, but more efficient
inRanges :: Ix a => [(a,a)] -> (a -> Bool)
inRanges xs = \x -> maybe False (`inRange` x) $ Map.lookupLE x mp
where
mp = foldl' add Map.empty xs
merge (l1,u1) (l2,u2) = (min l1 l2, max u1 u2)
overlap x1 x2 = x1 `inRange` fst x2 || x2 `inRange` fst x1
add mp x
| Just x2 <- Map.lookupLE (fst x) mp, overlap x x2 = add (Map.delete (fst x2) mp) (merge x x2)
| Just x2 <- Map.lookupGE (fst x) mp, overlap x x2 = add (Map.delete (fst x2) mp) (merge x x2)
| otherwise = Map.insert (fst x) (snd x) mp
general_util_test :: IO ()
general_util_test = do
testing "General.Util.splitPair" $ do
let a === b = if a == b then putChar '.' else error $ show (a,b)
splitPair ":" "module:foo:bar" === ("module","foo:bar")
do x <- try_ $ evaluate $ rnf $ splitPair "-" "module:foo"; isLeft x === True
splitPair "-" "module-" === ("module","")
testing_ "General.Util.inRanges" $ do
quickCheck $ \(x :: Int8) xs -> inRanges xs x == any (`inRange` x) xs
|
BartAdv/hoogle
|
src/General/Util.hs
|
bsd-3-clause
| 8,719 | 0 | 16 | 2,119 | 3,684 | 1,892 | 1,792 | 216 | 8 |
{-# LANGUAGE OverloadedStrings #-}
module PSBT.Bower (
Bower(..)
, BowerError(..)
, Dependency(..)
, bowerErrorHandler
, bowerErrorMessage
, createBowerFile
, minimalBower
, readBowerFile
) where
import Control.Applicative (empty, optional, (<|>))
import Control.Exception (Exception)
import Control.Monad (unless)
import Control.Monad.Catch (Handler (..), MonadThrow, throwM)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Reader (ReaderT (..), runReaderT)
import Data.Aeson (ToJSON, object, toJSON, (.=))
import Data.Aeson.BetterErrors (Parse, ParseError, asBool,
asObject, asString, displayError,
eachInArray, eachInObject, key,
keyMay, keyOrDefault,
throwCustomError)
import qualified Data.Aeson.BetterErrors as A (parse)
import Data.Aeson.Encode.Pretty (Config (..), defConfig,
encodePretty', keyOrder)
import qualified Data.ByteString.Lazy as B (hPutStr, readFile)
import Data.Char (toLower)
import Data.HashMap.Lazy (HashMap, toList)
import Data.Text (Text)
import qualified Data.Text as T (pack, unlines, unpack)
import System.Directory (doesFileExist)
import System.IO (IOMode (WriteMode), withFile,
writeFile)
import Text.Megaparsec (errorMessages, messageString)
import qualified Text.Megaparsec as M (parse)
import PSBT.SemVer (Range, displayRange, range)
data Dependency = Dependency {
packageName :: Text
, version :: Maybe Range
} deriving Show
instance ToJSON Dependency where
toJSON d = object [packageName d .= maybe "latest" displayRange (version d)]
data Bower = Bower {
name :: String
, description :: Maybe String
, mainModule :: Maybe [String]
, dependencies :: Maybe [Dependency]
, devDependencies :: Maybe [Dependency]
, resolutions :: Maybe [Dependency]
} deriving Show
minimalBower :: String -> Bower
minimalBower name = Bower name Nothing Nothing Nothing Nothing Nothing
instance ToJSON Bower where
toJSON b = object [
"name" .= name b
, "description" .= description b
, "main" .= mainModule b
, "dependencies" .= dependencies b
, "devDependencies" .= devDependencies b
, "resolutions" .= resolutions b
]
data BowerError = JSONError Text
| FileNotFound FilePath
deriving Show
instance Exception BowerError where
asDependencies :: Parse Text [Dependency]
asDependencies = do
depList <- eachInObject asString
traverse getDependency depList
where
getDependency (name,versionStr)
| versionStr == "latest" = return $ Dependency name Nothing
| otherwise = case M.parse range "Bower" versionStr of
Right r -> return $ Dependency name (Just r)
Left e -> throwCustomError . T.pack . unlines . map messageString . errorMessages $ e
asBower :: Parse Text Bower
asBower = Bower <$>
key "name" asString <*>
keyMay "description" asString <*>
keyMay "main" (eachInArray asString) <*>
keyMay "dependencies" asDependencies <*>
keyMay "devDependencies" asDependencies <*>
keyMay "resolutions" asDependencies
readBowerFile :: (MonadIO m, MonadThrow m) => FilePath -> m Bower
readBowerFile fp = do
exists <- liftIO $ doesFileExist fp
unless exists (throwM $ FileNotFound fp)
bower <- liftIO $ B.readFile fp
case A.parse asBower bower of
Left e -> throwM (JSONError . T.unlines $ displayError id e)
Right b -> return b
createBowerFile :: (MonadIO m, MonadThrow m) => Bower -> m ()
createBowerFile bower = liftIO $ do
b <- doesFileExist "bower.json"
if b then prompt else createTheFile
where
prompt = do
putStrLn "bower.json already exists. Do you want to overwrite it? (y/n)"
r <- toLower <$> getChar
case r of
'y' -> createTheFile
'n' -> return ()
_ -> prompt
orderList = ["name","description","main","dependencies","devDependencies","resolutions"]
jsonString = encodePretty' defConfig { confCompare = keyOrder orderList } bower
createTheFile = withFile "bower.json" WriteMode (`B.hPutStr` jsonString)
bowerErrorMessage :: BowerError -> String
bowerErrorMessage (JSONError msg) = "Error parsing bower.json: " ++ T.unpack msg
bowerErrorMessage (FileNotFound fp) = "bower.json not found: " ++ fp ++ " does not exist"
bowerErrorHandler :: MonadIO m => Handler m ()
bowerErrorHandler = Handler $ liftIO . putStrLn . bowerErrorMessage
|
LightAndLight/psbt
|
src/PSBT/Bower.hs
|
bsd-3-clause
| 5,251 | 0 | 16 | 1,693 | 1,309 | 719 | 590 | 109 | 4 |
{-# LANGUAGE ScopedTypeVariables #-}
module TestFSM3 where
import System.IO
import Control.Monad.State
import Control.Exception
data UserInput = UIActionSumTwoNumbers | UIActionQuit | UIInt Int | UIAny
data AppOut = AOEnd String | AOLink App | AOMessage String App
type UserState = [Int]
type NodeId = String
data App = App {
name :: NodeId,
message :: String,
parser :: String -> Maybe UserInput,
handler :: UserInput -> StateT UserState IO AppOut
-- can put state-specific stuff like ring tone, display props, etc here
}
idle = App {
name = "idle",
message = "What do you want to do?",
parser = \ i -> case i of
"quit" -> Just UIActionQuit
"sum" -> Just UIActionSumTwoNumbers
_ -> Nothing
,
handler = \e -> case e of
UIActionSumTwoNumbers -> return $ AOLink getANumber
UIActionQuit -> return $ AOEnd "Goodbye!"
}
getANumber = App {
name = "getANumber",
message = "Enter a number",
parser = fmap UIInt . readMaybe,
handler = \e -> case e of
UIInt i -> do
is <- get
let is' = i:is
put is'
return $ if length is' == 2 then AOLink sumTwoNumbers else AOMessage "Thanks ..." getANumber
}
sumTwoNumbers = App {
name = "sumTwoNumbers",
message = "Press enter to get the sum",
parser = const $ Just UIAny,
handler = const $ do
is <- get
return $ AOEnd ("And the sum is " ++ show (sum is))
}
getApp :: NodeId -> App
getApp "idle" = idle
getApp "getANumber" = getANumber
getApp "sumTwoNumbers" = sumTwoNumbers
getApp n = error $ "No state found for " ++ n
run :: App -> UserInput -> UserState -> IO (AppOut, UserState)
run app = runStateT . handler app
getUserInput :: App -> IO UserInput
getUserInput app = getLine >>= \c -> case parser app c of
Nothing -> print "Invalid Input" >> getUserInput app
Just i -> return i
runApp :: NodeId -> UserState -> IO ()
runApp nodeId userState = do
let oApp = getApp nodeId
print $ message oApp
e <- getUserInput oApp
(mApp, userState') <- run oApp e userState
case mApp of
AOEnd message -> writeFile "./temp" "" >> print message
AOLink app -> writeFile "./temp" (show (name app, userState'))
AOMessage message app -> writeFile "./temp" (show (name app, userState')) >> print message
main = do
stFile <- readFileMaybe "./temp"
case (stFile >>= readMaybe) :: Maybe (NodeId, UserState) of
Nothing -> runApp "idle" []
Just (nodeId, userState) -> runApp nodeId userState
-- utils
readMaybe :: (Read a) => String -> Maybe a
readMaybe s = case reads s of
[] -> Nothing
[(a, _)] -> Just a
readFileMaybe :: String -> IO (Maybe String)
readFileMaybe path = do
stFile <- try $ readFile path
case stFile of
Left (e :: IOException) -> return Nothing
Right f -> return $ Just f
|
homam/fsm-conversational-ui
|
src/TestFSM3.hs
|
bsd-3-clause
| 2,751 | 0 | 16 | 623 | 963 | 493 | 470 | 77 | 4 |
{-# LANGUAGE PackageImports #-}
module Control.Exception.Base (module M) where
import "base" Control.Exception.Base as M
|
silkapp/base-noprelude
|
src/Control/Exception/Base.hs
|
bsd-3-clause
| 126 | 0 | 4 | 18 | 23 | 17 | 6 | 3 | 0 |
-- | QuickCheck properties.
module Test.Properties
( fmapTermFunctorProp
, foldTermId
, freeVarsTVarsInTerm
, fmapFormulaFunctorProp
, foldFormulaId
, cnfProp
, cnfIdempotent
, prenexProp
, prenexIdempotent
, skolemizeProp
)
where
import qualified Data.Set as Set
import Control.Applicative
import Logic hiding (prenex, skolemize)
import Test.Var
-- | Checks whether the formula contains any binders ('Forall' or 'Exists').
binderFree :: Formula r f v -> Bool
binderFree = foldF
(\_ _ -> True)
(\_ _ -> False)
(\_ _ -> False)
id (&&) (&&) (&&)
-- | 'Term' 'fmap' satisfies the first 'Functor' law. Second one then holds
-- by parametricity.
fmapTermFunctorProp :: Term Var Var -> Bool
fmapTermFunctorProp t = fmap id t == t
-- | 'foldT' applied to constructors is identity.
foldTermId :: Term Var Var -> Bool
foldTermId t = t == foldT Var Function t
-- | A variable is in 'freeVars' @t@ precisely when it is in @t@.
freeVarsTVarsInTerm :: Var -> Term Var Var -> Bool
freeVarsTVarsInTerm s t = s `Set.member` fvT == contains s t
where
fvT = freeVarsT t
contains var = go
where
go (Var x) = var == x
go (Function _ ts) = any go ts
-- | 'Formula' 'fmap' satisfies the first 'Functor' law. See
-- 'fmap_term_functor_prop'.
fmapFormulaFunctorProp :: Formula Var Var Var -> Bool
fmapFormulaFunctorProp f = fmap id f == f
-- | 'foldF' applied to constructors is identity.
foldFormulaId :: Formula Var Var Var -> Bool
foldFormulaId f = f == foldF Relation Forall Exists Not And Or Implies f
-- | 'cnf' produces a conjunctive normal form.
cnfProp :: Formula Var Var Var -> Bool
cnfProp fl = check . cnf . snd . splitPrenex . prenex $ fl
where
check (And f g) = check f && check g
check (Or f g) = check2 (Or f g)
check (Not (Relation _ _)) = True
check (Relation _ _) = True
check _ = False
check2 (Or f g) = check2 f && check2 g
check2 (Not (Relation _ _)) = True
check2 (Relation _ _) = True
check2 _ = False
-- | 'cnf' is idempotent.
cnfIdempotent :: Formula Var Var Var -> Bool
cnfIdempotent f = cnf f' == cnf (cnf f')
where
f' = snd . splitPrenex . prenex $ f
-- | 'prenex' produces prenex normal form.
prenexProp :: Formula Var Var Var -> Bool
prenexProp = check . prenex
where
check (Forall _ f) = check f
check (Exists _ f) = check f
check f = binderFree f
-- | 'prenex' is idempotent with respect to formula structure (especially
-- /not/ with respect to variables, which can be renamed).
prenexIdempotent :: Formula Var Var Var -> Bool
prenexIdempotent f = prenex f `varEq` prenex (prenex f)
where
varEqT (Function f1 ts1) (Function f2 ts2) =
f1 == f2 && and (zipWith varEqT ts1 ts2)
varEqT (Var _) (Var _) = True
varEqT _ _ = False
varEq (Relation r1 ts1) (Relation r2 ts2) =
r1 == r2 && and (zipWith varEqT ts1 ts2)
varEq (Forall _ f1) (Forall _ f2) = f1 `varEq` f2
varEq (Exists _ f1) (Exists _ f2) = f1 `varEq` f2
varEq (Not f1) (Not f2) = f1 `varEq` f2
varEq (And f1 g1) (And f2 g2) = f1 `varEq` f2 && g1 `varEq` g2
varEq (Or f1 g1) (Or f2 g2) = f1 `varEq` f2 && g1 `varEq` g2
varEq (Implies f1 g1) (Implies f2 g2) = f1 `varEq` f2 && g1 `varEq` g2
varEq _ _ = False
-- | 'skolemize' produces Skolem normal form.
skolemizeProp :: Formula Var Var Var -> Bool
skolemizeProp fl = ((&&) <$> noEx <*> binderFree) . skolemize $ fl'
where
fl' = prenex fl
-- All existentially quantified variables.
exVars = exQualVars fl'
noEx = foldFw (`Set.notMember` exVars)
(const and) (const and) (const id) id (&&)
-- Extracts existentially quantified variables from prenex part.
exQualVars (Forall _ f) = exQualVars f
exQualVars (Exists x f) = Set.insert x (exQualVars f)
exQualVars _ = Set.empty
|
vituscze/logic
|
tests/Test/Properties.hs
|
bsd-3-clause
| 4,074 | 0 | 11 | 1,156 | 1,320 | 691 | 629 | 78 | 10 |
----------------------------------------------------------------------------
-- |
-- Module : Haskell.Language.Lexer
-- Copyright : (c) Sergey Vinokurov 2016
-- License : BSD3-style (see LICENSE)
-- Maintainer : [email protected]
-- Created : Thursday, 3 November 2016
----------------------------------------------------------------------------
module Haskell.Language.Lexer
( tokenize
-- , tokenizeM
-- , LiterateMode(..)
, LiterateLocation(..)
) where
-- import Data.Functor.Identity
import qualified Data.ByteString as BS
import GHC.Stack.Ext (WithCallStack)
import System.FilePath
-- import Haskell.Language.Lexer.FastTags (Token)
-- import Haskell.Language.Lexer.Lexer (tokenizeM)
-- import Haskell.Language.Lexer.Types (LiterateMode(..))
import Haskell.Language.Lexer.FastTags
import qualified Haskell.Language.LexerSimple.Lexer as SimpleLexer
import Haskell.Language.LexerSimple.Types (LiterateLocation(..))
tokenize :: WithCallStack => FilePath -> BS.ByteString -> [Pos ServerToken]
-- tokenize filename = runIdentity . tokenizeM filename mode
-- where
-- mode :: LiterateMode
-- mode
-- | takeExtension filename == ".lhs" = Literate
-- | otherwise = Vanilla
tokenize filename = SimpleLexer.tokenize filename mode
where
mode :: LiterateLocation a
mode
| takeExtension filename `elem` [".lhs", ".lhs-boot"]
= LiterateOutside
| otherwise
= Vanilla
|
sergv/tags-server
|
src/Haskell/Language/Lexer.hs
|
bsd-3-clause
| 1,472 | 0 | 11 | 261 | 182 | 116 | 66 | -1 | -1 |
main = print $ sum $ filter even $ takeWhile (<= 4000000) fib where
fib = 1 : 2 : zipWith (+) fib (tail fib)
|
foreverbell/project-euler-solutions
|
src/2.hs
|
bsd-3-clause
| 113 | 0 | 10 | 29 | 60 | 31 | 29 | 2 | 1 |
{-# LANGUAGE TypeOperators #-}
-- | an example of how repa and our extention can be used together
module Main where
import Raytracer
import Data.Time
import qualified Data.Array.Repa as R
import Data.Array.Repa.IO.BMP
import qualified Data.Array.Repa.Algorithms.Matrix as R
-- | used as the camera for this example
dummyCam :: Camera
dummyCam = createCamera (1,0,0) (0,0,0) (0,1,0) (45)
-- | This is the example
main :: IO ()
main = do
let hight = 500
let width = 500
-- make a sphere possition and make 2
-- others from rotated versions of the first
let spherePos1' = R.fromListUnboxed (R.ix2 1 3) [10.0,0.0,0.0]
spherePos2' <- R.mmultP spherePos1' (rotMatY (0-pi/4))
spherePos3' <- R.mmultP spherePos1' (rotMatY (pi/4))
--- take the vector part of the matrix
let spherePos1 = R.computeUnboxedS $
R.slice (R.transpose spherePos1') (R.Any R.:. (0::Int))
let spherePos2 = R.computeUnboxedS $
R.slice (R.transpose spherePos2') (R.Any R.:. (0::Int))
let spherePos3 = R.computeUnboxedS $
R.slice (R.transpose spherePos3') (R.Any R.:. (0::Int))
-- generate the objects fro the repa arrays (vectors)
let obj = ([EntO (createPlane vDown vUp (0.0,150.0,0.0) 1 0),
EntO (v2Sphere spherePos1 (t2c Blue) 2.0 0 16),
EntO (v2Sphere spherePos2 (t2c White) 2.0 0 16),
EntO (v2Sphere spherePos3 (t2c Red) 2.0 0 16),
EntL (createLight (6.0,0.0,0.0) (t2c White))])
putStrLn ("Starting trace on a " ++ show width ++ "x"
++ show hight ++ " ...")
t0 <- getCurrentTime
-- trace the image to an array
let image = trace2Array obj dummyCam (width ,hight) 2 --"test.bmp"
-- flipp the image 180
let imageFinal = R.computeUnboxedS $ rot180 image
--prin the image and it's 180 rotated counterpart
writeImageToBMP ("./revers.bmp") imageFinal
writeImageToBMP ("./normal.bmp") image
t1 <- getCurrentTime
putStrLn ("Trace is done (in "++ show (diffUTCTime t1 t0) ++
") creating image named " ++ "normal.bmp and revers.bmp")
-- | shamlessly stolen from the repa Tutorial to show that
-- you can postprosess our traced images
-- https://wiki.haskell.org/Numeric_Haskell:_A_Repa_Tutorial
rot180 :: (R.Source r e) => R.Array r R.DIM2 e -> R.Array R.D R.DIM2 e
rot180 g = R.backpermute e flop g
where
e@(R.Z R.:. x R.:. y ) = R.extent g
flop (R.Z R.:. i R.:. j ) =
(R.Z R.:. x - i - 1 R.:. y - j - 1 )
rotMatY :: Double -> R.Array R.U R.DIM2 Double
rotMatY angle = R.fromListUnboxed (R.ix2 3 3)[
cos(angle)::Double, 0.0, sin(angle)::Double,
0.0, 1.0, 0.0,
(0.0-sin(angle))::Double, 0.0, cos(angle)::Double]
|
axhav/AFPLAB3
|
executable/Preview.hs
|
bsd-3-clause
| 2,966 | 0 | 16 | 883 | 931 | 494 | 437 | 47 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Utils.Bytes
( stringToByteString
, byteStringToString
, hexStringToByteString
, byteStringToHexString
, hexstringToBase64
, c2w
, w2c
, blocks
, pad
, unpad
, all_chars
) where
import qualified Data.ByteString.Base64 as B64
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString as B
import GHC.Base (unsafeChr)
import Data.Char (ord)
import Data.Word (Word8)
import Data.Function
import qualified Data.List.Split as Split
import qualified Data.List as List
import qualified Data.Char as Ch
import Utils.Elmify ((|>))
-- CONVERSION
stringToByteString :: [Char] -> B.ByteString
stringToByteString str =
map c2w str
|> B.pack
byteStringToString :: B.ByteString -> [Char]
byteStringToString bs =
B.unpack bs
|> map w2c
c2w :: Char -> Word8
c2w = fromIntegral . ord
w2c :: Word8 -> Char
w2c = unsafeChr . fromIntegral
-- convert strings like "37f384" into a bytestring with that hexadecimal value
hexStringToByteString :: [Char] -> B.ByteString
hexStringToByteString str =
map c2w str -- [Char] -> [Word8]
|> B.pack -- [Word8] -> ByteString
|> B16.decode -- from Hex (Base16) to (ByteString, ByteString) (snd is for characters failing the parsing)
|> fst -- take the first from the tuple
-- convert a bytestring with a hexadecimal value into a string
byteStringToHexString :: B.ByteString -> [Char]
byteStringToHexString bStr =
B16.encode bStr -- binary -> Base16
|> B.unpack -- ByteString -> [Word8]
|> map w2c -- [Word8] -> [Char]
hexstringToBase64 :: [Char] -> B.ByteString
hexstringToBase64 str =
hexStringToByteString str -- convert to ByteString first
|> B64.encode -- encode Base64
-- utility to chop a ByteString into a list of bytestrings of sz bytes
blocks :: Int -> B.ByteString -> [B.ByteString]
blocks sz bs =
B.unpack bs
|> Split.chunksOf (fromIntegral sz)
|> map B.pack
pad_byte :: Word8
pad_byte =
0x04
pad :: Int -> B.ByteString -> B.ByteString
pad blksz key =
let
keysz =
B.length key
padding =
B.replicate blksz pad_byte
|> B.drop keysz
in
B.append key padding
unpad :: B.ByteString -> B.ByteString
unpad bs =
B.takeWhile (\c -> c /= pad_byte) bs
all_chars :: [Word8]
all_chars =
[1..255]::[Word8]
|
eelcoh/cryptochallenge
|
src/Utils/Bytes.hs
|
bsd-3-clause
| 2,364 | 0 | 11 | 511 | 574 | 326 | 248 | 74 | 1 |
module Eight where
decodedLength :: String -> Int
decodedLength [] = 0
decodedLength ('\\':stuff) =
case stuff of
'\\':rest -> 1 + decodedLength rest
'"':rest -> 1 + decodedLength rest
'x':rest -> 1 + decodedLength (drop 2 rest)
_ -> error "illegal escape"
decodedLength ['"'] = 0
decodedLength ('"':xs) = decodedLength xs
decodedLength (_:xs) = 1 + decodedLength xs
extraSpace :: String -> Int
extraSpace encoded = length encoded - decodedLength encoded
calculateExtraSpace :: [String] -> Int
calculateExtraSpace input = sum allLines
where allLines = map extraSpace input
eight :: IO Int
eight = do
input <- readFile "input/8.txt"
return . calculateExtraSpace . lines $ input
|
purcell/adventofcodeteam
|
app/Eight.hs
|
bsd-3-clause
| 698 | 0 | 11 | 127 | 261 | 130 | 131 | 21 | 4 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.EXT.RasterMultisample
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/EXT/raster_multisample.txt EXT_raster_multisample> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.EXT.RasterMultisample (
-- * Enums
gl_EFFECTIVE_RASTER_SAMPLES_EXT,
gl_MAX_RASTER_SAMPLES_EXT,
gl_MULTISAMPLE_RASTERIZATION_ALLOWED_EXT,
gl_RASTER_FIXED_SAMPLE_LOCATIONS_EXT,
gl_RASTER_MULTISAMPLE_EXT,
gl_RASTER_SAMPLES_EXT,
-- * Functions
glRasterSamplesEXT
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/EXT/RasterMultisample.hs
|
bsd-3-clause
| 933 | 0 | 4 | 103 | 64 | 50 | 14 | 10 | 0 |
{-# LANGUAGE TypeOperators #-}
module Zero.Bitstamp.API
(
BitstampAPI
, bitstampAPI
) where
import Data.Proxy (Proxy(..))
import Data.Text (Text)
import Servant.API
import Zero.Bitstamp.Internal
------------------------------------------------------------------------------
type BitstampAPI =
"api" :> "v2" :> "ticker" :> Capture "currency_pair" Text
:> Get '[JSON] Ticker
------------------------------------------------------------------------------
bitstampAPI :: Proxy BitstampAPI
bitstampAPI = Proxy
|
et4te/zero
|
src-shared/Zero/Bitstamp/API.hs
|
bsd-3-clause
| 567 | 0 | 11 | 109 | 103 | 61 | 42 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
module LendingClub.Monad where
import Control.Concurrent (ThreadId, forkIO)
import Control.Concurrent.Async
import Control.Concurrent.STM
import Control.Monad.Reader
import Data.ByteString
import Data.Configurator
import Data.IntSet as S
import Data.Vector as V
import LendingClub.Authorization
import LendingClub.Commands
import LendingClub.Listing
import Logging
data LendingClubState = LCS
{ lcListings :: TVar IntSet
, lcListingState :: TVar (Vector Listing)
, lcProcessingQueue :: TChan Listing
, lcMarketDataAccount :: Authorization -- Maybe remove from TVar
, lcApiUrl :: !ByteString
}
-- Maybe shouldn't have https
defaultApi :: ByteString
defaultApi = "api.lendingclub.com"
defaultAuthorization :: ByteString
defaultAuthorization = ""
defaultInvestorId :: InvestorId
defaultInvestorId = InvestorId 0
initializeLendingClub :: FilePath -> IO LendingClubState
initializeLendingClub lcConfig = do
ls <- newTVarIO S.empty
lss <- newTVarIO V.empty
pq <- newBroadcastTChanIO
config <- load [ Required lcConfig ]
auth <- lookupDefault defaultAuthorization config "lendingclub.authorization"
let mdAcct = Authorization auth
au <- lookupDefault defaultApi config "lendingclub.apiurl"
-- TODO initialize logs
return $ LCS ls lss pq mdAcct au
type LendingClub a = ReaderT LendingClubState IO a
runLendingClub :: LendingClubState -> LendingClub a -> IO a
runLendingClub = flip runReaderT
getApiUrl :: LendingClub ByteString
getApiUrl = asks lcApiUrl
enqueueListing :: Listing -> LendingClub ()
enqueueListing l = do
pq <- asks lcProcessingQueue
liftIO . atomically $ writeTChan pq l
writeListingsState :: Vector Listing -> LendingClub ThreadId
writeListingsState = forkLC . updateLCVar lcListingState
getListings :: LendingClub IntSet
getListings = readLCVar lcListings
readLCVar :: (MonadIO m, MonadReader r m) => (r -> TVar a) -> m a
readLCVar x = do
t <- asks x
liftIO $ readTVarIO t
updateLCVar :: (MonadIO m, MonadReader r m) => (r -> TVar a) -> a -> m ()
updateLCVar x val = do
t <- asks x
liftIO . atomically $ writeTVar t val
mapIOLC :: (IO a -> IO b) -> LendingClub a -> LendingClub b
mapIOLC f g = ask >>= liftIO . f . runReaderT g
forkLC :: LendingClub () -> LendingClub ThreadId
forkLC = mapIOLC forkIO
asyncLC :: LendingClub a -> LendingClub (Async a)
asyncLC = mapIOLC async
waitLC :: Async a -> LendingClub a
waitLC = liftIO . wait
-- | Does not talk to LendingClub's listings endpoint.
-- This uses in-memory data to retrieve listings.
{-
listingFromNote :: Note -> LendingClub (Maybe Listing)
listingFromNote (Note { N.loanId = lid }) = do
listings <- readLCVar lcListingState
return $ V.find (\l -> listingId l == lid) listings
-}
updateAllListings :: LendingClub ()
updateAllListings = do
auth <- asks lcMarketDataAccount
listingsNow <- liftIO $ allListings auth
addListings listingsNow
where
addListings :: Vector Listing -> LendingClub ()
addListings listings = do
_ <- writeListingsState listings
oldListings <- getListings
newListings <- V.foldM' (addListing oldListings) S.empty listings
updateLCVar lcListings newListings
addListing :: IntSet -> IntSet -> Listing -> LendingClub IntSet
addListing oldls ls l = do
let lid = listingId l
when (lid `S.notMember` oldls) $ do
infoM "LendingClub" "Detected new listing!"
enqueueListing l
return $ S.insert lid ls
|
WraithM/notescript
|
src/LendingClub/Monad.hs
|
bsd-3-clause
| 3,772 | 0 | 12 | 903 | 945 | 469 | 476 | 86 | 1 |
module Cardano.Wallet.API.V1.Errors where
import Universum
import Cardano.Wallet.API.V1.Headers (applicationJson)
import Data.Aeson (ToJSON, encode)
import Formatting (build, sformat)
import Servant (ServantErr (..))
import qualified Network.HTTP.Types as HTTP
class (ToJSON e) => ToServantError e where
declareServantError :: e -> ServantErr
toServantError :: e -> ServantErr
toServantError err =
mkServantErr (declareServantError err)
where
mkServantErr serr@ServantErr{..} = serr
{ errBody = encode err
, errHeaders = applicationJson : errHeaders
}
class (ToServantError e, Buildable e) => ToHttpErrorStatus e where
toHttpErrorStatus :: e -> HTTP.Status
toHttpErrorStatus err =
HTTP.Status (errHTTPCode $ toServantError err) (encodeUtf8 $ sformat build err)
|
input-output-hk/pos-haskell-prototype
|
wallet/src/Cardano/Wallet/API/V1/Errors.hs
|
mit
| 906 | 0 | 12 | 237 | 235 | 133 | 102 | -1 | -1 |
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE FlexibleContexts #-}
module Network.IPTables.ParserHelper where
import Data.Functor ((<$>), ($>))
import Network.IPTables.IsabelleToString (Word32, Word128)
import Data.List.Split (splitOn)
import qualified Network.IPTables.Generated as Isabelle
import Text.Parsec (char, choice, many, many1, Parsec, oneOf, noneOf, string, (<|>), try)
quotedString = do
a <- string "\""
b <- concat <$> many quotedChar
c <- string "\""
return (a ++ b ++ c)
where quotedChar = try (string "\\\\") <|> try (string "\\\"") <|> ((noneOf "\"\n") >>= \x -> return [x] )
nat :: Parsec String s Integer
nat = do
n <- read <$> many1 (oneOf ['0'..'9'])
if n < 0 then
error ("nat `" ++ show n ++ "' must be greater than or equal to zero")
else
return n
natMaxval :: Integer -> Parsec String s Isabelle.Nat
natMaxval maxval = do
n <- nat
if n > maxval then
error ("nat `" ++ show n ++ "' must be smaller than or equal to " ++ show maxval)
else
return (Isabelle.nat_of_integer n)
ipv4dotdecimal :: Parsec String s (Isabelle.Word Word32)
ipv4dotdecimal = do
a <- natMaxval 255
char '.'
b <- natMaxval 255
char '.'
c <- natMaxval 255
char '.'
d <- natMaxval 255
return $ ipv4word (a, (b, (c, d)))
where ipv4word :: (Isabelle.Nat, (Isabelle.Nat, (Isabelle.Nat, Isabelle.Nat))) -> Isabelle.Word Word32
ipv4word = Isabelle.ipv4addr_of_dotdecimal
ipv4addr :: Parsec String s (Isabelle.Ipt_iprange Word32)
ipv4addr = Isabelle.IpAddr <$> ipv4dotdecimal
ipv4cidr :: Parsec String s (Isabelle.Ipt_iprange Word32)
ipv4cidr = do
ip <- ipv4dotdecimal
char '/'
netmask <- natMaxval 32
return $ Isabelle.IpAddrNetmask ip netmask
ipv4range :: Parsec String s (Isabelle.Ipt_iprange Word32)
ipv4range = do
ip1 <- ipv4dotdecimal
char '-'
ip2 <- ipv4dotdecimal
return $ Isabelle.IpAddrRange ip1 ip2
ipv6colonsep :: Parsec String s (Isabelle.Word Word128)
ipv6colonsep = do
ipv6string <- many1 (oneOf $ ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ [':'])
let ipv6parts = map option_int $ splitOn ":" ipv6string
let parsed = case Isabelle.mk_ipv6addr ipv6parts
of Nothing -> error $ "invalid IPv6 address: " ++ ipv6string
Just x -> Isabelle.ipv6preferred_to_int x
return parsed
where option_int "" = Nothing
option_int i = Just (Isabelle.integer_to_16word (readHex i))
readHex :: String -> Integer
readHex x = read ("0x" ++ x)
ipv6addr :: Parsec String s (Isabelle.Ipt_iprange Word128)
ipv6addr = Isabelle.IpAddr <$> ipv6colonsep
ipv6cidr :: Parsec String s (Isabelle.Ipt_iprange Word128)
ipv6cidr = do
ip <- ipv6colonsep
char '/'
netmask <- natMaxval 128
return $ Isabelle.IpAddrNetmask ip netmask
ipv6range :: Parsec String s (Isabelle.Ipt_iprange Word128)
ipv6range = do
ip1 <- ipv6colonsep
char '-'
ip2 <- ipv6colonsep
return $ Isabelle.IpAddrRange ip1 ip2
protocol :: Parsec String s Isabelle.Protocol
protocol = choice (map make ps)
where make (s, p) = try (string s) $> Isabelle.Proto p
ps = [ ("tcp", Isabelle.tcp)
, ("udp", Isabelle.udp)
, ("icmpv6", Isabelle.iPv6ICMP)
, ("ipv6-icmp", Isabelle.iPv6ICMP)
, ("icmp", Isabelle.icmp)
, ("esp", Isabelle.esp)
, ("ah", Isabelle.ah)
, ("gre", Isabelle.gre)
]
iface :: Parsec String s Isabelle.Iface
iface = Isabelle.Iface <$> many1 (oneOf $ ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ ['+', '*', '.', '-'])
tcpFlag :: Parsec String s Isabelle.Tcp_flag
tcpFlag = choice $ map make ps
where make (s, p) = string s $> p
ps = [ ("SYN", Isabelle.TCP_SYN)
, ("ACK", Isabelle.TCP_ACK)
, ("FIN", Isabelle.TCP_FIN)
, ("PSH", Isabelle.TCP_PSH)
, ("URG", Isabelle.TCP_URG)
, ("RST", Isabelle.TCP_RST)
]
|
diekmann/Iptables_Semantics
|
haskell_tool/lib/Network/IPTables/ParserHelper.hs
|
bsd-2-clause
| 4,161 | 0 | 14 | 1,145 | 1,396 | 725 | 671 | 100 | 3 |
{-
- Origin:
- Constraint Programming in Haskell
- http://overtond.blogspot.com/2008/07/pre.html
- author: David Overton, Melbourne Australia
-
- Modifications:
- Monadic Constraint Programming
- http://www.cs.kuleuven.be/~toms/Haskell/
- Tom Schrijvers
-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Control.CP.FD.OvertonFD.OvertonFD (
OvertonFD,
fd_objective,
fd_domain,
FDVar,
OConstraint(..),
lookup,
) where
import Prelude hiding (lookup)
import Data.Maybe (fromJust,isJust)
import Control.Monad.State.Lazy
import Control.Monad.Trans
import qualified Data.Map as Map
import Data.Map ((!), Map)
import Control.Monad (liftM,(<=<))
import Control.CP.FD.OvertonFD.Domain as Domain
import Control.CP.FD.FD hiding ((!))
import Control.CP.Solver
import Control.CP.SearchTree
import Control.CP.EnumTerm
import Control.CP.Debug
--------------------------------------------------------------------------------
-- Solver instance -------------------------------------------------------------
--------------------------------------------------------------------------------
data OConstraint =
OHasValue FDVar Int
| OSame FDVar FDVar
| ODiff FDVar FDVar
| OLess FDVar FDVar
| OLessEq FDVar FDVar
| OAdd FDVar FDVar FDVar
| OSub FDVar FDVar FDVar
| OMult FDVar FDVar FDVar
| OAbs FDVar FDVar
deriving (Show,Eq)
instance Solver OvertonFD where
type Constraint OvertonFD = OConstraint
type Label OvertonFD = FDState
add c = debug ("addOverton("++(show c)++")") $ addOverton c
run p = debug ("runOverton") $ runOverton p
mark = get
goto = put
instance Term OvertonFD FDVar where
newvar = newVar ()
type Help OvertonFD FDVar = ()
help _ _ = ()
instance EnumTerm OvertonFD FDVar where
type TermBaseType OvertonFD FDVar = Int
getDomain = fd_domain
setValue var val = return [var `OHasValue` val]
--------------------------------------------------------------------------------
-- Constraints -----------------------------------------------------------------
--------------------------------------------------------------------------------
addOverton (OHasValue v i) = v `hasValue` i
addOverton (OSame a b) = a `same` b
addOverton (ODiff a b) = a `different` b
addOverton (OLess a b) = a .<. b
addOverton (OLessEq a b) = a .<=. b
addOverton (OAdd a b c) = addSum a b c
addOverton (OSub a b c) = addSub a b c
addOverton (OMult a b c) = addMult a b c
addOverton (OAbs a b) = addAbs a b
fd_domain :: FDVar -> OvertonFD [Int]
fd_domain v = do d <- lookup v
return $ elems d
fd_objective :: OvertonFD FDVar
fd_objective =
do s <- get
return $ objective s
--------------------------------------------------------------------------------
-- The FD monad
newtype OvertonFD a = OvertonFD { unFD :: State FDState a }
deriving (Monad, MonadState FDState)
-- FD variables
newtype FDVar = FDVar { unFDVar :: Int } deriving (Ord, Eq, Show)
type VarSupply = FDVar
data VarInfo = VarInfo
{ delayedConstraints :: OvertonFD Bool, domain :: Domain }
instance Show VarInfo where
show x = show $ domain x
type VarMap = Map FDVar VarInfo
data FDState = FDState
{ varSupply :: VarSupply, varMap :: VarMap, objective :: FDVar }
deriving Show
instance Eq FDState where
s1 == s2 = f s1 == f s2
where f s = head $ elems $ domain $ varMap s ! (objective s)
instance Ord FDState where
compare s1 s2 = compare (f s1) (f s2)
where f s = head $ elems $ domain $ varMap s ! (objective s)
-- TOM: inconsistency is not observable within the OvertonFD monad
consistentFD :: OvertonFD Bool
consistentFD = return True
-- Run the FD monad and produce a lazy list of possible solutions.
runOverton :: OvertonFD a -> a
runOverton fd =
let j = evalState (unFD fd) initState
in j
initState :: FDState
initState = FDState { varSupply = FDVar 0, varMap = Map.empty, objective = FDVar 0 }
-- Get a new FDVar
newVar :: ToDomain a => a -> OvertonFD FDVar
newVar d = do
s <- get
let v = varSupply s
put $ s { varSupply = FDVar (unFDVar v + 1) }
modify $ \s ->
let vm = varMap s
vi = VarInfo {
delayedConstraints = return True,
domain = toDomain d}
in
s { varMap = Map.insert v vi vm }
return v
newVars :: ToDomain a => Int -> a -> OvertonFD [FDVar]
newVars n d = replicateM n (newVar d)
-- Lookup the current domain of a variable.
lookup :: FDVar -> OvertonFD Domain
lookup x = do
s <- get
return . domain $ varMap s ! x
-- Update the domain of a variable and fire all delayed constraints
-- associated with that variable.
update :: FDVar -> Domain -> OvertonFD Bool
update x i = do
debug (show x ++ " <- " ++ show i) (return ())
s <- get
let vm = varMap s
let vi = vm ! x
debug ("where old domain = " ++ show (domain vi)) (return ())
put $ s { varMap = Map.insert x (vi { domain = i}) vm }
delayedConstraints vi
-- Add a new constraint for a variable to the constraint store.
addConstraint :: FDVar -> OvertonFD Bool -> OvertonFD ()
addConstraint x constraint = do
s <- get
let vm = varMap s
let vi = vm ! x
let cs = delayedConstraints vi
put $ s { varMap =
Map.insert x (vi { delayedConstraints = do b <- cs
if b then constraint
else return False}) vm }
-- Useful helper function for adding binary constraints between FDVars.
type BinaryConstraint = FDVar -> FDVar -> OvertonFD Bool
addBinaryConstraint :: BinaryConstraint -> BinaryConstraint
addBinaryConstraint f x y = do
let constraint = f x y
b <- constraint
when b $ (do addConstraint x constraint
addConstraint y constraint)
return b
-- Constrain a variable to a particular value.
hasValue :: FDVar -> Int -> OvertonFD Bool
var `hasValue` val = do
vals <- lookup var
if val `member` vals
then do let i = singleton val
if (i /= vals)
then update var i
else return True
else return False
-- Constrain two variables to have the same value.
same :: FDVar -> FDVar -> OvertonFD Bool
same = addBinaryConstraint $ \x y -> do
debug "inside same" $ return ()
xv <- lookup x
yv <- lookup y
debug (show xv ++ " same " ++ show yv) $ return ()
let i = xv `intersection` yv
if not $ Domain.null i
then whenwhen (i /= xv) (i /= yv) (update x i) (update y i)
else return False
whenwhen c1 c2 a1 a2 =
if c1
then do b1 <- a1
if b1
then if c2
then a2
else return True
else return False
else if c2
then a2
else return True
-- Constrain two variables to have different values.
different :: FDVar -> FDVar -> OvertonFD Bool
different = addBinaryConstraint $ \x y -> do
xv <- lookup x
yv <- lookup y
if not (isSingleton xv) || not (isSingleton yv) || xv /= yv
then whenwhen (isSingleton xv && xv `isSubsetOf` yv)
(isSingleton yv && yv `isSubsetOf` xv)
(update y (yv `difference` xv))
(update x (xv `difference` yv))
else return False
-- Constrain one variable to have a value less than the value of another
-- variable.
infix 4 .<.
(.<.) :: FDVar -> FDVar -> OvertonFD Bool
(.<.) = addBinaryConstraint $ \x y -> do
xv <- lookup x
yv <- lookup y
let xv' = filterLessThan (findMax yv) xv
let yv' = filterGreaterThan (findMin xv) yv
if not $ Domain.null xv'
then if not $ Domain.null yv'
then whenwhen (xv /= xv') (yv /= yv') (update x xv') (update y yv')
else return False
else return False
-- Constrain one variable to have a value less than or equal to the value of another
-- variable.
infix 4 .<=.
(.<=.) :: FDVar -> FDVar -> OvertonFD Bool
(.<=.) = addBinaryConstraint $ \x y -> do
xv <- lookup x
yv <- lookup y
let xv' = filterLessThan (1 + findMax yv) xv
let yv' = filterGreaterThan ((findMin xv) - 1) yv
if not $ Domain.null xv'
then if not $ Domain.null yv'
then whenwhen (xv /= xv') (yv /= yv') (update x xv') (update y yv')
else return False
else return False
{-
-- Get all solutions for a constraint without actually updating the
-- constraint store.
solutions :: OvertonFD s a -> OvertonFD s [a]
solutions constraint = do
s <- get
return $ evalStateT (unFD constraint) s
-- Label variables using a depth-first left-to-right search.
labelling :: [FDVar s] -> OvertonFD s [Int]
labelling = mapM label where
label var = do
vals <- lookup var
val <- OvertonFD . lift $ elems vals
var `hasValue` val
return val
-}
dump :: [FDVar] -> OvertonFD [Domain]
dump = mapM lookup
-- Add constraint (z = x `op` y) for var z
addArithmeticConstraint ::
(Domain -> Domain -> Domain) ->
(Domain -> Domain -> Domain) ->
(Domain -> Domain -> Domain) ->
FDVar -> FDVar -> FDVar -> OvertonFD Bool
addArithmeticConstraint getZDomain getXDomain getYDomain x y z = do
xv <- lookup x
yv <- lookup y
let constraint z x y getDomain = do
xv <- lookup x
yv <- lookup y
zv <- lookup z
let znew = debug "binaryArith:intersection" $ (debug "binaryArith:zv" $ zv) `intersection` (debug "binaryArith:getDomain" $ getDomain xv yv)
debug ("binaryArith:" ++ show z ++ " before: " ++ show zv ++ show "; after: " ++ show znew) (return ())
if debug "binaryArith:null?" $ not $ Domain.null (debug "binaryArith:null?:znew" $ znew)
then if (znew /= zv)
then debug ("binaryArith:update") $ update z znew
else return True
else return False
let zConstraint = debug "binaryArith: zConstraint" $ constraint z x y getZDomain
xConstraint = debug "binaryArith: xConstraint" $ constraint x z y getXDomain
yConstraint = debug "binaryArith: yConstraint" $ constraint y z x getYDomain
debug ("addBinaryArith: z x") (return ())
addConstraint z xConstraint
debug ("addBinaryArith: z y") (return ())
addConstraint z yConstraint
debug ("addBinaryArith: x z") (return ())
addConstraint x zConstraint
debug ("addBinaryArith: x y") (return ())
addConstraint x yConstraint
debug ("addBinaryArith: y z") (return ())
addConstraint y zConstraint
debug ("addBinaryArith: y x") (return ())
addConstraint y xConstraint
debug ("addBinaryArith: done") (return ())
return True
-- Add constraint (z = op x) for var z
addUnaryArithmeticConstraint :: (Domain -> Domain) -> (Domain -> Domain) -> FDVar -> FDVar -> OvertonFD Bool
addUnaryArithmeticConstraint getZDomain getXDomain x z = do
xv <- lookup x
let constraint z x getDomain = do
xv <- lookup x
zv <- lookup z
let znew = zv `intersection` (getDomain xv)
debug ("unaryArith:" ++ show z ++ " before: " ++ show zv ++ show "; after: " ++ show znew) (return ())
if not $ Domain.null znew
then if (znew /= zv)
then update z znew
else return True
else return False
let zConstraint = constraint z x getZDomain
xConstraint = constraint x z getXDomain
addConstraint z xConstraint
addConstraint x zConstraint
return True
addSum = addArithmeticConstraint getDomainPlus getDomainMinus getDomainMinus
addSub = addArithmeticConstraint getDomainMinus getDomainPlus (flip getDomainMinus)
addMult = addArithmeticConstraint getDomainMult getDomainDiv getDomainDiv
addAbs = addUnaryArithmeticConstraint absDomain (\z -> mapDomain z (\i -> [i,-i]))
getDomainPlus :: Domain -> Domain -> Domain
getDomainPlus xs ys = toDomain (zl, zh) where
zl = findMin xs + findMin ys
zh = findMax xs + findMax ys
getDomainMinus :: Domain -> Domain -> Domain
getDomainMinus xs ys = toDomain (zl, zh) where
zl = findMin xs - findMax ys
zh = findMax xs - findMin ys
getDomainMult :: Domain -> Domain -> Domain
getDomainMult xs ys = (\d -> debug ("multDomain" ++ show d ++ "=" ++ show xs ++ "*" ++ show ys ) d) $ toDomain (zl, zh) where
zl = minimum products
zh = maximum products
products = [x * y |
x <- [findMin xs, findMax xs],
y <- [findMin ys, findMax ys]]
getDomainDiv :: Domain -> Domain -> Domain
getDomainDiv xs ys = toDomain (zl, zh) where
zl = minimum quotientsl
zh = maximum quotientsh
quotientsl = [if y /= 0 then x `div` y else minBound |
x <- [findMin xs, findMax xs],
y <- [findMin ys, findMax ys]]
quotientsh = [if y /= 0 then x `div` y else maxBound |
x <- [findMin xs, findMax xs],
y <- [findMin ys, findMax ys]]
|
FranklinChen/monadiccp
|
Control/CP/FD/OvertonFD/OvertonFD.hs
|
bsd-3-clause
| 12,984 | 207 | 15 | 3,417 | 3,874 | 2,039 | 1,835 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : Plugins.Monitors.CoreTemp
-- Copyright : (c) Juraj Hercek
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Juraj Hercek <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- A core temperature monitor for Xmobar
--
-----------------------------------------------------------------------------
module Plugins.Monitors.CoreTemp where
import Plugins.Monitors.Common
import Plugins.Monitors.CoreCommon
import Data.Char (isDigit)
-- |
-- Core temperature default configuration. Default template contains only one
-- core temperature, user should specify custom template in order to get more
-- core frequencies.
coreTempConfig :: IO MConfig
coreTempConfig = mkMConfig
"Temp: <core0>C" -- template
(zipWith (++) (repeat "core") (map show [0 :: Int ..])) -- available
-- replacements
-- |
-- Function retrieves monitor string holding the core temperature
-- (or temperatures)
runCoreTemp :: [String] -> Monitor String
runCoreTemp _ = let path = ["/sys/bus/platform/devices/coretemp.",
"/temp",
"_input"]
lbl = Just ("_label", read . (dropWhile (not . isDigit)))
divisor = 1e3 :: Double
failureMessage = "CoreTemp: N/A"
in checkedDataRetrieval failureMessage path lbl (/divisor) show
|
tsiliakis/xmobar
|
src/Plugins/Monitors/CoreTemp.hs
|
bsd-3-clause
| 1,541 | 0 | 15 | 399 | 205 | 126 | 79 | 16 | 1 |
{-# LANGUAGE PatternGuards #-}
-- | This module does command line completion
module System.Console.CmdArgs.Explicit.Complete(
Complete(..), complete,
completeBash, completeZsh
) where
import System.Console.CmdArgs.Explicit.Type
import Control.Monad
import Data.List
import Data.Maybe
-- | How to complete a command line option.
-- The 'Show' instance is suitable for parsing from shell scripts.
data Complete
= CompleteValue String -- ^ Complete to a particular value
| CompleteFile String FilePath -- ^ Complete to a prefix, and a file
| CompleteDir String FilePath -- ^ Complete to a prefix, and a directory
deriving (Eq,Ord)
instance Show Complete where
show (CompleteValue a) = "VALUE " ++ a
show (CompleteFile a b) = "FILE " ++ a ++ " " ++ b
show (CompleteDir a b) = "DIR " ++ a ++ " " ++ b
showList xs = showString $ unlines (map show xs)
prepend :: String -> Complete -> Complete
prepend a (CompleteFile b c) = CompleteFile (a++b) c
prepend a (CompleteDir b c) = CompleteDir (a++b) c
prepend a (CompleteValue b) = CompleteValue (a++b)
-- | Given a current state, return the set of commands you could type now, in preference order.
complete
:: Mode a -- ^ Mode specifying which arguments are allowed
-> [String] -- ^ Arguments the user has already typed
-> (Int,Int) -- ^ 0-based index of the argument they are currently on, and the position in that argument
-> [Complete]
-- Roll forward looking at modes, and if you match a mode, enter it
-- If the person just before is a flag without arg, look at how you can complete that arg
-- If your prefix is a complete flag look how you can complete that flag
-- If your prefix looks like a flag, look for legitimate flags
-- Otherwise give a file/dir if they are arguments to this mode, and all flags
-- If you haven't seen any args/flags then also autocomplete to any child modes
complete mode_ args_ (i,_) = nub $ followArgs mode args now
where
(seen,next) = splitAt i args_
now = head $ next ++ [""]
(mode,args) = followModes mode_ seen
-- | Given a mode and some arguments, try and drill down into the mode
followModes :: Mode a -> [String] -> (Mode a, [String])
followModes m (x:xs) | Just m2 <- pickBy modeNames x $ modeModes m = followModes m2 xs
followModes m xs = (m,xs)
pickBy :: (a -> [String]) -> String -> [a] -> Maybe a
pickBy f name xs = find (\x -> name `elem` f x) xs `mplus`
find (\x -> any (name `isPrefixOf`) (f x)) xs
-- | Follow args deals with all seen arguments, then calls on to deal with the next one
followArgs :: Mode a -> [String] -> (String -> [Complete])
followArgs m = first
where
first [] = expectArgFlagMode (modeModes m) (argsPick 0) (modeFlags m)
first xs = norm 0 xs
-- i is the number of arguments that have gone past
norm i [] = expectArgFlag (argsPick i) (modeFlags m)
norm i ("--":xs) = expectArg $ argsPick (i + length xs)
norm i (('-':'-':x):xs) | null b, flagInfo flg == FlagReq = val i flg xs
| otherwise = norm i xs
where (a,b) = break (== '=') x
flg = getFlag a
norm i (('-':x:y):xs) = case flagInfo flg of
FlagReq | null y -> val i flg xs
| otherwise -> norm i xs
FlagOpt{} -> norm i xs
_ | "=" `isPrefixOf` y -> norm i xs
| null y -> norm i xs
| otherwise -> norm i (('-':y):xs)
where flg = getFlag [x]
norm i (x:xs) = norm (i+1) xs
val i flg [] = expectVal flg
val i flg (x:xs) = norm i xs
argsPick i = let (lst,end) = modeArgs m in if i < length lst then Just $ lst !! i else end
-- if you can't find the flag, pick one that is FlagNone (has all the right fallback)
getFlag x = fromMaybe (flagNone [] id "") $ pickBy flagNames x $ modeFlags m
expectArgFlagMode :: [Mode a] -> Maybe (Arg a) -> [Flag a] -> String -> [Complete]
expectArgFlagMode mode arg flag x
| "-" `isPrefixOf` x = expectFlag flag x ++ [CompleteValue "-" | x == "-", isJust arg]
| otherwise = expectMode mode x ++ expectArg arg x ++ expectFlag flag x
expectArgFlag :: Maybe (Arg a) -> [Flag a] -> String -> [Complete]
expectArgFlag arg flag x
| "-" `isPrefixOf` x = expectFlag flag x ++ [CompleteValue "-" | x == "-", isJust arg]
| otherwise = expectArg arg x ++ expectFlag flag x
expectMode :: [Mode a] -> String -> [Complete]
expectMode mode = expectStrings (map modeNames mode)
expectArg :: Maybe (Arg a) -> String -> [Complete]
expectArg Nothing x = []
expectArg (Just arg) x = expectFlagHelp (argType arg) x
expectFlag :: [Flag a] -> String -> [Complete]
expectFlag flag x
| (a,_:b) <- break (== '=') x = case pickBy (map f . flagNames) a flag of
Nothing -> []
Just flg -> map (prepend (a ++ "=")) $ expectVal flg b
| otherwise = expectStrings (map (map f . flagNames) flag) x
where f x = "-" ++ ['-' | length x > 1] ++ x
expectVal :: Flag a -> String -> [Complete]
expectVal flg = expectFlagHelp (flagType flg)
expectStrings :: [[String]] -> String -> [Complete]
expectStrings xs x = map CompleteValue $ concatMap (take 1 . filter (x `isPrefixOf`)) xs
expectFlagHelp :: FlagHelp -> String -> [Complete]
expectFlagHelp typ x = case typ of
"FILE" -> [CompleteFile "" x]
"DIR" -> [CompleteDir "" x]
"FILE/DIR" -> [CompleteFile "" x, CompleteDir "" x]
"DIR/FILE" -> [CompleteDir "" x, CompleteFile "" x]
'[':s | "]" `isSuffixOf` s -> expectFlagHelp (init s) x
_ -> []
---------------------------------------------------------------------
-- BASH SCRIPT
completeBash :: String -> [String]
completeBash prog =
["# Completion for " ++ prog
,"# Generated by CmdArgs: http://community.haskell.org/~ndm/cmdargs/"
,"_" ++ prog ++ "()"
,"{"
," # local CMDARGS_DEBUG=1 # uncomment to debug this script"
,""
," COMPREPLY=()"
," function add { COMPREPLY[((${#COMPREPLY[@]} + 1))]=$1 ; }"
," IFS=$'\\n\\r'"
,""
," export CMDARGS_COMPLETE=$((${COMP_CWORD} - 1))"
," result=`" ++ prog ++ " ${COMP_WORDS[@]:1}`"
,""
," if [ -n $CMDARGS_DEBUG ]; then"
," echo Call \\(${COMP_WORDS[@]:1}, $CMDARGS_COMPLETE\\) > cmdargs.tmp"
," echo $result >> cmdargs.tmp"
," fi"
," unset CMDARGS_COMPLETE"
," unset CMDARGS_COMPLETE_POS"
,""
," for x in $result ; do"
," case $x in"
," VALUE\\ *)"
," add ${x:6}"
," ;;"
," FILE\\ *)"
," local prefix=`expr match \"${x:5}\" '\\([^ ]*\\)'`"
," local match=`expr match \"${x:5}\" '[^ ]* \\(.*\\)'`"
," for x in `compgen -f -- \"$match\"`; do"
," add $prefix$x"
," done"
," ;;"
," DIR\\ *)"
," local prefix=`expr match \"${x:4}\" '\\([^ ]*\\)'`"
," local match=`expr match \"${x:4}\" '[^ ]* \\(.*\\)'`"
," for x in `compgen -d -- \"$match\"`; do"
," add $prefix$x"
," done"
," ;;"
," esac"
," done"
," unset IFS"
,""
," if [ -n $CMDARGS_DEBUG ]; then"
," echo echo COMPREPLY: ${#COMPREPLY[@]} = ${COMPREPLY[@]} >> cmdargs.tmp"
," fi"
,"}"
,"complete -o bashdefault -F _" ++ prog ++ " " ++ prog
]
---------------------------------------------------------------------
-- ZSH SCRIPT
completeZsh :: String -> [String]
completeZsh _ = ["echo TODO: help add Zsh completions to cmdargs programs"]
|
copland/cmdargs
|
System/Console/CmdArgs/Explicit/Complete.hs
|
bsd-3-clause
| 7,783 | 0 | 15 | 2,213 | 2,200 | 1,151 | 1,049 | 144 | 10 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
{-# LANGUAGE CPP #-}
module TcValidity (
Rank, UserTypeCtxt(..), checkValidType, checkValidMonoType,
expectedKindInCtxt,
checkValidTheta, checkValidFamPats,
checkValidInstance, validDerivPred,
checkInstTermination,
ClsInfo, checkValidCoAxiom, checkValidCoAxBranch,
checkValidTyFamEqn,
checkConsistentFamInst,
arityErr, badATErr
) where
#include "HsVersions.h"
-- friends:
import TcUnify ( tcSubType_NC )
import TcSimplify ( simplifyAmbiguityCheck )
import TypeRep
import TcType
import TcMType
import TysWiredIn ( coercibleClass, eqTyCon )
import PrelNames
import Type
import Unify( tcMatchTyX )
import Kind
import CoAxiom
import Class
import TyCon
-- others:
import HsSyn -- HsType
import TcRnMonad -- TcType, amongst others
import FunDeps
import FamInstEnv ( isDominatedBy, injectiveBranches,
InjectivityCheckResult(..) )
import FamInst ( makeInjectivityErrors )
import Name
import VarEnv
import VarSet
import ErrUtils
import DynFlags
import Util
import ListSetOps
import SrcLoc
import Outputable
import FastString
import Control.Monad
import Data.Maybe
import Data.List ( (\\) )
{-
************************************************************************
* *
Checking for ambiguity
* *
************************************************************************
Note [The ambiguity check for type signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
checkAmbiguity is a check on *user-supplied type signatures*. It is
*purely* there to report functions that cannot possibly be called. So for
example we want to reject:
f :: C a => Int
The idea is there can be no legal calls to 'f' because every call will
give rise to an ambiguous constraint. We could soundly omit the
ambiguity check on type signatures entirely, at the expense of
delaying ambiguity errors to call sites. Indeed, the flag
-XAllowAmbiguousTypes switches off the ambiguity check.
What about things like this:
class D a b | a -> b where ..
h :: D Int b => Int
The Int may well fix 'b' at the call site, so that signature should
not be rejected. Moreover, using *visible* fundeps is too
conservative. Consider
class X a b where ...
class D a b | a -> b where ...
instance D a b => X [a] b where...
h :: X a b => a -> a
Here h's type looks ambiguous in 'b', but here's a legal call:
...(h [True])...
That gives rise to a (X [Bool] beta) constraint, and using the
instance means we need (D Bool beta) and that fixes 'beta' via D's
fundep!
Behind all these special cases there is a simple guiding principle.
Consider
f :: <type>
f = ...blah...
g :: <type>
g = f
You would think that the definition of g would surely typecheck!
After all f has exactly the same type, and g=f. But in fact f's type
is instantiated and the instantiated constraints are solved against
the originals, so in the case an ambiguous type it won't work.
Consider our earlier example f :: C a => Int. Then in g's definition,
we'll instantiate to (C alpha) and try to deduce (C alpha) from (C a),
and fail.
So in fact we use this as our *definition* of ambiguity. We use a
very similar test for *inferred* types, to ensure that they are
unambiguous. See Note [Impedence matching] in TcBinds.
This test is very conveniently implemented by calling
tcSubType <type> <type>
This neatly takes account of the functional dependecy stuff above,
and implicit parameter (see Note [Implicit parameters and ambiguity]).
And this is what checkAmbiguity does.
What about this, though?
g :: C [a] => Int
Is every call to 'g' ambiguous? After all, we might have
intance C [a] where ...
at the call site. So maybe that type is ok! Indeed even f's
quintessentially ambiguous type might, just possibly be callable:
with -XFlexibleInstances we could have
instance C a where ...
and now a call could be legal after all! Well, we'll reject this
unless the instance is available *here*.
Note [When to call checkAmbiguity]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We call checkAmbiguity
(a) on user-specified type signatures
(b) in checkValidType
Conncerning (b), you might wonder about nested foralls. What about
f :: forall b. (forall a. Eq a => b) -> b
The nested forall is ambiguous. Originally we called checkAmbiguity
in the forall case of check_type, but that had two bad consequences:
* We got two error messages about (Eq b) in a nested forall like this:
g :: forall a. Eq a => forall b. Eq b => a -> a
* If we try to check for ambiguity of an nested forall like
(forall a. Eq a => b), the implication constraint doesn't bind
all the skolems, which results in "No skolem info" in error
messages (see Trac #10432).
To avoid this, we call checkAmbiguity once, at the top, in checkValidType.
(I'm still a bit worried about unbound skolems when the type mentions
in-scope type variables.)
In fact, because of the co/contra-variance implemented in tcSubType,
this *does* catch function f above. too.
Concerning (a) the ambiguity check is only used for *user* types, not
for types coming from inteface files. The latter can legitimately
have ambiguous types. Example
class S a where s :: a -> (Int,Int)
instance S Char where s _ = (1,1)
f:: S a => [a] -> Int -> (Int,Int)
f (_::[a]) x = (a*x,b)
where (a,b) = s (undefined::a)
Here the worker for f gets the type
fw :: forall a. S a => Int -> (# Int, Int #)
Note [Implicit parameters and ambiguity]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Only a *class* predicate can give rise to ambiguity
An *implicit parameter* cannot. For example:
foo :: (?x :: [a]) => Int
foo = length ?x
is fine. The call site will supply a particular 'x'
Furthermore, the type variables fixed by an implicit parameter
propagate to the others. E.g.
foo :: (Show a, ?x::[a]) => Int
foo = show (?x++?x)
The type of foo looks ambiguous. But it isn't, because at a call site
we might have
let ?x = 5::Int in foo
and all is well. In effect, implicit parameters are, well, parameters,
so we can take their type variables into account as part of the
"tau-tvs" stuff. This is done in the function 'FunDeps.grow'.
-}
checkAmbiguity :: UserTypeCtxt -> Type -> TcM ()
checkAmbiguity ctxt ty
| GhciCtxt <- ctxt -- Allow ambiguous types in GHCi's :kind command
= return () -- E.g. type family T a :: * -- T :: forall k. k -> *
-- Then :k T should work in GHCi, not complain that
-- (T k) is ambiguous!
| InfSigCtxt {} <- ctxt -- See Note [Validity of inferred types] in TcBinds
= return ()
| otherwise
= do { traceTc "Ambiguity check for" (ppr ty)
; let free_tkvs = varSetElemsKvsFirst (closeOverKinds (tyVarsOfType ty))
; (subst, _tvs) <- tcInstSkolTyVars free_tkvs
; let ty' = substTy subst ty
-- The type might have free TyVars, esp when the ambiguity check
-- happens during a call to checkValidType,
-- so we skolemise them as TcTyVars.
-- Tiresome; but the type inference engine expects TcTyVars
-- NB: The free tyvar might be (a::k), so k is also free
-- and we must skolemise it as well. Hence closeOverKinds.
-- (Trac #9222)
-- Solve the constraints eagerly because an ambiguous type
-- can cause a cascade of further errors. Since the free
-- tyvars are skolemised, we can safely use tcSimplifyTop
; (_wrap, wanted) <- addErrCtxtM (mk_msg ty') $
captureConstraints $
tcSubType_NC ctxt ty' ty'
; whenNoErrs $ -- only run the simplifier if we have a clean
-- environment. Otherwise we might trip.
-- example: indexed-types/should_fail/BadSock
-- fails in DEBUG mode without this
simplifyAmbiguityCheck ty wanted
; traceTc "Done ambiguity check for" (ppr ty) }
where
mk_msg ty tidy_env
= do { allow_ambiguous <- xoptM Opt_AllowAmbiguousTypes
; (tidy_env', tidy_ty) <- zonkTidyTcType tidy_env ty
; return (tidy_env', mk_msg tidy_ty $$ ppWhen (not allow_ambiguous) ambig_msg) }
where
mk_msg ty = pprSigCtxt ctxt (ptext (sLit "the ambiguity check for")) (ppr ty)
ambig_msg = ptext (sLit "To defer the ambiguity check to use sites, enable AllowAmbiguousTypes")
{-
************************************************************************
* *
Checking validity of a user-defined type
* *
************************************************************************
When dealing with a user-written type, we first translate it from an HsType
to a Type, performing kind checking, and then check various things that should
be true about it. We don't want to perform these checks at the same time
as the initial translation because (a) they are unnecessary for interface-file
types and (b) when checking a mutually recursive group of type and class decls,
we can't "look" at the tycons/classes yet. Also, the checks are rather
diverse, and used to really mess up the other code.
One thing we check for is 'rank'.
Rank 0: monotypes (no foralls)
Rank 1: foralls at the front only, Rank 0 inside
Rank 2: foralls at the front, Rank 1 on left of fn arrow,
basic ::= tyvar | T basic ... basic
r2 ::= forall tvs. cxt => r2a
r2a ::= r1 -> r2a | basic
r1 ::= forall tvs. cxt => r0
r0 ::= r0 -> r0 | basic
Another thing is to check that type synonyms are saturated.
This might not necessarily show up in kind checking.
type A i = i
data T k = MkT (k Int)
f :: T A -- BAD!
-}
checkValidType :: UserTypeCtxt -> Type -> TcM ()
-- Checks that the type is valid for the given context
-- Not used for instance decls; checkValidInstance instead
checkValidType ctxt ty
= do { traceTc "checkValidType" (ppr ty <+> text "::" <+> ppr (typeKind ty))
; rankn_flag <- xoptM Opt_RankNTypes
; let gen_rank :: Rank -> Rank
gen_rank r | rankn_flag = ArbitraryRank
| otherwise = r
rank1 = gen_rank r1
rank0 = gen_rank r0
r0 = rankZeroMonoType
r1 = LimitedRank True r0
rank
= case ctxt of
DefaultDeclCtxt-> MustBeMonoType
ResSigCtxt -> MustBeMonoType
PatSigCtxt -> rank0
RuleSigCtxt _ -> rank1
TySynCtxt _ -> rank0
ExprSigCtxt -> rank1
FunSigCtxt {} -> rank1
InfSigCtxt _ -> ArbitraryRank -- Inferred type
ConArgCtxt _ -> rank1 -- We are given the type of the entire
-- constructor, hence rank 1
ForSigCtxt _ -> rank1
SpecInstCtxt -> rank1
ThBrackCtxt -> rank1
GhciCtxt -> ArbitraryRank
_ -> panic "checkValidType"
-- Can't happen; not used for *user* sigs
-- Check the internal validity of the type itself
; check_type ctxt rank ty
-- Check that the thing has kind Type, and is lifted if necessary.
-- Do this *after* check_type, because we can't usefully take
-- the kind of an ill-formed type such as (a~Int)
; check_kind ctxt ty
-- Check for ambiguous types. See Note [When to call checkAmbiguity]
-- NB: this will happen even for monotypes, but that should be cheap;
-- and there may be nested foralls for the subtype test to examine
; checkAmbiguity ctxt ty
; traceTc "checkValidType done" (ppr ty <+> text "::" <+> ppr (typeKind ty)) }
checkValidMonoType :: Type -> TcM ()
checkValidMonoType ty = check_mono_type SigmaCtxt MustBeMonoType ty
check_kind :: UserTypeCtxt -> TcType -> TcM ()
-- Check that the type's kind is acceptable for the context
check_kind ctxt ty
| TySynCtxt {} <- ctxt
, returnsConstraintKind actual_kind
= do { ck <- xoptM Opt_ConstraintKinds
; if ck
then when (isConstraintKind actual_kind)
(do { dflags <- getDynFlags
; check_pred_ty dflags ctxt ty })
else addErrTc (constraintSynErr actual_kind) }
| Just k <- expectedKindInCtxt ctxt
= checkTc (tcIsSubKind actual_kind k) (kindErr actual_kind)
| otherwise
= return () -- Any kind will do
where
actual_kind = typeKind ty
-- Depending on the context, we might accept any kind (for instance, in a TH
-- splice), or only certain kinds (like in type signatures).
expectedKindInCtxt :: UserTypeCtxt -> Maybe Kind
expectedKindInCtxt (TySynCtxt _) = Nothing -- Any kind will do
expectedKindInCtxt ThBrackCtxt = Nothing
expectedKindInCtxt GhciCtxt = Nothing
-- The types in a 'default' decl can have varying kinds
-- See Note [Extended defaults]" in TcEnv
expectedKindInCtxt DefaultDeclCtxt = Nothing
expectedKindInCtxt (ForSigCtxt _) = Just liftedTypeKind
expectedKindInCtxt InstDeclCtxt = Just constraintKind
expectedKindInCtxt SpecInstCtxt = Just constraintKind
expectedKindInCtxt _ = Just openTypeKind
{-
Note [Higher rank types]
~~~~~~~~~~~~~~~~~~~~~~~~
Technically
Int -> forall a. a->a
is still a rank-1 type, but it's not Haskell 98 (Trac #5957). So the
validity checker allow a forall after an arrow only if we allow it
before -- that is, with Rank2Types or RankNTypes
-}
data Rank = ArbitraryRank -- Any rank ok
| LimitedRank -- Note [Higher rank types]
Bool -- Forall ok at top
Rank -- Use for function arguments
| MonoType SDoc -- Monotype, with a suggestion of how it could be a polytype
| MustBeMonoType -- Monotype regardless of flags
rankZeroMonoType, tyConArgMonoType, synArgMonoType :: Rank
rankZeroMonoType = MonoType (ptext (sLit "Perhaps you intended to use RankNTypes or Rank2Types"))
tyConArgMonoType = MonoType (ptext (sLit "GHC doesn't yet support impredicative polymorphism"))
synArgMonoType = MonoType (ptext (sLit "Perhaps you intended to use LiberalTypeSynonyms"))
funArgResRank :: Rank -> (Rank, Rank) -- Function argument and result
funArgResRank (LimitedRank _ arg_rank) = (arg_rank, LimitedRank (forAllAllowed arg_rank) arg_rank)
funArgResRank other_rank = (other_rank, other_rank)
forAllAllowed :: Rank -> Bool
forAllAllowed ArbitraryRank = True
forAllAllowed (LimitedRank forall_ok _) = forall_ok
forAllAllowed _ = False
----------------------------------------
check_mono_type :: UserTypeCtxt -> Rank
-> KindOrType -> TcM () -- No foralls anywhere
-- No unlifted types of any kind
check_mono_type ctxt rank ty
| isKind ty = return () -- IA0_NOTE: Do we need to check kinds?
| otherwise
= do { check_type ctxt rank ty
; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) }
check_type :: UserTypeCtxt -> Rank -> Type -> TcM ()
-- The args say what the *type context* requires, independent
-- of *flag* settings. You test the flag settings at usage sites.
--
-- Rank is allowed rank for function args
-- Rank 0 means no for-alls anywhere
check_type ctxt rank ty
| not (null tvs && null theta)
= do { checkTc (forAllAllowed rank) (forAllTyErr rank ty)
-- Reject e.g. (Maybe (?x::Int => Int)),
-- with a decent error message
; check_valid_theta SigmaCtxt theta
-- Allow type T = ?x::Int => Int -> Int
-- but not type T = ?x::Int
; check_type ctxt rank tau } -- Allow foralls to right of arrow
where
(tvs, theta, tau) = tcSplitSigmaTy ty
check_type _ _ (TyVarTy _) = return ()
check_type ctxt rank (FunTy arg_ty res_ty)
= do { check_type ctxt arg_rank arg_ty
; check_type ctxt res_rank res_ty }
where
(arg_rank, res_rank) = funArgResRank rank
check_type ctxt rank (AppTy ty1 ty2)
= do { check_arg_type ctxt rank ty1
; check_arg_type ctxt rank ty2 }
check_type ctxt rank ty@(TyConApp tc tys)
| isTypeSynonymTyCon tc || isTypeFamilyTyCon tc
= check_syn_tc_app ctxt rank ty tc tys
| isUnboxedTupleTyCon tc = check_ubx_tuple ctxt ty tys
| otherwise = mapM_ (check_arg_type ctxt rank) tys
check_type _ _ (LitTy {}) = return ()
check_type _ _ ty = pprPanic "check_type" (ppr ty)
----------------------------------------
check_syn_tc_app :: UserTypeCtxt -> Rank -> KindOrType
-> TyCon -> [KindOrType] -> TcM ()
-- Used for type synonyms and type synonym families,
-- which must be saturated,
-- but not data families, which need not be saturated
check_syn_tc_app ctxt rank ty tc tys
| tc_arity <= length tys -- Saturated
-- Check that the synonym has enough args
-- This applies equally to open and closed synonyms
-- It's OK to have an *over-applied* type synonym
-- data Tree a b = ...
-- type Foo a = Tree [a]
-- f :: Foo a b -> ...
= do { -- See Note [Liberal type synonyms]
; liberal <- xoptM Opt_LiberalTypeSynonyms
; if not liberal || isTypeFamilyTyCon tc then
-- For H98 and synonym families, do check the type args
mapM_ check_arg tys
else -- In the liberal case (only for closed syns), expand then check
case tcView ty of
Just ty' -> check_type ctxt rank ty'
Nothing -> pprPanic "check_tau_type" (ppr ty) }
| GhciCtxt <- ctxt -- Accept under-saturated type synonyms in
-- GHCi :kind commands; see Trac #7586
= mapM_ check_arg tys
| otherwise
= failWithTc (tyConArityErr tc tys)
where
tc_arity = tyConArity tc
check_arg | isTypeFamilyTyCon tc = check_arg_type ctxt rank
| otherwise = check_mono_type ctxt synArgMonoType
----------------------------------------
check_ubx_tuple :: UserTypeCtxt -> KindOrType
-> [KindOrType] -> TcM ()
check_ubx_tuple ctxt ty tys
= do { ub_tuples_allowed <- xoptM Opt_UnboxedTuples
; checkTc ub_tuples_allowed (ubxArgTyErr ty)
; impred <- xoptM Opt_ImpredicativeTypes
; let rank' = if impred then ArbitraryRank else tyConArgMonoType
-- c.f. check_arg_type
-- However, args are allowed to be unlifted, or
-- more unboxed tuples, so can't use check_arg_ty
; mapM_ (check_type ctxt rank') tys }
----------------------------------------
check_arg_type :: UserTypeCtxt -> Rank -> KindOrType -> TcM ()
-- The sort of type that can instantiate a type variable,
-- or be the argument of a type constructor.
-- Not an unboxed tuple, but now *can* be a forall (since impredicativity)
-- Other unboxed types are very occasionally allowed as type
-- arguments depending on the kind of the type constructor
--
-- For example, we want to reject things like:
--
-- instance Ord a => Ord (forall s. T s a)
-- and
-- g :: T s (forall b.b)
--
-- NB: unboxed tuples can have polymorphic or unboxed args.
-- This happens in the workers for functions returning
-- product types with polymorphic components.
-- But not in user code.
-- Anyway, they are dealt with by a special case in check_tau_type
check_arg_type ctxt rank ty
| isKind ty = return () -- IA0_NOTE: Do we need to check a kind?
| otherwise
= do { impred <- xoptM Opt_ImpredicativeTypes
; let rank' = case rank of -- Predictive => must be monotype
MustBeMonoType -> MustBeMonoType -- Monotype, regardless
_other | impred -> ArbitraryRank
| otherwise -> tyConArgMonoType
-- Make sure that MustBeMonoType is propagated,
-- so that we don't suggest -XImpredicativeTypes in
-- (Ord (forall a.a)) => a -> a
-- and so that if it Must be a monotype, we check that it is!
; check_type ctxt rank' ty
; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) }
-- NB the isUnLiftedType test also checks for
-- T State#
-- where there is an illegal partial application of State# (which has
-- kind * -> #); see Note [The kind invariant] in TypeRep
----------------------------------------
forAllTyErr :: Rank -> Type -> SDoc
forAllTyErr rank ty
= vcat [ hang (ptext (sLit "Illegal polymorphic or qualified type:")) 2 (ppr ty)
, suggestion ]
where
suggestion = case rank of
LimitedRank {} -> ptext (sLit "Perhaps you intended to use RankNTypes or Rank2Types")
MonoType d -> d
_ -> Outputable.empty -- Polytype is always illegal
unliftedArgErr, ubxArgTyErr :: Type -> SDoc
unliftedArgErr ty = sep [ptext (sLit "Illegal unlifted type:"), ppr ty]
ubxArgTyErr ty = sep [ptext (sLit "Illegal unboxed tuple type as function argument:"), ppr ty]
kindErr :: Kind -> SDoc
kindErr kind = sep [ptext (sLit "Expecting an ordinary type, but found a type of kind"), ppr kind]
{-
Note [Liberal type synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If -XLiberalTypeSynonyms is on, expand closed type synonyms *before*
doing validity checking. This allows us to instantiate a synonym defn
with a for-all type, or with a partially-applied type synonym.
e.g. type T a b = a
type S m = m ()
f :: S (T Int)
Here, T is partially applied, so it's illegal in H98. But if you
expand S first, then T we get just
f :: Int
which is fine.
IMPORTANT: suppose T is a type synonym. Then we must do validity
checking on an appliation (T ty1 ty2)
*either* before expansion (i.e. check ty1, ty2)
*or* after expansion (i.e. expand T ty1 ty2, and then check)
BUT NOT BOTH
If we do both, we get exponential behaviour!!
data TIACons1 i r c = c i ::: r c
type TIACons2 t x = TIACons1 t (TIACons1 t x)
type TIACons3 t x = TIACons2 t (TIACons1 t x)
type TIACons4 t x = TIACons2 t (TIACons2 t x)
type TIACons7 t x = TIACons4 t (TIACons3 t x)
************************************************************************
* *
\subsection{Checking a theta or source type}
* *
************************************************************************
Note [Implicit parameters in instance decls]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Implicit parameters _only_ allowed in type signatures; not in instance
decls, superclasses etc. The reason for not allowing implicit params in
instances is a bit subtle. If we allowed
instance (?x::Int, Eq a) => Foo [a] where ...
then when we saw
(e :: (?x::Int) => t)
it would be unclear how to discharge all the potential uses of the ?x
in e. For example, a constraint Foo [Int] might come out of e, and
applying the instance decl would show up two uses of ?x. Trac #8912.
-}
checkValidTheta :: UserTypeCtxt -> ThetaType -> TcM ()
checkValidTheta ctxt theta
= addErrCtxt (checkThetaCtxt ctxt theta) (check_valid_theta ctxt theta)
-------------------------
check_valid_theta :: UserTypeCtxt -> [PredType] -> TcM ()
check_valid_theta _ []
= return ()
check_valid_theta ctxt theta
= do { dflags <- getDynFlags
; warnTc (wopt Opt_WarnDuplicateConstraints dflags &&
notNull dups) (dupPredWarn dups)
; traceTc "check_valid_theta" (ppr theta)
; mapM_ (check_pred_ty dflags ctxt) theta }
where
(_,dups) = removeDups cmpPred theta
-------------------------
check_pred_ty :: DynFlags -> UserTypeCtxt -> PredType -> TcM ()
-- Check the validity of a predicate in a signature
-- Do not look through any type synonyms; any constraint kinded
-- type synonyms have been checked at their definition site
-- C.f. Trac #9838
check_pred_ty dflags ctxt pred
= do { checkValidMonoType pred
; check_pred_help False dflags ctxt pred }
check_pred_help :: Bool -- True <=> under a type synonym
-> DynFlags -> UserTypeCtxt
-> PredType -> TcM ()
check_pred_help under_syn dflags ctxt pred
| Just pred' <- coreView pred -- Switch on under_syn when going under a
-- synonym (Trac #9838, yuk)
= check_pred_help True dflags ctxt pred'
| otherwise
= case splitTyConApp_maybe pred of
Just (tc, tys)
| isTupleTyCon tc
-> check_tuple_pred under_syn dflags ctxt pred tys
| Just cls <- tyConClass_maybe tc
-> check_class_pred dflags ctxt pred cls tys -- Includes Coercible
| tc `hasKey` eqTyConKey
-> check_eq_pred dflags pred tys
_ -> check_irred_pred under_syn dflags ctxt pred
check_eq_pred :: DynFlags -> PredType -> [TcType] -> TcM ()
check_eq_pred dflags pred tys
= -- Equational constraints are valid in all contexts if type
-- families are permitted
do { checkTc (length tys == 3)
(tyConArityErr eqTyCon tys)
; checkTc (xopt Opt_TypeFamilies dflags || xopt Opt_GADTs dflags)
(eqPredTyErr pred) }
check_tuple_pred :: Bool -> DynFlags -> UserTypeCtxt -> PredType -> [PredType] -> TcM ()
check_tuple_pred under_syn dflags ctxt pred ts
= do { -- See Note [ConstraintKinds in predicates]
checkTc (under_syn || xopt Opt_ConstraintKinds dflags)
(predTupleErr pred)
; mapM_ (check_pred_help under_syn dflags ctxt) ts }
-- This case will not normally be executed because without
-- -XConstraintKinds tuple types are only kind-checked as *
check_irred_pred :: Bool -> DynFlags -> UserTypeCtxt -> PredType -> TcM ()
check_irred_pred under_syn dflags ctxt pred
-- The predicate looks like (X t1 t2) or (x t1 t2) :: Constraint
-- where X is a type function
= do { -- If it looks like (x t1 t2), require ConstraintKinds
-- see Note [ConstraintKinds in predicates]
-- But (X t1 t2) is always ok because we just require ConstraintKinds
-- at the definition site (Trac #9838)
failIfTc (not under_syn && not (xopt Opt_ConstraintKinds dflags)
&& hasTyVarHead pred)
(predIrredErr pred)
-- Make sure it is OK to have an irred pred in this context
-- See Note [Irreducible predicates in superclasses]
; failIfTc (is_superclass ctxt
&& not (xopt Opt_UndecidableInstances dflags)
&& has_tyfun_head pred)
(predSuperClassErr pred) }
where
is_superclass ctxt = case ctxt of { ClassSCCtxt _ -> True; _ -> False }
has_tyfun_head ty
= case tcSplitTyConApp_maybe ty of
Just (tc, _) -> isTypeFamilyTyCon tc
Nothing -> False
{- Note [ConstraintKinds in predicates]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Don't check for -XConstraintKinds under a type synonym, because that
was done at the type synonym definition site; see Trac #9838
e.g. module A where
type C a = (Eq a, Ix a) -- Needs -XConstraintKinds
module B where
import A
f :: C a => a -> a -- Does *not* need -XConstraintKinds
Note [Irreducible predicates in superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allowing type-family calls in class superclasses is somewhat dangerous
because we can write:
type family Fooish x :: * -> Constraint
type instance Fooish () = Foo
class Fooish () a => Foo a where
This will cause the constraint simplifier to loop because every time we canonicalise a
(Foo a) class constraint we add a (Fooish () a) constraint which will be immediately
solved to add+canonicalise another (Foo a) constraint. -}
-------------------------
check_class_pred :: DynFlags -> UserTypeCtxt -> PredType -> Class -> [TcType] -> TcM ()
check_class_pred dflags ctxt pred cls tys
| isIPClass cls
= do { check_arity
; checkTc (okIPCtxt ctxt) (badIPPred pred) }
| otherwise
= do { check_arity
; checkTc arg_tys_ok (predTyVarErr pred) }
where
check_arity = checkTc (classArity cls == length tys)
(tyConArityErr (classTyCon cls) tys)
flexible_contexts = xopt Opt_FlexibleContexts dflags
undecidable_ok = xopt Opt_UndecidableInstances dflags
arg_tys_ok = case ctxt of
SpecInstCtxt -> True -- {-# SPECIALISE instance Eq (T Int) #-} is fine
InstDeclCtxt -> checkValidClsArgs (flexible_contexts || undecidable_ok) tys
-- Further checks on head and theta
-- in checkInstTermination
_ -> checkValidClsArgs flexible_contexts tys
-------------------------
okIPCtxt :: UserTypeCtxt -> Bool
-- See Note [Implicit parameters in instance decls]
okIPCtxt (FunSigCtxt {}) = True
okIPCtxt (InfSigCtxt {}) = True
okIPCtxt ExprSigCtxt = True
okIPCtxt PatSigCtxt = True
okIPCtxt ResSigCtxt = True
okIPCtxt GenSigCtxt = True
okIPCtxt (ConArgCtxt {}) = True
okIPCtxt (ForSigCtxt {}) = True -- ??
okIPCtxt ThBrackCtxt = True
okIPCtxt GhciCtxt = True
okIPCtxt SigmaCtxt = True
okIPCtxt (DataTyCtxt {}) = True
okIPCtxt (PatSynCtxt {}) = True
okIPCtxt (ClassSCCtxt {}) = False
okIPCtxt (InstDeclCtxt {}) = False
okIPCtxt (SpecInstCtxt {}) = False
okIPCtxt (TySynCtxt {}) = False
okIPCtxt (RuleSigCtxt {}) = False
okIPCtxt DefaultDeclCtxt = False
badIPPred :: PredType -> SDoc
badIPPred pred = ptext (sLit "Illegal implicit parameter") <+> quotes (ppr pred)
{-
Note [Kind polymorphic type classes]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MultiParam check:
class C f where... -- C :: forall k. k -> Constraint
instance C Maybe where...
The dictionary gets type [C * Maybe] even if it's not a MultiParam
type class.
Flexibility check:
class C f where... -- C :: forall k. k -> Constraint
data D a = D a
instance C D where
The dictionary gets type [C * (D *)]. IA0_TODO it should be
generalized actually.
-}
checkThetaCtxt :: UserTypeCtxt -> ThetaType -> SDoc
checkThetaCtxt ctxt theta
= vcat [ptext (sLit "In the context:") <+> pprTheta theta,
ptext (sLit "While checking") <+> pprUserTypeCtxt ctxt ]
eqPredTyErr, predTyVarErr, predTupleErr, predIrredErr, predSuperClassErr :: PredType -> SDoc
eqPredTyErr pred = vcat [ ptext (sLit "Illegal equational constraint") <+> pprType pred
, parens (ptext (sLit "Use GADTs or TypeFamilies to permit this")) ]
predTyVarErr pred = vcat [ hang (ptext (sLit "Non type-variable argument"))
2 (ptext (sLit "in the constraint:") <+> pprType pred)
, parens (ptext (sLit "Use FlexibleContexts to permit this")) ]
predTupleErr pred = hang (ptext (sLit "Illegal tuple constraint:") <+> pprType pred)
2 (parens constraintKindsMsg)
predIrredErr pred = hang (ptext (sLit "Illegal constraint:") <+> pprType pred)
2 (parens constraintKindsMsg)
predSuperClassErr pred
= hang (ptext (sLit "Illegal constraint") <+> quotes (pprType pred)
<+> ptext (sLit "in a superclass context"))
2 (parens undecidableMsg)
constraintSynErr :: Type -> SDoc
constraintSynErr kind = hang (ptext (sLit "Illegal constraint synonym of kind:") <+> quotes (ppr kind))
2 (parens constraintKindsMsg)
dupPredWarn :: [[PredType]] -> SDoc
dupPredWarn dups = ptext (sLit "Duplicate constraint(s):") <+> pprWithCommas pprType (map head dups)
tyConArityErr :: TyCon -> [TcType] -> SDoc
-- For type-constructor arity errors, be careful to report
-- the number of /type/ arguments required and supplied,
-- ignoring the /kind/ arguments, which the user does not see.
-- (e.g. Trac #10516)
tyConArityErr tc tks
= arityErr (tyConFlavour tc) (tyConName tc)
tc_type_arity tc_type_args
where
tvs = tyConTyVars tc
kbs :: [Bool] -- True for a Type arg, false for a Kind arg
kbs = map isTypeVar tvs
-- tc_type_arity = number of *type* args expected
-- tc_type_args = number of *type* args encountered
tc_type_arity = count id kbs
tc_type_args = count (id . fst) (kbs `zip` tks)
arityErr :: Outputable a => String -> a -> Int -> Int -> SDoc
arityErr what name n m
= hsep [ ptext (sLit "The") <+> text what, quotes (ppr name), ptext (sLit "should have"),
n_arguments <> comma, text "but has been given",
if m==0 then text "none" else int m]
where
n_arguments | n == 0 = ptext (sLit "no arguments")
| n == 1 = ptext (sLit "1 argument")
| True = hsep [int n, ptext (sLit "arguments")]
{-
************************************************************************
* *
\subsection{Checking for a decent instance head type}
* *
************************************************************************
@checkValidInstHead@ checks the type {\em and} its syntactic constraints:
it must normally look like: @instance Foo (Tycon a b c ...) ...@
The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
flag is on, or (2)~the instance is imported (they must have been
compiled elsewhere). In these cases, we let them go through anyway.
We can also have instances for functions: @instance Foo (a -> b) ...@.
-}
checkValidInstHead :: UserTypeCtxt -> Class -> [Type] -> TcM ()
checkValidInstHead ctxt clas cls_args
= do { dflags <- getDynFlags
; checkTc (clas `notElem` abstractClasses)
(instTypeErr clas cls_args abstract_class_msg)
-- Check language restrictions;
-- but not for SPECIALISE isntance pragmas
; let ty_args = dropWhile isKind cls_args
; unless spec_inst_prag $
do { checkTc (xopt Opt_TypeSynonymInstances dflags ||
all tcInstHeadTyNotSynonym ty_args)
(instTypeErr clas cls_args head_type_synonym_msg)
; checkTc (xopt Opt_FlexibleInstances dflags ||
all tcInstHeadTyAppAllTyVars ty_args)
(instTypeErr clas cls_args head_type_args_tyvars_msg)
; checkTc (xopt Opt_MultiParamTypeClasses dflags ||
length ty_args == 1 || -- Only count type arguments
(xopt Opt_NullaryTypeClasses dflags &&
null ty_args))
(instTypeErr clas cls_args head_one_type_msg) }
-- May not contain type family applications
; mapM_ checkTyFamFreeness ty_args
; mapM_ checkValidMonoType ty_args
-- For now, I only allow tau-types (not polytypes) in
-- the head of an instance decl.
-- E.g. instance C (forall a. a->a) is rejected
-- One could imagine generalising that, but I'm not sure
-- what all the consequences might be
}
where
spec_inst_prag = case ctxt of { SpecInstCtxt -> True; _ -> False }
head_type_synonym_msg = parens (
text "All instance types must be of the form (T t1 ... tn)" $$
text "where T is not a synonym." $$
text "Use TypeSynonymInstances if you want to disable this.")
head_type_args_tyvars_msg = parens (vcat [
text "All instance types must be of the form (T a1 ... an)",
text "where a1 ... an are *distinct type variables*,",
text "and each type variable appears at most once in the instance head.",
text "Use FlexibleInstances if you want to disable this."])
head_one_type_msg = parens (
text "Only one type can be given in an instance head." $$
text "Use MultiParamTypeClasses if you want to allow more, or zero.")
abstract_class_msg =
text "The class is abstract, manual instances are not permitted."
abstractClasses :: [ Class ]
abstractClasses = [ coercibleClass ] -- See Note [Coercible Instances]
instTypeErr :: Class -> [Type] -> SDoc -> SDoc
instTypeErr cls tys msg
= hang (hang (ptext (sLit "Illegal instance declaration for"))
2 (quotes (pprClassPred cls tys)))
2 msg
{- Note [Valid 'deriving' predicate]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
validDerivPred checks for OK 'deriving' context. See Note [Exotic
derived instance contexts] in TcDeriv. However the predicate is
here because it uses sizeTypes, fvTypes.
It checks for three things
* No repeated variables (hasNoDups fvs)
* No type constructors. This is done by comparing
sizeTypes tys == length (fvTypes tys)
sizeTypes counts variables and constructors; fvTypes returns variables.
So if they are the same, there must be no constructors. But there
might be applications thus (f (g x)).
* Also check for a bizarre corner case, when the derived instance decl
would look like
instance C a b => D (T a) where ...
Note that 'b' isn't a parameter of T. This gives rise to all sorts of
problems; in particular, it's hard to compare solutions for equality
when finding the fixpoint, and that means the inferContext loop does
not converge. See Trac #5287.
-}
validDerivPred :: TyVarSet -> PredType -> Bool
-- See Note [Valid 'deriving' predicate]
validDerivPred tv_set pred
= case classifyPredType pred of
ClassPred _ tys -> check_tys tys
EqPred {} -> False -- reject equality constraints
_ -> True -- Non-class predicates are ok
where
check_tys tys = hasNoDups fvs
&& sizeTypes tys == fromIntegral (length fvs)
&& all (`elemVarSet` tv_set) fvs
where
fvs = fvTypes tys
{-
************************************************************************
* *
\subsection{Checking instance for termination}
* *
************************************************************************
-}
checkValidInstance :: UserTypeCtxt -> LHsType Name -> Type
-> TcM ([TyVar], ThetaType, Class, [Type])
checkValidInstance ctxt hs_type ty
| Just (clas,inst_tys) <- getClassPredTys_maybe tau
, inst_tys `lengthIs` classArity clas
= do { setSrcSpan head_loc (checkValidInstHead ctxt clas inst_tys)
; checkValidTheta ctxt theta
-- The Termination and Coverate Conditions
-- Check that instance inference will terminate (if we care)
-- For Haskell 98 this will already have been done by checkValidTheta,
-- but as we may be using other extensions we need to check.
--
-- Note that the Termination Condition is *more conservative* than
-- the checkAmbiguity test we do on other type signatures
-- e.g. Bar a => Bar Int is ambiguous, but it also fails
-- the termination condition, because 'a' appears more often
-- in the constraint than in the head
; undecidable_ok <- xoptM Opt_UndecidableInstances
; if undecidable_ok
then checkAmbiguity ctxt ty
else checkInstTermination inst_tys theta
; case (checkInstCoverage undecidable_ok clas theta inst_tys) of
IsValid -> return () -- Check succeeded
NotValid msg -> addErrTc (instTypeErr clas inst_tys msg)
; return (tvs, theta, clas, inst_tys) }
| otherwise
= failWithTc (ptext (sLit "Malformed instance head:") <+> ppr tau)
where
(tvs, theta, tau) = tcSplitSigmaTy ty
-- The location of the "head" of the instance
head_loc = case hs_type of
L _ (HsForAllTy _ _ _ _ (L loc _)) -> loc
L loc _ -> loc
{-
Note [Paterson conditions]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Termination test: the so-called "Paterson conditions" (see Section 5 of
"Understanding functional dependencies via Constraint Handling Rules,
JFP Jan 2007).
We check that each assertion in the context satisfies:
(1) no variable has more occurrences in the assertion than in the head, and
(2) the assertion has fewer constructors and variables (taken together
and counting repetitions) than the head.
This is only needed with -fglasgow-exts, as Haskell 98 restrictions
(which have already been checked) guarantee termination.
The underlying idea is that
for any ground substitution, each assertion in the
context has fewer type constructors than the head.
-}
checkInstTermination :: [TcType] -> ThetaType -> TcM ()
-- See Note [Paterson conditions]
checkInstTermination tys theta
= check_preds theta
where
head_fvs = fvTypes tys
head_size = sizeTypes tys
check_preds :: [PredType] -> TcM ()
check_preds preds = mapM_ check preds
check :: PredType -> TcM ()
check pred
= case classifyPredType pred of
EqPred {} -> return () -- See Trac #4200.
IrredPred {} -> check2 pred (sizeType pred)
ClassPred cls tys
| isIPClass cls
-> return () -- You can't get to class predicates from implicit params
| isCTupleClass cls -- Look inside tuple predicates; Trac #8359
-> check_preds tys
| otherwise
-> check2 pred (sizeTypes tys) -- Other ClassPreds
check2 pred pred_size
| not (null bad_tvs) = addErrTc (noMoreMsg bad_tvs what)
| pred_size >= head_size = addErrTc (smallerMsg what)
| otherwise = return ()
where
what = ptext (sLit "constraint") <+> quotes (ppr pred)
bad_tvs = fvType pred \\ head_fvs
smallerMsg :: SDoc -> SDoc
smallerMsg what
= vcat [ hang (ptext (sLit "The") <+> what)
2 (ptext (sLit "is no smaller than the instance head"))
, parens undecidableMsg ]
noMoreMsg :: [TcTyVar] -> SDoc -> SDoc
noMoreMsg tvs what
= vcat [ hang (ptext (sLit "Variable") <> plural tvs <+> quotes (pprWithCommas ppr tvs)
<+> occurs <+> ptext (sLit "more often"))
2 (sep [ ptext (sLit "in the") <+> what
, ptext (sLit "than in the instance head") ])
, parens undecidableMsg ]
where
occurs = if isSingleton tvs then ptext (sLit "occurs")
else ptext (sLit "occur")
undecidableMsg, constraintKindsMsg :: SDoc
undecidableMsg = ptext (sLit "Use UndecidableInstances to permit this")
constraintKindsMsg = ptext (sLit "Use ConstraintKinds to permit this")
{-
Note [Associated type instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We allow this:
class C a where
type T x a
instance C Int where
type T (S y) Int = y
type T Z Int = Char
Note that
a) The variable 'x' is not bound by the class decl
b) 'x' is instantiated to a non-type-variable in the instance
c) There are several type instance decls for T in the instance
All this is fine. Of course, you can't give any *more* instances
for (T ty Int) elsewhere, because it's an *associated* type.
Note [Checking consistent instantiation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class C a b where
type T a x b
instance C [p] Int
type T [p] y Int = (p,y,y) -- Induces the family instance TyCon
-- type TR p y = (p,y,y)
So we
* Form the mini-envt from the class type variables a,b
to the instance decl types [p],Int: [a->[p], b->Int]
* Look at the tyvars a,x,b of the type family constructor T
(it shares tyvars with the class C)
* Apply the mini-evnt to them, and check that the result is
consistent with the instance types [p] y Int
We do *not* assume (at this point) the the bound variables of
the associated type instance decl are the same as for the parent
instance decl. So, for example,
instance C [p] Int
type T [q] y Int = ...
would work equally well. Reason: making the *kind* variables line
up is much harder. Example (Trac #7282):
class Foo (xs :: [k]) where
type Bar xs :: *
instance Foo '[] where
type Bar '[] = Int
Here the instance decl really looks like
instance Foo k ('[] k) where
type Bar k ('[] k) = Int
but the k's are not scoped, and hence won't match Uniques.
So instead we just match structure, with tcMatchTyX, and check
that distinct type variables match 1-1 with distinct type variables.
HOWEVER, we *still* make the instance type variables scope over the
type instances, to pick up non-obvious kinds. Eg
class Foo (a :: k) where
type F a
instance Foo (b :: k -> k) where
type F b = Int
Here the instance is kind-indexed and really looks like
type F (k->k) (b::k->k) = Int
But if the 'b' didn't scope, we would make F's instance too
poly-kinded.
-}
-- | Extra information needed when type-checking associated types. The 'Class' is
-- the enclosing class, and the @VarEnv Type@ maps class variables to their
-- instance types.
type ClsInfo = (Class, VarEnv Type)
checkConsistentFamInst
:: Maybe ClsInfo
-> TyCon -- ^ Family tycon
-> [TyVar] -- ^ Type variables of the family instance
-> [Type] -- ^ Type patterns from instance
-> TcM ()
-- See Note [Checking consistent instantiation]
checkConsistentFamInst Nothing _ _ _ = return ()
checkConsistentFamInst (Just (clas, mini_env)) fam_tc at_tvs at_tys
= do { -- Check that the associated type indeed comes from this class
checkTc (Just clas == tyConAssoc_maybe fam_tc)
(badATErr (className clas) (tyConName fam_tc))
-- See Note [Checking consistent instantiation] in TcTyClsDecls
-- Check right to left, so that we spot type variable
-- inconsistencies before (more confusing) kind variables
; discardResult $ foldrM check_arg emptyTvSubst $
tyConTyVars fam_tc `zip` at_tys }
where
at_tv_set = mkVarSet at_tvs
check_arg :: (TyVar, Type) -> TvSubst -> TcM TvSubst
check_arg (fam_tc_tv, at_ty) subst
| Just inst_ty <- lookupVarEnv mini_env fam_tc_tv
= case tcMatchTyX at_tv_set subst at_ty inst_ty of
Just subst | all_distinct subst -> return subst
_ -> failWithTc $ wrongATArgErr at_ty inst_ty
-- No need to instantiate here, because the axiom
-- uses the same type variables as the assocated class
| otherwise
= return subst -- Allow non-type-variable instantiation
-- See Note [Associated type instances]
all_distinct :: TvSubst -> Bool
-- True if all the variables mapped the substitution
-- map to *distinct* type *variables*
all_distinct subst = go [] at_tvs
where
go _ [] = True
go acc (tv:tvs) = case lookupTyVar subst tv of
Nothing -> go acc tvs
Just ty | Just tv' <- tcGetTyVar_maybe ty
, tv' `notElem` acc
-> go (tv' : acc) tvs
_other -> False
badATErr :: Name -> Name -> SDoc
badATErr clas op
= hsep [ptext (sLit "Class"), quotes (ppr clas),
ptext (sLit "does not have an associated type"), quotes (ppr op)]
wrongATArgErr :: Type -> Type -> SDoc
wrongATArgErr ty instTy =
sep [ ptext (sLit "Type indexes must match class instance head")
, ptext (sLit "Found") <+> quotes (ppr ty)
<+> ptext (sLit "but expected") <+> quotes (ppr instTy)
]
{-
************************************************************************
* *
Checking type instance well-formedness and termination
* *
************************************************************************
-}
checkValidCoAxiom :: CoAxiom Branched -> TcM ()
checkValidCoAxiom (CoAxiom { co_ax_tc = fam_tc, co_ax_branches = branches })
= do { mapM_ (checkValidCoAxBranch Nothing fam_tc) branch_list
; foldlM_ check_branch_compat [] branch_list }
where
branch_list = fromBranches branches
injectivity = familyTyConInjectivityInfo fam_tc
check_branch_compat :: [CoAxBranch] -- previous branches in reverse order
-> CoAxBranch -- current branch
-> TcM [CoAxBranch]-- current branch : previous branches
-- Check for
-- (a) this banch is dominated by previous ones
-- (b) failure of injectivity
check_branch_compat prev_branches cur_branch
| cur_branch `isDominatedBy` prev_branches
= do { addWarnAt (coAxBranchSpan cur_branch) $
inaccessibleCoAxBranch fam_tc cur_branch
; return prev_branches }
| otherwise
= do { check_injectivity prev_branches cur_branch
; return (cur_branch : prev_branches) }
-- Injectivity check: check whether a new (CoAxBranch) can extend
-- already checked equations without violating injectivity
-- annotation supplied by the user.
-- See Note [Verifying injectivity annotation] in FamInstEnv
check_injectivity prev_branches cur_branch
| Injective inj <- injectivity
= do { let conflicts =
fst $ foldl (gather_conflicts inj prev_branches cur_branch)
([], 0) prev_branches
; mapM_ (\(err, span) -> setSrcSpan span $ addErr err)
(makeInjectivityErrors fam_tc cur_branch inj conflicts) }
| otherwise
= return ()
gather_conflicts inj prev_branches cur_branch (acc, n) branch
-- n is 0-based index of branch in prev_branches
= case injectiveBranches inj cur_branch branch of
InjectivityUnified ax1 ax2
| ax1 `isDominatedBy` (replace_br prev_branches n ax2)
-> (acc, n + 1)
| otherwise
-> (branch : acc, n + 1)
InjectivityAccepted -> (acc, n + 1)
-- Replace n-th element in the list. Assumes 0-based indexing.
replace_br :: [CoAxBranch] -> Int -> CoAxBranch -> [CoAxBranch]
replace_br brs n br = take n brs ++ [br] ++ drop (n+1) brs
-- Check that a "type instance" is well-formed (which includes decidability
-- unless -XUndecidableInstances is given).
--
checkValidCoAxBranch :: Maybe ClsInfo
-> TyCon -> CoAxBranch -> TcM ()
checkValidCoAxBranch mb_clsinfo fam_tc
(CoAxBranch { cab_tvs = tvs, cab_lhs = typats
, cab_rhs = rhs, cab_loc = loc })
= checkValidTyFamEqn mb_clsinfo fam_tc tvs typats rhs loc
-- | Do validity checks on a type family equation, including consistency
-- with any enclosing class instance head, termination, and lack of
-- polytypes.
checkValidTyFamEqn :: Maybe ClsInfo
-> TyCon -- ^ of the type family
-> [TyVar] -- ^ bound tyvars in the equation
-> [Type] -- ^ type patterns
-> Type -- ^ rhs
-> SrcSpan
-> TcM ()
checkValidTyFamEqn mb_clsinfo fam_tc tvs typats rhs loc
= setSrcSpan loc $
do { checkValidFamPats fam_tc tvs typats
-- The argument patterns, and RHS, are all boxed tau types
-- E.g Reject type family F (a :: k1) :: k2
-- type instance F (forall a. a->a) = ...
-- type instance F Int# = ...
-- type instance F Int = forall a. a->a
-- type instance F Int = Int#
-- See Trac #9357
; mapM_ checkValidMonoType typats
; checkValidMonoType rhs
-- We have a decidable instance unless otherwise permitted
; undecidable_ok <- xoptM Opt_UndecidableInstances
; unless undecidable_ok $
mapM_ addErrTc (checkFamInstRhs typats (tcTyFamInsts rhs))
-- Check that type patterns match the class instance head
; checkConsistentFamInst mb_clsinfo fam_tc tvs typats }
-- Make sure that each type family application is
-- (1) strictly smaller than the lhs,
-- (2) mentions no type variable more often than the lhs, and
-- (3) does not contain any further type family instances.
--
checkFamInstRhs :: [Type] -- lhs
-> [(TyCon, [Type])] -- type family instances
-> [MsgDoc]
checkFamInstRhs lhsTys famInsts
= mapMaybe check famInsts
where
size = sizeTypes lhsTys
fvs = fvTypes lhsTys
check (tc, tys)
| not (all isTyFamFree tys) = Just (nestedMsg what)
| not (null bad_tvs) = Just (noMoreMsg bad_tvs what)
| size <= sizeTypes tys = Just (smallerMsg what)
| otherwise = Nothing
where
what = ptext (sLit "type family application") <+> quotes (pprType (TyConApp tc tys))
bad_tvs = fvTypes tys \\ fvs
checkValidFamPats :: TyCon -> [TyVar] -> [Type] -> TcM ()
-- Patterns in a 'type instance' or 'data instance' decl should
-- a) contain no type family applications
-- (vanilla synonyms are fine, though)
-- b) properly bind all their free type variables
-- e.g. we disallow (Trac #7536)
-- type T a = Int
-- type instance F (T a) = a
-- c) Have the right number of patterns
checkValidFamPats fam_tc tvs ty_pats
= ASSERT2( length ty_pats == tyConArity fam_tc
, ppr ty_pats $$ ppr fam_tc $$ ppr (tyConArity fam_tc) )
-- A family instance must have exactly the same number of type
-- parameters as the family declaration. You can't write
-- type family F a :: * -> *
-- type instance F Int y = y
-- because then the type (F Int) would be like (\y.y)
-- But this is checked at the time the axiom is created
do { mapM_ checkTyFamFreeness ty_pats
; let unbound_tvs = filterOut (`elemVarSet` exactTyVarsOfTypes ty_pats) tvs
; checkTc (null unbound_tvs) (famPatErr fam_tc unbound_tvs ty_pats) }
-- Ensure that no type family instances occur in a type.
checkTyFamFreeness :: Type -> TcM ()
checkTyFamFreeness ty
= checkTc (isTyFamFree ty) $
tyFamInstIllegalErr ty
-- Check that a type does not contain any type family applications.
--
isTyFamFree :: Type -> Bool
isTyFamFree = null . tcTyFamInsts
-- Error messages
inaccessibleCoAxBranch :: TyCon -> CoAxBranch -> SDoc
inaccessibleCoAxBranch fam_tc (CoAxBranch { cab_tvs = tvs
, cab_lhs = lhs
, cab_rhs = rhs })
= ptext (sLit "Type family instance equation is overlapped:") $$
hang (pprUserForAll tvs)
2 (hang (pprTypeApp fam_tc lhs) 2 (equals <+> (ppr rhs)))
tyFamInstIllegalErr :: Type -> SDoc
tyFamInstIllegalErr ty
= hang (ptext (sLit "Illegal type synonym family application in instance") <>
colon) 2 $
ppr ty
nestedMsg :: SDoc -> SDoc
nestedMsg what
= sep [ ptext (sLit "Illegal nested") <+> what
, parens undecidableMsg ]
famPatErr :: TyCon -> [TyVar] -> [Type] -> SDoc
famPatErr fam_tc tvs pats
= hang (ptext (sLit "Family instance purports to bind type variable") <> plural tvs
<+> pprQuotedList tvs)
2 (hang (ptext (sLit "but the real LHS (expanding synonyms) is:"))
2 (pprTypeApp fam_tc (map expandTypeSynonyms pats) <+> ptext (sLit "= ...")))
{-
************************************************************************
* *
\subsection{Auxiliary functions}
* *
************************************************************************
-}
-- Free variables of a type, retaining repetitions, and expanding synonyms
-- Ignore kinds altogether: rightly or wrongly, we only check for
-- excessive occurrences of *type* variables.
-- e.g. type instance Demote {T k} a = T (Demote {k} (Any {k}))
--
-- c.f. sizeType, which is often called side by side with fvType
fvType, fv_type :: Type -> [TyVar]
fvType ty | isKind ty = []
| otherwise = fv_type ty
fv_type ty | Just exp_ty <- tcView ty = fv_type exp_ty
fv_type (TyVarTy tv) = [tv]
fv_type (TyConApp _ tys) = fvTypes tys
fv_type (LitTy {}) = []
fv_type (FunTy arg res) = fv_type arg ++ fv_type res
fv_type (AppTy fun arg) = fv_type fun ++ fv_type arg
fv_type (ForAllTy tyvar ty) = filter (/= tyvar) (fv_type ty)
fvTypes :: [Type] -> [TyVar]
fvTypes tys = concat (map fvType tys)
|
siddhanathan/ghc
|
compiler/typecheck/TcValidity.hs
|
bsd-3-clause
| 57,770 | 7 | 16 | 16,404 | 8,610 | 4,419 | 4,191 | -1 | -1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP
, NoImplicitPrelude
, BangPatterns
#-}
{-# OPTIONS_GHC -Wno-identities #-}
-- Whether there are identities depends on the platform
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.IO.FD
-- Copyright : (c) The University of Glasgow, 1994-2008
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable
--
-- Raw read/write operations on file descriptors
--
-----------------------------------------------------------------------------
module GHC.IO.FD (
FD(..),
openFile, mkFD, release,
setNonBlockingMode,
readRawBufferPtr, readRawBufferPtrNoBlock, writeRawBufferPtr,
stdin, stdout, stderr
) where
import GHC.Base
import GHC.Num
import GHC.Real
import GHC.Show
import GHC.Enum
import GHC.IO
import GHC.IO.IOMode
import GHC.IO.Buffer
import GHC.IO.BufferedIO
import qualified GHC.IO.Device
import GHC.IO.Device (SeekMode(..), IODeviceType(..))
import GHC.Conc.IO
import GHC.IO.Exception
#if defined(mingw32_HOST_OS)
import GHC.Windows
#endif
import Foreign
import Foreign.C
import qualified System.Posix.Internals
import System.Posix.Internals hiding (FD, setEcho, getEcho)
import System.Posix.Types
#if defined(mingw32_HOST_OS)
# if defined(i386_HOST_ARCH)
# define WINDOWS_CCONV stdcall
# elif defined(x86_64_HOST_ARCH)
# define WINDOWS_CCONV ccall
# else
# error Unknown mingw32 arch
# endif
#endif
c_DEBUG_DUMP :: Bool
c_DEBUG_DUMP = False
-- -----------------------------------------------------------------------------
-- The file-descriptor IO device
data FD = FD {
fdFD :: {-# UNPACK #-} !CInt,
#if defined(mingw32_HOST_OS)
-- On Windows, a socket file descriptor needs to be read and written
-- using different functions (send/recv).
fdIsSocket_ :: {-# UNPACK #-} !Int
#else
-- On Unix we need to know whether this FD has O_NONBLOCK set.
-- If it has, then we can use more efficient routines to read/write to it.
-- It is always safe for this to be off.
fdIsNonBlocking :: {-# UNPACK #-} !Int
#endif
}
#if defined(mingw32_HOST_OS)
fdIsSocket :: FD -> Bool
fdIsSocket fd = fdIsSocket_ fd /= 0
#endif
-- | @since 4.1.0.0
instance Show FD where
show fd = show (fdFD fd)
-- | @since 4.1.0.0
instance GHC.IO.Device.RawIO FD where
read = fdRead
readNonBlocking = fdReadNonBlocking
write = fdWrite
writeNonBlocking = fdWriteNonBlocking
-- | @since 4.1.0.0
instance GHC.IO.Device.IODevice FD where
ready = ready
close = close
isTerminal = isTerminal
isSeekable = isSeekable
seek = seek
tell = tell
getSize = getSize
setSize = setSize
setEcho = setEcho
getEcho = getEcho
setRaw = setRaw
devType = devType
dup = dup
dup2 = dup2
-- We used to use System.Posix.Internals.dEFAULT_BUFFER_SIZE, which is
-- taken from the value of BUFSIZ on the current platform. This value
-- varies too much though: it is 512 on Windows, 1024 on OS X and 8192
-- on Linux. So let's just use a decent size on every platform:
dEFAULT_FD_BUFFER_SIZE :: Int
dEFAULT_FD_BUFFER_SIZE = 8192
-- | @since 4.1.0.0
instance BufferedIO FD where
newBuffer _dev state = newByteBuffer dEFAULT_FD_BUFFER_SIZE state
fillReadBuffer fd buf = readBuf' fd buf
fillReadBuffer0 fd buf = readBufNonBlocking fd buf
flushWriteBuffer fd buf = writeBuf' fd buf
flushWriteBuffer0 fd buf = writeBufNonBlocking fd buf
readBuf' :: FD -> Buffer Word8 -> IO (Int, Buffer Word8)
readBuf' fd buf = do
when c_DEBUG_DUMP $
puts ("readBuf fd=" ++ show fd ++ " " ++ summaryBuffer buf ++ "\n")
(r,buf') <- readBuf fd buf
when c_DEBUG_DUMP $
puts ("after: " ++ summaryBuffer buf' ++ "\n")
return (r,buf')
writeBuf' :: FD -> Buffer Word8 -> IO (Buffer Word8)
writeBuf' fd buf = do
when c_DEBUG_DUMP $
puts ("writeBuf fd=" ++ show fd ++ " " ++ summaryBuffer buf ++ "\n")
writeBuf fd buf
-- -----------------------------------------------------------------------------
-- opening files
-- | Open a file and make an 'FD' for it. Truncates the file to zero
-- size when the `IOMode` is `WriteMode`.
openFile
:: FilePath -- ^ file to open
-> IOMode -- ^ mode in which to open the file
-> Bool -- ^ open the file in non-blocking mode?
-> IO (FD,IODeviceType)
openFile filepath iomode non_blocking =
withFilePath filepath $ \ f ->
let
oflags1 = case iomode of
ReadMode -> read_flags
WriteMode -> write_flags
ReadWriteMode -> rw_flags
AppendMode -> append_flags
#if defined(mingw32_HOST_OS)
binary_flags = o_BINARY
#else
binary_flags = 0
#endif
oflags2 = oflags1 .|. binary_flags
oflags | non_blocking = oflags2 .|. nonblock_flags
| otherwise = oflags2
in do
-- NB. always use a safe open(), because we don't know whether open()
-- will be fast or not. It can be slow on NFS and FUSE filesystems,
-- for example.
fd <- throwErrnoIfMinus1Retry "openFile" $ c_safe_open f oflags 0o666
(fD,fd_type) <- mkFD fd iomode Nothing{-no stat-}
False{-not a socket-}
non_blocking
`catchAny` \e -> do _ <- c_close fd
throwIO e
-- we want to truncate() if this is an open in WriteMode, but only
-- if the target is a RegularFile. ftruncate() fails on special files
-- like /dev/null.
when (iomode == WriteMode && fd_type == RegularFile) $
setSize fD 0
return (fD,fd_type)
std_flags, output_flags, read_flags, write_flags, rw_flags,
append_flags, nonblock_flags :: CInt
std_flags = o_NOCTTY
output_flags = std_flags .|. o_CREAT
read_flags = std_flags .|. o_RDONLY
write_flags = output_flags .|. o_WRONLY
rw_flags = output_flags .|. o_RDWR
append_flags = write_flags .|. o_APPEND
nonblock_flags = o_NONBLOCK
-- | Make a 'FD' from an existing file descriptor. Fails if the FD
-- refers to a directory. If the FD refers to a file, `mkFD` locks
-- the file according to the Haskell 2010 single writer/multiple reader
-- locking semantics (this is why we need the `IOMode` argument too).
mkFD :: CInt
-> IOMode
-> Maybe (IODeviceType, CDev, CIno)
-- the results of fdStat if we already know them, or we want
-- to prevent fdToHandle_stat from doing its own stat.
-- These are used for:
-- - we fail if the FD refers to a directory
-- - if the FD refers to a file, we lock it using (cdev,cino)
-> Bool -- ^ is a socket (on Windows)
-> Bool -- ^ is in non-blocking mode on Unix
-> IO (FD,IODeviceType)
mkFD fd iomode mb_stat is_socket is_nonblock = do
let _ = (is_socket, is_nonblock) -- warning suppression
(fd_type,dev,ino) <-
case mb_stat of
Nothing -> fdStat fd
Just stat -> return stat
let write = case iomode of
ReadMode -> False
_ -> True
case fd_type of
Directory ->
ioException (IOError Nothing InappropriateType "openFile"
"is a directory" Nothing Nothing)
-- regular files need to be locked
RegularFile -> do
-- On Windows we need an additional call to get a unique device id
-- and inode, since fstat just returns 0 for both.
(unique_dev, unique_ino) <- getUniqueFileInfo fd dev ino
r <- lockFile fd unique_dev unique_ino (fromBool write)
when (r == -1) $
ioException (IOError Nothing ResourceBusy "openFile"
"file is locked" Nothing Nothing)
_other_type -> return ()
#if defined(mingw32_HOST_OS)
when (not is_socket) $ setmode fd True >> return ()
#endif
return (FD{ fdFD = fd,
#if !defined(mingw32_HOST_OS)
fdIsNonBlocking = fromEnum is_nonblock
#else
fdIsSocket_ = fromEnum is_socket
#endif
},
fd_type)
getUniqueFileInfo :: CInt -> CDev -> CIno -> IO (Word64, Word64)
#if !defined(mingw32_HOST_OS)
getUniqueFileInfo _ dev ino = return (fromIntegral dev, fromIntegral ino)
#else
getUniqueFileInfo fd _ _ = do
with 0 $ \devptr -> do
with 0 $ \inoptr -> do
c_getUniqueFileInfo fd devptr inoptr
liftM2 (,) (peek devptr) (peek inoptr)
#endif
#if defined(mingw32_HOST_OS)
foreign import ccall unsafe "__hscore_setmode"
setmode :: CInt -> Bool -> IO CInt
#endif
-- -----------------------------------------------------------------------------
-- Standard file descriptors
stdFD :: CInt -> FD
stdFD fd = FD { fdFD = fd,
#if defined(mingw32_HOST_OS)
fdIsSocket_ = 0
#else
fdIsNonBlocking = 0
-- We don't set non-blocking mode on standard handles, because it may
-- confuse other applications attached to the same TTY/pipe
-- see Note [nonblock]
#endif
}
stdin, stdout, stderr :: FD
stdin = stdFD 0
stdout = stdFD 1
stderr = stdFD 2
-- -----------------------------------------------------------------------------
-- Operations on file descriptors
close :: FD -> IO ()
close fd =
do let closer realFd =
throwErrnoIfMinus1Retry_ "GHC.IO.FD.close" $
#if defined(mingw32_HOST_OS)
if fdIsSocket fd then
c_closesocket (fromIntegral realFd)
else
#endif
c_close (fromIntegral realFd)
-- release the lock *first*, because otherwise if we're preempted
-- after closing but before releasing, the FD may have been reused.
-- (#7646)
release fd
closeFdWith closer (fromIntegral (fdFD fd))
release :: FD -> IO ()
release fd = do _ <- unlockFile (fdFD fd)
return ()
#if defined(mingw32_HOST_OS)
foreign import WINDOWS_CCONV unsafe "HsBase.h closesocket"
c_closesocket :: CInt -> IO CInt
#endif
isSeekable :: FD -> IO Bool
isSeekable fd = do
t <- devType fd
return (t == RegularFile || t == RawDevice)
seek :: FD -> SeekMode -> Integer -> IO ()
seek fd mode off = do
throwErrnoIfMinus1Retry_ "seek" $
c_lseek (fdFD fd) (fromIntegral off) seektype
where
seektype :: CInt
seektype = case mode of
AbsoluteSeek -> sEEK_SET
RelativeSeek -> sEEK_CUR
SeekFromEnd -> sEEK_END
tell :: FD -> IO Integer
tell fd =
fromIntegral `fmap`
(throwErrnoIfMinus1Retry "hGetPosn" $
c_lseek (fdFD fd) 0 sEEK_CUR)
getSize :: FD -> IO Integer
getSize fd = fdFileSize (fdFD fd)
setSize :: FD -> Integer -> IO ()
setSize fd size = do
throwErrnoIf_ (/=0) "GHC.IO.FD.setSize" $
c_ftruncate (fdFD fd) (fromIntegral size)
devType :: FD -> IO IODeviceType
devType fd = do (ty,_,_) <- fdStat (fdFD fd); return ty
dup :: FD -> IO FD
dup fd = do
newfd <- throwErrnoIfMinus1 "GHC.IO.FD.dup" $ c_dup (fdFD fd)
return fd{ fdFD = newfd }
dup2 :: FD -> FD -> IO FD
dup2 fd fdto = do
-- Windows' dup2 does not return the new descriptor, unlike Unix
throwErrnoIfMinus1_ "GHC.IO.FD.dup2" $
c_dup2 (fdFD fd) (fdFD fdto)
return fd{ fdFD = fdFD fdto } -- original FD, with the new fdFD
setNonBlockingMode :: FD -> Bool -> IO FD
setNonBlockingMode fd set = do
setNonBlockingFD (fdFD fd) set
#if defined(mingw32_HOST_OS)
return fd
#else
return fd{ fdIsNonBlocking = fromEnum set }
#endif
ready :: FD -> Bool -> Int -> IO Bool
ready fd write msecs = do
r <- throwErrnoIfMinus1Retry "GHC.IO.FD.ready" $
fdReady (fdFD fd) (fromIntegral $ fromEnum $ write)
(fromIntegral msecs)
#if defined(mingw32_HOST_OS)
(fromIntegral $ fromEnum $ fdIsSocket fd)
#else
0
#endif
return (toEnum (fromIntegral r))
foreign import ccall safe "fdReady"
fdReady :: CInt -> CBool -> Int64 -> CBool -> IO CInt
-- ---------------------------------------------------------------------------
-- Terminal-related stuff
isTerminal :: FD -> IO Bool
isTerminal fd =
#if defined(mingw32_HOST_OS)
if fdIsSocket fd then return False
else is_console (fdFD fd) >>= return.toBool
#else
c_isatty (fdFD fd) >>= return.toBool
#endif
setEcho :: FD -> Bool -> IO ()
setEcho fd on = System.Posix.Internals.setEcho (fdFD fd) on
getEcho :: FD -> IO Bool
getEcho fd = System.Posix.Internals.getEcho (fdFD fd)
setRaw :: FD -> Bool -> IO ()
setRaw fd raw = System.Posix.Internals.setCooked (fdFD fd) (not raw)
-- -----------------------------------------------------------------------------
-- Reading and Writing
fdRead :: FD -> Ptr Word8 -> Int -> IO Int
fdRead fd ptr bytes
= do { r <- readRawBufferPtr "GHC.IO.FD.fdRead" fd ptr 0 (fromIntegral bytes)
; return (fromIntegral r) }
fdReadNonBlocking :: FD -> Ptr Word8 -> Int -> IO (Maybe Int)
fdReadNonBlocking fd ptr bytes = do
r <- readRawBufferPtrNoBlock "GHC.IO.FD.fdReadNonBlocking" fd ptr
0 (fromIntegral bytes)
case fromIntegral r of
(-1) -> return (Nothing)
n -> return (Just n)
fdWrite :: FD -> Ptr Word8 -> Int -> IO ()
fdWrite fd ptr bytes = do
res <- writeRawBufferPtr "GHC.IO.FD.fdWrite" fd ptr 0 (fromIntegral bytes)
let res' = fromIntegral res
if res' < bytes
then fdWrite fd (ptr `plusPtr` res') (bytes - res')
else return ()
-- XXX ToDo: this isn't non-blocking
fdWriteNonBlocking :: FD -> Ptr Word8 -> Int -> IO Int
fdWriteNonBlocking fd ptr bytes = do
res <- writeRawBufferPtrNoBlock "GHC.IO.FD.fdWriteNonBlocking" fd ptr 0
(fromIntegral bytes)
return (fromIntegral res)
-- -----------------------------------------------------------------------------
-- FD operations
-- Low level routines for reading/writing to (raw)buffers:
#if !defined(mingw32_HOST_OS)
{-
NOTE [nonblock]:
Unix has broken semantics when it comes to non-blocking I/O: you can
set the O_NONBLOCK flag on an FD, but it applies to the all other FDs
attached to the same underlying file, pipe or TTY; there's no way to
have private non-blocking behaviour for an FD. See bug #724.
We fix this by only setting O_NONBLOCK on FDs that we create; FDs that
come from external sources or are exposed externally are left in
blocking mode. This solution has some problems though. We can't
completely simulate a non-blocking read without O_NONBLOCK: several
cases are wrong here. The cases that are wrong:
* reading/writing to a blocking FD in non-threaded mode.
In threaded mode, we just make a safe call to read().
In non-threaded mode we call select() before attempting to read,
but that leaves a small race window where the data can be read
from the file descriptor before we issue our blocking read().
* readRawBufferNoBlock for a blocking FD
NOTE [2363]:
In the threaded RTS we could just make safe calls to read()/write()
for file descriptors in blocking mode without worrying about blocking
other threads, but the problem with this is that the thread will be
uninterruptible while it is blocked in the foreign call. See #2363.
So now we always call fdReady() before reading, and if fdReady
indicates that there's no data, we call threadWaitRead.
-}
readRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO Int
readRawBufferPtr loc !fd !buf !off !len
| isNonBlocking fd = unsafe_read -- unsafe is ok, it can't block
| otherwise = do r <- throwErrnoIfMinus1 loc
(unsafe_fdReady (fdFD fd) 0 0 0)
if r /= 0
then read
else do threadWaitRead (fromIntegral (fdFD fd)); read
where
do_read call = fromIntegral `fmap`
throwErrnoIfMinus1RetryMayBlock loc call
(threadWaitRead (fromIntegral (fdFD fd)))
read = if threaded then safe_read else unsafe_read
unsafe_read = do_read (c_read (fdFD fd) (buf `plusPtr` off) len)
safe_read = do_read (c_safe_read (fdFD fd) (buf `plusPtr` off) len)
-- return: -1 indicates EOF, >=0 is bytes read
readRawBufferPtrNoBlock :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO Int
readRawBufferPtrNoBlock loc !fd !buf !off !len
| isNonBlocking fd = unsafe_read -- unsafe is ok, it can't block
| otherwise = do r <- unsafe_fdReady (fdFD fd) 0 0 0
if r /= 0 then safe_read
else return 0
-- XXX see note [nonblock]
where
do_read call = do r <- throwErrnoIfMinus1RetryOnBlock loc call (return (-1))
case r of
(-1) -> return 0
0 -> return (-1)
n -> return (fromIntegral n)
unsafe_read = do_read (c_read (fdFD fd) (buf `plusPtr` off) len)
safe_read = do_read (c_safe_read (fdFD fd) (buf `plusPtr` off) len)
writeRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
writeRawBufferPtr loc !fd !buf !off !len
| isNonBlocking fd = unsafe_write -- unsafe is ok, it can't block
| otherwise = do r <- unsafe_fdReady (fdFD fd) 1 0 0
if r /= 0
then write
else do threadWaitWrite (fromIntegral (fdFD fd)); write
where
do_write call = fromIntegral `fmap`
throwErrnoIfMinus1RetryMayBlock loc call
(threadWaitWrite (fromIntegral (fdFD fd)))
write = if threaded then safe_write else unsafe_write
unsafe_write = do_write (c_write (fdFD fd) (buf `plusPtr` off) len)
safe_write = do_write (c_safe_write (fdFD fd) (buf `plusPtr` off) len)
writeRawBufferPtrNoBlock :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
writeRawBufferPtrNoBlock loc !fd !buf !off !len
| isNonBlocking fd = unsafe_write -- unsafe is ok, it can't block
| otherwise = do r <- unsafe_fdReady (fdFD fd) 1 0 0
if r /= 0 then write
else return 0
where
do_write call = do r <- throwErrnoIfMinus1RetryOnBlock loc call (return (-1))
case r of
(-1) -> return 0
n -> return (fromIntegral n)
write = if threaded then safe_write else unsafe_write
unsafe_write = do_write (c_write (fdFD fd) (buf `plusPtr` off) len)
safe_write = do_write (c_safe_write (fdFD fd) (buf `plusPtr` off) len)
isNonBlocking :: FD -> Bool
isNonBlocking fd = fdIsNonBlocking fd /= 0
foreign import ccall unsafe "fdReady"
unsafe_fdReady :: CInt -> CBool -> Int64 -> CBool -> IO CInt
#else /* mingw32_HOST_OS.... */
readRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
readRawBufferPtr loc !fd !buf !off !len
| threaded = blockingReadRawBufferPtr loc fd buf off len
| otherwise = asyncReadRawBufferPtr loc fd buf off len
writeRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
writeRawBufferPtr loc !fd !buf !off !len
| threaded = blockingWriteRawBufferPtr loc fd buf off len
| otherwise = asyncWriteRawBufferPtr loc fd buf off len
readRawBufferPtrNoBlock :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
readRawBufferPtrNoBlock = readRawBufferPtr
writeRawBufferPtrNoBlock :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
writeRawBufferPtrNoBlock = writeRawBufferPtr
-- Async versions of the read/write primitives, for the non-threaded RTS
asyncReadRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
asyncReadRawBufferPtr loc !fd !buf !off !len = do
(l, rc) <- asyncRead (fromIntegral (fdFD fd)) (fdIsSocket_ fd)
(fromIntegral len) (buf `plusPtr` off)
if l == (-1)
then
ioError (errnoToIOError loc (Errno (fromIntegral rc)) Nothing Nothing)
else return (fromIntegral l)
asyncWriteRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
asyncWriteRawBufferPtr loc !fd !buf !off !len = do
(l, rc) <- asyncWrite (fromIntegral (fdFD fd)) (fdIsSocket_ fd)
(fromIntegral len) (buf `plusPtr` off)
if l == (-1)
then
ioError (errnoToIOError loc (Errno (fromIntegral rc)) Nothing Nothing)
else return (fromIntegral l)
-- Blocking versions of the read/write primitives, for the threaded RTS
blockingReadRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
blockingReadRawBufferPtr loc !fd !buf !off !len
= throwErrnoIfMinus1Retry loc $
if fdIsSocket fd
then c_safe_recv (fdFD fd) (buf `plusPtr` off) (fromIntegral len) 0
else c_safe_read (fdFD fd) (buf `plusPtr` off) (fromIntegral len)
blockingWriteRawBufferPtr :: String -> FD -> Ptr Word8-> Int -> CSize -> IO CInt
blockingWriteRawBufferPtr loc !fd !buf !off !len
= throwErrnoIfMinus1Retry loc $
if fdIsSocket fd
then c_safe_send (fdFD fd) (buf `plusPtr` off) (fromIntegral len) 0
else do
r <- c_safe_write (fdFD fd) (buf `plusPtr` off) (fromIntegral len)
when (r == -1) c_maperrno
return r
-- we don't trust write() to give us the correct errno, and
-- instead do the errno conversion from GetLastError()
-- ourselves. The main reason is that we treat ERROR_NO_DATA
-- (pipe is closing) as EPIPE, whereas write() returns EINVAL
-- for this case. We need to detect EPIPE correctly, because it
-- shouldn't be reported as an error when it happens on stdout.
-- NOTE: "safe" versions of the read/write calls for use by the threaded RTS.
-- These calls may block, but that's ok.
foreign import WINDOWS_CCONV safe "recv"
c_safe_recv :: CInt -> Ptr Word8 -> CInt -> CInt{-flags-} -> IO CInt
foreign import WINDOWS_CCONV safe "send"
c_safe_send :: CInt -> Ptr Word8 -> CInt -> CInt{-flags-} -> IO CInt
#endif
foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
-- -----------------------------------------------------------------------------
-- utils
#if !defined(mingw32_HOST_OS)
throwErrnoIfMinus1RetryOnBlock :: String -> IO CSsize -> IO CSsize -> IO CSsize
throwErrnoIfMinus1RetryOnBlock loc f on_block =
do
res <- f
if (res :: CSsize) == -1
then do
err <- getErrno
if err == eINTR
then throwErrnoIfMinus1RetryOnBlock loc f on_block
else if err == eWOULDBLOCK || err == eAGAIN
then do on_block
else throwErrno loc
else return res
#endif
-- -----------------------------------------------------------------------------
-- Locking/unlocking
foreign import ccall unsafe "lockFile"
lockFile :: CInt -> Word64 -> Word64 -> CInt -> IO CInt
foreign import ccall unsafe "unlockFile"
unlockFile :: CInt -> IO CInt
#if defined(mingw32_HOST_OS)
foreign import ccall unsafe "get_unique_file_info"
c_getUniqueFileInfo :: CInt -> Ptr Word64 -> Ptr Word64 -> IO ()
#endif
|
shlevy/ghc
|
libraries/base/GHC/IO/FD.hs
|
bsd-3-clause
| 23,109 | 3 | 17 | 5,872 | 4,282 | 2,227 | 2,055 | 317 | 5 |
f = foo ((*) x)
|
mpickering/hlint-refactor
|
tests/examples/Lambda8.hs
|
bsd-3-clause
| 15 | 0 | 7 | 4 | 17 | 9 | 8 | 1 | 1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ur-PK">
<title>Kotlin Support</title>
<maps>
<homeID>kotlin</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
kingthorin/zap-extensions
|
addOns/kotlin/src/main/javahelp/org/zaproxy/addon/kotlin/resources/help_ur_PK/helpset_ur_PK.hs
|
apache-2.0
| 962 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
-- | Error handling style for the hackage server.
--
-- The point is to be able to abort and return appropriate HTTP errors, plus
-- human readable messages.
--
-- We use a standard error monad / exception style so that we can hide some of
-- the error checking plumbing.
--
-- We use a custom error type that enables us to render the error in an
-- appropriate way, ie themed html or plain text, depending on the context.
--
module Distribution.Server.Framework.Error (
-- * Server error monad
ServerPartE,
-- * Generating errors
MessageSpan(..),
errBadRequest,
errForbidden,
errNotFound,
errBadMediaType,
errInternalError,
throwError,
-- * Handling errors
ErrorResponse(..),
internalServerErrorResponse,
runServerPartE,
handleErrorResponse,
messageToText,
-- * Handy error message operator
(?!)
) where
import Happstack.Server
import Control.Monad.Except
import Data.Monoid
import qualified Happstack.Server.Internal.Monads as Happstack.Internal
import qualified Data.Text.Lazy as Text
import qualified Data.Text.Lazy.Encoding as Text
-- | The \"oh noes?!\" operator
--
(?!) :: Maybe a -> e -> Either e a
ma ?! e = maybe (Left e) Right ma
-- | A derivative of the 'ServerPartT' monad with an extra error monad layer.
--
-- So we can use the standard 'MonadError' methods like 'throwError'.
--
type ServerPartE a = ServerPartT (ExceptT ErrorResponse IO) a
-- | A type for generic error reporting that should be sufficient for
-- most purposes.
--
data ErrorResponse = ErrorResponse {
errorCode :: Int,
errorHeaders:: [(String, String)],
errorTitle :: String,
errorDetail :: [MessageSpan]
}
-- | Generic error; see comments for Monoid instance, below.
| GenericErrorResponse
deriving (Eq, Show)
-- | Monoid instance for ErrorResponse
--
-- This is required for the MonadPlus instance. We report the first non-generic
-- error we find.
--
-- TODO: It would be nicer to avoid the Monoid instance completely, but it
-- seems that's rather tricky with the way Happstack is set up.
instance Monoid ErrorResponse where
mempty = ErrorResponse 500 [] "Internal server error" []
GenericErrorResponse `mappend` b = b
a `mappend` _ = a
instance ToMessage ErrorResponse where
toResponse (ErrorResponse code hdrs title detail) =
let rspbody = title ++ ": " ++ messageToText detail ++ "\n"
in Response {
rsCode = code,
rsHeaders = mkHeaders (("Content-Type", "text/plain") : reverse hdrs),
rsFlags = nullRsFlags { rsfLength = ContentLength },
rsBody = Text.encodeUtf8 (Text.pack rspbody),
rsValidator = Nothing
}
toResponse GenericErrorResponse = toResponse internalServerErrorResponse
-- | Error response into a "Internal server error"
--
-- This is useful for code that needs to pattern match on ErrorResponse;
-- in the case for GenericErrorResponse.
internalServerErrorResponse :: ErrorResponse
internalServerErrorResponse = ErrorResponse 500 [] "Internal server error" []
-- | A message possibly including hypertext links.
--
-- The point is to be able to render error messages either as text or as html.
--
data MessageSpan = MLink String String | MText String
deriving (Eq, Show)
-- | Format a message as simple text.
--
-- For html or other formats you'll have to write your own function!
--
messageToText :: [MessageSpan] -> String
messageToText [] = ""
messageToText (MLink x _:xs) = x ++ messageToText xs
messageToText (MText x :xs) = x ++ messageToText xs
errBadRequest :: String -> [MessageSpan] -> ServerPartE a
errBadRequest title message = throwError (ErrorResponse 400 [] title message)
-- note: errUnauthorized is deliberately not provided because exceptions thrown
-- in this way bypass the FilterMonad stuff and so setHeaderM etc are ignored
-- but setHeaderM are usually needed for responding to auth errors.
errForbidden :: String -> [MessageSpan] -> ServerPartE a
errForbidden title message = throwError (ErrorResponse 403 [] title message)
errNotFound :: String -> [MessageSpan] -> ServerPartE a
errNotFound title message = throwError (ErrorResponse 404 [] title message)
errBadMediaType :: String -> [MessageSpan] -> ServerPartE a
errBadMediaType title message = throwError (ErrorResponse 415 [] title message)
errInternalError :: [MessageSpan] -> ServerPartE a
errInternalError message = throwError (ErrorResponse 500 [] title message)
where
title = "Internal server error"
-- | Run a 'ServerPartE', including a top-level fallback error handler.
--
-- Any 'ErrorResponse' exceptions are turned into a simple error response with
-- a \"text/plain\" formated body.
--
-- To use a nicer custom formatted error response, use 'handleErrorResponse'.
--
runServerPartE :: ServerPartE a -> ServerPart a
runServerPartE = mapServerPartT' (spUnwrapExceptT fallbackHandler)
where
fallbackHandler :: ErrorResponse -> ServerPart a
fallbackHandler err = finishWith (toResponse err)
handleErrorResponse :: (ErrorResponse -> ServerPartE Response)
-> ServerPartE a -> ServerPartE a
handleErrorResponse handler action =
catchError action (\errResp -> handler errResp >>= finishWith)
{-------------------------------------------------------------------------------
Happstack Auxiliary
-------------------------------------------------------------------------------}
-- | This is a direct adoptation of 'spUnwrapErrorT' but for 'ExceptT'
spUnwrapExceptT :: Monad m => (e -> ServerPartT m a)
-> Request
-> UnWebT (ExceptT e m) a
-> UnWebT m a
spUnwrapExceptT handler rq = \x -> do
err <- runExceptT x
case err of
Right a -> return a
Left e -> Happstack.Internal.ununWebT $
Happstack.Internal.runServerPartT (handler e) rq
|
ocharles/hackage-server
|
Distribution/Server/Framework/Error.hs
|
bsd-3-clause
| 5,947 | 0 | 14 | 1,237 | 1,082 | 603 | 479 | 82 | 2 |
module PackageTests.BuildDeps.TargetSpecificDeps3.Check where
import Test.Tasty.HUnit
import PackageTests.PackageTester
import System.FilePath
import Data.List
import qualified Control.Exception as E
import Text.Regex.Posix
suite :: SuiteConfig -> Assertion
suite config = do
let spec = PackageSpec
{ directory = "PackageTests" </> "BuildDeps" </> "TargetSpecificDeps3"
, configOpts = []
, distPref = Nothing
}
result <- cabal_build config spec
do
assertEqual "cabal build should fail - see test-log.txt" False (successful result)
assertBool "error should be in lemon.hs" $
"lemon.hs:" `isInfixOf` outputText result
assertBool "error should be \"Could not find module `System.Time\"" $
(intercalate " " $ lines $ outputText result)
=~ "Could not find module.*System.Time"
`E.catch` \exc -> do
putStrLn $ "Cabal result was "++show result
E.throwIO (exc :: E.SomeException)
|
trskop/cabal
|
Cabal/tests/PackageTests/BuildDeps/TargetSpecificDeps3/Check.hs
|
bsd-3-clause
| 1,017 | 0 | 15 | 259 | 223 | 118 | 105 | 24 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Data.ByteString (ByteString)
import qualified Data.HashMap.Strict as HM
import Data.Maybe (fromMaybe)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Network.HTTP.Client (defaultManagerSettings, newManager)
import Network.HTTP.ReverseProxy (ProxyDest (..),
WaiProxyResponse (..), defaultOnExc,
waiProxyTo)
import Network.HTTP.Types (status404)
import Network.Wai (requestHeaderHost, responseLBS)
import Network.Wai.Handler.Warp (run)
import System.Environment (getArgs, getEnv)
import Text.Read (readMaybe)
toPair :: String -> IO (ByteString, ProxyDest)
toPair s = maybe (error $ "Invalid argument: " ++ s) return $ do
(vhost, '=':rest) <- Just $ break (== '=') s
let (host, rest') =
case break (== ':') rest of
(x, ':':y) -> (toBS x, y)
_ -> ("localhost", rest)
port <- readMaybe rest'
return (toBS vhost, ProxyDest host port)
where
toBS = T.encodeUtf8 . T.pack
main :: IO ()
main = do
sport <- getEnv "PORT"
port <-
case readMaybe sport of
Nothing -> error $ "Invalid port: " ++ sport
Just port -> return port
args <- getArgs
pairs <- mapM toPair args
manager <- newManager defaultManagerSettings
let vhosts = HM.fromList pairs
dispatch req = return $ fromMaybe defRes $ do
vhost <- requestHeaderHost req
fmap WPRProxyDest $ HM.lookup vhost vhosts
defRes = WPRResponse $ responseLBS status404 [] "Host not found"
app = waiProxyTo dispatch defaultOnExc manager
run port app
|
snoyberg/warp-vhost
|
src/Main.hs
|
mit
| 1,936 | 0 | 15 | 672 | 536 | 287 | 249 | 43 | 2 |
{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
-- | Square representation
module Scrabble.Board.Square
(
Bonus(..)
, Square(..)
, debugSquare
, emptySquare
, showSquare
, taken
, toWord
) where
import Data.Aeson (ToJSON, FromJSON)
import GHC.Generics
import Scrabble.Bag
import Scrabble.Board.Point
import qualified Data.Maybe as Maybe
data Bonus = W3 | W2 | L3 | L2 | Star | NoBonus
deriving (Eq, Ord, Generic, ToJSON, FromJSON)
instance Show Bonus where
show W3 = "3W"
show W2 = "2W"
show L3 = "3L"
show L2 = "2L"
show Star = " *"
show NoBonus = " "
data Square = Square {
tile :: Maybe Tile,
bonus :: Bonus,
squarePos :: Point
} deriving (Eq, Ord, Generic)
instance Show Square where
show = showSquare True
emptySquare :: Square -> Bool
emptySquare (Square Nothing _ _) = True
emptySquare _ = False
taken :: Square -> Bool
taken = not . emptySquare
showSquare :: Bool -> Square -> String
showSquare printBonus (Square mt b _) =
maybe (if printBonus then show b else " ") (\t -> ' ' : show (letter t)) mt
debugSquare :: Square -> String
debugSquare (Square mt b p) = concat
["Square {tile: ", show mt, ", bonus: ", show b, ", pos: ", show p]
toWord :: [Square] -> [Letter]
toWord sqrs = letter <$> Maybe.catMaybes (tile <$> sqrs)
|
joshcough/Scrabble
|
src/Scrabble/Board/Square.hs
|
mit
| 1,354 | 0 | 11 | 341 | 463 | 258 | 205 | 44 | 2 |
module TC where
import AST
import Data.List
-- import Control.Monad.State
-- import Control.Monad.Trans.Except
type TCEnv = [(Var, Ty)]
data TCState = TCSt
{ tcEnv :: TCEnv, tcFreeLinVars :: [Var] }
deriving (Show)
isUnlimitedType :: Ty -> Bool
isUnlimitedType (TyQual Linear _) = False
isUnlimitedType _ = True
-- Consume a linear variable
consume :: Var -> TCState -> TCState
consume tv st =
let env' = filter (\(n, _) -> n /= tv) (tcEnv st) in
st { tcEnv = env' }
-- Check if contexts are equivalent
equivContexts :: TCEnv -> TCEnv -> Bool
equivContexts e1 e2 = e1 \\ e2 == []
-- Check if lin var lists are equivalent
equivVars :: [Var] -> [Var] -> Bool
equivVars vs1 vs2 = vs1 \\ vs2 == []
equivState :: TCState -> TCState -> Bool
equivState s1 s2 =
equivContexts (tcEnv s1) (tcEnv s2) &&
equivVars (tcFreeLinVars s1) (tcFreeLinVars s2)
-- Context Difference Operation
-- Set difference on the env against a list of tyvars
-- with the caveat that we *cannot* try and remove a linear variable.
contextDiff :: TCEnv -> [Var] -> TCEnv
contextDiff e1 [] = e1
contextDiff e1 e2 = foldr (\x acc -> removeVar x acc) e1 e2
where removeVar :: Var -> TCEnv -> TCEnv
removeVar _ [] = []
removeVar v ((n, t) : xs)
| v == n =
if isUnlimitedType t then xs
else error $ "Linear type " ++ v ++ " in context diff operation"
| otherwise = (n, t) : (removeVar v xs)
contextUpdate :: TCEnv -> (Var, Ty) -> TCEnv
contextUpdate env (v, t)
| isUnlimitedType t =
case lookup v env of
Just ty ->
if t == ty then env
else error $ "Trying to add duplicate entry with different type for var " ++ (show v)
Nothing ->
(v, t) : env
| otherwise = error $ "Trying to add linear variable " ++ (show v) ++ " in context update."
updateEnv :: TCState -> TCEnv -> TCState
updateEnv st env = st { tcEnv = env }
type TC a = TCState -> a
-- Duality function on types. Partial!
tyDual :: Ty -> Ty
tyDual (TyQual q pt) = TyQual q (preTyDual pt)
where preTyDual :: Pretype -> Pretype
preTyDual (TyRecv t1 t2) = TySend t1 (tyDual t2)
preTyDual (TySend t1 t2) = TyRecv t1 (tyDual t2)
preTyDual (TySelect xs) = TyBranch (map (\ (l, t) -> (l, (tyDual t))) xs)
preTyDual (TyBranch xs) = TySelect (map (\ (l, t) -> (l, (tyDual t))) xs)
tyDual TyEnd = TyEnd
tyDual t = error $ "Duality undefined for type " ++ (show t)
typeCheckVal :: Value -> TC (Ty, TCState)
typeCheckVal (VBool _) st = (TyBool, st)
typeCheckVal (Variable name) st =
case lookup name (tcEnv st) of
Just ty ->
if isUnlimitedType ty then
(ty, st)
else
(ty, (consume name st))
Nothing -> error $ "Unbound type variable " ++ name
typeCheck :: Process -> TC TCState
typeCheck Inaction st = st
typeCheck (Par p1 p2) st =
-- TC process 1, retrieve resulting state
let st' = typeCheck p1 st in
-- Perform context diff, checking to see we're not trying to nuke any free
-- linear variables
let diffSt = st { tcEnv = (contextDiff (tcEnv st') (tcFreeLinVars st')) } in
typeCheck p2 diffSt
typeCheck (If v p1 p2) st =
let (t, st') = typeCheckVal v st in
-- Conditional can only be predicated on a bool
if t /= TyBool then
error "Non-bool conditional."
else
-- Now, we need to type check each process, ensuring that they result in
-- equivalent states
let (s1, s2) = ((typeCheck p1 st), (typeCheck p2 st)) in
if equivState s1 s2 then s1
else error $ "Branches of conditional with different contexts"
-- Scope restriction: takes 2 channel names, one must have type T and the other
-- must have the dual of this.
-- We TC the process P assuming x is of type T and y is of type ~T, and then
-- the context difference operation ensures that
typeCheck (ScopeRestriction (Ch x) (Ch y) t p) st =
-- Check whether we can type P with (Gamma, c1 : T, c2 : ~T)
let st' = st { tcEnv = (x, t) : (y, tyDual t) : (tcEnv st) } in
let st'' = typeCheck p st' in
-- Finally, context diff to ensure we've got no nasty linear vars left over
st'' { tcEnv = contextDiff (tcEnv st') [x, y],
tcFreeLinVars = (tcFreeLinVars st') \\ [x, y] }
typeCheck t@(Output (Ch x) v p) st =
-- Three stages:
-- * Check that we can type x as a send pretype
-- * Check that the value we're sending is of the right type
-- * Context update on x, TC continuation
let (ty, st') = typeCheckVal (Variable x) st in
case ty of
TyQual q (TySend outTy contTy) ->
-- Now TC value against outTy
let (vTy, st'') = typeCheckVal v st' in
if vTy /= outTy then
error $ "Type mismatch when type checking output. Expected type "
++ (show outTy) ++ ", got " ++ (show vTy)
else
-- Now, finally, context update on st'' with x of type contTy and
-- TC continuation p: this gets us our final environment.
-- After this, we need to update the free linear variables list
-- if x is linear.
let env' = contextUpdate (tcEnv st'') (x, contTy) in
let st''' = typeCheck p (updateEnv st'' env') in
-- Now, update the linear free vars:
let lvs = if q == Linear then x : (tcFreeLinVars st''') else tcFreeLinVars st''' in
st''' { tcFreeLinVars = lvs }
badTy ->
error $ "Expected send type when typing " ++ (show t) ++ ", got "
++ (show badTy)
typeCheck t@(Input q (Ch x) v p) st =
-- Once again, three stages:
-- * Check that we can type x as a receive pretype
-- * Assuming y of type T, ctx update x of type contTy, try and type cont P
-- * If input qualifier is unrestricted, free linear vars in L should be empty
let (ty, st') = typeCheckVal (Variable x) st in
case ty of
TyQual q2 (TyRecv inTy contTy) ->
-- Typing P is a tad more complicated: we add y : T to the context (y being the
-- name of the variable to be bound by the recv), then do context update of
-- x : U (x being channel name, U being cont type) on this new environment.
let env = contextUpdate ((v, inTy) : (tcEnv st')) (v, inTy) in
-- Output:
-- * Context: Context diff with y
-- * LinVars: Set difference with y, but if q2 is linear then add x to L
let env' = contextDiff env [v] in
let linAdditions = if q2 == Linear then [x] else [] in
let linVars = linAdditions ++ ((tcFreeLinVars st') \\ [v]) in
let st'' = TCSt env' linVars in
-- Finally, we check to see that if qualifier q is unlimited, that the free
-- linear var set is empty.
if q == Unlimited then
if null (tcFreeLinVars st') then
st''
else error $ "Error in input: linear quantifier but unconsumed linear variables"
else st''
badTy ->
error $ "Expected recv type when typing " ++ (show t) ++ ", got "
++ (show badTy)
|
SimonJF/session-type-checker
|
TC.hs
|
mit
| 6,880 | 0 | 24 | 1,832 | 1,960 | 1,037 | 923 | 113 | 10 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
import System.Environment (getArgs)
import Network.Wai.Middleware.Static as S
import Network.Wai.Middleware.RequestLogger (logStdoutDev)
import Web.Scotty
import Network.MPD (MPD)
import qualified Network.MPD as MPD
import Control.Monad
import Control.Monad.IO.Class
-- import Control.Monad
import Data.String
import qualified Data.Text.Lazy as T
import Control.Periodically
import Control.Sound
import Data.Config
import Data.Song
import Data.Status
import Data.Control
import Data.Functor
main :: IO ()
main = do
args <- getArgs
some <- readFromFile (head args)
config <- case some of
Right config -> return config
Left string -> fail string
MPD.withMPD $ do
MPD.clear
MPD.add "local:track:startup.mp3"
MPD.play Nothing
every (refreshTime config * 1000) $ setupMPD config
scotty (port config) $ do
middleware $ S.staticPolicy (S.noDots >-> S.addBase "public")
middleware logStdoutDev
get "/" $ file "public/index.html"
get "/api/playlist" $
liftMPD playlist >>= handle >>= json
put "/api/playlist" $ do
song <- jsonData
let mpl = maxPlaylistLength config
handle =<< liftMPD (do
status <- MPD.status
if MPD.stPlaylistLength status >= mpl then
fail "Could not add song"
else addSong song)
text "OK"
get "/api/status" $
liftMPD vagnstatus >>= handle >>= json
get "/api/song" $ do
(query, rest) <- parseParams <$> params
songs <- toPlaylist <$> (handle =<< liftMPD (MPD.search query))
let limit = case lookup "limit" rest of
Just x -> case parseParam x of
Right x -> x
Left msg -> 10
Nothing -> 10
json $ take limit songs
put "/api/control" $ do
(x :: Control) <- jsonData
liftMPD $ control x
text "OK"
setupMPD :: Config -> IO ()
setupMPD config = do
x <- MPD.withMPD $ do
-- Always consume
MPD.consume True
-- Get status
status <- MPD.status
liftIO $ print (MPD.stTime status)
-- If almost empty, refill
when (almostEmpty (refreshTime config - 5) status) $ do
song <- addRandomSong
liftIO $ do
putStr "Added "
print song
let mpl = maxPlaylistLength config
-- If too long crop it
when (MPD.stPlaylistLength status > mpl) $
cropPlaylist (fromIntegral mpl)
-- If not playling, start playing
case MPD.stState status of
MPD.Playing -> return ()
otherwise -> void $ MPD.play Nothing
case x of
Right x -> return ()
Left err -> print err
liftMPD :: MPD a -> ActionM (MPD.Response a)
liftMPD x = liftIO . MPD.withMPD $ x
raiseShowable :: Show a => a -> ActionM b
raiseShowable err = raise . T.pack $ show err
handle :: MPD.Response a -> ActionM a
handle response =
case response of
Right value -> return value
Left err -> raiseShowable err
parseParams :: [Param] -> (MPD.Query, [Param])
parseParams = foldl parseQueryParam (MPD.anything, [])
parseQueryParam :: (MPD.Query, [Param]) -> Param -> (MPD.Query, [Param])
parseQueryParam (a, ps) ("title", title) =
(a MPD.<&> MPD.Title MPD.=? toValue title, ps)
parseQueryParam (a, ps) ("artist", artist) =
(a MPD.<&> MPD.Artist MPD.=? toValue artist, ps)
parseQueryParam (a, ps) p = (a, p:ps)
toValue :: T.Text -> MPD.Value
toValue = fromString . T.unpack
|
kalhauge/vagnplayer
|
src/Main.hs
|
mit
| 3,720 | 0 | 22 | 1,126 | 1,194 | 586 | 608 | 100 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.