code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Seats ( Seats
-- * Accessor
, getNum
-- * Our errors
, Error(..)
-- * Smart constructor
, make
) where
import Data.Validation
-- | Wrapper around 'Int' that ensures always positive.
newtype Seats = Seats { getNum :: Int }
deriving (Show, Eq)
data Error = BadCount Int -- ^ attempted number of seats
deriving (Eq)
instance Show Error where
show (BadCount seats) = "number of seats was " ++ show seats ++
", but must be positive"
-- | Smart constructor for 'Seats' that
-- ensures always positive.
make :: Int -> Validation Error Seats
make seats | seats <= 0 = Failure $ BadCount seats
| otherwise = Success $ Seats seats
|
pittsburgh-haskell/data-validation-demo-haskell
|
src/Seats.hs
|
bsd-3-clause
| 756 | 0 | 8 | 245 | 162 | 90 | 72 | 15 | 1 |
{-# LANGUAGE TypeFamilies, FlexibleInstances, PostfixOperators, GADTs, StandaloneDeriving #-}
{-# OPTIONS_HADDOCK hide #-}
module ForSyDe.Atom.MoC.DE.React.Core where
import ForSyDe.Atom.MoC
import ForSyDe.Atom.MoC.TimeStamp
import ForSyDe.Atom.Utility.Tuple
import Prelude hiding (until)
import Control.Concurrent
import Data.Time.Clock
-- | Type synonym for a base DE signal as a stream of 'DE' events, where the type of
-- tags has not been determined yet. In designs, it is advised to define a type alias
-- for signals, using an appropriate numerical type for tags, e.g.
--
-- > import ForSyDe.Atom.MoC.DE.React hiding (Signal) -- hide provided alias, to use your own
-- >
-- > type Signal a = SignalBase Int a
type SignalBase t a = Stream (RE t a)
-- | Convenience alias for a DE signal, where tags are represented using our exported
-- 'TimeStamp' type.
type Signal a = SignalBase TimeStamp a
-- | The reactor-like DE event, defined exactly like its 'ForSyDe.Atom.MoC.DE.DE'
-- predecessor, and identifying a discrete event signal. The type of the tag system
-- needs to satisfy all of the three properties, as suggested by the type constraints
-- imposed on it:
--
-- * it needs to be a numerical type and every representable number needs to have an
-- additive inverse.
--
-- * it needs to be unambiguously comparable (defines a total order).
--
-- * it needs to unambiguously define an equality operation.
--
-- Due to these properties not all numerical types can represent DE tags. A typical
-- example of inappropriate representation is 'Float'.
data RE t a where
RE :: (Num t, Ord t, Eq t)
=> { tag :: t, -- ^ timestamp
val :: a -- ^ the value
} -> RE t a
deriving instance (Num t, Ord t, Eq t, Eq t, Eq a) => Eq (RE t a)
instance (Num t, Ord t, Eq t) => MoC (RE t) where
type Fun (RE t) a b = (Bool, [a] -> b)
type Ret (RE t) b = ((), [b])
---------------------
(-.-) = undefined
---------------------
(RE t (_,f):-fs) -*- NullS = RE t (f [] ) :- fs -*- NullS
NullS -*- _ = NullS
(RE t (trigger,f):-fs) -*- px@(RE _ x:-xs)
| trigger = RE t (f [x]) :- fs -*- xs
| otherwise = RE t (f [] ) :- fs -*- px
---------------------
(-*) NullS = NullS
(-*) (RE t (_,x):-xs) = stream (map (RE t) x) +-+ (xs -*)
---------------------
(RE t v :- _) -<- xs = RE t v :- xs
---------------------
(RE d1 _ :- RE d2 _ :- _) -&- xs = (\(RE t v) -> RE (t + d2 - d1) v) <$> xs
(_ :- NullS) -&- _ = error "[MoC.DE.RE] signal delayed to infinity"
---------------------
-- | Shows the event with tag @t@ and value @v@ as @v\@t@.
instance (Show t, Show a) => Show (RE t a) where
showsPrec _ (RE t x) = (++) ( show x ++ "@" ++ show t )
-- | Reads the string of type @v\@t@ as an event @RE t v@.
instance (Read a,Read t, Num t, Ord t, Eq t, Eq t) => Read (RE t a) where
readsPrec _ x = [ (RE tg val, r2)
| (val,r1) <- reads $ takeWhile (/='@') x
, (tg, r2) <- reads $ tail $ dropWhile (/='@') x ]
-- | Allows for mapping of functions on a RE event.
instance (Num t, Ord t, Eq t) => Functor (RE t) where
fmap f (RE t a) = RE t (f a)
-- | Allows for lifting functions on a pair of RE events.
instance (Num t, Ord t, Eq t) => Applicative (RE t) where
pure = RE 0
(RE tf f) <*> (RE _ x) = RE tf (f x)
-----------------------------------------------------------------------------
-- These functions are not exported and are used internally.
infixl 5 -?-
infixl 5 -?
detect :: (Ord t, Num t) => SignalBase t a -> SignalBase t [Bool]
detect = (fmap . fmap) (const [True])
(-?-) :: (Ord t, Num t)
=> SignalBase t [Bool] -> SignalBase t a -> SignalBase t [Bool]
pg@(RE tg g :- gs) -?- px@(RE tx x :- xs)
| tg == tx = RE tg (True:g) :- gs -?- xs
| tg < tx = RE tg (False:g) :- gs -?- px
| tg > tx = RE tx (True:falsify g) :- pg -?- xs
pg@(RE tg g :- gs) -?- NullS = RE tg (False:g) :- gs -?- NullS
NullS -?- px@(RE tx x :- xs) = RE tx (True:repeat False) :- NullS -?- xs
NullS -?- NullS = NullS
falsify (_:xs) = False : falsify xs
falsify [] = []
(-?) s wrap = (fmap . fmap) wrap s
-----------------------------------------------------------------------------
unit :: (Num t, Ord t) => (t, a) -> SignalBase t a
-- | Wraps a (tuple of) pair(s) @(tag, value)@ into the equivalent unit signal(s). A
-- unit signal is a signal with one event with the period @tag@ carrying @value@,
-- starting at tag 0.
--
-- Helpers: @unit@ and @unit[2-4]@.
unit2 :: (Num t, Ord t)
=> ((t,a1),(t, a2))
-> (SignalBase t a1, SignalBase t a2)
unit3 :: (Num t, Ord t)
=> ((t,a1),(t, a2),(t, a3))
-> (SignalBase t a1, SignalBase t a2, SignalBase t a3)
unit4 :: (Num t, Ord t)
=> ((t,a1),(t, a2),(t, a3),(t, a4))
-> (SignalBase t a1, SignalBase t a2, SignalBase t a3, SignalBase t a4)
unit (t,v) = (RE 0 v :- RE t v :- NullS)
unit2 = ($$) (unit,unit)
unit3 = ($$$) (unit,unit,unit)
unit4 = ($$$$) (unit,unit,unit,unit)
-- | Creates a signal with an instant event at time 0.
instant :: (Num t, Ord t) => a -> SignalBase t a
instant v = RE 0 v :- NullS
-- | Transforms a list of tuples @(tag, value)@ into a RE signal. Checks if it is
-- well-formed.
signal :: (Num t, Ord t) => [(t, a)] -> SignalBase t a
signal = checkSignal . stream . fmap (\(t, v) -> RE t v)
-- | Takes the first part of the signal util a given timestamp. The last event of the
-- resulting signal is at the given timestamp and carries the previous value. This
-- utility is useful when plotting a signal, to specify the interval of plotting.
until :: (Num t, Ord t) => t -> SignalBase t a -> SignalBase t a
until _ NullS = NullS
until u (RE t v:-NullS)
| t < u = RE t v :- RE u v :- NullS
| otherwise = RE u v :- NullS
until u (RE t v:-xs)
| t < u = RE t v :- until u xs
| otherwise = RE u v :- NullS
-- | Reads a signal from a string and checks if it is well-formed. Like with the
-- @read@ function from @Prelude@, you must specify the type of the signal.
--
-- >>> readSignal "{ 1@0, 2@2, 3@5, 4@7, 5@10 }" :: Signal Int
-- {1@0s,2@2s,3@5s,4@7s,5@10s}
-- >>> readSignal "{ 1@1, 2@2, 3@5, 4@7, 5@10 }" :: Signal Int
-- {1@1s,2@2s,3@5s,4@7s,5@10s}
--
-- Incorrect usage (not covered by @doctest@):
--
-- > λ> readSignal "{ 1@0, 2@2, 3@5, 4@10, 5@7 }" :: Signal Int
-- > {1@0s,2@2s,3@5s*** Exception: [MoC.RE] malformed signal
readSignal :: (Num t, Ord t, Read t, Read a) => String -> SignalBase t a
readSignal s = checkSignal $ read s
-- | Checks if a signal is well-formed or not, according to the RE MoC
-- interpretation in ForSyDe-Atom.
checkSignal NullS = NullS
checkSignal (x:-NullS) = (x:-NullS)
checkSignal (x:-y:-xs) | tag x < tag y = x :-checkSignal (y:-xs)
| otherwise = error "[MoC.DE.RE] malformed signal"
-----------------------------------------------------------------------------
fromList1 (a1:_) = a1
fromList2 (a1:a2:_) = (a2,a1)
fromList3 (a1:a2:a3:_) = (a3,a2,a1)
fromList4 (a1:a2:a3:a4:_) = (a4,a3,a2,a1)
fromList5 (a1:a2:a3:a4:a5:_) = (a5,a4,a3,a2,a1)
fromList6 (a1:a2:a3:a4:a5:a6:_) = (a6,a5,a4,a3,a2,a1)
fromList7 (a1:a2:a3:a4:a5:a6:a7:_) = (a7,a6,a5,a4,a3,a2,a1)
fromList8 (a1:a2:a3:a4:a5:a6:a7:a8:_) = (a8,a7,a6,a5,a4,a3,a2,a1)
li1 f [x] = f x
-----------------------------------------------------------------------------
-- | Simulates a signal, calling delays according to the timestamps.
simulate :: (Num t, Ord t, Eq t, Show t, Real t, Show a)
=> t -> SignalBase t a -> IO ()
simulate t = execute . until t
where
execute NullS = return ()
execute (x:-NullS) = do
putStrLn $ show (tag x) ++ "\t" ++ show (val x)
threadDelay 1000000
execute (x:-y:-xs) = do
putStrLn $ show (tag x) ++ "\t" ++ show (val x)
let tsx = diffTimeToPicoseconds $ realToFrac (tag x)
tsy = diffTimeToPicoseconds $ realToFrac (tag y)
dly = fromIntegral $ (tsy - tsx) `div` 1000000
threadDelay dly
execute (y:-xs)
|
forsyde/forsyde-atom
|
src/ForSyDe/Atom/MoC/DE/React/Core.hs
|
bsd-3-clause
| 8,077 | 0 | 15 | 1,869 | 2,908 | 1,558 | 1,350 | -1 | -1 |
{-# OPTIONS_GHC -Wall #-}
module Main ( main ) where
import Data.Binary ( encode )
import JacobiRootsRaw300
main :: IO ()
main = do
writeFile "../src/JacobiRootsBinary.hs" blah
blah :: String
blah = unlines
[ "{-# OPTIONS_GHC -Wall #-}"
, "{-# Language OverloadedStrings #-}"
, ""
, "module JacobiRootsBinary ( allShiftedLegendreRootsBinary, allShiftedRadauRootsBinary ) where"
, ""
, "import Data.ByteString.Lazy ( ByteString )"
, ""
, "allShiftedLegendreRootsBinary :: ByteString"
, "allShiftedLegendreRootsBinary = " ++ show (encode allShiftedLegendreRootsRaw)
, ""
, "allShiftedRadauRootsBinary :: ByteString"
, "allShiftedRadauRootsBinary = " ++ show (encode allShiftedRadauRootsRaw)
]
|
ghorn/jacobi-roots
|
gen/Convert.hs
|
bsd-3-clause
| 789 | 0 | 10 | 188 | 121 | 69 | 52 | 21 | 1 |
module Main where
import Paths_tutTest
import System.Environment
import KeyPos
import Graphics.Vty
import Control.Monad.Tools
import Data.Time
import Numeric
main :: IO ()
main = do
[ fn ] <- getArgs
tutRule <- getDataFileName "tutcode-rule.txt" >>= readFile >>= return . read
keyPos <- getDataFileName "keyboard-pos.txt" >>= readFile >>= return . read
cnt <- readFile fn
cfg <- standardIOConfig
vty <- mkVty cfg
(width, height) <- displayBounds =<< outputForConfig cfg
(g, w, t) <- foreach (lines cnt) $ \ln -> do
let ( pos, dic ) = readTutLineWithDic keyPos tutRule ln
5 `timesDo` ( 0, 1, 1 ) $ \n ( g0, w0, t0 ) -> do
( g, w, t ) <- doWhile ( g0, w0, t0 ) $ \( good, whole, time ) -> do
( g, w, t, fin ) <- runTutTyping keyPos tutRule vty pos dic n ( good, whole, time )
return $ ( if fin then ( g, w, t ) else ( good, whole, time ),
fromIntegral g / ( fromIntegral w :: Double ) < 0.95 ||
fromIntegral w / t < 3 )
return ( g, w, t )
shutdown vty
putStrLn $ showFFloat ( Just 0 )
( fromIntegral g / fromIntegral w * 100 :: Double ) "" ++
"% " ++
show ( fromIntegral ( floor ( fromIntegral w / t * 100 ) :: Int ) /
100 :: Double )
runTutTyping ::
[ ( Char, KeyPos ) ] -> [ ( String, [ Char ] ) ] -> Vty
-> [ KeyPos ] -> [ ( Char, [ KeyPos ] ) ] -> Int -> ( Int, Int, NominalDiffTime )
-> IO ( Int, Int, NominalDiffTime, Bool )
runTutTyping keyPos tutRule vty str dic n ( g, w, t ) = do
cfg <- standardIOConfig
(wt, ht) <- displayBounds =<< outputForConfig cfg
let width = fromIntegral wt
img = string currentAttr $ show n ++ " " ++ showTut keyPos tutRule str
ret = show g ++ "/" ++ show w ++ " " ++
showFFloat ( Just 0 )
( fromIntegral g / ( fromIntegral w :: Double ) * 100 ) ""
++ "% "
++ showSpeed t ++ "sec " ++
showSpeed ( fromIntegral w / t ) ++ "key/sec"
update vty $ picForImage $ ( img <-> )
$ ( flip ( foldl (<->) )
$ map ( string currentAttr )
( splitString
( width `div` 2 ) "" $ map showTutDic dic ) )
$ ( !! 8 ) $ iterate ( <-> string currentAttr " " )
$ ( <-> string currentAttr ret )
$ ( !! 8 ) $ iterate ( <-> string currentAttr " " )
$ string currentAttr " "
pre <- getCurrentTime
( input, fin ) <- doWhile ( [ ], True ) $ \( pns, _ ) -> do
p <- getPos keyPos vty
update vty $ picForImage $ ( img <-> )
$ ( flip ( foldl (<->) ) $ map ( string currentAttr )
( splitString
( width `div` 2 ) "" $ map showTutDic dic ) )
$ ( !! 8 ) $ iterate ( <-> string currentAttr " " )
$ ( <-> string currentAttr ret )
$ ( !! 8 ) $ iterate ( <-> string currentAttr " " )
$ string currentAttr
$ ( replicate ( 1 + length ( show n ) ) ' ' ++ )
$ showTut keyPos tutRule
$ pns ++ [ p ]
return ( ( pns ++ [ p ], p /= PosEsc ),
p /= PosEsc && length ( pns ++ [ p ] ) < length str )
post <- getCurrentTime
return ( length $ filter id $ zipWith (==) input str, length str,
diffUTCTime post pre, fin )
timesDo :: Monad m => Int -> a -> ( Int -> a -> m a ) -> m a
( 0 `timesDo` x ) _ = return x
( n `timesDo` x ) act = do
x' <- act n x
( n - 1 ) `timesDo` x' $ act
showSpeed :: NominalDiffTime -> String
showSpeed s = show $ fromIntegral ( floor $ s * 100 :: Int ) / ( 100 :: Double )
splitString :: Int -> String -> [ String ] -> [ String ]
splitString _ "" [ ] = [ ]
splitString _ r [ ] = [ r ]
splitString n r sa@( s : ss )
| length ( r ++ s ) > n = r : splitString n "" sa
| otherwise = splitString n ( r ++ s ) ss
foreach :: [a] -> (a -> IO b) -> IO b
foreach [x] f = f x
foreach (x : xs) f = f x >> foreach xs f
|
YoshikuniJujo/tutTest
|
src/tutTyping.hs
|
bsd-3-clause
| 4,464 | 6 | 30 | 1,850 | 1,686 | 878 | 808 | 91 | 2 |
module GreetIfCool where
greetIfcool :: String -> IO ()
greetIfcool coolness =
case cool of
True -> putStrLn "Cool..."
False -> putStrLn "Meh..."
where cool = coolness == "very cool"
|
chengzh2008/hpffp
|
src/ch07-FunctionPattern/greetIfCool.hs
|
bsd-3-clause
| 196 | 0 | 8 | 43 | 59 | 30 | 29 | 7 | 2 |
module Data.Graph.Simple.Query.Paths (
) where
|
stefan-hoeck/labeled-graph
|
Data/Graph/Simple/Query/Paths.hs
|
bsd-3-clause
| 48 | 0 | 3 | 6 | 12 | 9 | 3 | 1 | 0 |
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__ >= 709
{-# LANGUAGE AutoDeriveTypeable #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.Trans.List
-- Copyright : (c) Andy Gill 2001,
-- (c) Oregon Graduate Institute of Science and Technology, 2001
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- The ListT monad transformer, adding backtracking to a given monad,
-- which must be commutative.
-----------------------------------------------------------------------------
module Control.Monad.Trans.List (
-- * The ListT monad transformer
ListT(..),
mapListT,
-- * Lifting other operations
liftCallCC,
liftCatch,
) where
import Control.Monad.IO.Class
import Control.Monad.Signatures
import Control.Monad.Trans.Class
import Data.Functor.Classes
import Control.Applicative
import Control.Monad
import Data.Foldable (Foldable(foldMap))
import Data.Traversable (Traversable(traverse))
-- | Parameterizable list monad, with an inner monad.
--
-- /Note:/ this does not yield a monad unless the argument monad is commutative.
newtype ListT m a = ListT { runListT :: m [a] }
instance (Eq1 m, Eq a) => Eq (ListT m a) where
ListT x == ListT y = eq1 x y
instance (Ord1 m, Ord a) => Ord (ListT m a) where
compare (ListT x) (ListT y) = compare1 x y
instance (Read1 m, Read a) => Read (ListT m a) where
readsPrec = readsData $ readsUnary1 "ListT" ListT
instance (Show1 m, Show a) => Show (ListT m a) where
showsPrec d (ListT m) = showsUnary1 "ListT" d m
instance (Eq1 m) => Eq1 (ListT m) where eq1 = (==)
instance (Ord1 m) => Ord1 (ListT m) where compare1 = compare
instance (Read1 m) => Read1 (ListT m) where readsPrec1 = readsPrec
instance (Show1 m) => Show1 (ListT m) where showsPrec1 = showsPrec
-- | Map between 'ListT' computations.
--
-- * @'runListT' ('mapListT' f m) = f ('runListT' m)@
mapListT :: (m [a] -> n [b]) -> ListT m a -> ListT n b
mapListT f m = ListT $ f (runListT m)
instance (Functor m) => Functor (ListT m) where
fmap f = mapListT $ fmap $ map f
instance (Foldable f) => Foldable (ListT f) where
foldMap f (ListT a) = foldMap (foldMap f) a
instance (Traversable f) => Traversable (ListT f) where
traverse f (ListT a) = ListT <$> traverse (traverse f) a
instance (Applicative m) => Applicative (ListT m) where
pure a = ListT $ pure [a]
f <*> v = ListT $ (<*>) <$> runListT f <*> runListT v
instance (Applicative m) => Alternative (ListT m) where
empty = ListT $ pure []
m <|> n = ListT $ (++) <$> runListT m <*> runListT n
instance (Monad m) => Monad (ListT m) where
return a = ListT $ return [a]
m >>= k = ListT $ do
a <- runListT m
b <- mapM (runListT . k) a
return (concat b)
fail _ = ListT $ return []
instance (Monad m) => MonadPlus (ListT m) where
mzero = ListT $ return []
m `mplus` n = ListT $ do
a <- runListT m
b <- runListT n
return (a ++ b)
instance MonadTrans ListT where
lift m = ListT $ do
a <- m
return [a]
instance (MonadIO m) => MonadIO (ListT m) where
liftIO = lift . liftIO
-- | Lift a @callCC@ operation to the new monad.
liftCallCC :: CallCC m [a] [b] -> CallCC (ListT m) a b
liftCallCC callCC f = ListT $
callCC $ \ c ->
runListT (f (\ a -> ListT $ c [a]))
-- | Lift a @catchE@ operation to the new monad.
liftCatch :: Catch e m [a] -> Catch e (ListT m) a
liftCatch catchE m h = ListT $ runListT m
`catchE` \ e -> runListT (h e)
|
DavidAlphaFox/ghc
|
libraries/transformers/Control/Monad/Trans/List.hs
|
bsd-3-clause
| 3,664 | 0 | 14 | 845 | 1,240 | 654 | 586 | 67 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
module Zodiac.Raw.Error(
RequestError(..)
, renderRequestError
) where
import Control.DeepSeq.Generics (genericRnf)
import Data.ByteString (ByteString)
import qualified Data.Text as T
import qualified Hadron.Core as H
import GHC.Generics (Generic)
import P
data RequestError =
InvalidHTTPMethod !ByteString
| HeaderNameInvalidUTF8 !ByteString
| URIInvalidUTF8 !ByteString
| HadronError !H.RequestError
deriving (Eq, Show, Generic)
instance NFData RequestError where rnf = genericRnf
renderRequestError :: RequestError -> Text
renderRequestError (InvalidHTTPMethod m) = T.unwords [
"invalid HTTP method:"
, T.pack (show m)
]
renderRequestError (HeaderNameInvalidUTF8 bs) = T.unwords [
"header name not valid UTF-8:"
, T.pack (show bs)
]
renderRequestError (URIInvalidUTF8 bs) = T.unwords [
"URI not valid UTF-8:"
, T.pack (show bs)
]
renderRequestError (HadronError he) =
H.renderRequestError he
|
ambiata/zodiac
|
zodiac-raw/src/Zodiac/Raw/Error.hs
|
bsd-3-clause
| 1,091 | 0 | 9 | 216 | 266 | 147 | 119 | 39 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-- | This module implements a translator from Feldspar expressions
-- @translateExpr@, that reinterprets the Feldspar imperative
-- representation as actions in the @C@ monad.
--
-- Note. This module is temporary and should be replaced by a proper
-- rewrite of the Feldspar Compiler backend.
--
module Feldspar.Compiler.FromImperative
( translateExpr
, translateTypeRep
, translateType
, compileType
, feldsparCIncludes
)
where
import Control.Monad.State
import qualified Data.Map as Map
import Language.C.Quote.C
import qualified Language.C.Syntax as C
import qualified Feldspar as F
import qualified Feldspar.Core.Constructs as F
import Text.PrettyPrint.Mainland
import Feldspar.Core.Constructs (SyntacticFeld)
import Feldspar.Core.Types (TypeRep,defaultSize)
import Feldspar.Core.Middleend.FromTyped (untypeType)
import Feldspar.Compiler (feldsparCIncludes, defaultOptions)
import Feldspar.Compiler.Imperative.FromCore (fromCoreExp)
import qualified Feldspar.Compiler.Imperative.FromCore as FromCore
import Feldspar.Compiler.Imperative.Frontend (isArray,isNativeArray)
import Feldspar.Compiler.Imperative.Representation
import Feldspar.Compiler.Backend.C.CodeGeneration (isInfixFun)
import Language.C.Monad
import Language.Embedded.Expression
type instance VarPred F.Data = F.Type
-- | Evaluate `Data` expressions
instance EvalExp F.Data
where
litExp = F.value
evalExp = F.eval
{-# INLINE litExp #-}
{-# INLINE evalExp #-}
-- | Compile `Data` expressions
instance CompExp F.Data
where
varExp = F.mkVariable
compExp = translateExpr
compType = translateType
{-# INLINE varExp #-}
{-# INLINE compExp #-}
{-# INLINE compType #-}
-- | Translate a Feldspar expression
translateExpr :: MonadC m => SyntacticFeld a => a -> m C.Exp
translateExpr a = do
s <- get
let als = Map.mapKeys fromInteger $ _aliases s
((es,ds,p,exp,ep),s')
= flip runState (fromInteger $ _unique s)
$ fromCoreExp defaultOptions als a
put $ s { _unique = toInteger s' }
mapM_ compileDeclaration ds
mapM_ compileEntity es
compileProgram p
compileExpression exp
-- TODO ep is currently ignored
translateTypeRep :: MonadC m => TypeRep a -> m C.Type
translateTypeRep trep = compileType
$ FromCore.compileType defaultOptions
$ untypeType trep (defaultSize trep)
{-# INLINE translateTypeRep #-}
compileEntity :: MonadC m => Entity () -> m ()
compileEntity StructDef{..} = do
ms <- mapM compileStructMember structMembers
addGlobal [cedecl| struct $id:structName { $sdecls:ms }; |]
compileEntity TypeDef{..} = do
ty <- compileType actualType
addGlobal [cedecl| typedef $ty:ty $id:typeName; |]
compileEntity Proc{..} = inFunction procName $ do
mapM_ compileParam inParams
let Left outs = outParams
mapM_ compileParam outs
inBlock $ maybe (return ()) compileBlock procBody
compileEntity ValueDef{..} = do
ty <- compileType $ varType valVar
is <- compileConstant valValue
addGlobal [cedecl| $ty:ty $id:(varName valVar) = { $is }; |]
compileStructMember :: MonadC m => StructMember () -> m C.FieldGroup
compileStructMember StructMember{..} = do
ty <- compileType structMemberType
return [csdecl| $ty:ty $id:structMemberName; |]
compileParam :: MonadC m => Variable () -> m ()
compileParam Variable{..} = do
ty <- compileType varType
addParam [cparam| $ty:ty $id:varName |]
compileBlock :: MonadC m => Block () -> m ()
compileBlock Block{..} = do
mapM_ compileDeclaration locals
compileProgram blockBody
compileDeclaration :: MonadC m => Declaration () -> m ()
compileDeclaration Declaration{..} = do
ty <- compileType $ varType declVar
case initVal of
Nothing -> if isArray (varType declVar)
then addLocal [cdecl| $ty:ty $id:(varName declVar) = NULL; |]
else addLocal [cdecl| $ty:ty $id:(varName declVar); |]
Just ini -> do
e <- compileExpression ini
addLocal [cdecl| $ty:ty $id:(varName declVar) = $e; |]
compileProgram :: MonadC m => Program () -> m ()
compileProgram Empty = return ()
compileProgram Comment{..} = addStms [cstms| ; /* comment */ |]
compileProgram Assign{..} = do
l <- compileExpression lhs
r <- compileExpression rhs
addStm [cstm| $l = $r; |]
compileProgram ProcedureCall{..} = do
as <- mapM compileActualParameter procCallParams
addStm [cstm| $id:(procCallName) ( $args:as ) ; |]
compileProgram Sequence{..} = mapM_ compileProgram sequenceProgs
compileProgram Switch{..}
| FunctionCall (Function "==" _) [_, _] <- scrutinee
, [ (Pat (ConstExpr (BoolConst True )), Block [] (Sequence [Sequence [Assign vt et]]))
, (Pat (ConstExpr (BoolConst False)), Block [] (Sequence [Sequence [Assign vf ef]]))
] <- alts
, vt == vf
= do
s <- compileExpression scrutinee
t <- compileExpression et
f <- compileExpression ef
v <- compileExpression vt
addStm [cstm| $v = $s ? $t : $f; |]
compileProgram Switch{..} = do
se <- compileExpression scrutinee
case alts of
[ (Pat (ConstExpr (BoolConst True)), tb) , (Pat (ConstExpr (BoolConst False)), eb) ] -> do
tb' <- inNewBlock_ $ compileBlock tb
eb' <- inNewBlock_ $ compileBlock eb
case (tb',eb') of
([],[]) -> return ()
(_ ,[]) -> addStm [cstm| if ( $se) {$items:tb'} |]
([],_ ) -> addStm [cstm| if ( ! $se) {$items:eb'} |]
(_ ,_ ) -> addStm [cstm| if ( $se) {$items:tb'} else {$items:eb'} |]
_ -> do
is <- inNewBlock_ $ mapM_ compileAlt alts
addStm [cstm| switch ($se) { $items:is } |]
compileProgram SeqLoop{..} = do
cond <- compileExpression sLoopCond
items <- inNewBlock_ $ compileBlock sLoopBlock >> compileBlock sLoopCondCalc
compileBlock sLoopCondCalc
-- TODO Code duplication. If `sLoopCondCalc` is large, it's better to use
-- `while(1)` with a conditional break inside.
addStm [cstm| while ($cond) { $items:items } |]
compileProgram ParLoop{..} = do
let ix = varName pLoopCounter
it <- compileType $ varType pLoopCounter
ib <- compileExpression pLoopEnd
is <- compileExpression pLoopStep
items <- inNewBlock_ $ compileBlock pLoopBlock
addStm [cstm| for($ty:it $id:ix = 0; $id:ix < $ib; $id:ix += $is) { $items:items } |]
compileProgram BlockProgram{..} = inBlock $ compileBlock blockProgram
compileAlt :: MonadC m => (Pattern (), Block ()) -> m ()
compileAlt (PatDefault,b) = do
ss <- inNewBlock_ $ compileBlock b
addStm [cstm| default: { $items:ss break; } |]
compileAlt (Pat p,b) = do
e <- compileExpression p
ss <- inNewBlock_ $ compileBlock b
addStm [cstm| case $e : { $items:ss break; } |]
showType :: C.Type -> String
showType = flip displayS "" . renderCompact . ppr
compileActualParameter :: MonadC m => ActualParameter () -> m C.Exp
compileActualParameter ValueParameter{..} = compileExpression valueParam
compileActualParameter TypeParameter{..} = do
ty <- compileType typeParam
return [cexp| $id:(showType ty) |]
compileActualParameter FunParameter{..} = return [cexp| $id:funParamName |]
compileExpression :: MonadC m => Expression () -> m C.Exp
compileExpression VarExpr{..} = return [cexp| $id:(varName varExpr) |]
compileExpression e@ArrayElem{..} = do
a <- compileExpression array
i <- compileExpression arrayIndex
t <- compileType $ typeof e
return $ if isNativeArray $ typeof array
then [cexp| $a[$i] |]
else [cexp| at($id:(showType t),$a,$i) |]
compileExpression StructField{..} = do
s <- compileExpression struct
return [cexp| $s.$id:(fieldName) |]
compileExpression ConstExpr{..} = compileConstant constExpr
compileExpression FunctionCall{..} = do
as <- mapM compileExpression funCallParams
case () of
_ | isInfixFun (funName function)
, [a,b] <- as
-> mkBinOp a b (funName function)
| otherwise
-> return [cexp| $id:(funName function)($args:as) |]
compileExpression Cast{..} = do
ty <- compileType castType
e <- compileExpression castExpr
return [cexp| ($ty:ty)($e) |]
compileExpression AddrOf{..} = do
e <- compileExpression addrExpr
return [cexp| &($e) |]
compileExpression SizeOf{..} = do
ty <- compileType sizeOf
return [cexp| sizeof($ty:ty) |]
compileExpression Deref{..} = do
e <- compileExpression ptrExpr
return [cexp| *($e) |]
mkBinOp :: MonadC m => C.Exp -> C.Exp -> String -> m C.Exp
mkBinOp a b = go
where
go "+" = return [cexp| $a + $b |]
go "-" = return [cexp| $a - $b |]
go "*" = return [cexp| $a * $b |]
go "/" = return [cexp| $a / $b |]
go "%" = return [cexp| $a % $b |]
go "==" = return [cexp| $a == $b |]
go "!=" = return [cexp| $a != $b |]
go "<" = return [cexp| $a < $b |]
go ">" = return [cexp| $a > $b |]
go "<=" = return [cexp| $a <= $b |]
go ">=" = return [cexp| $a >= $b |]
go "&&" = return [cexp| $a && $b |]
go "||" = return [cexp| $a || $b |]
go "&" = return [cexp| $a & $b |]
go "|" = return [cexp| $a | $b |]
go "^" = return [cexp| $a ^ $b |]
go "<<" = return [cexp| $a << $b |]
go ">>" = return [cexp| $a >> $b |]
-- go op = throw $ UnhandledOperator op -- TODO
compileConstant :: MonadC m => Constant () -> m C.Exp
compileConstant IntConst{..} = return [cexp| $const:intValue |]
compileConstant DoubleConst{..} = return [cexp| $const:doubleValue |]
compileConstant FloatConst{..} = return [cexp| $const:floatValue |]
compileConstant BoolConst{..}
| boolValue = addSystemInclude "stdbool.h" >> return [cexp| true |]
| otherwise = addSystemInclude "stdbool.h" >> return [cexp| false |]
compileConstant ComplexConst{..} = do
c1 <- compileConstant realPartComplexValue
c2 <- compileConstant imagPartComplexValue
return [cexp| $c1 + $c2 * I |]
compileConstant ArrayConst{..} = do
cs <- mapM compileConstant arrayValues
return [cexp| $exp:(head cs) |]
compileType :: MonadC m => Type -> m C.Type
compileType = go
where
go VoidType = return [cty| void |]
go (MachineVector 1 BoolType) = do
addSystemInclude "stdbool.h"
return [cty| typename bool |]
go (MachineVector 1 BitType) = return [cty| typename bit |]
go (MachineVector 1 FloatType) = return [cty| float |]
go (MachineVector 1 DoubleType) = return [cty| double |]
go (MachineVector 1 (ComplexType (MachineVector 1 FloatType))) = do
addSystemInclude "complex.h"
return [cty| _Complex float |]
go (MachineVector 1 (ComplexType (MachineVector 1 DoubleType))) = do
addSystemInclude "complex.h"
return [cty| _Complex double |]
go (ArrayType _ _) = do
addSystemInclude "feldspar_array.h"
return [cty| struct array * |]
go (NativeArray (Just 1) t) = go t
go (NativeArray Nothing t) = go t
go (NativeArray (Just _) t) = do
ty <- go t
return [cty| $ty:ty*|]
go (StructType n _) = return [cty| struct $id:(n) |]
go (MachineVector 1 (Pointer t)) = do
ty <- go t
return [cty| $ty:ty * |]
go (IVarType _) = return [cty| struct ivar |]
go (MachineVector 1 (NumType sig sz)) = do
addSystemInclude "stdint.h"
let base = case sig of
Signed -> "int"
Unsigned -> "uint"
let size = case sz of
S8 -> "8"
S16 -> "16"
S32 -> "32"
S40 -> "40"
S64 -> "64"
return [cty| typename $id:(concat [base,size,"_t"]) |]
-- | Extract the type of the expression as a C Type
translateType :: forall m expr a. (MonadC m, F.Type a) => expr a -> m C.Type
translateType _ = translateTypeRep (F.typeRep :: F.TypeRep a)
{-# INLINE translateType #-}
|
emwap/feldspar-compiler-shim
|
src/Feldspar/Compiler/FromImperative.hs
|
bsd-3-clause
| 12,099 | 0 | 17 | 2,740 | 3,633 | 1,888 | 1,745 | 278 | 20 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
--
-- (c) The University of Glasgow 2006
--
-- The purpose of this module is to transform an HsExpr into a CoreExpr which
-- when evaluated, returns a (Meta.Q Meta.Exp) computation analogous to the
-- input HsExpr. We do this in the DsM monad, which supplies access to
-- CoreExpr's of the "smart constructors" of the Meta.Exp datatype.
--
-- It also defines a bunch of knownKeyNames, in the same way as is done
-- in prelude/PrelNames. It's much more convenient to do it here, because
-- otherwise we have to recompile PrelNames whenever we add a Name, which is
-- a Royal Pain (triggers other recompilation).
-----------------------------------------------------------------------------
module DsMeta( dsBracket ) where
#include "HsVersions.h"
import {-# SOURCE #-} DsExpr ( dsExpr )
import MatchLit
import DsMonad
import qualified Language.Haskell.TH as TH
import HsSyn
import Class
import PrelNames
-- To avoid clashes with DsMeta.varName we must make a local alias for
-- OccName.varName we do this by removing varName from the import of
-- OccName above, making a qualified instance of OccName and using
-- OccNameAlias.varName where varName ws previously used in this file.
import qualified OccName( isDataOcc, isVarOcc, isTcOcc )
import Module
import Id
import Name hiding( isVarOcc, isTcOcc, varName, tcName )
import THNames
import NameEnv
import NameSet
import TcType
import TyCon
import TysWiredIn
import CoreSyn
import MkCore
import CoreUtils
import SrcLoc
import Unique
import BasicTypes
import Outputable
import Bag
import DynFlags
import FastString
import ForeignCall
import Util
import Maybes
import MonadUtils
import Data.ByteString ( unpack )
import Control.Monad
import Data.List
-----------------------------------------------------------------------------
dsBracket :: HsBracket Name -> [PendingTcSplice] -> DsM CoreExpr
-- Returns a CoreExpr of type TH.ExpQ
-- The quoted thing is parameterised over Name, even though it has
-- been type checked. We don't want all those type decorations!
dsBracket brack splices
= dsExtendMetaEnv new_bit (do_brack brack)
where
new_bit = mkNameEnv [(n, DsSplice (unLoc e)) | PendingTcSplice n e <- splices]
do_brack (VarBr _ n) = do { MkC e1 <- lookupOcc n ; return e1 }
do_brack (ExpBr e) = do { MkC e1 <- repLE e ; return e1 }
do_brack (PatBr p) = do { MkC p1 <- repTopP p ; return p1 }
do_brack (TypBr t) = do { MkC t1 <- repLTy t ; return t1 }
do_brack (DecBrG gp) = do { MkC ds1 <- repTopDs gp ; return ds1 }
do_brack (DecBrL _) = panic "dsBracket: unexpected DecBrL"
do_brack (TExpBr e) = do { MkC e1 <- repLE e ; return e1 }
{- -------------- Examples --------------------
[| \x -> x |]
====>
gensym (unpackString "x"#) `bindQ` \ x1::String ->
lam (pvar x1) (var x1)
[| \x -> $(f [| x |]) |]
====>
gensym (unpackString "x"#) `bindQ` \ x1::String ->
lam (pvar x1) (f (var x1))
-}
-------------------------------------------------------
-- Declarations
-------------------------------------------------------
repTopP :: LPat Name -> DsM (Core TH.PatQ)
repTopP pat = do { ss <- mkGenSyms (collectPatBinders pat)
; pat' <- addBinds ss (repLP pat)
; wrapGenSyms ss pat' }
repTopDs :: HsGroup Name -> DsM (Core (TH.Q [TH.Dec]))
repTopDs group@(HsGroup { hs_valds = valds
, hs_splcds = splcds
, hs_tyclds = tyclds
, hs_instds = instds
, hs_derivds = derivds
, hs_fixds = fixds
, hs_defds = defds
, hs_fords = fords
, hs_warnds = warnds
, hs_annds = annds
, hs_ruleds = ruleds
, hs_vects = vects
, hs_docs = docs })
= do { let { tv_bndrs = hsSigTvBinders valds
; bndrs = tv_bndrs ++ hsGroupBinders group } ;
ss <- mkGenSyms bndrs ;
-- Bind all the names mainly to avoid repeated use of explicit strings.
-- Thus we get
-- do { t :: String <- genSym "T" ;
-- return (Data t [] ...more t's... }
-- The other important reason is that the output must mention
-- only "T", not "Foo:T" where Foo is the current module
decls <- addBinds ss (
do { val_ds <- rep_val_binds valds
; _ <- mapM no_splice splcds
; tycl_ds <- mapM repTyClD (tyClGroupConcat tyclds)
; role_ds <- mapM repRoleD (concatMap group_roles tyclds)
; inst_ds <- mapM repInstD instds
; deriv_ds <- mapM repStandaloneDerivD derivds
; fix_ds <- mapM repFixD fixds
; _ <- mapM no_default_decl defds
; for_ds <- mapM repForD fords
; _ <- mapM no_warn (concatMap (wd_warnings . unLoc)
warnds)
; ann_ds <- mapM repAnnD annds
; rule_ds <- mapM repRuleD (concatMap (rds_rules . unLoc)
ruleds)
; _ <- mapM no_vect vects
; _ <- mapM no_doc docs
-- more needed
; return (de_loc $ sort_by_loc $
val_ds ++ catMaybes tycl_ds ++ role_ds
++ (concat fix_ds)
++ inst_ds ++ rule_ds ++ for_ds
++ ann_ds ++ deriv_ds) }) ;
decl_ty <- lookupType decQTyConName ;
let { core_list = coreList' decl_ty decls } ;
dec_ty <- lookupType decTyConName ;
q_decs <- repSequenceQ dec_ty core_list ;
wrapGenSyms ss q_decs
}
where
no_splice (L loc _)
= notHandledL loc "Splices within declaration brackets" empty
no_default_decl (L loc decl)
= notHandledL loc "Default declarations" (ppr decl)
no_warn (L loc (Warning thing _))
= notHandledL loc "WARNING and DEPRECATION pragmas" $
text "Pragma for declaration of" <+> ppr thing
no_vect (L loc decl)
= notHandledL loc "Vectorisation pragmas" (ppr decl)
no_doc (L loc _)
= notHandledL loc "Haddock documentation" empty
hsSigTvBinders :: HsValBinds Name -> [Name]
-- See Note [Scoped type variables in bindings]
hsSigTvBinders binds
= concatMap get_scoped_tvs sigs
where
get_scoped_tvs :: LSig Name -> [Name]
-- Both implicit and explicit quantified variables
-- We need the implicit ones for f :: forall (a::k). blah
-- here 'k' scopes too
get_scoped_tvs (L _ (TypeSig _ sig))
| HsIB { hsib_vars = implicit_vars
, hsib_body = sig1 } <- sig
, (explicit_vars, _) <- splitLHsForAllTy (hswc_body sig1)
= implicit_vars ++ map hsLTyVarName explicit_vars
get_scoped_tvs _ = []
sigs = case binds of
ValBindsIn _ sigs -> sigs
ValBindsOut _ sigs -> sigs
{- Notes
Note [Scoped type variables in bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f :: forall a. a -> a
f x = x::a
Here the 'forall a' brings 'a' into scope over the binding group.
To achieve this we
a) Gensym a binding for 'a' at the same time as we do one for 'f'
collecting the relevant binders with hsSigTvBinders
b) When processing the 'forall', don't gensym
The relevant places are signposted with references to this Note
Note [Binders and occurrences]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we desugar [d| data T = MkT |]
we want to get
Data "T" [] [Con "MkT" []] []
and *not*
Data "Foo:T" [] [Con "Foo:MkT" []] []
That is, the new data decl should fit into whatever new module it is
asked to fit in. We do *not* clone, though; no need for this:
Data "T79" ....
But if we see this:
data T = MkT
foo = reifyDecl T
then we must desugar to
foo = Data "Foo:T" [] [Con "Foo:MkT" []] []
So in repTopDs we bring the binders into scope with mkGenSyms and addBinds.
And we use lookupOcc, rather than lookupBinder
in repTyClD and repC.
-}
-- represent associated family instances
--
repTyClD :: LTyClDecl Name -> DsM (Maybe (SrcSpan, Core TH.DecQ))
repTyClD (L loc (FamDecl { tcdFam = fam })) = liftM Just $ repFamilyDecl (L loc fam)
repTyClD (L loc (SynDecl { tcdLName = tc, tcdTyVars = tvs, tcdRhs = rhs }))
= do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences]
; dec <- addTyClTyVarBinds tvs $ \bndrs ->
repSynDecl tc1 bndrs rhs
; return (Just (loc, dec)) }
repTyClD (L loc (DataDecl { tcdLName = tc, tcdTyVars = tvs, tcdDataDefn = defn }))
= do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences]
; dec <- addTyClTyVarBinds tvs $ \bndrs ->
repDataDefn tc1 bndrs Nothing defn
; return (Just (loc, dec)) }
repTyClD (L loc (ClassDecl { tcdCtxt = cxt, tcdLName = cls,
tcdTyVars = tvs, tcdFDs = fds,
tcdSigs = sigs, tcdMeths = meth_binds,
tcdATs = ats, tcdATDefs = atds }))
= do { cls1 <- lookupLOcc cls -- See note [Binders and occurrences]
; dec <- addTyVarBinds tvs $ \bndrs ->
do { cxt1 <- repLContext cxt
; sigs1 <- rep_sigs sigs
; binds1 <- rep_binds meth_binds
; fds1 <- repLFunDeps fds
; ats1 <- repFamilyDecls ats
; atds1 <- repAssocTyFamDefaults atds
; decls1 <- coreList decQTyConName (ats1 ++ atds1 ++ sigs1 ++ binds1)
; repClass cxt1 cls1 bndrs fds1 decls1
}
; return $ Just (loc, dec)
}
-------------------------
repRoleD :: LRoleAnnotDecl Name -> DsM (SrcSpan, Core TH.DecQ)
repRoleD (L loc (RoleAnnotDecl tycon roles))
= do { tycon1 <- lookupLOcc tycon
; roles1 <- mapM repRole roles
; roles2 <- coreList roleTyConName roles1
; dec <- repRoleAnnotD tycon1 roles2
; return (loc, dec) }
-------------------------
repDataDefn :: Core TH.Name -> Core [TH.TyVarBndr]
-> Maybe (Core [TH.TypeQ])
-> HsDataDefn Name
-> DsM (Core TH.DecQ)
repDataDefn tc bndrs opt_tys
(HsDataDefn { dd_ND = new_or_data, dd_ctxt = cxt, dd_kindSig = ksig
, dd_cons = cons, dd_derivs = mb_derivs })
= do { cxt1 <- repLContext cxt
; derivs1 <- repDerivs mb_derivs
; case (new_or_data, cons) of
(NewType, [con]) -> do { con' <- repC con
; ksig' <- repMaybeLKind ksig
; repNewtype cxt1 tc bndrs opt_tys ksig' con'
derivs1 }
(NewType, _) -> failWithDs (text "Multiple constructors for newtype:"
<+> pprQuotedList
(getConNames $ unLoc $ head cons))
(DataType, _) -> do { ksig' <- repMaybeLKind ksig
; consL <- mapM repC cons
; cons1 <- coreList conQTyConName consL
; repData cxt1 tc bndrs opt_tys ksig' cons1
derivs1 }
}
repSynDecl :: Core TH.Name -> Core [TH.TyVarBndr]
-> LHsType Name
-> DsM (Core TH.DecQ)
repSynDecl tc bndrs ty
= do { ty1 <- repLTy ty
; repTySyn tc bndrs ty1 }
repFamilyDecl :: LFamilyDecl Name -> DsM (SrcSpan, Core TH.DecQ)
repFamilyDecl decl@(L loc (FamilyDecl { fdInfo = info,
fdLName = tc,
fdTyVars = tvs,
fdResultSig = L _ resultSig,
fdInjectivityAnn = injectivity }))
= do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences]
; let mkHsQTvs :: [LHsTyVarBndr Name] -> LHsQTyVars Name
mkHsQTvs tvs = HsQTvs { hsq_implicit = [], hsq_explicit = tvs
, hsq_dependent = emptyNameSet }
resTyVar = case resultSig of
TyVarSig bndr -> mkHsQTvs [bndr]
_ -> mkHsQTvs []
; dec <- addTyClTyVarBinds tvs $ \bndrs ->
addTyClTyVarBinds resTyVar $ \_ ->
case info of
ClosedTypeFamily Nothing ->
notHandled "abstract closed type family" (ppr decl)
ClosedTypeFamily (Just eqns) ->
do { eqns1 <- mapM repTyFamEqn eqns
; eqns2 <- coreList tySynEqnQTyConName eqns1
; result <- repFamilyResultSig resultSig
; inj <- repInjectivityAnn injectivity
; repClosedFamilyD tc1 bndrs result inj eqns2 }
OpenTypeFamily ->
do { result <- repFamilyResultSig resultSig
; inj <- repInjectivityAnn injectivity
; repOpenFamilyD tc1 bndrs result inj }
DataFamily ->
do { kind <- repFamilyResultSigToMaybeKind resultSig
; repDataFamilyD tc1 bndrs kind }
; return (loc, dec)
}
-- | Represent result signature of a type family
repFamilyResultSig :: FamilyResultSig Name -> DsM (Core TH.FamilyResultSig)
repFamilyResultSig NoSig = repNoSig
repFamilyResultSig (KindSig ki) = do { ki' <- repLKind ki
; repKindSig ki' }
repFamilyResultSig (TyVarSig bndr) = do { bndr' <- repTyVarBndr bndr
; repTyVarSig bndr' }
-- | Represent result signature using a Maybe Kind. Used with data families,
-- where the result signature can be either missing or a kind but never a named
-- result variable.
repFamilyResultSigToMaybeKind :: FamilyResultSig Name
-> DsM (Core (Maybe TH.Kind))
repFamilyResultSigToMaybeKind NoSig =
do { coreNothing kindTyConName }
repFamilyResultSigToMaybeKind (KindSig ki) =
do { ki' <- repLKind ki
; coreJust kindTyConName ki' }
repFamilyResultSigToMaybeKind _ = panic "repFamilyResultSigToMaybeKind"
-- | Represent injectivity annotation of a type family
repInjectivityAnn :: Maybe (LInjectivityAnn Name)
-> DsM (Core (Maybe TH.InjectivityAnn))
repInjectivityAnn Nothing =
do { coreNothing injAnnTyConName }
repInjectivityAnn (Just (L _ (InjectivityAnn lhs rhs))) =
do { lhs' <- lookupBinder (unLoc lhs)
; rhs1 <- mapM (lookupBinder . unLoc) rhs
; rhs2 <- coreList nameTyConName rhs1
; injAnn <- rep2 injectivityAnnName [unC lhs', unC rhs2]
; coreJust injAnnTyConName injAnn }
repFamilyDecls :: [LFamilyDecl Name] -> DsM [Core TH.DecQ]
repFamilyDecls fds = liftM de_loc (mapM repFamilyDecl fds)
repAssocTyFamDefaults :: [LTyFamDefltEqn Name] -> DsM [Core TH.DecQ]
repAssocTyFamDefaults = mapM rep_deflt
where
-- very like repTyFamEqn, but different in the details
rep_deflt :: LTyFamDefltEqn Name -> DsM (Core TH.DecQ)
rep_deflt (L _ (TyFamEqn { tfe_tycon = tc
, tfe_pats = bndrs
, tfe_rhs = rhs }))
= addTyClTyVarBinds bndrs $ \ _ ->
do { tc1 <- lookupLOcc tc
; tys1 <- repLTys (hsLTyVarBndrsToTypes bndrs)
; tys2 <- coreList typeQTyConName tys1
; rhs1 <- repLTy rhs
; eqn1 <- repTySynEqn tys2 rhs1
; repTySynInst tc1 eqn1 }
-------------------------
-- represent fundeps
--
repLFunDeps :: [Located (FunDep (Located Name))] -> DsM (Core [TH.FunDep])
repLFunDeps fds = repList funDepTyConName repLFunDep fds
repLFunDep :: Located (FunDep (Located Name)) -> DsM (Core TH.FunDep)
repLFunDep (L _ (xs, ys))
= do xs' <- repList nameTyConName (lookupBinder . unLoc) xs
ys' <- repList nameTyConName (lookupBinder . unLoc) ys
repFunDep xs' ys'
-- Represent instance declarations
--
repInstD :: LInstDecl Name -> DsM (SrcSpan, Core TH.DecQ)
repInstD (L loc (TyFamInstD { tfid_inst = fi_decl }))
= do { dec <- repTyFamInstD fi_decl
; return (loc, dec) }
repInstD (L loc (DataFamInstD { dfid_inst = fi_decl }))
= do { dec <- repDataFamInstD fi_decl
; return (loc, dec) }
repInstD (L loc (ClsInstD { cid_inst = cls_decl }))
= do { dec <- repClsInstD cls_decl
; return (loc, dec) }
repClsInstD :: ClsInstDecl Name -> DsM (Core TH.DecQ)
repClsInstD (ClsInstDecl { cid_poly_ty = ty, cid_binds = binds
, cid_sigs = prags, cid_tyfam_insts = ats
, cid_datafam_insts = adts })
= addSimpleTyVarBinds tvs $
-- We must bring the type variables into scope, so their
-- occurrences don't fail, even though the binders don't
-- appear in the resulting data structure
--
-- But we do NOT bring the binders of 'binds' into scope
-- because they are properly regarded as occurrences
-- For example, the method names should be bound to
-- the selector Ids, not to fresh names (Trac #5410)
--
do { cxt1 <- repLContext cxt
; inst_ty1 <- repLTy inst_ty
; binds1 <- rep_binds binds
; prags1 <- rep_sigs prags
; ats1 <- mapM (repTyFamInstD . unLoc) ats
; adts1 <- mapM (repDataFamInstD . unLoc) adts
; decls <- coreList decQTyConName (ats1 ++ adts1 ++ binds1 ++ prags1)
; repInst cxt1 inst_ty1 decls }
where
(tvs, cxt, inst_ty) = splitLHsInstDeclTy ty
repStandaloneDerivD :: LDerivDecl Name -> DsM (SrcSpan, Core TH.DecQ)
repStandaloneDerivD (L loc (DerivDecl { deriv_type = ty }))
= do { dec <- addSimpleTyVarBinds tvs $
do { cxt' <- repLContext cxt
; inst_ty' <- repLTy inst_ty
; repDeriv cxt' inst_ty' }
; return (loc, dec) }
where
(tvs, cxt, inst_ty) = splitLHsInstDeclTy ty
repTyFamInstD :: TyFamInstDecl Name -> DsM (Core TH.DecQ)
repTyFamInstD decl@(TyFamInstDecl { tfid_eqn = eqn })
= do { let tc_name = tyFamInstDeclLName decl
; tc <- lookupLOcc tc_name -- See note [Binders and occurrences]
; eqn1 <- repTyFamEqn eqn
; repTySynInst tc eqn1 }
repTyFamEqn :: LTyFamInstEqn Name -> DsM (Core TH.TySynEqnQ)
repTyFamEqn (L _ (TyFamEqn { tfe_pats = HsIB { hsib_body = tys
, hsib_vars = var_names }
, tfe_rhs = rhs }))
= do { let hs_tvs = HsQTvs { hsq_implicit = var_names
, hsq_explicit = []
, hsq_dependent = emptyNameSet } -- Yuk
; addTyClTyVarBinds hs_tvs $ \ _ ->
do { tys1 <- repLTys tys
; tys2 <- coreList typeQTyConName tys1
; rhs1 <- repLTy rhs
; repTySynEqn tys2 rhs1 } }
repDataFamInstD :: DataFamInstDecl Name -> DsM (Core TH.DecQ)
repDataFamInstD (DataFamInstDecl { dfid_tycon = tc_name
, dfid_pats = HsIB { hsib_body = tys, hsib_vars = var_names }
, dfid_defn = defn })
= do { tc <- lookupLOcc tc_name -- See note [Binders and occurrences]
; let hs_tvs = HsQTvs { hsq_implicit = var_names
, hsq_explicit = []
, hsq_dependent = emptyNameSet } -- Yuk
; addTyClTyVarBinds hs_tvs $ \ bndrs ->
do { tys1 <- repList typeQTyConName repLTy tys
; repDataDefn tc bndrs (Just tys1) defn } }
repForD :: Located (ForeignDecl Name) -> DsM (SrcSpan, Core TH.DecQ)
repForD (L loc (ForeignImport { fd_name = name, fd_sig_ty = typ
, fd_fi = CImport (L _ cc) (L _ s) mch cis _ }))
= do MkC name' <- lookupLOcc name
MkC typ' <- repHsSigType typ
MkC cc' <- repCCallConv cc
MkC s' <- repSafety s
cis' <- conv_cimportspec cis
MkC str <- coreStringLit (static ++ chStr ++ cis')
dec <- rep2 forImpDName [cc', s', str, name', typ']
return (loc, dec)
where
conv_cimportspec (CLabel cls) = notHandled "Foreign label" (doubleQuotes (ppr cls))
conv_cimportspec (CFunction DynamicTarget) = return "dynamic"
conv_cimportspec (CFunction (StaticTarget _ fs _ True))
= return (unpackFS fs)
conv_cimportspec (CFunction (StaticTarget _ _ _ False))
= panic "conv_cimportspec: values not supported yet"
conv_cimportspec CWrapper = return "wrapper"
-- these calling conventions do not support headers and the static keyword
raw_cconv = cc == PrimCallConv || cc == JavaScriptCallConv
static = case cis of
CFunction (StaticTarget _ _ _ _) | not raw_cconv -> "static "
_ -> ""
chStr = case mch of
Just (Header _ h) | not raw_cconv -> unpackFS h ++ " "
_ -> ""
repForD decl = notHandled "Foreign declaration" (ppr decl)
repCCallConv :: CCallConv -> DsM (Core TH.Callconv)
repCCallConv CCallConv = rep2 cCallName []
repCCallConv StdCallConv = rep2 stdCallName []
repCCallConv CApiConv = rep2 cApiCallName []
repCCallConv PrimCallConv = rep2 primCallName []
repCCallConv JavaScriptCallConv = rep2 javaScriptCallName []
repSafety :: Safety -> DsM (Core TH.Safety)
repSafety PlayRisky = rep2 unsafeName []
repSafety PlayInterruptible = rep2 interruptibleName []
repSafety PlaySafe = rep2 safeName []
repFixD :: LFixitySig Name -> DsM [(SrcSpan, Core TH.DecQ)]
repFixD (L loc (FixitySig names (Fixity _ prec dir)))
= do { MkC prec' <- coreIntLit prec
; let rep_fn = case dir of
InfixL -> infixLDName
InfixR -> infixRDName
InfixN -> infixNDName
; let do_one name
= do { MkC name' <- lookupLOcc name
; dec <- rep2 rep_fn [prec', name']
; return (loc,dec) }
; mapM do_one names }
repRuleD :: LRuleDecl Name -> DsM (SrcSpan, Core TH.DecQ)
repRuleD (L loc (HsRule n act bndrs lhs _ rhs _))
= do { let bndr_names = concatMap ruleBndrNames bndrs
; ss <- mkGenSyms bndr_names
; rule1 <- addBinds ss $
do { bndrs' <- repList ruleBndrQTyConName repRuleBndr bndrs
; n' <- coreStringLit $ unpackFS $ snd $ unLoc n
; act' <- repPhases act
; lhs' <- repLE lhs
; rhs' <- repLE rhs
; repPragRule n' bndrs' lhs' rhs' act' }
; rule2 <- wrapGenSyms ss rule1
; return (loc, rule2) }
ruleBndrNames :: LRuleBndr Name -> [Name]
ruleBndrNames (L _ (RuleBndr n)) = [unLoc n]
ruleBndrNames (L _ (RuleBndrSig n sig))
| HsIB { hsib_vars = vars } <- sig
= unLoc n : vars
repRuleBndr :: LRuleBndr Name -> DsM (Core TH.RuleBndrQ)
repRuleBndr (L _ (RuleBndr n))
= do { MkC n' <- lookupLBinder n
; rep2 ruleVarName [n'] }
repRuleBndr (L _ (RuleBndrSig n sig))
= do { MkC n' <- lookupLBinder n
; MkC ty' <- repLTy (hsSigWcType sig)
; rep2 typedRuleVarName [n', ty'] }
repAnnD :: LAnnDecl Name -> DsM (SrcSpan, Core TH.DecQ)
repAnnD (L loc (HsAnnotation _ ann_prov (L _ exp)))
= do { target <- repAnnProv ann_prov
; exp' <- repE exp
; dec <- repPragAnn target exp'
; return (loc, dec) }
repAnnProv :: AnnProvenance Name -> DsM (Core TH.AnnTarget)
repAnnProv (ValueAnnProvenance (L _ n))
= do { MkC n' <- globalVar n -- ANNs are allowed only at top-level
; rep2 valueAnnotationName [ n' ] }
repAnnProv (TypeAnnProvenance (L _ n))
= do { MkC n' <- globalVar n
; rep2 typeAnnotationName [ n' ] }
repAnnProv ModuleAnnProvenance
= rep2 moduleAnnotationName []
-------------------------------------------------------
-- Constructors
-------------------------------------------------------
repC :: LConDecl Name -> DsM (Core TH.ConQ)
repC (L _ (ConDeclH98 { con_name = con
, con_qvars = Nothing, con_cxt = Nothing
, con_details = details }))
= repDataCon con details
repC (L _ (ConDeclH98 { con_name = con
, con_qvars = mcon_tvs, con_cxt = mcxt
, con_details = details }))
= do { let con_tvs = fromMaybe emptyLHsQTvs mcon_tvs
ctxt = unLoc $ fromMaybe (noLoc []) mcxt
; addTyVarBinds con_tvs $ \ ex_bndrs ->
do { c' <- repDataCon con details
; ctxt' <- repContext ctxt
; if isEmptyLHsQTvs con_tvs && null ctxt
then return c'
else rep2 forallCName ([unC ex_bndrs, unC ctxt', unC c'])
}
}
repC (L _ (ConDeclGADT { con_names = cons
, con_type = res_ty@(HsIB { hsib_vars = con_vars })}))
| (details, res_ty', L _ [] , []) <- gadtDetails
, [] <- con_vars
-- no implicit or explicit variables, no context = no need for a forall
= do { let doc = text "In the constructor for " <+> ppr (head cons)
; (hs_details, gadt_res_ty) <-
updateGadtResult failWithDs doc details res_ty'
; repGadtDataCons cons hs_details gadt_res_ty }
| (details,res_ty',ctxt, tvs) <- gadtDetails
= do { let doc = text "In the constructor for " <+> ppr (head cons)
con_tvs = HsQTvs { hsq_implicit = []
, hsq_explicit = (map (noLoc . UserTyVar . noLoc)
con_vars) ++ tvs
, hsq_dependent = emptyNameSet }
; addTyVarBinds con_tvs $ \ ex_bndrs -> do
{ (hs_details, gadt_res_ty) <-
updateGadtResult failWithDs doc details res_ty'
; c' <- repGadtDataCons cons hs_details gadt_res_ty
; ctxt' <- repContext (unLoc ctxt)
; rep2 forallCName ([unC ex_bndrs, unC ctxt', unC c']) } }
where
gadtDetails = gadtDeclDetails res_ty
repSrcUnpackedness :: SrcUnpackedness -> DsM (Core TH.SourceUnpackednessQ)
repSrcUnpackedness SrcUnpack = rep2 sourceUnpackName []
repSrcUnpackedness SrcNoUnpack = rep2 sourceNoUnpackName []
repSrcUnpackedness NoSrcUnpack = rep2 noSourceUnpackednessName []
repSrcStrictness :: SrcStrictness -> DsM (Core TH.SourceStrictnessQ)
repSrcStrictness SrcLazy = rep2 sourceLazyName []
repSrcStrictness SrcStrict = rep2 sourceStrictName []
repSrcStrictness NoSrcStrict = rep2 noSourceStrictnessName []
repBangTy :: LBangType Name -> DsM (Core (TH.BangTypeQ))
repBangTy ty = do
MkC u <- repSrcUnpackedness su'
MkC s <- repSrcStrictness ss'
MkC b <- rep2 bangName [u, s]
MkC t <- repLTy ty'
rep2 bangTypeName [b, t]
where
(su', ss', ty') = case ty of
L _ (HsBangTy (HsSrcBang _ su ss) ty) -> (su, ss, ty)
_ -> (NoSrcUnpack, NoSrcStrict, ty)
-------------------------------------------------------
-- Deriving clause
-------------------------------------------------------
repDerivs :: HsDeriving Name -> DsM (Core TH.CxtQ)
repDerivs deriv = do
let clauses = case deriv of
Nothing -> []
Just (L _ ctxt) -> ctxt
tys <- repList typeQTyConName
(rep_deriv . hsSigType)
clauses
:: DsM (Core [TH.PredQ])
repCtxt tys
where
rep_deriv :: LHsType Name -> DsM (Core TH.TypeQ)
rep_deriv (L _ ty) = repTy ty
-------------------------------------------------------
-- Signatures in a class decl, or a group of bindings
-------------------------------------------------------
rep_sigs :: [LSig Name] -> DsM [Core TH.DecQ]
rep_sigs sigs = do locs_cores <- rep_sigs' sigs
return $ de_loc $ sort_by_loc locs_cores
rep_sigs' :: [LSig Name] -> DsM [(SrcSpan, Core TH.DecQ)]
-- We silently ignore ones we don't recognise
rep_sigs' sigs = do { sigs1 <- mapM rep_sig sigs ;
return (concat sigs1) }
rep_sig :: LSig Name -> DsM [(SrcSpan, Core TH.DecQ)]
rep_sig (L loc (TypeSig nms ty)) = mapM (rep_wc_ty_sig sigDName loc ty) nms
rep_sig (L _ (PatSynSig {})) = notHandled "Pattern type signatures" empty
rep_sig (L loc (ClassOpSig is_deflt nms ty))
| is_deflt = mapM (rep_ty_sig defaultSigDName loc ty) nms
| otherwise = mapM (rep_ty_sig sigDName loc ty) nms
rep_sig d@(L _ (IdSig {})) = pprPanic "rep_sig IdSig" (ppr d)
rep_sig (L _ (FixSig {})) = return [] -- fixity sigs at top level
rep_sig (L loc (InlineSig nm ispec)) = rep_inline nm ispec loc
rep_sig (L loc (SpecSig nm tys ispec))
= concatMapM (\t -> rep_specialise nm t ispec loc) tys
rep_sig (L loc (SpecInstSig _ ty)) = rep_specialiseInst ty loc
rep_sig (L _ (MinimalSig {})) = notHandled "MINIMAL pragmas" empty
rep_ty_sig :: Name -> SrcSpan -> LHsSigType Name -> Located Name
-> DsM (SrcSpan, Core TH.DecQ)
rep_ty_sig mk_sig loc sig_ty nm
= do { nm1 <- lookupLOcc nm
; ty1 <- repHsSigType sig_ty
; sig <- repProto mk_sig nm1 ty1
; return (loc, sig) }
rep_wc_ty_sig :: Name -> SrcSpan -> LHsSigWcType Name -> Located Name
-> DsM (SrcSpan, Core TH.DecQ)
-- We must special-case the top-level explicit for-all of a TypeSig
-- See Note [Scoped type variables in bindings]
rep_wc_ty_sig mk_sig loc sig_ty nm
| HsIB { hsib_vars = implicit_tvs, hsib_body = sig1 } <- sig_ty
, (explicit_tvs, ctxt, ty) <- splitLHsSigmaTy (hswc_body sig1)
= do { nm1 <- lookupLOcc nm
; let rep_in_scope_tv tv = do { name <- lookupBinder (hsLTyVarName tv)
; repTyVarBndrWithKind tv name }
all_tvs = map (noLoc . UserTyVar . noLoc) implicit_tvs ++ explicit_tvs
; th_tvs <- repList tyVarBndrTyConName rep_in_scope_tv all_tvs
; th_ctxt <- repLContext ctxt
; th_ty <- repLTy ty
; ty1 <- if null all_tvs && null (unLoc ctxt)
then return th_ty
else repTForall th_tvs th_ctxt th_ty
; sig <- repProto mk_sig nm1 ty1
; return (loc, sig) }
rep_inline :: Located Name
-> InlinePragma -- Never defaultInlinePragma
-> SrcSpan
-> DsM [(SrcSpan, Core TH.DecQ)]
rep_inline nm ispec loc
= do { nm1 <- lookupLOcc nm
; inline <- repInline $ inl_inline ispec
; rm <- repRuleMatch $ inl_rule ispec
; phases <- repPhases $ inl_act ispec
; pragma <- repPragInl nm1 inline rm phases
; return [(loc, pragma)]
}
rep_specialise :: Located Name -> LHsSigType Name -> InlinePragma -> SrcSpan
-> DsM [(SrcSpan, Core TH.DecQ)]
rep_specialise nm ty ispec loc
= do { nm1 <- lookupLOcc nm
; ty1 <- repHsSigType ty
; phases <- repPhases $ inl_act ispec
; let inline = inl_inline ispec
; pragma <- if isEmptyInlineSpec inline
then -- SPECIALISE
repPragSpec nm1 ty1 phases
else -- SPECIALISE INLINE
do { inline1 <- repInline inline
; repPragSpecInl nm1 ty1 inline1 phases }
; return [(loc, pragma)]
}
rep_specialiseInst :: LHsSigType Name -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)]
rep_specialiseInst ty loc
= do { ty1 <- repHsSigType ty
; pragma <- repPragSpecInst ty1
; return [(loc, pragma)] }
repInline :: InlineSpec -> DsM (Core TH.Inline)
repInline NoInline = dataCon noInlineDataConName
repInline Inline = dataCon inlineDataConName
repInline Inlinable = dataCon inlinableDataConName
repInline spec = notHandled "repInline" (ppr spec)
repRuleMatch :: RuleMatchInfo -> DsM (Core TH.RuleMatch)
repRuleMatch ConLike = dataCon conLikeDataConName
repRuleMatch FunLike = dataCon funLikeDataConName
repPhases :: Activation -> DsM (Core TH.Phases)
repPhases (ActiveBefore _ i) = do { MkC arg <- coreIntLit i
; dataCon' beforePhaseDataConName [arg] }
repPhases (ActiveAfter _ i) = do { MkC arg <- coreIntLit i
; dataCon' fromPhaseDataConName [arg] }
repPhases _ = dataCon allPhasesDataConName
-------------------------------------------------------
-- Types
-------------------------------------------------------
addSimpleTyVarBinds :: [Name] -- the binders to be added
-> DsM (Core (TH.Q a)) -- action in the ext env
-> DsM (Core (TH.Q a))
addSimpleTyVarBinds names thing_inside
= do { fresh_names <- mkGenSyms names
; term <- addBinds fresh_names thing_inside
; wrapGenSyms fresh_names term }
addTyVarBinds :: LHsQTyVars Name -- the binders to be added
-> (Core [TH.TyVarBndr] -> DsM (Core (TH.Q a))) -- action in the ext env
-> DsM (Core (TH.Q a))
-- gensym a list of type variables and enter them into the meta environment;
-- the computations passed as the second argument is executed in that extended
-- meta environment and gets the *new* names on Core-level as an argument
addTyVarBinds (HsQTvs { hsq_implicit = imp_tvs, hsq_explicit = exp_tvs }) m
= do { fresh_imp_names <- mkGenSyms imp_tvs
; fresh_exp_names <- mkGenSyms (map hsLTyVarName exp_tvs)
; let fresh_names = fresh_imp_names ++ fresh_exp_names
; term <- addBinds fresh_names $
do { kbs <- repList tyVarBndrTyConName mk_tv_bndr
(exp_tvs `zip` fresh_exp_names)
; m kbs }
; wrapGenSyms fresh_names term }
where
mk_tv_bndr (tv, (_,v)) = repTyVarBndrWithKind tv (coreVar v)
addTyClTyVarBinds :: LHsQTyVars Name
-> (Core [TH.TyVarBndr] -> DsM (Core (TH.Q a)))
-> DsM (Core (TH.Q a))
-- Used for data/newtype declarations, and family instances,
-- so that the nested type variables work right
-- instance C (T a) where
-- type W (T a) = blah
-- The 'a' in the type instance is the one bound by the instance decl
addTyClTyVarBinds tvs m
= do { let tv_names = hsAllLTyVarNames tvs
; env <- dsGetMetaEnv
; freshNames <- mkGenSyms (filterOut (`elemNameEnv` env) tv_names)
-- Make fresh names for the ones that are not already in scope
-- This makes things work for family declarations
; term <- addBinds freshNames $
do { kbs <- repList tyVarBndrTyConName mk_tv_bndr (hsQTvExplicit tvs)
; m kbs }
; wrapGenSyms freshNames term }
where
mk_tv_bndr tv = do { v <- lookupBinder (hsLTyVarName tv)
; repTyVarBndrWithKind tv v }
-- Produce kinded binder constructors from the Haskell tyvar binders
--
repTyVarBndrWithKind :: LHsTyVarBndr Name
-> Core TH.Name -> DsM (Core TH.TyVarBndr)
repTyVarBndrWithKind (L _ (UserTyVar _)) nm
= repPlainTV nm
repTyVarBndrWithKind (L _ (KindedTyVar _ ki)) nm
= repLKind ki >>= repKindedTV nm
-- | Represent a type variable binder
repTyVarBndr :: LHsTyVarBndr Name -> DsM (Core TH.TyVarBndr)
repTyVarBndr (L _ (UserTyVar (L _ nm)) )= do { nm' <- lookupBinder nm
; repPlainTV nm' }
repTyVarBndr (L _ (KindedTyVar (L _ nm) ki)) = do { nm' <- lookupBinder nm
; ki' <- repLKind ki
; repKindedTV nm' ki' }
-- represent a type context
--
repLContext :: LHsContext Name -> DsM (Core TH.CxtQ)
repLContext (L _ ctxt) = repContext ctxt
repContext :: HsContext Name -> DsM (Core TH.CxtQ)
repContext ctxt = do preds <- repList typeQTyConName repLTy ctxt
repCtxt preds
repHsSigType :: LHsSigType Name -> DsM (Core TH.TypeQ)
repHsSigType ty = repLTy (hsSigType ty)
repHsSigWcType :: LHsSigWcType Name -> DsM (Core TH.TypeQ)
repHsSigWcType (HsIB { hsib_vars = vars
, hsib_body = sig1 })
| (explicit_tvs, ctxt, ty) <- splitLHsSigmaTy (hswc_body sig1)
= addTyVarBinds (HsQTvs { hsq_implicit = []
, hsq_explicit = map (noLoc . UserTyVar . noLoc) vars ++
explicit_tvs
, hsq_dependent = emptyNameSet })
$ \ th_tvs ->
do { th_ctxt <- repLContext ctxt
; th_ty <- repLTy ty
; if null vars && null explicit_tvs && null (unLoc ctxt)
then return th_ty
else repTForall th_tvs th_ctxt th_ty }
-- yield the representation of a list of types
--
repLTys :: [LHsType Name] -> DsM [Core TH.TypeQ]
repLTys tys = mapM repLTy tys
-- represent a type
--
repLTy :: LHsType Name -> DsM (Core TH.TypeQ)
repLTy (L _ ty) = repTy ty
repForall :: HsType Name -> DsM (Core TH.TypeQ)
-- Arg of repForall is always HsForAllTy or HsQualTy
repForall ty
| (tvs, ctxt, tau) <- splitLHsSigmaTy (noLoc ty)
= addTyVarBinds (HsQTvs { hsq_implicit = [], hsq_explicit = tvs
, hsq_dependent = emptyNameSet }) $ \bndrs ->
do { ctxt1 <- repLContext ctxt
; ty1 <- repLTy tau
; repTForall bndrs ctxt1 ty1 }
repTy :: HsType Name -> DsM (Core TH.TypeQ)
repTy ty@(HsForAllTy {}) = repForall ty
repTy ty@(HsQualTy {}) = repForall ty
repTy (HsTyVar (L _ n))
| isTvOcc occ = do tv1 <- lookupOcc n
repTvar tv1
| isDataOcc occ = do tc1 <- lookupOcc n
repPromotedDataCon tc1
| n == eqTyConName = repTequality
| otherwise = do tc1 <- lookupOcc n
repNamedTyCon tc1
where
occ = nameOccName n
repTy (HsAppTy f a) = do
f1 <- repLTy f
a1 <- repLTy a
repTapp f1 a1
repTy (HsFunTy f a) = do
f1 <- repLTy f
a1 <- repLTy a
tcon <- repArrowTyCon
repTapps tcon [f1, a1]
repTy (HsListTy t) = do
t1 <- repLTy t
tcon <- repListTyCon
repTapp tcon t1
repTy (HsPArrTy t) = do
t1 <- repLTy t
tcon <- repTy (HsTyVar (noLoc (tyConName parrTyCon)))
repTapp tcon t1
repTy (HsTupleTy HsUnboxedTuple tys) = do
tys1 <- repLTys tys
tcon <- repUnboxedTupleTyCon (length tys)
repTapps tcon tys1
repTy (HsTupleTy _ tys) = do tys1 <- repLTys tys
tcon <- repTupleTyCon (length tys)
repTapps tcon tys1
repTy (HsOpTy ty1 n ty2) = repLTy ((nlHsTyVar (unLoc n) `nlHsAppTy` ty1)
`nlHsAppTy` ty2)
repTy (HsParTy t) = repLTy t
repTy (HsEqTy t1 t2) = do
t1' <- repLTy t1
t2' <- repLTy t2
eq <- repTequality
repTapps eq [t1', t2']
repTy (HsKindSig t k) = do
t1 <- repLTy t
k1 <- repLKind k
repTSig t1 k1
repTy (HsSpliceTy splice _) = repSplice splice
repTy (HsExplicitListTy _ tys) = do
tys1 <- repLTys tys
repTPromotedList tys1
repTy (HsExplicitTupleTy _ tys) = do
tys1 <- repLTys tys
tcon <- repPromotedTupleTyCon (length tys)
repTapps tcon tys1
repTy (HsTyLit lit) = do
lit' <- repTyLit lit
repTLit lit'
repTy (HsWildCardTy (AnonWildCard _)) = repTWildCard
repTy ty = notHandled "Exotic form of type" (ppr ty)
repTyLit :: HsTyLit -> DsM (Core TH.TyLitQ)
repTyLit (HsNumTy _ i) = do iExpr <- mkIntegerExpr i
rep2 numTyLitName [iExpr]
repTyLit (HsStrTy _ s) = do { s' <- mkStringExprFS s
; rep2 strTyLitName [s']
}
-- represent a kind
--
repLKind :: LHsKind Name -> DsM (Core TH.Kind)
repLKind ki
= do { let (kis, ki') = splitHsFunType ki
; kis_rep <- mapM repLKind kis
; ki'_rep <- repNonArrowLKind ki'
; kcon <- repKArrow
; let f k1 k2 = repKApp kcon k1 >>= flip repKApp k2
; foldrM f ki'_rep kis_rep
}
-- | Represent a kind wrapped in a Maybe
repMaybeLKind :: Maybe (LHsKind Name)
-> DsM (Core (Maybe TH.Kind))
repMaybeLKind Nothing =
do { coreNothing kindTyConName }
repMaybeLKind (Just ki) =
do { ki' <- repLKind ki
; coreJust kindTyConName ki' }
repNonArrowLKind :: LHsKind Name -> DsM (Core TH.Kind)
repNonArrowLKind (L _ ki) = repNonArrowKind ki
repNonArrowKind :: HsKind Name -> DsM (Core TH.Kind)
repNonArrowKind (HsTyVar (L _ name))
| isLiftedTypeKindTyConName name = repKStar
| name `hasKey` constraintKindTyConKey = repKConstraint
| isTvOcc (nameOccName name) = lookupOcc name >>= repKVar
| otherwise = lookupOcc name >>= repKCon
repNonArrowKind (HsAppTy f a) = do { f' <- repLKind f
; a' <- repLKind a
; repKApp f' a'
}
repNonArrowKind (HsListTy k) = do { k' <- repLKind k
; kcon <- repKList
; repKApp kcon k'
}
repNonArrowKind (HsTupleTy _ ks) = do { ks' <- mapM repLKind ks
; kcon <- repKTuple (length ks)
; repKApps kcon ks'
}
repNonArrowKind k = notHandled "Exotic form of kind" (ppr k)
repRole :: Located (Maybe Role) -> DsM (Core TH.Role)
repRole (L _ (Just Nominal)) = rep2 nominalRName []
repRole (L _ (Just Representational)) = rep2 representationalRName []
repRole (L _ (Just Phantom)) = rep2 phantomRName []
repRole (L _ Nothing) = rep2 inferRName []
-----------------------------------------------------------------------------
-- Splices
-----------------------------------------------------------------------------
repSplice :: HsSplice Name -> DsM (Core a)
-- See Note [How brackets and nested splices are handled] in TcSplice
-- We return a CoreExpr of any old type; the context should know
repSplice (HsTypedSplice n _) = rep_splice n
repSplice (HsUntypedSplice n _) = rep_splice n
repSplice (HsQuasiQuote n _ _ _) = rep_splice n
rep_splice :: Name -> DsM (Core a)
rep_splice splice_name
= do { mb_val <- dsLookupMetaEnv splice_name
; case mb_val of
Just (DsSplice e) -> do { e' <- dsExpr e
; return (MkC e') }
_ -> pprPanic "HsSplice" (ppr splice_name) }
-- Should not happen; statically checked
-----------------------------------------------------------------------------
-- Expressions
-----------------------------------------------------------------------------
repLEs :: [LHsExpr Name] -> DsM (Core [TH.ExpQ])
repLEs es = repList expQTyConName repLE es
-- FIXME: some of these panics should be converted into proper error messages
-- unless we can make sure that constructs, which are plainly not
-- supported in TH already lead to error messages at an earlier stage
repLE :: LHsExpr Name -> DsM (Core TH.ExpQ)
repLE (L loc e) = putSrcSpanDs loc (repE e)
repE :: HsExpr Name -> DsM (Core TH.ExpQ)
repE (HsVar (L _ x)) =
do { mb_val <- dsLookupMetaEnv x
; case mb_val of
Nothing -> do { str <- globalVar x
; repVarOrCon x str }
Just (DsBound y) -> repVarOrCon x (coreVar y)
Just (DsSplice e) -> do { e' <- dsExpr e
; return (MkC e') } }
repE e@(HsIPVar _) = notHandled "Implicit parameters" (ppr e)
repE e@(HsOverLabel _) = notHandled "Overloaded labels" (ppr e)
repE e@(HsRecFld f) = case f of
Unambiguous _ x -> repE (HsVar (noLoc x))
Ambiguous{} -> notHandled "Ambiguous record selectors" (ppr e)
-- Remember, we're desugaring renamer output here, so
-- HsOverlit can definitely occur
repE (HsOverLit l) = do { a <- repOverloadedLiteral l; repLit a }
repE (HsLit l) = do { a <- repLiteral l; repLit a }
repE (HsLam (MG { mg_alts = L _ [m] })) = repLambda m
repE (HsLamCase _ (MG { mg_alts = L _ ms }))
= do { ms' <- mapM repMatchTup ms
; core_ms <- coreList matchQTyConName ms'
; repLamCase core_ms }
repE (HsApp x y) = do {a <- repLE x; b <- repLE y; repApp a b}
repE (OpApp e1 op _ e2) =
do { arg1 <- repLE e1;
arg2 <- repLE e2;
the_op <- repLE op ;
repInfixApp arg1 the_op arg2 }
repE (NegApp x _) = do
a <- repLE x
negateVar <- lookupOcc negateName >>= repVar
negateVar `repApp` a
repE (HsPar x) = repLE x
repE (SectionL x y) = do { a <- repLE x; b <- repLE y; repSectionL a b }
repE (SectionR x y) = do { a <- repLE x; b <- repLE y; repSectionR a b }
repE (HsCase e (MG { mg_alts = L _ ms }))
= do { arg <- repLE e
; ms2 <- mapM repMatchTup ms
; core_ms2 <- coreList matchQTyConName ms2
; repCaseE arg core_ms2 }
repE (HsIf _ x y z) = do
a <- repLE x
b <- repLE y
c <- repLE z
repCond a b c
repE (HsMultiIf _ alts)
= do { (binds, alts') <- liftM unzip $ mapM repLGRHS alts
; expr' <- repMultiIf (nonEmptyCoreList alts')
; wrapGenSyms (concat binds) expr' }
repE (HsLet (L _ bs) e) = do { (ss,ds) <- repBinds bs
; e2 <- addBinds ss (repLE e)
; z <- repLetE ds e2
; wrapGenSyms ss z }
-- FIXME: I haven't got the types here right yet
repE e@(HsDo ctxt (L _ sts) _)
| case ctxt of { DoExpr -> True; GhciStmtCtxt -> True; _ -> False }
= do { (ss,zs) <- repLSts sts;
e' <- repDoE (nonEmptyCoreList zs);
wrapGenSyms ss e' }
| ListComp <- ctxt
= do { (ss,zs) <- repLSts sts;
e' <- repComp (nonEmptyCoreList zs);
wrapGenSyms ss e' }
| otherwise
= notHandled "mdo, monad comprehension and [: :]" (ppr e)
repE (ExplicitList _ _ es) = do { xs <- repLEs es; repListExp xs }
repE e@(ExplicitPArr _ _) = notHandled "Parallel arrays" (ppr e)
repE e@(ExplicitTuple es boxed)
| not (all tupArgPresent es) = notHandled "Tuple sections" (ppr e)
| isBoxed boxed = do { xs <- repLEs [e | L _ (Present e) <- es]; repTup xs }
| otherwise = do { xs <- repLEs [e | L _ (Present e) <- es]
; repUnboxedTup xs }
repE (RecordCon { rcon_con_name = c, rcon_flds = flds })
= do { x <- lookupLOcc c;
fs <- repFields flds;
repRecCon x fs }
repE (RecordUpd { rupd_expr = e, rupd_flds = flds })
= do { x <- repLE e;
fs <- repUpdFields flds;
repRecUpd x fs }
repE (ExprWithTySig e ty)
= do { e1 <- repLE e
; t1 <- repHsSigWcType ty
; repSigExp e1 t1 }
repE (ArithSeq _ _ aseq) =
case aseq of
From e -> do { ds1 <- repLE e; repFrom ds1 }
FromThen e1 e2 -> do
ds1 <- repLE e1
ds2 <- repLE e2
repFromThen ds1 ds2
FromTo e1 e2 -> do
ds1 <- repLE e1
ds2 <- repLE e2
repFromTo ds1 ds2
FromThenTo e1 e2 e3 -> do
ds1 <- repLE e1
ds2 <- repLE e2
ds3 <- repLE e3
repFromThenTo ds1 ds2 ds3
repE (HsSpliceE splice) = repSplice splice
repE (HsStatic e) = repLE e >>= rep2 staticEName . (:[]) . unC
repE (HsUnboundVar name) = do
occ <- occNameLit name
sname <- repNameS occ
repUnboundVar sname
repE e@(PArrSeq {}) = notHandled "Parallel arrays" (ppr e)
repE e@(HsCoreAnn {}) = notHandled "Core annotations" (ppr e)
repE e@(HsSCC {}) = notHandled "Cost centres" (ppr e)
repE e@(HsTickPragma {}) = notHandled "Tick Pragma" (ppr e)
repE e@(HsTcBracketOut {}) = notHandled "TH brackets" (ppr e)
repE e = notHandled "Expression form" (ppr e)
-----------------------------------------------------------------------------
-- Building representations of auxillary structures like Match, Clause, Stmt,
repMatchTup :: LMatch Name (LHsExpr Name) -> DsM (Core TH.MatchQ)
repMatchTup (L _ (Match _ [p] _ (GRHSs guards (L _ wheres)))) =
do { ss1 <- mkGenSyms (collectPatBinders p)
; addBinds ss1 $ do {
; p1 <- repLP p
; (ss2,ds) <- repBinds wheres
; addBinds ss2 $ do {
; gs <- repGuards guards
; match <- repMatch p1 gs ds
; wrapGenSyms (ss1++ss2) match }}}
repMatchTup _ = panic "repMatchTup: case alt with more than one arg"
repClauseTup :: LMatch Name (LHsExpr Name) -> DsM (Core TH.ClauseQ)
repClauseTup (L _ (Match _ ps _ (GRHSs guards (L _ wheres)))) =
do { ss1 <- mkGenSyms (collectPatsBinders ps)
; addBinds ss1 $ do {
ps1 <- repLPs ps
; (ss2,ds) <- repBinds wheres
; addBinds ss2 $ do {
gs <- repGuards guards
; clause <- repClause ps1 gs ds
; wrapGenSyms (ss1++ss2) clause }}}
repGuards :: [LGRHS Name (LHsExpr Name)] -> DsM (Core TH.BodyQ)
repGuards [L _ (GRHS [] e)]
= do {a <- repLE e; repNormal a }
repGuards other
= do { zs <- mapM repLGRHS other
; let (xs, ys) = unzip zs
; gd <- repGuarded (nonEmptyCoreList ys)
; wrapGenSyms (concat xs) gd }
repLGRHS :: LGRHS Name (LHsExpr Name) -> DsM ([GenSymBind], (Core (TH.Q (TH.Guard, TH.Exp))))
repLGRHS (L _ (GRHS [L _ (BodyStmt e1 _ _ _)] e2))
= do { guarded <- repLNormalGE e1 e2
; return ([], guarded) }
repLGRHS (L _ (GRHS ss rhs))
= do { (gs, ss') <- repLSts ss
; rhs' <- addBinds gs $ repLE rhs
; guarded <- repPatGE (nonEmptyCoreList ss') rhs'
; return (gs, guarded) }
repFields :: HsRecordBinds Name -> DsM (Core [TH.Q TH.FieldExp])
repFields (HsRecFields { rec_flds = flds })
= repList fieldExpQTyConName rep_fld flds
where
rep_fld :: LHsRecField Name (LHsExpr Name) -> DsM (Core (TH.Q TH.FieldExp))
rep_fld (L _ fld) = do { fn <- lookupLOcc (hsRecFieldSel fld)
; e <- repLE (hsRecFieldArg fld)
; repFieldExp fn e }
repUpdFields :: [LHsRecUpdField Name] -> DsM (Core [TH.Q TH.FieldExp])
repUpdFields = repList fieldExpQTyConName rep_fld
where
rep_fld :: LHsRecUpdField Name -> DsM (Core (TH.Q TH.FieldExp))
rep_fld (L l fld) = case unLoc (hsRecFieldLbl fld) of
Unambiguous _ sel_name -> do { fn <- lookupLOcc (L l sel_name)
; e <- repLE (hsRecFieldArg fld)
; repFieldExp fn e }
_ -> notHandled "Ambiguous record updates" (ppr fld)
-----------------------------------------------------------------------------
-- Representing Stmt's is tricky, especially if bound variables
-- shadow each other. Consider: [| do { x <- f 1; x <- f x; g x } |]
-- First gensym new names for every variable in any of the patterns.
-- both static (x'1 and x'2), and dynamic ((gensym "x") and (gensym "y"))
-- if variables didn't shaddow, the static gensym wouldn't be necessary
-- and we could reuse the original names (x and x).
--
-- do { x'1 <- gensym "x"
-- ; x'2 <- gensym "x"
-- ; doE [ BindSt (pvar x'1) [| f 1 |]
-- , BindSt (pvar x'2) [| f x |]
-- , NoBindSt [| g x |]
-- ]
-- }
-- The strategy is to translate a whole list of do-bindings by building a
-- bigger environment, and a bigger set of meta bindings
-- (like: x'1 <- gensym "x" ) and then combining these with the translations
-- of the expressions within the Do
-----------------------------------------------------------------------------
-- The helper function repSts computes the translation of each sub expression
-- and a bunch of prefix bindings denoting the dynamic renaming.
repLSts :: [LStmt Name (LHsExpr Name)] -> DsM ([GenSymBind], [Core TH.StmtQ])
repLSts stmts = repSts (map unLoc stmts)
repSts :: [Stmt Name (LHsExpr Name)] -> DsM ([GenSymBind], [Core TH.StmtQ])
repSts (BindStmt p e _ _ _ : ss) =
do { e2 <- repLE e
; ss1 <- mkGenSyms (collectPatBinders p)
; addBinds ss1 $ do {
; p1 <- repLP p;
; (ss2,zs) <- repSts ss
; z <- repBindSt p1 e2
; return (ss1++ss2, z : zs) }}
repSts (LetStmt (L _ bs) : ss) =
do { (ss1,ds) <- repBinds bs
; z <- repLetSt ds
; (ss2,zs) <- addBinds ss1 (repSts ss)
; return (ss1++ss2, z : zs) }
repSts (BodyStmt e _ _ _ : ss) =
do { e2 <- repLE e
; z <- repNoBindSt e2
; (ss2,zs) <- repSts ss
; return (ss2, z : zs) }
repSts (ParStmt stmt_blocks _ _ _ : ss) =
do { (ss_s, stmt_blocks1) <- mapAndUnzipM rep_stmt_block stmt_blocks
; let stmt_blocks2 = nonEmptyCoreList stmt_blocks1
ss1 = concat ss_s
; z <- repParSt stmt_blocks2
; (ss2, zs) <- addBinds ss1 (repSts ss)
; return (ss1++ss2, z : zs) }
where
rep_stmt_block :: ParStmtBlock Name Name -> DsM ([GenSymBind], Core [TH.StmtQ])
rep_stmt_block (ParStmtBlock stmts _ _) =
do { (ss1, zs) <- repSts (map unLoc stmts)
; zs1 <- coreList stmtQTyConName zs
; return (ss1, zs1) }
repSts [LastStmt e _ _]
= do { e2 <- repLE e
; z <- repNoBindSt e2
; return ([], [z]) }
repSts [] = return ([],[])
repSts other = notHandled "Exotic statement" (ppr other)
-----------------------------------------------------------
-- Bindings
-----------------------------------------------------------
repBinds :: HsLocalBinds Name -> DsM ([GenSymBind], Core [TH.DecQ])
repBinds EmptyLocalBinds
= do { core_list <- coreList decQTyConName []
; return ([], core_list) }
repBinds b@(HsIPBinds _) = notHandled "Implicit parameters" (ppr b)
repBinds (HsValBinds decs)
= do { let { bndrs = hsSigTvBinders decs ++ collectHsValBinders decs }
-- No need to worrry about detailed scopes within
-- the binding group, because we are talking Names
-- here, so we can safely treat it as a mutually
-- recursive group
-- For hsSigTvBinders see Note [Scoped type variables in bindings]
; ss <- mkGenSyms bndrs
; prs <- addBinds ss (rep_val_binds decs)
; core_list <- coreList decQTyConName
(de_loc (sort_by_loc prs))
; return (ss, core_list) }
rep_val_binds :: HsValBinds Name -> DsM [(SrcSpan, Core TH.DecQ)]
-- Assumes: all the binders of the binding are alrady in the meta-env
rep_val_binds (ValBindsOut binds sigs)
= do { core1 <- rep_binds' (unionManyBags (map snd binds))
; core2 <- rep_sigs' sigs
; return (core1 ++ core2) }
rep_val_binds (ValBindsIn _ _)
= panic "rep_val_binds: ValBindsIn"
rep_binds :: LHsBinds Name -> DsM [Core TH.DecQ]
rep_binds binds = do { binds_w_locs <- rep_binds' binds
; return (de_loc (sort_by_loc binds_w_locs)) }
rep_binds' :: LHsBinds Name -> DsM [(SrcSpan, Core TH.DecQ)]
rep_binds' = mapM rep_bind . bagToList
rep_bind :: LHsBind Name -> DsM (SrcSpan, Core TH.DecQ)
-- Assumes: all the binders of the binding are alrady in the meta-env
-- Note GHC treats declarations of a variable (not a pattern)
-- e.g. x = g 5 as a Fun MonoBinds. This is indicated by a single match
-- with an empty list of patterns
rep_bind (L loc (FunBind
{ fun_id = fn,
fun_matches = MG { mg_alts
= L _ [L _ (Match _ [] _
(GRHSs guards (L _ wheres)))] } }))
= do { (ss,wherecore) <- repBinds wheres
; guardcore <- addBinds ss (repGuards guards)
; fn' <- lookupLBinder fn
; p <- repPvar fn'
; ans <- repVal p guardcore wherecore
; ans' <- wrapGenSyms ss ans
; return (loc, ans') }
rep_bind (L loc (FunBind { fun_id = fn
, fun_matches = MG { mg_alts = L _ ms } }))
= do { ms1 <- mapM repClauseTup ms
; fn' <- lookupLBinder fn
; ans <- repFun fn' (nonEmptyCoreList ms1)
; return (loc, ans) }
rep_bind (L loc (PatBind { pat_lhs = pat
, pat_rhs = GRHSs guards (L _ wheres) }))
= do { patcore <- repLP pat
; (ss,wherecore) <- repBinds wheres
; guardcore <- addBinds ss (repGuards guards)
; ans <- repVal patcore guardcore wherecore
; ans' <- wrapGenSyms ss ans
; return (loc, ans') }
rep_bind (L _ (VarBind { var_id = v, var_rhs = e}))
= do { v' <- lookupBinder v
; e2 <- repLE e
; x <- repNormal e2
; patcore <- repPvar v'
; empty_decls <- coreList decQTyConName []
; ans <- repVal patcore x empty_decls
; return (srcLocSpan (getSrcLoc v), ans) }
rep_bind (L _ (AbsBinds {})) = panic "rep_bind: AbsBinds"
rep_bind (L _ (AbsBindsSig {})) = panic "rep_bind: AbsBindsSig"
rep_bind (L _ dec@(PatSynBind {})) = notHandled "pattern synonyms" (ppr dec)
-----------------------------------------------------------------------------
-- Since everything in a Bind is mutually recursive we need rename all
-- all the variables simultaneously. For example:
-- [| AndMonoBinds (f x = x + g 2) (g x = f 1 + 2) |] would translate to
-- do { f'1 <- gensym "f"
-- ; g'2 <- gensym "g"
-- ; [ do { x'3 <- gensym "x"; fun f'1 [pvar x'3] [| x + g2 |]},
-- do { x'4 <- gensym "x"; fun g'2 [pvar x'4] [| f 1 + 2 |]}
-- ]}
-- This requires collecting the bindings (f'1 <- gensym "f"), and the
-- environment ( f |-> f'1 ) from each binding, and then unioning them
-- together. As we do this we collect GenSymBinds's which represent the renamed
-- variables bound by the Bindings. In order not to lose track of these
-- representations we build a shadow datatype MB with the same structure as
-- MonoBinds, but which has slots for the representations
-----------------------------------------------------------------------------
-- GHC allows a more general form of lambda abstraction than specified
-- by Haskell 98. In particular it allows guarded lambda's like :
-- (\ x | even x -> 0 | odd x -> 1) at the moment we can't represent this in
-- Haskell Template's Meta.Exp type so we punt if it isn't a simple thing like
-- (\ p1 .. pn -> exp) by causing an error.
repLambda :: LMatch Name (LHsExpr Name) -> DsM (Core TH.ExpQ)
repLambda (L _ (Match _ ps _ (GRHSs [L _ (GRHS [] e)] (L _ EmptyLocalBinds))))
= do { let bndrs = collectPatsBinders ps ;
; ss <- mkGenSyms bndrs
; lam <- addBinds ss (
do { xs <- repLPs ps; body <- repLE e; repLam xs body })
; wrapGenSyms ss lam }
repLambda (L _ m) = notHandled "Guarded labmdas" (pprMatch (LambdaExpr :: HsMatchContext Name) m)
-----------------------------------------------------------------------------
-- Patterns
-- repP deals with patterns. It assumes that we have already
-- walked over the pattern(s) once to collect the binders, and
-- have extended the environment. So every pattern-bound
-- variable should already appear in the environment.
-- Process a list of patterns
repLPs :: [LPat Name] -> DsM (Core [TH.PatQ])
repLPs ps = repList patQTyConName repLP ps
repLP :: LPat Name -> DsM (Core TH.PatQ)
repLP (L _ p) = repP p
repP :: Pat Name -> DsM (Core TH.PatQ)
repP (WildPat _) = repPwild
repP (LitPat l) = do { l2 <- repLiteral l; repPlit l2 }
repP (VarPat (L _ x)) = do { x' <- lookupBinder x; repPvar x' }
repP (LazyPat p) = do { p1 <- repLP p; repPtilde p1 }
repP (BangPat p) = do { p1 <- repLP p; repPbang p1 }
repP (AsPat x p) = do { x' <- lookupLBinder x; p1 <- repLP p; repPaspat x' p1 }
repP (ParPat p) = repLP p
repP (ListPat ps _ Nothing) = do { qs <- repLPs ps; repPlist qs }
repP (ListPat ps ty1 (Just (_,e))) = do { p <- repP (ListPat ps ty1 Nothing); e' <- repE (syn_expr e); repPview e' p}
repP (TuplePat ps boxed _)
| isBoxed boxed = do { qs <- repLPs ps; repPtup qs }
| otherwise = do { qs <- repLPs ps; repPunboxedTup qs }
repP (ConPatIn dc details)
= do { con_str <- lookupLOcc dc
; case details of
PrefixCon ps -> do { qs <- repLPs ps; repPcon con_str qs }
RecCon rec -> do { fps <- repList fieldPatQTyConName rep_fld (rec_flds rec)
; repPrec con_str fps }
InfixCon p1 p2 -> do { p1' <- repLP p1;
p2' <- repLP p2;
repPinfix p1' con_str p2' }
}
where
rep_fld :: LHsRecField Name (LPat Name) -> DsM (Core (TH.Name,TH.PatQ))
rep_fld (L _ fld) = do { MkC v <- lookupLOcc (hsRecFieldSel fld)
; MkC p <- repLP (hsRecFieldArg fld)
; rep2 fieldPatName [v,p] }
repP (NPat (L _ l) Nothing _ _) = do { a <- repOverloadedLiteral l; repPlit a }
repP (ViewPat e p _) = do { e' <- repLE e; p' <- repLP p; repPview e' p' }
repP p@(NPat _ (Just _) _ _) = notHandled "Negative overloaded patterns" (ppr p)
repP p@(SigPatIn {}) = notHandled "Type signatures in patterns" (ppr p)
-- The problem is to do with scoped type variables.
-- To implement them, we have to implement the scoping rules
-- here in DsMeta, and I don't want to do that today!
-- do { p' <- repLP p; t' <- repLTy t; repPsig p' t' }
-- repPsig :: Core TH.PatQ -> Core TH.TypeQ -> DsM (Core TH.PatQ)
-- repPsig (MkC p) (MkC t) = rep2 sigPName [p, t]
repP (SplicePat splice) = repSplice splice
repP other = notHandled "Exotic pattern" (ppr other)
----------------------------------------------------------
-- Declaration ordering helpers
sort_by_loc :: [(SrcSpan, a)] -> [(SrcSpan, a)]
sort_by_loc xs = sortBy comp xs
where comp x y = compare (fst x) (fst y)
de_loc :: [(a, b)] -> [b]
de_loc = map snd
----------------------------------------------------------
-- The meta-environment
-- A name/identifier association for fresh names of locally bound entities
type GenSymBind = (Name, Id) -- Gensym the string and bind it to the Id
-- I.e. (x, x_id) means
-- let x_id = gensym "x" in ...
-- Generate a fresh name for a locally bound entity
mkGenSyms :: [Name] -> DsM [GenSymBind]
-- We can use the existing name. For example:
-- [| \x_77 -> x_77 + x_77 |]
-- desugars to
-- do { x_77 <- genSym "x"; .... }
-- We use the same x_77 in the desugared program, but with the type Bndr
-- instead of Int
--
-- We do make it an Internal name, though (hence localiseName)
--
-- Nevertheless, it's monadic because we have to generate nameTy
mkGenSyms ns = do { var_ty <- lookupType nameTyConName
; return [(nm, mkLocalId (localiseName nm) var_ty) | nm <- ns] }
addBinds :: [GenSymBind] -> DsM a -> DsM a
-- Add a list of fresh names for locally bound entities to the
-- meta environment (which is part of the state carried around
-- by the desugarer monad)
addBinds bs m = dsExtendMetaEnv (mkNameEnv [(n,DsBound id) | (n,id) <- bs]) m
-- Look up a locally bound name
--
lookupLBinder :: Located Name -> DsM (Core TH.Name)
lookupLBinder (L _ n) = lookupBinder n
lookupBinder :: Name -> DsM (Core TH.Name)
lookupBinder = lookupOcc
-- Binders are brought into scope before the pattern or what-not is
-- desugared. Moreover, in instance declaration the binder of a method
-- will be the selector Id and hence a global; so we need the
-- globalVar case of lookupOcc
-- Look up a name that is either locally bound or a global name
--
-- * If it is a global name, generate the "original name" representation (ie,
-- the <module>:<name> form) for the associated entity
--
lookupLOcc :: Located Name -> DsM (Core TH.Name)
-- Lookup an occurrence; it can't be a splice.
-- Use the in-scope bindings if they exist
lookupLOcc (L _ n) = lookupOcc n
lookupOcc :: Name -> DsM (Core TH.Name)
lookupOcc n
= do { mb_val <- dsLookupMetaEnv n ;
case mb_val of
Nothing -> globalVar n
Just (DsBound x) -> return (coreVar x)
Just (DsSplice _) -> pprPanic "repE:lookupOcc" (ppr n)
}
globalVar :: Name -> DsM (Core TH.Name)
-- Not bound by the meta-env
-- Could be top-level; or could be local
-- f x = $(g [| x |])
-- Here the x will be local
globalVar name
| isExternalName name
= do { MkC mod <- coreStringLit name_mod
; MkC pkg <- coreStringLit name_pkg
; MkC occ <- nameLit name
; rep2 mk_varg [pkg,mod,occ] }
| otherwise
= do { MkC occ <- nameLit name
; MkC uni <- coreIntLit (getKey (getUnique name))
; rep2 mkNameLName [occ,uni] }
where
mod = ASSERT( isExternalName name) nameModule name
name_mod = moduleNameString (moduleName mod)
name_pkg = unitIdString (moduleUnitId mod)
name_occ = nameOccName name
mk_varg | OccName.isDataOcc name_occ = mkNameG_dName
| OccName.isVarOcc name_occ = mkNameG_vName
| OccName.isTcOcc name_occ = mkNameG_tcName
| otherwise = pprPanic "DsMeta.globalVar" (ppr name)
lookupType :: Name -- Name of type constructor (e.g. TH.ExpQ)
-> DsM Type -- The type
lookupType tc_name = do { tc <- dsLookupTyCon tc_name ;
return (mkTyConApp tc []) }
wrapGenSyms :: [GenSymBind]
-> Core (TH.Q a) -> DsM (Core (TH.Q a))
-- wrapGenSyms [(nm1,id1), (nm2,id2)] y
-- --> bindQ (gensym nm1) (\ id1 ->
-- bindQ (gensym nm2 (\ id2 ->
-- y))
wrapGenSyms binds body@(MkC b)
= do { var_ty <- lookupType nameTyConName
; go var_ty binds }
where
[elt_ty] = tcTyConAppArgs (exprType b)
-- b :: Q a, so we can get the type 'a' by looking at the
-- argument type. NB: this relies on Q being a data/newtype,
-- not a type synonym
go _ [] = return body
go var_ty ((name,id) : binds)
= do { MkC body' <- go var_ty binds
; lit_str <- nameLit name
; gensym_app <- repGensym lit_str
; repBindQ var_ty elt_ty
gensym_app (MkC (Lam id body')) }
nameLit :: Name -> DsM (Core String)
nameLit n = coreStringLit (occNameString (nameOccName n))
occNameLit :: OccName -> DsM (Core String)
occNameLit name = coreStringLit (occNameString name)
-- %*********************************************************************
-- %* *
-- Constructing code
-- %* *
-- %*********************************************************************
-----------------------------------------------------------------------------
-- PHANTOM TYPES for consistency. In order to make sure we do this correct
-- we invent a new datatype which uses phantom types.
newtype Core a = MkC CoreExpr
unC :: Core a -> CoreExpr
unC (MkC x) = x
rep2 :: Name -> [ CoreExpr ] -> DsM (Core a)
rep2 n xs = do { id <- dsLookupGlobalId n
; return (MkC (foldl App (Var id) xs)) }
dataCon' :: Name -> [CoreExpr] -> DsM (Core a)
dataCon' n args = do { id <- dsLookupDataCon n
; return $ MkC $ mkCoreConApps id args }
dataCon :: Name -> DsM (Core a)
dataCon n = dataCon' n []
-- %*********************************************************************
-- %* *
-- The 'smart constructors'
-- %* *
-- %*********************************************************************
--------------- Patterns -----------------
repPlit :: Core TH.Lit -> DsM (Core TH.PatQ)
repPlit (MkC l) = rep2 litPName [l]
repPvar :: Core TH.Name -> DsM (Core TH.PatQ)
repPvar (MkC s) = rep2 varPName [s]
repPtup :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
repPtup (MkC ps) = rep2 tupPName [ps]
repPunboxedTup :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
repPunboxedTup (MkC ps) = rep2 unboxedTupPName [ps]
repPcon :: Core TH.Name -> Core [TH.PatQ] -> DsM (Core TH.PatQ)
repPcon (MkC s) (MkC ps) = rep2 conPName [s, ps]
repPrec :: Core TH.Name -> Core [(TH.Name,TH.PatQ)] -> DsM (Core TH.PatQ)
repPrec (MkC c) (MkC rps) = rep2 recPName [c,rps]
repPinfix :: Core TH.PatQ -> Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ)
repPinfix (MkC p1) (MkC n) (MkC p2) = rep2 infixPName [p1, n, p2]
repPtilde :: Core TH.PatQ -> DsM (Core TH.PatQ)
repPtilde (MkC p) = rep2 tildePName [p]
repPbang :: Core TH.PatQ -> DsM (Core TH.PatQ)
repPbang (MkC p) = rep2 bangPName [p]
repPaspat :: Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ)
repPaspat (MkC s) (MkC p) = rep2 asPName [s, p]
repPwild :: DsM (Core TH.PatQ)
repPwild = rep2 wildPName []
repPlist :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
repPlist (MkC ps) = rep2 listPName [ps]
repPview :: Core TH.ExpQ -> Core TH.PatQ -> DsM (Core TH.PatQ)
repPview (MkC e) (MkC p) = rep2 viewPName [e,p]
--------------- Expressions -----------------
repVarOrCon :: Name -> Core TH.Name -> DsM (Core TH.ExpQ)
repVarOrCon vc str | isDataOcc (nameOccName vc) = repCon str
| otherwise = repVar str
repVar :: Core TH.Name -> DsM (Core TH.ExpQ)
repVar (MkC s) = rep2 varEName [s]
repCon :: Core TH.Name -> DsM (Core TH.ExpQ)
repCon (MkC s) = rep2 conEName [s]
repLit :: Core TH.Lit -> DsM (Core TH.ExpQ)
repLit (MkC c) = rep2 litEName [c]
repApp :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repApp (MkC x) (MkC y) = rep2 appEName [x,y]
repLam :: Core [TH.PatQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repLam (MkC ps) (MkC e) = rep2 lamEName [ps, e]
repLamCase :: Core [TH.MatchQ] -> DsM (Core TH.ExpQ)
repLamCase (MkC ms) = rep2 lamCaseEName [ms]
repTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
repTup (MkC es) = rep2 tupEName [es]
repUnboxedTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
repUnboxedTup (MkC es) = rep2 unboxedTupEName [es]
repCond :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repCond (MkC x) (MkC y) (MkC z) = rep2 condEName [x,y,z]
repMultiIf :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.ExpQ)
repMultiIf (MkC alts) = rep2 multiIfEName [alts]
repLetE :: Core [TH.DecQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repLetE (MkC ds) (MkC e) = rep2 letEName [ds, e]
repCaseE :: Core TH.ExpQ -> Core [TH.MatchQ] -> DsM( Core TH.ExpQ)
repCaseE (MkC e) (MkC ms) = rep2 caseEName [e, ms]
repDoE :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
repDoE (MkC ss) = rep2 doEName [ss]
repComp :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
repComp (MkC ss) = rep2 compEName [ss]
repListExp :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
repListExp (MkC es) = rep2 listEName [es]
repSigExp :: Core TH.ExpQ -> Core TH.TypeQ -> DsM (Core TH.ExpQ)
repSigExp (MkC e) (MkC t) = rep2 sigEName [e,t]
repRecCon :: Core TH.Name -> Core [TH.Q TH.FieldExp]-> DsM (Core TH.ExpQ)
repRecCon (MkC c) (MkC fs) = rep2 recConEName [c,fs]
repRecUpd :: Core TH.ExpQ -> Core [TH.Q TH.FieldExp] -> DsM (Core TH.ExpQ)
repRecUpd (MkC e) (MkC fs) = rep2 recUpdEName [e,fs]
repFieldExp :: Core TH.Name -> Core TH.ExpQ -> DsM (Core (TH.Q TH.FieldExp))
repFieldExp (MkC n) (MkC x) = rep2 fieldExpName [n,x]
repInfixApp :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repInfixApp (MkC x) (MkC y) (MkC z) = rep2 infixAppName [x,y,z]
repSectionL :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repSectionL (MkC x) (MkC y) = rep2 sectionLName [x,y]
repSectionR :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repSectionR (MkC x) (MkC y) = rep2 sectionRName [x,y]
------------ Right hand sides (guarded expressions) ----
repGuarded :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.BodyQ)
repGuarded (MkC pairs) = rep2 guardedBName [pairs]
repNormal :: Core TH.ExpQ -> DsM (Core TH.BodyQ)
repNormal (MkC e) = rep2 normalBName [e]
------------ Guards ----
repLNormalGE :: LHsExpr Name -> LHsExpr Name -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
repLNormalGE g e = do g' <- repLE g
e' <- repLE e
repNormalGE g' e'
repNormalGE :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
repNormalGE (MkC g) (MkC e) = rep2 normalGEName [g, e]
repPatGE :: Core [TH.StmtQ] -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
repPatGE (MkC ss) (MkC e) = rep2 patGEName [ss, e]
------------- Stmts -------------------
repBindSt :: Core TH.PatQ -> Core TH.ExpQ -> DsM (Core TH.StmtQ)
repBindSt (MkC p) (MkC e) = rep2 bindSName [p,e]
repLetSt :: Core [TH.DecQ] -> DsM (Core TH.StmtQ)
repLetSt (MkC ds) = rep2 letSName [ds]
repNoBindSt :: Core TH.ExpQ -> DsM (Core TH.StmtQ)
repNoBindSt (MkC e) = rep2 noBindSName [e]
repParSt :: Core [[TH.StmtQ]] -> DsM (Core TH.StmtQ)
repParSt (MkC sss) = rep2 parSName [sss]
-------------- Range (Arithmetic sequences) -----------
repFrom :: Core TH.ExpQ -> DsM (Core TH.ExpQ)
repFrom (MkC x) = rep2 fromEName [x]
repFromThen :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repFromThen (MkC x) (MkC y) = rep2 fromThenEName [x,y]
repFromTo :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repFromTo (MkC x) (MkC y) = rep2 fromToEName [x,y]
repFromThenTo :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repFromThenTo (MkC x) (MkC y) (MkC z) = rep2 fromThenToEName [x,y,z]
------------ Match and Clause Tuples -----------
repMatch :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.MatchQ)
repMatch (MkC p) (MkC bod) (MkC ds) = rep2 matchName [p, bod, ds]
repClause :: Core [TH.PatQ] -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.ClauseQ)
repClause (MkC ps) (MkC bod) (MkC ds) = rep2 clauseName [ps, bod, ds]
-------------- Dec -----------------------------
repVal :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
repVal (MkC p) (MkC b) (MkC ds) = rep2 valDName [p, b, ds]
repFun :: Core TH.Name -> Core [TH.ClauseQ] -> DsM (Core TH.DecQ)
repFun (MkC nm) (MkC b) = rep2 funDName [nm, b]
repData :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr]
-> Maybe (Core [TH.TypeQ]) -> Core (Maybe TH.Kind)
-> Core [TH.ConQ] -> Core TH.CxtQ -> DsM (Core TH.DecQ)
repData (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC ksig) (MkC cons) (MkC derivs)
= rep2 dataDName [cxt, nm, tvs, ksig, cons, derivs]
repData (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC ksig) (MkC cons)
(MkC derivs)
= rep2 dataInstDName [cxt, nm, tys, ksig, cons, derivs]
repNewtype :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr]
-> Maybe (Core [TH.TypeQ]) -> Core (Maybe TH.Kind)
-> Core TH.ConQ -> Core TH.CxtQ -> DsM (Core TH.DecQ)
repNewtype (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC ksig) (MkC con)
(MkC derivs)
= rep2 newtypeDName [cxt, nm, tvs, ksig, con, derivs]
repNewtype (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC ksig) (MkC con)
(MkC derivs)
= rep2 newtypeInstDName [cxt, nm, tys, ksig, con, derivs]
repTySyn :: Core TH.Name -> Core [TH.TyVarBndr]
-> Core TH.TypeQ -> DsM (Core TH.DecQ)
repTySyn (MkC nm) (MkC tvs) (MkC rhs)
= rep2 tySynDName [nm, tvs, rhs]
repInst :: Core TH.CxtQ -> Core TH.TypeQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
repInst (MkC cxt) (MkC ty) (MkC ds) = rep2 instanceDName [cxt, ty, ds]
repClass :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr]
-> Core [TH.FunDep] -> Core [TH.DecQ]
-> DsM (Core TH.DecQ)
repClass (MkC cxt) (MkC cls) (MkC tvs) (MkC fds) (MkC ds)
= rep2 classDName [cxt, cls, tvs, fds, ds]
repDeriv :: Core TH.CxtQ -> Core TH.TypeQ -> DsM (Core TH.DecQ)
repDeriv (MkC cxt) (MkC ty) = rep2 standaloneDerivDName [cxt, ty]
repPragInl :: Core TH.Name -> Core TH.Inline -> Core TH.RuleMatch
-> Core TH.Phases -> DsM (Core TH.DecQ)
repPragInl (MkC nm) (MkC inline) (MkC rm) (MkC phases)
= rep2 pragInlDName [nm, inline, rm, phases]
repPragSpec :: Core TH.Name -> Core TH.TypeQ -> Core TH.Phases
-> DsM (Core TH.DecQ)
repPragSpec (MkC nm) (MkC ty) (MkC phases)
= rep2 pragSpecDName [nm, ty, phases]
repPragSpecInl :: Core TH.Name -> Core TH.TypeQ -> Core TH.Inline
-> Core TH.Phases -> DsM (Core TH.DecQ)
repPragSpecInl (MkC nm) (MkC ty) (MkC inline) (MkC phases)
= rep2 pragSpecInlDName [nm, ty, inline, phases]
repPragSpecInst :: Core TH.TypeQ -> DsM (Core TH.DecQ)
repPragSpecInst (MkC ty) = rep2 pragSpecInstDName [ty]
repPragRule :: Core String -> Core [TH.RuleBndrQ] -> Core TH.ExpQ
-> Core TH.ExpQ -> Core TH.Phases -> DsM (Core TH.DecQ)
repPragRule (MkC nm) (MkC bndrs) (MkC lhs) (MkC rhs) (MkC phases)
= rep2 pragRuleDName [nm, bndrs, lhs, rhs, phases]
repPragAnn :: Core TH.AnnTarget -> Core TH.ExpQ -> DsM (Core TH.DecQ)
repPragAnn (MkC targ) (MkC e) = rep2 pragAnnDName [targ, e]
repTySynInst :: Core TH.Name -> Core TH.TySynEqnQ -> DsM (Core TH.DecQ)
repTySynInst (MkC nm) (MkC eqn)
= rep2 tySynInstDName [nm, eqn]
repDataFamilyD :: Core TH.Name -> Core [TH.TyVarBndr]
-> Core (Maybe TH.Kind) -> DsM (Core TH.DecQ)
repDataFamilyD (MkC nm) (MkC tvs) (MkC kind)
= rep2 dataFamilyDName [nm, tvs, kind]
repOpenFamilyD :: Core TH.Name
-> Core [TH.TyVarBndr]
-> Core TH.FamilyResultSig
-> Core (Maybe TH.InjectivityAnn)
-> DsM (Core TH.DecQ)
repOpenFamilyD (MkC nm) (MkC tvs) (MkC result) (MkC inj)
= rep2 openTypeFamilyDName [nm, tvs, result, inj]
repClosedFamilyD :: Core TH.Name
-> Core [TH.TyVarBndr]
-> Core TH.FamilyResultSig
-> Core (Maybe TH.InjectivityAnn)
-> Core [TH.TySynEqnQ]
-> DsM (Core TH.DecQ)
repClosedFamilyD (MkC nm) (MkC tvs) (MkC res) (MkC inj) (MkC eqns)
= rep2 closedTypeFamilyDName [nm, tvs, res, inj, eqns]
repTySynEqn :: Core [TH.TypeQ] -> Core TH.TypeQ -> DsM (Core TH.TySynEqnQ)
repTySynEqn (MkC lhs) (MkC rhs)
= rep2 tySynEqnName [lhs, rhs]
repRoleAnnotD :: Core TH.Name -> Core [TH.Role] -> DsM (Core TH.DecQ)
repRoleAnnotD (MkC n) (MkC roles) = rep2 roleAnnotDName [n, roles]
repFunDep :: Core [TH.Name] -> Core [TH.Name] -> DsM (Core TH.FunDep)
repFunDep (MkC xs) (MkC ys) = rep2 funDepName [xs, ys]
repProto :: Name -> Core TH.Name -> Core TH.TypeQ -> DsM (Core TH.DecQ)
repProto mk_sig (MkC s) (MkC ty) = rep2 mk_sig [s, ty]
repCtxt :: Core [TH.PredQ] -> DsM (Core TH.CxtQ)
repCtxt (MkC tys) = rep2 cxtName [tys]
repDataCon :: Located Name
-> HsConDeclDetails Name
-> DsM (Core TH.ConQ)
repDataCon con details
= do con' <- lookupLOcc con -- See Note [Binders and occurrences]
repConstr details Nothing [con']
repGadtDataCons :: [Located Name]
-> HsConDeclDetails Name
-> LHsType Name
-> DsM (Core TH.ConQ)
repGadtDataCons cons details res_ty
= do cons' <- mapM lookupLOcc cons -- See Note [Binders and occurrences]
repConstr details (Just res_ty) cons'
-- Invariant:
-- * for plain H98 data constructors second argument is Nothing and third
-- argument is a singleton list
-- * for GADTs data constructors second argument is (Just return_type) and
-- third argument is a non-empty list
repConstr :: HsConDeclDetails Name
-> Maybe (LHsType Name)
-> [Core TH.Name]
-> DsM (Core TH.ConQ)
repConstr (PrefixCon ps) Nothing [con]
= do arg_tys <- repList bangTypeQTyConName repBangTy ps
rep2 normalCName [unC con, unC arg_tys]
repConstr (PrefixCon ps) (Just (L _ res_ty)) cons
= do arg_tys <- repList bangTypeQTyConName repBangTy ps
res_ty' <- repTy res_ty
rep2 gadtCName [ unC (nonEmptyCoreList cons), unC arg_tys, unC res_ty']
repConstr (RecCon (L _ ips)) resTy cons
= do args <- concatMapM rep_ip ips
arg_vtys <- coreList varBangTypeQTyConName args
case resTy of
Nothing -> rep2 recCName [unC (head cons), unC arg_vtys]
Just (L _ res_ty) -> do
res_ty' <- repTy res_ty
rep2 recGadtCName [unC (nonEmptyCoreList cons), unC arg_vtys,
unC res_ty']
where
rep_ip (L _ ip) = mapM (rep_one_ip (cd_fld_type ip)) (cd_fld_names ip)
rep_one_ip :: LBangType Name -> LFieldOcc Name -> DsM (Core a)
rep_one_ip t n = do { MkC v <- lookupOcc (selectorFieldOcc $ unLoc n)
; MkC ty <- repBangTy t
; rep2 varBangTypeName [v,ty] }
repConstr (InfixCon st1 st2) Nothing [con]
= do arg1 <- repBangTy st1
arg2 <- repBangTy st2
rep2 infixCName [unC arg1, unC con, unC arg2]
repConstr (InfixCon {}) (Just _) _ =
panic "repConstr: infix GADT constructor should be in a PrefixCon"
repConstr _ _ _ =
panic "repConstr: invariant violated"
------------ Types -------------------
repTForall :: Core [TH.TyVarBndr] -> Core TH.CxtQ -> Core TH.TypeQ
-> DsM (Core TH.TypeQ)
repTForall (MkC tvars) (MkC ctxt) (MkC ty)
= rep2 forallTName [tvars, ctxt, ty]
repTvar :: Core TH.Name -> DsM (Core TH.TypeQ)
repTvar (MkC s) = rep2 varTName [s]
repTapp :: Core TH.TypeQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ)
repTapp (MkC t1) (MkC t2) = rep2 appTName [t1, t2]
repTapps :: Core TH.TypeQ -> [Core TH.TypeQ] -> DsM (Core TH.TypeQ)
repTapps f [] = return f
repTapps f (t:ts) = do { f1 <- repTapp f t; repTapps f1 ts }
repTSig :: Core TH.TypeQ -> Core TH.Kind -> DsM (Core TH.TypeQ)
repTSig (MkC ty) (MkC ki) = rep2 sigTName [ty, ki]
repTequality :: DsM (Core TH.TypeQ)
repTequality = rep2 equalityTName []
repTPromotedList :: [Core TH.TypeQ] -> DsM (Core TH.TypeQ)
repTPromotedList [] = repPromotedNilTyCon
repTPromotedList (t:ts) = do { tcon <- repPromotedConsTyCon
; f <- repTapp tcon t
; t' <- repTPromotedList ts
; repTapp f t'
}
repTLit :: Core TH.TyLitQ -> DsM (Core TH.TypeQ)
repTLit (MkC lit) = rep2 litTName [lit]
repTWildCard :: DsM (Core TH.TypeQ)
repTWildCard = rep2 wildCardTName []
--------- Type constructors --------------
repNamedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ)
repNamedTyCon (MkC s) = rep2 conTName [s]
repTupleTyCon :: Int -> DsM (Core TH.TypeQ)
-- Note: not Core Int; it's easier to be direct here
repTupleTyCon i = do dflags <- getDynFlags
rep2 tupleTName [mkIntExprInt dflags i]
repUnboxedTupleTyCon :: Int -> DsM (Core TH.TypeQ)
-- Note: not Core Int; it's easier to be direct here
repUnboxedTupleTyCon i = do dflags <- getDynFlags
rep2 unboxedTupleTName [mkIntExprInt dflags i]
repArrowTyCon :: DsM (Core TH.TypeQ)
repArrowTyCon = rep2 arrowTName []
repListTyCon :: DsM (Core TH.TypeQ)
repListTyCon = rep2 listTName []
repPromotedDataCon :: Core TH.Name -> DsM (Core TH.TypeQ)
repPromotedDataCon (MkC s) = rep2 promotedTName [s]
repPromotedTupleTyCon :: Int -> DsM (Core TH.TypeQ)
repPromotedTupleTyCon i = do dflags <- getDynFlags
rep2 promotedTupleTName [mkIntExprInt dflags i]
repPromotedNilTyCon :: DsM (Core TH.TypeQ)
repPromotedNilTyCon = rep2 promotedNilTName []
repPromotedConsTyCon :: DsM (Core TH.TypeQ)
repPromotedConsTyCon = rep2 promotedConsTName []
------------ Kinds -------------------
repPlainTV :: Core TH.Name -> DsM (Core TH.TyVarBndr)
repPlainTV (MkC nm) = rep2 plainTVName [nm]
repKindedTV :: Core TH.Name -> Core TH.Kind -> DsM (Core TH.TyVarBndr)
repKindedTV (MkC nm) (MkC ki) = rep2 kindedTVName [nm, ki]
repKVar :: Core TH.Name -> DsM (Core TH.Kind)
repKVar (MkC s) = rep2 varKName [s]
repKCon :: Core TH.Name -> DsM (Core TH.Kind)
repKCon (MkC s) = rep2 conKName [s]
repKTuple :: Int -> DsM (Core TH.Kind)
repKTuple i = do dflags <- getDynFlags
rep2 tupleKName [mkIntExprInt dflags i]
repKArrow :: DsM (Core TH.Kind)
repKArrow = rep2 arrowKName []
repKList :: DsM (Core TH.Kind)
repKList = rep2 listKName []
repKApp :: Core TH.Kind -> Core TH.Kind -> DsM (Core TH.Kind)
repKApp (MkC k1) (MkC k2) = rep2 appKName [k1, k2]
repKApps :: Core TH.Kind -> [Core TH.Kind] -> DsM (Core TH.Kind)
repKApps f [] = return f
repKApps f (k:ks) = do { f' <- repKApp f k; repKApps f' ks }
repKStar :: DsM (Core TH.Kind)
repKStar = rep2 starKName []
repKConstraint :: DsM (Core TH.Kind)
repKConstraint = rep2 constraintKName []
----------------------------------------------------------
-- Type family result signature
repNoSig :: DsM (Core TH.FamilyResultSig)
repNoSig = rep2 noSigName []
repKindSig :: Core TH.Kind -> DsM (Core TH.FamilyResultSig)
repKindSig (MkC ki) = rep2 kindSigName [ki]
repTyVarSig :: Core TH.TyVarBndr -> DsM (Core TH.FamilyResultSig)
repTyVarSig (MkC bndr) = rep2 tyVarSigName [bndr]
----------------------------------------------------------
-- Literals
repLiteral :: HsLit -> DsM (Core TH.Lit)
repLiteral (HsStringPrim _ bs)
= do dflags <- getDynFlags
word8_ty <- lookupType word8TyConName
let w8s = unpack bs
w8s_expr = map (\w8 -> mkCoreConApps word8DataCon
[mkWordLit dflags (toInteger w8)]) w8s
rep2 stringPrimLName [mkListExpr word8_ty w8s_expr]
repLiteral lit
= do lit' <- case lit of
HsIntPrim _ i -> mk_integer i
HsWordPrim _ w -> mk_integer w
HsInt _ i -> mk_integer i
HsFloatPrim r -> mk_rational r
HsDoublePrim r -> mk_rational r
HsCharPrim _ c -> mk_char c
_ -> return lit
lit_expr <- dsLit lit'
case mb_lit_name of
Just lit_name -> rep2 lit_name [lit_expr]
Nothing -> notHandled "Exotic literal" (ppr lit)
where
mb_lit_name = case lit of
HsInteger _ _ _ -> Just integerLName
HsInt _ _ -> Just integerLName
HsIntPrim _ _ -> Just intPrimLName
HsWordPrim _ _ -> Just wordPrimLName
HsFloatPrim _ -> Just floatPrimLName
HsDoublePrim _ -> Just doublePrimLName
HsChar _ _ -> Just charLName
HsCharPrim _ _ -> Just charPrimLName
HsString _ _ -> Just stringLName
HsRat _ _ -> Just rationalLName
_ -> Nothing
mk_integer :: Integer -> DsM HsLit
mk_integer i = do integer_ty <- lookupType integerTyConName
return $ HsInteger "" i integer_ty
mk_rational :: FractionalLit -> DsM HsLit
mk_rational r = do rat_ty <- lookupType rationalTyConName
return $ HsRat r rat_ty
mk_string :: FastString -> DsM HsLit
mk_string s = return $ HsString "" s
mk_char :: Char -> DsM HsLit
mk_char c = return $ HsChar "" c
repOverloadedLiteral :: HsOverLit Name -> DsM (Core TH.Lit)
repOverloadedLiteral (OverLit { ol_val = val})
= do { lit <- mk_lit val; repLiteral lit }
-- The type Rational will be in the environment, because
-- the smart constructor 'TH.Syntax.rationalL' uses it in its type,
-- and rationalL is sucked in when any TH stuff is used
mk_lit :: OverLitVal -> DsM HsLit
mk_lit (HsIntegral _ i) = mk_integer i
mk_lit (HsFractional f) = mk_rational f
mk_lit (HsIsString _ s) = mk_string s
repNameS :: Core String -> DsM (Core TH.Name)
repNameS (MkC name) = rep2 mkNameSName [name]
--------------- Miscellaneous -------------------
repGensym :: Core String -> DsM (Core (TH.Q TH.Name))
repGensym (MkC lit_str) = rep2 newNameName [lit_str]
repBindQ :: Type -> Type -- a and b
-> Core (TH.Q a) -> Core (a -> TH.Q b) -> DsM (Core (TH.Q b))
repBindQ ty_a ty_b (MkC x) (MkC y)
= rep2 bindQName [Type ty_a, Type ty_b, x, y]
repSequenceQ :: Type -> Core [TH.Q a] -> DsM (Core (TH.Q [a]))
repSequenceQ ty_a (MkC list)
= rep2 sequenceQName [Type ty_a, list]
repUnboundVar :: Core TH.Name -> DsM (Core TH.ExpQ)
repUnboundVar (MkC name) = rep2 unboundVarEName [name]
------------ Lists -------------------
-- turn a list of patterns into a single pattern matching a list
repList :: Name -> (a -> DsM (Core b))
-> [a] -> DsM (Core [b])
repList tc_name f args
= do { args1 <- mapM f args
; coreList tc_name args1 }
coreList :: Name -- Of the TyCon of the element type
-> [Core a] -> DsM (Core [a])
coreList tc_name es
= do { elt_ty <- lookupType tc_name; return (coreList' elt_ty es) }
coreList' :: Type -- The element type
-> [Core a] -> Core [a]
coreList' elt_ty es = MkC (mkListExpr elt_ty (map unC es ))
nonEmptyCoreList :: [Core a] -> Core [a]
-- The list must be non-empty so we can get the element type
-- Otherwise use coreList
nonEmptyCoreList [] = panic "coreList: empty argument"
nonEmptyCoreList xs@(MkC x:_) = MkC (mkListExpr (exprType x) (map unC xs))
coreStringLit :: String -> DsM (Core String)
coreStringLit s = do { z <- mkStringExpr s; return(MkC z) }
------------------- Maybe ------------------
-- | Construct Core expression for Nothing of a given type name
coreNothing :: Name -- ^ Name of the TyCon of the element type
-> DsM (Core (Maybe a))
coreNothing tc_name =
do { elt_ty <- lookupType tc_name; return (coreNothing' elt_ty) }
-- | Construct Core expression for Nothing of a given type
coreNothing' :: Type -- ^ The element type
-> Core (Maybe a)
coreNothing' elt_ty = MkC (mkNothingExpr elt_ty)
-- | Store given Core expression in a Just of a given type name
coreJust :: Name -- ^ Name of the TyCon of the element type
-> Core a -> DsM (Core (Maybe a))
coreJust tc_name es
= do { elt_ty <- lookupType tc_name; return (coreJust' elt_ty es) }
-- | Store given Core expression in a Just of a given type
coreJust' :: Type -- ^ The element type
-> Core a -> Core (Maybe a)
coreJust' elt_ty es = MkC (mkJustExpr elt_ty (unC es))
------------ Literals & Variables -------------------
coreIntLit :: Int -> DsM (Core Int)
coreIntLit i = do dflags <- getDynFlags
return (MkC (mkIntExprInt dflags i))
coreVar :: Id -> Core TH.Name -- The Id has type Name
coreVar id = MkC (Var id)
----------------- Failure -----------------------
notHandledL :: SrcSpan -> String -> SDoc -> DsM a
notHandledL loc what doc
| isGoodSrcSpan loc
= putSrcSpanDs loc $ notHandled what doc
| otherwise
= notHandled what doc
notHandled :: String -> SDoc -> DsM a
notHandled what doc = failWithDs msg
where
msg = hang (text what <+> text "not (yet) handled by Template Haskell")
2 doc
|
mcschroeder/ghc
|
compiler/deSugar/DsMeta.hs
|
bsd-3-clause
| 92,826 | 59 | 24 | 28,075 | 29,220 | 14,609 | 14,611 | 1,564 | 18 |
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module Main ( main ) where
import Chrome.Command
import Chrome.DB
import Chrome.Server
import Jetpack
import Opts
-- 2: Get the list of pages
data ChromiumPageInfo = ChromiumPageInfo
{ chromiumDebuggerUrl :: String
, pageURL :: String
} deriving (Show)
instance FromJSON ChromiumPageInfo where
parseJSON (JsObject obj) = ChromiumPageInfo
<$> obj .: "webSocketDebuggerUrl"
<*> obj .: "url"
parseJSON _ = mzero
getChromiumPageInfo :: Int -> IO (Maybe [ChromiumPageInfo])
getChromiumPageInfo port = do
request <- http_parseUrl ("http://localhost:" ++ show port ++ "/json")
manager <- http_newManager http_tlsManagerSettings
response <- http_httpLbs request manager
return $ js_decode (get_http_responseBody response)
main :: IO ()
main = do
Opts _dbpath <- opt_execParser fullopts
env_hSetBuffering env_stdin env_mk'NoBuffering
_dbExists <- env_doesFileExist _dbpath
_db <- if _dbExists then read <$> sio_readFile _dbpath else return (map_fromList [])
startTool _db _dbpath
return ()
where
fullopts = opt_info (opt_helper <*> opts)
( opt_fullDesc
<> opt_progDesc "Print a greeting for TARGET"
<> opt_header "hello - a test for optparse-applicative" )
tryUntilItIsWorking :: String -> IO (Maybe a) -> IO a
tryUntilItIsWorking errMsg action =
action >>= \mbres -> case mbres of
Just a -> return a
Nothing -> print errMsg >> ctrl_threadDelay 1000000 >> print "retrying.." >> tryUntilItIsWorking errMsg action
startTool :: DB -> FilePath -> IO ()
startTool _db _dbpath = do
shared <- stm_atomically $ stm_newTVar 0
pages <- tryUntilItIsWorking "please, close chrome debugger and press enter on this terminal" (getChromiumPageInfo 9160)
let
(host, port, path) = parseUri linkedinWS
linkedinWS = chromiumDebuggerUrl linkedinPage
linkedinPage = case filter (isPrefixOf "https://www.linkedin" . pageURL) pages of
[] -> error "open linkedin page and login before running this program"
(linkedinPage : _) -> linkedinPage
ws_runClient host port path $ \_conn -> do
let ctx = Ctx _db _dbpath _conn
_ <- ctrl_forkIO (webserver ctx)
loopAnalyse ctx
loopAnalyse :: Ctx -> IO ()
loopAnalyse ctx@(Ctx _db _dbpath _conn) = do
msg <- ws_receiveData _conn -- :: IO LbsByteString
putStrLn "-----" >> c8_putStrLn msg >> putStrLn "-----"
let mbres = js_decode msg :: Maybe CommandResult
mbLifeS = mbres >>= \res -> Just (js_fromJSON (resultValue res))
mbLife = mbLifeS >>= \lifeS -> case lifeS of {JsSuccess m -> m; JsError a -> traceShow a Nothing}
print mbres
case mbLife of
Nothing ->
loopAnalyse ctx
Just life -> do
putStrLn "------- LIFE --------"
let newDB = map_insert (name life) life (ctxDB ctx)
let ctx' = ctx{ ctxDB = newDB }
writeFile _dbpath (show newDB)
print "written:"
print newDB
putStrLn "------------------"
loopAnalyse ctx'
-- txt <- getLine
-- let cmd = searchName txt
-- print (A.encode cmd)
-- WS.sendTextData conn $ A.encode cmd
parseUri :: String -> (String, Int, String)
parseUri uri = fromMaybe (error "parseUri: Invalid URI") $ do
_u <- uri_parseURI uri
_auth <- get_uri_uriAuthority _u
let _port = case get_uri_uriPort _auth of (':' : _str) -> read _str; _ -> 80
return (get_uri_uriRegName _auth, _port, get_uri_uriPath _u)
|
rvion/ride
|
chrotomate/app/Main.hs
|
bsd-3-clause
| 3,519 | 0 | 17 | 801 | 1,016 | 489 | 527 | 80 | 3 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, ScopedTypeVariables, MagicHash #-}
{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.List
-- Copyright : (c) The University of Glasgow 1994-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- The List data type and its operations
--
-----------------------------------------------------------------------------
module GHC.List (
-- [] (..), -- built-in syntax; can't be used in export list
map, (++), filter, concat,
head, last, tail, init, uncons, null, length, (!!),
foldl, foldl', foldl1, foldl1', scanl, scanl1, scanl', foldr, foldr1,
scanr, scanr1, iterate, iterate', repeat, replicate, cycle,
take, drop, sum, product, maximum, minimum, splitAt, takeWhile, dropWhile,
span, break, reverse, and, or,
any, all, elem, notElem, lookup,
concatMap,
zip, zip3, zipWith, zipWith3, unzip, unzip3,
errorEmptyList,
) where
import Data.Maybe
import GHC.Base
import GHC.Num (Num(..))
import GHC.Integer (Integer)
infixl 9 !!
infix 4 `elem`, `notElem`
--------------------------------------------------------------
-- List-manipulation functions
--------------------------------------------------------------
-- | \(\mathcal{O}(1)\). Extract the first element of a list, which must be non-empty.
head :: [a] -> a
head (x:_) = x
head [] = badHead
{-# NOINLINE [1] head #-}
badHead :: a
badHead = errorEmptyList "head"
-- This rule is useful in cases like
-- head [y | (x,y) <- ps, x==t]
{-# RULES
"head/build" forall (g::forall b.(a->b->b)->b->b) .
head (build g) = g (\x _ -> x) badHead
"head/augment" forall xs (g::forall b. (a->b->b) -> b -> b) .
head (augment g xs) = g (\x _ -> x) (head xs)
#-}
-- | \(\mathcal{O}(1)\). Decompose a list into its head and tail. If the list is
-- empty, returns 'Nothing'. If the list is non-empty, returns @'Just' (x, xs)@,
-- where @x@ is the head of the list and @xs@ its tail.
--
-- @since 4.8.0.0
uncons :: [a] -> Maybe (a, [a])
uncons [] = Nothing
uncons (x:xs) = Just (x, xs)
-- | \(\mathcal{O}(1)\). Extract the elements after the head of a list, which
-- must be non-empty.
tail :: [a] -> [a]
tail (_:xs) = xs
tail [] = errorEmptyList "tail"
-- | \(\mathcal{O}(n)\). Extract the last element of a list, which must be
-- finite and non-empty.
last :: [a] -> a
#if defined(USE_REPORT_PRELUDE)
last [x] = x
last (_:xs) = last xs
last [] = errorEmptyList "last"
#else
-- Use foldl to make last a good consumer.
-- This will compile to good code for the actual GHC.List.last.
-- (At least as long it is eta-expanded, otherwise it does not, #10260.)
last xs = foldl (\_ x -> x) lastError xs
{-# INLINE last #-}
-- The inline pragma is required to make GHC remember the implementation via
-- foldl.
lastError :: a
lastError = errorEmptyList "last"
#endif
-- | \(\mathcal{O}(n)\). Return all the elements of a list except the last one.
-- The list must be non-empty.
init :: [a] -> [a]
#if defined(USE_REPORT_PRELUDE)
init [x] = []
init (x:xs) = x : init xs
init [] = errorEmptyList "init"
#else
-- eliminate repeated cases
init [] = errorEmptyList "init"
init (x:xs) = init' x xs
where init' _ [] = []
init' y (z:zs) = y : init' z zs
#endif
-- | \(\mathcal{O}(1)\). Test whether a list is empty.
null :: [a] -> Bool
null [] = True
null (_:_) = False
-- | \(\mathcal{O}(n)\). 'length' returns the length of a finite list as an
-- 'Int'. It is an instance of the more general 'Data.List.genericLength', the
-- result type of which may be any kind of number.
{-# NOINLINE [1] length #-}
length :: [a] -> Int
length xs = lenAcc xs 0
lenAcc :: [a] -> Int -> Int
lenAcc [] n = n
lenAcc (_:ys) n = lenAcc ys (n+1)
{-# RULES
"length" [~1] forall xs . length xs = foldr lengthFB idLength xs 0
"lengthList" [1] foldr lengthFB idLength = lenAcc
#-}
-- The lambda form turns out to be necessary to make this inline
-- when we need it to and give good performance.
{-# INLINE [0] lengthFB #-}
lengthFB :: x -> (Int -> Int) -> Int -> Int
lengthFB _ r = \ !a -> r (a + 1)
{-# INLINE [0] idLength #-}
idLength :: Int -> Int
idLength = id
-- | \(\mathcal{O}(n)\). 'filter', applied to a predicate and a list, returns
-- the list of those elements that satisfy the predicate; i.e.,
--
-- > filter p xs = [ x | x <- xs, p x]
--
-- >>> filter odd [1, 2, 3]
-- [1,3]
{-# NOINLINE [1] filter #-}
filter :: (a -> Bool) -> [a] -> [a]
filter _pred [] = []
filter pred (x:xs)
| pred x = x : filter pred xs
| otherwise = filter pred xs
{-# INLINE [0] filterFB #-} -- See Note [Inline FB functions]
filterFB :: (a -> b -> b) -> (a -> Bool) -> a -> b -> b
filterFB c p x r | p x = x `c` r
| otherwise = r
{-# RULES
"filter" [~1] forall p xs. filter p xs = build (\c n -> foldr (filterFB c p) n xs)
"filterList" [1] forall p. foldr (filterFB (:) p) [] = filter p
"filterFB" forall c p q. filterFB (filterFB c p) q = filterFB c (\x -> q x && p x)
#-}
-- Note the filterFB rule, which has p and q the "wrong way round" in the RHS.
-- filterFB (filterFB c p) q a b
-- = if q a then filterFB c p a b else b
-- = if q a then (if p a then c a b else b) else b
-- = if q a && p a then c a b else b
-- = filterFB c (\x -> q x && p x) a b
-- I originally wrote (\x -> p x && q x), which is wrong, and actually
-- gave rise to a live bug report. SLPJ.
-- | 'foldl', applied to a binary operator, a starting value (typically
-- the left-identity of the operator), and a list, reduces the list
-- using the binary operator, from left to right:
--
-- > foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
--
-- The list must be finite.
foldl :: forall a b. (b -> a -> b) -> b -> [a] -> b
{-# INLINE foldl #-}
foldl k z0 xs =
foldr (\(v::a) (fn::b->b) -> oneShot (\(z::b) -> fn (k z v))) (id :: b -> b) xs z0
-- See Note [Left folds via right fold]
{-
Note [Left folds via right fold]
Implementing foldl et. al. via foldr is only a good idea if the compiler can
optimize the resulting code (eta-expand the recursive "go"). See #7994.
We hope that one of the two measure kick in:
* Call Arity (-fcall-arity, enabled by default) eta-expands it if it can see
all calls and determine that the arity is large.
* The oneShot annotation gives a hint to the regular arity analysis that
it may assume that the lambda is called at most once.
See [One-shot lambdas] in CoreArity and especially [Eta expanding thunks]
in CoreArity.
The oneShot annotations used in this module are correct, as we only use them in
arguments to foldr, where we know how the arguments are called.
Note [Inline FB functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~
After fusion rules successfully fire, we are usually left with one or more calls
to list-producing functions abstracted over cons and nil. Here we call them
FB functions because their names usually end with 'FB'. It's a good idea to
inline FB functions because:
* They are higher-order functions and therefore benefits from inlining.
* When the final consumer is a left fold, inlining the FB functions is the only
way to make arity expansion to happen. See Note [Left fold via right fold].
For this reason we mark all FB functions INLINE [0]. The [0] phase-specifier
ensures that calls to FB functions can be written back to the original form
when no fusion happens.
Without these inline pragmas, the loop in perf/should_run/T13001 won't be
allocation-free. Also see #13001.
-}
-- ----------------------------------------------------------------------------
-- | A strict version of 'foldl'.
foldl' :: forall a b . (b -> a -> b) -> b -> [a] -> b
{-# INLINE foldl' #-}
foldl' k z0 xs =
foldr (\(v::a) (fn::b->b) -> oneShot (\(z::b) -> z `seq` fn (k z v))) (id :: b -> b) xs z0
-- See Note [Left folds via right fold]
-- | 'foldl1' is a variant of 'foldl' that has no starting value argument,
-- and thus must be applied to non-empty lists.
foldl1 :: (a -> a -> a) -> [a] -> a
foldl1 f (x:xs) = foldl f x xs
foldl1 _ [] = errorEmptyList "foldl1"
-- | A strict version of 'foldl1'
foldl1' :: (a -> a -> a) -> [a] -> a
foldl1' f (x:xs) = foldl' f x xs
foldl1' _ [] = errorEmptyList "foldl1'"
-- -----------------------------------------------------------------------------
-- List sum and product
-- | The 'sum' function computes the sum of a finite list of numbers.
sum :: (Num a) => [a] -> a
{-# INLINE sum #-}
sum = foldl (+) 0
-- | The 'product' function computes the product of a finite list of numbers.
product :: (Num a) => [a] -> a
{-# INLINE product #-}
product = foldl (*) 1
-- | \(\mathcal{O}(n)\). 'scanl' is similar to 'foldl', but returns a list of
-- successive reduced values from the left:
--
-- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--
-- Note that
--
-- > last (scanl f z xs) == foldl f z xs.
-- This peculiar arrangement is necessary to prevent scanl being rewritten in
-- its own right-hand side.
{-# NOINLINE [1] scanl #-}
scanl :: (b -> a -> b) -> b -> [a] -> [b]
scanl = scanlGo
where
scanlGo :: (b -> a -> b) -> b -> [a] -> [b]
scanlGo f q ls = q : (case ls of
[] -> []
x:xs -> scanlGo f (f q x) xs)
-- Note [scanl rewrite rules]
{-# RULES
"scanl" [~1] forall f a bs . scanl f a bs =
build (\c n -> a `c` foldr (scanlFB f c) (constScanl n) bs a)
"scanlList" [1] forall f (a::a) bs .
foldr (scanlFB f (:)) (constScanl []) bs a = tail (scanl f a bs)
#-}
{-# INLINE [0] scanlFB #-} -- See Note [Inline FB functions]
scanlFB :: (b -> a -> b) -> (b -> c -> c) -> a -> (b -> c) -> b -> c
scanlFB f c = \b g -> oneShot (\x -> let b' = f x b in b' `c` g b')
-- See Note [Left folds via right fold]
{-# INLINE [0] constScanl #-}
constScanl :: a -> b -> a
constScanl = const
-- | \(\mathcal{O}(n)\). 'scanl1' is a variant of 'scanl' that has no starting
-- value argument:
--
-- > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
scanl1 :: (a -> a -> a) -> [a] -> [a]
scanl1 f (x:xs) = scanl f x xs
scanl1 _ [] = []
-- | \(\mathcal{O}(n)\). A strictly accumulating version of 'scanl'
{-# NOINLINE [1] scanl' #-}
scanl' :: (b -> a -> b) -> b -> [a] -> [b]
-- This peculiar form is needed to prevent scanl' from being rewritten
-- in its own right hand side.
scanl' = scanlGo'
where
scanlGo' :: (b -> a -> b) -> b -> [a] -> [b]
scanlGo' f !q ls = q : (case ls of
[] -> []
x:xs -> scanlGo' f (f q x) xs)
-- Note [scanl rewrite rules]
{-# RULES
"scanl'" [~1] forall f a bs . scanl' f a bs =
build (\c n -> a `c` foldr (scanlFB' f c) (flipSeqScanl' n) bs a)
"scanlList'" [1] forall f a bs .
foldr (scanlFB' f (:)) (flipSeqScanl' []) bs a = tail (scanl' f a bs)
#-}
{-# INLINE [0] scanlFB' #-} -- See Note [Inline FB functions]
scanlFB' :: (b -> a -> b) -> (b -> c -> c) -> a -> (b -> c) -> b -> c
scanlFB' f c = \b g -> oneShot (\x -> let !b' = f x b in b' `c` g b')
-- See Note [Left folds via right fold]
{-# INLINE [0] flipSeqScanl' #-}
flipSeqScanl' :: a -> b -> a
flipSeqScanl' a !_b = a
{-
Note [scanl rewrite rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~
In most cases, when we rewrite a form to one that can fuse, we try to rewrite it
back to the original form if it does not fuse. For scanl, we do something a
little different. In particular, we rewrite
scanl f a bs
to
build (\c n -> a `c` foldr (scanlFB f c) (constScanl n) bs a)
When build is inlined, this becomes
a : foldr (scanlFB f (:)) (constScanl []) bs a
To rewrite this form back to scanl, we would need a rule that looked like
forall f a bs. a : foldr (scanlFB f (:)) (constScanl []) bs a = scanl f a bs
The problem with this rule is that it has (:) at its head. This would have the
effect of changing the way the inliner looks at (:), not only here but
everywhere. In most cases, this makes no difference, but in some cases it
causes it to come to a different decision about whether to inline something.
Based on nofib benchmarks, this is bad for performance. Therefore, we instead
match on everything past the :, which is just the tail of scanl.
-}
-- foldr, foldr1, scanr, and scanr1 are the right-to-left duals of the
-- above functions.
-- | 'foldr1' is a variant of 'foldr' that has no starting value argument,
-- and thus must be applied to non-empty lists.
foldr1 :: (a -> a -> a) -> [a] -> a
foldr1 f = go
where go [x] = x
go (x:xs) = f x (go xs)
go [] = errorEmptyList "foldr1"
{-# INLINE [0] foldr1 #-}
-- | \(\mathcal{O}(n)\). 'scanr' is the right-to-left dual of 'scanl'.
-- Note that
--
-- > head (scanr f z xs) == foldr f z xs.
{-# NOINLINE [1] scanr #-}
scanr :: (a -> b -> b) -> b -> [a] -> [b]
scanr _ q0 [] = [q0]
scanr f q0 (x:xs) = f x q : qs
where qs@(q:_) = scanr f q0 xs
{-# INLINE [0] strictUncurryScanr #-}
strictUncurryScanr :: (a -> b -> c) -> (a, b) -> c
strictUncurryScanr f pair = case pair of
(x, y) -> f x y
{-# INLINE [0] scanrFB #-} -- See Note [Inline FB functions]
scanrFB :: (a -> b -> b) -> (b -> c -> c) -> a -> (b, c) -> (b, c)
scanrFB f c = \x ~(r, est) -> (f x r, r `c` est)
-- This lazy pattern match on the tuple is necessary to prevent
-- an infinite loop when scanr receives a fusable infinite list,
-- which was the reason for #16943.
-- See Note [scanrFB and evaluation] below
{-# RULES
"scanr" [~1] forall f q0 ls . scanr f q0 ls =
build (\c n -> strictUncurryScanr c (foldr (scanrFB f c) (q0,n) ls))
"scanrList" [1] forall f q0 ls .
strictUncurryScanr (:) (foldr (scanrFB f (:)) (q0,[]) ls) =
scanr f q0 ls
#-}
{- Note [scanrFB and evaluation]
In a previous Version, the pattern match on the tuple in scanrFB used to be
strict. If scanr is called with a build expression, the following would happen:
The rule "scanr" would fire, and we obtain
build (\c n -> strictUncurryScanr c (foldr (scanrFB f c) (q0,n) (build g))))
The rule "foldr/build" now fires, and the second argument of strictUncurryScanr
will be the expression
g (scanrFB f c) (q0,n)
which will be evaluated, thanks to strictUncurryScanr.
The type of (g :: (a -> b -> b) -> b -> b) allows us to apply parametricity:
Either the tuple is returned (trivial), or scanrFB is called:
g (scanrFB f c) (q0,n) = scanrFB ... (g' (scanrFB f c) (q0,n))
Notice that thanks to the strictness of scanrFB, the expression
g' (scanrFB f c) (q0,n) gets evaluated as well. In particular, if g' is a
recursive case of g, parametricity applies again and we will again have a
possible call to scanrFB. In short, g (scanrFB f c) (q0,n) will end up being
completely evaluated. This is resource consuming for large lists and if the
recursion has no exit condition (and this will be the case in functions like
repeat or cycle), the program will crash (see #16943).
The solution: Don't make scanrFB strict in its last argument. Doing so will
remove the cause for the chain of evaluations, and all is well.
-}
-- | \(\mathcal{O}(n)\). 'scanr1' is a variant of 'scanr' that has no starting
-- value argument.
scanr1 :: (a -> a -> a) -> [a] -> [a]
scanr1 _ [] = []
scanr1 _ [x] = [x]
scanr1 f (x:xs) = f x q : qs
where qs@(q:_) = scanr1 f xs
-- | 'maximum' returns the maximum value from a list,
-- which must be non-empty, finite, and of an ordered type.
-- It is a special case of 'Data.List.maximumBy', which allows the
-- programmer to supply their own comparison function.
maximum :: (Ord a) => [a] -> a
{-# INLINABLE maximum #-}
maximum [] = errorEmptyList "maximum"
maximum xs = foldl1 max xs
-- We want this to be specialized so that with a strict max function, GHC
-- produces good code. Note that to see if this is happending, one has to
-- look at -ddump-prep, not -ddump-core!
{-# SPECIALIZE maximum :: [Int] -> Int #-}
{-# SPECIALIZE maximum :: [Integer] -> Integer #-}
-- | 'minimum' returns the minimum value from a list,
-- which must be non-empty, finite, and of an ordered type.
-- It is a special case of 'Data.List.minimumBy', which allows the
-- programmer to supply their own comparison function.
minimum :: (Ord a) => [a] -> a
{-# INLINABLE minimum #-}
minimum [] = errorEmptyList "minimum"
minimum xs = foldl1 min xs
{-# SPECIALIZE minimum :: [Int] -> Int #-}
{-# SPECIALIZE minimum :: [Integer] -> Integer #-}
-- | 'iterate' @f x@ returns an infinite list of repeated applications
-- of @f@ to @x@:
--
-- > iterate f x == [x, f x, f (f x), ...]
--
-- Note that 'iterate' is lazy, potentially leading to thunk build-up if
-- the consumer doesn't force each iterate. See 'iterate'' for a strict
-- variant of this function.
{-# NOINLINE [1] iterate #-}
iterate :: (a -> a) -> a -> [a]
iterate f x = x : iterate f (f x)
{-# INLINE [0] iterateFB #-} -- See Note [Inline FB functions]
iterateFB :: (a -> b -> b) -> (a -> a) -> a -> b
iterateFB c f x0 = go x0
where go x = x `c` go (f x)
{-# RULES
"iterate" [~1] forall f x. iterate f x = build (\c _n -> iterateFB c f x)
"iterateFB" [1] iterateFB (:) = iterate
#-}
-- | 'iterate'' is the strict version of 'iterate'.
--
-- It ensures that the result of each application of force to weak head normal
-- form before proceeding.
{-# NOINLINE [1] iterate' #-}
iterate' :: (a -> a) -> a -> [a]
iterate' f x =
let x' = f x
in x' `seq` (x : iterate' f x')
{-# INLINE [0] iterate'FB #-} -- See Note [Inline FB functions]
iterate'FB :: (a -> b -> b) -> (a -> a) -> a -> b
iterate'FB c f x0 = go x0
where go x =
let x' = f x
in x' `seq` (x `c` go x')
{-# RULES
"iterate'" [~1] forall f x. iterate' f x = build (\c _n -> iterate'FB c f x)
"iterate'FB" [1] iterate'FB (:) = iterate'
#-}
-- | 'repeat' @x@ is an infinite list, with @x@ the value of every element.
repeat :: a -> [a]
{-# INLINE [0] repeat #-}
-- The pragma just gives the rules more chance to fire
repeat x = xs where xs = x : xs
{-# INLINE [0] repeatFB #-} -- ditto -- See Note [Inline FB functions]
repeatFB :: (a -> b -> b) -> a -> b
repeatFB c x = xs where xs = x `c` xs
{-# RULES
"repeat" [~1] forall x. repeat x = build (\c _n -> repeatFB c x)
"repeatFB" [1] repeatFB (:) = repeat
#-}
-- | 'replicate' @n x@ is a list of length @n@ with @x@ the value of
-- every element.
-- It is an instance of the more general 'Data.List.genericReplicate',
-- in which @n@ may be of any integral type.
{-# INLINE replicate #-}
replicate :: Int -> a -> [a]
replicate n x = take n (repeat x)
-- | 'cycle' ties a finite list into a circular one, or equivalently,
-- the infinite repetition of the original list. It is the identity
-- on infinite lists.
cycle :: [a] -> [a]
cycle [] = errorEmptyList "cycle"
cycle xs = xs' where xs' = xs ++ xs'
-- | 'takeWhile', applied to a predicate @p@ and a list @xs@, returns the
-- longest prefix (possibly empty) of @xs@ of elements that satisfy @p@:
--
-- > takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2]
-- > takeWhile (< 9) [1,2,3] == [1,2,3]
-- > takeWhile (< 0) [1,2,3] == []
--
{-# NOINLINE [1] takeWhile #-}
takeWhile :: (a -> Bool) -> [a] -> [a]
takeWhile _ [] = []
takeWhile p (x:xs)
| p x = x : takeWhile p xs
| otherwise = []
{-# INLINE [0] takeWhileFB #-} -- See Note [Inline FB functions]
takeWhileFB :: (a -> Bool) -> (a -> b -> b) -> b -> a -> b -> b
takeWhileFB p c n = \x r -> if p x then x `c` r else n
-- The takeWhileFB rule is similar to the filterFB rule. It works like this:
-- takeWhileFB q (takeWhileFB p c n) n =
-- \x r -> if q x then (takeWhileFB p c n) x r else n =
-- \x r -> if q x then (\x' r' -> if p x' then x' `c` r' else n) x r else n =
-- \x r -> if q x then (if p x then x `c` r else n) else n =
-- \x r -> if q x && p x then x `c` r else n =
-- takeWhileFB (\x -> q x && p x) c n
{-# RULES
"takeWhile" [~1] forall p xs. takeWhile p xs =
build (\c n -> foldr (takeWhileFB p c n) n xs)
"takeWhileList" [1] forall p. foldr (takeWhileFB p (:) []) [] = takeWhile p
"takeWhileFB" forall c n p q. takeWhileFB q (takeWhileFB p c n) n =
takeWhileFB (\x -> q x && p x) c n
#-}
-- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@:
--
-- > dropWhile (< 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3]
-- > dropWhile (< 9) [1,2,3] == []
-- > dropWhile (< 0) [1,2,3] == [1,2,3]
--
dropWhile :: (a -> Bool) -> [a] -> [a]
dropWhile _ [] = []
dropWhile p xs@(x:xs')
| p x = dropWhile p xs'
| otherwise = xs
-- | 'take' @n@, applied to a list @xs@, returns the prefix of @xs@
-- of length @n@, or @xs@ itself if @n > 'length' xs@:
--
-- > take 5 "Hello World!" == "Hello"
-- > take 3 [1,2,3,4,5] == [1,2,3]
-- > take 3 [1,2] == [1,2]
-- > take 3 [] == []
-- > take (-1) [1,2] == []
-- > take 0 [1,2] == []
--
-- It is an instance of the more general 'Data.List.genericTake',
-- in which @n@ may be of any integral type.
take :: Int -> [a] -> [a]
#if defined(USE_REPORT_PRELUDE)
take n _ | n <= 0 = []
take _ [] = []
take n (x:xs) = x : take (n-1) xs
#else
{- We always want to inline this to take advantage of a known length argument
sign. Note, however, that it's important for the RULES to grab take, rather
than trying to INLINE take immediately and then letting the RULES grab
unsafeTake. Presumably the latter approach doesn't grab it early enough; it led
to an allocation regression in nofib/fft2. -}
{-# INLINE [1] take #-}
take n xs | 0 < n = unsafeTake n xs
| otherwise = []
-- A version of take that takes the whole list if it's given an argument less
-- than 1.
{-# NOINLINE [1] unsafeTake #-}
unsafeTake :: Int -> [a] -> [a]
unsafeTake !_ [] = []
unsafeTake 1 (x: _) = [x]
unsafeTake m (x:xs) = x : unsafeTake (m - 1) xs
{-# RULES
"take" [~1] forall n xs . take n xs =
build (\c nil -> if 0 < n
then foldr (takeFB c nil) (flipSeqTake nil) xs n
else nil)
"unsafeTakeList" [1] forall n xs . foldr (takeFB (:) []) (flipSeqTake []) xs n
= unsafeTake n xs
#-}
{-# INLINE [0] flipSeqTake #-}
-- Just flip seq, specialized to Int, but not inlined too early.
-- It's important to force the numeric argument here, even though
-- it's not used. Otherwise, take n [] doesn't force n. This is
-- bad for strictness analysis and unboxing, and leads to increased
-- allocation in T7257.
flipSeqTake :: a -> Int -> a
flipSeqTake x !_n = x
{-# INLINE [0] takeFB #-} -- See Note [Inline FB functions]
takeFB :: (a -> b -> b) -> b -> a -> (Int -> b) -> Int -> b
-- The \m accounts for the fact that takeFB is used in a higher-order
-- way by takeFoldr, so it's better to inline. A good example is
-- take n (repeat x)
-- for which we get excellent code... but only if we inline takeFB
-- when given four arguments
takeFB c n x xs
= \ m -> case m of
1 -> x `c` n
_ -> x `c` xs (m - 1)
#endif
-- | 'drop' @n xs@ returns the suffix of @xs@
-- after the first @n@ elements, or @[]@ if @n > 'length' xs@:
--
-- > drop 6 "Hello World!" == "World!"
-- > drop 3 [1,2,3,4,5] == [4,5]
-- > drop 3 [1,2] == []
-- > drop 3 [] == []
-- > drop (-1) [1,2] == [1,2]
-- > drop 0 [1,2] == [1,2]
--
-- It is an instance of the more general 'Data.List.genericDrop',
-- in which @n@ may be of any integral type.
drop :: Int -> [a] -> [a]
#if defined(USE_REPORT_PRELUDE)
drop n xs | n <= 0 = xs
drop _ [] = []
drop n (_:xs) = drop (n-1) xs
#else /* hack away */
{-# INLINE drop #-}
drop n ls
| n <= 0 = ls
| otherwise = unsafeDrop n ls
where
-- A version of drop that drops the whole list if given an argument
-- less than 1
unsafeDrop :: Int -> [a] -> [a]
unsafeDrop !_ [] = []
unsafeDrop 1 (_:xs) = xs
unsafeDrop m (_:xs) = unsafeDrop (m - 1) xs
#endif
-- | 'splitAt' @n xs@ returns a tuple where first element is @xs@ prefix of
-- length @n@ and second element is the remainder of the list:
--
-- > splitAt 6 "Hello World!" == ("Hello ","World!")
-- > splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])
-- > splitAt 1 [1,2,3] == ([1],[2,3])
-- > splitAt 3 [1,2,3] == ([1,2,3],[])
-- > splitAt 4 [1,2,3] == ([1,2,3],[])
-- > splitAt 0 [1,2,3] == ([],[1,2,3])
-- > splitAt (-1) [1,2,3] == ([],[1,2,3])
--
-- It is equivalent to @('take' n xs, 'drop' n xs)@ when @n@ is not @_|_@
-- (@splitAt _|_ xs = _|_@).
-- 'splitAt' is an instance of the more general 'Data.List.genericSplitAt',
-- in which @n@ may be of any integral type.
splitAt :: Int -> [a] -> ([a],[a])
#if defined(USE_REPORT_PRELUDE)
splitAt n xs = (take n xs, drop n xs)
#else
splitAt n ls
| n <= 0 = ([], ls)
| otherwise = splitAt' n ls
where
splitAt' :: Int -> [a] -> ([a], [a])
splitAt' _ [] = ([], [])
splitAt' 1 (x:xs) = ([x], xs)
splitAt' m (x:xs) = (x:xs', xs'')
where
(xs', xs'') = splitAt' (m - 1) xs
#endif /* USE_REPORT_PRELUDE */
-- | 'span', applied to a predicate @p@ and a list @xs@, returns a tuple where
-- first element is longest prefix (possibly empty) of @xs@ of elements that
-- satisfy @p@ and second element is the remainder of the list:
--
-- > span (< 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4])
-- > span (< 9) [1,2,3] == ([1,2,3],[])
-- > span (< 0) [1,2,3] == ([],[1,2,3])
--
-- 'span' @p xs@ is equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@
span :: (a -> Bool) -> [a] -> ([a],[a])
span _ xs@[] = (xs, xs)
span p xs@(x:xs')
| p x = let (ys,zs) = span p xs' in (x:ys,zs)
| otherwise = ([],xs)
-- | 'break', applied to a predicate @p@ and a list @xs@, returns a tuple where
-- first element is longest prefix (possibly empty) of @xs@ of elements that
-- /do not satisfy/ @p@ and second element is the remainder of the list:
--
-- > break (> 3) [1,2,3,4,1,2,3,4] == ([1,2,3],[4,1,2,3,4])
-- > break (< 9) [1,2,3] == ([],[1,2,3])
-- > break (> 9) [1,2,3] == ([1,2,3],[])
--
-- 'break' @p@ is equivalent to @'span' ('not' . p)@.
break :: (a -> Bool) -> [a] -> ([a],[a])
#if defined(USE_REPORT_PRELUDE)
break p = span (not . p)
#else
-- HBC version (stolen)
break _ xs@[] = (xs, xs)
break p xs@(x:xs')
| p x = ([],xs)
| otherwise = let (ys,zs) = break p xs' in (x:ys,zs)
#endif
-- | 'reverse' @xs@ returns the elements of @xs@ in reverse order.
-- @xs@ must be finite.
reverse :: [a] -> [a]
#if defined(USE_REPORT_PRELUDE)
reverse = foldl (flip (:)) []
#else
reverse l = rev l []
where
rev [] a = a
rev (x:xs) a = rev xs (x:a)
#endif
-- | 'and' returns the conjunction of a Boolean list. For the result to be
-- 'True', the list must be finite; 'False', however, results from a 'False'
-- value at a finite index of a finite or infinite list.
and :: [Bool] -> Bool
#if defined(USE_REPORT_PRELUDE)
and = foldr (&&) True
#else
and [] = True
and (x:xs) = x && and xs
{-# NOINLINE [1] and #-}
{-# RULES
"and/build" forall (g::forall b.(Bool->b->b)->b->b) .
and (build g) = g (&&) True
#-}
#endif
-- | 'or' returns the disjunction of a Boolean list. For the result to be
-- 'False', the list must be finite; 'True', however, results from a 'True'
-- value at a finite index of a finite or infinite list.
or :: [Bool] -> Bool
#if defined(USE_REPORT_PRELUDE)
or = foldr (||) False
#else
or [] = False
or (x:xs) = x || or xs
{-# NOINLINE [1] or #-}
{-# RULES
"or/build" forall (g::forall b.(Bool->b->b)->b->b) .
or (build g) = g (||) False
#-}
#endif
-- | Applied to a predicate and a list, 'any' determines if any element
-- of the list satisfies the predicate. For the result to be
-- 'False', the list must be finite; 'True', however, results from a 'True'
-- value for the predicate applied to an element at a finite index of a finite or infinite list.
any :: (a -> Bool) -> [a] -> Bool
#if defined(USE_REPORT_PRELUDE)
any p = or . map p
#else
any _ [] = False
any p (x:xs) = p x || any p xs
{-# NOINLINE [1] any #-}
{-# RULES
"any/build" forall p (g::forall b.(a->b->b)->b->b) .
any p (build g) = g ((||) . p) False
#-}
#endif
-- | Applied to a predicate and a list, 'all' determines if all elements
-- of the list satisfy the predicate. For the result to be
-- 'True', the list must be finite; 'False', however, results from a 'False'
-- value for the predicate applied to an element at a finite index of a finite or infinite list.
all :: (a -> Bool) -> [a] -> Bool
#if defined(USE_REPORT_PRELUDE)
all p = and . map p
#else
all _ [] = True
all p (x:xs) = p x && all p xs
{-# NOINLINE [1] all #-}
{-# RULES
"all/build" forall p (g::forall b.(a->b->b)->b->b) .
all p (build g) = g ((&&) . p) True
#-}
#endif
-- | 'elem' is the list membership predicate, usually written in infix form,
-- e.g., @x \`elem\` xs@. For the result to be
-- 'False', the list must be finite; 'True', however, results from an element
-- equal to @x@ found at a finite index of a finite or infinite list.
elem :: (Eq a) => a -> [a] -> Bool
#if defined(USE_REPORT_PRELUDE)
elem x = any (== x)
#else
elem _ [] = False
elem x (y:ys) = x==y || elem x ys
{-# NOINLINE [1] elem #-}
{-# RULES
"elem/build" forall x (g :: forall b . Eq a => (a -> b -> b) -> b -> b)
. elem x (build g) = g (\ y r -> (x == y) || r) False
#-}
#endif
-- | 'notElem' is the negation of 'elem'.
notElem :: (Eq a) => a -> [a] -> Bool
#if defined(USE_REPORT_PRELUDE)
notElem x = all (/= x)
#else
notElem _ [] = True
notElem x (y:ys)= x /= y && notElem x ys
{-# NOINLINE [1] notElem #-}
{-# RULES
"notElem/build" forall x (g :: forall b . Eq a => (a -> b -> b) -> b -> b)
. notElem x (build g) = g (\ y r -> (x /= y) && r) True
#-}
#endif
-- | \(\mathcal{O}(n)\). 'lookup' @key assocs@ looks up a key in an association
-- list.
--
-- >>> lookup 2 [(1, "first"), (2, "second"), (3, "third")]
-- Just "second"
lookup :: (Eq a) => a -> [(a,b)] -> Maybe b
lookup _key [] = Nothing
lookup key ((x,y):xys)
| key == x = Just y
| otherwise = lookup key xys
-- | Map a function over a list and concatenate the results.
concatMap :: (a -> [b]) -> [a] -> [b]
concatMap f = foldr ((++) . f) []
{-# NOINLINE [1] concatMap #-}
{-# RULES
"concatMap" forall f xs . concatMap f xs =
build (\c n -> foldr (\x b -> foldr c b (f x)) n xs)
#-}
-- | Concatenate a list of lists.
concat :: [[a]] -> [a]
concat = foldr (++) []
{-# NOINLINE [1] concat #-}
{-# RULES
"concat" forall xs. concat xs =
build (\c n -> foldr (\x y -> foldr c y x) n xs)
-- We don't bother to turn non-fusible applications of concat back into concat
#-}
-- | List index (subscript) operator, starting from 0.
-- It is an instance of the more general 'Data.List.genericIndex',
-- which takes an index of any integral type.
(!!) :: [a] -> Int -> a
#if defined(USE_REPORT_PRELUDE)
xs !! n | n < 0 = errorWithoutStackTrace "Prelude.!!: negative index"
[] !! _ = errorWithoutStackTrace "Prelude.!!: index too large"
(x:_) !! 0 = x
(_:xs) !! n = xs !! (n-1)
#else
-- We don't really want the errors to inline with (!!).
-- We may want to fuss around a bit with NOINLINE, and
-- if so we should be careful not to trip up known-bottom
-- optimizations.
tooLarge :: Int -> a
tooLarge _ = errorWithoutStackTrace (prel_list_str ++ "!!: index too large")
negIndex :: a
negIndex = errorWithoutStackTrace $ prel_list_str ++ "!!: negative index"
{-# INLINABLE (!!) #-}
xs !! n
| n < 0 = negIndex
| otherwise = foldr (\x r k -> case k of
0 -> x
_ -> r (k-1)) tooLarge xs n
#endif
--------------------------------------------------------------
-- The zip family
--------------------------------------------------------------
foldr2 :: (a -> b -> c -> c) -> c -> [a] -> [b] -> c
foldr2 k z = go
where
go [] _ys = z
go _xs [] = z
go (x:xs) (y:ys) = k x y (go xs ys)
{-# INLINE [0] foldr2 #-} -- See Note [Fusion for foldrN]
foldr2_left :: (a -> b -> c -> d) -> d -> a -> ([b] -> c) -> [b] -> d
foldr2_left _k z _x _r [] = z
foldr2_left k _z x r (y:ys) = k x y (r ys)
-- foldr2 k z xs ys = foldr (foldr2_left k z) (\_ -> z) xs ys
{-# RULES -- See Note [Fusion for foldrN]
"foldr2/left" forall k z ys (g::forall b.(a->b->b)->b->b) .
foldr2 k z (build g) ys = g (foldr2_left k z) (\_ -> z) ys
#-}
foldr3 :: (a -> b -> c -> d -> d) -> d -> [a] -> [b] -> [c] -> d
foldr3 k z = go
where
go [] _ _ = z
go _ [] _ = z
go _ _ [] = z
go (a:as) (b:bs) (c:cs) = k a b c (go as bs cs)
{-# INLINE [0] foldr3 #-} -- See Note [Fusion for foldrN]
foldr3_left :: (a -> b -> c -> d -> e) -> e -> a ->
([b] -> [c] -> d) -> [b] -> [c] -> e
foldr3_left k _z a r (b:bs) (c:cs) = k a b c (r bs cs)
foldr3_left _ z _ _ _ _ = z
-- foldr3 k n xs ys zs = foldr (foldr3_left k n) (\_ _ -> n) xs ys zs
{-# RULES -- See Note [Fusion for foldrN]
"foldr3/left" forall k z (g::forall b.(a->b->b)->b->b).
foldr3 k z (build g) = g (foldr3_left k z) (\_ _ -> z)
#-}
{- Note [Fusion for foldrN]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
We arrange that foldr2, foldr3, etc is a good consumer for its first
(left) list argument. Here's how. See below for the second, third
etc list arguments
* The rule "foldr2/left" (active only before phase 1) does this:
foldr2 k z (build g) ys = g (foldr2_left k z) (\_ -> z) ys
thereby fusing away the 'build' on the left argument
* To ensure this rule has a chance to fire, foldr2 has a NOINLINE[1] pragma
There used to be a "foldr2/right" rule, allowing foldr2 to fuse with a build
form on the right. However, this causes trouble if the right list ends in
a bottom that is only avoided by the left list ending at that spot. That is,
foldr2 f z [a,b,c] (d:e:f:_|_), where the right list is produced by a build
form, would cause the foldr2/right rule to introduce bottom. Example:
zip [1,2,3,4] (unfoldr (\s -> if s > 4 then undefined else Just (s,s+1)) 1)
should produce
[(1,1),(2,2),(3,3),(4,4)]
but with the foldr2/right rule it would instead produce
(1,1):(2,2):(3,3):(4,4):_|_
Note [Fusion for zipN/zipWithN]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We arrange that zip, zip3, etc, and zipWith, zipWit3 etc, are all
good consumers for their first (left) argument, and good producers.
Here's how. See Note [Fusion for foldr2] for why it can't fuse its
second (right) list argument.
NB: Zips for larger tuples are in the List module.
* Rule "zip" (active only before phase 1) rewrites
zip xs ys = build (\c n -> foldr2 (zipFB c) n xs ys)
See also Note [Inline FB functions]
Ditto rule "zipWith".
* To give this rule a chance to fire, we give zip a NOLINLINE[1]
pragma (although since zip is recursive it might not need it)
* Now the rules for foldr2 (see Note [Fusion for foldr2]) may fire,
or rules that fuse the build-produced output of zip.
* If none of these fire, rule "zipList" (active only in phase 1)
rewrites the foldr2 call back to zip
foldr2 (zipFB (:)) [] = zip
This rule will only fire when build has inlined, which also
happens in phase 1.
Ditto rule "zipWithList".
-}
----------------------------------------------
-- | \(\mathcal{O}(\min(m,n))\). 'zip' takes two lists and returns a list of
-- corresponding pairs.
--
-- > zip [1, 2] ['a', 'b'] = [(1, 'a'), (2, 'b')]
--
-- If one input list is short, excess elements of the longer list are
-- discarded:
--
-- > zip [1] ['a', 'b'] = [(1, 'a')]
-- > zip [1, 2] ['a'] = [(1, 'a')]
--
-- 'zip' is right-lazy:
--
-- > zip [] _|_ = []
-- > zip _|_ [] = _|_
--
-- 'zip' is capable of list fusion, but it is restricted to its
-- first list argument and its resulting list.
{-# NOINLINE [1] zip #-} -- See Note [Fusion for zipN/zipWithN]
zip :: [a] -> [b] -> [(a,b)]
zip [] _bs = []
zip _as [] = []
zip (a:as) (b:bs) = (a,b) : zip as bs
{-# INLINE [0] zipFB #-} -- See Note [Inline FB functions]
zipFB :: ((a, b) -> c -> d) -> a -> b -> c -> d
zipFB c = \x y r -> (x,y) `c` r
{-# RULES -- See Note [Fusion for zipN/zipWithN]
"zip" [~1] forall xs ys. zip xs ys = build (\c n -> foldr2 (zipFB c) n xs ys)
"zipList" [1] foldr2 (zipFB (:)) [] = zip
#-}
----------------------------------------------
-- | 'zip3' takes three lists and returns a list of triples, analogous to
-- 'zip'.
-- It is capable of list fusion, but it is restricted to its
-- first list argument and its resulting list.
{-# NOINLINE [1] zip3 #-}
zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
-- Specification
-- zip3 = zipWith3 (,,)
zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs
zip3 _ _ _ = []
{-# INLINE [0] zip3FB #-} -- See Note [Inline FB functions]
zip3FB :: ((a,b,c) -> xs -> xs') -> a -> b -> c -> xs -> xs'
zip3FB cons = \a b c r -> (a,b,c) `cons` r
{-# RULES -- See Note [Fusion for zipN/zipWithN]
"zip3" [~1] forall as bs cs. zip3 as bs cs = build (\c n -> foldr3 (zip3FB c) n as bs cs)
"zip3List" [1] foldr3 (zip3FB (:)) [] = zip3
#-}
-- The zipWith family generalises the zip family by zipping with the
-- function given as the first argument, instead of a tupling function.
----------------------------------------------
-- | \(\mathcal{O}(\min(m,n))\). 'zipWith' generalises 'zip' by zipping with the
-- function given as the first argument, instead of a tupling function. For
-- example, @'zipWith' (+)@ is applied to two lists to produce the list of
-- corresponding sums:
--
-- >>> zipWith (+) [1, 2, 3] [4, 5, 6]
-- [5,7,9]
--
-- 'zipWith' is right-lazy:
--
-- > zipWith f [] _|_ = []
--
-- 'zipWith' is capable of list fusion, but it is restricted to its
-- first list argument and its resulting list.
{-# NOINLINE [1] zipWith #-} -- See Note [Fusion for zipN/zipWithN]
zipWith :: (a->b->c) -> [a]->[b]->[c]
zipWith f = go
where
go [] _ = []
go _ [] = []
go (x:xs) (y:ys) = f x y : go xs ys
-- zipWithFB must have arity 2 since it gets two arguments in the "zipWith"
-- rule; it might not get inlined otherwise
{-# INLINE [0] zipWithFB #-} -- See Note [Inline FB functions]
zipWithFB :: (a -> b -> c) -> (d -> e -> a) -> d -> e -> b -> c
zipWithFB c f = \x y r -> (x `f` y) `c` r
{-# RULES -- See Note [Fusion for zipN/zipWithN]
"zipWith" [~1] forall f xs ys. zipWith f xs ys = build (\c n -> foldr2 (zipWithFB c f) n xs ys)
"zipWithList" [1] forall f. foldr2 (zipWithFB (:) f) [] = zipWith f
#-}
-- | The 'zipWith3' function takes a function which combines three
-- elements, as well as three lists and returns a list of their point-wise
-- combination, analogous to 'zipWith'.
-- It is capable of list fusion, but it is restricted to its
-- first list argument and its resulting list.
{-# NOINLINE [1] zipWith3 #-}
zipWith3 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
zipWith3 z = go
where
go (a:as) (b:bs) (c:cs) = z a b c : go as bs cs
go _ _ _ = []
{-# INLINE [0] zipWith3FB #-} -- See Note [Inline FB functions]
zipWith3FB :: (d -> xs -> xs') -> (a -> b -> c -> d) -> a -> b -> c -> xs -> xs'
zipWith3FB cons func = \a b c r -> (func a b c) `cons` r
{-# RULES
"zipWith3" [~1] forall f as bs cs. zipWith3 f as bs cs = build (\c n -> foldr3 (zipWith3FB c f) n as bs cs)
"zipWith3List" [1] forall f. foldr3 (zipWith3FB (:) f) [] = zipWith3 f
#-}
-- | 'unzip' transforms a list of pairs into a list of first components
-- and a list of second components.
unzip :: [(a,b)] -> ([a],[b])
{-# INLINE unzip #-}
-- Inline so that fusion `foldr` has an opportunity to fire.
-- See Note [Inline @unzipN@ functions] in GHC/OldList.hs.
unzip = foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])
-- | The 'unzip3' function takes a list of triples and returns three
-- lists, analogous to 'unzip'.
unzip3 :: [(a,b,c)] -> ([a],[b],[c])
{-# INLINE unzip3 #-}
-- Inline so that fusion `foldr` has an opportunity to fire.
-- See Note [Inline @unzipN@ functions] in GHC/OldList.hs.
unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
([],[],[])
--------------------------------------------------------------
-- Error code
--------------------------------------------------------------
-- Common up near identical calls to `error' to reduce the number
-- constant strings created when compiled:
errorEmptyList :: String -> a
errorEmptyList fun =
errorWithoutStackTrace (prel_list_str ++ fun ++ ": empty list")
prel_list_str :: String
prel_list_str = "Prelude."
|
sdiehl/ghc
|
libraries/base/GHC/List.hs
|
bsd-3-clause
| 42,559 | 0 | 14 | 11,334 | 6,035 | 3,464 | 2,571 | 445 | 4 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE UnicodeSyntax #-}
{-|
[@ISO639-1@] oc
[@ISO639-2@] oci
[@ISO639-3@] oci
[@Native name@] occitan, lenga d'òc
[@English name@] Occitan
-}
module Text.Numeral.Language.OCI.TestData (cardinals) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
import "base" Prelude ( Num )
import "numerals" Text.Numeral.Grammar.Reified ( defaultInflection )
import "this" Text.Numeral.Test ( TestData )
--------------------------------------------------------------------------------
-- Test data
--------------------------------------------------------------------------------
{-
Sources:
http://www.languagesandnumbers.com/how-to-count-in-occitan/en/oci/http://www.languagesandnumbers.com/how-to-count-in-occitan/en/oci/
Note: This is the Languedocien dialect.
-}
cardinals ∷ (Num i) ⇒ TestData i
cardinals =
[ ( "default"
, defaultInflection
, [ (0, "zèro")
, (1, "un")
, (2, "dos")
, (3, "tres")
, (4, "quatre")
, (5, "cinc")
, (6, "sièis")
, (7, "sèt")
, (8, "uèch")
, (9, "nòu")
, (10, "dètz")
, (11, "onze")
, (12, "dotze")
, (13, "tretze")
, (14, "catòrze")
, (15, "quinze")
, (16, "setze")
, (17, "dètz-e-sèt")
, (18, "dètz-e-uèch")
, (19, "dètz-e-nòu")
, (20, "vint")
, (21, "vint-e-un")
, (22, "vint-e-dos")
, (23, "vint-e-tres")
, (24, "vint-e-quatre")
, (25, "vint-e-cinc")
, (26, "vint-e-sièis")
, (27, "vint-e-sèt")
, (28, "vint-e-uèch")
, (29, "vint-e-nòu")
, (30, "trenta")
, (31, "trenta un")
, (32, "trenta dos")
, (33, "trenta tres")
, (34, "trenta quatre")
, (35, "trenta cinc")
, (36, "trenta sièis")
, (37, "trenta sèt")
, (38, "trenta uèch")
, (39, "trenta nòu")
, (40, "quaranta")
, (41, "quaranta un")
, (42, "quaranta dos")
, (43, "quaranta tres")
, (44, "quaranta quatre")
, (45, "quaranta cinc")
, (46, "quaranta sièis")
, (47, "quaranta sèt")
, (48, "quaranta uèch")
, (49, "quaranta nòu")
, (50, "cinquanta")
, (51, "cinquanta un")
, (52, "cinquanta dos")
, (53, "cinquanta tres")
, (54, "cinquanta quatre")
, (55, "cinquanta cinc")
, (56, "cinquanta sièis")
, (57, "cinquanta sèt")
, (58, "cinquanta uèch")
, (59, "cinquanta nòu")
, (60, "seissanta")
, (61, "seissanta un")
, (62, "seissanta dos")
, (63, "seissanta tres")
, (64, "seissanta quatre")
, (65, "seissanta cinc")
, (66, "seissanta sièis")
, (67, "seissanta sèt")
, (68, "seissanta uèch")
, (69, "seissanta nòu")
, (70, "setanta")
, (71, "setanta un")
, (72, "setanta dos")
, (73, "setanta tres")
, (74, "setanta quatre")
, (75, "setanta cinc")
, (76, "setanta sièis")
, (77, "setanta sèt")
, (78, "setanta uèch")
, (79, "setanta nòu")
, (80, "ochanta")
, (81, "ochanta un")
, (82, "ochanta dos")
, (83, "ochanta tres")
, (84, "ochanta quatre")
, (85, "ochanta cinc")
, (86, "ochanta sièis")
, (87, "ochanta sèt")
, (88, "ochanta uèch")
, (89, "ochanta nòu")
, (90, "nonanta")
, (91, "nonanta un")
, (92, "nonanta dos")
, (93, "nonanta tres")
, (94, "nonanta quatre")
, (95, "nonanta cinc")
, (96, "nonanta sièis")
, (97, "nonanta sèt")
, (98, "nonanta uèch")
, (99, "nonanta nòu")
, (100, "cent")
, (101, "cent un")
, (102, "cent dos")
, (103, "cent tres")
, (104, "cent quatre")
, (105, "cent cinc")
, (106, "cent sièis")
, (107, "cent sèt")
, (108, "cent uèch")
, (109, "cent nòu")
, (110, "cent dètz")
, (123, "cent vint-e-tres")
, (200, "dos cents")
, (300, "tres cents")
, (321, "tres cents vint-e-un")
, (400, "quatre cents")
, (500, "cinc cents")
, (600, "sièis cents")
, (700, "sèt cents")
, (800, "uèch cents")
, (900, "nòu cents")
, (909, "nòu cents nòu")
, (990, "nòu cents nonanta")
, (999, "nòu cents nonanta nòu")
, (1000, "mila")
, (1001, "mila un")
, (1008, "mila uèch")
, (1234, "mila dos cents trenta quatre")
, (2000, "dos mila")
, (3000, "tres mila")
, (4000, "quatre mila")
, (4321, "quatre mila tres cents vint-e-un")
, (5000, "cinc mila")
, (6000, "sièis mila")
, (7000, "sèt mila")
, (8000, "uèch mila")
, (9000, "nòu mila")
, (10000, "dètz mila")
, (12345, "dotze mila tres cents quaranta cinc")
, (20000, "vint mila")
, (30000, "trenta mila")
, (40000, "quaranta mila")
, (50000, "cinquanta mila")
, (54321, "cinquanta quatre mila tres cents vint-e-un")
, (60000, "seissanta mila")
, (70000, "setanta mila")
, (80000, "ochanta mila")
, (90000, "nonanta mila")
, (100000, "cent mila")
, (123456, "cent vint-e-tres mila quatre cents cinquanta sièis")
, (200000, "dos cents mila")
, (300000, "tres cents mila")
, (400000, "quatre cents mila")
, (500000, "cinc cents mila")
, (600000, "sièis cents mila")
, (654321, "sièis cents cinquanta quatre mila tres cents vint-e-un")
, (700000, "sèt cents mila")
, (800000, "uèch cents mila")
, (900000, "nòu cents mila")
, (1000000, "un milion")
, (1000001, "un milion un")
, (1234567, "un milion dos cents trenta quatre mila cinc cents seissanta sèt")
, (2000000, "dos milions")
, (3000000, "tres milions")
, (4000000, "quatre milions")
, (5000000, "cinc milions")
, (6000000, "sièis milions")
, (7000000, "sèt milions")
, (7654321, "sèt milions sièis cents cinquanta quatre mila tres cents vint-e-un")
, (8000000, "uèch milions")
, (9000000, "nòu milions")
, (1000000000, "un miliard")
, (1000000001, "un miliard un")
, (2000000000, "dos miliards")
, (3000000000, "tres miliards")
, (4000000000, "quatre miliards")
, (5000000000, "cinc miliards")
, (6000000000, "sièis miliards")
, (7000000000, "sèt miliards")
, (8000000000, "uèch miliards")
, (9000000000, "nòu miliards")
]
)
]
|
telser/numerals
|
src-test/Text/Numeral/Language/OCI/TestData.hs
|
bsd-3-clause
| 6,803 | 0 | 8 | 1,985 | 1,723 | 1,151 | 572 | 193 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent.MVar
import Control.Monad.IO.Class (liftIO)
import Prelude hiding (concat)
import Data.Conduit
import Data.Conduit.Network
import Data.Conduit.Text as DCT
import Data.Text (Text, concat, pack)
import qualified Data.Text.IO as TI
import YOLP
import Vim
defaultPort :: IO Int
defaultPort = return 5678
main :: IO ()
main = do
exitWatcher <- newEmptyMVar
port <- defaultPort
putStrLn $ "listening on " ++ show port
forkTCPServer (serverSettings port "*") (run exitWatcher)
takeMVar exitWatcher *> putStrLn "exit."
run ew appData =
appSource appData $$ decode utf8
=$= conduit ew
=$= encode utf8
=$= appSink appData
conduit :: MVar () -> ConduitM Text Text IO ()
conduit ew = do
msg <- (parseMsg <$>) <$> await
case msg of
Nothing -> liftIO $ do
putStr "Connection closed."
putMVar ew ()
(Just (n,loc)) -> do
x <- liftIO $ reportRainAt loc
respond (n,x)
conduit ew
respond (n,resp)
= yield . concat $ [
"[",
pack . show $ n,
",",
"\"",
resp,
"\"",
"]"
]
|
lesguillemets/rainfall-vim-hs
|
app/Main.hs
|
bsd-3-clause
| 1,304 | 0 | 14 | 439 | 399 | 209 | 190 | 46 | 2 |
{-# OPTIONS -Wall #-}
-- The grm grammar generator
-- Copyright 2011-2012, Brett Letner
module Grm.Lex
( Token(..)
, Point(..)
, lexFilePath
, lexContents
, ppToken
, ppTokenList
, happyError
, notWSToken
, unTWhitespace
, unTSLComment
, unTMLComment
, unTString
, unTChar
, unTNumber
, unTSymbol
, unTUsym
, unTUident
, unTLident
) where
import Control.Monad
import Data.Char
-- import Numeric
import Data.List
import Grm.Prims
import Text.PrettyPrint.Leijen
happyError :: [Token Point] -> a
happyError [] = error "unexpected end of tokens"
happyError (t:_) = error $ ppErr (startLoc t) ("unexpected token: " ++ show (show (ppToken t)))
-- fixme: doesn't work for empty modules (e.g. module Foo where)
notWSToken :: Token t -> Bool
notWSToken t = case t of
TWhitespace{} -> False
TSLComment{} -> False
TMLComment{} -> False
_ -> True
data Token a
= TWhitespace a String
| TSLComment a String
| TMLComment a String
| TString a String
| TChar a Char
| TNumber a String
| TSymbol a String
| TUsym a String
| TUident a String
| TLident a String
deriving (Show)
unTWhitespace :: Token t -> String
unTWhitespace (TWhitespace _ b) = b
unTWhitespace _ = error "unTWhitespace"
unTSLComment :: Token t -> String
unTSLComment (TSLComment _ b) = b
unTSLComment _ = error "unTSLComment"
unTMLComment :: Token t -> String
unTMLComment (TMLComment _ b) = b
unTMLComment _ = error "unTMLComment"
unTString :: Token t -> String
unTString (TString _ b) = b
unTString _ = error "unTString"
unTChar :: Token t -> Char
unTChar (TChar _ b) = b
unTChar _ = error "unTChar"
unTNumber :: Token t -> String
unTNumber (TNumber _ b) = b
unTNumber _ = error "unTNumber"
unTSymbol :: Token t -> String
unTSymbol (TSymbol _ b) = b
unTSymbol _ = error "unTSymbol"
unTUsym :: Token t -> String
unTUsym (TUsym _ b) = b
unTUsym _ = error "unTUsym"
unTUident :: Token t -> String
unTUident (TUident _ b) = b
unTUident _ = error "unTUident"
unTLident :: Token t -> String
unTLident (TLident _ b) = b
unTLident _ = error "unTLident"
instance Eq (Token a) where
(==) a b = case (a,b) of
(TWhitespace _ x, TWhitespace _ y) -> x == y
(TSLComment _ x, TSLComment _ y) -> x == y
(TMLComment _ x, TMLComment _ y) -> x == y
(TString _ x, TString _ y) -> x == y
(TChar _ x, TChar _ y) -> x == y
(TNumber _ x, TNumber _ y) -> x == y -- numbers are compared lexically
(TSymbol _ x, TSymbol _ y) -> x == y
(TUsym _ x, TUsym _ y) -> x == y
(TUident _ x, TUident _ y) -> x == y
(TLident _ x, TLident _ y) -> x == y
_ -> False
ppTokenList :: [Token a] -> Doc
ppTokenList = sep . map ppToken
ppToken :: Token a -> Doc
ppToken t = text $ case t of
TWhitespace _ s -> s
TSLComment _ s -> s
TMLComment _ s -> s
TString _ a -> show a
TChar _ a -> show a
TNumber _ s -> s
TSymbol _ s -> s
TUsym _ s -> s
TUident _ s -> s
TLident _ s -> s
instance HasMeta Token where
meta t = case t of
TWhitespace a _ -> a
TSLComment a _ -> a
TMLComment a _ -> a
TString a _ -> a
TChar a _ -> a
TNumber a _ -> a
TSymbol a _ -> a
TUsym a _ -> a
TUident a _ -> a
TLident a _ -> a
-- mapMetaM f t = case t of
-- TWhitespace a b -> f a >>= \x -> return (TWhitespace x b)
-- TSLComment a b -> f a >>= \x -> return (TSLComment x b)
-- TMLComment a b -> f a >>= \x -> return (TMLComment x b)
-- TString a b -> f a >>= \x -> return (TString x b)
-- TChar a b -> f a >>= \x -> return (TChar x b)
-- TNumber a b -> f a >>= \x -> return (TNumber x b)
-- TSymbol a b -> f a >>= \x -> return (TSymbol x b)
-- TUsym a b -> f a >>= \x -> return (TUsym x b)
-- TUident a b -> f a >>= \x -> return (TUident x b)
-- TLident a b -> f a >>= \x -> return (TLident x b)
lexFilePath :: [String] -> FilePath -> IO [Token Point]
lexFilePath syms fn = do
s <- readFile fn
lexContents syms fn s
lexContents :: [String] -> FilePath -> String -> IO [Token Point]
lexContents syms fn s = do
let st0 = initSt syms fn $ filter ((/=) '\r') s
let M f = lexTokens
case f st0 of
(Left e, st) -> error $ ppErr (stLoc st) e
(Right ts, st) -> case stInput st of
"" -> return ts
e -> error $ ppErr (stLoc st) $ "lexical error:" ++ show (head e)
initSt :: [String] -> FilePath -> String -> St
initSt syms fn s = St
{ stLoc = initLoc fn
, stInput = s
, stSymbols = syms
}
instance Monad M where
(M f) >>= g = M $ \st ->
let (ma, st1) = f st
in case ma of
Left e -> (Left e, st)
Right a ->
let M h = g a
in h st1
return a = M $ \st -> (Right a, st)
fail s = M $ \st -> (Left s, st)
data M a = M (St -> (Either String a, St))
getSt :: M St
getSt = M $ \st -> (Right st, st)
lexAnyChar :: M Char
lexAnyChar = M $ \st ->
let
loc0 = stLoc st
in case stInput st of
"" -> (Left "unexpected eof", st)
(c:cs) | c == eolChar ->
(Right c, st{ stInput = cs
, stLoc = loc0{ locColumn = 0, locLine = succ (locLine loc0) }})
(c:cs) ->
(Right c, st{ stInput = cs
, stLoc = loc0{ locColumn = succ (locColumn loc0) }})
tryLex :: M a -> M (Maybe a)
tryLex (M f) = M $ \st -> case f st of
(Left _, _) -> (Right Nothing, st)
(Right a, st1) -> (Right $ Just a, st1)
data St = St
{ stLoc :: Loc
, stInput :: String
, stSymbols :: [String]
} deriving (Show)
qualChar :: Char
qualChar = '.'
escChar :: Char
escChar = '\\'
dQuoteChar :: Char
dQuoteChar = '"'
sQuoteChar :: Char
sQuoteChar = '\''
eolChar :: Char
eolChar = '\n'
wsChar :: String
wsChar = [ ' ', eolChar ]
slCommentStart :: String
slCommentStart = "//"
mlCommentStart :: String
mlCommentStart = "/*"
mlCommentEnd :: String
mlCommentEnd = "*/"
-- slCommentStart = "--", doesn't work if you support the decrement statement, e.g. i--
-- mlCommentStart = "{-"
-- mlCommentEnd = "-}"
uidentStart :: String
uidentStart = [ 'A' .. 'Z' ]
lidentStart :: String
lidentStart = '_' : [ 'a' .. 'z' ]
identEnd :: String
identEnd = uidentStart ++ lidentStart ++ [ '0' .. '9' ]
getLoc :: M Loc
getLoc = liftM stLoc getSt
getSymbols :: M [String]
getSymbols = liftM stSymbols getSt
lexStringLit :: String -> M String
lexStringLit s = do
s1 <- sequence $ replicate (length s) lexAnyChar
if s1 == s
then return s
else fail $ "unexpected string:" ++ s
lexCharPred :: (Char -> Bool) -> M Char
lexCharPred p = do
c <- lexAnyChar
if p c
then return c
else fail $ "unexpected char:" ++ show c
many :: M a -> M [a]
many m = do
mx <- tryLex m
case mx of
Just x -> do
xs <- many m
return $ x : xs
Nothing -> return []
oneof :: [M a] -> M a
oneof [] = fail "token doesn't match any alternatives"
oneof (m:ms) = do
mx <- tryLex m
case mx of
Just x -> return x
Nothing -> oneof ms
lexKeyword :: M (Token Point)
lexKeyword = do
a <- getLoc
s <- oneof [ lexUpperWord, lexLowerWord ]
ss <- getSymbols
b <- getLoc
if s `elem` ss
then return $ TSymbol (Point a b) s
else fail $ "not a keyword:" ++ s
lexSymbol :: M (Token Point)
lexSymbol = do
a <- getLoc
ss <- getSymbols
s <- oneof [ lexUsymTok, liftM singleton $ lexCharPred (flip elem symChar) ]
b <- getLoc
if s `elem` ss
then return $ TSymbol (Point a b) s
else fail $ "not a symbol:" ++ s
usymChar :: String
usymChar = "!#$%&*+-/:<=>?@\\^|~"
symChar :: String
symChar = "(),;`{}[]."
lexUsymTok :: M String
lexUsymTok = many1 (lexCharPred $ flip elem usymChar)
lexUsym :: M (Token Point)
lexUsym = do
a <- getLoc
s <- lexUsymTok
b <- getLoc
return $ TUsym (Point a b) s
lexUident :: M (Token Point)
lexUident = do
a <- getLoc
s <- lexQualified
b <- getLoc
return $ TUident (Point a b) s
lexLident :: M (Token Point)
lexLident = do
a <- getLoc
s <- oneof [ lexLowerQualified, lexLowerWord ]
b <- getLoc
return $ TLident (Point a b) s
lexLowerQualified :: M String
lexLowerQualified = do
s1 <- lexQualified
s2 <- do
_ <- lexCharPred ((==) qualChar)
lexLowerWord
return $ qualify [s1,s2]
lexQualified :: M String
lexQualified = do
s0 <- lexUpperWord
ss <- many $ do
_ <- lexCharPred ((==) qualChar)
s <- lexUpperWord
return s
return $ qualify $ s0 : ss
lexUpperWord :: M String
lexUpperWord = do
c <- lexCharPred (flip elem uidentStart)
cs <- many $ lexCharPred (flip elem identEnd)
return $ c : cs
lexLowerWord :: M String
lexLowerWord = do
c <- lexCharPred (flip elem lidentStart)
cs <- many $ lexCharPred (flip elem identEnd)
return $ c : cs
qualify :: [String] -> String
qualify = concat . intersperse [qualChar]
many1 :: M a -> M [a]
many1 m = do
x <- m
xs <- many m
return $ x : xs
lexTokens :: M [Token Point]
lexTokens = many lexToken
lexToken :: M (Token Point)
lexToken = oneof
[ lexWhitespace
, lexSingleLineComment
, lexMultiLineComment
, lexString
, lexChar
, lexNumber
, lexKeyword
, lexLident -- must be before lexUident for qualification
, lexUident
, lexSymbol
, lexUsym
]
lexWhitespace :: M (Token Point)
lexWhitespace = do
a <- getLoc
s <- many1 $ lexCharPred (flip elem wsChar)
b <- getLoc
return $ TWhitespace (Point a b) s
lexSingleLineComment :: M (Token Point)
lexSingleLineComment = do
a <- getLoc
_ <- lexStringLit slCommentStart
cs <- many $ lexCharPred ((/=) eolChar)
b <- getLoc
return $ TSLComment (Point a b) $ slCommentStart ++ cs
lexMultiLineComment :: M (Token Point)
lexMultiLineComment = do
a <- getLoc
s <- lexMLCommentStart
b <- getLoc
return $ TMLComment (Point a b) s
lexMLCommentStart :: M String
lexMLCommentStart = do
sa <- lexStringLit mlCommentStart
sb <- lexMLCommentEnd
return $ sa ++ sb
lexMLCommentEnd :: M String
lexMLCommentEnd = do
ms0 <- tryLex $ lexStringLit mlCommentEnd
case ms0 of
Just s -> return s
Nothing -> do
ms <- tryLex lexMLCommentStart
sa <- case ms of
Just s -> return s
Nothing -> do
c <- lexAnyChar
return [c]
sb <- lexMLCommentEnd
return $ sa ++ sb
lexChar :: M (Token Point)
lexChar = do
a <- getLoc
_ <- lexCharPred ((==) sQuoteChar)
s <- oneof [ lexEscChar, liftM singleton $ lexCharPred ((/=) sQuoteChar) ]
_ <- lexCharPred ((==) sQuoteChar)
b <- getLoc
return $ TChar (Point a b) $ read ([sQuoteChar] ++ s ++ [sQuoteChar])
lexString :: M (Token Point)
lexString = do
a <- getLoc
_ <- lexCharPred ((==) dQuoteChar)
s <- liftM concat $ many $ oneof [ lexEscChar, liftM singleton $ lexCharPred ((/=) dQuoteChar) ]
_ <- lexCharPred ((==) dQuoteChar)
b <- getLoc
return $ TString (Point a b) $ read ([dQuoteChar] ++ s ++ [dQuoteChar])
lexDot :: M String
lexDot = liftM singleton $ lexCharPred ((==) '.')
lexSeq :: [M String] -> M String
lexSeq = liftM concat . sequence
lexExponent :: M String
lexExponent = do
a <- liftM toLower $
oneof [ lexCharPred ((==) 'e'), lexCharPred ((==) 'E') ]
b <- oneof [ lexCharPred ((==) '+') >> return ""
, liftM singleton $ lexCharPred ((==) '-')
, return ""
]
c <- lexDecimal
return $ a : b ++ c
lexNumber :: M (Token Point)
lexNumber = do
a <- getLoc
c <- oneof
[ liftM singleton $ lexCharPred ((==) '-')
, return ""
]
s <- oneof
[ lex0x "0x" isHexit
, lex0x "0X" isHexit
, lex0x "0o" isOctit
, lex0x "0O" isOctit
, lex0x "0b" isBinit
, lex0x "0B" isBinit
, lexFloat
, lexDecimal
]
b <- getLoc
return $ TNumber (Point a b) $ c ++ s
lexFloat :: M String
lexFloat = oneof
[ lexSeq [ lexDecimal, lexDot, lexDecimal, lexExponent ]
, lexSeq [ lexDecimal, lexDot, lexDecimal ]
, lexSeq [ lexDecimal, lexExponent ]
]
lexDecimal :: M String
lexDecimal = liftM delLeadingZeros $ many1 $ lexCharPred isDigit
lex0x :: String -> (Char -> Bool) -> M String
lex0x s f = do
cs <- sequence [lexCharPred ((==) c) | c <- s]
ds <- many1 $ lexCharPred f
return $ map toLower (cs ++ delLeadingZeros ds)
delLeadingZeros :: String -> String
delLeadingZeros x = case dropWhile ((==) '0') x of
[] -> "0"
a -> a
isHexit :: Char -> Bool
isHexit c = isDigit c || toLower c `elem` ['a' .. 'f']
isOctit :: Char -> Bool
isOctit c = c `elem` ['0' .. '7']
isBinit :: Char -> Bool
isBinit c = c `elem` ['0','1']
lexEscChar :: M String
lexEscChar = do
_ <- lexCharPred ((==) escChar)
s <- oneof
[ liftM (show . (read :: String -> Int)) lexDecimal
, liftM singleton lexAnyChar
]
return $ escChar : s
|
stevezhee/grm
|
Grm/Lex.hs
|
bsd-3-clause
| 12,623 | 0 | 20 | 3,334 | 5,014 | 2,531 | 2,483 | 424 | 10 |
{-# LANGUAGE CPP, GeneralizedNewtypeDeriving #-}
--------------------------------------------------------------------------------
-- | The LLVM Type System.
--
module Llvm.Types where
#include "HsVersions.h"
import GhcPrelude
import Data.Char
import Data.Int
import Numeric
import DynFlags
import FastString
import Outputable
import Unique
-- from NCG
import PprBase
import GHC.Float
-- -----------------------------------------------------------------------------
-- * LLVM Basic Types and Variables
--
-- | A global mutable variable. Maybe defined or external
data LMGlobal = LMGlobal {
getGlobalVar :: LlvmVar, -- ^ Returns the variable of the 'LMGlobal'
getGlobalValue :: Maybe LlvmStatic -- ^ Return the value of the 'LMGlobal'
}
-- | A String in LLVM
type LMString = FastString
-- | A type alias
type LlvmAlias = (LMString, LlvmType)
-- | Llvm Types
data LlvmType
= LMInt Int -- ^ An integer with a given width in bits.
| LMFloat -- ^ 32 bit floating point
| LMDouble -- ^ 64 bit floating point
| LMFloat80 -- ^ 80 bit (x86 only) floating point
| LMFloat128 -- ^ 128 bit floating point
| LMPointer LlvmType -- ^ A pointer to a 'LlvmType'
| LMArray Int LlvmType -- ^ An array of 'LlvmType'
| LMVector Int LlvmType -- ^ A vector of 'LlvmType'
| LMLabel -- ^ A 'LlvmVar' can represent a label (address)
| LMVoid -- ^ Void type
| LMStruct [LlvmType] -- ^ Packed structure type
| LMStructU [LlvmType] -- ^ Unpacked structure type
| LMAlias LlvmAlias -- ^ A type alias
| LMMetadata -- ^ LLVM Metadata
-- | Function type, used to create pointers to functions
| LMFunction LlvmFunctionDecl
deriving (Eq)
instance Outputable LlvmType where
ppr (LMInt size ) = char 'i' <> ppr size
ppr (LMFloat ) = text "float"
ppr (LMDouble ) = text "double"
ppr (LMFloat80 ) = text "x86_fp80"
ppr (LMFloat128 ) = text "fp128"
ppr (LMPointer x ) = ppr x <> char '*'
ppr (LMArray nr tp ) = char '[' <> ppr nr <> text " x " <> ppr tp <> char ']'
ppr (LMVector nr tp ) = char '<' <> ppr nr <> text " x " <> ppr tp <> char '>'
ppr (LMLabel ) = text "label"
ppr (LMVoid ) = text "void"
ppr (LMStruct tys ) = text "<{" <> ppCommaJoin tys <> text "}>"
ppr (LMStructU tys ) = text "{" <> ppCommaJoin tys <> text "}"
ppr (LMMetadata ) = text "metadata"
ppr (LMFunction (LlvmFunctionDecl _ _ _ r varg p _))
= ppr r <+> lparen <> ppParams varg p <> rparen
ppr (LMAlias (s,_)) = char '%' <> ftext s
ppParams :: LlvmParameterListType -> [LlvmParameter] -> SDoc
ppParams varg p
= let varg' = case varg of
VarArgs | null args -> sLit "..."
| otherwise -> sLit ", ..."
_otherwise -> sLit ""
-- by default we don't print param attributes
args = map fst p
in ppCommaJoin args <> ptext varg'
-- | An LLVM section definition. If Nothing then let LLVM decide the section
type LMSection = Maybe LMString
type LMAlign = Maybe Int
data LMConst = Global -- ^ Mutable global variable
| Constant -- ^ Constant global variable
| Alias -- ^ Alias of another variable
deriving (Eq)
-- | LLVM Variables
data LlvmVar
-- | Variables with a global scope.
= LMGlobalVar LMString LlvmType LlvmLinkageType LMSection LMAlign LMConst
-- | Variables local to a function or parameters.
| LMLocalVar Unique LlvmType
-- | Named local variables. Sometimes we need to be able to explicitly name
-- variables (e.g for function arguments).
| LMNLocalVar LMString LlvmType
-- | A constant variable
| LMLitVar LlvmLit
deriving (Eq)
instance Outputable LlvmVar where
ppr (LMLitVar x) = ppr x
ppr (x ) = ppr (getVarType x) <+> ppName x
-- | Llvm Literal Data.
--
-- These can be used inline in expressions.
data LlvmLit
-- | Refers to an integer constant (i64 42).
= LMIntLit Integer LlvmType
-- | Floating point literal
| LMFloatLit Double LlvmType
-- | Literal NULL, only applicable to pointer types
| LMNullLit LlvmType
-- | Vector literal
| LMVectorLit [LlvmLit]
-- | Undefined value, random bit pattern. Useful for optimisations.
| LMUndefLit LlvmType
deriving (Eq)
instance Outputable LlvmLit where
ppr l@(LMVectorLit {}) = ppLit l
ppr l = ppr (getLitType l) <+> ppLit l
-- | Llvm Static Data.
--
-- These represent the possible global level variables and constants.
data LlvmStatic
= LMComment LMString -- ^ A comment in a static section
| LMStaticLit LlvmLit -- ^ A static variant of a literal value
| LMUninitType LlvmType -- ^ For uninitialised data
| LMStaticStr LMString LlvmType -- ^ Defines a static 'LMString'
| LMStaticArray [LlvmStatic] LlvmType -- ^ A static array
| LMStaticStruc [LlvmStatic] LlvmType -- ^ A static structure type
| LMStaticPointer LlvmVar -- ^ A pointer to other data
-- static expressions, could split out but leave
-- for moment for ease of use. Not many of them.
| LMTrunc LlvmStatic LlvmType -- ^ Truncate
| LMBitc LlvmStatic LlvmType -- ^ Pointer to Pointer conversion
| LMPtoI LlvmStatic LlvmType -- ^ Pointer to Integer conversion
| LMAdd LlvmStatic LlvmStatic -- ^ Constant addition operation
| LMSub LlvmStatic LlvmStatic -- ^ Constant subtraction operation
instance Outputable LlvmStatic where
ppr (LMComment s) = text "; " <> ftext s
ppr (LMStaticLit l ) = ppr l
ppr (LMUninitType t) = ppr t <> text " undef"
ppr (LMStaticStr s t) = ppr t <> text " c\"" <> ftext s <> text "\\00\""
ppr (LMStaticArray d t) = ppr t <> text " [" <> ppCommaJoin d <> char ']'
ppr (LMStaticStruc d t) = ppr t <> text "<{" <> ppCommaJoin d <> text "}>"
ppr (LMStaticPointer v) = ppr v
ppr (LMTrunc v t)
= ppr t <> text " trunc (" <> ppr v <> text " to " <> ppr t <> char ')'
ppr (LMBitc v t)
= ppr t <> text " bitcast (" <> ppr v <> text " to " <> ppr t <> char ')'
ppr (LMPtoI v t)
= ppr t <> text " ptrtoint (" <> ppr v <> text " to " <> ppr t <> char ')'
ppr (LMAdd s1 s2)
= pprStaticArith s1 s2 (sLit "add") (sLit "fadd") "LMAdd"
ppr (LMSub s1 s2)
= pprStaticArith s1 s2 (sLit "sub") (sLit "fsub") "LMSub"
pprSpecialStatic :: LlvmStatic -> SDoc
pprSpecialStatic (LMBitc v t) =
ppr (pLower t) <> text ", bitcast (" <> ppr v <> text " to " <> ppr t
<> char ')'
pprSpecialStatic v@(LMStaticPointer x) = ppr (pLower $ getVarType x) <> comma <+> ppr v
pprSpecialStatic stat = ppr stat
pprStaticArith :: LlvmStatic -> LlvmStatic -> PtrString -> PtrString
-> String -> SDoc
pprStaticArith s1 s2 int_op float_op op_name =
let ty1 = getStatType s1
op = if isFloat ty1 then float_op else int_op
in if ty1 == getStatType s2
then ppr ty1 <+> ptext op <+> lparen <> ppr s1 <> comma <> ppr s2 <> rparen
else sdocWithDynFlags $ \dflags ->
error $ op_name ++ " with different types! s1: "
++ showSDoc dflags (ppr s1) ++ ", s2: " ++ showSDoc dflags (ppr s2)
-- -----------------------------------------------------------------------------
-- ** Operations on LLVM Basic Types and Variables
--
-- | Return the variable name or value of the 'LlvmVar'
-- in Llvm IR textual representation (e.g. @\@x@, @%y@ or @42@).
ppName :: LlvmVar -> SDoc
ppName v@(LMGlobalVar {}) = char '@' <> ppPlainName v
ppName v@(LMLocalVar {}) = char '%' <> ppPlainName v
ppName v@(LMNLocalVar {}) = char '%' <> ppPlainName v
ppName v@(LMLitVar {}) = ppPlainName v
-- | Return the variable name or value of the 'LlvmVar'
-- in a plain textual representation (e.g. @x@, @y@ or @42@).
ppPlainName :: LlvmVar -> SDoc
ppPlainName (LMGlobalVar x _ _ _ _ _) = ftext x
ppPlainName (LMLocalVar x LMLabel ) = text (show x)
ppPlainName (LMLocalVar x _ ) = text ('l' : show x)
ppPlainName (LMNLocalVar x _ ) = ftext x
ppPlainName (LMLitVar x ) = ppLit x
-- | Print a literal value. No type.
ppLit :: LlvmLit -> SDoc
ppLit (LMIntLit i (LMInt 32)) = ppr (fromInteger i :: Int32)
ppLit (LMIntLit i (LMInt 64)) = ppr (fromInteger i :: Int64)
ppLit (LMIntLit i _ ) = ppr ((fromInteger i)::Int)
ppLit (LMFloatLit r LMFloat ) = ppFloat $ narrowFp r
ppLit (LMFloatLit r LMDouble) = ppDouble r
ppLit f@(LMFloatLit _ _) = sdocWithDynFlags (\dflags ->
error $ "Can't print this float literal!" ++ showSDoc dflags (ppr f))
ppLit (LMVectorLit ls ) = char '<' <+> ppCommaJoin ls <+> char '>'
ppLit (LMNullLit _ ) = text "null"
-- #11487 was an issue where we passed undef for some arguments
-- that were actually live. By chance the registers holding those
-- arguments usually happened to have the right values anyways, but
-- that was not guaranteed. To find such bugs reliably, we set the
-- flag below when validating, which replaces undef literals (at
-- common types) with values that are likely to cause a crash or test
-- failure.
ppLit (LMUndefLit t ) = sdocWithDynFlags f
where f dflags
| gopt Opt_LlvmFillUndefWithGarbage dflags,
Just lit <- garbageLit t = ppLit lit
| otherwise = text "undef"
garbageLit :: LlvmType -> Maybe LlvmLit
garbageLit t@(LMInt w) = Just (LMIntLit (0xbbbbbbbbbbbbbbb0 `mod` (2^w)) t)
-- Use a value that looks like an untagged pointer, so we are more
-- likely to try to enter it
garbageLit t
| isFloat t = Just (LMFloatLit 12345678.9 t)
garbageLit t@(LMPointer _) = Just (LMNullLit t)
-- Using null isn't totally ideal, since some functions may check for null.
-- But producing another value is inconvenient since it needs a cast,
-- and the knowledge for how to format casts is in PpLlvm.
garbageLit _ = Nothing
-- More cases could be added, but this should do for now.
-- | Return the 'LlvmType' of the 'LlvmVar'
getVarType :: LlvmVar -> LlvmType
getVarType (LMGlobalVar _ y _ _ _ _) = y
getVarType (LMLocalVar _ y ) = y
getVarType (LMNLocalVar _ y ) = y
getVarType (LMLitVar l ) = getLitType l
-- | Return the 'LlvmType' of a 'LlvmLit'
getLitType :: LlvmLit -> LlvmType
getLitType (LMIntLit _ t) = t
getLitType (LMFloatLit _ t) = t
getLitType (LMVectorLit []) = panic "getLitType"
getLitType (LMVectorLit ls) = LMVector (length ls) (getLitType (head ls))
getLitType (LMNullLit t) = t
getLitType (LMUndefLit t) = t
-- | Return the 'LlvmType' of the 'LlvmStatic'
getStatType :: LlvmStatic -> LlvmType
getStatType (LMStaticLit l ) = getLitType l
getStatType (LMUninitType t) = t
getStatType (LMStaticStr _ t) = t
getStatType (LMStaticArray _ t) = t
getStatType (LMStaticStruc _ t) = t
getStatType (LMStaticPointer v) = getVarType v
getStatType (LMTrunc _ t) = t
getStatType (LMBitc _ t) = t
getStatType (LMPtoI _ t) = t
getStatType (LMAdd t _) = getStatType t
getStatType (LMSub t _) = getStatType t
getStatType (LMComment _) = error "Can't call getStatType on LMComment!"
-- | Return the 'LlvmLinkageType' for a 'LlvmVar'
getLink :: LlvmVar -> LlvmLinkageType
getLink (LMGlobalVar _ _ l _ _ _) = l
getLink _ = Internal
-- | Add a pointer indirection to the supplied type. 'LMLabel' and 'LMVoid'
-- cannot be lifted.
pLift :: LlvmType -> LlvmType
pLift LMLabel = error "Labels are unliftable"
pLift LMVoid = error "Voids are unliftable"
pLift LMMetadata = error "Metadatas are unliftable"
pLift x = LMPointer x
-- | Lift a variable to 'LMPointer' type.
pVarLift :: LlvmVar -> LlvmVar
pVarLift (LMGlobalVar s t l x a c) = LMGlobalVar s (pLift t) l x a c
pVarLift (LMLocalVar s t ) = LMLocalVar s (pLift t)
pVarLift (LMNLocalVar s t ) = LMNLocalVar s (pLift t)
pVarLift (LMLitVar _ ) = error $ "Can't lower a literal type!"
-- | Remove the pointer indirection of the supplied type. Only 'LMPointer'
-- constructors can be lowered.
pLower :: LlvmType -> LlvmType
pLower (LMPointer x) = x
pLower x = pprPanic "llvmGen(pLower)"
$ ppr x <+> text " is a unlowerable type, need a pointer"
-- | Lower a variable of 'LMPointer' type.
pVarLower :: LlvmVar -> LlvmVar
pVarLower (LMGlobalVar s t l x a c) = LMGlobalVar s (pLower t) l x a c
pVarLower (LMLocalVar s t ) = LMLocalVar s (pLower t)
pVarLower (LMNLocalVar s t ) = LMNLocalVar s (pLower t)
pVarLower (LMLitVar _ ) = error $ "Can't lower a literal type!"
-- | Test if the given 'LlvmType' is an integer
isInt :: LlvmType -> Bool
isInt (LMInt _) = True
isInt _ = False
-- | Test if the given 'LlvmType' is a floating point type
isFloat :: LlvmType -> Bool
isFloat LMFloat = True
isFloat LMDouble = True
isFloat LMFloat80 = True
isFloat LMFloat128 = True
isFloat _ = False
-- | Test if the given 'LlvmType' is an 'LMPointer' construct
isPointer :: LlvmType -> Bool
isPointer (LMPointer _) = True
isPointer _ = False
-- | Test if the given 'LlvmType' is an 'LMVector' construct
isVector :: LlvmType -> Bool
isVector (LMVector {}) = True
isVector _ = False
-- | Test if a 'LlvmVar' is global.
isGlobal :: LlvmVar -> Bool
isGlobal (LMGlobalVar _ _ _ _ _ _) = True
isGlobal _ = False
-- | Width in bits of an 'LlvmType', returns 0 if not applicable
llvmWidthInBits :: DynFlags -> LlvmType -> Int
llvmWidthInBits _ (LMInt n) = n
llvmWidthInBits _ (LMFloat) = 32
llvmWidthInBits _ (LMDouble) = 64
llvmWidthInBits _ (LMFloat80) = 80
llvmWidthInBits _ (LMFloat128) = 128
-- Could return either a pointer width here or the width of what
-- it points to. We will go with the former for now.
-- PMW: At least judging by the way LLVM outputs constants, pointers
-- should use the former, but arrays the latter.
llvmWidthInBits dflags (LMPointer _) = llvmWidthInBits dflags (llvmWord dflags)
llvmWidthInBits dflags (LMArray n t) = n * llvmWidthInBits dflags t
llvmWidthInBits dflags (LMVector n ty) = n * llvmWidthInBits dflags ty
llvmWidthInBits _ LMLabel = 0
llvmWidthInBits _ LMVoid = 0
llvmWidthInBits dflags (LMStruct tys) = sum $ map (llvmWidthInBits dflags) tys
llvmWidthInBits _ (LMStructU _) =
-- It's not trivial to calculate the bit width of the unpacked structs,
-- since they will be aligned depending on the specified datalayout (
-- http://llvm.org/docs/LangRef.html#data-layout ). One way we could support
-- this could be to make the LlvmCodeGen.Ppr.moduleLayout be a data type
-- that exposes the alignment information. However, currently the only place
-- we use unpacked structs is LLVM intrinsics that return them (e.g.,
-- llvm.sadd.with.overflow.*), so we don't actually need to compute their
-- bit width.
panic "llvmWidthInBits: not implemented for LMStructU"
llvmWidthInBits _ (LMFunction _) = 0
llvmWidthInBits dflags (LMAlias (_,t)) = llvmWidthInBits dflags t
llvmWidthInBits _ LMMetadata = panic "llvmWidthInBits: Meta-data has no runtime representation!"
-- -----------------------------------------------------------------------------
-- ** Shortcut for Common Types
--
i128, i64, i32, i16, i8, i1, i8Ptr :: LlvmType
i128 = LMInt 128
i64 = LMInt 64
i32 = LMInt 32
i16 = LMInt 16
i8 = LMInt 8
i1 = LMInt 1
i8Ptr = pLift i8
-- | The target architectures word size
llvmWord, llvmWordPtr :: DynFlags -> LlvmType
llvmWord dflags = LMInt (wORD_SIZE dflags * 8)
llvmWordPtr dflags = pLift (llvmWord dflags)
-- -----------------------------------------------------------------------------
-- * LLVM Function Types
--
-- | An LLVM Function
data LlvmFunctionDecl = LlvmFunctionDecl {
-- | Unique identifier of the function
decName :: LMString,
-- | LinkageType of the function
funcLinkage :: LlvmLinkageType,
-- | The calling convention of the function
funcCc :: LlvmCallConvention,
-- | Type of the returned value
decReturnType :: LlvmType,
-- | Indicates if this function uses varargs
decVarargs :: LlvmParameterListType,
-- | Parameter types and attributes
decParams :: [LlvmParameter],
-- | Function align value, must be power of 2
funcAlign :: LMAlign
}
deriving (Eq)
instance Outputable LlvmFunctionDecl where
ppr (LlvmFunctionDecl n l c r varg p a)
= let align = case a of
Just a' -> text " align " <> ppr a'
Nothing -> empty
in ppr l <+> ppr c <+> ppr r <+> char '@' <> ftext n <>
lparen <> ppParams varg p <> rparen <> align
type LlvmFunctionDecls = [LlvmFunctionDecl]
type LlvmParameter = (LlvmType, [LlvmParamAttr])
-- | LLVM Parameter Attributes.
--
-- Parameter attributes are used to communicate additional information about
-- the result or parameters of a function
data LlvmParamAttr
-- | This indicates to the code generator that the parameter or return value
-- should be zero-extended to a 32-bit value by the caller (for a parameter)
-- or the callee (for a return value).
= ZeroExt
-- | This indicates to the code generator that the parameter or return value
-- should be sign-extended to a 32-bit value by the caller (for a parameter)
-- or the callee (for a return value).
| SignExt
-- | This indicates that this parameter or return value should be treated in
-- a special target-dependent fashion during while emitting code for a
-- function call or return (usually, by putting it in a register as opposed
-- to memory).
| InReg
-- | This indicates that the pointer parameter should really be passed by
-- value to the function.
| ByVal
-- | This indicates that the pointer parameter specifies the address of a
-- structure that is the return value of the function in the source program.
| SRet
-- | This indicates that the pointer does not alias any global or any other
-- parameter.
| NoAlias
-- | This indicates that the callee does not make any copies of the pointer
-- that outlive the callee itself
| NoCapture
-- | This indicates that the pointer parameter can be excised using the
-- trampoline intrinsics.
| Nest
deriving (Eq)
instance Outputable LlvmParamAttr where
ppr ZeroExt = text "zeroext"
ppr SignExt = text "signext"
ppr InReg = text "inreg"
ppr ByVal = text "byval"
ppr SRet = text "sret"
ppr NoAlias = text "noalias"
ppr NoCapture = text "nocapture"
ppr Nest = text "nest"
-- | Llvm Function Attributes.
--
-- Function attributes are set to communicate additional information about a
-- function. Function attributes are considered to be part of the function,
-- not of the function type, so functions with different parameter attributes
-- can have the same function type. Functions can have multiple attributes.
--
-- Descriptions taken from <http://llvm.org/docs/LangRef.html#fnattrs>
data LlvmFuncAttr
-- | This attribute indicates that the inliner should attempt to inline this
-- function into callers whenever possible, ignoring any active inlining
-- size threshold for this caller.
= AlwaysInline
-- | This attribute indicates that the source code contained a hint that
-- inlining this function is desirable (such as the \"inline\" keyword in
-- C/C++). It is just a hint; it imposes no requirements on the inliner.
| InlineHint
-- | This attribute indicates that the inliner should never inline this
-- function in any situation. This attribute may not be used together
-- with the alwaysinline attribute.
| NoInline
-- | This attribute suggests that optimization passes and code generator
-- passes make choices that keep the code size of this function low, and
-- otherwise do optimizations specifically to reduce code size.
| OptSize
-- | This function attribute indicates that the function never returns
-- normally. This produces undefined behavior at runtime if the function
-- ever does dynamically return.
| NoReturn
-- | This function attribute indicates that the function never returns with
-- an unwind or exceptional control flow. If the function does unwind, its
-- runtime behavior is undefined.
| NoUnwind
-- | This attribute indicates that the function computes its result (or
-- decides to unwind an exception) based strictly on its arguments, without
-- dereferencing any pointer arguments or otherwise accessing any mutable
-- state (e.g. memory, control registers, etc) visible to caller functions.
-- It does not write through any pointer arguments (including byval
-- arguments) and never changes any state visible to callers. This means
-- that it cannot unwind exceptions by calling the C++ exception throwing
-- methods, but could use the unwind instruction.
| ReadNone
-- | This attribute indicates that the function does not write through any
-- pointer arguments (including byval arguments) or otherwise modify any
-- state (e.g. memory, control registers, etc) visible to caller functions.
-- It may dereference pointer arguments and read state that may be set in
-- the caller. A readonly function always returns the same value (or unwinds
-- an exception identically) when called with the same set of arguments and
-- global state. It cannot unwind an exception by calling the C++ exception
-- throwing methods, but may use the unwind instruction.
| ReadOnly
-- | This attribute indicates that the function should emit a stack smashing
-- protector. It is in the form of a \"canary\"—a random value placed on the
-- stack before the local variables that's checked upon return from the
-- function to see if it has been overwritten. A heuristic is used to
-- determine if a function needs stack protectors or not.
--
-- If a function that has an ssp attribute is inlined into a function that
-- doesn't have an ssp attribute, then the resulting function will have an
-- ssp attribute.
| Ssp
-- | This attribute indicates that the function should always emit a stack
-- smashing protector. This overrides the ssp function attribute.
--
-- If a function that has an sspreq attribute is inlined into a function
-- that doesn't have an sspreq attribute or which has an ssp attribute,
-- then the resulting function will have an sspreq attribute.
| SspReq
-- | This attribute indicates that the code generator should not use a red
-- zone, even if the target-specific ABI normally permits it.
| NoRedZone
-- | This attributes disables implicit floating point instructions.
| NoImplicitFloat
-- | This attribute disables prologue / epilogue emission for the function.
-- This can have very system-specific consequences.
| Naked
deriving (Eq)
instance Outputable LlvmFuncAttr where
ppr AlwaysInline = text "alwaysinline"
ppr InlineHint = text "inlinehint"
ppr NoInline = text "noinline"
ppr OptSize = text "optsize"
ppr NoReturn = text "noreturn"
ppr NoUnwind = text "nounwind"
ppr ReadNone = text "readnone"
ppr ReadOnly = text "readonly"
ppr Ssp = text "ssp"
ppr SspReq = text "ssqreq"
ppr NoRedZone = text "noredzone"
ppr NoImplicitFloat = text "noimplicitfloat"
ppr Naked = text "naked"
-- | Different types to call a function.
data LlvmCallType
-- | Normal call, allocate a new stack frame.
= StdCall
-- | Tail call, perform the call in the current stack frame.
| TailCall
deriving (Eq,Show)
-- | Different calling conventions a function can use.
data LlvmCallConvention
-- | The C calling convention.
-- This calling convention (the default if no other calling convention is
-- specified) matches the target C calling conventions. This calling
-- convention supports varargs function calls and tolerates some mismatch in
-- the declared prototype and implemented declaration of the function (as
-- does normal C).
= CC_Ccc
-- | This calling convention attempts to make calls as fast as possible
-- (e.g. by passing things in registers). This calling convention allows
-- the target to use whatever tricks it wants to produce fast code for the
-- target, without having to conform to an externally specified ABI
-- (Application Binary Interface). Implementations of this convention should
-- allow arbitrary tail call optimization to be supported. This calling
-- convention does not support varargs and requires the prototype of al
-- callees to exactly match the prototype of the function definition.
| CC_Fastcc
-- | This calling convention attempts to make code in the caller as efficient
-- as possible under the assumption that the call is not commonly executed.
-- As such, these calls often preserve all registers so that the call does
-- not break any live ranges in the caller side. This calling convention
-- does not support varargs and requires the prototype of all callees to
-- exactly match the prototype of the function definition.
| CC_Coldcc
-- | The GHC-specific 'registerised' calling convention.
| CC_Ghc
-- | Any calling convention may be specified by number, allowing
-- target-specific calling conventions to be used. Target specific calling
-- conventions start at 64.
| CC_Ncc Int
-- | X86 Specific 'StdCall' convention. LLVM includes a specific alias for it
-- rather than just using CC_Ncc.
| CC_X86_Stdcc
deriving (Eq)
instance Outputable LlvmCallConvention where
ppr CC_Ccc = text "ccc"
ppr CC_Fastcc = text "fastcc"
ppr CC_Coldcc = text "coldcc"
ppr CC_Ghc = text "ghccc"
ppr (CC_Ncc i) = text "cc " <> ppr i
ppr CC_X86_Stdcc = text "x86_stdcallcc"
-- | Functions can have a fixed amount of parameters, or a variable amount.
data LlvmParameterListType
-- Fixed amount of arguments.
= FixedArgs
-- Variable amount of arguments.
| VarArgs
deriving (Eq,Show)
-- | Linkage type of a symbol.
--
-- The description of the constructors is copied from the Llvm Assembly Language
-- Reference Manual <http://www.llvm.org/docs/LangRef.html#linkage>, because
-- they correspond to the Llvm linkage types.
data LlvmLinkageType
-- | Global values with internal linkage are only directly accessible by
-- objects in the current module. In particular, linking code into a module
-- with an internal global value may cause the internal to be renamed as
-- necessary to avoid collisions. Because the symbol is internal to the
-- module, all references can be updated. This corresponds to the notion
-- of the @static@ keyword in C.
= Internal
-- | Globals with @linkonce@ linkage are merged with other globals of the
-- same name when linkage occurs. This is typically used to implement
-- inline functions, templates, or other code which must be generated
-- in each translation unit that uses it. Unreferenced linkonce globals are
-- allowed to be discarded.
| LinkOnce
-- | @weak@ linkage is exactly the same as linkonce linkage, except that
-- unreferenced weak globals may not be discarded. This is used for globals
-- that may be emitted in multiple translation units, but that are not
-- guaranteed to be emitted into every translation unit that uses them. One
-- example of this are common globals in C, such as @int X;@ at global
-- scope.
| Weak
-- | @appending@ linkage may only be applied to global variables of pointer
-- to array type. When two global variables with appending linkage are
-- linked together, the two global arrays are appended together. This is
-- the Llvm, typesafe, equivalent of having the system linker append
-- together @sections@ with identical names when .o files are linked.
| Appending
-- | The semantics of this linkage follow the ELF model: the symbol is weak
-- until linked, if not linked, the symbol becomes null instead of being an
-- undefined reference.
| ExternWeak
-- | The symbol participates in linkage and can be used to resolve external
-- symbol references.
| ExternallyVisible
-- | Alias for 'ExternallyVisible' but with explicit textual form in LLVM
-- assembly.
| External
-- | Symbol is private to the module and should not appear in the symbol table
| Private
deriving (Eq)
instance Outputable LlvmLinkageType where
ppr Internal = text "internal"
ppr LinkOnce = text "linkonce"
ppr Weak = text "weak"
ppr Appending = text "appending"
ppr ExternWeak = text "extern_weak"
-- ExternallyVisible does not have a textual representation, it is
-- the linkage type a function resolves to if no other is specified
-- in Llvm.
ppr ExternallyVisible = empty
ppr External = text "external"
ppr Private = text "private"
-- -----------------------------------------------------------------------------
-- * LLVM Operations
--
-- | Llvm binary operators machine operations.
data LlvmMachOp
= LM_MO_Add -- ^ add two integer, floating point or vector values.
| LM_MO_Sub -- ^ subtract two ...
| LM_MO_Mul -- ^ multiply ..
| LM_MO_UDiv -- ^ unsigned integer or vector division.
| LM_MO_SDiv -- ^ signed integer ..
| LM_MO_URem -- ^ unsigned integer or vector remainder (mod)
| LM_MO_SRem -- ^ signed ...
| LM_MO_FAdd -- ^ add two floating point or vector values.
| LM_MO_FSub -- ^ subtract two ...
| LM_MO_FMul -- ^ multiply ...
| LM_MO_FDiv -- ^ divide ...
| LM_MO_FRem -- ^ remainder ...
-- | Left shift
| LM_MO_Shl
-- | Logical shift right
-- Shift right, filling with zero
| LM_MO_LShr
-- | Arithmetic shift right
-- The most significant bits of the result will be equal to the sign bit of
-- the left operand.
| LM_MO_AShr
| LM_MO_And -- ^ AND bitwise logical operation.
| LM_MO_Or -- ^ OR bitwise logical operation.
| LM_MO_Xor -- ^ XOR bitwise logical operation.
deriving (Eq)
instance Outputable LlvmMachOp where
ppr LM_MO_Add = text "add"
ppr LM_MO_Sub = text "sub"
ppr LM_MO_Mul = text "mul"
ppr LM_MO_UDiv = text "udiv"
ppr LM_MO_SDiv = text "sdiv"
ppr LM_MO_URem = text "urem"
ppr LM_MO_SRem = text "srem"
ppr LM_MO_FAdd = text "fadd"
ppr LM_MO_FSub = text "fsub"
ppr LM_MO_FMul = text "fmul"
ppr LM_MO_FDiv = text "fdiv"
ppr LM_MO_FRem = text "frem"
ppr LM_MO_Shl = text "shl"
ppr LM_MO_LShr = text "lshr"
ppr LM_MO_AShr = text "ashr"
ppr LM_MO_And = text "and"
ppr LM_MO_Or = text "or"
ppr LM_MO_Xor = text "xor"
-- | Llvm compare operations.
data LlvmCmpOp
= LM_CMP_Eq -- ^ Equal (Signed and Unsigned)
| LM_CMP_Ne -- ^ Not equal (Signed and Unsigned)
| LM_CMP_Ugt -- ^ Unsigned greater than
| LM_CMP_Uge -- ^ Unsigned greater than or equal
| LM_CMP_Ult -- ^ Unsigned less than
| LM_CMP_Ule -- ^ Unsigned less than or equal
| LM_CMP_Sgt -- ^ Signed greater than
| LM_CMP_Sge -- ^ Signed greater than or equal
| LM_CMP_Slt -- ^ Signed less than
| LM_CMP_Sle -- ^ Signed less than or equal
-- Float comparisons. GHC uses a mix of ordered and unordered float
-- comparisons.
| LM_CMP_Feq -- ^ Float equal
| LM_CMP_Fne -- ^ Float not equal
| LM_CMP_Fgt -- ^ Float greater than
| LM_CMP_Fge -- ^ Float greater than or equal
| LM_CMP_Flt -- ^ Float less than
| LM_CMP_Fle -- ^ Float less than or equal
deriving (Eq)
instance Outputable LlvmCmpOp where
ppr LM_CMP_Eq = text "eq"
ppr LM_CMP_Ne = text "ne"
ppr LM_CMP_Ugt = text "ugt"
ppr LM_CMP_Uge = text "uge"
ppr LM_CMP_Ult = text "ult"
ppr LM_CMP_Ule = text "ule"
ppr LM_CMP_Sgt = text "sgt"
ppr LM_CMP_Sge = text "sge"
ppr LM_CMP_Slt = text "slt"
ppr LM_CMP_Sle = text "sle"
ppr LM_CMP_Feq = text "oeq"
ppr LM_CMP_Fne = text "une"
ppr LM_CMP_Fgt = text "ogt"
ppr LM_CMP_Fge = text "oge"
ppr LM_CMP_Flt = text "olt"
ppr LM_CMP_Fle = text "ole"
-- | Llvm cast operations.
data LlvmCastOp
= LM_Trunc -- ^ Integer truncate
| LM_Zext -- ^ Integer extend (zero fill)
| LM_Sext -- ^ Integer extend (sign fill)
| LM_Fptrunc -- ^ Float truncate
| LM_Fpext -- ^ Float extend
| LM_Fptoui -- ^ Float to unsigned Integer
| LM_Fptosi -- ^ Float to signed Integer
| LM_Uitofp -- ^ Unsigned Integer to Float
| LM_Sitofp -- ^ Signed Int to Float
| LM_Ptrtoint -- ^ Pointer to Integer
| LM_Inttoptr -- ^ Integer to Pointer
| LM_Bitcast -- ^ Cast between types where no bit manipulation is needed
deriving (Eq)
instance Outputable LlvmCastOp where
ppr LM_Trunc = text "trunc"
ppr LM_Zext = text "zext"
ppr LM_Sext = text "sext"
ppr LM_Fptrunc = text "fptrunc"
ppr LM_Fpext = text "fpext"
ppr LM_Fptoui = text "fptoui"
ppr LM_Fptosi = text "fptosi"
ppr LM_Uitofp = text "uitofp"
ppr LM_Sitofp = text "sitofp"
ppr LM_Ptrtoint = text "ptrtoint"
ppr LM_Inttoptr = text "inttoptr"
ppr LM_Bitcast = text "bitcast"
-- -----------------------------------------------------------------------------
-- * Floating point conversion
--
-- | Convert a Haskell Double to an LLVM hex encoded floating point form. In
-- Llvm float literals can be printed in a big-endian hexadecimal format,
-- regardless of underlying architecture.
--
-- See Note [LLVM Float Types].
ppDouble :: Double -> SDoc
ppDouble d
= let bs = doubleToBytes d
hex d' = case showHex d' "" of
[] -> error "dToStr: too few hex digits for float"
[x] -> ['0',x]
[x,y] -> [x,y]
_ -> error "dToStr: too many hex digits for float"
in sdocWithDynFlags (\dflags ->
let fixEndian = if wORDS_BIGENDIAN dflags then id else reverse
str = map toUpper $ concat $ fixEndian $ map hex bs
in text "0x" <> text str)
-- Note [LLVM Float Types]
-- ~~~~~~~~~~~~~~~~~~~~~~~
-- We use 'ppDouble' for both printing Float and Double floating point types. This is
-- as LLVM expects all floating point constants (single & double) to be in IEEE
-- 754 Double precision format. However, for single precision numbers (Float)
-- they should be *representable* in IEEE 754 Single precision format. So the
-- easiest way to do this is to narrow and widen again.
-- (i.e., Double -> Float -> Double). We must be careful doing this that GHC
-- doesn't optimize that away.
-- Note [narrowFp & widenFp]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~
-- NOTE: we use float2Double & co directly as GHC likes to optimize away
-- successive calls of 'realToFrac', defeating the narrowing. (Bug #7600).
-- 'realToFrac' has inconsistent behaviour with optimisation as well that can
-- also cause issues, these methods don't.
narrowFp :: Double -> Float
{-# NOINLINE narrowFp #-}
narrowFp = double2Float
widenFp :: Float -> Double
{-# NOINLINE widenFp #-}
widenFp = float2Double
ppFloat :: Float -> SDoc
ppFloat = ppDouble . widenFp
--------------------------------------------------------------------------------
-- * Misc functions
--------------------------------------------------------------------------------
ppCommaJoin :: (Outputable a) => [a] -> SDoc
ppCommaJoin strs = hsep $ punctuate comma (map ppr strs)
ppSpaceJoin :: (Outputable a) => [a] -> SDoc
ppSpaceJoin strs = hsep (map ppr strs)
|
sdiehl/ghc
|
compiler/llvmGen/Llvm/Types.hs
|
bsd-3-clause
| 35,651 | 0 | 17 | 8,406 | 5,995 | 3,195 | 2,800 | 489 | 5 |
{-# LANGUAGE ExistentialQuantification #-}
module Control.Concurrent.Chan.ReadOnly
( ReadOnlyChan
, toReadOnlyChan
) where
import Control.Concurrent.Chan (Chan)
import Control.Concurrent.Chan.Class
data ReadOnlyChan b = forall a . ReadOnlyChan (Chan a) (a -> b)
instance Functor ReadOnlyChan where
fmap f (ReadOnlyChan c f') = ReadOnlyChan c (f . f')
toReadOnlyChan :: Chan a -> ReadOnlyChan a
toReadOnlyChan c = ReadOnlyChan c id
instance ChanDup ReadOnlyChan where
dupChan (ReadOnlyChan chan f) = do
chan' <- dupChan chan
return (ReadOnlyChan chan' f)
{-# INLINE dupChan #-}
instance ChanRead ReadOnlyChan where
readChan (ReadOnlyChan chan f) = f <$> readChan chan
{-# INLINE readChan #-}
|
osa1/privileged-concurrency
|
Control/Concurrent/Chan/ReadOnly.hs
|
bsd-3-clause
| 734 | 0 | 10 | 140 | 212 | 112 | 100 | 19 | 1 |
{-# LANGUAGE DeriveGeneric #-}
module Ssb.Message where
import GHC.Generics
import Data.Aeson
import Data.Int (Int64)
type MessageLink = String
type FeedLink = String
type HashType = String
type Signature = String
data Message a = Message
{ previous :: MessageLink
, author :: FeedLink
, sequence :: Int64
, timestamp :: Int64
, hash :: HashType
, content :: a
, signature :: Signature
} deriving (Show, Eq, Generic)
instance FromJSON a => FromJSON (Message a)
|
bkil-syslogng/haskell-scuttlebutt
|
src/Ssb/Message.hs
|
bsd-3-clause
| 483 | 0 | 8 | 97 | 138 | 84 | 54 | 19 | 0 |
{-# LANGUAGE NoImplicitPrelude #-}
module VYPe15.Types.Tokens
where
import Data.Char (Char)
import Data.Int (Int)
import Data.String (String)
import Text.Show (Show)
data Token
= TokenNumConst Int
| TokenCharConst Char
| TokenStringConst String
| TokenID String
| TokenAssign
| TokenPlus
| TokenMinus
| TokenTimes
| TokenDiv
| TokenMod
| TokenLess
| TokenGreater
| TokenLEQ
| TokenGEQ
| TokenEQ
| TokenNEQ
| TokenAND
| TokenOR
| TokenNEG
| TokenOB
| TokenCB
| TokenOCB
| TokenCCB
| TokenIf
| TokenElse
| TokenReturn
| TokenWhile
| TokenSemicolon
| TokenString
| TokenChar
| TokenInt
| TokenVoid
| TokenComma
deriving Show
|
Tr1p0d/VYPe15
|
src/VYPe15/Types/Tokens.hs
|
bsd-3-clause
| 714 | 0 | 6 | 185 | 162 | 104 | 58 | 41 | 0 |
-- (c) The University of Glasgow, 2006
{-# LANGUAGE CPP, ScopedTypeVariables #-}
-- | Package manipulation
module Packages (
module PackageConfig,
-- * Reading the package config, and processing cmdline args
PackageState(preloadPackages),
initPackages,
readPackageConfigs,
getPackageConfRefs,
resolvePackageConfig,
readPackageConfig,
listPackageConfigMap,
-- * Querying the package config
lookupPackage,
resolveInstalledPackageId,
searchPackageId,
getPackageDetails,
listVisibleModuleNames,
lookupModuleInAllPackages,
lookupModuleWithSuggestions,
LookupResult(..),
ModuleSuggestion(..),
ModuleOrigin(..),
-- * Inspecting the set of packages in scope
getPackageIncludePath,
getPackageLibraryPath,
getPackageLinkOpts,
getPackageExtraCcOpts,
getPackageFrameworkPath,
getPackageFrameworks,
getPreloadPackagesAnd,
collectIncludeDirs, collectLibraryPaths, collectLinkOpts,
packageHsLibs,
-- * Utils
packageKeyPackageIdString,
pprFlag,
pprPackages,
pprPackagesSimple,
pprModuleMap,
isDllName
)
where
#include "HsVersions.h"
import GHC.PackageDb
import PackageConfig
import DynFlags
import Name ( Name, nameModule_maybe )
import UniqFM
import Module
import Util
import Panic
import Outputable
import Maybes
import System.Environment ( getEnv )
import FastString
import ErrUtils ( debugTraceMsg, MsgDoc )
import Exception
import Unique
import System.Directory
import System.FilePath as FilePath
import qualified System.FilePath.Posix as FilePath.Posix
import Control.Monad
import Data.Char ( toUpper )
import Data.List as List
import Data.Map (Map)
#if __GLASGOW_HASKELL__ < 709
import Data.Monoid hiding ((<>))
#endif
import qualified Data.Map as Map
import qualified FiniteMap as Map
import qualified Data.Set as Set
-- ---------------------------------------------------------------------------
-- The Package state
-- | Package state is all stored in 'DynFlags', including the details of
-- all packages, which packages are exposed, and which modules they
-- provide.
--
-- The package state is computed by 'initPackages', and kept in DynFlags.
-- It is influenced by various package flags:
--
-- * @-package <pkg>@ and @-package-id <pkg>@ cause @<pkg>@ to become exposed.
-- If @-hide-all-packages@ was not specified, these commands also cause
-- all other packages with the same name to become hidden.
--
-- * @-hide-package <pkg>@ causes @<pkg>@ to become hidden.
--
-- * (there are a few more flags, check below for their semantics)
--
-- The package state has the following properties.
--
-- * Let @exposedPackages@ be the set of packages thus exposed.
-- Let @depExposedPackages@ be the transitive closure from @exposedPackages@ of
-- their dependencies.
--
-- * When searching for a module from an preload import declaration,
-- only the exposed modules in @exposedPackages@ are valid.
--
-- * When searching for a module from an implicit import, all modules
-- from @depExposedPackages@ are valid.
--
-- * When linking in a compilation manager mode, we link in packages the
-- program depends on (the compiler knows this list by the
-- time it gets to the link step). Also, we link in all packages
-- which were mentioned with preload @-package@ flags on the command-line,
-- or are a transitive dependency of same, or are \"base\"\/\"rts\".
-- The reason for this is that we might need packages which don't
-- contain any Haskell modules, and therefore won't be discovered
-- by the normal mechanism of dependency tracking.
-- Notes on DLLs
-- ~~~~~~~~~~~~~
-- When compiling module A, which imports module B, we need to
-- know whether B will be in the same DLL as A.
-- If it's in the same DLL, we refer to B_f_closure
-- If it isn't, we refer to _imp__B_f_closure
-- When compiling A, we record in B's Module value whether it's
-- in a different DLL, by setting the DLL flag.
-- | Given a module name, there may be multiple ways it came into scope,
-- possibly simultaneously. This data type tracks all the possible ways
-- it could have come into scope. Warning: don't use the record functions,
-- they're partial!
data ModuleOrigin =
-- | Module is hidden, and thus never will be available for import.
-- (But maybe the user didn't realize), so we'll still keep track
-- of these modules.)
ModHidden
-- | Module is public, and could have come from some places.
| ModOrigin {
-- | @Just False@ means that this module is in
-- someone's @exported-modules@ list, but that package is hidden;
-- @Just True@ means that it is available; @Nothing@ means neither
-- applies.
fromOrigPackage :: Maybe Bool
-- | Is the module available from a reexport of an exposed package?
-- There could be multiple.
, fromExposedReexport :: [PackageConfig]
-- | Is the module available from a reexport of a hidden package?
, fromHiddenReexport :: [PackageConfig]
-- | Did the module export come from a package flag? (ToDo: track
-- more information.
, fromPackageFlag :: Bool
}
instance Outputable ModuleOrigin where
ppr ModHidden = text "hidden module"
ppr (ModOrigin e res rhs f) = sep (punctuate comma (
(case e of
Nothing -> []
Just False -> [text "hidden package"]
Just True -> [text "exposed package"]) ++
(if null res
then []
else [text "reexport by" <+>
sep (map (ppr . packageConfigId) res)]) ++
(if null rhs
then []
else [text "hidden reexport by" <+>
sep (map (ppr . packageConfigId) res)]) ++
(if f then [text "package flag"] else [])
))
-- | Smart constructor for a module which is in @exposed-modules@. Takes
-- as an argument whether or not the defining package is exposed.
fromExposedModules :: Bool -> ModuleOrigin
fromExposedModules e = ModOrigin (Just e) [] [] False
-- | Smart constructor for a module which is in @reexported-modules@. Takes
-- as an argument whether or not the reexporting package is expsed, and
-- also its 'PackageConfig'.
fromReexportedModules :: Bool -> PackageConfig -> ModuleOrigin
fromReexportedModules True pkg = ModOrigin Nothing [pkg] [] False
fromReexportedModules False pkg = ModOrigin Nothing [] [pkg] False
-- | Smart constructor for a module which was bound by a package flag.
fromFlag :: ModuleOrigin
fromFlag = ModOrigin Nothing [] [] True
instance Monoid ModuleOrigin where
mempty = ModOrigin Nothing [] [] False
mappend (ModOrigin e res rhs f) (ModOrigin e' res' rhs' f') =
ModOrigin (g e e') (res ++ res') (rhs ++ rhs') (f || f')
where g (Just b) (Just b')
| b == b' = Just b
| otherwise = panic "ModOrigin: package both exposed/hidden"
g Nothing x = x
g x Nothing = x
mappend _ _ = panic "ModOrigin: hidden module redefined"
-- | Is the name from the import actually visible? (i.e. does it cause
-- ambiguity, or is it only relevant when we're making suggestions?)
originVisible :: ModuleOrigin -> Bool
originVisible ModHidden = False
originVisible (ModOrigin b res _ f) = b == Just True || not (null res) || f
-- | Are there actually no providers for this module? This will never occur
-- except when we're filtering based on package imports.
originEmpty :: ModuleOrigin -> Bool
originEmpty (ModOrigin Nothing [] [] False) = True
originEmpty _ = False
-- | 'UniqFM' map from 'PackageKey'
type PackageKeyMap = UniqFM
-- | 'UniqFM' map from 'PackageKey' to 'PackageConfig'
type PackageConfigMap = PackageKeyMap PackageConfig
-- | 'UniqFM' map from 'PackageKey' to (1) whether or not all modules which
-- are exposed should be dumped into scope, (2) any custom renamings that
-- should also be apply, and (3) what package name is associated with the
-- key, if it might be hidden
type VisibilityMap =
PackageKeyMap (Bool, [(ModuleName, ModuleName)], FastString)
-- | Map from 'ModuleName' to 'Module' to all the origins of the bindings
-- in scope. The 'PackageConf' is not cached, mostly for convenience reasons
-- (since this is the slow path, we'll just look it up again).
type ModuleToPkgConfAll =
Map ModuleName (Map Module ModuleOrigin)
data PackageState = PackageState {
-- | A mapping of 'PackageKey' to 'PackageConfig'. This list is adjusted
-- so that only valid packages are here. 'PackageConfig' reflects
-- what was stored *on disk*, except for the 'trusted' flag, which
-- is adjusted at runtime. (In particular, some packages in this map
-- may have the 'exposed' flag be 'False'.)
pkgIdMap :: PackageConfigMap,
-- | The packages we're going to link in eagerly. This list
-- should be in reverse dependency order; that is, a package
-- is always mentioned before the packages it depends on.
preloadPackages :: [PackageKey],
-- | This is a full map from 'ModuleName' to all modules which may possibly
-- be providing it. These providers may be hidden (but we'll still want
-- to report them in error messages), or it may be an ambiguous import.
moduleToPkgConfAll :: ModuleToPkgConfAll,
-- | This is a map from 'InstalledPackageId' to 'PackageKey', since GHC
-- internally deals in package keys but the database may refer to installed
-- package IDs.
installedPackageIdMap :: InstalledPackageIdMap
}
type InstalledPackageIdMap = Map InstalledPackageId PackageKey
type InstalledPackageIndex = Map InstalledPackageId PackageConfig
-- | Empty package configuration map
emptyPackageConfigMap :: PackageConfigMap
emptyPackageConfigMap = emptyUFM
-- | Find the package we know about with the given key (e.g. @foo_HASH@), if any
lookupPackage :: DynFlags -> PackageKey -> Maybe PackageConfig
lookupPackage dflags = lookupPackage' (pkgIdMap (pkgState dflags))
lookupPackage' :: PackageConfigMap -> PackageKey -> Maybe PackageConfig
lookupPackage' = lookupUFM
-- | Search for packages with a given package ID (e.g. \"foo-0.1\")
searchPackageId :: DynFlags -> SourcePackageId -> [PackageConfig]
searchPackageId dflags pid = filter ((pid ==) . sourcePackageId)
(listPackageConfigMap dflags)
-- | Extends the package configuration map with a list of package configs.
extendPackageConfigMap
:: PackageConfigMap -> [PackageConfig] -> PackageConfigMap
extendPackageConfigMap pkg_map new_pkgs
= foldl add pkg_map new_pkgs
where add pkg_map p = addToUFM pkg_map (packageConfigId p) p
-- | Looks up the package with the given id in the package state, panicing if it is
-- not found
getPackageDetails :: DynFlags -> PackageKey -> PackageConfig
getPackageDetails dflags pid =
expectJust "getPackageDetails" (lookupPackage dflags pid)
-- | Get a list of entries from the package database. NB: be careful with
-- this function, although all packages in this map are "visible", this
-- does not imply that the exposed-modules of the package are available
-- (they may have been thinned or renamed).
listPackageConfigMap :: DynFlags -> [PackageConfig]
listPackageConfigMap dflags = eltsUFM (pkgIdMap (pkgState dflags))
-- | Looks up a 'PackageKey' given an 'InstalledPackageId'
resolveInstalledPackageId :: DynFlags -> InstalledPackageId -> PackageKey
resolveInstalledPackageId dflags ipid =
expectJust "resolveInstalledPackageId"
(Map.lookup ipid (installedPackageIdMap (pkgState dflags)))
-- ----------------------------------------------------------------------------
-- Loading the package db files and building up the package state
-- | Call this after 'DynFlags.parseDynFlags'. It reads the package
-- database files, and sets up various internal tables of package
-- information, according to the package-related flags on the
-- command-line (@-package@, @-hide-package@ etc.)
--
-- Returns a list of packages to link in if we're doing dynamic linking.
-- This list contains the packages that the user explicitly mentioned with
-- @-package@ flags.
--
-- 'initPackages' can be called again subsequently after updating the
-- 'packageFlags' field of the 'DynFlags', and it will update the
-- 'pkgState' in 'DynFlags' and return a list of packages to
-- link in.
initPackages :: DynFlags -> IO (DynFlags, [PackageKey])
initPackages dflags = do
pkg_db <- case pkgDatabase dflags of
Nothing -> readPackageConfigs dflags
Just db -> return $ setBatchPackageFlags dflags db
(pkg_state, preload, this_pkg)
<- mkPackageState dflags pkg_db [] (thisPackage dflags)
return (dflags{ pkgDatabase = Just pkg_db,
pkgState = pkg_state,
thisPackage = this_pkg },
preload)
-- -----------------------------------------------------------------------------
-- Reading the package database(s)
readPackageConfigs :: DynFlags -> IO [PackageConfig]
readPackageConfigs dflags = do
conf_refs <- getPackageConfRefs dflags
confs <- liftM catMaybes $ mapM (resolvePackageConfig dflags) conf_refs
liftM concat $ mapM (readPackageConfig dflags) confs
getPackageConfRefs :: DynFlags -> IO [PkgConfRef]
getPackageConfRefs dflags = do
let system_conf_refs = [UserPkgConf, GlobalPkgConf]
e_pkg_path <- tryIO (getEnv $ map toUpper (programName dflags) ++ "_PACKAGE_PATH")
let base_conf_refs = case e_pkg_path of
Left _ -> system_conf_refs
Right path
| not (null path) && isSearchPathSeparator (last path)
-> map PkgConfFile (splitSearchPath (init path)) ++ system_conf_refs
| otherwise
-> map PkgConfFile (splitSearchPath path)
return $ reverse (extraPkgConfs dflags base_conf_refs)
-- later packages shadow earlier ones. extraPkgConfs
-- is in the opposite order to the flags on the
-- command line.
resolvePackageConfig :: DynFlags -> PkgConfRef -> IO (Maybe FilePath)
resolvePackageConfig dflags GlobalPkgConf = return $ Just (systemPackageConfig dflags)
resolvePackageConfig dflags UserPkgConf = handleIO (\_ -> return Nothing) $ do
dir <- versionedAppDir dflags
let pkgconf = dir </> "package.conf.d"
exist <- doesDirectoryExist pkgconf
return $ if exist then Just pkgconf else Nothing
resolvePackageConfig _ (PkgConfFile name) = return $ Just name
readPackageConfig :: DynFlags -> FilePath -> IO [PackageConfig]
readPackageConfig dflags conf_file = do
isdir <- doesDirectoryExist conf_file
proto_pkg_configs <-
if isdir
then readDirStylePackageConfig conf_file
else do
isfile <- doesFileExist conf_file
if isfile
then do
mpkgs <- tryReadOldFileStylePackageConfig
case mpkgs of
Just pkgs -> return pkgs
Nothing -> throwGhcExceptionIO $ InstallationError $
"ghc no longer supports single-file style package " ++
"databases (" ++ conf_file ++
") use 'ghc-pkg init' to create the database with " ++
"the correct format."
else throwGhcExceptionIO $ InstallationError $
"can't find a package database at " ++ conf_file
let
top_dir = topDir dflags
pkgroot = takeDirectory conf_file
pkg_configs1 = map (mungePackagePaths top_dir pkgroot) proto_pkg_configs
pkg_configs2 = setBatchPackageFlags dflags pkg_configs1
--
return pkg_configs2
where
readDirStylePackageConfig conf_dir = do
let filename = conf_dir </> "package.cache"
debugTraceMsg dflags 2 (text "Using binary package database:" <+> text filename)
readPackageDbForGhc filename
-- Single-file style package dbs have been deprecated for some time, but
-- it turns out that Cabal was using them in one place. So this is a
-- workaround to allow older Cabal versions to use this newer ghc.
-- We check if the file db contains just "[]" and if so, we look for a new
-- dir-style db in conf_file.d/, ie in a dir next to the given file.
-- We cannot just replace the file with a new dir style since Cabal still
-- assumes it's a file and tries to overwrite with 'writeFile'.
-- ghc-pkg also cooperates with this workaround.
tryReadOldFileStylePackageConfig = do
content <- readFile conf_file `catchIO` \_ -> return ""
if take 2 content == "[]"
then do
let conf_dir = conf_file <.> "d"
direxists <- doesDirectoryExist conf_dir
if direxists
then do debugTraceMsg dflags 2 (text "Ignoring old file-style db and trying:" <+> text conf_dir)
liftM Just (readDirStylePackageConfig conf_dir)
else return (Just []) -- ghc-pkg will create it when it's updated
else return Nothing
setBatchPackageFlags :: DynFlags -> [PackageConfig] -> [PackageConfig]
setBatchPackageFlags dflags pkgs = maybeDistrustAll pkgs
where
maybeDistrustAll pkgs'
| gopt Opt_DistrustAllPackages dflags = map distrust pkgs'
| otherwise = pkgs'
distrust pkg = pkg{ trusted = False }
-- TODO: This code is duplicated in utils/ghc-pkg/Main.hs
mungePackagePaths :: FilePath -> FilePath -> PackageConfig -> PackageConfig
-- Perform path/URL variable substitution as per the Cabal ${pkgroot} spec
-- (http://www.haskell.org/pipermail/libraries/2009-May/011772.html)
-- Paths/URLs can be relative to ${pkgroot} or ${pkgrooturl}.
-- The "pkgroot" is the directory containing the package database.
--
-- Also perform a similar substitution for the older GHC-specific
-- "$topdir" variable. The "topdir" is the location of the ghc
-- installation (obtained from the -B option).
mungePackagePaths top_dir pkgroot pkg =
pkg {
importDirs = munge_paths (importDirs pkg),
includeDirs = munge_paths (includeDirs pkg),
libraryDirs = munge_paths (libraryDirs pkg),
frameworkDirs = munge_paths (frameworkDirs pkg),
haddockInterfaces = munge_paths (haddockInterfaces pkg),
haddockHTMLs = munge_urls (haddockHTMLs pkg)
}
where
munge_paths = map munge_path
munge_urls = map munge_url
munge_path p
| Just p' <- stripVarPrefix "${pkgroot}" p = pkgroot ++ p'
| Just p' <- stripVarPrefix "$topdir" p = top_dir ++ p'
| otherwise = p
munge_url p
| Just p' <- stripVarPrefix "${pkgrooturl}" p = toUrlPath pkgroot p'
| Just p' <- stripVarPrefix "$httptopdir" p = toUrlPath top_dir p'
| otherwise = p
toUrlPath r p = "file:///"
-- URLs always use posix style '/' separators:
++ FilePath.Posix.joinPath
(r : -- We need to drop a leading "/" or "\\"
-- if there is one:
dropWhile (all isPathSeparator)
(FilePath.splitDirectories p))
-- We could drop the separator here, and then use </> above. However,
-- by leaving it in and using ++ we keep the same path separator
-- rather than letting FilePath change it to use \ as the separator
stripVarPrefix var path = case stripPrefix var path of
Just [] -> Just []
Just cs@(c : _) | isPathSeparator c -> Just cs
_ -> Nothing
-- -----------------------------------------------------------------------------
-- Modify our copy of the package database based on a package flag
-- (-package, -hide-package, -ignore-package).
applyPackageFlag
:: DynFlags
-> UnusablePackages
-> ([PackageConfig], VisibilityMap) -- Initial database
-> PackageFlag -- flag to apply
-> IO ([PackageConfig], VisibilityMap) -- new database
-- ToDo: Unfortunately, we still have to plumb the package config through,
-- because Safe Haskell trust is still implemented by modifying the database.
-- Eventually, track that separately and then axe @[PackageConfig]@ from
-- this fold entirely
applyPackageFlag dflags unusable (pkgs, vm) flag =
case flag of
ExposePackage arg (ModRenaming b rns) ->
case selectPackages (matching arg) pkgs unusable of
Left ps -> packageFlagErr dflags flag ps
Right (p:_,_) -> return (pkgs, vm')
where
n = fsPackageName p
vm' = addToUFM_C edit vm_cleared (packageConfigId p) (b, rns, n)
edit (b, rns, n) (b', rns', _) = (b || b', rns ++ rns', n)
-- ToDo: ATM, -hide-all-packages implicitly triggers change in
-- behavior, maybe eventually make it toggleable with a separate
-- flag
vm_cleared | gopt Opt_HideAllPackages dflags = vm
| otherwise = filterUFM_Directly
(\k (_,_,n') -> k == getUnique (packageConfigId p)
|| n /= n') vm
_ -> panic "applyPackageFlag"
HidePackage str ->
case selectPackages (matchingStr str) pkgs unusable of
Left ps -> packageFlagErr dflags flag ps
Right (ps,_) -> return (pkgs, vm')
where vm' = delListFromUFM vm (map packageConfigId ps)
-- we trust all matching packages. Maybe should only trust first one?
-- and leave others the same or set them untrusted
TrustPackage str ->
case selectPackages (matchingStr str) pkgs unusable of
Left ps -> packageFlagErr dflags flag ps
Right (ps,qs) -> return (map trust ps ++ qs, vm)
where trust p = p {trusted=True}
DistrustPackage str ->
case selectPackages (matchingStr str) pkgs unusable of
Left ps -> packageFlagErr dflags flag ps
Right (ps,qs) -> return (map distrust ps ++ qs, vm)
where distrust p = p {trusted=False}
IgnorePackage _ -> panic "applyPackageFlag: IgnorePackage"
selectPackages :: (PackageConfig -> Bool) -> [PackageConfig]
-> UnusablePackages
-> Either [(PackageConfig, UnusablePackageReason)]
([PackageConfig], [PackageConfig])
selectPackages matches pkgs unusable
= let (ps,rest) = partition matches pkgs
in if null ps
then Left (filter (matches.fst) (Map.elems unusable))
else Right (sortByVersion ps, rest)
-- A package named on the command line can either include the
-- version, or just the name if it is unambiguous.
matchingStr :: String -> PackageConfig -> Bool
matchingStr str p
= str == sourcePackageIdString p
|| str == packageNameString p
matchingId :: String -> PackageConfig -> Bool
matchingId str p = str == installedPackageIdString p
matchingKey :: String -> PackageConfig -> Bool
matchingKey str p = str == packageKeyString (packageConfigId p)
matching :: PackageArg -> PackageConfig -> Bool
matching (PackageArg str) = matchingStr str
matching (PackageIdArg str) = matchingId str
matching (PackageKeyArg str) = matchingKey str
sortByVersion :: [PackageConfig] -> [PackageConfig]
sortByVersion = sortBy (flip (comparing packageVersion))
comparing :: Ord a => (t -> a) -> t -> t -> Ordering
comparing f a b = f a `compare` f b
packageFlagErr :: DynFlags
-> PackageFlag
-> [(PackageConfig, UnusablePackageReason)]
-> IO a
-- for missing DPH package we emit a more helpful error message, because
-- this may be the result of using -fdph-par or -fdph-seq.
packageFlagErr dflags (ExposePackage (PackageArg pkg) _) []
| is_dph_package pkg
= throwGhcExceptionIO (CmdLineError (showSDoc dflags $ dph_err))
where dph_err = text "the " <> text pkg <> text " package is not installed."
$$ text "To install it: \"cabal install dph\"."
is_dph_package pkg = "dph" `isPrefixOf` pkg
packageFlagErr dflags flag reasons
= throwGhcExceptionIO (CmdLineError (showSDoc dflags $ err))
where err = text "cannot satisfy " <> pprFlag flag <>
(if null reasons then Outputable.empty else text ": ") $$
nest 4 (ppr_reasons $$
-- ToDo: this admonition seems a bit dodgy
text "(use -v for more information)")
ppr_reasons = vcat (map ppr_reason reasons)
ppr_reason (p, reason) =
pprReason (ppr (installedPackageId p) <+> text "is") reason
pprFlag :: PackageFlag -> SDoc
pprFlag flag = case flag of
IgnorePackage p -> text "-ignore-package " <> text p
HidePackage p -> text "-hide-package " <> text p
ExposePackage a rns -> ppr_arg a <> ppr_rns rns
TrustPackage p -> text "-trust " <> text p
DistrustPackage p -> text "-distrust " <> text p
where ppr_arg arg = case arg of
PackageArg p -> text "-package " <> text p
PackageIdArg p -> text "-package-id " <> text p
PackageKeyArg p -> text "-package-key " <> text p
ppr_rns (ModRenaming True []) = Outputable.empty
ppr_rns (ModRenaming b rns) =
if b then text "with" else Outputable.empty <+>
char '(' <> hsep (punctuate comma (map ppr_rn rns)) <> char ')'
ppr_rn (orig, new) | orig == new = ppr orig
| otherwise = ppr orig <+> text "as" <+> ppr new
-- -----------------------------------------------------------------------------
-- Wired-in packages
wired_in_pkgids :: [String]
wired_in_pkgids = map packageKeyString wiredInPackageKeys
findWiredInPackages
:: DynFlags
-> [PackageConfig] -- database
-> VisibilityMap -- info on what packages are visible
-> IO ([PackageConfig], VisibilityMap)
findWiredInPackages dflags pkgs vis_map = do
--
-- Now we must find our wired-in packages, and rename them to
-- their canonical names (eg. base-1.0 ==> base).
--
let
matches :: PackageConfig -> String -> Bool
pc `matches` pid = packageNameString pc == pid
-- find which package corresponds to each wired-in package
-- delete any other packages with the same name
-- update the package and any dependencies to point to the new
-- one.
--
-- When choosing which package to map to a wired-in package
-- name, we try to pick the latest version of exposed packages.
-- However, if there are no exposed wired in packages available
-- (e.g. -hide-all-packages was used), we can't bail: we *have*
-- to assign a package for the wired-in package: so we try again
-- with hidden packages included to (and pick the latest
-- version).
--
-- You can also override the default choice by using -ignore-package:
-- this works even when there is no exposed wired in package
-- available.
--
findWiredInPackage :: [PackageConfig] -> String
-> IO (Maybe PackageConfig)
findWiredInPackage pkgs wired_pkg =
let all_ps = [ p | p <- pkgs, p `matches` wired_pkg ]
all_exposed_ps =
[ p | p <- all_ps
, elemUFM (packageConfigId p) vis_map ] in
case all_exposed_ps of
[] -> case all_ps of
[] -> notfound
many -> pick (head (sortByVersion many))
many -> pick (head (sortByVersion many))
where
notfound = do
debugTraceMsg dflags 2 $
ptext (sLit "wired-in package ")
<> text wired_pkg
<> ptext (sLit " not found.")
return Nothing
pick :: PackageConfig
-> IO (Maybe PackageConfig)
pick pkg = do
debugTraceMsg dflags 2 $
ptext (sLit "wired-in package ")
<> text wired_pkg
<> ptext (sLit " mapped to ")
<> ppr (installedPackageId pkg)
return (Just pkg)
mb_wired_in_pkgs <- mapM (findWiredInPackage pkgs) wired_in_pkgids
let
wired_in_pkgs = catMaybes mb_wired_in_pkgs
wired_in_ids = map installedPackageId wired_in_pkgs
-- this is old: we used to assume that if there were
-- multiple versions of wired-in packages installed that
-- they were mutually exclusive. Now we're assuming that
-- you have one "main" version of each wired-in package
-- (the latest version), and the others are backward-compat
-- wrappers that depend on this one. e.g. base-4.0 is the
-- latest, base-3.0 is a compat wrapper depending on base-4.0.
{-
deleteOtherWiredInPackages pkgs = filterOut bad pkgs
where bad p = any (p `matches`) wired_in_pkgids
&& package p `notElem` map fst wired_in_ids
-}
updateWiredInDependencies pkgs = map upd_pkg pkgs
where upd_pkg pkg
| installedPackageId pkg `elem` wired_in_ids
= pkg {
packageKey = stringToPackageKey (packageNameString pkg)
}
| otherwise
= pkg
updateVisibilityMap vis_map = foldl' f vis_map wired_in_pkgs
where f vm p = case lookupUFM vis_map (packageConfigId p) of
Nothing -> vm
Just r -> addToUFM vm (stringToPackageKey
(packageNameString p)) r
return (updateWiredInDependencies pkgs, updateVisibilityMap vis_map)
-- ----------------------------------------------------------------------------
data UnusablePackageReason
= IgnoredWithFlag
| MissingDependencies [InstalledPackageId]
| ShadowedBy InstalledPackageId
type UnusablePackages = Map InstalledPackageId
(PackageConfig, UnusablePackageReason)
pprReason :: SDoc -> UnusablePackageReason -> SDoc
pprReason pref reason = case reason of
IgnoredWithFlag ->
pref <+> ptext (sLit "ignored due to an -ignore-package flag")
MissingDependencies deps ->
pref <+>
ptext (sLit "unusable due to missing or recursive dependencies:") $$
nest 2 (hsep (map ppr deps))
ShadowedBy ipid ->
pref <+> ptext (sLit "shadowed by package ") <> ppr ipid
reportUnusable :: DynFlags -> UnusablePackages -> IO ()
reportUnusable dflags pkgs = mapM_ report (Map.toList pkgs)
where
report (ipid, (_, reason)) =
debugTraceMsg dflags 2 $
pprReason
(ptext (sLit "package") <+>
ppr ipid <+> text "is") reason
-- ----------------------------------------------------------------------------
--
-- Detect any packages that have missing dependencies, and also any
-- mutually-recursive groups of packages (loops in the package graph
-- are not allowed). We do this by taking the least fixpoint of the
-- dependency graph, repeatedly adding packages whose dependencies are
-- satisfied until no more can be added.
--
findBroken :: [PackageConfig] -> UnusablePackages
findBroken pkgs = go [] Map.empty pkgs
where
go avail ipids not_avail =
case partitionWith (depsAvailable ipids) not_avail of
([], not_avail) ->
Map.fromList [ (installedPackageId p, (p, MissingDependencies deps))
| (p,deps) <- not_avail ]
(new_avail, not_avail) ->
go (new_avail ++ avail) new_ipids (map fst not_avail)
where new_ipids = Map.insertList
[ (installedPackageId p, p) | p <- new_avail ]
ipids
depsAvailable :: InstalledPackageIndex
-> PackageConfig
-> Either PackageConfig (PackageConfig, [InstalledPackageId])
depsAvailable ipids pkg
| null dangling = Left pkg
| otherwise = Right (pkg, dangling)
where dangling = filter (not . (`Map.member` ipids)) (depends pkg)
-- -----------------------------------------------------------------------------
-- Eliminate shadowed packages, giving the user some feedback
-- later packages in the list should shadow earlier ones with the same
-- package name/version. Additionally, a package may be preferred if
-- it is in the transitive closure of packages selected using -package-id
-- flags.
type UnusablePackage = (PackageConfig, UnusablePackageReason)
shadowPackages :: [PackageConfig] -> [InstalledPackageId] -> UnusablePackages
shadowPackages pkgs preferred
= let (shadowed,_) = foldl check ([],emptyUFM) pkgs
in Map.fromList shadowed
where
check :: ([(InstalledPackageId, UnusablePackage)], UniqFM PackageConfig)
-> PackageConfig
-> ([(InstalledPackageId, UnusablePackage)], UniqFM PackageConfig)
check (shadowed,pkgmap) pkg
| Just oldpkg <- lookupUFM pkgmap pkgid
, let
ipid_new = installedPackageId pkg
ipid_old = installedPackageId oldpkg
--
, ipid_old /= ipid_new
= if ipid_old `elem` preferred
then ((ipid_new, (pkg, ShadowedBy ipid_old)) : shadowed, pkgmap)
else ((ipid_old, (oldpkg, ShadowedBy ipid_new)) : shadowed, pkgmap')
| otherwise
= (shadowed, pkgmap')
where
pkgid = packageKeyFS (packageKey pkg)
pkgmap' = addToUFM pkgmap pkgid pkg
-- -----------------------------------------------------------------------------
ignorePackages :: [PackageFlag] -> [PackageConfig] -> UnusablePackages
ignorePackages flags pkgs = Map.fromList (concatMap doit flags)
where
doit (IgnorePackage str) =
case partition (matchingStr str) pkgs of
(ps, _) -> [ (installedPackageId p, (p, IgnoredWithFlag))
| p <- ps ]
-- missing package is not an error for -ignore-package,
-- because a common usage is to -ignore-package P as
-- a preventative measure just in case P exists.
doit _ = panic "ignorePackages"
-- -----------------------------------------------------------------------------
depClosure :: InstalledPackageIndex
-> [InstalledPackageId]
-> [InstalledPackageId]
depClosure index ipids = closure Map.empty ipids
where
closure set [] = Map.keys set
closure set (ipid : ipids)
| ipid `Map.member` set = closure set ipids
| Just p <- Map.lookup ipid index = closure (Map.insert ipid p set)
(depends p ++ ipids)
| otherwise = closure set ipids
-- -----------------------------------------------------------------------------
-- When all the command-line options are in, we can process our package
-- settings and populate the package state.
mkPackageState
:: DynFlags
-> [PackageConfig] -- initial database
-> [PackageKey] -- preloaded packages
-> PackageKey -- this package
-> IO (PackageState,
[PackageKey], -- new packages to preload
PackageKey) -- this package, might be modified if the current
-- package is a wired-in package.
mkPackageState dflags0 pkgs0 preload0 this_package = do
dflags <- interpretPackageEnv dflags0
{-
Plan.
1. P = transitive closure of packages selected by -package-id
2. Apply shadowing. When there are multiple packages with the same
packageKey,
* if one is in P, use that one
* otherwise, use the one highest in the package stack
[
rationale: we cannot use two packages with the same packageKey
in the same program, because packageKey is the symbol prefix.
Hence we must select a consistent set of packages to use. We have
a default algorithm for doing this: packages higher in the stack
shadow those lower down. This default algorithm can be overriden
by giving explicit -package-id flags; then we have to take these
preferences into account when selecting which other packages are
made available.
Our simple algorithm throws away some solutions: there may be other
consistent sets that would satisfy the -package flags, but it's
not GHC's job to be doing constraint solving.
]
3. remove packages selected by -ignore-package
4. remove any packages with missing dependencies, or mutually recursive
dependencies.
5. report (with -v) any packages that were removed by steps 2-4
6. apply flags to set exposed/hidden on the resulting packages
- if any flag refers to a package which was removed by 2-4, then
we can give an error message explaining why
7. hide any packages which are superseded by later exposed packages
-}
let
flags = reverse (packageFlags dflags)
-- pkgs0 with duplicate packages filtered out. This is
-- important: it is possible for a package in the global package
-- DB to have the same IPID as a package in the user DB, and
-- we want the latter to take precedence. This is not the same
-- as shadowing (below), since in this case the two packages
-- have the same ABI and are interchangeable.
--
-- #4072: note that we must retain the ordering of the list here
-- so that shadowing behaves as expected when we apply it later.
pkgs0_unique = snd $ foldr del (Set.empty,[]) pkgs0
where del p (s,ps)
| pid `Set.member` s = (s,ps)
| otherwise = (Set.insert pid s, p:ps)
where pid = installedPackageId p
-- XXX this is just a variant of nub
ipid_map = Map.fromList [ (installedPackageId p, p) | p <- pkgs0 ]
ipid_selected = depClosure ipid_map
[ InstalledPackageId (mkFastString i)
| ExposePackage (PackageIdArg i) _ <- flags ]
(ignore_flags, other_flags) = partition is_ignore flags
is_ignore IgnorePackage{} = True
is_ignore _ = False
shadowed = shadowPackages pkgs0_unique ipid_selected
ignored = ignorePackages ignore_flags pkgs0_unique
isBroken = (`Map.member` (Map.union shadowed ignored)).installedPackageId
pkgs0' = filter (not . isBroken) pkgs0_unique
broken = findBroken pkgs0'
unusable = shadowed `Map.union` ignored `Map.union` broken
pkgs1 = filter (not . (`Map.member` unusable) . installedPackageId) pkgs0'
reportUnusable dflags unusable
--
-- Calculate the initial set of packages, prior to any package flags.
-- This set contains the latest version of all valid (not unusable) packages,
-- or is empty if we have -hide-all-packages
--
let preferLater pkg pkg' =
case comparing packageVersion pkg pkg' of
GT -> pkg
_ -> pkg'
calcInitial m pkg = addToUFM_C preferLater m (fsPackageName pkg) pkg
initial = if gopt Opt_HideAllPackages dflags
then emptyUFM
else foldl' calcInitial emptyUFM pkgs1
vis_map1 = foldUFM (\p vm ->
if exposed p
then addToUFM vm (packageConfigId p)
(True, [], fsPackageName p)
else vm)
emptyUFM initial
--
-- Modify the package database according to the command-line flags
-- (-package, -hide-package, -ignore-package, -hide-all-packages).
-- This needs to know about the unusable packages, since if a user tries
-- to enable an unusable package, we should let them know.
--
(pkgs2, vis_map2) <- foldM (applyPackageFlag dflags unusable)
(pkgs1, vis_map1) other_flags
--
-- Sort out which packages are wired in. This has to be done last, since
-- it modifies the package keys of wired in packages, but when we process
-- package arguments we need to key against the old versions. We also
-- have to update the visibility map in the process.
--
(pkgs3, vis_map) <- findWiredInPackages dflags pkgs2 vis_map2
--
-- Here we build up a set of the packages mentioned in -package
-- flags on the command line; these are called the "preload"
-- packages. we link these packages in eagerly. The preload set
-- should contain at least rts & base, which is why we pretend that
-- the command line contains -package rts & -package base.
--
let preload1 = [ installedPackageId p | f <- flags, p <- get_exposed f ]
get_exposed (ExposePackage a _) = take 1 . sortByVersion
. filter (matching a)
$ pkgs2
get_exposed _ = []
let pkg_db = extendPackageConfigMap emptyPackageConfigMap pkgs3
ipid_map = Map.fromList [ (installedPackageId p, packageConfigId p)
| p <- pkgs3 ]
lookupIPID ipid
| Just pid <- Map.lookup ipid ipid_map = return pid
| otherwise = missingPackageErr dflags ipid
preload2 <- mapM lookupIPID preload1
let
-- add base & rts to the preload packages
basicLinkedPackages
| gopt Opt_AutoLinkPackages dflags
= filter (flip elemUFM pkg_db)
[basePackageKey, rtsPackageKey]
| otherwise = []
-- but in any case remove the current package from the set of
-- preloaded packages so that base/rts does not end up in the
-- set up preloaded package when we are just building it
preload3 = nub $ filter (/= this_package)
$ (basicLinkedPackages ++ preload2)
-- Close the preload packages with their dependencies
dep_preload <- closeDeps dflags pkg_db ipid_map (zip preload3 (repeat Nothing))
let new_dep_preload = filter (`notElem` preload0) dep_preload
let pstate = PackageState{
preloadPackages = dep_preload,
pkgIdMap = pkg_db,
moduleToPkgConfAll = mkModuleToPkgConfAll dflags pkg_db ipid_map vis_map,
installedPackageIdMap = ipid_map
}
return (pstate, new_dep_preload, this_package)
-- -----------------------------------------------------------------------------
-- | Makes the mapping from module to package info
mkModuleToPkgConfAll
:: DynFlags
-> PackageConfigMap
-> InstalledPackageIdMap
-> VisibilityMap
-> ModuleToPkgConfAll
mkModuleToPkgConfAll dflags pkg_db ipid_map vis_map =
foldl' extend_modmap emptyMap (eltsUFM pkg_db)
where
emptyMap = Map.empty
sing pk m _ = Map.singleton (mkModule pk m)
addListTo = foldl' merge
merge m (k, v) = Map.insertWith (Map.unionWith mappend) k v m
setOrigins m os = fmap (const os) m
extend_modmap modmap pkg = addListTo modmap theBindings
where
theBindings :: [(ModuleName, Map Module ModuleOrigin)]
theBindings | Just (b,rns,_) <- lookupUFM vis_map (packageConfigId pkg)
= newBindings b rns
| otherwise = newBindings False []
newBindings :: Bool
-> [(ModuleName, ModuleName)]
-> [(ModuleName, Map Module ModuleOrigin)]
newBindings e rns = es e ++ hiddens ++ map rnBinding rns
rnBinding :: (ModuleName, ModuleName)
-> (ModuleName, Map Module ModuleOrigin)
rnBinding (orig, new) = (new, setOrigins origEntry fromFlag)
where origEntry = case lookupUFM esmap orig of
Just r -> r
Nothing -> throwGhcException (CmdLineError (showSDoc dflags
(text "package flag: could not find module name" <+>
ppr orig <+> text "in package" <+> ppr pk)))
es :: Bool -> [(ModuleName, Map Module ModuleOrigin)]
es e = do
-- TODO: signature support
ExposedModule m exposedReexport _exposedSignature <- exposed_mods
let (pk', m', pkg', origin') =
case exposedReexport of
Nothing -> (pk, m, pkg, fromExposedModules e)
Just (OriginalModule ipid' m') ->
let pk' = expectJust "mkModuleToPkgConf" (Map.lookup ipid' ipid_map)
pkg' = pkg_lookup pk'
in (pk', m', pkg', fromReexportedModules e pkg')
return (m, sing pk' m' pkg' origin')
esmap :: UniqFM (Map Module ModuleOrigin)
esmap = listToUFM (es False) -- parameter here doesn't matter, orig will
-- be overwritten
hiddens = [(m, sing pk m pkg ModHidden) | m <- hidden_mods]
pk = packageConfigId pkg
pkg_lookup = expectJust "mkModuleToPkgConf" . lookupPackage' pkg_db
exposed_mods = exposedModules pkg
hidden_mods = hiddenModules pkg
-- -----------------------------------------------------------------------------
-- Extracting information from the packages in scope
-- Many of these functions take a list of packages: in those cases,
-- the list is expected to contain the "dependent packages",
-- i.e. those packages that were found to be depended on by the
-- current module/program. These can be auto or non-auto packages, it
-- doesn't really matter. The list is always combined with the list
-- of preload (command-line) packages to determine which packages to
-- use.
-- | Find all the include directories in these and the preload packages
getPackageIncludePath :: DynFlags -> [PackageKey] -> IO [String]
getPackageIncludePath dflags pkgs =
collectIncludeDirs `fmap` getPreloadPackagesAnd dflags pkgs
collectIncludeDirs :: [PackageConfig] -> [FilePath]
collectIncludeDirs ps = nub (filter notNull (concatMap includeDirs ps))
-- | Find all the library paths in these and the preload packages
getPackageLibraryPath :: DynFlags -> [PackageKey] -> IO [String]
getPackageLibraryPath dflags pkgs =
collectLibraryPaths `fmap` getPreloadPackagesAnd dflags pkgs
collectLibraryPaths :: [PackageConfig] -> [FilePath]
collectLibraryPaths ps = nub (filter notNull (concatMap libraryDirs ps))
-- | Find all the link options in these and the preload packages,
-- returning (package hs lib options, extra library options, other flags)
getPackageLinkOpts :: DynFlags -> [PackageKey] -> IO ([String], [String], [String])
getPackageLinkOpts dflags pkgs =
collectLinkOpts dflags `fmap` getPreloadPackagesAnd dflags pkgs
collectLinkOpts :: DynFlags -> [PackageConfig] -> ([String], [String], [String])
collectLinkOpts dflags ps =
(
concatMap (map ("-l" ++) . packageHsLibs dflags) ps,
concatMap (map ("-l" ++) . extraLibraries) ps,
concatMap ldOptions ps
)
packageHsLibs :: DynFlags -> PackageConfig -> [String]
packageHsLibs dflags p = map (mkDynName . addSuffix) (hsLibraries p)
where
ways0 = ways dflags
ways1 = filter (/= WayDyn) ways0
-- the name of a shared library is libHSfoo-ghc<version>.so
-- we leave out the _dyn, because it is superfluous
-- debug RTS includes support for -eventlog
ways2 | WayDebug `elem` ways1
= filter (/= WayEventLog) ways1
| otherwise
= ways1
tag = mkBuildTag (filter (not . wayRTSOnly) ways2)
rts_tag = mkBuildTag ways2
mkDynName x
| gopt Opt_Static dflags = x
| "HS" `isPrefixOf` x =
x ++ '-':programName dflags ++ projectVersion dflags
-- For non-Haskell libraries, we use the name "Cfoo". The .a
-- file is libCfoo.a, and the .so is libfoo.so. That way the
-- linker knows what we mean for the vanilla (-lCfoo) and dyn
-- (-lfoo) ways. We therefore need to strip the 'C' off here.
| Just x' <- stripPrefix "C" x = x'
| otherwise
= panic ("Don't understand library name " ++ x)
addSuffix rts@"HSrts" = rts ++ (expandTag rts_tag)
addSuffix other_lib = other_lib ++ (expandTag tag)
expandTag t | null t = ""
| otherwise = '_':t
-- | Find all the C-compiler options in these and the preload packages
getPackageExtraCcOpts :: DynFlags -> [PackageKey] -> IO [String]
getPackageExtraCcOpts dflags pkgs = do
ps <- getPreloadPackagesAnd dflags pkgs
return (concatMap ccOptions ps)
-- | Find all the package framework paths in these and the preload packages
getPackageFrameworkPath :: DynFlags -> [PackageKey] -> IO [String]
getPackageFrameworkPath dflags pkgs = do
ps <- getPreloadPackagesAnd dflags pkgs
return (nub (filter notNull (concatMap frameworkDirs ps)))
-- | Find all the package frameworks in these and the preload packages
getPackageFrameworks :: DynFlags -> [PackageKey] -> IO [String]
getPackageFrameworks dflags pkgs = do
ps <- getPreloadPackagesAnd dflags pkgs
return (concatMap frameworks ps)
-- -----------------------------------------------------------------------------
-- Package Utils
-- | Takes a 'ModuleName', and if the module is in any package returns
-- list of modules which take that name.
lookupModuleInAllPackages :: DynFlags
-> ModuleName
-> [(Module, PackageConfig)]
lookupModuleInAllPackages dflags m
= case lookupModuleWithSuggestions dflags m Nothing of
LookupFound a b -> [(a,b)]
LookupMultiple rs -> map f rs
where f (m,_) = (m, expectJust "lookupModule" (lookupPackage dflags
(modulePackageKey m)))
_ -> []
-- | The result of performing a lookup
data LookupResult =
-- | Found the module uniquely, nothing else to do
LookupFound Module PackageConfig
-- | Multiple modules with the same name in scope
| LookupMultiple [(Module, ModuleOrigin)]
-- | No modules found, but there were some hidden ones with
-- an exact name match. First is due to package hidden, second
-- is due to module being hidden
| LookupHidden [(Module, ModuleOrigin)] [(Module, ModuleOrigin)]
-- | Nothing found, here are some suggested different names
| LookupNotFound [ModuleSuggestion] -- suggestions
data ModuleSuggestion = SuggestVisible ModuleName Module ModuleOrigin
| SuggestHidden ModuleName Module ModuleOrigin
lookupModuleWithSuggestions :: DynFlags
-> ModuleName
-> Maybe FastString
-> LookupResult
lookupModuleWithSuggestions dflags m mb_pn
= case Map.lookup m (moduleToPkgConfAll pkg_state) of
Nothing -> LookupNotFound suggestions
Just xs ->
case foldl' classify ([],[],[]) (Map.toList xs) of
([], [], []) -> LookupNotFound suggestions
(_, _, [(m, _)]) -> LookupFound m (mod_pkg m)
(_, _, exposed@(_:_)) -> LookupMultiple exposed
(hidden_pkg, hidden_mod, []) -> LookupHidden hidden_pkg hidden_mod
where
classify (hidden_pkg, hidden_mod, exposed) (m, origin0) =
let origin = filterOrigin mb_pn (mod_pkg m) origin0
x = (m, origin)
in case origin of
ModHidden -> (hidden_pkg, x:hidden_mod, exposed)
_ | originEmpty origin -> (hidden_pkg, hidden_mod, exposed)
| originVisible origin -> (hidden_pkg, hidden_mod, x:exposed)
| otherwise -> (x:hidden_pkg, hidden_mod, exposed)
pkg_lookup = expectJust "lookupModuleWithSuggestions" . lookupPackage dflags
pkg_state = pkgState dflags
mod_pkg = pkg_lookup . modulePackageKey
-- Filters out origins which are not associated with the given package
-- qualifier. No-op if there is no package qualifier. Test if this
-- excluded all origins with 'originEmpty'.
filterOrigin :: Maybe FastString
-> PackageConfig
-> ModuleOrigin
-> ModuleOrigin
filterOrigin Nothing _ o = o
filterOrigin (Just pn) pkg o =
case o of
ModHidden -> if go pkg then ModHidden else mempty
ModOrigin { fromOrigPackage = e, fromExposedReexport = res,
fromHiddenReexport = rhs }
-> ModOrigin {
fromOrigPackage = if go pkg then e else Nothing
, fromExposedReexport = filter go res
, fromHiddenReexport = filter go rhs
, fromPackageFlag = False -- always excluded
}
where go pkg = pn == fsPackageName pkg
suggestions
| gopt Opt_HelpfulErrors dflags =
fuzzyLookup (moduleNameString m) all_mods
| otherwise = []
all_mods :: [(String, ModuleSuggestion)] -- All modules
all_mods = sortBy (comparing fst) $
[ (moduleNameString m, suggestion)
| (m, e) <- Map.toList (moduleToPkgConfAll (pkgState dflags))
, suggestion <- map (getSuggestion m) (Map.toList e)
]
getSuggestion name (mod, origin) =
(if originVisible origin then SuggestVisible else SuggestHidden)
name mod origin
listVisibleModuleNames :: DynFlags -> [ModuleName]
listVisibleModuleNames dflags =
map fst (filter visible (Map.toList (moduleToPkgConfAll (pkgState dflags))))
where visible (_, ms) = any originVisible (Map.elems ms)
-- | Find all the 'PackageConfig' in both the preload packages from 'DynFlags' and corresponding to the list of
-- 'PackageConfig's
getPreloadPackagesAnd :: DynFlags -> [PackageKey] -> IO [PackageConfig]
getPreloadPackagesAnd dflags pkgids =
let
state = pkgState dflags
pkg_map = pkgIdMap state
ipid_map = installedPackageIdMap state
preload = preloadPackages state
pairs = zip pkgids (repeat Nothing)
in do
all_pkgs <- throwErr dflags (foldM (add_package pkg_map ipid_map) preload pairs)
return (map (getPackageDetails dflags) all_pkgs)
-- Takes a list of packages, and returns the list with dependencies included,
-- in reverse dependency order (a package appears before those it depends on).
closeDeps :: DynFlags
-> PackageConfigMap
-> Map InstalledPackageId PackageKey
-> [(PackageKey, Maybe PackageKey)]
-> IO [PackageKey]
closeDeps dflags pkg_map ipid_map ps
= throwErr dflags (closeDepsErr pkg_map ipid_map ps)
throwErr :: DynFlags -> MaybeErr MsgDoc a -> IO a
throwErr dflags m
= case m of
Failed e -> throwGhcExceptionIO (CmdLineError (showSDoc dflags e))
Succeeded r -> return r
closeDepsErr :: PackageConfigMap
-> Map InstalledPackageId PackageKey
-> [(PackageKey,Maybe PackageKey)]
-> MaybeErr MsgDoc [PackageKey]
closeDepsErr pkg_map ipid_map ps = foldM (add_package pkg_map ipid_map) [] ps
-- internal helper
add_package :: PackageConfigMap
-> Map InstalledPackageId PackageKey
-> [PackageKey]
-> (PackageKey,Maybe PackageKey)
-> MaybeErr MsgDoc [PackageKey]
add_package pkg_db ipid_map ps (p, mb_parent)
| p `elem` ps = return ps -- Check if we've already added this package
| otherwise =
case lookupPackage' pkg_db p of
Nothing -> Failed (missingPackageMsg p <>
missingDependencyMsg mb_parent)
Just pkg -> do
-- Add the package's dependents also
ps' <- foldM add_package_ipid ps (depends pkg)
return (p : ps')
where
add_package_ipid ps ipid
| Just pid <- Map.lookup ipid ipid_map
= add_package pkg_db ipid_map ps (pid, Just p)
| otherwise
= Failed (missingPackageMsg ipid
<> missingDependencyMsg mb_parent)
missingPackageErr :: Outputable pkgid => DynFlags -> pkgid -> IO a
missingPackageErr dflags p
= throwGhcExceptionIO (CmdLineError (showSDoc dflags (missingPackageMsg p)))
missingPackageMsg :: Outputable pkgid => pkgid -> SDoc
missingPackageMsg p = ptext (sLit "unknown package:") <+> ppr p
missingDependencyMsg :: Maybe PackageKey -> SDoc
missingDependencyMsg Nothing = Outputable.empty
missingDependencyMsg (Just parent)
= space <> parens (ptext (sLit "dependency of") <+> ftext (packageKeyFS parent))
-- -----------------------------------------------------------------------------
packageKeyPackageIdString :: DynFlags -> PackageKey -> String
packageKeyPackageIdString dflags pkg_key
| pkg_key == mainPackageKey = "main"
| otherwise = maybe "(unknown)"
sourcePackageIdString
(lookupPackage dflags pkg_key)
-- | Will the 'Name' come from a dynamically linked library?
isDllName :: DynFlags -> PackageKey -> Module -> Name -> Bool
-- Despite the "dll", I think this function just means that
-- the synbol comes from another dynamically-linked package,
-- and applies on all platforms, not just Windows
isDllName dflags _this_pkg this_mod name
| gopt Opt_Static dflags = False
| Just mod <- nameModule_maybe name
-- Issue #8696 - when GHC is dynamically linked, it will attempt
-- to load the dynamic dependencies of object files at compile
-- time for things like QuasiQuotes or
-- TemplateHaskell. Unfortunately, this interacts badly with
-- intra-package linking, because we don't generate indirect
-- (dynamic) symbols for intra-package calls. This means that if a
-- module with an intra-package call is loaded without its
-- dependencies, then GHC fails to link. This is the cause of #
--
-- In the mean time, always force dynamic indirections to be
-- generated: when the module name isn't the module being
-- compiled, references are dynamic.
= if mod /= this_mod
then True
else case dllSplit dflags of
Nothing -> False
Just ss ->
let findMod m = let modStr = moduleNameString (moduleName m)
in case find (modStr `Set.member`) ss of
Just i -> i
Nothing -> panic ("Can't find " ++ modStr ++ "in DLL split")
in findMod mod /= findMod this_mod
| otherwise = False -- no, it is not even an external name
-- -----------------------------------------------------------------------------
-- Displaying packages
-- | Show (very verbose) package info
pprPackages :: DynFlags -> SDoc
pprPackages = pprPackagesWith pprPackageConfig
pprPackagesWith :: (PackageConfig -> SDoc) -> DynFlags -> SDoc
pprPackagesWith pprIPI dflags =
vcat (intersperse (text "---") (map pprIPI (listPackageConfigMap dflags)))
-- | Show simplified package info.
--
-- The idea is to only print package id, and any information that might
-- be different from the package databases (exposure, trust)
pprPackagesSimple :: DynFlags -> SDoc
pprPackagesSimple = pprPackagesWith pprIPI
where pprIPI ipi = let InstalledPackageId i = installedPackageId ipi
e = if exposed ipi then text "E" else text " "
t = if trusted ipi then text "T" else text " "
in e <> t <> text " " <> ftext i
-- | Show the mapping of modules to where they come from.
pprModuleMap :: DynFlags -> SDoc
pprModuleMap dflags =
vcat (map pprLine (Map.toList (moduleToPkgConfAll (pkgState dflags))))
where
pprLine (m,e) = ppr m $$ nest 50 (vcat (map (pprEntry m) (Map.toList e)))
pprEntry m (m',o)
| m == moduleName m' = ppr (modulePackageKey m') <+> parens (ppr o)
| otherwise = ppr m' <+> parens (ppr o)
fsPackageName :: PackageConfig -> FastString
fsPackageName = mkFastString . packageNameString
|
gcampax/ghc
|
compiler/main/Packages.hs
|
bsd-3-clause
| 60,033 | 239 | 22 | 16,176 | 10,450 | 5,672 | 4,778 | 837 | 11 |
module Network.Kontiki.RaftSpec where
import Data.Kontiki.MemLog
import Network.Kontiki.Raft
import Test.Hspec
import Test.QuickCheck
raftSpec :: Spec
raftSpec = describe "Raft Protocol" $ do
it "steps down and grant vote on Request Vote if term is greater" $ do
handleRequestVote
|
abailly/kontiki
|
test/Network/Kontiki/RaftSpec.hs
|
bsd-3-clause
| 330 | 0 | 10 | 86 | 59 | 33 | 26 | 9 | 1 |
module Buildsome.Color
( Scheme(..), scheme
) where
import Lib.ColorText (ColorText(..), withAttr)
import System.Console.ANSI (Color(..), ColorIntensity(..))
import qualified Lib.Printer as Printer
import qualified System.Console.ANSI as Console
fgColor :: ColorIntensity -> Color -> Console.SGR
fgColor = Console.SetColor Console.Foreground
-- bgColor :: ColorIntensity -> Color -> Console.SGR
-- bgColor = Console.SetColor Console.Background
data Scheme = Scheme
{ cWarning :: ColorText -> ColorText
, cError :: ColorText -> ColorText
, cTarget :: ColorText -> ColorText
, cPath :: ColorText -> ColorText
, cTiming :: ColorText -> ColorText
, cSuccess :: ColorText -> ColorText
, cCommand :: ColorText -> ColorText
, cStdout :: ColorText -> ColorText
, cStderr :: ColorText -> ColorText
, cPrinter :: Printer.ColorScheme
}
scheme :: Scheme
scheme = Scheme
{ cWarning = withAttr [fgColor Vivid Yellow]
, cError = withAttr [fgColor Vivid Red]
, cTarget = withAttr [fgColor Vivid Cyan]
, cPath = withAttr [fgColor Dull Cyan]
, cTiming = withAttr [fgColor Vivid Blue]
, cSuccess = withAttr [fgColor Vivid Green]
, cCommand = withAttr [fgColor Dull White]
, cStdout = withAttr [fgColor Dull Green]
, cStderr = withAttr [fgColor Dull Red]
, cPrinter = Printer.ColorScheme
{ Printer.cException = withAttr [fgColor Vivid Red]
, Printer.cOk = withAttr [fgColor Vivid Green]
}
}
|
nadavshemer/buildsome
|
src/Buildsome/Color.hs
|
gpl-2.0
| 1,456 | 0 | 11 | 286 | 423 | 245 | 178 | 33 | 1 |
module TypeArityTycon3 where
main :: A
main = 0
data A a = A a
|
roberth/uu-helium
|
test/staticerrors/TypeArityTycon3.hs
|
gpl-3.0
| 65 | 0 | 6 | 17 | 24 | 15 | 9 | 4 | 1 |
-- |
-- Module : Data.Hourglass.Internal
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : unknown
--
-- System lowlevel functions
--
{-# LANGUAGE CPP #-}
module Data.Hourglass.Internal
( dateTimeFromUnixEpochP
, dateTimeFromUnixEpoch
, systemGetTimezone
, systemGetElapsed
, systemGetElapsedP
) where
#ifdef WINDOWS
import Data.Hourglass.Internal.Win
#else
import Data.Hourglass.Internal.Unix
#endif
|
ppelleti/hs-hourglass
|
Data/Hourglass/Internal.hs
|
bsd-3-clause
| 508 | 0 | 4 | 93 | 44 | 34 | 10 | 8 | 0 |
{-# OPTIONS_GHC -cpp #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Version
-- Copyright : Isaac Jones, Simon Marlow 2003-2004
--
-- Maintainer : Isaac Jones <[email protected]>
-- Stability : alpha
-- Portability : portable
--
-- Versions for packages, based on the 'Version' datatype.
{- Copyright (c) 2003-2004, Isaac Jones
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Isaac Jones nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -}
module Distribution.Version (
-- * Package versions
Version(..),
showVersion,
parseVersion,
-- * Version ranges
VersionRange(..),
orLaterVersion, orEarlierVersion,
betweenVersionsInclusive,
withinRange,
showVersionRange,
parseVersionRange,
-- * Dependencies
Dependency(..),
#ifdef DEBUG
hunitTests
#endif
) where
#if __HUGS__ || __GLASGOW_HASKELL__ >= 603
import Data.Version ( Version(..), showVersion, parseVersion )
#endif
import Control.Monad ( liftM )
import Distribution.Compat.ReadP
#ifdef DEBUG
import HUnit
#endif
-- -----------------------------------------------------------------------------
-- The Version type
#if ( __GLASGOW_HASKELL__ && __GLASGOW_HASKELL__ < 603 ) || __NHC__
-- Code copied from Data.Version in GHC 6.3+ :
-- These #ifdefs are necessary because this code might be compiled as
-- part of ghc/lib/compat, and hence might be compiled by an older version
-- of GHC. In which case, we might need to pick up ReadP from
-- Distribution.Compat.ReadP, because the version in
-- Text.ParserCombinators.ReadP doesn't have all the combinators we need.
#if __GLASGOW_HASKELL__ <= 602 || __NHC__
import Distribution.Compat.ReadP
#else
import Text.ParserCombinators.ReadP
#endif
#if __GLASGOW_HASKELL__ < 602
import Data.Dynamic ( Typeable(..), TyCon, mkTyCon, mkAppTy )
#else
import Data.Typeable ( Typeable )
#endif
import Data.List ( intersperse, sort )
import Data.Char ( isDigit, isAlphaNum )
{- |
A 'Version' represents the version of a software entity.
An instance of 'Eq' is provided, which implements exact equality
modulo reordering of the tags in the 'versionTags' field.
An instance of 'Ord' is also provided, which gives lexicographic
ordering on the 'versionBranch' fields (i.e. 2.1 > 2.0, 1.2.3 > 1.2.2,
etc.). This is expected to be sufficient for many uses, but note that
you may need to use a more specific ordering for your versioning
scheme. For example, some versioning schemes may include pre-releases
which have tags @"pre1"@, @"pre2"@, and so on, and these would need to
be taken into account when determining ordering. In some cases, date
ordering may be more appropriate, so the application would have to
look for @date@ tags in the 'versionTags' field and compare those.
The bottom line is, don't always assume that 'compare' and other 'Ord'
operations are the right thing for every 'Version'.
Similarly, concrete representations of versions may differ. One
possible concrete representation is provided (see 'showVersion' and
'parseVersion'), but depending on the application a different concrete
representation may be more appropriate.
-}
data Version =
Version { versionBranch :: [Int],
-- ^ The numeric branch for this version. This reflects the
-- fact that most software versions are tree-structured; there
-- is a main trunk which is tagged with versions at various
-- points (1,2,3...), and the first branch off the trunk after
-- version 3 is 3.1, the second branch off the trunk after
-- version 3 is 3.2, and so on. The tree can be branched
-- arbitrarily, just by adding more digits.
--
-- We represent the branch as a list of 'Int', so
-- version 3.2.1 becomes [3,2,1]. Lexicographic ordering
-- (i.e. the default instance of 'Ord' for @[Int]@) gives
-- the natural ordering of branches.
versionTags :: [String] -- really a bag
-- ^ A version can be tagged with an arbitrary list of strings.
-- The interpretation of the list of tags is entirely dependent
-- on the entity that this version applies to.
}
deriving (Read,Show
#if __GLASGOW_HASKELL__ >= 602
,Typeable
#endif
)
#if __GLASGOW_HASKELL__ && __GLASGOW_HASKELL__ < 602
versionTc :: TyCon
versionTc = mkTyCon "Version"
instance Typeable Version where
typeOf _ = mkAppTy versionTc []
#endif
instance Eq Version where
v1 == v2 = versionBranch v1 == versionBranch v2
&& sort (versionTags v1) == sort (versionTags v2)
-- tags may be in any order
instance Ord Version where
v1 `compare` v2 = versionBranch v1 `compare` versionBranch v2
-- -----------------------------------------------------------------------------
-- A concrete representation of 'Version'
-- | Provides one possible concrete representation for 'Version'. For
-- a version with 'versionBranch' @= [1,2,3]@ and 'versionTags'
-- @= ["tag1","tag2"]@, the output will be @1.2.3-tag1-tag2@.
--
showVersion :: Version -> String
showVersion (Version branch tags)
= concat (intersperse "." (map show branch)) ++
concatMap ('-':) tags
-- | A parser for versions in the format produced by 'showVersion'.
--
#if __GLASGOW_HASKELL__ <= 602
parseVersion :: ReadP r Version
#else
parseVersion :: ReadP Version
#endif
parseVersion = do branch <- sepBy1 (liftM read $ munch1 isDigit) (char '.')
tags <- many (char '-' >> munch1 isAlphaNum)
return Version{versionBranch=branch, versionTags=tags}
#endif
-- -----------------------------------------------------------------------------
-- Version ranges
-- Todo: maybe move this to Distribution.Package.Version?
-- (package-specific versioning scheme).
data VersionRange
= AnyVersion
| ThisVersion Version -- = version
| LaterVersion Version -- > version (NB. not >=)
| EarlierVersion Version -- < version
-- ToDo: are these too general?
| UnionVersionRanges VersionRange VersionRange
| IntersectVersionRanges VersionRange VersionRange
deriving (Show,Read,Eq)
orLaterVersion :: Version -> VersionRange
orLaterVersion v = UnionVersionRanges (ThisVersion v) (LaterVersion v)
orEarlierVersion :: Version -> VersionRange
orEarlierVersion v = UnionVersionRanges (ThisVersion v) (EarlierVersion v)
betweenVersionsInclusive :: Version -> Version -> VersionRange
betweenVersionsInclusive v1 v2 =
IntersectVersionRanges (orLaterVersion v1) (orEarlierVersion v2)
laterVersion :: Version -> Version -> Bool
v1 `laterVersion` v2 = versionBranch v1 > versionBranch v2
earlierVersion :: Version -> Version -> Bool
v1 `earlierVersion` v2 = versionBranch v1 < versionBranch v2
-- |Does this version fall within the given range?
withinRange :: Version -> VersionRange -> Bool
withinRange _ AnyVersion = True
withinRange v1 (ThisVersion v2) = v1 == v2
withinRange v1 (LaterVersion v2) = v1 `laterVersion` v2
withinRange v1 (EarlierVersion v2) = v1 `earlierVersion` v2
withinRange v1 (UnionVersionRanges v2 v3)
= v1 `withinRange` v2 || v1 `withinRange` v3
withinRange v1 (IntersectVersionRanges v2 v3)
= v1 `withinRange` v2 && v1 `withinRange` v3
showVersionRange :: VersionRange -> String
showVersionRange AnyVersion = "-any"
showVersionRange (ThisVersion v) = '=' : '=' : showVersion v
showVersionRange (LaterVersion v) = '>' : showVersion v
showVersionRange (EarlierVersion v) = '<' : showVersion v
showVersionRange (UnionVersionRanges (ThisVersion v1) (LaterVersion v2))
| v1 == v2 = '>' : '=' : showVersion v1
showVersionRange (UnionVersionRanges (LaterVersion v2) (ThisVersion v1))
| v1 == v2 = '>' : '=' : showVersion v1
showVersionRange (UnionVersionRanges (ThisVersion v1) (EarlierVersion v2))
| v1 == v2 = '<' : '=' : showVersion v1
showVersionRange (UnionVersionRanges (EarlierVersion v2) (ThisVersion v1))
| v1 == v2 = '<' : '=' : showVersion v1
showVersionRange (UnionVersionRanges r1 r2)
= showVersionRange r1 ++ "||" ++ showVersionRange r2
showVersionRange (IntersectVersionRanges r1 r2)
= showVersionRange r1 ++ "&&" ++ showVersionRange r2
-- ------------------------------------------------------------
-- * Package dependencies
-- ------------------------------------------------------------
data Dependency = Dependency String VersionRange
deriving (Read, Show, Eq)
-- ------------------------------------------------------------
-- * Parsing
-- ------------------------------------------------------------
-- -----------------------------------------------------------
parseVersionRange :: ReadP r VersionRange
parseVersionRange = do
f1 <- factor
skipSpaces
(do
string "||"
skipSpaces
f2 <- factor
return (UnionVersionRanges f1 f2)
+++
do
string "&&"
skipSpaces
f2 <- factor
return (IntersectVersionRanges f1 f2)
+++
return f1)
where
factor = choice ((string "-any" >> return AnyVersion) :
map parseRangeOp rangeOps)
parseRangeOp (s,f) = string s >> skipSpaces >> liftM f parseVersion
rangeOps = [ ("<", EarlierVersion),
("<=", orEarlierVersion),
(">", LaterVersion),
(">=", orLaterVersion),
("==", ThisVersion) ]
#ifdef DEBUG
-- ------------------------------------------------------------
-- * Testing
-- ------------------------------------------------------------
-- |Simple version parser wrapper
doVersionParse :: String -> Either String Version
doVersionParse input = case results of
[y] -> Right y
[] -> Left "No parse"
_ -> Left "Ambigous parse"
where results = [ x | (x,"") <- readP_to_S parseVersion input ]
branch1 :: [Int]
branch1 = [1]
branch2 :: [Int]
branch2 = [1,2]
branch3 :: [Int]
branch3 = [1,2,3]
release1 :: Version
release1 = Version{versionBranch=branch1, versionTags=[]}
release2 :: Version
release2 = Version{versionBranch=branch2, versionTags=[]}
release3 :: Version
release3 = Version{versionBranch=branch3, versionTags=[]}
hunitTests :: [Test]
hunitTests
= [
"released version 1" ~: "failed"
~: (Right $ release1) ~=? doVersionParse "1",
"released version 3" ~: "failed"
~: (Right $ release3) ~=? doVersionParse "1.2.3",
"range comparison LaterVersion 1" ~: "failed"
~: True
~=? release3 `withinRange` (LaterVersion release2),
"range comparison LaterVersion 2" ~: "failed"
~: False
~=? release2 `withinRange` (LaterVersion release3),
"range comparison EarlierVersion 1" ~: "failed"
~: True
~=? release3 `withinRange` (LaterVersion release2),
"range comparison EarlierVersion 2" ~: "failed"
~: False
~=? release2 `withinRange` (LaterVersion release3),
"range comparison orLaterVersion 1" ~: "failed"
~: True
~=? release3 `withinRange` (orLaterVersion release3),
"range comparison orLaterVersion 2" ~: "failed"
~: True
~=? release3 `withinRange` (orLaterVersion release2),
"range comparison orLaterVersion 3" ~: "failed"
~: False
~=? release2 `withinRange` (orLaterVersion release3),
"range comparison orEarlierVersion 1" ~: "failed"
~: True
~=? release2 `withinRange` (orEarlierVersion release2),
"range comparison orEarlierVersion 2" ~: "failed"
~: True
~=? release2 `withinRange` (orEarlierVersion release3),
"range comparison orEarlierVersion 3" ~: "failed"
~: False
~=? release3 `withinRange` (orEarlierVersion release2)
]
#endif
|
alekar/hugs
|
packages/Cabal/Distribution/Version.hs
|
bsd-3-clause
| 13,158 | 22 | 14 | 2,709 | 2,100 | 1,157 | 943 | 86 | 1 |
{-# LANGUAGE RecursiveDo, ScopedTypeVariables #-}
module Reflex.Dom.Widget.Lazy where
import Reflex
import Reflex.Dom.Class
import Reflex.Dom.Widget.Basic
import Control.Monad.IO.Class
import Data.Fixed
import Data.Monoid
import qualified Data.Map as Map
import Data.Map (Map)
import GHCJS.DOM.Element
-- |A list view for long lists. Creates a scrollable element and only renders child row elements near the current scroll position.
virtualListWithSelection :: forall t m k v. (MonadWidget t m, Ord k)
=> Int -- ^ The height of the visible region in pixels
-> Int -- ^ The height of each row in pixels
-> Dynamic t Int -- ^ The total number of items
-> Int -- ^ The index of the row to scroll to on initialization
-> Event t Int -- ^ An 'Event' containing a row index. Used to scroll to the given index.
-> String -- ^ The element tag for the list
-> Dynamic t (Map String String) -- ^ The attributes of the list
-> String -- ^ The element tag for a row
-> Dynamic t (Map String String) -- ^ The attributes of each row
-> (k -> Dynamic t v -> m ()) -- ^ The row child element builder
-> Dynamic t (Map k v) -- ^ The 'Map' of items
-> m (Dynamic t (Int, Int), Event t k) -- ^ A tuple containing: a 'Dynamic' of the index (based on the current scroll position) and number of items currently being rendered, and an 'Event' of the selected key
virtualListWithSelection heightPx rowPx maxIndex i0 setI listTag listAttrs rowTag rowAttrs itemBuilder items = do
totalHeightStyle <- mapDyn (toHeightStyle . (*) rowPx) maxIndex
rec (container, itemList) <- elAttr "div" outerStyle $ elAttr' "div" containerStyle $ do
currentTop <- mapDyn (listWrapperStyle . fst) window
(_, lis) <- elDynAttr "div" totalHeightStyle $ tagWrapper listTag listAttrs currentTop $ listWithKey itemsInWindow $ \k v -> do
(li,_) <- tagWrapper rowTag rowAttrs (constDyn $ toHeightStyle rowPx) $ itemBuilder k v
return $ fmap (const k) (domEvent Click li)
return lis
scrollPosition <- holdDyn 0 $ domEvent Scroll container
window <- mapDyn (findWindow heightPx rowPx) scrollPosition
itemsInWindow <- combineDyn (\(_,(idx,num)) is -> Map.fromList $ take num $ Prelude.drop idx $ Map.toList is) window items
postBuild <- getPostBuild
performEvent_ $ fmap (\i -> liftIO $ setScrollTop (_el_element container) (i * rowPx)) $ leftmost [setI, fmap (const i0) postBuild]
indexAndLength <- mapDyn snd window
sel <- mapDyn (leftmost . Map.elems) itemList
return (indexAndLength, switch $ current sel)
where
toStyleAttr m = "style" =: (Map.foldWithKey (\k v s -> k <> ":" <> v <> ";" <> s) "" m)
outerStyle = toStyleAttr $ "position" =: "relative" <>
"height" =: (show heightPx <> "px")
containerStyle = toStyleAttr $ "overflow" =: "auto" <>
"position" =: "absolute" <>
"left" =: "0" <>
"right" =: "0" <>
"height" =: (show heightPx <> "px")
listWrapperStyle t = toStyleAttr $ "position" =: "relative" <>
"top" =: (show t <> "px")
toHeightStyle h = toStyleAttr ("height" =: (show h <> "px"))
tagWrapper elTag attrs attrsOverride c = do
attrs' <- combineDyn Map.union attrsOverride attrs
elDynAttr' elTag attrs' c
findWindow windowSize sizeIncrement startingPosition =
let (startingIndex, topOffsetPx) = startingPosition `divMod'` sizeIncrement
topPx = startingPosition - topOffsetPx
numItems = windowSize `div` sizeIncrement + 1
preItems = min startingIndex numItems
in (topPx - preItems * sizeIncrement, (startingIndex - preItems, preItems + numItems * 2))
|
hamishmack/reflex-dom
|
src/Reflex/Dom/Widget/Lazy.hs
|
bsd-3-clause
| 3,814 | 0 | 23 | 952 | 1,040 | 535 | 505 | 60 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Properties where
import Test.Framework.Providers.QuickCheck2
import Test.Framework.TH
import Test.QuickCheck
prop_list_reverse_reverse :: [Int] -> Bool
prop_list_reverse_reverse list = list == reverse (reverse list)
prop_list_length :: [Int] -> Int -> Bool
prop_list_length list i = length (i : list) == 1 + length list
tests = $testGroupGenerator
|
TomRegan/HaskellStarter
|
test/Properties.hs
|
mit
| 392 | 0 | 9 | 53 | 109 | 60 | 49 | 10 | 1 |
data List a = Nil | Cons a (List a)
|
hmemcpy/milewski-ctfp-pdf
|
src/content/1.7/code/haskell/snippet15.hs
|
gpl-3.0
| 35 | 0 | 8 | 9 | 22 | 12 | 10 | 1 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.AutoScaling.DisableMetricsCollection
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Disables monitoring of the specified metrics for the specified Auto Scaling
-- group.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DisableMetricsCollection.html>
module Network.AWS.AutoScaling.DisableMetricsCollection
(
-- * Request
DisableMetricsCollection
-- ** Request constructor
, disableMetricsCollection
-- ** Request lenses
, dmcAutoScalingGroupName
, dmcMetrics
-- * Response
, DisableMetricsCollectionResponse
-- ** Response constructor
, disableMetricsCollectionResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.AutoScaling.Types
import qualified GHC.Exts
data DisableMetricsCollection = DisableMetricsCollection
{ _dmcAutoScalingGroupName :: Text
, _dmcMetrics :: List "member" Text
} deriving (Eq, Ord, Read, Show)
-- | 'DisableMetricsCollection' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dmcAutoScalingGroupName' @::@ 'Text'
--
-- * 'dmcMetrics' @::@ ['Text']
--
disableMetricsCollection :: Text -- ^ 'dmcAutoScalingGroupName'
-> DisableMetricsCollection
disableMetricsCollection p1 = DisableMetricsCollection
{ _dmcAutoScalingGroupName = p1
, _dmcMetrics = mempty
}
-- | The name or Amazon Resource Name (ARN) of the group.
dmcAutoScalingGroupName :: Lens' DisableMetricsCollection Text
dmcAutoScalingGroupName =
lens _dmcAutoScalingGroupName (\s a -> s { _dmcAutoScalingGroupName = a })
-- | One or more of the following metrics:
--
-- GroupMinSize
--
-- GroupMaxSize
--
-- GroupDesiredCapacity
--
-- GroupInServiceInstances
--
-- GroupPendingInstances
--
-- GroupStandbyInstances
--
-- GroupTerminatingInstances
--
-- GroupTotalInstances
--
-- If you omit this parameter, all metrics are disabled.
dmcMetrics :: Lens' DisableMetricsCollection [Text]
dmcMetrics = lens _dmcMetrics (\s a -> s { _dmcMetrics = a }) . _List
data DisableMetricsCollectionResponse = DisableMetricsCollectionResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DisableMetricsCollectionResponse' constructor.
disableMetricsCollectionResponse :: DisableMetricsCollectionResponse
disableMetricsCollectionResponse = DisableMetricsCollectionResponse
instance ToPath DisableMetricsCollection where
toPath = const "/"
instance ToQuery DisableMetricsCollection where
toQuery DisableMetricsCollection{..} = mconcat
[ "AutoScalingGroupName" =? _dmcAutoScalingGroupName
, "Metrics" =? _dmcMetrics
]
instance ToHeaders DisableMetricsCollection
instance AWSRequest DisableMetricsCollection where
type Sv DisableMetricsCollection = AutoScaling
type Rs DisableMetricsCollection = DisableMetricsCollectionResponse
request = post "DisableMetricsCollection"
response = nullResponse DisableMetricsCollectionResponse
|
romanb/amazonka
|
amazonka-autoscaling/gen/Network/AWS/AutoScaling/DisableMetricsCollection.hs
|
mpl-2.0
| 3,971 | 0 | 10 | 790 | 417 | 261 | 156 | 52 | 1 |
{-# LANGUAGE CPP #-}
-- |
-- Module:
-- Reflex.Spider
-- Description:
-- This module exports all of the user-facing functionality of the 'Spider' 'Reflex' engine
module Reflex.Spider
( Spider
, SpiderTimeline
, Global
, SpiderHost
, runSpiderHost
, runSpiderHostForTimeline
, newSpiderTimeline
, withSpiderTimeline
-- * Deprecated
, SpiderEnv
) where
import Reflex.Spider.Internal
|
reflex-frp/reflex
|
src/Reflex/Spider.hs
|
bsd-3-clause
| 465 | 0 | 4 | 137 | 48 | 34 | 14 | 12 | 0 |
module List (
elemIndex, elemIndices,
find, findIndex, findIndices,
nub, nubBy, delete, deleteBy, (\\), deleteFirstsBy,
union, unionBy, intersect, intersectBy,
intersperse, transpose, partition, group, groupBy,
inits, tails, isPrefixOf, isSuffixOf,
mapAccumL, mapAccumR,
sort, sortBy, insert, insertBy, maximumBy, minimumBy,
genericLength, genericTake, genericDrop,
genericSplitAt, genericIndex, genericReplicate,
zip4, zip5, zip6, zip7,
zipWith4, zipWith5, zipWith6, zipWith7,
unzip4, unzip5, unzip6, unzip7, unfoldr,
-- ...and what the Prelude exports
-- []((:), []), -- This is built-in syntax
map, (++), concat, filter,
head, last, tail, init, null, length, (!!),
foldl, foldl1, scanl, scanl1, foldr, foldr1, scanr, scanr1,
iterate, repeat, replicate, cycle,
take, drop, splitAt, takeWhile, dropWhile, span, break,
lines, words, unlines, unwords, reverse, and, or,
any, all, elem, notElem, lookup,
sum, product, maximum, minimum, concatMap,
zip, zip3, zipWith, zipWith3, unzip, unzip3
) where
import Data.List hiding (foldl')
|
alekar/hugs
|
packages/haskell98/List.hs
|
bsd-3-clause
| 1,131 | 0 | 5 | 228 | 337 | 227 | 110 | 24 | 0 |
-- Copyright 2016 TensorFlow authors.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-- | Encoder and decoder for the TensorFlow \"TFRecords\" format.
{-# LANGUAGE Rank2Types #-}
module TensorFlow.Records
(
-- * Records
putTFRecord
, getTFRecord
, getTFRecords
-- * Implementation
-- | These may be useful for encoding or decoding to types other than
-- 'ByteString' that have their own Cereal codecs.
, getTFRecordLength
, getTFRecordData
, putTFRecordLength
, putTFRecordData
) where
import Control.Exception (evaluate)
import Control.Monad (when)
import Data.ByteString.Unsafe (unsafePackCStringLen)
import qualified Data.ByteString.Builder as B (Builder)
import Data.ByteString.Builder.Extra (runBuilder, Next(..))
import qualified Data.ByteString.Lazy as BL
import Data.Serialize.Get
( Get
, getBytes
, getWord32le
, getWord64le
, getLazyByteString
, isEmpty
, lookAhead
)
import Data.Serialize
( Put
, execPut
, putLazyByteString
, putWord32le
, putWord64le
)
import Data.Word (Word8, Word64)
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Ptr (Ptr, castPtr)
import System.IO.Unsafe (unsafePerformIO)
import TensorFlow.CRC32C (crc32cLBSMasked, crc32cUpdate, crc32cMask)
-- | Parse one TFRecord.
getTFRecord :: Get BL.ByteString
getTFRecord = getTFRecordLength >>= getTFRecordData
-- | Parse many TFRecords as a list. Note you probably want streaming instead
-- as provided by the tensorflow-records-conduit package.
getTFRecords :: Get [BL.ByteString]
getTFRecords = do
e <- isEmpty
if e then return [] else (:) <$> getTFRecord <*> getTFRecords
getCheckMaskedCRC32C :: BL.ByteString -> Get ()
getCheckMaskedCRC32C bs = do
wireCRC <- getWord32le
let maskedCRC = crc32cLBSMasked bs
when (maskedCRC /= wireCRC) $ fail $
"getCheckMaskedCRC32C: CRC mismatch, computed: " ++ show maskedCRC ++
", expected: " ++ show wireCRC
-- | Get a length and verify its checksum.
getTFRecordLength :: Get Word64
getTFRecordLength = do
buf <- lookAhead (getBytes 8)
getWord64le <* getCheckMaskedCRC32C (BL.fromStrict buf)
-- | Get a record payload and verify its checksum.
getTFRecordData :: Word64 -> Get BL.ByteString
getTFRecordData len = if len > 0x7fffffffffffffff
then fail "getTFRecordData: Record size overflows Int64"
else do
bs <- getLazyByteString (fromIntegral len)
getCheckMaskedCRC32C bs
return bs
putMaskedCRC32C :: BL.ByteString -> Put
putMaskedCRC32C = putWord32le . crc32cLBSMasked
-- Runs a Builder that's known to write a fixed number of bytes on an 'alloca'
-- buffer, and runs the given IO action on the result. Raises exceptions if
-- the Builder yields ByteString chunks or attempts to write more bytes than
-- expected.
unsafeWithFixedWidthBuilder :: Int -> B.Builder -> (Ptr Word8 -> IO r) -> IO r
unsafeWithFixedWidthBuilder n b act = allocaBytes n $ \ptr -> do
(_, signal) <- runBuilder b ptr n
case signal of
Done -> act ptr
More _ _ -> error "unsafeWithFixedWidthBuilder: Builder returned More."
Chunk _ _ -> error "unsafeWithFixedWidthBuilder: Builder returned Chunk."
-- | Put a record length and its checksum.
putTFRecordLength :: Word64 -> Put
putTFRecordLength x =
let put = putWord64le x
len = 8
crc = crc32cMask $ unsafePerformIO $
-- Serialized Word64 is always 8 bytes, so we can go fast by using
-- alloca.
unsafeWithFixedWidthBuilder len (execPut put) $ \ptr -> do
str <- unsafePackCStringLen (castPtr ptr, len)
-- Force the result to ensure it's evaluated before freeing ptr.
evaluate $ crc32cUpdate 0 str
in put *> putWord32le crc
-- | Put a record payload and its checksum.
putTFRecordData :: BL.ByteString -> Put
putTFRecordData bs = putLazyByteString bs *> putMaskedCRC32C bs
-- | Put one TFRecord with the given contents.
putTFRecord :: BL.ByteString -> Put
putTFRecord bs =
putTFRecordLength (fromIntegral $ BL.length bs) *> putTFRecordData bs
|
tensorflow/haskell
|
tensorflow-records/src/TensorFlow/Records.hs
|
apache-2.0
| 4,523 | 0 | 16 | 859 | 835 | 457 | 378 | 82 | 3 |
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeFamilies #-}
module T16110_Fail2 where
-- Ensure that kind variables don't leak into error messages if they're not
-- pertitent to the issue at hand
class C (a :: j) where
type T (a :: j) (b :: k) (c :: k)
type T a b b = Int
|
sdiehl/ghc
|
testsuite/tests/indexed-types/should_fail/T16110_Fail2.hs
|
bsd-3-clause
| 274 | 0 | 7 | 60 | 60 | 39 | 21 | 6 | 0 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Main (templates)
-- Copyright : (C) 2012-14 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- This test suite validates that we are able to generate usable lenses with
-- template haskell.
--
-- The commented code summarizes what will be auto-generated below
-----------------------------------------------------------------------------
module Main where
import Control.Lens
-- import Test.QuickCheck (quickCheck)
data Bar a b c = Bar { _baz :: (a, b) }
makeLenses ''Bar
checkBaz :: Iso (Bar a b c) (Bar a' b' c') (a, b) (a', b')
checkBaz = baz
data Quux a b = Quux { _quaffle :: Int, _quartz :: Double }
makeLenses ''Quux
checkQuaffle :: Lens (Quux a b) (Quux a' b') Int Int
checkQuaffle = quaffle
checkQuartz :: Lens (Quux a b) (Quux a' b') Double Double
checkQuartz = quartz
data Quark a = Qualified { _gaffer :: a }
| Unqualified { _gaffer :: a, _tape :: a }
makeLenses ''Quark
checkGaffer :: Lens' (Quark a) a
checkGaffer = gaffer
checkTape :: Traversal' (Quark a) a
checkTape = tape
data Hadron a b = Science { _a1 :: a, _a2 :: a, _c :: b }
makeLenses ''Hadron
checkA1 :: Lens' (Hadron a b) a
checkA1 = a1
checkA2 :: Lens' (Hadron a b) a
checkA2 = a2
checkC :: Lens (Hadron a b) (Hadron a b') b b'
checkC = c
data Perambulation a b
= Mountains { _terrain :: a, _altitude :: b }
| Beaches { _terrain :: a, _dunes :: a }
makeLenses ''Perambulation
checkTerrain :: Lens' (Perambulation a b) a
checkTerrain = terrain
checkAltitude :: Traversal (Perambulation a b) (Perambulation a b') b b'
checkAltitude = altitude
checkDunes :: Traversal' (Perambulation a b) a
checkDunes = dunes
makeLensesFor [("_terrain", "allTerrain"), ("_dunes", "allTerrain")] ''Perambulation
checkAllTerrain :: Traversal (Perambulation a b) (Perambulation a' b) a a'
checkAllTerrain = allTerrain
data LensCrafted a = Still { _still :: a }
| Works { _still :: a }
makeLenses ''LensCrafted
checkStill :: Lens (LensCrafted a) (LensCrafted b) a b
checkStill = still
data Task a = Task
{ taskOutput :: a -> IO ()
, taskState :: a
, taskStop :: IO ()
}
makeLensesFor [("taskOutput", "outputLens"), ("taskState", "stateLens"), ("taskStop", "stopLens")] ''Task
checkOutputLens :: Lens' (Task a) (a -> IO ())
checkOutputLens = outputLens
checkStateLens :: Lens' (Task a) a
checkStateLens = stateLens
checkStopLens :: Lens' (Task a) (IO ())
checkStopLens = stopLens
data Mono a = Mono { _monoFoo :: a, _monoBar :: Int }
makeClassy ''Mono
-- class HasMono t where
-- mono :: Simple Lens t Mono
-- instance HasMono Mono where
-- mono = id
checkMono :: HasMono t a => Lens' t (Mono a)
checkMono = mono
checkMono' :: Lens' (Mono a) (Mono a)
checkMono' = mono
checkMonoFoo :: HasMono t a => Lens' t a
checkMonoFoo = monoFoo
checkMonoBar :: HasMono t a => Lens' t Int
checkMonoBar = monoBar
data Nucleosis = Nucleosis { _nuclear :: Mono Int }
makeClassy ''Nucleosis
-- class HasNucleosis t where
-- nucleosis :: Simple Lens t Nucleosis
-- instance HasNucleosis Nucleosis
checkNucleosis :: HasNucleosis t => Lens' t Nucleosis
checkNucleosis = nucleosis
checkNucleosis' :: Lens' Nucleosis Nucleosis
checkNucleosis' = nucleosis
checkNuclear :: HasNucleosis t => Lens' t (Mono Int)
checkNuclear = nuclear
instance HasMono Nucleosis Int where
mono = nuclear
-- Dodek's example
data Foo = Foo { _fooX, _fooY :: Int }
makeClassy ''Foo
checkFoo :: HasFoo t => Lens' t Foo
checkFoo = foo
checkFoo' :: Lens' Foo Foo
checkFoo' = foo
checkFooX :: HasFoo t => Lens' t Int
checkFooX = fooX
checkFooY :: HasFoo t => Lens' t Int
checkFooY = fooY
data Dude a = Dude
{ dudeLevel :: Int
, dudeAlias :: String
, dudeLife :: ()
, dudeThing :: a
}
makeFields ''Dude
checkLevel :: HasLevel t a => Lens' t a
checkLevel = level
checkLevel' :: Lens' (Dude a) Int
checkLevel' = level
checkAlias :: HasAlias t a => Lens' t a
checkAlias = alias
checkAlias' :: Lens' (Dude a) String
checkAlias' = alias
checkLife :: HasLife t a => Lens' t a
checkLife = life
checkLife' :: Lens' (Dude a) ()
checkLife' = life
checkThing :: HasThing t a => Lens' t a
checkThing = thing
checkThing' :: Lens' (Dude a) a
checkThing' = thing
data Lebowski a = Lebowski
{ _lebowskiAlias :: String
, _lebowskiLife :: Int
, _lebowskiMansion :: String
, _lebowskiThing :: Maybe a
}
makeFields ''Lebowski
checkAlias2 :: Lens' (Lebowski a) String
checkAlias2 = alias
checkLife2 :: Lens' (Lebowski a) Int
checkLife2 = life
checkMansion :: HasMansion t a => Lens' t a
checkMansion = mansion
checkMansion' :: Lens' (Lebowski a) String
checkMansion' = mansion
checkThing2 :: Lens' (Lebowski a) (Maybe a)
checkThing2 = thing
data AbideConfiguration a = AbideConfiguration
{ _acLocation :: String
, _acDuration :: Int
, _acThing :: a
}
makeLensesWith abbreviatedFields ''AbideConfiguration
checkLocation :: HasLocation t a => Lens' t a
checkLocation = location
checkLocation' :: Lens' (AbideConfiguration a) String
checkLocation' = location
checkDuration :: HasDuration t a => Lens' t a
checkDuration = duration
checkDuration' :: Lens' (AbideConfiguration a) Int
checkDuration' = duration
checkThing3 :: Lens' (AbideConfiguration a) a
checkThing3 = thing
dudeDrink :: String
dudeDrink = (Dude 9 "El Duderino" () "white russian") ^. thing
lebowskiCarpet :: Maybe String
lebowskiCarpet = (Lebowski "Mr. Lebowski" 0 "" (Just "carpet")) ^. thing
abideAnnoyance :: String
abideAnnoyance = (AbideConfiguration "the tree" 10 "the wind") ^. thing
declareLenses [d|
data Quark1 a = Qualified1 { gaffer1 :: a }
| Unqualified1 { gaffer1 :: a, tape1 :: a }
|]
-- data Quark1 a = Qualified1 a | Unqualified1 a a
checkGaffer1 :: Lens' (Quark1 a) a
checkGaffer1 = gaffer1
checkTape1 :: Traversal' (Quark1 a) a
checkTape1 = tape1
declarePrisms [d|
data Exp = Lit Int | Var String | Lambda { bound::String, body::Exp }
|]
-- data Exp = Lit Int | Var String | Lambda { bound::String, body::Exp }
checkLit :: Int -> Exp
checkLit = Lit
checkVar :: String -> Exp
checkVar = Var
checkLambda :: String -> Exp -> Exp
checkLambda = Lambda
check_Lit :: Prism' Exp Int
check_Lit = _Lit
check_Var :: Prism' Exp String
check_Var = _Var
check_Lambda :: Prism' Exp (String, Exp)
check_Lambda = _Lambda
declarePrisms [d|
data Banana = Banana Int String
|]
-- data Banana = Banana Int String
check_Banana :: Iso' Banana (Int, String)
check_Banana = _Banana
cavendish :: Banana
cavendish = _Banana # (4, "Cavendish")
data family Family a b c
#if __GLASGOW_HASKELL >= 706
declareLenses [d|
data instance Family Int (a, b) a = FamilyInt { fm0 :: (b, a), fm1 :: Int }
|]
-- data instance Family Int (a, b) a = FamilyInt a b
checkFm0 :: Lens (Family Int (a, b) a) (Family Int (a', b') a') (b, a) (b', a')
checkFm0 = fm0
checkFm1 :: Lens' (Family Int (a, b) a) Int
checkFm1 = fm1
#endif
class Class a where
data Associated a
method :: a -> Int
declareLenses [d|
instance Class Int where
data Associated Int = AssociatedInt { mochi :: Double }
method = id
|]
-- instance Class Int where
-- data Associated Int = AssociatedInt Double
-- method = id
checkMochi :: Iso' (Associated Int) Double
checkMochi = mochi
#if __GLASGOW_HASKELL__ >= 706
declareFields [d|
data DeclaredFields f a
= DeclaredField1 { declaredFieldsA0 :: f a , declaredFieldsB0 :: Int }
| DeclaredField2 { declaredFieldsC0 :: String , declaredFieldsB0 :: Int }
deriving (Show)
|]
checkA0 :: HasA0 t a => Traversal' t a
checkA0 = a0
checkB0 :: HasB0 t a => Lens' t a
checkB0 = b0
checkC0 :: HasC0 t a => Traversal' t a
checkC0 = c0
checkA0' :: Traversal' (DeclaredFields f a) (f a)
checkA0' = a0
checkB0' :: Lens' (DeclaredFields f a) Int
checkB0' = b0
checkC0' :: Traversal' (DeclaredFields f a) String
checkC0' = c0
#endif
data Rank2Tests
= C1 { _r2length :: forall a. [a] -> Int
, _r2nub :: forall a. Eq a => [a] -> [a]
}
| C2 { _r2length :: forall a. [a] -> Int }
makeLenses ''Rank2Tests
checkR2length :: Getter Rank2Tests ([a] -> Int)
checkR2length = r2length
checkR2nub :: Eq a => Fold Rank2Tests ([a] -> [a])
checkR2nub = r2nub
data PureNoFields = PureNoFieldsA | PureNoFieldsB { _pureNoFields :: Int }
makeLenses ''PureNoFields
main :: IO ()
main = putStrLn "test/templates.hs: ok"
|
danidiaz/lens
|
tests/templates.hs
|
bsd-3-clause
| 8,885 | 0 | 12 | 1,838 | 2,545 | 1,395 | 1,150 | 203 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{- # OPTIONS_GHC -fno-defer-type-errors #-}
module T13446 where
import Data.Coerce (Coercible)
import GHC.Exts (Constraint)
import GHC.TypeLits (Symbol)
data Dict :: Constraint -> * where
Dict :: a => Dict a
infixr 9 :-
newtype a :- b = Sub (a => Dict b)
instance a => Show (a :- b) where
showsPrec d (Sub Dict) = showParen (d > 10) $ showString "Sub Dict"
class Lifting p f where
lifting :: p a :- p (f a)
data Blah a = Blah
newtype J (a :: JType) = J (Blah (J a))
newtype JComparable a = JComparable (J (T (JTy a)))
instance Lifting JReference JComparable where
lifting = Sub 'a'
class (Coercible a (J (JTy a))) => JReference a where
type JTy a :: JType
type T a
= 'Generic ('Iface "java.lang.Comparable") '[a]
data JType = Class Symbol
| Generic JType [JType]
| Iface Symbol
type JObject = J (Class "java.lang.Object")
instance JReference JObject where
type JTy JObject = 'Class "java.lang.Object"
|
ezyang/ghc
|
testsuite/tests/typecheck/should_fail/T13446.hs
|
bsd-3-clause
| 1,226 | 0 | 11 | 242 | 386 | 214 | 172 | 36 | 0 |
module Phone where
import Data.Char (isAlphaNum, toLower)
import Data.List (elemIndex, find, group, sort)
import Data.Maybe (fromMaybe)
convo :: [String]
convo = [ "Wanna play 20 questions"
, "Ya"
, "U 1st haha"
, "Lol ok. Have u ever tasted alcohol"
, "Lol ya"
, "Wow ur cool haha. Ur turn"
, "Ok. Do u think I am pretty Lol"
, "Lol ya"
, "Just making sure rofl ur turn"
]
-- validButtons = "1234567890*#"
type Digit = Char
-- Valid presses: 1 and up
type Presses = Int
data DaPhone = DaPhone [(Digit, String)]
deriving (Eq, Show)
phone :: DaPhone
phone = DaPhone [ ('1', "1")
, ('2', "abc2")
, ('3', "def3")
, ('4', "ghi4")
, ('5', "jkl5")
, ('6', "mno6")
, ('7', "pqrs7")
, ('8', "tuv8")
, ('9', "wxyz9")
, ('0', " 0")
, ('#', ".,")
]
reverseTaps :: DaPhone -> Char -> [(Digit, Presses)]
reverseTaps (DaPhone ph) ch
| ch == toLower ch = tap ch
| otherwise = ('*', 1) : tap (toLower ch)
where tap c =
case button of
Just (num, str) -> [(num, 1 + fromMaybe (-1) (elemIndex c str))]
Nothing -> []
where button = find (\(_, x) -> c `elem` x) ph
cellPhonesDead :: DaPhone -> String -> [(Digit, Presses)]
cellPhonesDead = concatMap . reverseTaps
cellPhonesDeadConvo :: DaPhone -> [String] -> [(Digit, Presses)]
cellPhonesDeadConvo ph str = cellPhonesDead ph $ concat str
-- 3
fingerTaps :: [(Digit, Presses)] -> Presses
fingerTaps = sum . map snd
-- 4
mostPopularLetter :: String -> Char
mostPopularLetter = mostPopularElem . filter isAlphaNum
mostPopularElem :: (Ord a, Eq a) => [a] -> a
mostPopularElem = snd . maximum . map (\x -> (length x, head x)) . group
letterCost :: DaPhone -> Char -> Presses
letterCost ph ch = fingerTaps $ reverseTaps ph ch
-- 5
coolestLtr :: [String] -> Char
coolestLtr = mostPopularLetter . concat
coolestWord :: [String] -> String
coolestWord = mostPopularElem . words . unwords
|
ashnikel/haskellbook
|
ch11/ch11.18_phone_ex.hs
|
mit
| 2,190 | 0 | 15 | 704 | 698 | 402 | 296 | 55 | 2 |
module Euler001 (euler1) where
euler1 :: Int
euler1 = sum [x | x <- [1..999] :: [Int], x `mod` 5 == 0 || x `mod` 3 == 0]
|
TrustNoOne/Euler
|
haskell/src/Euler001.hs
|
mit
| 122 | 0 | 12 | 29 | 72 | 42 | 30 | 3 | 1 |
-- | Re-export all symbols and instances of the process-extras
-- package. Adds the Chunk type with a ProcessOutput instance, and a
-- collectOutput function to turn a list of chunks into any instance
-- of ProcessOutput, such as (ExitCode, String, String). This means
-- you can have readCreateProcess output a list of Chunk, operate on
-- it to do progress reporting, and finally convert it to the type
-- that readProcessWithExitCode woud have returned.
{-# LANGUAGE CPP, FlexibleInstances, FunctionalDependencies, MultiParamTypeClasses, UndecidableInstances #-}
{-# OPTIONS_GHC -Wall -fno-warn-orphans #-}
module System.Process.ListLike
(
-- * Classes for process IO monad, output type, and creation type
ListLikeProcessIO(forceOutput)
, ProcessText
, ProcessResult(pidf, outf, errf, codef, intf)
, ProcessMaker(process, showProcessMakerForUser)
-- * The generalized process runners
, readCreateProcess
, readCreateProcessStrict
, readCreateProcessLazy
, readCreateProcessWithExitCode
, readProcessWithExitCode
-- * Utility functions based on showCommandForUser
, showCreateProcessForUser
, showCmdSpecForUser
-- * The Chunk type
, Chunk(..)
, collectOutput
, foldOutput
, writeOutput
, writeChunk
-- * Re-exports from process
, CmdSpec(..)
, CreateProcess(..)
, proc
, shell
, showCommandForUser
) where
import Control.DeepSeq (force)
import Control.Exception as C (evaluate, SomeException, throw)
import Data.ListLike.IO (hGetContents, hPutStr, ListLikeIO)
#if __GLASGOW_HASKELL__ <= 709
import Control.Applicative ((<$>), (<*>))
import Data.Monoid (mempty, mconcat)
#endif
import Data.Text (unpack)
import Data.Text.Lazy (Text, toChunks)
import System.Exit (ExitCode)
import System.IO (stdout, stderr)
import System.Process (CmdSpec(..), CreateProcess(..), proc, ProcessHandle, shell, showCommandForUser)
import System.Process.ByteString ()
import System.Process.ByteString.Lazy ()
import System.Process.Common
(ProcessMaker(process, showProcessMakerForUser), ListLikeProcessIO(forceOutput, readChunks),
ProcessText, ProcessResult(pidf, outf, errf, codef, intf), readCreateProcessStrict, readCreateProcessLazy,
readCreateProcessWithExitCode, readProcessWithExitCode, showCmdSpecForUser, showCreateProcessForUser)
import System.Process.Text ()
import System.Process.Text.Builder ()
import System.Process.Text.Lazy ()
instance ProcessText String Char
readCreateProcess :: (ProcessMaker maker, ProcessResult text result, ListLikeProcessIO text char) => maker -> text -> IO result
readCreateProcess = readCreateProcessLazy
-- | Like 'System.Process.readProcessWithExitCode' that takes a 'CreateProcess'.
instance ListLikeProcessIO String Char where
-- | This is required because strings are magically lazy. Without it
-- processes get exit status 13 - file read failures.
forceOutput = evaluate . force
-- | Read the handle as lazy text, convert to chunks of strict text,
-- and then unpack into strings.
readChunks h = do
t <- hGetContents h :: IO Text
return $ map unpack $ toChunks t
-- | This type is a concrete representation of the methods of class
-- ProcessOutput. If you take your process output as this type you
-- could, for example, echo all the output and then use collectOutput
-- below to convert it to any other instance of ProcessOutput.
data Chunk a
= ProcessHandle ProcessHandle
-- ^ This will always come first, before any output or exit code.
| Stdout a
| Stderr a
| Result ExitCode
| Exception SomeException
-- ^ Note that the instances below do not use this constructor.
deriving Show
instance Show ProcessHandle where
show _ = "<process>"
instance ListLikeProcessIO a c => ProcessResult a [Chunk a] where
pidf p = [ProcessHandle p]
outf x = [Stdout x]
errf x = [Stderr x]
intf e = throw e
codef c = [Result c]
instance ListLikeProcessIO a c => ProcessResult a (ExitCode, [Chunk a]) where
pidf p = (mempty, [ProcessHandle p])
codef c = (c, mempty)
outf x = (mempty, [Stdout x])
errf x = (mempty, [Stderr x])
intf e = throw e
foldOutput :: (ProcessHandle -> r) -- ^ called when the process handle becomes known
-> (a -> r) -- ^ stdout handler
-> (a -> r) -- ^ stderr handler
-> (SomeException -> r) -- ^ exception handler
-> (ExitCode -> r) -- ^ exit code handler
-> Chunk a
-> r
foldOutput p _ _ _ _ (ProcessHandle x) = p x
foldOutput _ o _ _ _ (Stdout x) = o x
foldOutput _ _ e _ _ (Stderr x) = e x
foldOutput _ _ _ i _ (Exception x) = i x
foldOutput _ _ _ _ r (Result x) = r x
-- | Turn a @[Chunk a]@ into any other instance of 'ProcessOutput'. I
-- usually use this after processing the chunk list to turn it into
-- the (ExitCode, String, String) type returned by readProcessWithExitCode.
collectOutput :: ProcessResult a b => [Chunk a] -> b
collectOutput xs = mconcat $ map (foldOutput pidf outf errf intf codef) xs
-- | Send Stdout chunks to stdout and Stderr chunks to stderr.
-- Returns input list unmodified.
writeOutput :: ListLikeIO a c => [Chunk a] -> IO [Chunk a]
writeOutput [] = return []
writeOutput (x : xs) = (:) <$> writeChunk x <*> writeOutput xs
writeChunk :: ListLikeIO a c => Chunk a -> IO (Chunk a)
writeChunk x =
foldOutput (\_ -> return x)
(\s -> hPutStr stdout s >> return x)
(\s -> hPutStr stderr s >> return x)
(\_ -> return x)
(\_ -> return x) x
|
seereason/process-extras
|
src/System/Process/ListLike.hs
|
mit
| 5,598 | 0 | 11 | 1,186 | 1,240 | 712 | 528 | 104 | 1 |
{- contains the GUI data types
-
-}
module Language.Astview.Gui.Types where
import Data.Label
import Data.IORef
import Graphics.UI.Gtk hiding (Language,get,set)
import Graphics.UI.Gtk.SourceView (SourceBuffer)
import Language.Astview.Language(Language,SrcSpan,Path,position)
-- |a type class for default values, compareable to mempty in class 'Monoid'
class Default a where
defaultValue :: a
type AstAction a = IORef AstState -> IO a
-- |union of internal program state and gui
data AstState = AstState
{ state :: State -- ^ intern program state
, gui :: GUI -- ^ gtk data types
, options :: Options -- ^ global program options
}
-- |data type for global options, which can be directly changed in the gui
-- (...or at least should be. Menu for changing font and font size not yet
-- implemented)
data Options = Options
{ font :: String -- ^ font name of textbuffer
, fsize :: Int -- ^ font size of textbuffer
, flattenLists :: Bool -- ^should lists be flattened
}
instance Default Options where
defaultValue = Options "Monospace" 9 True
-- |data type for the internal program state
data State = State
{ currentFile :: String -- ^ current file
, textchanged :: Bool -- ^ true if buffer changed after last save
, lastSelectionInText :: SrcSpan -- ^ last active cursor position
, lastSelectionInTree :: Path -- ^ last clicked tree cell
, knownLanguages :: [Language] -- ^ known languages, which can be parsed
, activeLanguage :: Maybe Language -- ^the currently selected language or Nothing if language is selected by file extension
}
instance Default State where
defaultValue = State
{ currentFile = unsavedDoc
, textchanged = False
, lastSelectionInText = position 0 0
, lastSelectionInTree = []
, knownLanguages = []
, activeLanguage = Nothing
}
-- |unsaved document
unsavedDoc :: String
unsavedDoc = "Unsaved document"
-- |main gui data type, contains gtk components
data GUI = GUI
{ window :: Window -- ^ main window
, tv :: TreeView -- ^ treeview
, sb :: SourceBuffer -- ^ sourceview
}
-- * getter functions
mkLabels [ ''AstState
, ''Options
, ''State
, ''GUI
]
getSourceBuffer :: AstAction SourceBuffer
getSourceBuffer = fmap (sb . gui) . readIORef
getTreeView :: AstAction TreeView
getTreeView = fmap (tv . gui) . readIORef
getAstState :: AstAction AstState
getAstState = readIORef
getGui :: AstAction GUI
getGui = fmap gui . readIORef
getState :: AstAction State
getState = fmap state . readIORef
getKnownLanguages :: AstAction [Language]
getKnownLanguages = fmap (knownLanguages . state) . readIORef
getChanged :: AstAction Bool
getChanged = fmap (textchanged . state) . readIORef
getCursor :: AstAction SrcSpan
getCursor = fmap (lastSelectionInText . state) . readIORef
getPath :: AstAction TreePath
getPath = fmap (lastSelectionInTree. state) . readIORef
getCurrentFile :: AstAction String
getCurrentFile = fmap (currentFile . state) . readIORef
getActiveLanguage :: AstAction (Maybe Language)
getActiveLanguage = fmap (activeLanguage . state) . readIORef
getWindow :: AstAction Window
getWindow = fmap (window . gui) . readIORef
getFlattenLists :: AstAction Bool
getFlattenLists = fmap (flattenLists . options) . readIORef
getFontsize :: AstAction Int
getFontsize = fmap (fsize . options) . readIORef
-- * setter functions
lensSetIoRef :: (AstState :-> a) -> (a :-> b) -> b -> AstAction ()
lensSetIoRef outerLens innerLens value ref = modifyIORef ref m where
m :: AstState -> AstState
m = modify outerLens (set innerLens value)
-- |stores the given cursor selection
setCursor :: SrcSpan -> AstAction ()
setCursor = lensSetIoRef lState lLastSelectionInText
-- |stores the given tree selection
setTreePath :: Path -> AstAction ()
setTreePath = lensSetIoRef lState lLastSelectionInTree
-- |stores file path of current opened file
setCurrentFile :: FilePath -> AstAction ()
setCurrentFile = lensSetIoRef lState lCurrentFile
-- |stores whether the current file buffer has been changed
setChanged :: Bool -> AstAction ()
setChanged = lensSetIoRef lState lTextchanged
-- |stores whether the lists in trees should be flattened
setFlattenLists :: Bool -> AstAction ()
setFlattenLists = lensSetIoRef lOptions lFlattenLists
setActiveLanguage :: Maybe Language -> AstAction ()
setActiveLanguage = lensSetIoRef lState lActiveLanguage
|
jokusi/Astview
|
src/gui/Language/Astview/Gui/Types.hs
|
mit
| 4,410 | 0 | 9 | 831 | 968 | 543 | 425 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
import Conduit (Sink, await, liftIO, (=$), ($$), ($$+), ($$+-))
import Control.Concurrent.Async (race_)
import Data.Binary (decode)
import Data.Binary.Get (runGet, getWord16be, getWord32le)
import Data.ByteString (ByteString)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Char8 as C
import Data.Char (ord)
import Data.Conduit.Network ( runTCPServer, runTCPClient
, serverSettings, clientSettings
, appSource, appSink)
import Data.Monoid ((<>))
import Data.IP (fromHostAddress, fromHostAddress6)
import GHC.IO.Handle (hSetBuffering, BufferMode(NoBuffering))
import GHC.IO.Handle.FD (stdout)
import Shadowsocks.Encrypt (getEncDec)
import Shadowsocks.Util
initRemote :: (ByteString -> IO ByteString)
-> Sink ByteString IO (ByteString, Int)
initRemote decrypt = await >>=
maybe (error "Invalid request") (\encRequest -> do
request <- liftIO $ decrypt encRequest
let addrType = S.head request
request' = S.drop 1 request
(addr, addrPort) <- case addrType of
1 -> do -- IPv4
let (ip, rest) = S.splitAt 4 request'
addr = C.pack $ show $ fromHostAddress $ runGet getWord32le
$ L.fromStrict ip
return (addr, S.take 2 rest)
3 -> do -- domain name
let addrLen = ord $ C.head request'
(domain, rest) = S.splitAt (addrLen + 1) request'
return (S.tail domain, S.take 2 rest)
4 -> do -- IPv6
let (ip, rest) = S.splitAt 16 request'
addr = C.pack $ show $ fromHostAddress6 $ decode
$ L.fromStrict ip
return (addr, S.take 2 rest)
_ -> error $ C.unpack $ S.snoc "Unknown address type: " addrType
let port = fromIntegral $ runGet getWord16be $ L.fromStrict addrPort
return (addr, port))
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
config <- parseConfigOptions
let localSettings = serverSettings (server_port config) "*"
C.putStrLn $ "starting server at " <> C.pack (show $ server_port config)
runTCPServer localSettings $ \client -> do
(encrypt, decrypt) <- getEncDec (method config) (password config)
(clientSource, (host, port)) <-
appSource client $$+ initRemote decrypt
let remoteSettings = clientSettings port host
C.putStrLn $ "connecting " <> host <> ":" <> C.pack (show port)
runTCPClient remoteSettings $ \appServer -> race_
(clientSource $$+- cryptConduit decrypt =$ appSink appServer)
(appSource appServer $$ cryptConduit encrypt =$ appSink client)
|
fishky/shadowsocks-haskell
|
server.hs
|
mit
| 3,047 | 0 | 24 | 1,017 | 883 | 466 | 417 | 59 | 4 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-missing-fields #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-----------------------------------------------------------------
-- Autogenerated by Thrift Compiler (0.9.0) --
-- --
-- DO NOT EDIT UNLESS YOU ARE SURE YOU KNOW WHAT YOU ARE DOING --
-----------------------------------------------------------------
module Database.HBase.Internal.Thrift.Hbase_Types where
import Prelude ( Bool(..), Enum, Double, String, Maybe(..),
Eq, Show, Ord,
return, length, IO, fromIntegral, fromEnum, toEnum,
(.), (&&), (||), (==), (++), ($), (-) )
import Control.Exception
import Data.ByteString.Lazy
import Data.Hashable
import Data.Int
import Data.Text.Lazy ( Text )
import qualified Data.Text.Lazy as TL
import Data.Typeable ( Typeable )
import qualified Data.HashMap.Strict as Map
import qualified Data.HashSet as Set
import qualified Data.Vector as Vector
import Thrift
import Thrift.Types ()
type Text = ByteString
type Bytes = ByteString
type ScannerID = Int32
data TCell = TCell{f_TCell_value :: Maybe ByteString,f_TCell_timestamp :: Maybe Int64} deriving (Show,Eq,Typeable)
instance Hashable TCell where
hashWithSalt salt record = salt `hashWithSalt` f_TCell_value record `hashWithSalt` f_TCell_timestamp record
write_TCell oprot record = do
writeStructBegin oprot "TCell"
case f_TCell_value record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("value",T_STRING,1)
writeBinary oprot _v
writeFieldEnd oprot}
case f_TCell_timestamp record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("timestamp",T_I64,2)
writeI64 oprot _v
writeFieldEnd oprot}
writeFieldStop oprot
writeStructEnd oprot
read_TCell_fields iprot record = do
(_,_t3,_id4) <- readFieldBegin iprot
if _t3 == T_STOP then return record else
case _id4 of
1 -> if _t3 == T_STRING then do
s <- readBinary iprot
read_TCell_fields iprot record{f_TCell_value=Just s}
else do
skip iprot _t3
read_TCell_fields iprot record
2 -> if _t3 == T_I64 then do
s <- readI64 iprot
read_TCell_fields iprot record{f_TCell_timestamp=Just s}
else do
skip iprot _t3
read_TCell_fields iprot record
_ -> do
skip iprot _t3
readFieldEnd iprot
read_TCell_fields iprot record
read_TCell iprot = do
_ <- readStructBegin iprot
record <- read_TCell_fields iprot (TCell{f_TCell_value=Nothing,f_TCell_timestamp=Nothing})
readStructEnd iprot
return record
data ColumnDescriptor = ColumnDescriptor{f_ColumnDescriptor_name :: Maybe ByteString,f_ColumnDescriptor_maxVersions :: Maybe Int32,f_ColumnDescriptor_compression :: Maybe TL.Text,f_ColumnDescriptor_inMemory :: Maybe Bool,f_ColumnDescriptor_bloomFilterType :: Maybe TL.Text,f_ColumnDescriptor_bloomFilterVectorSize :: Maybe Int32,f_ColumnDescriptor_bloomFilterNbHashes :: Maybe Int32,f_ColumnDescriptor_blockCacheEnabled :: Maybe Bool,f_ColumnDescriptor_timeToLive :: Maybe Int32} deriving (Show,Eq,Typeable)
instance Hashable ColumnDescriptor where
hashWithSalt salt record = salt `hashWithSalt` f_ColumnDescriptor_name record `hashWithSalt` f_ColumnDescriptor_maxVersions record `hashWithSalt` f_ColumnDescriptor_compression record `hashWithSalt` f_ColumnDescriptor_inMemory record `hashWithSalt` f_ColumnDescriptor_bloomFilterType record `hashWithSalt` f_ColumnDescriptor_bloomFilterVectorSize record `hashWithSalt` f_ColumnDescriptor_bloomFilterNbHashes record `hashWithSalt` f_ColumnDescriptor_blockCacheEnabled record `hashWithSalt` f_ColumnDescriptor_timeToLive record
write_ColumnDescriptor oprot record = do
writeStructBegin oprot "ColumnDescriptor"
case f_ColumnDescriptor_name record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("name",T_STRING,1)
writeBinary oprot _v
writeFieldEnd oprot}
case f_ColumnDescriptor_maxVersions record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("maxVersions",T_I32,2)
writeI32 oprot _v
writeFieldEnd oprot}
case f_ColumnDescriptor_compression record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("compression",T_STRING,3)
writeString oprot _v
writeFieldEnd oprot}
case f_ColumnDescriptor_inMemory record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("inMemory",T_BOOL,4)
writeBool oprot _v
writeFieldEnd oprot}
case f_ColumnDescriptor_bloomFilterType record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("bloomFilterType",T_STRING,5)
writeString oprot _v
writeFieldEnd oprot}
case f_ColumnDescriptor_bloomFilterVectorSize record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("bloomFilterVectorSize",T_I32,6)
writeI32 oprot _v
writeFieldEnd oprot}
case f_ColumnDescriptor_bloomFilterNbHashes record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("bloomFilterNbHashes",T_I32,7)
writeI32 oprot _v
writeFieldEnd oprot}
case f_ColumnDescriptor_blockCacheEnabled record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("blockCacheEnabled",T_BOOL,8)
writeBool oprot _v
writeFieldEnd oprot}
case f_ColumnDescriptor_timeToLive record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("timeToLive",T_I32,9)
writeI32 oprot _v
writeFieldEnd oprot}
writeFieldStop oprot
writeStructEnd oprot
read_ColumnDescriptor_fields iprot record = do
(_,_t8,_id9) <- readFieldBegin iprot
if _t8 == T_STOP then return record else
case _id9 of
1 -> if _t8 == T_STRING then do
s <- readBinary iprot
read_ColumnDescriptor_fields iprot record{f_ColumnDescriptor_name=Just s}
else do
skip iprot _t8
read_ColumnDescriptor_fields iprot record
2 -> if _t8 == T_I32 then do
s <- readI32 iprot
read_ColumnDescriptor_fields iprot record{f_ColumnDescriptor_maxVersions=Just s}
else do
skip iprot _t8
read_ColumnDescriptor_fields iprot record
3 -> if _t8 == T_STRING then do
s <- readString iprot
read_ColumnDescriptor_fields iprot record{f_ColumnDescriptor_compression=Just s}
else do
skip iprot _t8
read_ColumnDescriptor_fields iprot record
4 -> if _t8 == T_BOOL then do
s <- readBool iprot
read_ColumnDescriptor_fields iprot record{f_ColumnDescriptor_inMemory=Just s}
else do
skip iprot _t8
read_ColumnDescriptor_fields iprot record
5 -> if _t8 == T_STRING then do
s <- readString iprot
read_ColumnDescriptor_fields iprot record{f_ColumnDescriptor_bloomFilterType=Just s}
else do
skip iprot _t8
read_ColumnDescriptor_fields iprot record
6 -> if _t8 == T_I32 then do
s <- readI32 iprot
read_ColumnDescriptor_fields iprot record{f_ColumnDescriptor_bloomFilterVectorSize=Just s}
else do
skip iprot _t8
read_ColumnDescriptor_fields iprot record
7 -> if _t8 == T_I32 then do
s <- readI32 iprot
read_ColumnDescriptor_fields iprot record{f_ColumnDescriptor_bloomFilterNbHashes=Just s}
else do
skip iprot _t8
read_ColumnDescriptor_fields iprot record
8 -> if _t8 == T_BOOL then do
s <- readBool iprot
read_ColumnDescriptor_fields iprot record{f_ColumnDescriptor_blockCacheEnabled=Just s}
else do
skip iprot _t8
read_ColumnDescriptor_fields iprot record
9 -> if _t8 == T_I32 then do
s <- readI32 iprot
read_ColumnDescriptor_fields iprot record{f_ColumnDescriptor_timeToLive=Just s}
else do
skip iprot _t8
read_ColumnDescriptor_fields iprot record
_ -> do
skip iprot _t8
readFieldEnd iprot
read_ColumnDescriptor_fields iprot record
read_ColumnDescriptor iprot = do
_ <- readStructBegin iprot
record <- read_ColumnDescriptor_fields iprot (ColumnDescriptor{f_ColumnDescriptor_name=Nothing,f_ColumnDescriptor_maxVersions=Nothing,f_ColumnDescriptor_compression=Nothing,f_ColumnDescriptor_inMemory=Nothing,f_ColumnDescriptor_bloomFilterType=Nothing,f_ColumnDescriptor_bloomFilterVectorSize=Nothing,f_ColumnDescriptor_bloomFilterNbHashes=Nothing,f_ColumnDescriptor_blockCacheEnabled=Nothing,f_ColumnDescriptor_timeToLive=Nothing})
readStructEnd iprot
return record
data TRegionInfo = TRegionInfo{f_TRegionInfo_startKey :: Maybe ByteString,f_TRegionInfo_endKey :: Maybe ByteString,f_TRegionInfo_id :: Maybe Int64,f_TRegionInfo_name :: Maybe ByteString,f_TRegionInfo_version :: Maybe Int8,f_TRegionInfo_serverName :: Maybe ByteString,f_TRegionInfo_port :: Maybe Int32} deriving (Show,Eq,Typeable)
instance Hashable TRegionInfo where
hashWithSalt salt record = salt `hashWithSalt` f_TRegionInfo_startKey record `hashWithSalt` f_TRegionInfo_endKey record `hashWithSalt` f_TRegionInfo_id record `hashWithSalt` f_TRegionInfo_name record `hashWithSalt` f_TRegionInfo_version record `hashWithSalt` f_TRegionInfo_serverName record `hashWithSalt` f_TRegionInfo_port record
write_TRegionInfo oprot record = do
writeStructBegin oprot "TRegionInfo"
case f_TRegionInfo_startKey record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("startKey",T_STRING,1)
writeBinary oprot _v
writeFieldEnd oprot}
case f_TRegionInfo_endKey record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("endKey",T_STRING,2)
writeBinary oprot _v
writeFieldEnd oprot}
case f_TRegionInfo_id record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("id",T_I64,3)
writeI64 oprot _v
writeFieldEnd oprot}
case f_TRegionInfo_name record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("name",T_STRING,4)
writeBinary oprot _v
writeFieldEnd oprot}
case f_TRegionInfo_version record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("version",T_BYTE,5)
writeByte oprot _v
writeFieldEnd oprot}
case f_TRegionInfo_serverName record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("serverName",T_STRING,6)
writeBinary oprot _v
writeFieldEnd oprot}
case f_TRegionInfo_port record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("port",T_I32,7)
writeI32 oprot _v
writeFieldEnd oprot}
writeFieldStop oprot
writeStructEnd oprot
read_TRegionInfo_fields iprot record = do
(_,_t13,_id14) <- readFieldBegin iprot
if _t13 == T_STOP then return record else
case _id14 of
1 -> if _t13 == T_STRING then do
s <- readBinary iprot
read_TRegionInfo_fields iprot record{f_TRegionInfo_startKey=Just s}
else do
skip iprot _t13
read_TRegionInfo_fields iprot record
2 -> if _t13 == T_STRING then do
s <- readBinary iprot
read_TRegionInfo_fields iprot record{f_TRegionInfo_endKey=Just s}
else do
skip iprot _t13
read_TRegionInfo_fields iprot record
3 -> if _t13 == T_I64 then do
s <- readI64 iprot
read_TRegionInfo_fields iprot record{f_TRegionInfo_id=Just s}
else do
skip iprot _t13
read_TRegionInfo_fields iprot record
4 -> if _t13 == T_STRING then do
s <- readBinary iprot
read_TRegionInfo_fields iprot record{f_TRegionInfo_name=Just s}
else do
skip iprot _t13
read_TRegionInfo_fields iprot record
5 -> if _t13 == T_BYTE then do
s <- readByte iprot
read_TRegionInfo_fields iprot record{f_TRegionInfo_version=Just s}
else do
skip iprot _t13
read_TRegionInfo_fields iprot record
6 -> if _t13 == T_STRING then do
s <- readBinary iprot
read_TRegionInfo_fields iprot record{f_TRegionInfo_serverName=Just s}
else do
skip iprot _t13
read_TRegionInfo_fields iprot record
7 -> if _t13 == T_I32 then do
s <- readI32 iprot
read_TRegionInfo_fields iprot record{f_TRegionInfo_port=Just s}
else do
skip iprot _t13
read_TRegionInfo_fields iprot record
_ -> do
skip iprot _t13
readFieldEnd iprot
read_TRegionInfo_fields iprot record
read_TRegionInfo iprot = do
_ <- readStructBegin iprot
record <- read_TRegionInfo_fields iprot (TRegionInfo{f_TRegionInfo_startKey=Nothing,f_TRegionInfo_endKey=Nothing,f_TRegionInfo_id=Nothing,f_TRegionInfo_name=Nothing,f_TRegionInfo_version=Nothing,f_TRegionInfo_serverName=Nothing,f_TRegionInfo_port=Nothing})
readStructEnd iprot
return record
data Mutation = Mutation{f_Mutation_isDelete :: Maybe Bool,f_Mutation_column :: Maybe ByteString,f_Mutation_value :: Maybe ByteString,f_Mutation_writeToWAL :: Maybe Bool} deriving (Show,Eq,Typeable)
instance Hashable Mutation where
hashWithSalt salt record = salt `hashWithSalt` f_Mutation_isDelete record `hashWithSalt` f_Mutation_column record `hashWithSalt` f_Mutation_value record `hashWithSalt` f_Mutation_writeToWAL record
write_Mutation oprot record = do
writeStructBegin oprot "Mutation"
case f_Mutation_isDelete record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("isDelete",T_BOOL,1)
writeBool oprot _v
writeFieldEnd oprot}
case f_Mutation_column record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("column",T_STRING,2)
writeBinary oprot _v
writeFieldEnd oprot}
case f_Mutation_value record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("value",T_STRING,3)
writeBinary oprot _v
writeFieldEnd oprot}
case f_Mutation_writeToWAL record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("writeToWAL",T_BOOL,4)
writeBool oprot _v
writeFieldEnd oprot}
writeFieldStop oprot
writeStructEnd oprot
read_Mutation_fields iprot record = do
(_,_t18,_id19) <- readFieldBegin iprot
if _t18 == T_STOP then return record else
case _id19 of
1 -> if _t18 == T_BOOL then do
s <- readBool iprot
read_Mutation_fields iprot record{f_Mutation_isDelete=Just s}
else do
skip iprot _t18
read_Mutation_fields iprot record
2 -> if _t18 == T_STRING then do
s <- readBinary iprot
read_Mutation_fields iprot record{f_Mutation_column=Just s}
else do
skip iprot _t18
read_Mutation_fields iprot record
3 -> if _t18 == T_STRING then do
s <- readBinary iprot
read_Mutation_fields iprot record{f_Mutation_value=Just s}
else do
skip iprot _t18
read_Mutation_fields iprot record
4 -> if _t18 == T_BOOL then do
s <- readBool iprot
read_Mutation_fields iprot record{f_Mutation_writeToWAL=Just s}
else do
skip iprot _t18
read_Mutation_fields iprot record
_ -> do
skip iprot _t18
readFieldEnd iprot
read_Mutation_fields iprot record
read_Mutation iprot = do
_ <- readStructBegin iprot
record <- read_Mutation_fields iprot (Mutation{f_Mutation_isDelete=Nothing,f_Mutation_column=Nothing,f_Mutation_value=Nothing,f_Mutation_writeToWAL=Nothing})
readStructEnd iprot
return record
data BatchMutation = BatchMutation{f_BatchMutation_row :: Maybe ByteString,f_BatchMutation_mutations :: Maybe (Vector.Vector Mutation)} deriving (Show,Eq,Typeable)
instance Hashable BatchMutation where
hashWithSalt salt record = salt `hashWithSalt` f_BatchMutation_row record `hashWithSalt` f_BatchMutation_mutations record
write_BatchMutation oprot record = do
writeStructBegin oprot "BatchMutation"
case f_BatchMutation_row record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("row",T_STRING,1)
writeBinary oprot _v
writeFieldEnd oprot}
case f_BatchMutation_mutations record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("mutations",T_LIST,2)
(let f = Vector.mapM_ (\_viter22 -> write_Mutation oprot _viter22) in do {writeListBegin oprot (T_STRUCT,fromIntegral $ Vector.length _v); f _v;writeListEnd oprot})
writeFieldEnd oprot}
writeFieldStop oprot
writeStructEnd oprot
read_BatchMutation_fields iprot record = do
(_,_t24,_id25) <- readFieldBegin iprot
if _t24 == T_STOP then return record else
case _id25 of
1 -> if _t24 == T_STRING then do
s <- readBinary iprot
read_BatchMutation_fields iprot record{f_BatchMutation_row=Just s}
else do
skip iprot _t24
read_BatchMutation_fields iprot record
2 -> if _t24 == T_LIST then do
s <- (let f n = Vector.replicateM (fromIntegral n) ((read_Mutation iprot)) in do {(_etype29,_size26) <- readListBegin iprot; f _size26})
read_BatchMutation_fields iprot record{f_BatchMutation_mutations=Just s}
else do
skip iprot _t24
read_BatchMutation_fields iprot record
_ -> do
skip iprot _t24
readFieldEnd iprot
read_BatchMutation_fields iprot record
read_BatchMutation iprot = do
_ <- readStructBegin iprot
record <- read_BatchMutation_fields iprot (BatchMutation{f_BatchMutation_row=Nothing,f_BatchMutation_mutations=Nothing})
readStructEnd iprot
return record
data TIncrement = TIncrement{f_TIncrement_table :: Maybe ByteString,f_TIncrement_row :: Maybe ByteString,f_TIncrement_column :: Maybe ByteString,f_TIncrement_ammount :: Maybe Int64} deriving (Show,Eq,Typeable)
instance Hashable TIncrement where
hashWithSalt salt record = salt `hashWithSalt` f_TIncrement_table record `hashWithSalt` f_TIncrement_row record `hashWithSalt` f_TIncrement_column record `hashWithSalt` f_TIncrement_ammount record
write_TIncrement oprot record = do
writeStructBegin oprot "TIncrement"
case f_TIncrement_table record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("table",T_STRING,1)
writeBinary oprot _v
writeFieldEnd oprot}
case f_TIncrement_row record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("row",T_STRING,2)
writeBinary oprot _v
writeFieldEnd oprot}
case f_TIncrement_column record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("column",T_STRING,3)
writeBinary oprot _v
writeFieldEnd oprot}
case f_TIncrement_ammount record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("ammount",T_I64,4)
writeI64 oprot _v
writeFieldEnd oprot}
writeFieldStop oprot
writeStructEnd oprot
read_TIncrement_fields iprot record = do
(_,_t34,_id35) <- readFieldBegin iprot
if _t34 == T_STOP then return record else
case _id35 of
1 -> if _t34 == T_STRING then do
s <- readBinary iprot
read_TIncrement_fields iprot record{f_TIncrement_table=Just s}
else do
skip iprot _t34
read_TIncrement_fields iprot record
2 -> if _t34 == T_STRING then do
s <- readBinary iprot
read_TIncrement_fields iprot record{f_TIncrement_row=Just s}
else do
skip iprot _t34
read_TIncrement_fields iprot record
3 -> if _t34 == T_STRING then do
s <- readBinary iprot
read_TIncrement_fields iprot record{f_TIncrement_column=Just s}
else do
skip iprot _t34
read_TIncrement_fields iprot record
4 -> if _t34 == T_I64 then do
s <- readI64 iprot
read_TIncrement_fields iprot record{f_TIncrement_ammount=Just s}
else do
skip iprot _t34
read_TIncrement_fields iprot record
_ -> do
skip iprot _t34
readFieldEnd iprot
read_TIncrement_fields iprot record
read_TIncrement iprot = do
_ <- readStructBegin iprot
record <- read_TIncrement_fields iprot (TIncrement{f_TIncrement_table=Nothing,f_TIncrement_row=Nothing,f_TIncrement_column=Nothing,f_TIncrement_ammount=Nothing})
readStructEnd iprot
return record
data TColumn = TColumn{f_TColumn_columnName :: Maybe ByteString,f_TColumn_cell :: Maybe TCell} deriving (Show,Eq,Typeable)
instance Hashable TColumn where
hashWithSalt salt record = salt `hashWithSalt` f_TColumn_columnName record `hashWithSalt` f_TColumn_cell record
write_TColumn oprot record = do
writeStructBegin oprot "TColumn"
case f_TColumn_columnName record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("columnName",T_STRING,1)
writeBinary oprot _v
writeFieldEnd oprot}
case f_TColumn_cell record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("cell",T_STRUCT,2)
write_TCell oprot _v
writeFieldEnd oprot}
writeFieldStop oprot
writeStructEnd oprot
read_TColumn_fields iprot record = do
(_,_t39,_id40) <- readFieldBegin iprot
if _t39 == T_STOP then return record else
case _id40 of
1 -> if _t39 == T_STRING then do
s <- readBinary iprot
read_TColumn_fields iprot record{f_TColumn_columnName=Just s}
else do
skip iprot _t39
read_TColumn_fields iprot record
2 -> if _t39 == T_STRUCT then do
s <- (read_TCell iprot)
read_TColumn_fields iprot record{f_TColumn_cell=Just s}
else do
skip iprot _t39
read_TColumn_fields iprot record
_ -> do
skip iprot _t39
readFieldEnd iprot
read_TColumn_fields iprot record
read_TColumn iprot = do
_ <- readStructBegin iprot
record <- read_TColumn_fields iprot (TColumn{f_TColumn_columnName=Nothing,f_TColumn_cell=Nothing})
readStructEnd iprot
return record
data TRowResult = TRowResult{f_TRowResult_row :: Maybe ByteString,f_TRowResult_columns :: Maybe (Map.HashMap ByteString TCell),f_TRowResult_sortedColumns :: Maybe (Vector.Vector TColumn)} deriving (Show,Eq,Typeable)
instance Hashable TRowResult where
hashWithSalt salt record = salt `hashWithSalt` f_TRowResult_row record `hashWithSalt` f_TRowResult_columns record `hashWithSalt` f_TRowResult_sortedColumns record
write_TRowResult oprot record = do
writeStructBegin oprot "TRowResult"
case f_TRowResult_row record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("row",T_STRING,1)
writeBinary oprot _v
writeFieldEnd oprot}
case f_TRowResult_columns record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("columns",T_MAP,2)
(let {f [] = return (); f ((_kiter43,_viter44):t) = do {do {writeBinary oprot _kiter43;write_TCell oprot _viter44};f t}} in do {writeMapBegin oprot (T_STRING,T_STRUCT,fromIntegral $ Map.size _v); f (Map.toList _v);writeMapEnd oprot})
writeFieldEnd oprot}
case f_TRowResult_sortedColumns record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("sortedColumns",T_LIST,3)
(let f = Vector.mapM_ (\_viter45 -> write_TColumn oprot _viter45) in do {writeListBegin oprot (T_STRUCT,fromIntegral $ Vector.length _v); f _v;writeListEnd oprot})
writeFieldEnd oprot}
writeFieldStop oprot
writeStructEnd oprot
read_TRowResult_fields iprot record = do
(_,_t47,_id48) <- readFieldBegin iprot
if _t47 == T_STOP then return record else
case _id48 of
1 -> if _t47 == T_STRING then do
s <- readBinary iprot
read_TRowResult_fields iprot record{f_TRowResult_row=Just s}
else do
skip iprot _t47
read_TRowResult_fields iprot record
2 -> if _t47 == T_MAP then do
s <- (let {f 0 = return []; f n = do {k <- readBinary iprot; v <- (read_TCell iprot);r <- f (n-1); return $ (k,v):r}} in do {(_ktype50,_vtype51,_size49) <- readMapBegin iprot; l <- f _size49; return $ Map.fromList l})
read_TRowResult_fields iprot record{f_TRowResult_columns=Just s}
else do
skip iprot _t47
read_TRowResult_fields iprot record
3 -> if _t47 == T_LIST then do
s <- (let f n = Vector.replicateM (fromIntegral n) ((read_TColumn iprot)) in do {(_etype57,_size54) <- readListBegin iprot; f _size54})
read_TRowResult_fields iprot record{f_TRowResult_sortedColumns=Just s}
else do
skip iprot _t47
read_TRowResult_fields iprot record
_ -> do
skip iprot _t47
readFieldEnd iprot
read_TRowResult_fields iprot record
read_TRowResult iprot = do
_ <- readStructBegin iprot
record <- read_TRowResult_fields iprot (TRowResult{f_TRowResult_row=Nothing,f_TRowResult_columns=Nothing,f_TRowResult_sortedColumns=Nothing})
readStructEnd iprot
return record
data TScan = TScan{f_TScan_startRow :: Maybe ByteString,f_TScan_stopRow :: Maybe ByteString,f_TScan_timestamp :: Maybe Int64,f_TScan_columns :: Maybe (Vector.Vector ByteString),f_TScan_caching :: Maybe Int32,f_TScan_filterString :: Maybe ByteString,f_TScan_batchSize :: Maybe Int32,f_TScan_sortColumns :: Maybe Bool} deriving (Show,Eq,Typeable)
instance Hashable TScan where
hashWithSalt salt record = salt `hashWithSalt` f_TScan_startRow record `hashWithSalt` f_TScan_stopRow record `hashWithSalt` f_TScan_timestamp record `hashWithSalt` f_TScan_columns record `hashWithSalt` f_TScan_caching record `hashWithSalt` f_TScan_filterString record `hashWithSalt` f_TScan_batchSize record `hashWithSalt` f_TScan_sortColumns record
write_TScan oprot record = do
writeStructBegin oprot "TScan"
case f_TScan_startRow record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("startRow",T_STRING,1)
writeBinary oprot _v
writeFieldEnd oprot}
case f_TScan_stopRow record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("stopRow",T_STRING,2)
writeBinary oprot _v
writeFieldEnd oprot}
case f_TScan_timestamp record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("timestamp",T_I64,3)
writeI64 oprot _v
writeFieldEnd oprot}
case f_TScan_columns record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("columns",T_LIST,4)
(let f = Vector.mapM_ (\_viter61 -> writeBinary oprot _viter61) in do {writeListBegin oprot (T_STRING,fromIntegral $ Vector.length _v); f _v;writeListEnd oprot})
writeFieldEnd oprot}
case f_TScan_caching record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("caching",T_I32,5)
writeI32 oprot _v
writeFieldEnd oprot}
case f_TScan_filterString record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("filterString",T_STRING,6)
writeBinary oprot _v
writeFieldEnd oprot}
case f_TScan_batchSize record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("batchSize",T_I32,7)
writeI32 oprot _v
writeFieldEnd oprot}
case f_TScan_sortColumns record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("sortColumns",T_BOOL,8)
writeBool oprot _v
writeFieldEnd oprot}
writeFieldStop oprot
writeStructEnd oprot
read_TScan_fields iprot record = do
(_,_t63,_id64) <- readFieldBegin iprot
if _t63 == T_STOP then return record else
case _id64 of
1 -> if _t63 == T_STRING then do
s <- readBinary iprot
read_TScan_fields iprot record{f_TScan_startRow=Just s}
else do
skip iprot _t63
read_TScan_fields iprot record
2 -> if _t63 == T_STRING then do
s <- readBinary iprot
read_TScan_fields iprot record{f_TScan_stopRow=Just s}
else do
skip iprot _t63
read_TScan_fields iprot record
3 -> if _t63 == T_I64 then do
s <- readI64 iprot
read_TScan_fields iprot record{f_TScan_timestamp=Just s}
else do
skip iprot _t63
read_TScan_fields iprot record
4 -> if _t63 == T_LIST then do
s <- (let f n = Vector.replicateM (fromIntegral n) (readBinary iprot) in do {(_etype68,_size65) <- readListBegin iprot; f _size65})
read_TScan_fields iprot record{f_TScan_columns=Just s}
else do
skip iprot _t63
read_TScan_fields iprot record
5 -> if _t63 == T_I32 then do
s <- readI32 iprot
read_TScan_fields iprot record{f_TScan_caching=Just s}
else do
skip iprot _t63
read_TScan_fields iprot record
6 -> if _t63 == T_STRING then do
s <- readBinary iprot
read_TScan_fields iprot record{f_TScan_filterString=Just s}
else do
skip iprot _t63
read_TScan_fields iprot record
7 -> if _t63 == T_I32 then do
s <- readI32 iprot
read_TScan_fields iprot record{f_TScan_batchSize=Just s}
else do
skip iprot _t63
read_TScan_fields iprot record
8 -> if _t63 == T_BOOL then do
s <- readBool iprot
read_TScan_fields iprot record{f_TScan_sortColumns=Just s}
else do
skip iprot _t63
read_TScan_fields iprot record
_ -> do
skip iprot _t63
readFieldEnd iprot
read_TScan_fields iprot record
read_TScan iprot = do
_ <- readStructBegin iprot
record <- read_TScan_fields iprot (TScan{f_TScan_startRow=Nothing,f_TScan_stopRow=Nothing,f_TScan_timestamp=Nothing,f_TScan_columns=Nothing,f_TScan_caching=Nothing,f_TScan_filterString=Nothing,f_TScan_batchSize=Nothing,f_TScan_sortColumns=Nothing})
readStructEnd iprot
return record
data IOError = IOError{f_IOError_message :: Maybe TL.Text} deriving (Show,Eq,Typeable)
instance Exception IOError
instance Hashable IOError where
hashWithSalt salt record = salt `hashWithSalt` f_IOError_message record
write_IOError oprot record = do
writeStructBegin oprot "IOError"
case f_IOError_message record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("message",T_STRING,1)
writeString oprot _v
writeFieldEnd oprot}
writeFieldStop oprot
writeStructEnd oprot
read_IOError_fields iprot record = do
(_,_t73,_id74) <- readFieldBegin iprot
if _t73 == T_STOP then return record else
case _id74 of
1 -> if _t73 == T_STRING then do
s <- readString iprot
read_IOError_fields iprot record{f_IOError_message=Just s}
else do
skip iprot _t73
read_IOError_fields iprot record
_ -> do
skip iprot _t73
readFieldEnd iprot
read_IOError_fields iprot record
read_IOError iprot = do
_ <- readStructBegin iprot
record <- read_IOError_fields iprot (IOError{f_IOError_message=Nothing})
readStructEnd iprot
return record
data IllegalArgument = IllegalArgument{f_IllegalArgument_message :: Maybe TL.Text} deriving (Show,Eq,Typeable)
instance Exception IllegalArgument
instance Hashable IllegalArgument where
hashWithSalt salt record = salt `hashWithSalt` f_IllegalArgument_message record
write_IllegalArgument oprot record = do
writeStructBegin oprot "IllegalArgument"
case f_IllegalArgument_message record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("message",T_STRING,1)
writeString oprot _v
writeFieldEnd oprot}
writeFieldStop oprot
writeStructEnd oprot
read_IllegalArgument_fields iprot record = do
(_,_t78,_id79) <- readFieldBegin iprot
if _t78 == T_STOP then return record else
case _id79 of
1 -> if _t78 == T_STRING then do
s <- readString iprot
read_IllegalArgument_fields iprot record{f_IllegalArgument_message=Just s}
else do
skip iprot _t78
read_IllegalArgument_fields iprot record
_ -> do
skip iprot _t78
readFieldEnd iprot
read_IllegalArgument_fields iprot record
read_IllegalArgument iprot = do
_ <- readStructBegin iprot
record <- read_IllegalArgument_fields iprot (IllegalArgument{f_IllegalArgument_message=Nothing})
readStructEnd iprot
return record
data AlreadyExists = AlreadyExists{f_AlreadyExists_message :: Maybe TL.Text} deriving (Show,Eq,Typeable)
instance Exception AlreadyExists
instance Hashable AlreadyExists where
hashWithSalt salt record = salt `hashWithSalt` f_AlreadyExists_message record
write_AlreadyExists oprot record = do
writeStructBegin oprot "AlreadyExists"
case f_AlreadyExists_message record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("message",T_STRING,1)
writeString oprot _v
writeFieldEnd oprot}
writeFieldStop oprot
writeStructEnd oprot
read_AlreadyExists_fields iprot record = do
(_,_t83,_id84) <- readFieldBegin iprot
if _t83 == T_STOP then return record else
case _id84 of
1 -> if _t83 == T_STRING then do
s <- readString iprot
read_AlreadyExists_fields iprot record{f_AlreadyExists_message=Just s}
else do
skip iprot _t83
read_AlreadyExists_fields iprot record
_ -> do
skip iprot _t83
readFieldEnd iprot
read_AlreadyExists_fields iprot record
read_AlreadyExists iprot = do
_ <- readStructBegin iprot
record <- read_AlreadyExists_fields iprot (AlreadyExists{f_AlreadyExists_message=Nothing})
readStructEnd iprot
return record
|
danplubell/hbase-haskell
|
src/Database/HBase/Internal/Thrift/Hbase_Types.hs
|
mit
| 33,352 | 192 | 38 | 7,138 | 9,551 | 4,732 | 4,819 | 710 | 20 |
-- Copyright (c) 2013-2014 Vincent Legout <[email protected]>
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
module Tasks
( Arrow (..)
, arrows
, Diagram(..)
, diagrams
, Exec(..)
, execs
, height_sched
, margin_bottom
, margin_top
, margin_x_left
, n_tasks
, print_x_scale
, Text(..)
, texts
, tot_length
, unit_width
, VLine(..)
, vlines
) where
import Graphics.Rendering.Pango.Markup
import Graphics.Rendering.Pango.Enums
data Arrow = Arrow { x_arrow :: Double
, x_diagram :: Double
}
data Diagram = Diagram { title :: Markup
, x_axis :: String
, x_grid :: Double
, y_axis :: String
}
data Exec = Exec { start :: Double
, end :: Double
, color :: Int
, desc :: Markup
, diagram :: Double
, kind :: Int
, size :: Size
, execHeight :: Double
, alpha :: Double
}
data VLine = VLine { linex :: Double }
data Text = Text { textAbsc :: Double
, textStr :: String
, textSize :: Size
}
height_sched = 30.0
tot_length = 12.0
unit_width = 20.0
margin_bottom = 10.0
margin_top = 0.0
margin_x_left = 20.0
print_x_scale = True
n_tasks = 2
arrows = [ ]
diagrams = [ Diagram "" "t" 1 "π<sub>1</sub>"
, Diagram "" "t" 1 "π<sub>2</sub>"
]
execs = [ Exec 0 2 0 "τ<sub>1</sub>" 1 0 SizeTiny 1.0 1.0
, Exec 4 6 0 "τ<sub>1</sub>" 1 0 SizeTiny 1.0 1.0
, Exec 8 10 0 "τ<sub>1</sub>" 1 0 SizeTiny 1.0 1.0
, Exec 0 3.5 1 "τ<sub>2</sub>" 2 0 SizeTiny 1.0 1.0
, Exec 6 9.5 1 "τ<sub>2</sub>" 2 0 SizeTiny 1.0 1.0
]
vlines = [ VLine 12 ]
texts = [ ]
|
vlegout/draw
|
Tasks.hs
|
mit
| 2,854 | 2 | 8 | 842 | 480 | 294 | 186 | 58 | 1 |
module AST where
import Text.Show.Pretty
{-- AST Primitives --}
type TypeName = String
type MethodName = String
data DataType = IntegerType
| ObjectType TypeName
| CopyType TypeName
| ObjectArrayType TypeName
| IntegerArrayType
| ArrayType
| ArrayElementType
| NilType
deriving (Show)
-- Types
instance Eq DataType where
IntegerType == IntegerType = True
IntegerArrayType == IntegerArrayType = True
NilType == NilType = True
NilType == (ObjectType _) = True
(ObjectType _) == NilType = True
(ObjectType t1) == (ObjectType t2) = t1 == t2
(CopyType t1) == (CopyType t2) = t1 == t2
(ObjectArrayType t1) == (ObjectArrayType t2) = t1 == t2
(CopyType t1) == (ObjectType t2) = t1 == t2
(ObjectType t1) == (CopyType t2) = t1 == t2
ArrayType == (ObjectArrayType _) = True
(ObjectArrayType _) == ArrayType = True
ArrayType == IntegerArrayType = True
IntegerArrayType == ArrayType = True
_ == _ = False
-- Binary Operators
data BinOp = Add
| Sub
| Xor
| Mul
| Div
| Mod
| BitAnd
| BitOr
| And
| Or
| Lt
| Gt
| Eq
| Neq
| Lte
| Gte
deriving (Show, Eq, Enum)
data ModOp = ModAdd
| ModSub
| ModXor
deriving (Show, Eq, Enum)
{-- Generic AST Definitions --}
--Expressions
data GExpr v = Constant Integer
| Variable v
| ArrayElement (v, GExpr v)
| Nil
| Binary BinOp (GExpr v) (GExpr v)
deriving (Show, Eq)
--Statements
data GStmt m v = Assign v ModOp (GExpr v)
| AssignArrElem (v, GExpr v) ModOp (GExpr v)
| Swap (v, Maybe (GExpr v)) (v, Maybe (GExpr v))
| Conditional (GExpr v) [GStmt m v] [GStmt m v] (GExpr v)
| Loop (GExpr v) [GStmt m v] [GStmt m v] (GExpr v)
| ObjectBlock TypeName v [GStmt m v]
| LocalBlock DataType v (GExpr v) [GStmt m v] (GExpr v)
| LocalCall m [(v, Maybe (GExpr v))]
| LocalUncall m [(v, Maybe (GExpr v))]
| ObjectCall (v, Maybe (GExpr v)) MethodName [(v, Maybe (GExpr v))]
| ObjectUncall (v, Maybe (GExpr v)) MethodName [(v, Maybe (GExpr v))]
| ObjectConstruction TypeName (v, Maybe (GExpr v))
| ObjectDestruction TypeName (v, Maybe (GExpr v))
| CopyReference DataType (v, Maybe (GExpr v)) (v, Maybe (GExpr v))
| UnCopyReference DataType (v, Maybe (GExpr v)) (v, Maybe (GExpr v))
| ArrayConstruction (TypeName, GExpr v) v
| ArrayDestruction (TypeName, GExpr v) v
| Skip
deriving (Show, Eq)
--Field/Parameter declarations
data GDecl v = GDecl DataType v
deriving (Show, Eq)
--Method: Name, parameters, body
data GMDecl m v = GMDecl m [GDecl v] [GStmt m v]
deriving (Show, Eq)
--Class: Name, fields, methods
data GCDecl m v = GCDecl TypeName (Maybe TypeName) [GDecl v] [GMDecl m v]
deriving (Show, Eq)
--Program
newtype GProg m v = GProg [GCDecl m v]
deriving (Show, Eq)
{-- Specific AST Definitions --}
--Plain AST
type Identifier = String
type Expression = GExpr Identifier
type Statement = GStmt MethodName Identifier
type VariableDeclaration = GDecl Identifier
type MethodDeclaration = GMDecl MethodName Identifier
type ClassDeclaration = GCDecl MethodName Identifier
type Program = GProg MethodName Identifier
--Scoped AST
type SIdentifier = Integer
type SExpression = GExpr SIdentifier
type SStatement = GStmt SIdentifier SIdentifier
type SVariableDeclaration = GDecl SIdentifier
type SMethodDeclaration = GMDecl SIdentifier SIdentifier
type SProgram = [(TypeName, GMDecl SIdentifier SIdentifier)]
{-- Other Definitions --}
type Offset = Integer
data Symbol = LocalVariable DataType Identifier
| ClassField DataType Identifier TypeName Offset
| MethodParameter DataType Identifier
| Method [DataType] MethodName
deriving (Show, Eq)
type SymbolTable = [(SIdentifier, Symbol)]
type Scope = [(Identifier, SIdentifier)]
printAST :: (Show t) => t -> String
printAST = ppShow
|
cservenka/ROOPLPPC
|
src/AST.hs
|
mit
| 4,300 | 0 | 11 | 1,299 | 1,408 | 775 | 633 | 106 | 1 |
module FunctionSyntax where
sumTill :: Int -> Int
sumTill 1 = 1
sumTill n = n + sumTill (n - 1)
sumTill' :: Int -> Int
sumTill' n
| n == 1 = 1
| otherwise = n + sumTill' (n - 1)
sumTill'' :: Int -> Int
sumTill'' x = case x of
1 | x > 0 -> 1
_ -> x + sumTill'' (x - 1)
rot13Char :: Char -> Char
rot13Char c
| isUpper = undefined
| isLower = undefined
| otherwise = error "ERROR"
where
isUpper = 'A' <= c && c <= 'Z'
isLower = 'a' <= c && c <= 'z'
addOneSquare :: Int -> Int
addOneSquare x =
let y = x + 1
z = y + x
in y * y + z
|
abhin4v/haskell-classes
|
2016-02-23/FunctionSyntax.hs
|
cc0-1.0
| 556 | 0 | 11 | 162 | 279 | 139 | 140 | 24 | 2 |
module System.Console.ListPromptSpec
where
import System.Console.ListPrompt.Internal
import System.Console.ListPrompt.Types
import System.Console.Terminal.Size (Window (..))
import Test.Hspec
spec :: Spec
spec = -- do
describe "getDimensions" $ do
it "works when a `Window` is provided, centering the prompt" $ do
let dim = getDimensions 10 (Just (Window 80 80))
listPromptSize dim `shouldBe` (13, 74)
targetCoordinate dim `shouldBe` (32, 3)
|
yamadapc/list-prompt
|
test/System/Console/ListPromptSpec.hs
|
gpl-2.0
| 542 | 0 | 18 | 155 | 134 | 76 | 58 | 12 | 1 |
import Data.Tuple (swap)
potencia :: Float -> Int -> Float
potencia b = (!!) $ iterate (*b) 1
divisor :: Int -> Int -> (Int,Int)
divisor a b = (d,a-d)
where d = last $ takeWhile ((<=a).(*b)) [0..]
divisores :: Int -> [Int]
divisores x = 1:x:[n | n <- [2..x `div` 2] , x `mod` n == 0]
esPrimo :: Int -> Bool
esPrimo = (>2) . length . divisores
|
ABorgna/algebra1
|
clases/4.hs
|
gpl-2.0
| 353 | 1 | 11 | 81 | 210 | 119 | 91 | 10 | 1 |
-- file: ch07/callingpure.hs
name2reply :: String -> String
name2reply name =
"Pleased to meet you, " ++ name ++ ".\n" ++
"Your name contains " ++ charcount ++ " characters."
where charcount = show (length name)
main :: IO ()
main = do
putStrLn "Greetings once again. What is your name?"
inpStr <- getLine
let outStr = name2reply inpStr
putStrLn outStr
|
dormouse/blog
|
source/haskell/haskell_learn/callingpure.hs
|
gpl-2.0
| 395 | 0 | 10 | 103 | 101 | 48 | 53 | 11 | 1 |
module Cashlog.Data.Types where
data Article = Article {
articleId :: Int
, articleName :: String
, articlePrice :: Double
, articleCategoryId :: Int
} deriving (Show)
type ArticleSkeleton = (String, Double, Int)
data Category = Category {
categoryId :: Int
, categoryParent :: Int
, categoryName :: String
} deriving (Show)
type CategorySkeleton = (Int, String)
data Shop = Shop {
shopId :: Int
, shopName :: String
, shopCity :: String
} deriving (Show)
type ShopSkeleton = (String, String)
data VoucherPosition = VoucherPosition {
voucherPositionId :: Int
, voucherPositionVoucherId :: Int
, voucherPositionArticleId :: Int
, voucherPositionQuantity :: Double
, voucherPositionPrice :: Double
} deriving (Show)
type VoucherPositionSkeleton = (Int, Int, Double, Double)
data Voucher = Voucher {
voucherId :: Int
, voucherTimestamp :: String
, voucherShopId :: Int
} deriving (Show)
type VoucherSkeleton = (String, Int)
|
pads-fhs/Cashlog
|
src/Cashlog/Data/Types.hs
|
gpl-2.0
| 1,034 | 0 | 8 | 251 | 264 | 168 | 96 | 34 | 0 |
import Yi.Buffer.Basic
import Yi.Buffer.HighLevel
import Yi.Buffer.Indent
import Yi.Buffer.Misc
import Yi.Buffer.Normal
import Yi.Buffer.Region
import Yi.Buffer.Undo
import Yi.Buffer.Implementation
fun a = 2
|
codemac/yi-editor
|
tests/data/haskell/14.hs
|
gpl-2.0
| 208 | 0 | 5 | 20 | 57 | 36 | 21 | 9 | 1 |
-- -*- mode: haskell -*-
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
module RedBlackTree.Param where
import Autolib.Reader
import Autolib.ToDoc
import Data.Typeable
import Autolib.Set
data Param = Param { anzahl :: Int, stellen :: Int }
deriving ( Typeable )
example :: Param
example = Param { anzahl = 10, stellen = 2 }
$(derives [makeReader, makeToDoc] [''Param])
|
Erdwolf/autotool-bonn
|
src/Baum/RotSchwarzBaumProjekt/Param.hs
|
gpl-2.0
| 383 | 0 | 9 | 63 | 103 | 62 | 41 | 11 | 1 |
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
module Convert.Type where
import Autolib.Reader
import Autolib.ToDoc
import Data.Typeable
import qualified Convert.Input
import Autolib.Exp.Inter
import Autolib.Exp
import Autolib.NFA hiding ( alphabet )
import Autolib.Set
data Convert =
Convert { name :: Maybe [String] -- if Nothing, use (show input)
, input :: Convert.Input.Input Char
}
deriving ( Typeable , Show )
$(derives [makeReader, makeToDoc] [''Convert])
form :: Convert -> Doc
form conv = case name conv of
Nothing -> Convert.Input.lang $ input conv
Just css -> vcat $ map text css
eval :: Set Char -> Convert -> NFA Char Int
eval alpha conv = case input conv of
Convert.Input.NFA aut -> aut
Convert.Input.Exp exp -> inter ( std_sigma $ setToList alpha ) exp
-- local variables:
-- mode: haskell;
-- end;
|
Erdwolf/autotool-bonn
|
src/Convert/Type.hs
|
gpl-2.0
| 877 | 13 | 10 | 183 | 240 | 141 | 99 | 23 | 2 |
-- elefante.hs
-- Dibujo de un elefante.
-- José A. Alonso Jiménez <[email protected]>
-- Sevilla, 20 de Mayo de 2013
-- ---------------------------------------------------------------------
-- ---------------------------------------------------------------------
-- Ejercicio. Dibujar un elefante como en la figura elefante.png
-- ---------------------------------------------------------------------
import Graphics.Gloss
main :: IO ()
main = display (InWindow "Dibujo" (500,300) (20,20)) white dibujo
dibujo :: Picture
dibujo = elefante
elefante =
pictures
[rotate 20 (scale 3 2 (translate 30 40 (circleSolid 25))), -- cabeza
translate 150 (-20) (rectangleSolid 40 80), -- trompa
translate (-10) 40 (scale 1.5 1 (circleSolid 80)), -- cuerpo
translate 50 (-50)(rectangleSolid 40 70), -- pata delantera
translate (-60) (-50) (rectangleSolid 40 70), -- pata trasera
translate (-140) 50 (rotate (-100) (rectangleSolid 10 40)) -- cola
]
|
jaalonso/I1M-Cod-Temas
|
src/Tema_25/elefante.hs
|
gpl-2.0
| 1,022 | 0 | 13 | 207 | 257 | 142 | 115 | 13 | 1 |
module Constants where
import Data.Int
import Data.Word
import Graphics.UI.SDL as SDL
width :: Double
width = 1024
height :: Double
height = 600
gameWidth :: Double
gameWidth = width
gameHeight :: Double
gameHeight = height
-- Energy transmission between objects in collisions
velTrans :: Double
velTrans = 1.00
-- Max speed
maxVNorm :: Double
maxVNorm = 500
ballWidth, ballHeight :: Double
ballWidth = 25
ballHeight = 25
ballMargin :: Double
ballMargin = 3
ballSize :: Int16
ballSize = 25
-- Colors
fontColor :: SDL.Color
fontColor = SDL.Color 228 228 228
ballColor :: Word32
ballColor = 0xCC0011FF
velColor :: Word32
velColor = 0xCCBBFFFF
|
keera-studios/pang-a-lambda
|
Experiments/splitballs/Constants.hs
|
gpl-3.0
| 657 | 0 | 6 | 118 | 163 | 100 | 63 | 29 | 1 |
#!/usr/bin/env runhaskell -iscripts
{-# LANGUAGE UnicodeSyntax #-}
module PosToMd where
import Prelude.Unicode
import ToMarkdownList
import System.IO (hPutStrLn, stderr)
import Text.Megaparsec (parse)
main ∷ IO ()
main = do
text ← getContents
let list = haskellListToMdList <$> parse (haskellList List "posAndString") "" text
let info = mdListToMd "The supported positions are:" <$> list
either (hPutStrLn stderr ∘ show) (mapM_ putStrLn) info
|
39aldo39/klfc
|
scripts/PosToMd.hs
|
gpl-3.0
| 468 | 0 | 13 | 79 | 129 | 67 | 62 | 12 | 1 |
-- Run doctests for HGrib.
module Main ( main ) where
import Test.DocTest ( doctest )
main :: IO ()
main = doctest ["-idist/build", "-isrc", "-lgrib_api", "src"]
|
mjakob/hgrib
|
test/DocTest.hs
|
gpl-3.0
| 165 | 0 | 6 | 30 | 50 | 30 | 20 | 4 | 1 |
module Main (main) where
import Test.Framework
import Test.HUnit
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2
import HuffmanTree
import Bit
main :: IO ()
main = defaultMain tests
tests = [
--Test Bit .&.
testCase "Bit .&. test, One && One = One"
$ testBitAnd One One One,
testCase "Bit .&. test, Zero && Zero = Zero"
$ testBitAnd Zero Zero Zero,
testCase "Bit .&. test, One && Zero = Zero"
$ testBitAnd One Zero Zero,
testCase "Bit .&. test, Zero && One = Zero"
$ testBitAnd Zero One Zero,
--Test Bit .|.
testCase "Bit .|. test, One && One = One"
$ testBitOr One One One,
testCase "Bit .|. test, Zero && Zero = Zero"
$ testBitOr Zero Zero Zero,
testCase "Bit .|. test, One && Zero = Zero"
$ testBitOr One Zero One,
testCase "Bit .|. test, Zero && One = Zero"
$ testBitOr Zero One One,
--Test Bit xor
testCase "Bit xor test, One && One = One"
$ testBitXOR One One Zero,
testCase "Bit xor test, Zero && Zero = Zero"
$ testBitXOR Zero Zero Zero,
testCase "Bit xor test, One && Zero = Zero"
$ testBitXOR One Zero One,
testCase "Bit xor test, Zero && One = Zero"
$ testBitXOR Zero One One,
--Test Bit complement
testCase "Bit complement test, complement One = One"
$ testBitComplement One One,
testCase "Bit complement test, complement One = One"
$ testBitComplement Zero One,
--Test Bit shift
testCase "Bit shift test, shift One 1 = Zero"
$ testBitShift One 1 Zero,
testCase "Bit shift test, shift Zero 1 = Zero"
$ testBitShift Zero 1 Zero,
testCase "Bit shift test, shift One -1 = Zero"
$ testBitShift One 1 Zero,
testCase "Bit shift test, shift Zero -1 = Zero"
$ testBitShift Zero 1 Zero,
testCase "Bit shift test, shift One 0 = One"
$ testBitShift One 0 One,
testCase "Bit shift test, shift Zero 0 = Zero"
$ testBitShift Zero 0 Zero,
--Test Bit Rotate
testCase "Bit rotate test, rotate One 1 = One"
$ testBitRotate One 1 One,
testCase "Bit rotate test, rotate One -1 = One"
$ testBitRotate One (-1) One,
testCase "Bit rotate test, rotate Zero 1 = Zero"
$ testBitRotate Zero 1 Zero,
testCase "Bit rotate test, rotate Zero -1 = Zero"
$ testBitRotate Zero (-1) Zero,
testCase "Bit rotate test, rotate One 0 = One"
$ testBitRotate One 0 One,
testCase "Bit rotate test, rotate Zero 0 = Zero"
$ testBitRotate Zero 0 Zero,
testCase "Bit rotate test, rotate Zero 50 = Zero"
$ testBitRotate Zero 50 Zero,
testCase "Bit rotate test, rotate One 50 = One"
$ testBitRotate One 50 One,
--Test bitSize
testCase "Bit bitSize test, bitSize One = 1"
$ testBitSize One,
testCase "Bit bitSize test, bitSize Zero = 1"
$ testBitSize Zero,
--Test isSigned
testCase "Bit isSigned test, One = False"
$ testBitIsSigned One,
testCase "Bit isSigned test, Zero = False"
$ testBitIsSigned Zero,
--Test testBit
testCase "Bit testBit test, One 0 = True"
$ testBitTestBit One 0 True,
testCase "Bit testBit test, Zero 0 = False"
$ testBitTestBit Zero 0 False,
testCase "Bit testBit test, One 1 = False"
$ testBitTestBit One 1 False,
testCase "Bit testBit test, Zero 1 = False"
$ testBitTestBit Zero 1 False,
testCase "Bit testBit test, Zero 100 = False"
$ testBitTestBit Zero 100 False,
--Test Bit
testCase "Bit test, bit 1 = One"
$ testBitBit 1 One,
testCase "Bit test, bit 0 = Zero"
$ testBitBit 0 Zero,
--Test Bit popCount
testCase "Bit popCount test, popCount Zero = 0"
$ testBitPopCount Zero 0,
testCase "Bit popCount test, popCount One = 1"
$ testBitPopCount One 1
]
testBitAnd :: Bit -> Bit -> Bit -> Assertion
testBitAnd a b c = c @=? (a .&. b)
testBitOr :: Bit -> Bit -> Bit -> Assertion
testBitOr a b c = c @=? (a .|. b)
testBitXOR :: Bit -> Bit -> Bit -> Assertion
testBitXOR a b c = c @=? (a `xor` b)
testBitComplement :: Bit -> Bit -> Assertion
testBitComplement a b = b @=? (complement a)
testBitShift :: Bit -> Int -> Bit -> Assertion
testBitShift a b c = c @=? (shift a b)
testBitRotate :: Bit -> Int -> Bit -> Assertion
testBitRotate a b c = c @=? (rotate a b)
testBitSize :: Bit -> Assertion
testBitSize a = 1 @=? (bitSize a)
testBitIsSigned :: Bit -> Assertion
testBitIsSigned a = False @=? (isSigned a)
testBitTestBit :: Bit -> Int -> Bool -> Assertion
testBitTestBit a b c = c @=? (testBit a b)
testBitBit :: Int -> Bit -> Assertion
testBitBit a b = b @=? (bit a)
testBitPopCount :: Bit -> Int -> Assertion
testBitPopCount a b = b @=? (popCount a)
|
JacobLeach/huffman_encoding
|
test/TestBits.hs
|
gpl-3.0
| 4,869 | 0 | 9 | 1,379 | 1,150 | 576 | 574 | 114 | 1 |
import DB
import qualified Database.HDBC.Sqlite3 as Sqlite3
main = do
conn <- Sqlite3.connectSqlite3 "data.db"
print =<< getAllUserBio conn
|
swordfeng/tg-biobot
|
src/Dump.hs
|
gpl-3.0
| 149 | 0 | 9 | 27 | 40 | 21 | 19 | 5 | 1 |
{-- |
This overrides the @pandocCompiler@ function from Hakyll with one which
enables MathML, enables highlighted code-blocks, disables HTML5 figures
and works around CRLFs in files, which confused Pandoc.
-}
module Site.Pandoc (pandocCompiler) where
import Data.Set (insert, delete)
import Hakyll hiding (pandocCompiler, pandocCompilerWith)
import Text.Pandoc.Options
pandocReaderOptions :: ReaderOptions
pandocReaderOptions = def
{
readerSmart = True,
-- Yes, HTML5 figures are fancy, but I prefer a simple p > img.
-- I also need fenced code blocks.
readerExtensions = delete Ext_implicit_figures $
insert Ext_backtick_code_blocks $
readerExtensions def
}
pandocWriterOptions :: WriterOptions
pandocWriterOptions = def
{
writerHtml5 = True,
writerHighlight = True,
writerHTMLMathMethod = MathML Nothing
}
-- Pandoc cannot handle CRLF on systems that use LF line endings, so we
-- remove the CR before feeding things into Pandoc.
removeCr :: String -> String
removeCr = filter (/= '\r')
getBodyWithoutCr :: Compiler (Item String)
getBodyWithoutCr = fmap (fmap removeCr) getResourceBody
pandocCompilerWith :: ReaderOptions -> WriterOptions -> Compiler (Item String)
pandocCompilerWith ropt wopt =
cached "Hakyll.Web.Pandoc.pandocCompilerWith" $
writePandocWith wopt <$> (readPandocWith ropt =<< getBodyWithoutCr)
pandocCompiler :: Compiler (Item String)
pandocCompiler = pandocCompilerWith pandocReaderOptions pandocWriterOptions
|
budgefeeney/amixtureofmusings
|
Site/Pandoc.hs
|
gpl-3.0
| 1,552 | 0 | 9 | 303 | 252 | 140 | 112 | 25 | 1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
{-# LANGUAGE DeriveDataTypeable, BangPatterns #-}
-- |
-- #name_types#
-- GHC uses several kinds of name internally:
--
-- * 'OccName.OccName' represents names as strings with just a little more information:
-- the \"namespace\" that the name came from, e.g. the namespace of value, type constructors or
-- data constructors
--
-- * 'RdrName.RdrName': see "RdrName#name_types"
--
-- * 'Name.Name': see "Name#name_types"
--
-- * 'Id.Id': see "Id#name_types"
--
-- * 'Var.Var': see "Var#name_types"
module OccName (OccName(..),
HasOccName(..),
NameSpace(..),
isSymOcc,
mkOccNameFS,
isDataOcc,
tvName,
mkVarOccFS,
demoteOccName,
isTvOcc,
mkRecFldSelOcc,
occNameString,
tcClsName,
varName,
setOccNameSpace,
isVarNameSpace,
srcDataName,
dataName,
isTcOcc) where
import Language.Haskell.Utility.Util
import U.Unique
import Language.Haskell.Utility.FastString
import Lexeme
import Data.Data
{-
************************************************************************
* *
\subsection{Name space}
* *
************************************************************************
-}
data NameSpace = VarName -- Variables, including "real" data constructors
| DataName -- "Source" data constructors
| TvName -- Type variables
| TcClsName -- Type constructors and classes; Haskell has them
-- in the same name space for now.
deriving( Eq, Ord, Show )
{-! derive: Binary !-}
-- Note [Data Constructors]
-- see also: Note [Data Constructor Naming] in DataCon.hs
--
-- $real_vs_source_data_constructors
-- There are two forms of data constructor:
--
-- [Source data constructors] The data constructors mentioned in Haskell source code
--
-- [Real data constructors] The data constructors of the representation type, which may not be the same as the source type
--
-- For example:
--
-- > data T = T !(Int, Int)
--
-- The source datacon has type @(Int, Int) -> T@
-- The real datacon has type @Int -> Int -> T@
--
-- GHC chooses a representation based on the strictness etc.
tcClsName :: NameSpace
dataName, srcDataName :: NameSpace
tvName, varName :: NameSpace
-- Though type constructors and classes are in the same name space now,
-- the NameSpace type is abstract, so we can easily separate them later
tcClsName = TcClsName -- Not sure which!
dataName = DataName
srcDataName = DataName -- Haskell-source data constructors should be
-- in the Data name space
tvName = TvName
varName = VarName
isVarNameSpace :: NameSpace -> Bool -- Variables or type variables, but not constructors
isVarNameSpace TvName = True
isVarNameSpace VarName = True
isVarNameSpace _ = False
-- demoteNameSpace lowers the NameSpace if possible. We can not know
-- in advance, since a TvName can appear in an HsTyVar.
-- See Note [Demotion] in RnEnv
demoteNameSpace :: NameSpace -> Maybe NameSpace
demoteNameSpace VarName = Nothing
demoteNameSpace DataName = Nothing
demoteNameSpace TvName = Nothing
demoteNameSpace TcClsName = Just DataName
{-
************************************************************************
* *
\subsection[Name-pieces-datatypes]{The @OccName@ datatypes}
* *
************************************************************************
-}
data OccName = OccName
{ occNameSpace :: !NameSpace
, occNameFS :: !FastString
} deriving Show
instance Eq OccName where
(OccName sp1 s1) == (OccName sp2 s2) = s1 == s2 && sp1 == sp2
instance Ord OccName where
-- Compares lexicographically, *not* by Unique of the string
compare (OccName sp1 s1) (OccName sp2 s2)
= (s1 `compare` s2) `thenCmp` (sp1 `compare` sp2)
instance Data OccName where
-- don't traverse?
toConstr _ = abstractConstr "OccName"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "OccName"
instance HasOccName OccName where
occName = id
{-
Note [Suppressing uniques in OccNames]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This is a hack to de-wobblify the OccNames that contain uniques from
Template Haskell that have been turned into a string in the OccName.
See Note [Unique OccNames from Template Haskell] in Convert.hs
************************************************************************
* *
\subsection{Construction}
* *
************************************************************************
-}
mkOccName :: NameSpace -> String -> OccName
mkOccName occ_sp str = OccName occ_sp (mkFastString str)
mkOccNameFS :: NameSpace -> FastString -> OccName
mkOccNameFS occ_sp fs = OccName occ_sp fs
mkVarOccFS :: FastString -> OccName
mkVarOccFS fs = mkOccNameFS varName fs
-- demoteOccName lowers the Namespace of OccName.
-- see Note [Demotion]
demoteOccName :: OccName -> Maybe OccName
demoteOccName (OccName space name) = do
space' <- demoteNameSpace space
return $ OccName space' name
{- | Other names in the compiler add additional information to an OccName.
This class provides a consistent way to access the underlying OccName. -}
class HasOccName name where
occName :: name -> OccName
{-
************************************************************************
* *
Environments
* *
************************************************************************
OccEnvs are used mainly for the envts in ModIfaces.
Note [The Unique of an OccName]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
They are efficient, because FastStrings have unique Int# keys. We assume
this key is less than 2^24, and indeed FastStrings are allocated keys
sequentially starting at 0.
So we can make a Unique using
mkUnique ns key :: Unique
where 'ns' is a Char representing the name space. This in turn makes it
easy to build an OccEnv.
-}
instance Uniquable OccName where
-- See Note [The Unique of an OccName]
getUnique (OccName VarName fs) = mkVarOccUnique fs
getUnique (OccName DataName fs) = mkDataOccUnique fs
getUnique (OccName TvName fs) = mkTvOccUnique fs
getUnique (OccName TcClsName fs) = mkTcOccUnique fs
{-
************************************************************************
* *
\subsection{Predicates and taking them apart}
* *
************************************************************************
-}
occNameString :: OccName -> String
occNameString (OccName _ s) = unpackFS s
setOccNameSpace :: NameSpace -> OccName -> OccName
setOccNameSpace sp (OccName _ occ) = OccName sp occ
isTvOcc, isTcOcc, isDataOcc :: OccName -> Bool
isTvOcc (OccName TvName _) = True
isTvOcc _ = False
isTcOcc (OccName TcClsName _) = True
isTcOcc _ = False
isDataOcc (OccName DataName _) = True
isDataOcc _ = False
-- | Test if the 'OccName' is that for any operator (whether
-- it is a data constructor or variable or whatever)
isSymOcc :: OccName -> Bool
isSymOcc (OccName DataName s) = isLexConSym s
isSymOcc (OccName TcClsName s) = isLexSym s
isSymOcc (OccName VarName s) = isLexSym s
isSymOcc (OccName TvName s) = isLexSym s
{-
************************************************************************
* *
\subsection{Making system names}
* *
************************************************************************
Here's our convention for splitting up the interface file name space:
d... dictionary identifiers
(local variables, so no name-clash worries)
All of these other OccNames contain a mixture of alphabetic
and symbolic characters, and hence cannot possibly clash with
a user-written type or function name
$f... Dict-fun identifiers (from inst decls)
$dmop Default method for 'op'
$pnC n'th superclass selector for class C
$wf Worker for function 'f'
$sf.. Specialised version of f
D:C Data constructor for dictionary for class C
NTCo:T Coercion connecting newtype T with its representation type
TFCo:R Coercion connecting a data family to its representation type R
In encoded form these appear as Zdfxxx etc
:... keywords (export:, letrec: etc.)
--- I THINK THIS IS WRONG!
This knowledge is encoded in the following functions.
@mk_deriv@ generates an @OccName@ from the prefix and a string.
NB: The string must already be encoded!
-}
mk_deriv :: NameSpace
-> String -- Distinguishes one sort of derived name from another
-> String
-> OccName
mk_deriv occ_sp sys_prefix str = mkOccName occ_sp (sys_prefix ++ str)
--- Overloaded record field selectors
mkRecFldSelOcc :: String -> OccName
mkRecFldSelOcc = mk_deriv varName "$sel"
|
shayan-najd/HsParser
|
OccName.hs
|
gpl-3.0
| 9,873 | 7 | 9 | 2,867 | 1,036 | 582 | 454 | 106 | 1 |
import Development.Hake
import Development.Hake.FunSetRaw
import Variables
main = hake [
dflt [ target ]
,
rule "" ".c" $ \t (s:_) -> [ [ "cc", "-o", t, s ] ]
]
|
YoshikuniJujo/hake_haskell
|
web_page/samples/use_hakefileIs/hakeMain.hs
|
gpl-3.0
| 168 | 0 | 10 | 38 | 73 | 42 | 31 | 6 | 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.PagespeedOnline.PagespeedAPI.RunPagespeed
-- 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)
--
-- Runs PageSpeed analysis on the page at the specified URL, and returns
-- PageSpeed scores, a list of suggestions to make that page faster, and
-- other information.
--
-- /See:/ <https://developers.google.com/speed/docs/insights/v2/getting-started PageSpeed Insights API Reference> for @pagespeedonline.pagespeedapi.runpagespeed@.
module Network.Google.Resource.PagespeedOnline.PagespeedAPI.RunPagespeed
(
-- * REST Resource
PagespeedAPIRunPagespeedResource
-- * Creating a Request
, pagespeedAPIRunPagespeed
, PagespeedAPIRunPagespeed
-- * Request Lenses
, parpScreenshot
, parpLocale
, parpURL
, parpFilterThirdPartyResources
, parpStrategy
, parpRule
) where
import Network.Google.PageSpeed.Types
import Network.Google.Prelude
-- | A resource alias for @pagespeedonline.pagespeedapi.runpagespeed@ method which the
-- 'PagespeedAPIRunPagespeed' request conforms to.
type PagespeedAPIRunPagespeedResource =
"pagespeedonline" :>
"v2" :>
"runPagespeed" :>
QueryParam "url" Text :>
QueryParam "screenshot" Bool :>
QueryParam "locale" Text :>
QueryParam "filter_third_party_resources" Bool :>
QueryParam "strategy"
PagespeedAPIRunPagespeedStrategy
:>
QueryParams "rule" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Result
-- | Runs PageSpeed analysis on the page at the specified URL, and returns
-- PageSpeed scores, a list of suggestions to make that page faster, and
-- other information.
--
-- /See:/ 'pagespeedAPIRunPagespeed' smart constructor.
data PagespeedAPIRunPagespeed = PagespeedAPIRunPagespeed'
{ _parpScreenshot :: !Bool
, _parpLocale :: !(Maybe Text)
, _parpURL :: !Text
, _parpFilterThirdPartyResources :: !Bool
, _parpStrategy :: !(Maybe PagespeedAPIRunPagespeedStrategy)
, _parpRule :: !(Maybe [Text])
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'PagespeedAPIRunPagespeed' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'parpScreenshot'
--
-- * 'parpLocale'
--
-- * 'parpURL'
--
-- * 'parpFilterThirdPartyResources'
--
-- * 'parpStrategy'
--
-- * 'parpRule'
pagespeedAPIRunPagespeed
:: Text -- ^ 'parpURL'
-> PagespeedAPIRunPagespeed
pagespeedAPIRunPagespeed pParpURL_ =
PagespeedAPIRunPagespeed'
{ _parpScreenshot = False
, _parpLocale = Nothing
, _parpURL = pParpURL_
, _parpFilterThirdPartyResources = False
, _parpStrategy = Nothing
, _parpRule = Nothing
}
-- | Indicates if binary data containing a screenshot should be included
parpScreenshot :: Lens' PagespeedAPIRunPagespeed Bool
parpScreenshot
= lens _parpScreenshot
(\ s a -> s{_parpScreenshot = a})
-- | The locale used to localize formatted results
parpLocale :: Lens' PagespeedAPIRunPagespeed (Maybe Text)
parpLocale
= lens _parpLocale (\ s a -> s{_parpLocale = a})
-- | The URL to fetch and analyze
parpURL :: Lens' PagespeedAPIRunPagespeed Text
parpURL = lens _parpURL (\ s a -> s{_parpURL = a})
-- | Indicates if third party resources should be filtered out before
-- PageSpeed analysis.
parpFilterThirdPartyResources :: Lens' PagespeedAPIRunPagespeed Bool
parpFilterThirdPartyResources
= lens _parpFilterThirdPartyResources
(\ s a -> s{_parpFilterThirdPartyResources = a})
-- | The analysis strategy to use
parpStrategy :: Lens' PagespeedAPIRunPagespeed (Maybe PagespeedAPIRunPagespeedStrategy)
parpStrategy
= lens _parpStrategy (\ s a -> s{_parpStrategy = a})
-- | A PageSpeed rule to run; if none are given, all rules are run
parpRule :: Lens' PagespeedAPIRunPagespeed [Text]
parpRule
= lens _parpRule (\ s a -> s{_parpRule = a}) .
_Default
. _Coerce
instance GoogleRequest PagespeedAPIRunPagespeed where
type Rs PagespeedAPIRunPagespeed = Result
type Scopes PagespeedAPIRunPagespeed = '[]
requestClient PagespeedAPIRunPagespeed'{..}
= go (Just _parpURL) (Just _parpScreenshot)
_parpLocale
(Just _parpFilterThirdPartyResources)
_parpStrategy
(_parpRule ^. _Default)
(Just AltJSON)
pageSpeedService
where go
= buildClient
(Proxy :: Proxy PagespeedAPIRunPagespeedResource)
mempty
|
rueshyna/gogol
|
gogol-pagespeed/gen/Network/Google/Resource/PagespeedOnline/PagespeedAPI/RunPagespeed.hs
|
mpl-2.0
| 5,424 | 0 | 17 | 1,303 | 715 | 419 | 296 | 105 | 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.Classroom.UserProFiles.Guardians.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 guardian. The guardian will no longer receive guardian
-- notifications and the guardian will no longer be accessible via the API.
-- This method returns the following error codes: * \`PERMISSION_DENIED\`
-- if no user that matches the provided \`student_id\` is visible to the
-- requesting user, if the requesting user is not permitted to manage
-- guardians for the student identified by the \`student_id\`, if guardians
-- are not enabled for the domain in question, or for other access errors.
-- * \`INVALID_ARGUMENT\` if a \`student_id\` is specified, but its format
-- cannot be recognized (it is not an email address, nor a \`student_id\`
-- from the API). * \`NOT_FOUND\` if the requesting user is permitted to
-- modify guardians for the requested \`student_id\`, but no \`Guardian\`
-- record exists for that student with the provided \`guardian_id\`.
--
-- /See:/ <https://developers.google.com/classroom/ Google Classroom API Reference> for @classroom.userProfiles.guardians.delete@.
module Network.Google.Resource.Classroom.UserProFiles.Guardians.Delete
(
-- * REST Resource
UserProFilesGuardiansDeleteResource
-- * Creating a Request
, userProFilesGuardiansDelete
, UserProFilesGuardiansDelete
-- * Request Lenses
, upfgdStudentId
, upfgdXgafv
, upfgdUploadProtocol
, upfgdPp
, upfgdAccessToken
, upfgdUploadType
, upfgdGuardianId
, upfgdBearerToken
, upfgdCallback
) where
import Network.Google.Classroom.Types
import Network.Google.Prelude
-- | A resource alias for @classroom.userProfiles.guardians.delete@ method which the
-- 'UserProFilesGuardiansDelete' request conforms to.
type UserProFilesGuardiansDeleteResource =
"v1" :>
"userProfiles" :>
Capture "studentId" Text :>
"guardians" :>
Capture "guardianId" Text :>
QueryParam "$.xgafv" Text :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Empty
-- | Deletes a guardian. The guardian will no longer receive guardian
-- notifications and the guardian will no longer be accessible via the API.
-- This method returns the following error codes: * \`PERMISSION_DENIED\`
-- if no user that matches the provided \`student_id\` is visible to the
-- requesting user, if the requesting user is not permitted to manage
-- guardians for the student identified by the \`student_id\`, if guardians
-- are not enabled for the domain in question, or for other access errors.
-- * \`INVALID_ARGUMENT\` if a \`student_id\` is specified, but its format
-- cannot be recognized (it is not an email address, nor a \`student_id\`
-- from the API). * \`NOT_FOUND\` if the requesting user is permitted to
-- modify guardians for the requested \`student_id\`, but no \`Guardian\`
-- record exists for that student with the provided \`guardian_id\`.
--
-- /See:/ 'userProFilesGuardiansDelete' smart constructor.
data UserProFilesGuardiansDelete = UserProFilesGuardiansDelete'
{ _upfgdStudentId :: !Text
, _upfgdXgafv :: !(Maybe Text)
, _upfgdUploadProtocol :: !(Maybe Text)
, _upfgdPp :: !Bool
, _upfgdAccessToken :: !(Maybe Text)
, _upfgdUploadType :: !(Maybe Text)
, _upfgdGuardianId :: !Text
, _upfgdBearerToken :: !(Maybe Text)
, _upfgdCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'UserProFilesGuardiansDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'upfgdStudentId'
--
-- * 'upfgdXgafv'
--
-- * 'upfgdUploadProtocol'
--
-- * 'upfgdPp'
--
-- * 'upfgdAccessToken'
--
-- * 'upfgdUploadType'
--
-- * 'upfgdGuardianId'
--
-- * 'upfgdBearerToken'
--
-- * 'upfgdCallback'
userProFilesGuardiansDelete
:: Text -- ^ 'upfgdStudentId'
-> Text -- ^ 'upfgdGuardianId'
-> UserProFilesGuardiansDelete
userProFilesGuardiansDelete pUpfgdStudentId_ pUpfgdGuardianId_ =
UserProFilesGuardiansDelete'
{ _upfgdStudentId = pUpfgdStudentId_
, _upfgdXgafv = Nothing
, _upfgdUploadProtocol = Nothing
, _upfgdPp = True
, _upfgdAccessToken = Nothing
, _upfgdUploadType = Nothing
, _upfgdGuardianId = pUpfgdGuardianId_
, _upfgdBearerToken = Nothing
, _upfgdCallback = Nothing
}
-- | The student whose guardian is to be deleted. One of the following: * the
-- numeric identifier for the user * the email address of the user * the
-- string literal \`\"me\"\`, indicating the requesting user
upfgdStudentId :: Lens' UserProFilesGuardiansDelete Text
upfgdStudentId
= lens _upfgdStudentId
(\ s a -> s{_upfgdStudentId = a})
-- | V1 error format.
upfgdXgafv :: Lens' UserProFilesGuardiansDelete (Maybe Text)
upfgdXgafv
= lens _upfgdXgafv (\ s a -> s{_upfgdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
upfgdUploadProtocol :: Lens' UserProFilesGuardiansDelete (Maybe Text)
upfgdUploadProtocol
= lens _upfgdUploadProtocol
(\ s a -> s{_upfgdUploadProtocol = a})
-- | Pretty-print response.
upfgdPp :: Lens' UserProFilesGuardiansDelete Bool
upfgdPp = lens _upfgdPp (\ s a -> s{_upfgdPp = a})
-- | OAuth access token.
upfgdAccessToken :: Lens' UserProFilesGuardiansDelete (Maybe Text)
upfgdAccessToken
= lens _upfgdAccessToken
(\ s a -> s{_upfgdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
upfgdUploadType :: Lens' UserProFilesGuardiansDelete (Maybe Text)
upfgdUploadType
= lens _upfgdUploadType
(\ s a -> s{_upfgdUploadType = a})
-- | The \`id\` field from a \`Guardian\`.
upfgdGuardianId :: Lens' UserProFilesGuardiansDelete Text
upfgdGuardianId
= lens _upfgdGuardianId
(\ s a -> s{_upfgdGuardianId = a})
-- | OAuth bearer token.
upfgdBearerToken :: Lens' UserProFilesGuardiansDelete (Maybe Text)
upfgdBearerToken
= lens _upfgdBearerToken
(\ s a -> s{_upfgdBearerToken = a})
-- | JSONP
upfgdCallback :: Lens' UserProFilesGuardiansDelete (Maybe Text)
upfgdCallback
= lens _upfgdCallback
(\ s a -> s{_upfgdCallback = a})
instance GoogleRequest UserProFilesGuardiansDelete
where
type Rs UserProFilesGuardiansDelete = Empty
type Scopes UserProFilesGuardiansDelete = '[]
requestClient UserProFilesGuardiansDelete'{..}
= go _upfgdStudentId _upfgdGuardianId _upfgdXgafv
_upfgdUploadProtocol
(Just _upfgdPp)
_upfgdAccessToken
_upfgdUploadType
_upfgdBearerToken
_upfgdCallback
(Just AltJSON)
classroomService
where go
= buildClient
(Proxy :: Proxy UserProFilesGuardiansDeleteResource)
mempty
|
rueshyna/gogol
|
gogol-classroom/gen/Network/Google/Resource/Classroom/UserProFiles/Guardians/Delete.hs
|
mpl-2.0
| 7,951 | 0 | 20 | 1,754 | 955 | 563 | 392 | 136 | 1 |
{-
Copyright 2017 Thomas Tuegel
This file is part of recategorize.
recategorize 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 3 of the License, or
(at your option) any later version.
recategorize 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
module Category
( Category(..), Cat
, (:-), imply, given
, Vacuous
) where
import Data.Kind
newtype (:-) (a :: Constraint) (b :: Constraint) = Imply { given :: forall r. (b => r) -> (a => r) }
imply :: (forall r. (b => r) -> (a => r)) -> (a :- b)
imply = Imply
type Cat k = k -> k -> *
class Category (cat :: Cat k) where
type Obj cat :: k -> Constraint
source :: cat a b -> (() :- Obj cat a)
target :: cat a b -> (() :- Obj cat b)
arrow :: cat a b -> (() :- (Obj cat a, Obj cat b))
id :: Obj cat a => cat a a
(>>>) :: cat a b -> cat b c -> cat a c
(<<<) :: cat b c -> cat a b -> cat a c
source a = given (arrow a) (imply (\r -> r))
target a = given (arrow a) (imply (\r -> r))
(>>>) f g = (<<<) g f
(<<<) g f = (>>>) f g
class Vacuous (a :: k)
instance Vacuous a
instance Category (->) where
type Obj (->) = Vacuous
id = \a -> a
arrow _ = imply (\r -> r)
(>>>) f g = \x -> g (f x)
instance Category (:-) where
type Obj (:-) = Vacuous
id = imply (\a -> a)
arrow _ = imply (\r -> r)
(>>>) f g = imply (\c -> given f (given g c))
|
ttuegel/recategorize
|
src/Category.hs
|
lgpl-3.0
| 2,115 | 0 | 11 | 476 | 662 | 369 | 293 | -1 | -1 |
data Enc a = Single a | Multiple Int a deriving (Show)
encodeDirect :: Eq a => [a] -> [Enc a]
encodeDirect [] = []
encodeDirect (x:xs) = encodeDirect' (Single x) xs
where
encodeDirect' x [] = [x]
encodeDirect' (Single x) (y:ys)
| x == y = encodeDirect' (Multiple 2 x) ys
encodeDirect' (Multiple n x) (y:ys)
| x == y = encodeDirect' (Multiple (n+1) x) ys
encodeDirect' x (y:ys) = x:(encodeDirect' (Single y) ys)
|
alephnil/h99
|
13.hs
|
apache-2.0
| 476 | 0 | 12 | 140 | 241 | 122 | 119 | 10 | 4 |
{-# OPTIONS_GHC -F -pgmF hspec-discover #-}
-- Run with `stack setup && stack test` or `testOEIS`
--
--
|
peterokagey/haskellOEIS
|
test/Spec.hs
|
apache-2.0
| 104 | 0 | 2 | 18 | 6 | 5 | 1 | 1 | 0 |
module AlecSequences.A269423Spec (main, spec) where
import Test.Hspec
import AlecSequences.A269423 (a269423)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A269423" $
it "correctly computes the first 20 elements" $
take 20 (map a269423 [1..]) `shouldBe` expectedValue where
expectedValue = [1,1,3,1,7,4,8,8,10,16,3,9,7,12,13,25,12,4,12,14]
|
peterokagey/haskellOEIS
|
test/AlecSequences/A269423Spec.hs
|
apache-2.0
| 369 | 0 | 10 | 59 | 160 | 95 | 65 | 10 | 1 |
-- http://www.codewars.com/kata/5500d54c2ebe0a8e8a0003fd
module Codewars.Kata.GCD where
import Prelude hiding (gcd, lcm)
gcd :: Integral n => n -> n -> n
gcd = curry (fst . head . dropWhile ((/=0) . snd) . iterate (\(a, b) -> (b, a `mod` b)))
|
Bodigrim/katas
|
src/haskell/B-Greatest-common-divisor.hs
|
bsd-2-clause
| 244 | 0 | 12 | 41 | 106 | 62 | 44 | 4 | 1 |
{-# OPTIONS -fglasgow-exts -#include "../include/gui/qtc_hs_QAbstractItemDelegate_h.h" #-}
-----------------------------------------------------------------------------
{-| Module : QAbstractItemDelegate_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:21
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QAbstractItemDelegate_h (
QeditorEvent_h(..)
) where
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QAbstractItemDelegate ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractItemDelegate_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QAbstractItemDelegate_unSetUserMethod" qtc_QAbstractItemDelegate_unSetUserMethod :: Ptr (TQAbstractItemDelegate a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QAbstractItemDelegateSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractItemDelegate_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QAbstractItemDelegate ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractItemDelegate_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QAbstractItemDelegateSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractItemDelegate_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QAbstractItemDelegate ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractItemDelegate_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QAbstractItemDelegateSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractItemDelegate_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QAbstractItemDelegate ()) (QAbstractItemDelegate x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QAbstractItemDelegate setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QAbstractItemDelegate_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QAbstractItemDelegate_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractItemDelegate_setUserMethod" qtc_QAbstractItemDelegate_setUserMethod :: Ptr (TQAbstractItemDelegate a) -> CInt -> Ptr (Ptr (TQAbstractItemDelegate x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QAbstractItemDelegate :: (Ptr (TQAbstractItemDelegate x0) -> IO ()) -> IO (FunPtr (Ptr (TQAbstractItemDelegate x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QAbstractItemDelegate_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QAbstractItemDelegateSc a) (QAbstractItemDelegate x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QAbstractItemDelegate setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QAbstractItemDelegate_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QAbstractItemDelegate_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QAbstractItemDelegate ()) (QAbstractItemDelegate x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QAbstractItemDelegate setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QAbstractItemDelegate_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QAbstractItemDelegate_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractItemDelegate_setUserMethodVariant" qtc_QAbstractItemDelegate_setUserMethodVariant :: Ptr (TQAbstractItemDelegate a) -> CInt -> Ptr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QAbstractItemDelegate :: (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QAbstractItemDelegate_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QAbstractItemDelegateSc a) (QAbstractItemDelegate x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QAbstractItemDelegate setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QAbstractItemDelegate_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QAbstractItemDelegate_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QAbstractItemDelegate ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QAbstractItemDelegate_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QAbstractItemDelegate_unSetHandler" qtc_QAbstractItemDelegate_unSetHandler :: Ptr (TQAbstractItemDelegate a) -> CWString -> IO (CBool)
instance QunSetHandler (QAbstractItemDelegateSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QAbstractItemDelegate_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QAbstractItemDelegate ()) (QAbstractItemDelegate x0 -> QObject t1 -> QStyleOption t2 -> QModelIndex t3 -> IO (QObject t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO (Ptr (TQObject t0))
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
x3obj <- objectFromPtr_nf x3
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj x2obj x3obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractItemDelegate_setHandler1" qtc_QAbstractItemDelegate_setHandler1 :: Ptr (TQAbstractItemDelegate a) -> CWString -> Ptr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO (Ptr (TQObject t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate1 :: (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO (Ptr (TQObject t0))) -> IO (FunPtr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO (Ptr (TQObject t0))))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemDelegateSc a) (QAbstractItemDelegate x0 -> QObject t1 -> QStyleOption t2 -> QModelIndex t3 -> IO (QObject t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO (Ptr (TQObject t0))
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
x3obj <- objectFromPtr_nf x3
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj x2obj x3obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QcreateEditor_h (QAbstractItemDelegate ()) ((QWidget t1, QStyleOptionViewItem t2, QModelIndex t3)) where
createEditor_h x0 (x1, x2, x3)
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QAbstractItemDelegate_createEditor cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QAbstractItemDelegate_createEditor" qtc_QAbstractItemDelegate_createEditor :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQWidget t1) -> Ptr (TQStyleOptionViewItem t2) -> Ptr (TQModelIndex t3) -> IO (Ptr (TQWidget ()))
instance QcreateEditor_h (QAbstractItemDelegateSc a) ((QWidget t1, QStyleOptionViewItem t2, QModelIndex t3)) where
createEditor_h x0 (x1, x2, x3)
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QAbstractItemDelegate_createEditor cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance QsetHandler (QAbstractItemDelegate ()) (QAbstractItemDelegate x0 -> QEvent t1 -> QObject t2 -> QStyleOption t3 -> QModelIndex t4 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQEvent t1) -> Ptr (TQObject t2) -> Ptr (TQStyleOption t3) -> Ptr (TQModelIndex t4) -> IO (CBool)
setHandlerWrapper x0 x1 x2 x3 x4
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- qObjectFromPtr x2
x3obj <- objectFromPtr_nf x3
x4obj <- objectFromPtr_nf x4
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj x3obj x4obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractItemDelegate_setHandler2" qtc_QAbstractItemDelegate_setHandler2 :: Ptr (TQAbstractItemDelegate a) -> CWString -> Ptr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQEvent t1) -> Ptr (TQObject t2) -> Ptr (TQStyleOption t3) -> Ptr (TQModelIndex t4) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate2 :: (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQEvent t1) -> Ptr (TQObject t2) -> Ptr (TQStyleOption t3) -> Ptr (TQModelIndex t4) -> IO (CBool)) -> IO (FunPtr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQEvent t1) -> Ptr (TQObject t2) -> Ptr (TQStyleOption t3) -> Ptr (TQModelIndex t4) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemDelegateSc a) (QAbstractItemDelegate x0 -> QEvent t1 -> QObject t2 -> QStyleOption t3 -> QModelIndex t4 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQEvent t1) -> Ptr (TQObject t2) -> Ptr (TQStyleOption t3) -> Ptr (TQModelIndex t4) -> IO (CBool)
setHandlerWrapper x0 x1 x2 x3 x4
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- qObjectFromPtr x2
x3obj <- objectFromPtr_nf x3
x4obj <- objectFromPtr_nf x4
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj x3obj x4obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
class QeditorEvent_h x0 x1 where
editorEvent_h :: x0 -> x1 -> IO (Bool)
instance QeditorEvent_h (QAbstractItemDelegate ()) ((QEvent t1, QAbstractItemModel t2, QStyleOptionViewItem t3, QModelIndex t4)) where
editorEvent_h x0 (x1, x2, x3, x4)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
withObjectPtr x4 $ \cobj_x4 ->
qtc_QAbstractItemDelegate_editorEvent cobj_x0 cobj_x1 cobj_x2 cobj_x3 cobj_x4
foreign import ccall "qtc_QAbstractItemDelegate_editorEvent" qtc_QAbstractItemDelegate_editorEvent :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQEvent t1) -> Ptr (TQAbstractItemModel t2) -> Ptr (TQStyleOptionViewItem t3) -> Ptr (TQModelIndex t4) -> IO CBool
instance QeditorEvent_h (QAbstractItemDelegateSc a) ((QEvent t1, QAbstractItemModel t2, QStyleOptionViewItem t3, QModelIndex t4)) where
editorEvent_h x0 (x1, x2, x3, x4)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
withObjectPtr x4 $ \cobj_x4 ->
qtc_QAbstractItemDelegate_editorEvent cobj_x0 cobj_x1 cobj_x2 cobj_x3 cobj_x4
instance QsetHandler (QAbstractItemDelegate ()) (QAbstractItemDelegate x0 -> QPainter t1 -> QStyleOption t2 -> QModelIndex t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- objectFromPtr_nf x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractItemDelegate_setHandler3" qtc_QAbstractItemDelegate_setHandler3 :: Ptr (TQAbstractItemDelegate a) -> CWString -> Ptr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate3 :: (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()) -> IO (FunPtr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemDelegateSc a) (QAbstractItemDelegate x0 -> QPainter t1 -> QStyleOption t2 -> QModelIndex t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- objectFromPtr_nf x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qpaint_h (QAbstractItemDelegate ()) ((QPainter t1, QStyleOptionViewItem t2, QModelIndex t3)) where
paint_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QAbstractItemDelegate_paint cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QAbstractItemDelegate_paint" qtc_QAbstractItemDelegate_paint :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionViewItem t2) -> Ptr (TQModelIndex t3) -> IO ()
instance Qpaint_h (QAbstractItemDelegateSc a) ((QPainter t1, QStyleOptionViewItem t2, QModelIndex t3)) where
paint_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QAbstractItemDelegate_paint cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance QsetHandler (QAbstractItemDelegate ()) (QAbstractItemDelegate x0 -> QObject t1 -> QModelIndex t2 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQModelIndex t2) -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractItemDelegate_setHandler4" qtc_QAbstractItemDelegate_setHandler4 :: Ptr (TQAbstractItemDelegate a) -> CWString -> Ptr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQModelIndex t2) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate4 :: (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQModelIndex t2) -> IO ()) -> IO (FunPtr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQModelIndex t2) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemDelegateSc a) (QAbstractItemDelegate x0 -> QObject t1 -> QModelIndex t2 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQModelIndex t2) -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetEditorData_h (QAbstractItemDelegate ()) ((QWidget t1, QModelIndex t2)) where
setEditorData_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QAbstractItemDelegate_setEditorData cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QAbstractItemDelegate_setEditorData" qtc_QAbstractItemDelegate_setEditorData :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQWidget t1) -> Ptr (TQModelIndex t2) -> IO ()
instance QsetEditorData_h (QAbstractItemDelegateSc a) ((QWidget t1, QModelIndex t2)) where
setEditorData_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QAbstractItemDelegate_setEditorData cobj_x0 cobj_x1 cobj_x2
instance QsetHandler (QAbstractItemDelegate ()) (QAbstractItemDelegate x0 -> QObject t1 -> QObject t2 -> QModelIndex t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQObject t2) -> Ptr (TQModelIndex t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- qObjectFromPtr x2
x3obj <- objectFromPtr_nf x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractItemDelegate_setHandler5" qtc_QAbstractItemDelegate_setHandler5 :: Ptr (TQAbstractItemDelegate a) -> CWString -> Ptr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQObject t2) -> Ptr (TQModelIndex t3) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate5 :: (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQObject t2) -> Ptr (TQModelIndex t3) -> IO ()) -> IO (FunPtr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQObject t2) -> Ptr (TQModelIndex t3) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemDelegateSc a) (QAbstractItemDelegate x0 -> QObject t1 -> QObject t2 -> QModelIndex t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQObject t2) -> Ptr (TQModelIndex t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- qObjectFromPtr x2
x3obj <- objectFromPtr_nf x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetModelData_h (QAbstractItemDelegate ()) ((QWidget t1, QAbstractItemModel t2, QModelIndex t3)) where
setModelData_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QAbstractItemDelegate_setModelData cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QAbstractItemDelegate_setModelData" qtc_QAbstractItemDelegate_setModelData :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQWidget t1) -> Ptr (TQAbstractItemModel t2) -> Ptr (TQModelIndex t3) -> IO ()
instance QsetModelData_h (QAbstractItemDelegateSc a) ((QWidget t1, QAbstractItemModel t2, QModelIndex t3)) where
setModelData_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QAbstractItemDelegate_setModelData cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance QsetHandler (QAbstractItemDelegate ()) (QAbstractItemDelegate x0 -> QStyleOption t1 -> QModelIndex t2 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQStyleOption t1) -> Ptr (TQModelIndex t2) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj x2obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractItemDelegate_setHandler6" qtc_QAbstractItemDelegate_setHandler6 :: Ptr (TQAbstractItemDelegate a) -> CWString -> Ptr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQStyleOption t1) -> Ptr (TQModelIndex t2) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate6 :: (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQStyleOption t1) -> Ptr (TQModelIndex t2) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQStyleOption t1) -> Ptr (TQModelIndex t2) -> IO (Ptr (TQSize t0))))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemDelegateSc a) (QAbstractItemDelegate x0 -> QStyleOption t1 -> QModelIndex t2 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQStyleOption t1) -> Ptr (TQModelIndex t2) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj x2obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqsizeHint_h (QAbstractItemDelegate ()) ((QStyleOptionViewItem t1, QModelIndex t2)) where
qsizeHint_h x0 (x1, x2)
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QAbstractItemDelegate_sizeHint cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QAbstractItemDelegate_sizeHint" qtc_QAbstractItemDelegate_sizeHint :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQStyleOptionViewItem t1) -> Ptr (TQModelIndex t2) -> IO (Ptr (TQSize ()))
instance QqsizeHint_h (QAbstractItemDelegateSc a) ((QStyleOptionViewItem t1, QModelIndex t2)) where
qsizeHint_h x0 (x1, x2)
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QAbstractItemDelegate_sizeHint cobj_x0 cobj_x1 cobj_x2
instance QsizeHint_h (QAbstractItemDelegate ()) ((QStyleOptionViewItem t1, QModelIndex t2)) where
sizeHint_h x0 (x1, x2)
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QAbstractItemDelegate_sizeHint_qth cobj_x0 cobj_x1 cobj_x2 csize_ret_w csize_ret_h
foreign import ccall "qtc_QAbstractItemDelegate_sizeHint_qth" qtc_QAbstractItemDelegate_sizeHint_qth :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQStyleOptionViewItem t1) -> Ptr (TQModelIndex t2) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint_h (QAbstractItemDelegateSc a) ((QStyleOptionViewItem t1, QModelIndex t2)) where
sizeHint_h x0 (x1, x2)
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QAbstractItemDelegate_sizeHint_qth cobj_x0 cobj_x1 cobj_x2 csize_ret_w csize_ret_h
instance QsetHandler (QAbstractItemDelegate ()) (QAbstractItemDelegate x0 -> QObject t1 -> QStyleOption t2 -> QModelIndex t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
x3obj <- objectFromPtr_nf x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractItemDelegate_setHandler7" qtc_QAbstractItemDelegate_setHandler7 :: Ptr (TQAbstractItemDelegate a) -> CWString -> Ptr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate7 :: (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()) -> IO (FunPtr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemDelegateSc a) (QAbstractItemDelegate x0 -> QObject t1 -> QStyleOption t2 -> QModelIndex t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
x3obj <- objectFromPtr_nf x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QupdateEditorGeometry_h (QAbstractItemDelegate ()) ((QWidget t1, QStyleOptionViewItem t2, QModelIndex t3)) where
updateEditorGeometry_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QAbstractItemDelegate_updateEditorGeometry cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QAbstractItemDelegate_updateEditorGeometry" qtc_QAbstractItemDelegate_updateEditorGeometry :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQWidget t1) -> Ptr (TQStyleOptionViewItem t2) -> Ptr (TQModelIndex t3) -> IO ()
instance QupdateEditorGeometry_h (QAbstractItemDelegateSc a) ((QWidget t1, QStyleOptionViewItem t2, QModelIndex t3)) where
updateEditorGeometry_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QAbstractItemDelegate_updateEditorGeometry cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance QsetHandler (QAbstractItemDelegate ()) (QAbstractItemDelegate x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractItemDelegate_setHandler8" qtc_QAbstractItemDelegate_setHandler8 :: Ptr (TQAbstractItemDelegate a) -> CWString -> Ptr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate8 :: (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemDelegateSc a) (QAbstractItemDelegate x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qevent_h (QAbstractItemDelegate ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemDelegate_event cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemDelegate_event" qtc_QAbstractItemDelegate_event :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QAbstractItemDelegateSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemDelegate_event cobj_x0 cobj_x1
instance QsetHandler (QAbstractItemDelegate ()) (QAbstractItemDelegate x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractItemDelegate_setHandler9" qtc_QAbstractItemDelegate_setHandler9 :: Ptr (TQAbstractItemDelegate a) -> CWString -> Ptr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate9 :: (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemDelegate9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemDelegateSc a) (QAbstractItemDelegate x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemDelegate9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemDelegate9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemDelegate_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemDelegate x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractItemDelegateFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QeventFilter_h (QAbstractItemDelegate ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QAbstractItemDelegate_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QAbstractItemDelegate_eventFilter" qtc_QAbstractItemDelegate_eventFilter :: Ptr (TQAbstractItemDelegate a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QAbstractItemDelegateSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QAbstractItemDelegate_eventFilter cobj_x0 cobj_x1 cobj_x2
|
uduki/hsQt
|
Qtc/Gui/QAbstractItemDelegate_h.hs
|
bsd-2-clause
| 52,824 | 0 | 19 | 11,273 | 16,967 | 8,046 | 8,921 | -1 | -1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QNetworkProxy.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:31
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Network.QNetworkProxy (
QqNetworkProxy(..)
,QqNetworkProxy_nf(..)
,qNetworkProxyApplicationProxy
,qNetworkProxySetApplicationProxy
,user
,qNetworkProxy_delete
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Network.QNetworkProxy
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Network
import Qtc.ClassTypes.Network
class QqNetworkProxy x1 where
qNetworkProxy :: x1 -> IO (QNetworkProxy ())
instance QqNetworkProxy (()) where
qNetworkProxy ()
= withQNetworkProxyResult $
qtc_QNetworkProxy
foreign import ccall "qtc_QNetworkProxy" qtc_QNetworkProxy :: IO (Ptr (TQNetworkProxy ()))
instance QqNetworkProxy ((QNetworkProxy t1)) where
qNetworkProxy (x1)
= withQNetworkProxyResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QNetworkProxy1 cobj_x1
foreign import ccall "qtc_QNetworkProxy1" qtc_QNetworkProxy1 :: Ptr (TQNetworkProxy t1) -> IO (Ptr (TQNetworkProxy ()))
instance QqNetworkProxy ((ProxyType)) where
qNetworkProxy (x1)
= withQNetworkProxyResult $
qtc_QNetworkProxy2 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QNetworkProxy2" qtc_QNetworkProxy2 :: CLong -> IO (Ptr (TQNetworkProxy ()))
instance QqNetworkProxy ((ProxyType, String)) where
qNetworkProxy (x1, x2)
= withQNetworkProxyResult $
withCWString x2 $ \cstr_x2 ->
qtc_QNetworkProxy3 (toCLong $ qEnum_toInt x1) cstr_x2
foreign import ccall "qtc_QNetworkProxy3" qtc_QNetworkProxy3 :: CLong -> CWString -> IO (Ptr (TQNetworkProxy ()))
instance QqNetworkProxy ((ProxyType, String, Int)) where
qNetworkProxy (x1, x2, x3)
= withQNetworkProxyResult $
withCWString x2 $ \cstr_x2 ->
qtc_QNetworkProxy4 (toCLong $ qEnum_toInt x1) cstr_x2 (toCUShort x3)
foreign import ccall "qtc_QNetworkProxy4" qtc_QNetworkProxy4 :: CLong -> CWString -> CUShort -> IO (Ptr (TQNetworkProxy ()))
instance QqNetworkProxy ((ProxyType, String, Int, String)) where
qNetworkProxy (x1, x2, x3, x4)
= withQNetworkProxyResult $
withCWString x2 $ \cstr_x2 ->
withCWString x4 $ \cstr_x4 ->
qtc_QNetworkProxy5 (toCLong $ qEnum_toInt x1) cstr_x2 (toCUShort x3) cstr_x4
foreign import ccall "qtc_QNetworkProxy5" qtc_QNetworkProxy5 :: CLong -> CWString -> CUShort -> CWString -> IO (Ptr (TQNetworkProxy ()))
instance QqNetworkProxy ((ProxyType, String, Int, String, String)) where
qNetworkProxy (x1, x2, x3, x4, x5)
= withQNetworkProxyResult $
withCWString x2 $ \cstr_x2 ->
withCWString x4 $ \cstr_x4 ->
withCWString x5 $ \cstr_x5 ->
qtc_QNetworkProxy6 (toCLong $ qEnum_toInt x1) cstr_x2 (toCUShort x3) cstr_x4 cstr_x5
foreign import ccall "qtc_QNetworkProxy6" qtc_QNetworkProxy6 :: CLong -> CWString -> CUShort -> CWString -> CWString -> IO (Ptr (TQNetworkProxy ()))
class QqNetworkProxy_nf x1 where
qNetworkProxy_nf :: x1 -> IO (QNetworkProxy ())
instance QqNetworkProxy_nf (()) where
qNetworkProxy_nf ()
= withObjectRefResult $
qtc_QNetworkProxy
instance QqNetworkProxy_nf ((QNetworkProxy t1)) where
qNetworkProxy_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QNetworkProxy1 cobj_x1
instance QqNetworkProxy_nf ((ProxyType)) where
qNetworkProxy_nf (x1)
= withObjectRefResult $
qtc_QNetworkProxy2 (toCLong $ qEnum_toInt x1)
instance QqNetworkProxy_nf ((ProxyType, String)) where
qNetworkProxy_nf (x1, x2)
= withObjectRefResult $
withCWString x2 $ \cstr_x2 ->
qtc_QNetworkProxy3 (toCLong $ qEnum_toInt x1) cstr_x2
instance QqNetworkProxy_nf ((ProxyType, String, Int)) where
qNetworkProxy_nf (x1, x2, x3)
= withObjectRefResult $
withCWString x2 $ \cstr_x2 ->
qtc_QNetworkProxy4 (toCLong $ qEnum_toInt x1) cstr_x2 (toCUShort x3)
instance QqNetworkProxy_nf ((ProxyType, String, Int, String)) where
qNetworkProxy_nf (x1, x2, x3, x4)
= withObjectRefResult $
withCWString x2 $ \cstr_x2 ->
withCWString x4 $ \cstr_x4 ->
qtc_QNetworkProxy5 (toCLong $ qEnum_toInt x1) cstr_x2 (toCUShort x3) cstr_x4
instance QqNetworkProxy_nf ((ProxyType, String, Int, String, String)) where
qNetworkProxy_nf (x1, x2, x3, x4, x5)
= withObjectRefResult $
withCWString x2 $ \cstr_x2 ->
withCWString x4 $ \cstr_x4 ->
withCWString x5 $ \cstr_x5 ->
qtc_QNetworkProxy6 (toCLong $ qEnum_toInt x1) cstr_x2 (toCUShort x3) cstr_x4 cstr_x5
qNetworkProxyApplicationProxy :: (()) -> IO (QNetworkProxy ())
qNetworkProxyApplicationProxy ()
= withQNetworkProxyResult $
qtc_QNetworkProxy_applicationProxy
foreign import ccall "qtc_QNetworkProxy_applicationProxy" qtc_QNetworkProxy_applicationProxy :: IO (Ptr (TQNetworkProxy ()))
instance QhostName (QNetworkProxy a) (()) where
hostName x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QNetworkProxy_hostName cobj_x0
foreign import ccall "qtc_QNetworkProxy_hostName" qtc_QNetworkProxy_hostName :: Ptr (TQNetworkProxy a) -> IO (Ptr (TQString ()))
instance Qpassword (QNetworkProxy a) (()) where
password x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QNetworkProxy_password cobj_x0
foreign import ccall "qtc_QNetworkProxy_password" qtc_QNetworkProxy_password :: Ptr (TQNetworkProxy a) -> IO (Ptr (TQString ()))
instance Qport (QNetworkProxy a) (()) where
port x0 ()
= withUnsignedShortResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QNetworkProxy_port cobj_x0
foreign import ccall "qtc_QNetworkProxy_port" qtc_QNetworkProxy_port :: Ptr (TQNetworkProxy a) -> IO CUShort
qNetworkProxySetApplicationProxy :: ((QNetworkProxy t1)) -> IO ()
qNetworkProxySetApplicationProxy (x1)
= withObjectPtr x1 $ \cobj_x1 ->
qtc_QNetworkProxy_setApplicationProxy cobj_x1
foreign import ccall "qtc_QNetworkProxy_setApplicationProxy" qtc_QNetworkProxy_setApplicationProxy :: Ptr (TQNetworkProxy t1) -> IO ()
instance QsetHostName (QNetworkProxy a) ((String)) where
setHostName x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QNetworkProxy_setHostName cobj_x0 cstr_x1
foreign import ccall "qtc_QNetworkProxy_setHostName" qtc_QNetworkProxy_setHostName :: Ptr (TQNetworkProxy a) -> CWString -> IO ()
instance QsetPassword (QNetworkProxy a) ((String)) where
setPassword x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QNetworkProxy_setPassword cobj_x0 cstr_x1
foreign import ccall "qtc_QNetworkProxy_setPassword" qtc_QNetworkProxy_setPassword :: Ptr (TQNetworkProxy a) -> CWString -> IO ()
instance QsetPort (QNetworkProxy a) ((Int)) where
setPort x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QNetworkProxy_setPort cobj_x0 (toCUShort x1)
foreign import ccall "qtc_QNetworkProxy_setPort" qtc_QNetworkProxy_setPort :: Ptr (TQNetworkProxy a) -> CUShort -> IO ()
instance QsetType (QNetworkProxy a) ((ProxyType)) where
setType x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QNetworkProxy_setType cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QNetworkProxy_setType" qtc_QNetworkProxy_setType :: Ptr (TQNetworkProxy a) -> CLong -> IO ()
instance QsetUser (QNetworkProxy a) ((String)) (IO ()) where
setUser x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QNetworkProxy_setUser cobj_x0 cstr_x1
foreign import ccall "qtc_QNetworkProxy_setUser" qtc_QNetworkProxy_setUser :: Ptr (TQNetworkProxy a) -> CWString -> IO ()
instance Qqtype (QNetworkProxy a) (()) (IO (ProxyType)) where
qtype x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QNetworkProxy_type cobj_x0
foreign import ccall "qtc_QNetworkProxy_type" qtc_QNetworkProxy_type :: Ptr (TQNetworkProxy a) -> IO CLong
user :: QNetworkProxy a -> (()) -> IO (String)
user x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QNetworkProxy_user cobj_x0
foreign import ccall "qtc_QNetworkProxy_user" qtc_QNetworkProxy_user :: Ptr (TQNetworkProxy a) -> IO (Ptr (TQString ()))
qNetworkProxy_delete :: QNetworkProxy a -> IO ()
qNetworkProxy_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QNetworkProxy_delete cobj_x0
foreign import ccall "qtc_QNetworkProxy_delete" qtc_QNetworkProxy_delete :: Ptr (TQNetworkProxy a) -> IO ()
|
uduki/hsQt
|
Qtc/Network/QNetworkProxy.hs
|
bsd-2-clause
| 8,624 | 0 | 16 | 1,342 | 2,534 | 1,326 | 1,208 | -1 | -1 |
module OpenRTB.Types.BidRequest.Imp.Pmp.Deal where
import Prelude hiding (id)
import Data.Aeson
import Data.Text
import Data.Word
-- | This object constitutes a specific deal that was struck *a priori* between
-- a buyer and a seller. Its presence with the `Pmp` collection indicates
-- that this impression is available under the terms of that deal. Refer to
-- Section 7.2 for more details.
data Deal = Deal
{
-- | A unique identifier for the direct deal.
id :: Text
-- | Minimum bid for this impression expressed in CPM.
, bidFloor :: Double
-- | Currency specified using ISO-4217 alpha codes. This may be different
-- from bid currency returned by bidder if this is allowed by the
-- exchange.
, bidFloorCur :: Text
-- | Optional override of the overall auction type of the bid request, where
-- 1 = First Price, 2 = Second Price Plus, 3 = the value passed in
-- `bidFloor` is the agreed upon deal price. Additional auction type
-- can be defined by the exchange.
, at :: Maybe Word16
-- | Whitelist of buyer seats allowed to bid on this deal. Seat IDs must be
-- communicated between bidders and the exchange *a priori*. Omission
-- implies no seat restictions
, wSeat :: Maybe [Text]
-- | Array of advertiser domains (e.g., advertiser.com) allowed to bid on
-- this deal. Omission implies no advertiser restrictions.
, wADomain :: Maybe [Text]
-- | Placeholder for exchange-specfic extensions to OpenRTB.
, ext :: Maybe Value
}
|
ankhers/openRTB-hs
|
src/OpenRTB/Types/BidRequest/Imp/Pmp/Deal.hs
|
bsd-3-clause
| 1,545 | 0 | 10 | 361 | 122 | 83 | 39 | 13 | 0 |
module Codegen where
import qualified LLVM.General.AST as A
import qualified LLVM.General.AST.Type as T
import qualified LLVM.General.AST.Float as F
import qualified LLVM.General.AST.Constant as C
import qualified LLVM.General.AST.Instruction as I
import qualified LLVM.General.AST.CallingConvention as CC
import qualified LLVM.General.AST.AddrSpace as AddrSpace
import qualified LLVM.General.AST.Global as G
import Control.Monad.State
import Data.Maybe
import Data.Word
import qualified Data.List as List
import qualified Data.Map as Map
import Debug.Trace
import Scope
import AST
import Analyzer
import Type
structPtrSize :: Word32
structPtrSize = 32
alignment :: Word32
alignment = 0
addrSpace :: AddrSpace.AddrSpace
addrSpace = AddrSpace.AddrSpace 0
data CodegenState
= CodegenState
{ csProgram :: Maybe Program
, csScope :: Scope (Type, A.Operand)
, csClass :: Maybe Class
, csMethod :: Maybe Method
, lastInd :: Word
, instructions :: [A.Named I.Instruction]
, structSizes :: Map.Map ObjectType A.Operand
, lastLabel :: Word
, loops :: [(A.Name, A.Name)]
} deriving Show
defaultCodegenState :: CodegenState
defaultCodegenState = CodegenState
{ csProgram = Nothing
, csScope = []
, csClass = Nothing
, csMethod = Nothing
, lastInd = -1
, instructions = []
, structSizes = Map.empty
, lastLabel = 0
, loops = []
}
instance Scoped CodegenState (Type, A.Operand) where
getScope = csScope
setScope cs s = cs { csScope = s }
instance WithProgram CodegenState where
getProgram = fromJust . csProgram
instance WithClass CodegenState where
getClass = fromJust . csClass
instance WithMethod CodegenState where
getMethod = fromJust . csMethod
type Codegen a = State CodegenState a
addLoop :: (A.Name, A.Name) -> Codegen ()
addLoop n = modify $ \s -> s { loops = n : loops s }
removeLoop :: Codegen ()
removeLoop = modify $ \s -> s { loops = tail . loops $ s }
lastLoopEnd :: Codegen A.Name
lastLoopEnd = gets $ snd . head . loops
lastLoopNext :: Codegen A.Name
lastLoopNext = gets $ fst . head . loops
mapPrimaryType :: PrimaryType -> T.Type
mapPrimaryType TBoolean = T.IntegerType 1
mapPrimaryType TByte = T.IntegerType 8
mapPrimaryType TShort = T.IntegerType 16
mapPrimaryType TInt = T.IntegerType 32
mapPrimaryType TLong = T.IntegerType 64
mapPrimaryType TFloat = T.FloatingPointType 32 T.IEEE
mapPrimaryType TDouble = T.FloatingPointType 64 T.IEEE
literalToOp :: Literal -> A.Operand
literalToOp l = A.ConstantOperand $ f l
where
f (LBoolean False) = C.Int 1 0
f (LBoolean True) = C.Int 1 1
f (LByte i) = C.Int 8 $ toInteger i
f (LShort i) = C.Int 16 $ toInteger i
f (LInt i) = C.Int 32 $ toInteger i
f (LLong i) = C.Int 64 $ toInteger i
f (LFloat i) = C.Float $ F.Single i
f (LDouble i) = C.Float $ F.Double i
nullPrimaryValue :: PrimaryType -> Literal
nullPrimaryValue TBoolean = LBoolean False
nullPrimaryValue TByte = LByte 0
nullPrimaryValue TShort = LShort 0
nullPrimaryValue TInt = LInt 0
nullPrimaryValue TLong = LLong 0
nullPrimaryValue TFloat = LFloat 0.0
nullPrimaryValue TDouble = LDouble 0.0
nullValue :: Type -> Expression
nullValue (ObjectType _) = Expr Null 0
nullValue (PrimaryType pt) = Expr (Literal $ nullPrimaryValue pt) 0
nullValue NullType = error "null value"
mapType :: Type -> T.Type
mapType (PrimaryType t) = mapPrimaryType t
mapType (ObjectType t) = getPointerType . T.NamedTypeReference . A.Name $ t
mapType NullType = error "mapType"
mapMethodType :: Class -> MethodType -> T.Type
mapMethodType _ (ReturnType t) = mapType t
mapMethodType _ Void = T.VoidType
mapMethodType cls Constructor = getPointerType . A.NamedTypeReference . A.Name . className $ cls
nextName :: Codegen A.Name
nextName = do
i <- gets lastInd
let i' = i + 1
modify $ \s -> s { lastInd = i' }
return $ A.UnName i'
addNamedInstr :: A.Name -> I.Instruction -> Codegen A.Operand
addNamedInstr n instr = do
modify $ \s -> s { instructions = instructions s ++ [n A.:= instr] }
return $ A.LocalReference n
addInstr :: I.Instruction -> Codegen A.Operand
addInstr instr = do
n <- nextName
addNamedInstr n instr
addVoidInstr :: I.Instruction -> Codegen ()
addVoidInstr instr = modify $ \s -> s { instructions = instructions s ++ [A.Do instr] }
fromRight :: String -> Either a b -> b
fromRight _ (Right b) = b
fromRight err (Left _) = error $ "fromRight " ++ err
objType :: Type -> ObjectType
objType (ObjectType t) = t
objType _ = error "objType"
getPointerType :: T.Type -> T.Type
getPointerType t = T.PointerType t addrSpace
structFieldAddr :: Int -> A.Operand
structFieldAddr i = A.ConstantOperand . C.Int structPtrSize $ toInteger i
nullConstant :: ObjectType -> A.Operand
nullConstant t = A.ConstantOperand $ C.Null $ mapType $ ObjectType t
oneOp :: Type -> A.Operand
oneOp (PrimaryType t) = f t
where
f TByte = literalToOp $ LByte 1
f TShort = literalToOp $ LShort 1
f TInt = literalToOp $ LInt 1
f TLong = literalToOp $ LLong 1
f _ = error "typed one"
oneOp _ = error "typed one"
load :: A.Operand -> Codegen A.Operand
load ptr = addInstr $ I.Load False ptr Nothing alignment []
store :: A.Operand -> A.Operand -> Codegen ()
store ptr val = addVoidInstr $ I.Store False ptr val Nothing alignment []
call :: String -> [A.Operand] -> I.Instruction
call name params = I.Call False CC.C [] (Right . A.ConstantOperand . C.GlobalReference . A.Name $ name) (map (\s -> (s, [])) params) [] []
genMethodName :: ObjectType -> Method -> String
genMethodName obj mth = List.intercalate "$" $ obj : (show . methodType $ mth) : methodName mth : map (show . paramType) (methodParams mth)
sizeof :: ObjectType -> Codegen A.Operand
sizeof n = do
s' <- addInstr $ I.GetElementPtr False (nullConstant n) [oneOp $ PrimaryType TInt] []
addInstr $ I.PtrToInt s' (T.IntegerType structPtrSize) []
new :: ObjectType -> Codegen A.Operand
new obj = do
size <- sizeof obj
ptr <- addInstr $ call "malloc" [size]
addInstr $ I.BitCast ptr (getPointerType . A.NamedTypeReference . A.Name $ obj) []
alloca :: T.Type -> I.Instruction
alloca t = I.Alloca t Nothing alignment []
nextLabel :: String -> Codegen A.Name
nextLabel l = do
i' <- gets lastLabel
let i = i' + 1
modify $ \s -> s { lastLabel = i }
return $ A.Name $ l ++ "." ++ show i
popInstructions :: Codegen [A.Named I.Instruction]
popInstructions = do
i <- gets instructions
modify $ \s -> s { instructions = [] }
return i
getBBName :: A.BasicBlock -> A.Name
getBBName (A.BasicBlock name _ _) = name
emptyBlock :: A.Name -> I.Terminator -> A.BasicBlock
emptyBlock n t = A.BasicBlock n [] $ A.Do t
brBlock :: A.Name -> A.Name -> [A.Named I.Instruction] -> A.BasicBlock
brBlock name next instr = A.BasicBlock name instr $ I.Do $ I.Br next []
toList :: a -> [a]
toList a = [a]
genBrBlock :: A.Name -> [A.Named I.Instruction] -> A.Name -> [A.BasicBlock]
genBrBlock n instr finBlockName = [brBlock n finBlockName instr]
genParam :: Parameter -> Codegen ()
genParam (Parameter t n) = do
ptr <- addInstr $ alloca . mapType $ t
store ptr $ A.LocalReference $ A.Name n
void $ newLocalVar n (t, ptr)
genParams :: [Parameter] -> Codegen ()
genParams params = forM_ params genParam
mapParam :: Parameter -> G.Parameter
mapParam (Parameter t n) = G.Parameter (mapType t) (A.Name n) []
genStruct :: Class -> A.Definition
genStruct (Class name fields _) = A.TypeDefinition (A.Name name) $
Just $ T.StructureType False $ map (mapType . varType) fields
genMethodDefinition :: Class -> Method -> [A.BasicBlock] -> A.Definition
genMethodDefinition cls mth@(Method mt _ mp _) mthBlocks = A.GlobalDefinition G.functionDefaults
{ G.returnType = mapMethodType cls mt
, G.name = A.Name $ genMethodName (className cls) mth
, G.parameters = (map mapParam params, False)
, G.basicBlocks = mthBlocks
}
where
params = Parameter (ObjectType . className $ cls) "this" : mp
|
ademinn/JavaWithClasses
|
src/Codegen.hs
|
bsd-3-clause
| 8,084 | 0 | 13 | 1,677 | 3,065 | 1,580 | 1,485 | -1 | -1 |
module EC2Tests.PlacementGroupTests
( runPlacementGroupTests
)
where
import Data.Text (Text)
import Test.Hspec
import qualified Control.Exception.Lifted as E
import Cloud.AWS.EC2
import Cloud.AWS.EC2.Types (PlacementGroupStrategy(..))
import Util
import EC2Tests.Util
region :: Text
region = "us-east-1"
runPlacementGroupTests :: IO ()
runPlacementGroupTests = do
hspec describePlacementGroupsTest
hspec createAndDeletePlacementGroupTest
describePlacementGroupsTest :: Spec
describePlacementGroupsTest = do
describe "describePlacementGroups doesn't fail" $ do
it "describeInstances doesn't throw any exception" $ do
testEC2 region (describePlacementGroups [] []) `miss` anyConnectionException
createAndDeletePlacementGroupTest :: Spec
createAndDeletePlacementGroupTest = do
describe "{create,delete}PlacementGroup doesn't fail" $ do
it "{create,delete}PlacementGroup doesn't throw any exception" $ do
testEC2' region (E.finally
(createPlacementGroup groupName PlacementGroupStrategyCluster)
(deletePlacementGroup groupName)
) `miss` anyConnectionException
where
groupName = "createAndDeletePlacementGroupTest"
|
worksap-ate/aws-sdk
|
test/EC2Tests/PlacementGroupTests.hs
|
bsd-3-clause
| 1,236 | 0 | 18 | 230 | 233 | 125 | 108 | 29 | 1 |
module Blog.JSON
()
where
-- Extern
import Text.JSON
import Database.CouchDB.JSON ( jsonField
, jsonObject
, jsonString
)
import Text.JSON.Generic
import Text.Pandoc
-- Intern
import Blog.Definition
import Blog.Auxiliary (dropOK)
import Auxiliary (firstUp)
instance JSON (BlogEntry) where
showJSON x = JSObject $ toJSObject [ ("MetaData", JSArray $ map showJSON meta)
-- , ("Posting", showJSON post)
, ("Posting", toJSON_generic post)
]
where (Entry meta post) = x
readJSON x = Ok $ Entry meta post
where meta = peel x "MetaData"
post = peel x "Posting"
instance JSON (Pandoc) where
showJSON = toJSON_generic
readJSON = fromJSON_generic
instance JSON (MetaData) where
showJSON (Subject x) = JSObject $ toJSObject [ ("Subject", JSString $ toJSString $ x) ]
showJSON (Date x) = JSObject $ toJSObject [ ("Date", JSString $ toJSString $ x) ]
showJSON (To x) = JSObject $ toJSObject [ ("To", JSArray $ map (JSString . toJSString) $ (firstUp x)) ]
showJSON (From x) = JSObject $ toJSObject [ ("From", JSString $ toJSString $ x) ]
readJSON x = Ok $ case (fst.head $ jsObj) of
"Subject" -> Subject (fromOK.readJSON.snd.head $ jsObj)
"Date" -> Date (fromOK.readJSON.snd.head $ jsObj)
"To" -> To (map (fromOK.jsonString) ((fromOK.readJSONs.snd.head $ jsObj) :: [JSValue]))
"From" -> From (fromOK.readJSON.snd.head $ jsObj)
where jsObj = fromOK.jsonObject $ x
fromOK (Ok x) = x
fromOK (Error x) = error x
-- instance JSON (BlogText) where
-- showJSON (PureT x) = JSObject $ toJSObject [ ("PureT", JSString $ toJSString $ x) ]
-- showJSON (PureC x) = JSObject $ toJSObject [ ("PureC", showJSON x) ]
-- showJSON (MixT x y) = JSObject $ toJSObject [ ("MixT", JSArray [ JSString $ toJSString $ x, showJSON y] ) ]
-- showJSON (MixC x y) = JSObject $ toJSObject [ ("MixC", JSArray [ showJSON x, showJSON y ] ) ]
-- showJSON (Empty) = JSObject $ toJSObject [ ("Empty", JSNull) ]
-- readJSON x = Ok $ case (fst.head $ jsObj) of
-- "PureT" -> PureT (fromOK.readJSON.snd.head $ jsObj)
-- "PureC" -> PureC (fromOK.readJSON.snd.head $ jsObj)
-- "MixT" -> MixT (fromOK.jsonString.head.fromOK.readJSONs.snd.head $ jsObj) (fromOK.readJSON.head.(drop 1).fromOK.readJSONs.snd.head $ jsObj)
-- "MixC" -> MixC (fromOK.readJSON.head.fromOK.readJSONs.snd.head $ jsObj) (fromOK.readJSON.head.(drop 1).fromOK.readJSONs.snd.head $ jsObj)
-- "Empty" -> Empty
-- where jsObj = fromOK.jsonObject $ x
-- fromOK (Ok x) = x
-- fromOK (Error x) = error x
-- instance JSON (Command) where
-- showJSON (Break) = JSObject $ toJSObject [ ("Break", JSNull) ]
-- showJSON (Block x) = JSObject $ toJSObject [ ("Block", showJSON x) ]
-- showJSON (Bold x) = JSObject $ toJSObject [ ("Bold", showJSON x) ]
-- showJSON (Italic x) = JSObject $ toJSObject [ ("Italic", showJSON x) ]
-- showJSON (Underline x) = JSObject $ toJSObject [ ("Underline", showJSON x) ]
-- showJSON (Strike x) = JSObject $ toJSObject [ ("Strike", showJSON x) ]
-- showJSON (Section x) = JSObject $ toJSObject [ ("Section", showJSON x) ]
-- showJSON (Link x y ) = JSObject $ toJSObject [ ("Link", JSArray [ showJSON x, showJSON y ] ) ]
-- showJSON (CommandBlock x) = JSObject $ toJSObject [ ("CommandBlock", showJSON x) ]
-- showJSON (Code x) = JSObject $ toJSObject [ ("Code", showJSON x) ]
-- showJSON (Itemize x) = JSObject $ toJSObject [ ("Itemize", showJSON x) ]
-- showJSON (None) = JSObject $ toJSObject [ ("None", JSNull) ]
-- readJSON x = Ok $ case (fst.head $ jsObj) of
-- "Break" -> Break
-- "Block" -> Block (fromOK.readJSON.snd.head $ jsObj)
-- "Bold" -> Bold (fromOK.readJSON.snd.head $ jsObj)
-- "Italic" -> Italic (fromOK.readJSON.snd.head $ jsObj)
-- "Underline" -> Underline (fromOK.readJSON.snd.head $ jsObj)
-- "Strike" -> Strike (fromOK.readJSON.snd.head $ jsObj)
-- "Section" -> Section (fromOK.readJSON.snd.head $ jsObj)
-- "Link" -> Link (fromOK.jsonString.head.fromOK.readJSONs.snd.head $ jsObj) (fromOK.readJSON.head.(drop 1).fromOK.readJSONs.snd.head $ jsObj)
-- "CommandBlock" -> CommandBlock (map (fromOK.readJSON) (fromOK.readJSONs.snd.head $ jsObj))
-- "Code" -> Code (fromOK.readJSON.snd.head $ jsObj)
-- "Itemize" -> Itemize (map (fromOK.readJSON) (fromOK.readJSONs.snd.head $ jsObj))
-- "None" -> None
-- where jsObj = fromOK.jsonObject $ x
-- fromOK (Ok x) = x
-- fromOK (Error x) = error x
peel js key = (fromOK.(jsonField key)) $ fromOK.jsonObject $ js
where fromOK (Ok x) = x
fromOK (Error x) = error x
|
frosch03/frogblog
|
Blog/JSON.hs
|
bsd-3-clause
| 5,741 | 1 | 18 | 2,058 | 668 | 376 | 292 | 37 | 2 |
module BS where
import qualified Data.Text.IO as TIO
import qualified Data.Text.Encoding as TE
import qualified Data.ByteString.Lazy as BL
import qualified Codec.Compression.GZip as GZip
input :: BL.ByteString
input = "123"
compressed :: BL.ByteString
compressed = GZip.compress input
main :: IO ()
main = do
TIO.putStrLn $ TE.decodeUtf8 (BL.toStrict input)
TIO.putStrLn $ TE.decodeUtf8 (BL.toStrict compressed)
|
chengzh2008/hpffp
|
src/ch28-BasicLibraries/bytestring.hs
|
bsd-3-clause
| 420 | 0 | 11 | 61 | 128 | 75 | 53 | 13 | 1 |
{-# LANGUAGE CPP, DeriveDataTypeable, StandaloneDeriving #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Version
-- Copyright : Isaac Jones, Simon Marlow 2003-2004
-- Duncan Coutts 2008
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- Exports the 'Version' type along with a parser and pretty printer. A version
-- is something like @\"1.3.3\"@. It also defines the 'VersionRange' data
-- types. Version ranges are like @\">= 1.2 && < 2\"@.
{- Copyright (c) 2003-2004, Isaac Jones
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Isaac Jones nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -}
module Distribution.Version (
-- * Package versions
Version(..),
-- * Version ranges
VersionRange(..),
-- ** Constructing
anyVersion, noVersion,
thisVersion, notThisVersion,
laterVersion, earlierVersion,
orLaterVersion, orEarlierVersion,
unionVersionRanges, intersectVersionRanges,
withinVersion,
betweenVersionsInclusive,
-- ** Inspection
withinRange,
isAnyVersion,
isNoVersion,
isSpecificVersion,
simplifyVersionRange,
foldVersionRange,
foldVersionRange',
-- ** Modification
removeUpperBound,
-- * Version intervals view
asVersionIntervals,
VersionInterval,
LowerBound(..),
UpperBound(..),
Bound(..),
-- ** 'VersionIntervals' abstract type
-- | The 'VersionIntervals' type and the accompanying functions are exposed
-- primarily for completeness and testing purposes. In practice
-- 'asVersionIntervals' is the main function to use to
-- view a 'VersionRange' as a bunch of 'VersionInterval's.
--
VersionIntervals,
toVersionIntervals,
fromVersionIntervals,
withinIntervals,
versionIntervals,
mkVersionIntervals,
unionVersionIntervals,
intersectVersionIntervals,
) where
import Data.Data ( Data )
import Data.Typeable ( Typeable )
import Data.Version ( Version(..) )
import Distribution.Text ( Text(..) )
import qualified Distribution.Compat.ReadP as Parse
import Distribution.Compat.ReadP ((+++))
import qualified Text.PrettyPrint as Disp
import Text.PrettyPrint ((<>), (<+>))
import qualified Data.Char as Char (isDigit)
import Control.Exception (assert)
-- -----------------------------------------------------------------------------
-- Version ranges
-- Todo: maybe move this to Distribution.Package.Version?
-- (package-specific versioning scheme).
data VersionRange
= AnyVersion
| ThisVersion Version -- = version
| LaterVersion Version -- > version (NB. not >=)
| EarlierVersion Version -- < version
| WildcardVersion Version -- == ver.* (same as >= ver && < ver+1)
| UnionVersionRanges VersionRange VersionRange
| IntersectVersionRanges VersionRange VersionRange
| VersionRangeParens VersionRange -- just '(exp)' parentheses syntax
deriving (Show,Read,Eq,Typeable,Data)
#if __GLASGOW_HASKELL__ < 707
-- starting with ghc-7.7/base-4.7 this instance is provided in "Data.Data"
deriving instance Data Version
#endif
{-# DEPRECATED AnyVersion "Use 'anyVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED ThisVersion "use 'thisVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED LaterVersion "use 'laterVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED EarlierVersion "use 'earlierVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED WildcardVersion "use 'anyVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED UnionVersionRanges "use 'unionVersionRanges', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED IntersectVersionRanges "use 'intersectVersionRanges', 'foldVersionRange' or 'asVersionIntervals'" #-}
-- | The version range @-any@. That is, a version range containing all
-- versions.
--
-- > withinRange v anyVersion = True
--
anyVersion :: VersionRange
anyVersion = AnyVersion
-- | The empty version range, that is a version range containing no versions.
--
-- This can be constructed using any unsatisfiable version range expression,
-- for example @> 1 && < 1@.
--
-- > withinRange v anyVersion = False
--
noVersion :: VersionRange
noVersion = IntersectVersionRanges (LaterVersion v) (EarlierVersion v)
where v = Version [1] []
-- | The version range @== v@
--
-- > withinRange v' (thisVersion v) = v' == v
--
thisVersion :: Version -> VersionRange
thisVersion = ThisVersion
-- | The version range @< v || > v@
--
-- > withinRange v' (notThisVersion v) = v' /= v
--
notThisVersion :: Version -> VersionRange
notThisVersion v = UnionVersionRanges (EarlierVersion v) (LaterVersion v)
-- | The version range @> v@
--
-- > withinRange v' (laterVersion v) = v' > v
--
laterVersion :: Version -> VersionRange
laterVersion = LaterVersion
-- | The version range @>= v@
--
-- > withinRange v' (orLaterVersion v) = v' >= v
--
orLaterVersion :: Version -> VersionRange
orLaterVersion v = UnionVersionRanges (ThisVersion v) (LaterVersion v)
-- | The version range @< v@
--
-- > withinRange v' (earlierVersion v) = v' < v
--
earlierVersion :: Version -> VersionRange
earlierVersion = EarlierVersion
-- | The version range @<= v@
--
-- > withinRange v' (orEarlierVersion v) = v' <= v
--
orEarlierVersion :: Version -> VersionRange
orEarlierVersion v = UnionVersionRanges (ThisVersion v) (EarlierVersion v)
-- | The version range @vr1 || vr2@
--
-- > withinRange v' (unionVersionRanges vr1 vr2)
-- > = withinRange v' vr1 || withinRange v' vr2
--
unionVersionRanges :: VersionRange -> VersionRange -> VersionRange
unionVersionRanges = UnionVersionRanges
-- | The version range @vr1 && vr2@
--
-- > withinRange v' (intersectVersionRanges vr1 vr2)
-- > = withinRange v' vr1 && withinRange v' vr2
--
intersectVersionRanges :: VersionRange -> VersionRange -> VersionRange
intersectVersionRanges = IntersectVersionRanges
-- | The version range @== v.*@.
--
-- For example, for version @1.2@, the version range @== 1.2.*@ is the same as
-- @>= 1.2 && < 1.3@
--
-- > withinRange v' (laterVersion v) = v' >= v && v' < upper v
-- > where
-- > upper (Version lower t) = Version (init lower ++ [last lower + 1]) t
--
withinVersion :: Version -> VersionRange
withinVersion = WildcardVersion
-- | The version range @>= v1 && <= v2@.
--
-- In practice this is not very useful because we normally use inclusive lower
-- bounds and exclusive upper bounds.
--
-- > withinRange v' (laterVersion v) = v' > v
--
betweenVersionsInclusive :: Version -> Version -> VersionRange
betweenVersionsInclusive v1 v2 =
IntersectVersionRanges (orLaterVersion v1) (orEarlierVersion v2)
{-# DEPRECATED betweenVersionsInclusive
"In practice this is not very useful because we normally use inclusive lower bounds and exclusive upper bounds" #-}
-- | Given a version range, remove the highest upper bound. Example: @(>= 1 && <
-- 3) || (>= 4 && < 5)@ is converted to @(>= 1 && < 3) || (>= 4)@.
removeUpperBound :: VersionRange -> VersionRange
removeUpperBound = fromVersionIntervals . relaxLastInterval . toVersionIntervals
where
relaxLastInterval (VersionIntervals intervals) =
VersionIntervals (relaxLastInterval' intervals)
relaxLastInterval' [] = []
relaxLastInterval' [(l,_)] = [(l, NoUpperBound)]
relaxLastInterval' (i:is) = i : relaxLastInterval' is
-- | Fold over the basic syntactic structure of a 'VersionRange'.
--
-- This provides a syntacic view of the expression defining the version range.
-- The syntactic sugar @\">= v\"@, @\"<= v\"@ and @\"== v.*\"@ is presented
-- in terms of the other basic syntax.
--
-- For a semantic view use 'asVersionIntervals'.
--
foldVersionRange :: a -- ^ @\"-any\"@ version
-> (Version -> a) -- ^ @\"== v\"@
-> (Version -> a) -- ^ @\"> v\"@
-> (Version -> a) -- ^ @\"< v\"@
-> (a -> a -> a) -- ^ @\"_ || _\"@ union
-> (a -> a -> a) -- ^ @\"_ && _\"@ intersection
-> VersionRange -> a
foldVersionRange anyv this later earlier union intersect = fold
where
fold AnyVersion = anyv
fold (ThisVersion v) = this v
fold (LaterVersion v) = later v
fold (EarlierVersion v) = earlier v
fold (WildcardVersion v) = fold (wildcard v)
fold (UnionVersionRanges v1 v2) = union (fold v1) (fold v2)
fold (IntersectVersionRanges v1 v2) = intersect (fold v1) (fold v2)
fold (VersionRangeParens v) = fold v
wildcard v = intersectVersionRanges
(orLaterVersion v)
(earlierVersion (wildcardUpperBound v))
-- | An extended variant of 'foldVersionRange' that also provides a view of
-- in which the syntactic sugar @\">= v\"@, @\"<= v\"@ and @\"== v.*\"@ is presented
-- explicitly rather than in terms of the other basic syntax.
--
foldVersionRange' :: a -- ^ @\"-any\"@ version
-> (Version -> a) -- ^ @\"== v\"@
-> (Version -> a) -- ^ @\"> v\"@
-> (Version -> a) -- ^ @\"< v\"@
-> (Version -> a) -- ^ @\">= v\"@
-> (Version -> a) -- ^ @\"<= v\"@
-> (Version -> Version -> a) -- ^ @\"== v.*\"@ wildcard. The
-- function is passed the
-- inclusive lower bound and the
-- exclusive upper bounds of the
-- range defined by the wildcard.
-> (a -> a -> a) -- ^ @\"_ || _\"@ union
-> (a -> a -> a) -- ^ @\"_ && _\"@ intersection
-> (a -> a) -- ^ @\"(_)\"@ parentheses
-> VersionRange -> a
foldVersionRange' anyv this later earlier orLater orEarlier
wildcard union intersect parens = fold
where
fold AnyVersion = anyv
fold (ThisVersion v) = this v
fold (LaterVersion v) = later v
fold (EarlierVersion v) = earlier v
fold (UnionVersionRanges (ThisVersion v)
(LaterVersion v')) | v==v' = orLater v
fold (UnionVersionRanges (LaterVersion v)
(ThisVersion v')) | v==v' = orLater v
fold (UnionVersionRanges (ThisVersion v)
(EarlierVersion v')) | v==v' = orEarlier v
fold (UnionVersionRanges (EarlierVersion v)
(ThisVersion v')) | v==v' = orEarlier v
fold (WildcardVersion v) = wildcard v (wildcardUpperBound v)
fold (UnionVersionRanges v1 v2) = union (fold v1) (fold v2)
fold (IntersectVersionRanges v1 v2) = intersect (fold v1) (fold v2)
fold (VersionRangeParens v) = parens (fold v)
-- | Does this version fall within the given range?
--
-- This is the evaluation function for the 'VersionRange' type.
--
withinRange :: Version -> VersionRange -> Bool
withinRange v = foldVersionRange
True
(\v' -> versionBranch v == versionBranch v')
(\v' -> versionBranch v > versionBranch v')
(\v' -> versionBranch v < versionBranch v')
(||)
(&&)
-- | View a 'VersionRange' as a union of intervals.
--
-- This provides a canonical view of the semantics of a 'VersionRange' as
-- opposed to the syntax of the expression used to define it. For the syntactic
-- view use 'foldVersionRange'.
--
-- Each interval is non-empty. The sequence is in increasing order and no
-- intervals overlap or touch. Therefore only the first and last can be
-- unbounded. The sequence can be empty if the range is empty
-- (e.g. a range expression like @< 1 && > 2@).
--
-- Other checks are trivial to implement using this view. For example:
--
-- > isNoVersion vr | [] <- asVersionIntervals vr = True
-- > | otherwise = False
--
-- > isSpecificVersion vr
-- > | [(LowerBound v InclusiveBound
-- > ,UpperBound v' InclusiveBound)] <- asVersionIntervals vr
-- > , v == v' = Just v
-- > | otherwise = Nothing
--
asVersionIntervals :: VersionRange -> [VersionInterval]
asVersionIntervals = versionIntervals . toVersionIntervals
-- | Does this 'VersionRange' place any restriction on the 'Version' or is it
-- in fact equivalent to 'AnyVersion'.
--
-- Note this is a semantic check, not simply a syntactic check. So for example
-- the following is @True@ (for all @v@).
--
-- > isAnyVersion (EarlierVersion v `UnionVersionRanges` orLaterVersion v)
--
isAnyVersion :: VersionRange -> Bool
isAnyVersion vr = case asVersionIntervals vr of
[(LowerBound v InclusiveBound, NoUpperBound)] | isVersion0 v -> True
_ -> False
-- | This is the converse of 'isAnyVersion'. It check if the version range is
-- empty, if there is no possible version that satisfies the version range.
--
-- For example this is @True@ (for all @v@):
--
-- > isNoVersion (EarlierVersion v `IntersectVersionRanges` LaterVersion v)
--
isNoVersion :: VersionRange -> Bool
isNoVersion vr = case asVersionIntervals vr of
[] -> True
_ -> False
-- | Is this version range in fact just a specific version?
--
-- For example the version range @\">= 3 && <= 3\"@ contains only the version
-- @3@.
--
isSpecificVersion :: VersionRange -> Maybe Version
isSpecificVersion vr = case asVersionIntervals vr of
[(LowerBound v InclusiveBound
,UpperBound v' InclusiveBound)]
| v == v' -> Just v
_ -> Nothing
-- | Simplify a 'VersionRange' expression. For non-empty version ranges
-- this produces a canonical form. Empty or inconsistent version ranges
-- are left as-is because that provides more information.
--
-- If you need a canonical form use
-- @fromVersionIntervals . toVersionIntervals@
--
-- It satisfies the following properties:
--
-- > withinRange v (simplifyVersionRange r) = withinRange v r
--
-- > withinRange v r = withinRange v r'
-- > ==> simplifyVersionRange r = simplifyVersionRange r'
-- > || isNoVersion r
-- > || isNoVersion r'
--
simplifyVersionRange :: VersionRange -> VersionRange
simplifyVersionRange vr
-- If the version range is inconsistent then we just return the
-- original since that has more information than ">1 && < 1", which
-- is the canonical inconsistent version range.
| null (versionIntervals vi) = vr
| otherwise = fromVersionIntervals vi
where
vi = toVersionIntervals vr
----------------------------
-- Wildcard range utilities
--
wildcardUpperBound :: Version -> Version
wildcardUpperBound (Version lowerBound ts) = Version upperBound ts
where
upperBound = init lowerBound ++ [last lowerBound + 1]
isWildcardRange :: Version -> Version -> Bool
isWildcardRange (Version branch1 _) (Version branch2 _) = check branch1 branch2
where check (n:[]) (m:[]) | n+1 == m = True
check (n:ns) (m:ms) | n == m = check ns ms
check _ _ = False
------------------
-- Intervals view
--
-- | A complementary representation of a 'VersionRange'. Instead of a boolean
-- version predicate it uses an increasing sequence of non-overlapping,
-- non-empty intervals.
--
-- The key point is that this representation gives a canonical representation
-- for the semantics of 'VersionRange's. This makes it easier to check things
-- like whether a version range is empty, covers all versions, or requires a
-- certain minimum or maximum version. It also makes it easy to check equality
-- or containment. It also makes it easier to identify \'simple\' version
-- predicates for translation into foreign packaging systems that do not
-- support complex version range expressions.
--
newtype VersionIntervals = VersionIntervals [VersionInterval]
deriving (Eq, Show)
-- | Inspect the list of version intervals.
--
versionIntervals :: VersionIntervals -> [VersionInterval]
versionIntervals (VersionIntervals is) = is
type VersionInterval = (LowerBound, UpperBound)
data LowerBound = LowerBound Version !Bound deriving (Eq, Show)
data UpperBound = NoUpperBound | UpperBound Version !Bound deriving (Eq, Show)
data Bound = ExclusiveBound | InclusiveBound deriving (Eq, Show)
minLowerBound :: LowerBound
minLowerBound = LowerBound (Version [0] []) InclusiveBound
isVersion0 :: Version -> Bool
isVersion0 (Version [0] _) = True
isVersion0 _ = False
instance Ord LowerBound where
LowerBound ver bound <= LowerBound ver' bound' = case compare ver ver' of
LT -> True
EQ -> not (bound == ExclusiveBound && bound' == InclusiveBound)
GT -> False
instance Ord UpperBound where
_ <= NoUpperBound = True
NoUpperBound <= UpperBound _ _ = False
UpperBound ver bound <= UpperBound ver' bound' = case compare ver ver' of
LT -> True
EQ -> not (bound == InclusiveBound && bound' == ExclusiveBound)
GT -> False
invariant :: VersionIntervals -> Bool
invariant (VersionIntervals intervals) = all validInterval intervals
&& all doesNotTouch' adjacentIntervals
where
doesNotTouch' :: (VersionInterval, VersionInterval) -> Bool
doesNotTouch' ((_,u), (l',_)) = doesNotTouch u l'
adjacentIntervals :: [(VersionInterval, VersionInterval)]
adjacentIntervals
| null intervals = []
| otherwise = zip intervals (tail intervals)
checkInvariant :: VersionIntervals -> VersionIntervals
checkInvariant is = assert (invariant is) is
-- | Directly construct a 'VersionIntervals' from a list of intervals.
--
-- Each interval must be non-empty. The sequence must be in increasing order
-- and no invervals may overlap or touch. If any of these conditions are not
-- satisfied the function returns @Nothing@.
--
mkVersionIntervals :: [VersionInterval] -> Maybe VersionIntervals
mkVersionIntervals intervals
| invariant (VersionIntervals intervals) = Just (VersionIntervals intervals)
| otherwise = Nothing
validVersion :: Version -> Bool
validVersion (Version [] _) = False
validVersion (Version vs _) = all (>=0) vs
validInterval :: (LowerBound, UpperBound) -> Bool
validInterval i@(l, u) = validLower l && validUpper u && nonEmpty i
where
validLower (LowerBound v _) = validVersion v
validUpper NoUpperBound = True
validUpper (UpperBound v _) = validVersion v
-- Check an interval is non-empty
--
nonEmpty :: VersionInterval -> Bool
nonEmpty (_, NoUpperBound ) = True
nonEmpty (LowerBound l lb, UpperBound u ub) =
(l < u) || (l == u && lb == InclusiveBound && ub == InclusiveBound)
-- Check an upper bound does not intersect, or even touch a lower bound:
--
-- ---| or ---) but not ---] or ---) or ---]
-- |--- (--- (--- [--- [---
--
doesNotTouch :: UpperBound -> LowerBound -> Bool
doesNotTouch NoUpperBound _ = False
doesNotTouch (UpperBound u ub) (LowerBound l lb) =
u < l
|| (u == l && ub == ExclusiveBound && lb == ExclusiveBound)
-- | Check an upper bound does not intersect a lower bound:
--
-- ---| or ---) or ---] or ---) but not ---]
-- |--- (--- (--- [--- [---
--
doesNotIntersect :: UpperBound -> LowerBound -> Bool
doesNotIntersect NoUpperBound _ = False
doesNotIntersect (UpperBound u ub) (LowerBound l lb) =
u < l
|| (u == l && not (ub == InclusiveBound && lb == InclusiveBound))
-- | Test if a version falls within the version intervals.
--
-- It exists mostly for completeness and testing. It satisfies the following
-- properties:
--
-- > withinIntervals v (toVersionIntervals vr) = withinRange v vr
-- > withinIntervals v ivs = withinRange v (fromVersionIntervals ivs)
--
withinIntervals :: Version -> VersionIntervals -> Bool
withinIntervals v (VersionIntervals intervals) = any withinInterval intervals
where
withinInterval (lowerBound, upperBound) = withinLower lowerBound
&& withinUpper upperBound
withinLower (LowerBound v' ExclusiveBound) = v' < v
withinLower (LowerBound v' InclusiveBound) = v' <= v
withinUpper NoUpperBound = True
withinUpper (UpperBound v' ExclusiveBound) = v' > v
withinUpper (UpperBound v' InclusiveBound) = v' >= v
-- | Convert a 'VersionRange' to a sequence of version intervals.
--
toVersionIntervals :: VersionRange -> VersionIntervals
toVersionIntervals = foldVersionRange
( chkIvl (minLowerBound, NoUpperBound))
(\v -> chkIvl (LowerBound v InclusiveBound, UpperBound v InclusiveBound))
(\v -> chkIvl (LowerBound v ExclusiveBound, NoUpperBound))
(\v -> if isVersion0 v then VersionIntervals [] else
chkIvl (minLowerBound, UpperBound v ExclusiveBound))
unionVersionIntervals
intersectVersionIntervals
where
chkIvl interval = checkInvariant (VersionIntervals [interval])
-- | Convert a 'VersionIntervals' value back into a 'VersionRange' expression
-- representing the version intervals.
--
fromVersionIntervals :: VersionIntervals -> VersionRange
fromVersionIntervals (VersionIntervals []) = noVersion
fromVersionIntervals (VersionIntervals intervals) =
foldr1 UnionVersionRanges [ interval l u | (l, u) <- intervals ]
where
interval (LowerBound v InclusiveBound)
(UpperBound v' InclusiveBound) | v == v'
= ThisVersion v
interval (LowerBound v InclusiveBound)
(UpperBound v' ExclusiveBound) | isWildcardRange v v'
= WildcardVersion v
interval l u = lowerBound l `intersectVersionRanges'` upperBound u
lowerBound (LowerBound v InclusiveBound)
| isVersion0 v = AnyVersion
| otherwise = orLaterVersion v
lowerBound (LowerBound v ExclusiveBound) = LaterVersion v
upperBound NoUpperBound = AnyVersion
upperBound (UpperBound v InclusiveBound) = orEarlierVersion v
upperBound (UpperBound v ExclusiveBound) = EarlierVersion v
intersectVersionRanges' vr AnyVersion = vr
intersectVersionRanges' AnyVersion vr = vr
intersectVersionRanges' vr vr' = IntersectVersionRanges vr vr'
unionVersionIntervals :: VersionIntervals -> VersionIntervals
-> VersionIntervals
unionVersionIntervals (VersionIntervals is0) (VersionIntervals is'0) =
checkInvariant (VersionIntervals (union is0 is'0))
where
union is [] = is
union [] is' = is'
union (i:is) (i':is') = case unionInterval i i' of
Left Nothing -> i : union is (i' :is')
Left (Just i'') -> union is (i'':is')
Right Nothing -> i' : union (i :is) is'
Right (Just i'') -> union (i'':is) is'
unionInterval :: VersionInterval -> VersionInterval
-> Either (Maybe VersionInterval) (Maybe VersionInterval)
unionInterval (lower , upper ) (lower', upper')
-- Non-intersecting intervals with the left interval ending first
| upper `doesNotTouch` lower' = Left Nothing
-- Non-intersecting intervals with the right interval first
| upper' `doesNotTouch` lower = Right Nothing
-- Complete or partial overlap, with the left interval ending first
| upper <= upper' = lowerBound `seq`
Left (Just (lowerBound, upper'))
-- Complete or partial overlap, with the left interval ending first
| otherwise = lowerBound `seq`
Right (Just (lowerBound, upper))
where
lowerBound = min lower lower'
intersectVersionIntervals :: VersionIntervals -> VersionIntervals
-> VersionIntervals
intersectVersionIntervals (VersionIntervals is0) (VersionIntervals is'0) =
checkInvariant (VersionIntervals (intersect is0 is'0))
where
intersect _ [] = []
intersect [] _ = []
intersect (i:is) (i':is') = case intersectInterval i i' of
Left Nothing -> intersect is (i':is')
Left (Just i'') -> i'' : intersect is (i':is')
Right Nothing -> intersect (i:is) is'
Right (Just i'') -> i'' : intersect (i:is) is'
intersectInterval :: VersionInterval -> VersionInterval
-> Either (Maybe VersionInterval) (Maybe VersionInterval)
intersectInterval (lower , upper ) (lower', upper')
-- Non-intersecting intervals with the left interval ending first
| upper `doesNotIntersect` lower' = Left Nothing
-- Non-intersecting intervals with the right interval first
| upper' `doesNotIntersect` lower = Right Nothing
-- Complete or partial overlap, with the left interval ending first
| upper <= upper' = lowerBound `seq`
Left (Just (lowerBound, upper))
-- Complete or partial overlap, with the right interval ending first
| otherwise = lowerBound `seq`
Right (Just (lowerBound, upper'))
where
lowerBound = max lower lower'
-------------------------------
-- Parsing and pretty printing
--
instance Text VersionRange where
disp = fst
. foldVersionRange' -- precedence:
( Disp.text "-any" , 0 :: Int)
(\v -> (Disp.text "==" <> disp v , 0))
(\v -> (Disp.char '>' <> disp v , 0))
(\v -> (Disp.char '<' <> disp v , 0))
(\v -> (Disp.text ">=" <> disp v , 0))
(\v -> (Disp.text "<=" <> disp v , 0))
(\v _ -> (Disp.text "==" <> dispWild v , 0))
(\(r1, p1) (r2, p2) -> (punct 2 p1 r1 <+> Disp.text "||" <+> punct 2 p2 r2 , 2))
(\(r1, p1) (r2, p2) -> (punct 1 p1 r1 <+> Disp.text "&&" <+> punct 1 p2 r2 , 1))
(\(r, p) -> (Disp.parens r, p))
where dispWild (Version b _) =
Disp.hcat (Disp.punctuate (Disp.char '.') (map Disp.int b))
<> Disp.text ".*"
punct p p' | p < p' = Disp.parens
| otherwise = id
parse = expr
where
expr = do Parse.skipSpaces
t <- term
Parse.skipSpaces
(do _ <- Parse.string "||"
Parse.skipSpaces
e <- expr
return (UnionVersionRanges t e)
+++
return t)
term = do f <- factor
Parse.skipSpaces
(do _ <- Parse.string "&&"
Parse.skipSpaces
t <- term
return (IntersectVersionRanges f t)
+++
return f)
factor = Parse.choice $ parens expr
: parseAnyVersion
: parseWildcardRange
: map parseRangeOp rangeOps
parseAnyVersion = Parse.string "-any" >> return AnyVersion
parseWildcardRange = do
_ <- Parse.string "=="
Parse.skipSpaces
branch <- Parse.sepBy1 digits (Parse.char '.')
_ <- Parse.char '.'
_ <- Parse.char '*'
return (WildcardVersion (Version branch []))
parens p = Parse.between (Parse.char '(' >> Parse.skipSpaces)
(Parse.char ')' >> Parse.skipSpaces)
(do a <- p
Parse.skipSpaces
return (VersionRangeParens a))
digits = do
first <- Parse.satisfy Char.isDigit
if first == '0'
then return 0
else do rest <- Parse.munch Char.isDigit
return (read (first : rest))
parseRangeOp (s,f) = Parse.string s >> Parse.skipSpaces >> fmap f parse
rangeOps = [ ("<", EarlierVersion),
("<=", orEarlierVersion),
(">", LaterVersion),
(">=", orLaterVersion),
("==", ThisVersion) ]
|
fpco/cabal
|
Cabal/Distribution/Version.hs
|
bsd-3-clause
| 29,942 | 0 | 17 | 8,044 | 5,591 | 2,999 | 2,592 | 392 | 12 |
module Name (
Name(name_string), name,
freshName, freshNames
) where
import Utilities
import Data.Function
import Data.List
import Data.Ord
data Name = Name {
name_string :: String,
name_id :: Maybe Id
}
instance Show Name where
show = show . pPrint
instance Eq Name where
(==) = (==) `on` name_key
instance Ord Name where
compare = comparing name_key
instance Pretty Name where
pPrintPrec level _ n = text (escape $ name_string n) <> maybe empty (\i -> char '_' <> text (show i)) (name_id n)
where escape | level == haskellLevel = concatMap $ \c -> if c == '$' then "" else [c]
| otherwise = id
name_key :: Name -> Either String Id
name_key n = maybe (Left $ name_string n) Right (name_id n)
name :: String -> Name
name s = Name s Nothing
freshName :: IdSupply -> String -> (IdSupply, Name)
freshName ids s = second (Name s . Just) $ stepIdSupply ids
freshNames :: IdSupply -> [String] -> (IdSupply, [Name])
freshNames = mapAccumL freshName
|
batterseapower/core-haskell
|
Name.hs
|
bsd-3-clause
| 1,027 | 0 | 13 | 252 | 393 | 211 | 182 | 30 | 1 |
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-@ LIQUID "--diff" @-}
module Language.Haskell.Liquid.Liquid (
-- * Executable command
liquid
-- * Single query
, runLiquid
-- * Ghci State
, MbEnv
) where
import Prelude hiding (error)
import Data.Maybe
import System.Exit
import Control.DeepSeq
import Text.PrettyPrint.HughesPJ
import CoreSyn
import Var
import HscTypes (SourceError)
import System.Console.CmdArgs.Verbosity (whenLoud, whenNormal)
import System.Console.CmdArgs.Default
import GHC (HscEnv)
import qualified Control.Exception as Ex
import qualified Language.Fixpoint.Types.Config as FC
import qualified Language.Haskell.Liquid.UX.DiffCheck as DC
import Language.Fixpoint.Misc
import Language.Fixpoint.Solver
import qualified Language.Fixpoint.Types as F
import Language.Haskell.Liquid.Types
import Language.Haskell.Liquid.UX.Errors
import Language.Haskell.Liquid.UX.CmdLine
import Language.Haskell.Liquid.UX.Tidy
import Language.Haskell.Liquid.GHC.Interface
import Language.Haskell.Liquid.Constraint.Generate
import Language.Haskell.Liquid.Constraint.ToFixpoint
import Language.Haskell.Liquid.Constraint.Types
import Language.Haskell.Liquid.Transforms.Rec
import Language.Haskell.Liquid.UX.Annotate (mkOutput)
type MbEnv = Maybe HscEnv
------------------------------------------------------------------------------
liquid :: [String] -> IO b
------------------------------------------------------------------------------
liquid args = getOpts args >>= runLiquid Nothing >>= exitWith . fst
------------------------------------------------------------------------------
-- | This fellow does the real work
------------------------------------------------------------------------------
runLiquid :: MbEnv -> Config -> IO (ExitCode, MbEnv)
------------------------------------------------------------------------------
runLiquid mE cfg = do
(d, mE') <- checkMany cfg mempty mE (files cfg)
return (ec d, mE')
where
ec = resultExit . o_result
------------------------------------------------------------------------------
checkMany :: Config -> Output Doc -> MbEnv -> [FilePath] -> IO (Output Doc, MbEnv)
------------------------------------------------------------------------------
checkMany cfg d mE (f:fs) = do
(d', mE') <- checkOne mE cfg f
checkMany cfg (d `mappend` d') mE' fs
checkMany _ d mE [] =
return (d, mE)
------------------------------------------------------------------------------
checkOne :: MbEnv -> Config -> FilePath -> IO (Output Doc, Maybe HscEnv)
------------------------------------------------------------------------------
checkOne mE cfg t = do
z <- actOrDie (checkOne' mE cfg t)
case z of
Left e -> do
d <- exitWithResult cfg t $ mempty { o_result = e }
return (d, Nothing)
Right r ->
return r
checkOne' :: MbEnv -> Config -> FilePath -> IO (Output Doc, Maybe HscEnv)
checkOne' mE cfg t = do
(gInfo, hEnv) <- getGhcInfo mE cfg t
d <- liquidOne t gInfo
return (d, Just hEnv)
actOrDie :: IO a -> IO (Either ErrorResult a)
actOrDie act =
(Right <$> act)
`Ex.catch` (\(e :: SourceError) -> handle e)
`Ex.catch` (\(e :: Error) -> handle e)
`Ex.catch` (\(e :: UserError) -> handle e)
`Ex.catch` (\(e :: [Error]) -> handle e)
handle :: (Result a) => a -> IO (Either ErrorResult b)
handle = return . Left . result
------------------------------------------------------------------------------
liquidOne :: FilePath -> GhcInfo -> IO (Output Doc)
------------------------------------------------------------------------------
liquidOne tgt info = do
whenNormal $ donePhase Loud "Extracted Core using GHC"
let cfg = config $ spec info
whenLoud $ do putStrLn "**** Config **************************************************"
print cfg
whenLoud $ do putStrLn $ showpp info
putStrLn "*************** Original CoreBinds ***************************"
putStrLn $ render $ pprintCBs (cbs info)
let cbs' = transformScope (cbs info)
whenLoud $ do donePhase Loud "transformRecExpr"
putStrLn "*************** Transform Rec Expr CoreBinds *****************"
putStrLn $ render $ pprintCBs cbs'
putStrLn "*************** Slicing Out Unchanged CoreBinds *****************"
dc <- prune cfg cbs' tgt info
let cbs'' = maybe cbs' DC.newBinds dc
let info' = maybe info (\z -> info {spec = DC.newSpec z}) dc
let cgi = {-# SCC "generateConstraints" #-} generateConstraints $! info' {cbs = cbs''}
cgi `deepseq` donePhase Loud "generateConstraints"
whenLoud $ dumpCs cgi
out <- solveCs cfg tgt cgi info' dc
whenNormal $ donePhase Loud "solve"
let out' = mconcat [maybe mempty DC.oldOutput dc, out]
DC.saveResult tgt out'
exitWithResult cfg tgt out'
dumpCs :: CGInfo -> IO ()
dumpCs cgi = do
putStrLn "***************************** SubCs *******************************"
putStrLn $ render $ pprintMany (hsCs cgi)
putStrLn "***************************** FixCs *******************************"
putStrLn $ render $ pprintMany (fixCs cgi)
putStrLn "***************************** WfCs ********************************"
putStrLn $ render $ pprintMany (hsWfs cgi)
pprintMany :: (PPrint a) => [a] -> Doc
pprintMany xs = vcat [ pprint x $+$ text " " | x <- xs ]
checkedNames :: Maybe DC.DiffCheck -> Maybe [String]
checkedNames dc = concatMap names . DC.newBinds <$> dc
where
names (NonRec v _ ) = [render . text $ shvar v]
names (Rec xs) = map (shvar . fst) xs
shvar = showpp . varName
prune :: Config -> [CoreBind] -> FilePath -> GhcInfo -> IO (Maybe DC.DiffCheck)
prune cfg cbinds tgt info
| not (null vs) = return . Just $ DC.DC (DC.thin cbinds vs) mempty sp
| diffcheck cfg = DC.slice tgt cbinds sp
| otherwise = return Nothing
where
vs = tgtVars sp
sp = spec info
solveCs :: Config -> FilePath -> CGInfo -> GhcInfo -> Maybe DC.DiffCheck -> IO (Output Doc)
solveCs cfg tgt cgi info dc
= do finfo <- cgInfoFInfo info cgi tgt
F.Result r sol <- solve fx finfo
let names = checkedNames dc
let warns = logErrors cgi
let annm = annotMap cgi
let res = ferr sol r
let out0 = mkOutput cfg res sol annm
return $ out0 { o_vars = names }
{ o_errors = e2u sol <$> warns }
{ o_result = res }
where
fx = def { FC.solver = fromJust (smtsolver cfg)
, FC.linear = linear cfg
, FC.newcheck = newcheck cfg
-- , FC.extSolver = extSolver cfg
, FC.eliminate = eliminate cfg
, FC.save = saveQuery cfg
, FC.srcFile = tgt
, FC.cores = cores cfg
, FC.minPartSize = minPartSize cfg
, FC.maxPartSize = maxPartSize cfg
, FC.elimStats = elimStats cfg
-- , FC.stats = True
}
ferr s = fmap (cinfoUserError s . snd)
cinfoUserError :: F.FixSolution -> Cinfo -> UserError
cinfoUserError s = e2u s . cinfoError
e2u :: F.FixSolution -> Error -> UserError
e2u s = fmap pprint . tidyError s
-- writeCGI tgt cgi = {-# SCC "ConsWrite" #-} writeFile (extFileName Cgi tgt) str
-- where
-- str = {-# SCC "PPcgi" #-} showpp cgi
|
ssaavedra/liquidhaskell
|
src/Language/Haskell/Liquid/Liquid.hs
|
bsd-3-clause
| 7,985 | 0 | 16 | 2,124 | 2,099 | 1,088 | 1,011 | 147 | 2 |
module Main where
import qualified Streaming.Prelude as Str
import qualified System.IO.Streams as IOS
import Conduit.Simple as S
import Control.Exception
import Criterion.Main
import Data.Conduit as C
import Data.Conduit.Combinators as C
import Fusion as F hiding ((&))
import Data.Function ((&))
import Pipes as P
import qualified Pipes.Prelude as P
import Test.Hspec
import Test.Hspec.Expectations
main :: IO ()
main = do
hspec $ do
describe "basic tests" $
it "passes tests" $ True `shouldBe` True
defaultMain [
bgroup "basic" [ bench "stream" $ nfIO stream_basic
, bench "iostreams" $ nfIO iostreams_basic
, bench "pipes" $ nfIO pipes_basic
, bench "conduit" $ nfIO conduit_basic
-- , bench "simple-conduit" $ nfIO simple_conduit_basic
-- , bench "fusion" $ nfIO fusion_basic
]
]
pipes_basic :: IO Int
pipes_basic = do
xs <- P.toListM $ P.each [1..1000000]
>-> P.filter even
>-> P.map (+1)
>-> P.drop 1000
>-> P.map (+1)
>-> P.filter (\x -> x `mod` 2 == 0)
assert (Prelude.length xs == 499000) $
return (Prelude.length xs)
conduit_basic :: IO Int
conduit_basic = do
xs <- C.yieldMany [1..1000000]
C.$= C.filter even
C.$= C.map ((+1) :: Int -> Int)
C.$= (C.drop 1000 >> C.awaitForever C.yield)
C.$= C.map ((+1) :: Int -> Int)
C.$= C.filter (\x -> x `mod` 2 == 0)
C.$$ C.sinkList
assert (Prelude.length xs == 499000) $
return (Prelude.length (xs :: [Int]))
simple_conduit_basic :: IO Int
simple_conduit_basic = do
xs <- S.sourceList [1..1000000]
S.$= S.filterC even
S.$= S.mapC ((+1) :: Int -> Int)
S.$= S.dropC 1000
S.$= S.mapC ((+1) :: Int -> Int)
S.$= S.filterC (\x -> x `mod` 2 == 0)
S.$$ S.sinkList
assert (Prelude.length xs == 499000) $
return (Prelude.length (xs :: [Int]))
fusion_basic :: IO Int
fusion_basic = do
xs <- F.toListM $ F.each [1..1000000]
& F.filter even
& F.map (+1)
& F.drop 1000
& F.map (+1)
& F.filter (\x -> x `mod` 2 == 0)
assert (Prelude.length xs == 499000) $
return (Prelude.length (xs :: [Int]))
stream_basic :: IO Int
stream_basic = do
xs <- Str.toListM $ Str.each [1..1000000]
& Str.filter even
& Str.map (+1)
& Str.drop 1000
& Str.map (+1)
& Str.filter (\x -> x `mod` 2 == 0)
assert (Prelude.length xs == 499000) $
return (Prelude.length (xs :: [Int]))
iostreams_basic :: IO Int
iostreams_basic = do
s0 <- IOS.fromList [1..1000000]
s1 <- IOS.filter even s0
s2 <- IOS.map (+1) s1
s3 <- IOS.drop 1000 s2
s4 <- IOS.map (+1) s3
s5 <- IOS.filter (\x -> x `mod` 2 == 0) s4
xs <- IOS.toList s5
assert (Prelude.length xs == 499000) $
return (Prelude.length (xs :: [Int]))
|
PierreR/streaming
|
benchmarks/StreamingTest.hs
|
bsd-3-clause
| 3,131 | 0 | 15 | 1,046 | 1,209 | 632 | 577 | 87 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-} -- For deriving Num for Literal and Offset
-- |
-- Module : HBPF.Internal
-- Description : Internal types for BPF assembly representation and pretty printing
-- Copyright : (c) Andrew Duffy and Matt Denton, 2016
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : unknown
--
-- Internal types
--
module HBPF.Internal where
-- (
-- ld , ldh , ldx , ldxb
-- , st , stx
-- , andI , orI , sub
-- , jmp , ja , jeq , jneq , jgt , jge
-- , tax , txa
-- , ret , retA
-- , LoadAddress(..)
-- , StoreAddress(..)
-- , ArithAddress(..)
-- , ReturnAddress(..)
-- , ConditionalJmpAddress(..)
-- , toString
-- , label
-- , Instr(..)
-- , NamedRegister(..)
-- , IndexedRegister(..)
-- ) where
import Data.String (IsString)
--
-- * Representations of registers, both named registers and the 16 indexed registers
--
-- |Named registers. BPF's virtual machine only has two: an accumulator A and an auxiliary X
data NamedRegister = A | X
-- |Indexed registers. BPF's virtual machine provides 16 general purpose registers
data IndexedRegister = M0 | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | M9 | M10 | M11 | M12 | M13 | M14 | M15
--
-- * Domain-specific versions of primitives
--
-- | Represents a numeric Literal (immediate value)
newtype Literal = Literal { unLiteral :: Int } deriving (Eq, Show, Num)
-- | Representation of a byte offset
newtype Offset = Offset { unOffset :: Int } deriving (Eq, Show, Num)
-- | Representation of a label that appears in the assembly
newtype Label = Label { unLabel :: String } deriving (Eq, Show, IsString)
--
-- * Addressing Types
--
-- | Addressing options for the @ld*@ family of instructions
data LoadAddress = LoadAddrLiteral Literal
| LoadAddrByteOff Offset
| LoadAddrNamedRegister NamedRegister
| LoadAddrIndexedRegister IndexedRegister
| LoadAddrNibble Offset -- only used for ldxb and ldx
| LoadAddrOffFromX Offset -- only for ld, ldh, ldb
-- | Addressing options for the @st@ and @stx@ instructions
data StoreAddress = StoreAddrIndexedRegister IndexedRegister
data ReturnAddress = ReturnAddrLiteral Literal
| ReturnAddrA NamedRegister
-- |Sum type of addressing options available for arithmetic instructions
data ArithAddress = ArithAddrLiteral Literal
| ArithAddrRegister NamedRegister
-- | Sum type of addressing options available for unconditional jump instructions
data UnconditionalJmpAddress = UnconditionalJmpAddrLabel Label
-- | Addressing options available for conditional jumps
data ConditionalJmpAddress = ConditionalJmpAddrLiteralTrue Literal Label
| ConditionalJmpAddrLiteralTrueFalse Literal Label Label
-- | Different load sizes
data LoadType = LoadWord | LoadHalfWord | LoadByte
--
-- * Instructions
--
-- |BPF Instruction set as an ADT:
data BPFInstr =
-- Load and store instructions
ILoad NamedRegister LoadType LoadAddress
| IStore NamedRegister StoreAddress
-- Arithmetic instructions
| ILeftShift ArithAddress
| IRightShift ArithAddress
| IAnd ArithAddress
| IOr ArithAddress
| IMod ArithAddress
| IMult ArithAddress
| IDiv ArithAddress
| IAdd ArithAddress
| ISub ArithAddress
-- Conditional/Unconditional Jump instructions
| IJmp UnconditionalJmpAddress
| IJAbove UnconditionalJmpAddress
| IJEq ConditionalJmpAddress
| IJNotEq ConditionalJmpAddress
| IJGreater ConditionalJmpAddress
| IJGreaterEq ConditionalJmpAddress
-- Misc
| ISwapAX
| ISwapXA
| IRet ReturnAddress
-- For ease of use
ld :: LoadAddress -> [Instr]
ld addr = [IInstr $ ILoad A LoadWord addr]
ldh :: LoadAddress -> [Instr]
ldh addr = [IInstr $ ILoad A LoadHalfWord addr]
ldx :: LoadAddress -> [Instr]
ldx addr = [IInstr $ ILoad X LoadWord addr]
ldxb :: LoadAddress -> [Instr]
ldxb addr = [IInstr $ ILoad X LoadByte addr]
st :: StoreAddress -> [Instr]
st addr = [IInstr $ IStore A addr]
stx :: StoreAddress -> [Instr]
stx addr = [IInstr $ IStore X addr]
andI :: ArithAddress -> [Instr]
andI addr = [IInstr $ IAnd addr]
orI :: ArithAddress -> [Instr]
orI addr = [IInstr $ IOr addr]
sub :: ArithAddress -> [Instr]
sub addr = [IInstr $ ISub addr]
jmp :: UnconditionalJmpAddress -> [Instr]
jmp a = [IInstr $ IJmp a]
ja :: UnconditionalJmpAddress -> [Instr]
ja a = [IInstr $ IJAbove a]
jeq :: ConditionalJmpAddress -> [Instr]
jeq a = [IInstr $ IJEq a]
jneq :: ConditionalJmpAddress -> [Instr]
jneq a = [IInstr $ IJNotEq a]
jgt :: ConditionalJmpAddress -> [Instr]
jgt a = [IInstr $ IJGreater a]
jge :: ConditionalJmpAddress -> [Instr]
jge a = [IInstr $ IJGreaterEq a]
tax :: [Instr]
tax = [IInstr ISwapAX]
txa :: [Instr]
txa = [IInstr ISwapXA]
ret :: Literal -> [Instr]
ret a = [IInstr $ IRet (ReturnAddrLiteral a)]
retA :: [Instr]
retA = [IInstr $ IRet (ReturnAddrA A)]
-- |The stream of emitted instructions will consist of both "true" BPF instructions and labels
data Instr = IInstr BPFInstr | ILabel Label
goto :: String -> Label
goto s = Label s
label :: String -> [Instr]
label s = [ILabel (Label s)]
-- | Pretty print 'BPFInstr' instructions. Not exported, just used to implements 'toString'
-- | in the 'StringRep' instance of 'BPFInstr'
printBPFInstr :: BPFInstr -> String
printBPFInstr (ILoad reg typ addr) =
let location = case reg of
A -> "ld"
X -> "ldx"
rest = toString addr
prefix = case typ of
(LoadWord) -> ""
(LoadHalfWord) -> "h"
(LoadByte) -> "b"
in location ++ prefix ++ " " ++ rest
printBPFInstr (IStore namedReg addr) =
let location = case namedReg of
A -> "st"
X -> "stx"
rest = toString addr
in location ++ " " ++ rest
printBPFInstr (ILeftShift a) = "lsh " ++ toString a
printBPFInstr (IRightShift a) = "rsh " ++ toString a
printBPFInstr (IAnd a) = "and " ++ toString a
printBPFInstr (IOr a) = "or " ++ toString a
printBPFInstr (IMod a) = "mod " ++ toString a
printBPFInstr (IMult a) = "mul " ++ toString a
printBPFInstr (IDiv a) = "div " ++ toString a
printBPFInstr (IAdd a) = "add " ++ toString a
printBPFInstr (ISub a) = "sub " ++ toString a
printBPFInstr (IJmp a) = "jmp " ++ toString a
printBPFInstr (IJAbove a) = "ja " ++ toString a
printBPFInstr (IJEq a) = "jeq " ++ toString a
printBPFInstr (IJNotEq a) = "jne " ++ toString a
printBPFInstr (IJGreater a) = "jgt " ++ toString a
printBPFInstr (IJGreaterEq a) = "jge " ++ toString a
printBPFInstr (ISwapAX) = "tax"
printBPFInstr (ISwapXA) = "txa"
printBPFInstr (IRet a) = "ret " ++ toString a
--
-- * Below are all of the 'StringRep' instances needed to serialize a representation of BPF assembly
-- * instructions for outputting.
--
-- | A class that creates a 'toString' method
class StringRep a where
toString :: a -> String
instance StringRep BPFInstr where
toString = printBPFInstr
-- |Converts a list of BPF assembly instructions and labels into a string representation
instance StringRep [Instr] where
toString = unlines . map toString
instance StringRep ReturnAddress where
toString (ReturnAddrLiteral l) = "#" ++ (show . unLiteral) l
toString (ReturnAddrA namedReg) = --should error if namedReg is X
"a"
instance StringRep IndexedRegister where
toString (M0) = "M[0]"
toString (M1) = "M[1]"
toString (M2) = "M[2]"
toString (M3) = "M[3]"
toString (M4) = "M[4]"
toString (M5) = "M[5]"
toString (M6) = "M[6]"
toString (M7) = "M[7]"
toString (M8) = "M[8]"
toString (M9) = "M[9]"
toString (M10) = "M[10]"
toString (M11) = "M[11]"
toString (M12) = "M[12]"
toString (M13) = "M[13]"
toString (M14) = "M[14]"
toString (M15) = "M[15]"
instance StringRep LoadAddress where
toString = let printLoadAddress :: LoadAddress -> String
printLoadAddress (LoadAddrLiteral lit) = "#" ++ (show . unLiteral) lit
printLoadAddress (LoadAddrByteOff bos) = "[" ++ (show . unOffset) bos ++ "]"
printLoadAddress (LoadAddrIndexedRegister m) = toString m
printLoadAddress (LoadAddrNamedRegister r) = case r of { A -> "a" ; _ -> "x" }
printLoadAddress (LoadAddrNibble lan) = "4*([" ++ (show . unOffset) lan ++ "]&0xf)"
printLoadAddress (LoadAddrOffFromX ofx) = "[x + " ++ (show . unOffset) ofx ++ "]"
in printLoadAddress
instance StringRep StoreAddress where
toString (StoreAddrIndexedRegister m) = toString m
instance StringRep ArithAddress where
toString (ArithAddrLiteral lit) = "#" ++ (show . unLiteral) lit
toString (ArithAddrRegister A) = "A"
toString (ArithAddrRegister X) = "X"
instance StringRep UnconditionalJmpAddress where
toString (UnconditionalJmpAddrLabel l) = (unLabel) l ++ ":"
instance StringRep ConditionalJmpAddress where
toString (ConditionalJmpAddrLiteralTrue lit lt) = "#" ++ (show . unLiteral) lit ++ "," ++ unLabel lt
toString (ConditionalJmpAddrLiteralTrueFalse lit lt lf) = "#" ++ (show . unLiteral) lit ++ "," ++ unLabel lt ++ "," ++ unLabel lf
instance StringRep Label where
toString (Label l) = l ++ ":"
instance StringRep Instr where
toString (IInstr i) = toString i
toString (ILabel l) = toString l
|
hBPF/hBPF
|
HBPF/Internal.hs
|
bsd-3-clause
| 9,755 | 0 | 14 | 2,459 | 2,402 | 1,300 | 1,102 | 175 | 5 |
{-# LANGUAGE ExistentialQuantification, ScopedTypeVariables, TypeFamilies, TypeOperators, RankNTypes, FlexibleContexts, UndecidableInstances #-}
module Data.Vector.Generic.Static where
import Control.Applicative
import Prelude hiding (map, take, drop, concatMap)
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as MG
import Unsafe.Coerce
import Data.Nat
import Data.Fin
import Data.Vector.Fusion.Stream (Stream)
import Data.Vector.Generic.New (New)
newtype Vec n v a = Vec { unVec :: v a }
deriving (Show, Eq)
length :: (G.Vector v a, Nat n) => Vec n v a -> n
{-# INLINE length #-}
length = unsafeCoerce . G.length . unVec
-- null
empty :: G.Vector v a => Vec Z v a
{-# INLINE empty #-}
empty = Vec G.empty
singleton :: G.Vector v a => a -> Vec (S Z) v a
{-# INLINE singleton #-}
singleton = Vec . G.singleton
cons :: G.Vector v a => a -> Vec n v a -> Vec (S n) v a
{-# INLINE cons #-}
cons x (Vec xs) = Vec (G.cons x xs)
snoc :: G.Vector v a => Vec n v a -> a -> Vec (S n) v a
{-# INLINE snoc #-}
snoc (Vec xs) x = Vec (G.snoc xs x)
replicate :: forall a n v. (Nat n, G.Vector v a) => n -> a -> Vec n v a
{-# INLINE replicate #-}
replicate n = Vec . G.replicate (natToInt n)
generate :: forall n v a. (Nat n, G.Vector v a) => n -> (Fin n -> a) -> Vec n v a
{-# INLINE generate #-}
generate n f = Vec (G.generate (natToInt n) (f . Fin))
(++) :: G.Vector v a => Vec m v a -> Vec n v a -> Vec (m :+: n) v a
{-# INLINE (++) #-}
Vec ms ++ Vec ns = Vec (ms G.++ ns)
copy :: G.Vector v a => Vec n v a -> Vec n v a
{-# INLINE copy #-}
copy (Vec vs) = Vec (G.copy vs)
(!) :: G.Vector v a => Vec n v a -> Fin n -> a
{-# INLINE (!) #-}
Vec vs ! Fin i = G.unsafeIndex vs i
head :: G.Vector v a => Vec (S n) v a -> a
{-# INLINE head #-}
head (Vec vs) = G.unsafeHead vs
last :: G.Vector v a => Vec (S n) v a -> a
{-# INLINE last #-}
last (Vec vs) = G.unsafeLast vs
-- indexM
-- headM
-- lastM
slice :: (G.Vector v a, Nat k) => Fin n -> k -> Vec (n :+: k) v a -> Vec k v a
{-# INLINE slice #-}
slice (Fin i) k (Vec vs) = Vec (G.unsafeSlice i (natToInt k) vs)
init :: G.Vector v a => Vec (S n) v a -> Vec n v a
{-# INLINE init #-}
init (Vec vs) = Vec (G.unsafeInit vs)
tail :: G.Vector v a => Vec (S n) v a -> Vec n v a
{-# INLINE tail #-}
tail (Vec vs) = Vec (G.unsafeTail vs)
take :: (G.Vector v a, Nat k) => k -> Vec (n :+: k) v a -> Vec k v a
{-# INLINE take #-}
take k (Vec vs) = Vec (G.take (natToInt k) vs)
drop :: (G.Vector v a, Nat k) => k -> Vec (n :+: k) v a -> Vec n v a
{-# INLINE drop #-}
drop k (Vec vs) = Vec (G.drop (natToInt k) vs)
-- splitAt?
-- accum
-- accumulate
-- accumulate_
-- (//)
-- update
-- update_
backpermute :: (G.Vector v a, G.Vector v Int) => Vec m v a -> Vec n v (Fin m) -> Vec n v a
{-# INLINE backpermute #-}
backpermute (Vec vs) (Vec is) = Vec (G.unsafeBackpermute vs (unsafeCoerce is))
reverse :: G.Vector v a => Vec n v a -> Vec n v a
{-# INLINE reverse #-}
reverse (Vec vs) = Vec (G.reverse vs)
map :: (G.Vector v a, G.Vector v b) => (a -> b) -> Vec n v a -> Vec n v b
{-# INLINE map #-}
map f (Vec vs) = Vec (G.map f vs)
imap :: (G.Vector v a, G.Vector v b) => (Fin n -> a -> b) -> Vec n v a -> Vec n v b
{-# INLINE imap #-}
imap f (Vec vs) = Vec (G.imap (f . Fin) vs)
concatMap :: (G.Vector v a, G.Vector v b) => (a -> Vec n v b) -> Vec m v a -> Vec (m :*: n) v b
{-# INLINE concatMap #-}
concatMap f (Vec as) = Vec (G.concatMap (unVec . f) as)
zipWith :: (G.Vector v a, G.Vector v b, G.Vector v c) => (a -> b -> c) -> Vec n v a -> Vec n v b -> Vec n v c
{-# INLINE zipWith #-}
zipWith f (Vec as) (Vec bs) = Vec (G.zipWith f as bs)
zipWith3 :: (G.Vector v a, G.Vector v b, G.Vector v c, G.Vector v d) => (a -> b -> c -> d) -> Vec n v a -> Vec n v b -> Vec n v c -> Vec n v d
{-# INLINE zipWith3 #-}
zipWith3 f (Vec as) (Vec bs) (Vec cs) = Vec (G.zipWith3 f as bs cs)
zipWith4 :: (G.Vector v a, G.Vector v b, G.Vector v c, G.Vector v d, G.Vector v e) => (a -> b -> c -> d -> e) -> Vec n v a -> Vec n v b -> Vec n v c -> Vec n v d -> Vec n v e
{-# INLINE zipWith4 #-}
zipWith4 f (Vec as) (Vec bs) (Vec cs) (Vec ds) = Vec (G.zipWith4 f as bs cs ds)
zipWith5 :: (G.Vector v a, G.Vector v b, G.Vector v c, G.Vector v d, G.Vector v e, G.Vector v f) => (a -> b -> c -> d -> e -> f) -> Vec n v a -> Vec n v b -> Vec n v c -> Vec n v d -> Vec n v e -> Vec n v f
{-# INLINE zipWith5 #-}
zipWith5 f (Vec as) (Vec bs) (Vec cs) (Vec ds) (Vec es) = Vec (G.zipWith5 f as bs cs ds es)
zipWith6 :: (G.Vector v a, G.Vector v b, G.Vector v c, G.Vector v d, G.Vector v e, G.Vector v f, G.Vector v g) => (a -> b -> c -> d -> e -> f -> g) -> Vec n v a -> Vec n v b -> Vec n v c -> Vec n v d -> Vec n v e -> Vec n v f -> Vec n v g
{-# INLINE zipWith6 #-}
zipWith6 f (Vec as) (Vec bs) (Vec cs) (Vec ds) (Vec es) (Vec fs) = Vec (G.zipWith6 f as bs cs ds es fs)
izipWith :: (G.Vector v a, G.Vector v b, G.Vector v c) => (Fin n -> a -> b -> c) -> Vec n v a -> Vec n v b -> Vec n v c
{-# INLINE izipWith #-}
izipWith f (Vec as) (Vec bs) = Vec (G.izipWith (f . Fin) as bs)
izipWith3 :: (G.Vector v a, G.Vector v b, G.Vector v c, G.Vector v d) => (Fin n -> a -> b -> c -> d) -> Vec n v a -> Vec n v b -> Vec n v c -> Vec n v d
{-# INLINE izipWith3 #-}
izipWith3 f (Vec as) (Vec bs) (Vec cs) = Vec (G.izipWith3 (f . Fin) as bs cs)
izipWith4 :: (G.Vector v a, G.Vector v b, G.Vector v c, G.Vector v d, G.Vector v e) => (Fin n -> a -> b -> c -> d -> e) -> Vec n v a -> Vec n v b -> Vec n v c -> Vec n v d -> Vec n v e
{-# INLINE izipWith4 #-}
izipWith4 f (Vec as) (Vec bs) (Vec cs) (Vec ds) = Vec (G.izipWith4 (f . Fin) as bs cs ds)
izipWith5 :: (G.Vector v a, G.Vector v b, G.Vector v c, G.Vector v d, G.Vector v e, G.Vector v f) => (Fin n -> a -> b -> c -> d -> e -> f) -> Vec n v a -> Vec n v b -> Vec n v c -> Vec n v d -> Vec n v e -> Vec n v f
{-# INLINE izipWith5 #-}
izipWith5 f (Vec as) (Vec bs) (Vec cs) (Vec ds) (Vec es) = Vec (G.izipWith5 (f . Fin) as bs cs ds es)
izipWith6 :: (G.Vector v a, G.Vector v b, G.Vector v c, G.Vector v d, G.Vector v e, G.Vector v f, G.Vector v g) => (Fin n -> a -> b -> c -> d -> e -> f -> g) -> Vec n v a -> Vec n v b -> Vec n v c -> Vec n v d -> Vec n v e -> Vec n v f -> Vec n v g
{-# INLINE izipWith6 #-}
izipWith6 f (Vec as) (Vec bs) (Vec cs) (Vec ds) (Vec es) (Vec fs) = Vec (G.izipWith6 (f . Fin) as bs cs ds es fs)
zip :: (G.Vector v a, G.Vector v b, G.Vector v (a, b)) => Vec n v a -> Vec n v b -> Vec n v (a, b)
{-# INLINE zip #-}
zip (Vec as) (Vec bs) = Vec (G.zip as bs)
zip3 :: (G.Vector v a, G.Vector v b, G.Vector v c, G.Vector v (a, b, c)) => Vec n v a -> Vec n v b -> Vec n v c -> Vec n v (a, b, c)
{-# INLINE zip3 #-}
zip3 (Vec as) (Vec bs) (Vec cs) = Vec (G.zip3 as bs cs)
zip4 :: (G.Vector v a, G.Vector v b, G.Vector v c, G.Vector v d, G.Vector v (a, b, c, d)) => Vec n v a -> Vec n v b -> Vec n v c -> Vec n v d -> Vec n v (a, b, c, d)
{-# INLINE zip4 #-}
zip4 (Vec as) (Vec bs) (Vec cs) (Vec ds) = Vec (G.zip4 as bs cs ds)
zip5 :: (G.Vector v a, G.Vector v b, G.Vector v c, G.Vector v d, G.Vector v e, G.Vector v (a, b, c, d, e)) => Vec n v a -> Vec n v b -> Vec n v c -> Vec n v d -> Vec n v e -> Vec n v (a, b, c, d, e)
{-# INLINE zip5 #-}
zip5 (Vec as) (Vec bs) (Vec cs) (Vec ds) (Vec es) = Vec (G.zip5 as bs cs ds es)
zip6 :: (G.Vector v a, G.Vector v b, G.Vector v c, G.Vector v d, G.Vector v e, G.Vector v f, G.Vector v (a, b, c, d, e, f)) => Vec n v a -> Vec n v b -> Vec n v c -> Vec n v d -> Vec n v e -> Vec n v f -> Vec n v (a, b, c, d, e, f)
{-# INLINE zip6 #-}
zip6 (Vec as) (Vec bs) (Vec cs) (Vec ds) (Vec es) (Vec fs) = Vec (G.zip6 as bs cs ds es fs)
unzip :: (G.Vector v a, G.Vector v b, G.Vector v (a, b)) => Vec n v (a, b) -> (Vec n v a, Vec n v b)
{-# INLINE unzip #-}
unzip (Vec vs) = (Vec as, Vec bs)
where (as, bs) = G.unzip vs
unzip3 :: (G.Vector v a, G.Vector v b, G.Vector v c, G.Vector v (a, b, c)) => Vec n v (a, b, c) -> (Vec n v a, Vec n v b, Vec n v c)
{-# INLINE unzip3 #-}
unzip3 (Vec vs) = (Vec as, Vec bs, Vec cs)
where (as, bs, cs) = G.unzip3 vs
unzip4 :: (G.Vector v a, G.Vector v b, G.Vector v c, G.Vector v d, G.Vector v (a, b, c, d)) => Vec n v (a, b, c, d) -> (Vec n v a, Vec n v b, Vec n v c, Vec n v d)
{-# INLINE unzip4 #-}
unzip4 (Vec vs) = (Vec as, Vec bs, Vec cs, Vec ds)
where (as, bs, cs, ds) = G.unzip4 vs
unzip5 :: (G.Vector v a, G.Vector v b, G.Vector v c, G.Vector v d, G.Vector v e, G.Vector v (a, b, c, d, e)) => Vec n v (a, b, c, d, e) -> (Vec n v a, Vec n v b, Vec n v c, Vec n v d, Vec n v e)
{-# INLINE unzip5 #-}
unzip5 (Vec vs) = (Vec as, Vec bs, Vec cs, Vec ds, Vec es)
where (as, bs, cs, ds, es) = G.unzip5 vs
unzip6 :: (G.Vector v a, G.Vector v b, G.Vector v c, G.Vector v d, G.Vector v e, G.Vector v f, G.Vector v (a, b, c, d, e, f)) => Vec n v (a, b, c, d, e, f) -> (Vec n v a, Vec n v b, Vec n v c, Vec n v d, Vec n v e, Vec n v f)
{-# INLINE unzip6 #-}
unzip6 (Vec vs) = (Vec as, Vec bs, Vec cs, Vec ds, Vec es, Vec fs)
where (as, bs, cs, ds, es, fs) = G.unzip6 vs
-- filter
-- ifilter
-- takeWhile
-- dropWhile
-- partition
-- unstablePartition
-- span
-- break
elem :: (G.Vector v a, Eq a) => a -> Vec n v a -> Bool
{-# INLINE elem #-}
elem x (Vec vs) = G.elem x vs
notElem :: (G.Vector v a, Eq a) => a -> Vec n v a -> Bool
{-# INLINE notElem #-}
notElem x (Vec vs) = G.notElem x vs
find :: (G.Vector v a, Eq a) => (a -> Bool) -> Vec n v a -> Maybe a
{-# INLINE find #-}
find p (Vec vs) = G.find p vs
findIndex :: G.Vector v a => (a -> Bool) -> Vec n v a -> Maybe (Fin n)
{-# INLINE findIndex #-}
findIndex p (Vec vs) = fmap Fin $ G.findIndex p vs
findIndices :: (G.Vector v a, G.Vector v Int, G.Vector v (Fin n)) => (a -> Bool) -> Vec n v a -> Vec m v (Fin n) -- should we return proof that m <= n? Maybe just return k and m such that m + k = n.
{-# INLINE findIndices #-}
findIndices p (Vec vs) = Vec (G.map Fin $ G.findIndices p vs)
elemIndex :: G.Vector v a => Eq a => a -> Vec n v a -> Maybe (Fin n)
{-# INLINE elemIndex #-}
elemIndex x (Vec vs) = fmap Fin $ G.elemIndex x vs
elemIndices :: (G.Vector v a, G.Vector v Int, G.Vector v (Fin n)) => Eq a => a -> Vec n v a -> Vec m v (Fin n)
{-# INLINE elemIndices #-}
elemIndices x (Vec vs) = Vec (G.map Fin $ G.elemIndices x vs)
foldl :: G.Vector v b => (a -> b -> a) -> a -> Vec n v b -> a
{-# INLINE foldl #-}
foldl f z (Vec vs) = G.foldl f z vs
foldl1 :: G.Vector v a => (a -> a -> a) -> Vec (S n) v a -> a
{-# INLINE foldl1 #-}
foldl1 f (Vec vs) = G.foldl1 f vs
foldl' :: G.Vector v b => (a -> b -> a) -> a -> Vec n v b -> a
foldl' f z (Vec vs) = G.foldl' f z vs
foldl1' :: G.Vector v a => (a -> a -> a) -> Vec (S n) v a -> a
foldl1' f (Vec vs) = G.foldl1' f vs
foldr :: G.Vector v a => (a -> b -> b) -> b -> Vec n v a -> b
{-# INLINE foldr #-}
foldr f z (Vec vs) = G.foldr f z vs
foldr1 :: G.Vector v a => (a -> a -> a) -> Vec (S n) v a -> a
{-# INLINE foldr1 #-}
foldr1 f (Vec vs) = G.foldr1 f vs
foldr' :: G.Vector v a => (a -> b -> b) -> b -> Vec n v a -> b
foldr' f z (Vec vs) = G.foldr' f z vs
foldr1' :: G.Vector v a => (a -> a -> a) -> Vec (S n) v a -> a
foldr1' f (Vec vs) = G.foldr1' f vs
ifoldl :: G.Vector v b => (a -> Fin n -> b -> a) -> a -> Vec n v b -> a
{-# INLINE ifoldl #-}
ifoldl f z (Vec vs) = G.ifoldl (\a b -> f a (Fin b)) z vs
ifoldl' :: G.Vector v b => (a -> Fin n -> b -> a) -> a -> Vec n v b -> a
ifoldl' f z (Vec vs) = G.ifoldl' (\a b -> f a (Fin b)) z vs
ifoldr :: G.Vector v a => (Fin n -> a -> b -> b) -> b -> Vec n v a -> b
{-# INLINE ifoldr #-}
ifoldr f z (Vec vs) = G.ifoldr (f . Fin) z vs
ifoldr' :: G.Vector v a => (Fin n -> a -> b -> b) -> b -> Vec n v a -> b
ifoldr' f z (Vec vs) = G.ifoldr' (f . Fin) z vs
all :: G.Vector v a => (a -> Bool) -> Vec n v a -> Bool
{-# INLINE all #-}
all p (Vec vs) = G.all p vs
any :: G.Vector v a => (a -> Bool) -> Vec n v a -> Bool
{-# INLINE any #-}
any p (Vec vs) = G.any p vs
and :: G.Vector v Bool => Vec n v Bool -> Bool
{-# INLINE and #-}
and (Vec vs) = G.and vs
or :: G.Vector v Bool => Vec n v Bool -> Bool
{-# INLINE or #-}
or (Vec vs) = G.or vs
sum :: (G.Vector v a, Num a) => Vec n v a -> a
{-# INLINE sum #-}
sum (Vec vs) = G.sum vs
product :: (G.Vector v a, Num a) => Vec n v a -> a
{-# INLINE product #-}
product (Vec vs) = G.product vs
minimum :: (Ord a, G.Vector v a) => Vec (S n) v a -> a
{-# INLINE minimum #-}
minimum (Vec vs) = G.minimum vs
minimumBy :: G.Vector v a => (a -> a -> Ordering) -> Vec (S n) v a -> a
{-# INLINE minimumBy #-}
minimumBy c (Vec vs) = G.minimumBy c vs
minIndex :: (Ord a, G.Vector v a) => Vec (S n) v a -> Fin (S n)
{-# INLINE minIndex #-}
minIndex (Vec vs) = Fin (G.minIndex vs)
minIndexBy :: G.Vector v a => (a -> a -> Ordering) -> Vec (S n) v a -> Fin (S n)
{-# INLINE minIndexBy #-}
minIndexBy c (Vec vs) = Fin (G.minIndexBy c vs)
maximum :: (Ord a, G.Vector v a) => Vec (S n) v a -> a
{-# INLINE maximum #-}
maximum (Vec vs) = G.maximum vs
maximumBy :: G.Vector v a => (a -> a -> Ordering) -> Vec (S n) v a -> a
{-# INLINE maximumBy #-}
maximumBy c (Vec vs) = G.maximumBy c vs
maxIndex :: (Ord a, G.Vector v a) => Vec (S n) v a -> Fin (S n)
{-# INLINE maxIndex #-}
maxIndex (Vec vs) = Fin (G.maxIndex vs)
maxIndexBy :: G.Vector v a => (a -> a -> Ordering) -> Vec (S n) v a -> Fin (S n)
{-# INLINE maxIndexBy #-}
maxIndexBy c (Vec vs) = Fin (G.maxIndexBy c vs)
unfoldr :: G.Vector v a => (b -> Maybe (a, b)) -> b -> (forall n. Vec n v a -> r) -> r
{-# INLINE unfoldr #-}
unfoldr f x c = c (Vec (G.unfoldr f x))
-- prescanl
-- prescanl'
-- postscanl
-- postscanl'
-- scanl
-- scanl'
-- scanl1
-- scanl1'
-- prescanr
-- prescanr'
-- postscanr
-- postscanr'
-- scanr
-- scanr'
-- scanr1
-- scanr1'
enumFromN :: forall v a n. (G.Vector v a, Num a, Nat n) => a -> n -> Vec n v a
{-# INLINE enumFromN #-}
enumFromN x n = Vec (G.enumFromN x (natToInt n))
enumFromStepN :: forall v a n. (G.Vector v a, Num a, Nat n) => a -> a -> n -> Vec n v a
{-# INLINE enumFromStepN #-}
enumFromStepN x x1 n = Vec (G.enumFromStepN x x1 (natToInt n))
-- enumFromTo
-- enumFromThenTo
toList :: G.Vector v a => Vec n v a -> [a]
{-# INLINE toList #-}
toList (Vec vs) = G.toList vs
fromList :: G.Vector v a => [a] -> (forall n. Vec n v a -> r) -> r
{-# INLINE fromList #-}
fromList xs f = f (Vec (G.fromList xs))
stream :: G.Vector v a => Vec n v a -> Stream a
{-# INLINE stream #-}
stream (Vec vs) = G.stream vs
unstream :: G.Vector v a => Stream a -> (forall n. Vec n v a -> r) -> r
{-# INLINE unstream #-}
unstream s f = f (Vec (G.unstream s))
streamR :: G.Vector v a => Vec n v a -> Stream a
{-# INLINE streamR #-}
streamR (Vec vs) = G.streamR vs
unstreamR :: G.Vector v a => Stream a -> (forall n. Vec n v a -> r) -> r
{-# INLINE unstreamR #-}
unstreamR s f = f (Vec (G.unstreamR s))
new :: G.Vector v a => New a -> (forall n. Vec n v a -> r) -> r
{-# INLINE new #-}
new n f = f (Vec (G.new n))
allFin :: forall n v. (Nat n, G.Vector v (Fin n)) => n -> Vec n v (Fin n)
{-# INLINE allFin #-}
allFin n = Vec (G.generate (natToInt n) Fin)
indexed :: (G.Vector v a, G.Vector v (Fin n, a)) => Vec n v a -> Vec n v (Fin n, a)
{-# INLINE indexed #-}
indexed = imap (,)
|
copumpkin/vector-static
|
Data/Vector/Generic/Static.hs
|
bsd-3-clause
| 15,116 | 0 | 14 | 3,804 | 9,046 | 4,600 | 4,446 | 273 | 1 |
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module EFA.Application.Type where
import qualified EFA.Flow.SequenceState.Index as Idx
import qualified EFA.Flow.Sequence.Quantity as SeqQty
import qualified EFA.Flow.State.Quantity as StateQty
import qualified EFA.Flow.State.Absolute as StateAbs
import qualified EFA.Flow.Topology.Quantity as TopoQty
import qualified EFA.Signal.Sequence as Sequ
import qualified EFA.Flow.Topology.Index as TopoIdx
import EFA.Equation.Result (Result)
import qualified EFA.Signal.Record as Record
import qualified EFA.Signal.Signal as Sig
import EFA.Signal.Data (Data, Nil, (:>))
import Data.Vector (Vector)
import Data.Map (Map)
type EnvResult node a = StateQty.Graph node (Result a) (Result a)
-- type PerStateSweepVariable node sweep vec a =
-- Map Idx.State (Map node (Maybe ((sweep::(* -> *) -> * -> *) vec a)))
-- | Data Type to store the optimal solution per state
type OptimalSolutionPerState node a =
Map Idx.State (Map [a] (Maybe (a, a, Int, EnvResult node a)))
type OptimalSolutionOfOneState node a = Map [a] (Maybe (a, a, Int, EnvResult node a))
-- | Data Type to store the optimal solution of all states
type OptimalSolution node a = Map [a] (Maybe (a, a, Idx.State, Int, EnvResult node a))
-- | Data Type to store the stack of the optimal abjective Function per state
type OptStackPerState (sweep :: (* -> *) -> * -> *) vec a = Map Idx.State (Map [a] (Result (sweep vec a)))
-- | Data Type to store the average solution per state
type AverageSolutionPerState node a = Map Idx.State (Map [a] (Maybe a))
type ControlMatrices node vec a = Map (TopoIdx.Position node) (Sig.PSignal2 Vector vec a)
type EqSystem node a =
forall s. StateAbs.EquationSystemIgnore node s a a
-- | Complete Sweep over all States and complete Requirement Room
type Sweep node sweep vec a = Map Idx.State (Map [a] (SweepPerReq node sweep vec a))
{-
data Sweep node sweep vec a = Sweep {
sweepData :: Map Idx.State (Map [a] (PerStateSweep node sweep vec a)),
sweepStoragePower :: Map Idx.State (Map node (Maybe (sweep vec a)))}
-}
type StoragePowerMap node (sweep :: (* -> *) -> * -> *) vec a = Map node (Maybe (Result (sweep vec a)))
-- | Sweep over one Position in Requirement Room
data SweepPerReq node (sweep :: (* -> *) -> * -> *) vec a =
SweepPerReq {
etaSys :: Result (sweep vec a),
condVec :: Result (sweep vec Bool),
storagePowerMap :: StoragePowerMap node sweep vec a,
envResult :: EnvResult node (sweep vec a) }
instance Show (SweepPerReq node sweep vec a) where
show _ = "<SweepPerReq>"
{-
data Interpolation node vec a =
Interpolation {
controlMatrices :: ControlMatrices node vec a,
reqsAndDofsSignals :: Record.PowerRecord node vec a}
-}
type InterpolationOfAllStates node vec a =
Map Idx.State (InterpolationOfOneState node vec a)
data InterpolationOfOneState node vec a =
InterpolationOfOneState {
controlMatricesOfState :: ControlMatrices node vec a,
optObjectiveSignalOfState :: Sig.UTSignal vec a,
-- tileChangeSignal :: vec [(a,a,a,a)],
reqsAndDofsSignalsOfState :: Record.PowerRecord node vec a}
data Simulation node vec a =
Simulation {
envSim:: TopoQty.Section node (Result (Data (vec :> Nil) a)),
signals :: Record.PowerRecord node vec a }
data EnergyFlowAnalysis node vec a = EnergyFlowAnalysis {
powerSequence :: Sequ.List (Record.PowerRecord node vec a),
sequenceFlowGraph ::
SeqQty.Graph node (Result (Data Nil a)) (Result (Data (vec :> Nil) a)),
stateFlowGraph :: EnvResult node (Data Nil a)}
data SignalBasedOptimisation node (sweep :: (* -> *) -> * -> *)
sweepVec a intVec b simVec c efaVec d =
SignalBasedOptimisation {
optimalSolutionPerState :: OptimalSolutionPerState node a,
averageSolutionPerState :: AverageSolutionPerState node a,
interpolationPerState :: InterpolationOfAllStates node intVec a,
-- optimalSolutionSig :: OptimalSolution node a,
simulation :: Simulation node simVec a,
analysis :: EnergyFlowAnalysis node efaVec d,
stateFlowGraphSweep :: EnvResult node (sweep sweepVec a)}
instance Show (SignalBasedOptimisation node sweep sweepVec a intVec b simVec c efaVec d) where
show _ = "<SignalBasedOptimisation>"
|
energyflowanalysis/efa-2.1
|
src/EFA/Application/Type.hs
|
bsd-3-clause
| 4,354 | 0 | 15 | 782 | 1,104 | 653 | 451 | 66 | 0 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.NV.FillRectangle
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/NV/fill_rectangle.txt NV_fill_rectangle> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.NV.FillRectangle (
-- * Enums
gl_FILL_RECTANGLE_NV
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/NV/FillRectangle.hs
|
bsd-3-clause
| 649 | 0 | 4 | 78 | 37 | 31 | 6 | 3 | 0 |
-- | Pattern Translation
--
--
-- This is a naive, but straightforward compilation of pattern match to sum and product types.
--
-- We translate
-- case x of {p -> e' | ps}
-- into
-- let
-- kf = \() -> case x of ps
-- in
-- m
-- where x match p then Succes e' else FailCont (kf x) ---> m
--
-- We translate (case x of {} : T) to 'abort T'
--
-- The judgment x match (p -> e) then ks else kf ---> m
-- is defined as as
-- x match {f1 = p1, ..., fN = pN) then ks else kf ---> let ... xi = x.fi ... in m
-- where x1 match p1 then (x2 match p2 then ... xN match pN then ks) else kf ---> m
-- x match Con p1 ... pN then ks else kf ---> case coerceOutδ x of { fCon x1 .... xN -> m | |kf| }
-- where x1 match p1 then (x2 match p2 then ... xN match pN then ks) else kf ---> m
-- x match _ then Success e else kf ---> |e|
-- x match _ then (y match p then ks) else kf ---> m
-- where y match p then ks else kf ---> m
-- x match y then Success e else kf ---> |e[x/y]|
-- x match y then (y' match p then ks) else kf ---> m
-- where y'[x/y] match p[x/y] then ks[x/y] else kf ---> m
--
-- coerceOutδ is the term (δ.data [λα:⋆.α]) that witnesses
-- the unrolling from δ τs to
-- Sum { fCon1 : σ1[τs/βs], ... fConN : σN[τs/βs] }
-- for the datatype δ β = fCon1 : σ1 | ... | fConN : σN
{-# LANGUAGE ViewPatterns, DeriveDataTypeable, DeriveGeneric #-}
module Insomnia.ToF.Pattern where
import Control.Lens
import Control.Monad.Reader
import qualified Data.Map as M
import Data.Monoid (Monoid(..), Endo(..))
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import qualified Unbound.Generics.LocallyNameless as U
import qualified Unbound.Generics.LocallyNameless.Unsafe as UU
import Insomnia.ToF.Env
import Insomnia.Expr
import Insomnia.Types (Label(..))
import qualified FOmega.Syntax as F
import Insomnia.ToF.Type (type')
import Insomnia.ToF.Expr (expr, valueConstructor)
patternTranslation :: ToF m
=> Var
-> [Clause]
-> F.Type
-> m (U.Bind F.Var F.Term)
patternTranslation v clauses_ resultTy =
withFreshName (U.name2String v) $ \v' ->
local (valEnv %~ M.insert v (v', LocalTermVar)) $ do
let defaultClause = F.DefaultClause $ Left $ F.CaseMatchFailure resultTy
j <- patternTranslation' v' clauses_ defaultClause
m <- translateJob (optimizeJob j)
return $ U.bind v' m
-- naive translation - each source language clause becomes its own
-- split task that interrogates one constructor and we try each task
-- in turn. that means naively we'd end up with a lot of nested cases
-- of the same subject. it's not efficient but it's hard to get
-- wrong.
patternTranslation' :: ToF m
=> F.Var
-> [Clause]
-> F.DefaultClause
-> m Job
patternTranslation' v' clauses_ defaultClause =
case clauses_ of
[] -> return $ FailJ v' $ FailCont defaultClause
[clause] -> do
task <- clauseToTask v' clause
return $ TryTaskJ task (FailJ v' $ FailCont defaultClause)
(clause:clauses') -> do
js <- patternTranslation' v' clauses' defaultClause
task <- clauseToTask v' clause
return $ TryTaskJ task js
-- optimize a job to combine split tasks
optimizeJob :: Job -> Job
optimizeJob j =
case j of
FailJ {} -> j
TryTaskJ (SplitTk v1 co1 io1 tasks1) (TryTaskJ (SplitTk v2 _co2 io2 tasks2) jrest)
| v1 `U.aeq` v2, io1 `U.aeq` io2, Just jointTask <- meshSplitTasks v1 co1 io1 (tasks1 ++ tasks2) ->
optimizeJob (TryTaskJ jointTask jrest)
TryTaskJ j1 jrest -> TryTaskJ j1 (optimizeJob jrest)
meshSplitTasks :: F.Var
-> InstantiationCoercion
-> DtInOut
-> [SplitTaskInfo]
-> Maybe Task
meshSplitTasks v co io tasks_ =
let go tasks =
case tasks of
(SplitTaskInfo fld1 _bnd1):(SplitTaskInfo fld2 _bnd2):_rest
| fld1 == fld2 ->
-- we have something like
-- case subj of
-- ConA (Con1 p1) -> e1
-- ConA (Con2 p2) -> e2
-- restClauses
-- eventually we should make something like
-- case subj of
-- ConA y -> case y of { Con1 p1 -> e1 ; Con2 p2 -> e2 ; restClauses }
-- restClauses
--
-- but not quite yet. For now just bail.
Nothing
split1:rest -> fmap (split1:) (go rest)
[] -> Just []
in fmap (SplitTk v co io) (go tasks_)
data Task =
SuccessTk !Expr
| LetTk !F.Var (U.Bind Var Task)
| ProjectTk !F.Var (U.Bind [(U.Embed F.Field, F.Var)] Task)
| SplitTk !F.Var !InstantiationCoercion !DtInOut ![SplitTaskInfo]
-- try each split task in turn until one succeeds, or else fail.
-- Note that we expect the split tasks to share a failure
-- continuation
deriving (Typeable, Generic, Show)
-- wrapper around an extracted datatype injection/projection term
newtype DtInOut = DtInOut F.Term
deriving (Typeable, Generic, Show)
-- split the subject by matching on the given value constructor and
-- then running the continuation task.
data SplitTaskInfo =
SplitTaskInfo !F.Field (U.Bind [(U.Embed F.Field, F.Var)] Task)
deriving (Typeable, Generic, Show)
data Job =
FailJ !F.Var !FailCont
| TryTaskJ !Task !Job -- try task otherwise job
deriving (Typeable, Generic, Show)
newtype FailCont = FailCont F.DefaultClause
deriving (Show, Generic, Typeable)
instance U.Alpha Task
instance U.Alpha SplitTaskInfo
instance U.Alpha DtInOut
instance U.Alpha Job
instance U.Alpha FailCont
clauseToTask :: ToF m => F.Var -> Clause -> m Task
clauseToTask v' (Clause bnd) =
let (pat, e) = UU.unsafeUnbind bnd
sk = SuccessTk e
in patternToTask v' pat sk
-- | @patternToTask y pat j@ matches the subject @y@ with pattern @pat@ and the continues with job @j@
patternToTask :: ToF m => F.Var -> Pattern -> Task -> m Task
patternToTask v' pat sj =
case pat of
WildcardP -> return $ sj
VarP y -> return $ LetTk v' (U.bind y sj)
RecordP lps ->
let fps = map (\(U.unembed -> (Label lbl), x) -> (F.FUser lbl, x)) lps
in freshPatternVars fps $ \fys yps -> do
task' <- matchTheseAndThen yps sj
return $ ProjectTk v' (U.bind fys task')
ConP (U.unembed -> vc) (U.unembed -> mco) ps -> do
(dtInOut, f) <- valueConstructor vc
co <- case mco of
Nothing -> throwError "ToF.Pattern.translateTask: Expected a type instantiation annotation on constructor pattern"
Just co -> return co
let fps = zip (map F.FTuple [0..]) ps
freshPatternVars fps $ \fys yps -> do
task' <- matchTheseAndThen yps sj
return $ SplitTk v' co (DtInOut dtInOut) [SplitTaskInfo f (U.bind fys task')]
matchTheseAndThen :: ToF m => [(F.Var, Pattern)] -> Task -> m Task
matchTheseAndThen [] sk = return sk
matchTheseAndThen ((v',pat):rest) sk = do
task' <- matchTheseAndThen rest sk
patternToTask v' pat task'
translateJob :: ToF m =>
Job -> m F.Term
translateJob (FailJ v' (FailCont defaultClause)) =
return $ F.Case (F.V v') [] defaultClause
translateJob (TryTaskJ task (FailJ _subj fk)) =
translateTask task fk
translateJob (TryTaskJ task j@(TryTaskJ {})) = do
mfk <- translateJob j
let fk = FailCont $ F.DefaultClause $ Right mfk
translateTask task fk
translateTask :: ToF m =>
Task -> FailCont -> m F.Term
translateTask (SuccessTk e) _fk = expr e
translateTask (LetTk v' bnd) fk =
U.lunbind bnd $ \(y, sk) ->
-- instead of doing substitution or anything like that, just
-- run the rest of the translation in an env where y is also mapped to v'
local (valEnv %~ M.insert y (v', LocalTermVar))
$ translateTask sk fk
translateTask (ProjectTk v' bnd) fk =
U.lunbind bnd $ \(fys, sk) -> do
m_ <- translateTask sk fk
return (projectFields fys v' m_)
translateTask (SplitTk v' co dtInOut splitTasks) fk = do
clauses <- mapM (translateSplitTask fk) splitTasks
caseConstruct v' dtInOut co clauses fk
translateSplitTask :: ToF m =>
FailCont
-> SplitTaskInfo
-> m F.Clause
translateSplitTask fk (SplitTaskInfo f bnd) =
U.lunbind bnd $ \(fys, sk) -> do
m_ <- translateTask sk fk
clauseConstruct f fys m_
clauseConstruct :: ToF m
=> F.Field
-> [(U.Embed F.Field, F.Var)]
-> F.Term
-> m F.Clause
clauseConstruct f fys successTm =
withFreshName "z" $ \z ->
return $ F.Clause f $ U.bind z (projectFields fys z successTm)
-- | caseConstruct y Con {0 = y1, ..., n-1 = yN} ms mf
-- builds the term
-- case outδ y of { Con z -> let {y1, ... yN} = z in ms | _ -> mf }
-- where outδ = δ.data [λα:⋆.α] and "let {vs...} = z in m" is sugar for lets and projections
caseConstruct :: ToF m
=> F.Var
-> DtInOut
-> InstantiationCoercion
-> [F.Clause]
-> FailCont
-> m F.Term
caseConstruct ysubj (DtInOut dtInOut)
(InstantiationSynthesisCoercion _ tyargs _) clauses (FailCont defaultClause) = do
(tyArgs', ks) <- liftM unzip $ mapM type' tyargs
d <- U.lfresh (U.s2n "δ")
let
dtOut = dtInOut `F.Proj` F.FDataOut
-- For polymorphic types constructors we need to build a higher-order context.
-- Consider the clause: case l of (Cons ·¢· [Int] x xs) -> x + sum xs
-- In that case, we need to translate to:
-- case Δ.out [λ (δ:⋆→⋆) . δ Int] l of (Cons z) -> let x = z.0 xs = z.1 in ...
-- That is, we have to know that the polymorphic type Δ was instantiated with τs
-- and the context should be λ (δ:κ1→⋯κN→⋆) . (⋯ (δ τ1) ⋯ τN)
--
here = let kD = (ks `F.kArrs` F.KType)
appdD = (F.TV d) `F.tApps` tyArgs'
in F.TLam $ U.bind (d, U.embed kD) appdD
subject = F.App (F.PApp dtOut here) (F.V ysubj)
return $ F.Case subject clauses defaultClause
freshPatternVars :: ToF m
=> [(F.Field, Pattern)]
-> ([(U.Embed F.Field, F.Var)] -> [(F.Var, Pattern)] -> m ans)
-> m ans
freshPatternVars [] kont = kont [] []
freshPatternVars ((f, p):fps) kont =
let n = case f of
F.FUser s -> s
_ -> "ω" -- can't happen, I think
in withFreshName n $ \y ->
freshPatternVars fps $ \fys yps ->
kont ((U.embed f,y):fys) ((y,p):yps)
-- | projectFields {... fi = yi ... } x body
-- returns
-- let ... let yi = x . fi in ... in body
projectFields :: [(U.Embed F.Field, F.Var)] -> F.Var -> F.Term -> F.Term
projectFields fys vsubj mbody =
let
ms = map (\(f, y) ->
let
p = F.Proj (F.V vsubj) (U.unembed f)
in Endo (F.Let . U.bind (y, U.embed p)))
fys
in
appEndo (mconcat ms) mbody
|
lambdageek/insomnia
|
src/Insomnia/ToF/Pattern.hs
|
bsd-3-clause
| 11,061 | 0 | 20 | 3,099 | 2,939 | 1,513 | 1,426 | 219 | 5 |
instance (MonadState s m) => MonadState s (NondetT m) where
get = NondetT $ do
s <- get
return [s]
put s = NondetT $ do
put s
return [()]
|
davdar/quals
|
writeup-old/sections/04MonadicAAM/04Optimizations/00Widen/07NondetTMonadState.hs
|
bsd-3-clause
| 158 | 0 | 11 | 50 | 82 | 39 | 43 | -1 | -1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.INTEL
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- A convenience module, combining all raw modules containing INTEL extensions.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.INTEL (
module Graphics.Rendering.OpenGL.Raw.INTEL.MapTexture,
module Graphics.Rendering.OpenGL.Raw.INTEL.ParallelArrays,
module Graphics.Rendering.OpenGL.Raw.INTEL.PerformanceQuery
) where
import Graphics.Rendering.OpenGL.Raw.INTEL.MapTexture
import Graphics.Rendering.OpenGL.Raw.INTEL.ParallelArrays
import Graphics.Rendering.OpenGL.Raw.INTEL.PerformanceQuery
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/INTEL.hs
|
bsd-3-clause
| 881 | 0 | 5 | 92 | 81 | 66 | 15 | 7 | 0 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeApplications #-}
module Main
( main
) where
import Universum
import qualified Codec.Archive.Tar as Tar
import Crypto.Hash (Digest, SHA512, hashlazy)
import qualified Data.ByteString.Lazy as BSL
import Data.List ((\\))
import qualified Data.Text.Lazy.IO as TL
import Data.Version (showVersion)
import Formatting (Format, format, mapf, text, (%))
import qualified NeatInterpolation as NI (text)
import Options.Applicative (Parser, execParser, footerDoc, fullDesc,
header, help, helper, info, infoOption, long, metavar,
option, progDesc, short)
import Options.Applicative.Types (readerAsk)
import System.Exit (ExitCode (ExitFailure))
import System.FilePath (normalise, takeFileName, (<.>), (</>))
import qualified System.PosixCompat as PosixCompat
import System.Process (readProcess)
import Text.PrettyPrint.ANSI.Leijen (Doc)
import Paths_cardano_sl (version)
import Pos.Util (directory, ls, withTempDir)
data UpdateGenOptions = UpdateGenOptions
{ oldDir :: !Text
, newDir :: !Text
, outputTar :: !Text
} deriving (Show)
optionsParser :: Parser UpdateGenOptions
optionsParser = do
oldDir <- textOption $
long "old"
<> metavar "PATH"
<> help "Path to directory with old program."
newDir <- textOption $
long "new"
<> metavar "PATH"
<> help "Path to directory with new program."
outputTar <- textOption $
short 'o'
<> long "output"
<> metavar "PATH"
<> help "Path to output .tar-file with diff."
pure UpdateGenOptions{..}
where
textOption = option (toText <$> readerAsk)
getUpdateGenOptions :: IO UpdateGenOptions
getUpdateGenOptions = execParser programInfo
where
programInfo = info (helper <*> versionOption <*> optionsParser) $
fullDesc <> progDesc ("")
<> header "Cardano SL updates generator."
<> footerDoc usageExample
versionOption = infoOption
("cardano-genupdate-" <> showVersion version)
(long "version" <> help "Show version.")
usageExample :: Maybe Doc
usageExample = (Just . fromString @Doc . toString @Text) [NI.text|
Command example:
stack exec -- cardano-genupdate --old /tmp/app-v000 --new /tmp/app-v001 -o /tmp/app-update.tar
Both directories must have equal file structure (e.g. they must contain the same
files in the same subdirectories correspondingly), otherwise 'cardano-genupdate' will fail.
Please note that 'cardano-genupdate' uses 'bsdiff' program, so make sure 'bsdiff' is available in the PATH.|]
main :: IO ()
main = do
UpdateGenOptions{..} <- getUpdateGenOptions
createUpdate (toString oldDir)
(toString newDir)
(toString outputTar)
-- | Outputs a `FilePath` as a `LText`.
fp :: Format LText (String -> LText)
fp = mapf toLText text
createUpdate :: FilePath -> FilePath -> FilePath -> IO ()
createUpdate oldDir newDir updPath = do
oldFiles <- ls oldDir
newFiles <- ls newDir
-- find directories and fail if there are any (we can't handle
-- directories)
do oldNotFiles <- filterM (fmap (not . PosixCompat.isRegularFile) . PosixCompat.getFileStatus . normalise) oldFiles
newNotFiles <- filterM (fmap (not . PosixCompat.isRegularFile) . PosixCompat.getFileStatus . normalise) newFiles
unless (null oldNotFiles && null newNotFiles) $ do
unless (null oldNotFiles) $ do
TL.putStrLn $ format (fp%" contains not-files:") oldDir
for_ oldNotFiles $ TL.putStrLn . format (" * "%fp)
unless (null newNotFiles) $ do
TL.putStrLn $ format (fp%" contains not-files:") newDir
for_ newNotFiles $ TL.putStrLn . format (" * "%fp)
putText "Generation aborted."
exitWith (ExitFailure 2)
-- fail if lists of files are unequal
do let notInOld = map takeFileName newFiles \\ map takeFileName oldFiles
let notInNew = map takeFileName oldFiles \\ map takeFileName newFiles
unless (null notInOld && null notInNew) $ do
unless (null notInOld) $ do
putText "these files are in the NEW dir but not in the OLD dir:"
for_ notInOld $ TL.putStrLn . format (" * "%fp)
unless (null notInNew) $ do
TL.putStr "these files are in the OLD dir but not in the NEW dir:"
for_ notInNew $ TL.putStrLn . format (" * "%fp)
putText "Generation aborted."
exitWith (ExitFailure 3)
-- otherwise, for all files, generate hashes and a diff
withTempDir (directory updPath) "temp" $ \tempDir -> do
(manifest, bsdiffs) <-
fmap (unzip . catMaybes) $
forM oldFiles $ \f -> do
let fname = takeFileName f
oldFile = oldDir </> fname
newFile = newDir </> fname
diffFile = tempDir </> (fname <.> "bsdiff")
oldHash <- hashFile oldFile
newHash <- hashFile newFile
if oldHash == newHash
then return Nothing
else do
_ <- readProcess "bsdiff" [oldFile, newFile, diffFile] mempty
diffHash <- hashFile diffFile
return (Just (unwords [oldHash, newHash, diffHash],
takeFileName diffFile))
-- write the MANIFEST file
writeFile (tempDir </> "MANIFEST") (unlines manifest)
-- put diffs and a manifesto into a tar file
Tar.create updPath tempDir ("MANIFEST" : bsdiffs)
hashLBS :: LByteString -> Text
hashLBS lbs = show $ hashSHA512 lbs
where
hashSHA512 :: LByteString -> Digest SHA512
hashSHA512 = hashlazy
hashFile :: FilePath -> IO Text
hashFile f = hashLBS <$> BSL.readFile f
|
input-output-hk/pos-haskell-prototype
|
tools/src/genupdate/Main.hs
|
mit
| 6,060 | 0 | 24 | 1,765 | 1,475 | 757 | 718 | 123 | 2 |
{-- snippet parallelMap --}
import Control.Parallel (par)
parallelMap :: (a -> b) -> [a] -> [b]
parallelMap f (x:xs) = let r = f x
in r `par` r : parallelMap f xs
parallelMap _ _ = []
{-- /snippet parallelMap --}
{-- snippet forceList --}
forceList :: [a] -> ()
forceList (x:xs) = x `pseq` forceList xs
forceList _ = ()
{-- /snippet forceList --}
{-- snippet stricterMap --}
stricterMap :: (a -> b) -> [a] -> [b]
stricterMap f xs = forceList xs `seq` map f xs
{-- /snippet stricterMap --}
{-- snippet forceListAndElts --}
forceListAndElts :: (a -> ()) -> [a] -> ()
forceListAndElts forceElt (x:xs) =
forceElt x `seq` forceListAndElts forceElt xs
forceListAndElts _ _ = ()
{-- /snippet forceListAndElts --}
|
binesiyu/ifl
|
examples/ch24/ParMap.hs
|
mit
| 759 | 0 | 9 | 178 | 271 | 148 | 123 | 14 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
-- | Slotting utilities.
module Pos.Core.Slotting.Util
(
-- * Helpers using 'MonadSlots[Data]'
getCurrentSlotFlat
, slotFromTimestamp
-- * Worker which ticks when slot starts and its parameters
, OnNewSlotParams (..)
, defaultOnNewSlotParams
, ActionTerminationPolicy (..)
) where
import Universum
import Data.Time.Units (Microsecond, convertUnit)
import Pos.Core.Slotting.Class (MonadSlots (..), MonadSlotsData)
import Pos.Core.Slotting.EpochIndex (EpochIndex (..))
import Pos.Core.Slotting.LocalSlotIndex (LocalSlotIndex (..),
mkLocalSlotIndex)
import Pos.Core.Slotting.MemState (getSystemStartM,
withSlottingVarAtomM)
import Pos.Core.Slotting.SlotCount (SlotCount)
import Pos.Core.Slotting.SlotId (FlatSlotId, SlotId (..),
flattenSlotId)
import Pos.Core.Slotting.TimeDiff (addTimeDiffToTimestamp)
import Pos.Core.Slotting.Timestamp (Timestamp (..))
import Pos.Core.Slotting.Types (EpochSlottingData (..), SlottingData,
getAllEpochIndices, lookupEpochSlottingData)
import Pos.Util.Util (leftToPanic)
-- | Get flat id of current slot based on MonadSlots.
getCurrentSlotFlat :: MonadSlots ctx m => SlotCount -> m (Maybe FlatSlotId)
getCurrentSlotFlat epochSlots =
fmap (flattenSlotId epochSlots) <$> getCurrentSlot epochSlots
-- | Parameters for `onNewSlot`.
data OnNewSlotParams = OnNewSlotParams
{ onspStartImmediately :: !Bool
-- ^ Whether first action should be executed ASAP (i. e. basically
-- when the program starts), or only when new slot starts.
--
-- For example, if the program is started in the middle of a slot
-- and this parameter in 'False', we will wait for half of slot
-- and only then will do something.
, onspTerminationPolicy :: !ActionTerminationPolicy
-- ^ What should be done if given action doesn't finish before new
-- slot starts. See the description of 'ActionTerminationPolicy'.
}
-- | Default parameters which were used by almost all code before this
-- data type was introduced.
defaultOnNewSlotParams :: OnNewSlotParams
defaultOnNewSlotParams =
OnNewSlotParams
{ onspStartImmediately = True
, onspTerminationPolicy = NoTerminationPolicy
}
-- | This policy specifies what should be done if the action passed to
-- `onNewSlot` doesn't finish when current slot finishes.
--
-- We don't want to run given action more than once in parallel for
-- variety of reasons:
-- 1. If action hangs for some reason, there can be infinitely growing pool
-- of hanging actions with probably bad consequences (e. g. leaking memory).
-- 2. Thread management will be quite complicated if we want to fork
-- threads inside `onNewSlot`.
-- 3. If more than one action is launched, they may use same resources
-- concurrently, so the code must account for it.
data ActionTerminationPolicy
= NoTerminationPolicy
-- ^ Even if action keeps running after current slot finishes,
-- we'll just wait and start action again only after the previous
-- one finishes.
| NewSlotTerminationPolicy !Text
-- ^ If new slot starts, running action will be cancelled. Name of
-- the action should be passed for logging.
-- | Compute current slot from current timestamp based on data
-- provided by 'MonadSlotsData'.
slotFromTimestamp
:: MonadSlotsData ctx m
=> SlotCount
-> Timestamp
-> m (Maybe SlotId)
slotFromTimestamp epochSlots approxCurTime = do
systemStart <- getSystemStartM
withSlottingVarAtomM (iterateBackwardsSearch systemStart)
where
iterateBackwardsSearch
:: Timestamp
-> SlottingData
-> Maybe SlotId
iterateBackwardsSearch systemStart slottingData = do
let allEpochIndex = getAllEpochIndices slottingData
-- We first reverse the indices since the most common calls to this funcion
-- will be from next/current index and close.
let reversedEpochIndices = reverse allEpochIndex
let iterateIndicesUntilJust
:: [EpochIndex]
-> Maybe SlotId
iterateIndicesUntilJust [] = Nothing
iterateIndicesUntilJust indices = do
-- Get current index or return @Nothing@ if the indices list is empty.
let mCurrentEpochIndex :: Maybe EpochIndex
mCurrentEpochIndex = case indices of
(x:_) -> Just x
_ -> Nothing
-- Try to find a slot.
let mFoundSlot = mCurrentEpochIndex >>= findSlot systemStart slottingData
case mFoundSlot of
-- If you found a slot, then return it
Just foundSlot -> Just foundSlot
-- If no slot is found, iterate with the rest of the list
Nothing -> iterateIndicesUntilJust $ case indices of
[] -> []
(_:xs) -> xs
-- Iterate the indices recursively with the reverse indices, starting
-- with the most recent one.
iterateIndicesUntilJust reversedEpochIndices
-- Find a slot using timestamps. If no @EpochSlottingData@ is found return
-- @Nothing@.
findSlot
:: Timestamp
-> SlottingData
-> EpochIndex
-> Maybe SlotId
findSlot systemStart slottingData epochIndex = do
epochSlottingData <- lookupEpochSlottingData epochIndex slottingData
computeSlotUsingEpoch systemStart approxCurTime epochIndex epochSlottingData
computeSlotUsingEpoch
:: Timestamp
-> Timestamp
-> EpochIndex
-> EpochSlottingData
-> Maybe SlotId
computeSlotUsingEpoch systemStart (Timestamp curTime) epoch EpochSlottingData {..}
| curTime < epochStart = Nothing
| curTime < epochStart + epochDuration = Just $ SlotId epoch localSlot
| otherwise = Nothing
where
epochStart :: Microsecond
epochStart = getTimestamp (esdStartDiff `addTimeDiffToTimestamp` systemStart)
localSlotNumeric :: Word16
localSlotNumeric = fromIntegral $ (curTime - epochStart) `div` slotDuration
localSlot :: LocalSlotIndex
localSlot =
leftToPanic "computeSlotUsingEpoch: " $
mkLocalSlotIndex epochSlots localSlotNumeric
slotDuration :: Microsecond
slotDuration = convertUnit esdSlotDuration
epochDuration :: Microsecond
epochDuration = slotDuration * fromIntegral epochSlots
|
input-output-hk/pos-haskell-prototype
|
core/src/Pos/Core/Slotting/Util.hs
|
mit
| 6,825 | 0 | 22 | 1,847 | 901 | 509 | 392 | 108 | 5 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module Snap.Snaplet.Internal.Initializer
( addPostInitHook
, addPostInitHookBase
, toSnapletHook
, bracketInit
, modifyCfg
, nestSnaplet
, embedSnaplet
, makeSnaplet
, nameSnaplet
, onUnload
, addRoutes
, wrapSite
, runInitializer
, runSnaplet
, combineConfig
, serveSnaplet
, serveSnapletNoArgParsing
, loadAppConfig
, printInfo
, getRoutes
, getEnvironment
, modifyMaster
) where
------------------------------------------------------------------------------
import Control.Applicative ((<$>))
import Control.Concurrent.MVar (MVar, modifyMVar_, newEmptyMVar,
putMVar, readMVar)
import Control.Exception.Lifted (SomeException, catch, try)
import Control.Lens (ALens', cloneLens, over, set,
storing, (^#))
import Control.Monad (Monad (..), join, liftM, unless,
when, (=<<))
import Control.Monad.Reader (ask)
import Control.Monad.State (get, modify)
import Control.Monad.Trans (lift, liftIO)
import Control.Monad.Trans.Writer hiding (pass)
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as B
import Data.Configurator (Worth (..), addToConfig, empty,
loadGroups, subconfig)
import qualified Data.Configurator.Types as C
import Data.IORef (IORef, atomicModifyIORef,
newIORef, readIORef)
import Data.Maybe (Maybe (..), fromJust, fromMaybe,
isNothing)
import Data.Text (Text)
import qualified Data.Text as T
import Prelude (Bool (..), Either (..), Eq (..),
String, concat, concatMap,
const, either,
error, filter, flip, fst, id,
map, not, show, ($), ($!), (++),
(.))
import Snap.Core (Snap, liftSnap, route)
import Snap.Http.Server (Config, completeConfig,
getCompression, getErrorHandler,
getOther, getVerbose, httpServe)
import Snap.Util.GZip (withCompression)
import System.Directory (copyFile,
createDirectoryIfMissing,
doesDirectoryExist,
getCurrentDirectory)
import System.Directory.Tree (DirTree (..), FileName, buildL,
dirTree, readDirectoryWith)
import System.FilePath.Posix (dropFileName, makeRelative,
(</>))
import System.IO (FilePath, IO, hPutStrLn, stderr)
------------------------------------------------------------------------------
import Snap.Snaplet.Config (AppConfig, appEnvironment,
commandLineAppConfig)
import qualified Snap.Snaplet.Internal.Lensed as L
import qualified Snap.Snaplet.Internal.LensT as LT
import Snap.Snaplet.Internal.Types
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- | 'get' for InitializerState.
iGet :: Initializer b v (InitializerState b)
iGet = Initializer $ LT.getBase
------------------------------------------------------------------------------
-- | 'modify' for InitializerState.
iModify :: (InitializerState b -> InitializerState b) -> Initializer b v ()
iModify f = Initializer $ do
b <- LT.getBase
LT.putBase $ f b
------------------------------------------------------------------------------
-- | 'gets' for InitializerState.
iGets :: (InitializerState b -> a) -> Initializer b v a
iGets f = Initializer $ do
b <- LT.getBase
return $ f b
------------------------------------------------------------------------------
-- | Lets you retrieve the list of routes currently set up by an Initializer.
-- This can be useful in debugging.
getRoutes :: Initializer b v [ByteString]
getRoutes = liftM (map fst) $ iGets _handlers
------------------------------------------------------------------------------
-- | Return the current environment string. This will be the
-- environment given to 'runSnaplet' or from the command line when
-- using 'serveSnaplet'. Usefully for changing behavior during
-- development and testing.
getEnvironment :: Initializer b v String
getEnvironment = iGets _environment
------------------------------------------------------------------------------
-- | Converts a plain hook into a Snaplet hook.
toSnapletHook :: (v -> IO (Either Text v))
-> (Snaplet v -> IO (Either Text (Snaplet v)))
toSnapletHook f (Snaplet cfg reset val) = do
val' <- f val
return $! Snaplet cfg reset <$> val'
------------------------------------------------------------------------------
-- | Adds an IO action that modifies the current snaplet state to be run at
-- the end of initialization on the state that was created. This makes it
-- easier to allow one snaplet's state to be modified by another snaplet's
-- initializer. A good example of this is when a snaplet has templates that
-- define its views. The Heist snaplet provides the 'addTemplates' function
-- which allows other snaplets to set up their own templates. 'addTemplates'
-- is implemented using this function.
addPostInitHook :: (v -> IO (Either Text v))
-> Initializer b v ()
addPostInitHook = addPostInitHook' . toSnapletHook
addPostInitHook' :: (Snaplet v -> IO (Either Text (Snaplet v)))
-> Initializer b v ()
addPostInitHook' h = do
h' <- upHook h
addPostInitHookBase h'
------------------------------------------------------------------------------
-- | Variant of addPostInitHook for when you have things wrapped in a Snaplet.
addPostInitHookBase :: (Snaplet b -> IO (Either Text (Snaplet b)))
-> Initializer b v ()
addPostInitHookBase = Initializer . lift . tell . Hook
------------------------------------------------------------------------------
-- | Helper function for transforming hooks.
upHook :: (Snaplet v -> IO (Either Text (Snaplet v)))
-> Initializer b v (Snaplet b -> IO (Either Text (Snaplet b)))
upHook h = Initializer $ do
l <- ask
return $ upHook' l h
------------------------------------------------------------------------------
-- | Helper function for transforming hooks.
upHook' :: Monad m => ALens' b a -> (a -> m (Either e a)) -> b -> m (Either e b)
upHook' l h b = do
v <- h (b ^# l)
return $ case v of
Left e -> Left e
Right v' -> Right $ storing l v' b
------------------------------------------------------------------------------
-- | Modifies the Initializer's SnapletConfig.
modifyCfg :: (SnapletConfig -> SnapletConfig) -> Initializer b v ()
modifyCfg f = iModify $ over curConfig $ \c -> f c
------------------------------------------------------------------------------
-- | If a snaplet has a filesystem presence, this function creates and copies
-- the files if they dont' already exist.
setupFilesystem :: Maybe (IO FilePath)
-- ^ The directory where the snaplet's reference files are
-- stored. Nothing if the snaplet doesn't come with any
-- files that need to be installed.
-> FilePath
-- ^ Directory where the files should be copied.
-> Initializer b v ()
setupFilesystem Nothing _ = return ()
setupFilesystem (Just getSnapletDataDir) targetDir = do
exists <- liftIO $ doesDirectoryExist targetDir
unless exists $ do
printInfo "...setting up filesystem"
liftIO $ createDirectoryIfMissing True targetDir
srcDir <- liftIO getSnapletDataDir
liftIO $ readDirectoryWith (doCopy srcDir targetDir) srcDir
return ()
where
doCopy srcRoot targetRoot filename = do
createDirectoryIfMissing True directory
copyFile filename toDir
where
toDir = targetRoot </> makeRelative srcRoot filename
directory = dropFileName toDir
------------------------------------------------------------------------------
-- | All snaplet initializers must be wrapped in a call to @makeSnaplet@,
-- which handles standardized housekeeping common to all snaplets.
-- Common usage will look something like
-- this:
--
-- @
-- fooInit :: SnapletInit b Foo
-- fooInit = makeSnaplet \"foo\" \"An example snaplet\" Nothing $ do
-- -- Your initializer code here
-- return $ Foo 42
-- @
--
-- Note that you're writing your initializer code in the Initializer monad,
-- and makeSnaplet converts it into an opaque SnapletInit type. This allows
-- us to use the type system to ensure that the API is used correctly.
makeSnaplet :: Text
-- ^ A default id for this snaplet. This is only used when
-- the end-user has not already set an id using the
-- nameSnaplet function.
-> Text
-- ^ A human readable description of this snaplet.
-> Maybe (IO FilePath)
-- ^ The path to the directory holding the snaplet's reference
-- filesystem content. This will almost always be the
-- directory returned by Cabal's getDataDir command, but it
-- has to be passed in because it is defined in a
-- package-specific import. Setting this value to Nothing
-- doesn't preclude the snaplet from having files in in the
-- filesystem, it just means that they won't be copied there
-- automatically.
-> Initializer b v v
-- ^ Snaplet initializer.
-> SnapletInit b v
makeSnaplet snapletId desc getSnapletDataDir m = SnapletInit $ do
modifyCfg $ \c -> if isNothing $ _scId c
then set scId (Just snapletId) c else c
sid <- iGets (T.unpack . fromJust . _scId . _curConfig)
topLevel <- iGets _isTopLevel
unless topLevel $ do
modifyCfg $ over scUserConfig (subconfig (T.pack sid))
modifyCfg $ \c -> set scFilePath
(_scFilePath c </> "snaplets" </> sid) c
iModify (set isTopLevel False)
modifyCfg $ set scDescription desc
cfg <- iGets _curConfig
printInfo $ T.pack $ concat
["Initializing "
,sid
," @ /"
,B.unpack $ buildPath $ _scRouteContext cfg
]
-- This has to happen here because it needs to be after scFilePath is set
-- up but before the config file is read.
setupFilesystem getSnapletDataDir (_scFilePath cfg)
env <- iGets _environment
let configLocation = _scFilePath cfg </> (env ++ ".cfg")
liftIO $ addToConfig [Optional configLocation]
(_scUserConfig cfg)
mkSnaplet m
------------------------------------------------------------------------------
-- | Internal function that gets the SnapletConfig out of the initializer
-- state and uses it to create a (Snaplet a).
mkSnaplet :: Initializer b v v -> Initializer b v (Snaplet v)
mkSnaplet m = do
res <- m
cfg <- iGets _curConfig
setInTop <- iGets masterReloader
l <- getLens
let modifier = setInTop . set (cloneLens l . snapletValue)
return $ Snaplet cfg modifier res
------------------------------------------------------------------------------
-- | Brackets an initializer computation, restoring curConfig after the
-- computation returns.
bracketInit :: Initializer b v a -> Initializer b v a
bracketInit m = do
s <- iGet
res <- m
iModify (set curConfig (_curConfig s))
return res
------------------------------------------------------------------------------
-- | Handles modifications to InitializerState that need to happen before a
-- snaplet is called with either nestSnaplet or embedSnaplet.
setupSnapletCall :: ByteString -> Initializer b v ()
setupSnapletCall rte = do
curId <- iGets (fromJust . _scId . _curConfig)
modifyCfg (over scAncestry (curId:))
modifyCfg (over scId (const Nothing))
unless (B.null rte) $ modifyCfg (over scRouteContext (rte:))
------------------------------------------------------------------------------
-- | Runs another snaplet's initializer and returns the initialized Snaplet
-- value. Calling an initializer with nestSnaplet gives the nested snaplet
-- access to the same base state that the current snaplet has. This makes it
-- possible for the child snaplet to make use of functionality provided by
-- sibling snaplets.
nestSnaplet :: ByteString
-- ^ The root url for all the snaplet's routes. An empty
-- string gives the routes the same root as the parent
-- snaplet's routes.
-> SnapletLens v v1
-- ^ Lens identifying the snaplet
-> SnapletInit b v1
-- ^ The initializer function for the subsnaplet.
-> Initializer b v (Snaplet v1)
nestSnaplet rte l (SnapletInit snaplet) =
with l $ bracketInit $ do
setupSnapletCall rte
snaplet
------------------------------------------------------------------------------
-- | Runs another snaplet's initializer and returns the initialized Snaplet
-- value. The difference between this and 'nestSnaplet' is the first type
-- parameter in the third argument. The \"v1 v1\" makes the child snaplet
-- think that it is the top-level state, which means that it will not be able
-- to use functionality provided by snaplets included above it in the snaplet
-- tree. This strongly isolates the child snaplet, and allows you to eliminate
-- the b type variable. The embedded snaplet can still get functionality
-- from other snaplets, but only if it nests or embeds the snaplet itself.
--
-- Note that this function does not change where this snaplet is located in
-- the filesystem. The snaplet directory structure convention stays the same.
-- Also, embedSnaplet limits the ways that snaplets can interact, so we
-- usually recommend using nestSnaplet instead. However, we provide this
-- function because sometimes reduced flexibility is useful. In short, if
-- you don't understand what this function does for you from looking at its
-- type, you probably don't want to use it.
embedSnaplet :: ByteString
-- ^ The root url for all the snaplet's routes. An empty
-- string gives the routes the same root as the parent
-- snaplet's routes.
--
-- NOTE: Because of the stronger isolation provided by
-- embedSnaplet, you should be more careful about using an
-- empty string here.
-> SnapletLens v v1
-- ^ Lens identifying the snaplet
-> SnapletInit v1 v1
-- ^ The initializer function for the subsnaplet.
-> Initializer b v (Snaplet v1)
embedSnaplet rte l (SnapletInit snaplet) = bracketInit $ do
curLens <- getLens
setupSnapletCall ""
chroot rte (cloneLens curLens . subSnaplet l) snaplet
------------------------------------------------------------------------------
-- | Changes the base state of an initializer.
chroot :: ByteString
-> SnapletLens (Snaplet b) v1
-> Initializer v1 v1 a
-> Initializer b v a
chroot rte l (Initializer m) = do
curState <- iGet
let newSetter f = masterReloader curState (over (cloneLens l) f)
((a,s), (Hook hook)) <- liftIO $ runWriterT $ LT.runLensT m id $
curState {
_handlers = [],
_hFilter = id,
masterReloader = newSetter
}
let handler = chrootHandler l $ _hFilter s $ route $ _handlers s
iModify $ over handlers (++[(rte,handler)])
. set cleanup (_cleanup s)
addPostInitHookBase $ upHook' l hook
return a
------------------------------------------------------------------------------
-- | Changes the base state of a handler.
chrootHandler :: SnapletLens (Snaplet v) b'
-> Handler b' b' a -> Handler b v a
chrootHandler l (Handler h) = Handler $ do
s <- get
(a, s') <- liftSnap $ L.runLensed h id (s ^# l)
modify $ storing l s'
return a
------------------------------------------------------------------------------
-- | Sets a snaplet's name. All snaplets have a default name set by the
-- snaplet author. This function allows you to override that name. You will
-- have to do this if you have more than one instance of the same kind of
-- snaplet because snaplet names must be unique. This function must
-- immediately surround the snaplet's initializer. For example:
--
-- @fooState <- nestSnaplet \"fooA\" $ nameSnaplet \"myFoo\" $ fooInit@
nameSnaplet :: Text
-- ^ The snaplet name
-> SnapletInit b v
-- ^ The snaplet initializer function
-> SnapletInit b v
nameSnaplet nm (SnapletInit m) = SnapletInit $
modifyCfg (set scId (Just nm)) >> m
------------------------------------------------------------------------------
-- | Adds routing to the current 'Handler'. The new routes are merged with
-- the main routing section and take precedence over existing routing that was
-- previously defined.
addRoutes :: [(ByteString, Handler b v ())]
-> Initializer b v ()
addRoutes rs = do
l <- getLens
ctx <- iGets (_scRouteContext . _curConfig)
let modRoute (r,h) = ( buildPath (r:ctx)
, setPattern r >> withTop' l h)
let rs' = map modRoute rs
iModify (\v -> over handlers (++rs') v)
where
setPattern r = do
p <- getRoutePattern
when (isNothing p) $ setRoutePattern r
------------------------------------------------------------------------------
-- | Wraps the /base/ snaplet's routing in another handler, allowing you to run
-- code before and after all routes in an application.
--
-- Here are some examples of things you might do:
--
-- > wrapSite (\site -> logHandlerStart >> site >> logHandlerFinished)
-- > wrapSite (\site -> ensureAdminUser >> site)
--
wrapSite :: (Handler b v () -> Handler b v ())
-- ^ Handler modifier function
-> Initializer b v ()
wrapSite f0 = do
f <- mungeFilter f0
iModify (\v -> over hFilter (f.) v)
------------------------------------------------------------------------------
mungeFilter :: (Handler b v () -> Handler b v ())
-> Initializer b v (Handler b b () -> Handler b b ())
mungeFilter f = do
myLens <- Initializer ask
return $ \m -> with' myLens $ f' m
where
f' (Handler m) = f $ Handler $ L.withTop id m
------------------------------------------------------------------------------
-- | Attaches an unload handler to the snaplet. The unload handler will be
-- called when the server shuts down, or is reloaded.
onUnload :: IO () -> Initializer b v ()
onUnload m = do
cleanupRef <- iGets _cleanup
liftIO $ atomicModifyIORef cleanupRef f
where
f curCleanup = (curCleanup >> m, ())
------------------------------------------------------------------------------
-- |
logInitMsg :: IORef Text -> Text -> IO ()
logInitMsg ref msg = atomicModifyIORef ref (\cur -> (cur `T.append` msg, ()))
------------------------------------------------------------------------------
-- | Initializers should use this function for all informational or error
-- messages to be displayed to the user. On application startup they will be
-- sent to the console. When executed from the reloader, they will be sent
-- back to the user in the HTTP response.
printInfo :: Text -> Initializer b v ()
printInfo msg = do
logRef <- iGets _initMessages
liftIO $ logInitMsg logRef (msg `T.append` "\n")
------------------------------------------------------------------------------
-- | Builds an IO reload action for storage in the SnapletState.
mkReloader :: FilePath
-> String
-> ((Snaplet b -> Snaplet b) -> IO ())
-> IORef (IO ())
-> Initializer b b (Snaplet b)
-> IO (Either Text Text)
mkReloader cwd env resetter cleanupRef i = do
join $ readIORef cleanupRef
!res <- runInitializer' resetter env i cwd
either (return . Left) good res
where
good (b,is) = do
_ <- resetter (const b)
msgs <- readIORef $ _initMessages is
return $ Right msgs
------------------------------------------------------------------------------
-- | Runs a top-level snaplet in the Snap monad.
runBase :: Handler b b a
-> MVar (Snaplet b)
-> Snap a
runBase (Handler m) mvar = do
!b <- liftIO (readMVar mvar)
(!a, _) <- L.runLensed m id b
return $! a
------------------------------------------------------------------------------
-- | Lets you change a snaplet's initial state. It's alomst like a reload,
-- except that it doesn't run the initializer. It just modifies the result of
-- the initializer. This can be used to let you define actions for reloading
-- individual snaplets.
modifyMaster :: v -> Handler b v ()
modifyMaster v = do
modifier <- getsSnapletState _snapletModifier
liftIO $ modifier v
------------------------------------------------------------------------------
-- | Internal function for running Initializers. If any exceptions were
-- thrown by the initializer, this function catches them, runs any cleanup
-- actions that had been registered, and returns an expanded error message
-- containing the exception details as well as all messages generated by the
-- initializer before the exception was thrown.
runInitializer :: ((Snaplet b -> Snaplet b) -> IO ())
-> String
-> Initializer b b (Snaplet b)
-> IO (Either Text (Snaplet b, InitializerState b))
runInitializer resetter env b =
getCurrentDirectory >>= runInitializer' resetter env b
------------------------------------------------------------------------------
runInitializer' :: ((Snaplet b -> Snaplet b) -> IO ())
-> String
-> Initializer b b (Snaplet b)
-> FilePath
-> IO (Either Text (Snaplet b, InitializerState b))
runInitializer' resetter env b@(Initializer i) cwd = do
cleanupRef <- newIORef (return ())
let reloader_ = mkReloader cwd env resetter cleanupRef b
let builtinHandlers = [("/admin/reload", reloadSite)]
let cfg = SnapletConfig [] cwd Nothing "" empty [] Nothing reloader_
logRef <- newIORef ""
let body = do
((res, s), (Hook hook)) <- runWriterT $ LT.runLensT i id $
InitializerState True cleanupRef builtinHandlers id cfg logRef
env resetter
res' <- hook res
return $ (,s) <$> res'
handler e = do
join $ readIORef cleanupRef
logMessages <- readIORef logRef
return $ Left $ T.unlines
[ "Initializer threw an exception..."
, T.pack $ show (e :: SomeException)
, ""
, "...but before it died it generated the following output:"
, logMessages
]
catch body handler
------------------------------------------------------------------------------
-- | Given an environment and a Snaplet initializer, produce a concatenated log
-- of all messages generated during initialization, a snap handler, and a
-- cleanup action. The environment is an arbitrary string such as \"devel\" or
-- \"production\". This string is used to determine the name of the
-- configuration files used by each snaplet. If an environment of Nothing is
-- used, then runSnaplet defaults to \"devel\".
runSnaplet :: Maybe String -> SnapletInit b b -> IO (Text, Snap (), IO ())
runSnaplet env (SnapletInit b) = do
snapletMVar <- newEmptyMVar
let resetter f = modifyMVar_ snapletMVar (return . f)
eRes <- runInitializer resetter (fromMaybe "devel" env) b
let go (siteSnaplet,is) = do
putMVar snapletMVar siteSnaplet
msgs <- liftIO $ readIORef $ _initMessages is
let handler = runBase (_hFilter is $ route $ _handlers is) snapletMVar
cleanupAction <- readIORef $ _cleanup is
return (msgs, handler, cleanupAction)
either (error . ('\n':) . T.unpack) go eRes
------------------------------------------------------------------------------
-- | Given a configuration and a snap handler, complete it and produce the
-- completed configuration as well as a new toplevel handler with things like
-- compression and a 500 handler set up.
combineConfig :: Config Snap a -> Snap () -> IO (Config Snap a, Snap ())
combineConfig config handler = do
conf <- completeConfig config
let catch500 = (flip catch $ fromJust $ getErrorHandler conf)
let compress = if fromJust (getCompression conf)
then withCompression else id
let site = compress $ catch500 handler
return (conf, site)
------------------------------------------------------------------------------
-- | Initialize and run a Snaplet. This function parses command-line arguments,
-- runs the given Snaplet initializer, and starts an HTTP server running the
-- Snaplet's toplevel 'Handler'.
serveSnaplet :: Config Snap AppConfig
-- ^ The configuration of the server - you can usually pass a
-- default 'Config' via
-- 'Snap.Http.Server.Config.defaultConfig'.
-> SnapletInit b b
-- ^ The snaplet initializer function.
-> IO ()
serveSnaplet startConfig initializer = do
config <- commandLineAppConfig startConfig
serveSnapletNoArgParsing config initializer
------------------------------------------------------------------------------
-- | Like 'serveSnaplet', but don't try to parse command-line arguments.
serveSnapletNoArgParsing :: Config Snap AppConfig
-- ^ The configuration of the server - you can usually pass a
-- default 'Config' via
-- 'Snap.Http.Server.Config.defaultConfig'.
-> SnapletInit b b
-- ^ The snaplet initializer function.
-> IO ()
serveSnapletNoArgParsing config initializer = do
let env = appEnvironment =<< getOther config
(msgs, handler, doCleanup) <- runSnaplet env initializer
(conf, site) <- combineConfig config handler
createDirectoryIfMissing False "log"
let serve = httpServe conf
when (loggingEnabled conf) $ liftIO $ hPutStrLn stderr $ T.unpack msgs
_ <- try $ serve $ site
:: IO (Either SomeException ())
doCleanup
where
loggingEnabled = not . (== Just False) . getVerbose
------------------------------------------------------------------------------
-- | Allows you to get all of your app's config data in the IO monad without
-- the web server infrastructure.
loadAppConfig :: FileName
-- ^ The name of the config file to look for. In snap
-- applications, this is something based on the
-- environment...i.e. @devel.cfg@.
-> FilePath
-- ^ Path to the root directory of your project.
-> IO C.Config
loadAppConfig cfg root = do
tree <- buildL root
let groups = loadAppConfig' cfg "" $ dirTree tree
loadGroups groups
------------------------------------------------------------------------------
-- | Recursive worker for loadAppConfig.
loadAppConfig' :: FileName -> Text -> DirTree a -> [(Text, Worth a)]
loadAppConfig' cfg _prefix d@(Dir _ c) =
(map ((_prefix,) . Required) $ getCfg cfg d) ++
concatMap (\a -> loadAppConfig' cfg (nextPrefix $ name a) a) snaplets
where
nextPrefix p = T.concat [_prefix, T.pack p, "."]
snapletsDirs = filter isSnapletsDir c
snaplets = concatMap (filter isDir . contents) snapletsDirs
loadAppConfig' _ _ _ = []
isSnapletsDir :: DirTree t -> Bool
isSnapletsDir (Dir "snaplets" _) = True
isSnapletsDir _ = False
isDir :: DirTree t -> Bool
isDir (Dir _ _) = True
isDir _ = False
isCfg :: FileName -> DirTree t -> Bool
isCfg cfg (File n _) = cfg == n
isCfg _ _ = False
getCfg :: FileName -> DirTree b -> [b]
getCfg cfg (Dir _ c) = map file $ filter (isCfg cfg) c
getCfg _ _ = []
|
sopvop/snap
|
src/Snap/Snaplet/Internal/Initializer.hs
|
bsd-3-clause
| 29,194 | 0 | 19 | 7,776 | 5,567 | 2,891 | 2,676 | 386 | 2 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
-- A monad for manipulating ordered lists. Follows the implementation
-- given in the appendix of O'Neill's and Burton's JFP paper, but
-- doesn't impose any fixed limit of the number of elements.
-- References:
-- Dietz and Sleator: "Two algorithms for maintaining order in a
-- list", in Proc. of 19th ACM Symposium of Theory of Computing, 1987.
-- O'Neill and Burton: "A New Method For Functional Arrays", Journal
-- of Functional Programming, vol7, no 5, September 1997.
module Control.Monad.Adaptive.OrderedList(
Record,
OrderedList,
rval,
next,
order,
delete,
spliceOut,
deleted,
insert,
base,
run,
inM,
record
) where
import Control.Monad(ap,unless)
import Control.Monad.Adaptive.MonadUtil
import Control.Monad.Adaptive.Ref
import Control.Monad.Adaptive.CircularList hiding (delete,insert,next,update)
import qualified Control.Monad.Adaptive.CircularList as CircularList
import System.IO.Unsafe(unsafePerformIO) -- for diagnostic
-- Export:
insert :: Ref m r => Record m r a -> a -> OrderedList m r a (Record m r a)
next :: Ref m r => Record m r a -> OrderedList m r a (Record m r a)
delete :: Ref m r => Record m r a -> OrderedList m r a ()
spliceOut :: Ref m r => Record m r a -> Record m r a -> OrderedList m r a ()
deleted :: Ref m r => Record m r a -> OrderedList m r a Bool
order :: Ref m r => Record m r a -> Record m r a ->
OrderedList m r a Ordering
rval :: Ref m r => Record m r a -> OrderedList m r a a
run :: Ref m r => OrderedList m r a b -> m b
inM :: Ref m r => m b -> OrderedList m r a b
base :: Ref m r => OrderedList m r a (Record m r a)
-- Local:
newtype Record m r a = Record (CircularList m r (Bool,Integer,a))
deR (Record r) = r
data OrderedList m r a b = OL ((r Integer,r Integer,Record m r a) -> m b)
deOL (OL f) = f
run l = do
base <- Record `fmap` circularList (False,0,undefined)
s <- newRef 0
mr <- newRef m
deOL l (mr,s,base)
where
m = 2^16
inM m = OL $ \e -> m
instance Ref m r => Monad (OrderedList m r a) where
return a = inM (return a)
(OL m) >>= f = OL $ \e -> m e >>= \a -> deOL (f a) e
instance Ref m r => Functor (OrderedList m r a) where
fmap f m = m >>= return . f
instance Ref m r => Ref (OrderedList m r a) r where
newRef v = inM (newRef v)
readRef r = inM (readRef r)
writeRef r v = inM (writeRef r v)
mop a o b = op2 o a b
op2 f a b = op1 f a `ap` b
op1 f a = return f `ap` a
instance Eq (OrderedList m r a b) where { }
instance Show (OrderedList m r a b) where { }
instance (Ref m r, Num b) => Num (OrderedList m r a b) where
(+) = op2 (+)
(-) = op2 (-)
(*) = op2 (*)
negate = op1 negate
abs = op1 abs
signum = op1 signum
fromInteger = return . fromInteger
-- fromInt = return . fromInt
instance Ord (OrderedList m r a b) where { }
instance (Ref m r, Real b) => Real (OrderedList m r a b) where { }
instance Enum (OrderedList m r a b) where { }
instance (Ref m r, Integral b) => Integral (OrderedList m r a b) where
rem = op2 rem
div = op2 div
mod = op2 mod
base = OL $ \(m,n,b) -> return b
bigM :: Ref m r => OrderedList m r a Integer
bigM = OL $ \(m,n,b) -> readRef m
size :: Ref m r => OrderedList m r a Integer
size = OL $ \(m,n,b) -> readRef n
adjsize :: Ref m r => Integer -> OrderedList m r a ()
adjsize i = OL $ \(m,n,b) -> do s <- readRef n
writeRef n (s+i)
setSize :: Ref m r => Integer -> OrderedList m r a ()
setSize n' = OL $ \(m,n,b) -> writeRef n n'
record :: Ref m r => Record m r a -> OrderedList m r a (Bool,Integer,a)
record r = inM (val (deR r))
rval r = (\ (d,i,a) -> a) `fmap` record r
next r = Record `fmap` inM (CircularList.next (deR r))
s x = next x
-- label
l :: Ref m r => Record m r a -> OrderedList m r a Integer
l r = (\ (d,i,a) -> i) `fmap` record r
-- gap
g e f = (l f - l e) `mod` bigM
deleted r = (\ (d,i,a) -> d) `fmap` record r
lbase :: Ref m r => OrderedList m r a Integer
lbase = base >>= l
gstar :: Ref m r => Record m r a -> Record m r a -> OrderedList m r a Integer
gstar e f = ifM (mop (l e) (==) (l f))
bigM
(g e f)
order x y = do b <- base
return (compare) `ap` g b x `ap` g b y
update :: Ref m r => ((Bool,Integer)->(Bool,Integer)) ->
Record m r a -> OrderedList m r a ()
update f r = do
(d,i,a) <- record r
let (d',i') = f (d,i)
inM (CircularList.update (deR r) (d',i',a))
delete r = unlessM (deleted r) $ do
ifM (mop lbase (==) (l r))
(error "OrderedList.delete on base element")
(do inM (CircularList.delete (deR r))
update (\ (_,i) -> (True,i)) r
adjsize (-1)
checkinvariant)
spliceOut r s = next r >>= spl where
spl r = do
unlessM (mop lbase (==) (l r)) $
whenM ((==LT) `fmap` order r s)
(do r' <- next r
delete r
spl r')
increaseBigM :: Ref m r => OrderedList m r a ()
increaseBigM = do OL $ \(m,n,b) -> mapRef (*2) m
insert r a = do
ifM (deleted r)
(error "insert: deleted") $ do
whenM (mop bigM (<=) (4*(size+1)*(size+1)))
increaseBigM
r' <- s r
d <- gstar r r'
unless (d > 1)
(renumber r)
li <- (l r + (gstar r r' `div` 2)) `mod` bigM
inM (CircularList.insert (deR r) (False,li,a))
adjsize 1
checkinvariant
next r
renumber :: Ref m r => Record m r a -> OrderedList m r a ()
renumber e = do
let getj j e0 ej = do
ifM (mop (g e0 ej) (>) (return (j * j)))
(return (j,ej)) $ do
ej' <- s ej
ifM (mop (l ej') (==) (l e))
(return (j,ej)) $ do
getj (j+1) e0 ej'
(j,sje) <- s e >>= getj 1 e
d <- gstar e sje
le <- l e
m <- bigM
let ren k ek | k == j = return ()
| otherwise = do
update (const (False,(le + ((k * d) `div` j)) `mod` m)) ek
s ek >>= ren (k+1)
s e >>= ren 1
checkinvariant :: Ref m r => OrderedList m r a ()
checkinvariant = return () -- prall >> base >>= inv
where inv r = do
r' <- s r
unlessM (mop lbase (==) (l r')) $ do
ifM (mop (order r r') (==) (return LT))
(inv r')
(error "invariant")
prall :: Ref m r => OrderedList m r a ()
prall = uprint "prall:" >> base >>= pr where
pr r = do
x <- l r
uprint (show x)
r' <- s r
unlessM (mop (base >>= order r') (==) (return EQ))
(pr r')
uprint s = OL$ (\s' -> unsafePerformIO (putStrLn s) `seq` return ())
|
Blaisorblade/Haskell-Adaptive
|
Control/Monad/Adaptive/OrderedList.hs
|
bsd-3-clause
| 6,741 | 0 | 23 | 2,106 | 3,306 | 1,690 | 1,616 | 170 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-| DRBD proc file parser
This module holds the definition of the parser that extracts status
information from the DRBD proc file.
-}
{-
Copyright (C) 2012 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Storage.Drbd.Parser (drbdStatusParser, commaIntParser) where
import Prelude ()
import Ganeti.Prelude
import Control.Applicative ((<|>))
import qualified Data.Attoparsec.Text as A
import qualified Data.Attoparsec.Combinator as AC
import Data.Attoparsec.Text (Parser)
import Data.List
import Data.Maybe
import Data.Text (Text, unpack)
import Ganeti.Storage.Drbd.Types
-- | Our own space-skipping function, because A.skipSpace also skips
-- newline characters. It skips ZERO or more spaces, so it does not
-- fail if there are no spaces.
skipSpaces :: Parser ()
skipSpaces = A.skipWhile A.isHorizontalSpace
-- | Skips spaces and the given string, then executes a parser and
-- returns its result.
skipSpacesAndString :: Text -> Parser a -> Parser a
skipSpacesAndString s parser =
skipSpaces
*> A.string s
*> parser
-- | Predicate verifying (potentially bad) end of lines
isBadEndOfLine :: Char -> Bool
isBadEndOfLine c = (c == '\0') || A.isEndOfLine c
-- | Takes a parser and returns it with the content wrapped in a Maybe
-- object. The resulting parser never fails, but contains Nothing if
-- it couldn't properly parse the string.
optional :: Parser a -> Parser (Maybe a)
optional parser = (Just <$> parser) <|> pure Nothing
-- | The parser for a whole DRBD status file.
drbdStatusParser :: [DrbdInstMinor] -> Parser DRBDStatus
drbdStatusParser instMinor =
DRBDStatus <$> versionInfoParser
<*> deviceParser instMinor `AC.manyTill` A.endOfInput
<* A.endOfInput
-- | The parser for the version information lines.
versionInfoParser :: Parser VersionInfo
versionInfoParser = do
versionF <- optional versionP
apiF <- optional apiP
protoF <- optional protoP
srcVersionF <- optional srcVersion
ghF <- fmap unpack <$> optional gh
builderF <- fmap unpack <$> optional builder
if isNothing versionF
&& isNothing apiF
&& isNothing protoF
&& isNothing srcVersionF
&& isNothing ghF
&& isNothing builderF
then fail "versionInfo"
else pure $ VersionInfo versionF apiF protoF srcVersionF ghF builderF
where versionP =
A.string "version:"
*> skipSpaces
*> fmap unpack (A.takeWhile $ not . A.isHorizontalSpace)
apiP =
skipSpacesAndString "(api:" . fmap unpack $ A.takeWhile (/= '/')
protoP =
A.string "/proto:"
*> fmap Data.Text.unpack (A.takeWhile (/= ')'))
<* A.takeTill A.isEndOfLine <* A.endOfLine
srcVersion =
A.string "srcversion:"
*> AC.skipMany1 A.space
*> fmap unpack (A.takeTill A.isEndOfLine)
<* A.endOfLine
gh =
A.string "GIT-hash:"
*> skipSpaces
*> A.takeWhile (not . A.isHorizontalSpace)
builder =
skipSpacesAndString "build by" $
skipSpaces
*> A.takeTill A.isEndOfLine
<* A.endOfLine
-- | The parser for a (multi-line) string representing a device.
deviceParser :: [DrbdInstMinor] -> Parser DeviceInfo
deviceParser instMinor = do
_ <- additionalEOL
deviceNum <- skipSpaces *> A.decimal <* A.char ':'
cs <- skipSpacesAndString "cs:" connStateParser
if cs == Unconfigured
then do
_ <- additionalEOL
return $ UnconfiguredDevice deviceNum
else do
ro <- skipSpaces *> skipRoleString *> localRemoteParser roleParser
ds <- skipSpacesAndString "ds:" $ localRemoteParser diskStateParser
replicProtocol <- A.space *> A.anyChar
io <- skipSpaces *> ioFlagsParser <* A.skipWhile isBadEndOfLine
pIndicators <- perfIndicatorsParser
syncS <- conditionalSyncStatusParser cs
reS <- optional resyncParser
act <- optional actLogParser
_ <- additionalEOL
let inst = find ((deviceNum ==) . dimMinor) instMinor
iName = fmap dimInstName inst
return $ DeviceInfo deviceNum cs ro ds replicProtocol io pIndicators
syncS reS act iName
where conditionalSyncStatusParser SyncSource = Just <$> syncStatusParser
conditionalSyncStatusParser SyncTarget = Just <$> syncStatusParser
conditionalSyncStatusParser _ = pure Nothing
skipRoleString = A.string "ro:" <|> A.string "st:"
resyncParser = skipSpacesAndString "resync:" additionalInfoParser
actLogParser = skipSpacesAndString "act_log:" additionalInfoParser
additionalEOL = A.skipWhile A.isEndOfLine
-- | The parser for the connection state.
connStateParser :: Parser ConnState
connStateParser =
standAlone
<|> disconnecting
<|> unconnected
<|> timeout
<|> brokenPipe
<|> networkFailure
<|> protocolError
<|> tearDown
<|> wfConnection
<|> wfReportParams
<|> connected
<|> startingSyncS
<|> startingSyncT
<|> wfBitMapS
<|> wfBitMapT
<|> wfSyncUUID
<|> syncSource
<|> syncTarget
<|> pausedSyncS
<|> pausedSyncT
<|> verifyS
<|> verifyT
<|> unconfigured
where standAlone = A.string "StandAlone" *> pure StandAlone
disconnecting = A.string "Disconnectiog" *> pure Disconnecting
unconnected = A.string "Unconnected" *> pure Unconnected
timeout = A.string "Timeout" *> pure Timeout
brokenPipe = A.string "BrokenPipe" *> pure BrokenPipe
networkFailure = A.string "NetworkFailure" *> pure NetworkFailure
protocolError = A.string "ProtocolError" *> pure ProtocolError
tearDown = A.string "TearDown" *> pure TearDown
wfConnection = A.string "WFConnection" *> pure WFConnection
wfReportParams = A.string "WFReportParams" *> pure WFReportParams
connected = A.string "Connected" *> pure Connected
startingSyncS = A.string "StartingSyncS" *> pure StartingSyncS
startingSyncT = A.string "StartingSyncT" *> pure StartingSyncT
wfBitMapS = A.string "WFBitMapS" *> pure WFBitMapS
wfBitMapT = A.string "WFBitMapT" *> pure WFBitMapT
wfSyncUUID = A.string "WFSyncUUID" *> pure WFSyncUUID
syncSource = A.string "SyncSource" *> pure SyncSource
syncTarget = A.string "SyncTarget" *> pure SyncTarget
pausedSyncS = A.string "PausedSyncS" *> pure PausedSyncS
pausedSyncT = A.string "PausedSyncT" *> pure PausedSyncT
verifyS = A.string "VerifyS" *> pure VerifyS
verifyT = A.string "VerifyT" *> pure VerifyT
unconfigured = A.string "Unconfigured" *> pure Unconfigured
-- | Parser for recognizing strings describing two elements of the
-- same type separated by a '/'. The first one is considered local,
-- the second remote.
localRemoteParser :: Parser a -> Parser (LocalRemote a)
localRemoteParser parser = LocalRemote <$> parser <*> (A.char '/' *> parser)
-- | The parser for resource roles.
roleParser :: Parser Role
roleParser =
primary
<|> secondary
<|> unknown
where primary = A.string "Primary" *> pure Primary
secondary = A.string "Secondary" *> pure Secondary
unknown = A.string "Unknown" *> pure Unknown
-- | The parser for disk states.
diskStateParser :: Parser DiskState
diskStateParser =
diskless
<|> attaching
<|> failed
<|> negotiating
<|> inconsistent
<|> outdated
<|> dUnknown
<|> consistent
<|> upToDate
where diskless = A.string "Diskless" *> pure Diskless
attaching = A.string "Attaching" *> pure Attaching
failed = A.string "Failed" *> pure Failed
negotiating = A.string "Negotiating" *> pure Negotiating
inconsistent = A.string "Inconsistent" *> pure Inconsistent
outdated = A.string "Outdated" *> pure Outdated
dUnknown = A.string "DUnknown" *> pure DUnknown
consistent = A.string "Consistent" *> pure Consistent
upToDate = A.string "UpToDate" *> pure UpToDate
-- | The parser for I/O flags.
ioFlagsParser :: Parser String
ioFlagsParser = fmap unpack . A.takeWhile $ not . isBadEndOfLine
-- | The parser for performance indicators.
perfIndicatorsParser :: Parser PerfIndicators
perfIndicatorsParser =
PerfIndicators
<$> skipSpacesAndString "ns:" A.decimal
<*> skipSpacesAndString "nr:" A.decimal
<*> skipSpacesAndString "dw:" A.decimal
<*> skipSpacesAndString "dr:" A.decimal
<*> skipSpacesAndString "al:" A.decimal
<*> skipSpacesAndString "bm:" A.decimal
<*> skipSpacesAndString "lo:" A.decimal
<*> skipSpacesAndString "pe:" A.decimal
<*> skipSpacesAndString "ua:" A.decimal
<*> skipSpacesAndString "ap:" A.decimal
<*> optional (skipSpacesAndString "ep:" A.decimal)
<*> optional (skipSpacesAndString "wo:" A.anyChar)
<*> optional (skipSpacesAndString "oos:" A.decimal)
<* skipSpaces <* A.endOfLine
-- | The parser for the syncronization status.
syncStatusParser :: Parser SyncStatus
syncStatusParser = do
_ <- statusBarParser
percent <-
skipSpacesAndString "sync'ed:" $ skipSpaces *> A.double <* A.char '%'
partSyncSize <- skipSpaces *> A.char '(' *> A.decimal
totSyncSize <- A.char '/' *> A.decimal <* A.char ')'
sizeUnit <- sizeUnitParser <* optional A.endOfLine
timeToEnd <- skipSpacesAndString "finish:" $ skipSpaces *> timeParser
sp <-
skipSpacesAndString "speed:" $
skipSpaces
*> commaIntParser
<* skipSpaces
<* A.char '('
<* commaIntParser
<* A.char ')'
w <- skipSpacesAndString "want:" (
skipSpaces
*> (Just <$> commaIntParser)
)
<|> pure Nothing
sSizeUnit <- skipSpaces *> sizeUnitParser
sTimeUnit <- A.char '/' *> timeUnitParser
_ <- A.endOfLine
return $
SyncStatus percent partSyncSize totSyncSize sizeUnit timeToEnd sp w
sSizeUnit sTimeUnit
-- | The parser for recognizing (and discarding) the sync status bar.
statusBarParser :: Parser ()
statusBarParser =
skipSpaces
*> A.char '['
*> A.skipWhile (== '=')
*> A.skipWhile (== '>')
*> A.skipWhile (== '.')
*> A.char ']'
*> pure ()
-- | The parser for recognizing data size units (only the ones
-- actually found in DRBD files are implemented).
sizeUnitParser :: Parser SizeUnit
sizeUnitParser =
kilobyte
<|> megabyte
where kilobyte = A.string "K" *> pure KiloByte
megabyte = A.string "M" *> pure MegaByte
-- | The parser for recognizing time (hh:mm:ss).
timeParser :: Parser Time
timeParser = Time <$> h <*> m <*> s
where h = A.decimal :: Parser Int
m = A.char ':' *> A.decimal :: Parser Int
s = A.char ':' *> A.decimal :: Parser Int
-- | The parser for recognizing time units (only the ones actually
-- found in DRBD files are implemented).
timeUnitParser :: Parser TimeUnit
timeUnitParser = second
where second = A.string "sec" *> pure Second
-- | Haskell does not recognise ',' as the thousands separator every 3
-- digits but DRBD uses it, so we need an ah-hoc parser.
-- If a number beginning with more than 3 digits without a comma is
-- parsed, only the first 3 digits are considered to be valid, the rest
-- is not consumed, and left for further parsing.
commaIntParser :: Parser Int
commaIntParser = do
first <-
AC.count 3 A.digit <|> AC.count 2 A.digit <|> AC.count 1 A.digit
allDigits <- commaIntHelper (read first)
pure allDigits
-- | Helper (triplet parser) for the commaIntParser
commaIntHelper :: Int -> Parser Int
commaIntHelper acc = nextTriplet <|> end
where nextTriplet = do
_ <- A.char ','
triplet <- AC.count 3 A.digit
commaIntHelper $ acc * 1000 + (read triplet :: Int)
end = pure acc :: Parser Int
-- | Parser for the additional information provided by DRBD <= 8.0.
additionalInfoParser::Parser AdditionalInfo
additionalInfoParser = AdditionalInfo
<$> skipSpacesAndString "used:" A.decimal
<*> (A.char '/' *> A.decimal)
<*> skipSpacesAndString "hits:" A.decimal
<*> skipSpacesAndString "misses:" A.decimal
<*> skipSpacesAndString "starving:" A.decimal
<*> skipSpacesAndString "dirty:" A.decimal
<*> skipSpacesAndString "changed:" A.decimal
<* A.endOfLine
|
leshchevds/ganeti
|
src/Ganeti/Storage/Drbd/Parser.hs
|
bsd-2-clause
| 13,713 | 0 | 26 | 3,211 | 2,899 | 1,421 | 1,478 | 268 | 4 |
{-# OPTIONS_GHC -Wall #-}
module Nitpick.TopLevelTypes (topLevelTypes) where
import Prelude hiding (maybe)
import qualified Data.Foldable as F
import qualified Data.Map as Map
import qualified AST.Expression.Valid as Valid
import qualified AST.Declaration as Decl
import qualified AST.Module.Name as ModuleName
import qualified AST.Pattern as P
import qualified AST.Type as Type
import qualified AST.Variable as Var
import qualified Elm.Package as Pkg
import qualified Reporting.Annotation as A
import qualified Reporting.Error.Type as Error
import qualified Reporting.Result as Result
import qualified Reporting.Warning as Warning
topLevelTypes
:: Map.Map String Type.Canonical
-> [Decl.ValidDecl]
-> Result.Result Warning.Warning Error.Error ()
topLevelTypes typeEnv validDecls =
do F.traverse_ (warnMissingAnnotation typeEnv) validDecls
checkMainType typeEnv validDecls
-- MISSING ANNOTATIONS
warnMissingAnnotation
:: Map.Map String Type.Canonical
-> Decl.ValidDecl
-> Result.Result Warning.Warning Error.Error ()
warnMissingAnnotation typeEnv (A.A (region,_) decl) =
case decl of
Decl.Definition (Valid.Definition (A.A _ (P.Var name)) _ Nothing) ->
case Map.lookup name typeEnv of
Nothing ->
return ()
Just tipe ->
Result.warn region (Warning.MissingTypeAnnotation name tipe)
_ ->
return ()
-- MAIN TYPE
checkMainType
:: Map.Map String Type.Canonical
-> [Decl.ValidDecl]
-> Result.Result w Error.Error ()
checkMainType typeEnv decls =
case decls of
A.A (region,_) (Decl.Definition (Valid.Definition (A.A _ (P.Var "main")) _ _)) : _ ->
case Map.lookup "main" typeEnv of
Nothing ->
return ()
Just typeOfMain ->
let tipe = Type.deepDealias typeOfMain
in
if tipe `elem` validMainTypes
then return ()
else Result.throw region (Error.BadMain typeOfMain)
_ : remainingDecls ->
checkMainType typeEnv remainingDecls
[] ->
return ()
validMainTypes :: [Type.Canonical]
validMainTypes =
[ element
, html
, signal element
, signal html
]
html :: Type.Canonical
html =
Type.Type (Var.fromModule virtualDom "Node")
virtualDom :: ModuleName.Canonical
virtualDom =
ModuleName.Canonical (Pkg.Name "evancz" "virtual-dom") ["VirtualDom"]
element :: Type.Canonical
element =
core ["Graphics","Element"] "Element"
signal :: Type.Canonical -> Type.Canonical
signal tipe =
Type.App (core ["Signal"] "Signal") [ tipe ]
core :: [String] -> String -> Type.Canonical
core home name =
Type.Type (Var.inCore home name)
|
laszlopandy/elm-compiler
|
src/Nitpick/TopLevelTypes.hs
|
bsd-3-clause
| 2,761 | 0 | 18 | 672 | 799 | 432 | 367 | 77 | 5 |
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow 1994-2004
--
-- -----------------------------------------------------------------------------
module SPARC.Regs (
-- registers
showReg,
virtualRegSqueeze,
realRegSqueeze,
classOfRealReg,
allRealRegs,
-- machine specific info
gReg, iReg, lReg, oReg, fReg,
fp, sp, g0, g1, g2, o0, o1, f0, f1, f6, f8, f22, f26, f27,
-- allocatable
allocatableRegs,
-- args
argRegs,
allArgRegs,
callClobberedRegs,
--
mkVirtualReg,
regDotColor
)
where
import CodeGen.Platform.SPARC
import Reg
import RegClass
import Format
import Unique
import Outputable
import FastTypes
import FastBool
{-
The SPARC has 64 registers of interest; 32 integer registers and 32
floating point registers. The mapping of STG registers to SPARC
machine registers is defined in StgRegs.h. We are, of course,
prepared for any eventuality.
The whole fp-register pairing thing on sparcs is a huge nuisance. See
includes/stg/MachRegs.h for a description of what's going on
here.
-}
-- | Get the standard name for the register with this number.
showReg :: RegNo -> String
showReg n
| n >= 0 && n < 8 = "%g" ++ show n
| n >= 8 && n < 16 = "%o" ++ show (n-8)
| n >= 16 && n < 24 = "%l" ++ show (n-16)
| n >= 24 && n < 32 = "%i" ++ show (n-24)
| n >= 32 && n < 64 = "%f" ++ show (n-32)
| otherwise = panic "SPARC.Regs.showReg: unknown sparc register"
-- Get the register class of a certain real reg
classOfRealReg :: RealReg -> RegClass
classOfRealReg reg
= case reg of
RealRegSingle i
| i < 32 -> RcInteger
| otherwise -> RcFloat
RealRegPair{} -> RcDouble
-- | regSqueeze_class reg
-- Calculuate the maximum number of register colors that could be
-- denied to a node of this class due to having this reg
-- as a neighbour.
--
{-# INLINE virtualRegSqueeze #-}
virtualRegSqueeze :: RegClass -> VirtualReg -> FastInt
virtualRegSqueeze cls vr
= case cls of
RcInteger
-> case vr of
VirtualRegI{} -> _ILIT(1)
VirtualRegHi{} -> _ILIT(1)
_other -> _ILIT(0)
RcFloat
-> case vr of
VirtualRegF{} -> _ILIT(1)
VirtualRegD{} -> _ILIT(2)
_other -> _ILIT(0)
RcDouble
-> case vr of
VirtualRegF{} -> _ILIT(1)
VirtualRegD{} -> _ILIT(1)
_other -> _ILIT(0)
_other -> _ILIT(0)
{-# INLINE realRegSqueeze #-}
realRegSqueeze :: RegClass -> RealReg -> FastInt
realRegSqueeze cls rr
= case cls of
RcInteger
-> case rr of
RealRegSingle regNo
| regNo < 32 -> _ILIT(1)
| otherwise -> _ILIT(0)
RealRegPair{} -> _ILIT(0)
RcFloat
-> case rr of
RealRegSingle regNo
| regNo < 32 -> _ILIT(0)
| otherwise -> _ILIT(1)
RealRegPair{} -> _ILIT(2)
RcDouble
-> case rr of
RealRegSingle regNo
| regNo < 32 -> _ILIT(0)
| otherwise -> _ILIT(1)
RealRegPair{} -> _ILIT(1)
_other -> _ILIT(0)
-- | All the allocatable registers in the machine,
-- including register pairs.
allRealRegs :: [RealReg]
allRealRegs
= [ (RealRegSingle i) | i <- [0..63] ]
++ [ (RealRegPair i (i+1)) | i <- [32, 34 .. 62 ] ]
-- | Get the regno for this sort of reg
gReg, lReg, iReg, oReg, fReg :: Int -> RegNo
gReg x = x -- global regs
oReg x = (8 + x) -- output regs
lReg x = (16 + x) -- local regs
iReg x = (24 + x) -- input regs
fReg x = (32 + x) -- float regs
-- | Some specific regs used by the code generator.
g0, g1, g2, fp, sp, o0, o1, f0, f1, f6, f8, f22, f26, f27 :: Reg
f6 = RegReal (RealRegSingle (fReg 6))
f8 = RegReal (RealRegSingle (fReg 8))
f22 = RegReal (RealRegSingle (fReg 22))
f26 = RegReal (RealRegSingle (fReg 26))
f27 = RegReal (RealRegSingle (fReg 27))
-- g0 is always zero, and writes to it vanish.
g0 = RegReal (RealRegSingle (gReg 0))
g1 = RegReal (RealRegSingle (gReg 1))
g2 = RegReal (RealRegSingle (gReg 2))
-- FP, SP, int and float return (from C) regs.
fp = RegReal (RealRegSingle (iReg 6))
sp = RegReal (RealRegSingle (oReg 6))
o0 = RegReal (RealRegSingle (oReg 0))
o1 = RegReal (RealRegSingle (oReg 1))
f0 = RegReal (RealRegSingle (fReg 0))
f1 = RegReal (RealRegSingle (fReg 1))
-- | Produce the second-half-of-a-double register given the first half.
{-
fPair :: Reg -> Maybe Reg
fPair (RealReg n)
| n >= 32 && n `mod` 2 == 0 = Just (RealReg (n+1))
fPair (VirtualRegD u)
= Just (VirtualRegHi u)
fPair reg
= trace ("MachInstrs.fPair: can't get high half of supposed double reg " ++ showPpr reg)
Nothing
-}
-- | All the regs that the register allocator can allocate to,
-- with the the fixed use regs removed.
--
allocatableRegs :: [RealReg]
allocatableRegs
= let isFree rr
= case rr of
RealRegSingle r
-> isFastTrue (freeReg r)
RealRegPair r1 r2
-> isFastTrue (freeReg r1)
&& isFastTrue (freeReg r2)
in filter isFree allRealRegs
-- | The registers to place arguments for function calls,
-- for some number of arguments.
--
argRegs :: RegNo -> [Reg]
argRegs r
= case r of
0 -> []
1 -> map (RegReal . RealRegSingle . oReg) [0]
2 -> map (RegReal . RealRegSingle . oReg) [0,1]
3 -> map (RegReal . RealRegSingle . oReg) [0,1,2]
4 -> map (RegReal . RealRegSingle . oReg) [0,1,2,3]
5 -> map (RegReal . RealRegSingle . oReg) [0,1,2,3,4]
6 -> map (RegReal . RealRegSingle . oReg) [0,1,2,3,4,5]
_ -> panic "MachRegs.argRegs(sparc): don't know about >6 arguments!"
-- | All all the regs that could possibly be returned by argRegs
--
allArgRegs :: [Reg]
allArgRegs
= map (RegReal . RealRegSingle) [oReg i | i <- [0..5]]
-- These are the regs that we cannot assume stay alive over a C call.
-- TODO: Why can we assume that o6 isn't clobbered? -- BL 2009/02
--
callClobberedRegs :: [Reg]
callClobberedRegs
= map (RegReal . RealRegSingle)
( oReg 7 :
[oReg i | i <- [0..5]] ++
[gReg i | i <- [1..7]] ++
[fReg i | i <- [0..31]] )
-- | Make a virtual reg with this format.
mkVirtualReg :: Unique -> Format -> VirtualReg
mkVirtualReg u format
| not (isFloatFormat format)
= VirtualRegI u
| otherwise
= case format of
FF32 -> VirtualRegF u
FF64 -> VirtualRegD u
_ -> panic "mkVReg"
regDotColor :: RealReg -> SDoc
regDotColor reg
= case classOfRealReg reg of
RcInteger -> text "blue"
RcFloat -> text "red"
_other -> text "green"
|
TomMD/ghc
|
compiler/nativeGen/SPARC/Regs.hs
|
bsd-3-clause
| 7,616 | 0 | 15 | 2,721 | 1,930 | 1,031 | 899 | 151 | 10 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Yesod.Core.Types where
import qualified Blaze.ByteString.Builder as BBuilder
import qualified Blaze.ByteString.Builder.Char.Utf8
import Control.Applicative (Applicative (..))
import Control.Applicative ((<$>))
import Control.Arrow (first)
import Control.Exception (Exception)
import Control.Monad (liftM, ap)
import Control.Monad.Base (MonadBase (liftBase))
import Control.Monad.Catch (MonadCatch (..))
import Control.Monad.Catch (MonadMask (..))
import Control.Monad.IO.Class (MonadIO (liftIO))
import Control.Monad.Logger (LogLevel, LogSource,
MonadLogger (..))
import Control.Monad.Trans.Control (MonadBaseControl (..))
import Control.Monad.Trans.Resource (MonadResource (..), InternalState, runInternalState, MonadThrow (..), monadThrow, ResourceT)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as L
import Data.Conduit (Flush, Source)
import Data.IORef (IORef)
import Data.Map (Map, unionWith)
import qualified Data.Map as Map
import Data.Monoid (Endo (..), Last (..),
Monoid (..))
import Data.Serialize (Serialize (..),
putByteString)
import Data.String (IsString (fromString))
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Lazy.Builder as TBuilder
import Data.Time (UTCTime)
import Data.Typeable (Typeable)
import Language.Haskell.TH.Syntax (Loc)
import qualified Network.HTTP.Types as H
import Network.Wai (FilePart,
RequestBodyLength)
import qualified Network.Wai as W
import qualified Network.Wai.Parse as NWP
import System.Log.FastLogger (LogStr, LoggerSet, toLogStr, pushLogStr)
import qualified System.Random.MWC as MWC
import Network.Wai.Logger (DateCacheGetter)
import Text.Blaze.Html (Html, toHtml)
import Text.Hamlet (HtmlUrl)
import Text.Julius (JavascriptUrl)
import Web.Cookie (SetCookie)
import Yesod.Core.Internal.Util (getTime, putTime)
import Control.Monad.Trans.Class (MonadTrans (..))
import Yesod.Routes.Class (RenderRoute (..), ParseRoute (..))
import Control.Monad.Reader (MonadReader (..))
#if !MIN_VERSION_base(4, 6, 0)
import Prelude hiding (catch)
#endif
import Control.DeepSeq (NFData (rnf))
import Data.Conduit.Lazy (MonadActive, monadActive)
import Yesod.Core.TypeCache (TypeMap, KeyedTypeMap)
#if MIN_VERSION_monad_logger(0, 3, 10)
import Control.Monad.Logger (MonadLoggerIO (..))
#endif
import Data.Semigroup (Semigroup)
-- Sessions
type SessionMap = Map Text ByteString
type SaveSession = SessionMap -- ^ The session contents after running the handler
-> IO [Header]
newtype SessionBackend = SessionBackend
{ sbLoadSession :: W.Request
-> IO (SessionMap, SaveSession) -- ^ Return the session data and a function to save the session
}
data SessionCookie = SessionCookie (Either UTCTime ByteString) ByteString SessionMap
deriving (Show, Read)
instance Serialize SessionCookie where
put (SessionCookie a b c) = do
either putTime putByteString a
put b
put (map (first T.unpack) $ Map.toList c)
get = do
a <- getTime
b <- get
c <- map (first T.pack) <$> get
return $ SessionCookie (Left a) b (Map.fromList c)
data ClientSessionDateCache =
ClientSessionDateCache {
csdcNow :: !UTCTime
, csdcExpires :: !UTCTime
, csdcExpiresSerialized :: !ByteString
} deriving (Eq, Show)
-- | The parsed request information. This type augments the standard WAI
-- 'W.Request' with additional information.
data YesodRequest = YesodRequest
{ reqGetParams :: ![(Text, Text)]
-- ^ Same as 'W.queryString', but decoded to @Text@.
, reqCookies :: ![(Text, Text)]
, reqWaiRequest :: !W.Request
, reqLangs :: ![Text]
-- ^ Languages which the client supports. This is an ordered list by preference.
, reqToken :: !(Maybe Text)
-- ^ A random, session-specific token used to prevent CSRF attacks.
, reqSession :: !SessionMap
-- ^ Initial session sent from the client.
--
-- Since 1.2.0
, reqAccept :: ![ContentType]
-- ^ An ordered list of the accepted content types.
--
-- Since 1.2.0
}
-- | An augmented WAI 'W.Response'. This can either be a standard @Response@,
-- or a higher-level data structure which Yesod will turn into a @Response@.
data YesodResponse
= YRWai !W.Response
| YRWaiApp !W.Application
| YRPlain !H.Status ![Header] !ContentType !Content !SessionMap
-- | A tuple containing both the POST parameters and submitted files.
type RequestBodyContents =
( [(Text, Text)]
, [(Text, FileInfo)]
)
data FileInfo = FileInfo
{ fileName :: !Text
, fileContentType :: !Text
, fileSourceRaw :: !(Source (ResourceT IO) ByteString)
, fileMove :: !(FilePath -> IO ())
}
data FileUpload = FileUploadMemory !(NWP.BackEnd L.ByteString)
| FileUploadDisk !(InternalState -> NWP.BackEnd FilePath)
| FileUploadSource !(NWP.BackEnd (Source (ResourceT IO) ByteString))
-- | How to determine the root of the application for constructing URLs.
--
-- Note that future versions of Yesod may add new constructors without bumping
-- the major version number. As a result, you should /not/ pattern match on
-- @Approot@ values.
data Approot master = ApprootRelative -- ^ No application root.
| ApprootStatic !Text
| ApprootMaster !(master -> Text)
| ApprootRequest !(master -> W.Request -> Text)
type ResolvedApproot = Text
data AuthResult = Authorized | AuthenticationRequired | Unauthorized Text
deriving (Eq, Show, Read)
data ScriptLoadPosition master
= BottomOfBody
| BottomOfHeadBlocking
| BottomOfHeadAsync (BottomOfHeadAsync master)
type BottomOfHeadAsync master
= [Text] -- ^ urls to load asynchronously
-> Maybe (HtmlUrl (Route master)) -- ^ widget of js to run on async completion
-> (HtmlUrl (Route master)) -- ^ widget to insert at the bottom of <head>
type Texts = [Text]
-- | Wrap up a normal WAI application as a Yesod subsite.
newtype WaiSubsite = WaiSubsite { runWaiSubsite :: W.Application }
data RunHandlerEnv site = RunHandlerEnv
{ rheRender :: !(Route site -> [(Text, Text)] -> Text)
, rheRoute :: !(Maybe (Route site))
, rheSite :: !site
, rheUpload :: !(RequestBodyLength -> FileUpload)
, rheLog :: !(Loc -> LogSource -> LogLevel -> LogStr -> IO ())
, rheOnError :: !(ErrorResponse -> YesodApp)
, rheGetMaxExpires :: IO Text
-- ^ How to respond when an error is thrown internally.
--
-- Since 1.2.0
}
data HandlerData site parentRoute = HandlerData
{ handlerRequest :: !YesodRequest
, handlerEnv :: !(RunHandlerEnv site)
, handlerState :: !(IORef GHState)
, handlerToParent :: !(Route site -> parentRoute)
, handlerResource :: !InternalState
}
data YesodRunnerEnv site = YesodRunnerEnv
{ yreLogger :: !Logger
, yreSite :: !site
, yreSessionBackend :: !(Maybe SessionBackend)
, yreGen :: !MWC.GenIO
}
data YesodSubRunnerEnv sub parent parentMonad = YesodSubRunnerEnv
{ ysreParentRunner :: !(ParentRunner parent parentMonad)
, ysreGetSub :: !(parent -> sub)
, ysreToParentRoute :: !(Route sub -> Route parent)
, ysreParentEnv :: !(YesodRunnerEnv parent) -- FIXME maybe get rid of this and remove YesodRunnerEnv in ParentRunner?
}
type ParentRunner parent m
= m TypedContent
-> YesodRunnerEnv parent
-> Maybe (Route parent)
-> W.Application
-- | A generic handler monad, which can have a different subsite and master
-- site. We define a newtype for better error message.
newtype HandlerT site m a = HandlerT
{ unHandlerT :: HandlerData site (MonadRoute m) -> m a
}
type family MonadRoute (m :: * -> *)
type instance MonadRoute IO = ()
type instance MonadRoute (HandlerT site m) = (Route site)
data GHState = GHState
{ ghsSession :: SessionMap
, ghsRBC :: Maybe RequestBodyContents
, ghsIdent :: Int
, ghsCache :: TypeMap
, ghsCacheBy :: KeyedTypeMap
, ghsHeaders :: Endo [Header]
}
-- | An extension of the basic WAI 'W.Application' datatype to provide extra
-- features needed by Yesod. Users should never need to use this directly, as
-- the 'HandlerT' monad and template haskell code should hide it away.
type YesodApp = YesodRequest -> ResourceT IO YesodResponse
-- | A generic widget, allowing specification of both the subsite and master
-- site datatypes. While this is simply a @WriterT@, we define a newtype for
-- better error messages.
newtype WidgetT site m a = WidgetT
{ unWidgetT :: HandlerData site (MonadRoute m) -> m (a, GWData (Route site))
}
instance (a ~ (), Monad m) => Monoid (WidgetT site m a) where
mempty = return ()
mappend x y = x >> y
instance (a ~ (), Monad m) => Semigroup (WidgetT site m a)
-- | A 'String' can be trivially promoted to a widget.
--
-- For example, in a yesod-scaffold site you could use:
--
-- @getHomeR = do defaultLayout "Widget text"@
instance (Monad m, a ~ ()) => IsString (WidgetT site m a) where
fromString = toWidget . toHtml . T.pack
where toWidget x = WidgetT $ const $ return $ ((), GWData (Body (const x))
mempty mempty mempty mempty mempty mempty)
type RY master = Route master -> [(Text, Text)] -> Text
-- | Newtype wrapper allowing injection of arbitrary content into CSS.
--
-- Usage:
--
-- > toWidget $ CssBuilder "p { color: red }"
--
-- Since: 1.1.3
newtype CssBuilder = CssBuilder { unCssBuilder :: TBuilder.Builder }
-- | Content for a web page. By providing this datatype, we can easily create
-- generic site templates, which would have the type signature:
--
-- > PageContent url -> HtmlUrl url
data PageContent url = PageContent
{ pageTitle :: Html
, pageHead :: HtmlUrl url
, pageBody :: HtmlUrl url
}
data Content = ContentBuilder !BBuilder.Builder !(Maybe Int) -- ^ The content and optional content length.
| ContentSource !(Source (ResourceT IO) (Flush BBuilder.Builder))
| ContentFile !FilePath !(Maybe FilePart)
| ContentDontEvaluate !Content
data TypedContent = TypedContent !ContentType !Content
type RepHtml = Html
{-# DEPRECATED RepHtml "Please use Html instead" #-}
newtype RepJson = RepJson Content
newtype RepPlain = RepPlain Content
newtype RepXml = RepXml Content
type ContentType = ByteString -- FIXME Text?
-- | Prevents a response body from being fully evaluated before sending the
-- request.
--
-- Since 1.1.0
newtype DontFullyEvaluate a = DontFullyEvaluate { unDontFullyEvaluate :: a }
-- | Responses to indicate some form of an error occurred.
data ErrorResponse =
NotFound
| InternalError Text
| InvalidArgs [Text]
| NotAuthenticated
| PermissionDenied Text
| BadMethod H.Method
deriving (Show, Eq, Typeable)
----- header stuff
-- | Headers to be added to a 'Result'.
data Header =
AddCookie SetCookie
| DeleteCookie ByteString ByteString
| Header ByteString ByteString
deriving (Eq, Show)
-- FIXME In the next major version bump, let's just add strictness annotations
-- to Header (and probably everywhere else). We can also add strictness
-- annotations to SetCookie in the cookie package.
instance NFData Header where
rnf (AddCookie x) = rnf x
rnf (DeleteCookie x y) = x `seq` y `seq` ()
rnf (Header x y) = x `seq` y `seq` ()
data Location url = Local url | Remote Text
deriving (Show, Eq)
-- | A diff list that does not directly enforce uniqueness.
-- When creating a widget Yesod will use nub to make it unique.
newtype UniqueList x = UniqueList ([x] -> [x])
data Script url = Script { scriptLocation :: Location url, scriptAttributes :: [(Text, Text)] }
deriving (Show, Eq)
data Stylesheet url = Stylesheet { styleLocation :: Location url, styleAttributes :: [(Text, Text)] }
deriving (Show, Eq)
newtype Title = Title { unTitle :: Html }
newtype Head url = Head (HtmlUrl url)
deriving Monoid
instance Semigroup (Head a)
newtype Body url = Body (HtmlUrl url)
deriving Monoid
instance Semigroup (Body a)
type CssBuilderUrl a = (a -> [(Text, Text)] -> Text) -> TBuilder.Builder
data GWData a = GWData
{ gwdBody :: !(Body a)
, gwdTitle :: !(Last Title)
, gwdScripts :: !(UniqueList (Script a))
, gwdStylesheets :: !(UniqueList (Stylesheet a))
, gwdCss :: !(Map (Maybe Text) (CssBuilderUrl a)) -- media type
, gwdJavascript :: !(Maybe (JavascriptUrl a))
, gwdHead :: !(Head a)
}
instance Monoid (GWData a) where
mempty = GWData mempty mempty mempty mempty mempty mempty mempty
mappend (GWData a1 a2 a3 a4 a5 a6 a7)
(GWData b1 b2 b3 b4 b5 b6 b7) = GWData
(a1 `mappend` b1)
(a2 `mappend` b2)
(a3 `mappend` b3)
(a4 `mappend` b4)
(unionWith mappend a5 b5)
(a6 `mappend` b6)
(a7 `mappend` b7)
instance Semigroup (GWData a)
data HandlerContents =
HCContent H.Status !TypedContent
| HCError ErrorResponse
| HCSendFile ContentType FilePath (Maybe FilePart)
| HCRedirect H.Status Text
| HCCreated Text
| HCWai W.Response
| HCWaiApp W.Application
deriving Typeable
instance Show HandlerContents where
show (HCContent status (TypedContent t _)) = "HCContent " ++ show (status, t)
show (HCError e) = "HCError " ++ show e
show (HCSendFile ct fp mfp) = "HCSendFile " ++ show (ct, fp, mfp)
show (HCRedirect s t) = "HCRedirect " ++ show (s, t)
show (HCCreated t) = "HCCreated " ++ show t
show (HCWai _) = "HCWai"
show (HCWaiApp _) = "HCWaiApp"
instance Exception HandlerContents
-- Instances for WidgetT
instance Monad m => Functor (WidgetT site m) where
fmap = liftM
instance Monad m => Applicative (WidgetT site m) where
pure = return
(<*>) = ap
instance Monad m => Monad (WidgetT site m) where
return a = WidgetT $ const $ return (a, mempty)
WidgetT x >>= f = WidgetT $ \r -> do
(a, wa) <- x r
(b, wb) <- unWidgetT (f a) r
return (b, wa `mappend` wb)
instance MonadIO m => MonadIO (WidgetT site m) where
liftIO = lift . liftIO
instance MonadBase b m => MonadBase b (WidgetT site m) where
liftBase = WidgetT . const . liftBase . fmap (, mempty)
instance MonadBaseControl b m => MonadBaseControl b (WidgetT site m) where
#if MIN_VERSION_monad_control(1,0,0)
type StM (WidgetT site m) a = StM m (a, GWData (Route site))
liftBaseWith f = WidgetT $ \reader' ->
liftBaseWith $ \runInBase ->
liftM (\x -> (x, mempty))
(f $ runInBase . flip unWidgetT reader')
restoreM = WidgetT . const . restoreM
#else
data StM (WidgetT site m) a = StW (StM m (a, GWData (Route site)))
liftBaseWith f = WidgetT $ \reader' ->
liftBaseWith $ \runInBase ->
liftM (\x -> (x, mempty))
(f $ liftM StW . runInBase . flip unWidgetT reader')
restoreM (StW base) = WidgetT $ const $ restoreM base
#endif
instance Monad m => MonadReader site (WidgetT site m) where
ask = WidgetT $ \hd -> return (rheSite $ handlerEnv hd, mempty)
local f (WidgetT g) = WidgetT $ \hd -> g hd
{ handlerEnv = (handlerEnv hd)
{ rheSite = f $ rheSite $ handlerEnv hd
}
}
instance MonadTrans (WidgetT site) where
lift = WidgetT . const . liftM (, mempty)
instance MonadThrow m => MonadThrow (WidgetT site m) where
throwM = lift . throwM
instance MonadCatch m => MonadCatch (HandlerT site m) where
catch (HandlerT m) c = HandlerT $ \r -> m r `catch` \e -> unHandlerT (c e) r
instance MonadMask m => MonadMask (HandlerT site m) where
mask a = HandlerT $ \e -> mask $ \u -> unHandlerT (a $ q u) e
where q u (HandlerT b) = HandlerT (u . b)
uninterruptibleMask a =
HandlerT $ \e -> uninterruptibleMask $ \u -> unHandlerT (a $ q u) e
where q u (HandlerT b) = HandlerT (u . b)
instance MonadCatch m => MonadCatch (WidgetT site m) where
catch (WidgetT m) c = WidgetT $ \r -> m r `catch` \e -> unWidgetT (c e) r
instance MonadMask m => MonadMask (WidgetT site m) where
mask a = WidgetT $ \e -> mask $ \u -> unWidgetT (a $ q u) e
where q u (WidgetT b) = WidgetT (u . b)
uninterruptibleMask a =
WidgetT $ \e -> uninterruptibleMask $ \u -> unWidgetT (a $ q u) e
where q u (WidgetT b) = WidgetT (u . b)
instance (Applicative m, MonadIO m, MonadBase IO m, MonadThrow m) => MonadResource (WidgetT site m) where
liftResourceT f = WidgetT $ \hd -> liftIO $ fmap (, mempty) $ runInternalState f (handlerResource hd)
instance MonadIO m => MonadLogger (WidgetT site m) where
monadLoggerLog a b c d = WidgetT $ \hd ->
liftIO $ fmap (, mempty) $ rheLog (handlerEnv hd) a b c (toLogStr d)
#if MIN_VERSION_monad_logger(0, 3, 10)
instance MonadIO m => MonadLoggerIO (WidgetT site m) where
askLoggerIO = WidgetT $ \hd -> return (rheLog (handlerEnv hd), mempty)
#endif
instance MonadActive m => MonadActive (WidgetT site m) where
monadActive = lift monadActive
instance MonadActive m => MonadActive (HandlerT site m) where
monadActive = lift monadActive
instance MonadTrans (HandlerT site) where
lift = HandlerT . const
-- Instances for HandlerT
instance Monad m => Functor (HandlerT site m) where
fmap = liftM
instance Monad m => Applicative (HandlerT site m) where
pure = return
(<*>) = ap
instance Monad m => Monad (HandlerT site m) where
return = HandlerT . const . return
HandlerT x >>= f = HandlerT $ \r -> x r >>= \x' -> unHandlerT (f x') r
instance MonadIO m => MonadIO (HandlerT site m) where
liftIO = lift . liftIO
instance MonadBase b m => MonadBase b (HandlerT site m) where
liftBase = lift . liftBase
instance Monad m => MonadReader site (HandlerT site m) where
ask = HandlerT $ return . rheSite . handlerEnv
local f (HandlerT g) = HandlerT $ \hd -> g hd
{ handlerEnv = (handlerEnv hd)
{ rheSite = f $ rheSite $ handlerEnv hd
}
}
-- | Note: although we provide a @MonadBaseControl@ instance, @lifted-base@'s
-- @fork@ function is incompatible with the underlying @ResourceT@ system.
-- Instead, if you must fork a separate thread, you should use
-- @resourceForkIO@.
--
-- Using fork usually leads to an exception that says
-- \"Control.Monad.Trans.Resource.register\': The mutable state is being accessed
-- after cleanup. Please contact the maintainers.\"
instance MonadBaseControl b m => MonadBaseControl b (HandlerT site m) where
#if MIN_VERSION_monad_control(1,0,0)
type StM (HandlerT site m) a = StM m a
liftBaseWith f = HandlerT $ \reader' ->
liftBaseWith $ \runInBase ->
f $ runInBase . (\(HandlerT r) -> r reader')
restoreM = HandlerT . const . restoreM
#else
data StM (HandlerT site m) a = StH (StM m a)
liftBaseWith f = HandlerT $ \reader' ->
liftBaseWith $ \runInBase ->
f $ liftM StH . runInBase . (\(HandlerT r) -> r reader')
restoreM (StH base) = HandlerT $ const $ restoreM base
#endif
instance MonadThrow m => MonadThrow (HandlerT site m) where
throwM = lift . monadThrow
instance (MonadIO m, MonadBase IO m, MonadThrow m) => MonadResource (HandlerT site m) where
liftResourceT f = HandlerT $ \hd -> liftIO $ runInternalState f (handlerResource hd)
instance MonadIO m => MonadLogger (HandlerT site m) where
monadLoggerLog a b c d = HandlerT $ \hd ->
liftIO $ rheLog (handlerEnv hd) a b c (toLogStr d)
#if MIN_VERSION_monad_logger(0, 3, 10)
instance MonadIO m => MonadLoggerIO (HandlerT site m) where
askLoggerIO = HandlerT $ \hd -> return (rheLog (handlerEnv hd))
#endif
instance Monoid (UniqueList x) where
mempty = UniqueList id
UniqueList x `mappend` UniqueList y = UniqueList $ x . y
instance Semigroup (UniqueList x)
instance IsString Content where
fromString = flip ContentBuilder Nothing . Blaze.ByteString.Builder.Char.Utf8.fromString
instance RenderRoute WaiSubsite where
data Route WaiSubsite = WaiSubsiteRoute [Text] [(Text, Text)]
deriving (Show, Eq, Read, Ord)
renderRoute (WaiSubsiteRoute ps qs) = (ps, qs)
instance ParseRoute WaiSubsite where
parseRoute (x, y) = Just $ WaiSubsiteRoute x y
data Logger = Logger
{ loggerSet :: !LoggerSet
, loggerDate :: !DateCacheGetter
}
loggerPutStr :: Logger -> LogStr -> IO ()
loggerPutStr (Logger ls _) = pushLogStr ls
|
Daniel-Diaz/yesod
|
yesod-core/Yesod/Core/Types.hs
|
mit
| 22,121 | 0 | 16 | 5,980 | 5,743 | 3,183 | 2,560 | -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="ja-JP">
<title>Linux WebDrivers</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/webdrivers/webdriverlinux/src/main/javahelp/org/zaproxy/zap/extension/webdriverlinux/resources/help_ja_JP/helpset_ja_JP.hs
|
apache-2.0
| 961 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
{-# LANGUAGE MagicHash #-}
module StrictBinds where
import GHC.Exts
foo = let x = 3# +# y
y = x in
True
|
ezyang/ghc
|
testsuite/tests/typecheck/should_fail/StrictBinds.hs
|
bsd-3-clause
| 123 | 0 | 9 | 41 | 35 | 20 | 15 | 6 | 1 |
{-# LANGUAGE PatternSynonyms, ExistentialQuantification #-}
module ExQuant where
data Showable = forall a . Show a => Showable a
pattern Nasty{a} = Showable a
qux = a (Showable True)
foo = (Showable ()) { a = True }
|
ezyang/ghc
|
testsuite/tests/patsyn/should_fail/records-exquant.hs
|
bsd-3-clause
| 220 | 0 | 8 | 42 | 78 | 42 | 36 | 6 | 1 |
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you 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.
--
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Thrift.Types where
import Data.Foldable (foldl')
import Data.Hashable ( Hashable, hashWithSalt )
import Data.Int
import Test.QuickCheck.Arbitrary
import Test.QuickCheck.Gen (elements)
import Data.Text.Lazy (Text)
import qualified Data.ByteString.Lazy as LBS
import qualified Data.HashMap.Strict as Map
import qualified Data.HashSet as Set
import qualified Data.Vector as Vector
instance (Hashable k, Hashable v) => Hashable (Map.HashMap k v) where
hashWithSalt salt = foldl' hashWithSalt salt . Map.toList
instance (Hashable a) => Hashable (Set.HashSet a) where
hashWithSalt = foldl' hashWithSalt
instance (Hashable a) => Hashable (Vector.Vector a) where
hashWithSalt = Vector.foldl' hashWithSalt
type TypeMap = Map.HashMap Int16 (Text, ThriftType)
data ThriftVal = TStruct (Map.HashMap Int16 (Text, ThriftVal))
| TMap ThriftType ThriftType [(ThriftVal, ThriftVal)]
| TList ThriftType [ThriftVal]
| TSet ThriftType [ThriftVal]
| TBool Bool
| TByte Int8
| TI16 Int16
| TI32 Int32
| TI64 Int64
| TString LBS.ByteString
| TDouble Double
deriving (Eq, Show)
-- Information is needed here for collection types (ie T_STRUCT, T_MAP,
-- T_LIST, and T_SET) so that we know what types those collections are
-- parameterized by. In most protocols, this cannot be discerned directly
-- from the data being read.
data ThriftType
= T_STOP
| T_VOID
| T_BOOL
| T_BYTE
| T_DOUBLE
| T_I16
| T_I32
| T_I64
| T_STRING
| T_STRUCT TypeMap
| T_MAP ThriftType ThriftType
| T_SET ThriftType
| T_LIST ThriftType
deriving ( Eq, Show )
-- NOTE: when using toEnum information about parametized types is NOT preserved.
-- This design choice is consistent woth the Thrift implementation in other
-- languages
instance Enum ThriftType where
fromEnum T_STOP = 0
fromEnum T_VOID = 1
fromEnum T_BOOL = 2
fromEnum T_BYTE = 3
fromEnum T_DOUBLE = 4
fromEnum T_I16 = 6
fromEnum T_I32 = 8
fromEnum T_I64 = 10
fromEnum T_STRING = 11
fromEnum (T_STRUCT _) = 12
fromEnum (T_MAP _ _) = 13
fromEnum (T_SET _) = 14
fromEnum (T_LIST _) = 15
toEnum 0 = T_STOP
toEnum 1 = T_VOID
toEnum 2 = T_BOOL
toEnum 3 = T_BYTE
toEnum 4 = T_DOUBLE
toEnum 6 = T_I16
toEnum 8 = T_I32
toEnum 10 = T_I64
toEnum 11 = T_STRING
toEnum 12 = T_STRUCT Map.empty
toEnum 13 = T_MAP T_VOID T_VOID
toEnum 14 = T_SET T_VOID
toEnum 15 = T_LIST T_VOID
toEnum t = error $ "Invalid ThriftType " ++ show t
data MessageType
= M_CALL
| M_REPLY
| M_EXCEPTION
| M_ONEWAY
deriving ( Eq, Show )
instance Enum MessageType where
fromEnum M_CALL = 1
fromEnum M_REPLY = 2
fromEnum M_EXCEPTION = 3
fromEnum M_ONEWAY = 4
toEnum 1 = M_CALL
toEnum 2 = M_REPLY
toEnum 3 = M_EXCEPTION
toEnum 4 = M_ONEWAY
toEnum t = error $ "Invalid MessageType " ++ show t
instance Arbitrary MessageType where
arbitrary = elements [M_CALL, M_REPLY, M_EXCEPTION, M_ONEWAY]
|
traceguide/api-php
|
vendor/apache/thrift/lib/hs/src/Thrift/Types.hs
|
mit
| 4,101 | 0 | 9 | 1,078 | 858 | 479 | 379 | 92 | 0 |
{-# LANGUAGE TypeFamilies #-}
module ShouldCompile where
class C1 a where
data S1 a :: *
-- instance of data families can be data or newtypes
instance C1 Char where
newtype S1 Char = S1Char ()
|
urbanslug/ghc
|
testsuite/tests/indexed-types/should_compile/Simple7.hs
|
bsd-3-clause
| 200 | 0 | 7 | 43 | 44 | 25 | 19 | 6 | 0 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ImpredicativeTypes #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE StandaloneDeriving #-}
module Data.KDTree where
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Algorithms.Intro as I
import qualified Data.List as L
import Data.Function
import Control.DeepSeq
import Control.Arrow
import Data.Functor.Foldable
--------------------------------------------------
class KDCompare a where
data Dim a :: *
kSucc :: Dim a -> Dim a
kFirst :: Dim a
dimDistance :: Dim a -> a -> a -> Double
realSqDist :: a -> a -> Double
dimCompare :: Dim a -> a -> a -> Ordering
--------------------------------------------------
-- | define a kd tree
-- planes are seperated by point + normal
data KDTree v a = Node (Dim a) a (KDTree v a) (KDTree v a)
| Leaf (Dim a) (v a)
deriving instance (Show (v a), Show (Dim a), Show a) => Show (KDTree v a)
deriving instance (Read (v a), Read (Dim a), Read a) => Read (KDTree v a)
deriving instance (Eq (v a), Eq (Dim a), Eq a) => Eq (KDTree v a)
-- | define the fix point variant of KDTree
data KDTreeF v a f = NodeF (Dim a) a f f
| LeafF (Dim a) (v a)
deriving (Functor)
-- implement Base, Foldable and Unfoldable for KDTree
type instance Base (KDTree v a) = KDTreeF v a
instance Foldable (KDTree v a) where
project (Leaf d a) = LeafF d a
project (Node d p l r) = NodeF d p l r
instance Unfoldable (KDTree v a) where
embed (LeafF d a) = Leaf d a
embed (NodeF d p l r) = Node d p l r
---
instance (NFData (v a), NFData a) => NFData (KDTree v a) where
rnf (Leaf _ vs) = rnf vs
rnf (Node _ _ l r) = rnf l `seq` rnf r `seq` ()
--------------------------------------------------
newtype BucketSize = BucketSize {unMB :: Int}
deriving (Eq,Ord,Show,Read,Num)
--------------------------------------------------
empty :: (KDCompare a, G.Vector v a) => KDTree v a
empty = Leaf kFirst G.empty
singleton :: (KDCompare a, G.Vector v a) => a -> KDTree v a
singleton x = Leaf kFirst (G.singleton x)
toVec :: (G.Vector v a) => KDTree v a -> v a
toVec = cata toVecF
toVecF :: (G.Vector v a) => KDTreeF v a (v a) -> v a
toVecF (LeafF _ xs) = xs
toVecF (NodeF _ _ l r) = l G.++ r
toList :: (G.Vector v a) => KDTree v a -> [a]
toList = cata toListF
toListF :: (G.Vector v a) => KDTreeF v a [a] -> [a]
toListF (LeafF _ xs) = G.toList xs
toListF (NodeF _ _ l r) = l ++ r
--------------------------------------------------
--------------------------------------------------
kdtree :: (KDCompare a, G.Vector v a) => BucketSize -> v a -> KDTree v a
kdtree mb vs = ana (kdtreeF mb) (kFirst,vs)
kdtree' :: (KDCompare a, G.Vector v a) => Dim a -> BucketSize -> v a -> KDTree v a
kdtree' kf mb vs = ana (kdtreeF mb) (kf,vs)
{-# INLINABLE kdtree #-}
{-# INLINABLE kdtree' #-}
kdtreeF :: (KDCompare a, G.Vector v a)
=> BucketSize -> (Dim a,v a) -> KDTreeF v a (Dim a,v a)
kdtreeF (BucketSize mb) = go
where go (k,fs) | G.length fs <= mb = LeafF k fs
| otherwise = NodeF k (G.head r) (kSucc k,l) (kSucc k,r)
where (l,r) = splitBuckets k fs
{-# INLINABLE kdtreeF #-}
splitBuckets :: (KDCompare a, G.Vector v a)
=> Dim a -> v a -> (v a, v a)
splitBuckets dim vs = G.splitAt (G.length vs `quot` 2)
. vecSortBy (dimCompare dim)
$ vs
{-# INLINABLE splitBuckets #-}
--------------------------------------------------
verify :: (KDCompare a, G.Vector v a) => KDTree v a -> Bool
verify (Node d p l r) = leftValid && rightValid
where leftSmaller = G.all (\x -> x `comp` p == LT) $ toVec l
rightSmaller = G.all (\x -> x `comp` p /= LT) $ toVec r
leftValid = verify l && leftSmaller
rightValid = verify r && rightSmaller
comp = dimCompare d
verify (Leaf _ _ ) = True
--------------------------------------------------
-- | get all points in the tree, sorted by distance to the 'q'uery point
-- | this is the 'bread and butter' function and should be quite fast
nearestNeighbors :: (KDCompare a, G.Vector v a) => a -> KDTree v a -> [a]
nearestNeighbors q = cata (nearestNeighborsF q)
{-# INLINABLE nearestNeighbors #-}
nearestNeighborsF :: (KDCompare a, G.Vector v a) => a -> KDTreeF v a [a] -> [a]
nearestNeighborsF q (LeafF _ vs) = L.sortBy (compare `on` realSqDist q) . G.toList $ vs
nearestNeighborsF q (NodeF d p l r) = if x < 0 then go l r else go r l
where x = dimDistance d q p
go = mergeBuckets x q
{-# INLINABLE nearestNeighborsF #-}
-- recursively merge the two children
-- the second line makes sure that points in the
-- 'safe' region are prefered
mergeBuckets :: (KDCompare a) => Double -> a -> [a] -> [a] -> [a]
mergeBuckets d q = go
where rdq = realSqDist q
go [] bs = bs
go (a:as) bs | rdq a < d*d = a : go as bs
go as [] = as
go (a:as) (b:bs) | rdq a < rdq b = a : go as (b:bs)
| otherwise = b : go (a:as) bs
{-# INLINABLE mergeBuckets #-}
--------------------------------------------------
-- | get the nearest neighbor of point q
nearestNeighbor :: (KDCompare a, G.Vector v a) => a -> KDTree v a -> a
nearestNeighbor q = head . nearestNeighbors q
{-# INLINABLE nearestNeighbor #-}
----------------------------------------------------
-- | return the points around a 'q'uery point up to radius 'r'
pointsAround :: (KDCompare a, G.Vector v a) => Double -> a -> KDTree v a -> [a]
pointsAround r q = takeWhile (\p -> realSqDist q p < r*r) . nearestNeighbors q
{-# INLINABLE pointsAround #-}
--------------------------------------------------
partition :: (KDCompare a, G.Vector v a, Eq (Dim a))
=> Dim a -> Ordering -> a -> KDTree v a -> (KDTree v a, KDTree v a)
partition dim ord q = go
where go (Leaf d vs) = (Leaf d valid, Leaf d invalid)
where predicate = (== ord) . flip (dimCompare dim) q
(valid,invalid) = G.unstablePartition predicate vs
go (Node d p l r) | dim /= d = (Node d p lval rval, Node d p linv rinv)
| otherwise = case ord of
GT -> case dimCompare dim q p of
LT -> ( Node d p lval r
, Node d p linv empty
)
GT -> ( Node d p empty rval
, Node d p l rinv
)
EQ -> ( Node d p empty r
, Node d p l empty
)
LT -> case dimCompare dim q p of
LT -> ( Node d p lval empty
, Node d p linv r
)
GT -> ( Node d p l rval
, Node d p empty rinv
)
EQ -> ( Node d p l empty
, Node d p empty r
)
EQ -> case dimCompare dim q p of
LT -> ( Node d p lval empty
, Node d p linv r
)
_ -> ( Node d p empty rval
, Node d p l rinv
)
where (lval,linv) = go l
(rval,rinv) = go r
{-# INLINABLE partition #-}
select :: (KDCompare a, G.Vector v a, Eq (Dim a))
=> Dim a -> Ordering -> a -> KDTree v a -> KDTree v a
select dim ord q = fst . partition dim ord q
{-# INLINABLE select #-}
delete :: (KDCompare a, G.Vector v a, Eq (Dim a))
=> Dim a -> Ordering -> a -> KDTree v a -> KDTree v a
delete dim ord q = snd . partition dim ord q
{-# INLINABLE delete #-}
--------------------------------------------------------------------------------
merge :: (Eq (Dim a), G.Vector v a, KDCompare a)
=> BucketSize -> KDTree v a -> KDTree v a -> KDTree v a
merge (BucketSize bs) = go
where go (Node d p l r) kd = Node d p (go l l') (go r r')
where (l',r') = partition d LT p kd
go (Leaf ad avs) (Leaf _ bvs) | G.length avs + G.length bvs < bs = Leaf ad (avs G.++ bvs)
| otherwise = kdtree' ad (BucketSize bs) (avs G.++ bvs)
go kd (Node d p l r) = Node d p (go l l') (go r r')
where (l',r') = partition d LT p kd
{-# INLINABLE merge #-}
--------------------------------------------------------------------------------
update :: (KDCompare a, G.Vector v a, Eq (Dim a))
=> BucketSize -> Dim a -> Ordering -> a -> (a -> a) -> KDTree v a -> KDTree v a
update bs dim ord q f = uncurry (merge bs)
. first (kdtree bs . G.map f . toVec)
. partition dim ord q
{-# INLINABLE update #-}
--------------------------------------------------------------------------------
-- mostly util stuff here
pretty :: (G.Vector v a, Show (v a), Show (Dim a), Show a) => KDTree v a -> String
pretty = go 0
where go d (Leaf p xs) = replicate (2*d) ' '
++ "Leaf " ++ show p ++ " "
++ G.foldl' (\acc x -> acc
++ replicate (2*d + 2) ' '
++ show x ++ "\n") "\n" xs
go d (Node k p l r) = replicate (2*d) ' '
++ "Node " ++ show k ++ " " ++ show p ++ "\n"
++ go (d+1) l
++ go (d+1) r
vecSortBy :: G.Vector v a => I.Comparison a -> v a -> v a
vecSortBy f = G.modify (I.sortBy f)
{-# INLINABLE vecSortBy #-}
|
fhaust/kdtree
|
src/Data/KDTree.hs
|
mit
| 10,682 | 0 | 17 | 4,074 | 3,723 | 1,906 | 1,817 | 161 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.