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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
-- Copyright 2020 Google LLC
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE ForeignFunctionInterface #-}
module CLib2 where
foreign import ccall clib2 :: IO Int
| google/hrepl | hrepl/tests/CLib2.hs | apache-2.0 | 688 | 0 | 6 | 116 | 31 | 24 | 7 | 3 | 0 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QAbstractSpinBox.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:36
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Enums.Gui.QAbstractSpinBox (
StepEnabledFlag, StepEnabled, eStepNone, fStepNone, eStepUpEnabled, fStepUpEnabled, eStepDownEnabled, fStepDownEnabled
, ButtonSymbols, eUpDownArrows, ePlusMinus, eNoButtons
, CorrectionMode, eCorrectToPreviousValue, eCorrectToNearestValue
)
where
import Foreign.C.Types
import Qtc.Classes.Base
import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr)
import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int)
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
data CStepEnabledFlag a = CStepEnabledFlag a
type StepEnabledFlag = QEnum(CStepEnabledFlag Int)
ieStepEnabledFlag :: Int -> StepEnabledFlag
ieStepEnabledFlag x = QEnum (CStepEnabledFlag x)
instance QEnumC (CStepEnabledFlag Int) where
qEnum_toInt (QEnum (CStepEnabledFlag x)) = x
qEnum_fromInt x = QEnum (CStepEnabledFlag x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> StepEnabledFlag -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
data CStepEnabled a = CStepEnabled a
type StepEnabled = QFlags(CStepEnabled Int)
ifStepEnabled :: Int -> StepEnabled
ifStepEnabled x = QFlags (CStepEnabled x)
instance QFlagsC (CStepEnabled Int) where
qFlags_toInt (QFlags (CStepEnabled x)) = x
qFlags_fromInt x = QFlags (CStepEnabled x)
withQFlagsResult x
= do
ti <- x
return $ qFlags_fromInt $ fromIntegral ti
withQFlagsListResult x
= do
til <- x
return $ map qFlags_fromInt til
instance Qcs (QObject c -> StepEnabled -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qFlags_fromInt hint)
return ()
eStepNone :: StepEnabledFlag
eStepNone
= ieStepEnabledFlag $ 0
eStepUpEnabled :: StepEnabledFlag
eStepUpEnabled
= ieStepEnabledFlag $ 1
eStepDownEnabled :: StepEnabledFlag
eStepDownEnabled
= ieStepEnabledFlag $ 2
fStepNone :: StepEnabled
fStepNone
= ifStepEnabled $ 0
fStepUpEnabled :: StepEnabled
fStepUpEnabled
= ifStepEnabled $ 1
fStepDownEnabled :: StepEnabled
fStepDownEnabled
= ifStepEnabled $ 2
data CButtonSymbols a = CButtonSymbols a
type ButtonSymbols = QEnum(CButtonSymbols Int)
ieButtonSymbols :: Int -> ButtonSymbols
ieButtonSymbols x = QEnum (CButtonSymbols x)
instance QEnumC (CButtonSymbols Int) where
qEnum_toInt (QEnum (CButtonSymbols x)) = x
qEnum_fromInt x = QEnum (CButtonSymbols x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> ButtonSymbols -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
eUpDownArrows :: ButtonSymbols
eUpDownArrows
= ieButtonSymbols $ 0
ePlusMinus :: ButtonSymbols
ePlusMinus
= ieButtonSymbols $ 1
eNoButtons :: ButtonSymbols
eNoButtons
= ieButtonSymbols $ 2
data CCorrectionMode a = CCorrectionMode a
type CorrectionMode = QEnum(CCorrectionMode Int)
ieCorrectionMode :: Int -> CorrectionMode
ieCorrectionMode x = QEnum (CCorrectionMode x)
instance QEnumC (CCorrectionMode Int) where
qEnum_toInt (QEnum (CCorrectionMode x)) = x
qEnum_fromInt x = QEnum (CCorrectionMode x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> CorrectionMode -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
eCorrectToPreviousValue :: CorrectionMode
eCorrectToPreviousValue
= ieCorrectionMode $ 0
eCorrectToNearestValue :: CorrectionMode
eCorrectToNearestValue
= ieCorrectionMode $ 1
| keera-studios/hsQt | Qtc/Enums/Gui/QAbstractSpinBox.hs | bsd-2-clause | 7,971 | 0 | 18 | 1,812 | 2,203 | 1,086 | 1,117 | 192 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE Rank2Types #-}
module EFA.Data.Vector where
import qualified Data.Vector.Unboxed as UV
import qualified Data.Vector as V
import qualified Data.List as List
import qualified Data.List.HT as ListHT
import qualified Data.List.Match as Match
import qualified Data.Set as Set
import qualified Data.NonEmpty as NonEmpty
import qualified Data.Foldable as Fold
import Data.Functor (Functor)
import Data.Tuple.HT (mapFst)
import Data.Maybe.HT (toMaybe)
import Data.Ord (Ordering, (>=), (<=), (<), (>))
import Data.Eq (Eq((==)))
import Data.Function ((.), ($), id, flip)
import Data.Maybe (Maybe(Just, Nothing), maybe, isJust, fromMaybe)
import Data.Bool (Bool(False, True), (&&), not)
import Data.Tuple (snd, fst)
import Text.Show (Show, show)
import Prelude (Num, Int, Integer, Ord, error, (++), (+), (-), subtract, min, max, fmap, succ)
{- |
We could replace this by suitable:Suitable.
-}
class Storage vector y where
data Constraints vector y :: *
constraints :: vector y -> Constraints vector y
instance Storage [] y where
data Constraints [] y = ListConstraints
constraints _ = ListConstraints
instance Storage V.Vector y where
data Constraints V.Vector y = VectorConstraints
constraints _ = VectorConstraints
instance (UV.Unbox y) => Storage UV.Vector y where
data Constraints UV.Vector y = UV.Unbox y => UnboxedVectorConstraints
constraints _ = UnboxedVectorConstraints
readUnbox ::
(UV.Unbox a => UV.Vector a -> b) ->
(Storage UV.Vector a => UV.Vector a -> b)
readUnbox f x = case constraints x of UnboxedVectorConstraints -> f x
writeUnbox ::
(UV.Unbox a => UV.Vector a) ->
(Storage UV.Vector a => UV.Vector a)
writeUnbox x =
let z = case constraints z of UnboxedVectorConstraints -> x
in z
instance (Storage v y) => Storage (NonEmpty.T v) y where
data Constraints (NonEmpty.T v) y = (Storage v y) => NonEmptyConstraints
constraints _ = NonEmptyConstraints
readNonEmpty ::
(Storage v a => NonEmpty.T v a -> b) ->
(Storage (NonEmpty.T v) a => NonEmpty.T v a -> b)
readNonEmpty f x = case constraints x of NonEmptyConstraints -> f x
writeNonEmpty ::
(Storage v a => NonEmpty.T v a) ->
(Storage (NonEmpty.T v) a => NonEmpty.T v a)
writeNonEmpty x =
let z = case constraints z of NonEmptyConstraints -> x
in z
--------------------------------------------------------------
-- Singleton Class
{-
{-# DEPRECATED head, tail "use viewL instead" #-}
{-# DEPRECATED last, init "use viewR instead" #-}
-}
class Singleton vec where
maximum :: (Ord d, Storage vec d) => vec d -> d
minimum :: (Ord d, Storage vec d) => vec d -> d
minmax :: (Ord d, Storage vec d) => vec d -> (d, d)
singleton :: (Storage vec d) => d -> vec d
empty :: (Storage vec d) => vec d
append :: (Storage vec d) => vec d -> vec d -> vec d
concat :: (Storage vec d) => [vec d] -> vec d
head :: (Storage vec d) => vec d -> d
tail :: (Storage vec d) => vec d -> vec d
last :: (Storage vec d) => vec d -> d
init :: (Storage vec d) => vec d -> vec d
viewL :: (Storage vec d) => vec d -> Maybe (d, vec d)
viewR :: (Storage vec d) => vec d -> Maybe (vec d, d)
all :: (Storage vec d) => (d -> Bool) -> vec d -> Bool
any :: (Storage vec d) => (d -> Bool) -> vec d -> Bool
_minmaxSemiStrict :: (Ord d) => (d, d) -> d -> (d, d)
_minmaxSemiStrict acc@(mini, maxi) x =
let mn = x >= mini
mx = x <= maxi
in if mn && mx
then acc
else if not mn
then (x, maxi)
else (mini, x)
minmaxStrict :: (Ord d) => (d, d) -> d -> (d, d)
minmaxStrict (mini, maxi) x =
case (x < mini, x > maxi) of
(False, False) -> (mini, maxi)
(True, False) -> (x, maxi)
(False, True) -> (mini, x)
(True, True) -> error "minmax: lower bound larger than upper bound"
-- space leak
_minmaxLazy :: (Ord d) => (d, d) -> d -> (d, d)
_minmaxLazy (a, b) x = (a `min` x, b `max` x)
instance Singleton V.Vector where
maximum x = V.maximum x
minimum x = V.minimum x
minmax xs = V.foldl' minmaxStrict (y, y) ys
where (y, ys) =
fromMaybe (error "Signal.Vector.minmax: empty UV-Vector") (viewL xs)
singleton x = V.singleton x
empty = V.empty
append = (V.++)
concat = V.concat
head = V.head
tail = V.tail
last = V.last
init = V.init
viewL xs = toMaybe (not $ V.null xs) (V.head xs, V.tail xs)
viewR xs = toMaybe (not $ V.null xs) (V.init xs, V.last xs)
all = V.all
any = V.any
instance Singleton UV.Vector where
maximum x = readUnbox UV.maximum x
minimum x = readUnbox UV.minimum x
minmax =
readUnbox $
\xs ->
let (y, ys) =
fromMaybe (error "Signal.Vector.minmax: empty UV-Vector") (viewL xs)
in UV.foldl' minmaxStrict (y, y) ys
singleton x = writeUnbox (UV.singleton x)
empty = writeUnbox UV.empty
append = readUnbox (UV.++)
concat xs = writeUnbox (UV.concat xs)
head = readUnbox UV.head
tail = readUnbox UV.tail
last = readUnbox UV.last
init = readUnbox UV.init
viewL = readUnbox (\xs -> toMaybe (not $ UV.null xs) (UV.head xs, UV.tail xs))
viewR = readUnbox (\xs -> toMaybe (not $ UV.null xs) (UV.init xs, UV.last xs))
all f = readUnbox (UV.all f)
any f = readUnbox (UV.any f)
instance Singleton [] where
maximum x = List.maximum x
minimum x = List.minimum x
minmax (x:xs) = List.foldl' minmaxStrict (x, x) xs
minmax [] = error "Signal.Vector.minmax: empty list"
singleton x = [x]
empty = []
append = (++)
concat = List.concat
head = List.head
tail = List.tail
last = List.last
init = List.init
viewL = ListHT.viewL
viewR = ListHT.viewR
all = List.all
any = List.any
------------------------------------------------------------
-- | Functor
class Walker vec where
map :: (Storage vec a, Storage vec b) => (a -> b) -> vec a -> vec b
imap :: (Storage vec a, Storage vec b) => (Int -> a -> b) -> vec a -> vec b
foldr :: (Storage vec a) => (a -> b -> b) -> b -> vec a -> b
foldl :: (Storage vec a) => (b -> a -> b) -> b -> vec a -> b
{- |
For fully defined values it holds
@equalBy f xs ys == (and (zipWith f xs ys) && length xs == length ys)@
but for lists @equalBy@ is lazier.
-}
equalBy :: (Storage vec a, Storage vec b) => (a -> b -> Bool) -> vec a -> vec b -> Bool
instance Walker [] where
map = List.map
imap f = List.zipWith f [0..]
foldr = List.foldr
foldl = List.foldl'
equalBy f =
let go (x:xs) (y:ys) = f x y && go xs ys
go [] [] = True
go _ _ = False
in go
instance Walker UV.Vector where
map f xs = writeUnbox (readUnbox (UV.map f) xs)
imap f xs = writeUnbox (readUnbox (UV.imap f) xs)
foldr f a = readUnbox (UV.foldr f a)
foldl f a = readUnbox (UV.foldl' f a)
equalBy f =
readUnbox (\xs ->
readUnbox (\ys ->
UV.length xs == UV.length ys && UV.and (UV.zipWith f xs ys)))
instance Walker V.Vector where
map = V.map
imap = V.imap
foldr = V.foldr
foldl = V.foldl'
equalBy f xs ys =
V.length xs == V.length ys && V.and (V.zipWith f xs ys)
------------------------------------------------------------
-- | Zipper
class Zipper vec where
zipWith ::
(Storage vec a, Storage vec b, Storage vec c) =>
(a -> b -> c) -> vec a -> vec b -> vec c
zip ::
(Zipper vec, Storage vec a, Storage vec b, Storage vec (a,b)) =>
vec a -> vec b -> vec (a, b)
zip = zipWith (,)
instance Zipper [] where
zipWith f x y = List.zipWith f x y -- if V.lenCheck x y then zipWith f x y else error "Error in V.lenCheck List -- unequal Length"
instance Zipper V.Vector where
zipWith f x y = V.zipWith f x y -- if V.lenCheck x y then V.zipWith f x y else error "Error in V.lenCheck V -- unequal Length"
instance Zipper UV.Vector where
zipWith f xs ys = writeUnbox (readUnbox (readUnbox (UV.zipWith f) xs) ys)
-- if V.lenCheck x y then UV.zipWith f x y else error "Error in V.lenCheck UV -- unequal Length"
instance Zipper (NonEmpty.T vec) where
zipWith f xs ys = writeNonEmpty $ zipWith f (readNonEmpty id xs) (readNonEmpty id ys)
deltaMap ::
(Storage vec b, Storage vec c, Singleton vec, Zipper vec) =>
(b -> b -> c) -> vec b -> vec c
deltaMap f l = maybe empty (zipWith f l . snd) $ viewL l
------------------------------------------------------------
-- | Zipper4
class Zipper4 vec where
zipWith4 ::
(Storage vec a, Storage vec b, Storage vec c, Storage vec d, Storage vec e) =>
(a -> b -> c -> d -> e) -> vec a -> vec b -> vec c -> vec d -> vec e
instance Zipper4 [] where
zipWith4 f w x y z = List.zipWith4 f w x y z -- if V.lenCheck x y then zipWith f x y else error "Error in V.lenCheck List -- unequal Length"
instance Zipper4 V.Vector where
zipWith4 f w x y z = V.zipWith4 f w x y z -- if V.lenCheck x y then V.zipWith f x y else error "Error in V.lenCheck V -- unequal Length"
instance Zipper4 UV.Vector where
zipWith4 f w x y z =
writeUnbox (readUnbox (readUnbox (readUnbox (readUnbox (UV.zipWith4 f) w) x) y) z) -- if V.lenCheck x y then UV.zipWith f x y else error "Error in V.lenCheck UV -- unequal Length"
{-
deltaMap2:: (a -> a -> b -> b -> c) -> vec a -> vec a -> vec b -> vec b -> vec c
deltaMap2 f xs ys = zipWith4 f xs (tail xs) ys (tail ys)
deltaMapReverse2 :: (a -> a -> b -> b -> c) -> vec a -> vec a -> vec b -> vec b -> vec c
deltaMapReverse2 f xs ys = zipWith4 f (tail xs) xs (tail ys) ys
-}
--------------------------------------------------------------
-- Vector conversion
class Convert c1 c2 where
convert :: (Storage c1 a, Storage c2 a) => c1 a -> c2 a
instance Convert UV.Vector V.Vector where
convert x = readUnbox UV.convert x
instance Convert V.Vector UV.Vector where
convert x = writeUnbox (V.convert x)
instance Convert UV.Vector UV.Vector where
convert = id
instance Convert V.Vector V.Vector where
convert = id
instance Convert [] [] where
convert = id
instance Convert [] UV.Vector where
convert x = writeUnbox (UV.fromList x)
instance Convert [] V.Vector where
convert x = V.fromList x
instance Convert V.Vector [] where
convert x = V.toList x
instance Convert UV.Vector [] where
convert x = readUnbox UV.toList x
--------------------------------------------------------------
-- Length & Length Check
class Len s where
len :: s -> Int
instance Len [d] where
len = List.length
instance Len (V.Vector d) where
len = V.length
instance UV.Unbox d => Len (UV.Vector d) where
len = UV.length
lenCheck ::
(Len v1, Len v2) =>
v1 -> v2 -> Bool
lenCheck x y = len x == len y
class Length vec where
length :: Storage vec a => vec a -> Int
instance Length v => Length (NonEmpty.T v) where
length = readNonEmpty $ succ . length . NonEmpty.tail
instance Length [] where
length = List.length
instance Length V.Vector where
length = V.length
instance Length UV.Vector where
length = readUnbox UV.length
type family Core (v :: * -> *) :: * -> *
type instance Core (NonEmpty.T f) = Core f
type instance Core [] = []
type instance Core V.Vector = V.Vector
type instance Core UV.Vector = UV.Vector
data Remainder v a b =
RemainderLeft (NonEmpty.T v a)
| NoRemainder
| RemainderRight (NonEmpty.T v b)
class DiffLength v where
diffLength ::
(Storage v a, Storage (Core v) a,
Storage v b, Storage (Core v) b) =>
v a -> v b -> Remainder (Core v) a b
instance DiffLength v => DiffLength (NonEmpty.T v) where
diffLength =
readNonEmpty $ \(NonEmpty.Cons _ as) ->
readNonEmpty $ \(NonEmpty.Cons _ bs) ->
diffLength as bs
--------------------------------------------------------------
-- Transpose Class
class Transpose v1 v2 where
transpose :: (Storage v1 d) => v2 (v1 d) -> v2 (v1 d)
instance Transpose [] [] where
transpose x = if List.all (== List.head lens) lens then List.transpose x else error "Error in V.Transpose -- unequal length"
where lens = map len x
instance Transpose V.Vector V.Vector where
transpose xs = if all (== len0) lens then V.map (flip V.map xs) fs else error "Error in V.Transpose -- unequal length"
where fs = V.map (flip (V.!)) $ V.fromList [0..len0-1]
lens = V.map len xs
len0 = V.head lens
instance Transpose UV.Vector V.Vector where
transpose xs =
case constraints $ fst $ maybe (error("Error in EFA.Signal.Vector/transpose - empty head")) id $ viewL xs of
UnboxedVectorConstraints ->
let fs = V.map (flip (UV.!)) $ V.fromList [0..len0-1]
lens = V.map len xs
len0 = V.head lens
in if all (== len0) lens
then V.map (convert . flip V.map xs) fs
else error "Error in V.Transpose -- unequal length"
class FromList vec where
fromList :: (Storage vec d) => [d] -> vec d
toList :: (Storage vec d) => vec d -> [d]
instance FromList [] where
fromList x = x
toList x = x
instance FromList V.Vector where
fromList = V.fromList
toList = V.toList
instance FromList UV.Vector where
fromList x = writeUnbox (UV.fromList x)
toList x = readUnbox UV.toList x
class Sort vec where
sort :: (Ord d, Storage vec d) => vec d -> vec d
instance Sort [] where
sort = List.sort
instance Sort V.Vector where
sort = V.fromList . List.sort . V.toList
instance Sort UV.Vector where
sort = readUnbox (UV.fromList . List.sort . UV.toList)
class SortBy vec where
sortBy :: (Storage vec d) => (d -> d -> Ordering) -> vec d -> vec d
instance SortBy [] where
sortBy f = List.sortBy f
instance SortBy V.Vector where
sortBy f = V.fromList . (List.sortBy f) . V.toList
instance SortBy UV.Vector where
sortBy f = readUnbox (UV.fromList . (List.sortBy f) . UV.toList)
class Filter vec where
filter :: Storage vec d => (d -> Bool) -> vec d -> vec d
instance Filter [] where
filter = List.filter
instance Filter V.Vector where
filter = V.filter
instance Filter UV.Vector where
filter f = readUnbox (UV.filter f)
{-
An according function in the vector library would save us from the 'error'
and from the duplicate computation of 'f'
(or alternatively from storing a Maybe in a vector).
-}
mapMaybe ::
(Walker vec, Filter vec, Storage vec a, Storage vec b) =>
(a -> Maybe b) -> vec a -> vec b
mapMaybe f =
map
(\a ->
case f a of
Just b -> b
Nothing -> error "mapMaybe: filter has passed a Nothing") .
filter (isJust . f)
class Lookup vec where
lookUp :: (Storage vec d, Eq d) => vec d -> [Int] -> vec d
instance Lookup [] where
lookUp xs = lookUpGen (V.fromList xs V.!? )
instance Lookup V.Vector where
lookUp xs = V.fromList . lookUpGen (xs V.!?)
instance Lookup UV.Vector where
lookUp =
readUnbox (\xs -> UV.fromList . lookUpGen (xs UV.!?))
{-# INLINE lookUpGen #-}
lookUpGen :: Show i => (i -> Maybe a) -> [i] -> [a]
lookUpGen look idxs =
case ListHT.partitionMaybe look idxs of
(ys, []) -> ys
(_, invalidIdxs) ->
error $ "lookUpGen: indices out of Range: " ++ show invalidIdxs
++ "\nAll indices: " ++ show idxs
class LookupMaybe vec d where
lookupMaybe :: vec d -> Int -> Maybe d
instance LookupMaybe [] d where
lookupMaybe xs idx = if idx >=0 && idx <= (length xs)
then Just $ xs List.!! idx
else Nothing
instance LookupMaybe V.Vector d where
lookupMaybe xs idx = xs V.!? idx
instance UV.Unbox d => LookupMaybe UV.Vector d where
lookupMaybe xs idx = xs UV.!? idx
class LookupUnsafe vec d where
lookupUnsafe :: vec d -> Int -> d
instance UV.Unbox d => LookupUnsafe UV.Vector d where
lookupUnsafe xs idx = xs UV.! idx
instance LookupUnsafe V.Vector d where
lookupUnsafe xs idx = xs V.! idx
instance LookupUnsafe [] d where
lookupUnsafe xs idx = xs List.!! idx
class Reverse v where
reverse :: (Storage v d) => v d -> v d
instance Reverse [] where
reverse = List.reverse
instance Reverse V.Vector where
reverse = V.reverse
instance Reverse UV.Vector where
reverse = readUnbox UV.reverse
class Find v where
findIndex :: (Storage v d) => (d -> Bool) -> v d -> Maybe Int
findIndices :: (Storage v d) => (d -> Bool) -> v d -> v Int
instance Find [] where
findIndex x = List.findIndex x
findIndices x = List.findIndices x
instance Find V.Vector where
findIndex x = V.findIndex x
findIndices x = V.findIndices x
instance Find UV.Vector where
findIndex f xs = readUnbox (UV.findIndex f) xs
findIndices f xs = readUnbox (UV.findIndices f) xs
class Slice v where
slice :: (Storage v d) => Int -> Int -> v d -> v d
instance Slice [] where
slice start num = List.take num . List.drop start
instance Slice V.Vector where
slice = V.slice
instance Slice UV.Vector where
slice start num = readUnbox (UV.slice start num)
class Split v where
drop, take :: (Storage v d) => Int -> v d -> v d
splitAt :: (Storage v d) => Int -> v d -> (v d, v d)
instance Split [] where
drop = List.drop
take = List.take
splitAt = List.splitAt
instance Split V.Vector where
drop = V.drop
take = V.take
splitAt = V.splitAt
instance Split UV.Vector where
drop k = readUnbox (UV.drop k)
take k = readUnbox (UV.take k)
splitAt k = readUnbox (UV.splitAt k)
class SplitMatch v where
dropMatch :: (Storage v b, Storage v d, Storage (Core v) d) => v b -> v d -> Core v d
takeMatch :: (Storage v b, Storage v d) => v b -> v d -> v d
splitAtMatch :: (Storage v b, Storage v d) => v b -> v d -> (v d, Core v d)
instance SplitMatch v => SplitMatch (NonEmpty.T v) where
dropMatch =
readNonEmpty $ \(NonEmpty.Cons _ xs) ->
readNonEmpty $ \(NonEmpty.Cons _ ys) ->
dropMatch xs ys
takeMatch =
readNonEmpty $ \(NonEmpty.Cons _ xs) ->
readNonEmpty $ \(NonEmpty.Cons y ys) ->
NonEmpty.Cons y $ takeMatch xs ys
splitAtMatch =
readNonEmpty $ \(NonEmpty.Cons _ xs) ->
readNonEmpty $ \(NonEmpty.Cons y ys) ->
mapFst (NonEmpty.Cons y) $ splitAtMatch xs ys
instance SplitMatch [] where
dropMatch = Match.drop
takeMatch = Match.take
splitAtMatch = Match.splitAt
instance SplitMatch V.Vector where
dropMatch = drop . length
takeMatch = take . length
splitAtMatch = splitAt . length
instance SplitMatch UV.Vector where
dropMatch = drop . length
takeMatch = take . length
splitAtMatch = splitAt . length
cumulate :: (Num a) => NonEmpty.T [] a -> [a] -> [a]
cumulate storage =
NonEmpty.tail . NonEmpty.scanl (+) (NonEmpty.last storage)
decumulate :: (Num a) => NonEmpty.T [] a -> [a] -> [a]
decumulate inStorage outStorage =
ListHT.mapAdjacent subtract $ NonEmpty.last inStorage : outStorage
propCumulate :: NonEmpty.T [] Integer -> [Integer] -> Bool
propCumulate storage incoming =
decumulate storage (cumulate storage incoming) == incoming
-- | creates a vector of unique and sorted elements
class Unique v d where
unique :: Ord d => v d -> v d
instance Unique [] d where
unique = Set.toList . Set.fromList
instance Unique V.Vector d where
unique = fromList . Set.toList . Set.fromList . toList
instance (UV.Unbox d) => Unique UV.Vector d where
unique = readUnbox (fromList . Set.toList . Set.fromList . toList)
{-
might be moved to non-empty package
-}
argMaximumKey ::
(Fold.Foldable f, Ord b) =>
(a -> b) -> NonEmpty.T f a -> (Int, a)
argMaximumKey f (NonEmpty.Cons x xs) =
snd $ snd $
Fold.foldl
(\(pos, (maxMeas, (maxPos, maxVal))) xi ->
(succ pos,
let fx = f xi
in if fx>maxMeas
then (fx, (pos,xi))
else (maxMeas, (maxPos,maxVal))))
(1, (f x, (0,x))) xs
argMaximum ::
(Fold.Foldable f, Ord a) =>
NonEmpty.T f a -> (Int, a)
argMaximum = argMaximumKey id
{-
The Functor constraint could be saved
by merging the fmap with the fold.
'f' is evaluated twice for every sub-maximum.
Does this hurt?
-}
argMaximumKey2 ::
(Functor f, Fold.Foldable f, Fold.Foldable g, Ord b) =>
(a -> b) ->
NonEmpty.T f (NonEmpty.T g a) -> ((Int, Int), a)
argMaximumKey2 f =
(\(n,(m,a)) -> ((n,m), a)) .
argMaximumKey (f . snd) .
fmap (argMaximumKey f)
argMaximum2 ::
(Functor f, Fold.Foldable f, Fold.Foldable g, Ord a) =>
NonEmpty.T f (NonEmpty.T g a) -> ((Int, Int), a)
argMaximum2 = argMaximumKey2 id
| energyflowanalysis/efa-2.1 | src/EFA/Data/Vector.hs | bsd-3-clause | 20,581 | 0 | 17 | 5,027 | 8,019 | 4,165 | 3,854 | 494 | 4 |
module Auto.Score
(
BitString
, bitStringToNum
, mutateBitString
, crossBitString
, numToBitString
, makeIndividual
, makePopulation
, flipBitAt
)
where
import Data.Array
import System.Random
-- type ScoreType = Double
-- class Score a where
-- score :: a -> ScoreType
type BitString = Array Int Bool
-- Make a bitstring of size i.
makeBitString :: Int -> BitString
makeBitString i = array (0,i-1) [(j,False) | j <- [0..i-1]]
-- Convert bitstring to number.
bitStringToNum :: BitString -> Int
bitStringToNum arr = go $ assocs arr
where go [] = 0
go ((_,False):xs) = go xs
go ((i,True):xs) = (2^i) + (go xs)
-- Flip bit at i in bitstring.
mutateBitString :: BitString -> Int -> BitString
mutateBitString arr i = arr // [(i,b)]
where b = not $ arr ! i
-- Crossover bitstrings arr1 and arr2.
crossBitString :: BitString -> BitString -> Int -> BitString
crossBitString arr1 arr2 i = array s l
where s = bounds arr1
l = zipWith f (assocs arr1) (assocs arr2)
f (i1,v1) (_,v2)
| (i1 < i) = (i1,v1)
| otherwise = (i1,v2)
-- Convert int to list of 0s and 1s.
numToBits :: Int -> [Int]
numToBits 0 = []
numToBits y = let (a,b) = quotRem y 2 in [b] ++ numToBits a
-- Make bitstring of number i and length s.
numToBitString :: Int -> Int -> BitString
numToBitString i s = makeBitString s // str
where str = zip [0..] $ map (== 1) $ numToBits i
makeIndividual :: Int -> Int -> StdGen -> Array Int BitString
makeIndividual bits params g = listArray (0,params-1) strings
where nums = take params $ randomRs (0, 2 ^ bits - 1) g
strings = map (flip numToBitString bits) nums
makePopulation :: Int -> Int -> Int -> StdGen -> [Array Int BitString]
makePopulation 0 _ _ _ = []
makePopulation popSize bits params g = ind : restPop
where (g',g'') = split g
restPop = makePopulation (popSize-1) bits params g''
ind = makeIndividual bits params g'
flipBitAt :: Int -> Int -> Array Int BitString -> Array Int BitString
flipBitAt b p bstr = bstr // [(p,ind)]
where ind = mutateBitString (bstr ! p) b
| iu-parfunc/AutoObsidian | src/Auto/Score.hs | bsd-3-clause | 2,161 | 0 | 11 | 551 | 801 | 428 | 373 | 49 | 3 |
{-# LANGUAGE CPP #-}
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702
{-# LANGUAGE Trustworthy #-}
#endif
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.Trans.Either
-- Copyright : (C) 2008-2014 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : provisional
-- Portability : MPTCs
--
-- This module provides a minimalist 'Either' monad transformer.
-----------------------------------------------------------------------------
module Control.Monad.Trans.Either
( EitherT(..)
, eitherT
, bimapEitherT
, mapEitherT
, hoistEither
, left
, right
) where
import Control.Applicative
import Control.Monad (liftM, MonadPlus(..))
import Control.Monad.Base (MonadBase(..), liftBaseDefault)
import Control.Monad.Cont.Class
import Control.Monad.Error.Class
import Control.Monad.Free.Class
import Control.Monad.Catch as MonadCatch
import Control.Monad.Fix
import Control.Monad.IO.Class
import Control.Monad.Reader.Class
import Control.Monad.State (MonadState,get,put)
import Control.Monad.Trans.Class
import Control.Monad.Trans.Control (MonadBaseControl(..), MonadTransControl(..), defaultLiftBaseWith, defaultRestoreM)
import Control.Monad.Writer.Class
import Control.Monad.Random (MonadRandom,getRandom,getRandoms,getRandomR,getRandomRs)
import Data.Foldable
import Data.Function (on)
import Data.Functor.Bind
import Data.Functor.Plus
import Data.Traversable
import Data.Semigroup
-- | 'EitherT' is a version of 'Control.Monad.Trans.Error.ErrorT' that does not
-- require a spurious 'Control.Monad.Error.Class.Error' instance for the 'Left'
-- case.
--
-- 'Either' is a perfectly usable 'Monad' without such a constraint. 'ErrorT' is
-- not the generalization of the current 'Either' monad, it is something else.
--
-- This is necessary for both theoretical and practical reasons. For instance an
-- apomorphism is the generalized anamorphism for this Monad, but it cannot be
-- written with 'ErrorT'.
--
-- In addition to the combinators here, the @errors@ package provides a large
-- number of combinators for working with this type.
newtype EitherT e m a = EitherT { runEitherT :: m (Either e a) }
instance Show (m (Either e a)) => Show (EitherT e m a) where
showsPrec d (EitherT m) = showParen (d > 10) $
showString "EitherT " . showsPrec 11 m
{-# INLINE showsPrec #-}
instance Read (m (Either e a)) => Read (EitherT e m a) where
readsPrec d = readParen (d > 10)
(\r' -> [ (EitherT m, t)
| ("EitherT", s) <- lex r'
, (m, t) <- readsPrec 11 s])
{-# INLINE readsPrec #-}
instance Eq (m (Either e a)) => Eq (EitherT e m a) where
(==) = (==) `on` runEitherT
{-# INLINE (==) #-}
instance Ord (m (Either e a)) => Ord (EitherT e m a) where
compare = compare `on` runEitherT
{-# INLINE compare #-}
-- | Given a pair of actions, one to perform in case of failure, and one to perform
-- in case of success, run an 'EitherT' and get back a monadic result.
eitherT :: Monad m => (a -> m c) -> (b -> m c) -> EitherT a m b -> m c
eitherT f g (EitherT m) = m >>= \z -> case z of
Left a -> f a
Right b -> g b
{-# INLINE eitherT #-}
-- | Analogous to 'Left'. Equivalent to 'throwError'.
left :: Monad m => e -> EitherT e m a
left = EitherT . return . Left
{-# INLINE left #-}
-- | Analogous to 'Right'. Equivalent to 'return'.
right :: Monad m => a -> EitherT e m a
right = return
{-# INLINE right #-}
-- | Map over both failure and success.
bimapEitherT :: Functor m => (e -> f) -> (a -> b) -> EitherT e m a -> EitherT f m b
bimapEitherT f g (EitherT m) = EitherT (fmap h m) where
h (Left e) = Left (f e)
h (Right a) = Right (g a)
{-# INLINE bimapEitherT #-}
-- | Map the unwrapped computation using the given function.
--
-- @
-- 'runEitherT' ('mapEitherT' f m) = f ('runEitherT' m)
-- @
mapEitherT :: (m (Either e a) -> n (Either e' b)) -> EitherT e m a -> EitherT e' n b
mapEitherT f m = EitherT $ f (runEitherT m)
{-# INLINE mapEitherT #-}
-- | Lift an 'Either' into an 'EitherT'
hoistEither :: Monad m => Either e a -> EitherT e m a
hoistEither = EitherT . return
{-# INLINE hoistEither #-}
instance Monad m => Functor (EitherT e m) where
fmap f = EitherT . liftM (fmap f) . runEitherT
{-# INLINE fmap #-}
instance Monad m => Apply (EitherT e m) where
EitherT f <.> EitherT v = EitherT $ f >>= \mf -> case mf of
Left e -> return (Left e)
Right k -> v >>= \mv -> case mv of
Left e -> return (Left e)
Right x -> return (Right (k x))
{-# INLINE (<.>) #-}
instance Monad m => Applicative (EitherT e m) where
pure a = EitherT $ return (Right a)
{-# INLINE pure #-}
EitherT f <*> EitherT v = EitherT $ f >>= \mf -> case mf of
Left e -> return (Left e)
Right k -> v >>= \mv -> case mv of
Left e -> return (Left e)
Right x -> return (Right (k x))
{-# INLINE (<*>) #-}
instance (Monad m, Monoid e) => Alternative (EitherT e m) where
EitherT m <|> EitherT n = EitherT $ m >>= \a -> case a of
Left l -> liftM (\b -> case b of
Left l' -> Left (mappend l l')
Right r -> Right r) n
Right r -> return (Right r)
{-# INLINE (<|>) #-}
empty = EitherT $ return (Left mempty)
{-# INLINE empty #-}
instance (Monad m, Monoid e) => MonadPlus (EitherT e m) where
mplus = (<|>)
{-# INLINE mplus #-}
mzero = empty
{-# INLINE mzero #-}
instance Monad m => Semigroup (EitherT e m a) where
EitherT m <> EitherT n = EitherT $ m >>= \a -> case a of
Left _ -> n
Right r -> return (Right r)
{-# INLINE (<>) #-}
instance (Monad m, Semigroup e) => Alt (EitherT e m) where
EitherT m <!> EitherT n = EitherT $ m >>= \a -> case a of
Left l -> liftM (\b -> case b of
Left l' -> Left (l <> l')
Right r -> Right r) n
Right r -> return (Right r)
{-# INLINE (<!>) #-}
instance Monad m => Bind (EitherT e m) where
(>>-) = (>>=)
{-# INLINE (>>-) #-}
instance Monad m => Monad (EitherT e m) where
return a = EitherT $ return (Right a)
{-# INLINE return #-}
m >>= k = EitherT $ do
a <- runEitherT m
case a of
Left l -> return (Left l)
Right r -> runEitherT (k r)
{-# INLINE (>>=) #-}
fail = EitherT . fail
{-# INLINE fail #-}
instance Monad m => MonadError e (EitherT e m) where
throwError = EitherT . return . Left
{-# INLINE throwError #-}
EitherT m `catchError` h = EitherT $ m >>= \a -> case a of
Left l -> runEitherT (h l)
Right r -> return (Right r)
{-# INLINE catchError #-}
-- | Throws exceptions into the base monad.
instance MonadThrow m => MonadThrow (EitherT e m) where
throwM = lift . throwM
{-# INLINE throwM #-}
-- | Catches exceptions from the base monad.
instance MonadCatch m => MonadCatch (EitherT e m) where
catch (EitherT m) f = EitherT $ MonadCatch.catch m (runEitherT . f)
{-# INLINE catch #-}
instance MonadFix m => MonadFix (EitherT e m) where
mfix f = EitherT $ mfix $ \a -> runEitherT $ f $ case a of
Right r -> r
_ -> error "empty mfix argument"
{-# INLINE mfix #-}
instance MonadTrans (EitherT e) where
lift = EitherT . liftM Right
{-# INLINE lift #-}
instance MonadIO m => MonadIO (EitherT e m) where
liftIO = lift . liftIO
{-# INLINE liftIO #-}
instance MonadCont m => MonadCont (EitherT e m) where
callCC f = EitherT $
callCC $ \c ->
runEitherT (f (\a -> EitherT $ c (Right a)))
{-# INLINE callCC #-}
instance MonadReader r m => MonadReader r (EitherT e m) where
ask = lift ask
{-# INLINE ask #-}
local f (EitherT m) = EitherT (local f m)
{-# INLINE local #-}
instance MonadState s m => MonadState s (EitherT e m) where
get = lift get
{-# INLINE get #-}
put = lift . put
{-# INLINE put #-}
instance MonadWriter s m => MonadWriter s (EitherT e m) where
tell = lift . tell
{-# INLINE tell #-}
listen = mapEitherT $ \ m -> do
(a, w) <- listen m
return $! fmap (\ r -> (r, w)) a
{-# INLINE listen #-}
pass = mapEitherT $ \ m -> pass $ do
a <- m
return $! case a of
Left l -> (Left l, id)
Right (r, f) -> (Right r, f)
{-# INLINE pass #-}
instance MonadRandom m => MonadRandom (EitherT e m) where
getRandom = lift getRandom
{-# INLINE getRandom #-}
getRandoms = lift getRandoms
{-# INLINE getRandoms #-}
getRandomR = lift . getRandomR
{-# INLINE getRandomR #-}
getRandomRs = lift . getRandomRs
{-# INLINE getRandomRs #-}
instance Foldable m => Foldable (EitherT e m) where
foldMap f = foldMap (either mempty f) . runEitherT
{-# INLINE foldMap #-}
instance (Functor f, MonadFree f m) => MonadFree f (EitherT e m) where
wrap = EitherT . wrap . fmap runEitherT
instance (Monad f, Traversable f) => Traversable (EitherT e f) where
traverse f (EitherT a) =
EitherT <$> traverse (either (pure . Left) (fmap Right . f)) a
{-# INLINE traverse #-}
instance MonadBase b m => MonadBase b (EitherT e m) where
liftBase = liftBaseDefault
{-# INLINE liftBase #-}
instance MonadTransControl (EitherT e) where
newtype StT (EitherT e) a = StEitherT {unStEitherT :: Either e a}
liftWith f = EitherT $ liftM return $ f $ liftM StEitherT . runEitherT
{-# INLINE liftWith #-}
restoreT = EitherT . liftM unStEitherT
{-# INLINE restoreT #-}
instance MonadBaseControl b m => MonadBaseControl b (EitherT e m) where
newtype StM (EitherT e m) a = StMEitherT { unStMEitherT :: StM m (StT (EitherT e) a) }
liftBaseWith = defaultLiftBaseWith StMEitherT
{-# INLINE liftBaseWith #-}
restoreM = defaultRestoreM unStMEitherT
{-# INLINE restoreM #-}
| phaazon/either | src/Control/Monad/Trans/Either.hs | bsd-3-clause | 9,810 | 0 | 20 | 2,184 | 3,134 | 1,640 | 1,494 | 218 | 2 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
-- import Data.Char (isPunctuation, isSpace)
-- import Data.List (intercalate)
-- import Data.Monoid (mappend)
import Data.Text (Text)
import qualified Data.Map.Strict as Map
import Control.Exception (finally)
import Control.Monad (forM_, forever)
import Control.Concurrent (MVar, newMVar, modifyMVar_, modifyMVar, readMVar)
import Control.Monad.IO.Class (liftIO)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import System.Environment (lookupEnv)
import Data.Maybe (fromMaybe, fromJust)
import Data.List (intercalate)
import qualified Network.WebSockets as WS
import System.Random (randomIO)
import Warships.BattleField
import Warships.Generator (brandNewField)
type PlayerID = Int
instance Show WS.Connection where
show _ = "Connection"
data Player
= Player
{ connection :: !WS.Connection
, field :: !BattleField
} deriving Show
type GameID = Int
data ServerState
= ServerState
{ players :: !(Map.Map PlayerID Player)
} deriving Show
-- | All messages that server can `broadcast` to players.
data OutputMessage
-- | Returns when a user searches for a game with specific ID, but it can't be found.
= NotFoundGameID
-- | Found game already has two players.
| NoFreeSlots
-- | User joined a game and received their ID.
| PlayerID PlayerID
| Own BattleField
| Enemy BattleField
deriving Eq
instance Show OutputMessage where
show NotFoundGameID = "NotFoundGameID"
show NoFreeSlots = "NoFreeSlots"
show (PlayerID pID) = "PlayerID " ++ show pID
show (Own bf) = "Own " ++ displayOwnField bf
show (Enemy bf) = "Enemy " ++ displayEnemysField bf
-- | All messages that server accepts.
data IntputMessage
-- | User joins an existing game.
= JoinGame PlayerID
-- | User attacks enemy's field.
| Attack
deriving (Read, Show, Eq)
getEnvWithDefault :: String -> String -> IO String
getEnvWithDefault name defaultValue = do
x <- lookupEnv name
return $ fromMaybe defaultValue x
newServerState :: ServerState
newServerState = ServerState Map.empty
addClient :: PlayerID -> Player -> ServerState -> ServerState
addClient pID player state
= state { players = Map.insert pID player (players state) }
removeClient :: PlayerID -> ServerState -> ServerState
removeClient pID s = s { players = Map.delete pID (players s) }
broadcast :: Text -> ServerState -> IO ()
broadcast message ServerState{..} = do
T.putStrLn message
forM_ (map connection $ Map.elems players) (`WS.sendTextData` message)
main :: IO ()
main = do
state <- newMVar newServerState
port <- read <$> getEnvWithDefault "PORT" "3636" :: IO Int
host <- getEnvWithDefault "HOST" "0.0.0.0"
putStrLn ("Running server on " ++ host ++ ":" ++ show port)
WS.runServer host port $ application state
application :: MVar ServerState -> WS.ServerApp
application state pending = do
client <- WS.acceptRequest pending
pID <- abs <$> randomIO
WS.forkPingThread client 30
msg <- WS.receiveData client :: IO T.Text
let disconnect = modifyMVar_ state $ \s -> return (removeClient pID s)
flip finally disconnect $ do
liftIO $ modifyMVar_ state $ \s -> do
field <- brandNewField
return (addClient pID (Player client field) s)
s <- readMVar state
print s
broadcastPlayer s pID
talk pID client state
broadcastM :: OutputMessage -> WS.Connection -> IO ()
broadcastM msg conn = do
T.putStrLn (T.pack (show msg))
WS.sendTextData conn (T.pack (show msg))
broadcastPlayer :: ServerState -> PlayerID -> IO ()
broadcastPlayer ServerState{..} pID =
case Map.lookup pID players of
Just Player{..} -> do
broadcastM (PlayerID pID) connection
broadcastM (Own field) connection
Nothing -> return ()
talk :: PlayerID -> WS.Connection -> MVar ServerState -> IO ()
talk pID conn state = forever $ do
msg <- T.unpack <$> WS.receiveData conn :: IO String
s' <- readMVar state
print msg
print s'
case read msg of
-- NewGame -> do
-- gameID <- randomIO
-- modifyMVar_ state $ \s -> return $ s { games = Map.insert gameID () (games s) }
-- broadcastMessage (NewGameID gameID) s'
JoinGame gID ->
case Map.lookup gID (players s') of
Just (Player c f) -> do
broadcastM (Enemy f) conn
broadcastM (Enemy (field $ fromJust $ Map.lookup pID (players s'))) c
Nothing ->
broadcastM NotFoundGameID conn
-- Attack -> do
-- let f' = attack (read msg) (field s')
-- if gameComplete f'
-- then do
-- f'' <- brandNewField
-- modifyMVar_ state $ \s -> return $ s { field = f'' }
-- else
-- modifyMVar_ state $ \s -> return $ s { field = f' }
-- liftIO $ readMVar state >>= broadcastField
-- gameComplete :: BattleField -> Bool
-- gameComplete = all (==0) . Map.elems . ships
-- broadcastField :: ServerState -> IO ()
-- broadcastField state@ServerState{..} =
-- broadcast (displayField field) state
displayOwnField :: BattleField -> String
displayOwnField = displayField "H"
displayEnemysField :: BattleField -> String
displayEnemysField = displayField "E"
displayField :: String -> BattleField -> String
displayField hiddenShip bf = intercalate "" [ intercalate "" [ sc $ getCell (x, y) bf | y <- [0..height bf - 1] ] | x <- [0..width bf - 1] ]
where
sc Empty = "E"
sc Miss = "M"
sc (Ship Hidden _) = hiddenShip
sc (Ship Injured _) = "I"
sc (Ship Killed _) = "K"
| triplepointfive/battleship | app/Main.hs | bsd-3-clause | 5,602 | 0 | 23 | 1,277 | 1,530 | 782 | 748 | 126 | 5 |
module Day1 where
import Data.List (findIndex, inits)
-- slower than a foldr (does 2 passes over input), but more readable/declarative
floorCount :: String -> Int
floorCount input = ups - downs
where ups = charCount '(' input
downs = charCount ')' input
charCount c = length . filter (== c)
floorCount2 :: String -> Int
floorCount2 = foldr ((+) . parenvals) 0
where parenvals '(' = 1
parenvals ')' = -1
parenvals _ = 0
hitBasement :: String -> Maybe Int
hitBasement input = findIndex (< 0) trip
where trip = map floorCount $ inits input
solution :: String -> IO ()
solution input = do
print $ floorCount input -- part 1
print $ hitBasement input -- part 2
| yarbroughw/advent | src/Day1.hs | bsd-3-clause | 706 | 0 | 9 | 170 | 226 | 118 | 108 | 19 | 3 |
{-# LANGUAGE TypeFamilies #-}
module Language.Shelspel.Codegen.Bash where
import Language.Shelspel.AST
import Language.Shelspel.Codegen.Types
import Control.Monad
codegen :: Program -> String
codegen prog = script
where bash = flip execState empty $ cgen prog
script = foldl (++) "" $ reverse bash
type Bash = [String]
empty :: Bash
empty = []
type instance S = Bash
type instance R = ()
-- --------------------------------------------------------------------------------
-- | Weave two actions through the code generator. The first is called
-- on each element, then the second action is executed.
weave :: (a -> State S R) -> State S R -> [a] -> State S R
weave f a = mapM_ (\x -> f x >> a)
-- | Weave a call to 'cgen' over each list.
--
-- This can be used, eg, to to intercalate semicolons or newlines:
-- > nl `cgweave` program
-- > semic `cgweave` program
cgweave :: CGen x => State S R -> [x] -> State S R
cgweave = weave cgen
-- | Insert an element into the stream
stream :: String -> State S R
stream s = modify (s:)
-- | Insert a newline (\n) into the stream
nl :: State S R
nl = stream "\n"
-- | Call the element as a subprocess. E.g.
--
-- > $(echo "hello world")
subproc :: CGen x => x -> State S R
subproc x = do
stream "$("
cgen x
stream ")"
-- | Evaluate the expression as a mathematical expression
--
-- > $(( 40 + 2 ))
math :: Expr -> State S R
math e = do
stream "$(("
stream " "
cgen e
stream " "
stream "))"
-- | Insert a semicolon (;)
semic :: State S R
semic = stream ";"
-- -------------------------------------------------------------------------------- --
instance CGen Expr where
cgen (Literal s) = stream $ "\"" ++ s ++ "\""
cgen (Var i) = stream $ "${" ++ i ++ "}"
cgen (BinOp o x y) =
do
stream "$(( "
cgen x
stream " "
cgen o
stream " "
cgen y
stream " ))"
instance CGen Op where
cgen Add = stream "+"
cgen Sub = stream "-"
cgen Mul = stream "*"
cgen Div = stream "/"
cgen (Compare o) = cgen o
instance CGen Ordering where
cgen LT = stream "-lt"
cgen EQ = stream "-eq"
cgen GT = stream "-gt"
instance CGen CompoundStatement where
cgen (Match e ms) =
do
stream "case "
cgen e
stream " in"
nl
forM_ ms $ \(m, as) -> do
cgen m
stream ")"
nl
nl `cgweave` as
nl
semic >> semic
cgen (For i a cs) =
do
stream "for "
stream i
stream " in "
subproc a
semic
stream "do"
nl
nl `cgweave` cs
stream "done"
cgen (While a cs) =
do
stream "while"
stream " "
stream "[["
stream " "
cgen a
stream " "
stream "]]"
nl
stream "do"
nl
nl `cgweave` cs
stream "done"
instance CGen Action where
cgen (Call i as) =
do
stream i
stream " "
(stream " ") `cgweave` as
cgen (Cmpd s) = cgen s
cgen (Pipe c a) =
do
cgen c
stream " | "
cgen a
cgen (Sink a s p m) =
do
cgen a
stream " "
cgen m
stream p
stream " "
cgen s
cgen (Store i c) =
do
stream i
stream "="
subproc c
cgen (Eval e) =
do
stream "# Bare expressions are not supported: "
cgen e
cgen (Result c) = stream $ "return " ++ show c
instance CGen Mode where
cgen Write = stream ">"
cgen Append = stream ">>"
instance CGen Captured where
cgen (Captured s a) =
do
cgen a
stream " "
cgen s
instance CGen Stream where
cgen Stdout = stream ""
cgen Stderr = stream "3>&1 1>&2- 2>&3-" -- swap stderr and stdout
cgen All = stream "2>&1"
instance CGen Cmd where
cgen (Execute a) = cgen a
cgen (Funcdef i ps cs) =
do
stream "function"
stream " "
stream i
stream "()"
stream " "
stream "{"
nl
let define i n = stream "local " >> def i n
def i n = cgen $ Define n $ Literal $ "${" ++ show i ++ "}"
weave (uncurry define) nl $ zip [1..] ps
nl
nl `cgweave` cs
stream "}"
nl
cgen (Define i e) =
do
stream i
stream "="
cgen e
instance CGen Program where
cgen (Program cs) = nl `cgweave` cs
| badi/shelspel | src/Language/Shelspel/Codegen/Bash.hs | bsd-3-clause | 4,704 | 0 | 16 | 1,820 | 1,508 | 696 | 812 | 165 | 1 |
{-# LANGUAGE OverloadedStrings, ViewPatterns #-}
import Control.Exception (catch, SomeException)
import Control.Monad
import Control.Monad.Trans (liftIO)
import qualified Data.ByteString.UTF8 as B
import Data.List (isPrefixOf, sortBy)
import Data.Maybe
import Safe (readMay)
import System.Directory
import System.Environment
import System.Exit
import System.IO (withFile, IOMode(ReadWriteMode))
import System.Process
import Pygmalion.Config
import Pygmalion.Core
import Pygmalion.File
import Pygmalion.Log
import Pygmalion.Make
import Pygmalion.RPC.Client
--import Pygmalion.JSON
main :: IO ()
main = do
args <- getArgs
parseConfiglessArgs args $ do
cf <- getConfiguration
initLogger (logLevel cf)
wd <- getCurrentDirectory
parseArgs cf wd args
usage :: IO ()
usage = do
putStrLn $ "Usage: " ++ queryExecutable ++ " [command]"
putStrLn "where [command] is one of the following:"
putStrLn " help Prints this message."
putStrLn " start-server Starts the pygmalion daemon."
putStrLn " stop-server Terminates the pygmalion daemon."
putStrLn " init Initializes a pygmalion index rooted at"
putStrLn " the current directory."
putStrLn " make [command] Runs the provided command, observes the calls to"
putStrLn " compilers it makes, and indexes the compiled files."
putStrLn " index ([file]|[command]) Manually request indexing. If a single"
putStrLn " argument is provided, it's interpreted"
putStrLn " as a file to index using the default"
putStrLn " compiler flags. Multiple arguments are"
putStrLn " interpreted as a compiler invocation"
putStrLn " (e.g. 'clang -c file.c') and the compiler"
putStrLn " flags to use will be extracted appropriately."
putStrLn " wait Blocks until all previous requests have been"
putStrLn " handled by the pygmalion daemon."
putStrLn " generate-compile-commands Prints a clang compilation database."
putStrLn " compile-flags [file] Prints the compilation flags for the"
putStrLn " given file, or nothing on failure. If"
putStrLn " the file isn't in the database, a guess"
putStrLn " will be printed if possible."
putStrLn " working-directory [file] Prints the working directory at the time"
putStrLn " the file was compiled. Guesses if needed."
putStrLn " inclusions [file] Lists the files included by the given file."
putStrLn " includers [file] Lists the files which include the given file."
putStrLn " inclusion-hierarchy [file] Prints a graphviz graph showing the inclusion"
putStrLn " hierarchy of the given file."
putStrLn " definition [file] [line] [col]"
putStrLn " declaration [file] [line] [col]"
putStrLn " callers [file] [line] [col]"
putStrLn " callees [file] [line] [col]"
putStrLn " bases [file] [line] [col]"
putStrLn " overrides [file] [line] [col]"
putStrLn " members [file] [line] [col]"
putStrLn " references [file] [line] [col]"
putStrLn " hierarchy [file] [line] [col] Prints a graphviz graph showing the inheritance"
putStrLn " hierarchy of the identifier at this location."
bail
parseConfiglessArgs :: [String] -> IO () -> IO ()
parseConfiglessArgs ["init"] _ = initialize
parseConfiglessArgs ["help"] _ = usage
parseConfiglessArgs [] _ = usage
parseConfiglessArgs _ c = c
parseArgs :: Config -> FilePath -> [String] -> IO ()
parseArgs _ _ ["start-server"] = startServer
parseArgs c _ ["stop-server"] = stopServer c
parseArgs c wd ("index" : file : []) = asSourceFile wd file >>= indexFile c
parseArgs c _ ("index" : cmd : args) = indexUserCommand c cmd args
parseArgs c _ ("make" : args) = makeCommand c args
parseArgs c _ ("wait" : []) = waitForServer c
parseArgs c _ ["generate-compile-commands"] = printCDB c
parseArgs c wd ["compile-flags", f] = asSourceFile wd f >>= printFlags c
parseArgs c wd ["working-directory", f] = asSourceFile wd f >>= printDir c
parseArgs c wd ["inclusions", f] = asSourceFile wd f >>= printInclusions c
parseArgs c wd ["includers", f] = asSourceFile wd f >>= printIncluders c
parseArgs c wd ["inclusion-hierarchy", f] = asSourceFile wd f >>= printInclusionHierarchy c
parseArgs c wd ["definition", f, line, col] = do sf <- asSourceFile wd f
printDef c sf (readMay line) (readMay col)
parseArgs c wd ["declaration", f, line, col] = do sf <- asSourceFile wd f
printDecl c sf (readMay line) (readMay col)
parseArgs c wd ["callers", f, line, col] = do sf <- asSourceFile wd f
printCallers c sf (readMay line) (readMay col)
parseArgs c wd ["callees", f, line, col] = do sf <- asSourceFile wd f
printCallees c sf (readMay line) (readMay col)
parseArgs c wd ["bases", f, line, col] = do sf <- asSourceFile wd f
printBases c sf (readMay line) (readMay col)
parseArgs c wd ["overrides", f, line, col] = do sf <- asSourceFile wd f
printOverrides c sf (readMay line) (readMay col)
parseArgs c wd ["members", f, line, col] = do sf <- asSourceFile wd f
printMembers c sf (readMay line) (readMay col)
parseArgs c wd ["references", f, line, col] = do sf <- asSourceFile wd f
printRefs c sf (readMay line) (readMay col)
parseArgs c wd ["hierarchy", f, line, col] = do sf <- asSourceFile wd f
printHierarchy c sf (readMay line) (readMay col)
parseArgs _ _ _ = usage
startServer :: IO ()
startServer = void $ waitForProcess =<< runCommand "pygd"
stopServer :: Config -> IO ()
stopServer cf = withRPC cf $ runRPC rpcStop
initialize :: IO ()
initialize = do
putStrLn "Initializing a pygmalion index..."
createDirectoryIfMissing True pygmalionDir
withFile configFile ReadWriteMode (\_ -> return ())
indexFile :: Config -> SourceFile -> IO ()
indexFile cf f = do
mayMTime <- getMTime f
case mayMTime of
Just mtime -> withRPC cf $ runRPC (rpcIndexFile f mtime)
Nothing -> putStrLn $ "Couldn't read file " ++ show f
makeCommand :: Config -> [String] -> IO ()
makeCommand cf args = do
let cmd = if null args then "" else head args
args' = if null args then [] else tail args
-- Make sure pygd is running.
withRPC cf (runRPC rpcPing) `catch` handleRPCFailure
-- Observe the build process.
code <- observeMake cf cmd args'
case code of
ExitSuccess -> return ()
_ -> liftIO $ bailWith' code $ queryExecutable ++ ": Command failed"
where
handleRPCFailure :: SomeException -> IO ()
handleRPCFailure _ = putStrLn $ "Can't connect to pygd. "
++ "Build information will not be recorded."
waitForServer :: Config -> IO ()
waitForServer cf = withRPC cf $ runRPC rpcWait
-- FIXME: Reimplement with RPC.
printCDB :: Config -> IO ()
{-
printCDB = withDB $ \h -> getAllSourceFiles h >>= putStrLn . sourceRecordsToJSON
-}
printCDB = undefined
printFlags :: Config -> SourceFile -> IO ()
printFlags cf f = getCommandInfoOr bail f cf >>= putFlags
where
putFlags (ciArgs -> args) = putStrLn . unwords . map B.toString $ args
printDir :: Config -> SourceFile -> IO ()
printDir cf f = getCommandInfoOr bail f cf >>= putDir
where putDir (ciWorkingPath -> wd) = putStrLn . B.toString $ wd
getCommandInfoOr :: IO () -> SourceFile -> Config -> IO CommandInfo
getCommandInfoOr a f cf = do
cmd <- withRPC cf $ runRPC (rpcGetSimilarCommandInfo f)
unless (isJust cmd) a
return . fromJust $ cmd
printInclusions :: Config -> SourceFile -> IO ()
printInclusions cf file = do
is <- withRPC cf $ runRPC (rpcGetInclusions file)
mapM_ putInclusion (sortBy (locationOrder cf) is)
where
putInclusion sf = putStrLn $ unSourceFile sf ++ ":1:1: Inclusion of "
++ unSourceFile file
printIncluders :: Config -> SourceFile -> IO ()
printIncluders cf file = do
is <- withRPC cf $ runRPC (rpcGetIncluders file)
mapM_ putIncluder (sortBy (locationOrder cf) is)
where
putIncluder sf = putStrLn $ unSourceFile sf ++ ":1:1: Includer of "
++ unSourceFile file
locationOrder :: Config -> SourceFile -> SourceFile -> Ordering
locationOrder cf a b
| inProject a && inProject b = compare a b
| inProject a = LT
| inProject b = GT
| otherwise = compare a b
where
inProject f = projectDir cf `isPrefixOf` unSourceFile f
printInclusionHierarchy :: Config -> SourceFile -> IO ()
printInclusionHierarchy cf file = do
dotGraph <- withRPC cf $ runRPC (rpcGetInclusionHierarchy file)
case dotGraph of
[] -> putStrLn "diGraph G {}" -- Print an empty graph instead of an error.
_ -> putStrLn dotGraph
printDef :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO ()
printDef = queryCmd "definition" rpcGetDefinition putDef
where
putDef (DefInfo n _ (SourceLocation idF idLine idCol) k _) =
putStrLn $ unSourceFile idF ++ ":" ++ show idLine ++ ":" ++ show idCol ++
": Definition: " ++ B.toString n ++ " [" ++ show k ++ "]"
printDecl :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO ()
printDecl = queryCmd "declaration" rpcGetDeclReferenced putDecl
where
putDecl (DefInfo n _ (SourceLocation idF idLine idCol) k _) =
putStrLn $ unSourceFile idF ++ ":" ++ show idLine ++ ":" ++ show idCol ++
": Declaration: " ++ B.toString n ++ " [" ++ show k ++ "]"
printCallers :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO ()
printCallers = queryCmd "caller" rpcGetCallers putCaller
where
putCaller (Invocation (DefInfo n _ _ _ _) (SourceLocation idF idLine idCol)) =
putStrLn $ unSourceFile idF ++ ":" ++ show idLine ++ ":" ++ show idCol ++
": Caller: " ++ B.toString n
printCallees :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO ()
printCallees = queryCmd "callee" rpcGetCallees putCallee
where
putCallee (DefInfo n _ (SourceLocation idF idLine idCol) k _) =
putStrLn $ unSourceFile idF ++ ":" ++ show idLine ++ ":" ++ show idCol ++
": Callee: " ++ B.toString n ++ " [" ++ show k ++ "]"
printBases :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO ()
printBases = queryCmd "base" rpcGetBases putBase
where
putBase (DefInfo n _ (SourceLocation idF idLine idCol) k _) =
putStrLn $ unSourceFile idF ++ ":" ++ show idLine ++ ":" ++ show idCol ++
": Base: " ++ B.toString n ++ " [" ++ show k ++ "]"
printOverrides :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO ()
printOverrides = queryCmd "override" rpcGetOverrides putOverride
where
putOverride (DefInfo n _ (SourceLocation idF idLine idCol) k _) =
putStrLn $ unSourceFile idF ++ ":" ++ show idLine ++ ":" ++ show idCol ++
": Override: " ++ B.toString n ++ " [" ++ show k ++ "]"
printMembers :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO ()
printMembers = queryCmd "member" rpcGetMembers putMember
where
putMember (DefInfo n _ (SourceLocation idF idLine idCol) k _) =
putStrLn $ unSourceFile idF ++ ":" ++ show idLine ++ ":" ++ show idCol ++
": Member: " ++ B.toString n ++ " [" ++ show k ++ "]"
printRefs :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO ()
printRefs = queryCmd "reference" rpcGetRefs putRef
where
putRef (SourceReference (SourceLocation idF idLine idCol) k ctx) =
putStrLn $ unSourceFile idF ++ ":" ++ show idLine ++ ":" ++ show idCol ++
": Reference: " ++ B.toString ctx ++ " [" ++ show k ++ "]"
printHierarchy :: Config -> SourceFile -> Maybe Int -> Maybe Int -> IO ()
printHierarchy cf file (Just line) (Just col) = do
dotGraph <- withRPC cf $ runRPC (rpcGetHierarchy (SourceLocation file line col))
case dotGraph of
[] -> putStrLn "diGraph G {}" -- Print an empty graph instead of an error.
_ -> putStrLn dotGraph
printHierarchy _ _ _ _ = usage
queryCmd :: String -> (SourceLocation -> RPC [a]) -> (a -> IO ())
-> Config -> SourceFile -> Maybe Int -> Maybe Int -> IO ()
queryCmd item rpcCall f cf file (Just line) (Just col) = do
results <- withRPC cf $ runRPC (rpcCall (SourceLocation file line col))
case results of
[] -> bailWith (errMsg item file line col)
_ -> mapM_ f results
queryCmd _ _ _ _ _ _ _ = usage
errMsg :: String -> SourceFile -> SourceLine -> SourceCol -> String
errMsg item f line col = errPrefix ++ "No " ++ item ++ " available for an identifier at this "
++ "location. Make sure the file compiles with no errors "
++ "and the index is up-to-date."
where
errPrefix = unSourceFile f ++ ":" ++ show line ++ ":" ++ show col ++ ": "
bail :: IO ()
bail = exitWith (ExitFailure (-1))
bail' :: ExitCode -> IO ()
bail' = exitWith
bailWith :: String -> IO ()
bailWith s = putStrLn s >> bail
bailWith' :: ExitCode -> String -> IO ()
bailWith' code s = putStrLn s >> bail' code
| sethfowler/pygmalion | tools/Pygmalion.hs | bsd-3-clause | 13,828 | 0 | 17 | 3,937 | 4,083 | 1,957 | 2,126 | 241 | 4 |
-- Copyright (c) 2012-2013, Christoph Pohl BSD License (see
-- http://www.opensource.org/licenses/BSD-3-Clause)
-------------------------------------------------------------------------------
--
-- Project Euler Problem 13
--
-- The following iterative sequence is defined for the set of positive
-- integers:
--
-- n → n/2 (n is even) n → 3n + 1 (n is odd)
--
-- Using the rule above and starting with 13, we generate the following
-- sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
--
-- It can be seen that this sequence (starting at 13 and finishing at 1)
-- contains 10 terms. Although it has not been proved yet (Collatz Problem), it
-- is thought that all starting numbers finish at 1.
--
-- Which starting number, under one million, produces the longest chain?
--
-- NOTE: Once the chain starts the terms are allowed to go above one million.
module Main where
import Data.List
import Data.Maybe
main :: IO ()
main = print result
result = 1 + fromMaybe 0 (elemIndex (maximum(listOfLengths)) listOfLengths)
listOfLengths :: [Int]
listOfLengths = map collatzLength [1..1000000]
collatzLength :: Integer -> Int
collatzLength n = collatzLength' n 1
collatzLength' :: Integer -> Int -> Int
collatzLength' n acc | n == 1 = acc
| even n = collatzLength' (n `div` 2) (acc+1)
| otherwise = collatzLength' (3*n + 1) (acc+1)
| Psirus/euler | src/euler014.hs | bsd-3-clause | 1,403 | 0 | 11 | 283 | 227 | 128 | 99 | 14 | 1 |
{-# LANGUAGE CPP, MagicHash #-}
#if __GLASGOW_HASKELL__ >= 703
{-# LANGUAGE Unsafe #-}
#endif
-- |
-- Copyright : (c) 2010 Simon Meier
--
-- Original serialization code from 'Data.Binary.Builder':
-- (c) Lennart Kolmodin, Ross Patterson
--
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Simon Meier <[email protected]>
-- Portability : GHC
--
-- Utilty module defining unchecked shifts.
--
-- These functions are undefined when the amount being shifted by is
-- greater than the size in bits of a machine Int#.-
--
#if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__)
#include "MachDeps.h"
#endif
module Data.ByteString.Builder.Prim.Internal.UncheckedShifts (
shiftr_w16
, shiftr_w32
, shiftr_w64
, shiftr_w
, caseWordSize_32_64
) where
#if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__)
import GHC.Base
import GHC.Word (Word32(..),Word16(..),Word64(..))
#if WORD_SIZE_IN_BITS < 64 && __GLASGOW_HASKELL__ >= 608
import GHC.Word (uncheckedShiftRL64#)
#endif
#else
import Data.Word
#endif
import Foreign
------------------------------------------------------------------------
-- Unchecked shifts
-- | Right-shift of a 'Word16'.
{-# INLINE shiftr_w16 #-}
shiftr_w16 :: Word16 -> Int -> Word16
-- | Right-shift of a 'Word32'.
{-# INLINE shiftr_w32 #-}
shiftr_w32 :: Word32 -> Int -> Word32
-- | Right-shift of a 'Word64'.
{-# INLINE shiftr_w64 #-}
shiftr_w64 :: Word64 -> Int -> Word64
-- | Right-shift of a 'Word'.
{-# INLINE shiftr_w #-}
shiftr_w :: Word -> Int -> Word
#if WORD_SIZE_IN_BITS < 64
shiftr_w w s = fromIntegral $ (`shiftr_w32` s) $ fromIntegral w
#else
shiftr_w w s = fromIntegral $ (`shiftr_w64` s) $ fromIntegral w
#endif
#if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__)
shiftr_w16 (W16# w) (I# i) = W16# (w `uncheckedShiftRL#` i)
shiftr_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftRL#` i)
#if WORD_SIZE_IN_BITS < 64
shiftr_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftRL64#` i)
#if __GLASGOW_HASKELL__ <= 606
-- Exported by GHC.Word in GHC 6.8 and higher
foreign import ccall unsafe "stg_uncheckedShiftRL64"
uncheckedShiftRL64# :: Word64# -> Int# -> Word64#
#endif
#else
shiftr_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftRL#` i)
#endif
#else
shiftr_w16 = shiftR
shiftr_w32 = shiftR
shiftr_w64 = shiftR
#endif
-- | Select an implementation depending on the bit-size of 'Word's.
-- Currently, it produces a runtime failure if the bitsize is different.
-- This is detected by the testsuite.
{-# INLINE caseWordSize_32_64 #-}
caseWordSize_32_64 :: a -- Value to use for 32-bit 'Word's
-> a -- Value to use for 64-bit 'Word's
-> a
caseWordSize_32_64 f32 f64 =
#if MIN_VERSION_base(4,7,0)
case finiteBitSize (undefined :: Word) of
#else
case bitSize (undefined :: Word) of
#endif
32 -> f32
64 -> f64
s -> error $ "caseWordSize_32_64: unsupported Word bit-size " ++ show s
| DavidAlphaFox/ghc | libraries/bytestring/Data/ByteString/Builder/Prim/Internal/UncheckedShifts.hs | bsd-3-clause | 2,954 | 0 | 9 | 551 | 400 | 250 | 150 | 30 | 3 |
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
{-@ LIQUID "--no-termination "@-}
import Language.Haskell.Liquid.Prelude
incr x = (x, [x+1])
chk (x, [y]) = liquidAssertB (x <y)
prop = chk $ incr n
where n = choose 0
incr2 x = (True, 9, x, 'o', x+1)
chk2 (_, _, x, _, y) = liquidAssertB (x <y)
prop2 = chk2 $ incr2 n
where n = choose 0
incr3 x = (x, ( (0, x+1)))
chk3 (x, ((_, y))) = liquidAssertB (x <y)
prop3 = chk3 (incr3 n)
where n = choose 0
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/pair00.hs | bsd-3-clause | 471 | 0 | 8 | 112 | 249 | 140 | 109 | 15 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
module Plots.API
( -- * Data types and classes
PointLike
, Axis
, r2Axis
, renderAxis
, Plot
, PlotState
, PlotStateM
, R2Backend
-- * Plotable
, addPlotable
, addPlotable'
, addPlotableL
, addPlotableL'
, diagramPlot
-- ** Bounds
, xMin, xMax
, yMin, yMax
, zMin, zMax
-- ** Grid lines
, noGridLines
, addLegendEntry
-- ** Ticks
-- , ticks
-- Grid lines
-- , recentProps
, cartesianLabels
-- ** Axis labels
-- ** Axis title
-- * Legend
, addLegendEntry
-- Themes
-- , corperateTheme
-- , blackAndWhiteTheme
-- * Diagrams essentials
, (#)
, Diagram, V2 (..), V3 (..)
, SizeSpec
, lc
, fc
, fcA
-- * Optics
-- ** Basis elements
-- | These basis elements can be used to select a specific coordinate axis.
-- These can be used henever a function has a @E v@ argument.
, ex, ey, ez
-- ** Common functions
-- | These lens functions can be used to change some of the more advanced
-- aspects of the axis.
, (&)
, set, (.~)
, over, (%~)
, (&~)
, (.=), assign
, (%=), modify
-- * Axis adjustments
-- ** Axis size
-- ** Axis labels
-- *** Label text
, axisLabel
, xAxisLabel
, yAxisLabel
, zAxisLabel
, cartesianLabels
-- *** Label position
, AxisLabelPosition (..)
, axesLabelPositions
, axisLabelPosition
-- , axisPlotProperties
-- *** Label gaps
, setAxisLabelGap
, setAxesLabelGaps
-- * Axis scaling
, setAxisRatio
, equalAxis
-- ** Axis line type
, AxisLineType (..)
-- , allAxisLineType
-- , xAxisLineType
-- , yAxisLineType
-- , zAxisLineType
-- * Axis ticks
-- | Placement of major and minor ticks.
-- , noMinorTicks
-- , noMajorTicks
, module Plots.Axis.Ticks
-- * Axis Tick Labels
, module Plots.Axis.Labels
-- ** Axis Grid
, noGridLines
, noGridLine
, setMajorGridLines
, setMajorGridLine
, noMajorGridLines
, noMajorGridLine
, setMinorGridLines
, setMinorGridLine
, noMinorGridLines
, noMinorGridLine
, allGridLines
-- ** Axis Lines
, middleAxisLines
, boxAxisLines
-- ** Axis ticks
, noAxisTicks
, noMajorTicks
, noMinorTicks
, centerAxisTicks
, insideAxisTicks
-- ** Axis theme
, PlotStyle
, plotColor
, plotMarker
, axisTheme
, module Plots.Themes
-- *** Colour bar
, ColourBarOpts
, ColourMap
-- , C
, showColourBar
) where
import Control.Lens hiding (( # ))
import Control.Monad.State.Lazy
import Data.Default
import Data.Monoid.Recommend
import Data.Typeable
import Diagrams.Coordinates.Isomorphic
import Diagrams.Prelude hiding (r2)
import Diagrams.TwoD.Text
import Linear
import Plots.Axis
import Plots.Axis.Grid
import Plots.Axis.Labels
import Plots.Axis.Render
import Plots.Axis.Ticks
import Plots.Axis.ColourBar
import Plots.Types
import Plots.Themes
-- import Plots.Types.Bar
-- import Plots.Types.Surface
-- $ pointlike
-- The 'PointLike' class is used for convienience so you don't have to
-- convert whatever data type you're already using. Some common
-- instances are:
--
-- @
-- PointLike V2 Double (Double,Double)
-- PointLike V2 Double (V2 Double)
-- PointLike V3 Float (Float, Float, Float)
-- @
--
-- This means whenever you see @PointLike (BaseSpace v) n p@ in a type constaint,
-- the @p@ in the type signature could be @(Double, Double)@ or @V2
-- Double@ or anything
-- $ data
-- Since the plot making functions are super-polymorphic it is
-- important the that data has a concrete type signature or the compiler
-- won't be able to work out which type to use. The following data is
-- used thoughout the examples:
--
-- @
-- pointData1 = [(1,3), (2,5.5), (3.2, 6), (3.5, 6.1)] :: [(Double,Double)]
-- pointData2 = U.fromList [V2 1.2 2.7, V2 2 5.1, V2 3.2 2.6, V2 3.5 5] :: U.Vector (V2 Double)
-- barData1 = [55.3, 43.2, 12.5, 18.3, 32.0] :: [Double]
-- barData2 = [("apples", 55), ("oranges",43), ("pears", 12), ("mangos", 18)] :: [(String, Double)]
-- @
-- | Convienient type synonym for renderable types that all the standard
-- 2D backends support.
type R2Backend b n =
(Renderable (Path V2 n) b,
Renderable (Text n) b,
Typeable b,
TypeableFloat n,
Enum n)
-- type AxisStateM b v n = State (Axis b v n)
-- type AxisState b v n = AxisStateM b v n ()
type PlotStateM a b = State (PropertiedPlot a b)
-- | The plot state allows you to use lenses for the plot @a@ as well as
-- the @PlotProperties@.
type PlotState a b = PlotStateM a b ()
-- type PropertyStateM b v n a = State (PlotProperties b v n) a
-- type PropertyState b v n = State (PlotProperties b v n) ()
-- newtype PlotStateM p b v n = PState (State (p, PlotProperties))
-- deriving (Functor, Applicative, Monad, MonadState (P.Axis b v n))
------------------------------------------------------------------------
-- Plot properties
------------------------------------------------------------------------
-- $properties
-- Every plot has a assosiating 'PlotProperties'. These contain general
-- attributes like the legend entries and the style and the name for
-- the plot.
--
-- There are several ways to adjust the properties.
------------------------------------------------------------------------
-- Plotable
------------------------------------------------------------------------
-- $plotable
-- The 'Plotable' class defines ways of converting the data type to a
-- diagram for some axis. There are several variants for adding an axis
-- with constraints @('InSpace' v n a, 'Plotable' a b)@:
--
-- @
-- 'addPlotable' :: a -> 'AxisState' b v n
-- 'addPlotable'' :: a -> 'PlotState' a b -> 'AxisState' b v n
-- 'addPlotableL' :: 'String' -> a -> 'AxisState' b v n
-- 'addPlotableL'' :: 'String' -> a -> 'PlotState' a b -> 'AxisState' b v n
-- @
--
-- The last argument is a 'PlotState' so you can use @do@ notation to
-- make adjustments to the plot. The @L@ suffix stands for \"legend\",
-- it is equivalent of using 'addLegendEntry' in the 'PlotState'. Since
-- legend entries are so common it has it's own suffix. The following
-- are equivalent:
--
-- @
-- myaxis = 'r2Axis' &~ do
-- 'addPlotable'' myplot $ do
-- 'addLegendEntry' "my plot"
-- @
--
-- @
-- myaxis = 'r2Axis' &~ do
-- 'addPlotableL' "my plot" myplot
-- @
--
-- Most of the time you won't use these functions directly. However,
-- other plotting functions follow this naming convention where instead
-- of @a@, it takes the data needed to make the plot.
-- | Add something 'Plotable' to the axis.
-- addPlotable :: (InSpace (BaseSpace v) n a, MoPlotable a b) => a -> AxisState b v n
addPlotable :: (InSpace (BaseSpace v) n a, MonadState (Axis b v n) m, Plotable a b)
=> a -> m ()
addPlotable a = axisPlots %= flip snoc (Plot' a mempty)
-- | Add something 'Plotable' and modify the 'PlotState' of that plot.
addPlotable' :: (InSpace (BaseSpace v) n a, MonadState (Axis b v n) m, Plotable a b)
=> a -> PlotState a b -> m ()
addPlotable' a s = axisPlots <>= [Plot' a (Endo $ execState s)]
-- | Add something 'Plotable' with given legend entry.
addPlotableL :: (InSpace (BaseSpace v) n a, MonadState (Axis b v n) m, Plotable a b)
=> String -> a -> m ()
addPlotableL l a = addPlotable' a $ addLegendEntry l
-- | Add something 'Plotable' with given legend entry and modify the
-- 'PlotState' of that plot.
addPlotableL' :: (InSpace (BaseSpace v) n a, MonadState (Axis b v n) m, Plotable a b)
=> String -> a -> PlotState a b -> m ()
addPlotableL' l a s = addPlotable' a $ addLegendEntry l >> s
------------------------------------------------------------------------
-- Diagram Plot
------------------------------------------------------------------------
diagramPlot
:: (v ~ BaseSpace c,
Renderable (Path V2 n) b,
MonadState (Axis b c n) m,
Typeable b,
Typeable v,
Metric v,
TypeableFloat n)
=> QDiagram b v n Any -> m ()
diagramPlot = addPlotable
------------------------------------------------------------------------
-- Axis properties
------------------------------------------------------------------------
-- | Traversal over the axis' most recent 'PlotProperties'.
-- recentProps :: PropertyState b v n -> AxisState b v n
-- recentProps s = axisPlots . _last . _2 %= (execState s .)
-- Legend
------------
addLegendEntry :: (MonadState a m, HasPlotProperties a b, Num (N a))
=> String -> m ()
addLegendEntry s = legendEntries <>= [mkLegendEntry s]
-- axisState :: Axis b v n -> AxisStateM b v n a -> Axis b v n
-- axisState a s = execState s a
--
--
-- main = defaultMain myPlot
-- @@
--
-- @@
-- $ runHaskell myPlot.hs -o myPlot.pdf
-- @@
--
--
-- Currently @plots@ supports line, scatter, function and bar plots. Hopefully
-- more will be added soon.
--
--
-- | Standard 2D axis.
r2Axis :: R2Backend b n => Axis b V2 n
r2Axis = def
-- | Standard 2D axis.
-- r3Axis :: R2Backend b n => Axis b V3 n
-- r3Axis = def
-- | Set the label for the given axis.
--
-- @@
-- myaxis = 'r2Axis' &~ 'axisLabel' 'ex' "x-axis"
-- @@
axisLabel :: E v -> Lens' (Axis b v n) String
axisLabel (E e) = axisLabels . e . axisLabelText
-- | Lens onto the x axis label.
xAxisLabel :: R1 v => Lens' (Axis b v n) String
xAxisLabel = axisLabel ex
-- | Lens onto the y axis label.
yAxisLabel :: R2 v => Lens' (Axis b v n) String
yAxisLabel = axisLabel ey
-- | Lens onto the z axis label.
zAxisLabel :: R3 v => Lens' (Axis b v n) String
zAxisLabel = axisLabel ex
-- | Set the position of the given axis label.
axisLabelPosition :: E v -> Lens' (Axis b v n) AxisLabelPosition
axisLabelPosition (E e) = axisLabels . e . axisLabelPos
-- | Set the position of all axes labels.
axesLabelPositions :: Traversable v => Traversal' (Axis b v n) AxisLabelPosition
axesLabelPositions = axisLabels . traversed . axisLabelPos
-- | Set the gap between the axis and the axis label.
setAxisLabelGap :: E v -> Lens' (Axis b v n) n
setAxisLabelGap (E e) = axisLabels . e . axisLabelGap
-- | Set the gaps between all axes and the axis labels.
setAxesLabelGaps :: Traversable v => Traversal' (Axis b v n) n
setAxesLabelGaps = axisLabels . traverse . axisLabelGap
-- | Label the x,y and z axis with \"x\", \"y\" and \"z\" respectively.
cartesianLabels :: (Traversable v, MonadState (Axis b v n) m) => m ()
cartesianLabels =
partsOf (axisLabels . traverse . axisLabelText) .= ["x", "y", "z"]
-- | Set the aspect ratio of given axis.
setAxisRatio :: MonadState (Axis b v n) m => E v -> n -> m ()
setAxisRatio e n = axisScaling . el e . aspectRatio .= Commit n
-- | Make each axis have the same unit length.
equalAxis :: (MonadState (Axis b v n) m, Functor v, Num n) => m ()
equalAxis = axisScaling . mapped . aspectRatio .= Commit 1
------------------------------------------------------------------------
-- Grid lines
------------------------------------------------------------------------
-- | Set no major or minor grid lines for all axes.
noGridLines :: (Functor v, MonadState (Axis b v n) m) => m ()
noGridLines = noMajorGridLines >> noMinorGridLines
-- | Set no major or minor grid lines for given axes.
noGridLine :: MonadState (Axis b v n) m => E v -> m ()
noGridLine e = noMajorGridLine e >> noMinorGridLine e
-- Majors
-- | Add major grid lines for all axes.
setMajorGridLines :: (Functor v, MonadState (Axis b v n) m) => m ()
setMajorGridLines = axisGridLines . mapped . majorGridF .= tickGridF
-- | Add major grid lines for given axis.
setMajorGridLine :: MonadState (Axis b v n) m => E v -> m ()
setMajorGridLine (E e) = axisGridLines . e . majorGridF .= tickGridF
-- | Set no major grid lines for all axes.
noMajorGridLines :: (Functor v, MonadState (Axis b v n) m) => m ()
noMajorGridLines = axisGridLines . mapped . majorGridF .= noGridF
-- | Set no major grid lines for given axis.
noMajorGridLine :: MonadState (Axis b v n) m => E v -> m ()
noMajorGridLine (E l) = axisGridLines . l . majorGridF .= noGridF
-- Minors
-- | Add minor grid lines for all axes.
setMinorGridLines :: (Functor v, MonadState (Axis b v n) m) => m ()
setMinorGridLines = axisGridLines . mapped . minorGridF .= tickGridF
-- | Add minor grid lines for given axis.
setMinorGridLine :: MonadState (Axis b v n) m => E v -> m ()
setMinorGridLine (E l) = axisGridLines . l . minorGridF .= tickGridF
-- | Set no minor grid lines for all axes.
noMinorGridLines :: (Functor v, MonadState (Axis b v n) m) => m ()
noMinorGridLines = axisGridLines . mapped . minorGridF .= noGridF
-- | Set no minor grid lines for given axis.
noMinorGridLine :: MonadState (Axis b v n) m => E v -> m ()
noMinorGridLine (E l) = axisGridLines . l . minorGridF .= noGridF
-- | Traversal over both major and minor grid lines for all axes.
allGridLines :: Traversable v => Traversal' (Axis b v n) (GridLines v n)
allGridLines = axisGridLines . traverse
------------------------------------------------------------------------
-- Bounds
------------------------------------------------------------------------
boundMin :: HasBounds a c => E c -> Lens' a (Recommend (N a))
boundMin (E l) = bounds . _Wrapped . l . lowerBound
boundMax :: HasBounds a c => E c -> Lens' a (Recommend (N a))
boundMax (E l) = bounds . _Wrapped . l . upperBound
xMin :: (HasBounds a c, R1 c) => Lens' a (Recommend (N a))
xMin = boundMin ex
xMax :: (HasBounds a c, R1 c) => Lens' a (Recommend (N a))
xMax = boundMax ex
yMin :: (HasBounds a c, R2 c) => Lens' a (Recommend (N a))
yMin = boundMin ey
yMax :: (HasBounds a c, R2 c) => Lens' a (Recommend (N a))
yMax = boundMax ey
zMin :: (HasBounds a c, R3 c) => Lens' a (Recommend (N a))
zMin = boundMin ey
zMax :: (HasBounds a c, R3 c) => Lens' a (Recommend (N a))
zMax = boundMin ey
------------------------------------------------------------------------
-- Grid lines
------------------------------------------------------------------------
-- | Set all axis grid lines to form a box.
boxAxisLines :: (Functor v, MonadState (Axis b v n) m) => m ()
boxAxisLines =
axisLines . mapped . axisLineType .= BoxAxisLine
-- | Set all axis grid lines to pass though the origin. If the origin is
-- not in bounds the line will be on the edge closest to the origin.
middleAxisLines :: (Functor v, MonadState (Axis b v n) m) => m ()
middleAxisLines =
axisLines . mapped . axisLineType .= MiddleAxisLine
-- -- | Traversal over all axis line types.
-- axisLineTypes :: HasAxisLines a v => Tranversal' a AxisLineType
-- axisLineTypes = axisLines . traversed . axisLine
-- -- | Lens onto x axis line type.
-- xAxisLineType :: (L.R1 v, HasAxisLines a v) => Lens' a AxisLineType
-- xAxisLineType = axisLine ex . axisLineType
-- -- | Lens onto y axis line type.
-- yAxisLineType :: (L.V2 n v, HasAxisLines a v) => Lens' a AxisLineType
-- yAxisLineType = axisLine ey . axisLineType
-- -- | Lens onto z axis line type.
-- zAxisLineType :: (L.V3 n v, HasAxisLines a v) => Lens' a AxisLineType
-- zAxisLineType = axisLine ez . axisLineType
-- xAxisArrowOpts :: (L.R1 v, HasAxisLines a v) => Lens' a (Maybe ArrowOpts)
-- xAxisArrowOpts = axisLine ex . axisArrowOpts
-- yAxisArrowOpts :: (L.V2 n v, HasAxisLines a v) => Lens' a (Maybe ArrowOpts)
-- yAxisArrowOpts = axisLine ey . axisArrowOpts
-- zAxisArrowOpts :: (L.V3 n v, HasAxisLines a v) => Lens' a (Maybe ArrowOpts)
-- zAxisArrowOpts = axisLines ez . axisArrowOpts
--
------------------------------------------------------------------------
-- Ticks
------------------------------------------------------------------------
-- | Remove minor ticks from all axes.
noMinorTicks :: (Functor v, MonadState (Axis b v n) m) => m ()
noMinorTicks =
axisTicks . mapped . minorTickAlign .= noTicks
-- | Remove major ticks from all axes.
noMajorTicks :: (Functor v, MonadState (Axis b v n) m) => m ()
noMajorTicks =
axisTicks . mapped . majorTickAlign .= noTicks
-- | Remove both major and minor ticks from all axes.
noAxisTicks :: (Functor v, MonadState (Axis b v n) m) => m ()
noAxisTicks = noMinorTicks >> noMajorTicks
centerAxisTicks :: (Functor v, MonadState (Axis b v n) m) => m ()
centerAxisTicks =
axisTicks . mapped . tickAlign .= centerTicks
insideAxisTicks :: (Functor v, MonadState (Axis b v n) m) => m ()
insideAxisTicks =
axisTicks . mapped . tickAlign .= insideTicks
------------------------------------------------------------------------
-- Style
------------------------------------------------------------------------
-- $style
-- Styles are a key part of a plot. It defines properties like colours
-- and markers for each plot. The default way a plot gets it's style is
-- from the axis theme. This is a list of plot styles that is zipped
-- with the plots when the axis is rendered.
------------------------------------------------------------------------
-- Colour bar
------------------------------------------------------------------------
-- $colourbar
-- The 'ColourBar' provides a visual key between a colour and value. The
-- colour bar is not shown by default, it either needs a plot like
-- 'addHeatMap' to turn it on or it can be turned on explicitly by
-- 'showColorBar'.
showColourBar :: MonadState (Axis b v n) m => m ()
showColourBar = axisColourBar . cbShow .= True
{-# ANN module ("HLint: ignore Use import/export shortcut" :: String) #-}
| bergey/plots | src/Plots/API.hs | bsd-3-clause | 17,846 | 0 | 11 | 3,773 | 3,273 | 1,846 | 1,427 | -1 | -1 |
module ETA.CodeGen.Env where
import ETA.BasicTypes.Id
import ETA.StgSyn.StgSyn
import ETA.Types.Type
import ETA.Types.TyCon
import Codec.JVM
import ETA.Util
import ETA.Debug
import ETA.CodeGen.Types
import ETA.CodeGen.Closure
import ETA.CodeGen.Monad
import ETA.CodeGen.Utils
import ETA.CodeGen.ArgRep
import ETA.CodeGen.Name
import Control.Monad (liftM)
import Data.Maybe (catMaybes)
getArgReferences :: [NonVoid StgArg] -> CodeGen [FieldRef]
getArgReferences xs = fmap catMaybes $ traverse f xs
where f (NonVoid (StgVarArg var)) = fmap g (getCgIdInfo var)
f _ = return Nothing
g CgIdInfo { cgLocation } = getLocField cgLocation
getArgLoadCode :: NonVoid StgArg -> CodeGen Code
getArgLoadCode (NonVoid (StgVarArg var)) = liftM idInfoLoadCode $ getCgIdInfo var
getArgLoadCode (NonVoid (StgLitArg literal)) = return . snd $ cgLit literal
getNonVoidArgCodes :: [StgArg] -> CodeGen [Code]
getNonVoidArgCodes [] = return []
getNonVoidArgCodes (arg:args)
| isVoidRep (argPrimRep arg) = getNonVoidArgCodes args
| otherwise = do
code <- getArgLoadCode (NonVoid arg)
codes <- getNonVoidArgCodes args
return (code:codes)
getNonVoidArgFtCodes :: [StgArg] -> CodeGen [(FieldType, Code)]
getNonVoidArgFtCodes [] = return []
getNonVoidArgFtCodes (arg:args)
| isVoidRep (argPrimRep arg) = getNonVoidArgFtCodes args
| otherwise = do
code <- getArgLoadCode (NonVoid arg)
ftCodes <- getNonVoidArgFtCodes args
return ((ft, code) : ftCodes)
where primRep = argPrimRep arg
ft = expectJust "getNonVoidArgFtCodes" . primRepFieldType_maybe $ primRep
getNonVoidArgRepCodes :: [StgArg] -> CodeGen [(PrimRep, Code)]
getNonVoidArgRepCodes [] = return []
getNonVoidArgRepCodes (arg:args)
| isVoidRep rep = getNonVoidArgRepCodes args
| otherwise = do
code <- getArgLoadCode (NonVoid arg)
repCodes <- getNonVoidArgRepCodes args
return ((rep, code) : repCodes)
where rep = argPrimRep arg
idInfoLoadCode :: CgIdInfo -> Code
idInfoLoadCode CgIdInfo { cgLocation } = loadLoc cgLocation
rebindId :: NonVoid Id -> CgLoc -> CodeGen ()
rebindId nvId@(NonVoid id) cgLoc = do
info <- getCgIdInfo id
bindId nvId (cgLambdaForm info) cgLoc
bindId :: NonVoid Id -> LambdaFormInfo -> CgLoc -> CodeGen ()
bindId nvId@(NonVoid id) lfInfo cgLoc =
addBinding (mkCgIdInfoWithLoc id lfInfo cgLoc)
bindArg :: NonVoid Id -> CgLoc -> CodeGen ()
bindArg nvid@(NonVoid id) = bindId nvid (mkLFArgument id)
bindArgs :: [(NonVoid Id, CgLoc)] -> CodeGen ()
bindArgs = mapM_ (\(nvId, cgLoc) -> bindArg nvId cgLoc)
rhsIdInfo :: Id -> LambdaFormInfo -> CodeGen (CgIdInfo, CgLoc)
rhsIdInfo id lfInfo = do
dflags <- getDynFlags
modClass <- getModClass
let qualifiedClass = qualifiedName modClass (idNameText dflags id)
rhsGenIdInfo id lfInfo (obj qualifiedClass)
-- TODO: getJavaInfo generalize to unify rhsIdInfo and rhsConIdInfo
rhsConIdInfo :: Id -> LambdaFormInfo -> CodeGen (CgIdInfo, CgLoc)
rhsConIdInfo id lfInfo@(LFCon dataCon) = do
dflags <- getDynFlags
let dataClass = dataConClass dflags dataCon
rhsGenIdInfo id lfInfo (obj dataClass)
rhsGenIdInfo :: Id -> LambdaFormInfo -> FieldType -> CodeGen (CgIdInfo, CgLoc)
rhsGenIdInfo id lfInfo ft = do
cgLoc <- newTemp True ft
return (mkCgIdInfoWithLoc id lfInfo cgLoc, cgLoc)
mkRhsInit :: CgLoc -> Code -> Code
mkRhsInit = storeLoc
maybeLetNoEscape :: CgIdInfo -> Maybe (Label, [CgLoc])
maybeLetNoEscape CgIdInfo { cgLocation = LocLne label argLocs }
= Just (label, argLocs)
maybeLetNoEscape _ = Nothing
| alexander-at-github/eta | compiler/ETA/CodeGen/Env.hs | bsd-3-clause | 3,536 | 0 | 12 | 600 | 1,239 | 622 | 617 | -1 | -1 |
module Rho.TrackerComms.PeerResponse where
import Data.Monoid
import Data.Word (Word32)
import Network.Socket (SockAddr)
data PeerResponse = PeerResponse
{ prInterval :: Word32
, prLeechers :: Maybe Word32
, prSeeders :: Maybe Word32
, prPeers :: [SockAddr]
} deriving (Show, Eq)
instance Monoid PeerResponse where
mempty = PeerResponse 0 Nothing Nothing []
PeerResponse i1 ls1 ss1 ps1 `mappend` PeerResponse i2 ls2 ss2 ps2 =
PeerResponse (max i1 i2) (ls1 `mw` ls2) (ss1 `mw` ss2) (ps1 <> ps2)
where
Nothing `mw` Nothing = Nothing
Just w `mw` Nothing = Just w
Nothing `mw` Just w = Just w
Just w1 `mw` Just w2 = Just (w1 + w2)
| osa1/rho-torrent | src/Rho/TrackerComms/PeerResponse.hs | bsd-3-clause | 735 | 0 | 10 | 211 | 264 | 142 | 122 | 18 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | This module is intended to be imported @qualified@, for example:
--
-- > import qualified Test.Tasty.Laws.Functor as Functor
--
module Test.Tasty.Laws.Functor
( testUnit
, test
, testExhaustive
, testSeries
, testSeriesExhaustive
, module Data.Functor.Laws
) where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>))
#endif
import Test.DumbCheck (Serial(series), Series, uncurry3, zipA3)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.DumbCheck (testSeriesProperty)
import Data.Functor.Laws (identity, composition)
import Text.Show.Functions ()
-- | @tasty@ 'TestTree' for 'Functor' laws. The type parameter for the
-- 'Functor' is '()' which unless you are dealing with partial functions,
-- should be enough to test any 'Functor'.
testUnit :: (Functor f, Eq (f ()), Show (f ())) => Series (f ()) -> TestTree
testUnit ss = testSeries1 $ zipA3 ss [const ()] [const ()]
-- | @tasty@ 'TestTree' for 'Functor' laws. Monomorphic sum 'Series' for @f@
-- and @g@ in the compose law.
--
-- @
-- fmap (\a -> a) . (\a -> a) == fmap (\a -> a) . fmap (\a -> a)
-- fmap (\b -> b) . (\b -> b) == fmap (\b -> b) . fmap (\b -> b)
-- ...
-- @
test
:: forall f a . (Eq (f a), Functor f, Show (f a), Serial a)
=> Series (f a) -> TestTree
test ss = testSeries1 $ zip3 ss (series :: Series (a -> a))
(series :: Series (a -> a))
-- | @tasty@ 'TestTree' for 'Functor' laws. Monomorphic product 'Series' for
-- @f@ and @g@ in the compose law.
--
-- @
-- fmap (\a -> a) . (\a -> a) == fmap (\a -> a) . fmap (\a -> a)
-- fmap (\a -> a) . (\a -> b) == fmap (\a -> a) . fmap (\a -> b)
-- fmap (\a -> a) . (\b -> b) == fmap (\a -> a) . fmap (\b -> b)
-- ...
-- @
testExhaustive
:: forall f a . (Eq (f a), Functor f, Show (f a), Serial a)
=> Series (f a) -> TestTree
testExhaustive ss = testSeries1 $ zipA3 ss (series :: Series (a -> a))
(series :: Series (a -> a))
-- | @tasty@ 'TestTree' for 'Functor' laws. Polymorphic sum 'Series' for
-- @f@ and @g@ in the compose law.
--
-- @
-- fmap (\a0 -> b0) . (\b0 -> c0) == fmap (\a0 -> b0) . fmap (\b0 -> c0)
-- fmap (\a1 -> b1) . (\b1 -> c1) == fmap (\a1 -> a1) . fmap (\b1 -> c1)
-- fmap (\a2 -> b2) . (\b2 -> c2) == fmap (\a2 -> a2) . fmap (\b2 -> c2)
-- ...
-- @
-- testPoly
-- :: forall f a b c .
-- ( Functor f
-- , Eq (f a), Show a, Show (f a) , Serial a
-- , Eq (f b), Show b, Show (f b) , Serial b
-- , Eq (f c), Show c, Show (f c) , Serial c
-- , Serial (a -> b), Serial (b -> c)
-- )
-- => Proxy b -> Proxy c -> Series (f a) -> TestTree
-- testPoly _ _ = testWithComp $ \fs ->
-- composition fs (series :: Series (b -> c))
-- (series :: Series (a -> b))
-- | @tasty@ 'TestTree' for 'Functor' laws with explict sum 'Series' for
-- @f@ and @g@ in the compose law.
--
-- @
-- fmap (\a0 -> b0) . (\b0 -> c0) == fmap (\a0 -> b0) . fmap (\b0 -> c0)
-- fmap (\a1 -> b1) . (\b1 -> c1) == fmap (\a1 -> a1) . fmap (\b1 -> c1)
-- fmap (\a1 -> b1) . (\b1 -> c1) == fmap (\a1 -> a1) . fmap (\b1 -> c1)
-- ...
-- @
testSeries
:: ( Eq (f c), Eq (f b), Functor f, Show (f c))
=> Series (f c) -> Series (a -> b) -> Series (c -> a) -> TestTree
testSeries xs fs gs = testSeries1 (zip3 xs fs gs)
-- | @tasty@ 'TestTree' for 'Functor' laws with explicit product 'Series'
-- for @f@ and @g@ in the compose law.
--
-- @
-- fmap (\a0 -> b0) . (\b0 -> c0) == fmap (\a0 -> b0) . fmap (\b0 -> c0)
-- fmap (\a0 -> b0) . (\b0 -> c1) == fmap (\a0 -> a0) . fmap (\b0 -> c1)
-- fmap (\a0 -> b0) . (\b0 -> c0) == fmap (\a0 -> a0) . fmap (\b1 -> c1)
-- ...
-- @
testSeriesExhaustive
:: ( Eq (f c), Eq (f b), Functor f, Show (f c))
=> Series (f c) -> Series (a -> b) -> Series (c -> a) -> TestTree
testSeriesExhaustive xs fs gs = testSeries1 (zipA3 xs fs gs)
testSeries1
:: (Eq (f c), Eq (f b), Functor f, Show (f c))
=> Series (f c, a -> b, c -> a) -> TestTree
testSeries1 ss = testGroup "Functor laws"
[ testSeriesProperty "fmap id ≡ id" identity ((\(x,_,_) -> x) <$> ss)
, testSeriesProperty "fmap (f . g) ≡ fmap f . fmap g" (uncurry3 composition) ss
]
| jdnavarro/tasty-laws | Test/Tasty/Laws/Functor.hs | bsd-3-clause | 4,265 | 0 | 12 | 1,049 | 874 | 499 | 375 | 42 | 1 |
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Main where
import Data.List (sort)
import qualified Data.StringMap as M
import qualified Data.StringMap.Dim2Search as D2
-- ----------------------------------------
--
-- auxiliary functions for mapping pairs of Ints to Strings and vice versa
intToKey :: Int -> Int -> Int -> String
intToKey base len val = tok len val ""
where
tok 0 _ acc = acc
tok i v acc = tok (i - 1) v' (d : acc)
where
(v', r) = v `divMod` base
d = toEnum (r + fromEnum '0')
intPairToKey :: Int -> Int -> (Int, Int) -> String
intPairToKey base len (x, y) = merge x' y'
where
x' = intToKey base len x
y' = intToKey base len y
merge :: [a] -> [a] -> [a]
merge [] [] = []
merge (x : xs) (y : ys) = x : y : merge xs ys
intFromKey :: String -> Int
intFromKey = read
unMerge :: [a] -> ([a], [a])
unMerge [] = ([], [])
unMerge (x : y : s) = (x : xs, y : ys)
where
(xs, ys) = unMerge s
-- ----------------------------------------
--
-- experiment to understand 2-dimensional location
-- search implemented by using the StringMap impl.
--
-- an ordering on strings (representing pairs of ints)
-- that is isomorphic to the partial ordering
-- used for 2-dimensional search
instance Ord Point' where
(P' s1) <= (P' s2) = s1 `le` s2
where
le [] [] = True
le (x1 : y1 : ds1) (x2 : y2 : ds2)
| x1 == x2 && y1 == y2 = ds1 `le` ds2
| x1 == x2 && y1 < y2 = ds1 `leX` ds2
| x1 < x2 && y1 == y2 = ds1 `leY` ds2
| x1 < x2 && y1 < y2 = True
| otherwise = False
leX [] [] = True -- the result for the Y dimension is already known
leX (x1 : y1 : ds1) (x2 : y2 : ds2)
| x1 == x2 = ds1 `leX` ds2
| x1 < x2 = True
| otherwise = False
leY [] [] = True -- the result for the X dimension is already known
leY (x1 : y1 : ds1) (x2 : y2 : ds2)
| y1 == y2 = ds1 `leY` ds2
| y1 < y2 = True
| otherwise = False
-- toPoint' and fromPoint': the bijection Point <-> Point'
toPoint' :: Point -> Point'
toPoint' (P p) = P' $ intPairToKey base len p
where
base = 2 -- or 10
len = 10 -- or 3 (or something else)
fromPoint' :: Point' -> Point
fromPoint' (P' ds) = P (intFromKey xs, intFromKey ys)
where
(xs, ys) = unMerge ds
-- the test, whether the `le` ordering is preserved, when working with Point'
propOrdered :: Point -> Point -> Bool
propOrdered p1 p2
= (p1 `le` p2) == (toPoint' p1 <= toPoint' p2)
-- very quick check test
propTest :: Int -> [(Point, Point)]
propTest n
= filter (not . uncurry propOrdered) qs
where
xs = [1..n]
ps = [P (x, y) | x <- xs, y <- xs]
qs = [(p1, p2) | p1 <- ps, p2 <- ps]
test1 :: Bool
test1 = null $ propTest 20
-- ----------------------------------------
newtype Point = P {unP :: (Int, Int) } deriving (Eq)
newtype PointSet = PS {unPS :: [Point] } deriving (Eq)
-- assuming only smart constructor mkPS is used
newtype Point' = P' {unP' :: String } deriving (Eq)
newtype PointSet' = PS' {unPS' :: M.StringMap ()} deriving (Eq)
instance Show Point where show = show . unP
instance Show Point' where show = show . unP'
instance Show PointSet where show = show . unPS
instance Show PointSet' where show = show . M.keys . unPS'
class PartOrd a where
le :: a -> a -> Bool
ge :: a -> a -> Bool
instance PartOrd Point where
(P (x1, y1)) `le` (P (x2, y2))
= x1 <= x2 && y1 <= y2
(P (x1, y1)) `ge` (P (x2, y2))
= x1 >= x2 && y1 >= y2
instance PartOrd Point' where
(P' p1) `le` (P' p2)
= not . M.null . D2.lookupLE p2 $ (M.singleton p1 ())
(P' p1) `ge` (P' p2)
= not . M.null . D2.lookupGE p2 $ (M.singleton p1 ())
class Lookup p s | s -> p where
lookupLE :: p -> s -> s
lookupGE :: p -> s -> s
instance Lookup Point PointSet where
lookupLE p ps = PS . filter (`le` p) . unPS $ ps
lookupGE p ps = PS . filter (`ge` p) . unPS $ ps
instance Lookup Point' PointSet' where
lookupLE p ps = PS' . D2.lookupLE (unP' p) . unPS' $ ps
lookupGE p ps = PS' . D2.lookupGE (unP' p) . unPS' $ ps
-- the bijection between Point and Point'
pToP' :: Point -> Point'
pToP' = P' . intPairToKey 10 5 . unP -- base 10, 5 digits
p'ToP :: Point' -> Point
p'ToP (P' p') = P (intFromKey xs, intFromKey ys)
where
(xs, ys) = unMerge p'
-- the bijection between PointSet and PointSet'
psToPS' :: PointSet -> PointSet'
psToPS' = PS' . M.fromList . map (\(P' x) -> (x, ())) . map pToP' . unPS
ps'ToPS :: PointSet' -> PointSet
ps'ToPS = mkPS . map (unP . p'ToP . P') . M.keys . unPS'
mkP :: Int -> Int -> Point
mkP x y = P (x, y)
mkP' :: Int -> Int -> Point'
mkP' x y = pToP' $ mkP x y
mkPS :: [(Int, Int)] -> PointSet
mkPS = PS . map P . sort
mkPS' :: [(Int, Int)] -> PointSet'
mkPS' = psToPS' . mkPS
mkxx :: Int -> Point
mkxx i = mkP i i
mkxx' :: Int -> Point'
mkxx' = pToP' . mkxx
mkD2 :: [Int] -> PointSet
mkD2 = PS . map mkxx
mkD2' :: [Int] -> PointSet'
mkD2' = psToPS' . mkD2
d1 :: PointSet
d1 = mkD2 [1,10,100,105,107,125,200, 205, 222]
d1' :: PointSet'
d1' = psToPS' d1
d2 :: PointSet
d2 = mkD2 [2,10,20,25,100,111,155,200,333,500]
d2' :: PointSet'
d2' = psToPS' d2
d0' :: PointSet'
d0' = mkD2' [10,100]
mkSquare :: Int -> Int -> PointSet
mkSquare n m = mkPS [(i, j) | i <- [n..m], j <- [n..m]]
-- input list must contain at least 3 different elements
mkPointPointSet :: [Int] -> ([Point], PointSet)
mkPointPointSet xs0
= (ps, ps')
where
xs@(_ : ys@(_:_:_)) = sort xs0
xs' = init ys
ps = [mkP i j | i <- xs, j <- xs ]
ps' = mkPS [ (i, j) | i <- xs', j <- xs']
ps1 :: PointSet
xs1 :: [Point]
(xs1, ps1) = mkPointPointSet [1,2,10,20,25,100,111,155,200,333,500,505]
lawBijection :: PointSet -> Bool
lawBijection ps
= ps == (ps'ToPS . psToPS' $ ps)
lawPredicateMorphism :: (Point -> Bool) -> (Point' -> Bool) ->
Point -> Bool
lawPredicateMorphism p p' x
= p x == (p' $ pToP' x)
lawPredicate2Morphism :: (Point -> Point -> Bool) -> (Point' -> Point' -> Bool) ->
Point -> Point -> Bool
lawPredicate2Morphism p2 p2' x y
= lawPredicateMorphism (p2 x) (p2' $ pToP' x) y
lawPointSetMorphism :: (PointSet -> PointSet) -> (PointSet' -> PointSet') ->
PointSet -> Bool
lawPointSetMorphism f f' ps
= f ps == (ps'ToPS . f' . psToPS' $ ps)
lawLookupGE :: Point -> PointSet -> Bool
lawLookupGE p ps = lawPointSetMorphism (lookupGE p) (lookupGE $ pToP' p) ps
lawLookupLE :: Point -> PointSet -> Bool
lawLookupLE p ps = lawPointSetMorphism (lookupLE p) (lookupLE $ pToP' p) ps
testPointPointSet :: (Point -> PointSet -> Bool) -> ([Point], PointSet) -> [Point]
testPointPointSet law (xs, ps)
= filter (\p -> not $ law p ps) xs
testLookup :: ([Point], PointSet) -> Bool
testLookup ps
= null (testPointPointSet lawLookupLE ps)
&&
null (testPointPointSet lawLookupGE ps)
theTest :: Bool
theTest = testLookup $
mkPointPointSet [1,2,10,20,25,100,111,155,200,333,500,505]
main :: IO ()
main = print theTest >> return ()
-- ----------------------------------------
| alexbiehl/StringMap | tests/Dim2Test.hs | mit | 7,588 | 0 | 13 | 2,262 | 3,022 | 1,639 | 1,383 | 171 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{-|
Copyright: Aaron Taylor, 2016
License: MIT
Maintainer: [email protected]
Class, instances and transformer for monads capable of HTTP requests.
In some cases, it is useful to generalize this capability. For example, it can be used provide mock responses for testing.
-}
module Control.Monad.Http (
-- * Class
MonadHttp(..),
-- * Transformer
HttpT(..),
runHttpT
) where
import qualified Control.Monad.Catch as Catch
import qualified Control.Monad.Except as Except
import qualified Control.Monad.Reader as Reader
import qualified Control.Monad.Trans as Trans
import qualified Data.ByteString.Lazy as LBS
import qualified Network.HTTP.Simple as HTTPSimple
import qualified Network.HTTP.Client as HTTP
import qualified Network.HTTP.Types as HTTP
{-|
The class of monads capable of HTTP requests.
-}
class Monad m => MonadHttp m where
performRequest :: HTTP.Request -> m (HTTP.Response LBS.ByteString)
instance MonadHttp IO where
performRequest = HTTPSimple.httpLbs
instance Catch.MonadThrow m => MonadHttp (HttpT m) where
performRequest request = check
where
check = do
response <- Reader.ask
let status = HTTP.responseStatus response
if status >= HTTP.ok200 && status < HTTP.multipleChoices300
then return response
else
let
badResponse = response { HTTP.responseBody = () }
body = LBS.toStrict . HTTP.responseBody $ response
in
Catch.throwM $ HTTP.HttpExceptionRequest request (HTTP.StatusCodeException badResponse body)
instance Trans.MonadIO m => MonadHttp (Except.ExceptT e m) where
performRequest = HTTPSimple.httpLbs
{-|
An HTTP transformer monad parameterized by an inner monad 'm'.
-}
newtype HttpT m a = HttpT { unHttpT :: Reader.ReaderT (HTTP.Response LBS.ByteString) m a }
deriving (Functor, Applicative, Monad, Trans.MonadTrans, Catch.MonadThrow, Catch.MonadCatch, Trans.MonadIO, Reader.MonadReader (HTTP.Response LBS.ByteString))
{-|
Run an HTTP monad action and extract the inner monad.
-}
runHttpT ::
HttpT m a -- ^ The HTTP monad transformer
-> HTTP.Response LBS.ByteString -- ^ The response
-> m a -- ^ The resulting inner monad
runHttpT = Reader.runReaderT . unHttpT
instance Except.MonadError e m => Except.MonadError e (HttpT m) where
throwError = Trans.lift . Except.throwError
catchError m f = HttpT . Reader.ReaderT $ \r -> Except.catchError
(runHttpT m r)
(\e -> runHttpT (f e) r)
| hamsterdam/kawhi | library/Control/Monad/Http.hs | mit | 2,822 | 0 | 17 | 691 | 585 | 326 | 259 | 45 | 1 |
data A a = A (A a a)
| roberth/uu-helium | test/kinderrors/KindError7.hs | gpl-3.0 | 22 | 0 | 8 | 9 | 19 | 10 | 9 | 1 | 0 |
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE OverloadedStrings #-}
--------------------------------------------------------------------
-- |
-- Copyright : (c) Edward Kmett and Dan Doel 2013
-- License : BSD2
-- Maintainer: Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability: non-portable
--
-- This module provides the parser for terms
--------------------------------------------------------------------
module Ermine.Parser.Pattern
( validate
, pattern
, pattern0
, pattern1
, PP
) where
import Control.Applicative
import Control.Lens hiding (op)
import Data.Foldable as Foldable
import Data.Text (Text)
import Data.Void
import qualified Data.Set as Set
import Ermine.Builtin.Global
import Ermine.Builtin.Pattern
import Ermine.Builtin.Type (anyType)
import Ermine.Parser.Literal
import Ermine.Parser.Style
import Ermine.Parser.Type
import Ermine.Syntax
import Text.Parser.Combinators
import Text.Parser.Token
-- | Check a 'Binder' for linearity.
--
-- Each variable name must be used at most once in the pattern.
validate :: (Functor m, Monad m, Ord v) => Binder v a -> (v -> m Void) -> m ()
validate b e =
() <$ foldlM (\s n -> if n `Set.member` s then vacuous $ e n else return $ Set.insert n s)
Set.empty
(vars b)
-- | The simple pattern type generated by pattern parsing.
type PP = P Ann Text
varP :: (Monad m, TokenParsing m) => m PP
varP = termIdentifier <&> sigp ?? anyType
-- | Parse a single pattern part (e.g. an argument to a lambda)
pattern0 :: (Monad m, TokenParsing m) => m PP
pattern0
= conp nothingg [] <$ symbol "Nothing"
<|> varP
<|> strictp <$ symbol "!" <*> pattern0
<|> _p <$ symbol "_"
<|> litp <$> literal
<|> parens (tup' <$> patterns)
sigP :: (Monad m, TokenParsing m) => m PP
sigP = sigp <$> try (termIdentifier <* colon) <*> annotation
-- TODO: remove this when constructor patterns really work.
eP, longhP, justP, nothingP :: (Monad m, TokenParsing m) => m PP
eP = conp eg <$ symbol "E" <*> many pattern1
justP = conp justg <$ symbol "Just" <*> many pattern1
nothingP = conp nothingg <$ symbol "Nothing" <*> many pattern1
longhP = conp longhg <$ symbol "Long#" <*> many pattern1
-- as patterns
pattern1 :: (Monad m, TokenParsing m) => m PP
pattern1
= asp <$> try (termIdentifier <* symbol "@") <*> pattern1
<|> pattern0
-- | Parse a single pattern (e.g. a case statement alt pattern)
pattern2 :: (Monad m, TokenParsing m) => m PP
pattern2
= eP
<|> justP
<|> nothingP
<|> longhP
<|> pattern1
-- existentials sigP
pattern3 :: (Monad m, TokenParsing m) => m PP
pattern3
= sigP
<|> pattern2
patterns :: (Monad m, TokenParsing m) => m [PP]
patterns = commaSep pattern3
-- | Parse a single pattern (e.g. a case statement alt pattern)
pattern :: (Monad m, TokenParsing m) => m PP
pattern = pattern2
| PipocaQuemada/ermine | src/Ermine/Parser/Pattern.hs | bsd-2-clause | 2,871 | 2 | 16 | 570 | 780 | 427 | 353 | 65 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
module Distribution.Client.Cron
( cron
, Signal(..)
, ReceivedSignal(..)
, rethrowSignalsAsExceptions
) where
import Control.Monad (forM_)
import Control.Exception (Exception)
import Control.Concurrent (myThreadId, threadDelay, throwTo)
import System.Random (randomRIO)
import System.Locale (defaultTimeLocale)
import Data.Time.Format (formatTime)
import Data.Time.Clock (UTCTime, getCurrentTime, addUTCTime)
import Data.Time.LocalTime (getCurrentTimeZone, utcToZonedTime)
import Data.Typeable (Typeable)
import qualified System.Posix.Signals as Posix
import Distribution.Verbosity (Verbosity)
import Distribution.Simple.Utils hiding (warn)
data ReceivedSignal = ReceivedSignal Signal UTCTime
deriving (Show, Typeable)
data Signal = SIGABRT
| SIGINT
| SIGQUIT
| SIGTERM
deriving (Show, Typeable)
instance Exception ReceivedSignal
-- | "Re"throw signals as exceptions to the invoking thread
rethrowSignalsAsExceptions :: [Signal] -> IO ()
rethrowSignalsAsExceptions signals = do
tid <- myThreadId
forM_ signals $ \s ->
let handler = do
time <- getCurrentTime
throwTo tid (ReceivedSignal s time)
in Posix.installHandler (toPosixSignal s) (Posix.Catch handler) Nothing
toPosixSignal :: Signal -> Posix.Signal
toPosixSignal SIGABRT = Posix.sigABRT
toPosixSignal SIGINT = Posix.sigINT
toPosixSignal SIGQUIT = Posix.sigQUIT
toPosixSignal SIGTERM = Posix.sigTERM
-- | @cron verbosity interval act@ runs @act@ over and over with
-- the specified interval.
cron :: Verbosity -> Int -> (a -> IO a) -> (a -> IO ())
cron verbosity interval action x = do
x' <- action x
interval' <- pertabate interval
logNextSyncMessage interval'
wait interval'
cron verbosity interval action x'
where
-- to stop all mirror clients hitting the server at exactly the same time
-- we randomly adjust the wait time by +/- 10%
pertabate i = let deviation = i `div` 10
in randomRIO (i + deviation, i - deviation)
-- Annoyingly, threadDelay takes an Int number of microseconds, so we cannot
-- wait much longer than an hour. So have to wait repeatedly. Sigh.
wait minutes | minutes > 60 = do threadDelay (60 * 60 * 1000000)
wait (minutes - 60)
| otherwise = threadDelay (minutes * 60 * 1000000)
logNextSyncMessage minutes = do
now <- getCurrentTime
tz <- getCurrentTimeZone
let nextSync = addUTCTime (fromIntegral (60 * minutes)) now
notice verbosity $
"Next try will be in " ++ show minutes ++ " minutes, at "
++ formatTime defaultTimeLocale "%R %Z" (utcToZonedTime tz nextSync)
| haskell-infra/hackage-server | Distribution/Client/Cron.hs | bsd-3-clause | 2,758 | 0 | 17 | 623 | 688 | 363 | 325 | 58 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleInstances #-}
-- | Generate HPC (Haskell Program Coverage) reports
module Stack.Coverage
( deleteHpcReports
, updateTixFile
, generateHpcReport
, HpcReportOpts(..)
, generateHpcReportForTargets
, generateHpcUnifiedReport
, generateHpcMarkupIndex
) where
import Control.Applicative
import Control.Exception.Lifted
import Control.Monad (liftM, when, unless, void)
import Control.Monad.Catch (MonadCatch)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (MonadReader, asks)
import Control.Monad.Trans.Resource
import qualified Data.ByteString.Char8 as S8
import Data.Foldable (forM_, asum, toList)
import Data.Function
import Data.List
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as LT
import Data.Traversable (forM)
import Trace.Hpc.Tix
import Network.HTTP.Download (HasHttpManager)
import Path
import Path.IO
import Prelude hiding (FilePath, writeFile)
import Stack.Build.Source (parseTargetsFromBuildOpts)
import Stack.Build.Target
import Stack.Constants
import Stack.Package
import Stack.Types
import qualified System.Directory as D
import System.FilePath (dropExtension, isPathSeparator)
import System.Process.Read
import Text.Hastache (htmlEscape)
-- | Invoked at the beginning of running with "--coverage"
deleteHpcReports :: (MonadIO m, MonadThrow m, MonadReader env m, HasEnvConfig env)
=> m ()
deleteHpcReports = do
hpcDir <- hpcReportDir
removeTreeIfExists hpcDir
-- | Move a tix file into a sub-directory of the hpc report directory. Deletes the old one if one is
-- present.
updateTixFile :: (MonadIO m,MonadReader env m,HasConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,HasEnvConfig env)
=> PackageName -> Path Abs File -> m ()
updateTixFile pkgName tixSrc = do
exists <- fileExists tixSrc
when exists $ do
tixDest <- tixFilePath pkgName (dropExtension (toFilePath (filename tixSrc)))
removeFileIfExists tixDest
createTree (parent tixDest)
-- Remove exe modules because they are problematic. This could be revisited if there's a GHC
-- version that fixes https://ghc.haskell.org/trac/ghc/ticket/1853
mtix <- readTixOrLog tixSrc
case mtix of
Nothing -> $logError $ "Failed to read " <> T.pack (toFilePath tixSrc)
Just tix -> do
liftIO $ writeTix (toFilePath tixDest) (removeExeModules tix)
removeFileIfExists tixSrc
-- | Get the directory used for hpc reports for the given pkgId.
hpcPkgPath :: (MonadIO m,MonadReader env m,HasConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,HasEnvConfig env)
=> PackageName -> m (Path Abs Dir)
hpcPkgPath pkgName = do
outputDir <- hpcReportDir
pkgNameRel <- parseRelDir (packageNameString pkgName)
return (outputDir </> pkgNameRel)
-- | Get the tix file location, given the name of the file (without extension), and the package
-- identifier string.
tixFilePath :: (MonadIO m,MonadReader env m,HasConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,HasEnvConfig env)
=> PackageName -> String -> m (Path Abs File)
tixFilePath pkgName tixName = do
pkgPath <- hpcPkgPath pkgName
tixRel <- parseRelFile (tixName ++ "/" ++ tixName ++ ".tix")
return (pkgPath </> tixRel)
-- | Generates the HTML coverage report and shows a textual coverage summary for a package.
generateHpcReport :: (MonadIO m,MonadReader env m,HasConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,HasEnvConfig env)
=> Path Abs Dir -> Package -> [Text] -> m ()
generateHpcReport pkgDir package tests = do
-- If we're using > GHC 7.10, the hpc 'include' parameter must specify a ghc package key. See
-- https://github.com/commercialhaskell/stack/issues/785
let pkgName = packageNameText (packageName package)
pkgId = packageIdentifierString (packageIdentifier package)
compilerVersion <- asks (envConfigCompilerVersion . getEnvConfig)
eincludeName <-
-- Pre-7.8 uses plain PKG-version in tix files.
if getGhcVersion compilerVersion < $(mkVersion "7.10") then return $ Right $ Just pkgId
-- We don't expect to find a package key if there is no library.
else if not (packageHasLibrary package) then return $ Right Nothing
-- Look in the inplace DB for the package key.
-- See https://github.com/commercialhaskell/stack/issues/1181#issuecomment-148968986
else do
mghcPkgKey <- findPackageKeyForBuiltPackage pkgDir (packageIdentifier package)
case mghcPkgKey of
Nothing -> do
let msg = "Failed to find GHC package key for " <> pkgName
$logError msg
return $ Left msg
Just ghcPkgKey -> return $ Right $ Just $ T.unpack ghcPkgKey
forM_ tests $ \testName -> do
tixSrc <- tixFilePath (packageName package) (T.unpack testName)
let report = "coverage report for " <> pkgName <> "'s test-suite \"" <> testName <> "\""
reportDir = parent tixSrc
case eincludeName of
Left err -> generateHpcErrorReport reportDir (sanitize (T.unpack err))
-- Restrict to just the current library code, if there is a library in the package (see
-- #634 - this will likely be customizable in the future)
Right mincludeName -> do
let extraArgs = case mincludeName of
Just includeName -> ["--include", includeName ++ ":"]
Nothing -> []
generateHpcReportInternal tixSrc reportDir report extraArgs extraArgs
generateHpcReportInternal :: (MonadIO m,MonadReader env m,HasConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,HasEnvConfig env)
=> Path Abs File -> Path Abs Dir -> Text -> [String] -> [String] -> m ()
generateHpcReportInternal tixSrc reportDir report extraMarkupArgs extraReportArgs = do
-- If a .tix file exists, move it to the HPC output directory and generate a report for it.
tixFileExists <- fileExists tixSrc
if not tixFileExists
then $logError $ T.concat
[ "Didn't find .tix for "
, report
, " - expected to find it at "
, T.pack (toFilePath tixSrc)
, "."
]
else (`catch` \err -> do
let msg = show (err :: ReadProcessException)
$logError (T.pack msg)
generateHpcErrorReport reportDir $ sanitize msg) $
(`onException` $logError ("Error occurred while producing " <> report)) $ do
-- Directories for .mix files.
hpcRelDir <- hpcRelativeDir
-- Compute arguments used for both "hpc markup" and "hpc report".
pkgDirs <- Map.keys . envConfigPackages <$> asks getEnvConfig
let args =
-- Use index files from all packages (allows cross-package coverage results).
concatMap (\x -> ["--srcdir", toFilePath x]) pkgDirs ++
-- Look for index files in the correct dir (relative to each pkgdir).
["--hpcdir", toFilePath hpcRelDir, "--reset-hpcdirs"]
menv <- getMinimalEnvOverride
$logInfo $ "Generating " <> report
outputLines <- liftM S8.lines $ readProcessStdout Nothing menv "hpc"
( "report"
: toFilePath tixSrc
: (args ++ extraReportArgs)
)
if all ("(0/0)" `S8.isSuffixOf`) outputLines
then do
let msg html = T.concat
[ "Error: The "
, report
, " did not consider any code. One possible cause of this is"
, " if your test-suite builds the library code (see stack "
, if html then "<a href='https://github.com/commercialhaskell/stack/issues/1008'>" else ""
, "issue #1008"
, if html then "</a>" else ""
, "). It may also indicate a bug in stack or"
, " the hpc program. Please report this issue if you think"
, " your coverage report should have meaningful results."
]
$logError (msg False)
generateHpcErrorReport reportDir (msg True)
else do
-- Print output, stripping @\r@ characters because Windows.
forM_ outputLines ($logInfo . T.decodeUtf8 . S8.filter (not . (=='\r')))
$logInfo
("The " <> report <> " is available at " <>
T.pack (toFilePath (reportDir </> $(mkRelFile "hpc_index.html"))))
-- Generate the markup.
void $ readProcessStdout Nothing menv "hpc"
( "markup"
: toFilePath tixSrc
: ("--destdir=" ++ toFilePath reportDir)
: (args ++ extraMarkupArgs)
)
data HpcReportOpts = HpcReportOpts
{ hroptsInputs :: [Text]
, hroptsAll :: Bool
, hroptsDestDir :: Maybe String
} deriving (Show)
generateHpcReportForTargets :: (MonadIO m, HasHttpManager env, MonadReader env m, MonadBaseControl IO m, MonadCatch m, MonadLogger m, HasEnvConfig env)
=> HpcReportOpts -> m ()
generateHpcReportForTargets opts = do
let (tixFiles, targetNames) = partition (".tix" `T.isSuffixOf`) (hroptsInputs opts)
targetTixFiles <-
-- When there aren't any package component arguments, then
-- don't default to all package components.
if not (hroptsAll opts) && null targetNames
then return []
else do
when (hroptsAll opts && not (null targetNames)) $
$logWarn $ "Since --all is used, it is redundant to specify these targets: " <> T.pack (show targetNames)
(_,_,targets) <- parseTargetsFromBuildOpts
AllowNoTargets
defaultBuildOpts
{ boptsTargets = if hroptsAll opts then [] else targetNames
}
liftM concat $ forM (Map.toList targets) $ \(name, target) ->
case target of
STUnknown -> fail $
packageNameString name ++ " isn't a known local page"
STNonLocal -> fail $
"Expected a local package, but " ++
packageNameString name ++
" is either an extra-dep or in the snapshot."
STLocalComps comps -> do
pkgPath <- hpcPkgPath name
forM (toList comps) $ \nc ->
case nc of
CTest testName ->
liftM (pkgPath </>) $ parseRelFile (T.unpack testName ++ ".tix")
_ -> fail $
"Can't specify anything except test-suites as hpc report targets (" ++
packageNameString name ++
" is used with a non test-suite target)"
STLocalAll -> do
pkgPath <- hpcPkgPath name
exists <- dirExists pkgPath
if exists
then do
(_, files) <- listDirectory pkgPath
return (filter ((".tix" `isSuffixOf`) . toFilePath) files)
else return []
tixPaths <- liftM (++ targetTixFiles) $ mapM (parseRelAsAbsFile . T.unpack) tixFiles
when (null tixPaths) $
fail "Not generating combined report, because no targets or tix files are specified."
reportDir <- case hroptsDestDir opts of
Nothing -> liftM (</> $(mkRelDir "combined/custom")) hpcReportDir
Just destDir -> do
liftIO $ D.createDirectoryIfMissing True destDir
parseRelAsAbsDir destDir
generateUnionReport "combined report" reportDir tixPaths
generateHpcUnifiedReport :: (MonadIO m,MonadReader env m,HasConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,HasEnvConfig env)
=> m ()
generateHpcUnifiedReport = do
outputDir <- hpcReportDir
createTree outputDir
(dirs, _) <- listDirectory outputDir
tixFiles <- liftM (concat . concat) $ forM (filter (("combined" /=) . dirnameString) dirs) $ \dir -> do
(dirs', _) <- listDirectory dir
forM dirs' $ \dir' -> do
(_, files) <- listDirectory dir'
return (filter ((".tix" `isSuffixOf`) . toFilePath) files)
let reportDir = outputDir </> $(mkRelDir "combined/all")
if length tixFiles < 2
then $logInfo $ T.concat
[ if null tixFiles then "No tix files" else "Only one tix file"
, " found in "
, T.pack (toFilePath outputDir)
, ", so not generating a unified coverage report."
]
else generateUnionReport "unified report" reportDir tixFiles
generateUnionReport :: (MonadIO m,MonadReader env m,HasConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,HasEnvConfig env)
=> Text -> Path Abs Dir -> [Path Abs File] -> m ()
generateUnionReport report reportDir tixFiles = do
tixes <- mapM (liftM (fmap removeExeModules) . readTixOrLog) tixFiles
$logDebug $ "Using the following tix files: " <> T.pack (show tixFiles)
let (errs, tix) = unionTixes (catMaybes tixes)
unless (null errs) $ $logWarn $ T.concat $
"The following modules are left out of the " : report : " due to version mismatches: " :
intersperse ", " (map T.pack errs)
tixDest <- liftM (reportDir </>) $ parseRelFile (dirnameString reportDir ++ ".tix")
createTree (parent tixDest)
liftIO $ writeTix (toFilePath tixDest) tix
generateHpcReportInternal tixDest reportDir report [] []
readTixOrLog :: (MonadLogger m, MonadIO m, MonadBaseControl IO m) => Path b File -> m (Maybe Tix)
readTixOrLog path = do
mtix <- liftIO (readTix (toFilePath path)) `catch` \(ErrorCall err) -> do
$logError $ "Error while reading tix: " <> T.pack err
return Nothing
when (isNothing mtix) $
$logError $ "Failed to read tix file " <> T.pack (toFilePath path)
return mtix
-- | Module names which contain '/' have a package name, and so they weren't built into the
-- executable.
removeExeModules :: Tix -> Tix
removeExeModules (Tix ms) = Tix (filter (\(TixModule name _ _ _) -> '/' `elem` name) ms)
unionTixes :: [Tix] -> ([String], Tix)
unionTixes tixes = (Map.keys errs, Tix (Map.elems outputs))
where
(errs, outputs) = Map.mapEither id $ Map.unionsWith merge $ map toMap tixes
toMap (Tix ms) = Map.fromList (map (\x@(TixModule k _ _ _) -> (k, Right x)) ms)
merge (Right (TixModule k hash1 len1 tix1))
(Right (TixModule _ hash2 len2 tix2))
| hash1 == hash2 && len1 == len2 = Right (TixModule k hash1 len1 (zipWith (+) tix1 tix2))
merge _ _ = Left ()
generateHpcMarkupIndex :: (MonadIO m,MonadReader env m,MonadLogger m,MonadCatch m,HasEnvConfig env)
=> m ()
generateHpcMarkupIndex = do
outputDir <- hpcReportDir
let outputFile = outputDir </> $(mkRelFile "index.html")
createTree outputDir
(dirs, _) <- listDirectory outputDir
rows <- liftM (catMaybes . concat) $ forM dirs $ \dir -> do
(subdirs, _) <- listDirectory dir
forM subdirs $ \subdir -> do
let indexPath = subdir </> $(mkRelFile "hpc_index.html")
exists' <- fileExists indexPath
if not exists' then return Nothing else do
relPath <- stripDir outputDir indexPath
let package = dirname dir
testsuite = dirname subdir
return $ Just $ T.concat
[ "<tr><td>"
, pathToHtml package
, "</td><td><a href=\""
, pathToHtml relPath
, "\">"
, pathToHtml testsuite
, "</a></td></tr>"
]
liftIO $ T.writeFile (toFilePath outputFile) $ T.concat $
[ "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
-- Part of the css from HPC's output HTML
, "<style type=\"text/css\">"
, "table.dashboard { border-collapse: collapse; border: solid 1px black }"
, ".dashboard td { border: solid 1px black }"
, ".dashboard th { border: solid 1px black }"
, "</style>"
, "</head>"
, "<body>"
] ++
(if null rows
then
[ "<b>No hpc_index.html files found in \""
, pathToHtml outputDir
, "\".</b>"
]
else
[ "<table class=\"dashboard\" width=\"100%\" boder=\"1\"><tbody>"
, "<p><b>NOTE: This is merely a listing of the html files found in the coverage reports directory. Some of these reports may be old.</b></p>"
, "<tr><th>Package</th><th>TestSuite</th><th>Modification Time</th></tr>"
] ++
rows ++
["</tbody></table>"]) ++
["</body></html>"]
unless (null rows) $
$logInfo $ "\nAn index of the generated HTML coverage reports is available at " <>
T.pack (toFilePath outputFile)
generateHpcErrorReport :: MonadIO m => Path Abs Dir -> Text -> m ()
generateHpcErrorReport dir err = do
createTree dir
liftIO $ T.writeFile (toFilePath (dir </> $(mkRelFile "hpc_index.html"))) $ T.concat
[ "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></head><body>"
, "<h1>HPC Report Generation Error</h1>"
, "<p>"
, err
, "</p>"
, "</body></html>"
]
pathToHtml :: Path b t -> Text
pathToHtml = T.dropWhileEnd (=='/') . sanitize . toFilePath
sanitize :: String -> Text
sanitize = LT.toStrict . htmlEscape . LT.pack
dirnameString :: Path r Dir -> String
dirnameString = dropWhileEnd isPathSeparator . toFilePath . dirname
findPackageKeyForBuiltPackage :: (MonadIO m, MonadReader env m, MonadThrow m, HasEnvConfig env)
=> Path Abs Dir -> PackageIdentifier -> m (Maybe Text)
findPackageKeyForBuiltPackage pkgDir pkgId = do
distDir <- distDirFromDir pkgDir
path <- liftM (distDir </>) $
parseRelFile ("package.conf.inplace/" ++ packageIdentifierString pkgId ++ "-inplace.conf")
contents <- liftIO $ T.readFile (toFilePath path)
return $ asum (map (T.stripPrefix "key: ") (T.lines contents))
| mathhun/stack | src/Stack/Coverage.hs | bsd-3-clause | 20,063 | 0 | 28 | 6,609 | 4,547 | 2,305 | 2,242 | 336 | 9 |
{-|
Module : Idris.IBC
Description : Core representations and code to generate IBC files.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.IBC (loadIBC, loadPkgIndex,
writeIBC, writePkgIndex,
hasValidIBCVersion, IBCPhase(..)) where
import Idris.Core.Evaluate
import Idris.Core.TT
import Idris.Core.Binary
import Idris.Core.CaseTree
import Idris.AbsSyntax
import Idris.Imports
import Idris.Error
import Idris.DeepSeq
import Idris.Delaborate
import qualified Idris.Docstrings as D
import Idris.Docstrings (Docstring)
import Idris.Output
import IRTS.System (getIdrisLibDir)
import Paths_idris
import qualified Cheapskate.Types as CT
import Data.Binary
import Data.Functor
import Data.Vector.Binary
import Data.List as L
import Data.Maybe (catMaybes)
import Data.ByteString.Lazy as B hiding (length, elem, map)
import qualified Data.Text as T
import qualified Data.Set as S
import Control.Monad
import Control.DeepSeq
import Control.Monad.State.Strict hiding (get, put)
import qualified Control.Monad.State.Strict as ST
import System.FilePath
import System.Directory
import Codec.Archive.Zip
import Debug.Trace
ibcVersion :: Word16
ibcVersion = 144
-- | When IBC is being loaded - we'll load different things (and omit
-- different structures/definitions) depending on which phase we're in.
data IBCPhase = IBC_Building -- ^ when building the module tree
| IBC_REPL Bool -- ^ when loading modules for the REPL Bool = True for top level module
deriving (Show, Eq)
data IBCFile = IBCFile {
ver :: Word16
, sourcefile :: FilePath
, ibc_reachablenames :: ![Name]
, ibc_imports :: ![(Bool, FilePath)]
, ibc_importdirs :: ![FilePath]
, ibc_implicits :: ![(Name, [PArg])]
, ibc_fixes :: ![FixDecl]
, ibc_statics :: ![(Name, [Bool])]
, ibc_classes :: ![(Name, ClassInfo)]
, ibc_records :: ![(Name, RecordInfo)]
, ibc_instances :: ![(Bool, Bool, Name, Name)]
, ibc_dsls :: ![(Name, DSL)]
, ibc_datatypes :: ![(Name, TypeInfo)]
, ibc_optimise :: ![(Name, OptInfo)]
, ibc_syntax :: ![Syntax]
, ibc_keywords :: ![String]
, ibc_objs :: ![(Codegen, FilePath)]
, ibc_libs :: ![(Codegen, String)]
, ibc_cgflags :: ![(Codegen, String)]
, ibc_dynamic_libs :: ![String]
, ibc_hdrs :: ![(Codegen, String)]
, ibc_totcheckfail :: ![(FC, String)]
, ibc_flags :: ![(Name, [FnOpt])]
, ibc_fninfo :: ![(Name, FnInfo)]
, ibc_cg :: ![(Name, CGInfo)]
, ibc_docstrings :: ![(Name, (Docstring D.DocTerm, [(Name, Docstring D.DocTerm)]))]
, ibc_moduledocs :: ![(Name, Docstring D.DocTerm)]
, ibc_transforms :: ![(Name, (Term, Term))]
, ibc_errRev :: ![(Term, Term)]
, ibc_coercions :: ![Name]
, ibc_lineapps :: ![(FilePath, Int, PTerm)]
, ibc_namehints :: ![(Name, Name)]
, ibc_metainformation :: ![(Name, MetaInformation)]
, ibc_errorhandlers :: ![Name]
, ibc_function_errorhandlers :: ![(Name, Name, Name)] -- fn, arg, handler
, ibc_metavars :: ![(Name, (Maybe Name, Int, [Name], Bool, Bool))]
, ibc_patdefs :: ![(Name, ([([(Name, Term)], Term, Term)], [PTerm]))]
, ibc_postulates :: ![Name]
, ibc_externs :: ![(Name, Int)]
, ibc_parsedSpan :: !(Maybe FC)
, ibc_usage :: ![(Name, Int)]
, ibc_exports :: ![Name]
, ibc_autohints :: ![(Name, Name)]
, ibc_deprecated :: ![(Name, String)]
, ibc_defs :: ![(Name, Def)]
, ibc_total :: ![(Name, Totality)]
, ibc_injective :: ![(Name, Injectivity)]
, ibc_access :: ![(Name, Accessibility)]
, ibc_fragile :: ![(Name, String)]
, ibc_constraints :: ![(FC, UConstraint)]
}
deriving Show
{-!
deriving instance Binary IBCFile
!-}
initIBC :: IBCFile
initIBC = IBCFile ibcVersion "" [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] Nothing [] [] [] [] [] [] [] [] [] []
hasValidIBCVersion :: FilePath -> Idris Bool
hasValidIBCVersion fp = do
archiveFile <- runIO $ B.readFile fp
case toArchiveOrFail archiveFile of
Left _ -> return False
Right archive -> do ver <- getEntry 0 "ver" archive
return (ver == ibcVersion)
loadIBC :: Bool -- ^ True = reexport, False = make everything private
-> IBCPhase
-> FilePath -> Idris ()
loadIBC reexport phase fp
= do imps <- getImported
case lookup fp imps of
Nothing -> load True
Just p -> if (not p && reexport) then load False else return ()
where
load fullLoad = do
logIBC 1 $ "Loading ibc " ++ fp ++ " " ++ show reexport
archiveFile <- runIO $ B.readFile fp
case toArchiveOrFail archiveFile of
Left _ -> do
ifail $ fp ++ " isn't loadable, it may have an old ibc format.\n"
++ "Please clean and rebuild it."
Right archive -> do
if fullLoad
then process reexport phase archive fp
else unhide phase archive
addImported reexport fp
-- | Load an entire package from its index file
loadPkgIndex :: String -> Idris ()
loadPkgIndex pkg = do ddir <- runIO getIdrisLibDir
addImportDir (ddir </> pkg)
fp <- findPkgIndex pkg
loadIBC True IBC_Building fp
makeEntry :: (Binary b) => String -> [b] -> Maybe Entry
makeEntry name val = if L.null val
then Nothing
else Just $ toEntry name 0 (encode val)
entries :: IBCFile -> [Entry]
entries i = catMaybes [Just $ toEntry "ver" 0 (encode $ ver i),
makeEntry "sourcefile" (sourcefile i),
makeEntry "ibc_imports" (ibc_imports i),
makeEntry "ibc_importdirs" (ibc_importdirs i),
makeEntry "ibc_implicits" (ibc_implicits i),
makeEntry "ibc_fixes" (ibc_fixes i),
makeEntry "ibc_statics" (ibc_statics i),
makeEntry "ibc_classes" (ibc_classes i),
makeEntry "ibc_records" (ibc_records i),
makeEntry "ibc_instances" (ibc_instances i),
makeEntry "ibc_dsls" (ibc_dsls i),
makeEntry "ibc_datatypes" (ibc_datatypes i),
makeEntry "ibc_optimise" (ibc_optimise i),
makeEntry "ibc_syntax" (ibc_syntax i),
makeEntry "ibc_keywords" (ibc_keywords i),
makeEntry "ibc_objs" (ibc_objs i),
makeEntry "ibc_libs" (ibc_libs i),
makeEntry "ibc_cgflags" (ibc_cgflags i),
makeEntry "ibc_dynamic_libs" (ibc_dynamic_libs i),
makeEntry "ibc_hdrs" (ibc_hdrs i),
makeEntry "ibc_totcheckfail" (ibc_totcheckfail i),
makeEntry "ibc_flags" (ibc_flags i),
makeEntry "ibc_fninfo" (ibc_fninfo i),
makeEntry "ibc_cg" (ibc_cg i),
makeEntry "ibc_docstrings" (ibc_docstrings i),
makeEntry "ibc_moduledocs" (ibc_moduledocs i),
makeEntry "ibc_transforms" (ibc_transforms i),
makeEntry "ibc_errRev" (ibc_errRev i),
makeEntry "ibc_coercions" (ibc_coercions i),
makeEntry "ibc_lineapps" (ibc_lineapps i),
makeEntry "ibc_namehints" (ibc_namehints i),
makeEntry "ibc_metainformation" (ibc_metainformation i),
makeEntry "ibc_errorhandlers" (ibc_errorhandlers i),
makeEntry "ibc_function_errorhandlers" (ibc_function_errorhandlers i),
makeEntry "ibc_metavars" (ibc_metavars i),
makeEntry "ibc_patdefs" (ibc_patdefs i),
makeEntry "ibc_postulates" (ibc_postulates i),
makeEntry "ibc_externs" (ibc_externs i),
toEntry "ibc_parsedSpan" 0 . encode <$> ibc_parsedSpan i,
makeEntry "ibc_usage" (ibc_usage i),
makeEntry "ibc_exports" (ibc_exports i),
makeEntry "ibc_autohints" (ibc_autohints i),
makeEntry "ibc_deprecated" (ibc_deprecated i),
makeEntry "ibc_defs" (ibc_defs i),
makeEntry "ibc_total" (ibc_total i),
makeEntry "ibc_injective" (ibc_injective i),
makeEntry "ibc_access" (ibc_access i),
makeEntry "ibc_fragile" (ibc_fragile i)]
-- TODO: Put this back in shortly after minimising/pruning constraints
-- makeEntry "ibc_constraints" (ibc_constraints i)]
writeArchive :: FilePath -> IBCFile -> Idris ()
writeArchive fp i = do let a = L.foldl (\x y -> addEntryToArchive y x) emptyArchive (entries i)
runIO $ B.writeFile fp (fromArchive a)
writeIBC :: FilePath -> FilePath -> Idris ()
writeIBC src f
= do logIBC 1 $ "Writing ibc " ++ show f
i <- getIState
-- case (Data.List.map fst (idris_metavars i)) \\ primDefs of
-- (_:_) -> ifail "Can't write ibc when there are unsolved metavariables"
-- [] -> return ()
resetNameIdx
ibcf <- mkIBC (ibc_write i) (initIBC { sourcefile = src })
idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f)
writeArchive f ibcf
logIBC 1 "Written")
(\c -> do logIBC 1 $ "Failed " ++ pshow i c)
return ()
-- | Write a package index containing all the imports in the current
-- IState Used for ':search' of an entire package, to ensure
-- everything is loaded.
writePkgIndex :: FilePath -> Idris ()
writePkgIndex f
= do i <- getIState
let imps = map (\ (x, y) -> (True, x)) $ idris_imported i
logIBC 1 $ "Writing package index " ++ show f ++ " including\n" ++
show (map snd imps)
resetNameIdx
let ibcf = initIBC { ibc_imports = imps }
idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f)
writeArchive f ibcf
logIBC 1 "Written")
(\c -> do logIBC 1 $ "Failed " ++ pshow i c)
return ()
mkIBC :: [IBCWrite] -> IBCFile -> Idris IBCFile
mkIBC [] f = return f
mkIBC (i:is) f = do ist <- getIState
logIBC 5 $ show i ++ " " ++ show (L.length is)
f' <- ibc ist i f
mkIBC is f'
ibc :: IState -> IBCWrite -> IBCFile -> Idris IBCFile
ibc i (IBCFix d) f = return f { ibc_fixes = d : ibc_fixes f }
ibc i (IBCImp n) f = case lookupCtxtExact n (idris_implicits i) of
Just v -> return f { ibc_implicits = (n,v): ibc_implicits f }
_ -> ifail "IBC write failed"
ibc i (IBCStatic n) f
= case lookupCtxtExact n (idris_statics i) of
Just v -> return f { ibc_statics = (n,v): ibc_statics f }
_ -> ifail "IBC write failed"
ibc i (IBCClass n) f
= case lookupCtxtExact n (idris_classes i) of
Just v -> return f { ibc_classes = (n,v): ibc_classes f }
_ -> ifail "IBC write failed"
ibc i (IBCRecord n) f
= case lookupCtxtExact n (idris_records i) of
Just v -> return f { ibc_records = (n,v): ibc_records f }
_ -> ifail "IBC write failed"
ibc i (IBCInstance int res n ins) f
= return f { ibc_instances = (int, res, n, ins) : ibc_instances f }
ibc i (IBCDSL n) f
= case lookupCtxtExact n (idris_dsls i) of
Just v -> return f { ibc_dsls = (n,v): ibc_dsls f }
_ -> ifail "IBC write failed"
ibc i (IBCData n) f
= case lookupCtxtExact n (idris_datatypes i) of
Just v -> return f { ibc_datatypes = (n,v): ibc_datatypes f }
_ -> ifail "IBC write failed"
ibc i (IBCOpt n) f = case lookupCtxtExact n (idris_optimisation i) of
Just v -> return f { ibc_optimise = (n,v): ibc_optimise f }
_ -> ifail "IBC write failed"
ibc i (IBCSyntax n) f = return f { ibc_syntax = n : ibc_syntax f }
ibc i (IBCKeyword n) f = return f { ibc_keywords = n : ibc_keywords f }
ibc i (IBCImport n) f = return f { ibc_imports = n : ibc_imports f }
ibc i (IBCImportDir n) f = return f { ibc_importdirs = n : ibc_importdirs f }
ibc i (IBCObj tgt n) f = return f { ibc_objs = (tgt, n) : ibc_objs f }
ibc i (IBCLib tgt n) f = return f { ibc_libs = (tgt, n) : ibc_libs f }
ibc i (IBCCGFlag tgt n) f = return f { ibc_cgflags = (tgt, n) : ibc_cgflags f }
ibc i (IBCDyLib n) f = return f {ibc_dynamic_libs = n : ibc_dynamic_libs f }
ibc i (IBCHeader tgt n) f = return f { ibc_hdrs = (tgt, n) : ibc_hdrs f }
ibc i (IBCDef n) f
= do f' <- case lookupDefExact n (tt_ctxt i) of
Just v -> return f { ibc_defs = (n,v) : ibc_defs f }
_ -> ifail "IBC write failed"
case lookupCtxtExact n (idris_patdefs i) of
Just v -> return f' { ibc_patdefs = (n,v) : ibc_patdefs f }
_ -> return f' -- Not a pattern definition
ibc i (IBCDoc n) f = case lookupCtxtExact n (idris_docstrings i) of
Just v -> return f { ibc_docstrings = (n,v) : ibc_docstrings f }
_ -> ifail "IBC write failed"
ibc i (IBCCG n) f = case lookupCtxtExact n (idris_callgraph i) of
Just v -> return f { ibc_cg = (n,v) : ibc_cg f }
_ -> ifail "IBC write failed"
ibc i (IBCCoercion n) f = return f { ibc_coercions = n : ibc_coercions f }
ibc i (IBCAccess n a) f = return f { ibc_access = (n,a) : ibc_access f }
ibc i (IBCFlags n a) f = return f { ibc_flags = (n,a) : ibc_flags f }
ibc i (IBCFnInfo n a) f = return f { ibc_fninfo = (n,a) : ibc_fninfo f }
ibc i (IBCTotal n a) f = return f { ibc_total = (n,a) : ibc_total f }
ibc i (IBCInjective n a) f = return f { ibc_injective = (n,a) : ibc_injective f }
ibc i (IBCTrans n t) f = return f { ibc_transforms = (n, t) : ibc_transforms f }
ibc i (IBCErrRev t) f = return f { ibc_errRev = t : ibc_errRev f }
ibc i (IBCLineApp fp l t) f
= return f { ibc_lineapps = (fp,l,t) : ibc_lineapps f }
ibc i (IBCNameHint (n, ty)) f
= return f { ibc_namehints = (n, ty) : ibc_namehints f }
ibc i (IBCMetaInformation n m) f = return f { ibc_metainformation = (n,m) : ibc_metainformation f }
ibc i (IBCErrorHandler n) f = return f { ibc_errorhandlers = n : ibc_errorhandlers f }
ibc i (IBCFunctionErrorHandler fn a n) f =
return f { ibc_function_errorhandlers = (fn, a, n) : ibc_function_errorhandlers f }
ibc i (IBCMetavar n) f =
case lookup n (idris_metavars i) of
Nothing -> return f
Just t -> return f { ibc_metavars = (n, t) : ibc_metavars f }
ibc i (IBCPostulate n) f = return f { ibc_postulates = n : ibc_postulates f }
ibc i (IBCExtern n) f = return f { ibc_externs = n : ibc_externs f }
ibc i (IBCTotCheckErr fc err) f = return f { ibc_totcheckfail = (fc, err) : ibc_totcheckfail f }
ibc i (IBCParsedRegion fc) f = return f { ibc_parsedSpan = Just fc }
ibc i (IBCModDocs n) f = case lookupCtxtExact n (idris_moduledocs i) of
Just v -> return f { ibc_moduledocs = (n,v) : ibc_moduledocs f }
_ -> ifail "IBC write failed"
ibc i (IBCUsage n) f = return f { ibc_usage = n : ibc_usage f }
ibc i (IBCExport n) f = return f { ibc_exports = n : ibc_exports f }
ibc i (IBCAutoHint n h) f = return f { ibc_autohints = (n, h) : ibc_autohints f }
ibc i (IBCDeprecate n r) f = return f { ibc_deprecated = (n, r) : ibc_deprecated f }
ibc i (IBCFragile n r) f = return f { ibc_fragile = (n,r) : ibc_fragile f }
ibc i (IBCConstraint fc u) f = return f { ibc_constraints = (fc, u) : ibc_constraints f }
getEntry :: (Binary b, NFData b) => b -> FilePath -> Archive -> Idris b
getEntry alt f a = case findEntryByPath f a of
Nothing -> return alt
Just e -> return $! (force . decode . fromEntry) e
unhide :: IBCPhase -> Archive -> Idris ()
unhide phase ar = do
processImports True phase ar
processAccess True phase ar
process :: Bool -- ^ Reexporting
-> IBCPhase
-> Archive -> FilePath -> Idris ()
process reexp phase archive fn = do
ver <- getEntry 0 "ver" archive
when (ver /= ibcVersion) $ do
logIBC 1 "ibc out of date"
let e = if ver < ibcVersion
then " an earlier " else " a later "
ifail $ "Incompatible ibc version.\nThis library was built with"
++ e ++ "version of Idris.\n" ++ "Please clean and rebuild."
source <- getEntry "" "sourcefile" archive
srcok <- runIO $ doesFileExist source
when srcok $ timestampOlder source fn
processImportDirs archive
processImports reexp phase archive
processImplicits archive
processInfix archive
processStatics archive
processClasses archive
processRecords archive
processInstances archive
processDSLs archive
processDatatypes archive
processOptimise archive
processSyntax archive
processKeywords archive
processObjectFiles archive
processLibs archive
processCodegenFlags archive
processDynamicLibs archive
processHeaders archive
processPatternDefs archive
processFlags archive
processFnInfo archive
processTotalityCheckError archive
processCallgraph archive
processDocs archive
processModuleDocs archive
processCoercions archive
processTransforms archive
processErrRev archive
processLineApps archive
processNameHints archive
processMetaInformation archive
processErrorHandlers archive
processFunctionErrorHandlers archive
processMetaVars archive
processPostulates archive
processExterns archive
processParsedSpan archive
processUsage archive
processExports archive
processAutoHints archive
processDeprecate archive
processDefs archive
processTotal archive
processInjective archive
processAccess reexp phase archive
processFragile archive
processConstraints archive
timestampOlder :: FilePath -> FilePath -> Idris ()
timestampOlder src ibc = do
srct <- runIO $ getModificationTime src
ibct <- runIO $ getModificationTime ibc
if (srct > ibct)
then ifail $ unlines [ "Module needs reloading:"
, unwords ["\tSRC :", show src]
, unwords ["\tModified at:", show srct]
, unwords ["\tIBC :", show ibc]
, unwords ["\tModified at:", show ibct]
]
else return ()
processPostulates :: Archive -> Idris ()
processPostulates ar = do
ns <- getEntry [] "ibc_postulates" ar
updateIState (\i -> i { idris_postulates = idris_postulates i `S.union` S.fromList ns })
processExterns :: Archive -> Idris ()
processExterns ar = do
ns <- getEntry [] "ibc_externs" ar
updateIState (\i -> i{ idris_externs = idris_externs i `S.union` S.fromList ns })
processParsedSpan :: Archive -> Idris ()
processParsedSpan ar = do
fc <- getEntry Nothing "ibc_parsedSpan" ar
updateIState (\i -> i { idris_parsedSpan = fc })
processUsage :: Archive -> Idris ()
processUsage ar = do
ns <- getEntry [] "ibc_usage" ar
updateIState (\i -> i { idris_erasureUsed = ns ++ idris_erasureUsed i })
processExports :: Archive -> Idris ()
processExports ar = do
ns <- getEntry [] "ibc_exports" ar
updateIState (\i -> i { idris_exports = ns ++ idris_exports i })
processAutoHints :: Archive -> Idris ()
processAutoHints ar = do
ns <- getEntry [] "ibc_autohints" ar
mapM_ (\(n,h) -> addAutoHint n h) ns
processDeprecate :: Archive -> Idris ()
processDeprecate ar = do
ns <- getEntry [] "ibc_deprecated" ar
mapM_ (\(n,reason) -> addDeprecated n reason) ns
processFragile :: Archive -> Idris ()
processFragile ar = do
ns <- getEntry [] "ibc_fragile" ar
mapM_ (\(n,reason) -> addFragile n reason) ns
processConstraints :: Archive -> Idris ()
processConstraints ar = do
cs <- getEntry [] "ibc_constraints" ar
mapM_ (\ (fc, c) -> addConstraints fc (0, [c])) cs
processImportDirs :: Archive -> Idris ()
processImportDirs ar = do
fs <- getEntry [] "ibc_importdirs" ar
mapM_ addImportDir fs
processImports :: Bool -> IBCPhase -> Archive -> Idris ()
processImports reexp phase ar = do
fs <- getEntry [] "ibc_imports" ar
mapM_ (\(re, f) -> do
i <- getIState
ibcsd <- valIBCSubDir i
ids <- allImportDirs
fp <- findImport ids ibcsd f
-- if (f `elem` imported i)
-- then logLvl 1 $ "Already read " ++ f
putIState (i { imported = f : imported i })
let phase' = case phase of
IBC_REPL _ -> IBC_REPL False
p -> p
case fp of
LIDR fn -> do
logIBC 1 $ "Failed at " ++ fn
ifail "Must be an ibc"
IDR fn -> do
logIBC 1 $ "Failed at " ++ fn
ifail "Must be an ibc"
IBC fn src -> loadIBC (reexp && re) phase' fn) fs
processImplicits :: Archive -> Idris ()
processImplicits ar = do
imps <- getEntry [] "ibc_implicits" ar
mapM_ (\ (n, imp) -> do
i <- getIState
case lookupDefAccExact n False (tt_ctxt i) of
Just (n, Hidden) -> return ()
Just (n, Private) -> return ()
_ -> putIState (i { idris_implicits = addDef n imp (idris_implicits i) })) imps
processInfix :: Archive -> Idris ()
processInfix ar = do
f <- getEntry [] "ibc_fixes" ar
updateIState (\i -> i { idris_infixes = sort $ f ++ idris_infixes i })
processStatics :: Archive -> Idris ()
processStatics ar = do
ss <- getEntry [] "ibc_statics" ar
mapM_ (\ (n, s) ->
updateIState (\i -> i { idris_statics = addDef n s (idris_statics i) })) ss
processClasses :: Archive -> Idris ()
processClasses ar = do
cs <- getEntry [] "ibc_classes" ar
mapM_ (\ (n, c) -> do
i <- getIState
-- Don't lose instances from previous IBCs, which
-- could have loaded in any order
let is = case lookupCtxtExact n (idris_classes i) of
Just (CI _ _ _ _ _ ins _) -> ins
_ -> []
let c' = c { class_instances = class_instances c ++ is }
putIState (i { idris_classes = addDef n c' (idris_classes i) })) cs
processRecords :: Archive -> Idris ()
processRecords ar = do
rs <- getEntry [] "ibc_records" ar
mapM_ (\ (n, r) ->
updateIState (\i -> i { idris_records = addDef n r (idris_records i) })) rs
processInstances :: Archive -> Idris ()
processInstances ar = do
cs <- getEntry [] "ibc_instances" ar
mapM_ (\ (i, res, n, ins) -> addInstance i res n ins) cs
processDSLs :: Archive -> Idris ()
processDSLs ar = do
cs <- getEntry [] "ibc_dsls" ar
mapM_ (\ (n, c) -> updateIState (\i ->
i { idris_dsls = addDef n c (idris_dsls i) })) cs
processDatatypes :: Archive -> Idris ()
processDatatypes ar = do
cs <- getEntry [] "ibc_datatypes" ar
mapM_ (\ (n, c) -> updateIState (\i ->
i { idris_datatypes = addDef n c (idris_datatypes i) })) cs
processOptimise :: Archive -> Idris ()
processOptimise ar = do
cs <- getEntry [] "ibc_optimise" ar
mapM_ (\ (n, c) -> updateIState (\i ->
i { idris_optimisation = addDef n c (idris_optimisation i) })) cs
processSyntax :: Archive -> Idris ()
processSyntax ar = do
s <- getEntry [] "ibc_syntax" ar
updateIState (\i -> i { syntax_rules = updateSyntaxRules s (syntax_rules i) })
processKeywords :: Archive -> Idris ()
processKeywords ar = do
k <- getEntry [] "ibc_keywords" ar
updateIState (\i -> i { syntax_keywords = k ++ syntax_keywords i })
processObjectFiles :: Archive -> Idris ()
processObjectFiles ar = do
os <- getEntry [] "ibc_objs" ar
mapM_ (\ (cg, obj) -> do
dirs <- allImportDirs
o <- runIO $ findInPath dirs obj
addObjectFile cg o) os
processLibs :: Archive -> Idris ()
processLibs ar = do
ls <- getEntry [] "ibc_libs" ar
mapM_ (uncurry addLib) ls
processCodegenFlags :: Archive -> Idris ()
processCodegenFlags ar = do
ls <- getEntry [] "ibc_cgflags" ar
mapM_ (uncurry addFlag) ls
processDynamicLibs :: Archive -> Idris ()
processDynamicLibs ar = do
ls <- getEntry [] "ibc_dynamic_libs" ar
res <- mapM (addDyLib . return) ls
mapM_ checkLoad res
where
checkLoad (Left _) = return ()
checkLoad (Right err) = ifail err
processHeaders :: Archive -> Idris ()
processHeaders ar = do
hs <- getEntry [] "ibc_hdrs" ar
mapM_ (uncurry addHdr) hs
processPatternDefs :: Archive -> Idris ()
processPatternDefs ar = do
ds <- getEntry [] "ibc_patdefs" ar
mapM_ (\ (n, d) -> updateIState (\i ->
i { idris_patdefs = addDef n (force d) (idris_patdefs i) })) ds
processDefs :: Archive -> Idris ()
processDefs ar = do
ds <- getEntry [] "ibc_defs" ar
mapM_ (\ (n, d) -> do
d' <- updateDef d
case d' of
TyDecl _ _ -> return ()
_ -> do
logIBC 1 $ "SOLVING " ++ show n
solveDeferred emptyFC n
updateIState (\i -> i { tt_ctxt = addCtxtDef n d' (tt_ctxt i) })) ds
where
updateDef (CaseOp c t args o s cd) = do
o' <- mapM updateOrig o
cd' <- updateCD cd
return $ CaseOp c t args o' s cd'
updateDef t = return t
updateOrig (Left t) = liftM Left (update t)
updateOrig (Right (l, r)) = do
l' <- update l
r' <- update r
return $ Right (l', r')
updateCD (CaseDefs (ts, t) (cs, c) (is, i) (rs, r)) = do
c' <- updateSC c
r' <- updateSC r
return $ CaseDefs (cs, c') (cs, c') (cs, c') (rs, r')
updateSC (Case t n alts) = do
alts' <- mapM updateAlt alts
return (Case t n alts')
updateSC (ProjCase t alts) = do
alts' <- mapM updateAlt alts
return (ProjCase t alts')
updateSC (STerm t) = do
t' <- update t
return (STerm t')
updateSC c = return c
updateAlt (ConCase n i ns t) = do
t' <- updateSC t
return (ConCase n i ns t')
updateAlt (FnCase n ns t) = do
t' <- updateSC t
return (FnCase n ns t')
updateAlt (ConstCase c t) = do
t' <- updateSC t
return (ConstCase c t')
updateAlt (SucCase n t) = do
t' <- updateSC t
return (SucCase n t')
updateAlt (DefaultCase t) = do
t' <- updateSC t
return (DefaultCase t')
-- We get a lot of repetition in sub terms and can save a fair chunk
-- of memory if we make sure they're shared. addTT looks for a term
-- and returns it if it exists already, while also keeping stats of
-- how many times a subterm is repeated.
update t = do
tm <- addTT t
case tm of
Nothing -> update' t
Just t' -> return t'
update' (P t n ty) = do
n' <- getSymbol n
return $ P t n' ty
update' (App s f a) = liftM2 (App s) (update' f) (update' a)
update' (Bind n b sc) = do
b' <- updateB b
sc' <- update sc
return $ Bind n b' sc'
where
updateB (Let t v) = liftM2 Let (update' t) (update' v)
updateB b = do
ty' <- update' (binderTy b)
return (b { binderTy = ty' })
update' (Proj t i) = do
t' <- update' t
return $ Proj t' i
update' t = return t
processDocs :: Archive -> Idris ()
processDocs ar = do
ds <- getEntry [] "ibc_docstrings" ar
mapM_ (\(n, a) -> addDocStr n (fst a) (snd a)) ds
processModuleDocs :: Archive -> Idris ()
processModuleDocs ar = do
ds <- getEntry [] "ibc_moduledocs" ar
mapM_ (\ (n, d) -> updateIState (\i ->
i { idris_moduledocs = addDef n d (idris_moduledocs i) })) ds
processAccess :: Bool -- ^ Reexporting?
-> IBCPhase
-> Archive -> Idris ()
processAccess reexp phase ar = do
ds <- getEntry [] "ibc_access" ar
mapM_ (\ (n, a_in) -> do
let a = if reexp then a_in else Hidden
logIBC 3 $ "Setting " ++ show (a, n) ++ " to " ++ show a
updateIState (\i -> i { tt_ctxt = setAccess n a (tt_ctxt i) })
if (not reexp)
then do
logIBC 1 $ "Not exporting " ++ show n
setAccessibility n Hidden
else logIBC 1 $ "Exporting " ++ show n
-- Everything should be available at the REPL from
-- things imported publicly
when (phase == IBC_REPL True) $ setAccessibility n Public) ds
processFlags :: Archive -> Idris ()
processFlags ar = do
ds <- getEntry [] "ibc_flags" ar
mapM_ (\ (n, a) -> setFlags n a) ds
processFnInfo :: Archive -> Idris ()
processFnInfo ar = do
ds <- getEntry [] "ibc_fninfo" ar
mapM_ (\ (n, a) -> setFnInfo n a) ds
processTotal :: Archive -> Idris ()
processTotal ar = do
ds <- getEntry [] "ibc_total" ar
mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setTotal n a (tt_ctxt i) })) ds
processInjective :: Archive -> Idris ()
processInjective ar = do
ds <- getEntry [] "ibc_injective" ar
mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setInjective n a (tt_ctxt i) })) ds
processTotalityCheckError :: Archive -> Idris ()
processTotalityCheckError ar = do
es <- getEntry [] "ibc_totcheckfail" ar
updateIState (\i -> i { idris_totcheckfail = idris_totcheckfail i ++ es })
processCallgraph :: Archive -> Idris ()
processCallgraph ar = do
ds <- getEntry [] "ibc_cg" ar
mapM_ (\ (n, a) -> addToCG n a) ds
processCoercions :: Archive -> Idris ()
processCoercions ar = do
ns <- getEntry [] "ibc_coercions" ar
mapM_ (\ n -> addCoercion n) ns
processTransforms :: Archive -> Idris ()
processTransforms ar = do
ts <- getEntry [] "ibc_transforms" ar
mapM_ (\ (n, t) -> addTrans n t) ts
processErrRev :: Archive -> Idris ()
processErrRev ar = do
ts <- getEntry [] "ibc_errRev" ar
mapM_ addErrRev ts
processLineApps :: Archive -> Idris ()
processLineApps ar = do
ls <- getEntry [] "ibc_lineapps" ar
mapM_ (\ (f, i, t) -> addInternalApp f i t) ls
processNameHints :: Archive -> Idris ()
processNameHints ar = do
ns <- getEntry [] "ibc_namehints" ar
mapM_ (\ (n, ty) -> addNameHint n ty) ns
processMetaInformation :: Archive -> Idris ()
processMetaInformation ar = do
ds <- getEntry [] "ibc_metainformation" ar
mapM_ (\ (n, m) -> updateIState (\i ->
i { tt_ctxt = setMetaInformation n m (tt_ctxt i) })) ds
processErrorHandlers :: Archive -> Idris ()
processErrorHandlers ar = do
ns <- getEntry [] "ibc_errorhandlers" ar
updateIState (\i -> i { idris_errorhandlers = idris_errorhandlers i ++ ns })
processFunctionErrorHandlers :: Archive -> Idris ()
processFunctionErrorHandlers ar = do
ns <- getEntry [] "ibc_function_errorhandlers" ar
mapM_ (\ (fn,arg,handler) -> addFunctionErrorHandlers fn arg [handler]) ns
processMetaVars :: Archive -> Idris ()
processMetaVars ar = do
ns <- getEntry [] "ibc_metavars" ar
updateIState (\i -> i { idris_metavars = L.reverse ns ++ idris_metavars i })
----- For Cheapskate and docstrings
instance Binary a => Binary (D.Docstring a) where
put (D.DocString opts lines) = do put opts ; put lines
get = do opts <- get
lines <- get
return (D.DocString opts lines)
instance Binary CT.Options where
put (CT.Options x1 x2 x3 x4) = do put x1 ; put x2 ; put x3 ; put x4
get = do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (CT.Options x1 x2 x3 x4)
instance Binary D.DocTerm where
put D.Unchecked = putWord8 0
put (D.Checked t) = putWord8 1 >> put t
put (D.Example t) = putWord8 2 >> put t
put (D.Failing e) = putWord8 3 >> put e
get = do i <- getWord8
case i of
0 -> return D.Unchecked
1 -> fmap D.Checked get
2 -> fmap D.Example get
3 -> fmap D.Failing get
_ -> error "Corrupted binary data for DocTerm"
instance Binary a => Binary (D.Block a) where
put (D.Para lines) = do putWord8 0 ; put lines
put (D.Header i lines) = do putWord8 1 ; put i ; put lines
put (D.Blockquote bs) = do putWord8 2 ; put bs
put (D.List b t xs) = do putWord8 3 ; put b ; put t ; put xs
put (D.CodeBlock attr txt src) = do putWord8 4 ; put attr ; put txt ; put src
put (D.HtmlBlock txt) = do putWord8 5 ; put txt
put D.HRule = putWord8 6
get = do i <- getWord8
case i of
0 -> fmap D.Para get
1 -> liftM2 D.Header get get
2 -> fmap D.Blockquote get
3 -> liftM3 D.List get get get
4 -> liftM3 D.CodeBlock get get get
5 -> liftM D.HtmlBlock get
6 -> return D.HRule
_ -> error "Corrupted binary data for Block"
instance Binary a => Binary (D.Inline a) where
put (D.Str txt) = do putWord8 0 ; put txt
put D.Space = putWord8 1
put D.SoftBreak = putWord8 2
put D.LineBreak = putWord8 3
put (D.Emph xs) = putWord8 4 >> put xs
put (D.Strong xs) = putWord8 5 >> put xs
put (D.Code xs tm) = putWord8 6 >> put xs >> put tm
put (D.Link a b c) = putWord8 7 >> put a >> put b >> put c
put (D.Image a b c) = putWord8 8 >> put a >> put b >> put c
put (D.Entity a) = putWord8 9 >> put a
put (D.RawHtml x) = putWord8 10 >> put x
get = do i <- getWord8
case i of
0 -> liftM D.Str get
1 -> return D.Space
2 -> return D.SoftBreak
3 -> return D.LineBreak
4 -> liftM D.Emph get
5 -> liftM D.Strong get
6 -> liftM2 D.Code get get
7 -> liftM3 D.Link get get get
8 -> liftM3 D.Image get get get
9 -> liftM D.Entity get
10 -> liftM D.RawHtml get
_ -> error "Corrupted binary data for Inline"
instance Binary CT.ListType where
put (CT.Bullet c) = putWord8 0 >> put c
put (CT.Numbered nw i) = putWord8 1 >> put nw >> put i
get = do i <- getWord8
case i of
0 -> liftM CT.Bullet get
1 -> liftM2 CT.Numbered get get
_ -> error "Corrupted binary data for ListType"
instance Binary CT.CodeAttr where
put (CT.CodeAttr a b) = put a >> put b
get = liftM2 CT.CodeAttr get get
instance Binary CT.NumWrapper where
put (CT.PeriodFollowing) = putWord8 0
put (CT.ParenFollowing) = putWord8 1
get = do i <- getWord8
case i of
0 -> return CT.PeriodFollowing
1 -> return CT.ParenFollowing
_ -> error "Corrupted binary data for NumWrapper"
----- Generated by 'derive'
instance Binary SizeChange where
put x
= case x of
Smaller -> putWord8 0
Same -> putWord8 1
Bigger -> putWord8 2
Unknown -> putWord8 3
get
= do i <- getWord8
case i of
0 -> return Smaller
1 -> return Same
2 -> return Bigger
3 -> return Unknown
_ -> error "Corrupted binary data for SizeChange"
instance Binary CGInfo where
put (CGInfo x1 x2 x3)
= do put x1
-- put x3 -- Already used SCG info for totality check
put x3
get
= do x1 <- get
x3 <- get
return (CGInfo x1 [] x3)
instance Binary CaseType where
put x = case x of
Updatable -> putWord8 0
Shared -> putWord8 1
get = do i <- getWord8
case i of
0 -> return Updatable
1 -> return Shared
_ -> error "Corrupted binary data for CaseType"
instance Binary SC where
put x
= case x of
Case x1 x2 x3 -> do putWord8 0
put x1
put x2
put x3
ProjCase x1 x2 -> do putWord8 1
put x1
put x2
STerm x1 -> do putWord8 2
put x1
UnmatchedCase x1 -> do putWord8 3
put x1
ImpossibleCase -> do putWord8 4
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
x3 <- get
return (Case x1 x2 x3)
1 -> do x1 <- get
x2 <- get
return (ProjCase x1 x2)
2 -> do x1 <- get
return (STerm x1)
3 -> do x1 <- get
return (UnmatchedCase x1)
4 -> return ImpossibleCase
_ -> error "Corrupted binary data for SC"
instance Binary CaseAlt where
put x
= {-# SCC "putCaseAlt" #-}
case x of
ConCase x1 x2 x3 x4 -> do putWord8 0
put x1
put x2
put x3
put x4
ConstCase x1 x2 -> do putWord8 1
put x1
put x2
DefaultCase x1 -> do putWord8 2
put x1
FnCase x1 x2 x3 -> do putWord8 3
put x1
put x2
put x3
SucCase x1 x2 -> do putWord8 4
put x1
put x2
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (ConCase x1 x2 x3 x4)
1 -> do x1 <- get
x2 <- get
return (ConstCase x1 x2)
2 -> do x1 <- get
return (DefaultCase x1)
3 -> do x1 <- get
x2 <- get
x3 <- get
return (FnCase x1 x2 x3)
4 -> do x1 <- get
x2 <- get
return (SucCase x1 x2)
_ -> error "Corrupted binary data for CaseAlt"
instance Binary CaseDefs where
put (CaseDefs x1 x2 x3 x4)
= do -- don't need totality checked or inlined versions
put x2
put x4
get
= do x2 <- get
x4 <- get
return (CaseDefs x2 x2 x2 x4)
instance Binary CaseInfo where
put x@(CaseInfo x1 x2 x3) = do put x1
put x2
put x3
get = do x1 <- get
x2 <- get
x3 <- get
return (CaseInfo x1 x2 x3)
instance Binary Def where
put x
= {-# SCC "putDef" #-}
case x of
Function x1 x2 -> do putWord8 0
put x1
put x2
TyDecl x1 x2 -> do putWord8 1
put x1
put x2
-- all primitives just get added at the start, don't write
Operator x1 x2 x3 -> do return ()
-- no need to add/load original patterns, because they're not
-- used again after totality checking
CaseOp x1 x2 x3 _ _ x4 -> do putWord8 3
put x1
put x2
put x3
put x4
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
return (Function x1 x2)
1 -> do x1 <- get
x2 <- get
return (TyDecl x1 x2)
-- Operator isn't written, don't read
3 -> do x1 <- get
x2 <- get
x3 <- get
-- x4 <- get
-- x3 <- get always []
x5 <- get
return (CaseOp x1 x2 x3 [] [] x5)
_ -> error "Corrupted binary data for Def"
instance Binary Accessibility where
put x
= case x of
Public -> putWord8 0
Frozen -> putWord8 1
Private -> putWord8 2
Hidden -> putWord8 3
get
= do i <- getWord8
case i of
0 -> return Public
1 -> return Frozen
2 -> return Private
3 -> return Hidden
_ -> error "Corrupted binary data for Accessibility"
safeToEnum :: (Enum a, Bounded a, Integral int) => String -> int -> a
safeToEnum label x' = result
where
x = fromIntegral x'
result
| x < fromEnum (minBound `asTypeOf` result)
|| x > fromEnum (maxBound `asTypeOf` result)
= error $ label ++ ": corrupted binary representation in IBC"
| otherwise = toEnum x
instance Binary PReason where
put x
= case x of
Other x1 -> do putWord8 0
put x1
Itself -> putWord8 1
NotCovering -> putWord8 2
NotPositive -> putWord8 3
Mutual x1 -> do putWord8 4
put x1
NotProductive -> putWord8 5
BelieveMe -> putWord8 6
UseUndef x1 -> do putWord8 7
put x1
ExternalIO -> putWord8 8
get
= do i <- getWord8
case i of
0 -> do x1 <- get
return (Other x1)
1 -> return Itself
2 -> return NotCovering
3 -> return NotPositive
4 -> do x1 <- get
return (Mutual x1)
5 -> return NotProductive
6 -> return BelieveMe
7 -> do x1 <- get
return (UseUndef x1)
8 -> return ExternalIO
_ -> error "Corrupted binary data for PReason"
instance Binary Totality where
put x
= case x of
Total x1 -> do putWord8 0
put x1
Partial x1 -> do putWord8 1
put x1
Unchecked -> do putWord8 2
Productive -> do putWord8 3
Generated -> do putWord8 4
get
= do i <- getWord8
case i of
0 -> do x1 <- get
return (Total x1)
1 -> do x1 <- get
return (Partial x1)
2 -> return Unchecked
3 -> return Productive
4 -> return Generated
_ -> error "Corrupted binary data for Totality"
instance Binary MetaInformation where
put x
= case x of
EmptyMI -> do putWord8 0
DataMI x1 -> do putWord8 1
put x1
get = do i <- getWord8
case i of
0 -> return EmptyMI
1 -> do x1 <- get
return (DataMI x1)
_ -> error "Corrupted binary data for MetaInformation"
instance Binary DataOpt where
put x = case x of
Codata -> putWord8 0
DefaultEliminator -> putWord8 1
DataErrRev -> putWord8 2
DefaultCaseFun -> putWord8 3
get = do i <- getWord8
case i of
0 -> return Codata
1 -> return DefaultEliminator
2 -> return DataErrRev
3 -> return DefaultCaseFun
_ -> error "Corrupted binary data for DataOpt"
instance Binary FnOpt where
put x
= case x of
Inlinable -> putWord8 0
TotalFn -> putWord8 1
Dictionary -> putWord8 2
AssertTotal -> putWord8 3
Specialise x -> do putWord8 4
put x
Coinductive -> putWord8 5
PartialFn -> putWord8 6
Implicit -> putWord8 7
Reflection -> putWord8 8
ErrorHandler -> putWord8 9
ErrorReverse -> putWord8 10
CoveringFn -> putWord8 11
NoImplicit -> putWord8 12
Constructor -> putWord8 13
CExport x1 -> do putWord8 14
put x1
AutoHint -> putWord8 15
PEGenerated -> putWord8 16
get
= do i <- getWord8
case i of
0 -> return Inlinable
1 -> return TotalFn
2 -> return Dictionary
3 -> return AssertTotal
4 -> do x <- get
return (Specialise x)
5 -> return Coinductive
6 -> return PartialFn
7 -> return Implicit
8 -> return Reflection
9 -> return ErrorHandler
10 -> return ErrorReverse
11 -> return CoveringFn
12 -> return NoImplicit
13 -> return Constructor
14 -> do x1 <- get
return $ CExport x1
15 -> return AutoHint
16 -> return PEGenerated
_ -> error "Corrupted binary data for FnOpt"
instance Binary Fixity where
put x
= case x of
Infixl x1 -> do putWord8 0
put x1
Infixr x1 -> do putWord8 1
put x1
InfixN x1 -> do putWord8 2
put x1
PrefixN x1 -> do putWord8 3
put x1
get
= do i <- getWord8
case i of
0 -> do x1 <- get
return (Infixl x1)
1 -> do x1 <- get
return (Infixr x1)
2 -> do x1 <- get
return (InfixN x1)
3 -> do x1 <- get
return (PrefixN x1)
_ -> error "Corrupted binary data for Fixity"
instance Binary FixDecl where
put (Fix x1 x2)
= do put x1
put x2
get
= do x1 <- get
x2 <- get
return (Fix x1 x2)
instance Binary ArgOpt where
put x
= case x of
HideDisplay -> putWord8 0
InaccessibleArg -> putWord8 1
AlwaysShow -> putWord8 2
UnknownImp -> putWord8 3
get
= do i <- getWord8
case i of
0 -> return HideDisplay
1 -> return InaccessibleArg
2 -> return AlwaysShow
3 -> return UnknownImp
_ -> error "Corrupted binary data for Static"
instance Binary Static where
put x
= case x of
Static -> putWord8 0
Dynamic -> putWord8 1
get
= do i <- getWord8
case i of
0 -> return Static
1 -> return Dynamic
_ -> error "Corrupted binary data for Static"
instance Binary Plicity where
put x
= case x of
Imp x1 x2 x3 x4 _ ->
do putWord8 0
put x1
put x2
put x3
put x4
Exp x1 x2 x3 ->
do putWord8 1
put x1
put x2
put x3
Constraint x1 x2 ->
do putWord8 2
put x1
put x2
TacImp x1 x2 x3 ->
do putWord8 3
put x1
put x2
put x3
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (Imp x1 x2 x3 x4 False)
1 -> do x1 <- get
x2 <- get
x3 <- get
return (Exp x1 x2 x3)
2 -> do x1 <- get
x2 <- get
return (Constraint x1 x2)
3 -> do x1 <- get
x2 <- get
x3 <- get
return (TacImp x1 x2 x3)
_ -> error "Corrupted binary data for Plicity"
instance (Binary t) => Binary (PDecl' t) where
put x
= case x of
PFix x1 x2 x3 -> do putWord8 0
put x1
put x2
put x3
PTy x1 x2 x3 x4 x5 x6 x7 x8
-> do putWord8 1
put x1
put x2
put x3
put x4
put x5
put x6
put x7
put x8
PClauses x1 x2 x3 x4 -> do putWord8 2
put x1
put x2
put x3
put x4
PData x1 x2 x3 x4 x5 x6 ->
do putWord8 3
put x1
put x2
put x3
put x4
put x5
put x6
PParams x1 x2 x3 -> do putWord8 4
put x1
put x2
put x3
PNamespace x1 x2 x3 -> do putWord8 5
put x1
put x2
put x3
PRecord x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 ->
do putWord8 6
put x1
put x2
put x3
put x4
put x5
put x6
put x7
put x8
put x9
put x10
put x11
put x12
PClass x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12
-> do putWord8 7
put x1
put x2
put x3
put x4
put x5
put x6
put x7
put x8
put x9
put x10
put x11
put x12
PInstance x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 ->
do putWord8 8
put x1
put x2
put x3
put x4
put x5
put x6
put x7
put x8
put x9
put x10
put x11
put x12
put x13
put x14
put x15
PDSL x1 x2 -> do putWord8 9
put x1
put x2
PCAF x1 x2 x3 -> do putWord8 10
put x1
put x2
put x3
PMutual x1 x2 -> do putWord8 11
put x1
put x2
PPostulate x1 x2 x3 x4 x5 x6 x7 x8
-> do putWord8 12
put x1
put x2
put x3
put x4
put x5
put x6
put x7
put x8
PSyntax x1 x2 -> do putWord8 13
put x1
put x2
PDirective x1 -> error "Cannot serialize PDirective"
PProvider x1 x2 x3 x4 x5 x6 ->
do putWord8 15
put x1
put x2
put x3
put x4
put x5
put x6
PTransform x1 x2 x3 x4 -> do putWord8 16
put x1
put x2
put x3
put x4
PRunElabDecl x1 x2 x3 -> do putWord8 17
put x1
put x2
put x3
POpenInterfaces x1 x2 x3 -> do putWord8 18
put x1
put x2
put x3
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
x3 <- get
return (PFix x1 x2 x3)
1 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
x7 <- get
x8 <- get
return (PTy x1 x2 x3 x4 x5 x6 x7 x8)
2 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (PClauses x1 x2 x3 x4)
3 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
return (PData x1 x2 x3 x4 x5 x6)
4 -> do x1 <- get
x2 <- get
x3 <- get
return (PParams x1 x2 x3)
5 -> do x1 <- get
x2 <- get
x3 <- get
return (PNamespace x1 x2 x3)
6 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
x7 <- get
x8 <- get
x9 <- get
x10 <- get
x11 <- get
x12 <- get
return (PRecord x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12)
7 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
x7 <- get
x8 <- get
x9 <- get
x10 <- get
x11 <- get
x12 <- get
return (PClass x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12)
8 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
x7 <- get
x8 <- get
x9 <- get
x10 <- get
x11 <- get
x12 <- get
x13 <- get
x14 <- get
x15 <- get
return (PInstance x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15)
9 -> do x1 <- get
x2 <- get
return (PDSL x1 x2)
10 -> do x1 <- get
x2 <- get
x3 <- get
return (PCAF x1 x2 x3)
11 -> do x1 <- get
x2 <- get
return (PMutual x1 x2)
12 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
x7 <- get
x8 <- get
return (PPostulate x1 x2 x3 x4 x5 x6 x7 x8)
13 -> do x1 <- get
x2 <- get
return (PSyntax x1 x2)
14 -> do error "Cannot deserialize PDirective"
15 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
return (PProvider x1 x2 x3 x4 x5 x6)
16 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (PTransform x1 x2 x3 x4)
17 -> do x1 <- get
x2 <- get
x3 <- get
return (PRunElabDecl x1 x2 x3)
18 -> do x1 <- get
x2 <- get
x3 <- get
return (POpenInterfaces x1 x2 x3)
_ -> error "Corrupted binary data for PDecl'"
instance Binary t => Binary (ProvideWhat' t) where
put (ProvTerm x1 x2) = do putWord8 0
put x1
put x2
put (ProvPostulate x1) = do putWord8 1
put x1
get = do y <- getWord8
case y of
0 -> do x1 <- get
x2 <- get
return (ProvTerm x1 x2)
1 -> do x1 <- get
return (ProvPostulate x1)
_ -> error "Corrupted binary data for ProvideWhat"
instance Binary Using where
put (UImplicit x1 x2) = do putWord8 0; put x1; put x2
put (UConstraint x1 x2) = do putWord8 1; put x1; put x2
get = do i <- getWord8
case i of
0 -> do x1 <- get; x2 <- get; return (UImplicit x1 x2)
1 -> do x1 <- get; x2 <- get; return (UConstraint x1 x2)
_ -> error "Corrupted binary data for Using"
instance Binary SyntaxInfo where
put (Syn x1 x2 x3 x4 _ _ x5 x6 x7 _ _ x8 _ _ _)
= do put x1
put x2
put x3
put x4
put x5
put x6
put x7
put x8
get
= do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
x7 <- get
x8 <- get
return (Syn x1 x2 x3 x4 [] id x5 x6 x7 Nothing 0 x8 0 True True)
instance (Binary t) => Binary (PClause' t) where
put x
= case x of
PClause x1 x2 x3 x4 x5 x6 -> do putWord8 0
put x1
put x2
put x3
put x4
put x5
put x6
PWith x1 x2 x3 x4 x5 x6 x7 -> do putWord8 1
put x1
put x2
put x3
put x4
put x5
put x6
put x7
PClauseR x1 x2 x3 x4 -> do putWord8 2
put x1
put x2
put x3
put x4
PWithR x1 x2 x3 x4 x5 -> do putWord8 3
put x1
put x2
put x3
put x4
put x5
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
return (PClause x1 x2 x3 x4 x5 x6)
1 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
x7 <- get
return (PWith x1 x2 x3 x4 x5 x6 x7)
2 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (PClauseR x1 x2 x3 x4)
3 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (PWithR x1 x2 x3 x4 x5)
_ -> error "Corrupted binary data for PClause'"
instance (Binary t) => Binary (PData' t) where
put x
= case x of
PDatadecl x1 x2 x3 x4 -> do putWord8 0
put x1
put x2
put x3
put x4
PLaterdecl x1 x2 x3 -> do putWord8 1
put x1
put x2
put x3
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (PDatadecl x1 x2 x3 x4)
1 -> do x1 <- get
x2 <- get
x3 <- get
return (PLaterdecl x1 x2 x3)
_ -> error "Corrupted binary data for PData'"
instance Binary PunInfo where
put x
= case x of
TypeOrTerm -> putWord8 0
IsType -> putWord8 1
IsTerm -> putWord8 2
get
= do i <- getWord8
case i of
0 -> return TypeOrTerm
1 -> return IsType
2 -> return IsTerm
_ -> error "Corrupted binary data for PunInfo"
instance Binary PTerm where
put x
= case x of
PQuote x1 -> do putWord8 0
put x1
PRef x1 x2 x3 -> do putWord8 1
put x1
put x2
put x3
PInferRef x1 x2 x3 -> do putWord8 2
put x1
put x2
put x3
PPatvar x1 x2 -> do putWord8 3
put x1
put x2
PLam x1 x2 x3 x4 x5 -> do putWord8 4
put x1
put x2
put x3
put x4
put x5
PPi x1 x2 x3 x4 x5 -> do putWord8 5
put x1
put x2
put x3
put x4
put x5
PLet x1 x2 x3 x4 x5 x6 -> do putWord8 6
put x1
put x2
put x3
put x4
put x5
put x6
PTyped x1 x2 -> do putWord8 7
put x1
put x2
PAppImpl x1 x2 -> error "PAppImpl in final term"
PApp x1 x2 x3 -> do putWord8 8
put x1
put x2
put x3
PAppBind x1 x2 x3 -> do putWord8 9
put x1
put x2
put x3
PMatchApp x1 x2 -> do putWord8 10
put x1
put x2
PCase x1 x2 x3 -> do putWord8 11
put x1
put x2
put x3
PTrue x1 x2 -> do putWord8 12
put x1
put x2
PResolveTC x1 -> do putWord8 15
put x1
PRewrite x1 x2 x3 x4 x5 -> do putWord8 17
put x1
put x2
put x3
put x4
put x5
PPair x1 x2 x3 x4 x5 -> do putWord8 18
put x1
put x2
put x3
put x4
put x5
PDPair x1 x2 x3 x4 x5 x6 -> do putWord8 19
put x1
put x2
put x3
put x4
put x5
put x6
PAlternative x1 x2 x3 -> do putWord8 20
put x1
put x2
put x3
PHidden x1 -> do putWord8 21
put x1
PType x1 -> do putWord8 22
put x1
PGoal x1 x2 x3 x4 -> do putWord8 23
put x1
put x2
put x3
put x4
PConstant x1 x2 -> do putWord8 24
put x1
put x2
Placeholder -> putWord8 25
PDoBlock x1 -> do putWord8 26
put x1
PIdiom x1 x2 -> do putWord8 27
put x1
put x2
PReturn x1 -> do putWord8 28
put x1
PMetavar x1 x2 -> do putWord8 29
put x1
put x2
PProof x1 -> do putWord8 30
put x1
PTactics x1 -> do putWord8 31
put x1
PImpossible -> putWord8 33
PCoerced x1 -> do putWord8 34
put x1
PUnifyLog x1 -> do putWord8 35
put x1
PNoImplicits x1 -> do putWord8 36
put x1
PDisamb x1 x2 -> do putWord8 37
put x1
put x2
PUniverse x1 -> do putWord8 38
put x1
PRunElab x1 x2 x3 -> do putWord8 39
put x1
put x2
put x3
PAs x1 x2 x3 -> do putWord8 40
put x1
put x2
put x3
PElabError x1 -> do putWord8 41
put x1
PQuasiquote x1 x2 -> do putWord8 42
put x1
put x2
PUnquote x1 -> do putWord8 43
put x1
PQuoteName x1 x2 x3 -> do putWord8 44
put x1
put x2
put x3
PIfThenElse x1 x2 x3 x4 -> do putWord8 45
put x1
put x2
put x3
put x4
PConstSugar x1 x2 -> do putWord8 46
put x1
put x2
PWithApp x1 x2 x3 -> do putWord8 47
put x1
put x2
put x3
get
= do i <- getWord8
case i of
0 -> do x1 <- get
return (PQuote x1)
1 -> do x1 <- get
x2 <- get
x3 <- get
return (PRef x1 x2 x3)
2 -> do x1 <- get
x2 <- get
x3 <- get
return (PInferRef x1 x2 x3)
3 -> do x1 <- get
x2 <- get
return (PPatvar x1 x2)
4 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (PLam x1 x2 x3 x4 x5)
5 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (PPi x1 x2 x3 x4 x5)
6 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
return (PLet x1 x2 x3 x4 x5 x6)
7 -> do x1 <- get
x2 <- get
return (PTyped x1 x2)
8 -> do x1 <- get
x2 <- get
x3 <- get
return (PApp x1 x2 x3)
9 -> do x1 <- get
x2 <- get
x3 <- get
return (PAppBind x1 x2 x3)
10 -> do x1 <- get
x2 <- get
return (PMatchApp x1 x2)
11 -> do x1 <- get
x2 <- get
x3 <- get
return (PCase x1 x2 x3)
12 -> do x1 <- get
x2 <- get
return (PTrue x1 x2)
15 -> do x1 <- get
return (PResolveTC x1)
17 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (PRewrite x1 x2 x3 x4 x5)
18 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (PPair x1 x2 x3 x4 x5)
19 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
return (PDPair x1 x2 x3 x4 x5 x6)
20 -> do x1 <- get
x2 <- get
x3 <- get
return (PAlternative x1 x2 x3)
21 -> do x1 <- get
return (PHidden x1)
22 -> do x1 <- get
return (PType x1)
23 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (PGoal x1 x2 x3 x4)
24 -> do x1 <- get
x2 <- get
return (PConstant x1 x2)
25 -> return Placeholder
26 -> do x1 <- get
return (PDoBlock x1)
27 -> do x1 <- get
x2 <- get
return (PIdiom x1 x2)
28 -> do x1 <- get
return (PReturn x1)
29 -> do x1 <- get
x2 <- get
return (PMetavar x1 x2)
30 -> do x1 <- get
return (PProof x1)
31 -> do x1 <- get
return (PTactics x1)
33 -> return PImpossible
34 -> do x1 <- get
return (PCoerced x1)
35 -> do x1 <- get
return (PUnifyLog x1)
36 -> do x1 <- get
return (PNoImplicits x1)
37 -> do x1 <- get
x2 <- get
return (PDisamb x1 x2)
38 -> do x1 <- get
return (PUniverse x1)
39 -> do x1 <- get
x2 <- get
x3 <- get
return (PRunElab x1 x2 x3)
40 -> do x1 <- get
x2 <- get
x3 <- get
return (PAs x1 x2 x3)
41 -> do x1 <- get
return (PElabError x1)
42 -> do x1 <- get
x2 <- get
return (PQuasiquote x1 x2)
43 -> do x1 <- get
return (PUnquote x1)
44 -> do x1 <- get
x2 <- get
x3 <- get
return (PQuoteName x1 x2 x3)
45 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (PIfThenElse x1 x2 x3 x4)
46 -> do x1 <- get
x2 <- get
return (PConstSugar x1 x2)
47 -> do x1 <- get
x2 <- get
x3 <- get
return (PWithApp x1 x2 x3)
_ -> error "Corrupted binary data for PTerm"
instance Binary PAltType where
put x
= case x of
ExactlyOne x1 -> do putWord8 0
put x1
FirstSuccess -> putWord8 1
TryImplicit -> putWord8 2
get
= do i <- getWord8
case i of
0 -> do x1 <- get
return (ExactlyOne x1)
1 -> return FirstSuccess
2 -> return TryImplicit
_ -> error "Corrupted binary data for PAltType"
instance (Binary t) => Binary (PTactic' t) where
put x
= case x of
Intro x1 -> do putWord8 0
put x1
Focus x1 -> do putWord8 1
put x1
Refine x1 x2 -> do putWord8 2
put x1
put x2
Rewrite x1 -> do putWord8 3
put x1
LetTac x1 x2 -> do putWord8 4
put x1
put x2
Exact x1 -> do putWord8 5
put x1
Compute -> putWord8 6
Trivial -> putWord8 7
Solve -> putWord8 8
Attack -> putWord8 9
ProofState -> putWord8 10
ProofTerm -> putWord8 11
Undo -> putWord8 12
Try x1 x2 -> do putWord8 13
put x1
put x2
TSeq x1 x2 -> do putWord8 14
put x1
put x2
Qed -> putWord8 15
ApplyTactic x1 -> do putWord8 16
put x1
Reflect x1 -> do putWord8 17
put x1
Fill x1 -> do putWord8 18
put x1
Induction x1 -> do putWord8 19
put x1
ByReflection x1 -> do putWord8 20
put x1
ProofSearch x1 x2 x3 x4 x5 x6 -> do putWord8 21
put x1
put x2
put x3
put x4
put x5
put x6
DoUnify -> putWord8 22
CaseTac x1 -> do putWord8 23
put x1
SourceFC -> putWord8 24
Intros -> putWord8 25
Equiv x1 -> do putWord8 26
put x1
Claim x1 x2 -> do putWord8 27
put x1
put x2
Unfocus -> putWord8 28
MatchRefine x1 -> do putWord8 29
put x1
LetTacTy x1 x2 x3 -> do putWord8 30
put x1
put x2
put x3
TCInstance -> putWord8 31
GoalType x1 x2 -> do putWord8 32
put x1
put x2
TCheck x1 -> do putWord8 33
put x1
TEval x1 -> do putWord8 34
put x1
TDocStr x1 -> do putWord8 35
put x1
TSearch x1 -> do putWord8 36
put x1
Skip -> putWord8 37
TFail x1 -> do putWord8 38
put x1
Abandon -> putWord8 39
get
= do i <- getWord8
case i of
0 -> do x1 <- get
return (Intro x1)
1 -> do x1 <- get
return (Focus x1)
2 -> do x1 <- get
x2 <- get
return (Refine x1 x2)
3 -> do x1 <- get
return (Rewrite x1)
4 -> do x1 <- get
x2 <- get
return (LetTac x1 x2)
5 -> do x1 <- get
return (Exact x1)
6 -> return Compute
7 -> return Trivial
8 -> return Solve
9 -> return Attack
10 -> return ProofState
11 -> return ProofTerm
12 -> return Undo
13 -> do x1 <- get
x2 <- get
return (Try x1 x2)
14 -> do x1 <- get
x2 <- get
return (TSeq x1 x2)
15 -> return Qed
16 -> do x1 <- get
return (ApplyTactic x1)
17 -> do x1 <- get
return (Reflect x1)
18 -> do x1 <- get
return (Fill x1)
19 -> do x1 <- get
return (Induction x1)
20 -> do x1 <- get
return (ByReflection x1)
21 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
return (ProofSearch x1 x2 x3 x4 x5 x6)
22 -> return DoUnify
23 -> do x1 <- get
return (CaseTac x1)
24 -> return SourceFC
25 -> return Intros
26 -> do x1 <- get
return (Equiv x1)
27 -> do x1 <- get
x2 <- get
return (Claim x1 x2)
28 -> return Unfocus
29 -> do x1 <- get
return (MatchRefine x1)
30 -> do x1 <- get
x2 <- get
x3 <- get
return (LetTacTy x1 x2 x3)
31 -> return TCInstance
32 -> do x1 <- get
x2 <- get
return (GoalType x1 x2)
33 -> do x1 <- get
return (TCheck x1)
34 -> do x1 <- get
return (TEval x1)
35 -> do x1 <- get
return (TDocStr x1)
36 -> do x1 <- get
return (TSearch x1)
37 -> return Skip
38 -> do x1 <- get
return (TFail x1)
39 -> return Abandon
_ -> error "Corrupted binary data for PTactic'"
instance (Binary t) => Binary (PDo' t) where
put x
= case x of
DoExp x1 x2 -> do putWord8 0
put x1
put x2
DoBind x1 x2 x3 x4 -> do putWord8 1
put x1
put x2
put x3
put x4
DoBindP x1 x2 x3 x4 -> do putWord8 2
put x1
put x2
put x3
put x4
DoLet x1 x2 x3 x4 x5 -> do putWord8 3
put x1
put x2
put x3
put x4
put x5
DoLetP x1 x2 x3 -> do putWord8 4
put x1
put x2
put x3
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
return (DoExp x1 x2)
1 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (DoBind x1 x2 x3 x4)
2 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (DoBindP x1 x2 x3 x4)
3 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (DoLet x1 x2 x3 x4 x5)
4 -> do x1 <- get
x2 <- get
x3 <- get
return (DoLetP x1 x2 x3)
_ -> error "Corrupted binary data for PDo'"
instance (Binary t) => Binary (PArg' t) where
put x
= case x of
PImp x1 x2 x3 x4 x5 ->
do putWord8 0
put x1
put x2
put x3
put x4
put x5
PExp x1 x2 x3 x4 ->
do putWord8 1
put x1
put x2
put x3
put x4
PConstraint x1 x2 x3 x4 ->
do putWord8 2
put x1
put x2
put x3
put x4
PTacImplicit x1 x2 x3 x4 x5 ->
do putWord8 3
put x1
put x2
put x3
put x4
put x5
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (PImp x1 x2 x3 x4 x5)
1 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (PExp x1 x2 x3 x4)
2 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
return (PConstraint x1 x2 x3 x4)
3 -> do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (PTacImplicit x1 x2 x3 x4 x5)
_ -> error "Corrupted binary data for PArg'"
instance Binary ClassInfo where
put (CI x1 x2 x3 x4 x5 _ x6)
= do put x1
put x2
put x3
put x4
put x5
put x6
get
= do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
return (CI x1 x2 x3 x4 x5 [] x6)
instance Binary RecordInfo where
put (RI x1 x2 x3)
= do put x1
put x2
put x3
get
= do x1 <- get
x2 <- get
x3 <- get
return (RI x1 x2 x3)
instance Binary OptInfo where
put (Optimise x1 x2)
= do put x1
put x2
get
= do x1 <- get
x2 <- get
return (Optimise x1 x2)
instance Binary FnInfo where
put (FnInfo x1)
= put x1
get
= do x1 <- get
return (FnInfo x1)
instance Binary TypeInfo where
put (TI x1 x2 x3 x4 x5) = do put x1
put x2
put x3
put x4
put x5
get = do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
return (TI x1 x2 x3 x4 x5)
instance Binary SynContext where
put x
= case x of
PatternSyntax -> putWord8 0
TermSyntax -> putWord8 1
AnySyntax -> putWord8 2
get
= do i <- getWord8
case i of
0 -> return PatternSyntax
1 -> return TermSyntax
2 -> return AnySyntax
_ -> error "Corrupted binary data for SynContext"
instance Binary Syntax where
put (Rule x1 x2 x3)
= do putWord8 0
put x1
put x2
put x3
put (DeclRule x1 x2)
= do putWord8 1
put x1
put x2
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
x3 <- get
return (Rule x1 x2 x3)
1 -> do x1 <- get
x2 <- get
return (DeclRule x1 x2)
_ -> error "Corrupted binary data for Syntax"
instance (Binary t) => Binary (DSL' t) where
put (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9 x10)
= do put x1
put x2
put x3
put x4
put x5
put x6
put x7
put x8
put x9
put x10
get
= do x1 <- get
x2 <- get
x3 <- get
x4 <- get
x5 <- get
x6 <- get
x7 <- get
x8 <- get
x9 <- get
x10 <- get
return (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9 x10)
instance Binary SSymbol where
put x
= case x of
Keyword x1 -> do putWord8 0
put x1
Symbol x1 -> do putWord8 1
put x1
Expr x1 -> do putWord8 2
put x1
SimpleExpr x1 -> do putWord8 3
put x1
Binding x1 -> do putWord8 4
put x1
get
= do i <- getWord8
case i of
0 -> do x1 <- get
return (Keyword x1)
1 -> do x1 <- get
return (Symbol x1)
2 -> do x1 <- get
return (Expr x1)
3 -> do x1 <- get
return (SimpleExpr x1)
4 -> do x1 <- get
return (Binding x1)
_ -> error "Corrupted binary data for SSymbol"
instance Binary Codegen where
put x
= case x of
Via ir str -> do putWord8 0
put ir
put str
Bytecode -> putWord8 1
get
= do i <- getWord8
case i of
0 -> do x1 <- get
x2 <- get
return (Via x1 x2)
1 -> return Bytecode
_ -> error "Corrupted binary data for Codegen"
instance Binary IRFormat where
put x = case x of
IBCFormat -> putWord8 0
JSONFormat -> putWord8 1
get = do i <- getWord8
case i of
0 -> return IBCFormat
1 -> return JSONFormat
_ -> error "Corrupted binary data for IRFormat"
| tpsinnem/Idris-dev | src/Idris/IBC.hs | bsd-3-clause | 100,046 | 0 | 21 | 55,355 | 27,569 | 12,662 | 14,907 | 2,406 | 17 |
-- | Build instance tycons for the PData and PDatas type families.
--
-- TODO: the PData and PDatas cases are very similar.
-- We should be able to factor out the common parts.
module Vectorise.Generic.PData
( buildPDataTyCon
, buildPDatasTyCon )
where
import Vectorise.Monad
import Vectorise.Builtins
import Vectorise.Generic.Description
import Vectorise.Utils
import Vectorise.Env( GlobalEnv( global_fam_inst_env ) )
import BuildTyCl
import DataCon
import TyCon
import Type
import FamInst
import FamInstEnv
import TcMType
import Name
import Util
import MonadUtils
import Control.Monad
-- buildPDataTyCon ------------------------------------------------------------
-- | Build the PData instance tycon for a given type constructor.
buildPDataTyCon :: TyCon -> TyCon -> SumRepr -> VM FamInst
buildPDataTyCon orig_tc vect_tc repr
= fixV $ \fam_inst ->
do let repr_tc = dataFamInstRepTyCon fam_inst
name' <- mkLocalisedName mkPDataTyConOcc orig_name
rhs <- buildPDataTyConRhs orig_name vect_tc repr_tc repr
pdata <- builtin pdataTyCon
buildDataFamInst name' pdata vect_tc rhs
where
orig_name = tyConName orig_tc
buildDataFamInst :: Name -> TyCon -> TyCon -> AlgTyConRhs -> VM FamInst
buildDataFamInst name' fam_tc vect_tc rhs
= do { axiom_name <- mkDerivedName mkInstTyCoOcc name'
; (_, tyvars') <- liftDs $ tcInstSigTyVars (getSrcSpan name') tyvars
; let ax = mkSingleCoAxiom Representational axiom_name tyvars' [] fam_tc pat_tys rep_ty
tys' = mkTyVarTys tyvars'
rep_ty = mkTyConApp rep_tc tys'
pat_tys = [mkTyConApp vect_tc tys']
rep_tc = mkAlgTyCon name'
(mkTyConBindersPreferAnon tyvars' liftedTypeKind)
liftedTypeKind
(map (const Nominal) tyvars')
Nothing
[] -- no stupid theta
rhs
(DataFamInstTyCon ax fam_tc pat_tys)
False -- not GADT syntax
; liftDs $ newFamInst (DataFamilyInst rep_tc) ax }
where
tyvars = tyConTyVars vect_tc
buildPDataTyConRhs :: Name -> TyCon -> TyCon -> SumRepr -> VM AlgTyConRhs
buildPDataTyConRhs orig_name vect_tc repr_tc repr
= do data_con <- buildPDataDataCon orig_name vect_tc repr_tc repr
return $ DataTyCon { data_cons = [data_con], is_enum = False }
buildPDataDataCon :: Name -> TyCon -> TyCon -> SumRepr -> VM DataCon
buildPDataDataCon orig_name vect_tc repr_tc repr
= do let tvs = tyConTyVars vect_tc
dc_name <- mkLocalisedName mkPDataDataConOcc orig_name
comp_tys <- mkSumTys repr_sel_ty mkPDataType repr
fam_envs <- readGEnv global_fam_inst_env
rep_nm <- liftDs $ newTyConRepName dc_name
liftDs $ buildDataCon fam_envs dc_name
False -- not infix
rep_nm
(map (const no_bang) comp_tys)
(Just $ map (const HsLazy) comp_tys)
[] -- no field labels
(mkTyVarBinders Specified tvs)
[] -- no existentials
[] -- no eq spec
[] -- no context
comp_tys
(mkFamilyTyConApp repr_tc (mkTyVarTys tvs))
repr_tc
where
no_bang = HsSrcBang Nothing NoSrcUnpack NoSrcStrict
-- buildPDatasTyCon -----------------------------------------------------------
-- | Build the PDatas instance tycon for a given type constructor.
buildPDatasTyCon :: TyCon -> TyCon -> SumRepr -> VM FamInst
buildPDatasTyCon orig_tc vect_tc repr
= fixV $ \fam_inst ->
do let repr_tc = dataFamInstRepTyCon fam_inst
name' <- mkLocalisedName mkPDatasTyConOcc orig_name
rhs <- buildPDatasTyConRhs orig_name vect_tc repr_tc repr
pdatas <- builtin pdatasTyCon
buildDataFamInst name' pdatas vect_tc rhs
where
orig_name = tyConName orig_tc
buildPDatasTyConRhs :: Name -> TyCon -> TyCon -> SumRepr -> VM AlgTyConRhs
buildPDatasTyConRhs orig_name vect_tc repr_tc repr
= do data_con <- buildPDatasDataCon orig_name vect_tc repr_tc repr
return $ DataTyCon { data_cons = [data_con], is_enum = False }
buildPDatasDataCon :: Name -> TyCon -> TyCon -> SumRepr -> VM DataCon
buildPDatasDataCon orig_name vect_tc repr_tc repr
= do let tvs = tyConTyVars vect_tc
dc_name <- mkLocalisedName mkPDatasDataConOcc orig_name
comp_tys <- mkSumTys repr_sels_ty mkPDatasType repr
fam_envs <- readGEnv global_fam_inst_env
rep_nm <- liftDs $ newTyConRepName dc_name
liftDs $ buildDataCon fam_envs dc_name
False -- not infix
rep_nm
(map (const no_bang) comp_tys)
(Just $ map (const HsLazy) comp_tys)
[] -- no field labels
(mkTyVarBinders Specified tvs)
[] -- no existentials
[] -- no eq spec
[] -- no context
comp_tys
(mkFamilyTyConApp repr_tc (mkTyVarTys tvs))
repr_tc
where
no_bang = HsSrcBang Nothing NoSrcUnpack NoSrcStrict
-- Utils ----------------------------------------------------------------------
-- | Flatten a SumRepr into a list of data constructor types.
mkSumTys
:: (SumRepr -> Type)
-> (Type -> VM Type)
-> SumRepr
-> VM [Type]
mkSumTys repr_selX_ty mkTc repr
= sum_tys repr
where
sum_tys EmptySum = return []
sum_tys (UnarySum r) = con_tys r
sum_tys d@(Sum { repr_cons = cons })
= liftM (repr_selX_ty d :) (concatMapM con_tys cons)
con_tys (ConRepr _ r) = prod_tys r
prod_tys EmptyProd = return []
prod_tys (UnaryProd r) = liftM singleton (comp_ty r)
prod_tys (Prod { repr_comps = comps }) = mapM comp_ty comps
comp_ty r = mkTc (compOrigType r)
{-
mk_fam_inst :: TyCon -> TyCon -> (TyCon, [Type])
mk_fam_inst fam_tc arg_tc
= (fam_tc, [mkTyConApp arg_tc . mkTyVarTys $ tyConTyVars arg_tc])
-}
| vTurbine/ghc | compiler/vectorise/Vectorise/Generic/PData.hs | bsd-3-clause | 6,567 | 0 | 14 | 2,207 | 1,369 | 689 | 680 | 122 | 5 |
{-# OPTIONS -Wall -fno-warn-missing-signatures -fno-warn-name-shadowing #-}
-- | Load the configuration file.
module HN.Config (getConfig) where
import HN.Types
import Data.ConfigFile
import Database.PostgreSQL.Simple (ConnectInfo(..))
import qualified Data.Text as T
import Network.Mail.Mime
import Github.Auth (GithubAuth(..))
import qualified Data.ByteString.Char8 as BS
getConfig :: FilePath -> IO Config
getConfig conf = do
contents <- readFile conf
let config = do
c <- readstring emptyCP contents
[pghost,pgport,pguser,pgpass,pgdb]
<- mapM (get c "POSTGRESQL")
["host","port","user","pass","db"]
[domain,cache]
<- mapM (get c "WEB")
["domain","cache"]
[admin,siteaddy]
<- mapM (get c "ADDRESSES") ["admin","site_addy"]
let gituser = BS.pack <$> getMaybe c "GITHUB" "user"
gitpw = BS.pack <$> getMaybe c "GITHUB" "password"
auth = GithubBasicAuth <$> gituser <*> gitpw
return Config {
configPostgres = ConnectInfo pghost (read pgport) pguser pgpass pgdb
, configDomain = domain
, configAdmin = Address Nothing (T.pack admin)
, configSiteAddy = Address Nothing (T.pack siteaddy)
, configCacheDir = cache
, configGithubAuth = auth
}
case config of
Left cperr -> error $ show cperr
Right config -> return config
getMaybe c section name =
case get c section name of
Left _ -> Nothing
Right x -> Just x
| lwm/haskellnews | src/HN/Config.hs | bsd-3-clause | 1,545 | 0 | 18 | 421 | 459 | 245 | 214 | 39 | 2 |
{-# LANGUAGE ForeignFunctionInterface #-}
module Main where
import Foreign.C.Types
foreign import ccall "foo" foo :: IO CInt
main :: IO ()
main = foo >>= print
| sdiehl/ghc | testsuite/tests/ffi/should_run/T17471.hs | bsd-3-clause | 163 | 0 | 6 | 29 | 45 | 26 | 19 | 6 | 1 |
{-# LANGUAGE EmptyDataDecls #-}
module Opaleye.SQLite.PGTypes (module Opaleye.SQLite.PGTypes) where
import Opaleye.SQLite.Internal.Column (Column)
import qualified Opaleye.SQLite.Internal.Column as C
import qualified Opaleye.SQLite.Internal.PGTypes as IPT
import qualified Opaleye.SQLite.Internal.HaskellDB.PrimQuery as HPQ
import qualified Opaleye.SQLite.Internal.HaskellDB.Sql.Default as HSD (quote)
import qualified Data.CaseInsensitive as CI
import qualified Data.Text as SText
import qualified Data.Text.Lazy as LText
import qualified Data.ByteString as SByteString
import qualified Data.ByteString.Lazy as LByteString
import qualified Data.Time as Time
import qualified Data.UUID as UUID
import Data.Int (Int64)
data PGBool
data PGDate
data PGFloat4
data PGFloat8
data PGInt8
data PGInt4
data PGInt2
data PGNumeric
data PGText
data PGTime
data PGTimestamp
data PGTimestamptz
data PGUuid
data PGCitext
data PGArray a
data PGBytea
data PGJson
data PGJsonb
instance C.PGNum PGFloat8 where
pgFromInteger = pgDouble . fromInteger
instance C.PGNum PGInt4 where
pgFromInteger = pgInt4 . fromInteger
instance C.PGNum PGInt8 where
pgFromInteger = pgInt8 . fromInteger
instance C.PGFractional PGFloat8 where
pgFromRational = pgDouble . fromRational
literalColumn :: HPQ.Literal -> Column a
literalColumn = IPT.literalColumn
{-# WARNING literalColumn
"'literalColumn' has been moved to Opaleye.Internal.PGTypes"
#-}
pgString :: String -> Column PGText
pgString = IPT.literalColumn . HPQ.StringLit
pgLazyByteString :: LByteString.ByteString -> Column PGBytea
pgLazyByteString = IPT.literalColumn . HPQ.ByteStringLit . LByteString.toStrict
pgStrictByteString :: SByteString.ByteString -> Column PGBytea
pgStrictByteString = IPT.literalColumn . HPQ.ByteStringLit
pgStrictText :: SText.Text -> Column PGText
pgStrictText = IPT.literalColumn . HPQ.StringLit . SText.unpack
pgLazyText :: LText.Text -> Column PGText
pgLazyText = IPT.literalColumn . HPQ.StringLit . LText.unpack
pgInt4 :: Int -> Column PGInt4
pgInt4 = IPT.literalColumn . HPQ.IntegerLit . fromIntegral
pgInt8 :: Int64 -> Column PGInt8
pgInt8 = IPT.literalColumn . HPQ.IntegerLit . fromIntegral
-- SQLite needs to be told that numeric literals without decimal
-- points are actual REAL
pgDouble :: Double -> Column PGFloat8
pgDouble = C.unsafeCast "REAL" . IPT.literalColumn . HPQ.DoubleLit
pgBool :: Bool -> Column PGBool
pgBool = IPT.literalColumn . HPQ.BoolLit
pgUUID :: UUID.UUID -> Column PGUuid
pgUUID = C.unsafeCoerceColumn . pgString . UUID.toString
unsafePgFormatTime :: Time.FormatTime t => HPQ.Name -> String -> t -> Column c
unsafePgFormatTime = IPT.unsafePgFormatTime
{-# WARNING unsafePgFormatTime
"'unsafePgFormatTime' has been moved to Opaleye.Internal.PGTypes"
#-}
pgDay :: Time.Day -> Column PGDate
pgDay = IPT.unsafePgFormatTime "date" "'%F'"
pgUTCTime :: Time.UTCTime -> Column PGTimestamptz
pgUTCTime = IPT.unsafePgFormatTime "timestamptz" "'%FT%TZ'"
pgLocalTime :: Time.LocalTime -> Column PGTimestamp
pgLocalTime = IPT.unsafePgFormatTime "timestamp" "'%FT%T'"
pgTimeOfDay :: Time.TimeOfDay -> Column PGTime
pgTimeOfDay = IPT.unsafePgFormatTime "time" "'%T'"
-- "We recommend not using the type time with time zone"
-- http://www.postgresql.org/docs/8.3/static/datatype-datetime.html
pgCiStrictText :: CI.CI SText.Text -> Column PGCitext
pgCiStrictText = IPT.literalColumn . HPQ.StringLit . SText.unpack . CI.original
pgCiLazyText :: CI.CI LText.Text -> Column PGCitext
pgCiLazyText = IPT.literalColumn . HPQ.StringLit . LText.unpack . CI.original
-- No CI String instance since postgresql-simple doesn't define FromField (CI String)
-- The json data type was introduced in PostgreSQL version 9.2
-- JSON values must be SQL string quoted
pgJSON :: String -> Column PGJson
pgJSON = IPT.castToType "json" . HSD.quote
pgStrictJSON :: SByteString.ByteString -> Column PGJson
pgStrictJSON = pgJSON . IPT.strictDecodeUtf8
pgLazyJSON :: LByteString.ByteString -> Column PGJson
pgLazyJSON = pgJSON . IPT.lazyDecodeUtf8
-- The jsonb data type was introduced in PostgreSQL version 9.4
-- JSONB values must be SQL string quoted
--
-- TODO: We need to add literal JSON and JSONB types.
pgJSONB :: String -> Column PGJsonb
pgJSONB = IPT.castToType "jsonb" . HSD.quote
pgStrictJSONB :: SByteString.ByteString -> Column PGJsonb
pgStrictJSONB = pgJSONB . IPT.strictDecodeUtf8
pgLazyJSONB :: LByteString.ByteString -> Column PGJsonb
pgLazyJSONB = pgJSONB . IPT.lazyDecodeUtf8
| bergmark/haskell-opaleye | opaleye-sqlite/src/Opaleye/SQLite/PGTypes.hs | bsd-3-clause | 4,512 | 0 | 9 | 626 | 995 | 558 | 437 | -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="id-ID">
<title>Kode Dx | ZAP Perpanjangan</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Isi</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Indeks</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Mencari</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorit</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/codedx/src/main/javahelp/org/zaproxy/zap/extension/codedx/resources/help_id_ID/helpset_id_ID.hs | apache-2.0 | 966 | 78 | 66 | 159 | 413 | 209 | 204 | -1 | -1 |
module CRC32 (crc32_tab, crc32, crc32String) where
import Data.Bits
import Data.Word
import Data.Char
-- table and sample code derived from
-- http://www.opensource.apple.com/source/xnu/xnu-1456.1.26/bsd/libkern/crc32.c
-- * COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or
-- * code or tables extracted from it, as desired without restriction.
crc32_tab :: [Word32]
crc32_tab = [
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
]
crc32 :: [Word8] -> Word32
crc32 msg = go 0xffffffff msg
where go crc [] = crc
go crc (w:ws) = go crc' ws
where crc' = (crc `shiftR` 8) `xor`
(crc32_tab !! fI (fI crc `xor` w))
fI x = fromIntegral x
crc32String :: String -> Word32
crc32String = crc32 . map (fromIntegral . ord)
| seahug/parconc-examples | crc32/CRC32.hs | bsd-3-clause | 3,868 | 100 | 15 | 488 | 1,059 | 670 | 389 | 58 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Xmobar.Commands
-- Copyright : (c) Andrea Rossato
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Jose A. Ortega Ruiz <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- The 'Exec' class and the 'Command' data type.
--
-- The 'Exec' class rappresents the executable types, whose constructors may
-- appear in the 'Config.commands' field of the 'Config.Config' data type.
--
-- The 'Command' data type is for OS commands to be run by xmobar
--
-----------------------------------------------------------------------------
module Commands
( Command (..)
, Exec (..)
, tenthSeconds
) where
import Prelude
import Control.Concurrent
import Control.Exception (handle, SomeException(..))
import Data.Char
import System.Process
import System.Exit
import System.IO (hClose)
import Signal
import XUtil
class Show e => Exec e where
alias :: e -> String
alias e = takeWhile (not . isSpace) $ show e
rate :: e -> Int
rate _ = 10
run :: e -> IO String
run _ = return ""
start :: e -> (String -> IO ()) -> IO ()
start e cb = go
where go = run e >>= cb >> tenthSeconds (rate e) >> go
trigger :: e -> (Maybe SignalType -> IO ()) -> IO ()
trigger _ sh = sh Nothing
data Command = Com Program Args Alias Rate
deriving (Show,Read,Eq)
type Args = [String]
type Program = String
type Alias = String
type Rate = Int
instance Exec Command where
alias (Com p _ a _)
| p /= "" = if a == "" then p else a
| otherwise = ""
start (Com prog args _ r) cb = if r > 0 then go else exec
where go = exec >> tenthSeconds r >> go
exec = do
(i,o,e,p) <- runInteractiveProcess prog args Nothing Nothing
exit <- waitForProcess p
let closeHandles = hClose o >> hClose i >> hClose e
getL = handle (\(SomeException _) -> return "")
(hGetLineSafe o)
case exit of
ExitSuccess -> do str <- getL
closeHandles
cb str
_ -> do closeHandles
cb $ "Could not execute command " ++ prog
-- | Work around to the Int max bound: since threadDelay takes an Int, it
-- is not possible to set a thread delay grater than about 45 minutes.
-- With a little recursion we solve the problem.
tenthSeconds :: Int -> IO ()
tenthSeconds s | s >= x = do threadDelay (x * 100000)
tenthSeconds (s - x)
| otherwise = threadDelay (s * 100000)
where x = (maxBound :: Int) `div` 100000
| dragosboca/xmobar | src/Commands.hs | bsd-3-clause | 2,869 | 0 | 17 | 957 | 722 | 382 | 340 | 54 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.C.String
-- Copyright : (c) The FFI task force 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Utilities for primitive marshalling of C strings.
--
-- The marshalling converts each Haskell character, representing a Unicode
-- code point, to one or more bytes in a manner that, by default, is
-- determined by the current locale. As a consequence, no guarantees
-- can be made about the relative length of a Haskell string and its
-- corresponding C string, and therefore all the marshalling routines
-- include memory allocation. The translation between Unicode and the
-- encoding of the current locale may be lossy.
--
-----------------------------------------------------------------------------
module Foreign.C.String ( -- representation of strings in C
-- * C strings
CString,
CStringLen,
-- ** Using a locale-dependent encoding
-- | These functions are different from their @CAString@ counterparts
-- in that they will use an encoding determined by the current locale,
-- rather than always assuming ASCII.
-- conversion of C strings into Haskell strings
--
peekCString,
peekCStringLen,
-- conversion of Haskell strings into C strings
--
newCString,
newCStringLen,
-- conversion of Haskell strings into C strings using temporary storage
--
withCString,
withCStringLen,
charIsRepresentable,
-- ** Using 8-bit characters
-- | These variants of the above functions are for use with C libraries
-- that are ignorant of Unicode. These functions should be used with
-- care, as a loss of information can occur.
castCharToCChar,
castCCharToChar,
castCharToCUChar,
castCUCharToChar,
castCharToCSChar,
castCSCharToChar,
peekCAString,
peekCAStringLen,
newCAString,
newCAStringLen,
withCAString,
withCAStringLen,
-- * C wide strings
-- | These variants of the above functions are for use with C libraries
-- that encode Unicode using the C @wchar_t@ type in a system-dependent
-- way. The only encodings supported are
--
-- * UTF-32 (the C compiler defines @__STDC_ISO_10646__@), or
--
-- * UTF-16 (as used on Windows systems).
CWString,
CWStringLen,
peekCWString,
peekCWStringLen,
newCWString,
newCWStringLen,
withCWString,
withCWStringLen,
) where
import Foreign.Marshal.Array
import Foreign.C.Types
import Foreign.Ptr
import Foreign.Storable
import Data.Word
import Control.Monad
import GHC.Char
import GHC.List
import GHC.Real
import GHC.Num
import GHC.Base
import {-# SOURCE #-} GHC.IO.Encoding
import qualified GHC.Foreign as GHC
-----------------------------------------------------------------------------
-- Strings
-- representation of strings in C
-- ------------------------------
-- | A C string is a reference to an array of C characters terminated by NUL.
type CString = Ptr CChar
-- | A string with explicit length information in bytes instead of a
-- terminating NUL (allowing NUL characters in the middle of the string).
type CStringLen = (Ptr CChar, Int)
-- exported functions
-- ------------------
--
-- * the following routines apply the default conversion when converting the
-- C-land character encoding into the Haskell-land character encoding
-- | Marshal a NUL terminated C string into a Haskell string.
--
peekCString :: CString -> IO String
peekCString s = getForeignEncoding >>= flip GHC.peekCString s
-- | Marshal a C string with explicit length into a Haskell string.
--
peekCStringLen :: CStringLen -> IO String
peekCStringLen s = getForeignEncoding >>= flip GHC.peekCStringLen s
-- | Marshal a Haskell string into a NUL terminated C string.
--
-- * the Haskell string may /not/ contain any NUL characters
--
-- * new storage is allocated for the C string and must be
-- explicitly freed using 'Foreign.Marshal.Alloc.free' or
-- 'Foreign.Marshal.Alloc.finalizerFree'.
--
newCString :: String -> IO CString
newCString s = getForeignEncoding >>= flip GHC.newCString s
-- | Marshal a Haskell string into a C string (ie, character array) with
-- explicit length information.
--
-- * new storage is allocated for the C string and must be
-- explicitly freed using 'Foreign.Marshal.Alloc.free' or
-- 'Foreign.Marshal.Alloc.finalizerFree'.
--
newCStringLen :: String -> IO CStringLen
newCStringLen s = getForeignEncoding >>= flip GHC.newCStringLen s
-- | Marshal a Haskell string into a NUL terminated C string using temporary
-- storage.
--
-- * the Haskell string may /not/ contain any NUL characters
--
-- * the memory is freed when the subcomputation terminates (either
-- normally or via an exception), so the pointer to the temporary
-- storage must /not/ be used after this.
--
withCString :: String -> (CString -> IO a) -> IO a
withCString s f = getForeignEncoding >>= \enc -> GHC.withCString enc s f
-- | Marshal a Haskell string into a C string (ie, character array)
-- in temporary storage, with explicit length information.
--
-- * the memory is freed when the subcomputation terminates (either
-- normally or via an exception), so the pointer to the temporary
-- storage must /not/ be used after this.
--
withCStringLen :: String -> (CStringLen -> IO a) -> IO a
withCStringLen s f = getForeignEncoding >>= \enc -> GHC.withCStringLen enc s f
-- -- | Determines whether a character can be accurately encoded in a 'CString'.
-- -- Unrepresentable characters are converted to '?' or their nearest visual equivalent.
charIsRepresentable :: Char -> IO Bool
charIsRepresentable c = getForeignEncoding >>= flip GHC.charIsRepresentable c
-- single byte characters
-- ----------------------
--
-- ** NOTE: These routines don't handle conversions! **
-- | Convert a C byte, representing a Latin-1 character, to the corresponding
-- Haskell character.
castCCharToChar :: CChar -> Char
castCCharToChar ch = unsafeChr (fromIntegral (fromIntegral ch :: Word8))
-- | Convert a Haskell character to a C character.
-- This function is only safe on the first 256 characters.
castCharToCChar :: Char -> CChar
castCharToCChar ch = fromIntegral (ord ch)
-- | Convert a C @unsigned char@, representing a Latin-1 character, to
-- the corresponding Haskell character.
castCUCharToChar :: CUChar -> Char
castCUCharToChar ch = unsafeChr (fromIntegral (fromIntegral ch :: Word8))
-- | Convert a Haskell character to a C @unsigned char@.
-- This function is only safe on the first 256 characters.
castCharToCUChar :: Char -> CUChar
castCharToCUChar ch = fromIntegral (ord ch)
-- | Convert a C @signed char@, representing a Latin-1 character, to the
-- corresponding Haskell character.
castCSCharToChar :: CSChar -> Char
castCSCharToChar ch = unsafeChr (fromIntegral (fromIntegral ch :: Word8))
-- | Convert a Haskell character to a C @signed char@.
-- This function is only safe on the first 256 characters.
castCharToCSChar :: Char -> CSChar
castCharToCSChar ch = fromIntegral (ord ch)
-- | Marshal a NUL terminated C string into a Haskell string.
--
peekCAString :: CString -> IO String
peekCAString cp = do
l <- lengthArray0 nUL cp
if l <= 0 then return "" else loop "" (l-1)
where
loop s i = do
xval <- peekElemOff cp i
let val = castCCharToChar xval
val `seq` if i <= 0 then return (val:s) else loop (val:s) (i-1)
-- | Marshal a C string with explicit length into a Haskell string.
--
peekCAStringLen :: CStringLen -> IO String
peekCAStringLen (cp, len)
| len <= 0 = return "" -- being (too?) nice.
| otherwise = loop [] (len-1)
where
loop acc i = do
xval <- peekElemOff cp i
let val = castCCharToChar xval
-- blow away the coercion ASAP.
if (val `seq` (i == 0))
then return (val:acc)
else loop (val:acc) (i-1)
-- | Marshal a Haskell string into a NUL terminated C string.
--
-- * the Haskell string may /not/ contain any NUL characters
--
-- * new storage is allocated for the C string and must be
-- explicitly freed using 'Foreign.Marshal.Alloc.free' or
-- 'Foreign.Marshal.Alloc.finalizerFree'.
--
newCAString :: String -> IO CString
newCAString str = do
ptr <- mallocArray0 (length str)
let
go [] n = pokeElemOff ptr n nUL
go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1)
go str 0
return ptr
-- | Marshal a Haskell string into a C string (ie, character array) with
-- explicit length information.
--
-- * new storage is allocated for the C string and must be
-- explicitly freed using 'Foreign.Marshal.Alloc.free' or
-- 'Foreign.Marshal.Alloc.finalizerFree'.
--
newCAStringLen :: String -> IO CStringLen
newCAStringLen str = do
ptr <- mallocArray0 len
let
go [] n = n `seq` return () -- make it strict in n
go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1)
go str 0
return (ptr, len)
where
len = length str
-- | Marshal a Haskell string into a NUL terminated C string using temporary
-- storage.
--
-- * the Haskell string may /not/ contain any NUL characters
--
-- * the memory is freed when the subcomputation terminates (either
-- normally or via an exception), so the pointer to the temporary
-- storage must /not/ be used after this.
--
withCAString :: String -> (CString -> IO a) -> IO a
withCAString str f =
allocaArray0 (length str) $ \ptr ->
let
go [] n = pokeElemOff ptr n nUL
go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1)
in do
go str 0
f ptr
-- | Marshal a Haskell string into a C string (ie, character array)
-- in temporary storage, with explicit length information.
--
-- * the memory is freed when the subcomputation terminates (either
-- normally or via an exception), so the pointer to the temporary
-- storage must /not/ be used after this.
--
withCAStringLen :: String -> (CStringLen -> IO a) -> IO a
withCAStringLen str f =
allocaArray len $ \ptr ->
let
go [] n = n `seq` return () -- make it strict in n
go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1)
in do
go str 0
f (ptr,len)
where
len = length str
-- auxiliary definitions
-- ----------------------
-- C's end of string character
--
nUL :: CChar
nUL = 0
-- allocate an array to hold the list and pair it with the number of elements
newArrayLen :: Storable a => [a] -> IO (Ptr a, Int)
newArrayLen xs = do
a <- newArray xs
return (a, length xs)
-----------------------------------------------------------------------------
-- Wide strings
-- representation of wide strings in C
-- -----------------------------------
-- | A C wide string is a reference to an array of C wide characters
-- terminated by NUL.
type CWString = Ptr CWchar
-- | A wide character string with explicit length information in 'CWchar's
-- instead of a terminating NUL (allowing NUL characters in the middle
-- of the string).
type CWStringLen = (Ptr CWchar, Int)
-- | Marshal a NUL terminated C wide string into a Haskell string.
--
peekCWString :: CWString -> IO String
peekCWString cp = do
cs <- peekArray0 wNUL cp
return (cWcharsToChars cs)
-- | Marshal a C wide string with explicit length into a Haskell string.
--
peekCWStringLen :: CWStringLen -> IO String
peekCWStringLen (cp, len) = do
cs <- peekArray len cp
return (cWcharsToChars cs)
-- | Marshal a Haskell string into a NUL terminated C wide string.
--
-- * the Haskell string may /not/ contain any NUL characters
--
-- * new storage is allocated for the C wide string and must
-- be explicitly freed using 'Foreign.Marshal.Alloc.free' or
-- 'Foreign.Marshal.Alloc.finalizerFree'.
--
newCWString :: String -> IO CWString
newCWString = newArray0 wNUL . charsToCWchars
-- | Marshal a Haskell string into a C wide string (ie, wide character array)
-- with explicit length information.
--
-- * new storage is allocated for the C wide string and must
-- be explicitly freed using 'Foreign.Marshal.Alloc.free' or
-- 'Foreign.Marshal.Alloc.finalizerFree'.
--
newCWStringLen :: String -> IO CWStringLen
newCWStringLen str = newArrayLen (charsToCWchars str)
-- | Marshal a Haskell string into a NUL terminated C wide string using
-- temporary storage.
--
-- * the Haskell string may /not/ contain any NUL characters
--
-- * the memory is freed when the subcomputation terminates (either
-- normally or via an exception), so the pointer to the temporary
-- storage must /not/ be used after this.
--
withCWString :: String -> (CWString -> IO a) -> IO a
withCWString = withArray0 wNUL . charsToCWchars
-- | Marshal a Haskell string into a C wide string (i.e. wide
-- character array) in temporary storage, with explicit length
-- information.
--
-- * the memory is freed when the subcomputation terminates (either
-- normally or via an exception), so the pointer to the temporary
-- storage must /not/ be used after this.
--
withCWStringLen :: String -> (CWStringLen -> IO a) -> IO a
withCWStringLen str f =
withArrayLen (charsToCWchars str) $ \ len ptr -> f (ptr, len)
-- auxiliary definitions
-- ----------------------
wNUL :: CWchar
wNUL = 0
cWcharsToChars :: [CWchar] -> [Char]
charsToCWchars :: [Char] -> [CWchar]
#ifdef mingw32_HOST_OS
-- On Windows, wchar_t is 16 bits wide and CWString uses the UTF-16 encoding.
-- coding errors generate Chars in the surrogate range
cWcharsToChars = map chr . fromUTF16 . map fromIntegral
where
fromUTF16 (c1:c2:wcs)
| 0xd800 <= c1 && c1 <= 0xdbff && 0xdc00 <= c2 && c2 <= 0xdfff =
((c1 - 0xd800)*0x400 + (c2 - 0xdc00) + 0x10000) : fromUTF16 wcs
fromUTF16 (c:wcs) = c : fromUTF16 wcs
fromUTF16 [] = []
charsToCWchars = foldr utf16Char [] . map ord
where
utf16Char c wcs
| c < 0x10000 = fromIntegral c : wcs
| otherwise = let c' = c - 0x10000 in
fromIntegral (c' `div` 0x400 + 0xd800) :
fromIntegral (c' `mod` 0x400 + 0xdc00) : wcs
#else /* !mingw32_HOST_OS */
cWcharsToChars xs = map castCWcharToChar xs
charsToCWchars xs = map castCharToCWchar xs
-- These conversions only make sense if __STDC_ISO_10646__ is defined
-- (meaning that wchar_t is ISO 10646, aka Unicode)
castCWcharToChar :: CWchar -> Char
castCWcharToChar ch = chr (fromIntegral ch )
castCharToCWchar :: Char -> CWchar
castCharToCWchar ch = fromIntegral (ord ch)
#endif /* !mingw32_HOST_OS */
| ryantm/ghc | libraries/base/Foreign/C/String.hs | bsd-3-clause | 14,693 | 0 | 16 | 2,992 | 2,349 | 1,293 | 1,056 | 162 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | Tag a Binary instance with the stack version number to ensure we're
-- reading a compatible format.
module Data.Binary.VersionTagged
( taggedDecodeOrLoad
, taggedEncodeFile
, Binary (..)
, BinarySchema (..)
, decodeFileOrFailDeep
, encodeFile
, NFData (..)
, genericRnf
) where
import Control.DeepSeq.Generics (NFData (..), genericRnf)
import Control.Exception (Exception)
import Control.Monad.Catch (MonadThrow (..))
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Binary (Binary (..), encodeFile, decodeFileOrFail, putWord8, getWord8)
import Data.Binary.Get (ByteOffset)
import Data.Typeable (Typeable)
import Control.Exception.Enclosed (tryAnyDeep)
import System.FilePath (takeDirectory)
import System.Directory (createDirectoryIfMissing)
import qualified Data.ByteString as S
import Data.ByteString (ByteString)
import Control.Monad (forM_, when)
import Data.Proxy
magic :: ByteString
magic = "stack"
-- | A @Binary@ instance that also has a schema version
class (Binary a, NFData a) => BinarySchema a where
binarySchema :: Proxy a -> Int
newtype WithTag a = WithTag a
deriving NFData
instance forall a. BinarySchema a => Binary (WithTag a) where
get = do
forM_ (S.unpack magic) $ \w -> do
w' <- getWord8
when (w /= w')
$ fail "Mismatched magic string, forcing a recompute"
tag' <- get
if binarySchema (Proxy :: Proxy a) == tag'
then fmap WithTag get
else fail "Mismatched tags, forcing a recompute"
put (WithTag x) = do
mapM_ putWord8 $ S.unpack magic
put (binarySchema (Proxy :: Proxy a))
put x
-- | Write to the given file, with a version tag.
taggedEncodeFile :: (BinarySchema a, MonadIO m)
=> FilePath
-> a
-> m ()
taggedEncodeFile fp x = liftIO $ do
createDirectoryIfMissing True $ takeDirectory fp
encodeFile fp $ WithTag x
-- | Read from the given file. If the read fails, run the given action and
-- write that back to the file. Always starts the file off with the version
-- tag.
taggedDecodeOrLoad :: (BinarySchema a, MonadIO m)
=> FilePath
-> m a
-> m a
taggedDecodeOrLoad fp mx = do
eres <- decodeFileOrFailDeep fp
case eres of
Left _ -> do
x <- mx
taggedEncodeFile fp x
return x
Right (WithTag x) -> return x
-- | Ensure that there are no lurking exceptions deep inside the parsed
-- value... because that happens unfortunately. See
-- https://github.com/commercialhaskell/stack/issues/554
decodeFileOrFailDeep :: (Binary a, NFData a, MonadIO m, MonadThrow n)
=> FilePath
-> m (n a)
decodeFileOrFailDeep fp = liftIO $ fmap (either throwM return) $ tryAnyDeep $ do
eres <- decodeFileOrFail fp
case eres of
Left (offset, str) -> throwM $ DecodeFileFailure fp offset str
Right x -> return x
data DecodeFileFailure = DecodeFileFailure FilePath ByteOffset String
deriving Typeable
instance Show DecodeFileFailure where
show (DecodeFileFailure fp offset str) = concat
[ "Decoding of "
, fp
, " failed at offset "
, show offset
, ": "
, str
]
instance Exception DecodeFileFailure
| Denommus/stack | src/Data/Binary/VersionTagged.hs | bsd-3-clause | 3,538 | 0 | 15 | 939 | 854 | 456 | 398 | 85 | 2 |
{-# OPTIONS_GHC -fplugin LinkerTicklingPlugin #-}
module Main where
main :: IO ()
main = return ()
| siddhanathan/ghc | testsuite/tests/plugins/plugins06.hs | bsd-3-clause | 101 | 0 | 6 | 18 | 25 | 14 | 11 | 4 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Prelude
import RIO
import Control.Teardown
main :: IO ()
main = do
baruta <- newTeardown "baruta" (return () :: IO ())
bqto <- newTeardown "barquisimeto" (return () :: IO ())
colombia <- newTeardown "colombia" (return () :: IO ())
mexico <- newTeardown "mexico" (return () :: IO ())
caracas <- newTeardown "caracas" (return [baruta] :: IO [Teardown])
venezuela <- newTeardown "venezuela" (return [bqto, caracas] :: IO [Teardown])
earth <- newTeardown "earth"
(return [colombia, mexico, venezuela] :: IO [Teardown])
result <- runTeardown earth
Prelude.print $ prettyTeardownResult result
| roman/Haskell-teardown | examples/teardown-example/src/Main.hs | isc | 764 | 0 | 11 | 171 | 266 | 133 | 133 | 18 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module XmlParse where
import qualified Data.Char as Char
import Data.Conduit.Attoparsec
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.XML.Types as XML
import Text.Megaparsec
import Text.Megaparsec.Prim
import Text.Megaparsec.Pos
import XmlEvents
import qualified XmlTree as Tree
getEventLocation :: Event -> Location
getEventLocation (EventBeginElement _ _ r) = r
getEventLocation (EventEndElement _ r) = r
getEventLocation (EventContent _ r) = r
getEventLocation (EventCDATA _ r) = r
updatePosEvent :: Int -> SourcePos -> Event -> SourcePos
updatePosEvent _ p e = buildPos src startPos
where
(Location src pos) = getEventLocation e
startPos = posRangeStart pos
buildPos n (Position l c) = flip setSourceName n . flip setSourceColumn c . flip setSourceLine l $ p
tryHandle :: MonadParsec s m Event => (Event -> Either [Message] a) -> m a
tryHandle f = token updatePosEvent f
singleUnexpected :: String -> Either [Message] a
singleUnexpected = Left . pure . Unexpected
parseBegin :: Event -> Either [Message] (XML.Name, [(XML.Name, [XML.Content])], Location)
parseBegin (EventBeginElement n a p) = Right (n, a, p)
parseBegin e = singleUnexpected . show $ e
parseEnd :: XML.Name -> Event -> Either [Message] Location
parseEnd n1 (EventEndElement n2 p) | n1 == n2 = Right p
parseEnd n e = singleUnexpected $ "Expected end element " ++ show n ++ " but found " ++ show e
eventToTextContent :: Event -> Either [Message] Tree.Content
eventToTextContent (EventContent (XML.ContentText t) p) = Right (Tree.Content (Tree.ContentText t) p)
eventToTextContent (EventCDATA t p) = Right (Tree.Content (Tree.ContentText t) p)
eventToTextContent e = singleUnexpected . show $ e
eventToEntityContent :: Event -> Either [Message] Tree.Content
eventToEntityContent (EventContent (XML.ContentEntity t) p) = Right (Tree.Content (Tree.ContentEntity t) p)
eventToEntityContent e = singleUnexpected . show $ e
mergePositionRange :: PositionRange -> PositionRange -> PositionRange
mergePositionRange (PositionRange p1 p2) (PositionRange p3 p4) = PositionRange (minimum positions) (maximum positions) where positions = [p1, p2, p3, p4]
mergeLocation :: Location -> Location -> Location
mergeLocation (Location src1 p1) (Location _ p2) = Location src1 (mergePositionRange p1 p2)
getTextContentOrEmpty :: Tree.Content -> Text
getTextContentOrEmpty (Tree.Content (Tree.ContentText t) _) = t
getTextContentOrEmpty _ = Text.empty
concatContent :: MonadParsec s m Event => m Tree.Content
concatContent = do
contents <- some (tryHandle eventToTextContent)
case contents of
[] -> fail "Empty content list"
(x : xs) ->
let text = Text.concat . fmap getTextContentOrEmpty $ contents
in
if Text.null text
then fail "Empty content"
else return $ Tree.Content (Tree.ContentText text) (foldr mergeLocation (Tree.location x) (Tree.location <$> xs))
elementOrContentParser :: MonadParsec s m Event => m (Either Tree.Element Tree.Content)
elementOrContentParser
= (Left <$> elementParser)
<|> (Right <$> concatContent)
<|> (Right <$> (tryHandle eventToEntityContent))
elementParser :: MonadParsec s m Event => m Tree.Element
elementParser = do
(name, attr, beginPos) <- tryHandle parseBegin
children <- many elementOrContentParser
endPos <- tryHandle (parseEnd name)
return $ Tree.Element name attr beginPos endPos children
whitespaceContent :: MonadParsec s m Event => m ()
whitespaceContent = tryHandle whitespaceEvent
where
whitespaceEvent (EventContent (XML.ContentText t) _) | Text.all Char.isSpace t = Right ()
whitespaceEvent e = singleUnexpected . show $ e
rootParser :: MonadParsec s m Event => m Tree.Element
rootParser = do
_ <- many whitespaceContent
elementParser
parseElementEvents :: [Event] -> Either [String] Tree.Element
parseElementEvents events = do
case runParser rootParser "" events of
Left e -> Left (messageString <$> errorMessages e)
Right x -> Right x
| scott-fleischman/haskell-xml-infer | src/XmlParse.hs | mit | 4,024 | 0 | 19 | 667 | 1,410 | 715 | 695 | 80 | 3 |
module Main where
import qualified ExpressionProblem1a as EP1a
import qualified ExpressionProblem1b as EP1b
import qualified ExpressionProblem2a as EP2a
import qualified ExpressionProblem2b as EP2b
import qualified ExpressionProblem3a as EP3a
import qualified ExpressionProblem3b as EP3b
-- References
-- http://c2.com/cgi/wiki?ExpressionProblem
-- http://koerbitz.me/posts/Solving-the-Expression-Problem-in-Haskell-and-Java.html
-- http://koerbitz.me/posts/Sum-Types-Visitors-and-the-Expression-Problem.html
-- https://www.staff.science.uu.nl/~swier004/Publications/DataTypesALaCarte.pdf
-- https://oleksandrmanzyuk.wordpress.com/2014/06/18/from-object-algebras-to-finally-tagless-interpreters-2/
-- https://www.andres-loeh.de/OpenDatatypes.pdf
-- http://wadler.blogspot.com/2008/02/data-types-la-carte.html
-- Expression problem (1)
-- Using single ADT
--
-- Can add new functions: just create a new function, e.g. "perimeter"
--
-- Can't add new shapes: "Shape" ADT and existing functions are closed
expressionProblem1 :: IO ()
expressionProblem1 = do
putStrLn "ExpressionProblem1"
let shapes = [EP1a.Square 10.0, EP1a.Circle 10.0]
print $ map EP1a.area shapes
print $ map EP1b.perimeter shapes
-- Expression problem (2)
-- Using type classes and separate ADT for each shape
--
-- Straightforward to add new functions: declare a new type class and
-- implement an instance for each shape
--
-- Straightforward to add new shapes: declare a new ADT and implement existing
-- type classes
--
-- Problem: Heterogeneous lists of shapes not possible
expressionProblem2 :: IO ()
expressionProblem2 = do
putStrLn "ExpressionProblem2"
let
squares = [EP2a.Square 10.0, EP2a.Square 20.0]
circles = [EP2a.Circle 10.0, EP2a.Circle 20.0]
rectangles = [EP2b.Rectangle 10.0 20.0, EP2b.Rectangle 20.0 30.0]
print $ map EP2a.area squares
print $ map EP2b.perimeter squares
print $ map EP2a.area circles
print $ map EP2b.perimeter circles
print $ map EP2a.area rectangles
print $ map EP2b.perimeter rectangles
-- Expression problem (2)
-- Use existential quantification to solve the previous problem
expressionProblem3 :: IO ()
expressionProblem3 = do
putStrLn "ExpressionProblem3"
let shapes = [
EP3b.Shape $ EP3a.Square 10.0,
EP3b.Shape $ EP3a.Circle 10.0,
EP3b.Shape $ EP3b.Rectangle 10.0 20.0
]
print $ map EP3a.area shapes
print $ map EP3b.perimeter shapes
main :: IO ()
main =
expressionProblem1 >>
expressionProblem2 >>
expressionProblem3
| rcook/expression-problem | src/Main.hs | mit | 2,520 | 0 | 13 | 380 | 441 | 235 | 206 | 40 | 1 |
import Data.List (sortBy)
import Data.Ord (comparing)
collatz :: Integer -> [Integer]
collatz n
| n == 1 = [1]
| n `mod` 2 == 0 = n : collatz (n `div` 2)
| otherwise = n : collatz (3 * n + 1)
collatzSequences :: Integer -> [[Integer]]
collatzSequences n = map collatz [1..n]
collatzSequenceLengths :: Integer -> [(Integer, Int)]
collatzSequenceLengths n = zip [1..n] (map length (collatzSequences n))
solution = last $ sortBy (comparing snd ) $ collatzSequenceLengths 999999
--solution = maximumBy . comparing . snd $ collatzSequenceLengths 999999 | DylanSp/Project-Euler-in-Haskell | prob14/solution.hs | mit | 611 | 0 | 10 | 153 | 225 | 119 | 106 | 12 | 1 |
module Rubik.Tables.Distances where
import Rubik.Cube
import Rubik.Solver
import Rubik.Tables.Internal
import Rubik.Tables.Moves
import qualified Data.Vector.Storable.Allocated as S
import qualified Data.Vector.HalfByte as HB
d_CornerOrien_UDSlice
= distanceTable2 "dist_CornerOrien_UDSlice" move18CornerOrien move18UDSlice
d_EdgeOrien_UDSlice
= distanceTable2 "dist_EdgeOrien_UDSlice" move18EdgeOrien move18UDSlice
d_UDEdgePermu2_UDSlicePermu2
= distanceTable2 "dist_EdgePermu2" move10UDEdgePermu2 move10UDSlicePermu2
d_CornerPermu_UDSlicePermu2
= distanceTable2 "dist_CornerPermu_UDSlicePermu2" move10CornerPermu move10UDSlicePermu2
dSym_CornerOrien_FlipUDSlicePermu
= saved' "dist_SymFlipUDSlicePermu_CornerOrien" $
distanceWithSym2'
move18SymFlipUDSlicePermu move18CornerOrien
invertedSym16CornerOrien
symProjFlipUDSlicePermu
rawProjection
n1
n2
:: HB.Vector'
where
n1 = 1523864
n2 = range ([] :: [CornerOrien])
dSym_CornerOrien_CornerPermu
= saved' "dist_SymCornerPermu_CornerOrien" $
distanceWithSym2'
move18SymCornerPermu move18CornerOrien
invertedSym16CornerOrien
symProjCornerPermu
rawProjection
n1
n2
:: S.Vector DInt
where
n1 = 2768
n2 = range ([] :: [CornerOrien])
| Lysxia/twentyseven | src/Rubik/Tables/Distances.hs | mit | 1,328 | 0 | 9 | 247 | 215 | 121 | 94 | 39 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ConstraintKinds #-}
-- | Warning: This module should be considered highly experimental.
module Data.Sequences where
import Data.Maybe (fromJust, isJust)
import Data.Monoid (Monoid, mconcat, mempty)
import Data.MonoTraversable
import Data.Int (Int64, Int)
import qualified Data.List as List
import qualified Control.Monad (filterM, replicateM)
import Prelude (Bool (..), Monad (..), Maybe (..), Ordering (..), Ord (..), Eq (..), Functor (..), fromIntegral, otherwise, (-), fst, snd, Integral, ($), flip, maybe, error)
import Data.Char (Char, isSpace)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import Control.Category
import Control.Arrow ((***), first, second)
import Control.Monad (liftM)
import qualified Data.Sequence as Seq
import qualified Data.DList as DList
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Storable as VS
import Data.String (IsString)
import qualified Data.List.NonEmpty as NE
import qualified Data.ByteString.Unsafe as SU
import Data.GrowingAppend
import Data.Vector.Instances ()
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Algorithms.Merge as VAM
import Data.Ord (comparing)
-- | 'SemiSequence' was created to share code between 'IsSequence' and 'MinLen'.
--
-- @Semi@ means 'SemiGroup'
-- A 'SemiSequence' can accomodate a 'SemiGroup' such as 'NonEmpty' or 'MinLen'
-- A Monoid should be able to fill out 'IsSequence'.
--
-- 'SemiSequence' operations maintain the same type because they all maintain the same number of elements or increase them.
-- However, a decreasing function such as filter may change they type.
-- For example, from 'NonEmpty' to '[]'
-- This type-changing function exists on 'NonNull' as 'nfilter'
--
-- 'filter' and other such functions are placed in 'IsSequence'
class (Integral (Index seq), GrowingAppend seq) => SemiSequence seq where
-- | The type of the index of a sequence.
type Index seq
-- | 'intersperse' takes an element and intersperses that element between
-- the elements of the sequence.
--
-- @
-- > 'intersperse' ',' "abcde"
-- "a,b,c,d,e"
-- @
intersperse :: Element seq -> seq -> seq
-- FIXME split :: (Element seq -> Bool) -> seq -> [seq]
-- | Reverse a sequence
--
-- @
-- > 'reverse' "hello world"
-- "dlrow olleh"
-- @
reverse :: seq -> seq
-- | 'find' takes a predicate and a sequence and returns the first element in
-- the sequence matching the predicate, or 'Nothing' if there isn't an element
-- that matches the predicate.
--
-- @
-- > 'find' (== 5) [1 .. 10]
-- 'Just' 5
--
-- > 'find' (== 15) [1 .. 10]
-- 'Nothing'
-- @
find :: (Element seq -> Bool) -> seq -> Maybe (Element seq)
-- | Sort a sequence using an supplied element ordering function.
--
-- @
-- > let compare' x y = case 'compare' x y of LT -> GT; EQ -> EQ; GT -> LT
-- > 'sortBy' compare' [5,3,6,1,2,4]
-- [6,5,4,3,2,1]
-- @
sortBy :: (Element seq -> Element seq -> Ordering) -> seq -> seq
-- | Prepend an element onto a sequence.
--
-- @
-- > 4 \``cons`` [1,2,3]
-- [4,1,2,3]
-- @
cons :: Element seq -> seq -> seq
-- | Append an element onto a sequence.
--
-- @
-- > [1,2,3] \``snoc`` 4
-- [1,2,3,4]
-- @
snoc :: seq -> Element seq -> seq
-- | Create a sequence from a single element.
--
-- @
-- > 'singleton' 'a' :: 'String'
-- "a"
-- > 'singleton' 'a' :: 'Vector' 'Char'
-- 'Data.Vector.fromList' "a"
-- @
singleton :: IsSequence seq => Element seq -> seq
singleton = opoint
{-# INLINE singleton #-}
-- | Sequence Laws:
--
-- @
-- 'fromList' . 'otoList' = 'id'
-- 'fromList' (x <> y) = 'fromList' x <> 'fromList' y
-- 'otoList' ('fromList' x <> 'fromList' y) = x <> y
-- @
class (Monoid seq, MonoTraversable seq, SemiSequence seq, MonoPointed seq) => IsSequence seq where
-- | Convert a list to a sequence.
--
-- @
-- > 'fromList' ['a', 'b', 'c'] :: Text
-- "abc"
-- @
fromList :: [Element seq] -> seq
-- this definition creates the Monoid constraint
-- However, all the instances define their own fromList
fromList = mconcat . fmap singleton
-- below functions change type fron the perspective of NonEmpty
-- | 'break' applies a predicate to a sequence, and returns a tuple where
-- the first element is the longest prefix (possibly empty) of elements that
-- /do not satisfy/ the predicate. The second element of the tuple is the
-- remainder of the sequence.
--
-- @'break' p@ is equivalent to @'span' ('not' . p)@
--
-- @
-- > 'break' (> 3) ('fromList' [1,2,3,4,1,2,3,4] :: 'Vector' 'Int')
-- (fromList [1,2,3],fromList [4,1,2,3,4])
--
-- > 'break' (< 'z') ('fromList' "abc" :: 'Text')
-- ("","abc")
--
-- > 'break' (> 'z') ('fromList' "abc" :: 'Text')
-- ("abc","")
-- @
break :: (Element seq -> Bool) -> seq -> (seq, seq)
break f = (fromList *** fromList) . List.break f . otoList
-- | 'span' applies a predicate to a sequence, and returns a tuple where
-- the first element is the longest prefix (possibly empty) that
-- /does satisfy/ the predicate. The second element of the tuple is the
-- remainder of the sequence.
--
-- @'span' p xs@ is equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@
--
-- @
-- > 'span' (< 3) ('fromList' [1,2,3,4,1,2,3,4] :: 'Vector' 'Int')
-- (fromList [1,2],fromList [3,4,1,2,3,4])
--
-- > 'span' (< 'z') ('fromList' "abc" :: 'Text')
-- ("abc","")
--
-- > 'span' (< 0) [1,2,3]
-- ([],[1,2,3])
-- @
span :: (Element seq -> Bool) -> seq -> (seq, seq)
span f = (fromList *** fromList) . List.span f . otoList
-- | 'dropWhile' returns the suffix remaining after 'takeWhile'.
--
-- @
-- > 'dropWhile' (< 3) [1,2,3,4,5,1,2,3]
-- [3,4,5,1,2,3]
--
-- > 'dropWhile' (< 'z') ('fromList' "abc" :: 'Text')
-- ""
-- @
dropWhile :: (Element seq -> Bool) -> seq -> seq
dropWhile f = fromList . List.dropWhile f . otoList
-- | 'takeWhile' applies a predicate to a sequence, and returns the
-- longest prefix (possibly empty) of the sequence of elements that
-- /satisfy/ the predicate.
--
-- @
-- > 'takeWhile' (< 3) [1,2,3,4,5,1,2,3]
-- [1,2]
--
-- > 'takeWhile' (< 'z') ('fromList' "abc" :: 'Text')
-- "abc"
-- @
takeWhile :: (Element seq -> Bool) -> seq -> seq
takeWhile f = fromList . List.takeWhile f . otoList
-- | @'splitAt' n se@ returns a tuple where the first element is the prefix of
-- the sequence @se@ with length @n@, and the second element is the remainder of
-- the sequence.
--
-- @
-- > 'splitAt' 6 "Hello world!"
-- ("Hello ","world!")
--
-- > 'splitAt' 3 ('fromList' [1,2,3,4,5] :: 'Vector' 'Int')
-- (fromList [1,2,3],fromList [4,5])
-- @
splitAt :: Index seq -> seq -> (seq, seq)
splitAt i = (fromList *** fromList) . List.genericSplitAt i . otoList
-- | Equivalent to 'splitAt'.
unsafeSplitAt :: Index seq -> seq -> (seq, seq)
unsafeSplitAt i seq = (unsafeTake i seq, unsafeDrop i seq)
-- | @'take' n@ returns the prefix of a sequence of length @n@, or the
-- sequence itself if @n > 'olength' seq@.
--
-- @
-- > 'take' 3 "abcdefg"
-- "abc"
-- > 'take' 4 ('fromList' [1,2,3,4,5,6] :: 'Vector' 'Int')
-- fromList [1,2,3,4]
-- @
take :: Index seq -> seq -> seq
take i = fst . splitAt i
-- | Equivalent to 'take'.
unsafeTake :: Index seq -> seq -> seq
unsafeTake = take
-- | @'drop' n@ returns the suffix of a sequence after the first @n@
-- elements, or an empty sequence if @n > 'olength' seq@.
--
-- @
-- > 'drop' 3 "abcdefg"
-- "defg"
-- > 'drop' 4 ('fromList' [1,2,3,4,5,6] :: 'Vector' 'Int')
-- fromList [5,6]
-- @
drop :: Index seq -> seq -> seq
drop i = snd . splitAt i
-- | Equivalent to 'drop'
unsafeDrop :: Index seq -> seq -> seq
unsafeDrop = drop
-- | 'partition' takes a predicate and a sequence and returns the pair of
-- sequences of elements which do and do not satisfy the predicate.
--
-- @
-- 'partition' p se = ('filter' p se, 'filter' ('not' . p) se)
-- @
partition :: (Element seq -> Bool) -> seq -> (seq, seq)
partition f = (fromList *** fromList) . List.partition f . otoList
-- | 'uncons' returns the tuple of the first element of a sequence and the rest
-- of the sequence, or 'Nothing' if the sequence is empty.
--
-- @
-- > 'uncons' ('fromList' [1,2,3,4] :: 'Vector' 'Int')
-- 'Just' (1,fromList [2,3,4])
--
-- > 'uncons' ([] :: ['Int'])
-- 'Nothing'
-- @
uncons :: seq -> Maybe (Element seq, seq)
uncons = fmap (second fromList) . uncons . otoList
-- | 'unsnoc' returns the tuple of the init of a sequence and the last element,
-- or 'Nothing' if the sequence is empty.
--
-- @
-- > 'uncons' ('fromList' [1,2,3,4] :: 'Vector' 'Int')
-- 'Just' (fromList [1,2,3],4)
--
-- > 'uncons' ([] :: ['Int'])
-- 'Nothing'
-- @
unsnoc :: seq -> Maybe (seq, Element seq)
unsnoc = fmap (first fromList) . unsnoc . otoList
-- | 'filter' given a predicate returns a sequence of all elements that satisfy
-- the predicate.
--
-- @
-- > 'filter' (< 5) [1 .. 10]
-- [1,2,3,4]
-- @
filter :: (Element seq -> Bool) -> seq -> seq
filter f = fromList . List.filter f . otoList
-- | The monadic version of 'filter'.
filterM :: Monad m => (Element seq -> m Bool) -> seq -> m seq
filterM f = liftM fromList . filterM f . otoList
-- replicates are not in SemiSequence to allow for zero
-- | @'replicate' n x@ is a sequence of length @n@ with @x@ as the
-- value of every element.
--
-- @
-- > 'replicate' 10 'a' :: Text
-- "aaaaaaaaaa"
-- @
replicate :: Index seq -> Element seq -> seq
replicate i = fromList . List.genericReplicate i
-- | The monadic version of 'replicateM'.
replicateM :: Monad m => Index seq -> m (Element seq) -> m seq
replicateM i = liftM fromList . Control.Monad.replicateM (fromIntegral i)
-- below functions are not in SemiSequence because they return a List (instead of NonEmpty)
-- | 'group' takes a sequence and returns a list of sequences such that the
-- concatenation of the result is equal to the argument. Each subsequence in
-- the result contains only equal elements, using the supplied equality test.
--
-- @
-- > 'groupBy' (==) "Mississippi"
-- ["M","i","ss","i","ss","i","pp","i"]
-- @
groupBy :: (Element seq -> Element seq -> Bool) -> seq -> [seq]
groupBy f = fmap fromList . List.groupBy f . otoList
-- | Similar to standard 'groupBy', but operates on the whole collection,
-- not just the consecutive items.
groupAllOn :: Eq b => (Element seq -> b) -> seq -> [seq]
groupAllOn f = fmap fromList . groupAllOn f . otoList
-- | 'subsequences' returns a list of all subsequences of the argument.
--
-- @
-- > 'subsequences' "abc"
-- ["","a","b","ab","c","ac","bc","abc"]
-- @
subsequences :: seq -> [seq]
subsequences = List.map fromList . List.subsequences . otoList
-- | 'permutations' returns a list of all permutations of the argument.
--
-- @
-- > 'permutations' "abc"
-- ["abc","bac","cba","bca","cab","acb"]
-- @
permutations :: seq -> [seq]
permutations = List.map fromList . List.permutations . otoList
-- | __Unsafe__
--
-- Get the tail of a sequence, throw an exception if the sequence is empty.
--
-- @
-- > 'tailEx' [1,2,3]
-- [2,3]
-- @
tailEx :: seq -> seq
tailEx = snd . maybe (error "Data.Sequences.tailEx") id . uncons
-- | __Unsafe__
--
-- Get the init of a sequence, throw an exception if the sequence is empty.
--
-- @
-- > 'initEx' [1,2,3]
-- [1,2]
-- @
initEx :: seq -> seq
initEx = fst . maybe (error "Data.Sequences.initEx") id . unsnoc
-- | Equivalent to 'tailEx'.
unsafeTail :: seq -> seq
unsafeTail = tailEx
-- | Equivalent to 'initEx'.
unsafeInit :: seq -> seq
unsafeInit = initEx
-- | Get the element of a sequence at a certain index, returns 'Nothing'
-- if that index does not exist.
--
-- @
-- > 'index' ('fromList' [1,2,3] :: 'Vector' 'Int') 1
-- 'Just' 2
-- > 'index' ('fromList' [1,2,3] :: 'Vector' 'Int') 4
-- 'Nothing'
-- @
index :: seq -> Index seq -> Maybe (Element seq)
index seq' idx = headMay (drop idx seq')
-- | __Unsafe__
--
-- Get the element of a sequence at a certain index, throws an exception
-- if the index does not exist.
indexEx :: seq -> Index seq -> Element seq
indexEx seq' idx = maybe (error "Data.Sequences.indexEx") id (index seq' idx)
-- | Equivalent to 'indexEx'.
unsafeIndex :: seq -> Index seq -> Element seq
unsafeIndex = indexEx
{-# INLINE fromList #-}
{-# INLINE break #-}
{-# INLINE span #-}
{-# INLINE dropWhile #-}
{-# INLINE takeWhile #-}
{-# INLINE splitAt #-}
{-# INLINE unsafeSplitAt #-}
{-# INLINE take #-}
{-# INLINE unsafeTake #-}
{-# INLINE drop #-}
{-# INLINE unsafeDrop #-}
{-# INLINE partition #-}
{-# INLINE uncons #-}
{-# INLINE unsnoc #-}
{-# INLINE filter #-}
{-# INLINE filterM #-}
{-# INLINE replicate #-}
{-# INLINE replicateM #-}
{-# INLINE groupBy #-}
{-# INLINE groupAllOn #-}
{-# INLINE subsequences #-}
{-# INLINE permutations #-}
{-# INLINE tailEx #-}
{-# INLINE initEx #-}
{-# INLINE unsafeTail #-}
{-# INLINE unsafeInit #-}
{-# INLINE index #-}
{-# INLINE indexEx #-}
{-# INLINE unsafeIndex #-}
-- | Use "Data.List"'s implementation of 'Data.List.find'.
defaultFind :: MonoFoldable seq => (Element seq -> Bool) -> seq -> Maybe (Element seq)
defaultFind f = List.find f . otoList
{-# INLINE defaultFind #-}
-- | Use "Data.List"'s implementation of 'Data.List.intersperse'.
defaultIntersperse :: IsSequence seq => Element seq -> seq -> seq
defaultIntersperse e = fromList . List.intersperse e . otoList
{-# INLINE defaultIntersperse #-}
-- | Use "Data.List"'s implementation of 'Data.List.reverse'.
defaultReverse :: IsSequence seq => seq -> seq
defaultReverse = fromList . List.reverse . otoList
{-# INLINE defaultReverse #-}
-- | Use "Data.List"'s implementation of 'Data.List.sortBy'.
defaultSortBy :: IsSequence seq => (Element seq -> Element seq -> Ordering) -> seq -> seq
defaultSortBy f = fromList . sortBy f . otoList
{-# INLINE defaultSortBy #-}
-- | Sort a vector using an supplied element ordering function.
vectorSortBy :: VG.Vector v e => (e -> e -> Ordering) -> v e -> v e
vectorSortBy f = VG.modify (VAM.sortBy f)
{-# INLINE vectorSortBy #-}
-- | Sort a vector.
vectorSort :: (VG.Vector v e, Ord e) => v e -> v e
vectorSort = VG.modify VAM.sort
{-# INLINE vectorSort #-}
-- | Use "Data.List"'s 'Data.List.:' to prepend an element to a sequence.
defaultCons :: IsSequence seq => Element seq -> seq -> seq
defaultCons e = fromList . (e:) . otoList
{-# INLINE defaultCons #-}
-- | Use "Data.List"'s 'Data.List.++' to append an element to a sequence.
defaultSnoc :: IsSequence seq => seq -> Element seq -> seq
defaultSnoc seq e = fromList (otoList seq List.++ [e])
{-# INLINE defaultSnoc #-}
-- | like Data.List.tail, but an input of 'mempty' returns 'mempty'
tailDef :: IsSequence seq => seq -> seq
tailDef xs = case uncons xs of
Nothing -> mempty
Just tuple -> snd tuple
{-# INLINE tailDef #-}
-- | like Data.List.init, but an input of 'mempty' returns 'mempty'
initDef :: IsSequence seq => seq -> seq
initDef xs = case unsnoc xs of
Nothing -> mempty
Just tuple -> fst tuple
{-# INLINE initDef #-}
instance SemiSequence [a] where
type Index [a] = Int
intersperse = List.intersperse
reverse = List.reverse
find = List.find
sortBy f = V.toList . sortBy f . V.fromList
cons = (:)
snoc = defaultSnoc
{-# INLINE intersperse #-}
{-# INLINE reverse #-}
{-# INLINE find #-}
{-# INLINE sortBy #-}
{-# INLINE cons #-}
{-# INLINE snoc #-}
instance IsSequence [a] where
fromList = id
filter = List.filter
filterM = Control.Monad.filterM
break = List.break
span = List.span
dropWhile = List.dropWhile
takeWhile = List.takeWhile
splitAt = List.splitAt
take = List.take
drop = List.drop
uncons [] = Nothing
uncons (x:xs) = Just (x, xs)
unsnoc [] = Nothing
unsnoc (x0:xs0) =
Just (loop id x0 xs0)
where
loop front x [] = (front [], x)
loop front x (y:z) = loop (front . (x:)) y z
partition = List.partition
replicate = List.replicate
replicateM = Control.Monad.replicateM
groupBy = List.groupBy
groupAllOn f (head : tail) =
(head : matches) : groupAllOn f nonMatches
where
(matches, nonMatches) = partition ((== f head) . f) tail
groupAllOn _ [] = []
{-# INLINE fromList #-}
{-# INLINE break #-}
{-# INLINE span #-}
{-# INLINE dropWhile #-}
{-# INLINE takeWhile #-}
{-# INLINE splitAt #-}
{-# INLINE unsafeSplitAt #-}
{-# INLINE take #-}
{-# INLINE unsafeTake #-}
{-# INLINE drop #-}
{-# INLINE unsafeDrop #-}
{-# INLINE partition #-}
{-# INLINE uncons #-}
{-# INLINE unsnoc #-}
{-# INLINE filter #-}
{-# INLINE filterM #-}
{-# INLINE replicate #-}
{-# INLINE replicateM #-}
{-# INLINE groupBy #-}
{-# INLINE groupAllOn #-}
{-# INLINE subsequences #-}
{-# INLINE permutations #-}
{-# INLINE tailEx #-}
{-# INLINE initEx #-}
{-# INLINE unsafeTail #-}
{-# INLINE unsafeInit #-}
instance SemiSequence (NE.NonEmpty a) where
type Index (NE.NonEmpty a) = Int
intersperse = NE.intersperse
reverse = NE.reverse
find x = find x . NE.toList
cons = NE.cons
snoc xs x = NE.fromList $ flip snoc x $ NE.toList xs
sortBy f = NE.fromList . sortBy f . NE.toList
{-# INLINE intersperse #-}
{-# INLINE reverse #-}
{-# INLINE find #-}
{-# INLINE sortBy #-}
{-# INLINE cons #-}
{-# INLINE snoc #-}
instance SemiSequence S.ByteString where
type Index S.ByteString = Int
intersperse = S.intersperse
reverse = S.reverse
find = S.find
cons = S.cons
snoc = S.snoc
sortBy = defaultSortBy
{-# INLINE intersperse #-}
{-# INLINE reverse #-}
{-# INLINE find #-}
{-# INLINE sortBy #-}
{-# INLINE cons #-}
{-# INLINE snoc #-}
instance IsSequence S.ByteString where
fromList = S.pack
replicate = S.replicate
filter = S.filter
break = S.break
span = S.span
dropWhile = S.dropWhile
takeWhile = S.takeWhile
splitAt = S.splitAt
take = S.take
unsafeTake = SU.unsafeTake
drop = S.drop
unsafeDrop = SU.unsafeDrop
partition = S.partition
uncons = S.uncons
unsnoc s
| S.null s = Nothing
| otherwise = Just (S.init s, S.last s)
groupBy = S.groupBy
tailEx = S.tail
initEx = S.init
unsafeTail = SU.unsafeTail
{-# INLINE fromList #-}
{-# INLINE break #-}
{-# INLINE span #-}
{-# INLINE dropWhile #-}
{-# INLINE takeWhile #-}
{-# INLINE splitAt #-}
{-# INLINE unsafeSplitAt #-}
{-# INLINE take #-}
{-# INLINE unsafeTake #-}
{-# INLINE drop #-}
{-# INLINE unsafeDrop #-}
{-# INLINE partition #-}
{-# INLINE uncons #-}
{-# INLINE unsnoc #-}
{-# INLINE filter #-}
{-# INLINE filterM #-}
{-# INLINE replicate #-}
{-# INLINE replicateM #-}
{-# INLINE groupBy #-}
{-# INLINE groupAllOn #-}
{-# INLINE subsequences #-}
{-# INLINE permutations #-}
{-# INLINE tailEx #-}
{-# INLINE initEx #-}
{-# INLINE unsafeTail #-}
{-# INLINE unsafeInit #-}
index bs i
| i >= S.length bs = Nothing
| otherwise = Just (S.index bs i)
indexEx = S.index
unsafeIndex = SU.unsafeIndex
{-# INLINE index #-}
{-# INLINE indexEx #-}
{-# INLINE unsafeIndex #-}
instance SemiSequence T.Text where
type Index T.Text = Int
intersperse = T.intersperse
reverse = T.reverse
find = T.find
cons = T.cons
snoc = T.snoc
sortBy = defaultSortBy
{-# INLINE intersperse #-}
{-# INLINE reverse #-}
{-# INLINE find #-}
{-# INLINE sortBy #-}
{-# INLINE cons #-}
{-# INLINE snoc #-}
instance IsSequence T.Text where
fromList = T.pack
replicate i c = T.replicate i (T.singleton c)
filter = T.filter
break = T.break
span = T.span
dropWhile = T.dropWhile
takeWhile = T.takeWhile
splitAt = T.splitAt
take = T.take
drop = T.drop
partition = T.partition
uncons = T.uncons
unsnoc t
| T.null t = Nothing
| otherwise = Just (T.init t, T.last t)
groupBy = T.groupBy
tailEx = T.tail
initEx = T.init
{-# INLINE fromList #-}
{-# INLINE break #-}
{-# INLINE span #-}
{-# INLINE dropWhile #-}
{-# INLINE takeWhile #-}
{-# INLINE splitAt #-}
{-# INLINE unsafeSplitAt #-}
{-# INLINE take #-}
{-# INLINE unsafeTake #-}
{-# INLINE drop #-}
{-# INLINE unsafeDrop #-}
{-# INLINE partition #-}
{-# INLINE uncons #-}
{-# INLINE unsnoc #-}
{-# INLINE filter #-}
{-# INLINE filterM #-}
{-# INLINE replicate #-}
{-# INLINE replicateM #-}
{-# INLINE groupBy #-}
{-# INLINE groupAllOn #-}
{-# INLINE subsequences #-}
{-# INLINE permutations #-}
{-# INLINE tailEx #-}
{-# INLINE initEx #-}
{-# INLINE unsafeTail #-}
{-# INLINE unsafeInit #-}
index t i
| i >= T.length t = Nothing
| otherwise = Just (T.index t i)
indexEx = T.index
unsafeIndex = T.index
{-# INLINE index #-}
{-# INLINE indexEx #-}
{-# INLINE unsafeIndex #-}
instance SemiSequence L.ByteString where
type Index L.ByteString = Int64
intersperse = L.intersperse
reverse = L.reverse
find = L.find
cons = L.cons
snoc = L.snoc
sortBy = defaultSortBy
{-# INLINE intersperse #-}
{-# INLINE reverse #-}
{-# INLINE find #-}
{-# INLINE sortBy #-}
{-# INLINE cons #-}
{-# INLINE snoc #-}
instance IsSequence L.ByteString where
fromList = L.pack
replicate = L.replicate
filter = L.filter
break = L.break
span = L.span
dropWhile = L.dropWhile
takeWhile = L.takeWhile
splitAt = L.splitAt
take = L.take
drop = L.drop
partition = L.partition
uncons = L.uncons
unsnoc s
| L.null s = Nothing
| otherwise = Just (L.init s, L.last s)
groupBy = L.groupBy
tailEx = L.tail
initEx = L.init
{-# INLINE fromList #-}
{-# INLINE break #-}
{-# INLINE span #-}
{-# INLINE dropWhile #-}
{-# INLINE takeWhile #-}
{-# INLINE splitAt #-}
{-# INLINE unsafeSplitAt #-}
{-# INLINE take #-}
{-# INLINE unsafeTake #-}
{-# INLINE drop #-}
{-# INLINE unsafeDrop #-}
{-# INLINE partition #-}
{-# INLINE uncons #-}
{-# INLINE unsnoc #-}
{-# INLINE filter #-}
{-# INLINE filterM #-}
{-# INLINE replicate #-}
{-# INLINE replicateM #-}
{-# INLINE groupBy #-}
{-# INLINE groupAllOn #-}
{-# INLINE subsequences #-}
{-# INLINE permutations #-}
{-# INLINE tailEx #-}
{-# INLINE initEx #-}
{-# INLINE unsafeTail #-}
{-# INLINE unsafeInit #-}
indexEx = L.index
unsafeIndex = L.index
{-# INLINE index #-}
{-# INLINE indexEx #-}
{-# INLINE unsafeIndex #-}
instance SemiSequence TL.Text where
type Index TL.Text = Int64
intersperse = TL.intersperse
reverse = TL.reverse
find = TL.find
cons = TL.cons
snoc = TL.snoc
sortBy = defaultSortBy
{-# INLINE intersperse #-}
{-# INLINE reverse #-}
{-# INLINE find #-}
{-# INLINE sortBy #-}
{-# INLINE cons #-}
{-# INLINE snoc #-}
instance IsSequence TL.Text where
fromList = TL.pack
replicate i c = TL.replicate i (TL.singleton c)
filter = TL.filter
break = TL.break
span = TL.span
dropWhile = TL.dropWhile
takeWhile = TL.takeWhile
splitAt = TL.splitAt
take = TL.take
drop = TL.drop
partition = TL.partition
uncons = TL.uncons
unsnoc t
| TL.null t = Nothing
| otherwise = Just (TL.init t, TL.last t)
groupBy = TL.groupBy
tailEx = TL.tail
initEx = TL.init
{-# INLINE fromList #-}
{-# INLINE break #-}
{-# INLINE span #-}
{-# INLINE dropWhile #-}
{-# INLINE takeWhile #-}
{-# INLINE splitAt #-}
{-# INLINE unsafeSplitAt #-}
{-# INLINE take #-}
{-# INLINE unsafeTake #-}
{-# INLINE drop #-}
{-# INLINE unsafeDrop #-}
{-# INLINE partition #-}
{-# INLINE uncons #-}
{-# INLINE unsnoc #-}
{-# INLINE filter #-}
{-# INLINE filterM #-}
{-# INLINE replicate #-}
{-# INLINE replicateM #-}
{-# INLINE groupBy #-}
{-# INLINE groupAllOn #-}
{-# INLINE subsequences #-}
{-# INLINE permutations #-}
{-# INLINE tailEx #-}
{-# INLINE initEx #-}
{-# INLINE unsafeTail #-}
{-# INLINE unsafeInit #-}
indexEx = TL.index
unsafeIndex = TL.index
{-# INLINE index #-}
{-# INLINE indexEx #-}
{-# INLINE unsafeIndex #-}
instance SemiSequence (Seq.Seq a) where
type Index (Seq.Seq a) = Int
cons = (Seq.<|)
snoc = (Seq.|>)
reverse = Seq.reverse
sortBy = Seq.sortBy
intersperse = defaultIntersperse
find = defaultFind
{-# INLINE intersperse #-}
{-# INLINE reverse #-}
{-# INLINE find #-}
{-# INLINE sortBy #-}
{-# INLINE cons #-}
{-# INLINE snoc #-}
instance IsSequence (Seq.Seq a) where
fromList = Seq.fromList
replicate = Seq.replicate
replicateM = Seq.replicateM
filter = Seq.filter
--filterM = Seq.filterM
break = Seq.breakl
span = Seq.spanl
dropWhile = Seq.dropWhileL
takeWhile = Seq.takeWhileL
splitAt = Seq.splitAt
take = Seq.take
drop = Seq.drop
partition = Seq.partition
uncons s =
case Seq.viewl s of
Seq.EmptyL -> Nothing
x Seq.:< xs -> Just (x, xs)
unsnoc s =
case Seq.viewr s of
Seq.EmptyR -> Nothing
xs Seq.:> x -> Just (xs, x)
--groupBy = Seq.groupBy
tailEx = Seq.drop 1
initEx xs = Seq.take (Seq.length xs - 1) xs
{-# INLINE fromList #-}
{-# INLINE break #-}
{-# INLINE span #-}
{-# INLINE dropWhile #-}
{-# INLINE takeWhile #-}
{-# INLINE splitAt #-}
{-# INLINE unsafeSplitAt #-}
{-# INLINE take #-}
{-# INLINE unsafeTake #-}
{-# INLINE drop #-}
{-# INLINE unsafeDrop #-}
{-# INLINE partition #-}
{-# INLINE uncons #-}
{-# INLINE unsnoc #-}
{-# INLINE filter #-}
{-# INLINE filterM #-}
{-# INLINE replicate #-}
{-# INLINE replicateM #-}
{-# INLINE groupBy #-}
{-# INLINE groupAllOn #-}
{-# INLINE subsequences #-}
{-# INLINE permutations #-}
{-# INLINE tailEx #-}
{-# INLINE initEx #-}
{-# INLINE unsafeTail #-}
{-# INLINE unsafeInit #-}
index seq' i
| i >= Seq.length seq' = Nothing
| otherwise = Just (Seq.index seq' i)
indexEx = Seq.index
unsafeIndex = Seq.index
{-# INLINE index #-}
{-# INLINE indexEx #-}
{-# INLINE unsafeIndex #-}
instance SemiSequence (DList.DList a) where
type Index (DList.DList a) = Int
cons = DList.cons
snoc = DList.snoc
reverse = defaultReverse
sortBy = defaultSortBy
intersperse = defaultIntersperse
find = defaultFind
{-# INLINE intersperse #-}
{-# INLINE reverse #-}
{-# INLINE find #-}
{-# INLINE sortBy #-}
{-# INLINE cons #-}
{-# INLINE snoc #-}
instance IsSequence (DList.DList a) where
fromList = DList.fromList
replicate = DList.replicate
tailEx = DList.tail
{-# INLINE fromList #-}
{-# INLINE replicate #-}
{-# INLINE tailEx #-}
instance SemiSequence (V.Vector a) where
type Index (V.Vector a) = Int
reverse = V.reverse
find = V.find
cons = V.cons
snoc = V.snoc
sortBy = vectorSortBy
intersperse = defaultIntersperse
{-# INLINE intersperse #-}
{-# INLINE reverse #-}
{-# INLINE find #-}
{-# INLINE sortBy #-}
{-# INLINE cons #-}
{-# INLINE snoc #-}
instance IsSequence (V.Vector a) where
fromList = V.fromList
replicate = V.replicate
replicateM = V.replicateM
filter = V.filter
filterM = V.filterM
break = V.break
span = V.span
dropWhile = V.dropWhile
takeWhile = V.takeWhile
splitAt = V.splitAt
take = V.take
drop = V.drop
unsafeTake = V.unsafeTake
unsafeDrop = V.unsafeDrop
partition = V.partition
uncons v
| V.null v = Nothing
| otherwise = Just (V.head v, V.tail v)
unsnoc v
| V.null v = Nothing
| otherwise = Just (V.init v, V.last v)
--groupBy = V.groupBy
tailEx = V.tail
initEx = V.init
unsafeTail = V.unsafeTail
unsafeInit = V.unsafeInit
{-# INLINE fromList #-}
{-# INLINE break #-}
{-# INLINE span #-}
{-# INLINE dropWhile #-}
{-# INLINE takeWhile #-}
{-# INLINE splitAt #-}
{-# INLINE unsafeSplitAt #-}
{-# INLINE take #-}
{-# INLINE unsafeTake #-}
{-# INLINE drop #-}
{-# INLINE unsafeDrop #-}
{-# INLINE partition #-}
{-# INLINE uncons #-}
{-# INLINE unsnoc #-}
{-# INLINE filter #-}
{-# INLINE filterM #-}
{-# INLINE replicate #-}
{-# INLINE replicateM #-}
{-# INLINE groupBy #-}
{-# INLINE groupAllOn #-}
{-# INLINE subsequences #-}
{-# INLINE permutations #-}
{-# INLINE tailEx #-}
{-# INLINE initEx #-}
{-# INLINE unsafeTail #-}
{-# INLINE unsafeInit #-}
index v i
| i >= V.length v = Nothing
| otherwise = Just (v V.! i)
indexEx = (V.!)
unsafeIndex = V.unsafeIndex
{-# INLINE index #-}
{-# INLINE indexEx #-}
{-# INLINE unsafeIndex #-}
instance U.Unbox a => SemiSequence (U.Vector a) where
type Index (U.Vector a) = Int
intersperse = defaultIntersperse
reverse = U.reverse
find = U.find
cons = U.cons
snoc = U.snoc
sortBy = vectorSortBy
{-# INLINE intersperse #-}
{-# INLINE reverse #-}
{-# INLINE find #-}
{-# INLINE sortBy #-}
{-# INLINE cons #-}
{-# INLINE snoc #-}
instance U.Unbox a => IsSequence (U.Vector a) where
fromList = U.fromList
replicate = U.replicate
replicateM = U.replicateM
filter = U.filter
filterM = U.filterM
break = U.break
span = U.span
dropWhile = U.dropWhile
takeWhile = U.takeWhile
splitAt = U.splitAt
take = U.take
drop = U.drop
unsafeTake = U.unsafeTake
unsafeDrop = U.unsafeDrop
partition = U.partition
uncons v
| U.null v = Nothing
| otherwise = Just (U.head v, U.tail v)
unsnoc v
| U.null v = Nothing
| otherwise = Just (U.init v, U.last v)
--groupBy = U.groupBy
tailEx = U.tail
initEx = U.init
unsafeTail = U.unsafeTail
unsafeInit = U.unsafeInit
{-# INLINE fromList #-}
{-# INLINE break #-}
{-# INLINE span #-}
{-# INLINE dropWhile #-}
{-# INLINE takeWhile #-}
{-# INLINE splitAt #-}
{-# INLINE unsafeSplitAt #-}
{-# INLINE take #-}
{-# INLINE unsafeTake #-}
{-# INLINE drop #-}
{-# INLINE unsafeDrop #-}
{-# INLINE partition #-}
{-# INLINE uncons #-}
{-# INLINE unsnoc #-}
{-# INLINE filter #-}
{-# INLINE filterM #-}
{-# INLINE replicate #-}
{-# INLINE replicateM #-}
{-# INLINE groupBy #-}
{-# INLINE groupAllOn #-}
{-# INLINE subsequences #-}
{-# INLINE permutations #-}
{-# INLINE tailEx #-}
{-# INLINE initEx #-}
{-# INLINE unsafeTail #-}
{-# INLINE unsafeInit #-}
index v i
| i >= U.length v = Nothing
| otherwise = Just (v U.! i)
indexEx = (U.!)
unsafeIndex = U.unsafeIndex
{-# INLINE index #-}
{-# INLINE indexEx #-}
{-# INLINE unsafeIndex #-}
instance VS.Storable a => SemiSequence (VS.Vector a) where
type Index (VS.Vector a) = Int
reverse = VS.reverse
find = VS.find
cons = VS.cons
snoc = VS.snoc
intersperse = defaultIntersperse
sortBy = vectorSortBy
{-# INLINE intersperse #-}
{-# INLINE reverse #-}
{-# INLINE find #-}
{-# INLINE sortBy #-}
{-# INLINE cons #-}
{-# INLINE snoc #-}
instance VS.Storable a => IsSequence (VS.Vector a) where
fromList = VS.fromList
replicate = VS.replicate
replicateM = VS.replicateM
filter = VS.filter
filterM = VS.filterM
break = VS.break
span = VS.span
dropWhile = VS.dropWhile
takeWhile = VS.takeWhile
splitAt = VS.splitAt
take = VS.take
drop = VS.drop
unsafeTake = VS.unsafeTake
unsafeDrop = VS.unsafeDrop
partition = VS.partition
uncons v
| VS.null v = Nothing
| otherwise = Just (VS.head v, VS.tail v)
unsnoc v
| VS.null v = Nothing
| otherwise = Just (VS.init v, VS.last v)
--groupBy = U.groupBy
tailEx = VS.tail
initEx = VS.init
unsafeTail = VS.unsafeTail
unsafeInit = VS.unsafeInit
{-# INLINE fromList #-}
{-# INLINE break #-}
{-# INLINE span #-}
{-# INLINE dropWhile #-}
{-# INLINE takeWhile #-}
{-# INLINE splitAt #-}
{-# INLINE unsafeSplitAt #-}
{-# INLINE take #-}
{-# INLINE unsafeTake #-}
{-# INLINE drop #-}
{-# INLINE unsafeDrop #-}
{-# INLINE partition #-}
{-# INLINE uncons #-}
{-# INLINE unsnoc #-}
{-# INLINE filter #-}
{-# INLINE filterM #-}
{-# INLINE replicate #-}
{-# INLINE replicateM #-}
{-# INLINE groupBy #-}
{-# INLINE groupAllOn #-}
{-# INLINE subsequences #-}
{-# INLINE permutations #-}
{-# INLINE tailEx #-}
{-# INLINE initEx #-}
{-# INLINE unsafeTail #-}
{-# INLINE unsafeInit #-}
index v i
| i >= VS.length v = Nothing
| otherwise = Just (v VS.! i)
indexEx = (VS.!)
unsafeIndex = VS.unsafeIndex
{-# INLINE index #-}
{-# INLINE indexEx #-}
{-# INLINE unsafeIndex #-}
-- | A typeclass for sequences whose elements have the 'Eq' typeclass
class (MonoFoldableEq seq, IsSequence seq, Eq (Element seq)) => EqSequence seq where
-- | 'stripPrefix' drops the given prefix from a sequence.
-- It returns 'Nothing' if the sequence did not start with the prefix
-- given, or 'Just' the sequence after the prefix, if it does.
--
-- @
-- > 'stripPrefix' "foo" "foobar"
-- 'Just' "foo"
-- > 'stripPrefix' "abc" "foobar"
-- 'Nothing'
-- @
stripPrefix :: seq -> seq -> Maybe seq
stripPrefix x y = fmap fromList (otoList x `stripPrefix` otoList y)
-- | 'stripSuffix' drops the given suffix from a sequence.
-- It returns 'Nothing' if the sequence did not end with the suffix
-- given, or 'Just' the sequence before the suffix, if it does.
--
-- @
-- > 'stripSuffix' "bar" "foobar"
-- 'Just' "foo"
-- > 'stripSuffix' "abc" "foobar"
-- 'Nothing'
-- @
stripSuffix :: seq -> seq -> Maybe seq
stripSuffix x y = fmap fromList (otoList x `stripSuffix` otoList y)
-- | 'isPrefixOf' takes two sequences and returns 'True' if the first
-- sequence is a prefix of the second.
isPrefixOf :: seq -> seq -> Bool
isPrefixOf x y = otoList x `isPrefixOf` otoList y
-- | 'isSuffixOf' takes two sequences and returns 'True' if the first
-- sequence is a suffix of the second.
isSuffixOf :: seq -> seq -> Bool
isSuffixOf x y = otoList x `isSuffixOf` otoList y
-- | 'isInfixOf' takes two sequences and returns 'true' if the first
-- sequence is contained, wholly and intact, anywhere within the second.
isInfixOf :: seq -> seq -> Bool
isInfixOf x y = otoList x `isInfixOf` otoList y
-- | Equivalent to @'groupBy' (==)@
group :: seq -> [seq]
group = groupBy (==)
-- | Similar to standard 'group', but operates on the whole collection,
-- not just the consecutive items.
--
-- Equivalent to @'groupAllOn' id@
groupAll :: seq -> [seq]
groupAll = groupAllOn id
{-# INLINE isPrefixOf #-}
{-# INLINE isSuffixOf #-}
{-# INLINE isInfixOf #-}
{-# INLINE stripPrefix #-}
{-# INLINE stripSuffix #-}
{-# INLINE group #-}
{-# INLINE groupAll #-}
{-# DEPRECATED elem "use oelem" #-}
elem :: EqSequence seq => Element seq -> seq -> Bool
elem = oelem
{-# DEPRECATED notElem "use onotElem" #-}
notElem :: EqSequence seq => Element seq -> seq -> Bool
notElem = onotElem
instance Eq a => EqSequence [a] where
stripPrefix = List.stripPrefix
stripSuffix x y = fmap reverse (List.stripPrefix (reverse x) (reverse y))
group = List.group
isPrefixOf = List.isPrefixOf
isSuffixOf x y = List.isPrefixOf (List.reverse x) (List.reverse y)
isInfixOf = List.isInfixOf
{-# INLINE stripPrefix #-}
{-# INLINE stripSuffix #-}
{-# INLINE group #-}
{-# INLINE groupAll #-}
{-# INLINE isPrefixOf #-}
{-# INLINE isSuffixOf #-}
{-# INLINE isInfixOf #-}
instance EqSequence S.ByteString where
stripPrefix x y
| x `S.isPrefixOf` y = Just (S.drop (S.length x) y)
| otherwise = Nothing
stripSuffix x y
| x `S.isSuffixOf` y = Just (S.take (S.length y - S.length x) y)
| otherwise = Nothing
group = S.group
isPrefixOf = S.isPrefixOf
isSuffixOf = S.isSuffixOf
isInfixOf = S.isInfixOf
{-# INLINE stripPrefix #-}
{-# INLINE stripSuffix #-}
{-# INLINE group #-}
{-# INLINE groupAll #-}
{-# INLINE isPrefixOf #-}
{-# INLINE isSuffixOf #-}
{-# INLINE isInfixOf #-}
instance EqSequence L.ByteString where
stripPrefix x y
| x `L.isPrefixOf` y = Just (L.drop (L.length x) y)
| otherwise = Nothing
stripSuffix x y
| x `L.isSuffixOf` y = Just (L.take (L.length y - L.length x) y)
| otherwise = Nothing
group = L.group
isPrefixOf = L.isPrefixOf
isSuffixOf = L.isSuffixOf
isInfixOf x y = L.unpack x `List.isInfixOf` L.unpack y
{-# INLINE stripPrefix #-}
{-# INLINE stripSuffix #-}
{-# INLINE group #-}
{-# INLINE groupAll #-}
{-# INLINE isPrefixOf #-}
{-# INLINE isSuffixOf #-}
{-# INLINE isInfixOf #-}
instance EqSequence T.Text where
stripPrefix = T.stripPrefix
stripSuffix = T.stripSuffix
group = T.group
isPrefixOf = T.isPrefixOf
isSuffixOf = T.isSuffixOf
isInfixOf = T.isInfixOf
{-# INLINE stripPrefix #-}
{-# INLINE stripSuffix #-}
{-# INLINE group #-}
{-# INLINE groupAll #-}
{-# INLINE isPrefixOf #-}
{-# INLINE isSuffixOf #-}
{-# INLINE isInfixOf #-}
instance EqSequence TL.Text where
stripPrefix = TL.stripPrefix
stripSuffix = TL.stripSuffix
group = TL.group
isPrefixOf = TL.isPrefixOf
isSuffixOf = TL.isSuffixOf
isInfixOf = TL.isInfixOf
{-# INLINE stripPrefix #-}
{-# INLINE stripSuffix #-}
{-# INLINE group #-}
{-# INLINE groupAll #-}
{-# INLINE isPrefixOf #-}
{-# INLINE isSuffixOf #-}
{-# INLINE isInfixOf #-}
instance Eq a => EqSequence (Seq.Seq a)
instance Eq a => EqSequence (V.Vector a)
instance (Eq a, U.Unbox a) => EqSequence (U.Vector a)
instance (Eq a, VS.Storable a) => EqSequence (VS.Vector a)
-- | A typeclass for sequences whose elements have the 'Ord' typeclass
class (EqSequence seq, MonoFoldableOrd seq) => OrdSequence seq where
-- | Sort a ordered sequence.
--
-- @
-- > 'sort' [4,3,1,2]
-- [1,2,3,4]
-- @
sort :: seq -> seq
sort = fromList . sort . otoList
{-# INLINE sort #-}
instance Ord a => OrdSequence [a] where
sort = V.toList . sort . V.fromList
{-# INLINE sort #-}
instance OrdSequence S.ByteString where
sort = S.sort
{-# INLINE sort #-}
instance OrdSequence L.ByteString
instance OrdSequence T.Text
instance OrdSequence TL.Text
instance Ord a => OrdSequence (Seq.Seq a)
instance Ord a => OrdSequence (V.Vector a) where
sort = vectorSort
{-# INLINE sort #-}
instance (Ord a, U.Unbox a) => OrdSequence (U.Vector a) where
sort = vectorSort
{-# INLINE sort #-}
instance (Ord a, VS.Storable a) => OrdSequence (VS.Vector a) where
sort = vectorSort
{-# INLINE sort #-}
-- | A typeclass for sequences whose elements are 'Char's.
class (IsSequence t, IsString t, Element t ~ Char) => Textual t where
-- | Break up a textual sequence into a list of words, which were delimited
-- by white space.
--
-- @
-- > 'words' "abc def ghi"
-- ["abc","def","ghi"]
-- @
words :: t -> [t]
-- | Join a list of textual sequences using seperating spaces.
--
-- @
-- > 'unwords' ["abc","def","ghi"]
-- "abc def ghi"
-- @
unwords :: [t] -> t
-- | Break up a textual sequence at newline characters.
--
--
-- @
-- > 'lines' "hello\\nworld"
-- ["hello","world"]
-- @
lines :: t -> [t]
-- | Join a list of textual sequences using newlines.
--
-- @
-- > 'unlines' ["abc","def","ghi"]
-- "abc\\ndef\\nghi"
-- @
unlines :: [t] -> t
-- | Convert a textual sequence to lower-case.
--
-- @
-- > 'toLower' "HELLO WORLD"
-- "hello world"
-- @
toLower :: t -> t
-- | Convert a textual sequence to upper-case.
--
-- @
-- > 'toUpper' "hello world"
-- "HELLO WORLD"
-- @
toUpper :: t -> t
-- | Convert a textual sequence to folded-case.
--
-- Slightly different from 'toLower', see @"Data.Text".'Data.Text.toCaseFold'@
toCaseFold :: t -> t
-- | Split a textual sequence into two parts, split at the first space.
--
-- @
-- > 'breakWord' "hello world"
-- ("hello","world")
-- @
breakWord :: t -> (t, t)
breakWord = fmap (dropWhile isSpace) . break isSpace
{-# INLINE breakWord #-}
-- | Split a textual sequence into two parts, split at the newline.
--
-- @
-- > 'breakLine' "abc\\ndef"
-- ("abc","def")
-- @
breakLine :: t -> (t, t)
breakLine =
(killCR *** drop 1) . break (== '\n')
where
killCR t =
case unsnoc t of
Just (t', '\r') -> t'
_ -> t
instance (c ~ Char) => Textual [c] where
words = List.words
unwords = List.unwords
lines = List.lines
unlines = List.unlines
toLower = TL.unpack . TL.toLower . TL.pack
toUpper = TL.unpack . TL.toUpper . TL.pack
toCaseFold = TL.unpack . TL.toCaseFold . TL.pack
{-# INLINE words #-}
{-# INLINE unwords #-}
{-# INLINE lines #-}
{-# INLINE unlines #-}
{-# INLINE toLower #-}
{-# INLINE toUpper #-}
{-# INLINE toCaseFold #-}
instance Textual T.Text where
words = T.words
unwords = T.unwords
lines = T.lines
unlines = T.unlines
toLower = T.toLower
toUpper = T.toUpper
toCaseFold = T.toCaseFold
{-# INLINE words #-}
{-# INLINE unwords #-}
{-# INLINE lines #-}
{-# INLINE unlines #-}
{-# INLINE toLower #-}
{-# INLINE toUpper #-}
{-# INLINE toCaseFold #-}
instance Textual TL.Text where
words = TL.words
unwords = TL.unwords
lines = TL.lines
unlines = TL.unlines
toLower = TL.toLower
toUpper = TL.toUpper
toCaseFold = TL.toCaseFold
{-# INLINE words #-}
{-# INLINE unwords #-}
{-# INLINE lines #-}
{-# INLINE unlines #-}
{-# INLINE toLower #-}
{-# INLINE toUpper #-}
{-# INLINE toCaseFold #-}
-- | Takes all of the `Just` values from a sequence of @Maybe t@s and
-- concatenates them into an unboxed sequence of @t@s.
--
-- Since 0.6.2
catMaybes :: (IsSequence (f (Maybe t)), Functor f,
Element (f (Maybe t)) ~ Maybe t)
=> f (Maybe t) -> f t
catMaybes = fmap fromJust . filter isJust
-- | Same as @sortBy . comparing@.
--
-- Since 0.7.0
sortOn :: (Ord o, SemiSequence seq) => (Element seq -> o) -> seq -> seq
sortOn = sortBy . comparing
{-# INLINE sortOn #-}
| pikajude/mono-traversable | src/Data/Sequences.hs | mit | 44,679 | 0 | 13 | 12,140 | 8,133 | 4,665 | 3,468 | 1,029 | 2 |
module SecretHandshake (handshake) where
handshake :: Int -> [String]
handshake n = error "You need to implement this function."
| exercism/xhaskell | exercises/practice/secret-handshake/src/SecretHandshake.hs | mit | 130 | 0 | 6 | 20 | 32 | 18 | 14 | 3 | 1 |
module DebugDisplay (toBinaryRepresentation) where
import Utilities(testBitAt)
import Data.Word(Word8)
import Data.Bits(Bits)
-- Useful Debug Display Functions
toBinaryRepresentation :: Bits a => [a] -> String
toBinaryRepresentation [] = []
toBinaryRepresentation (x:xs) = (concat [show $ boolToInt . testBitAt n $ x | n <- [0..7]]) ++ toBinaryRepresentation xs
where
boolToInt :: Bool -> Int
boolToInt False = 0
boolToInt True = 1
| tombusby/haskell-des | debug/DebugDisplay.hs | mit | 443 | 0 | 11 | 71 | 155 | 84 | 71 | 10 | 2 |
module Jbobaf (
module Jbobaf.Jitro,
module Jbobaf.Lerfendi,
module Jbobaf.Selmaho,
module Jbobaf.Valsi,
module Jbobaf.Vlatai
) where
import Jbobaf.Jitro
import Jbobaf.Lerfendi
import Jbobaf.Selmaho
import Jbobaf.Valsi
import Jbobaf.Vlatai
| jwodder/jbobaf | haskell/Jbobaf.hs | mit | 245 | 0 | 5 | 30 | 61 | 39 | 22 | 11 | 0 |
{-# LANGUAGE OverloadedStrings #-}
import CFDI (UUID(..))
import CFDI.PAC (ppCancelError, cancelCFDI)
import CFDI.PAC.Dummy (Dummy(..))
import CFDI.PAC.Fel (Fel(Fel), FelEnv(..))
import CFDI.PAC.ITimbre (ITimbre(ITimbre), ITimbreEnv(..))
import qualified Data.ByteString.Char8 as C8 (putStrLn)
import Data.Char (toLower)
import Data.Text (pack)
import Data.Text.Encoding (encodeUtf8)
import System.Environment (getArgs, getEnv, lookupEnv)
import System.Exit (ExitCode(ExitFailure), exitWith)
import System.IO (hPutStrLn, stderr)
main :: IO ()
main = do
args <- getArgs
case args of
(pacName : pfxPem : pfxPass : uuidStr : _) -> do
environment <- lookupEnv "CFDI_ENVIRONMENT"
let uuid = UUID $ pack uuidStr
isTest = (map toLower <$> environment) == Just "test"
case map toLower pacName of
"itimbre" -> do
user <- getEnv "CFDI_ITIMBRE_USER"
pass <- getEnv "CFDI_ITIMBRE_PASS"
rfc <- getEnv "CFDI_ITIMBRE_RFC"
let pac = ITimbre
(pack user)
(pack pass)
(pack rfc)
(pack pfxPass)
(pack pfxPem)
(if isTest
then ItimbreTestingEnv
else ItimbreProductionEnv
)
eitherErrOrAck <- cancelCFDI pac uuid
case eitherErrOrAck of
Left cancelError -> do
hPutStrLn stderr $ ppCancelError cancelError
exitWith $ ExitFailure 4
Right ack -> C8.putStrLn $ encodeUtf8 ack
"fel" -> do
user <- getEnv "CFDI_FEL_USER"
pass <- getEnv "CFDI_FEL_PASS"
rfc <- getEnv "CFDI_FEL_RFC"
let pac = Fel
(pack user)
(pack pass)
(pack rfc)
(pack pfxPem)
(pack pfxPass)
(if isTest then FelTestingEnv else FelProductionEnv)
eitherErrOrAck <- cancelCFDI pac uuid
case eitherErrOrAck of
Left cancelError -> do
hPutStrLn stderr $ ppCancelError cancelError
exitWith $ ExitFailure 4
Right ack -> C8.putStrLn $ encodeUtf8 ack
"dummy" -> do
eitherErrOrAck <- cancelCFDI Dummy uuid
case eitherErrOrAck of
Left cancelError -> do
hPutStrLn stderr $ ppCancelError cancelError
exitWith $ ExitFailure 4
Right ack -> C8.putStrLn $ encodeUtf8 ack
unknownPac -> do
hPutStrLn stderr $ "Unknown PAC " ++ unknownPac
exitWith $ ExitFailure 3
_ -> do
hPutStrLn stderr "Usage: cfdi_cancel [PAC name] [CFDI UUID]"
exitWith $ ExitFailure 2
| yusent/cfdis | cancel_cfdi/main.hs | mit | 2,827 | 0 | 23 | 1,041 | 756 | 376 | 380 | 71 | 10 |
{-# LANGUAGE RecursiveDo #-}
module Types.Parser.Types
( Imperative (..)
, VerbPhrase (..)
, NounPhrase (..)
, PrepPhrase (..)
, AdjPhrase (..)
, Noun
, Verb
, Determiner
, Preposition
, Adjective
) where
import Prelude
import Data.Text
data Imperative = Type1 VerbPhrase NounPhrase
| Type2 VerbPhrase PrepPhrase
| Type3 VerbPhrase NounPhrase PrepPhrase
| ImperativeClause Verb
deriving Show
type Noun = Text
type Verb = Text
type Determiner = Text
type Preposition = Text
type Adjective = Text
type Number = Text
data VerbPhrase = VerbPhrase1 Verb NounPhrase
| Verb Verb
deriving Show
data NounPhrase = NounPhrase1 Determiner NounPhrase
| NounPhrase2 Determiner AdjPhrase NounPhrase
| NounPhrase3 Number Noun
| Noun Noun
deriving Show
data PrepPhrase = PrepPhrase Preposition NounPhrase
| Preposition Preposition
deriving Show
data AdjPhrase = Adjective Adjective deriving Show
| mlitchard/cosmos | library/Types/Parser/Types.hs | mit | 1,136 | 0 | 6 | 387 | 224 | 140 | 84 | 37 | 0 |
-- copied from stackoverflow. review later to reenact
combinations :: Int -> [a] -> [[a]]
combinations k xs = combinations' (length xs) k xs
where
combinations' n k' l@(y:ys)
| k' == 0 = [[]]
| k' >= n = [l]
| null l = []
| otherwise = map (y :) (combinations' (n - 1) (k' - 1) ys) ++ combinations' (n - 1) k' ys
cardinality :: [a] -> Int
cardinality = length
subset :: Eq a => [a] -> [a] -> [a]
subset xs ys = filter (flip elem $ ys) xs
subset' :: Eq a => [[a]] -> [a]
subset' = foldl1 subset
subsetCardinality :: Eq a => [[a]] -> Int
subsetCardinality = cardinality . subset'
sieveMethod' :: Eq a => Int -> Int -> [[a]] -> Int
sieveMethod' acc k xs
| k == length xs = acc + factor * subsetCardinality xs
| otherwise = sieveMethod' (acc + factor * s) (k + 1) xs
where factor = if k `mod` 2 == 0 then -1 else 1
comb = combinations k xs
s = sum $ map subsetCardinality comb
sieveMethod :: Eq a => [[a]] -> Int
sieveMethod xs
| null xs = 0
| length xs == 1 = cardinality (head xs)
| otherwise = union + sieveMethod' 0 2 xs
where union = sum $ map cardinality xs
| HenningBrandt/Study | Sieve_Method/sieve.hs | mit | 1,159 | 0 | 13 | 326 | 562 | 287 | 275 | 28 | 2 |
module Palindrome where
import Utils ((|>))
import Control.Monad
import System.Exit (exitSuccess)
import Data.Char
palindrome :: IO ()
palindrome = forever $ do
line1 <- getLine
case (isPalindrome line1) of
True ->
do putStrLn "It's a palindrome"
exitSuccess
False ->
putStrLn "Not a palindrome"
isPalindrome :: String -> Bool
isPalindrome xs =
xs
|> map toLower
|> filter (flip elem ['a'..'z'])
|> (\xs -> xs == reverse xs)
| andrewMacmurray/haskell-book-solutions | src/ch13/palindrome.hs | mit | 480 | 0 | 13 | 122 | 160 | 83 | 77 | 20 | 2 |
{-# LANGUAGE NoMonomorphismRestriction
#-}
module Plugins.Gallery.Gallery.Manual52 where
import Diagrams.Prelude
example = hcat [ square 2
, circle 1 # withEnvelope (square 3 :: D R2)
, square 2
, text "hi" <> phantom (circle 2 :: D R2)
]
| andrey013/pluginstest | Plugins/Gallery/Gallery/Manual52.hs | mit | 311 | 0 | 10 | 111 | 84 | 44 | 40 | 7 | 1 |
{-# LANGUAGE OverloadedLists #-}
module Irg.Lab1.Geometry.Shapes where
import qualified Irg.Lab1.Geometry.Vector as V
import qualified Data.Vector as V2
import Data.Maybe
import Debug.Trace
type Number = Float
myTrace :: Show a => a -> a
myTrace x = if False then traceShowId x else x
polygonFill :: Polygon -> [(Dot, Dot)]
polygonFill p@(Polygon poly)
| polygonOrientation p /= Clockwise = error "The polygon has to be oriented clockwise"
| otherwise = mapMaybe getPolyLineForY ([minimum ys .. maximum ys] :: [Number])
where
edges = myTrace $ polygonEdges p
len = length poly
ys = map ((V2.! 1) . unpackDot) $ V.toList poly
yOfNthVertex n = unpackDot (poly V2.! n) V2.! 1
leftEdges = myTrace $ map fst $ filter (\(_, i) -> yOfNthVertex i < yOfNthVertex ((i+1) `mod` len)) $ zip edges [0..]
rightEdges = filter (`notElem` leftEdges) edges
getXsOfEdgesOnY edgess y = mapMaybe (getXOfIntersection y) edgess
getPolyLineForY y
| null (getXsOfEdgesOnY rightEdges y) || null (getXsOfEdgesOnY leftEdges y) = Nothing
| l < d = Just (Dot [l, y, 1], Dot [d, y, 1])
| otherwise = Nothing
where
l = maximum (myTrace $ getXsOfEdgesOnY leftEdges y)
d = minimum (getXsOfEdgesOnY rightEdges y)
toListWithValid :: Int -> V.Vector Number -> [Number]
toListWithValid n vec
| length vec == n = V.toList vec
| otherwise = error $ "Invalid vector size (" ++ show (length vec) ++ ")"
fromListWithValid :: Int -> [Number] -> V.Vector Number
fromListWithValid n ls
| length ls == n = V.fromList ls
| otherwise = error $ "Invalid list size (" ++ show (length ls) ++ ")"
data Dot = Dot (V.Vector Number) deriving (Eq, Show)
data Line = Line (V.Vector Number) deriving (Eq, Show)
data Polygon = Polygon (V.Vector Dot) deriving (Eq, Show)
data Location = Above | On | Under deriving (Eq, Show)
data InOut = Inside | Outside deriving (Eq, Show)
data Orientation = Clockwise | Counterclockwise | Neither deriving (Eq, Show)
relationDotLine :: Dot -> Line -> Location
relationDotLine dot line
| scalar > 0 = Above
| scalar == 0 = On
| otherwise = Under
where scalar = V.scalarProduct (unpackDot dot) (unpackLine line)
relationDotPolyNthEdge :: Int -> Dot -> Polygon -> Location
relationDotPolyNthEdge n dot poly = relationDotLine dot (polygonEdges poly !! n)
isDotInsidePolygon :: Dot -> Polygon -> Bool
isDotInsidePolygon dot poly = above && (orientation == Counterclockwise) || under && (orientation == Clockwise)
where
under = all ((Above /=) . relationDotLine dot) $ polygonEdges poly
above = all ((Under /=) . relationDotLine dot) $ polygonEdges poly
orientation = polygonOrientation poly
lineFromDots :: Dot -> Dot -> Line
lineFromDots (Dot d1) (Dot d2) = Line $ V.vectorProduct d1 d2
polygonEdges :: Polygon -> [Line]
polygonEdges (Polygon poly) = fmap (\i -> lineFromDots (poly V2.! i) (poly V2.! ((i+1) `mod` len))) lens
where
lens = [0..len-1]
len = length poly
polygonOrientation :: Polygon -> Orientation
polygonOrientation p@(Polygon poly)
| clockwise = Clockwise
| counterclockwise = Counterclockwise
| otherwise = Neither
where
edges = polygonEdges p
len = length poly
lens = [0..len-1] :: [Int]
relationPolyEdgeAndNextVertex i = relationDotLine (poly V2.! ((i + 2) `mod` len)) (edges !! i)
clockwise = all ((Above /=) . relationPolyEdgeAndNextVertex) lens
counterclockwise = all ((Under /=) . relationPolyEdgeAndNextVertex) lens
getXOfIntersection :: Number -> Line -> Maybe Number
getXOfIntersection y (Line edge)
| edge V2.! 0 == 0 = Nothing
| otherwise = Just ((-(edge V2.! 1) * y - (edge V2.! 2)) / (edge V2.! 0))
reversePolygon :: Polygon -> Polygon
reversePolygon = polygonFromLists . reverse . polygonToLists
polygonToClockwise :: Polygon -> Polygon
polygonToClockwise poly
| polygonOrientation poly == Counterclockwise = reversePolygon poly
| polygonOrientation poly == Neither = error "Neither clockwise nor counterclockwise"
| otherwise = poly
unpackDot :: Dot -> V.Vector Number
unpackDot (Dot a) = a
unpackLine :: Line -> V.Vector Number
unpackLine (Line a) = a
unpackPolygon :: Polygon -> V.Vector Dot
unpackPolygon (Polygon a) = a
dotFromList :: [Number] -> Dot
dotFromList = Dot . fromListWithValid 3
dotToList :: Dot -> [Number]
dotToList = toListWithValid 3 . unpackDot
lineFromList :: [Number] -> Line
lineFromList = Line . fromListWithValid 3
lineToList :: Line -> [Number]
lineToList = toListWithValid 3 . unpackLine
polygonFromLists :: [[Number]] -> Polygon
polygonFromLists = Polygon . V.fromList . map dotFromList
polygonToLists :: Polygon -> [[Number]]
polygonToLists = map (V.toList . unpackDot) . V.toList . unpackPolygon
| DominikDitoIvosevic/Uni | IRG/src/Irg/Lab1/Geometry/Shapes.hs | mit | 4,980 | 0 | 17 | 1,164 | 1,804 | 939 | 865 | 99 | 2 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Widgets.LoadingSplash
( loadingSplash, loadingSplashD
) where
import qualified Reflex.Dom as Dom
import Control.Lens ((.~), (&))
import Commons
import Widgets.Generation
-- | When the incoming event is Busy, it shows the loading splash.
-- It hides as soon as Idle event is coming.
--
-- Note, loadingSplash is a special widget.
-- We need it load as soon as possible to show it during page loading.
-- Therefore, I added its html code dirctly to qua-view.html, so it starts spinning even before
-- the javascript code is loaded.
-- Also note, that our static css is placed in a separate file (not in place of generated JS code),
-- so we can safely write required css code below in a splice.
loadingSplashD :: Reflex t => Event t (IsBusy "program") -> QuaWidget t x ()
loadingSplashD isBusyE = do
let cfg = def & Dom.modifyAttributes .~ fmap setClass isBusyE
void $ getElementById cfg "qua-view-loading-div"
where
setClass Busy = "class" =: Just "qua-view-loading-busy"
setClass Idle = "class" =: Just "qua-view-loading-idle"
-- | Show the loading splash, no events processed.
loadingSplash :: Reflex t => QuaWidget t x ()
loadingSplash = void $ getElementById def "qua-view-loading-div"
-- | This function is fully evaluated at compile time.
-- It generates css code for existing Dom elements
$(do
-- create unique css identifiers
rotRed <- newVar
rotGrey <- newVar
-- generate a chunk of css in qua-view.css
qcss
[cassius|
#qua-view-loading-div
z-index: 775
height: 0
width: 0
top: 0
left: 0
padding: 0
margin: 0
.qua-view-loading-idle
display: none
.qua-view-loading-busy
display: block
#qua-view-loading-splash
z-index: 777
position: fixed
height: 40%
padding: 0
top: 50%
left: 50%
margin: 0 -50% 0 0
transform: translate(-50%, -50%)
#qua-view-loading-background
z-index: 776
position: fixed
height: 100%
width: 100%
padding: 0
margin: 0
top: 0
left: 0
background-color: rgba(255,255,255,0.8)
#qua-view-loading-splash-red-circle
position: relative
transform-origin: 36px 36px
-ms-transform-origin: 36px 36px
-moz-transform-origin: 36px 36px
-webkit-transform-origin: 36px 36px
-webkit-animation: #{rotRed} 3s linear infinite
-moz-animation: #{rotRed} 3s linear infinite
-ms-animation: #{rotRed} 3s linear infinite
-o-animation: #{rotRed} 3s linear infinite
animation: #{rotRed} 3s linear infinite
#qua-view-loading-splash-grey-circle
position: relative
transform-origin: 36px 36px
-ms-transform-origin: 36px 36px
-moz-transform-origin: 36px 36px
-webkit-transform-origin: 36px 36px
-webkit-animation: #{rotGrey} 8s linear infinite
-moz-animation: #{rotGrey} 8s linear infinite
-ms-animation: #{rotGrey} 8s linear infinite
-o-animation: #{rotGrey} 8s linear infinite
animation: #{rotGrey} 8s linear infinite
@-webkit-keyframes #{rotRed}
from
-ms-transform: rotate(0deg)
-moz-transform: rotate(0deg)
-webkit-transform: rotate(0deg)
-o-transform: rotate(0deg)
transform: rotate(0deg)
to
-ms-transform: rotate(360deg)
-moz-transform: rotate(360deg)
-webkit-transform: rotate(360deg)
-o-transform: rotate(360deg)
transform: rotate(360deg)
@keyframes #{rotRed}
from
-ms-transform: rotate(0deg)
-moz-transform: rotate(0deg)
-webkit-transform: rotate(0deg)
-o-transform: rotate(0deg)
transform: rotate(0deg)
to
-ms-transform: rotate(360deg)
-moz-transform: rotate(360deg)
-webkit-transform: rotate(360deg)
-o-transform: rotate(360deg)
transform: rotate(360deg)
@-webkit-keyframes #{rotGrey}
from
-ms-transform: rotate(360deg)
-moz-transform: rotate(360deg)
-webkit-transform: rotate(360deg)
-o-transform: rotate(360deg)
transform: rotate(360deg)
to
-ms-transform: rotate(0deg)
-moz-transform: rotate(0deg)
-webkit-transform: rotate(0deg)
-o-transform: rotate(0deg)
transform: rotate(0deg)
@keyframes #{rotGrey}
from
-ms-transform: rotate(360deg)
-moz-transform: rotate(360deg)
-webkit-transform: rotate(360deg)
-o-transform: rotate(360deg)
transform: rotate(360deg)
to
-ms-transform: rotate(0deg)
-moz-transform: rotate(0deg)
-webkit-transform: rotate(0deg)
-o-transform: rotate(0deg)
transform: rotate(0deg)
|]
return []
)
| achirkin/qua-view | src/Widgets/LoadingSplash.hs | mit | 5,130 | 0 | 12 | 1,470 | 251 | 137 | 114 | 24 | 2 |
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad.Trans.Resource
import Data.Conduit (($$))
import Data.Conduit.List (sinkNull)
import Data.Map (Map, empty, insert)
import Data.Text (Text, unpack)
import Text.XML.Stream.Parse
import Text.XML (Name, nameLocalName)
data Person = Person Int Text
deriving Show
parsePerson map = tagName "person" (requireAttr "age") (\age -> do
name <- content
return $ Person (read (unpack age)) name)
parsePeople = parsePeople' empty
parsePeople' map = tagNoAttr "people" (many (parsePerson map))
main = do
people <- runResourceT (parseFile def "Person.xml" $$ force "people required" parsePeople)
print people
| kberger/xml-streaming | Xml.hs | mit | 674 | 0 | 15 | 108 | 226 | 122 | 104 | 18 | 1 |
module AuthBench (benchAuth, authEnv) where
import Criterion.Main
import Control.Monad
import Control.DeepSeq
import Control.Exception
import Data.ByteString as BS
import Crypto.Saltine.Core.Auth
import BenchUtils
authEnv :: IO Key
authEnv = newKey
benchAuth :: Key -> Benchmark
benchAuth k = do
let authVerify :: ByteString -> Bool
authVerify message = do
let authenticator = auth k message
verify k authenticator message
bgroup "Auth"
[ bench "newKey" $ nfIO newKey
, bgroup "auth"
[ bench "128 B" $ nf (auth k) bs128
, bench "1 MB" $ nf (auth k) mb1
, bench "5 MB" $ nf (auth k) mb5
]
, bgroup "auth+verify"
[ bench "128 B" $ nf authVerify bs128
, bench "1 MB" $ nf authVerify mb1
, bench "5 MB" $ nf authVerify mb5
]
]
| tel/saltine | bench/AuthBench.hs | mit | 825 | 0 | 15 | 227 | 269 | 136 | 133 | 26 | 1 |
import System.Environment (getArgs)
import Data.List
import Data.List.Split
import Control.Monad
import System.Console.ANSI
import Juicer.Freeze
import Juicer.Puree
main :: IO()
main = do
args <- getArgs
case args of
(archivename:[]) -> do
maybeArchive <- thaw archivename
case maybeArchive of
Nothing -> return ()
Just archive -> pour archive
otherwise -> putStrLn "pour [archive]"
pour :: Feed -> IO ()
pour (Feed (Channel title desc) posts) = do
channelTitleStyle
putStrLn title
channelDescStyle
putStrLn desc
textStyle
putStrLn "---------------------------------------------------"
mapM_ showPost posts
textStyle
showPost :: Metapost -> IO()
showPost (Metapost _ (Post title desc)) = do
titleStyle
putStrLn title
textStyle
showContent desc
putStrLn ""
showContent :: Content -> IO()
showContent (Content elements) = do
mapM_ showElement elements
putStrLn ""
showElement :: Element -> IO()
showElement (Text s) = do
textStyle
putStr s
showElement (Link title maybeHref) = do
linkStyle
putStr title
showElement (Image link maybeHeight maybeWidth) = do
imageStyle
putStr link
channelTitleStyle :: IO()
channelTitleStyle = setSGR [SetConsoleIntensity BoldIntensity, SetColor Foreground Dull Green]
channelDescStyle :: IO()
channelDescStyle = setSGR [SetConsoleIntensity BoldIntensity, SetColor Foreground Dull Magenta]
titleStyle :: IO()
titleStyle = setSGR [SetConsoleIntensity BoldIntensity, SetColor Foreground Vivid Blue]
textStyle :: IO()
textStyle = setSGR [SetConsoleIntensity NormalIntensity, SetColor Foreground Dull White]
linkStyle :: IO()
linkStyle = setSGR [SetConsoleIntensity NormalIntensity, SetColor Foreground Dull Red]
imageStyle :: IO()
imageStyle = setSGR [SetConsoleIntensity NormalIntensity, SetColor Foreground Dull Blue]
| blanu/juicer | pour.hs | gpl-2.0 | 1,903 | 0 | 16 | 375 | 609 | 289 | 320 | 60 | 3 |
module Game where
import DIYGraph
import Parse
import Dictionary
import Graph
import Places
import Player
import Text.ParserCombinators.Parsec.Error
-- TODO -- change mapGraph to places, game to gameState
data Game = Game { player :: Player,
mapGraph :: Graph Place String,
dictionary :: Dictionary } deriving (Eq, Show)
-- | Turns a game file into either an error message from the parser or a game.
initGame :: String -> Either String Game
initGame file =
let p = parsePlaces file
d = parseDictionary file in
parseGame p d
-- TODO: is this the best way to "add" these Eithers?
-- | Attemps to parse the game file into a Game. If both the list of Places
-- and the Dictionary parse, then make the game. If the Places were fine, but
-- the dictionary wasn't, show the error for the dictionary. Otherwise, show
-- the error for the dictionary. (Unfortunately, I'm not sure this works
-- because I couldn't figure out how to test.)
parseGame :: Either ParseError [Place] -> Either ParseError Dictionary ->
Either String Game
parseGame (Right p) (Right d) = Right $ makeGame p d
parseGame (Right _) (Left d) = Left $ show d
parseGame (Left p) _ = Left $ show p
-- | Makes a game by creating a graph from the places and combining the
-- Dictionary and graph into a Game.
makeGame :: [Place] -> Dictionary -> Game
makeGame p d = let graph = createGraph p in
Game (makePlayer graph) graph d
| emhoracek/explora | library/Game.hs | gpl-2.0 | 1,495 | 0 | 9 | 361 | 298 | 159 | 139 | 24 | 1 |
module Main where
import Lexical
import Scanner
import Parser
import Weeder
import AST
import System.Directory
--------------------------------------------------------------------
testVFiles :: IO [(String, String)]
testVFiles = do
f <- getDirectoryContents "assignment_testcases/a1"
let files = ["assignment_testcases/a1/" ++ file | file <- f, file /= ".", file /= "..", take 2 file /= "Je", take 1 file /= "."]
contents <- mapM readFile files
return (zip contents files)
testEFiles :: IO [(String, String)]
testEFiles = do
f <- getDirectoryContents "assignment_testcases/a1"
let files = ["assignment_testcases/a1/" ++ file | file <- f, file /= ".", file /= "..", take 2 file == "Je"]
contents <- mapM readFile files
return (zip contents files)
testValidFiles :: IO ()
testValidFiles = do
dfa <- readLR1
files <- testVFiles
tokenByFiles <- mapM (scannerRunner 0 0) files
let tokenByFilesFiltered = zip (map (filter (\(tk, fn) -> not (elem (tokenType tk) [Comment, WhiteSpace]))) tokenByFiles) (map snd files)
let tokenByFilesStillValid = filter (not . any (\token -> (tokenType $ fst token) == FAILURE) . fst) tokenByFilesFiltered
let astByFiles = map (\(tokens, file) -> (map tokenToAST tokens, file)) tokenByFilesStillValid
let resultByFiles = map (\(ast, file) -> (run (dfa, ast ++ [AST "EOF" []]), file)) astByFiles
let validParsed = filter (\x -> (length . snd $ fst x)==0) resultByFiles
let fileAsts = map (\x -> ((buildAST . units . fst $ fst x), snd x)) validParsed
let unweeded = filter (\x -> (weed (snd x) (fst x)) == Nothing) fileAsts
let weeded = filter (\x -> (weed (snd x) (fst x)) /= Nothing) fileAsts
putStrLn $ ("Valid Tests Weeded: " ++ (show $ length weeded) ++ "/" ++ (show $ length fileAsts))
putStrLn $ foldl (\acc x -> acc ++ x ++ "\n") "" (map snd weeded)
testInvalidFiles :: IO ()
testInvalidFiles = do
dfa <- readLR1
files <- testEFiles
tokenByFiles <- mapM (scannerRunner 0 0) files
let tokenByFilesFiltered = zip (map (filter (\(tk, fn) -> not (elem (tokenType tk) [Comment, WhiteSpace]))) tokenByFiles) (map snd files)
let tokenByFilesStillValid = filter (not . any (\token -> (tokenType $ fst token) == FAILURE) . fst) tokenByFilesFiltered
let astByFiles = map (\(tokens, file) -> (map tokenToAST tokens, file)) tokenByFilesStillValid
let resultByFiles = map (\(ast, file) -> (run (dfa, ast ++ [AST "EOF" []]), file)) astByFiles
let validParsed = filter (\x -> (length . snd $ fst x)==0) resultByFiles
let fileAsts = map (\x -> ((buildAST . units . fst $ fst x), snd x)) validParsed
let unweeded = filter (\x -> (weed (snd x) (fst x)) == Nothing) fileAsts
let weeded = filter (\x -> (weed (snd x) (fst x)) /= Nothing) fileAsts
putStrLn $ ("Invalid Tests Weeded: " ++ (show $ length weeded) ++ "/" ++ (show $ length fileAsts))
putStrLn $ foldl (\acc x -> acc ++ x ++ "\n") "" (map snd unweeded)
main :: IO ()
main = do
testValidFiles
testInvalidFiles
| yangsiwei880813/CS644 | src/WMain.hs | gpl-2.0 | 3,044 | 0 | 21 | 628 | 1,343 | 681 | 662 | 53 | 1 |
module Main where
import TheNotes
main :: IO ()
main = theNotes
| NorfairKing/the-notes | app/Main.hs | gpl-2.0 | 76 | 0 | 6 | 24 | 22 | 13 | 9 | 4 | 1 |
module Blockchain.Structures where
import qualified Data.Digest.Pure.SHA as SHA
import qualified Data.ByteString.Lazy as B
import qualified Data.Binary.Get as BI
import qualified Data.Map as Map
-- Account-based proof-of-stake cryptocurrency model
type Timestamp = Int
first8bytesAsNumber :: B.ByteString -> Integer
first8bytesAsNumber bs = fromIntegral $ BI.runGet BI.getWord64le first8 where first8 = B.take 8 bs
data Account =
Account {
publicKey :: B.ByteString
}
instance Show Account where show acc = show $ accountId acc
instance Eq Account where a1 == a2 = accountId a1 == accountId a2
instance Ord Account where compare a b = compare (accountId a) (accountId b)
accountId :: Account -> Int
accountId acc = fromIntegral $ first8bytesAsNumber $ publicKey acc
data Transaction =
Transaction {
sender :: Account,
recipient :: Account,
amount :: Int,
fee :: Int,
txTimestamp :: Timestamp
} deriving (Show)
instance Eq Transaction where t1 == t2 = accountId (sender t1) == accountId (sender t2)
&& accountId (recipient t1) == accountId (recipient t2)
&& txTimestamp t1 == txTimestamp t2
validate :: Transaction -> Bool
validate _ = True
minFee :: Int
minFee = 1
data Block =
Block {
transactions :: [Transaction],
baseTarget :: Integer,
generator :: Account,
generationSignature :: B.ByteString,
blockTimestamp :: Timestamp
} deriving (Show)
initialBaseTarget :: Integer
initialBaseTarget = 153722867
maxBaseTarget :: Integer
maxBaseTarget = initialBaseTarget * (fromIntegral systemBalance)
containsTx :: Transaction -> Block -> Bool
containsTx tx block = elem tx $ transactions block
calcGenerationSignature :: Block -> Account -> B.ByteString
calcGenerationSignature prevBlock acct = SHA.bytestringDigest $ SHA.sha256 $ B.append (generationSignature prevBlock) pk
where pk = publicKey acct
formBlock :: Block -> Account -> Timestamp -> [Transaction] -> Block
formBlock prevBlock gen timestamp txs =
Block{transactions = filter validate txs, blockTimestamp = timestamp, baseTarget = bt, generator = gen, generationSignature = gs}
where prevTarget = baseTarget prevBlock
maxTarget = min (2*prevTarget) maxBaseTarget
minTarget = max (prevTarget `div` 2) 1
candidate = prevTarget*(toInteger (timestamp - (blockTimestamp prevBlock))) `div` 60
bt = min (max minTarget candidate) maxTarget
gs = calcGenerationSignature prevBlock gen -- is gs 64 bytes?
blockId :: Block -> Int
blockId block = (blockTimestamp block) + (fromIntegral $ first8bytesAsNumber $ generationSignature block)
type BlockChain = [Block]
two64 :: Double
two64 = 18446744073709551616.0
cumulativeDifficulty :: BlockChain -> Double
cumulativeDifficulty chain = sum(map (\bl -> two64 / (fromIntegral $ baseTarget bl) ) chain)
type BlockTree = [BlockChain]
data LocalView =
LocalView{
nodeChain :: BlockChain, -- simplification - one blockchain per node(but true for NRS)
balances :: Map.Map Account Int
} deriving (Show)
accountBalance :: LocalView -> Account -> Int
accountBalance view acc = Map.findWithDefault 0 acc (balances view)
effectiveBalance :: LocalView -> Account -> Int
effectiveBalance view acc = accountBalance view acc -- todo: simplification, no 1440 blocks waiting for now
addMoney :: Int -> Account -> Map.Map Account Int -> Map.Map Account Int
addMoney diff acc blns = Map.insert acc ((Map.findWithDefault 0 acc blns) + diff) blns
applyTx :: Transaction -> Map.Map Account Int -> Map.Map Account Int
applyTx tx blns = addMoney amt (recipient tx) $ addMoney (-amt - (fee tx)) (sender tx) blns
where
amt = amount tx
processBlock :: Block -> Map.Map Account Int -> Map.Map Account Int
processBlock block priorBalances = appliedWithFees
where
txs = transactions block
txApplied = foldl (\bs tx -> applyTx tx bs) priorBalances txs
fees = sum(map fee txs)
appliedWithFees = addMoney fees (generator block) txApplied
pushBlock :: Block -> Node -> Node
pushBlock bl node = node{localView = updView, unconfirmedTxs = updTxs}
where
view = localView node
txs = unconfirmedTxs node
updTxs = foldl (\ts tx -> if containsTx tx bl then ts else ts++[tx]) [] txs
updView = view{nodeChain = nodeChain view ++ [bl], balances = processBlock bl $ balances view}
pushBlocks :: [Block] -> Node -> Node
pushBlocks bls node = foldl (\n bl -> pushBlock bl n) node bls
data Node =
Node {
localView :: LocalView,
unconfirmedTxs :: [Transaction],
account :: Account -- simplification - one account per node
--isForging :: Bool - simplification - always on for now
} deriving (Show)
instance Eq Node where n1 == n2 = nodeId n1 == nodeId n2
instance Ord Node where compare a b = compare (nodeId a) (nodeId b)
lastNodeBlock :: Node -> Block
lastNodeBlock nd = last $ nodeChain $ localView nd
nodeChainLength :: Node -> Int
nodeChainLength nd = length $ nodeChain $ localView nd
processIncomingBlock :: Block -> Node -> Node
processIncomingBlock block node = updNode
where
lastBlock = lastNodeBlock node
sigHash = first8bytesAsNumber $ calcGenerationSignature lastBlock (generator block)
updNode = case first8bytesAsNumber (generationSignature block) == sigHash of
True -> pushBlock block node
False -> node
nodeId :: Node -> Int
nodeId node = fromIntegral $ first8bytesAsNumber $ publicKey $ account node
selfBalance :: Node -> Int
selfBalance node = accountBalance (localView node) (account node)
calculateHit :: Block -> Account -> Integer
calculateHit prevBlock acc = fromIntegral $ first8bytesAsNumber $ calcGenerationSignature prevBlock acc
-- hitTime :: Account -> Block -> LocalView -> Timestamp
-- hitTime acct prevBl view = (blockTimestamp prevBl) + (calculateHit prevBl acct)*(effectiveBalance view acct) `div` (baseTarget prevBl)
verifyHit :: Integer -> Block -> Timestamp -> Int -> Bool
verifyHit hit prevBlock timestamp effBalance = (eta > 0) && hit < target -- && hit >= prevTarget) - after block 215000
where eta = timestamp - blockTimestamp prevBlock
effbt = (toInteger effBalance)*(baseTarget prevBlock)
target = effbt*(toInteger eta)
-- prevTarget = effbt * (eta-1)
forge :: Node -> Timestamp -> Maybe Node
forge node ts = case checkhit of
True -> Just $ pushBlock generatedBlock node
False -> Nothing
where
view = localView node
acct = account node
lastbl = last $ nodeChain view
hit = calculateHit lastbl acct
effBalance = effectiveBalance view acct
checkhit = verifyHit hit lastbl ts effBalance
generatedBlock = formBlock lastbl acct ts (unconfirmedTxs node)
maxBlocksFromPeer :: Int
maxBlocksFromPeer = 10*1440
commonChain :: BlockChain -> BlockChain -> BlockChain -> BlockChain
commonChain chain1 chain2 common = case (chain1, chain2) of
(bl1:ct1, bl2:ct2) -> if blockId bl1 == blockId bl2 then commonChain ct1 ct2 (common ++ [bl1]) else common
_ -> common
-- Nodes are modifiyng !!! so map works wrong, changed [Node] to [Int]
data Network =
Network {
nodes :: [Node],
connections :: Map.Map Node [Int] -- todo add latency(avg latency time), trust?
} deriving (Show)
systemBalance :: Int
systemBalance = 1000000000
outgoingConnections :: Network -> Node -> [Node]
outgoingConnections network node = let ids = Map.findWithDefault [] node (connections network) in
filter (\n -> elem (nodeId n) ids) (nodes network)
outgoingConnectionsIds :: Network -> Node -> [Int]
outgoingConnectionsIds network node = Map.findWithDefault [] node (connections network)
updateNode :: Node -> Network -> Network
updateNode nd network = network{nodes = ns}
where
ndId = nodeId nd
ns = map (\n -> if (nodeId n == ndId) then nd else n) (nodes network)
blockTree :: Network -> BlockTree
blockTree sys = error "not impl"
-- todo: define canonical blockchain and implement it's extraction from blocktree of a system
canonicalBlockchain :: Network -> Maybe BlockChain
canonicalBlockchain sys = Nothing | ConsensusResearch/ForgingSimulation | blockchain.hs | gpl-2.0 | 8,422 | 0 | 14 | 1,923 | 2,426 | 1,282 | 1,144 | 160 | 3 |
-- 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without
-- any remainder.
-- What is the smallest positive number that is evenly divisible by all of the numbers from 1
-- to 20?
-- lcm is what we need for this
listLCM xs = foldr (lcm) 2 xs
ans = listLCM [3..20]
| ciderpunx/project_euler_in_haskell | euler005.hs | gpl-2.0 | 308 | 0 | 6 | 70 | 37 | 21 | 16 | 2 | 1 |
module QFeldspar.CSE where
import QFeldspar.Expression.GADTFirstOrder
import QFeldspar.Expression.Utils.Equality.GADTFirstOrder
import QFeldspar.Expression.Utils.GADTFirstOrder(prdAllM,sucAll,isVal)
import QFeldspar.MyPrelude hiding (foldl,fmap)
import qualified QFeldspar.Type.GADT as TG
import QFeldspar.ChangeMonad
import QFeldspar.Singleton
import QFeldspar.Variable.Typed
import QFeldspar.Environment.Typed
import QFeldspar.Magic
-- type family Env a :: [*]
-- type instance Env (Exp s g a) = g
cse :: TG.Type a => Exp s g a -> Exp s g a
cse = tilNotChg cseOne
cseOne :: forall s g a. TG.Type a => Exp s g a -> Chg (Exp s g a)
cseOne ee = case ee of
Lit i -> pure (Lit i)
ConB b -> pure (ConB b)
Prm x es -> cseOneEnv x Emp es
Var x -> pure (Var x)
Abs eb -> Abs <$> cseOne eb
App ef ea -> cseOne2 App ef ea
Cnd ec et ef -> cseOne3 Cnd ec et ef
Whl ec eb ei -> cseOne3 Whl ec eb ei
Tpl ef es -> cseOne2 Tpl ef es
Fst e -> Fst <$> cseOne e
Snd e -> Snd <$> cseOne e
Ary el ef -> cseOne2 Ary el ef
Len e -> Len <$> cseOne e
Ind ea ei -> cseOne2 Ind ea ei
LeT el eb -> cseOne2F LeT el eb
Cmx er ei -> cseOne2 Cmx er ei
Tag x e -> Tag x <$> cseOne e
Mul er ei -> cseOne2 Mul er ei
Add er ei -> cseOne2 Add er ei
Sub er ei -> cseOne2 Sub er ei
Eql er ei -> cseOne2 Eql er ei
Ltd er ei -> cseOne2 Ltd er ei
Non -> pure Non
Som eb -> Som <$> cseOne eb
May l m n -> cseOne3 May l m n
AryV m n -> cseOne2 AryV m n
LenV n -> LenV <$> cseOne n
IndV m n -> cseOne2 IndV m n
Int i -> pure (Int i)
Rat i -> pure (Rat i)
Mem m -> Mem <$> cseOne m
Fix m -> Fix <$> cseOne m
remTag :: forall s g a. Exp s g a -> Exp s g a
remTag ee = case ee of
Tag _ e -> remTag e
_ -> $(genOverloaded 'ee ''Exp ['Tag]
(\ tt -> if
| matchQ tt [t| Exp a a a |] -> [| remTag |]
| matchQ tt [t| Env (Exp a a) a |] -> [| fmap remTag |]
| otherwise -> [| id |]))
remTheTag :: forall s g a. String -> Exp s g a -> Exp s g a
remTheTag x ee = case ee of
Tag y e
| x == y -> e
| otherwise -> Tag y (remTheTag x e)
_ -> $(genOverloaded 'ee ''Exp ['Tag]
(\ tt -> if
| matchQ tt [t| Exp a a a |] -> [| remTheTag x |]
| matchQ tt [t| Env (Exp a a) a |] -> [| fmap (remTheTag x) |]
| otherwise -> [| id |]))
hasSubtermEnv :: (TG.Type b , TG.Types d) => Exp s g b -> Env (Exp s g) d -> Bool
hasSubtermEnv ex = TG.fld (\ b e -> b || hasSubterm ex e) False
cseOneEnv :: forall s g a d d' as c.
(Match c as a , TG.Type a , TG.Types d , TG.Types d' , as ~ Add d d') =>
Var s c -> Env (Exp s g) d -> Env (Exp s g) d' ->
Chg (Exp s g a)
cseOneEnv x d d' = do
let tsd = sin :: Env TG.Typ d
let tsd' = sin :: Env TG.Typ d'
PrfHasSin <- getPrfHasSinM (add tsd tsd')
case d' of
Emp -> Prm x <$> TG.mapMC cseOne (add d d')
Ext (e :: Exp s g te) (es :: Env (Exp s g) tes) -> case TG.getPrfHasSinEnvOf d' of
(PrfHasSin,PrfHasSin) -> case obvious :: Add (Add d (te ': '[])) tes :~: Add d (te ': tes) of
Rfl -> let f tss = case tss of
[] -> do PrfHasSin <- getPrfHasSinM (add tsd (Ext (sinTyp e) Emp))
cseOneEnv x (add d (Ext e Emp)) es
(Exs1 ex tx : ts) -> case getPrfHasSin tx of
PrfHasSin -> if hasSubtermEnv ex es
then chg (LeT ex (Prm x (TG.mapC (\ ee -> absSubterm (Var Zro) (sucAll ex) (sucAll ee))
(add d d'))))
else f ts
in f (findSubterms e)
cseOne3 :: (TG.Type a , TG.Type b , TG.Type c , TG.Type d) =>
(Exp s g a -> Exp s g b -> Exp s g c -> Exp s g d) ->
Exp s g a -> Exp s g b -> Exp s g c -> Chg (Exp s g d)
cseOne3 k l m n = let fm tss = case tss of
[] -> k <$> cseOne l <*> cseOne m <*> cseOne n
(Exs1 ex tx : ts) -> case getPrfHasSin tx of
PrfHasSin -> if hasSubterm ex n
then chg (LeT ex (absSubterm (Var Zro) (sucAll ex) (sucAll (k l m n))))
else fm ts
fl tss = case tss of
[] -> fm (findSubterms m)
(Exs1 ex tx : ts) -> case getPrfHasSin tx of
PrfHasSin -> if hasSubterm ex m || hasSubterm ex n
then chg (LeT ex (absSubterm (Var Zro) (sucAll ex) (sucAll (k l m n))))
else fl ts
in fl (findSubterms l)
cseOne2 :: (TG.Type a, TG.Type b, TG.Type c) =>
(Exp s g a -> Exp s g b -> Exp s g c) ->
Exp s g a -> Exp s g b -> Chg (Exp s g c)
cseOne2 k m n = let f tss = case tss of
[] -> k <$> cseOne m <*> cseOne n
(Exs1 ex tx : ts) -> case getPrfHasSin tx of
PrfHasSin -> if hasSubterm ex n
then chg (LeT ex (absSubterm (Var Zro) (sucAll ex) (sucAll (k m n))))
else f ts
in f (findSubterms m)
cseOne2F :: (TG.Type a, TG.Type b, TG.Type c) =>
(Exp s g a -> Exp s (a ': g) b -> Exp s g c) ->
Exp s g a -> Exp s (a ': g) b -> Chg (Exp s g c)
cseOne2F k m n = let f tss = case tss of
[] -> k <$> cseOne m <*> cseOne n
(Exs1 ex tx : ts) -> case getPrfHasSin tx of
PrfHasSin -> if hasSubterm (sucAll ex) n
then chg (LeT ex (absSubterm (Var Zro) (sucAll ex) (sucAll (k m n))))
else f ts
in f (findSubterms m)
absSubterm :: forall a b s g.
(TG.Type a , TG.Type b) =>
Exp s g b -> Exp s g b -> Exp s g a -> Exp s g a
absSubterm xx ex ee = let t = sin :: TG.Typ a in
case eqlSin (sinTyp ex) t of
Rgt Rfl | eql ex ee -> xx
_ -> case ee of
Prm x es -> Prm x (TG.mapC (absSubterm xx ex) es)
_ -> $(genOverloaded 'ee ''Exp ['Prm]
(\ tt -> if
| matchQ tt [t| Exp a (a ': a) a |] -> [| absSubterm (sucAll xx) (sucAll ex) |]
| matchQ tt [t| Exp a a a |] -> [| absSubterm xx ex |]
| otherwise -> [| id |]))
hasSubterm :: (TG.Type b , TG.Type a) => Exp s g b -> Exp s g a -> Bool
hasSubterm ex ee = numSubterm ex ee /= (0 :: Word32)
numSubterm :: forall s g a b . (TG.Type a , TG.Type b) =>
Exp s g b -> Exp s g a -> Word32
numSubterm ex ee = let t = sin :: TG.Typ a in
(case eqlSin (sinTyp ex) t of
Rgt Rfl -> if eql ex ee
then (1 :: Word32)
else 0
_ -> 0) + (case ee of
Prm _ es -> TG.fld (\ b e -> b + numSubterm ex e) 0 es
_ -> $(recAppMQ 'ee ''Exp (const [| 0 :: Word32 |]) ['Prm]
[| \ _x -> (0 :: Word32) |] [| (+) |] [| (+) |]
(\ tt -> if
| matchQ tt [t| Exp a (a ': a) a |] -> [| numSubterm (sucAll ex) |]
| matchQ tt [t| Exp a a a |] -> [| numSubterm ex |]
| otherwise -> [| const (0 :: Word32) |])))
findSubterms :: forall s g a. TG.Type a =>
Exp s g a -> [Exs1 (Exp s g) TG.Typ]
findSubterms ee = (if not (isVal ee) && not (partialApp ee)
then ((Exs1 ee (sinTyp ee)) :)
else id)(case ee of
Prm _ es -> TG.fld (\ b e -> b ++ findSubterms e) [] es
_ -> $(recAppMQ 'ee ''Exp (const [| [] |]) ['Prm]
[| \ _x -> [] |] [| (++) |] [| (++) |]
(\ tt -> if
| matchQ tt [t| Exp a (a ': a) a |] -> [| findSubtermsF |]
| matchQ tt [t| Exp a a a |] -> [| findSubterms |]
| otherwise -> [| const [] |])))
findSubtermsF :: TG.Type b => Exp s (a ': g) b -> [Exs1 (Exp s g) TG.Typ]
findSubtermsF e = foldr (\ (Exs1 eg t) xxs -> case prdAllM eg of
Nothing -> xxs
Just eg' -> (Exs1 eg' t) : xxs) [] (findSubterms e)
partialApp :: TG.Type a => Exp s g a -> Bool
partialApp (App l _) = case sinTyp l of
TG.Arr _ (TG.Arr _ _) -> True
_ -> False
partialApp _ = False
| shayan-najd/QFeldspar | QFeldspar/CSE.hs | gpl-3.0 | 9,586 | 0 | 38 | 4,479 | 3,817 | 1,920 | 1,897 | -1 | -1 |
-- |
-- Module : Language.Go.Parser.Tokens
-- Copyright : (c) 2011 Andrew Robbins
-- License : GPLv3 (see COPYING)
--
-- This module defines Go tokens and the parser type.
-- It also defines various utility functions for the lexer and parser.
module Language.Go.Parser.Tokens (
-- * Parser
GoParser,
GoParserState(..),
runGoParser,
enterParen,
exitParen,
-- * Tokens and utilities for lexer
GoToken(..),
GoTokenPos(..),
insertSemi,
stripComments,
token,
tokenFromComment,
tokenFromInt,
tokenFromReal,
tokenFromImag,
tokenFromChar,
tokenFromRawStr,
tokenFromString,
unquoteChar,
unquoteString,
-- * Parsers for elementary punctuation
goTokLParen,
goTokRParen,
goTokLBrace,
goTokRBrace,
goTokLBracket,
goTokRBracket,
goTokSemicolon,
goTokColon,
goTokColonEq,
goTokEqual,
goTokComma,
goTokFullStop,
goTokEllipsis,
goTokAsterisk,
goTokArrow,
goAssignOp,
-- * Parsers for keywords
goTokBreak,
goTokCase,
goTokChan,
goTokConst,
goTokContinue,
goTokDefault,
goTokDefer,
goTokElse,
goTokFallthrough,
goTokFor,
goTokFunc,
goTokGo,
goTokGoto,
goTokIf,
goTokImport,
goTokInterface,
goTokMap,
goTokPackage,
goTokRange,
goTokReturn,
goTokSelect,
goTokStruct,
goTokSwitch,
goTokType,
goTokVar,
) where
import Numeric (readDec, readHex, readOct, readFloat)
import Data.Maybe (mapMaybe)
import Data.Char (chr, isOctDigit)
import Language.Go.Syntax.AST
import Text.Parsec.String
import Text.Parsec.Prim hiding (token)
import qualified Text.Parsec.Prim as Prim
import Text.Parsec.Pos (SourcePos, SourceName)
import Text.Parsec.Error (ParseError)
import Text.Parsec.Combinator
-- | GoParser is the type used for all parsers
type GoParser a = GenParser GoTokenPos GoParserState a
data GoParserState = GoParserState { noComposite :: Bool, parenDepth :: Int }
runGoParser :: GoParser a -> SourceName -> [GoTokenPos] -> Either ParseError a
runGoParser p = runP p $ GoParserState { noComposite = False, parenDepth = 0 }
enterParen :: GoParser ()
enterParen = do
st <- getState
putState $ st { parenDepth = (parenDepth st) + 1 }
exitParen :: GoParser ()
exitParen = do
st <- getState
let newst = st { parenDepth = (parenDepth st) - 1 }
if parenDepth newst < 0 then fail "negative paren depth" else return ()
putState newst
-- | GoTokenPos encodes tokens and source positions
data GoTokenPos = GoTokenPos !SourcePos !GoToken
deriving (Eq, Show)
-- | GoToken encodes tokens
data GoToken = GoTokNone
| GoTokComment Bool String -- False=singleline True=multiline
-- BEGIN literals
| GoTokInt (Maybe String) Integer
| GoTokReal (Maybe String) Float
| GoTokImag (Maybe String) Float
| GoTokChar (Maybe String) Char
| GoTokStr (Maybe String) String
-- END literals
-- BEGIN wraps
| GoTokLParen -- '('
| GoTokRParen -- ')'
| GoTokLBrace -- '{'
| GoTokRBrace -- '}'
| GoTokLBracket -- '['
| GoTokRBracket -- ']'
-- END wraps
-- BEGIN keywords
| GoTokBreak
| GoTokCase
| GoTokChan
| GoTokConst
| GoTokContinue
| GoTokDefault
| GoTokDefer
| GoTokElse
| GoTokFallthrough
| GoTokFor
| GoTokFunc
| GoTokGo
| GoTokGoto
| GoTokIf
| GoTokImport
| GoTokInterface
| GoTokMap
| GoTokPackage
| GoTokRange
| GoTokReturn
| GoTokSelect
| GoTokStruct
| GoTokSwitch
| GoTokType
| GoTokVar
-- END keywords
| GoTokSemicolonAuto
| GoTokSemicolon -- ';'
| GoTokColon -- ':'
| GoTokColonEq -- ':='
| GoTokEqual -- '='
| GoTokComma -- ','
| GoTokFullStop -- '.'
| GoTokEllipsis -- '...'
-- BEGIN operators
| GoTokLOR -- '||'
| GoTokLAND -- '&&'
| GoTokEQ -- '=='
| GoTokNE -- '!='
| GoTokLT -- '<'
| GoTokLE -- '<='
| GoTokGT -- '>'
| GoTokGE -- '>='
| GoTokPlus -- '+'
| GoTokMinus -- '-'
| GoTokIOR -- '|'
| GoTokXOR -- '^'
| GoTokAsterisk -- '*'
| GoTokSolidus -- '/'
| GoTokPercent -- '%'
| GoTokSHL -- '<<'
| GoTokSHR -- '>>'
| GoTokAND -- '&'
| GoTokBUT -- '&^'
| GoTokExclaim -- '!'
| GoTokArrow -- '<-'
| GoTokDec -- '--'
| GoTokInc -- '++'
-- END operators
-- BEGIN names
| GoTokId String
| GoTokOp String -- future extensions
-- END names
| GoTokInvalid String
deriving (Eq, Read, Show)
-- Data, Typeable
-- False=singleline True=multiline
tokenFromComment :: Bool -> String -> GoToken
tokenFromComment False s = GoTokComment False $ drop 2 $ init s -- strip // and \n
tokenFromComment True s = GoTokComment True $ drop 2 $ init $ init s -- strip /* and */
tokenFromInt :: String -> GoToken
tokenFromInt s = tok where
num = case s of
'0':'x':h -> readHex h
'0':'X':h -> readHex h
'0':_ -> readOct s
_ -> readDec s
tok = case num of
(x, ""):_ -> GoTokInt (Just s) x
_ -> GoTokInvalid s
parseFloat s = readFloat (before ++ after)
where (bef, af) = break (== '.') s
before = if (bef == "") && not (null af) then '0':bef else bef
after = case af of
"." -> ".0"
'.':'e':s -> ".0e" ++ s
'.':'E':s -> ".0E" ++ s
_ -> af
tokenFromReal :: String -> GoToken
tokenFromReal s = case parseFloat s of
(x, ""):_ -> GoTokReal (Just s) x
_ -> GoTokInvalid s
tokenFromImag :: String -> GoToken
tokenFromImag s = case parseFloat (init s) of
(x, ""):_ -> GoTokImag (Just s) x
_ -> GoTokInvalid s
tokenFromRawStr :: String -> GoToken
tokenFromRawStr s = GoTokStr (Just s) (init $ tail s)
tokenFromString :: String -> GoToken
tokenFromString s = case unquoteString $ init $ tail s of
Just q -> GoTokStr (Just s) q
Nothing -> GoTokInvalid s
-- | @tokenFromChar c@ unquotes the Go representation of a single
-- character literal, including the single quotes.
tokenFromChar :: String -> GoToken
tokenFromChar s =
case c of
Just c -> GoTokChar (Just s) c
Nothing -> GoTokInvalid s
where c = unquoteChar $ init $ tail s
unquoteChar :: String -> Maybe Char
unquoteChar ['\\', c] = case c of
'a' -> Just '\a'
'b' -> Just '\b'
'f' -> Just '\f'
'n' -> Just '\n'
'r' -> Just '\r'
't' -> Just '\t'
'v' -> Just '\v'
'\'' -> Just '\''
'\"' -> Just '\"'
'\\' -> Just '\\'
_ -> Nothing
unquoteChar s = case s of
['\\','x', a, b] -> hex [a, b]
['\\', 'u', a, b, c, d] -> hex [a,b,c,d]
['\\', 'U', a, b, c, d, e, f, g, h] -> hex [a,b,c,d,e,f,g,h]
['\\', a, b, c] -> oct [a, b, c]
[c] -> Just c
_ -> Nothing
where hex s = case readHex s of
((n, _):_) -> Just $ chr n
_ -> Nothing
oct s = case readOct s of
((n, _):_) -> Just $ chr n
_ -> Nothing
unquoteString :: String -> Maybe String
unquoteString s = fmap reverse v
where (_, v) = unquote s (Just "")
unquote :: String -> Maybe String -> (String, Maybe String)
unquote "" accum = ("", accum)
unquote s Nothing = (s, Nothing)
unquote s (Just accum) = case c of Just c -> unquote s' $ Just (c:accum); Nothing -> (s, Nothing)
where (c, s') = case s of
('\\':'x':_) -> (unquoteChar $ take 4 s, drop 4 s)
('\\':'u':_) -> (unquoteChar $ take 6 s, drop 6 s)
('\\':'U':_) -> (unquoteChar $ take 10 s, drop 10 s)
('\\':c2:_) -> (unquoteChar $ take n s, drop n s) where n = if isOctDigit c2 then 4 else 2
(c:ss) -> (Just c, ss)
tokenEq :: GoToken -> GoToken -> Bool
tokenEq (GoTokComment _ _) (GoTokComment _ _) = True
tokenEq (GoTokInt _ _) (GoTokInt _ _) = True
tokenEq (GoTokReal _ _) (GoTokReal _ _) = True
tokenEq (GoTokImag _ _) (GoTokImag _ _) = True
tokenEq (GoTokStr _ _) (GoTokStr _ _) = True
tokenEq (GoTokId _) (GoTokId _) = True
tokenEq (GoTokOp _) (GoTokOp _) = True
tokenEq a b = a == b
token :: GoToken -> GoParser GoToken
token tok = Prim.token showTok posnTok testTok
where showTok (GoTokenPos _ t) = show t
posnTok (GoTokenPos pos _) = pos
testTok (GoTokenPos _ t) = if tokenEq tok t
then Just t
else Nothing
stripComments :: [GoTokenPos] -> [GoTokenPos]
stripComments tokens = mapMaybe nocomm tokens where
nocomm tok = case tok of
-- single line comment: restore newline
GoTokenPos pos (GoTokComment False _) -> Just $ GoTokenPos pos GoTokSemicolonAuto
GoTokenPos _ (GoTokComment True _) -> Nothing
_ -> Just tok
stripNone :: [GoTokenPos] -> [GoTokenPos]
stripNone tokens = filter nonull tokens where
nonull (GoTokenPos _ x) = (x /= GoTokNone)
stripAuto :: [GoTokenPos] -> [GoTokenPos]
stripAuto tokens = filter nonull tokens where
nonull (GoTokenPos _ x) = (x /= GoTokSemicolonAuto)
needSemi :: GoToken -> Bool
needSemi token = case token of
GoTokId _ -> True
GoTokInt _ _ -> True
GoTokReal _ _ -> True
GoTokImag _ _ -> True
GoTokChar _ _ -> True
GoTokStr _ _ -> True
GoTokBreak -> True
GoTokContinue -> True
GoTokFallthrough -> True
GoTokReturn -> True
GoTokDec -> True
GoTokInc -> True
GoTokRParen -> True
GoTokRBrace -> True
GoTokRBracket -> True
_ -> False
appendSemi :: [GoTokenPos] -> [GoTokenPos]
appendSemi tokens = tokens ++ semi where
semi = [GoTokenPos (lastpos $ last tokens) GoTokSemicolonAuto]
lastpos (GoTokenPos pos _) = pos
-- | @insertSemi@ performs semicolon insertion.
insertSemi :: [GoTokenPos] -> [GoTokenPos]
insertSemi = stripAuto . stripNone .
insertAfter . stripNone . appendSemi
insertAfter :: [GoTokenPos] -> [GoTokenPos]
insertAfter [] = []
insertAfter (xt:[]) = xt:[]
insertAfter ((xt@(GoTokenPos _ x)):(yt@(GoTokenPos yp y)):zs) = xt:(insertAfter ((repl y):zs))
where cond = if needSemi x then GoTokSemicolon else GoTokNone
repl GoTokSemicolonAuto = GoTokenPos yp cond
repl _ = yt
-- token parsers
goTokLParen = token $ GoTokLParen
goTokRParen = token $ GoTokRParen
goTokLBrace = token $ GoTokLBrace
goTokRBrace = token $ GoTokRBrace
goTokLBracket = token $ GoTokLBracket
goTokRBracket = token $ GoTokRBracket
goTokSemicolon= token $ GoTokSemicolon -- ';'
goTokColon = token $ GoTokColon -- ':'
goTokColonEq = token $ GoTokColonEq -- ':='
goTokEqual = token $ GoTokEqual -- '='
goTokComma = token $ GoTokComma -- ','
goTokFullStop = token $ GoTokFullStop -- '.'
goTokEllipsis = token $ GoTokEllipsis -- '...'
goTokAsterisk = token $ GoTokAsterisk
goTokArrow = token $ GoTokArrow
-- BEGIN keywords
goTokBreak = token $ GoTokBreak
goTokCase = token $ GoTokCase
goTokChan = token $ GoTokChan
goTokConst = token $ GoTokConst
goTokContinue = token $ GoTokContinue
goTokDefault = token $ GoTokDefault
goTokDefer = token $ GoTokDefer
goTokElse = token $ GoTokElse
goTokFallthrough = token $ GoTokFallthrough
goTokFor = token $ GoTokFor
goTokFunc = token $ GoTokFunc
goTokGo = token $ GoTokGo
goTokGoto = token $ GoTokGoto
goTokIf = token $ GoTokIf
goTokImport = token $ GoTokImport
goTokInterface= token $ GoTokInterface
goTokMap = token $ GoTokMap
goTokPackage = token $ GoTokPackage
goTokRange = token $ GoTokRange
goTokReturn = token $ GoTokReturn
goTokSelect = token $ GoTokSelect
goTokStruct = token $ GoTokStruct
goTokSwitch = token $ GoTokSwitch
goTokType = token $ GoTokType
goTokVar = token $ GoTokVar
-- END keywords
goOperator :: GoParser GoOp
goOperator = do
GoTokOp name <- token $ GoTokOp ""
return $ GoOp name
-- | Standard @assign_op@
--
-- See also: SS. 11.6. Assignments
goAssignOp :: GoParser GoOp
goAssignOp = try $ do
(GoTokenPos _ op) <- lookAhead anyToken
case op of
GoTokOp opname -> if last opname == '='
then goOperator
else fail "Assignment What?"
GoTokEqual -> do anyToken; return (GoOp "=")
x -> unexpected (show x)
| remyoudompheng/hs-language-go | Language/Go/Parser/Tokens.hs | gpl-3.0 | 13,285 | 0 | 15 | 4,322 | 3,743 | 2,050 | 1,693 | 357 | 18 |
--- |
--- | This module contains the DC-stuff for connections to other peers
--- |
--- Copyright : (c) Florian Richter 2011
--- License : GPL
---
module DCToClient (
startupClient
, handleClient
, stopClient
, downloadFilelist
, downloadFile
) where
import System.IO
import System.Timeout
import Network.Socket
import Control.Concurrent
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Data.Map as M
import Data.List
import Data.List.Split
import Data.Char (toLower)
import Control.Monad
import Control.Concurrent.STM
import Control.Exception (finally)
import System.Random (randomRIO)
import Config
import Filemgmt
import Filelist
import DCCommon
import FixedQueueTypes
import FixedQueue
import Search
-- | convert string to lower case (didn't find a library function)
toLowerCase :: String -> String
toLowerCase [] = []
toLowerCase (x:xs) = (toLower x) : xs
-- | get next file (if any), which is queued to be downloaded from this nick
nextToDownload :: AppState -> Nick -> IO (Maybe DcJob)
nextToDownload appState nick = do
jobs <- atomically $ readTVar (appJobs appState)
case M.lookup nick jobs of
Just (Job file _) -> putStrLn ("nextToDownload" ++ file)
Nothing -> putStrLn ("nextToDownload nothing")
return (M.lookup nick jobs)
-- | get next file (if any), which is queued to be downloaded from this nick
-- | if there is non, wait at least 5 seconds for new ones
nextToDownloadBlock :: AppState -> Nick -> IO (Maybe DcJob)
nextToDownloadBlock appState nick = do
timeout 5000000 $ atomically $ do
jobs <- readTVar (appJobs appState)
case M.lookup nick jobs of
Just file -> return file
Nothing -> retry
-- | connection startup handler, send nick
startupClient :: AppState -> Handle -> IO ()
startupClient appState h = do
putStrLn "startup client"
sendCmd h "MyNick" (configNick $ appConfig appState)
sendCmd h "Lock" "EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=HASKELLDC00.668ABCABC"
hFlush h
-- | connection message handler
handleClient :: AppState -> Handle -> ConnectionState -> String -> IO ConnectionState
handleClient appState h conState msg = do
case getCmd msg of
Just "$MyNick" -> do
-- TODO: check if known
let nick = tail $ dropWhile (/=' ') msg
putStrLn ("Connection from: " ++ nick)
-- add connection to connectionlist
modifyMVar_ (appConnections appState) (return . (nick:))
next <- nextToDownload appState nick
case next of
Just (Job file _) -> return (ToClient (Just nick) Download)
Nothing -> return (ToClient (Just nick) DontKnow)
Just "$Lock" -> do
putStrLn "Lock"
sendCmd h "Supports" "MiniSlots XmlBZList ADCGet TTHF"
let ToClient nick state = conState
case state of
Download -> sendCmd h "Direction" "Download 42"
_ -> sendCmd h "Direction" "Upload 42"
sendCmd h "Key" "........A .....0.0. 0. 0. 0. 0. 0."
return conState
Just "$Key" -> do
-- who cares for keys...
return conState
Just "$Quit" -> do
-- nice you tell me, just disconnect!
return conState
Just "$Supports" -> do
putStrLn "Supports"
-- TODO some checks would be nice
return conState
Just "$Direction" -> do
putStrLn "Direction"
let direction = toLowerCase $ takeWhile (/=' ') $ tail $ dropWhile (/=' ') msg
putStrLn (show direction)
let ToClient (Just nick) state = conState
case state of
Download -> putStrLn "state download"
_ -> putStrLn "state upload"
case state of
-- I don't like random number battles :)
Download -> if direction /= "upload" then hClose h else return ()
_ -> if direction /= "download" then hClose h else return ()
-- wtf, what does he want?
next <- nextToDownload appState nick
case next of
Just (Job file _) -> sendCmd h "ADCGET" ("file " ++ file ++ " 0 -1")
_ -> return ()
return conState
Just "$Get" -> do
putStrLn "Get"
let filenameOffset = tail $ dropWhile (/=' ') msg
let filename = takeWhile (/='$') filenameOffset
let offset = read $ tail $ dropWhile (/='$') filenameOffset
sizeAndContent<- getFileSizeAndContent appState filename offset
case sizeAndContent of
Just (filesize, content) -> do
putStrLn ("Filename: " ++ filename)
putStrLn ("Filesize: " ++ (show filesize))
sendCmd h "FileLength" (show filesize)
return (ToClient Nothing (Upload content))
Nothing -> do
putStrLn ("File not Found: " ++ filename)
sendCmd h "Error" "File not Available"
return (ToClient Nothing DontKnow)
Just "$Send" -> case conState of
ToClient _ (Upload content) -> do
putStrLn "Send raw data"
L.hPut h content
hFlush h
return (ToClient Nothing DontKnow)
ToClient _ _ -> do
putStrLn "Send without get"
putStrLn msg
sendCmd h "Error" "no send before get"
return conState
Just "$ADCGET" -> do
putStrLn "ADCGet"
let msg_split = splitOn " " msg
putStrLn (show msg_split)
if ((length msg_split) /= 5) || ((msg_split !! 1) /= "file")
then do
sendCmd h "Error" "invalid parameters to ADCGet"
hClose h
return (ToClient Nothing DontKnow)
else do
let filename = msg_split !! 2
let fileOffset = msg_split !! 3
let fileBufSize = msg_split !! 4
sizeAndContent <- getFileSizeAndContent appState filename (read fileOffset)
case sizeAndContent of
Just (filesize, content) -> do
putStrLn ("Filename: " ++ filename)
putStrLn ("Filesize: " ++ (show filesize))
sendCmd h "ADCSND" ("file " ++ filename ++ " 0 " ++ (show filesize))
L.hPut h content
hFlush h
--hClose h
return (ToClient Nothing DontKnow)
Nothing -> do
putStrLn ("File not Found: " ++ filename)
sendCmd h "Error" "File not Available"
return (ToClient Nothing DontKnow)
Just "$ADCSND" -> do
putStrLn "ADCSND"
let msg_split = splitOn " " msg
putStrLn (show msg_split)
if ((length msg_split) /= 5) || ((msg_split !! 1) /= "file")
then do
sendCmd h "Error" "invalid parameters to ADCSND"
hClose h
return (ToClient Nothing DontKnow)
else do
let filename = msg_split !! 2
-- let fileOffset = read (msg_split !! 3)
let fileBufSize = read (msg_split !! 4)
let (ToClient (Just nick) _) = conState
Just (Job file handler) <- nextToDownload appState nick
return (ToClient (Just nick) (DownloadJob fileBufSize handler (nextHandler appState nick)))
Nothing -> do
putStrLn "No Command:"
putStrLn msg
return conState
_ -> do
putStrLn "Unkown command:"
putStrLn msg
return conState
where
downloadHandler :: Handle -> L.ByteString -> IO ()
downloadHandler handle file = do
L.writeFile "test.bla" file
nextHandler :: AppState -> Nick -> Handle -> IO Bool
nextHandler appState nick handle = do
putStrLn "what's to download?"
next <- nextToDownloadBlock appState nick
case next of
Just (Job file _) -> do
putStrLn ("next: " ++ (file))
sendCmd h "ADCGET" ("file " ++ file ++ " 0 -1")
return False
_ -> return True
stopClient :: AppState -> ConnectionState -> IO ()
stopClient appState lastConState = do
case lastConState of
ToClient (Just nick) _ -> modifyMVar_ (appConnections appState) (return . delete nick)
_ -> return ()
-- | synchronized download of filelist
downloadFilelist :: AppState -> Nick -> IO B.ByteString
downloadFilelist appState nick = do
mvar <- newEmptyMVar
downloadFile appState (filelistHandler mvar) nick dcFilelist
takeMVar mvar
where
filelistHandler :: MVar B.ByteString -> DownloadHandler
filelistHandler mvar handle content = do
let fileNonLazy = B.concat $ L.toChunks content
fileNonLazy `seq` putMVar mvar fileNonLazy
putStrLn "download complete (handler)"
-- | asynchronous download start, should be called from different thread
downloadFile :: AppState -> DownloadHandler -> Nick -> String -> IO ()
downloadFile appState downloadHandler nick file = do
putStrLn "insert download"
putStrLn (nick ++ " " ++ (configMyIp $ appConfig appState) ++ ":" ++ (configMyPort $ appConfig appState))
atomically $ do
jobs <- readTVar (appJobs appState)
when (M.member nick jobs) retry
writeTVar (appJobs appState) (M.insert nick (Job file (deleteJobWrapper appState nick downloadHandler)) jobs)
connections <- readMVar (appConnections appState)
putStrLn ("connections: " ++ (show connections))
if nick `notElem` connections
then withMVar (appHubHandle appState) $ \hubHandle -> do
sendCmd hubHandle "ConnectToMe" (nick ++ " " ++ (configMyIp $ appConfig appState) ++ ":" ++ (configMyPort $ appConfig appState))
else return ()
where
--
deleteJobWrapper :: AppState -> Nick -> DownloadHandler -> DownloadHandler
deleteJobWrapper appState nick nestedHandler handle content = do
nestedHandler handle content `finally` removeJob appState nick
removeJob appState nick = atomically $ do
jobs <- readTVar (appJobs appState)
writeTVar (appJobs appState) (M.delete nick jobs)
-- vim: sw=4 expandtab
| f1ori/hadcc | DCToClient.hs | gpl-3.0 | 12,653 | 142 | 13 | 5,564 | 2,598 | 1,346 | 1,252 | 217 | 25 |
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
module CompilerUtils (
fromList, Migration(..), MigrationMap, compiledMain
) where
import Control.Exception (SomeException, catch)
import Control.Monad (forM_, void)
import Data.Map (Map, fromList)
import qualified Data.Map as M
import Database.PostgreSQL.Simple
(Connection, Only(..), execute, query_, begin, commit)
import Database.PostgreSQL.Migrations (connectEnv)
import Database.PostgreSQL.Migrate (initializeDb)
import System.Environment (getArgs, getProgName)
type Version = String
data Migration = Migration { migName :: String
, migUp :: Connection -> IO ()
, migDown :: Connection -> IO ()
}
type MigrationMap = Map Version Migration
compiledMain :: MigrationMap -> IO ()
compiledMain migrations = do
args <- getArgs
case args of
"init":[] -> initializeDb
"list":[] -> listMigrations migrations
"migrate":[] -> runMigrations migrations
"rollback":[] -> runRollback migrations
_ -> do
progName <- getProgName
putStrLn $ "Usage: " ++ progName ++ " migrate|rollback"
putStrLn $ " " ++ progName ++ " list"
putStrLn $ " " ++ progName ++ " init"
listMigrations :: MigrationMap -> IO ()
listMigrations migrations =
forM_ (M.toAscList migrations) $ \(_, Migration name _ _) -> putStrLn name
-- | Runs all new migrations in a given directory and dumps the
-- resulting schema to a file \"schema.sql\" in the migrations
-- directory.
--
-- Determining which migrations to run is done by querying the database for the
-- largest version in the /schema_migrations/ table, and choosing all
-- migrations in the given directory with higher versions.
runMigrations :: MigrationMap -> IO ()
runMigrations migrationsIn = do
conn <- connectEnv
res <- query_ conn
"select version from schema_migrations order by version desc limit 1"
let latestVersion = case res of
[] -> ""
(Only latest):_ -> latest
let migrations = M.toAscList $
M.filterWithKey (\k _ -> k > latestVersion) migrationsIn
forM_ migrations (doone conn)
where doone conn (version, Migration name up down) = do
putStrLn $ "=== Running Migration " ++ name
ok <- catch
(do
begin conn
void $ execute conn "insert into schema_migrations values(?)"
(Only version)
up conn
commit conn
return True)
(\(e :: SomeException) -> return False)
if ok
then putStrLn "=== Success"
else putStrLn "=== Migration Failed!"
runRollback :: MigrationMap -> IO ()
runRollback migrations = do
conn <- connectEnv
res <- query_ conn
"select version from schema_migrations order by version desc limit 1"
case res of
[] -> putStrLn "=== DB Fully Rolled Back!"
(Only latest):_ -> do
let (Migration name _ down) = migrations M.! latest
putStrLn $ "=== Running Rollback " ++ name
ok <- catch
(do
begin conn
down conn
void $ execute conn "delete from schema_migrations where version = ?"
(Only latest)
commit conn
return True)
(\(e :: SomeException) -> return False)
if ok
then putStrLn "=== Success"
else putStrLn "=== Migration Failed!"
| alevy/postgresql-orm | static/CompilerUtils.hs | gpl-3.0 | 3,481 | 0 | 20 | 1,003 | 877 | 445 | 432 | 80 | 5 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Drive.Replies.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 reply.
--
-- /See:/ <https://developers.google.com/drive/ Drive API Reference> for @drive.replies.delete@.
module Network.Google.Resource.Drive.Replies.Delete
(
-- * REST Resource
RepliesDeleteResource
-- * Creating a Request
, repliesDelete
, RepliesDelete
-- * Request Lenses
, rdReplyId
, rdFileId
, rdCommentId
) where
import Network.Google.Drive.Types
import Network.Google.Prelude
-- | A resource alias for @drive.replies.delete@ method which the
-- 'RepliesDelete' request conforms to.
type RepliesDeleteResource =
"drive" :>
"v3" :>
"files" :>
Capture "fileId" Text :>
"comments" :>
Capture "commentId" Text :>
"replies" :>
Capture "replyId" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] ()
-- | Deletes a reply.
--
-- /See:/ 'repliesDelete' smart constructor.
data RepliesDelete = RepliesDelete'
{ _rdReplyId :: !Text
, _rdFileId :: !Text
, _rdCommentId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'RepliesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rdReplyId'
--
-- * 'rdFileId'
--
-- * 'rdCommentId'
repliesDelete
:: Text -- ^ 'rdReplyId'
-> Text -- ^ 'rdFileId'
-> Text -- ^ 'rdCommentId'
-> RepliesDelete
repliesDelete pRdReplyId_ pRdFileId_ pRdCommentId_ =
RepliesDelete'
{ _rdReplyId = pRdReplyId_
, _rdFileId = pRdFileId_
, _rdCommentId = pRdCommentId_
}
-- | The ID of the reply.
rdReplyId :: Lens' RepliesDelete Text
rdReplyId
= lens _rdReplyId (\ s a -> s{_rdReplyId = a})
-- | The ID of the file.
rdFileId :: Lens' RepliesDelete Text
rdFileId = lens _rdFileId (\ s a -> s{_rdFileId = a})
-- | The ID of the comment.
rdCommentId :: Lens' RepliesDelete Text
rdCommentId
= lens _rdCommentId (\ s a -> s{_rdCommentId = a})
instance GoogleRequest RepliesDelete where
type Rs RepliesDelete = ()
type Scopes RepliesDelete =
'["https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.file"]
requestClient RepliesDelete'{..}
= go _rdFileId _rdCommentId _rdReplyId (Just AltJSON)
driveService
where go
= buildClient (Proxy :: Proxy RepliesDeleteResource)
mempty
| rueshyna/gogol | gogol-drive/gen/Network/Google/Resource/Drive/Replies/Delete.hs | mpl-2.0 | 3,289 | 0 | 16 | 826 | 467 | 278 | 189 | 72 | 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.Datastore.Projects.Operations.Cancel
-- 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)
--
-- Starts asynchronous cancellation on a long-running operation. The server
-- makes a best effort to cancel the operation, but success is not
-- guaranteed. If the server doesn\'t support this method, it returns
-- \`google.rpc.Code.UNIMPLEMENTED\`. Clients can use
-- Operations.GetOperation or other methods to check whether the
-- cancellation succeeded or whether the operation completed despite
-- cancellation. On successful cancellation, the operation is not deleted;
-- instead, it becomes an operation with an Operation.error value with a
-- google.rpc.Status.code of 1, corresponding to \`Code.CANCELLED\`.
--
-- /See:/ <https://cloud.google.com/datastore/ Cloud Datastore API Reference> for @datastore.projects.operations.cancel@.
module Network.Google.Resource.Datastore.Projects.Operations.Cancel
(
-- * REST Resource
ProjectsOperationsCancelResource
-- * Creating a Request
, projectsOperationsCancel
, ProjectsOperationsCancel
-- * Request Lenses
, pocXgafv
, pocUploadProtocol
, pocAccessToken
, pocUploadType
, pocName
, pocCallback
) where
import Network.Google.Datastore.Types
import Network.Google.Prelude
-- | A resource alias for @datastore.projects.operations.cancel@ method which the
-- 'ProjectsOperationsCancel' request conforms to.
type ProjectsOperationsCancelResource =
"v1" :>
CaptureMode "name" "cancel" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Post '[JSON] Empty
-- | Starts asynchronous cancellation on a long-running operation. The server
-- makes a best effort to cancel the operation, but success is not
-- guaranteed. If the server doesn\'t support this method, it returns
-- \`google.rpc.Code.UNIMPLEMENTED\`. Clients can use
-- Operations.GetOperation or other methods to check whether the
-- cancellation succeeded or whether the operation completed despite
-- cancellation. On successful cancellation, the operation is not deleted;
-- instead, it becomes an operation with an Operation.error value with a
-- google.rpc.Status.code of 1, corresponding to \`Code.CANCELLED\`.
--
-- /See:/ 'projectsOperationsCancel' smart constructor.
data ProjectsOperationsCancel =
ProjectsOperationsCancel'
{ _pocXgafv :: !(Maybe Xgafv)
, _pocUploadProtocol :: !(Maybe Text)
, _pocAccessToken :: !(Maybe Text)
, _pocUploadType :: !(Maybe Text)
, _pocName :: !Text
, _pocCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsOperationsCancel' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pocXgafv'
--
-- * 'pocUploadProtocol'
--
-- * 'pocAccessToken'
--
-- * 'pocUploadType'
--
-- * 'pocName'
--
-- * 'pocCallback'
projectsOperationsCancel
:: Text -- ^ 'pocName'
-> ProjectsOperationsCancel
projectsOperationsCancel pPocName_ =
ProjectsOperationsCancel'
{ _pocXgafv = Nothing
, _pocUploadProtocol = Nothing
, _pocAccessToken = Nothing
, _pocUploadType = Nothing
, _pocName = pPocName_
, _pocCallback = Nothing
}
-- | V1 error format.
pocXgafv :: Lens' ProjectsOperationsCancel (Maybe Xgafv)
pocXgafv = lens _pocXgafv (\ s a -> s{_pocXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pocUploadProtocol :: Lens' ProjectsOperationsCancel (Maybe Text)
pocUploadProtocol
= lens _pocUploadProtocol
(\ s a -> s{_pocUploadProtocol = a})
-- | OAuth access token.
pocAccessToken :: Lens' ProjectsOperationsCancel (Maybe Text)
pocAccessToken
= lens _pocAccessToken
(\ s a -> s{_pocAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pocUploadType :: Lens' ProjectsOperationsCancel (Maybe Text)
pocUploadType
= lens _pocUploadType
(\ s a -> s{_pocUploadType = a})
-- | The name of the operation resource to be cancelled.
pocName :: Lens' ProjectsOperationsCancel Text
pocName = lens _pocName (\ s a -> s{_pocName = a})
-- | JSONP
pocCallback :: Lens' ProjectsOperationsCancel (Maybe Text)
pocCallback
= lens _pocCallback (\ s a -> s{_pocCallback = a})
instance GoogleRequest ProjectsOperationsCancel where
type Rs ProjectsOperationsCancel = Empty
type Scopes ProjectsOperationsCancel =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/datastore"]
requestClient ProjectsOperationsCancel'{..}
= go _pocName _pocXgafv _pocUploadProtocol
_pocAccessToken
_pocUploadType
_pocCallback
(Just AltJSON)
datastoreService
where go
= buildClient
(Proxy :: Proxy ProjectsOperationsCancelResource)
mempty
| brendanhay/gogol | gogol-datastore/gen/Network/Google/Resource/Datastore/Projects/Operations/Cancel.hs | mpl-2.0 | 5,850 | 0 | 15 | 1,202 | 716 | 425 | 291 | 101 | 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.AdSenseHost.Accounts.Reports.Generate
-- 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)
--
-- Generate an AdSense report based on the report request sent in the query
-- parameters. Returns the result as JSON; to retrieve output in CSV format
-- specify \"alt=csv\" as a query parameter.
--
-- /See:/ <https://developers.google.com/adsense/host/ AdSense Host API Reference> for @adsensehost.accounts.reports.generate@.
module Network.Google.Resource.AdSenseHost.Accounts.Reports.Generate
(
-- * REST Resource
AccountsReportsGenerateResource
-- * Creating a Request
, accountsReportsGenerate
, AccountsReportsGenerate
-- * Request Lenses
, argDimension
, argLocale
, argEndDate
, argStartDate
, argAccountId
, argMetric
, argSort
, argFilter
, argStartIndex
, argMaxResults
) where
import Network.Google.AdSenseHost.Types
import Network.Google.Prelude
-- | A resource alias for @adsensehost.accounts.reports.generate@ method which the
-- 'AccountsReportsGenerate' request conforms to.
type AccountsReportsGenerateResource =
"adsensehost" :>
"v4.1" :>
"accounts" :>
Capture "accountId" Text :>
"reports" :>
QueryParam "startDate" Text :>
QueryParam "endDate" Text :>
QueryParams "dimension" Text :>
QueryParam "locale" Text :>
QueryParams "metric" Text :>
QueryParams "sort" Text :>
QueryParams "filter" Text :>
QueryParam "startIndex" (Textual Word32) :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :> Get '[JSON] Report
-- | Generate an AdSense report based on the report request sent in the query
-- parameters. Returns the result as JSON; to retrieve output in CSV format
-- specify \"alt=csv\" as a query parameter.
--
-- /See:/ 'accountsReportsGenerate' smart constructor.
data AccountsReportsGenerate =
AccountsReportsGenerate'
{ _argDimension :: !(Maybe [Text])
, _argLocale :: !(Maybe Text)
, _argEndDate :: !Text
, _argStartDate :: !Text
, _argAccountId :: !Text
, _argMetric :: !(Maybe [Text])
, _argSort :: !(Maybe [Text])
, _argFilter :: !(Maybe [Text])
, _argStartIndex :: !(Maybe (Textual Word32))
, _argMaxResults :: !(Maybe (Textual Word32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountsReportsGenerate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'argDimension'
--
-- * 'argLocale'
--
-- * 'argEndDate'
--
-- * 'argStartDate'
--
-- * 'argAccountId'
--
-- * 'argMetric'
--
-- * 'argSort'
--
-- * 'argFilter'
--
-- * 'argStartIndex'
--
-- * 'argMaxResults'
accountsReportsGenerate
:: Text -- ^ 'argEndDate'
-> Text -- ^ 'argStartDate'
-> Text -- ^ 'argAccountId'
-> AccountsReportsGenerate
accountsReportsGenerate pArgEndDate_ pArgStartDate_ pArgAccountId_ =
AccountsReportsGenerate'
{ _argDimension = Nothing
, _argLocale = Nothing
, _argEndDate = pArgEndDate_
, _argStartDate = pArgStartDate_
, _argAccountId = pArgAccountId_
, _argMetric = Nothing
, _argSort = Nothing
, _argFilter = Nothing
, _argStartIndex = Nothing
, _argMaxResults = Nothing
}
-- | Dimensions to base the report on.
argDimension :: Lens' AccountsReportsGenerate [Text]
argDimension
= lens _argDimension (\ s a -> s{_argDimension = a})
. _Default
. _Coerce
-- | Optional locale to use for translating report output to a local
-- language. Defaults to \"en_US\" if not specified.
argLocale :: Lens' AccountsReportsGenerate (Maybe Text)
argLocale
= lens _argLocale (\ s a -> s{_argLocale = a})
-- | End of the date range to report on in \"YYYY-MM-DD\" format, inclusive.
argEndDate :: Lens' AccountsReportsGenerate Text
argEndDate
= lens _argEndDate (\ s a -> s{_argEndDate = a})
-- | Start of the date range to report on in \"YYYY-MM-DD\" format,
-- inclusive.
argStartDate :: Lens' AccountsReportsGenerate Text
argStartDate
= lens _argStartDate (\ s a -> s{_argStartDate = a})
-- | Hosted account upon which to report.
argAccountId :: Lens' AccountsReportsGenerate Text
argAccountId
= lens _argAccountId (\ s a -> s{_argAccountId = a})
-- | Numeric columns to include in the report.
argMetric :: Lens' AccountsReportsGenerate [Text]
argMetric
= lens _argMetric (\ s a -> s{_argMetric = a}) .
_Default
. _Coerce
-- | The name of a dimension or metric to sort the resulting report on,
-- optionally prefixed with \"+\" to sort ascending or \"-\" to sort
-- descending. If no prefix is specified, the column is sorted ascending.
argSort :: Lens' AccountsReportsGenerate [Text]
argSort
= lens _argSort (\ s a -> s{_argSort = a}) . _Default
. _Coerce
-- | Filters to be run on the report.
argFilter :: Lens' AccountsReportsGenerate [Text]
argFilter
= lens _argFilter (\ s a -> s{_argFilter = a}) .
_Default
. _Coerce
-- | Index of the first row of report data to return.
argStartIndex :: Lens' AccountsReportsGenerate (Maybe Word32)
argStartIndex
= lens _argStartIndex
(\ s a -> s{_argStartIndex = a})
. mapping _Coerce
-- | The maximum number of rows of report data to return.
argMaxResults :: Lens' AccountsReportsGenerate (Maybe Word32)
argMaxResults
= lens _argMaxResults
(\ s a -> s{_argMaxResults = a})
. mapping _Coerce
instance GoogleRequest AccountsReportsGenerate where
type Rs AccountsReportsGenerate = Report
type Scopes AccountsReportsGenerate =
'["https://www.googleapis.com/auth/adsensehost"]
requestClient AccountsReportsGenerate'{..}
= go _argAccountId (Just _argStartDate)
(Just _argEndDate)
(_argDimension ^. _Default)
_argLocale
(_argMetric ^. _Default)
(_argSort ^. _Default)
(_argFilter ^. _Default)
_argStartIndex
_argMaxResults
(Just AltJSON)
adSenseHostService
where go
= buildClient
(Proxy :: Proxy AccountsReportsGenerateResource)
mempty
| brendanhay/gogol | gogol-adsense-host/gen/Network/Google/Resource/AdSenseHost/Accounts/Reports/Generate.hs | mpl-2.0 | 7,121 | 0 | 22 | 1,758 | 1,135 | 656 | 479 | 156 | 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.Directory.Resources.Buildings.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a building.
--
-- /See:/ <https://developers.google.com/admin-sdk/ Admin SDK API Reference> for @directory.resources.buildings.get@.
module Network.Google.Resource.Directory.Resources.Buildings.Get
(
-- * REST Resource
ResourcesBuildingsGetResource
-- * Creating a Request
, resourcesBuildingsGet
, ResourcesBuildingsGet
-- * Request Lenses
, rbgXgafv
, rbgUploadProtocol
, rbgAccessToken
, rbgBuildingId
, rbgUploadType
, rbgCustomer
, rbgCallback
) where
import Network.Google.Directory.Types
import Network.Google.Prelude
-- | A resource alias for @directory.resources.buildings.get@ method which the
-- 'ResourcesBuildingsGet' request conforms to.
type ResourcesBuildingsGetResource =
"admin" :>
"directory" :>
"v1" :>
"customer" :>
Capture "customer" Text :>
"resources" :>
"buildings" :>
Capture "buildingId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Building
-- | Retrieves a building.
--
-- /See:/ 'resourcesBuildingsGet' smart constructor.
data ResourcesBuildingsGet =
ResourcesBuildingsGet'
{ _rbgXgafv :: !(Maybe Xgafv)
, _rbgUploadProtocol :: !(Maybe Text)
, _rbgAccessToken :: !(Maybe Text)
, _rbgBuildingId :: !Text
, _rbgUploadType :: !(Maybe Text)
, _rbgCustomer :: !Text
, _rbgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ResourcesBuildingsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rbgXgafv'
--
-- * 'rbgUploadProtocol'
--
-- * 'rbgAccessToken'
--
-- * 'rbgBuildingId'
--
-- * 'rbgUploadType'
--
-- * 'rbgCustomer'
--
-- * 'rbgCallback'
resourcesBuildingsGet
:: Text -- ^ 'rbgBuildingId'
-> Text -- ^ 'rbgCustomer'
-> ResourcesBuildingsGet
resourcesBuildingsGet pRbgBuildingId_ pRbgCustomer_ =
ResourcesBuildingsGet'
{ _rbgXgafv = Nothing
, _rbgUploadProtocol = Nothing
, _rbgAccessToken = Nothing
, _rbgBuildingId = pRbgBuildingId_
, _rbgUploadType = Nothing
, _rbgCustomer = pRbgCustomer_
, _rbgCallback = Nothing
}
-- | V1 error format.
rbgXgafv :: Lens' ResourcesBuildingsGet (Maybe Xgafv)
rbgXgafv = lens _rbgXgafv (\ s a -> s{_rbgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
rbgUploadProtocol :: Lens' ResourcesBuildingsGet (Maybe Text)
rbgUploadProtocol
= lens _rbgUploadProtocol
(\ s a -> s{_rbgUploadProtocol = a})
-- | OAuth access token.
rbgAccessToken :: Lens' ResourcesBuildingsGet (Maybe Text)
rbgAccessToken
= lens _rbgAccessToken
(\ s a -> s{_rbgAccessToken = a})
-- | The unique ID of the building to retrieve.
rbgBuildingId :: Lens' ResourcesBuildingsGet Text
rbgBuildingId
= lens _rbgBuildingId
(\ s a -> s{_rbgBuildingId = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
rbgUploadType :: Lens' ResourcesBuildingsGet (Maybe Text)
rbgUploadType
= lens _rbgUploadType
(\ s a -> s{_rbgUploadType = a})
-- | The unique ID for the customer\'s Google Workspace account. As an
-- account administrator, you can also use the \`my_customer\` alias to
-- represent your account\'s customer ID.
rbgCustomer :: Lens' ResourcesBuildingsGet Text
rbgCustomer
= lens _rbgCustomer (\ s a -> s{_rbgCustomer = a})
-- | JSONP
rbgCallback :: Lens' ResourcesBuildingsGet (Maybe Text)
rbgCallback
= lens _rbgCallback (\ s a -> s{_rbgCallback = a})
instance GoogleRequest ResourcesBuildingsGet where
type Rs ResourcesBuildingsGet = Building
type Scopes ResourcesBuildingsGet =
'["https://www.googleapis.com/auth/admin.directory.resource.calendar",
"https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly"]
requestClient ResourcesBuildingsGet'{..}
= go _rbgCustomer _rbgBuildingId _rbgXgafv
_rbgUploadProtocol
_rbgAccessToken
_rbgUploadType
_rbgCallback
(Just AltJSON)
directoryService
where go
= buildClient
(Proxy :: Proxy ResourcesBuildingsGetResource)
mempty
| brendanhay/gogol | gogol-admin-directory/gen/Network/Google/Resource/Directory/Resources/Buildings/Get.hs | mpl-2.0 | 5,427 | 0 | 21 | 1,314 | 795 | 463 | 332 | 119 | 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.CloudResourceManager.TagValues.GetIAMPolicy
-- 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)
--
-- Gets the access control policy for a TagValue. The returned policy may
-- be empty if no such policy or resource exists. The \`resource\` field
-- should be the TagValue\'s resource name. For example:
-- \`tagValues\/1234\`. The caller must have the
-- \`cloudresourcemanager.googleapis.com\/tagValues.getIamPolicy\`
-- permission on the identified TagValue to get the access control policy.
--
-- /See:/ <https://cloud.google.com/resource-manager Cloud Resource Manager API Reference> for @cloudresourcemanager.tagValues.getIamPolicy@.
module Network.Google.Resource.CloudResourceManager.TagValues.GetIAMPolicy
(
-- * REST Resource
TagValuesGetIAMPolicyResource
-- * Creating a Request
, tagValuesGetIAMPolicy
, TagValuesGetIAMPolicy
-- * Request Lenses
, tvgipXgafv
, tvgipUploadProtocol
, tvgipAccessToken
, tvgipUploadType
, tvgipPayload
, tvgipResource
, tvgipCallback
) where
import Network.Google.Prelude
import Network.Google.ResourceManager.Types
-- | A resource alias for @cloudresourcemanager.tagValues.getIamPolicy@ method which the
-- 'TagValuesGetIAMPolicy' request conforms to.
type TagValuesGetIAMPolicyResource =
"v3" :>
CaptureMode "resource" "getIamPolicy" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] GetIAMPolicyRequest :>
Post '[JSON] Policy
-- | Gets the access control policy for a TagValue. The returned policy may
-- be empty if no such policy or resource exists. The \`resource\` field
-- should be the TagValue\'s resource name. For example:
-- \`tagValues\/1234\`. The caller must have the
-- \`cloudresourcemanager.googleapis.com\/tagValues.getIamPolicy\`
-- permission on the identified TagValue to get the access control policy.
--
-- /See:/ 'tagValuesGetIAMPolicy' smart constructor.
data TagValuesGetIAMPolicy =
TagValuesGetIAMPolicy'
{ _tvgipXgafv :: !(Maybe Xgafv)
, _tvgipUploadProtocol :: !(Maybe Text)
, _tvgipAccessToken :: !(Maybe Text)
, _tvgipUploadType :: !(Maybe Text)
, _tvgipPayload :: !GetIAMPolicyRequest
, _tvgipResource :: !Text
, _tvgipCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TagValuesGetIAMPolicy' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tvgipXgafv'
--
-- * 'tvgipUploadProtocol'
--
-- * 'tvgipAccessToken'
--
-- * 'tvgipUploadType'
--
-- * 'tvgipPayload'
--
-- * 'tvgipResource'
--
-- * 'tvgipCallback'
tagValuesGetIAMPolicy
:: GetIAMPolicyRequest -- ^ 'tvgipPayload'
-> Text -- ^ 'tvgipResource'
-> TagValuesGetIAMPolicy
tagValuesGetIAMPolicy pTvgipPayload_ pTvgipResource_ =
TagValuesGetIAMPolicy'
{ _tvgipXgafv = Nothing
, _tvgipUploadProtocol = Nothing
, _tvgipAccessToken = Nothing
, _tvgipUploadType = Nothing
, _tvgipPayload = pTvgipPayload_
, _tvgipResource = pTvgipResource_
, _tvgipCallback = Nothing
}
-- | V1 error format.
tvgipXgafv :: Lens' TagValuesGetIAMPolicy (Maybe Xgafv)
tvgipXgafv
= lens _tvgipXgafv (\ s a -> s{_tvgipXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
tvgipUploadProtocol :: Lens' TagValuesGetIAMPolicy (Maybe Text)
tvgipUploadProtocol
= lens _tvgipUploadProtocol
(\ s a -> s{_tvgipUploadProtocol = a})
-- | OAuth access token.
tvgipAccessToken :: Lens' TagValuesGetIAMPolicy (Maybe Text)
tvgipAccessToken
= lens _tvgipAccessToken
(\ s a -> s{_tvgipAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
tvgipUploadType :: Lens' TagValuesGetIAMPolicy (Maybe Text)
tvgipUploadType
= lens _tvgipUploadType
(\ s a -> s{_tvgipUploadType = a})
-- | Multipart request metadata.
tvgipPayload :: Lens' TagValuesGetIAMPolicy GetIAMPolicyRequest
tvgipPayload
= lens _tvgipPayload (\ s a -> s{_tvgipPayload = a})
-- | REQUIRED: The resource for which the policy is being requested. See the
-- operation documentation for the appropriate value for this field.
tvgipResource :: Lens' TagValuesGetIAMPolicy Text
tvgipResource
= lens _tvgipResource
(\ s a -> s{_tvgipResource = a})
-- | JSONP
tvgipCallback :: Lens' TagValuesGetIAMPolicy (Maybe Text)
tvgipCallback
= lens _tvgipCallback
(\ s a -> s{_tvgipCallback = a})
instance GoogleRequest TagValuesGetIAMPolicy where
type Rs TagValuesGetIAMPolicy = Policy
type Scopes TagValuesGetIAMPolicy =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only"]
requestClient TagValuesGetIAMPolicy'{..}
= go _tvgipResource _tvgipXgafv _tvgipUploadProtocol
_tvgipAccessToken
_tvgipUploadType
_tvgipCallback
(Just AltJSON)
_tvgipPayload
resourceManagerService
where go
= buildClient
(Proxy :: Proxy TagValuesGetIAMPolicyResource)
mempty
| brendanhay/gogol | gogol-resourcemanager/gen/Network/Google/Resource/CloudResourceManager/TagValues/GetIAMPolicy.hs | mpl-2.0 | 6,141 | 0 | 16 | 1,295 | 790 | 465 | 325 | 117 | 1 |
module LastDigit where
-- fastPower :: Integer -> Integer -> Integer
-- fastPower a b = mod (b * (fastPower (a - 1) b)) 10
-- lastDigit :: Integer -> Integer -> Integer
-- lastDigit _ 9460519178175124365941571214880402830019368270018729041658731800055367147675563748201080421764071920 = 6
-- lastDigit b 0 = 1
-- lastDigit b 1 = mod b 10
-- lastDigit b a|b >= 10 = if (mod b 10 == 0) then 0 else lastDigit a $ mod b 10
-- |otherwise = mod (fastPower b a) 10
--
import Data.List.Split
-- <func append> -> <empty unit> -> <base elem> -> <exponential> -> <res>
fastContAppendOp :: Integral a => (b -> b -> b) -> b -> b -> a -> b
fastContAppendOp _ e _ 0 = e
fastContAppendOp f e a k
| mod k 2 == 1 = f a (fastContAppendOp f e a (k - 1))
| otherwise = fastContAppendOp f e (f a a) (div k 2)
-- Optimized specified FCOODCMWDBAE algorithm on Monoid <N+, *> with mod operation
-- <base> -> <exp> -> <moder> -> <res>
fastExpModOpti :: Integral a => a -> a -> a -> a
fastExpModOpti a k m = fastContAppendOp (\a b -> (mod (a * b) m)) 1 a k
-- Problem 1193 Specified algorithm
-- <A> -> <M> -> <N> -> <res>
passwordAtNthDay :: Int -> Int -> Int -> Int
passwordAtNthDay a m n = mod (fastExpModOpti a n m) m
splitAndExtInt :: String -> [Int]
splitAndExtInt s = map read $ splitOn " " s
lastDigit :: Integer -> Integer -> Integer
lastDigit a b = fastExpModOpti a b 10
| ice1000/OI-codes | codewars/101-200/last-digit-of-a-large-number.hs | agpl-3.0 | 1,383 | 0 | 11 | 298 | 340 | 178 | 162 | 15 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-
Bustle.UI.FilterDialog: allows the user to filter the displayed log
Copyright © 2011 Collabora Ltd.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-}
module Bustle.UI.FilterDialog
( runFilterDialog
)
where
import Data.List (intercalate, groupBy, elemIndices)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Function as F
import Graphics.UI.Gtk
import Bustle.Translation (__)
import Bustle.Types
namespace :: String
-> (String, String)
namespace name = case reverse (elemIndices '.' name) of
[] -> ("", name)
(i:_) -> splitAt (i + 1) name
formatNames :: (UniqueName, Set OtherName)
-> String
formatNames (u, os)
| Set.null os = unUniqueName u
| otherwise = intercalate "\n" . map (formatGroup . groupGroup) $ groups
where
groups = groupBy ((==) `F.on` fst) . map (namespace . unOtherName) $ Set.toAscList os
groupGroup [] = error "unpossible empty group from groupBy"
groupGroup xs@((ns, _):_) = (ns, map snd xs)
formatGroup (ns, [y]) = ns ++ y
formatGroup (ns, ys) = ns ++ "{" ++ intercalate "," ys ++ "}"
type NameStore = ListStore (Bool, (UniqueName, Set OtherName))
makeStore :: [(UniqueName, Set OtherName)]
-> Set UniqueName
-> IO NameStore
makeStore names currentlyHidden =
listStoreNew $ map toPair names
where
toPair name@(u, _) = (not (Set.member u currentlyHidden), name)
makeView :: NameStore
-> IO ScrolledWindow
makeView nameStore = do
nameView <- treeViewNewWithModel nameStore
-- We want rules because otherwise it's tough to see where each group
-- starts and ends
treeViewSetRulesHint nameView True
treeViewSetHeadersVisible nameView False
widgetSetSizeRequest nameView 600 371
tickyCell <- cellRendererToggleNew
tickyColumn <- treeViewColumnNew
treeViewColumnPackStart tickyColumn tickyCell True
treeViewAppendColumn nameView tickyColumn
cellLayoutSetAttributes tickyColumn tickyCell nameStore $ \(ticked, _) ->
[ cellToggleActive := ticked ]
on tickyCell cellToggled $ \pathstr -> do
let [i] = stringToTreePath pathstr
(v, ns) <- listStoreGetValue nameStore i
listStoreSetValue nameStore i (not v, ns)
nameCell <- cellRendererTextNew
nameColumn <- treeViewColumnNew
treeViewColumnPackStart nameColumn nameCell True
treeViewAppendColumn nameView nameColumn
cellLayoutSetAttributes nameColumn nameCell nameStore $ \(_, ns) ->
[ cellText := formatNames ns ]
sw <- scrolledWindowNew Nothing Nothing
scrolledWindowSetPolicy sw PolicyAutomatic PolicyAutomatic
containerAdd sw nameView
return sw
runFilterDialog :: WindowClass parent
=> parent -- ^ The window to which to attach the dialog
-> [(UniqueName, Set OtherName)] -- ^ Names, in order of appearance
-> Set UniqueName -- ^ Currently-hidden names
-> IO (Set UniqueName) -- ^ The set of names to *hide*
runFilterDialog parent names currentlyHidden = do
d <- dialogNew
(windowWidth, windowHeight) <- windowGetSize parent
windowSetDefaultSize d (windowWidth * 7 `div` 8) (windowHeight `div` 2)
d `set` [ windowTransientFor := parent ]
dialogAddButton d stockClose ResponseClose
vbox <- castToBox <$> dialogGetContentArea d
boxSetSpacing vbox 6
nameStore <- makeStore names currentlyHidden
sw <- makeView nameStore
instructions <- labelNew (Nothing :: Maybe String)
widgetSetSizeRequest instructions 600 (-1)
labelSetMarkup instructions
(__ "Unticking a service hides its column in the diagram, \
\and all messages it is involved in. That is, all methods it calls \
\or are called on it, the corresponding returns, and all signals it \
\emits will be hidden.")
labelSetLineWrap instructions True
boxPackStart vbox instructions PackNatural 0
boxPackStart vbox sw PackGrow 0
widgetShowAll vbox
_ <- dialogRun d
widgetDestroy d
results <- listStoreToList nameStore
return $ Set.fromList [ u
| (ticked, (u, _)) <- results
, not ticked
]
| wjt/bustle | Bustle/UI/FilterDialog.hs | lgpl-2.1 | 4,963 | 0 | 14 | 1,156 | 1,127 | 566 | 561 | 89 | 3 |
module QuickCheckTests where
import Test.QuickCheck
import Data.List (sort)
import Data.Char (toUpper)
gen :: (Arbitrary a) => Gen a
gen = do
a <- arbitrary
return a
divisor :: Gen Float
divisor = arbitrary `suchThat` (/= 0)
half x = x / 2
halfIdentity = ((*2) . half)
prop_half :: Property
prop_half =
forAll divisor
(\x -> (half x) * 2 == x)
listOrdered :: (Ord a) => [a] -> Bool
listOrdered xs = snd $ foldr go (Nothing, True) xs
where go _ status@(_, False) = status
go y (Nothing, t) = (Just y, t)
go y (Just x, t) = (Just y, x >= y)
prop_listOrdered :: Property
prop_listOrdered =
forAll (genList :: Gen [Int])
(\x -> listOrdered (sort x) == True)
genList :: (Arbitrary a, Eq a) => Gen [a]
genList = do
a <- arbitrary
b <- arbitrary
c <- arbitrary
return [a,b,c]
plusAssociative :: Int -> Int -> Int -> Bool
plusAssociative x y z = x + (y + z) == (x + y) + z
plusCommutative :: Double -> Double -> Bool
plusCommutative x y = x + y == y + x
plusAssociativeMul :: Int -> Int -> Int -> Bool
plusAssociativeMul x y z = x * (y * z) == (x * y) * z
plusCommutativeMul x y = x * y == y * x
--using the identity wrapper
data Identity a = Identity a deriving (Eq, Ord, Show)
identityGen :: Arbitrary a => Gen (Identity a)
identityGen = do
a <- arbitrary
return (Identity a)
instance Arbitrary a => Arbitrary (Identity a) where
arbitrary = identityGen
identityGenInt :: Gen (Identity Int)
identityGenInt = identityGen
quotremTest x (Positive y) = (quot x y) * y + (rem x y) == x
divmodTest x (Positive y) = (div x y) * y + (mod x y) == x
expoAssociative x y z = x ^ (y ^ z) == (x ^ y) ^ z
expoCommutative x y = x ^ y == y ^ x
prop_reverseListTwice :: Property
prop_reverseListTwice =
forAll (genList :: Gen [Int] )
(\x -> (reverse . reverse) x == id x)
capitalizeWord [] = []
capitalizeWord (x:xs) = toUpper x : xs
twice f = f . f
fourTimes = twice . twice
prop_capitalizeWord =
forAll (gen :: Gen [Char])
(\x -> (capitalizeWord x == twice capitalizeWord x) && (capitalizeWord x == fourTimes capitalizeWord x))
prop_sort =
forAll (gen :: Gen[Int])
(\x -> (sort x == twice sort x) && (sort x == fourTimes sort x))
data Fool =
Fulse
| Frue
deriving (Eq, Show)
genFool :: Gen Fool
genFool = do
oneof [return $ Fulse,
return $ Frue]
genFool' :: Gen Fool
genFool' = do
frequency [(3, return $ Fulse),
(1, return $ Frue)]
main :: IO ()
main = do
quickCheck prop_half
quickCheck prop_listOrdered
quickCheck plusAssociative
quickCheck plusCommutative
quickCheck plusAssociativeMul
quickCheck (plusCommutativeMul :: Int -> Int -> Bool)
quickCheck (divmodTest :: Int -> (Positive Int) -> Bool)
quickCheck (quotremTest :: Int -> (Positive Int) -> Bool)
quickCheck (expoAssociative :: Int -> Int -> Int -> Bool)
quickCheck (expoCommutative :: Int -> Int -> Bool)
quickCheck (prop_reverseListTwice)
quickCheck (prop_capitalizeWord)
quickCheck (prop_sort)
| thewoolleyman/haskellbook | 14/07/maor/QuickCheckTests.hs | unlicense | 2,988 | 0 | 12 | 676 | 1,344 | 698 | 646 | 92 | 3 |
module Coins.A265415 (a265415) where
import Coins.A260643 (a260643_list)
import Data.List (elemIndices)
a265415 :: Int -> Int
a265415 n = a265415_list !! (n - 1)
a265415_list :: [Int]
a265415_list = map (+1) $ elemIndices 1 a260643_list
| peterokagey/haskellOEIS | src/Coins/A265415.hs | apache-2.0 | 239 | 0 | 7 | 36 | 88 | 50 | 38 | 7 | 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="ru-RU">
<title>Highlighter</title>
<maps>
<homeID>highlighter</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | secdec/zap-extensions | addOns/highlighter/src/main/javahelp/help_ru_RU/helpset_ru_RU.hs | apache-2.0 | 964 | 114 | 29 | 155 | 420 | 208 | 212 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Spark.Core.Internal.ColumnStructures where
import Control.Arrow ((&&&))
import Data.Function(on)
import Data.Vector(Vector)
import Spark.Core.Internal.DatasetStructures
import Spark.Core.Internal.DatasetFunctions()
import Spark.Core.Internal.RowStructures
import Spark.Core.Internal.TypesStructures
import Spark.Core.Internal.OpStructures
import Spark.Core.StructuresInternal
import Spark.Core.Try
{-| The data structure that implements the notion of data columns.
The type on this one may either be a Cell or a proper type.
A column of data from a dataset
The ref is a reference potentially to the originating
dataset, but it may be more general than that to perform
type-safe tricks.
Unlike Spark, columns are always attached to a reference dataset or dataframe.
One cannot materialize a column out of thin air. In order to broadcast a value
along a given column, the `broadcast` function is provided.
TODO: try something like this https://www.vidarholen.net/contents/junk/catbag.html
-}
data ColumnData ref a = ColumnData {
_cOrigin :: !UntypedDataset,
_cType :: !DataType,
_cOp :: !GeneralizedColOp,
-- The name in the dataset.
-- If not set, it will be deduced from the operation.
_cReferingPath :: !(Maybe FieldName)
}
{-| A generalization of the column operation.
This structure is useful to performn some extra operations not supported by
the Spark engine:
- express joins with an observable
- keep track of DAGs of column operations (not implemented yet)
-}
data GeneralizedColOp =
GenColExtraction !FieldPath
| GenColFunction !SqlFunctionName !(Vector GeneralizedColOp)
| GenColLit !DataType !Cell
-- This is the extra operation that needs to be flattened with a broadcast.
| BroadcastColOp !UntypedLocalData
| GenColStruct !(Vector GeneralizedTransField)
deriving (Eq, Show)
data GeneralizedTransField = GeneralizedTransField {
gtfName :: !FieldName,
gtfValue :: !GeneralizedColOp
} deriving (Eq, Show)
{-| A column of data from a dataset or a dataframe.
This column is typed: the operations on this column will be
validdated by Haskell' type inferenc.
-}
type Column ref a = ColumnData ref a
{-| An untyped column of data from a dataset or a dataframe.
This column is untyped and may not be properly constructed. Any error
will be found during the analysis phase at runtime.
This type encapsulates both Dataframes and datasets.
-}
data Column' = Column' !DynColumn
{-| (internal) -}
-- TODO: remove
type DynColumn = Try (ColumnData UnknownReference Cell)
-- | (dev)
-- The type of untyped column data.
type UntypedColumnData = ColumnData UnknownReference Cell
{-| (dev)
A column for which the type of the cells is unavailable (at the type level),
but for which the origin is available at the type level.
-}
type GenericColumn ref = Column ref Cell
{-| A dummy data type that indicates the data referenc is missing.
-}
data UnknownReference
{-| A tag that carries the reference information of a column at a
type level. This is useful when creating column.
See ref and colRef.
-}
data ColumnReference a = ColumnReference
instance forall ref a. Eq (ColumnData ref a) where
(==) = (==) `on` (_cOrigin &&& _cType &&& _cOp &&& _cReferingPath)
| tjhunter/karps | haskell/src/Spark/Core/Internal/ColumnStructures.hs | apache-2.0 | 3,393 | 0 | 11 | 548 | 377 | 229 | 148 | -1 | -1 |
module Nanocoin.Network.RPC (
rpcServer
) where
import Protolude hiding (get, intercalate, print, putText)
import Data.Aeson hiding (json, json')
import Data.Text (intercalate)
import Web.Scotty
import Data.List ((\\))
import qualified Data.Map as Map
import Logger
import Address
import qualified Address
import Nanocoin.Network.Message (Msg(..))
import Nanocoin.Network.Node as Node
import Nanocoin.Network.Peer
import qualified Key
import qualified Nanocoin.Ledger as L
import qualified Nanocoin.Block as B
import qualified Nanocoin.MemPool as MP
import qualified Nanocoin.Transaction as T
import qualified Nanocoin.Network.Cmd as Cmd
-------------------------------------------------------------------------------
-- RPC (HTTP) Server
-------------------------------------------------------------------------------
runNodeActionM
:: Logger
-> NodeEnv
-> NodeT (LoggerT IO) a
-> ActionM a
runNodeActionM logger nodeEnv =
liftIO . runLoggerT logger . runNodeT nodeEnv
-- | Starts an RPC server for interaction via HTTP
rpcServer
:: Logger
-> NodeEnv
-> Chan Cmd.Cmd
-> IO ()
rpcServer logger nodeEnv cmdChan = do
(NodeConfig hostName p2pPort rpcPort keys) <-
liftIO $ nodeConfig <$> runNodeT nodeEnv ask
let runNodeActionM' = runNodeActionM logger nodeEnv
scotty rpcPort $ do
--------------------------------------------------
-- Queries
--------------------------------------------------
get "/address" $
json =<< runNodeActionM' getNodeAddress
get "/blocks" $
json =<< runNodeActionM' getBlockChain
get "/mempool" $
json =<< runNodeActionM' getMemPool
get "/ledger" $
json =<< runNodeActionM' getLedger
--------------------------------------------------
-- Commands
--------------------------------------------------
get "/mineBlock" $ do
eBlock <- runNodeActionM' mineBlock
case eBlock of
Left err -> text $ show err
Right block -> do
let blockCmd = Cmd.BlockCmd block
liftIO $ writeChan cmdChan blockCmd
json block
get "/transfer/:toAddr/:amount" $ do
toAddr' <- param "toAddr"
amount <- param "amount"
case mkAddress (encodeUtf8 toAddr') of
Left err -> text $ toSL err
Right toAddr -> do
keys <- runNodeActionM' Node.getNodeKeys
tx <- liftIO $ T.transferTransaction keys toAddr amount
let txMsg = Cmd.TransactionCmd tx
liftIO $ writeChan cmdChan txMsg
json tx
| tdietert/nanocoin | src/Nanocoin/Network/RPC.hs | apache-2.0 | 2,533 | 0 | 22 | 543 | 610 | 313 | 297 | 64 | 3 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.APPLE.FloatPixels
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/APPLE/float_pixels.txt APPLE_float_pixels> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.APPLE.FloatPixels (
-- * Enums
gl_ALPHA_FLOAT16_APPLE,
gl_ALPHA_FLOAT32_APPLE,
gl_COLOR_FLOAT_APPLE,
gl_HALF_APPLE,
gl_INTENSITY_FLOAT16_APPLE,
gl_INTENSITY_FLOAT32_APPLE,
gl_LUMINANCE_ALPHA_FLOAT16_APPLE,
gl_LUMINANCE_ALPHA_FLOAT32_APPLE,
gl_LUMINANCE_FLOAT16_APPLE,
gl_LUMINANCE_FLOAT32_APPLE,
gl_RGBA_FLOAT16_APPLE,
gl_RGBA_FLOAT32_APPLE,
gl_RGB_FLOAT16_APPLE,
gl_RGB_FLOAT32_APPLE
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/APPLE/FloatPixels.hs | bsd-3-clause | 1,012 | 0 | 4 | 117 | 76 | 57 | 19 | 16 | 0 |
module Data.Strict.Maybe where
data Maybe' a = Just' !a | Nothing'
lazy :: Maybe' a -> Maybe a
lazy Nothing' = Nothing
lazy (Just' a) = Just a
{-# INLINABLE lazy #-}
strict :: Maybe a -> Maybe' a
strict Nothing = Nothing'
strict (Just a) = Just' a
{-# INLINABLE strict #-}
maybe' :: b -> (a -> b) -> Maybe' a -> b
maybe' y f Nothing' = y
maybe' y f (Just' x) = f x
{-# INLINABLE maybe' #-}
| effectfully/prefolds | src/Data/Strict/Maybe.hs | bsd-3-clause | 397 | 0 | 8 | 90 | 164 | 84 | 80 | 13 | 1 |
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}
module Lichen.Plagiarism.Render where
import Data.Monoid ((<>))
import Text.Blaze.Html5 ((!))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import Clay ((?))
import qualified Clay as C
import qualified Clay.Size as C.S
import qualified Clay.Render as C.R
import qualified Clay.Text as C.T
import qualified Clay.Font as C.F
import Language.Javascript.JMacro
import Lichen.Util
hs :: Show a => a -> H.Html
hs = H.toHtml . sq
stylesheet :: C.Css
stylesheet = mconcat [ ".centered" ? C.textAlign C.center
, ".matches" ? C.color C.white <> C.backgroundColor C.grey
, ".hovering" ? C.color C.white <> C.backgroundColor C.blue
, ".selected-red" ? C.color C.white <> C.backgroundColor C.red
, ".selected-orange" ? C.color C.white <> C.backgroundColor C.orange
, ".selected-yellow" ? C.color C.white <> C.backgroundColor C.greenyellow
, ".selected-green" ? C.color C.white <> C.backgroundColor C.green
, ".selected-blue" ? C.color C.white <> C.backgroundColor C.turquoise
, ".selected-indigo" ? C.color C.white <> C.backgroundColor C.indigo
, ".selected-violet" ? C.color C.white <> C.backgroundColor C.violet
, ".scrollable-pane" ? mconcat [ C.width $ C.S.pct 45
, C.height $ C.S.vh 80
, C.overflowY C.scroll
, C.position C.absolute
, C.whiteSpace C.T.pre
, C.fontFamily [] [C.F.monospace]
]
, "#left" ? C.left (C.S.px 0)
, "#right" ? C.left (C.S.pct 50)
]
javascript :: JStat
javascript = [jmacro|
var currentHighlight = "selected-red";
fun nextHighlight cur {
switch (cur) {
case "selected-red": return "selected-orange";
case "selected-orange": return "selected-yellow";
case "selected-yellow": return "selected-green";
case "selected-green": return "selected-blue";
case "selected-blue": return "selected-indigo";
case "selected-indigo": return "selected-violet";
case "selected-violet": return "selected-red";
}
}
$("#left > .matches").each(function() {
$(this).on("click", function(_) {
var hash = $(this).data("hash");
var pos = $("#right > .matches[data-hash=" + hash + "]")[0].offsetTop;
$("#right").scrollTop(pos);
});
});
$("#right > .matches").each(function() {
$(this).on("click", function(_) {
var hash = $(this).data("hash");
var pos = $("#left > .matches[data-hash=" + hash + "]")[0].offsetTop;
$("#left").scrollTop(pos);
});
});
$(".matches").each(function() {
$(this).hover(function () {
$(this).toggleClass("hovering");
var hash = $(this).data("hash");
var side = $(this).parent("#left").length ? "#right" : "#left";
$(side + " > .matches[data-hash=" + hash + "]").toggleClass("hovering");
});
$(this).on("contextmenu", function(_) {
var hash = $(this).data("hash");
if ($(this).is("*[class*='selected']")) {
$(".matches[data-hash=" + hash + "]").removeClass(\_ c -> (c.match(/(^|\s)selected-\S+/) || []).join(' '));
} else {
$(".matches[data-hash=" + hash + "]").addClass(currentHighlight);
currentHighlight = nextHighlight(currentHighlight);
}
return false;
});
});
|]
renderPage :: H.Html -> H.Html
renderPage b = H.docTypeHtml $ mconcat
[ H.head $ mconcat
[ H.meta ! A.charset "utf-8"
, H.meta ! A.httpEquiv "X-UA-Compatible" ! A.content "IE=edge"
, H.meta ! A.name "viewport" ! A.content "width=device-width, initial-scale=1"
, H.title "Plagiarism Detection"
, H.style . H.toHtml $ C.renderWith C.R.compact [] stylesheet
]
, H.body $ mconcat
[ b
, H.script ! A.src "https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" $ ""
, H.script . hs $ renderJs javascript
]
]
| Submitty/AnalysisTools | src/Lichen/Plagiarism/Render.hs | bsd-3-clause | 4,602 | 0 | 14 | 1,542 | 735 | 396 | 339 | 49 | 1 |
{-# LANGUAGE GADTs, KindSignatures, RankNTypes, ScopedTypeVariables, StandaloneDeriving, FlexibleInstances #-}
module Binder where
import Expr
import Transport
data Bindee :: * -> * where
Temperature :: Bindee StringExpr
deriving instance Show (Bindee a)
instance Read (Bindee StringExpr) where
readsPrec d = readParen False $ \ r0 ->
[ (Temperature,r1)
| ("Temperature",r1) <- lex r0
]
evalBindee :: Bindee a -> IO a
evalBindee (Temperature) = return (Lit "76")
readBindeeReply :: Bindee a -> String -> a
readBindeeReply (Temperature {}) i = read i
evalBindeeEnv :: Env -> Id -> Bindee StringExpr -> IO Env
evalBindeeEnv env u p = do
r <- evalBindee p
let v = evalStringExpr env r
let env' = (u,v) : env
return env'
| ku-fpg/remote-monad-examples | classic-examples/Deep/Binder.hs | bsd-3-clause | 769 | 0 | 11 | 169 | 259 | 132 | 127 | 21 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Dir.Everything(module Data.List.Extra, module Dir.Everything) where
import Data.List.Extra
import Language.Haskell.TH.Syntax
import System.Timeout
usedFunction1 = undefined :: (T1 -> T1) -> ()
usedFunction2 = Other
unusedFunction = 12 :: Int
(=~=) a b = a == b -- used
(==~==) a b = a == b
class ClassWithFunc a where
classWithFunc :: a
data D1 = D1 {d1 :: Int}
data D2 = D2 {d2 :: Int}
data D3 = D3 {d3 :: Int}
data D4 = D4 {d4 :: Int}
data D5 = D5_ {d5 :: Int}
data D6 = D6_ Int
data D7 = D7 Int
type T1 = D1
type T2 = D2
data Other = Other
data Data
= Ctor1 {field1 :: Int, field2 :: Int, field3 :: Int}
| Ctor2 String
type Type = Data
data Orphan = Orphan
templateHaskell :: Int
templateHaskell = $(timeout `seq` lift (1 :: Int))
| ndmitchell/weeder | test/foo/src/Dir/Everything.hs | bsd-3-clause | 797 | 0 | 9 | 171 | 307 | 185 | 122 | 29 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
-- |
-- Module: $HEADER$
-- Description: Data type for RPM and DPKG package version
-- Copyright: (c) 2014 Peter Trsko
-- License: BSD3
--
-- Maintainer: [email protected]
-- Stability: experimental
-- Portability: DeriveDataTypeable, DeriveGeneric, NoImplicitPrelude
--
-- Data type for RPM and DPKG package version.
module Data.PkgVersion.Internal.PkgVersion
(
-- * PkgVersion
PkgVersion(..)
)
where
import Data.Bool (otherwise)
import Data.Data (Data)
import Data.Eq (Eq((==)))
import Data.Function ((.), flip)
import Data.Functor (Functor(fmap))
import Data.Monoid ((<>))
import Data.Typeable (Typeable)
import Data.Word (Word32)
import GHC.Generics (Generic)
import Text.Show (Show(show, showsPrec), showString)
import Data.Text as Strict (Text)
import Data.Text as Strict.Text (empty, null, pack, singleton)
import Data.Default.Class (Default(def))
import Data.PkgVersion.Class
( HasEpoch(epoch)
, HasVersion(version)
, HasRelease(release)
, Serializable(toStrictText, toString)
)
-- | Generic package version that works for both RPM and DPKG, but 'Data.Eq.Eq'
-- and 'Data.Ord.Ord' instances have to be defined separately for each.
--
-- It rerpresents version in format:
--
-- > [epoch:]version[-release]
--
-- Both RPM and DPKG use similar versioning scheme, therefore this data type is
-- used as basis for both 'Data.PkgVersion.Internal.RpmVersion.RpmVersion' and
-- 'Data.PkgVersion.Internal.DpkgVersion.DpkgVersion'.
data PkgVersion = PkgVersion
{ _pkgEpoch :: !Word32
, _pkgVersion :: !Strict.Text
, _pkgRelease :: !Strict.Text
}
deriving (Data, Generic, Typeable)
-- {{{ Instances for PkgVersion -----------------------------------------------
-- | Instance reflects the shared idea that if epoch is not present then it is
-- considered to be zero and that release may be empty:
--
-- @
-- 'def' = 'PkgVersion'
-- { '_pkgEpoch' = 0
-- , '_pkgVersion' = \"\"
-- , '_pkgRelease' = \"\"
-- }
-- @
instance Default PkgVersion where
def = PkgVersion
{ _pkgEpoch = 0
, _pkgVersion = Strict.Text.empty
, _pkgRelease = Strict.Text.empty
}
-- | Flipped version of 'fmap'. Not exported.
(<$$>) :: Functor f => f a -> (a -> b) -> f b
(<$$>) = flip fmap
{-# INLINE (<$$>) #-}
instance HasEpoch PkgVersion where
epoch f s@(PkgVersion{_pkgEpoch = a}) =
f a <$$> \b -> s{_pkgEpoch = b}
instance HasVersion PkgVersion where
version f s@(PkgVersion{_pkgVersion = a}) =
f a <$$> \b -> s{_pkgVersion = b}
instance HasRelease PkgVersion where
release f s@(PkgVersion{_pkgRelease = a}) =
f a <$$> \b -> s{_pkgRelease = b}
instance Serializable PkgVersion where
toStrictText (PkgVersion e v r) = e' <> v <> r'
where
colon = Strict.Text.singleton ':'
dash = Strict.Text.singleton '-'
e'
| e == 0 = Strict.Text.empty
| otherwise = Strict.Text.pack (show e) <> colon
r'
| Strict.Text.null r = Strict.Text.empty
| otherwise = dash <> r
instance Show PkgVersion where
showsPrec _ = showString . toString
-- }}} Instances for PkgVersion -----------------------------------------------
| trskop/pkg-version | src/Data/PkgVersion/Internal/PkgVersion.hs | bsd-3-clause | 3,367 | 0 | 12 | 729 | 716 | 431 | 285 | 64 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
module Language.Rsc.Liquid.Qualifiers (scrapeQuals) where
import Data.List (delete, nub)
import Data.Maybe (fromMaybe)
import Language.Fixpoint.Types hiding (quals)
import Language.Rsc.Annotations
import Language.Rsc.AST
import Language.Rsc.Core.Env
import Language.Rsc.Errors
import Language.Rsc.Liquid.Refinements
import Language.Rsc.Locations
import Language.Rsc.Names
import Language.Rsc.Pretty
import Language.Rsc.Program
import Language.Rsc.SystemUtils
import Language.Rsc.Traversals
import qualified Language.Rsc.Types as T
import Language.Rsc.Visitor
import Text.PrettyPrint.HughesPJ
-- | Extracts all qualifiers from a RefScript program
--
-- Excludes qualifier declarations (qualif Q(...): ...)
--
-- XXX: No need to do `mkUq` here, since we're dropping common bindings later.
--
---------------------------------------------------------------------------------
scrapeQuals :: RefScript -> [Qualifier]
---------------------------------------------------------------------------------
scrapeQuals (Rsc { code = Src ss }) =
qualifiers $ {- mkUq . -} foldStmts tbv [] [] $ filter nonLibFile ss
where
tbv = defaultVisitor { accStmt = gos, accCElt = goe, ctxStmt = ctx }
gos c (FunctionStmt l x _ _) = [(qualify c x, t) | SigAnn _ _ t <- fFact l]
gos c (VarDeclStmt _ vds) = [(qualify c x, t) | VarDecl l x _ <- vds
, VarAnn _ _ _ (Just t) <- fFact l]
gos _ _ = []
goe c (Constructor l _ _) = [(qualify c x, t) | CtorAnn t <- fFact l, let x = Id l "ctor" ]
goe c (MemberVarDecl l _ x _) = [(qualify c x, t) | MemberAnn (T.FI _ _ _ t) <- fFact l ]
goe c (MemberMethDecl l _ x _ _) = [(qualify c x, t) | MemberAnn (T.MI _ _ mts) <- fFact l, (_, t) <- mts ]
-- XXX: Use this perhaps to make the bindings unique
qualify _ (Id a x) = Id a x -- (mconcat c ++ x)
ctx c (ModuleStmt _ m _ ) = symbolString (symbol m) : c
ctx c (ClassStmt _ m _ ) = symbolString (symbol m) : c
ctx c _ = c
nonLibFile :: IsLocated a => Statement a -> Bool
nonLibFile = not . isDeclarationFile -- not . isSuffixOf ".d.ts" . srcSpanFile
-- mkUq = zipWith tx ([0..] :: [Int])
-- where
-- tx i (Id l s, t) = (Id l $ s ++ "_" ++ show i, t)
-- XXX: Will drop multiple bindings tp the same name
-- To fix, replace envFromList' with something else
--
qualifiers xts = concatMap (refTypeQualifiers γ0) xts
where
γ0 = envSEnv $ envMap rTypeSort $ envFromList' xts
refTypeQualifiers γ0 (l, t)
= efoldRType rTypeSort addQs γ0 [] t
where
addQs γ t qs = mkQuals l γ t ++ qs
mkQuals l γ t = [ mkQual l γ v so pa | pa <- conjuncts ra, noThis (syms pa) ]
where
RR so (Reft (v, ra)) = rTypeSortedReft t
noThis = all (not . isPrefixOfSym thisSym)
mkQual l γ v so p = Q (symbol "Auto") ((v, so) : yts) (subst θ p) l0
where
yts = [(y, lookupSort l x γ) | (x, y) <- xys ]
θ = mkSubst [(x, eVar y) | (x, y) <- xys]
xys = zipWith (\x i -> (x, symbol ("~A" ++ show i))) xs [0..]
xs = delete v $ orderedFreeVars γ p
l0 = sourcePos l
-- XXX: The error won't be triggered cause we've dropped multiple bidings
-- at `qualifiers`.
--
lookupSort l x γ = fromMaybe errorMsg $ lookupSEnv x γ
where
errorMsg = die $ bug (srcPos l) $ "Unbound variable " ++ show x ++ " in specification for " ++ show (unId l)
orderedFreeVars γ = nub . filter (`memberSEnv` γ) . syms
instance {-# OVERLAPPING #-} PP [Qualifier] where
pp = vcat . map toFix
-- pp qs = vcat $ map (\q -> pp (q_name q) <+> colon <+> pp (q_body q)) qs
instance PP Qualifier where
pp = toFix
| UCSD-PL/RefScript | src/Language/Rsc/Liquid/Qualifiers.hs | bsd-3-clause | 4,088 | 0 | 14 | 1,236 | 1,234 | 661 | 573 | 58 | 7 |
module Arbitrary where
import Test.QuickCheck
import qualified Data.ByteString.Lazy as BS
import Frenetic.Common
import Control.Monad
import Nettle.Arbitrary
import Frenetic.NetCore.Types hiding (Switch)
import qualified Frenetic.NetCore.Types as NetCore
import Frenetic.NetCore.Semantics
import Frenetic.Topo
arbPort :: Gen Port
arbPort = oneof [ return n | n <- [1 .. 5] ]
arbSwitch :: Gen Switch
arbSwitch = oneof [ return n | n <- [1 .. 10] ]
arbGenPktId :: Gen Id
arbGenPktId = oneof [ return 900, return 901, return 902 ]
arbCountersId :: Gen Id
arbCountersId = oneof [ return 500, return 501, return 502 ]
arbGetPktId :: Gen Id
arbGetPktId = oneof [ return 600, return 601, return 602 ]
arbMonSwitchId :: Gen Id
arbMonSwitchId = oneof [ return 700, return 701, return 702 ]
arbFwd :: Gen Act
arbFwd = liftM2 ActFwd arbitrary arbitrary
arbFwds :: Gen [Act]
arbFwds = oneof [ liftM2 (:) arbFwd arbFwds, return [] ]
arbInterval :: Gen Int
arbInterval = oneof [ return (-1), return 0, return 1, return 30 ]
instance Arbitrary Act where
arbitrary = oneof
[ arbFwd
, liftM2 ActQueryPktCounter arbCountersId arbInterval
, liftM2 ActQueryByteCounter arbCountersId arbInterval
, liftM ActGetPkt arbGetPktId
, liftM ActMonSwitch arbMonSwitchId
]
instance Arbitrary Modification where
arbitrary = sized $ \s -> frequency [ (2, return unmodified), (1, mod s) ]
where mod s = do
a1 <- if s < 1 then return Nothing else arbitrary
a2 <- if s < 2 then return Nothing else arbitrary
a3 <- if s < 3 then return Nothing else arbitrary
a4 <- if s < 4 then return Nothing else arbitrary
a5 <- if s < 5 then return Nothing else arbitrary
a6 <- if s < 6 then return Nothing else arbitrary
a7 <- if s < 7 then return Nothing else arbitrary
a8 <- if s < 8 then return Nothing else arbitrary
a9 <- if s < 9 then return Nothing else arbitrary
return (Modification a1 a2 a3 a4 a5 a6 a7 a8 a9)
instance Arbitrary Pol where
arbitrary = sized $ \s -> case s of
0 -> return PolEmpty
otherwise -> oneof
[ liftM2 PolProcessIn (resize (s-1) arbitrary) (resize (s-1) arbitrary)
, liftM2 PolUnion (resize (s-1) arbitrary) (resize (s-1) arbitrary)
-- , liftM2 PolSeq (resize (s-1) arbitrary) (resize (s-1) arbitrary)
, liftM2 PolRestrict (resize (s-1) arbitrary) (resize (s-1) arbitrary)
, liftM PolGenPacket (resize (s-1) arbGenPktId)
]
instance Arbitrary Predicate where
arbitrary = sized $ \s ->
let small =
[ liftM DlSrc arbitrary
, liftM DlDst arbitrary
, liftM DlTyp arbitrary
, liftM DlVlan arbitrary
, liftM DlVlanPcp arbitrary
, liftM NwSrc arbitrary
, liftM NwDst arbitrary
, liftM NwProto arbitrary
, liftM NwTos arbitrary
, liftM TpSrcPort arbitrary
, liftM TpDstPort arbitrary
, liftM IngressPort arbPort
, liftM NetCore.Switch arbSwitch
, return None
, return Any
]
large =
[ liftM2 Or (resize (s-1) arbitrary) (resize (s-1) arbitrary)
, liftM2 And (resize (s-1) arbitrary) (resize (s-1) arbitrary)
, liftM Not (resize (s-1) arbitrary)
]
in if s == 0 then oneof small else oneof (small ++ large)
instance Arbitrary Loc where
arbitrary = liftM2 Loc arbSwitch arbPort
expectsNwFields :: Word16 -> Bool
expectsNwFields 0x800 = True
expectsNwFields 0x806 = True
expectsNwFields _ = False
-- Does not generate ToQueue
instance Arbitrary PseudoPort where
arbitrary = frequency [ (5, liftM Physical arbPort)
, (1, return AllPorts)
]
instance Arbitrary ByteString where
arbitrary = return BS.empty
-- This isn't perfect, but we attempt to build a reasonable set of headers.
-- We favors building IP and ARP packets and fill out the Maybe-typed nw*
-- fields for IP and ARP packets.
instance Arbitrary Packet where
arbitrary = do
dlSrc <- arbitrary
dlDst <- arbitrary
-- generate IP and ARP packets most of the time
dlTyp <- frequency [(10, return 0x800), (5, return 0x806), (1, arbitrary)]
dlVlan <- arbitrary
dlVlanPcp <- arbitrary
let nwArbitrary :: Arbitrary a => Gen (Maybe a)
-- do not ever use NoMonmorphismRestriction
nwArbitrary = if expectsNwFields dlTyp then
liftM Just arbitrary
else
return Nothing
pktNwSrc <- nwArbitrary
pktNwDst <- nwArbitrary
pktNwProto <- arbitrary
pktNwTos <- arbitrary
pktTpSrc <- nwArbitrary
pktTpDst <- nwArbitrary
return (Packet dlSrc dlDst dlTyp dlVlan dlVlanPcp pktNwSrc pktNwDst
pktNwProto pktNwTos pktTpSrc pktTpDst)
arbInPkt = liftM3 InPkt arbitrary arbitrary (liftM Just arbitrary)
arbInGenPkt = liftM5 InGenPkt arbGenPktId arbSwitch arbitrary arbitrary
arbitrary
arbInCounters = liftM5 InCounters arbCountersId arbSwitch arbitrary
arbitrary arbitrary
-- TODO(arjun): arbInSwitchEvt
instance Arbitrary In where
arbitrary = oneof [ arbInPkt, arbInGenPkt, arbInCounters ]
| frenetic-lang/netcore-1.0 | testsuite/Arbitrary.hs | bsd-3-clause | 5,323 | 0 | 17 | 1,469 | 1,599 | 828 | 771 | 116 | 1 |
#!/usr/bin/env runhaskell
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-cse #-}
-- This program can crashed by attempting to read an uninitialized 'IORef' with incorrect user input (when he chooses not to input a line after the confirmation)
module Main where
import Data.IORef
import Data.Global
import System.IO
import Text.Printf
un "input" =:: (uninitialized, ut [t| String |] :: UT IORef)
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
putStr $ printf "This program prints its input (after the confirmation prompt). Would you like to provide input? [y/N]: "
getLine >>= \conf -> case conf of
('y':_) -> do
putStr $ "Input: "
getLine >>= writeIORef input
_ -> return ()
putStrLn . printf "The input: %s" =<< readIORef input
| bairyn/global | examples/uninitialized/Main.hs | bsd-3-clause | 815 | 0 | 15 | 189 | 164 | 84 | 80 | 18 | 2 |
{-# LANGUAGE DeriveDataTypeable, FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction, OverloadedStrings, TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module KeyFlags
(Masked(..), testCode, compatible, Keyboard(..),
decodeKeyboard, decodeModifiers, Modifier(..), encodeMask,
decodeFunctionKey, functionKeys, isAlphabeticModifier, _Char, _JIS) where
import KeyFlags.Macros
import Control.Applicative ((<$>))
import Control.Lens (makePrisms)
import Data.Bits
import qualified Data.Text.IO as T
import Foreign.C.Types
import Language.Haskell.TH (runIO)
do table <- runIO $ procLR . parse <$> T.readFile "data/keycodes.dat"
defineKeyCode "Keyboard" [t| CLong |] table
makePrisms ''Keyboard
decodeModifiers :: Mask Modifier -> [Modifier]
decodeModifiers b = [m | m <- modifiers, testCode m b]
encodeMask :: (Masked a, Num (Mask a)) => [a] -> Mask a
encodeMask = foldl (.|.) 0 . map toMask
data Modifier = AlphaShift
| Shift
| Control
| Alternate
| Command
| NumericPad
| HelpM
| Function
| Independent
deriving (Read, Show, Eq, Ord, Enum)
instance Masked Modifier where
type Mask Modifier = CULong
toMask AlphaShift = alphaShiftMask
toMask Alternate = alternateMask
toMask Shift = shiftMask
toMask Control = controlMask
toMask Command = commandMask
toMask NumericPad = numericPadMask
toMask HelpM = helpMask
toMask Function = functionMask
toMask Independent = independentMask
isAlphabeticModifier :: Modifier -> Bool
isAlphabeticModifier a = compatible Shift a || compatible AlphaShift a
modifiers :: [Modifier]
modifiers = [ AlphaShift
, Shift
, Control
, Alternate
, Command
, NumericPad
, HelpM
, Function
, Independent
]
alphaShiftMask :: Mask Modifier
alphaShiftMask = 1 `shiftL` 16
shiftMask :: Mask Modifier
shiftMask = 1 `shiftL` 17
controlMask :: Mask Modifier
controlMask = 1 `shiftL` 18
alternateMask :: Mask Modifier
alternateMask = 1 `shiftL` 19
commandMask :: Mask Modifier
commandMask = 1 `shiftL` 20
numericPadMask :: Mask Modifier
numericPadMask = 1 `shiftL` 21
helpMask :: Mask Modifier
helpMask = 1 `shiftL` 22
functionMask :: Mask Modifier
functionMask = 1 `shiftL` 23
independentMask :: Mask Modifier
independentMask = 0xffff0000
functionKeys :: [Keyboard]
functionKeys = case break (==Home) funs0 of
(as, bs) -> as ++ head bs : drop 2 bs
funs0 :: [Keyboard]
funs0 = [CursorUp
, CursorDown
, CursorLeft
, CursorRight
] ++ [ Fn n | n <- [1..35]] ++
[ PcInsert
, Delete
, Home
, undefined
, End
, Pageup
, Pagedown
, PcPrintscreen
, PcScrolllock
]
decodeFunctionKey :: Char -> Maybe Keyboard
decodeFunctionKey = flip lookup functionKeyDic
functionKeyDic :: [(Char, Keyboard)]
functionKeyDic =
case break ((== Home) . snd) $ zip ['\xF700'..] funs0 of
(as, bs) -> as ++ head bs : drop 2 bs
| konn/hskk | cocoa/KeyFlags.hs | bsd-3-clause | 3,268 | 0 | 10 | 951 | 876 | 497 | 379 | 96 | 1 |
module ProjectEuler.Problem225 (solution225) where
import Data.List
takeUntilSubSeq :: Eq a => [a] -> [a] -> [a]
takeUntilSubSeq _ [] = []
takeUntilSubSeq ss (x : xs) = if ss `isPrefixOf` xs
then [x]
else x : takeUntilSubSeq ss xs
modTribs :: Integer -> [Integer]
modTribs n = modTribs' 1 1 1
where modTribs' x y z = x : modTribs' y z ((x + y + z) `mod` n)
nonTribDivisor :: Integer -> Bool
nonTribDivisor = notElem 0 . takeUntilSubSeq [1, 1, 1] . modTribs
genericSolution225 :: Int -> Integer
genericSolution225 = (filter nonTribDivisor [1,3..] !!) . subtract 1
solution225 :: Integer
solution225 = genericSolution225 124
| guillaume-nargeot/project-euler-haskell | src/ProjectEuler/Problem225.hs | bsd-3-clause | 641 | 0 | 13 | 124 | 260 | 142 | 118 | 16 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module Test.Anemone.Foreign.Time where
import Anemone.Foreign.Time
import qualified Data.ByteString.Char8 as Char8
import Data.Thyme.Calendar (Day(..), YearMonthDay(..), gregorianValid)
import Disorder.Core.Run (ExpectedTestSpeed(..), disorderCheckEnvAll)
import Disorder.Jack (Property)
import Disorder.Jack ((===), gamble, arbitrary, choose, listOf)
import P
import Text.Printf (printf)
mkDay :: YearMonthDay -> Either TimeError Day
mkDay ymd =
case gregorianValid ymd of
Nothing ->
Left $ TimeInvalidDate ymd
Just day ->
Right day
prop_parseYearMonthDay :: Property
prop_parseYearMonthDay =
gamble (choose (0, 9999)) $ \y ->
gamble (choose (1, 12)) $ \m ->
gamble (choose (1, 31)) $ \d ->
gamble (listOf arbitrary) $ \xs ->
let
ymd =
YearMonthDay y m d
eymd =
fmap (const (ymd, Char8.pack xs)) $ mkDay ymd
str =
Char8.pack $ printf "%04d-%02d-%02d%s" y m d xs
in
parseYearMonthDay str === eymd
prop_parseDay :: Property
prop_parseDay =
gamble (choose (0, 9999)) $ \y ->
gamble (choose (1, 12)) $ \m ->
gamble (choose (1, 31)) $ \d ->
gamble (listOf arbitrary) $ \xs ->
let
ymd =
YearMonthDay y m d
eday =
fmap (, Char8.pack xs) $ mkDay ymd
str =
Char8.pack $ printf "%04d-%02d-%02d%s" y m d xs
in
parseDay str === eday
prop_parseRenderError :: Property
prop_parseRenderError =
gamble (choose (0, 9999)) $ \y ->
gamble (choose (1, 12)) $ \m ->
gamble (choose (1, 31)) $ \d ->
gamble (listOf arbitrary) $ \xs ->
let
ymd =
YearMonthDay y m d
eymd =
fmap (const (ymd, Char8.pack xs)) $ mkDay ymd
str =
Char8.pack $ printf "%04d-%02d-%02d%s" y m d xs
in
first renderTimeError (parseYearMonthDay str) === first renderTimeError eymd
return []
tests =
$disorderCheckEnvAll TestRunMore
| ambiata/anemone | test/Test/Anemone/Foreign/Time.hs | bsd-3-clause | 2,203 | 0 | 23 | 587 | 732 | 392 | 340 | 67 | 2 |
{-# LANGUAGE BangPatterns #-}
module PLY.Internal.StrictReplicate where
import Data.Vector.Generic (Vector, fromList)
import Data.Vector.Fusion.Bundle.Monadic (fromStream, toList)
import Data.Vector.Fusion.Bundle.Size (Size(..))
import Data.Vector.Fusion.Stream.Monadic (Stream (..), Step(..))
-- | Yield a 'Stream' of values obtained by performing the monadic
-- action the given number of times. Each value yielded by the monadic
-- action is evaluated to WHNF.
replicateStreamM' :: Monad m => Int -> m a -> Stream m a
{-# INLINE [1] replicateStreamM' #-}
replicateStreamM' n p = Stream step n
where
{-# INLINE [0] step #-}
step i | i <= 0 = return Done
| otherwise = do { !x <- p; return $ Yield x (i-1) }
-- |Execute the monadic action the given number of times and store the
-- results in a vector. Each value yielded by the monadic action is
-- evaluated to WHNF.
replicateM' :: (Monad m, Vector v a) => Int -> m a -> m (v a)
replicateM' n p = do let s = replicateStreamM' n p
xs <- toList (fromStream s (Exact n))
return (fromList xs)
{-# INLINE replicateM' #-}
| acowley/ply-loader | src/PLY/Internal/StrictReplicate.hs | bsd-3-clause | 1,137 | 0 | 13 | 247 | 295 | 161 | 134 | 17 | 1 |
module Language.Slice.Syntax.AST
( IncludeDelimiters(..)
, Ident(..)
, NsQualIdent(..)
, SliceType(..)
, SliceVal(..)
, SliceDecl(..)
-- , DefaultValue(..)
, Annotation(..)
, FieldDecl(..)
, MethodDecl(..)
, MethodOrFieldDecl(..)
) where
data IncludeDelimiters = AngleBrackets | Quotes deriving (Show, Read, Eq)
newtype Ident = Ident String deriving (Show, Read, Eq)
data NsQualIdent = NsQualIdent { name :: String, ns :: [String] }
deriving (Show, Read, Eq)
data SliceType = STVoid
| STBool | STByte | STShort | STInt | STLong
| STFloat | STDouble
| STString
| STUserDefined NsQualIdent
| STUserDefinedPrx NsQualIdent
deriving (Show, Read, Eq)
data SliceVal = SliceBool Bool
| SliceStr String
| SliceInteger Integer
| SliceDouble Double
| SliceIdentifier NsQualIdent
deriving (Show, Read, Eq)
data SliceDecl = ModuleDecl Ident [SliceDecl]
| IncludeDecl IncludeDelimiters String
| EnumDecl Ident [Ident]
| StructDecl Ident [FieldDecl]
| ClassDecl Ident (Maybe NsQualIdent) [MethodOrFieldDecl]
| InterfaceDecl Ident [NsQualIdent] [MethodDecl]
| InterfaceFDecl NsQualIdent
| SequenceDecl SliceType Ident
| DictionaryDecl SliceType SliceType Ident
| ExceptionDecl Ident [NsQualIdent] [FieldDecl]
| ConstDecl SliceType Ident SliceVal
deriving (Show, Read, Eq)
data Annotation = Idempotent deriving (Show, Read, Eq)
data FieldDecl = FieldDecl SliceType Ident (Maybe SliceVal) deriving (Show, Read, Eq)
data MethodDecl = MethodDecl SliceType Ident [FieldDecl] [NsQualIdent] (Maybe Annotation) deriving (Show, Read, Eq)
data MethodOrFieldDecl = MDecl MethodDecl | FDecl FieldDecl deriving (Show, Read, Eq)
| paulkoerbitz/language-slice | src/Language/Slice/Syntax/AST.hs | bsd-3-clause | 2,057 | 0 | 9 | 672 | 531 | 314 | 217 | 44 | 0 |
module Settings.Builders.Cabal (cabalBuilderArgs) where
import Hadrian.Builder (getBuilderPath, needBuilder)
import Hadrian.Haskell.Cabal
import Builder
import Context
import Flavour
import Packages
import Settings.Builders.Common
import qualified Settings.Builders.Common as S
cabalBuilderArgs :: Args
cabalBuilderArgs = builder (Cabal Setup) ? do
verbosity <- expr getVerbosity
top <- expr topDirectory
pkg <- getPackage
path <- getContextPath
stage <- getStage
let prefix = "${pkgroot}" ++ (if windowsHost then "" else "/..")
mconcat [ arg "configure"
-- Don't strip libraries when cross compiling.
-- TODO: We need to set @--with-strip=(stripCmdPath :: Action FilePath)@,
-- and if it's @:@ disable stripping as well. As it is now, I believe
-- we might have issues with stripping on Windows, as I can't see a
-- consumer of 'stripCmdPath'.
-- TODO: See https://github.com/snowleopard/hadrian/issues/549.
, flag CrossCompiling ? pure [ "--disable-executable-stripping"
, "--disable-library-stripping" ]
-- We don't want to strip the debug RTS
, S.package rts ? pure [ "--disable-executable-stripping"
, "--disable-library-stripping" ]
, arg "--cabal-file"
, arg $ pkgCabalFile pkg
, arg "--distdir"
, arg $ top -/- path
, arg "--ipid"
, arg "$pkg-$version"
, arg "--prefix"
, arg prefix
-- NB: this is valid only because Hadrian puts the @docs@ and
-- @libraries@ folders in the same relative position:
--
-- * libraries in @_build/stageN/libraries@
-- * docs in @_build/docs/html/libraries@
--
-- This doesn't hold if we move the @docs@ folder anywhere else.
, arg "--htmldir"
, arg $ "${pkgroot}/../../docs/html/libraries/" ++ pkgName pkg
, withStaged $ Ghc CompileHs
, withStaged (GhcPkg Update)
, withBuilderArgs (GhcPkg Update stage)
, bootPackageDatabaseArgs
, libraryArgs
, configureArgs
, bootPackageConstraints
, withStaged $ Cc CompileC
, notStage0 ? with (Ld stage)
, withStaged (Ar Pack)
, with Alex
, with Happy
, verbosity < Chatty ?
pure [ "-v0", "--configure-option=--quiet"
, "--configure-option=--disable-option-checking" ] ]
-- TODO: Isn't vanilla always built? If yes, some conditions are redundant.
-- TODO: Need compiler_stage1_CONFIGURE_OPTS += --disable-library-for-ghci?
-- TODO: should `elem` be `wayUnit`?
-- This approach still doesn't work. Previously libraries were build only in the
-- Default flavours and not using context.
libraryArgs :: Args
libraryArgs = do
flavourWays <- getLibraryWays
contextWay <- getWay
package <- getPackage
withGhci <- expr ghcWithInterpreter
dynPrograms <- expr (flavour >>= dynamicGhcPrograms)
let ways = flavourWays ++ [contextWay]
hasVanilla = vanilla `elem` ways
hasProfiling = any (wayUnit Profiling) ways
hasDynamic = any (wayUnit Dynamic) ways
pure [ if hasVanilla
then "--enable-library-vanilla"
else "--disable-library-vanilla"
, if hasProfiling
then "--enable-library-profiling"
else "--disable-library-profiling"
, if (hasVanilla || hasProfiling) &&
package /= rts && withGhci && not dynPrograms
then "--enable-library-for-ghci"
else "--disable-library-for-ghci"
, if hasDynamic
then "--enable-shared"
else "--disable-shared" ]
-- TODO: LD_OPTS?
configureArgs :: Args
configureArgs = do
top <- expr topDirectory
pkg <- getPackage
stage <- getStage
libPath <- expr $ stageLibPath stage
let conf key expr = do
values <- unwords <$> expr
not (null values) ?
arg ("--configure-option=" ++ key ++ "=" ++ values)
cFlags = mconcat [ remove ["-Werror"] cArgs
, getStagedSettingList ConfCcArgs
, arg $ "-I" ++ libPath
-- See https://github.com/snowleopard/hadrian/issues/523
, arg $ "-iquote"
, arg $ top -/- pkgPath pkg
, arg $ "-I" ++ top -/- "includes" ]
ldFlags = ldArgs <> (getStagedSettingList ConfGccLinkerArgs)
cppFlags = cppArgs <> (getStagedSettingList ConfCppArgs)
cldFlags <- unwords <$> (cFlags <> ldFlags)
mconcat
[ conf "CFLAGS" cFlags
, conf "LDFLAGS" ldFlags
, conf "CPPFLAGS" cppFlags
, not (null cldFlags) ? arg ("--gcc-options=" ++ cldFlags)
, conf "--with-iconv-includes" $ arg =<< getSetting IconvIncludeDir
, conf "--with-iconv-libraries" $ arg =<< getSetting IconvLibDir
, conf "--with-gmp-includes" $ arg =<< getSetting GmpIncludeDir
, conf "--with-gmp-libraries" $ arg =<< getSetting GmpLibDir
, conf "--with-curses-libraries" $ arg =<< getSetting CursesLibDir
, flag CrossCompiling ? (conf "--host" $ arg =<< getSetting TargetPlatformFull)
, conf "--with-cc" $ arg =<< getBuilderPath . (Cc CompileC) =<< getStage
, notStage0 ? (arg =<< ("--ghc-option=-ghcversion-file=" ++) <$> expr ((-/-) <$> topDirectory <*> ghcVersionH stage))]
bootPackageConstraints :: Args
bootPackageConstraints = stage0 ? do
bootPkgs <- expr $ stagePackages Stage0
let pkgs = filter (\p -> p /= compiler && isLibrary p) bootPkgs
constraints <- expr $ forM (sort pkgs) $ \pkg -> do
version <- pkgVersion pkg
return $ ((pkgName pkg ++ " == ") ++) version
pure $ concat [ ["--constraint", c] | c <- constraints ]
cppArgs :: Args
cppArgs = do
stage <- getStage
libPath <- expr $ stageLibPath stage
arg $ "-I" ++ libPath
withBuilderKey :: Builder -> String
withBuilderKey b = case b of
Ar _ _ -> "--with-ar="
Ld _ -> "--with-ld="
Cc _ _ -> "--with-gcc="
Ghc _ _ -> "--with-ghc="
Alex -> "--with-alex="
Happy -> "--with-happy="
GhcPkg _ _ -> "--with-ghc-pkg="
_ -> error $ "withBuilderKey: not supported builder " ++ show b
-- | Add arguments to builders if needed.
withBuilderArgs :: Builder -> Args
withBuilderArgs b = case b of
GhcPkg _ stage -> do
top <- expr topDirectory
pkgDb <- expr $ packageDbPath stage
notStage0 ? arg ("--ghc-pkg-option=--global-package-db=" ++ top -/- pkgDb)
_ -> return [] -- no arguments
-- | Expression 'with Alex' appends "--with-alex=/path/to/alex" and needs Alex.
with :: Builder -> Args
with b = do
path <- getBuilderPath b
if null path then mempty else do
top <- expr topDirectory
expr $ needBuilder b
arg $ withBuilderKey b ++ unifyPath (top </> path)
withStaged :: (Stage -> Builder) -> Args
withStaged sb = with . sb =<< getStage
| sdiehl/ghc | hadrian/src/Settings/Builders/Cabal.hs | bsd-3-clause | 7,325 | 0 | 18 | 2,267 | 1,578 | 804 | 774 | 142 | 8 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Distributed.Process.ManagedProcess.Timer
-- Copyright : (c) Tim Watson 2017
-- License : BSD3 (see the file LICENSE)
--
-- Maintainer : Tim Watson <[email protected]>
-- Stability : experimental
-- Portability : non-portable (requires concurrency)
--
-- This module provides a wrap around a simple 'Timer' that can be started,
-- stopped, reset, cleared, and read. A convenient function is provided for
-- creating a @Match@ expression for the timer.
--
-- [Notes]
--
-- The timers defined in this module are based on a @TVar Bool@. When the
-- client program is @-threaded@ (i.e. @rtsSupportsBoundThreads == True@), then
-- the timers are set using @registerDelay@, which is very efficient and relies
-- only no the RTS IO Manager. When we're not @-threaded@, we fall back to using
-- "Control.Distributed.Process.Extras.Timer" to set the @TVar@, which has much
-- the same effect, but requires us to spawn a process to handle setting the
-- @TVar@ - a process which could theoretically die before setting the variable.
--
module Control.Distributed.Process.ManagedProcess.Timer
( Timer(timerDelay)
, TimerKey
, delayTimer
, startTimer
, stopTimer
, resetTimer
, clearTimer
, matchTimeout
, matchKey
, matchRun
, isActive
, readTimer
, TimedOut(..)
) where
import Control.Concurrent (rtsSupportsBoundThreads)
import Control.Concurrent.STM hiding (check)
import Control.Distributed.Process
( matchSTM
, Process
, ProcessId
, Match
, Message
, liftIO
)
import qualified Control.Distributed.Process as P
( liftIO
)
import Control.Distributed.Process.Extras.Time (asTimeout, Delay(..))
import Control.Distributed.Process.Extras.Timer
( cancelTimer
, runAfter
, TimerRef
)
import Data.Binary (Binary)
import Data.Maybe (isJust, fromJust)
import Data.Typeable (Typeable)
import GHC.Conc (registerDelay)
import GHC.Generics
--------------------------------------------------------------------------------
-- Timeout Management --
--------------------------------------------------------------------------------
-- | A key for storing timers in prioritised process backing state.
type TimerKey = Int
-- | Used during STM reads on Timers and to implement blocking. Since timers
-- can be associated with a "TimerKey", the second constructor for this type
-- yields a key indicating whic "Timer" it refers to. Note that the user is
-- responsible for establishing and maintaining the mapping between @Timer@s
-- and their keys.
data TimedOut = TimedOut | Yield TimerKey
deriving (Eq, Show, Typeable, Generic)
instance Binary TimedOut where
-- | We hold timers in 2 states, each described by a Delay.
-- isActive = isJust . mtSignal
-- the TimerRef is optional since we only use the Timer module from extras
-- when we're unable to registerDelay (i.e. not running under -threaded)
data Timer = Timer { timerDelay :: Delay
, mtPidRef :: Maybe TimerRef
, mtSignal :: Maybe (TVar Bool)
}
-- | @True@ if a @Timer@ is currently active.
isActive :: Timer -> Bool
isActive = isJust . mtSignal
-- | Creates a default @Timer@ which is inactive.
delayTimer :: Delay -> Timer
delayTimer d = Timer d noPid noTVar
where
noPid = Nothing :: Maybe ProcessId
noTVar = Nothing :: Maybe (TVar Bool)
-- | Starts a @Timer@
-- Will use the GHC @registerDelay@ API if @rtsSupportsBoundThreads == True@
startTimer :: Delay -> Process Timer
startTimer d
| Delay t <- d = establishTimer t
| otherwise = return $ delayTimer d
where
establishTimer t'
| rtsSupportsBoundThreads = do sig <- liftIO $ registerDelay (asTimeout t')
return Timer { timerDelay = d
, mtPidRef = Nothing
, mtSignal = Just sig
}
| otherwise = do
tSig <- liftIO $ newTVarIO False
-- NB: runAfter spawns a process, which is defined in terms of
-- expectTimeout (asTimeout t) :: Process (Maybe CancelTimer)
--
tRef <- runAfter t' $ P.liftIO $ atomically $ writeTVar tSig True
return Timer { timerDelay = d
, mtPidRef = Just tRef
, mtSignal = Just tSig
}
-- | Stops a previously started @Timer@. Has no effect if the @Timer@ is inactive.
stopTimer :: Timer -> Process Timer
stopTimer t@Timer{..} = do
clearTimer mtPidRef
return t { mtPidRef = Nothing
, mtSignal = Nothing
}
-- | Clears and restarts a @Timer@.
resetTimer :: Timer -> Delay -> Process Timer
resetTimer Timer{..} d = clearTimer mtPidRef >> startTimer d
-- | Clears/cancels a running timer. Has no effect if the @Timer@ is inactive.
clearTimer :: Maybe TimerRef -> Process ()
clearTimer ref
| isJust ref = cancelTimer (fromJust ref)
| otherwise = return ()
-- | Creates a @Match@ for a given timer, for use with Cloud Haskell's messaging
-- primitives for selective receives.
matchTimeout :: Timer -> [Match (Either TimedOut Message)]
matchTimeout t@Timer{..}
| isActive t = [ matchSTM (readTimer $ fromJust mtSignal)
(return . Left) ]
| otherwise = []
-- | Create a match expression for a given @Timer@. When the timer expires
-- (i.e. the "TVar Bool" is set to @True@), the "Match" will return @Yield i@,
-- where @i@ is the given "TimerKey".
matchKey :: TimerKey -> Timer -> [Match (Either TimedOut Message)]
matchKey i t@Timer{..}
| isActive t = [matchSTM (readTVar (fromJust mtSignal) >>= \expired ->
if expired then return (Yield i) else retry)
(return . Left)]
| otherwise = []
-- | As "matchKey", but instead of a returning @Yield i@, the generated "Match"
-- handler evaluates the first argument - and expression from "TimerKey" to
-- @Process Message@ - to determine its result.
matchRun :: (TimerKey -> Process Message)
-> TimerKey
-> Timer
-> [Match Message]
matchRun f k t@Timer{..}
| isActive t = [matchSTM (readTVar (fromJust mtSignal) >>= \expired ->
if expired then return k else retry) f]
| otherwise = []
-- | Reads a given @TVar Bool@ for a timer, and returns @STM TimedOut@ once the
-- variable is set to true. Will @retry@ in the meanwhile.
readTimer :: TVar Bool -> STM TimedOut
readTimer t = do
expired <- readTVar t
if expired then return TimedOut
else retry
| haskell-distributed/distributed-process-client-server | src/Control/Distributed/Process/ManagedProcess/Timer.hs | bsd-3-clause | 7,031 | 0 | 14 | 1,811 | 1,146 | 634 | 512 | 107 | 2 |
module LetLang.Parser
( expression
, program
, parseProgram
) where
import Control.Monad (void)
import Data.Maybe (fromMaybe)
import LetLang.Data
import Text.Megaparsec
import Text.Megaparsec.Expr
import qualified Text.Megaparsec.Lexer as L
import Text.Megaparsec.String
parseProgram :: String -> Either String Program
parseProgram input = case runParser program "Program Parser" input of
Left err -> Left $ show err
Right p -> Right p
spaceConsumer :: Parser ()
spaceConsumer = L.space (void spaceChar) lineCmnt blockCmnt
where lineCmnt = L.skipLineComment "//"
blockCmnt = L.skipBlockComment "/*" "*/"
symbol = L.symbol spaceConsumer
parens = between (symbol "(") (symbol ")")
minus = symbol "-"
equal = symbol "="
comma = symbol ","
longArrow = symbol "==>"
lexeme :: Parser a -> Parser a
lexeme = L.lexeme spaceConsumer
keyWord :: String -> Parser ()
keyWord w = string w *> notFollowedBy alphaNumChar *> spaceConsumer
reservedWords :: [String]
reservedWords =
[ "let*", "let", "in", "if", "then", "else", "zero?", "minus"
, "equal?", "greater?", "less?", "cons", "car", "cdr", "emptyList"
, "list", "cond", "end"
]
binOpsMap :: [(String, BinOp)]
binOpsMap =
[ ("+", Add), ("-", Sub), ("*", Mul), ("/", Div), ("equal?", Eq)
, ("greater?", Gt), ("less?", Le), ("cons", Cons) ]
binOp :: Parser BinOp
binOp = do
opStr <- foldl1 (<|>) (fmap (try . symbol . fst) binOpsMap)
return $ fromMaybe
(error ("Unknown operator '" `mappend` opStr `mappend` "'"))
(lookup opStr binOpsMap)
unaryOpsMap :: [(String, UnaryOp)]
unaryOpsMap =
[ ("car", Car), ("cdr", Cdr), ("minus", Minus), ("zero?", IsZero) ]
unaryOp :: Parser UnaryOp
unaryOp = do
opStr <- foldl1 (<|>) (fmap (try . symbol . fst) unaryOpsMap)
return $ fromMaybe
(error ("Unknown operator '" `mappend` opStr `mappend` "'"))
(lookup opStr unaryOpsMap)
-- | Identifier ::= String (without reserved words)
identifier :: Parser String
identifier = lexeme (p >>= check)
where
p = (:) <$> letterChar <*> many alphaNumChar
check x = if x `elem` reservedWords
then fail $
concat ["keyword ", show x, " cannot be an identifier"]
else return x
integer :: Parser Integer
integer = lexeme L.integer
-- expressionPair ::= (Expression, Expression)
expressionPair :: Parser (Expression, Expression)
expressionPair = parens $ do
expr1 <- expression
comma
expr2 <- expression
return (expr1, expr2)
-- | ConstExpr ::= Number
constExpr :: Parser Expression
constExpr = ConstExpr . ExprNum <$> integer
-- | BinOpExpr ::= BinOp (Expression, Expression)
binOpExpr :: Parser Expression
binOpExpr = do
op <- binOp
exprPair <- expressionPair
return $ uncurry (BinOpExpr op) exprPair
-- | UnaryOpExpr ::= UnaryOp (Expression)
unaryOpExpr :: Parser Expression
unaryOpExpr = do
op <- unaryOp
expr <- parens expression
return $ UnaryOpExpr op expr
-- | IfExpr ::= if Expression then Expression
ifExpr :: Parser Expression
ifExpr = do
keyWord "if"
ifE <- expression
keyWord "then"
thenE <- expression
keyWord "else"
elseE <- expression
return $ CondExpr [(ifE, thenE), (ConstExpr (ExprBool True), elseE)]
-- | VarExpr ::= Identifier
varExpr :: Parser Expression
varExpr = VarExpr <$> identifier
-- | letStarExpr ::= let* {Identifier = Expression}* in Expression
letStarExpr :: Parser Expression
letStarExpr = letFamilyExpr "let*" LetStarExpr
-- | letExpr ::= let {Identifier = Expression}* in Expression
letExpr :: Parser Expression
letExpr = letFamilyExpr "let" LetExpr
letFamilyExpr :: String
-> ([(String, Expression)] -> Expression -> Expression)
-> Parser Expression
letFamilyExpr letType builder = do
keyWord letType
bindings <- many binding
keyWord "in"
body <- expression
return $ builder bindings body
where
binding = try $ do
var <- identifier
equal
val <- expression
return (var, val)
-- | ManyExprs ::= <empty>
-- ::= Many1Exprs
manyExprs :: Parser [Expression]
manyExprs = sepBy expression comma
-- | Many1Exprs ::= Expression
-- ::= Expression , Many1Exprs
many1Exprs :: Parser [Expression]
many1Exprs = sepBy1 expression comma
-- | ListExpr ::= list (ListItems)
listExpr :: Parser Expression
listExpr = do
keyWord "list"
ListExpr <$> parens manyExprs
-- | EmptyListExpr ::= emptyList
emptyListExpr :: Parser Expression
emptyListExpr = keyWord "emptyList" >> return EmptyListExpr
-- | CondExpr ::= cond {Expression ==> Expression}* end
condExpr :: Parser Expression
condExpr = do
keyWord "cond"
pairs <- many pair
keyWord "end"
return $ CondExpr pairs
where
pair = try $ do
expr1 <- expression
longArrow
expr2 <- expression
return (expr1, expr2)
-- | Expression ::= ConstExpr
-- ::= BinOpExpr
-- ::= UnaryOpExpr
-- ::= IfExpr
-- ::= CondExpr
-- ::= VarExpr
-- ::= LetStarExpr
-- ::= LetExpr
-- ::= EmptyListExpr
-- ::= ListExpr
expression :: Parser Expression
expression = try constExpr
<|> try binOpExpr
<|> try unaryOpExpr
<|> try ifExpr
<|> try condExpr
<|> try varExpr
<|> try letStarExpr
<|> try letExpr
<|> try emptyListExpr
<|> try listExpr
program :: Parser Program
program = do
spaceConsumer
expr <- expression
eof
return $ Prog expr
| li-zhirui/EoplLangs | src/LetLang/Parser.hs | bsd-3-clause | 5,590 | 0 | 14 | 1,365 | 1,549 | 815 | 734 | 147 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Actions.Submap
-- Copyright : (c) Jason Creighton <[email protected]>
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Jason Creighton <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- A module that allows the user to create a sub-mapping of key bindings.
--
-----------------------------------------------------------------------------
module XMonad.Actions.Submap (
-- * Usage
-- $usage
submap,
submapDefault
) where
import Data.Bits
import XMonad hiding (keys)
import qualified Data.Map as M
import Control.Monad.Fix (fix)
{- $usage
First, import this module into your @~\/.xmonad\/xmonad.hs@:
> import XMonad.Actions.Submap
Allows you to create a sub-mapping of keys. Example:
> , ((modm, xK_a), submap . M.fromList $
> [ ((0, xK_n), spawn "mpc next")
> , ((0, xK_p), spawn "mpc prev")
> , ((0, xK_z), spawn "mpc random")
> , ((0, xK_space), spawn "mpc toggle")
> ])
So, for example, to run 'spawn \"mpc next\"', you would hit mod-a (to
trigger the submapping) and then 'n' to run that action. (0 means \"no
modifier\"). You are, of course, free to use any combination of
modifiers in the submapping. However, anyModifier will not work,
because that is a special value passed to XGrabKey() and not an actual
modifier.
For detailed instructions on editing your key bindings, see
"XMonad.Doc.Extending#Editing_key_bindings".
-}
-- | Given a 'Data.Map.Map' from key bindings to X () actions, return
-- an action which waits for a user keypress and executes the
-- corresponding action, or does nothing if the key is not found in
-- the map.
submap :: M.Map (KeyMask, KeySym) (X ()) -> X ()
submap keys = submapDefault (return ()) keys
-- | Like 'submap', but executes a default action if the key did not match.
submapDefault :: X () -> M.Map (KeyMask, KeySym) (X ()) -> X ()
submapDefault def keys = do
XConf { theRoot = root, display = d } <- ask
io $ grabKeyboard d root False grabModeAsync grabModeAsync currentTime
(m, s) <- io $ allocaXEvent $ \p -> fix $ \nextkey -> do
maskEvent d keyPressMask p
KeyEvent { ev_keycode = code, ev_state = m } <- getEvent p
keysym <- keycodeToKeysym d code 0
if isModifierKey keysym
then nextkey
else return (m, keysym)
-- Remove num lock mask and Xkb group state bits
m' <- cleanMask $ m .&. ((1 `shiftL` 12) - 1)
maybe def id (M.lookup (m', s) keys)
io $ ungrabKeyboard d currentTime
| MasseR/xmonadcontrib | XMonad/Actions/Submap.hs | bsd-3-clause | 2,784 | 0 | 17 | 718 | 398 | 219 | 179 | 23 | 2 |
{-# LANGUAGE TemplateHaskell, GADTs #-}
module Input where
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.GADT.Compare.TH
import Foreign.C.Types (CDouble(..))
import GHC.Float (float2Double)
import qualified SFML.Window as SFML
circleMass, circleRadius :: Num a => a
circleMass = 10
circleRadius = 20
isPress :: SFML.SFEvent -> Bool
isPress SFML.SFEvtKeyPressed {} = True
isPress _ = False
isRelease :: SFML.SFEvent -> Bool
isRelease SFML.SFEvtKeyReleased {} = True
isRelease _ = False
eventKeycode :: SFML.SFEvent -> SFML.KeyCode
eventKeycode = SFML.code
isKey :: SFML.KeyCode -> SFML.SFEvent -> Bool
isKey keycode = (== keycode) . eventKeycode
isKeyPressed :: SFML.KeyCode -> SFML.SFEvent -> Bool
isKeyPressed key event = isPress event && isKey key event
isCtrlKeyPressed :: SFML.KeyCode -> SFML.SFEvent -> Bool
isCtrlKeyPressed key event = isKeyPressed key event && SFML.ctrl event
wasButtonPressed :: Int -> SFML.SFEvent -> Bool
wasButtonPressed button (SFML.SFEvtJoystickButtonPressed _ b) = button == b
wasButtonPressed _ _ = False
data GamepadInput = GamepadInput
{ leftXAxis :: CDouble
, leftYAxis :: CDouble
, rightXAxis :: CDouble
, yPressed :: Bool
}
initialInput :: GamepadInput
initialInput = GamepadInput
{ leftXAxis = 0
, leftYAxis = 0
, rightXAxis = 0
, yPressed = False
}
type JoystickID = Int
data JoystickAxis = JoyLX | JoyLY | JoyRX
sfmlAxisIndex :: JoystickAxis -> Int
sfmlAxisIndex JoyLX = 0
sfmlAxisIndex JoyLY = 1
sfmlAxisIndex JoyRX = 4
-- TODO: check
padButtonA, padButtonB, padButtonX, padButtonY :: Int
padButtonA = 0
padButtonB = 1
padButtonX = 2
padButtonY = 3
padTriggerLeft, padTriggerRight, padButtonBack, padButtonStart :: Int
padTriggerLeft = 4
padTriggerRight = 5
padButtonBack = 6
padButtonStart = 7
padButtonHome, padLeftStick, padRightStick :: Int
padButtonHome = 8
padLeftStick = 9
padRightStick = 10
pollInput :: MonadIO m => Maybe JoystickID -> m GamepadInput
pollInput mGamepad =
let deadzone v = if abs v < 0.15 then 0 else v
getAxis g a = fmap (/100) $ liftIO $ SFML.getAxisPosition g $ sfmlAxisIndex a
in case mGamepad of
Nothing -> return initialInput
Just gamepad -> do
currentLeftXAxis <- getAxis gamepad JoyLX
currentLeftYAxis <- getAxis gamepad JoyLY
currentRightXAxis <- getAxis gamepad JoyRX
currentYPressed <- liftIO $ SFML.isJoystickButtonPressed gamepad padButtonY
return GamepadInput
{ leftXAxis = CDouble $ float2Double $ deadzone currentLeftXAxis
, leftYAxis = CDouble $ float2Double $ deadzone currentLeftYAxis
, rightXAxis = CDouble $ float2Double $ deadzone currentRightXAxis
, yPressed = currentYPressed
}
data SfmlEventTag a where
JoyAxisEvent :: JoystickID -> SfmlEventTag SFML.SFEvent
JoyButtonEvent :: JoystickID -> SfmlEventTag SFML.SFEvent
KeyEvent :: SfmlEventTag SFML.SFEvent
OtherEvent :: SfmlEventTag SFML.SFEvent
deriveGEq ''SfmlEventTag
deriveGCompare ''SfmlEventTag
| Emmatipate/ava | src/Input.hs | bsd-3-clause | 3,140 | 0 | 16 | 690 | 846 | 461 | 385 | 81 | 3 |
module StringCompressorKata.Day1Spec (spec) where
import Test.Hspec
import StringCompressorKata.Day1 (compress)
spec :: Spec
spec = do
it "compresses nothing to empty string" $ do
compress Nothing `shouldBe` ""
it "compresses empty string to empty string" $ do
compress (Just "") `shouldBe` ""
it "compresses one char string" $ do
compress (Just "a") `shouldBe` "1a"
it "compresses string of unique characters" $ do
compress (Just "abc") `shouldBe` "1a1b1c"
it "compress string of repeated characters" $ do
compress (Just "aabbcc") `shouldBe` "2a2b2c"
| Alex-Diez/haskell-tdd-kata | old-katas/test/StringCompressorKata/Day1Spec.hs | bsd-3-clause | 674 | 0 | 13 | 201 | 170 | 84 | 86 | 15 | 1 |
{-# LANGUAGE TypeFamilies #-}
module QualifiedMethods where
import qualified ExportListWildcards as ExportListWildcards
import qualified DataFamilies as DataFamilies
import OtherClass
data Rodor = Rodor
x :: ExportListWildcards.Foo
x = ExportListWildcards.Foo1
instance ExportListWildcards.Bar Rodor where
x Rodor = x
instance DataFamilies.ListLike Rodor where
type I Rodor = Rodor
h _ = Rodor
| phischu/fragnix | tests/quick/QualifiedAssociates/QualifiedMethods.hs | bsd-3-clause | 413 | 0 | 6 | 69 | 86 | 51 | 35 | 13 | 1 |
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
module Data.Type.BitRecords2.Writer.ByteStringBuilder where
| sheyll/isobmff-builder | src/Data/Type/BitRecords2/Writer/ByteStringBuilder.hs | bsd-3-clause | 152 | 0 | 3 | 13 | 11 | 9 | 2 | 3 | 0 |
{-# LANGUAGE CPP, TypeFamilies #-}
-----------------------------------------------------------------------------
--
-- Machine-dependent assembly language
--
-- (c) The University of Glasgow 1993-2004
--
-----------------------------------------------------------------------------
module X86.Instr (Instr(..), Operand(..), PrefetchVariant(..), JumpDest,
getJumpDestBlockId, canShortcut, shortcutStatics,
shortcutJump, i386_insert_ffrees, allocMoreStack,
maxSpillSlots, archWordFormat)
where
#include "HsVersions.h"
#include "nativeGen/NCG.h"
import GhcPrelude
import X86.Cond
import X86.Regs
import Instruction
import Format
import RegClass
import Reg
import TargetReg
import BlockId
import Hoopl.Collections
import Hoopl.Label
import CodeGen.Platform
import Cmm
import FastString
import Outputable
import Platform
import BasicTypes (Alignment)
import CLabel
import DynFlags
import UniqSet
import Unique
import UniqSupply
import Debug (UnwindTable)
import Control.Monad
import Data.Maybe (fromMaybe)
-- Format of an x86/x86_64 memory address, in bytes.
--
archWordFormat :: Bool -> Format
archWordFormat is32Bit
| is32Bit = II32
| otherwise = II64
-- | Instruction instance for x86 instruction set.
instance Instruction Instr where
regUsageOfInstr = x86_regUsageOfInstr
patchRegsOfInstr = x86_patchRegsOfInstr
isJumpishInstr = x86_isJumpishInstr
jumpDestsOfInstr = x86_jumpDestsOfInstr
patchJumpInstr = x86_patchJumpInstr
mkSpillInstr = x86_mkSpillInstr
mkLoadInstr = x86_mkLoadInstr
takeDeltaInstr = x86_takeDeltaInstr
isMetaInstr = x86_isMetaInstr
mkRegRegMoveInstr = x86_mkRegRegMoveInstr
takeRegRegMoveInstr = x86_takeRegRegMoveInstr
mkJumpInstr = x86_mkJumpInstr
mkStackAllocInstr = x86_mkStackAllocInstr
mkStackDeallocInstr = x86_mkStackDeallocInstr
-- -----------------------------------------------------------------------------
-- Intel x86 instructions
{-
Intel, in their infinite wisdom, selected a stack model for floating
point registers on x86. That might have made sense back in 1979 --
nowadays we can see it for the nonsense it really is. A stack model
fits poorly with the existing nativeGen infrastructure, which assumes
flat integer and FP register sets. Prior to this commit, nativeGen
could not generate correct x86 FP code -- to do so would have meant
somehow working the register-stack paradigm into the register
allocator and spiller, which sounds very difficult.
We have decided to cheat, and go for a simple fix which requires no
infrastructure modifications, at the expense of generating ropey but
correct FP code. All notions of the x86 FP stack and its insns have
been removed. Instead, we pretend (to the instruction selector and
register allocator) that x86 has six floating point registers, %fake0
.. %fake5, which can be used in the usual flat manner. We further
claim that x86 has floating point instructions very similar to SPARC
and Alpha, that is, a simple 3-operand register-register arrangement.
Code generation and register allocation proceed on this basis.
When we come to print out the final assembly, our convenient fiction
is converted to dismal reality. Each fake instruction is
independently converted to a series of real x86 instructions.
%fake0 .. %fake5 are mapped to %st(0) .. %st(5). To do reg-reg
arithmetic operations, the two operands are pushed onto the top of the
FP stack, the operation done, and the result copied back into the
relevant register. There are only six %fake registers because 2 are
needed for the translation, and x86 has 8 in total.
The translation is inefficient but is simple and it works. A cleverer
translation would handle a sequence of insns, simulating the FP stack
contents, would not impose a fixed mapping from %fake to %st regs, and
hopefully could avoid most of the redundant reg-reg moves of the
current translation.
We might as well make use of whatever unique FP facilities Intel have
chosen to bless us with (let's not be churlish, after all).
Hence GLDZ and GLD1. Bwahahahahahahaha!
-}
{-
Note [x86 Floating point precision]
Intel's internal floating point registers are by default 80 bit
extended precision. This means that all operations done on values in
registers are done at 80 bits, and unless the intermediate values are
truncated to the appropriate size (32 or 64 bits) by storing in
memory, calculations in registers will give different results from
calculations which pass intermediate values in memory (eg. via
function calls).
One solution is to set the FPU into 64 bit precision mode. Some OSs
do this (eg. FreeBSD) and some don't (eg. Linux). The problem here is
that this will only affect 64-bit precision arithmetic; 32-bit
calculations will still be done at 64-bit precision in registers. So
it doesn't solve the whole problem.
There's also the issue of what the C library is expecting in terms of
precision. It seems to be the case that glibc on Linux expects the
FPU to be set to 80 bit precision, so setting it to 64 bit could have
unexpected effects. Changing the default could have undesirable
effects on other 3rd-party library code too, so the right thing would
be to save/restore the FPU control word across Haskell code if we were
to do this.
gcc's -ffloat-store gives consistent results by always storing the
results of floating-point calculations in memory, which works for both
32 and 64-bit precision. However, it only affects the values of
user-declared floating point variables in C, not intermediate results.
GHC in -fvia-C mode uses -ffloat-store (see the -fexcess-precision
flag).
Another problem is how to spill floating point registers in the
register allocator. Should we spill the whole 80 bits, or just 64?
On an OS which is set to 64 bit precision, spilling 64 is fine. On
Linux, spilling 64 bits will round the results of some operations.
This is what gcc does. Spilling at 80 bits requires taking up a full
128 bit slot (so we get alignment). We spill at 80-bits and ignore
the alignment problems.
In the future [edit: now available in GHC 7.0.1, with the -msse2
flag], we'll use the SSE registers for floating point. This requires
a CPU that supports SSE2 (ordinary SSE only supports 32 bit precision
float ops), which means P4 or Xeon and above. Using SSE will solve
all these problems, because the SSE registers use fixed 32 bit or 64
bit precision.
--SDM 1/2003
-}
data Instr
-- comment pseudo-op
= COMMENT FastString
-- location pseudo-op (file, line, col, name)
| LOCATION Int Int Int String
-- some static data spat out during code
-- generation. Will be extracted before
-- pretty-printing.
| LDATA Section (Alignment, CmmStatics)
-- start a new basic block. Useful during
-- codegen, removed later. Preceding
-- instruction should be a jump, as per the
-- invariants for a BasicBlock (see Cmm).
| NEWBLOCK BlockId
-- unwinding information
-- See Note [Unwinding information in the NCG].
| UNWIND CLabel UnwindTable
-- specify current stack offset for benefit of subsequent passes.
-- This carries a BlockId so it can be used in unwinding information.
| DELTA Int
-- Moves.
| MOV Format Operand Operand
| CMOV Cond Format Operand Reg
| MOVZxL Format Operand Operand -- format is the size of operand 1
| MOVSxL Format Operand Operand -- format is the size of operand 1
-- x86_64 note: plain mov into a 32-bit register always zero-extends
-- into the 64-bit reg, in contrast to the 8 and 16-bit movs which
-- don't affect the high bits of the register.
-- Load effective address (also a very useful three-operand add instruction :-)
| LEA Format Operand Operand
-- Int Arithmetic.
| ADD Format Operand Operand
| ADC Format Operand Operand
| SUB Format Operand Operand
| SBB Format Operand Operand
| MUL Format Operand Operand
| MUL2 Format Operand -- %edx:%eax = operand * %rax
| IMUL Format Operand Operand -- signed int mul
| IMUL2 Format Operand -- %edx:%eax = operand * %eax
| DIV Format Operand -- eax := eax:edx/op, edx := eax:edx%op
| IDIV Format Operand -- ditto, but signed
-- Int Arithmetic, where the effects on the condition register
-- are important. Used in specialized sequences such as MO_Add2.
-- Do not rewrite these instructions to "equivalent" ones that
-- have different effect on the condition register! (See #9013.)
| ADD_CC Format Operand Operand
| SUB_CC Format Operand Operand
-- Simple bit-twiddling.
| AND Format Operand Operand
| OR Format Operand Operand
| XOR Format Operand Operand
| NOT Format Operand
| NEGI Format Operand -- NEG instruction (name clash with Cond)
| BSWAP Format Reg
-- Shifts (amount may be immediate or %cl only)
| SHL Format Operand{-amount-} Operand
| SAR Format Operand{-amount-} Operand
| SHR Format Operand{-amount-} Operand
| BT Format Imm Operand
| NOP
-- x86 Float Arithmetic.
-- Note that we cheat by treating G{ABS,MOV,NEG} of doubles
-- as single instructions right up until we spit them out.
-- all the 3-operand fake fp insns are src1 src2 dst
-- and furthermore are constrained to be fp regs only.
-- IMPORTANT: keep is_G_insn up to date with any changes here
| GMOV Reg Reg -- src(fpreg), dst(fpreg)
| GLD Format AddrMode Reg -- src, dst(fpreg)
| GST Format Reg AddrMode -- src(fpreg), dst
| GLDZ Reg -- dst(fpreg)
| GLD1 Reg -- dst(fpreg)
| GFTOI Reg Reg -- src(fpreg), dst(intreg)
| GDTOI Reg Reg -- src(fpreg), dst(intreg)
| GITOF Reg Reg -- src(intreg), dst(fpreg)
| GITOD Reg Reg -- src(intreg), dst(fpreg)
| GDTOF Reg Reg -- src(fpreg), dst(fpreg)
| GADD Format Reg Reg Reg -- src1, src2, dst
| GDIV Format Reg Reg Reg -- src1, src2, dst
| GSUB Format Reg Reg Reg -- src1, src2, dst
| GMUL Format Reg Reg Reg -- src1, src2, dst
-- FP compare. Cond must be `elem` [EQQ, NE, LE, LTT, GE, GTT]
-- Compare src1 with src2; set the Zero flag iff the numbers are
-- comparable and the comparison is True. Subsequent code must
-- test the %eflags zero flag regardless of the supplied Cond.
| GCMP Cond Reg Reg -- src1, src2
| GABS Format Reg Reg -- src, dst
| GNEG Format Reg Reg -- src, dst
| GSQRT Format Reg Reg -- src, dst
| GSIN Format CLabel CLabel Reg Reg -- src, dst
| GCOS Format CLabel CLabel Reg Reg -- src, dst
| GTAN Format CLabel CLabel Reg Reg -- src, dst
| GFREE -- do ffree on all x86 regs; an ugly hack
-- SSE2 floating point: we use a restricted set of the available SSE2
-- instructions for floating-point.
-- use MOV for moving (either movss or movsd (movlpd better?))
| CVTSS2SD Reg Reg -- F32 to F64
| CVTSD2SS Reg Reg -- F64 to F32
| CVTTSS2SIQ Format Operand Reg -- F32 to I32/I64 (with truncation)
| CVTTSD2SIQ Format Operand Reg -- F64 to I32/I64 (with truncation)
| CVTSI2SS Format Operand Reg -- I32/I64 to F32
| CVTSI2SD Format Operand Reg -- I32/I64 to F64
-- use ADD, SUB, and SQRT for arithmetic. In both cases, operands
-- are Operand Reg.
-- SSE2 floating-point division:
| FDIV Format Operand Operand -- divisor, dividend(dst)
-- use CMP for comparisons. ucomiss and ucomisd instructions
-- compare single/double prec floating point respectively.
| SQRT Format Operand Reg -- src, dst
-- Comparison
| TEST Format Operand Operand
| CMP Format Operand Operand
| SETCC Cond Operand
-- Stack Operations.
| PUSH Format Operand
| POP Format Operand
-- both unused (SDM):
-- | PUSHA
-- | POPA
-- Jumping around.
| JMP Operand [Reg] -- including live Regs at the call
| JXX Cond BlockId -- includes unconditional branches
| JXX_GBL Cond Imm -- non-local version of JXX
-- Table jump
| JMP_TBL Operand -- Address to jump to
[Maybe BlockId] -- Blocks in the jump table
Section -- Data section jump table should be put in
CLabel -- Label of jump table
| CALL (Either Imm Reg) [Reg]
-- Other things.
| CLTD Format -- sign extend %eax into %edx:%eax
| FETCHGOT Reg -- pseudo-insn for ELF position-independent code
-- pretty-prints as
-- call 1f
-- 1: popl %reg
-- addl __GLOBAL_OFFSET_TABLE__+.-1b, %reg
| FETCHPC Reg -- pseudo-insn for Darwin position-independent code
-- pretty-prints as
-- call 1f
-- 1: popl %reg
-- bit counting instructions
| POPCNT Format Operand Reg -- [SSE4.2] count number of bits set to 1
| BSF Format Operand Reg -- bit scan forward
| BSR Format Operand Reg -- bit scan reverse
-- prefetch
| PREFETCH PrefetchVariant Format Operand -- prefetch Variant, addr size, address to prefetch
-- variant can be NTA, Lvl0, Lvl1, or Lvl2
| LOCK Instr -- lock prefix
| XADD Format Operand Operand -- src (r), dst (r/m)
| CMPXCHG Format Operand Operand -- src (r), dst (r/m), eax implicit
| MFENCE
data PrefetchVariant = NTA | Lvl0 | Lvl1 | Lvl2
data Operand
= OpReg Reg -- register
| OpImm Imm -- immediate value
| OpAddr AddrMode -- memory reference
-- | Returns which registers are read and written as a (read, written)
-- pair.
x86_regUsageOfInstr :: Platform -> Instr -> RegUsage
x86_regUsageOfInstr platform instr
= case instr of
MOV _ src dst -> usageRW src dst
CMOV _ _ src dst -> mkRU (use_R src [dst]) [dst]
MOVZxL _ src dst -> usageRW src dst
MOVSxL _ src dst -> usageRW src dst
LEA _ src dst -> usageRW src dst
ADD _ src dst -> usageRM src dst
ADC _ src dst -> usageRM src dst
SUB _ src dst -> usageRM src dst
SBB _ src dst -> usageRM src dst
IMUL _ src dst -> usageRM src dst
IMUL2 _ src -> mkRU (eax:use_R src []) [eax,edx]
MUL _ src dst -> usageRM src dst
MUL2 _ src -> mkRU (eax:use_R src []) [eax,edx]
DIV _ op -> mkRU (eax:edx:use_R op []) [eax,edx]
IDIV _ op -> mkRU (eax:edx:use_R op []) [eax,edx]
ADD_CC _ src dst -> usageRM src dst
SUB_CC _ src dst -> usageRM src dst
AND _ src dst -> usageRM src dst
OR _ src dst -> usageRM src dst
XOR _ (OpReg src) (OpReg dst)
| src == dst -> mkRU [] [dst]
XOR _ src dst -> usageRM src dst
NOT _ op -> usageM op
BSWAP _ reg -> mkRU [reg] [reg]
NEGI _ op -> usageM op
SHL _ imm dst -> usageRM imm dst
SAR _ imm dst -> usageRM imm dst
SHR _ imm dst -> usageRM imm dst
BT _ _ src -> mkRUR (use_R src [])
PUSH _ op -> mkRUR (use_R op [])
POP _ op -> mkRU [] (def_W op)
TEST _ src dst -> mkRUR (use_R src $! use_R dst [])
CMP _ src dst -> mkRUR (use_R src $! use_R dst [])
SETCC _ op -> mkRU [] (def_W op)
JXX _ _ -> mkRU [] []
JXX_GBL _ _ -> mkRU [] []
JMP op regs -> mkRUR (use_R op regs)
JMP_TBL op _ _ _ -> mkRUR (use_R op [])
CALL (Left _) params -> mkRU params (callClobberedRegs platform)
CALL (Right reg) params -> mkRU (reg:params) (callClobberedRegs platform)
CLTD _ -> mkRU [eax] [edx]
NOP -> mkRU [] []
GMOV src dst -> mkRU [src] [dst]
GLD _ src dst -> mkRU (use_EA src []) [dst]
GST _ src dst -> mkRUR (src : use_EA dst [])
GLDZ dst -> mkRU [] [dst]
GLD1 dst -> mkRU [] [dst]
GFTOI src dst -> mkRU [src] [dst]
GDTOI src dst -> mkRU [src] [dst]
GITOF src dst -> mkRU [src] [dst]
GITOD src dst -> mkRU [src] [dst]
GDTOF src dst -> mkRU [src] [dst]
GADD _ s1 s2 dst -> mkRU [s1,s2] [dst]
GSUB _ s1 s2 dst -> mkRU [s1,s2] [dst]
GMUL _ s1 s2 dst -> mkRU [s1,s2] [dst]
GDIV _ s1 s2 dst -> mkRU [s1,s2] [dst]
GCMP _ src1 src2 -> mkRUR [src1,src2]
GABS _ src dst -> mkRU [src] [dst]
GNEG _ src dst -> mkRU [src] [dst]
GSQRT _ src dst -> mkRU [src] [dst]
GSIN _ _ _ src dst -> mkRU [src] [dst]
GCOS _ _ _ src dst -> mkRU [src] [dst]
GTAN _ _ _ src dst -> mkRU [src] [dst]
CVTSS2SD src dst -> mkRU [src] [dst]
CVTSD2SS src dst -> mkRU [src] [dst]
CVTTSS2SIQ _ src dst -> mkRU (use_R src []) [dst]
CVTTSD2SIQ _ src dst -> mkRU (use_R src []) [dst]
CVTSI2SS _ src dst -> mkRU (use_R src []) [dst]
CVTSI2SD _ src dst -> mkRU (use_R src []) [dst]
FDIV _ src dst -> usageRM src dst
SQRT _ src dst -> mkRU (use_R src []) [dst]
FETCHGOT reg -> mkRU [] [reg]
FETCHPC reg -> mkRU [] [reg]
COMMENT _ -> noUsage
LOCATION{} -> noUsage
UNWIND{} -> noUsage
DELTA _ -> noUsage
POPCNT _ src dst -> mkRU (use_R src []) [dst]
BSF _ src dst -> mkRU (use_R src []) [dst]
BSR _ src dst -> mkRU (use_R src []) [dst]
-- note: might be a better way to do this
PREFETCH _ _ src -> mkRU (use_R src []) []
LOCK i -> x86_regUsageOfInstr platform i
XADD _ src dst -> usageMM src dst
CMPXCHG _ src dst -> usageRMM src dst (OpReg eax)
MFENCE -> noUsage
_other -> panic "regUsage: unrecognised instr"
where
-- # Definitions
--
-- Written: If the operand is a register, it's written. If it's an
-- address, registers mentioned in the address are read.
--
-- Modified: If the operand is a register, it's both read and
-- written. If it's an address, registers mentioned in the address
-- are read.
-- 2 operand form; first operand Read; second Written
usageRW :: Operand -> Operand -> RegUsage
usageRW op (OpReg reg) = mkRU (use_R op []) [reg]
usageRW op (OpAddr ea) = mkRUR (use_R op $! use_EA ea [])
usageRW _ _ = panic "X86.RegInfo.usageRW: no match"
-- 2 operand form; first operand Read; second Modified
usageRM :: Operand -> Operand -> RegUsage
usageRM op (OpReg reg) = mkRU (use_R op [reg]) [reg]
usageRM op (OpAddr ea) = mkRUR (use_R op $! use_EA ea [])
usageRM _ _ = panic "X86.RegInfo.usageRM: no match"
-- 2 operand form; first operand Modified; second Modified
usageMM :: Operand -> Operand -> RegUsage
usageMM (OpReg src) (OpReg dst) = mkRU [src, dst] [src, dst]
usageMM (OpReg src) (OpAddr ea) = mkRU (use_EA ea [src]) [src]
usageMM _ _ = panic "X86.RegInfo.usageMM: no match"
-- 3 operand form; first operand Read; second Modified; third Modified
usageRMM :: Operand -> Operand -> Operand -> RegUsage
usageRMM (OpReg src) (OpReg dst) (OpReg reg) = mkRU [src, dst, reg] [dst, reg]
usageRMM (OpReg src) (OpAddr ea) (OpReg reg) = mkRU (use_EA ea [src, reg]) [reg]
usageRMM _ _ _ = panic "X86.RegInfo.usageRMM: no match"
-- 1 operand form; operand Modified
usageM :: Operand -> RegUsage
usageM (OpReg reg) = mkRU [reg] [reg]
usageM (OpAddr ea) = mkRUR (use_EA ea [])
usageM _ = panic "X86.RegInfo.usageM: no match"
-- Registers defd when an operand is written.
def_W (OpReg reg) = [reg]
def_W (OpAddr _ ) = []
def_W _ = panic "X86.RegInfo.def_W: no match"
-- Registers used when an operand is read.
use_R (OpReg reg) tl = reg : tl
use_R (OpImm _) tl = tl
use_R (OpAddr ea) tl = use_EA ea tl
-- Registers used to compute an effective address.
use_EA (ImmAddr _ _) tl = tl
use_EA (AddrBaseIndex base index _) tl =
use_base base $! use_index index tl
where use_base (EABaseReg r) tl = r : tl
use_base _ tl = tl
use_index EAIndexNone tl = tl
use_index (EAIndex i _) tl = i : tl
mkRUR src = src' `seq` RU src' []
where src' = filter (interesting platform) src
mkRU src dst = src' `seq` dst' `seq` RU src' dst'
where src' = filter (interesting platform) src
dst' = filter (interesting platform) dst
-- | Is this register interesting for the register allocator?
interesting :: Platform -> Reg -> Bool
interesting _ (RegVirtual _) = True
interesting platform (RegReal (RealRegSingle i)) = freeReg platform i
interesting _ (RegReal (RealRegPair{})) = panic "X86.interesting: no reg pairs on this arch"
-- | Applies the supplied function to all registers in instructions.
-- Typically used to change virtual registers to real registers.
x86_patchRegsOfInstr :: Instr -> (Reg -> Reg) -> Instr
x86_patchRegsOfInstr instr env
= case instr of
MOV fmt src dst -> patch2 (MOV fmt) src dst
CMOV cc fmt src dst -> CMOV cc fmt (patchOp src) (env dst)
MOVZxL fmt src dst -> patch2 (MOVZxL fmt) src dst
MOVSxL fmt src dst -> patch2 (MOVSxL fmt) src dst
LEA fmt src dst -> patch2 (LEA fmt) src dst
ADD fmt src dst -> patch2 (ADD fmt) src dst
ADC fmt src dst -> patch2 (ADC fmt) src dst
SUB fmt src dst -> patch2 (SUB fmt) src dst
SBB fmt src dst -> patch2 (SBB fmt) src dst
IMUL fmt src dst -> patch2 (IMUL fmt) src dst
IMUL2 fmt src -> patch1 (IMUL2 fmt) src
MUL fmt src dst -> patch2 (MUL fmt) src dst
MUL2 fmt src -> patch1 (MUL2 fmt) src
IDIV fmt op -> patch1 (IDIV fmt) op
DIV fmt op -> patch1 (DIV fmt) op
ADD_CC fmt src dst -> patch2 (ADD_CC fmt) src dst
SUB_CC fmt src dst -> patch2 (SUB_CC fmt) src dst
AND fmt src dst -> patch2 (AND fmt) src dst
OR fmt src dst -> patch2 (OR fmt) src dst
XOR fmt src dst -> patch2 (XOR fmt) src dst
NOT fmt op -> patch1 (NOT fmt) op
BSWAP fmt reg -> BSWAP fmt (env reg)
NEGI fmt op -> patch1 (NEGI fmt) op
SHL fmt imm dst -> patch1 (SHL fmt imm) dst
SAR fmt imm dst -> patch1 (SAR fmt imm) dst
SHR fmt imm dst -> patch1 (SHR fmt imm) dst
BT fmt imm src -> patch1 (BT fmt imm) src
TEST fmt src dst -> patch2 (TEST fmt) src dst
CMP fmt src dst -> patch2 (CMP fmt) src dst
PUSH fmt op -> patch1 (PUSH fmt) op
POP fmt op -> patch1 (POP fmt) op
SETCC cond op -> patch1 (SETCC cond) op
JMP op regs -> JMP (patchOp op) regs
JMP_TBL op ids s lbl -> JMP_TBL (patchOp op) ids s lbl
GMOV src dst -> GMOV (env src) (env dst)
GLD fmt src dst -> GLD fmt (lookupAddr src) (env dst)
GST fmt src dst -> GST fmt (env src) (lookupAddr dst)
GLDZ dst -> GLDZ (env dst)
GLD1 dst -> GLD1 (env dst)
GFTOI src dst -> GFTOI (env src) (env dst)
GDTOI src dst -> GDTOI (env src) (env dst)
GITOF src dst -> GITOF (env src) (env dst)
GITOD src dst -> GITOD (env src) (env dst)
GDTOF src dst -> GDTOF (env src) (env dst)
GADD fmt s1 s2 dst -> GADD fmt (env s1) (env s2) (env dst)
GSUB fmt s1 s2 dst -> GSUB fmt (env s1) (env s2) (env dst)
GMUL fmt s1 s2 dst -> GMUL fmt (env s1) (env s2) (env dst)
GDIV fmt s1 s2 dst -> GDIV fmt (env s1) (env s2) (env dst)
GCMP fmt src1 src2 -> GCMP fmt (env src1) (env src2)
GABS fmt src dst -> GABS fmt (env src) (env dst)
GNEG fmt src dst -> GNEG fmt (env src) (env dst)
GSQRT fmt src dst -> GSQRT fmt (env src) (env dst)
GSIN fmt l1 l2 src dst -> GSIN fmt l1 l2 (env src) (env dst)
GCOS fmt l1 l2 src dst -> GCOS fmt l1 l2 (env src) (env dst)
GTAN fmt l1 l2 src dst -> GTAN fmt l1 l2 (env src) (env dst)
CVTSS2SD src dst -> CVTSS2SD (env src) (env dst)
CVTSD2SS src dst -> CVTSD2SS (env src) (env dst)
CVTTSS2SIQ fmt src dst -> CVTTSS2SIQ fmt (patchOp src) (env dst)
CVTTSD2SIQ fmt src dst -> CVTTSD2SIQ fmt (patchOp src) (env dst)
CVTSI2SS fmt src dst -> CVTSI2SS fmt (patchOp src) (env dst)
CVTSI2SD fmt src dst -> CVTSI2SD fmt (patchOp src) (env dst)
FDIV fmt src dst -> FDIV fmt (patchOp src) (patchOp dst)
SQRT fmt src dst -> SQRT fmt (patchOp src) (env dst)
CALL (Left _) _ -> instr
CALL (Right reg) p -> CALL (Right (env reg)) p
FETCHGOT reg -> FETCHGOT (env reg)
FETCHPC reg -> FETCHPC (env reg)
NOP -> instr
COMMENT _ -> instr
LOCATION {} -> instr
UNWIND {} -> instr
DELTA _ -> instr
JXX _ _ -> instr
JXX_GBL _ _ -> instr
CLTD _ -> instr
POPCNT fmt src dst -> POPCNT fmt (patchOp src) (env dst)
BSF fmt src dst -> BSF fmt (patchOp src) (env dst)
BSR fmt src dst -> BSR fmt (patchOp src) (env dst)
PREFETCH lvl format src -> PREFETCH lvl format (patchOp src)
LOCK i -> LOCK (x86_patchRegsOfInstr i env)
XADD fmt src dst -> patch2 (XADD fmt) src dst
CMPXCHG fmt src dst -> patch2 (CMPXCHG fmt) src dst
MFENCE -> instr
_other -> panic "patchRegs: unrecognised instr"
where
patch1 :: (Operand -> a) -> Operand -> a
patch1 insn op = insn $! patchOp op
patch2 :: (Operand -> Operand -> a) -> Operand -> Operand -> a
patch2 insn src dst = (insn $! patchOp src) $! patchOp dst
patchOp (OpReg reg) = OpReg $! env reg
patchOp (OpImm imm) = OpImm imm
patchOp (OpAddr ea) = OpAddr $! lookupAddr ea
lookupAddr (ImmAddr imm off) = ImmAddr imm off
lookupAddr (AddrBaseIndex base index disp)
= ((AddrBaseIndex $! lookupBase base) $! lookupIndex index) disp
where
lookupBase EABaseNone = EABaseNone
lookupBase EABaseRip = EABaseRip
lookupBase (EABaseReg r) = EABaseReg $! env r
lookupIndex EAIndexNone = EAIndexNone
lookupIndex (EAIndex r i) = (EAIndex $! env r) i
--------------------------------------------------------------------------------
x86_isJumpishInstr
:: Instr -> Bool
x86_isJumpishInstr instr
= case instr of
JMP{} -> True
JXX{} -> True
JXX_GBL{} -> True
JMP_TBL{} -> True
CALL{} -> True
_ -> False
x86_jumpDestsOfInstr
:: Instr
-> [BlockId]
x86_jumpDestsOfInstr insn
= case insn of
JXX _ id -> [id]
JMP_TBL _ ids _ _ -> [id | Just id <- ids]
_ -> []
x86_patchJumpInstr
:: Instr -> (BlockId -> BlockId) -> Instr
x86_patchJumpInstr insn patchF
= case insn of
JXX cc id -> JXX cc (patchF id)
JMP_TBL op ids section lbl
-> JMP_TBL op (map (fmap patchF) ids) section lbl
_ -> insn
-- -----------------------------------------------------------------------------
-- | Make a spill instruction.
x86_mkSpillInstr
:: DynFlags
-> Reg -- register to spill
-> Int -- current stack delta
-> Int -- spill slot to use
-> Instr
x86_mkSpillInstr dflags reg delta slot
= let off = spillSlotToOffset platform slot - delta
in
case targetClassOfReg platform reg of
RcInteger -> MOV (archWordFormat is32Bit)
(OpReg reg) (OpAddr (spRel dflags off))
RcDouble -> GST FF80 reg (spRel dflags off) {- RcFloat/RcDouble -}
RcDoubleSSE -> MOV FF64 (OpReg reg) (OpAddr (spRel dflags off))
_ -> panic "X86.mkSpillInstr: no match"
where platform = targetPlatform dflags
is32Bit = target32Bit platform
-- | Make a spill reload instruction.
x86_mkLoadInstr
:: DynFlags
-> Reg -- register to load
-> Int -- current stack delta
-> Int -- spill slot to use
-> Instr
x86_mkLoadInstr dflags reg delta slot
= let off = spillSlotToOffset platform slot - delta
in
case targetClassOfReg platform reg of
RcInteger -> MOV (archWordFormat is32Bit)
(OpAddr (spRel dflags off)) (OpReg reg)
RcDouble -> GLD FF80 (spRel dflags off) reg {- RcFloat/RcDouble -}
RcDoubleSSE -> MOV FF64 (OpAddr (spRel dflags off)) (OpReg reg)
_ -> panic "X86.x86_mkLoadInstr"
where platform = targetPlatform dflags
is32Bit = target32Bit platform
spillSlotSize :: Platform -> Int
spillSlotSize dflags = if is32Bit then 12 else 8
where is32Bit = target32Bit dflags
maxSpillSlots :: DynFlags -> Int
maxSpillSlots dflags
= ((rESERVED_C_STACK_BYTES dflags - 64) `div` spillSlotSize (targetPlatform dflags)) - 1
-- = 0 -- useful for testing allocMoreStack
-- number of bytes that the stack pointer should be aligned to
stackAlign :: Int
stackAlign = 16
-- convert a spill slot number to a *byte* offset, with no sign:
-- decide on a per arch basis whether you are spilling above or below
-- the C stack pointer.
spillSlotToOffset :: Platform -> Int -> Int
spillSlotToOffset platform slot
= 64 + spillSlotSize platform * slot
--------------------------------------------------------------------------------
-- | See if this instruction is telling us the current C stack delta
x86_takeDeltaInstr
:: Instr
-> Maybe Int
x86_takeDeltaInstr instr
= case instr of
DELTA i -> Just i
_ -> Nothing
x86_isMetaInstr
:: Instr
-> Bool
x86_isMetaInstr instr
= case instr of
COMMENT{} -> True
LOCATION{} -> True
LDATA{} -> True
NEWBLOCK{} -> True
UNWIND{} -> True
DELTA{} -> True
_ -> False
-- | Make a reg-reg move instruction.
-- On SPARC v8 there are no instructions to move directly between
-- floating point and integer regs. If we need to do that then we
-- have to go via memory.
--
x86_mkRegRegMoveInstr
:: Platform
-> Reg
-> Reg
-> Instr
x86_mkRegRegMoveInstr platform src dst
= case targetClassOfReg platform src of
RcInteger -> case platformArch platform of
ArchX86 -> MOV II32 (OpReg src) (OpReg dst)
ArchX86_64 -> MOV II64 (OpReg src) (OpReg dst)
_ -> panic "x86_mkRegRegMoveInstr: Bad arch"
RcDouble -> GMOV src dst
RcDoubleSSE -> MOV FF64 (OpReg src) (OpReg dst)
_ -> panic "X86.RegInfo.mkRegRegMoveInstr: no match"
-- | Check whether an instruction represents a reg-reg move.
-- The register allocator attempts to eliminate reg->reg moves whenever it can,
-- by assigning the src and dest temporaries to the same real register.
--
x86_takeRegRegMoveInstr
:: Instr
-> Maybe (Reg,Reg)
x86_takeRegRegMoveInstr (MOV _ (OpReg r1) (OpReg r2))
= Just (r1,r2)
x86_takeRegRegMoveInstr _ = Nothing
-- | Make an unconditional branch instruction.
x86_mkJumpInstr
:: BlockId
-> [Instr]
x86_mkJumpInstr id
= [JXX ALWAYS id]
x86_mkStackAllocInstr
:: Platform
-> Int
-> Instr
x86_mkStackAllocInstr platform amount
= case platformArch platform of
ArchX86 -> SUB II32 (OpImm (ImmInt amount)) (OpReg esp)
ArchX86_64 -> SUB II64 (OpImm (ImmInt amount)) (OpReg rsp)
_ -> panic "x86_mkStackAllocInstr"
x86_mkStackDeallocInstr
:: Platform
-> Int
-> Instr
x86_mkStackDeallocInstr platform amount
= case platformArch platform of
ArchX86 -> ADD II32 (OpImm (ImmInt amount)) (OpReg esp)
ArchX86_64 -> ADD II64 (OpImm (ImmInt amount)) (OpReg rsp)
_ -> panic "x86_mkStackDeallocInstr"
i386_insert_ffrees
:: [GenBasicBlock Instr]
-> [GenBasicBlock Instr]
i386_insert_ffrees blocks
| any (any is_G_instr) [ instrs | BasicBlock _ instrs <- blocks ]
= map insertGFREEs blocks
| otherwise
= blocks
where
insertGFREEs (BasicBlock id insns)
= BasicBlock id (insertBeforeNonlocalTransfers GFREE insns)
insertBeforeNonlocalTransfers :: Instr -> [Instr] -> [Instr]
insertBeforeNonlocalTransfers insert insns
= foldr p [] insns
where p insn r = case insn of
CALL _ _ -> insert : insn : r
JMP _ _ -> insert : insn : r
JXX_GBL _ _ -> panic "insertBeforeNonlocalTransfers: cannot handle JXX_GBL"
_ -> insn : r
-- if you ever add a new FP insn to the fake x86 FP insn set,
-- you must update this too
is_G_instr :: Instr -> Bool
is_G_instr instr
= case instr of
GMOV{} -> True
GLD{} -> True
GST{} -> True
GLDZ{} -> True
GLD1{} -> True
GFTOI{} -> True
GDTOI{} -> True
GITOF{} -> True
GITOD{} -> True
GDTOF{} -> True
GADD{} -> True
GDIV{} -> True
GSUB{} -> True
GMUL{} -> True
GCMP{} -> True
GABS{} -> True
GNEG{} -> True
GSQRT{} -> True
GSIN{} -> True
GCOS{} -> True
GTAN{} -> True
GFREE -> panic "is_G_instr: GFREE (!)"
_ -> False
--
-- Note [extra spill slots]
--
-- If the register allocator used more spill slots than we have
-- pre-allocated (rESERVED_C_STACK_BYTES), then we must allocate more
-- C stack space on entry and exit from this proc. Therefore we
-- insert a "sub $N, %rsp" at every entry point, and an "add $N, %rsp"
-- before every non-local jump.
--
-- This became necessary when the new codegen started bundling entire
-- functions together into one proc, because the register allocator
-- assigns a different stack slot to each virtual reg within a proc.
-- To avoid using so many slots we could also:
--
-- - split up the proc into connected components before code generator
--
-- - rename the virtual regs, so that we re-use vreg names and hence
-- stack slots for non-overlapping vregs.
--
-- Note that when a block is both a non-local entry point (with an
-- info table) and a local branch target, we have to split it into
-- two, like so:
--
-- <info table>
-- L:
-- <code>
--
-- becomes
--
-- <info table>
-- L:
-- subl $rsp, N
-- jmp Lnew
-- Lnew:
-- <code>
--
-- and all branches pointing to L are retargetted to point to Lnew.
-- Otherwise, we would repeat the $rsp adjustment for each branch to
-- L.
--
allocMoreStack
:: Platform
-> Int
-> NatCmmDecl statics X86.Instr.Instr
-> UniqSM (NatCmmDecl statics X86.Instr.Instr)
allocMoreStack _ _ top@(CmmData _ _) = return top
allocMoreStack platform slots proc@(CmmProc info lbl live (ListGraph code)) = do
let entries = entryBlocks proc
uniqs <- replicateM (length entries) getUniqueM
let
delta = ((x + stackAlign - 1) `quot` stackAlign) * stackAlign -- round up
where x = slots * spillSlotSize platform -- sp delta
alloc = mkStackAllocInstr platform delta
dealloc = mkStackDeallocInstr platform delta
new_blockmap :: LabelMap BlockId
new_blockmap = mapFromList (zip entries (map mkBlockId uniqs))
insert_stack_insns (BasicBlock id insns)
| Just new_blockid <- mapLookup id new_blockmap
= [ BasicBlock id [alloc, JXX ALWAYS new_blockid]
, BasicBlock new_blockid block' ]
| otherwise
= [ BasicBlock id block' ]
where
block' = foldr insert_dealloc [] insns
insert_dealloc insn r = case insn of
JMP _ _ -> dealloc : insn : r
JXX_GBL _ _ -> panic "insert_dealloc: cannot handle JXX_GBL"
_other -> x86_patchJumpInstr insn retarget : r
where retarget b = fromMaybe b (mapLookup b new_blockmap)
new_code = concatMap insert_stack_insns code
-- in
return (CmmProc info lbl live (ListGraph new_code))
data JumpDest = DestBlockId BlockId | DestImm Imm
getJumpDestBlockId :: JumpDest -> Maybe BlockId
getJumpDestBlockId (DestBlockId bid) = Just bid
getJumpDestBlockId _ = Nothing
canShortcut :: Instr -> Maybe JumpDest
canShortcut (JXX ALWAYS id) = Just (DestBlockId id)
canShortcut (JMP (OpImm imm) _) = Just (DestImm imm)
canShortcut _ = Nothing
-- This helper shortcuts a sequence of branches.
-- The blockset helps avoid following cycles.
shortcutJump :: (BlockId -> Maybe JumpDest) -> Instr -> Instr
shortcutJump fn insn = shortcutJump' fn (setEmpty :: LabelSet) insn
where shortcutJump' fn seen insn@(JXX cc id) =
if setMember id seen then insn
else case fn id of
Nothing -> insn
Just (DestBlockId id') -> shortcutJump' fn seen' (JXX cc id')
Just (DestImm imm) -> shortcutJump' fn seen' (JXX_GBL cc imm)
where seen' = setInsert id seen
shortcutJump' _ _ other = other
-- Here because it knows about JumpDest
shortcutStatics :: (BlockId -> Maybe JumpDest) -> (Alignment, CmmStatics) -> (Alignment, CmmStatics)
shortcutStatics fn (align, Statics lbl statics)
= (align, Statics lbl $ map (shortcutStatic fn) statics)
-- we need to get the jump tables, so apply the mapping to the entries
-- of a CmmData too.
shortcutLabel :: (BlockId -> Maybe JumpDest) -> CLabel -> CLabel
shortcutLabel fn lab
| Just blkId <- maybeLocalBlockLabel lab = shortBlockId fn emptyUniqSet blkId
| otherwise = lab
shortcutStatic :: (BlockId -> Maybe JumpDest) -> CmmStatic -> CmmStatic
shortcutStatic fn (CmmStaticLit (CmmLabel lab))
= CmmStaticLit (CmmLabel (shortcutLabel fn lab))
shortcutStatic fn (CmmStaticLit (CmmLabelDiffOff lbl1 lbl2 off))
= CmmStaticLit (CmmLabelDiffOff (shortcutLabel fn lbl1) lbl2 off)
-- slightly dodgy, we're ignoring the second label, but this
-- works with the way we use CmmLabelDiffOff for jump tables now.
shortcutStatic _ other_static
= other_static
shortBlockId
:: (BlockId -> Maybe JumpDest)
-> UniqSet Unique
-> BlockId
-> CLabel
shortBlockId fn seen blockid =
case (elementOfUniqSet uq seen, fn blockid) of
(True, _) -> blockLbl blockid
(_, Nothing) -> blockLbl blockid
(_, Just (DestBlockId blockid')) -> shortBlockId fn (addOneToUniqSet seen uq) blockid'
(_, Just (DestImm (ImmCLbl lbl))) -> lbl
(_, _other) -> panic "shortBlockId"
where uq = getUnique blockid
| ezyang/ghc | compiler/nativeGen/X86/Instr.hs | bsd-3-clause | 40,860 | 0 | 17 | 12,981 | 9,638 | 4,884 | 4,754 | 626 | 102 |
--
--
--
----------------
-- Exercise 6.9.
----------------
--
--
--
module E'6''9 where
import E'6''8 ( rotate90 )
import Pictures ( Picture )
import Data.List ( transpose )
-- If picture is rectangular:
rotate90anticlockwise :: Picture -> [[Char]]
rotate90anticlockwise picture
= reverse (transpose picture)
-- Other solution for "rotate90anticlockwise":
rotate90anticlockwise' :: Picture -> [[Char]]
rotate90anticlockwise' picture
= (rotate90 . rotate90 . rotate90) picture
| pascal-knodel/haskell-craft | _/links/E'6''9.hs | mit | 500 | 0 | 8 | 87 | 110 | 67 | 43 | 10 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
module TallyHo.CountMinSketchC (
module TallyHo.CountMinSketch
, countMinSketchC
) where
import ClassyPrelude.Conduit
import TallyHo.CountMinSketch
countMinSketchC :: (PrimMonad m, Hashable a) => Int -> Int -> Sink a m (CountMinSketch a)
countMinSketchC d wShift = do
ss <- lift $ cmsNew d wShift
awaitForever $ lift . cmsAdd ss
lift $ cmsUnsafeFreeze ss
| non/tallyho | src/main/haskell/TallyHo/CountMinSketchC.hs | apache-2.0 | 402 | 0 | 10 | 67 | 119 | 61 | 58 | 11 | 1 |
module TypeInference1 where
-- f x y=x+y+3
myConcat x = x ++ "yo"
myMult x = (x/3)*5
myCom x = x > (length [1..10])
myAlph x = x < 'z'
triple :: Int -> Int
triple x = x * 3
x=5
-- y=x+5
-- w=y*10
-- x=5
-- y=x+5
-- f=4/y
-- bigNum= (^)5 $ 10
-- a=(+)
-- b=5
-- -- c=b 10
-- -- d=c 200
-- a=12+b
-- b=10000*c
functionH (x:_) = x
functionC x y = if (x > y) then True else False
foo1 x y = y
foo2 x y = x
r x = tail x
| punitrathore/haskell-first-principles | src/typeInference1.hs | bsd-3-clause | 433 | 0 | 8 | 122 | 180 | 101 | 79 | 13 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
module Test.Basement.UTF8
( tests )
where
import Basement.Types.CharUTF8
import Foundation
import Foundation.Check
import Foundation.String
tests = Group "utf8"
[ Property "CharUTF8" $ \c -> decodeCharUTF8 (encodeCharUTF8 c) === c
]
| vincenthz/hs-foundation | foundation/tests/Test/Basement/UTF8.hs | bsd-3-clause | 436 | 0 | 12 | 82 | 74 | 44 | 30 | 13 | 1 |
Subsets and Splits