code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
module B where
import A (message)
main :: IO ()
main = do
putStrLn message
|
sdiehl/ghc
|
testsuite/tests/driver/T16500/B.hs
|
Haskell
|
bsd-3-clause
| 81
|
{-# LANGUAGE OverloadedStrings #-}
module Poly1305 (tests) where
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B ()
import Imports
import Crypto.Error
import qualified Crypto.MAC.Poly1305 as Poly1305
import qualified Data.ByteArray as B (convert)
instance Show Poly1305.Auth where
show _ = "Auth"
data Chunking = Chunking Int Int
deriving (Show,Eq)
instance Arbitrary Chunking where
arbitrary = Chunking <$> choose (1,34) <*> choose (1,2048)
tests = testGroup "Poly1305"
[ testCase "V0" $
let key = "\x85\xd6\xbe\x78\x57\x55\x6d\x33\x7f\x44\x52\xfe\x42\xd5\x06\xa8\x01\x03\x80\x8a\xfb\x0d\xb2\xfd\x4a\xbf\xf6\xaf\x41\x49\xf5\x1b" :: ByteString
msg = "Cryptographic Forum Research Group" :: ByteString
tag = "\xa8\x06\x1d\xc1\x30\x51\x36\xc6\xc2\x2b\x8b\xaf\x0c\x01\x27\xa9" :: ByteString
in tag @=? B.convert (Poly1305.auth key msg)
, testProperty "Chunking" $ \(Chunking chunkLen totalLen) ->
let key = B.replicate 32 0
msg = B.pack $ take totalLen $ concat (replicate 10 [1..255])
in Poly1305.auth key msg == Poly1305.finalize (foldr (flip Poly1305.update) (throwCryptoError $ Poly1305.initialize key) (chunks chunkLen msg))
]
where
chunks i bs
| B.length bs < i = [bs]
| otherwise = let (b1,b2) = B.splitAt i bs in b1 : chunks i b2
|
tekul/cryptonite
|
tests/Poly1305.hs
|
Haskell
|
bsd-3-clause
| 1,410
|
module Test15 where
f n = n * (f (n - 1))
g = 13 * (f (13 - 1))
|
SAdams601/HaRe
|
old/testing/refacFunDef/Test15_AstOut.hs
|
Haskell
|
bsd-3-clause
| 67
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DeriveDataTypeable #-}
module TypedIds where
import Data.Maybe(isJust)
import Data.Generics
{-+
Haskell declaration introduce names in two name spaces. Type classes and
types live in one name space. Values (functions, data constructors) live
in another name space.
-}
data NameSpace = ClassOrTypeNames | ValueNames deriving (Eq,Ord,Show, Data, Typeable)
{-+
Identifiers can denote many different types of entities. It is clear from
the defining occurence of an identifier what type of entity it denotes.
The type #IdTy# can be seen as a refinement of #NameSpace#.
From the use of an identifier, we can tell what name space it refers
to, but not the exact type of entity, hence the need for two different types.
-}
data IdTy i
= Value
| FieldOf i (TypeInfo i)
| MethodOf i Int [i] -- name of class, number of superclasses, names of all methods
| ConstrOf i (TypeInfo i)
| Class Int [i] -- number of superclasses, names of all methods
| Type (TypeInfo i)
| Assertion -- P-Logic assertion name
| Property -- P-Logic property name
deriving (Eq,Ord,Show,Read, Data, Typeable)
-- These structures contain a lot of redundancy, so we shouldn't really
-- use any comparison operations on them.
data ConInfo i = ConInfo
{ conName :: i
, conArity :: Int
, conFields :: Maybe [i] -- length agrees with conArity
} deriving (Eq,Ord,Show,Read, Data, Typeable)
data DefTy = Newtype | Data | Synonym | Primitive
deriving (Eq,Ord,Show,Read, Data, Typeable)
data TypeInfo i = TypeInfo
{ defType :: Maybe DefTy
, constructors :: [ConInfo i]
, fields :: [i]
} deriving (Eq,Ord,Show,Read, Data, Typeable)
blankTypeInfo = TypeInfo { defType = Nothing, constructors = [], fields = [] }
instance Functor ConInfo where
fmap f c = c { conName = f (conName c),
conFields = fmap (map f) (conFields c) }
instance Functor TypeInfo where
fmap f t = t { constructors = map (fmap f) (constructors t)
, fields = map f (fields t)
}
instance Functor IdTy where
fmap f (FieldOf x tyInfo) = FieldOf (f x) (fmap f tyInfo)
fmap f (MethodOf x n xs) = MethodOf (f x) n (map f xs)
fmap f (ConstrOf t tyInfo) = ConstrOf (f t) (fmap f tyInfo)
fmap _ Value = Value
fmap f (Class n xs) = Class n (f `map` xs)
fmap f (Type tyInfo) = Type (fmap f tyInfo)
fmap _ Assertion = Assertion
fmap _ Property = Property
class HasNameSpace t where
namespace :: t -> NameSpace
instance HasNameSpace (IdTy id) where
namespace Value = ValueNames
namespace (FieldOf {}) = ValueNames
namespace (MethodOf {}) = ValueNames
namespace (ConstrOf {}) = ValueNames
namespace (Class {}) = ClassOrTypeNames
namespace (Type {}) = ClassOrTypeNames
namespace Assertion = ValueNames -- hmm
namespace Property = ValueNames -- hmm
-- owner :: IdTy i -> Maybe i
owner (FieldOf dt _) = Just dt
owner (MethodOf cl _ _) = Just cl
owner (ConstrOf dt _) = Just dt
owner _ = Nothing
-- isSubordinate :: IdTy i -> Bool
isSubordinate = isJust . owner
-- belongsTo :: idTy i -> i -> Bool
idty `belongsTo` t = owner idty == Just t
isAssertion Assertion = True
isAssertion Property = True
isAssertion _ = False
isClassOrType,isValue :: HasNameSpace t => t -> Bool
isClassOrType = (== ClassOrTypeNames) . namespace
isValue = (== ValueNames) . namespace
class HasIdTy i t | t->i where
idTy :: t -> IdTy i
instance HasIdTy i (IdTy i) where idTy = id
--instance HasNameSpace NameSpace where namespace = id
|
kmate/HaRe
|
old/tools/base/Modules/TypedIds.hs
|
Haskell
|
bsd-3-clause
| 3,831
|
--
-- (c) The University of Glasgow
--
{-# LANGUAGE DeriveDataTypeable #-}
module Avail (
Avails,
AvailInfo(..),
IsPatSyn(..),
avail,
patSynAvail,
availsToNameSet,
availsToNameSetWithSelectors,
availsToNameEnv,
availName, availNames, availNonFldNames,
availNamesWithSelectors,
availFlds,
stableAvailCmp
) where
import Name
import NameEnv
import NameSet
import FieldLabel
import Binary
import Outputable
import Util
import Data.Function
-- -----------------------------------------------------------------------------
-- The AvailInfo type
-- | Records what things are "available", i.e. in scope
data AvailInfo = Avail IsPatSyn Name -- ^ An ordinary identifier in scope
| AvailTC Name
[Name]
[FieldLabel]
-- ^ A type or class in scope. Parameters:
--
-- 1) The name of the type or class
-- 2) The available pieces of type or class,
-- excluding field selectors.
-- 3) The record fields of the type
-- (see Note [Representing fields in AvailInfo]).
--
-- The AvailTC Invariant:
-- * If the type or class is itself
-- to be in scope, it must be
-- *first* in this list. Thus,
-- typically: @AvailTC Eq [Eq, ==, \/=]@
deriving( Eq )
-- Equality used when deciding if the
-- interface has changed
data IsPatSyn = NotPatSyn | IsPatSyn deriving Eq
-- | A collection of 'AvailInfo' - several things that are \"available\"
type Avails = [AvailInfo]
{-
Note [Representing fields in AvailInfo]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When -XDuplicateRecordFields is disabled (the normal case), a
datatype like
data T = MkT { foo :: Int }
gives rise to the AvailInfo
AvailTC T [T, MkT] [FieldLabel "foo" False foo],
whereas if -XDuplicateRecordFields is enabled it gives
AvailTC T [T, MkT] [FieldLabel "foo" True $sel:foo:MkT]
since the label does not match the selector name.
The labels in a field list are not necessarily unique:
data families allow the same parent (the family tycon) to have
multiple distinct fields with the same label. For example,
data family F a
data instance F Int = MkFInt { foo :: Int }
data instance F Bool = MkFBool { foo :: Bool}
gives rise to
AvailTC F [F, MkFInt, MkFBool]
[FieldLabel "foo" True $sel:foo:MkFInt, FieldLabel "foo" True $sel:foo:MkFBool].
Moreover, note that the flIsOverloaded flag need not be the same for
all the elements of the list. In the example above, this occurs if
the two data instances are defined in different modules, one with
`-XDuplicateRecordFields` enabled and one with it disabled. Thus it
is possible to have
AvailTC F [F, MkFInt, MkFBool]
[FieldLabel "foo" True $sel:foo:MkFInt, FieldLabel "foo" False foo].
If the two data instances are defined in different modules, both
without `-XDuplicateRecordFields`, it will be impossible to export
them from the same module (even with `-XDuplicateRecordfields`
enabled), because they would be represented identically. The
workaround here is to enable `-XDuplicateRecordFields` on the defining
modules.
-}
-- | Compare lexicographically
stableAvailCmp :: AvailInfo -> AvailInfo -> Ordering
stableAvailCmp (Avail _ n1) (Avail _ n2) = n1 `stableNameCmp` n2
stableAvailCmp (Avail {}) (AvailTC {}) = LT
stableAvailCmp (AvailTC n ns nfs) (AvailTC m ms mfs) =
(n `stableNameCmp` m) `thenCmp`
(cmpList stableNameCmp ns ms) `thenCmp`
(cmpList (stableNameCmp `on` flSelector) nfs mfs)
stableAvailCmp (AvailTC {}) (Avail {}) = GT
patSynAvail :: Name -> AvailInfo
patSynAvail n = Avail IsPatSyn n
avail :: Name -> AvailInfo
avail n = Avail NotPatSyn n
-- -----------------------------------------------------------------------------
-- Operations on AvailInfo
availsToNameSet :: [AvailInfo] -> NameSet
availsToNameSet avails = foldr add emptyNameSet avails
where add avail set = extendNameSetList set (availNames avail)
availsToNameSetWithSelectors :: [AvailInfo] -> NameSet
availsToNameSetWithSelectors avails = foldr add emptyNameSet avails
where add avail set = extendNameSetList set (availNamesWithSelectors avail)
availsToNameEnv :: [AvailInfo] -> NameEnv AvailInfo
availsToNameEnv avails = foldr add emptyNameEnv avails
where add avail env = extendNameEnvList env
(zip (availNames avail) (repeat avail))
-- | Just the main name made available, i.e. not the available pieces
-- of type or class brought into scope by the 'GenAvailInfo'
availName :: AvailInfo -> Name
availName (Avail _ n) = n
availName (AvailTC n _ _) = n
-- | All names made available by the availability information (excluding overloaded selectors)
availNames :: AvailInfo -> [Name]
availNames (Avail _ n) = [n]
availNames (AvailTC _ ns fs) = ns ++ [ flSelector f | f <- fs, not (flIsOverloaded f) ]
-- | All names made available by the availability information (including overloaded selectors)
availNamesWithSelectors :: AvailInfo -> [Name]
availNamesWithSelectors (Avail _ n) = [n]
availNamesWithSelectors (AvailTC _ ns fs) = ns ++ map flSelector fs
-- | Names for non-fields made available by the availability information
availNonFldNames :: AvailInfo -> [Name]
availNonFldNames (Avail _ n) = [n]
availNonFldNames (AvailTC _ ns _) = ns
-- | Fields made available by the availability information
availFlds :: AvailInfo -> [FieldLabel]
availFlds (AvailTC _ _ fs) = fs
availFlds _ = []
-- -----------------------------------------------------------------------------
-- Printing
instance Outputable AvailInfo where
ppr = pprAvail
pprAvail :: AvailInfo -> SDoc
pprAvail (Avail _ n) = ppr n
pprAvail (AvailTC n ns fs) = ppr n <> braces (hsep (punctuate comma (map ppr ns ++ map (ppr . flLabel) fs)))
instance Binary AvailInfo where
put_ bh (Avail b aa) = do
putByte bh 0
put_ bh aa
put_ bh b
put_ bh (AvailTC ab ac ad) = do
putByte bh 1
put_ bh ab
put_ bh ac
put_ bh ad
get bh = do
h <- getByte bh
case h of
0 -> do aa <- get bh
b <- get bh
return (Avail b aa)
_ -> do ab <- get bh
ac <- get bh
ad <- get bh
return (AvailTC ab ac ad)
instance Binary IsPatSyn where
put_ bh IsPatSyn = putByte bh 0
put_ bh NotPatSyn = putByte bh 1
get bh = do
h <- getByte bh
case h of
0 -> return IsPatSyn
_ -> return NotPatSyn
|
tjakway/ghcjvm
|
compiler/basicTypes/Avail.hs
|
Haskell
|
bsd-3-clause
| 7,103
|
module Main where
import Control.Concurrent
import qualified Control.Exception as E
trapHandler :: MVar Int -> MVar () -> IO ()
trapHandler inVar caughtVar =
(do E.mask_ $ do
trapMsg <- takeMVar inVar
putStrLn ("Handler got: " ++ show trapMsg)
trapHandler inVar caughtVar
)
`E.catch`
(trapExc inVar caughtVar)
trapExc :: MVar Int -> MVar () -> E.SomeException -> IO ()
-- If we have been killed then we are done
trapExc inVar caughtVar e
| Just E.ThreadKilled <- E.fromException e = return ()
-- Otherwise...
trapExc inVar caughtVar e =
do putStrLn ("Exception: " ++ show e)
putMVar caughtVar ()
trapHandler inVar caughtVar
main :: IO ()
main = do
inVar <- newEmptyMVar
caughtVar <- newEmptyMVar
tid <- forkIO (trapHandler inVar caughtVar)
yield
putMVar inVar 1
threadDelay 1000
throwTo tid (E.ErrorCall "1st")
takeMVar caughtVar
putMVar inVar 2
threadDelay 1000
throwTo tid (E.ErrorCall "2nd")
-- the second time around, exceptions will be blocked, because
-- the trapHandler is effectively "still in the handler" from the
-- first exception. I'm not sure if this is by design or by
-- accident. Anyway, the trapHandler will at some point block
-- in takeMVar, and thereby become interruptible, at which point
-- it will receive the second exception.
takeMVar caughtVar
-- Running the GHCi way complains that tid is blocked indefinitely if
-- it still exists, so kill it.
killThread tid
putStrLn "All done"
|
ezyang/ghc
|
testsuite/tests/concurrent/should_run/conc035.hs
|
Haskell
|
bsd-3-clause
| 1,544
|
{-# LANGUAGE RankNTypes, ScopedTypeVariables #-}
-- Trac #2494, should generate an error message
module Foo where
foo :: (forall m. Monad m => Maybe (m a) -> Maybe (m a)) -> Maybe a -> Maybe a
foo _ x = x
{-# RULES
"foo/foo"
forall (f :: forall m. Monad m => Maybe (m a) -> Maybe (m a))
(g :: forall m. Monad m => Maybe (m b) -> Maybe (m b)) x.
foo f (foo g x) = foo (f . g) x
#-}
|
wxwxwwxxx/ghc
|
testsuite/tests/typecheck/should_compile/T2494.hs
|
Haskell
|
bsd-3-clause
| 400
|
-- !!! Duplicate export of constructor
module M(T(K1,K1)) where
data T = K1
|
urbanslug/ghc
|
testsuite/tests/module/mod5.hs
|
Haskell
|
bsd-3-clause
| 76
|
{-# OPTIONS_GHC -Wall #-}
module CSI where
data Boy = Matthew | Peter | Jack | Arnold | Carl
deriving (Eq,Show)
boys :: [Boy]
boys = [Matthew, Peter, Jack, Arnold, Carl]
-- says accuser accused = True
says :: Boy -> Boy -> Bool
-- None of the kids has claimed guilty, so we assume that all of them claim inocence.
says Matthew Matthew = False
says Peter Peter = False
says Jack Jack = False
says Arnold Arnold = False
says Carl Carl = False
-- Matthew: Carl didn’t do it, and neither did I.
-- says Matthew Matthew = False
says Matthew Carl = False
says Matthew _ = True
-- Peter: It was Matthew or it was Jack.
says Peter Matthew = True
says Peter Jack = True
says Peter _ = False
-- Jack: Matthew and Peter are both lying.
says Jack y = not(says Matthew y) && not(says Peter y)
-- Arnold: Matthew or Peter is speaking the truth, but not both.
says Arnold y = (says Matthew y && not(says Peter y)) || (not(says Matthew y) && says Peter y)
-- Carl: What Arnold says is not true.
says Carl y = not(says Arnold y)
-- The accusers of a boy is each boy that says he is guilty.
accusers :: Boy -> [Boy]
accusers accused = [accuser | accuser <- boys, says accuser accused]
-- The one that all the honest kids point. Only 3 will say the truth, therefore,
-- the one accused by 3 is the right one.
guilty :: [Boy]
guilty = [boy | boy <- boys, length (accusers boy) == 3]
-- The lier is didn't claim guilty therefore is a lier. The kid that didn't accused him too.
honest :: [Boy]
honest = accusers (head guilty)
|
Gurrt/software-testing
|
week-1/CSI.hs
|
Haskell
|
mit
| 1,530
|
import Data.List
import Data.Char
data Fig = W | B | WD | BD | E deriving (Show, Eq)
type Board = [[Fig]]
type Pos = (Int, Int)
charToFig :: Char -> Fig
charToFig 'w' = W
charToFig 'W' = WD
charToFig 'b' = B
charToFig 'B' = BD
charToFig '.' = E
figToChar :: Fig -> Char
figToChar W = 'w'
figToChar WD = 'W'
figToChar B = 'b'
figToChar BD = 'B'
figToChar E = '.'
initialBoardStr = ".b.b.b.b\n\
\b.b.b.b.\n\
\.b.b.b.b\n\
\........\n\
\........\n\
\w.w.w.w.\n\
\.w.w.w.w\n\
\w.w.w.w."
fromStr :: String -> [Fig]
fromStr = map charToFig
toStr :: [Fig] -> String
toStr = intersperse ' ' . map figToChar
initBoard :: String -> Board
initBoard = map fromStr . lines
szachownica = initBoard initialBoardStr
boardToStr :: Board -> [String]
boardToStr b = map toStr b
showBoard :: Board -> String
showBoard board = unlines . addColNumbers . addRowNumbers $ boardToStr board
where
addRowNumber num line = (show num) ++ " " ++ line
addRowNumbers board = zipWith addRowNumber [0..7] board
addColNumbers board = [" 0 1 2 3 4 5 6 7 "] ++ board
getFig :: Board -> Pos -> Fig
getFig b (row, column) = b !! row !! column
replaceWithFig :: Fig -> [Fig] -> Int -> [Fig]
replaceWithFig f (_:t) 0 = f : t
replaceWithFig f (h:t) col = h:replaceWithFig f t (col-1)
setFig :: Fig -> Board -> Pos -> Board
setFig fig (headBoard:tailBoard) (0, column) = replaceWithFig fig headBoard column : tailBoard
setFig fig (headBoard:tailBoard) (row, column) = headBoard : setFig fig tailBoard ((row-1), column)
--countWhiteFigs :: Board -> Int
--countWhiteFigs [] = 0
--countWhiteFigs (h:t) = (countWhiteFigs t) + (length (filter (\f -> f == W || f == WD) h))
boardToNumberOfWhiteFigures :: Board -> Int
boardToNumberOfWhiteFigures [] = 0
boardToNumberOfWhiteFigures (h:t) = let
isWhiteFig fig = fig == W || fig == WD :: Bool
areWhiteFigs figs = filter isWhiteFig figs :: [Fig]
in
length (areWhiteFigs h) + boardToNumberOfWhiteFigures t
--boardToNumberOfBlackFigures :: Board -> Int
--boardToNumberOfBlackFigures [] = 0
--boardToNumberOfBlackFigures (h:t) = let
-- isBlackFig fig = fig == B || fig == BD :: Bool
-- areBlackFigs figs = filter isBlackFig figs :: [Fig]
-- in
-- length (areBlackFigs h) + boardToNumberOfBlackFigures t
boardToNumberOfBlackFigures :: Board -> Int
boardToNumberOfBlackFigures b = foldr (\_ acc -> 1 + acc) 0 (foldr (\x acc -> if (isBlackFig x) then x:acc else acc) [] [uhu | uhu<- [ble | ble<-b]])
isBlackFig :: Fig -> Bool
isBlackFig f = f `elem` [B,BD]
areBlackFigs :: [Fig] -> [Fig]
areBlackFigs = foldr (\x acc -> if (isBlackFig x) then x:acc else acc) []-- filter isBlackFig figs :: [Fig]
dlugosc :: [t]->Int
dlugosc = foldr (\_ acc -> 1 +acc) 0
--blabla :: [Int] -> [Int]
--blabla = foldr (\x acc -> x:acc) []
getRow :: Pos -> Int
getRow = fst
getCol :: Pos -> Int
getCol = snd
isEmpty :: Board -> Pos -> Bool
isEmpty b p = getFig b p == E
isWhite :: Board -> Pos -> Bool
isWhite b p = getFig b p `elem` [W,WD]
isBlack :: Board -> Pos -> Bool
isBlack b p = getFig b p `elem` [B,BD]
isValidPos :: Pos -> Bool
isValidPos (row,col) = let validPositions = [0..7] in (row `elem` validPositions && col `elem` validPositions)
countPos :: Pos -> Pos -> Pos
countPos (r1,c1) (r2,c2) = (abs (r2-r1)+r2, abs (c2-c1)+c2)
countPos2 :: Pos -> Pos -> Pos
countPos2 (row, col) (neighborRow, neighborCol) =
((countIndex row neighborRow), (countIndex col neighborCol))
where
countIndex index neighborIndex = 2 * neighborIndex - index
capturedPos :: Pos -> Pos -> Pos
capturedPos prevPos@(r1,c1) newPos@(r2,c2) = ((r1+r2) `quot` 2,(c1+c2) `quot` 2)
--setFig :: Fig -> Board -> Pos -> Board
--setFig fig (headBoard:tailBoard) (0, column) = replaceWithFig fig headBoard column : tailBoard
--setFig fig (headBoard:tailBoard) (row, column) = headBoard : setFig fig tailBoard ((row-1), column)
makeCaptureMove :: Board -> Pos -> Pos -> Board
makeCaptureMove b curp newp
| isWhite b from = (setFig E (setFig W (setFig E b from) to) (capturedPos from to))
| isBlack b from =
|
RAFIRAF/HASKELL
|
warcaby-trening.hs
|
Haskell
|
mit
| 4,456
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-|
Module : PostgREST.QueryBuilder
Description : PostgREST SQL generating functions.
This module provides functions to consume data types that
represent database objects (e.g. Relation, Schema, SqlQuery)
and produces SQL Statements.
Any function that outputs a SQL fragment should be in this module.
-}
module PostgREST.QueryBuilder (
addRelations
, addJoinConditions
, asJson
, callProc
, createReadStatement
, createWriteStatement
, operators
, pgFmtIdent
, pgFmtLit
, requestToQuery
, sourceSubqueryName
, unquoted
) where
import qualified Hasql as H
import qualified Hasql.Backend as B
import qualified Hasql.Postgres as P
import qualified Data.Aeson as JSON
import PostgREST.RangeQuery (NonnegRange, rangeLimit, rangeOffset)
import Control.Error (note, fromMaybe, mapMaybe)
import qualified Data.HashMap.Strict as HM
import Data.List (find)
import Data.Monoid ((<>))
import Data.Text (Text, intercalate, unwords, replace, isInfixOf, toLower, split)
import qualified Data.Text as T (map, takeWhile)
import Data.String.Conversions (cs)
import Control.Applicative (empty, (<|>))
import Data.Tree (Tree(..))
import qualified Data.Vector as V
import PostgREST.Types
import qualified Data.Map as M
import Text.Regex.TDFA ((=~))
import qualified Data.ByteString.Char8 as BS
import Data.Scientific ( FPFormat (..)
, formatScientific
, isInteger
)
import Prelude hiding (unwords)
type PStmt = H.Stmt P.Postgres
instance Monoid PStmt where
mappend (B.Stmt query params prep) (B.Stmt query' params' prep') =
B.Stmt (query <> query') (params <> params') (prep && prep')
mempty = B.Stmt "" empty True
type StatementT = PStmt -> PStmt
createReadStatement :: SqlQuery -> NonnegRange -> Bool -> Bool -> Bool -> B.Stmt P.Postgres
createReadStatement selectQuery range isSingle countTable asCsv =
B.Stmt (
wrapLimitedQuery selectQuery [
if countTable then countAllF else countNoneF,
countF,
"null", -- location header can not be calucalted
if asCsv
then asCsvF
else if isSingle then asJsonSingleF else asJsonF
] selectStarF range
) V.empty True
createWriteStatement :: SqlQuery -> SqlQuery -> Bool -> Bool ->
[Text] -> Bool -> Payload -> B.Stmt P.Postgres
createWriteStatement _ _ _ _ _ _ (PayloadParseError _) = undefined
createWriteStatement selectQuery mutateQuery isSingle echoRequested
pKeys asCsv (PayloadJSON (UniformObjects rows)) =
B.Stmt (
wrapQuery mutateQuery [
countNoneF, -- when updateing it does not make sense
countF,
if isSingle then locationF pKeys else "null",
if echoRequested
then
if asCsv
then asCsvF
else if isSingle then asJsonSingleF else asJsonF
else "null"
] selectQuery
) (V.singleton . B.encodeValue . JSON.Array . V.map JSON.Object $ rows) True
addRelations :: Schema -> [Relation] -> Maybe ReadRequest -> ReadRequest -> Either Text ReadRequest
addRelations schema allRelations parentNode node@(Node n@(query, (table, _)) forest) =
case parentNode of
Nothing -> Node (query, (table, Nothing)) <$> updatedForest
(Just (Node (_, (parentTable, _)) _)) -> Node <$> (addRel n <$> rel) <*> updatedForest
where
rel = note ("no relation between " <> table <> " and " <> parentTable)
$ findRelation schema table parentTable
<|> findRelation schema parentTable table
addRel :: (ReadQuery, (NodeName, Maybe Relation)) -> Relation -> (ReadQuery, (NodeName, Maybe Relation))
addRel (q, (t, _)) r = (q, (t, Just r))
where
updatedForest = mapM (addRelations schema allRelations (Just node)) forest
findRelation s t1 t2 =
find (\r -> s == (tableSchema . relTable) r && t1 == (tableName . relTable) r && t2 == (tableName . relFTable) r) allRelations
addJoinConditions :: Schema -> ReadRequest -> Either Text ReadRequest
addJoinConditions schema (Node (query, (n, r)) forest) =
case r of
Nothing -> Node (updatedQuery, (n,r)) <$> updatedForest -- this is the root node
Just rel@(Relation{relType=Child}) -> Node (addCond updatedQuery (getJoinConditions rel),(n,r)) <$> updatedForest
Just (Relation{relType=Parent}) -> Node (updatedQuery, (n,r)) <$> updatedForest
Just rel@(Relation{relType=Many, relLTable=(Just linkTable)}) ->
Node (qq, (n, r)) <$> updatedForest
where
q = addCond updatedQuery (getJoinConditions rel)
qq = q{from=tableName linkTable : from q}
_ -> Left "unknown relation"
where
-- add parentTable and parentJoinConditions to the query
updatedQuery = foldr (flip addCond) query parentJoinConditions
where
parentJoinConditions = map (getJoinConditions . snd) parents
parents = mapMaybe (getParents . rootLabel) forest
getParents (_, (tbl, Just rel@(Relation{relType=Parent}))) = Just (tbl, rel)
getParents _ = Nothing
updatedForest = mapM (addJoinConditions schema) forest
addCond q con = q{flt_=con ++ flt_ q}
asJson :: StatementT
asJson s = s {
B.stmtTemplate =
"array_to_json(coalesce(array_agg(row_to_json(t)), '{}'))::character varying from ("
<> B.stmtTemplate s <> ") t" }
callProc :: QualifiedIdentifier -> JSON.Object -> PStmt
callProc qi params = do
let args = intercalate "," $ map assignment (HM.toList params)
B.Stmt ("select * from " <> fromQi qi <> "(" <> args <> ")") empty True
where
assignment (n,v) = pgFmtIdent n <> ":=" <> insertableValue v
operators :: [(Text, SqlFragment)]
operators = [
("eq", "="),
("gte", ">="), -- has to be before gt (parsers)
("gt", ">"),
("lte", "<="), -- has to be before lt (parsers)
("lt", "<"),
("neq", "<>"),
("like", "like"),
("ilike", "ilike"),
("in", "in"),
("notin", "not in"),
("isnot", "is not"), -- has to be before is (parsers)
("is", "is"),
("@@", "@@"),
("@>", "@>"),
("<@", "<@")
]
pgFmtIdent :: SqlFragment -> SqlFragment
pgFmtIdent x =
let escaped = replace "\"" "\"\"" (trimNullChars $ cs x) in
if (cs escaped :: BS.ByteString) =~ danger
then "\"" <> escaped <> "\""
else escaped
where danger = "^$|^[^a-z_]|[^a-z_0-9]" :: BS.ByteString
pgFmtLit :: SqlFragment -> SqlFragment
pgFmtLit x =
let trimmed = trimNullChars x
escaped = "'" <> replace "'" "''" trimmed <> "'"
slashed = replace "\\" "\\\\" escaped in
if "\\\\" `isInfixOf` escaped
then "E" <> slashed
else slashed
requestToQuery :: Schema -> DbRequest -> SqlQuery
requestToQuery _ (DbMutate (Insert _ (PayloadParseError _))) = undefined
requestToQuery _ (DbMutate (Update _ (PayloadParseError _) _)) = undefined
requestToQuery schema (DbRead (Node (Select colSelects tbls conditions ord, (mainTbl, _)) forest)) =
query
where
-- TODO! the folloing helper functions are just to remove the "schema" part when the table is "source" which is the name
-- of our WITH query part
tblSchema tbl = if tbl == sourceSubqueryName then "" else schema
qi = QualifiedIdentifier (tblSchema mainTbl) mainTbl
toQi t = QualifiedIdentifier (tblSchema t) t
query = unwords [
("WITH " <> intercalate ", " (map fst withs)) `emptyOnNull` withs,
"SELECT ", intercalate ", " (map (pgFmtSelectItem qi) colSelects ++ selects),
"FROM ", intercalate ", " (map (fromQi . toQi) tbls ++ map snd withs),
("WHERE " <> intercalate " AND " ( map (pgFmtCondition qi ) conditions )) `emptyOnNull` conditions,
orderF (fromMaybe [] ord)
]
orderF ts =
if null ts
then ""
else "ORDER BY " <> clause
where
clause = intercalate "," (map queryTerm ts)
queryTerm :: OrderTerm -> Text
queryTerm t = " "
<> cs (pgFmtColumn qi $ otTerm t) <> " "
<> (cs.show) (otDirection t) <> " "
<> maybe "" (cs.show) (otNullOrder t) <> " "
(withs, selects) = foldr getQueryParts ([],[]) forest
getQueryParts :: Tree ReadNode -> ([(SqlFragment, Text)], [SqlFragment]) -> ([(SqlFragment,Text)], [SqlFragment])
getQueryParts (Node n@(_, (table, Just (Relation {relType=Child}))) forst) (w,s) = (w,sel:s)
where
sel = "("
<> "SELECT array_to_json(array_agg(row_to_json("<>table<>"))) "
<> "FROM (" <> subquery <> ") " <> table
<> ") AS " <> table
where subquery = requestToQuery schema (DbRead (Node n forst))
getQueryParts (Node n@(_, (table, Just (Relation {relType=Parent}))) forst) (w,s) = (wit:w,sel:s)
where
sel = "row_to_json(" <> table <> ".*) AS "<>table --TODO must be singular
wit = (table <> " AS ( " <> subquery <> " )", table)
where subquery = requestToQuery schema (DbRead (Node n forst))
getQueryParts (Node n@(_, (table, Just (Relation {relType=Many}))) forst) (w,s) = (w,sel:s)
where
sel = "("
<> "SELECT array_to_json(array_agg(row_to_json("<>table<>"))) "
<> "FROM (" <> subquery <> ") " <> table
<> ") AS " <> table
where subquery = requestToQuery schema (DbRead (Node n forst))
--the following is just to remove the warning
--getQueryParts is not total but requestToQuery is called only after addJoinConditions which ensures the only
--posible relations are Child Parent Many
getQueryParts (Node (_,(_,Nothing)) _) _ = undefined
requestToQuery schema (DbMutate (Insert mainTbl (PayloadJSON (UniformObjects rows)))) =
let qi = QualifiedIdentifier schema mainTbl
cols = map pgFmtIdent $ fromMaybe [] (HM.keys <$> (rows V.!? 0))
colsString = intercalate ", " cols in
unwords [
"INSERT INTO ", fromQi qi,
" (" <> colsString <> ")" <>
" SELECT " <> colsString <>
" FROM json_populate_recordset(null::" , fromQi qi, ", ?)",
" RETURNING " <> fromQi qi <> ".*"
]
requestToQuery schema (DbMutate (Update mainTbl (PayloadJSON (UniformObjects rows)) conditions)) =
case rows V.!? 0 of
Just obj ->
let assignments = map
(\(k,v) -> pgFmtIdent k <> "=" <> insertableValue v) $ HM.toList obj in
unwords [
"UPDATE ", fromQi qi,
" SET " <> intercalate "," assignments <> " ",
("WHERE " <> intercalate " AND " ( map (pgFmtCondition qi ) conditions )) `emptyOnNull` conditions,
"RETURNING " <> fromQi qi <> ".*"
]
Nothing -> undefined
where
qi = QualifiedIdentifier schema mainTbl
requestToQuery schema (DbMutate (Delete mainTbl conditions)) =
query
where
qi = QualifiedIdentifier schema mainTbl
query = unwords [
"DELETE FROM ", fromQi qi,
("WHERE " <> intercalate " AND " ( map (pgFmtCondition qi ) conditions )) `emptyOnNull` conditions,
"RETURNING " <> fromQi qi <> ".*"
]
sourceSubqueryName :: SqlFragment
sourceSubqueryName = "pg_source"
unquoted :: JSON.Value -> Text
unquoted (JSON.String t) = t
unquoted (JSON.Number n) =
cs $ formatScientific Fixed (if isInteger n then Just 0 else Nothing) n
unquoted (JSON.Bool b) = cs . show $ b
unquoted v = cs $ JSON.encode v
-- private functions
asCsvF :: SqlFragment
asCsvF = asCsvHeaderF <> " || '\n' || " <> asCsvBodyF
where
asCsvHeaderF =
"(SELECT string_agg(a.k, ',')" <>
" FROM (" <>
" SELECT json_object_keys(r)::TEXT as k" <>
" FROM ( " <>
" SELECT row_to_json(hh) as r from " <> sourceSubqueryName <> " as hh limit 1" <>
" ) s" <>
" ) a" <>
")"
asCsvBodyF = "coalesce(string_agg(substring(t::text, 2, length(t::text) - 2), '\n'), '')"
asJsonF :: SqlFragment
asJsonF = "array_to_json(array_agg(row_to_json(t)))::character varying"
asJsonSingleF :: SqlFragment --TODO! unsafe when the query actually returns multiple rows, used only on inserting and returning single element
asJsonSingleF = "string_agg(row_to_json(t)::text, ',')::character varying "
countAllF :: SqlFragment
countAllF = "(SELECT pg_catalog.count(1) FROM (SELECT * FROM " <> sourceSubqueryName <> ") a )"
countF :: SqlFragment
countF = "pg_catalog.count(t)"
countNoneF :: SqlFragment
countNoneF = "null"
locationF :: [Text] -> SqlFragment
locationF pKeys =
"(" <>
" WITH s AS (SELECT row_to_json(ss) as r from " <> sourceSubqueryName <> " as ss limit 1)" <>
" SELECT string_agg(json_data.key || '=' || coalesce( 'eq.' || json_data.value, 'is.null'), '&')" <>
" FROM s, json_each_text(s.r) AS json_data" <>
(
if null pKeys
then ""
else " WHERE json_data.key IN ('" <> intercalate "','" pKeys <> "')"
) <>
")"
fromQi :: QualifiedIdentifier -> SqlFragment
fromQi t = (if s == "" then "" else pgFmtIdent s <> ".") <> pgFmtIdent n
where
n = qiName t
s = qiSchema t
getJoinConditions :: Relation -> [Filter]
getJoinConditions (Relation t cols ft fcs typ lt lc1 lc2) =
case typ of
Child -> zipWith (toFilter tN ftN) cols fcs
Parent -> zipWith (toFilter tN ftN) cols fcs
Many -> zipWith (toFilter tN ltN) cols (fromMaybe [] lc1) ++ zipWith (toFilter ftN ltN) fcs (fromMaybe [] lc2)
where
s = if typ == Parent then "" else tableSchema t
tN = tableName t
ftN = tableName ft
ltN = fromMaybe "" (tableName <$> lt)
toFilter :: Text -> Text -> Column -> Column -> Filter
toFilter tb ftb c fc = Filter (colName c, Nothing) "=" (VForeignKey (QualifiedIdentifier s tb) (ForeignKey fc{colTable=(colTable fc){tableName=ftb}}))
emptyOnNull :: Text -> [a] -> Text
emptyOnNull val x = if null x then "" else val
insertableValue :: JSON.Value -> SqlFragment
insertableValue JSON.Null = "null"
insertableValue v = (<> "::unknown") . pgFmtLit $ unquoted v
whiteList :: Text -> SqlFragment
whiteList val = fromMaybe
(cs (pgFmtLit val) <> "::unknown ")
(find ((==) . toLower $ val) ["null","true","false"])
pgFmtColumn :: QualifiedIdentifier -> Text -> SqlFragment
pgFmtColumn table "*" = fromQi table <> ".*"
pgFmtColumn table c = fromQi table <> "." <> pgFmtIdent c
pgFmtField :: QualifiedIdentifier -> Field -> SqlFragment
pgFmtField table (c, jp) = pgFmtColumn table c <> pgFmtJsonPath jp
pgFmtSelectItem :: QualifiedIdentifier -> SelectItem -> SqlFragment
pgFmtSelectItem table (f@(_, jp), Nothing) = pgFmtField table f <> pgFmtAsJsonPath jp
pgFmtSelectItem table (f@(_, jp), Just cast ) = "CAST (" <> pgFmtField table f <> " AS " <> cast <> " )" <> pgFmtAsJsonPath jp
pgFmtCondition :: QualifiedIdentifier -> Filter -> SqlFragment
pgFmtCondition table (Filter (col,jp) ops val) =
notOp <> " " <> sqlCol <> " " <> pgFmtOperator opCode <> " " <>
if opCode `elem` ["is","isnot"] then whiteList (getInner val) else sqlValue
where
headPredicate:rest = split (=='.') ops
hasNot caseTrue caseFalse = if headPredicate == "not" then caseTrue else caseFalse
opCode = hasNot (head rest) headPredicate
notOp = hasNot headPredicate ""
sqlCol = case val of
VText _ -> pgFmtColumn table col <> pgFmtJsonPath jp
VForeignKey qi _ -> pgFmtColumn qi col
sqlValue = valToStr val
getInner v = case v of
VText s -> s
_ -> ""
valToStr v = case v of
VText s -> pgFmtValue opCode s
VForeignKey (QualifiedIdentifier s _) (ForeignKey Column{colTable=Table{tableName=ft}, colName=fc}) -> pgFmtColumn qi fc
where qi = QualifiedIdentifier (if ft == sourceSubqueryName then "" else s) ft
_ -> ""
pgFmtValue :: Text -> Text -> SqlFragment
pgFmtValue opCode val =
case opCode of
"like" -> unknownLiteral $ T.map star val
"ilike" -> unknownLiteral $ T.map star val
"in" -> "(" <> intercalate ", " (map unknownLiteral $ split (==',') val) <> ") "
"notin" -> "(" <> intercalate ", " (map unknownLiteral $ split (==',') val) <> ") "
"@@" -> "to_tsquery(" <> unknownLiteral val <> ") "
_ -> unknownLiteral val
where
star c = if c == '*' then '%' else c
unknownLiteral = (<> "::unknown ") . pgFmtLit
pgFmtOperator :: Text -> SqlFragment
pgFmtOperator opCode = fromMaybe "=" $ M.lookup opCode operatorsMap
where
operatorsMap = M.fromList operators
pgFmtJsonPath :: Maybe JsonPath -> SqlFragment
pgFmtJsonPath (Just [x]) = "->>" <> pgFmtLit x
pgFmtJsonPath (Just (x:xs)) = "->" <> pgFmtLit x <> pgFmtJsonPath ( Just xs )
pgFmtJsonPath _ = ""
pgFmtAsJsonPath :: Maybe JsonPath -> SqlFragment
pgFmtAsJsonPath Nothing = ""
pgFmtAsJsonPath (Just xx) = " AS " <> last xx
trimNullChars :: Text -> Text
trimNullChars = T.takeWhile (/= '\x0')
withSourceF :: SqlFragment -> SqlFragment
withSourceF s = "WITH " <> sourceSubqueryName <> " AS (" <> s <>")"
fromF :: SqlFragment -> SqlFragment -> SqlFragment
fromF sel limit = "FROM (" <> sel <> " " <> limit <> ") t"
limitF :: NonnegRange -> SqlFragment
limitF r = "LIMIT " <> limit <> " OFFSET " <> offset
where
limit = maybe "ALL" (cs . show) $ rangeLimit r
offset = cs . show $ rangeOffset r
selectStarF :: SqlFragment
selectStarF = "SELECT * FROM " <> sourceSubqueryName
wrapLimitedQuery :: SqlQuery -> [Text] -> Text -> NonnegRange -> SqlQuery
wrapLimitedQuery source selectColumns returnSelect range =
withSourceF source <>
" SELECT " <>
intercalate ", " selectColumns <>
" " <>
fromF returnSelect ( limitF range )
wrapQuery :: SqlQuery -> [Text] -> Text -> SqlQuery
wrapQuery source selectColumns returnSelect =
withSourceF source <>
" SELECT " <>
intercalate ", " selectColumns <>
" " <>
fromF returnSelect ""
|
NikolayS/postgrest
|
src/PostgREST/QueryBuilder.hs
|
Haskell
|
mit
| 17,914
|
module Problem45 where
{--
Task description:
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ...
Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ...
It can be verified that T285 = P165 = H143 = 40755.
Find the next triangle number that is also pentagonal and hexagonal.
--}
import Control.Arrow as Arrow
import Data.List as List
type N = Int
type Stream = ([N],[N])
type Point = (N,N)
-- Definition of number functions:
triangle,pentagonal,hexagonal :: N -> N
triangle n = n*(n+1) `div` 2
pentagonal n = n*(3*n-1) `div` 2
hexagonal n = n*(2*n-1) -- Evry hexagonal number is also a triangle number.
-- n = (sqrt(24x+1)+1)/6
isPentagonal :: N -> Bool
isPentagonal n = let m = 24*n+1
o = sqrt $ fromIntegral m :: Double
p = (o+1)/6
in ceiling p == floor p
solution = last . take 3 . filter isPentagonal $ fmap hexagonal [1..]
main = print solution
|
runjak/projectEuler
|
src/Problem45.hs
|
Haskell
|
mit
| 1,073
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Filesystem
import Control.Applicative
import Control.Monad
import Stackage.CLI
import Options.Applicative (Parser)
import Options.Applicative.Builder (strArgument, metavar, value)
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Typeable (Typeable)
import Network.HTTP.Client
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Network.HTTP.Types.Status (statusCode)
import Network.HTTP.Types.Header (hUserAgent)
import qualified Data.ByteString.Lazy as LBS
import System.Exit (exitFailure)
import System.Environment (getArgs)
import System.IO (hPutStrLn, stderr)
import Control.Exception
import qualified Paths_stackage_cabal as CabalInfo
type Snapshot = String
data InitException
= InvalidSnapshot
| SnapshotNotFound
| UnexpectedHttpException HttpException
| CabalConfigExists
deriving (Show, Typeable)
instance Exception InitException
version :: String
version = $(simpleVersion CabalInfo.version)
header :: String
header = "Initializes cabal.config"
progDesc :: String
progDesc = header
userAgent :: Text
userAgent = "stackage-init/" <> T.pack version
snapshotParser :: Parser Snapshot
snapshotParser = strArgument mods where
mods = (metavar "SNAPSHOT" <> value "lts")
toUrl :: Snapshot -> String
toUrl t = "https://www.stackage.org/" <> t <> "/cabal.config"
snapshotReq :: Snapshot -> IO Request
snapshotReq snapshot = case parseUrl (toUrl snapshot) of
Left _ -> throwIO $ InvalidSnapshot
Right req -> return req
{ requestHeaders = [(hUserAgent, T.encodeUtf8 userAgent)]
}
downloadSnapshot :: Snapshot -> IO LBS.ByteString
downloadSnapshot snapshot = withManager tlsManagerSettings $ \manager -> do
let getResponseLbs req = do
response <- httpLbs req manager
return $ responseBody response
let handle404 firstTry (StatusCodeException s _ _)
| statusCode s == 404 = if firstTry
then do
req <- snapshotReq $ "snapshot/" <> snapshot
getResponseLbs req `catch` handle404 False
else do
throwIO $ SnapshotNotFound
handle404 _ e = throwIO $ UnexpectedHttpException e
req <- snapshotReq snapshot
getResponseLbs req `catch` handle404 True
initSnapshot :: Snapshot -> IO ()
initSnapshot snapshot = do
configExists <- isFile "cabal.config"
when configExists $ throwIO $ CabalConfigExists
downloadSnapshot snapshot >>= LBS.writeFile "cabal.config"
handleInitExceptions :: Snapshot -> InitException -> IO ()
handleInitExceptions snapshot e = hPutStrLn stderr (err e) >> exitFailure where
err InvalidSnapshot
= "Invalid snapshot: " <> snapshot
err SnapshotNotFound
= "Snapshot not found: " <> snapshot
err CabalConfigExists
= "Warning: Cabal config already exists.\n"
<> "No action taken."
err (UnexpectedHttpException e)
= "Unexpected http exception:\n"
<> show e
main = do
(snapshot, ()) <- simpleOptions
version
header
progDesc
snapshotParser -- global parser
empty -- subcommands
initSnapshot snapshot `catch` handleInitExceptions snapshot
|
fpco/stackage-cabal
|
main/Init.hs
|
Haskell
|
mit
| 3,252
|
{-# LANGUAGE MultiWayIf #-}
module Data.Bitsplit.Types
(Address, mkAddress, Split, mkSplit, unpackSplit, isEmpty) where
import Data.Ratio
import Data.Natural
import Data.Map (fromList, toList)
--import qualified Network.Bitcoin.Types as BT
newtype Address = Address String deriving (Eq, Show, Ord) --BT.Address
mkAddress :: String -> Maybe Address
mkAddress = Just . Address --BT.mkAddress
newtype Split = Split [(Address, Ratio Natural)] deriving (Show, Eq)
-- Guarantees from constructor (gen test this!):
-- Every Address is unique
-- All of the "values" add up to exactly one, or zero if empty
-- Because of the above, every number is [0, 1]
split = Right . Split
dedupe :: Ord a => [(a, b)] -> [(a, b)]
dedupe = toList . fromList
mkSplit :: [(Address, Ratio Natural)] -> Either String Split
mkSplit [] = split []
mkSplit [(address, _)] = split [(address, 1)]
mkSplit ratios =
let deduped = dedupe ratios
total = foldl (+) 0 $ fmap snd deduped
in if -- | True -> split deduped -- use for testing failing stuff
| length deduped < length ratios -> Left "Duplicate addresses in list"
| total == 1 -> split deduped
| otherwise -> Left "Total not equal to 1"
isEmpty :: Split -> Bool
isEmpty (Split []) = True
isEmpty _ = False
unpackSplit :: Split -> [(Address, Ratio Natural)]
unpackSplit (Split split) = split
|
micmarsh/bitsplit-hs
|
src/Data/Bitsplit/Types.hs
|
Haskell
|
mit
| 1,401
|
module Jhc.Function where
{-# SUPERINLINE id, const, (.), ($), ($!), flip #-}
infixr 9 .
infixr 0 $, $!, `seq`
id x = x
const x _ = x
f . g = \x -> f (g x)
f $ x = f x
f $! x = x `seq` f x
flip f x y = f y x
-- asTypeOf is a type-restricted version of const. It is usually used
-- as an infix operator, and its typing forces its first argument
-- (which is usually overloaded) to have the same type as the second.
{-# SUPERINLINE asTypeOf #-}
asTypeOf :: a -> a -> a
asTypeOf = const
{-# INLINE seq #-}
foreign import primitive seq :: a -> b -> b
infixl 0 `on`
-- | @'fix' f@ is the least fixed point of the function @f@,
-- i.e. the least defined @x@ such that @f x = x@.
fix :: (a -> a) -> a
fix f = let x = f x in x
-- | @(*) \`on\` f = \\x y -> f x * f y@.
--
-- Typical usage: @'Data.List.sortBy' ('compare' \`on\` 'fst')@.
--
-- Algebraic properties:
--
-- * @(*) \`on\` 'id' = (*)@ (if @(*) ∉ {⊥, 'const' ⊥}@)
--
-- * @((*) \`on\` f) \`on\` g = (*) \`on\` (f . g)@
--
-- * @'flip' on f . 'flip' on g = 'flip' on (g . f)@
-- Proofs (so that I don't have to edit the test-suite):
-- (*) `on` id
-- =
-- \x y -> id x * id y
-- =
-- \x y -> x * y
-- = { If (*) /= _|_ or const _|_. }
-- (*)
-- (*) `on` f `on` g
-- =
-- ((*) `on` f) `on` g
-- =
-- \x y -> ((*) `on` f) (g x) (g y)
-- =
-- \x y -> (\x y -> f x * f y) (g x) (g y)
-- =
-- \x y -> f (g x) * f (g y)
-- =
-- \x y -> (f . g) x * (f . g) y
-- =
-- (*) `on` (f . g)
-- =
-- (*) `on` f . g
-- flip on f . flip on g
-- =
-- (\h (*) -> (*) `on` h) f . (\h (*) -> (*) `on` h) g
-- =
-- (\(*) -> (*) `on` f) . (\(*) -> (*) `on` g)
-- =
-- \(*) -> (*) `on` g `on` f
-- = { See above. }
-- \(*) -> (*) `on` g . f
-- =
-- (\h (*) -> (*) `on` h) (g . f)
-- =
-- flip on (g . f)
on :: (b -> b -> c) -> (a -> b) -> a -> a -
|
m-alvarez/jhc
|
lib/jhc/Jhc/Function.hs
|
Haskell
|
mit
| 1,869
|
{-# LANGUAGE CPP #-}
module GHCJS.DOM.StyleSheet (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.StyleSheet
#else
module Graphics.UI.Gtk.WebKit.DOM.StyleSheet
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.StyleSheet
#else
import Graphics.UI.Gtk.WebKit.DOM.StyleSheet
#endif
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/StyleSheet.hs
|
Haskell
|
mit
| 435
|
{-# LANGUAGE CPP #-}
module GHCJS.DOM.Coordinates (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.Coordinates
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.Coordinates
#else
#endif
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/Coordinates.hs
|
Haskell
|
mit
| 346
|
module MinHS.Evaluator where
import qualified MinHS.Env as E
import MinHS.Syntax
import MinHS.Pretty
import qualified Text.PrettyPrint.ANSI.Leijen as PP
type VEnv = E.Env Value
data VFun = VFun (Value -> Value)
instance Show VFun where
show _ = error "Tried to show lambda"
data Value = I Integer
| B Bool
| Nil
| Cons Integer Value
| Lam VFun
deriving (Show)
instance PP.Pretty Value where
pretty (I i) = numeric i
pretty (B b) = datacon $ show b
pretty (Nil) = datacon "Nil"
pretty (Cons x v) = PP.parens (datacon "Cons" PP.<+> numeric x PP.<+> PP.pretty v)
pretty _ = undefined -- should not ever be used
evaluate :: Program -> Value
evaluate bs = evalE E.empty (Let bs (Var "main"))
lam :: (Value -> Value) -> Value
lam f = Lam $ VFun f
evalE :: VEnv -> Exp -> Value
evalE env (Var name) = case E.lookup env name of
Just v -> v
_ -> error $ "Not in scope: " ++ name
evalE _ (Prim op) = evalOp op
evalE _ (Con val) = case val of
"True" -> B True
"False" -> B False
"Nil" -> Nil
"Cons" -> lam $ \(I h) -> lam $ \t -> Cons h t
evalE _ (Num n) = I n
evalE env (If p t e) = case evalE env p of
B True -> evalE env t
B False -> evalE env e
evalE env (App e1 e2) =
let
Lam (VFun f) = evalE env e1
x = evalE env e2
in f x
evalE env (Let [] body) = evalE env body
evalE env (Let (bind : binds) body) = case bind of
Bind name _ args def ->
let env' = E.add env (name, bindLam env args def)
in evalE env' (Let binds body)
evalE env f@(Letfun (Bind name _ args body)) =
let env' = E.add env (name, evalE env f)
in bindLam env' args body
evalE env (Letrec binds body) =
let
eval (Bind name _ args def) = (name, bindLam env' args def)
bindVals = eval `map` binds
env' = E.addAll env bindVals
in evalE env' body
bindLam :: VEnv -> [Id] -> Exp -> Value
bindLam env [] body = evalE env body
bindLam env (arg : args) body =
lam $ \v ->
let env' = E.add env (arg, v)
in bindLam env' args body
evalOp :: Op -> Value
evalOp op =
let
intOp f = lam $ \(I n1) -> lam $ \(I n2) -> I (n1 `f` n2)
boolOp f = lam $ \(I n1) -> lam $ \(I n2) -> B (n1 `f` n2)
in case op of
Add -> intOp (+)
Sub -> intOp (-)
Mul -> intOp (*)
Quot -> intOp div
Rem -> intOp rem
Eq -> boolOp (==)
Gt -> boolOp (>)
Ge -> boolOp (>=)
Lt -> boolOp (<)
Le -> boolOp (<=)
Ne -> boolOp (/=)
Neg -> lam $ \(I n) -> I (-n)
Null -> lam $ \l -> case l of
Cons _ _ -> B False
Nil -> B True
Head -> lam $ \l -> case l of
Cons i _ -> I i
_ -> error "Head of Nil!"
Tail -> lam $ \l -> case l of
Cons _ t -> t
_ -> error "Tail of Nil!"
|
pierzchalski/cs3161a1
|
MinHS/Evaluator.hs
|
Haskell
|
mit
| 2,781
|
-- Sum of Digits / Digital Root
-- http://www.codewars.com/kata/541c8630095125aba6000c00/
module DigitalRoot where
import Data.Char (digitToInt)
digitalRoot :: Integral a => a -> a
digitalRoot n | (n `div` 10) == 0 = n
| otherwise = digitalRoot . fromIntegral . sum . map digitToInt . show . fromIntegral $ n
|
gafiatulin/codewars
|
src/6 kyu/DigitalRoot.hs
|
Haskell
|
mit
| 326
|
module GHCJS.DOM.ClientRectList (
) where
|
manyoo/ghcjs-dom
|
ghcjs-dom-webkit/src/GHCJS/DOM/ClientRectList.hs
|
Haskell
|
mit
| 44
|
-- Code to deal with star colors
module Color where
data Color = RGB
{ colorR :: Double
, colorG :: Double
, colorB :: Double
}
deriving (Show,Eq)
addColors :: Color -> Color -> Color
addColors a b =
RGB { colorR = ((colorR a) + (colorR b))
, colorG = ((colorG a) + (colorG b))
, colorB = ((colorB a) + (colorB b))
}
scaleColor :: Color -> Double -> Color
scaleColor clr sf =
RGB { colorR = sf * (colorR clr)
, colorG = sf * (colorG clr)
, colorB = sf * (colorB clr)
}
|
j3camero/galaxyatlas
|
OldCrap/haskell/stardata/src/Color.hs
|
Haskell
|
mit
| 577
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module NFKD (specs) where
import Data.Monoid
import Data.Text.Normal.NFKD
import Data.String
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck (Arbitrary(..))
import Test.QuickCheck.Instances ()
instance Arbitrary Normal where
arbitrary = fmap fromText arbitrary
angstrom_sign, a_with_ring, e_acute, e_with_acute :: IsString a => a
-- should be identical under NFKC
angstrom_sign = "\8491"
a_with_ring = "\197"
e_acute = "\233"
e_with_acute = "e\769"
specs = do
describe "Normal type" $ do
prop "should look identical to Text type" $
\a -> show (toText a) == show a
prop "should Read identical to Text type" $
\a -> fromText (read (show a))
== read (show $ toText a)
it "should normalize when using IsString instance" $ do
"a" `shouldBe` fromText "a"
angstrom_sign `shouldBe` fromText a_with_ring
describe "fromText" $ do
prop "is idempotent" $
\a -> toText a == toText (fromText (toText a))
it "normalizes" $ do
fromText angstrom_sign `shouldBe` fromText a_with_ring
fromText e_with_acute `shouldBe` fromText e_acute
describe "appending" $ do
describe "follows monoid laws" $ do
prop "mappend mempty x = x" $ \(a :: Normal) -> a == mempty <> a
prop "mappend x mempty = x" $ \(a :: Normal) -> a == a <> mempty
prop "mappend x (mappend y z) = mappend (mappend x y) z" $
\(a :: Normal) b c -> a <> (b <> c) == (a <> b) <> c
prop "mconcat = foldr mappend mempty" $
\(as :: [Normal]) -> mconcat as == foldr (<>) mempty as
it "normalizes the result" $
property $ \a b -> fromText a <> fromText b == fromText (a <> b)
it "normalizes the result, take 2" $
fromText "e" <> fromText "\769" `shouldBe` fromText e_with_acute
{-# ANN module ("HLint: ignore Use camelCase" :: String) #-}
|
pikajude/text-normal
|
tests/NFKD.hs
|
Haskell
|
mit
| 2,103
|
{-| This module provides 'xmlFormatter' that can be used with 'Test.Hspec.Runner.hspecWith'.
Example usage:
> import Test.Hspec.Formatters.Jenkins (xmlFormatter)
> import Test.Hspec.Runner
>
> main :: IO ()
> main = do
> summary <- withFile "results.xml" WriteMode $ \h -> do
> let c = defaultConfig
> { configFormatter = xmlFormatter
> , configHandle = h
> }
> hspecWith c spec
> unless (summaryFailures summary == 0) $
> exitFailure
An example project is located in @example@ directory.
-}
{-# LANGUAGE OverloadedStrings #-}
module Test.Hspec.Formatters.Jenkins (xmlFormatter) where
import Data.List (intercalate)
import Test.Hspec.Formatters
import Test.Hspec.Runner (Path)
import Text.Blaze.Renderer.String (renderMarkup)
import Text.Blaze.Internal
failure, skipped :: Markup -> Markup
failure = customParent "failure"
skipped = customParent "skipped"
name, className, message :: String -> Attribute
name = customAttribute "name" . stringValue
className = customAttribute "classname" . stringValue
message = customAttribute "message" . stringValue
testcase :: Path -> Markup -> Markup
testcase (xs,x) = customParent "testcase" ! name x ! className (intercalate "." xs)
-- | Format Hspec result to Jenkins-friendly XML.
xmlFormatter :: Formatter
xmlFormatter = silent {
headerFormatter = do
writeLine "<?xml version='1.0' encoding='UTF-8'?>"
writeLine "<testsuite>"
, exampleSucceeded = \path -> do
writeLine $ renderMarkup $
testcase path ""
, exampleFailed = \path err -> do
writeLine $ renderMarkup $
testcase path $
failure ! message (either formatException id err) $ ""
, examplePending = \path mdesc -> do
writeLine $ renderMarkup $
testcase path $
case mdesc of
Just desc -> skipped ! message desc $ ""
Nothing -> skipped ""
, footerFormatter = do
writeLine "</testsuite>"
}
|
worksap-ate/hspec-jenkins
|
lib/Test/Hspec/Formatters/Jenkins.hs
|
Haskell
|
mit
| 1,988
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
-- |Multi-parameter variant of Applicative.
-- The contained data type is an explicit type parameter,
-- allowing instances to be made dependent on it.
--
-- The Applicative type class is split into two classes:
-- @Pure f a@, which provides @pure :: a -> f a@, and
-- @Applicative' f a b@, which provides
-- @(<*>) :: f (a -> b) -> f a -> f b@.
--
-- Note that, unlike regular monads, multi-parameter
-- monads with restrictions do not always imply the existence
-- of (meaningul) instances of Applicative\'.
-- For example, Set can be a Monad' (with Ord-restrictions),
-- but it cannot be a meaningful Applicative'-instance, since
-- '<*> :: f (a -> b) -> f a -> f b' would require the context 'Ord (a -> b)'.
--
-- For technical reasons, the instance 'Applicative\' Set a b' is
-- provided nonetheless, with the definition
--
-- @
-- f <*> x = Set.fromList $ Set.toList f Ap.<*> Set.toList x
-- @
--
-- This might as well be undefined, as, by default, a set of functions
-- is not constructible. Should the user declare '(Ord (a -> b))', however,
-- @<*>@ will work.
--
-- Adapted from Oleg Kiselyov's
-- 'http://okmij.org/ftp/Haskell/types.html#restricted-datatypes'.
module Control.Applicative.MultiParam (
Applicative'(..),
Pure(..),
) where
import qualified Control.Monad as Mo
import qualified Control.Applicative as Ap
import qualified Data.Set as Set
import Data.Functor.MultiParam
import Text.ParserCombinators.ReadP(ReadP)
import Text.ParserCombinators.ReadPrec(ReadPrec)
import GHC.Conc(STM)
class Pure f a where
pure :: a -> f a
class Functor' f a b => Applicative' f a b where
(<*>) :: f (a -> b) -> f a -> f b
instance Pure [] a where pure = Mo.return
instance Applicative' [] a b where f <*> x = f Ap.<*> x
instance Pure IO a where pure = Mo.return
instance Applicative' IO a b where f <*> x = f Ap.<*> x
instance Pure Maybe a where pure = Mo.return
instance Applicative' Maybe a b where f <*> x = f Ap.<*> x
instance Pure ReadP a where pure = Mo.return
instance Applicative' ReadP a b where f <*> x = f Ap.<*> x
instance Pure ReadPrec a where pure = Mo.return
instance Applicative' ReadPrec a b where f <*> x = f Ap.<*> x
instance Pure STM a where pure = Mo.return
instance Applicative' STM a b where f <*> x = f Ap.<*> x
instance Ord a => Pure Set.Set a where pure = Set.singleton
instance (Ord a, Ord b) => Applicative' Set.Set a b where
f <*> x = Set.fromList $ Set.toList f Ap.<*> Set.toList x
|
ombocomp/MultiParamMonad
|
Control/Applicative/MultiParam.hs
|
Haskell
|
mit
| 2,542
|
{-# LANGUAGE Arrows,
OverlappingInstances,
UndecidableInstances,
IncoherentInstances,
NoMonomorphismRestriction,
MultiParamTypeClasses,
FlexibleInstances,
RebindableSyntax #-}
-- Das Modul \hsSource{Circuit.ShowType.Instance} beschreibt, wie die Arrow-Klasse zu implementieren sind um damit später Schaltkreise
-- beschreiben, bearbeiten oder benutzen zu können.
module System.ArrowVHDL.Circuit.ShowType.Instance
where
-- Folgenden Module werden benötigt, um die Instanzen definieren zu können:
import System.ArrowVHDL.Circuit.ShowType.Class
import Prelude hiding (id, (.))
import qualified Prelude as Pr
import Control.Category
import System.ArrowVHDL.Circuit.Graphs
import System.ArrowVHDL.Circuit.Descriptor
-- Showtype wird hier für bestimmte Tupel-Typen beschrieben. Einzig die Tupel-Information ist das, was mittels Showtype in Pin-Informationen
-- übersetzt wird.
-- Die \hsSource{ShowType}-Instanz definiert die verschiedenen Typenvarianten, welche abbildbar sind.
-- Mit dem Typ \hsSource{(b, c) -> (c, b)} stellt die folgende Variante eine dar, in der die Ein- und Ausgänge miteinander vertauscht werden.
instance ShowType (b, c) (c, b) where
showType _
= emptyCircuit { nodeDesc = MkNode
{ label = "|b,c>c,b|"
, nodeId = 0
, sinks = mkPins 2
, sources = mkPins 2
}
}
where nd = nodeDesc emptyCircuit
-- Diese Variante mit dem Typ \hsSource{b -> (b, b)} beschreibt den Fall, in dem ein Eingang verdoppelt wird.
instance ShowType b (b, b) where
showType _
= emptyCircuit { nodeDesc = MkNode
{ label = "|b>b,b|"
, nodeId = 0
, sinks = mkPins 1
, sources = mkPins 2
}
}
where nd = nodeDesc emptyCircuit
-- Mit dem Typ \hsSource{(b, b) -> b} wir dann der Fall abgebildet, der zwei Eingänge auf einen zusammenfasst.
instance ShowType (b, b) b where
showType _
= emptyCircuit { nodeDesc = MkNode
{ label = "|b,b>b|"
, nodeId = 0
, sinks = mkPins 2
, sources = mkPins 1
}
}
where nd = nodeDesc emptyCircuit
-- instance ShowType (b, c) (b', c') where
-- showType _ = emptyCircuit { label = "b,c>b',c'"
-- , sinks = mkPins 1
-- , sources = mkPins 1
-- }
--
-- instance ShowType b b where
-- showType _ = emptyCircuit { label = "|b>b|"
-- , sinks = mkPins 1
-- , sources = mkPins 1
-- }
--
-- instance ShowType (b -> (c, d)) where
-- showType _ = emptyCircuit { label = "b>c,d"
-- , sinks = mkPins 1
-- , sources = mkPins 1
-- }
--
-- instance ShowType ((b, c) -> d) where
-- showType _ = emptyCircuit { label = "b,c>d"
-- , sinks = mkPins 1
-- , sources = mkPins 1
-- }
-- Letztlich bleibt noch der allgemeinste Fall der Möglich ist. Diese Varianten ist somit auch eine \begriff{CatchAll} Variante.
instance ShowType b c where
showType _
= emptyCircuit { nodeDesc = MkNode
{ label = "|b>c|"
, nodeId = 0
, sinks = mkPins 1
, sources = mkPins 1
}
}
where nd = nodeDesc emptyCircuit
|
frosch03/arrowVHDL
|
src/System/ArrowVHDL/Circuit/ShowType/Instance.hs
|
Haskell
|
cc0-1.0
| 3,970
|
module StartingOut (
doubleMe,
doubleUs,
doubleSmallNumber,
listComprehension
) where
doubleMe x = x + x
doubleUs x y = doubleMe x + doubleMe y
doubleSmallNumber x = if x > 100
then x
else x*2
-- We usually use ' to either denote a strict version of a function (one that isn't lazy) or a slightly modified version of a function or a variable
doubleSmallNumber' x = (if x > 100 then x else x*2) + 1
-- functions can't begin with uppercase letters
-- When a function doesn't take any parameters, we usually say it's a definition (or a name)
conanO'Brien = "It's a-me, Conan O'Brien!"
-- a list comprehension is composed of: one output function, at least one list-drawing-function, and any number of predicates
listComprehension = [ x*y | x <- [2,5,10], y <- [8,10,11], x*y > 50, x+y > 20]
nouns = ["hobo","frog","pope"]
adjectives = ["lazy","grouchy","scheming"]
adjectiveNoun = [adjective ++ " " ++ noun | adjective <- adjectives, noun <- nouns]
removeNonUppercase st = [ c | c <- st, c `elem` ['A'..'Z']]
triangles = [ (a,b,c) | c <- [1..10], b <- [1..10], a <- [1..10] ]
rightTriangle a b c = a^2 + b^2 == c^2
rightTriangles = [ (a, b, c) | (a, b, c) <- triangles, rightTriangle a b c ]
|
mboogerd/hello-haskell
|
src/lyah/StartingOut.hs
|
Haskell
|
apache-2.0
| 1,254
|
-- 1234567890
-- oooxoxoooo
dec2oct 0 = []
dec2oct n =
let a = n `mod` 8
b = n `div` 8
in
a:(dec2oct b)
oct2ans s [] = s
oct2ans s (n:ns) =
let n' = if n <= 3
then n
else if n <= 4
then n + 1
else n + 2
s' = s * 10 + n'
in
oct2ans s' ns
ans i =
let t = reverse $ dec2oct i
in
oct2ans 0 t
main = do
c <- getContents
let i = takeWhile (/= 0) $ map read $ lines c :: [Int]
o = map ans i
mapM_ print o
|
a143753/AOJ
|
0208.hs
|
Haskell
|
apache-2.0
| 507
|
{-# LANGUAGE BangPatterns, FlexibleContexts #-}
-- |
-- Module : Statistics.Transform
-- Copyright : (c) 2011 Bryan O'Sullivan
-- License : BSD3
--
-- Maintainer : bos@serpentine.com
-- Stability : experimental
-- Portability : portable
--
-- Fourier-related transformations of mathematical functions.
--
-- These functions are written for simplicity and correctness, not
-- speed. If you need a fast FFT implementation for your application,
-- you should strongly consider using a library of FFTW bindings
-- instead.
module Statistics.Transform
(
-- * Type synonyms
CD
-- * Discrete cosine transform
, dct
, dct_
, idct
, idct_
-- * Fast Fourier transform
, fft
, ifft
) where
import Control.Monad (when)
import Control.Monad.ST (ST)
import Data.Bits (shiftL, shiftR)
import Data.Complex (Complex(..), conjugate, realPart)
import Numeric.SpecFunctions (log2)
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as M
import qualified Data.Vector.Unboxed as U
type CD = Complex Double
-- | Discrete cosine transform (DCT-II).
dct :: (G.Vector v CD, G.Vector v Double, G.Vector v Int) => v Double -> v Double
dct = dctWorker . G.map (:+0)
-- | Discrete cosine transform (DCT-II). Only real part of vector is
-- transformed, imaginary part is ignored.
dct_ :: (G.Vector v CD, G.Vector v Double, G.Vector v Int) => v CD -> v Double
dct_ = dctWorker . G.map (\(i :+ _) -> i :+ 0)
dctWorker :: (G.Vector v CD, G.Vector v Double, G.Vector v Int) => v CD -> v Double
dctWorker xs
-- length 1 is special cased because shuffle algorithms fail for it.
| G.length xs == 1 = G.map ((2*) . realPart) xs
| vectorOK xs = G.map realPart $ G.zipWith (*) weights (fft interleaved)
| otherwise = error "Statistics.Transform.dct: bad vector length"
where
interleaved = G.backpermute xs $ G.enumFromThenTo 0 2 (len-2) G.++
G.enumFromThenTo (len-1) (len-3) 1
weights = G.cons 2 . G.generate (len-1) $ \x ->
2 * exp ((0:+(-1))*fi (x+1)*pi/(2*n))
where n = fi len
len = G.length xs
-- | Inverse discrete cosine transform (DCT-III). It's inverse of
-- 'dct' only up to scale parameter:
--
-- > (idct . dct) x = (* length x)
idct :: (G.Vector v CD, G.Vector v Double) => v Double -> v Double
idct = idctWorker . G.map (:+0)
-- | Inverse discrete cosine transform (DCT-III). Only real part of vector is
-- transformed, imaginary part is ignored.
idct_ :: U.Vector CD -> U.Vector Double
idct_ = idctWorker . G.map (\(i :+ _) -> i :+ 0)
idctWorker :: (G.Vector v CD, G.Vector v Double) => v CD -> v Double
idctWorker xs
| vectorOK xs = G.generate len interleave
| otherwise = error "Statistics.Transform.dct: bad vector length"
where
interleave z | even z = vals `G.unsafeIndex` halve z
| otherwise = vals `G.unsafeIndex` (len - halve z - 1)
vals = G.map realPart . ifft $ G.zipWith (*) weights xs
weights
= G.cons n
$ G.generate (len - 1) $ \x -> 2 * n * exp ((0:+1) * fi (x+1) * pi/(2*n))
where n = fi len
len = G.length xs
-- | Inverse fast Fourier transform.
ifft :: G.Vector v CD => v CD -> v CD
ifft xs
| vectorOK xs = G.map ((/fi (G.length xs)) . conjugate) . fft . G.map conjugate $ xs
| otherwise = error "Statistics.Transform.ifft: bad vector length"
-- | Radix-2 decimation-in-time fast Fourier transform.
fft :: G.Vector v CD => v CD -> v CD
fft v | vectorOK v = G.create $ do mv <- G.thaw v
mfft mv
return mv
| otherwise = error "Statistics.Transform.fft: bad vector length"
-- Vector length must be power of two. It's not checked
mfft :: (M.MVector v CD) => v s CD -> ST s ()
mfft vec = bitReverse 0 0
where
bitReverse i j | i == len-1 = stage 0 1
| otherwise = do
when (i < j) $ M.swap vec i j
let inner k l | k <= l = inner (k `shiftR` 1) (l-k)
| otherwise = bitReverse (i+1) (l+k)
inner (len `shiftR` 1) j
stage l !l1 | l == m = return ()
| otherwise = do
let !l2 = l1 `shiftL` 1
!e = -6.283185307179586/fromIntegral l2
flight j !a | j == l1 = stage (l+1) l2
| otherwise = do
let butterfly i | i >= len = flight (j+1) (a+e)
| otherwise = do
let i1 = i + l1
xi1 :+ yi1 <- M.read vec i1
let !c = cos a
!s = sin a
d = (c*xi1 - s*yi1) :+ (s*xi1 + c*yi1)
ci <- M.read vec i
M.write vec i1 (ci - d)
M.write vec i (ci + d)
butterfly (i+l2)
butterfly j
flight 0 0
len = M.length vec
m = log2 len
fi :: Int -> CD
fi = fromIntegral
halve :: Int -> Int
halve = (`shiftR` 1)
vectorOK :: G.Vector v a => v a -> Bool
{-# INLINE vectorOK #-}
vectorOK v = (1 `shiftL` log2 n) == n where n = G.length v
|
fpco/statistics
|
Statistics/Transform.hs
|
Haskell
|
bsd-2-clause
| 5,058
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QCalendarWidget.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:35
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Enums.Gui.QCalendarWidget (
HorizontalHeaderFormat, eNoHorizontalHeader, eSingleLetterDayNames, eShortDayNames, eLongDayNames
, VerticalHeaderFormat, eNoVerticalHeader, eISOWeekNumbers
, QCalendarWidgetSelectionMode
)
where
import Foreign.C.Types
import Qtc.Classes.Base
import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr)
import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int)
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
data CHorizontalHeaderFormat a = CHorizontalHeaderFormat a
type HorizontalHeaderFormat = QEnum(CHorizontalHeaderFormat Int)
ieHorizontalHeaderFormat :: Int -> HorizontalHeaderFormat
ieHorizontalHeaderFormat x = QEnum (CHorizontalHeaderFormat x)
instance QEnumC (CHorizontalHeaderFormat Int) where
qEnum_toInt (QEnum (CHorizontalHeaderFormat x)) = x
qEnum_fromInt x = QEnum (CHorizontalHeaderFormat x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> HorizontalHeaderFormat -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
eNoHorizontalHeader :: HorizontalHeaderFormat
eNoHorizontalHeader
= ieHorizontalHeaderFormat $ 0
eSingleLetterDayNames :: HorizontalHeaderFormat
eSingleLetterDayNames
= ieHorizontalHeaderFormat $ 1
eShortDayNames :: HorizontalHeaderFormat
eShortDayNames
= ieHorizontalHeaderFormat $ 2
eLongDayNames :: HorizontalHeaderFormat
eLongDayNames
= ieHorizontalHeaderFormat $ 3
data CVerticalHeaderFormat a = CVerticalHeaderFormat a
type VerticalHeaderFormat = QEnum(CVerticalHeaderFormat Int)
ieVerticalHeaderFormat :: Int -> VerticalHeaderFormat
ieVerticalHeaderFormat x = QEnum (CVerticalHeaderFormat x)
instance QEnumC (CVerticalHeaderFormat Int) where
qEnum_toInt (QEnum (CVerticalHeaderFormat x)) = x
qEnum_fromInt x = QEnum (CVerticalHeaderFormat x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> VerticalHeaderFormat -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
eNoVerticalHeader :: VerticalHeaderFormat
eNoVerticalHeader
= ieVerticalHeaderFormat $ 0
eISOWeekNumbers :: VerticalHeaderFormat
eISOWeekNumbers
= ieVerticalHeaderFormat $ 1
data CQCalendarWidgetSelectionMode a = CQCalendarWidgetSelectionMode a
type QCalendarWidgetSelectionMode = QEnum(CQCalendarWidgetSelectionMode Int)
ieQCalendarWidgetSelectionMode :: Int -> QCalendarWidgetSelectionMode
ieQCalendarWidgetSelectionMode x = QEnum (CQCalendarWidgetSelectionMode x)
instance QEnumC (CQCalendarWidgetSelectionMode Int) where
qEnum_toInt (QEnum (CQCalendarWidgetSelectionMode x)) = x
qEnum_fromInt x = QEnum (CQCalendarWidgetSelectionMode x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> QCalendarWidgetSelectionMode -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
instance QeNoSelection QCalendarWidgetSelectionMode where
eNoSelection
= ieQCalendarWidgetSelectionMode $ 0
instance QeSingleSelection QCalendarWidgetSelectionMode where
eSingleSelection
= ieQCalendarWidgetSelectionMode $ 1
|
keera-studios/hsQt
|
Qtc/Enums/Gui/QCalendarWidget.hs
|
Haskell
|
bsd-2-clause
| 6,712
|
module Main (main) where
import Test.Hspec (hspecX, descriptions)
import Control.Monad (msum)
import qualified Web.MusicBrainz.Testing.XML as X
main :: IO ()
main = hspecX $ descriptions [X.specs]
|
ocharles/Web-MusicBrainz
|
Web/MusicBrainz/Testing/Main.hs
|
Haskell
|
bsd-2-clause
| 200
|
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DataKinds #-}
module Propellor.PrivData (
withPrivData,
withSomePrivData,
addPrivData,
setPrivData,
unsetPrivData,
unsetPrivDataUnused,
dumpPrivData,
editPrivData,
filterPrivData,
listPrivDataFields,
makePrivDataDir,
decryptPrivData,
readPrivData,
readPrivDataFile,
PrivMap,
PrivInfo,
forceHostContext,
) where
import System.IO
import Data.Maybe
import Data.List
import Data.Typeable
import Control.Monad
import Control.Monad.IfElse
import "mtl" Control.Monad.Reader
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Lazy as L
import Control.Applicative
import Data.Monoid
import Prelude
import Propellor.Types
import Propellor.Types.PrivData
import Propellor.Types.MetaTypes
import Propellor.Types.Info
import Propellor.Message
import Propellor.Info
import Propellor.Gpg
import Propellor.PrivData.Paths
import Utility.Monad
import Utility.PartialPrelude
import Utility.Exception
import Utility.Tmp
import Utility.SafeCommand
import Utility.Process.NonConcurrent
import Utility.Misc
import Utility.FileMode
import Utility.Env
import Utility.Table
import Utility.Directory
-- | Allows a Property to access the value of a specific PrivDataField,
-- for use in a specific Context or HostContext.
--
-- Example use:
--
-- > withPrivData (PrivFile pemfile) (Context "joeyh.name") $ \getdata ->
-- > property "joeyh.name ssl cert" $ getdata $ \privdata ->
-- > liftIO $ writeFile pemfile (privDataVal privdata)
-- > where pemfile = "/etc/ssl/certs/web.pem"
--
-- Note that if the value is not available, the action is not run
-- and instead it prints a message to help the user make the necessary
-- private data available.
--
-- The resulting Property includes Info about the PrivDataField
-- being used, which is necessary to ensure that the privdata is sent to
-- the remote host by propellor.
withPrivData
::
( IsContext c
, IsPrivDataSource s
, IncludesInfo metatypes ~ 'True
)
=> s
-> c
-> (((PrivData -> Propellor Result) -> Propellor Result) -> Property metatypes)
-> Property metatypes
withPrivData s = withPrivData' snd [s]
-- Like withPrivData, but here any one of a list of PrivDataFields can be used.
withSomePrivData
::
( IsContext c
, IsPrivDataSource s
, IncludesInfo metatypes ~ 'True
)
=> [s]
-> c
-> ((((PrivDataField, PrivData) -> Propellor Result) -> Propellor Result) -> Property metatypes)
-> Property metatypes
withSomePrivData = withPrivData' id
withPrivData'
::
( IsContext c
, IsPrivDataSource s
, IncludesInfo metatypes ~ 'True
)
=> ((PrivDataField, PrivData) -> v)
-> [s]
-> c
-> (((v -> Propellor Result) -> Propellor Result) -> Property metatypes)
-> Property metatypes
withPrivData' feed srclist c mkprop = addinfo $ mkprop $ \a ->
maybe missing (a . feed) =<< getM get fieldlist
where
get field = do
context <- mkHostContext hc <$> asks hostName
maybe Nothing (\privdata -> Just (field, privdata))
<$> liftIO (getLocalPrivData field context)
missing = do
Context cname <- mkHostContext hc <$> asks hostName
warningMessage $ "Missing privdata " ++ intercalate " or " fieldnames ++ " (for " ++ cname ++ ")"
infoMessage $
"Fix this by running:" :
showSet (map (\s -> (privDataField s, Context cname, describePrivDataSource s)) srclist)
return FailedChange
addinfo p = p `addInfoProperty` (toInfo privset)
privset = PrivInfo $ S.fromList $
map (\s -> (privDataField s, describePrivDataSource s, hc)) srclist
fieldnames = map show fieldlist
fieldlist = map privDataField srclist
hc = asHostContext c
showSet :: [(PrivDataField, Context, Maybe PrivDataSourceDesc)] -> [String]
showSet = concatMap go
where
go (f, Context c, md) = catMaybes
[ Just $ " propellor --set '" ++ show f ++ "' '" ++ c ++ "' \\"
, maybe Nothing (\d -> Just $ " " ++ d) md
, Just ""
]
addPrivData :: (PrivDataField, Maybe PrivDataSourceDesc, HostContext) -> Property (HasInfo + UnixLike)
addPrivData v = pureInfoProperty (show v) (PrivInfo (S.singleton v))
{- Gets the requested field's value, in the specified context if it's
- available, from the host's local privdata cache. -}
getLocalPrivData :: PrivDataField -> Context -> IO (Maybe PrivData)
getLocalPrivData field context =
getPrivData field context . fromMaybe M.empty <$> localcache
where
localcache = catchDefaultIO Nothing $ readish <$> readFile privDataLocal
type PrivMap = M.Map (PrivDataField, Context) String
-- | Get only the set of PrivData that the Host's Info says it uses.
filterPrivData :: Host -> PrivMap -> PrivMap
filterPrivData host = M.filterWithKey (\k _v -> S.member k used)
where
used = S.map (\(f, _, c) -> (f, mkHostContext c (hostName host))) $
fromPrivInfo $ fromInfo $ hostInfo host
getPrivData :: PrivDataField -> Context -> PrivMap -> Maybe PrivData
getPrivData field context m = do
s <- M.lookup (field, context) m
return (PrivData s)
setPrivData :: PrivDataField -> Context -> IO ()
setPrivData field context = do
putStrLn "Enter private data on stdin; ctrl-D when done:"
setPrivDataTo field context . PrivData =<< hGetContentsStrict stdin
unsetPrivData :: PrivDataField -> Context -> IO ()
unsetPrivData field context = do
modifyPrivData $ M.delete (field, context)
descUnset field context
descUnset :: PrivDataField -> Context -> IO ()
descUnset field context =
putStrLn $ "Private data unset: " ++ show field ++ " " ++ show context
unsetPrivDataUnused :: [Host] -> IO ()
unsetPrivDataUnused hosts = do
deleted <- modifyPrivData' $ \m ->
let (keep, del) = M.partitionWithKey (\k _ -> k `M.member` usedby) m
in (keep, M.keys del)
mapM_ (uncurry descUnset) deleted
where
usedby = mkUsedByMap hosts
dumpPrivData :: PrivDataField -> Context -> IO ()
dumpPrivData field context = do
maybe (error "Requested privdata is not set.")
(L.hPut stdout . privDataByteString)
=<< (getPrivData field context <$> decryptPrivData)
editPrivData :: PrivDataField -> Context -> IO ()
editPrivData field context = do
v <- getPrivData field context <$> decryptPrivData
v' <- withTmpFile "propellorXXXX" $ \f th -> do
hClose th
maybe noop (\p -> writeFileProtected' f (`L.hPut` privDataByteString p)) v
editor <- getEnvDefault "EDITOR" "vi"
unlessM (boolSystemNonConcurrent editor [File f]) $
error "Editor failed; aborting."
PrivData <$> readFile f
setPrivDataTo field context v'
listPrivDataFields :: [Host] -> IO ()
listPrivDataFields hosts = do
m <- decryptPrivData
section "Currently set data:"
showtable $ map mkrow (M.keys m)
let missing = M.keys $ M.difference wantedmap m
unless (null missing) $ do
section "Missing data that would be used if set:"
showtable $ map mkrow missing
section "How to set missing data:"
mapM_ putStrLn $ showSet $
map (\(f, c) -> (f, c, join $ M.lookup (f, c) descmap)) missing
where
header = ["Field", "Context", "Used by"]
mkrow k@(field, Context context) =
[ shellEscape $ show field
, shellEscape context
, intercalate ", " $ sort $ fromMaybe [] $ M.lookup k usedby
]
usedby = mkUsedByMap hosts
wantedmap = M.fromList $ zip (M.keys usedby) (repeat "")
descmap = M.unions $ map (`mkPrivDataMap` id) hosts
section desc = putStrLn $ "\n" ++ desc
showtable rows = do
putStr $ unlines $ formatTable $ tableWithHeader header rows
mkUsedByMap :: [Host] -> M.Map (PrivDataField, Context) [HostName]
mkUsedByMap = M.unionsWith (++) . map (\h -> mkPrivDataMap h $ const [hostName h])
mkPrivDataMap :: Host -> (Maybe PrivDataSourceDesc -> a) -> M.Map (PrivDataField, Context) a
mkPrivDataMap host mkv = M.fromList $
map (\(f, d, c) -> ((f, mkHostContext c (hostName host)), mkv d))
(S.toList $ fromPrivInfo $ fromInfo $ hostInfo host)
setPrivDataTo :: PrivDataField -> Context -> PrivData -> IO ()
setPrivDataTo field context (PrivData value) = do
modifyPrivData set
putStrLn "Private data set."
where
set = M.insert (field, context) value
modifyPrivData :: (PrivMap -> PrivMap) -> IO ()
modifyPrivData f = modifyPrivData' (\m -> (f m, ()))
modifyPrivData' :: (PrivMap -> (PrivMap, a)) -> IO a
modifyPrivData' f = do
makePrivDataDir
m <- decryptPrivData
let (m', r) = f m
privdata <- privDataFile
gpgEncrypt privdata (show m')
void $ boolSystem "git" [Param "add", File privdata]
return r
decryptPrivData :: IO PrivMap
decryptPrivData = readPrivData <$> (gpgDecrypt =<< privDataFile)
readPrivData :: String -> PrivMap
readPrivData = fromMaybe M.empty . readish
readPrivDataFile :: FilePath -> IO PrivMap
readPrivDataFile f = readPrivData <$> readFileStrict f
makePrivDataDir :: IO ()
makePrivDataDir = createDirectoryIfMissing False privDataDir
newtype PrivInfo = PrivInfo
{ fromPrivInfo :: S.Set (PrivDataField, Maybe PrivDataSourceDesc, HostContext) }
deriving (Eq, Ord, Show, Typeable, Monoid)
-- PrivInfo always propagates out of containers, so that propellor
-- can see which hosts need it.
instance IsInfo PrivInfo where
propagateInfo _ = PropagatePrivData
-- | Sets the context of any privdata that uses HostContext to the
-- provided name.
forceHostContext :: String -> PrivInfo -> PrivInfo
forceHostContext name i = PrivInfo $ S.map go (fromPrivInfo i)
where
go (f, d, HostContext ctx) = (f, d, HostContext (const $ ctx name))
|
ArchiveTeam/glowing-computing-machine
|
src/Propellor/PrivData.hs
|
Haskell
|
bsd-2-clause
| 9,424
|
module TestModuleMany where
import HEP.Automation.EventGeneration.Type
import HEP.Automation.JobQueue.JobType
import HEP.Automation.MadGraph.Model
import HEP.Automation.MadGraph.Model.SM
import HEP.Automation.MadGraph.SetupType
import HEP.Automation.MadGraph.Type
import HEP.Storage.WebDAV.Type
psetup :: ProcessSetup SM
psetup = PS { model = SM
, process = MGProc [] [ "p p > t t~" ]
, processBrief = "ttbar"
, workname = "ttbar"
, hashSalt = HashSalt Nothing }
param :: ModelParam SM
param = SMParam
rsetupgen :: Int -> RunSetup
rsetupgen x =
RS { numevent = 10000
, machine = LHC7 ATLAS
, rgrun = Auto
, rgscale = 200
, match = MLM
, cut = DefCut
, pythia = RunPYTHIA
, lhesanitizer = []
, pgs = RunPGS (AntiKTJet 0.4, WithTau)
, uploadhep = NoUploadHEP
, setnum = x
}
eventsets :: [EventSet]
eventsets = [ EventSet psetup param (rsetupgen x) | x <- [2..10] ]
webdavdir :: WebDAVRemoteDir
webdavdir = WebDAVRemoteDir "newtest"
|
wavewave/jobqueue-sender
|
TestModuleMany.hs
|
Haskell
|
bsd-2-clause
| 1,097
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Exception (bracketOnError)
import Control.Monad.State.Lazy
import Data.Maybe (fromMaybe)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network hiding (socketPort)
import Network.BSD (getProtocolNumber)
import Network.Socket hiding (PortNumber, accept, sClose)
import Options.Applicative
import Purescript.Ide
import System.Directory
import System.Exit
import System.FilePath
import System.IO
-- Copied from upstream impl of listenOn
-- bound to localhost interface instead of iNADDR_ANY
listenOnLocalhost :: PortID -> IO Socket
listenOnLocalhost (PortNumber port) = do
proto <- getProtocolNumber "tcp"
localhost <- inet_addr "127.0.0.1"
bracketOnError
(socket AF_INET Stream proto)
sClose
(\sock ->
do setSocketOption sock ReuseAddr 1
bindSocket sock (SockAddrInet port localhost)
listen sock maxListenQueue
return sock)
data Options = Options
{ optionsDirectory :: Maybe FilePath
, optionsPort :: Maybe Int
}
main :: IO ()
main = do
Options dir port <- execParser opts
maybe (return ()) setCurrentDirectory dir
startServer (PortNumber . fromIntegral $ fromMaybe 4242 port) emptyPscState
where
parser =
Options <$>
optional (strOption (long "directory" <> short 'd')) <*>
optional (option auto (long "port" <> short 'p'))
opts = info parser mempty
startServer :: PortID -> PscState -> IO ()
startServer port st_in =
withSocketsDo $
do sock <- listenOnLocalhost port
evalStateT (forever (loop sock)) st_in
where
acceptCommand sock = do
(h,_,_) <- accept sock
hSetEncoding h utf8
cmd <- T.hGetLine h
return (cmd, h)
loop :: Socket -> PscIde ()
loop sock = do
(cmd,h) <- liftIO $ acceptCommand sock
case parseCommand cmd of
Right cmd' -> do
result <- handleCommand cmd'
liftIO $ T.hPutStrLn h result
Left err -> liftIO $ hPrint h err
liftIO $ hClose h
handleCommand :: Command -> PscIde T.Text
handleCommand (TypeLookup ident) = fromMaybe "Not found" <$> findTypeForName ident
handleCommand (Completion stub) = T.intercalate ", " <$> findCompletion stub
handleCommand (Load moduleName) = do
path <- liftIO $ filePathFromModule moduleName
case path of
Right p -> loadModule p >> return "Success"
Left err -> return err
handleCommand Print = T.intercalate ", " <$> printModules
handleCommand Quit = liftIO exitSuccess
filePathFromModule :: T.Text -> IO (Either T.Text FilePath)
filePathFromModule moduleName = do
cwd <- getCurrentDirectory
let path = cwd </> "output" </> T.unpack moduleName </> "externs.purs"
ex <- doesFileExist path
return $
if ex
then Right path
else Left "Module could not be found"
|
epost/psc-ide
|
server/Main.hs
|
Haskell
|
bsd-3-clause
| 3,181
|
module Day20 where
{-# LANGUAGE TupleSections #-}
-- Improvements to Day18
import Control.Monad.Gen
import Control.Monad.Trans.Either
import Control.Monad.Reader
import qualified Data.Map as Map
data Type
= Function Type Type -- a -> b
| RecordT [(String, Type)] -- a * b
| VariantT [(String, Type)] -- a + b
deriving (Eq, Show)
-- t2 = { x: 10, y: 20 } : { x : Int, y : Int }
-- t3 = { x: 10, y: 20, z: 30 } : { x : Int, y : Int, z : Int }
-- f : { x : Int } -> Int
-- f tuple = tuple.x
-- f t3
-- eitherIS = { left : Int | right : String }
-- x = left 5 : eitherIS
-- Note: In a bidirectional HOAS, functions always take a checked term to
-- checked term. Why? Because we want to take in and return canonical values
-- (which are possibly neutral), not computations.
-- Canonical values
data CheckTerm
-- Neither a constructor nor change of direction.
--
-- The type is the return type.
= Let String InferTerm Type (InferTerm -> CheckTerm)
-- switch direction (infer -> check)
| Neutral InferTerm
-- constructors
-- \x -> CheckedTerm
| Abs String (InferTerm -> CheckTerm)
| Record [(String, CheckTerm)]
| Variant String CheckTerm
-- Computations
data InferTerm
-- switch direction (check -> infer)
= Annot CheckTerm Type
-- Used in both reification and typechecking.
-- We don't use the type during reification, but do during checking.
| Unique Int (Maybe Type)
-- eliminators
--
-- note that eliminators always take an InferTerm as the inspected term,
-- since that's the neutral position, then CheckTerms for the rest
| App InferTerm CheckTerm
| AccessField InferTerm String
| Case InferTerm Type [(String, InferTerm -> CheckTerm)]
data NCheckTerm
= NLet String NInferTerm Type NCheckTerm
| NNeutral NInferTerm
| NAbs String NCheckTerm
| NRecord [(String, NCheckTerm)]
| NVariant String NCheckTerm
deriving Show
data NInferTerm
= NVar String
| NAnnot NCheckTerm Type
| NApp NInferTerm NCheckTerm
| NAccessField NInferTerm String
| NCase NInferTerm Type [(String, NCheckTerm)]
deriving Show
-- In reflection we use a map reader to look up bound variables by name
reflect :: NCheckTerm -> CheckTerm
reflect t = runReader (cReflect t) Map.empty
cReflect :: NCheckTerm -> Reader (Map.Map String InferTerm) CheckTerm
cReflect nTm = case nTm of
NLet name iTm ty cTm -> do
table <- ask
iTm' <- iReflect iTm
return $ Let name iTm' ty $ \arg ->
runReader (cReflect cTm) (Map.insert name arg table)
NNeutral iTm -> Neutral <$> iReflect iTm
NAbs name cTm -> do
table <- ask
return $ Abs name $ \arg ->
runReader (cReflect cTm) (Map.insert name arg table)
NRecord fields -> do
fields' <- Map.toList <$> traverse cReflect (Map.fromList fields)
return $ Record fields'
NVariant str cTm -> Variant str <$> cReflect cTm
iReflect :: NInferTerm -> Reader (Map.Map String InferTerm) InferTerm
iReflect nTm = case nTm of
NVar name -> do
let ty = undefined
cTm <- reader (Map.! name)
return $ Annot cTm ty
NAnnot cTm ty -> Annot <$> cReflect cTm <*> pure ty
NApp iTm cTm -> App <$> iReflect iTm <*> cReflect cTm
NAccessField iTm name -> AccessField <$> iReflect iTm <*> pure name
NCase iTm ty cases -> do
iTm' <- iReflect iTm
table <- ask
cases' <- (`Map.traverseWithKey` Map.fromList cases) $ \name cTm ->
return $ \cTmArg ->
runReader (cReflect cTm) (Map.insert name cTmArg table)
return $ Case iTm' ty (Map.toList cases')
-- In reification we use a map reader to look up temporarily named variables
reify :: CheckTerm -> NCheckTerm
reify t = runGen (runReaderT (cReify t) Map.empty)
iReify :: InferTerm -> ReaderT (Map.Map Int NInferTerm) (Gen Int) NInferTerm
iReify t = case t of
Unique ident _ -> (Map.! ident) <$> ask
Annot cTm ty -> NAnnot <$> cReify cTm <*> pure ty
App t1 t2 -> NApp <$> iReify t1 <*> cReify t2
AccessField subTm name -> NAccessField <$> iReify subTm <*> pure name
Case iTm ty branches -> do
iTm' <- iReify iTm
branches' <- (`Map.traverseWithKey` Map.fromList branches) $ \name f -> do
ident <- gen
local (Map.insert ident (NVar name)) $
cReify (f (Unique ident Nothing))
return $ NCase iTm' ty (Map.toList branches')
cReify :: CheckTerm -> ReaderT (Map.Map Int NInferTerm) (Gen Int) NCheckTerm
cReify t = case t of
Let name iTm ty f -> do
iTm' <- iReify iTm
ident <- gen
nom <- local (Map.insert ident (NVar name)) $
cReify (f (Unique ident Nothing))
return $ NLet name iTm' ty nom
Neutral iTm -> NNeutral <$> iReify iTm
Abs name f -> do
ident <- gen
nom <- local (Map.insert ident (NVar name)) $
cReify (f (Unique ident Nothing))
return $ NAbs name nom
Record fields -> do
fields' <- Map.toList <$> traverse cReify (Map.fromList fields)
return $ NRecord fields'
Variant tag content -> NVariant tag <$> cReify content
type EvalCtx = Either String
type CheckCtx = EitherT String (Gen Int)
eval :: InferTerm -> EvalCtx CheckTerm
eval t = case t of
Annot cTerm _ -> return cTerm
Unique _ _ -> Left "invariant violation: found Unique in evaluation"
App f x -> do
f' <- eval f
case f' of
-- XXX stop propagating neutrals?
Neutral f'' -> return $ Neutral (App f'' x)
Abs _ f'' -> return $ Neutral (f'' x)
_ -> Left "invariant violation: eval found non-Neutral / Abs in function position"
AccessField iTm name -> do
evaled <- eval iTm
case evaled of
Neutral nTm -> return $ Neutral (AccessField nTm name)
Record fields -> case Map.lookup name (Map.fromList fields) of
Just field -> return field
Nothing -> Left "didn't find field in record"
_ -> Left "unexpected"
Case iTm ty branches -> do
evaled <- eval iTm
case evaled of
Neutral nTm -> return $ Neutral (Case nTm ty branches)
Variant name cTm -> case Map.lookup name (Map.fromList branches) of
Just branch -> return $ branch cTm
Nothing -> Left "invariant violation: evaluation didn't find matching variant in case"
_ -> Left "invariant violation: evalutaion found non neutral - variant in case"
runChecker :: CheckCtx () -> String
runChecker calc = case runGen (runEitherT calc) of
Right () -> "success!"
Left str -> str
-- runInference :: CheckCtx Type -> Type
-- runInference calc = case runGen (runEitherT calc) of
-- Left str -> error $ "(runInference) invariant violation: " ++ str
-- Right ty -> ty
unifyTy :: Type -> Type -> CheckCtx Type
unifyTy (Function dom1 codom1) (Function dom2 codom2) =
Function <$> unifyTy dom1 dom2 <*> unifyTy codom1 codom2
unifyTy (RecordT lTy) (RecordT rTy) = do
-- RecordT [(String, Type)]
-- Take the intersection of possible records. Make sure the overlap matches!
let isect = Map.intersectionWith (,) (Map.fromList lTy) (Map.fromList rTy)
isect' <- mapM (uncurry unifyTy) isect
return $ RecordT (Map.toList isect')
unifyTy (VariantT lTy) (VariantT rTy) = do
-- Take the union of possible variants. Make sure overlap matches!
let isect = Map.intersectionWith (,) (Map.fromList lTy) (Map.fromList rTy)
isect' <- mapM (uncurry unifyTy) isect
let union = Map.union (Map.fromList lTy) (Map.fromList rTy)
-- Overwrite with extra data we may have learned from unifying the types in
-- the intersection
let result = Map.union isect' union
return $ VariantT (Map.toList result)
unifyTy l r = left ("failed unification " ++ show (l, r))
check :: CheckTerm -> Type -> CheckCtx ()
check eTm ty = case eTm of
-- t1: infered, t2: infer -> check
Let _name t1 ty' body -> do
t1Ty <- infer t1
_ <- unifyTy t1Ty ty'
let bodyVal = body t1
check bodyVal ty
Neutral iTm -> do
iTy <- infer iTm
_ <- unifyTy ty iTy
return ()
Abs _ body -> do
let Function domain codomain = ty
v <- Unique <$> lift gen <*> pure (Just domain)
let evaled = body v
check evaled codomain
Record fields -> do
-- Record [(String, CheckTerm)]
--
-- Here we define our notion of record subtyping -- we check that the
-- record we've been given has at least the fields expected of it and of
-- the right type.
let fieldMap = Map.fromList fields
case ty of
RecordT fieldTys -> mapM_
(\(name, subTy) -> case Map.lookup name fieldMap of
Just subTm -> check subTm subTy
Nothing -> left "failed to find required field in record"
)
fieldTys
_ -> left "failed to check a record against a non-record type"
-- Variant String CheckTerm
--
-- Here we define our notion of variant subtyping -- we check that the
-- variant we've been given is in the row
Variant name t' -> case ty of
VariantT fieldTys -> case Map.lookup name (Map.fromList fieldTys) of
Just expectedTy -> check t' expectedTy
Nothing -> left "failed to find required field in record"
_ -> left "failed to check a record against a non-record type"
infer :: InferTerm -> CheckCtx Type
infer t = case t of
Annot _ ty -> pure ty
Unique _ _ -> left "invariant violation: infer found Unique"
App t1 t2 -> do
Function domain codomain <- infer t1
check t2 domain
return codomain
-- rec.name
AccessField recTm name -> do
inspectTy <- infer recTm
case inspectTy of
RecordT parts -> case Map.lookup name (Map.fromList parts) of
Just subTy -> return subTy
Nothing -> left "didn't find the accessed key"
_ -> left "found non-record unexpectedly"
-- (case [varTm] of [cases]) : [ty]
Case varTm ty cases -> do
-- check that the inspected value is a variant,
-- check all of its cases and the branches to see if all are aligned,
-- finally that each typechecks
varTmTy <- infer varTm
case varTmTy of
VariantT tyParts -> do
let tyMap = Map.fromList tyParts
caseMap = Map.fromList cases
bothMatch = Map.null (tyMap Map.\\ caseMap)
&& Map.null (caseMap Map.\\ tyMap)
when (not bothMatch) (left "case misalignment")
let mergedMap = Map.mergeWithKey
(\name l r -> Just (name, l, r))
(const (Map.fromList []))
(const (Map.fromList []))
tyMap
caseMap
mapM_
(\(_name, branchTy, rhs) -> do
v <- Unique <$> lift gen <*> pure (Just branchTy)
check (rhs (Neutral v)) ty
)
mergedMap
_ -> left "found non-variant in case"
return ty
main :: IO ()
main = putStrLn "here"
-- let unit = Record []
-- unitTy = RecordT []
-- xy = Record
-- [ ("x", unit)
-- , ("y", unit)
-- ]
-- xyTy = RecordT
-- [ ("x", unitTy)
-- , ("y", unitTy)
-- ]
-- -- boring
-- print $ runChecker $
-- let tm = Abs "id" (\x -> x)
-- ty = Function unitTy unitTy
-- in check tm ty
-- -- standard record
-- print $ runChecker $
-- let tm = Let
-- "xy"
-- (Annot xy xyTy)
-- xyTy
-- (\x -> Neutral
-- (AccessField (Annot x xyTy) "x")
-- )
-- in check tm unitTy
-- -- record subtyping
-- print $ runChecker $
-- let xRecTy = RecordT [("x", unitTy)]
-- tm = Let
-- "xy"
-- (Annot xy xRecTy)
-- xRecTy
-- (\x -> Neutral
-- (AccessField (Annot x xRecTy) "x")
-- )
-- in check tm unitTy
-- -- variant subtyping
-- --
-- -- left () : { left () | right () }
-- print $ runChecker $
-- let eitherTy = VariantT
-- [ ("left", unitTy)
-- , ("right", unitTy)
-- ]
-- in check (Variant "left" unit) eitherTy
-- -- let x = left () : { left : () | right : () }
-- -- in case x of
-- -- left y -> y
-- -- right y -> y
-- print $
-- let eitherTy = VariantT
-- [ ("left", unitTy)
-- , ("right", unitTy)
-- ]
-- tm = Let
-- "e"
-- (Annot (Variant "left" unit) eitherTy)
-- eitherTy
-- (\x -> Neutral
-- (Case (Annot x eitherTy) unitTy
-- [ ("left", \y -> y)
-- , ("right", \y -> y)
-- ]
-- )
-- )
-- in (runChecker (check tm unitTy), reify <$> eval (Annot tm unitTy))
|
joelburget/daily-typecheckers
|
src/Day20.hs
|
Haskell
|
bsd-3-clause
| 12,440
|
module Husky.Wai.FileApplication
(
fileApplication
) where
import System.FilePath
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as LB
import Data.Enumerator (yield, Stream(EOF))
import Data.CaseInsensitive ( mk )
import Network.Wai
import Network.HTTP.Types
header :: String -> String -> Header
header key value = (mk (B.pack key), (B.pack value))
-- | WAI application to host file at given urlPath
fileApplication :: String -> FilePath -> Application
fileApplication urlPath file request = do
liftIO $ putStrLn $ (show $ remoteHost request) ++ " connected."
if tail (B.unpack $ rawPathInfo request) == urlPath
then (liftIO . putStrLn) "good URL." >>
yield (ResponseFile statusOK headers file Nothing) EOF
else (liftIO . putStrLn) "bad URL." >>
yield (responseLBS statusNotFound [headerContentType (B.pack "text/plain")] (LB.pack "404 Not Found")) EOF
where
headers = [ headerContentType (B.pack $ guessContentType file) ]
guessContentType :: FilePath -> String
guessContentType path = byExt (takeExtension path)
where
byExt ".org" = "text/plain"
byExt ".txt" = "text/plain"
byExt _ = "application/octet-stream"
|
abaw/husky
|
Husky/Wai/FileApplication.hs
|
Haskell
|
bsd-3-clause
| 1,362
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Model where
import Data.Time.Clock
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.SqlQQ
import Database.PostgreSQL.Simple.Types
import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.ToRow
import qualified Data.Text as T
data Paste = Paste { content :: T.Text
} deriving Show
instance FromRow Paste where
fromRow = Paste <$> field
instance ToRow Paste where
toRow t = [toField (content t)]
-- Initialize database
createPasteBox :: Query
createPasteBox =
[sql|
CREATE TABLE IF NOT EXISTS paste (
lid SERIAL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_DATE,
content TEXT NOT NULL );
|]
addPasteReturningID :: Connection -> Paste -> IO [Only Int]
addPasteReturningID con a = query con "INSERT INTO paste (created_at, content) VALUES (NOW (), ?) RETURNING lid" $ a
getPasteWithID :: Connection -> Int -> IO [Paste]
getPasteWithID c n = query c "SELECT TEXT(content) FROM paste WHERE lid = ?" $ Only n
|
sivteck/hs-pastebin
|
src/Model.hs
|
Haskell
|
bsd-3-clause
| 1,248
|
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GADTs #-}
module Main where
type X a b = Y a b
type Function c d =
c -> Int -> d
-> Int
newtype A = B Int
data C = D String | E deriving (Show)
data Z a b =
Z
(X a b)
(X a b
, X a b)
data F = F
{ c :: String,
d :: String
} deriving (Eq, Show)
data Sql where
Sql :: Sql.Connection conn => conn -> Sql
build :: F
build =
F { c = "c"
, d = "d" }
test :: Num n => n -> F
test _ =
build { c = "C", d = "D" } :: F
class (Num r, Ord r) => Repository r where
create :: r -> String -> Int -> IO ()
read :: String -> IO (Maybe Int)
instance Num a => Repository (Dict String Int) where
type X = Y
create dict string int = Dict.set dict string int
read = Dict.get
|
hecrj/haskell-format
|
test/specs/types/input.hs
|
Haskell
|
bsd-3-clause
| 754
|
{-# LANGUAGE TypeOperators #-}
module LiuMS.Config
( Config (..), Language, SiteInfo (..)
, liuMSInfo, mkConfig
, askContentPath, askCacheManager, askSiteInfo
) where
import Control.Monad.Reader
import Control.Monad.Trans.Except
import Servant
import LiuMS.CacheManager
import LiuMS.Compiler
import LiuMS.Compiler.Markdown
data Config = Config
{ contentPath :: FilePath
, cacheManager :: CacheManager
, siteInfo :: [(Language, SiteInfo)]
}
type Language = String
data SiteInfo = SiteInfo
{ title :: String
, description :: String
, author :: String
, language :: String
} deriving (Eq, Show)
liuMSInfo :: [(Language, SiteInfo)]
liuMSInfo =
[ ( "cmn-Hans-CN"
, SiteInfo
{ title = "Liu.ms"
, description = "我,刘闽晟,是一位对计算机科学、语言学、政治科学感兴趣的本科生。点击网站来了解我的生活、兴趣、观点。"
, author = "刘闽晟"
, language = "cmn-Hans-CN"
}
)
, ( "eng-Latn-US"
, SiteInfo
{ title = "Liu.ms"
, description = "I am Minsheng Liu, an undergraduate interested in CS, Linguistics, and Political Science. Click this site to learn more about my life, interests, and viewpoints."
, author = "Minsheng Liu"
, language = "eng-Latn-US"
}
)
]
mkConfig :: FilePath -> FilePath -> Config
mkConfig contentPath cachePath = Config contentPath manager liuMSInfo where
manager = CacheManager (contentPath ++ "/contents")
cachePath
[("md", markdown)]
askContentPath :: (MonadReader Config m) => m FilePath
askContentPath = contentPath <$> ask
askCacheManager :: (MonadReader Config m) => m CacheManager
askCacheManager = cacheManager <$> ask
askSiteInfo :: (MonadReader Config m) => m SiteInfo
askSiteInfo = do infos <- siteInfo <$> ask
return $ snd $ head infos
|
notcome/liu-ms-adult
|
src/LiuMS/Config.hs
|
Haskell
|
bsd-3-clause
| 1,960
|
{-# LANGUAGE FlexibleInstances,
FlexibleContexts #-}
module Obsidian.MonadObsidian.PureAPI where
import Obsidian.MonadObsidian.Exp
import Obsidian.MonadObsidian.Arr
-- import Bitwise
--import Data.Bits
import Control.Monad
import Data.Foldable
--------------------------------------------------------------------------------
pure f a = return $ f a
--------------------------------------------------------------------------------
(??) b (x,y) = ifThenElse b x y
intLog 1 = 0
intLog n = 1 + (intLog (div n 2))
--------------------------------------------------------------------------------
{-
unriffle' :: Arr s a -> Arr s a
unriffle' arr | even (len arr) = mkArr (\ix -> arr ! (rotLocalL ix bits) ) n
where
n = len arr
bits = fromIntegral $ intLog n
unriffle' _ = error "unriffle' demands even length"
riffle' :: Arr s a -> Arr s a
riffle' arr | even (len arr) = mkArr (\ix -> arr ! (rotLocalR ix bits) ) n
where
n = len arr
bits = fromIntegral $ intLog n
riffle' _ = error "riffle' demands even length"
-}
instance Foldable (Arr s) where
foldr f o arr =
Prelude.foldr f o [arr ! (fromIntegral ix) | ix <- [0.. (len arr - 1)]]
--------------------------------------------------------------------------------
flatten :: (Arr s (Arr s a)) -> Arr s a
flatten arrs | len (arrs ! 0) == 1 =
mkArr (\ix -> (arrs ! ix) ! 0) m
where
k = len arrs
n = len (arrs ! 0)
m = k * n
flatten arrs = mkArr (\ix -> (arrs ! (ix `divi` fromIntegral k)) ! (ix `modi` fromIntegral n)) m
where k = len arrs
n = len (arrs ! 0)
m = k*n
restruct :: Int -> Arr s a -> (Arr s (Arr s a))
restruct n arr = mkArr (\ix -> inner ix) n
where
m = len arr
k = m `div` n
inner a = mkArr (\ix -> arr ! ((a * fromIntegral k) + ix) ) k
--------------------------------------------------------------------------------
chopN :: Int -> Arr s a -> Arr s (Arr s a)
chopN n arr =
mkArr (\o -> (mkArr (\i -> arr ! ((o * (fromIntegral n)) + i)) n)) (fromIntegral m)
where
m = (len arr) `div` n
nParts :: Int -> Arr s a -> Arr s (Arr s a)
nParts n arr = mkArr (\o -> (mkArr (\i -> arr ! (((fromIntegral m) * o) + i)) m)) (fromIntegral n)
where
m = (len arr) `div` n
unChop :: Arr s (Arr s a) -> Arr s a
unChop arr = mkArr (\ix -> let x = ix `modi` fromIntegral w
y = ix `divi` fromIntegral w
in (arr ! y) ! x) newLen
where
h = len arr
w = len (arr ! 0)
newLen = h * w
--------------------------------------------------------------------------------
rev :: Arr s a -> Arr s a
rev arr = mkArr ixf n
where
ixf ix = arr ! (fromIntegral (n-1) - ix)
n = len arr
--------------------------------------------------------------------------------
split :: Int -> Arr s a -> (Arr s a,Arr s a)
split m arr =
let n = len arr
h1 = mkArr (\ix -> arr ! ix) m
h2 = mkArr (\ix -> arr ! (ix + (fromIntegral m))) (n-m)
in (h1,h2)
halve :: Arr s a -> (Arr s a,Arr s a)
halve arr = split (len arr `div` 2) arr
conc :: Choice a => (Arr s a, Arr s a) -> Arr s a
conc (arr1,arr2) =
let (n,n') = (len arr1,len arr2)
in mkArr (\ix -> ifThenElse (ix <* fromIntegral n)
(arr1 ! ix)
(arr2 ! (ix - fromIntegral n))) (n+n')
{-
oeSplit. Odd Even Split. used to create
a more general riffle
-}
oeSplit :: Arr s a -> (Arr s a, Arr s a)
oeSplit arr =
let n = len arr
nhalf = div n 2
in (mkArray (\ix -> arr ! (2 * ix)) (n - nhalf),
mkArray (\ix -> arr ! ((2 * ix) + 1)) nhalf)
{-
shuffle, (use with caution)
-}
shuffle :: Choice a => (Arr s a, Arr s a) -> (Arr s a)
shuffle (arr1,arr2) =
let (n1,n2) = (len arr1,len arr2)
in (mkArray (\ix -> ifThenElse ((modi ix 2) ==* 0)
(arr1 ! (divi ix 2))
(arr2 ! (divi (ix - 1) 2)))
(n1 + n2))
--------------------------------------------------------------------------------
evens :: Choice a => ((a,a) -> (a,a)) -> Arr s a -> Arr s a
evens f arr =
let n = len arr
in mkArr (\ix -> ifThenElse ((modi ix 2) ==* 0)
(ifThenElse ((ix + 1) <* (fromIntegral n))
(fst (f (arr ! ix,arr ! (ix + 1))))
(arr ! ix))
(ifThenElse (ix <* (fromIntegral n))
(snd (f (arr ! (ix - 1),arr ! ix)))
(arr ! ix))) n
odds f arr = let (a1,a2) = split 1 arr
in conc (a1,evens f a2)
--------------------------------------------------------------------------------
{-
pair :: Arr s a -> Arr (a,a)
pair arr | odd (len arr) = error "Pair: Odd n"
| otherwise = mkArr (\ix -> (arr ! (ix * 2),
arr ! ((ix * 2) + 1))) nhalf
where
n = len arr
nhalf = div n 2
-}
pair :: Arr s a -> Arr s (a,a)
pair arr | odd (len arr) = error "Pair: Odd n"
| otherwise = mkArr (\ix -> (arr ! (ix * 2),
arr ! ((ix * 2 ) + 1))) nhalf
where
n = len arr
nhalf = div n 2
{-
unpair :: Choice a => Arr (a,a) -> Arr s a
unpair arr =
let n = len arr
in mkArr (\ix -> ifThenElse ((mod ix 2) ==* 0)
(fst (arr ! (div ix 2)))
(snd (arr ! (div (ix-1) 2)))) (2*n)
-}
unpair :: Choice a => Arr s (a,a) -> Arr s a
unpair arr =
let n = len arr
in mkArr (\ix -> ifThenElse ((modi ix 2) ==* 0)
(fst (arr ! (divi ix 2)))
(snd (arr ! (divi ix 2)))) (2*n)
pairwise :: Functor (Arr s) => (a -> a -> b) -> Arr s a -> Arr s b
pairwise f = fmap (uncurry f) . pair
--------------------------------------------------------------------------------
zipp :: (Arr s a, Arr s b) -> Arr s (a,b)
zipp (arr1,arr2) = mkArr (\ix -> (arr1 ! ix,arr2 ! ix)) n
where n = min (len arr1) (len arr2)
unzipp :: Arr s (a,b) -> (Arr s a, Arr s b)
unzipp arr = (mkArr (\ix -> fst (arr ! ix)) n,
mkArr (\ix -> snd (arr ! ix)) n)
where n = len arr
--------------------------------------------------------------------------------
evens2 :: Choice a => ((a,a) -> (a,a)) -> Arr s a -> Arr s a
evens2 f arr =
let n = len arr
in mkArr (\ix -> ifThenElse ((ix `modi` 2) ==* 0)
(fst (f (arr ! ix,arr ! (ix + 1))))
(snd (f (arr ! (ix - 1),arr ! ix)))) n
odds2 :: Choice a => ((a,a) -> (a,a)) -> Arr s a -> Arr s a
odds2 f arr =
let n = len arr
in mkArr (\ix -> ifThenElse (((ix - 1) `modi` 2) ==* 0)
(fst (f (arr ! ix,arr ! (ix + 1))))
(snd (f (arr ! (ix - 1),arr ! ix)))) n
endS :: Int -> Arr s a -> Arr s a
endS n arr = mkArr (\ix -> arr ! (ix + (fromIntegral n)) ) nl
where l = len arr
nl = l - n
gz :: [Arr s a] -> (Arr s [a])
gz xs =
let n1 = len (head xs) -- deal with different lenghts !
in mkArr (\ix -> map (! ix) xs) n1
--gz = undefined
guz :: Arr s [a] -> [Arr s a]
guz arr =
let n = len arr
m = length (arr ! (E (LitInt 0)))
in [mkArr (\ix -> (arr ! ix) !! i) n | i <- [0..(m-1)]]
|
svenssonjoel/MonadObsidian
|
Obsidian/MonadObsidian/PureAPI.hs
|
Haskell
|
bsd-3-clause
| 7,686
|
-- |
-- Module: Control.Proxy.ByteString.List
-- Copyright: (c) 2013 Ertugrul Soeylemez
-- License: BSD3
-- Maintainer: Ertugrul Soeylemez <es@ertes.de>
module Control.Proxy.ByteString.List
( -- * Basic operations
fromLazyS,
unfoldrS,
unpackD,
-- * Substreams
dropD,
dropWhileD,
takeD,
takeWhileD
)
where
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as Bl
import Control.Proxy hiding (dropD, dropWhileD, takeWhileD)
import Data.ByteString (ByteString)
import Data.Word
-- | Equivalent to 'B.drop'.
dropD ::
(Monad m, Proxy p)
=> Int -- ^ Number of initial bytes to drop.
-> () -> Pipe p ByteString ByteString m r
dropD n = runIdentityK (loop n >=> idT)
where
loop n =
request >=> \bs ->
let len = B.length bs in
if len < n
then loop (n - len) ()
else respond (B.drop n bs)
-- | Equivalent to 'B.dropWhile'.
dropWhileD ::
(Monad m, Proxy p)
=> (Word8 -> Bool) -- ^ Drop bytes while this predicate is true.
-> () -> Pipe p ByteString ByteString m r
dropWhileD p = runIdentityK (loop >=> idT)
where
loop =
request >=> \bs ->
let sfx = B.dropWhile p bs in
if B.null sfx
then loop ()
else respond sfx
-- | Turn the given lazy 'ByteString' into a stream of its strict
-- chunks.
fromLazyS :: (Monad m, Proxy p) => Bl.ByteString -> () -> Producer p ByteString m ()
fromLazyS = fromListS . Bl.toChunks
-- | Equivalent of 'B.take'.
takeD ::
(Monad m, Proxy p)
=> Int -- ^ Number of bytes to take.
-> () -> Pipe p ByteString ByteString m ()
takeD = runIdentityK . loop
where
loop n =
request >=> \bs ->
let len = B.length bs in
if len < n
then respond bs >>= loop (n - len)
else respond (B.take n bs)
-- | Equivalent to 'B.takeWhile'.
takeWhileD ::
(Monad m, Proxy p)
=> (Word8 -> Bool) -- ^ Take bytes while this predicate is true.
-> () -> Pipe p ByteString ByteString m ()
takeWhileD p = runIdentityK loop
where
loop =
request >=> \bs ->
let (pfx, sfx) = B.span p bs in
if B.null sfx
then respond pfx >>= loop
else respond pfx
-- | Equivalent of 'B.unfoldr'. Generate a 'ByteString' stream using
-- the given generator function. Notice that the first argument is only
-- the chunk size, not the maximum size.
unfoldrS ::
(Monad m, Proxy p)
=> Int -- ^ Chunk size.
-> (a -> Maybe (Word8, a)) -- ^ Generator function.
-> a -- ^ Seed.
-> () -> Producer p ByteString m ()
unfoldrS n f = runIdentityK . loop
where
loop x =
let (bs, my) = B.unfoldrN n f x in
const (respond bs) >=>
maybe return loop my
-- | Unpack a stream of 'ByteString's into individual bytes.
unpackD :: (Monad m, Proxy p) => () -> Pipe p ByteString Word8 m r
unpackD = runIdentityK (foreverK $ request >=> mapM_ respond . B.unpack)
|
ertes/pipes-bytestring
|
Control/Proxy/ByteString/List.hs
|
Haskell
|
bsd-3-clause
| 3,137
|
{- |
Maintainer : simons@cryp.to
Stability : experimental
Portability : portable
The preferred method for rendering a 'Document' or single 'Content'
is by using the pretty printing facility defined in "Pretty".
Pretty-printing does not work well for cases, however, where the
formatting in the XML document is significant. Examples of this
case are XHTML's @\<pre\>@ tag, Docbook's @\<literallayout\>@ tag,
and many more.
Theoretically, the document author could avoid this problem by
wrapping the contents of these tags in a \<![CDATA[...]]\> section,
but often this is not practical, for instance when the
literal-layout section contains other elements. Finally, program
writers could manually format these elements by transforming them
into a 'literal' string in their 'CFliter', etc., but this is
annoying to do and prone to omissions and formatting errors.
As an alternative, this module provides the function 'verbatim',
which will format XML 'Content' as a 'String' while retaining the
formatting of the input document unchanged.
/Know problems/:
* HaXml's parser eats line feeds between two tags.
* 'Attribute's should be formatted by making them an instance of
'Verbatim' as well, but since an 'Attribute' is just a tuple,
not a full data type, the helper function 'verbAttr' must be
used instead.
* 'CMisc' is not yet supported.
* 'Element's, which contain no content, are formatted as
@\<element-name\/\>@, even if they were not defined as being of
type @EMPTY@. In XML this perfectly alright, but in SGML it is
not. Those, who wish to use 'verbatim' to format parts of say
an HTML page will have to (a) replace problematic elements by
'literal's /before/ running 'verbatim' or (b) use a second
search-and-replace stage to fix this.
-}
module Text.XML.HaXml.Verbatim where
import Text.XML.HaXml.Types
-- |This class promises that the function 'verbatim' knows how to
-- format this data type into a string without changing the
-- formatting.
class Verbatim a where
verbatim :: a -> String
instance (Verbatim a) => Verbatim [a] where
verbatim = concat . (map verbatim)
instance Verbatim Char where
verbatim c = [c]
instance (Verbatim a, Verbatim b) => Verbatim (Either a b) where
verbatim (Left v) = verbatim v
verbatim (Right v) = verbatim v
instance Verbatim (Content i) where
verbatim (CElem c _) = verbatim c
verbatim (CString _ c _) = c
verbatim (CRef c _) = verbatim c
verbatim (CMisc _ _) = error "NYI: verbatim not defined for CMisc"
instance Verbatim (Element i) where
verbatim (Elem nam att []) = "<" ++ nam ++ (concat . (map verbAttr)) att
++ "/>"
verbatim (Elem nam att cont) = "<" ++ nam ++ (concat . (map verbAttr)) att
++ ">" ++ verbatim cont ++ "</" ++ nam ++ ">"
instance Verbatim Reference where
verbatim (RefEntity r) = "&" ++ verbatim r ++ ";"
verbatim (RefChar c) = "&#" ++ show c ++ ";"
-- |This is a helper function is required because Haskell does not
-- allow to make an ordinary tuple (like 'Attribute') an instance of a
-- class. The resulting output will preface the actual attribute with
-- a single blank so that lists of 'Attribute's can be handled
-- implicitly by the definition for lists of 'Verbatim' data types.
verbAttr :: Attribute -> String
verbAttr (n, AttValue v) = " " ++ n ++ "=\"" ++ verbatim v ++ "\""
|
FranklinChen/hugs98-plus-Sep2006
|
packages/HaXml/src/Text/XML/HaXml/Verbatim.hs
|
Haskell
|
bsd-3-clause
| 3,563
|
module ReadPNG where
import Data.Array.Repa.IO.DevIL
import Data.Array.Repa as R
import Data.Array.Repa.Repr.ForeignPtr
import Data.Array.Accelerate.IO
import Data.Array.Accelerate as A
import Data.Array.Accelerate.Interpreter
import Control.Monad
import ReadDist
import Codec.BMP
import System.Environment
exec = do
(filename:_) <- getArgs
(testRead filename) >>= putStrLn
testRead :: String -> IO String
testRead filename = (liftM show) $ readImage' filename
trim :: A.Array A.DIM3 Word8 -> A.Array A.DIM2 Word8
trim im = run $ A.slice (use im) (lift (A.Z A.:. A.All A.:. A.All A.:. (0::Int)))
readImage' :: FilePath -> IO (A.Array A.DIM2 Word8)
readImage' = (liftM fromRepa) . (flip (>>=) copyP) . (liftM strip) . runIL . readImage
strip :: Image -> (R.Array F R.DIM2 Word8)
strip (Grey x) = x
strip _ = error "Image corrupted. Did you use Matrixbmp to generate it?"
|
vmchale/EMD
|
src/ReadPNG.hs
|
Haskell
|
bsd-3-clause
| 884
|
-- | Basebull library module
module Basebull where
import qualified Data.Foldable as F
import qualified Data.ByteString.Lazy as BL
import Data.Csv.Streaming
-- a simple type alias for data
type BaseballStats = (BL.ByteString, Int, BL.ByteString, Int)
fourth :: (a, b, c, d) -> d
fourth (_, _, _, d) = d
baseballStats ::BL.ByteString -> Records BaseballStats
baseballStats = decode NoHeader
summer :: (a, b, c, Int) -> Int -> Int
summer = (+). fourth
-- FilePath is just an alias for String
getAtBatsSum :: FilePath -> IO Int
getAtBatsSum battingCsv = do
csvData <- BL.readFile battingCsv
return $ F.foldr summer 0 (baseballStats csvData)
|
emaphis/Haskell-Practice
|
basebull/src/Basebull.hs
|
Haskell
|
bsd-3-clause
| 653
|
module Backend.InterpreterSpec where
import Test.Hspec
import qualified Data.Map as Map
import Frontend.Parser
import Backend.Interpreter
testEnv = Map.fromList [("x", Int 1), ("y", Int 2)]
spec :: Spec
spec =
describe "eval" $ do
it "evaluates ints" $
eval (Int 1) testEnv `shouldBe` 1
it "evaluates variables" $
eval (Var "x") testEnv `shouldBe` 1
it "evaluates binary arithmetic operations" $ do
eval (Add (Int 1) (Int 2)) testEnv `shouldBe` 3
eval (Sub (Int 4) (Int 3)) testEnv `shouldBe` 1
eval (Mul (Int 3) (Int 2)) testEnv `shouldBe` 6
eval (Div (Int 4) (Int 2)) testEnv `shouldBe` 2
eval (Neg (Int 3)) testEnv `shouldBe` -3
|
JCGrant/JLang
|
test/Backend/InterpreterSpec.hs
|
Haskell
|
bsd-3-clause
| 690
|
{-# LANGUAGE MagicHash,UnboxedTuples #-}
module Data.Util.Size
( unsafeSizeof
, strictUnsafeSizeof
)where
import GHC.Exts
import Foreign
unsafeSizeof :: a -> Int
unsafeSizeof a =
case unpackClosure# a of
(# x, ptrs, nptrs #) ->
sizeOf header +
I# (sizeofByteArray# (unsafeCoerce# ptrs) +#
sizeofByteArray# nptrs)
where
header :: Int
header = undefined
strictUnsafeSizeof :: a -> Int
strictUnsafeSizeof = (unsafeSizeof $!)
|
cutsea110/data-util
|
Data/Util/Size.hs
|
Haskell
|
bsd-3-clause
| 486
|
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
-- |
module VK.App.Actions (VKAction(..)
, module Exp) where
import Control.DeepSeq
import qualified Data.Text as T
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import Network.API.Builder (APIError (..))
import qualified Web.Routes.TH as WRTH
import qualified VK.API as VK
import VK.App.Actions.Types as Exp
import VK.App.Internal.Orphans ()
import VK.App.Types
data VKAction = AppInit
| SetAjaxRunning !Bool
| SetApiState !(VK.VKApp ApiState)
| Authorize !VKAction
| SetAuthState !AuthState
| Audios !AudiosAction
| Search !T.Text
| ApiError !(APIError VK.VKError)
| Refresh
deriving (Show, Typeable, Generic, NFData)
$(WRTH.derivePathInfo ''VKAction)
|
eryx67/vk-api-example
|
src/VK/App/Actions.hs
|
Haskell
|
bsd-3-clause
| 1,208
|
{-# LANGUAGE DataKinds, ExplicitForAll, FlexibleContexts, OverloadedStrings #-}
{-# LANGUAGE RecursiveDo, ScopedTypeVariables, TypeApplications #-}
{-# LANGUAGE TypeFamilies, TypeOperators #-}
{-# OPTIONS_GHC -fdefer-typed-holes #-}
module Shaped.Reflex where
import Reflex
import Reflex.Dom
import Servant.Reflex
import Data.Text
import Generics.SOP
import qualified Data.Map as Map
import Data.Monoid
import Shaped
import Data.Functor.Const
import Data.Functor.Identity
-- | A formlet is a way of constructing an input widget for only a part of the
-- form (For example, only for the user password). The two parameters that are
-- passed are a generic event to force the update of the field, and the error to
-- be displayed (as the validation is done elsewhere).
newtype Formlet t m a = Formlet
{ unFormlet :: Event t () -> Dynamic t (Maybe Text) -> m (Dynamic t a) }
-- | An endpoint is a reflex function to query an endpoint. It takes as
-- arguments the input (in the same format the servant-reflex library takes it),
-- and an event to trigger the api request. It returns an event with a nested
-- either value: the first either is to track if the communication with the
-- server has gone well, the second one to discriminate between an error value
-- for the form or a validated input.
type Endpoint t m a s = Dynamic t (Either Text a)
-> Event t ()
-> m (Event t (ReqResult (Either (s (Const (Maybe Text))) a)))
-- | This is the function that should be called to construct a form for a
-- record. It takes as input a Shaped formlet, a Shaped validation, title and
-- attributes for the button, and the endpoint to which it should address the
-- request for the server. It returns a dynamic value representing the state of
-- the form in general, but also an event tracking the server response after a
-- request. Internally, the function creates the widgets for input, runs the
-- client-side validations, controls the communication via the endpoint.
form :: ( Shaped a s , Code a ~ c, SListI2 c, c ~ '[c1]
, MonadWidget t m
, Code (s (Formlet t m)) ~ Map2 (Formlet t m) c
, Code (s (Const (Maybe Text))) ~ Map2 (Const (Maybe Text)) c
, Code (s (Either Text)) ~ Map2 (Either Text) c
, Code (s Identity) ~ Map2 Identity c
, Code (s (Validation (Either Text))) ~ Map2 (Validation (Either Text)) c
, Code (s (Event t :.: Const (Maybe Text))) ~ Map2 (Event t :.: Const (Maybe Text)) c
, Generic a
, Generic (s (Event t :.: Const (Maybe Text)))
, Generic (s (Formlet t m))
, Generic (s (Const (Maybe Text)))
, Generic (s (Either Text))
, Generic (s (Validation (Either Text)))
, Generic (s Identity))
=> s (Formlet t m)
-> s (Validation (Either Text))
-> Text -> Map.Map AttributeName Text
-> Endpoint t m a s
-> m ( Dynamic t (Either (s (Const (Maybe Text))) a)
, Event t (Either Text (Either (s (Const (Maybe Text))) a)) )
form shapedWidget clientVal buttonTitle btnConfig endpoint = mdo
postBuild <- getPostBuild
-- Here I read a tentative user from the created interface
rawUser <- createInterface send (splitShaped errorEvent) shapedWidget
-- Here I define the button. This could probably be mixed with the button code
send <- (formButton buttonTitle btnConfig) send (() <$ serverResponse)
-- This part does the server request and parses back the response without
-- depending on the types in servant-reflex
serverResponse <- let query = either (const $ Left "Please fill correctly the fields above") Right <$> validationResult
in (fmap . fmap) parseReqResult (endpoint query send)
let
-- Validation result is the rawUser ran through the validation
validationResult = transfGen . flip validateRecord clientVal <$> rawUser
validationErrorComponent = either id (const nullError) <$> validationResult
-- Error event is the sum of the event from the form and that of the server
errorEvent = leftmost [ updated validationErrorComponent
, tagPromptlyDyn validationErrorComponent postBuild
, formErrorFromServer ]
-- Here we retrieve only the error from the server events
formErrorFromServer = fst . fanEither . snd . fanEither $ serverResponse
-- In the end, I return both the dynamic containing the event and the raw
-- event signal from the server. Probably the type could be changed slightly here.
-- display validationResult
return (validationResult, serverResponse)
-- | This function is only concerned with the creation of the visual widget. The
-- first argument forces the error, the second argument is the event response
-- from the server with an error, the third is the formlet per se. The functions
-- return a dynamic of a (non validated) record. This is a function meant to be
-- used internally.
createInterface :: forall t m a s c c1 .
( Shaped a s, Code a ~ c, SListI2 c, c ~ '[c1]
, MonadWidget t m
, Code (s (Formlet t m)) ~ Map2 (Formlet t m) c
, Code (s (Event t :.: Const (Maybe Text))) ~ Map2 (Event t :.: Const (Maybe Text)) c
, Generic (s (Formlet t m))
, Generic (s (Event t :.: Const (Maybe Text)))
, Generic a)
=> Event t ()
-> s (Event t :.: Const (Maybe Text))
-> s (Formlet t m)
-> m (Dynamic t a)
createInterface e shapedError shapedFormlet = unComp . fmap to . hsequence $ hzipWith (subFun e) a b
where
a :: POP (Event t :.: Const (Maybe Text)) c
a = singleSOPtoPOP . fromSOPI $ from shapedError
b :: SOP (Formlet t m) c
b = fromSOPI $ from shapedFormlet
-- | This function passes the actual arguments to the formlet. It's meant to be
-- used internally in createInterface
subFun :: MonadWidget t m => Event t () -> (Event t :.: Const (Maybe Text)) a -> Formlet t m a -> (m :.: Dynamic t) a
subFun e (Comp a) (Formlet f) = Comp $ do
let eventWithoutConst = getConst <$> a
dynamicError <- holdDyn Nothing eventWithoutConst
f e dynamicError
-- | This function builds a button, which is disabled during the server requests
-- (so that the user can't repeatedly submit before the server sent the previous
-- response).
formButton :: DomBuilder t m => Text -> Map.Map AttributeName Text -> Event t () -> Event t () -> m (Event t ())
formButton buttonTitle initialAttr disable enable = divClass "form-group" $ do
(e, _) <- element "button" conf (text buttonTitle)
return (domEvent Click e)
where
conf = def & elementConfig_initialAttributes .~ initialAttr
& elementConfig_modifyAttributes .~ mergeWith (\_ b -> b)
[ const disableAttr <$> disable
, const enableAttr <$> enable ]
disableAttr = fmap Just initialAttr <> "disabled" =: Just "true"
enableAttr = fmap Just initialAttr <> "disabled" =: Nothing
-- Either move this temporary in shaped with the intent of reporting that
-- upstream, or define a synonym. Discuss this on the generics-sop tracker!
instance (Applicative f, Applicative g) => Applicative (f :.: g) where
pure x = Comp (pure (pure x))
Comp f <*> Comp x = Comp ((<*>) <$> f <*> x)
--------------------------------------------------------------------------------
-- | Parse the response from the API, to not expose the users to the types in
-- servant-reflex
parseReqResult :: ReqResult a -> Either Text a
parseReqResult (ResponseSuccess a _) = Right a
parseReqResult (ResponseFailure t _) = Left t
parseReqResult (RequestFailure s) = Left s
---------------------------------------------------------------------------------
-- I begin understanding this as belonging to a simple sum, not SOP or POP
-- | Create a blank error for a generic data type.
nullError :: forall a s c c1.
( Shaped a s, Code a ~ c, c ~ '[c1], SListI2 c
, Code (s (Const (Maybe Text))) ~ Map2 (Const (Maybe Text)) c
, Generic (s (Const (Maybe Text))))
=> s (Const (Maybe Text))
nullError = to . toSOPI
-- . id @(SOP (Const (Maybe Text)) c)
. singlePOPtoSOP
. id @(POP (Const (Maybe Text)) c)
$ hpure (Const Nothing)
|
meditans/shaped
|
src/Shaped/Reflex.hs
|
Haskell
|
bsd-3-clause
| 8,282
|
module YandexDirect.Entity
( module YandexDirect.Entity.Core
, module YandexDirect.Entity.Ad
, module YandexDirect.Entity.AdExtension
, module YandexDirect.Entity.AdGroup
, module YandexDirect.Entity.Campaign
, module YandexDirect.Entity.Dictionary
, module YandexDirect.Entity.Keyword
, module YandexDirect.Entity.SitelinksSet
) where
import YandexDirect.Entity.Core
import YandexDirect.Entity.Ad
import YandexDirect.Entity.AdExtension
import YandexDirect.Entity.AdGroup
import YandexDirect.Entity.Campaign
import YandexDirect.Entity.Dictionary
import YandexDirect.Entity.Keyword
import YandexDirect.Entity.SitelinksSet
|
effectfully/YandexDirect
|
src/YandexDirect/Entity.hs
|
Haskell
|
bsd-3-clause
| 640
|
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-orphans #-} -- In the test suite, so OK
module Main(main) where
import Safe
import Safe.Exact
import qualified Safe.Foldable as F
import Control.DeepSeq
import Control.Exception
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
import System.IO.Unsafe
import Test.QuickCheck.Test
import Test.QuickCheck hiding ((===))
---------------------------------------------------------------------
-- TESTS
main :: IO ()
main = do
-- All from the docs, so check they match
tailMay dNil === Nothing
tailMay [1,3,4] === Just [3,4]
tailDef [12] [] === [12]
tailDef [12] [1,3,4] === [3,4]
tailNote "help me" dNil `err` "Safe.tailNote [], help me"
tailNote "help me" [1,3,4] === [3,4]
tailSafe [] === dNil
tailSafe [1,3,4] === [3,4]
findJust (== 2) [d1,2,3] === 2
findJust (== 4) [d1,2,3] `err` "Safe.findJust"
F.findJust (== 2) [d1,2,3] === 2
F.findJust (== 4) [d1,2,3] `err` "Safe.Foldable.findJust"
F.findJustDef 20 (== 4) [d1,2,3] === 20
F.findJustNote "my note" (== 4) [d1,2,3] `errs` ["Safe.Foldable.findJustNote","my note"]
takeExact 3 [d1,2] `errs` ["Safe.Exact.takeExact","index=3","length=2"]
takeExact (-1) [d1,2] `errs` ["Safe.Exact.takeExact","negative","index=-1"]
takeExact 1 (takeExact 3 [d1,2]) === [1] -- test is lazy
quickCheck_ $ \(Int10 i) (List10 (xs :: [Int])) -> do
let (t,d) = splitAt i xs
let good = length t == i
let f name exact may note res =
if good then do
exact i xs === res
note "foo" i xs === res
may i xs === Just res
else do
exact i xs `err` ("Safe.Exact." ++ name ++ "Exact")
note "foo" i xs `errs` ["Safe.Exact." ++ name ++ "ExactNote","foo"]
may i xs === Nothing
f "take" takeExact takeExactMay takeExactNote t
f "drop" dropExact dropExactMay dropExactNote d
f "splitAt" splitAtExact splitAtExactMay splitAtExactNote (t, d)
return True
take 2 (zipExact [1,2,3] [1,2]) === [(1,1),(2,2)]
zipExact [d1,2,3] [d1,2] `errs` ["Safe.Exact.zipExact","first list is longer than the second"]
zipExact [d1,2] [d1,2,3] `errs` ["Safe.Exact.zipExact","second list is longer than the first"]
zipExact dNil dNil === []
predMay (minBound :: Int) === Nothing
succMay (maxBound :: Int) === Nothing
predMay ((minBound + 1) :: Int) === Just minBound
succMay ((maxBound - 1) :: Int) === Just maxBound
quickCheck_ $ \(List10 (xs :: [Int])) x -> do
let ys = maybeToList x ++ xs
let res = zip xs ys
let f name exact may note =
if isNothing x then do
exact xs ys === res
note "foo" xs ys === res
may xs ys === Just res
else do
exact xs ys `err` ("Safe.Exact." ++ name ++ "Exact")
note "foo" xs ys `errs` ["Safe.Exact." ++ name ++ "ExactNote","foo"]
may xs ys === Nothing
f "zip" zipExact zipExactMay zipExactNote
f "zipWith" (zipWithExact (,)) (zipWithExactMay (,)) (`zipWithExactNote` (,))
return True
take 2 (zip3Exact [1,2,3] [1,2,3] [1,2]) === [(1,1,1),(2,2,2)]
zip3Exact [d1,2] [d1,2,3] [d1,2,3] `errs` ["Safe.Exact.zip3Exact","first list is shorter than the others"]
zip3Exact [d1,2,3] [d1,2] [d1,2,3] `errs` ["Safe.Exact.zip3Exact","second list is shorter than the others"]
zip3Exact [d1,2,3] [d1,2,3] [d1,2] `errs` ["Safe.Exact.zip3Exact","third list is shorter than the others"]
zip3Exact dNil dNil dNil === []
quickCheck_ $ \(List10 (xs :: [Int])) x1 x2 -> do
let ys = maybeToList x1 ++ xs
let zs = maybeToList x2 ++ xs
let res = zip3 xs ys zs
let f name exact may note =
if isNothing x1 && isNothing x2 then do
exact xs ys zs === res
note "foo" xs ys zs === res
may xs ys zs === Just res
else do
exact xs ys zs `err` ("Safe.Exact." ++ name ++ "Exact")
note "foo" xs ys zs `errs` ["Safe.Exact." ++ name ++ "ExactNote","foo"]
may xs ys zs === Nothing
f "zip3" zip3Exact zip3ExactMay zip3ExactNote
f "zipWith3" (zipWith3Exact (,,)) (zipWith3ExactMay (,,)) (flip zipWith3ExactNote (,,))
return True
---------------------------------------------------------------------
-- UTILITIES
quickCheck_ prop = do
r <- quickCheckResult prop
unless (isSuccess r) $ error "Test failed"
d1 = 1 :: Double
dNil = [] :: [Double]
(===) :: (Show a, Eq a) => a -> a -> IO ()
(===) a b = when (a /= b) $ error $ "Mismatch: " ++ show a ++ " /= " ++ show b
err :: NFData a => a -> String -> IO ()
err a b = errs a [b]
errs :: NFData a => a -> [String] -> IO ()
errs a bs = do
res <- try $ evaluate $ rnf a
case res of
Right v -> error $ "Expected error, but succeeded: " ++ show bs
Left (msg :: SomeException) -> forM_ bs $ \b -> do
let s = show msg
unless (b `isInfixOf` s) $ error $ "Invalid error string, got " ++ show s ++ ", want " ++ show b
let f xs = " " ++ map (\x -> if sepChar x then ' ' else x) xs ++ " "
unless (f b `isInfixOf` f s) $ error $ "Not standalone error string, got " ++ show s ++ ", want " ++ show b
sepChar x = isSpace x || x `elem` ",;."
newtype Int10 = Int10 Int deriving Show
instance Arbitrary Int10 where
arbitrary = fmap Int10 $ choose (-3, 10)
newtype List10 a = List10 [a] deriving Show
instance Arbitrary a => Arbitrary (List10 a) where
arbitrary = do i <- choose (0, 10); fmap List10 $ vector i
instance Testable a => Testable (IO a) where
property = property . unsafePerformIO
|
ndmitchell/safe
|
Test.hs
|
Haskell
|
bsd-3-clause
| 5,953
|
module Recommendations(recommendedMoviesFor) where
import Data as Data(PersonName, title, name, rate, allItems, tryFindByName)
import Utils as Utils(tryList, reverseBy, except, groupBy)
recommendedMoviesFor :: PersonName -> (PersonName -> PersonName -> Either String Float)
-> Either String [(String, Float)]
recommendedMoviesFor pn simf = do
titles <- map title <$> tryFindByName pn allItems
otherItems <- tryList "Has not other users" $
((except title titles) . (except name [pn])) allItems
let groups = groupBy title otherItems
rates <- mapM (calculate . summarize . titleize) groups
return $ reverseBy snd rates
where
titleize items = (title $ head items, items)
summarizeItem item = do
sim <- simf pn $ name item
return (sim, rate item * sim)
summarize (title, items) = ((,) title) <$> mapM summarizeItem items
calculate (Right (title, summaries)) = Right (title, total / simSum)
where
simSum = (sum . (map fst)) summaries
total = (sum . (map snd)) summaries
|
vprokopchuk256/programming-collective-intelligence
|
src/Recommendations.hs
|
Haskell
|
bsd-3-clause
| 1,108
|
module PreludeList (
map, (++), filter, concat, concatMap, 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, mininum, zip, zip3, zipWith, zipWith3, unzip, unzip3 )
where
import PreludeBase
infixl 9 !!
infixr 5 ++
infix 4 `elem`, `notElem`
isSpace :: Char -> Bool
isSpace x = x `elem` " \t\r\n"
-- map and append
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = f x : map f xs
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)
filter :: (a -> Bool) -> [a] -> [a]
filter p [] = []
filter p (x:xs) | p x = x : filter p xs
| otherwise = filter p xs
concat :: [[a]] -> [a]
concat = foldr (++) []
concatMap :: (a -> [b]) -> [a] -> [b]
concatMap f = concat . map f
head :: [a] -> a
head (x:_) = x
head _ = error "Prelude.head: empty list"
tail :: [a] -> [a]
tail (_:xs) = xs
tail _ = error "Prelude.tail: empty list"
last :: [a] -> a
last [x] = x
last (_:xs) = last xs
last [] = error "Prelude.last: empty list"
init :: [a] -> [a]
init [x] = []
init (x:xs) = x : init xs
init [] = error "Prelude.init: empty list"
null :: [a] -> Bool
null [] = True
null _ = False
length :: [a] -> Int
length [] = 0
length (_:xs) = 1 + length xs
(!!) :: [a] -> Int -> a
xs !! n | n < 0 = error "Prelude.!!: negative index"
[] !! _ = error "Prelude.!!: empty list"
(x:_) !! 0 = x
(_:xs) !! n = xs !! (n - 1)
foldl :: (a -> b -> a) -> a -> [b] -> a
foldl f z [] = z
foldl f z (x:xs) = foldl f (f z x) xs
foldl1 :: (a -> a -> a) -> [a] -> a
foldl1 f (x:xs) = foldl f x xs
foldl1 f [] = error "Prelude.foldl1: empty list"
scanl :: (a -> b -> a) -> a -> [b] -> [a]
scanl f q xs = q : (case xs of
[] -> []
x : xs -> scanl f (f q x) xs)
scanl1 :: (a -> a -> a) -> [a] -> [a]
scanl1 f (x:xs) = scanl f x xs
scanl1 _ [] = []
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f v [] = v
foldr f v (x:xs) = f x (foldr f v xs)
foldr1 :: (a -> a -> a) -> [a] -> a
foldr1 _ [x] = x
foldr1 f (x:xs) = f x (foldr1 f xs)
foldr1 _ [] = error "Prelude.foldr1: empty list"
scanr :: (a -> b -> b) -> b -> [a] -> [b]
scanr f q0 [] = [q0]
scanr f q0 (x:xs) = f x q : qs
where
qs@(q:_) = scanr f q0 xs
scanr1 :: (a -> a -> a) -> [a] -> [a]
scanr1 f [] = []
scanr1 f [x] = [x]
scanr1 f (x:xs) = f x q : qs
where
qs@(q:_) = scanr1 f xs
iterate :: (a -> a) -> a -> [a]
iterate f x = x : iterate f (f x)
repeat :: a -> [a]
repeat x = x : repeat x
replicate :: Int -> a -> [a]
replicate n = take n . repeat
cycle :: [a] -> [a]
cycle [] = error "Prelude.cycle: empty list"
cycle xs = xs ++ cycle xs
take :: Int -> [a] -> [a]
take n _ | n <= 0 = []
take _ [] = []
take n (x:xs) = x : take (n - 1) xs
drop :: Int -> [a] -> [a]
drop n xs | n <= 0 = xs
drop _ [] = []
drop n (_:xs) = drop (n - 1) xs
splitAt :: Int -> [a] -> ([a], [a])
splitAt n xs = (take n xs, drop n xs)
takeWhile :: (a -> Bool) -> [a] -> [a]
takeWhile p [] = []
takeWhile p (x:xs)
| p x = x : takeWhile p xs
| otherwise = []
dropWhile :: (a -> Bool) -> [a] -> [a]
dropWhile p [] = []
dropWhile p (x:xs)
| p x = dropWhile p xs
| otherwise = xs
span, break :: (a -> Bool) -> [a] -> ([a], [a])
span p [] = ([],[])
span p xs@(x:xs')
| p x = (x:ys,zs)
| otherwise = ([],xs)
where (ys,zs) = span p xs'
break p = span (not . p)
lines :: String -> [String]
lines [] = []
lines s = let (l, s') = break (== '\n') s
in l : case s' of
[] -> []
(_:s'') -> lines s''
words :: String -> [String]
words s = case dropWhile isSpace s of
"" -> []
s' -> w : words s''
where
(w, s'') = break isSpace s'
unlines :: [String] -> String
unlines = concatMap (++ "\n")
unwords :: [String] -> String
unwords [] = []
unwords ws = foldr1 (\w s -> w ++ (' ':s)) ws
reverse :: [a] -> [a]
reverse = foldl (flip (:)) []
and, or :: [Bool] -> Bool
and = foldr (&&) True
or = foldr (||) False
any, all :: (a -> Bool) -> [a] -> Bool
any p = or . map p
all p = and . map p
elem, notElem :: Eq a => a -> [a] -> Bool
elem x = any (== x)
notElem x = all (/= x)
lookup :: Eq a => a -> [(a,b)] -> Maybe b
lookup key [] = Nothing
lookup key ((x,y):xs)
| x == key = Just y
| otherwise = lookup key xs
sum, product :: Num a => [a] -> a
sum = foldr (+) 0
product = foldr (*) 1
maximum, minimum :: Ord a => [a] -> a
maximum [] = error "Prelude.maximum: empty list"
maximum xs = foldr1 max xs
minimum [] = error "Prelude.minimum: empty list"
minimum xs = foldr1 min xs
zip :: [a] -> [b] -> [(a,b)]
zip = zipWith (\a b -> (a,b))
zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
zip3 = zipWith3 (\a b c -> (a,b,c))
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith f (a:as) (b:bs) = f a b : zipWith f as bs
zipWith _ _ _ = []
zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
zipWith3 f (a:as) (b:bs) (c:cs) = f a b c : zipWith3 f as bs cs
zipWith3 _ _ _ _ = []
unzip :: [(a,b)] -> ([a],[b])
unzip = foldr (\(a,b) ~(as,bs) -> (a:as, b:bs)) ([],[])
unzip3 :: [(a,b,c)] -> ([a],[b],[c])
unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as, b:bs, c:cs)) ([],[],[])
instance Eq a => Eq [a] where
[] == [] = True
(x:xs) == (y:ys) = (x == y) && (xs == ys)
_ == _ = False
sequence :: Monad m => [m a] -> m [a]
sequence ms = foldr k (return []) ms
where
k m m' = do { x <- m; xs <- m'; return (x:xs) }
sequence_ :: Monad m => [m a] -> m ()
sequence_ = foldr (>>) (return ())
mapM :: Monad m => (a -> m b) -> [a] -> m [b]
mapM f = sequence . map f
mapM_ :: Monad m => (a -> m b) -> [a] -> m ()
mapM_ f = sequence_ . map f
|
rodrigogribeiro/mptc
|
test/Data/Full/PreludeList.hs
|
Haskell
|
bsd-3-clause
| 6,265
|
#!/usr/bin/env runhaskell
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (threadDelay)
import Control.Concurrent.MVar (MVar (..), putMVar, takeMVar)
import Control.Exception (tryJust)
import Control.Monad (forever, guard)
import qualified Data.ByteString.Lazy as BS
import System.Environment (getArgs)
import System.Exit (exitFailure, exitSuccess)
import System.IO (IOMode (ReadMode),
SeekMode (AbsoluteSeek), hPutStrLn,
hSeek, openFile, stderr)
import System.IO.Error (isDoesNotExistError)
import System.Posix.Files (fileSize, getFileStatus)
-- some type aliases for readability
type FilePosition = Integer
type MicroSeconds = Int
-- TODO: Implement `tail -F` behavior -- streamLines is `tail -f`
-- |Tail a file, sending complete lines to the passed-in IO function.
-- If the file disappears, streamLines will return, and the function will be
-- called one final time with a Left.
streamLines
:: FilePath
-> FilePosition -- ^ Position in the file to start reading at. Very likely
-- you want to pass 0.
-> MicroSeconds -- ^ delay between each check of the file in microseconds
-> (Either String BS.ByteString -> IO ()) -- ^ function to be called with
-- each new complete line
-> IO ()
streamLines path sizeSoFar delay callback = go sizeSoFar
where
go sizeSoFar = do
threadDelay delay
errorOrStat <- tryJust (guard . isDoesNotExistError) $ getFileStatus path
case errorOrStat of
Left e -> callback $ Left "File does not exist"
Right stat -> do
let newSize = fromIntegral $ fileSize stat :: Integer
if newSize > sizeSoFar
then do
handle <- openFile path ReadMode
hSeek handle AbsoluteSeek sizeSoFar
newContents <- BS.hGetContents handle
let lines = BS.splitWith (==10) newContents
let startNext = newSize - (toInteger $ BS.length $ last lines)
mapM_ (callback . Right) $ init lines
go startNext
else do
go sizeSoFar
usage = "usage: tailf file"
tailCallback :: Either String BS.ByteString -> IO ()
tailCallback (Left e) = do
hPutStrLn stderr "aborting: file does not exist"
exitFailure
tailCallback (Right line) = do
BS.putStr line
BS.putStr $ BS.singleton 10
main = do
args <- getArgs
case args of
[] -> do
putStrLn usage
exitFailure
["-h"] -> do
putStrLn usage
exitSuccess
["--help"] -> do
putStrLn usage
exitSuccess
[path] -> do
streamLines path 0 1000000 tailCallback
|
radix/json-log-viewer
|
src/Messin.hs
|
Haskell
|
mit
| 2,922
|
module Text.HTML.TagSoup2.Str(module Text.StringLike) where
import Text.StringLike
data Pos str = Pos Position str
instance StringLike str => StringLike (Pos str) where
position :: Tag (Position str) -> Tag str
position = undefined
|
ndmitchell/tagsoup
|
src/Text/HTML/TagSoup2/Str.hs
|
Haskell
|
bsd-3-clause
| 239
|
-- dets.hs -- bugs from the Erlang's dets library
--
-- Copyright (c) 2017-2020 Rudy Matela.
-- Distributed under the 3-Clause BSD licence (see the file LICENSE).
--
--
-- In 2016, John Hughes wrote a paper titled:
--
-- "Experiences with QuickCheck: Testing the Hard Stuff And Staying Sane"
--
-- http://publications.lib.chalmers.se/records/fulltext/232550/local_232550.pdf
--
-- In it, among other things, he describes how he used QuviQ QuickCheck to find
-- 5 bugs in Erlang's dets library which were "open problems" at the time.
--
--
-- Fastforward to my PhD exam in 2017 (Rudy), John Hughes, one of my examiners
-- challenged me to use LeanCheck to try to find one of the bugs of Erlang's
-- dets library which he thought would be unreachable by LeanCheck.
--
-- Unreachable above means appearing too late in the enumeration to be able
-- to practially reach it.
--
-- Turns out Hughes was right, LeanCheck runs out of memory before reaching the
-- bug.
--
--
-- This is a reconstruction of the program written during my PhD exam
-- (2017-11-24).
--
-- This program does not really test the dets library directly, but merely
-- pattern matches the bug. So the dummy property under test returns False for
-- the specific bug we're looking for.
--
--
-- This version seaches for the 5 bugs found by QuickCheck described in Hughes'
-- paper. It is able to find 2 of these 5. We run out of memory before being
-- able to reach the other 3.
--
-- By cheating a bit, we can increase bugs found to 3,
-- but 2 are then still out of reach.
--
--
-- Dets library online manual: http://erlang.org/doc/man/dets.html
import Test.LeanCheck
-- For simplicity, we only stick ourselves with 3 different possible database
-- names
data Name = A | B | C
deriving (Eq, Ord, Show, Read)
type Key = Int
type Value = Int
type Object = (Key, Value)
-- The most important operations in Erlang's dets.
data Op = All -- all() -> [tab_name()]
| Close Name -- close(Name)
| Delete Name Key -- delete(Name, Key)
| DeleteAllObjects Name -- delete_all_objects(Name)
-- | First Name -- first(Name) -> Key
| Insert Name [Object] -- insert(Name, Objects)
| InsertNew Name [Object] -- insert_new(Name, Objects) -> boolean()
| Lookup Name Key -- lookup(Name, Key) -> Objects
| Member Name Key -- member(Name, Key) -> boolean()
-- | Next Name Key -- next(Name, Key) -> boolean()
| Open Name -- open_file(...)
| GetContents Name -- get_contents(Name) -> Objects
deriving (Eq, Ord, Show, Read)
-- NOTE: I couldn't find get_contents on the dets documentation, but it is listed on Hughes paper
-- as one of the operations. Perhaps he implemented it using first and next.
-- NOTE (2): I am admittedly cheating a bit
-- by ommiting First and Next in
-- place of GetContents.
-- A Program has a prefix and a parallel section that follows immediately
data Program = Program [Op] [[Op]]
deriving (Eq, Ord, Show, Read)
instance Listable Name where list = [A, B, C]
-- This is an unoptimized generator as it will generate invalid programs like:
--
-- Program [Close A, Lookup B 0] []
instance Listable Op where
tiers = cons0 All
\/ cons1 Close
\/ cons2 Delete
\/ cons1 DeleteAllObjects
-- \/ cons1 First
\/ cons2 Insert
\/ cons2 InsertNew
\/ cons2 Lookup
\/ cons2 Member
-- \/ cons2 Next
\/ cons1 Open
\/ cons1 GetContents
instance Listable Program where
tiers = cons2 Program
-- open(a)
-- -------------|-----------------
-- insert(a,[]) | insert_new(a,[])
bug1 :: Program
bug1 = Program
[Open A] -- initialization
[ [Insert A []] -- thread 1
, [InsertNew A []] -- thread 2
]
-- open(a)
-- ----------------|---------------------
-- insert(a,{0,0}) | insert_new(a,{0,0})
bug2 :: Program
bug2 = Program
[Open A]
[ [Insert A [(0,0)]]
, [InsertNew A [(0,0)]]
]
-- open(a)
-- --------|----------------
-- open(a) | insert(a,{0,0})
-- | get_contents(a)
bug3 :: Program
bug3 = Program
[Open A]
[ [Open A]
, [ Insert A [(0,0)]
, GetContents A
]
]
-- This was the one John Hughes originally
-- challenged me to find using LeanCheck
-- after my PhD examination. (Rudy, 2017)
bug4 :: Program
bug4 = Program
[ Open A
, Close A
, Open A
]
[ [Lookup A 0]
, [Insert A [(0,0)]]
, [Insert A [(0,0)]]
]
bug5 :: Program
bug5 = Program
[ Open A
, Insert A [(1,0)]
]
[ [ Lookup A 0
, Delete A 1
]
, [Open A]
]
prop1, prop2, prop3, prop4, prop5 :: Program -> Bool
prop1 p = p /= bug1
prop2 p = p /= bug2
prop3 p = p /= bug3
prop4 p = p /= bug4
prop5 p = p /= bug5
main :: IO ()
main = do
checkFor 200000 prop1 -- bug found after 88 410 tests
checkFor 4000000 prop2 -- bug found after 2 044 950 tests
checkFor 2000000 prop3 -- bug not found, more tests and we go out of memory...
checkFor 2000000 prop4 -- bug not found, more tests and we go out of memory...
checkFor 2000000 prop5 -- bug not found, more tests and we go out of memory...
-- If I recall correcly, John Hughes mentioned that each test took 3 seconds to
-- run. That means LeanCheck would find the first bug after 3 days, and the
-- second bug after 2 months. This could be improved if we cheat by removing
-- some of the uneeded operations in our Program datatype.
--
-- 1. Supposing we drop the "All" and "DeleteAllObjects" operation:
--
-- * bug 1 is found after 18 580 tests
-- * bug 3 is found after 300 104 tests
-- * bug 3 is found after 1 204 421 tests
-- * bugs 4 and 5 are not found
--
-- 2. Supposing we just allow a single database name "A"
--
-- * bug 1 is found after 10 651 tests
-- * bug 3 is found after 144 852 tests
-- * bug 3 is found after 534 550 tests
-- * bugs 4 and 5 are not found
--
-- Other improvements are possible:
--
-- * generating a set of parallel programs instead of a list as the order does
-- not matter (we would have to change the Program comparison function
-- accordingly)
--
-- * only generating valid programs (we only operate on A after open'ing it)
--
-- * generating a set of operations, then from that generate a set of programs
-- with these operations
--
-- But I conjecture bugs 4 and 5 will be simply out of reach anyway.
|
rudymatela/llcheck
|
bench/dets.hs
|
Haskell
|
bsd-3-clause
| 6,570
|
-- |Binary instances for images. Currently it only supports the type
-- `Image Grayscale D32`.
{-#LANGUAGE ScopedTypeVariables, FlexibleInstances#-}
module CV.Binary where
import CV.Image (Image,GrayScale,D32)
import CV.Conversions
import Data.Maybe (fromJust)
import Data.Binary
import Data.Array.CArray
import Data.Array.IArray
-- NOTE: This binary instance is NOT PORTABLE.
instance Binary (Image GrayScale D32) where
put img = do
let arr :: CArray (Int,Int) Double = copyImageToCArray img
put (bounds arr)
put . unsafeCArrayToByteString $ arr
get = do
bds <- get
get >>= return . copyCArrayToImage . fromJust . unsafeByteStringToCArray bds
|
BeautifulDestinations/CV
|
CV/Binary.hs
|
Haskell
|
bsd-3-clause
| 726
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
module Main (main) where
import Control.Monad (join)
import Control.Monad.Reader (ReaderT(..))
import Control.Concurrent.STM (STM, atomically)
import Data.Kind (Type)
class Monad (Transaction m) => MonadPersist m where
type Transaction m :: Type -> Type
atomicTransaction :: Transaction m y -> m y
instance MonadPersist (ReaderT () IO) where
type Transaction (ReaderT () IO) = ReaderT () STM
atomicTransaction act = ReaderT (atomically . runReaderT act)
main :: IO ()
main = join (runReaderT doPure2 ()) >>= \x -> seq x (return ())
doPure2 :: MonadPersist m => m (IO ())
doPure2 = atomicTransaction $ do
() <- pure ()
() <- pure ()
error "exit never happens"
|
sdiehl/ghc
|
testsuite/tests/simplCore/should_run/T16066.hs
|
Haskell
|
bsd-3-clause
| 778
|
{-# LANGUAGE FlexibleInstances #-}
--
-- 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.
--
module Thrift.Transport.HttpClient
( module Thrift.Transport
, HttpClient (..)
, openHttpClient
) where
import Thrift.Transport
import Thrift.Transport.IOBuffer
import Network.URI
import Network.HTTP hiding (port, host)
import Data.Maybe (fromJust)
import Data.Monoid (mempty)
import Control.Exception (throw)
import qualified Data.ByteString.Lazy as LBS
-- | 'HttpClient', or THttpClient implements the Thrift Transport
-- | Layer over http or https.
data HttpClient =
HttpClient {
hstream :: HandleStream LBS.ByteString,
uri :: URI,
writeBuffer :: WriteBuffer,
readBuffer :: ReadBuffer
}
uriAuth :: URI -> URIAuth
uriAuth = fromJust . uriAuthority
host :: URI -> String
host = uriRegName . uriAuth
port :: URI -> Int
port uri_ =
if portStr == mempty then
httpPort
else
read portStr
where
portStr = dropWhile (== ':') $ uriPort $ uriAuth uri_
httpPort = 80
-- | Use 'openHttpClient' to create an HttpClient connected to @uri@
openHttpClient :: URI -> IO HttpClient
openHttpClient uri_ = do
stream <- openTCPConnection (host uri_) (port uri_)
wbuf <- newWriteBuffer
rbuf <- newReadBuffer
return $ HttpClient stream uri_ wbuf rbuf
instance Transport HttpClient where
tClose = close . hstream
tPeek = peekBuf . readBuffer
tRead = readBuf . readBuffer
tWrite = writeBuf . writeBuffer
tFlush hclient = do
body <- flushBuf $ writeBuffer hclient
let request = Request {
rqURI = uri hclient,
rqHeaders = [
mkHeader HdrContentType "application/x-thrift",
mkHeader HdrContentLength $ show $ LBS.length body],
rqMethod = POST,
rqBody = body
}
res <- sendHTTP (hstream hclient) request
case res of
Right response ->
fillBuf (readBuffer hclient) (rspBody response)
Left _ ->
throw $ TransportExn "THttpConnection: HTTP failure from server" TE_UNKNOWN
return ()
tIsOpen _ = return True
|
jcgruenhage/dendrite
|
vendor/src/github.com/apache/thrift/lib/hs/src/Thrift/Transport/HttpClient.hs
|
Haskell
|
apache-2.0
| 2,967
|
-- -------------------------------------------------------------------------------------
-- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
-- For email, run on linux (perl v5.8.5):
-- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
-- -------------------------------------------------------------------------------------
import Data.List
main :: IO ()
main = do
ip <- getContents
let ts = map read . words . last . lines $ ip
ans = snd . foldl' (\a@(freeTill, spent) wt ->
if wt <= freeTill then (freeTill, spent) else (wt + 4, spent + 1) )
(-1, 0) $ sort ts
putStrLn $ show ans
|
cbrghostrider/Hacking
|
HackerRank/Algorithms/Greedy/priyankaAndToys.hs
|
Haskell
|
mit
| 739
|
-- | Helper functions for template Haskell, to avoid stage restrictions.
module Strive.Internal.TH
( options
, makeLenses
) where
import Data.Aeson.TH (Options, defaultOptions, fieldLabelModifier)
import Data.Char (isUpper, toLower, toUpper)
import Data.Maybe (isJust)
import qualified Language.Haskell.TH as TH
import qualified Language.Haskell.TH.Syntax as TH
-- | Default FromJSON options.
options :: Options
options = defaultOptions
{ fieldLabelModifier = underscore . dropPrefix
}
underscore :: String -> String
underscore = concatMap go
where
go c = if isUpper c
then ['_', toLower c]
else [c]
dropPrefix :: String -> String
dropPrefix = drop 1 . dropWhile (/= '_')
-- | Generate lens classes and instances for a type.
makeLenses :: String -> TH.Q [TH.Dec]
makeLenses string = do
maybeName <- TH.lookupTypeName string
case maybeName of
Just name -> do
info <- TH.reify name
case info of
TH.TyConI (TH.DataD _ _ _ _ [TH.RecC _ triples] _) -> do
classes <- makeLensClasses triples
instances <- makeLensInstances name triples
return (classes ++ instances)
_ -> fail "reify failed"
_ -> fail "lookupTypeName failed"
makeLensClasses :: [TH.VarStrictType] -> TH.Q [TH.Dec]
makeLensClasses [] = return []
makeLensClasses (triple : triples) = do
exists <- lensExists triple
if exists
then makeLensClasses triples
else do
klass <- makeLensClass triple
classes <- makeLensClasses triples
return (klass : classes)
makeLensClass :: TH.VarStrictType -> TH.Q TH.Dec
makeLensClass triple = do
exists <- lensExists triple
if exists
then fail "lens already exists"
else do
a <- TH.newName "a"
b <- TH.newName "b"
let klass = TH.ClassD [] name types dependencies declarations
name = TH.mkName (getLensName triple)
types = [TH.PlainTV a, TH.PlainTV b]
dependencies = [TH.FunDep [a] [b]]
declarations = [TH.SigD field typ]
field = TH.mkName (getFieldName triple)
typ = TH.AppT (TH.AppT (TH.ConT (TH.mkName "Lens")) (TH.VarT a)) (TH.VarT b)
return klass
lensExists :: TH.VarStrictType -> TH.Q Bool
lensExists triple = do
let name = getLensName triple
maybeName <- TH.lookupTypeName name
return (isJust maybeName)
getLensName :: TH.VarStrictType -> String
getLensName triple = capitalize (getFieldName triple) ++ "Lens"
capitalize :: String -> String
capitalize "" = ""
capitalize (c : cs) = toUpper c : cs
getFieldName :: TH.VarStrictType -> String
getFieldName (var, _, _) = (lensName . show) var
lensName :: String -> String
lensName x = if y `elem` keywords then y ++ "_" else y
where
y = dropPrefix x
keywords = ["data", "type"]
makeLensInstances :: TH.Name -> [TH.VarStrictType] -> TH.Q [TH.Dec]
makeLensInstances name triples = mapM (makeLensInstance name) triples
makeLensInstance :: TH.Name -> TH.VarStrictType -> TH.Q TH.Dec
makeLensInstance name triple@(var, _, typ) = do
f <- TH.newName "f"
x <- TH.newName "x"
a <- TH.newName "a"
Just fmap' <- TH.lookupValueName "fmap"
let field = TH.mkName (getFieldName triple)
return $ TH.InstanceD
Nothing
[]
(TH.AppT (TH.AppT (TH.ConT (TH.mkName (getLensName triple))) (TH.ConT name)) typ)
[TH.FunD field [TH.Clause [TH.VarP f, TH.VarP x] (TH.NormalB (TH.AppE (TH.AppE (TH.VarE fmap') (TH.LamE [TH.VarP a] (TH.RecUpdE (TH.VarE x) [(var, TH.VarE a)]))) (TH.AppE (TH.VarE f) (TH.AppE (TH.VarE var) (TH.VarE x))))) []]]
|
liskin/strive
|
library/Strive/Internal/TH.hs
|
Haskell
|
mit
| 3,523
|
{-# htermination foldM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a #-}
import Monad
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Monad_foldM_2.hs
|
Haskell
|
mit
| 90
|
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module with consumer properties types and functions.
-----------------------------------------------------------------------------
module Kafka.Consumer.ConsumerProperties
( ConsumerProperties(..)
, CallbackPollMode(..)
, brokersList
, autoCommit
, noAutoCommit
, noAutoOffsetStore
, groupId
, clientId
, setCallback
, logLevel
, compression
, suppressDisconnectLogs
, statisticsInterval
, extraProps
, extraProp
, debugOptions
, queuedMaxMessagesKBytes
, callbackPollMode
, module X
)
where
import Control.Monad (MonadPlus (mplus))
import Data.Map (Map)
import qualified Data.Map as M
import Data.Semigroup as Sem
import Data.Text (Text)
import qualified Data.Text as Text
import Kafka.Consumer.Types (ConsumerGroupId (..))
import Kafka.Internal.Setup (KafkaConf (..), Callback(..))
import Kafka.Types (BrokerAddress (..), ClientId (..), KafkaCompressionCodec (..), KafkaDebug (..), KafkaLogLevel (..), Millis (..), kafkaCompressionCodecToText, kafkaDebugToText)
import Kafka.Consumer.Callbacks as X
-- | Whether the callback polling should be done synchronously or not.
data CallbackPollMode =
-- | You have to poll the consumer frequently to handle new messages
-- as well as rebalance and keep alive events.
-- This enables lowering the footprint and having full control over when polling
-- happens, at the cost of manually managing those events.
CallbackPollModeSync
-- | Handle polling rebalance and keep alive events for you in a background thread.
| CallbackPollModeAsync deriving (Show, Eq)
-- | Properties to create 'Kafka.Consumer.Types.KafkaConsumer'.
data ConsumerProperties = ConsumerProperties
{ cpProps :: Map Text Text
, cpLogLevel :: Maybe KafkaLogLevel
, cpCallbacks :: [Callback]
, cpCallbackPollMode :: CallbackPollMode
}
instance Sem.Semigroup ConsumerProperties where
(ConsumerProperties m1 ll1 cb1 _) <> (ConsumerProperties m2 ll2 cb2 cup2) =
ConsumerProperties (M.union m2 m1) (ll2 `mplus` ll1) (cb1 `mplus` cb2) cup2
{-# INLINE (<>) #-}
-- | /Right biased/ so we prefer newer properties over older ones.
instance Monoid ConsumerProperties where
mempty = ConsumerProperties
{ cpProps = M.empty
, cpLogLevel = Nothing
, cpCallbacks = []
, cpCallbackPollMode = CallbackPollModeAsync
}
{-# INLINE mempty #-}
mappend = (Sem.<>)
{-# INLINE mappend #-}
-- | Set the <https://kafka.apache.org/documentation/#bootstrap.servers list of brokers> to contact to connect to the Kafka cluster.
brokersList :: [BrokerAddress] -> ConsumerProperties
brokersList bs =
let bs' = Text.intercalate "," (unBrokerAddress <$> bs)
in extraProps $ M.fromList [("bootstrap.servers", bs')]
-- | Set the <https://kafka.apache.org/documentation/#auto.commit.interval.ms auto commit interval> and enables <https://kafka.apache.org/documentation/#enable.auto.commit auto commit>.
autoCommit :: Millis -> ConsumerProperties
autoCommit (Millis ms) = extraProps $
M.fromList
[ ("enable.auto.commit", "true")
, ("auto.commit.interval.ms", Text.pack $ show ms)
]
-- | Disable <https://kafka.apache.org/documentation/#enable.auto.commit auto commit> for the consumer.
noAutoCommit :: ConsumerProperties
noAutoCommit =
extraProps $ M.fromList [("enable.auto.commit", "false")]
-- | Disable auto offset store for the consumer.
--
-- See <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md enable.auto.offset.store> for more information.
noAutoOffsetStore :: ConsumerProperties
noAutoOffsetStore =
extraProps $ M.fromList [("enable.auto.offset.store", "false")]
-- | Set the consumer <https://kafka.apache.org/documentation/#group.id group id>.
groupId :: ConsumerGroupId -> ConsumerProperties
groupId (ConsumerGroupId cid) =
extraProps $ M.fromList [("group.id", cid)]
-- | Set the <https://kafka.apache.org/documentation/#client.id consumer identifier>.
clientId :: ClientId -> ConsumerProperties
clientId (ClientId cid) =
extraProps $ M.fromList [("client.id", cid)]
-- | Set the consumer callback.
--
-- For examples of use, see:
--
-- * 'errorCallback'
-- * 'logCallback'
-- * 'statsCallback'
setCallback :: Callback -> ConsumerProperties
setCallback cb = mempty { cpCallbacks = [cb] }
-- | Set the logging level.
-- Usually is used with 'debugOptions' to configure which logs are needed.
logLevel :: KafkaLogLevel -> ConsumerProperties
logLevel ll = mempty { cpLogLevel = Just ll }
-- | Set the <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md compression.codec> for the consumer.
compression :: KafkaCompressionCodec -> ConsumerProperties
compression c =
extraProps $ M.singleton "compression.codec" (kafkaCompressionCodecToText c)
-- | Suppresses consumer <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md log.connection.close>.
--
-- It might be useful to turn this off when interacting with brokers
-- with an aggressive @connection.max.idle.ms@ value.
suppressDisconnectLogs :: ConsumerProperties
suppressDisconnectLogs =
extraProps $ M.fromList [("log.connection.close", "false")]
-- | Set the <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md statistics.interval.ms> for the producer.
statisticsInterval :: Millis -> ConsumerProperties
statisticsInterval (Millis t) =
extraProps $ M.singleton "statistics.interval.ms" (Text.pack $ show t)
-- | Set any configuration options that are supported by /librdkafka/.
-- The full list can be found <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md here>
extraProps :: Map Text Text -> ConsumerProperties
extraProps m = mempty { cpProps = m }
{-# INLINE extraProps #-}
-- | Set any configuration option that is supported by /librdkafka/.
-- The full list can be found <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md here>
extraProp :: Text -> Text -> ConsumerProperties
extraProp k v = mempty { cpProps = M.singleton k v }
{-# INLINE extraProp #-}
-- | Set <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md debug> features for the consumer.
-- Usually is used with 'logLevel'.
debugOptions :: [KafkaDebug] -> ConsumerProperties
debugOptions [] = extraProps M.empty
debugOptions d =
let points = Text.intercalate "," (kafkaDebugToText <$> d)
in extraProps $ M.fromList [("debug", points)]
-- | Set <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md queued.max.messages.kbytes>
queuedMaxMessagesKBytes :: Int -> ConsumerProperties
queuedMaxMessagesKBytes kBytes =
extraProp "queued.max.messages.kbytes" (Text.pack $ show kBytes)
{-# INLINE queuedMaxMessagesKBytes #-}
-- | Set the callback poll mode. Default value is 'CallbackPollModeAsync'.
callbackPollMode :: CallbackPollMode -> ConsumerProperties
callbackPollMode mode = mempty { cpCallbackPollMode = mode }
|
haskell-works/kafka-client
|
src/Kafka/Consumer/ConsumerProperties.hs
|
Haskell
|
mit
| 7,103
|
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeFamilies #-}
--------------------------------------------------------------------
-- |
-- Copyright : © Oleg Grenrus 2014
-- License : MIT
-- Maintainer: Oleg Grenrus <oleg.grenrus@iki.fi>
-- Stability : experimental
-- Portability: non-portable
--
--------------------------------------------------------------------
module Data.Algebra.Boolean.NormalForm (
NormalForm(..),
module Data.Algebra.Boolean.CoBoolean
) where
import Data.Algebra.Boolean.CoBoolean
import Data.Algebra.Boolean.FreeBoolean
import GHC.Exts (Constraint)
-- | Class unifying different boolean normal forms.
class CoBoolean1 nf => NormalForm nf where
-- | 'NormalForm' could be constrained, so the 'Set' based implementations could be included.
type NFConstraint nf a :: Constraint
type NFConstraint nf a = ()
-- | Lift a value into normal form.
toNormalForm :: a -> nf a
-- | Simplify the formula, if some terms are ⊥ or ⊤.
simplify :: (NFConstraint nf a) => (a -> Maybe Bool) -> nf a -> nf a
-- | transform from free boolean form
fromFreeBoolean :: (NFConstraint nf a) => FreeBoolean a -> nf a
instance NormalForm FreeBoolean where
toNormalForm = FBValue
simplify _ = id
fromFreeBoolean = id
|
phadej/boolean-normal-forms
|
src/Data/Algebra/Boolean/NormalForm.hs
|
Haskell
|
mit
| 1,275
|
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE BangPatterns #-}
-- | This module provides the ability to create reapers: dedicated cleanup
-- threads. These threads will automatically spawn and die based on the
-- presence of a workload to process on. Example uses include:
--
-- * Killing long-running jobs
-- * Closing unused connections in a connection pool
-- * Pruning a cache of old items (see example below)
--
-- For real-world usage, search the <https://github.com/yesodweb/wai WAI family of packages>
-- for imports of "Control.Reaper".
module Control.Reaper (
-- * Example: Regularly cleaning a cache
-- $example1
-- * Settings
ReaperSettings
, defaultReaperSettings
-- * Accessors
, reaperAction
, reaperDelay
, reaperCons
, reaperNull
, reaperEmpty
-- * Type
, Reaper(..)
-- * Creation
, mkReaper
-- * Helper
, mkListAction
) where
import Control.AutoUpdate.Util (atomicModifyIORef')
import Control.Concurrent (forkIO, threadDelay, killThread, ThreadId)
import Control.Exception (mask_)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
-- | Settings for creating a reaper. This type has two parameters:
-- @workload@ gives the entire workload, whereas @item@ gives an
-- individual piece of the queue. A common approach is to have @workload@
-- be a list of @item@s. This is encouraged by 'defaultReaperSettings' and
-- 'mkListAction'.
--
-- @since 0.1.1
data ReaperSettings workload item = ReaperSettings
{ reaperAction :: workload -> IO (workload -> workload)
-- ^ The action to perform on a workload. The result of this is a
-- \"workload modifying\" function. In the common case of using lists,
-- the result should be a difference list that prepends the remaining
-- workload to the temporary workload. For help with setting up such
-- an action, see 'mkListAction'.
--
-- Default: do nothing with the workload, and then prepend it to the
-- temporary workload. This is incredibly useless; you should
-- definitely override this default.
--
-- @since 0.1.1
, reaperDelay :: {-# UNPACK #-} !Int
-- ^ Number of microseconds to delay between calls of 'reaperAction'.
--
-- Default: 30 seconds.
--
-- @since 0.1.1
, reaperCons :: item -> workload -> workload
-- ^ Add an item onto a workload.
--
-- Default: list consing.
--
-- @since 0.1.1
, reaperNull :: workload -> Bool
-- ^ Check if a workload is empty, in which case the worker thread
-- will shut down.
--
-- Default: 'null'.
--
-- @since 0.1.1
, reaperEmpty :: workload
-- ^ An empty workload.
--
-- Default: empty list.
--
-- @since 0.1.1
}
-- | Default @ReaperSettings@ value, biased towards having a list of work
-- items.
--
-- @since 0.1.1
defaultReaperSettings :: ReaperSettings [item] item
defaultReaperSettings = ReaperSettings
{ reaperAction = \wl -> return (wl ++)
, reaperDelay = 30000000
, reaperCons = (:)
, reaperNull = null
, reaperEmpty = []
}
-- | A data structure to hold reaper APIs.
data Reaper workload item = Reaper {
-- | Adding an item to the workload
reaperAdd :: item -> IO ()
-- | Reading workload.
, reaperRead :: IO workload
-- | Stopping the reaper thread if exists.
-- The current workload is returned.
, reaperStop :: IO workload
-- | Killing the reaper thread immediately if exists.
, reaperKill :: IO ()
}
-- | State of reaper.
data State workload = NoReaper -- ^ No reaper thread
| Workload workload -- ^ The current jobs
-- | Create a reaper addition function. This function can be used to add
-- new items to the workload. Spawning of reaper threads will be handled
-- for you automatically.
--
-- @since 0.1.1
mkReaper :: ReaperSettings workload item -> IO (Reaper workload item)
mkReaper settings@ReaperSettings{..} = do
stateRef <- newIORef NoReaper
tidRef <- newIORef Nothing
return Reaper {
reaperAdd = add settings stateRef tidRef
, reaperRead = readRef stateRef
, reaperStop = stop stateRef
, reaperKill = kill tidRef
}
where
readRef stateRef = do
mx <- readIORef stateRef
case mx of
NoReaper -> return reaperEmpty
Workload wl -> return wl
stop stateRef = atomicModifyIORef' stateRef $ \mx ->
case mx of
NoReaper -> (NoReaper, reaperEmpty)
Workload x -> (Workload reaperEmpty, x)
kill tidRef = do
mtid <- readIORef tidRef
case mtid of
Nothing -> return ()
Just tid -> killThread tid
add :: ReaperSettings workload item
-> IORef (State workload) -> IORef (Maybe ThreadId)
-> item -> IO ()
add settings@ReaperSettings{..} stateRef tidRef item =
mask_ $ do
next <- atomicModifyIORef' stateRef cons
next
where
cons NoReaper = let !wl = reaperCons item reaperEmpty
in (Workload wl, spawn settings stateRef tidRef)
cons (Workload wl) = let wl' = reaperCons item wl
in (Workload wl', return ())
spawn :: ReaperSettings workload item
-> IORef (State workload) -> IORef (Maybe ThreadId)
-> IO ()
spawn settings stateRef tidRef = do
tid <- forkIO $ reaper settings stateRef tidRef
writeIORef tidRef $ Just tid
reaper :: ReaperSettings workload item
-> IORef (State workload) -> IORef (Maybe ThreadId)
-> IO ()
reaper settings@ReaperSettings{..} stateRef tidRef = do
threadDelay reaperDelay
-- Getting the current jobs. Push an empty job to the reference.
wl <- atomicModifyIORef' stateRef swapWithEmpty
-- Do the jobs. A function to merge the left jobs and
-- new jobs is returned.
!merge <- reaperAction wl
-- Merging the left jobs and new jobs.
-- If there is no jobs, this thread finishes.
next <- atomicModifyIORef' stateRef (check merge)
next
where
swapWithEmpty NoReaper = error "Control.Reaper.reaper: unexpected NoReaper (1)"
swapWithEmpty (Workload wl) = (Workload reaperEmpty, wl)
check _ NoReaper = error "Control.Reaper.reaper: unexpected NoReaper (2)"
check merge (Workload wl)
-- If there is no job, reaper is terminated.
| reaperNull wl' = (NoReaper, writeIORef tidRef Nothing)
-- If there are jobs, carry them out.
| otherwise = (Workload wl', reaper settings stateRef tidRef)
where
wl' = merge wl
-- | A helper function for creating 'reaperAction' functions. You would
-- provide this function with a function to process a single work item and
-- return either a new work item, or @Nothing@ if the work item is
-- expired.
--
-- @since 0.1.1
mkListAction :: (item -> IO (Maybe item'))
-> [item]
-> IO ([item'] -> [item'])
mkListAction f =
go id
where
go !front [] = return front
go !front (x:xs) = do
my <- f x
let front' =
case my of
Nothing -> front
Just y -> front . (y:)
go front' xs
-- $example1
-- In this example code, we use a 'Data.Map.Strict.Map' to cache fibonacci numbers, and a 'Reaper' to prune the cache.
--
-- The @main@ function first creates a 'Reaper', with fields to initialize the
-- cache ('reaperEmpty'), add items to it ('reaperCons'), and prune it ('reaperAction').
-- The reaper will run every two seconds ('reaperDelay'), but will stop running while
-- 'reaperNull' is true.
--
-- @main@ then loops infinitely ('Control.Monad.forever'). Each second it calculates the fibonacci number
-- for a value between 30 and 34, first trying the cache ('reaperRead' and 'Data.Map.Strict.lookup'),
-- then falling back to manually calculating it (@fib@)
-- and updating the cache with the result ('reaperAdd')
--
-- @clean@ simply removes items cached for more than 10 seconds.
-- This function is where you would perform IO-related cleanup,
-- like killing threads or closing connections, if that was the purpose of your reaper.
--
-- @
-- module Main where
--
-- import "Data.Time" (UTCTime, getCurrentTime, diffUTCTime)
-- import "Control.Reaper"
-- import "Control.Concurrent" (threadDelay)
-- import "Data.Map.Strict" (Map)
-- import qualified "Data.Map.Strict" as Map
-- import "Control.Monad" (forever)
-- import "System.Random" (getStdRandom, randomR)
--
-- fib :: 'Int' -> 'Int'
-- fib 0 = 0
-- fib 1 = 1
-- fib n = fib (n-1) + fib (n-2)
--
-- type Cache = 'Data.Map.Strict.Map' 'Int' ('Int', 'Data.Time.Clock.UTCTime')
--
-- main :: IO ()
-- main = do
-- reaper <- 'mkReaper' 'defaultReaperSettings'
-- { 'reaperEmpty' = Map.'Data.Map.Strict.empty'
-- , 'reaperCons' = \\(k, v, time) workload -> Map.'Data.Map.Strict.insert' k (v, time) workload
-- , 'reaperAction' = clean
-- , 'reaperDelay' = 1000000 * 2 -- Clean every 2 seconds
-- , 'reaperNull' = Map.'Data.Map.Strict.null'
-- }
-- forever $ do
-- fibArg <- 'System.Random.getStdRandom' ('System.Random.randomR' (30,34))
-- cache <- 'reaperRead' reaper
-- let cachedResult = Map.'Data.Map.Strict.lookup' fibArg cache
-- case cachedResult of
-- 'Just' (fibResult, _createdAt) -> 'putStrLn' $ "Found in cache: `fib " ++ 'show' fibArg ++ "` " ++ 'show' fibResult
-- 'Nothing' -> do
-- let fibResult = fib fibArg
-- 'putStrLn' $ "Calculating `fib " ++ 'show' fibArg ++ "` " ++ 'show' fibResult
-- time <- 'Data.Time.Clock.getCurrentTime'
-- ('reaperAdd' reaper) (fibArg, fibResult, time)
-- 'threadDelay' 1000000 -- 1 second
--
-- -- Remove items > 10 seconds old
-- clean :: Cache -> IO (Cache -> Cache)
-- clean oldMap = do
-- currentTime <- 'Data.Time.Clock.getCurrentTime'
-- let pruned = Map.'Data.Map.Strict.filter' (\\(_, createdAt) -> currentTime \`diffUTCTime\` createdAt < 10.0) oldMap
-- return (\\newData -> Map.'Data.Map.Strict.union' pruned newData)
-- @
|
tolysz/wai
|
auto-update/Control/Reaper.hs
|
Haskell
|
mit
| 10,059
|
import Control.Applicative
import Text.Parsec
import Text.Parsec.String (Parser)
import Text.Parsec.Language (haskellStyle)
import qualified Text.Parsec.Token as Tok
data Expr = Add String String deriving Show
lexer :: Tok.TokenParser ()
lexer = Tok.makeTokenParser style
where ops = ["->","\\","+","*","-","="]
style = haskellStyle {Tok.reservedOpNames = ops }
identifier :: Parser String
identifier = Tok.identifier lexer
parseM :: Parser Expr
parseM = do
a <- identifier
char '+'
b <- identifier
return $ Add a b
parseA :: Parser Expr
parseA = Add <$> identifier <* char '+' <*> identifier
main :: IO ()
main = do
s0 <- getLine
print $ parse parseM "<stdin>" s0
s1 <- getLine
print $ parse parseA "<stdin>" s1
|
riwsky/wiwinwlh
|
src/parsec_applicative.hs
|
Haskell
|
mit
| 747
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE QuasiQuotes #-}
module Graphics.Urho3D.Resource.Cache(
ResourceCache
, resourceCacheContext
, priorityLast
, cacheAddResourceDir
, cacheGetResource
) where
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Cpp as C
import Graphics.Urho3D.Resource.Internal.Cache
import Graphics.Urho3D.Resource.Resource
import Graphics.Urho3D.Core.Object
import Graphics.Urho3D.Core.Context
import Graphics.Urho3D.Creatable
import Graphics.Urho3D.Math.StringHash
import Graphics.Urho3D.Monad
import Data.Monoid
import Data.Proxy
import Foreign
import Foreign.C.String
C.context (C.cppCtx <> resourceCacheCntx <> contextContext <> resourceContext <> objectContext)
C.include "<Urho3D/Resource/ResourceCache.h>"
C.using "namespace Urho3D"
resourceCacheContext :: C.Context
resourceCacheContext = resourceCacheCntx <> resourceContext <> objectContext
newResourceCache :: Ptr Context -> IO (Ptr ResourceCache)
newResourceCache ptr = [C.exp| ResourceCache* { new ResourceCache( $(Context* ptr) ) } |]
deleteResourceCache :: Ptr ResourceCache -> IO ()
deleteResourceCache ptr = [C.exp| void { delete $(ResourceCache* ptr) } |]
instance Creatable (Ptr ResourceCache) where
type CreationOptions (Ptr ResourceCache) = Ptr Context
newObject = liftIO . newResourceCache
deleteObject = liftIO . deleteResourceCache
instance Subsystem ResourceCache where
getSubsystemImpl ptr = [C.exp| ResourceCache* { $(Object* ptr)->GetSubsystem<ResourceCache>() } |]
-- | Default periority for resource cache
priorityLast :: Word
priorityLast = fromIntegral [C.pure| unsigned int { PRIORITY_LAST } |]
-- | Add a resource load directory. Optional priority parameter which will control search order.
cacheAddResourceDir :: forall a m ptr . (Parent ResourceCache a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to ResourceCache or acenstor
-> FilePath -- ^ Path to directory
-> Word -- ^ Priority (default is priorityLast)
-> m Bool
cacheAddResourceDir ptr pathName priority = liftIO $ withCString pathName $ \pathName' -> do
let ptr' = parentPointer ptr
priority' = fromIntegral priority
toBool <$> [C.exp| int { (int)$(ResourceCache* ptr')->AddResourceDir(String($(const char* pathName')), $(unsigned int priority')) } |]
-- | Loading a resource by name
cacheGetResource :: forall a b m ptr . (Parent ResourceCache a, Pointer ptr a, ResourceType b, MonadIO m)
=> ptr -- ^ Pointer to ResourceCache or acenstor
-> String -- ^ Resource name
-> Bool -- ^ send event on failure?
-> m (Maybe (Ptr b)) -- ^ pointer to resource
cacheGetResource ptr name sendEvent = liftIO $ withCString name $ \name' -> do
let ptr' = parentPointer ptr
rest = fromIntegral . stringHashValue $ resourceType (Proxy :: Proxy b)
sendEvent' = if sendEvent then 1 else 0
resPtr <- [C.exp| Resource* { $(ResourceCache* ptr')->GetResource(StringHash($(unsigned int rest)), String($(const char* name')), $(int sendEvent') != 0) } |]
checkNullPtr' resPtr (return.castPtr)
|
Teaspot-Studio/Urho3D-Haskell
|
src/Graphics/Urho3D/Resource/Cache.hs
|
Haskell
|
mit
| 3,048
|
module Server.Swagger where
import API
import Servant.Swagger
import Data.Swagger
import Servant
swaggerServer :: Handler Swagger
swaggerServer = return (toSwagger basicApi)
|
lierdakil/markco
|
server/src/Server/Swagger.hs
|
Haskell
|
mit
| 176
|
{-#LANGUAGE FlexibleContexts #-}
{-#LANGUAGE FlexibleInstances #-}
{-#LANGUAGE OverloadedStrings #-}
{-#LANGUAGE TupleSections #-}
{-#LANGUAGE TypeSynonymInstances #-}
{-#LANGUAGE MultiParamTypeClasses #-}
{-#LANGUAGE ScopedTypeVariables #-}
module Text.Ginger.Run.FuncUtils
where
import Prelude ( (.), ($), (==), (/=)
, (>), (<), (>=), (<=)
, (+), (-), (*), (/), div, (**), (^)
, (||), (&&)
, (++)
, Show, show
, undefined, otherwise
, Maybe (..)
, Bool (..)
, Int, Integer, String
, fromIntegral, floor, round
, not
, show
, uncurry
, seq
, fst, snd
, maybe
, Either (..)
, id
)
import qualified Prelude
import Data.Maybe (fromMaybe, isJust)
import qualified Data.List as List
import Text.Ginger.AST
import Text.Ginger.Html
import Text.Ginger.GVal
import Text.Ginger.Run.Type
import Text.Printf
import Text.PrintfA
import Data.Scientific (formatScientific)
import Data.Text (Text)
import Data.String (fromString)
import qualified Data.Text as Text
import qualified Data.ByteString.UTF8 as UTF8
import Control.Monad
import Control.Monad.Identity
import Control.Monad.Writer
import Control.Monad.Reader
import Control.Monad.State
import Control.Applicative
import qualified Data.HashMap.Strict as HashMap
import Data.HashMap.Strict (HashMap)
import Data.Scientific (Scientific)
import Data.Scientific as Scientific
import Data.Default (def)
import Safe (readMay, lastDef, headMay)
import Network.HTTP.Types (urlEncode)
import Debug.Trace (trace)
import Data.Maybe (isNothing)
import Data.List (lookup, zipWith, unzip)
unaryFunc :: forall m h p. (Monad m) => (GVal (Run p m h) -> GVal (Run p m h)) -> Function (Run p m h)
unaryFunc f [] = do
warn $ ArgumentsError Nothing "expected exactly one argument (zero given)"
return def
unaryFunc f ((_, x):[]) =
return (f x)
unaryFunc f ((_, x):_) = do
warn $ ArgumentsError Nothing "expected exactly one argument (more given)"
return (f x)
binaryFunc :: forall m h p. (Monad m) => (GVal (Run p m h) -> GVal (Run p m h) -> GVal (Run p m h)) -> Function (Run p m h)
binaryFunc f [] = do
warn $ ArgumentsError Nothing "expected exactly two arguments (zero given)"
return def
binaryFunc f (_:[]) = do
warn $ ArgumentsError Nothing "expected exactly two arguments (one given)"
return def
binaryFunc f ((_, x):(_, y):[]) =
return (f x y)
binaryFunc f ((_, x):(_, y):_) = do
warn $ ArgumentsError Nothing "expected exactly two arguments (more given)"
return (f x y)
ignoreArgNames :: ([a] -> b) -> ([(c, a)] -> b)
ignoreArgNames f args = f (Prelude.map snd args)
variadicNumericFunc :: Monad m => Scientific -> ([Scientific] -> Scientific) -> [(Maybe Text, GVal (Run p m h))] -> Run p m h (GVal (Run p m h))
variadicNumericFunc zero f args =
return . toGVal . f $ args'
where
args' :: [Scientific]
args' = Prelude.map (fromMaybe zero . asNumber . snd) args
unaryNumericFunc :: Monad m => Scientific -> (Scientific -> Scientific) -> [(Maybe Text, GVal (Run p m h))] -> Run p m h (GVal (Run p m h))
unaryNumericFunc zero f args =
return . toGVal . f $ args'
where
args' :: Scientific
args' = case args of
[] -> 0
(arg:_) -> fromMaybe zero . asNumber . snd $ arg
variadicStringFunc :: Monad m => ([Text] -> Text) -> [(Maybe Text, GVal (Run p m h))] -> Run p m h (GVal (Run p m h))
variadicStringFunc f args =
return . toGVal . f $ args'
where
args' :: [Text]
args' = Prelude.map (asText . snd) args
-- | Match args according to a given arg spec, Python style.
-- The return value is a triple of @(matched, args, kwargs, unmatchedNames)@,
-- where @matches@ is a hash map of named captured arguments, args is a list of
-- remaining unmatched positional arguments, kwargs is a list of remaining
-- unmatched named arguments, and @unmatchedNames@ contains the argument names
-- that haven't been matched.
extractArgs :: [Text] -> [(Maybe Text, a)] -> (HashMap Text a, [a], HashMap Text a, [Text])
extractArgs argNames args =
let (matchedPositional, argNames', args') = matchPositionalArgs argNames args
(matchedKeyword, argNames'', args'') = matchKeywordArgs argNames' args'
unmatchedPositional = [ a | (Nothing, a) <- args'' ]
unmatchedKeyword = HashMap.fromList [ (k, v) | (Just k, v) <- args'' ]
in ( HashMap.fromList (matchedPositional ++ matchedKeyword)
, unmatchedPositional
, unmatchedKeyword
, argNames''
)
where
matchPositionalArgs :: [Text] -> [(Maybe Text, a)] -> ([(Text, a)], [Text], [(Maybe Text, a)])
matchPositionalArgs [] args = ([], [], args)
matchPositionalArgs names [] = ([], names, [])
matchPositionalArgs names@(n:ns) allArgs@((anm, arg):args)
| Just n == anm || isNothing anm =
let (matched, ns', args') = matchPositionalArgs ns args
in ((n, arg):matched, ns', args')
| otherwise = ([], names, allArgs)
matchKeywordArgs :: [Text] -> [(Maybe Text, a)] -> ([(Text, a)], [Text], [(Maybe Text, a)])
matchKeywordArgs [] args = ([], [], args)
matchKeywordArgs names allArgs@((Nothing, arg):args) =
let (matched, ns', args') = matchKeywordArgs names args
in (matched, ns', (Nothing, arg):args')
matchKeywordArgs names@(n:ns) args =
case (lookup (Just n) args) of
Nothing ->
let (matched, ns', args') = matchKeywordArgs ns args
in (matched, n:ns', args')
Just v ->
let args' = [ (k,v) | (k,v) <- args, k /= Just n ]
(matched, ns', args'') = matchKeywordArgs ns args'
in ((n,v):matched, ns', args'')
-- | Parse argument list into type-safe argument structure.
extractArgsT :: ([Maybe a] -> b) -> [Text] -> [(Maybe Text, a)] -> Either ([a], HashMap Text a, [Text]) b
extractArgsT f argNames args =
let (matchedMap, freeArgs, freeKwargs, unmatched) = extractArgs argNames args
in if List.null freeArgs && HashMap.null freeKwargs
then Right (f $ fmap (\name -> HashMap.lookup name matchedMap) argNames)
else Left (freeArgs, freeKwargs, unmatched)
-- | Parse argument list into flat list of matched arguments.
extractArgsL :: [Text] -> [(Maybe Text, a)] -> Either ([a], HashMap Text a, [Text]) [Maybe a]
extractArgsL = extractArgsT id
extractArgsDefL :: [(Text, a)] -> [(Maybe Text, a)] -> Either ([a], HashMap Text a, [Text]) [a]
extractArgsDefL argSpec args =
let (names, defs) = unzip argSpec
in injectDefaults defs <$> extractArgsL names args
injectDefaults :: [a] -> [Maybe a] -> [a]
injectDefaults = zipWith fromMaybe
|
tdammers/ginger
|
src/Text/Ginger/Run/FuncUtils.hs
|
Haskell
|
mit
| 7,011
|
module Day3Spec (main, spec) where
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
import Test.QuickCheck.Property
import Test.QuickCheck.Modifiers
import Test.Hspec
import Day3
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "When Santa is alone" $ do
it "visits only one house for one instruction" $ do
santaHouses ">" `shouldBe` 2
it "visits houses from a file" $ do
contents <- readFile "test/input-day3.txt"
santaHouses contents `shouldBe` 2081
describe "When the Robot and Santa are working together" $ do
it "visits one house each for two diff instructions" $ do
combinedHouses "><" `shouldBe` 3
it "they visit their same houses but counts it once" $ do
combinedHouses "^vv^" `shouldBe` 3
it "they both visit the same house but counts it only once" $ do
combinedHouses "^>>^" `shouldBe` 4
it "visits 5 houses each" $ do
combinedHouses "^v^v^v^v^v" `shouldBe` 11
it "visits naughty houses" $ do
combinedHouses ">>v^" `shouldBe` 4
it "Visits houses form a file" $ do
contents <- readFile "test/input-day3.txt"
combinedHouses contents `shouldBe` 2341
|
AndrewSinclair/aoc-haskell
|
test/Day3Spec.hs
|
Haskell
|
mit
| 1,203
|
module Optimization where
import Numeric.LinearAlgebra
class Optimize a where
--optimizeInit :: a -> Double -> Double -> (Int, Int) -> a
paramUpdate :: a -> a
data SGD = SGD {
sgdLearningRate :: Double,
sgdDecay :: Double,
sgdMomentum :: Double,
sgdParams :: [Matrix R],
sgdGparams :: [Matrix R],
sgdDeltaPre :: [Matrix R],
sgdBatchSize :: Double
}
instance Optimize SGD where
paramUpdate sgd =
let learningRate = sgdLearningRate sgd in
let decay = sgdDecay sgd in
let momentum = sgdMomentum sgd in
let params = sgdParams sgd in
let gparams = sgdGparams sgd in
let deltaPre = sgdDeltaPre sgd in
let batchSize = sgdBatchSize sgd in
let _sgd (px:pxs) (gx: gxs) (dx:dxs) paUpdate deUpdate gaZeros =
let r = rows gx in
let c = cols gx in
let lrMat = (r >< c) [learningRate..]:: (Matrix R) in
let batchSizeMat = (r >< c) [batchSize..] :: (Matrix R) in
let momMat = (r >< c) [momentum..] :: (Matrix R) in
let gUp = gx * lrMat / batchSizeMat in
let ugd = momMat * dx - gx in
let pu = px + ugd in _sgd pxs gxs dxs (paUpdate++[pu]) (deUpdate++[ugd]) (gaZeros++[(r >< c) [0..]])
_sgd [] [] [] paUpdate deUpdate gaZeros = SGD {
sgdLearningRate=learningRate,
sgdDecay=decay,
sgdMomentum=momentum,
sgdParams=paUpdate,
sgdGparams=gaZeros,
sgdDeltaPre=deUpdate,
sgdBatchSize=0
} in
_sgd params gparams deltaPre [] [] []
data Adadelta = Adadelta {
adaDecay :: Double,
adaEpsilon :: Double,
adaBatchSize :: Double,
adaParams :: [Matrix R],
adaGparams :: [Matrix R],
adaAccGrad :: [Matrix R],
adaAccDelta :: [Matrix R]
}
instance Optimize Adadelta where
paramUpdate ada =
let decay = adaDecay ada in
let epsilon = adaEpsilon ada in
let batchSize = adaBatchSize ada in
let params = adaParams ada in
let gparams = adaGparams ada in
let accGrad = adaAccGrad ada in
let accDelta = adaAccDelta ada in
let _ada (px:pxs) (gx:gxs) (accgx:accgxs) (accdx:accdxs) paUpdate gradUpdate deltaUpdate gaZeros =
let r = rows px in
let c = cols px in
let decayMat = (r >< c) [decay ..] :: (Matrix R) in
let epsilonMat = (r >< c) [epsilon ..] :: (Matrix R) in
let batchSizeMat = (r >< c) [batchSize ..] :: (Matrix R) in
let oneMat = (r >< c) [1.0 ..]:: (Matrix R) in
let gUp = accgx / batchSizeMat in
let gradUp = decayMat * accgx + (oneMat - decayMat) * gUp * gUp in
let ugd = (cmap (\x -> -(sqrt x)) (accdx + epsilonMat)) / (cmap (\x -> sqrt x) (accgx + epsilonMat)) * gUp in
let deltaUp = decayMat * accdx + (oneMat - decayMat) * ugd * ugd in
let pu = px + ugd in
_ada pxs gxs accgxs accdxs (pu:paUpdate) (gradUp:gradUpdate) (deltaUp:deltaUpdate) (((r >< c)[0.0 ..]):gaZeros)
_ada [] [] [] [] paUpdate gradUpdate deltaUpdate gaZeros = Adadelta {
adaDecay=decay,
adaEpsilon=epsilon,
adaBatchSize=batchSize,
adaParams=(reverse paUpdate),
adaGparams=(reverse gaZeros),
adaAccGrad=(reverse gradUpdate),
adaAccDelta=(reverse deltaUpdate)
}
in _ada params gparams accGrad accDelta [] [] [] []
|
neutronest/vortex
|
vortex/Optimization.hs
|
Haskell
|
mit
| 3,455
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
------------------------------------------------------------------------------
-- | This module defines our application's state type and an alias for its
-- handler monad.
module Application where
------------------------------------------------------------------------------
import Control.Lens
import Snap
import Snap.Snaplet
import Snap.Snaplet.Heist
import Snap.Snaplet.Auth
import Snap.Snaplet.Session
import Snap.Snaplet.SqliteSimple
------------------------------------------------------------------------------
data App = App
{ _heist :: Snaplet (Heist App)
, _sess :: Snaplet SessionManager
, _db :: Snaplet Sqlite
, _auth :: Snaplet (AuthManager App)
}
makeLenses ''App
instance HasHeist App where
heistLens = subSnaplet heist
instance HasSqlite (Handler b App) where
getSqliteState = with db get
------------------------------------------------------------------------------
type AppHandler = Handler App App
|
santolucito/Peers
|
src/Application.hs
|
Haskell
|
apache-2.0
| 1,096
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGLWidget.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:32
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Opengl.QGLWidget (
QqGLWidget(..)
,QautoBufferSwap(..)
,colormap
,qGLWidgetConvertToGLFormat, qGLWidgetConvertToGLFormat_nf
,QfontDisplayListBase(..)
,QglDraw(..)
,QglInit(..)
,QgrabFrameBuffer(..), QgrabFrameBuffer_nf(..)
,QinitializeGL(..)
,QinitializeOverlayGL(..)
,makeOverlayCurrent
,overlayContext
,QpaintGL(..)
,QpaintOverlayGL(..)
,qglClearColor
,qglColor
,QrenderPixmap(..), QrenderPixmap_nf(..)
,QrenderText(..)
,QresizeGL(..)
,QresizeOverlayGL(..)
,QsetAutoBufferSwap(..)
,setColormap
,QupdateGL(..)
,QupdateOverlayGL(..)
,qGLWidget_delete
,qGLWidget_deleteLater
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
import Qtc.Classes.Opengl
import Qtc.ClassTypes.Opengl
instance QuserMethod (QGLWidget ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QGLWidget_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QGLWidget_userMethod" qtc_QGLWidget_userMethod :: Ptr (TQGLWidget a) -> CInt -> IO ()
instance QuserMethod (QGLWidgetSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QGLWidget_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QGLWidget ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QGLWidget_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QGLWidget_userMethodVariant" qtc_QGLWidget_userMethodVariant :: Ptr (TQGLWidget a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QGLWidgetSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QGLWidget_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqGLWidget x1 where
qGLWidget :: x1 -> IO (QGLWidget ())
instance QqGLWidget (()) where
qGLWidget ()
= withQGLWidgetResult $
qtc_QGLWidget
foreign import ccall "qtc_QGLWidget" qtc_QGLWidget :: IO (Ptr (TQGLWidget ()))
instance QqGLWidget ((QWidget t1)) where
qGLWidget (x1)
= withQGLWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget1 cobj_x1
foreign import ccall "qtc_QGLWidget1" qtc_QGLWidget1 :: Ptr (TQWidget t1) -> IO (Ptr (TQGLWidget ()))
instance QqGLWidget ((QGLContext t1)) where
qGLWidget (x1)
= withQGLWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget2 cobj_x1
foreign import ccall "qtc_QGLWidget2" qtc_QGLWidget2 :: Ptr (TQGLContext t1) -> IO (Ptr (TQGLWidget ()))
instance QqGLWidget ((QGLFormat t1)) where
qGLWidget (x1)
= withQGLWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget3 cobj_x1
foreign import ccall "qtc_QGLWidget3" qtc_QGLWidget3 :: Ptr (TQGLFormat t1) -> IO (Ptr (TQGLWidget ()))
instance QqGLWidget ((QGLContext t1, QWidget t2)) where
qGLWidget (x1, x2)
= withQGLWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLWidget4 cobj_x1 cobj_x2
foreign import ccall "qtc_QGLWidget4" qtc_QGLWidget4 :: Ptr (TQGLContext t1) -> Ptr (TQWidget t2) -> IO (Ptr (TQGLWidget ()))
instance QqGLWidget ((QGLFormat t1, QWidget t2)) where
qGLWidget (x1, x2)
= withQGLWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLWidget5 cobj_x1 cobj_x2
foreign import ccall "qtc_QGLWidget5" qtc_QGLWidget5 :: Ptr (TQGLFormat t1) -> Ptr (TQWidget t2) -> IO (Ptr (TQGLWidget ()))
instance QqGLWidget ((QWidget t1, QGLWidget t2, WindowFlags)) where
qGLWidget (x1, x2, x3)
= withQGLWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLWidget6 cobj_x1 cobj_x2 (toCLong $ qFlags_toInt x3)
foreign import ccall "qtc_QGLWidget6" qtc_QGLWidget6 :: Ptr (TQWidget t1) -> Ptr (TQGLWidget t2) -> CLong -> IO (Ptr (TQGLWidget ()))
instance QqGLWidget ((QGLContext t1, QWidget t2, QGLWidget t3, WindowFlags)) where
qGLWidget (x1, x2, x3, x4)
= withQGLWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGLWidget7 cobj_x1 cobj_x2 cobj_x3 (toCLong $ qFlags_toInt x4)
foreign import ccall "qtc_QGLWidget7" qtc_QGLWidget7 :: Ptr (TQGLContext t1) -> Ptr (TQWidget t2) -> Ptr (TQGLWidget t3) -> CLong -> IO (Ptr (TQGLWidget ()))
instance QqGLWidget ((QGLFormat t1, QWidget t2, QGLWidget t3, WindowFlags)) where
qGLWidget (x1, x2, x3, x4)
= withQGLWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGLWidget8 cobj_x1 cobj_x2 cobj_x3 (toCLong $ qFlags_toInt x4)
foreign import ccall "qtc_QGLWidget8" qtc_QGLWidget8 :: Ptr (TQGLFormat t1) -> Ptr (TQWidget t2) -> Ptr (TQGLWidget t3) -> CLong -> IO (Ptr (TQGLWidget ()))
class QautoBufferSwap x0 x1 where
autoBufferSwap :: x0 -> x1 -> IO (Bool)
instance QautoBufferSwap (QGLWidget ()) (()) where
autoBufferSwap x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_autoBufferSwap cobj_x0
foreign import ccall "qtc_QGLWidget_autoBufferSwap" qtc_QGLWidget_autoBufferSwap :: Ptr (TQGLWidget a) -> IO CBool
instance QautoBufferSwap (QGLWidgetSc a) (()) where
autoBufferSwap x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_autoBufferSwap cobj_x0
instance QbindTexture (QGLWidget a) ((QImage t1)) where
bindTexture x0 (x1)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_bindTexture2 cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_bindTexture2" qtc_QGLWidget_bindTexture2 :: Ptr (TQGLWidget a) -> Ptr (TQImage t1) -> IO CUInt
instance QbindTexture (QGLWidget a) ((QImage t1, Int)) where
bindTexture x0 (x1, x2)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_bindTexture3 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QGLWidget_bindTexture3" qtc_QGLWidget_bindTexture3 :: Ptr (TQGLWidget a) -> Ptr (TQImage t1) -> CInt -> IO CUInt
instance QbindTexture (QGLWidget a) ((QImage t1, Int, Int)) where
bindTexture x0 (x1, x2, x3)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_bindTexture5 cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QGLWidget_bindTexture5" qtc_QGLWidget_bindTexture5 :: Ptr (TQGLWidget a) -> Ptr (TQImage t1) -> CInt -> CInt -> IO CUInt
instance QbindTexture (QGLWidget a) ((QPixmap t1)) where
bindTexture x0 (x1)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_bindTexture1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_bindTexture1" qtc_QGLWidget_bindTexture1 :: Ptr (TQGLWidget a) -> Ptr (TQPixmap t1) -> IO CUInt
instance QbindTexture (QGLWidget a) ((QPixmap t1, Int)) where
bindTexture x0 (x1, x2)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_bindTexture4 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QGLWidget_bindTexture4" qtc_QGLWidget_bindTexture4 :: Ptr (TQGLWidget a) -> Ptr (TQPixmap t1) -> CInt -> IO CUInt
instance QbindTexture (QGLWidget a) ((QPixmap t1, Int, Int)) where
bindTexture x0 (x1, x2, x3)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_bindTexture6 cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QGLWidget_bindTexture6" qtc_QGLWidget_bindTexture6 :: Ptr (TQGLWidget a) -> Ptr (TQPixmap t1) -> CInt -> CInt -> IO CUInt
instance QbindTexture (QGLWidget a) ((String)) where
bindTexture x0 (x1)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGLWidget_bindTexture cobj_x0 cstr_x1
foreign import ccall "qtc_QGLWidget_bindTexture" qtc_QGLWidget_bindTexture :: Ptr (TQGLWidget a) -> CWString -> IO CUInt
colormap :: QGLWidget a -> (()) -> IO (QGLColormap ())
colormap x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_colormap cobj_x0
foreign import ccall "qtc_QGLWidget_colormap" qtc_QGLWidget_colormap :: Ptr (TQGLWidget a) -> IO (Ptr (TQGLColormap ()))
instance Qcontext (QGLWidget a) (()) (IO (QGLContext ())) where
context x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_context cobj_x0
foreign import ccall "qtc_QGLWidget_context" qtc_QGLWidget_context :: Ptr (TQGLWidget a) -> IO (Ptr (TQGLContext ()))
qGLWidgetConvertToGLFormat :: ((QImage t1)) -> IO (QImage ())
qGLWidgetConvertToGLFormat (x1)
= withQImageResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_convertToGLFormat cobj_x1
foreign import ccall "qtc_QGLWidget_convertToGLFormat" qtc_QGLWidget_convertToGLFormat :: Ptr (TQImage t1) -> IO (Ptr (TQImage ()))
qGLWidgetConvertToGLFormat_nf :: ((QImage t1)) -> IO (QImage ())
qGLWidgetConvertToGLFormat_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_convertToGLFormat cobj_x1
instance QdeleteTexture (QGLWidget a) ((Int)) where
deleteTexture x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_deleteTexture cobj_x0 (toCUInt x1)
foreign import ccall "qtc_QGLWidget_deleteTexture" qtc_QGLWidget_deleteTexture :: Ptr (TQGLWidget a) -> CUInt -> IO ()
instance QdoneCurrent (QGLWidget a) (()) (IO ()) where
doneCurrent x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_doneCurrent cobj_x0
foreign import ccall "qtc_QGLWidget_doneCurrent" qtc_QGLWidget_doneCurrent :: Ptr (TQGLWidget a) -> IO ()
instance QdoubleBuffer (QGLWidget a) (()) where
doubleBuffer x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_doubleBuffer cobj_x0
foreign import ccall "qtc_QGLWidget_doubleBuffer" qtc_QGLWidget_doubleBuffer :: Ptr (TQGLWidget a) -> IO CBool
instance Qevent (QGLWidget ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_event_h" qtc_QGLWidget_event_h :: Ptr (TQGLWidget a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QGLWidgetSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_event_h cobj_x0 cobj_x1
class QfontDisplayListBase x0 x1 where
fontDisplayListBase :: x0 -> x1 -> IO (Int)
instance QfontDisplayListBase (QGLWidget ()) ((QFont t1)) where
fontDisplayListBase x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_fontDisplayListBase cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_fontDisplayListBase" qtc_QGLWidget_fontDisplayListBase :: Ptr (TQGLWidget a) -> Ptr (TQFont t1) -> IO CInt
instance QfontDisplayListBase (QGLWidgetSc a) ((QFont t1)) where
fontDisplayListBase x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_fontDisplayListBase cobj_x0 cobj_x1
instance QfontDisplayListBase (QGLWidget ()) ((QFont t1, Int)) where
fontDisplayListBase x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_fontDisplayListBase1 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QGLWidget_fontDisplayListBase1" qtc_QGLWidget_fontDisplayListBase1 :: Ptr (TQGLWidget a) -> Ptr (TQFont t1) -> CInt -> IO CInt
instance QfontDisplayListBase (QGLWidgetSc a) ((QFont t1, Int)) where
fontDisplayListBase x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_fontDisplayListBase1 cobj_x0 cobj_x1 (toCInt x2)
instance Qformat (QGLWidget a) (()) (IO (QGLFormat ())) where
format x0 ()
= withQGLFormatResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_format cobj_x0
foreign import ccall "qtc_QGLWidget_format" qtc_QGLWidget_format :: Ptr (TQGLWidget a) -> IO (Ptr (TQGLFormat ()))
class QglDraw x0 x1 where
glDraw :: x0 -> x1 -> IO ()
instance QglDraw (QGLWidget ()) (()) where
glDraw x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_glDraw_h cobj_x0
foreign import ccall "qtc_QGLWidget_glDraw_h" qtc_QGLWidget_glDraw_h :: Ptr (TQGLWidget a) -> IO ()
instance QglDraw (QGLWidgetSc a) (()) where
glDraw x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_glDraw_h cobj_x0
class QglInit x0 x1 where
glInit :: x0 -> x1 -> IO ()
instance QglInit (QGLWidget ()) (()) where
glInit x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_glInit_h cobj_x0
foreign import ccall "qtc_QGLWidget_glInit_h" qtc_QGLWidget_glInit_h :: Ptr (TQGLWidget a) -> IO ()
instance QglInit (QGLWidgetSc a) (()) where
glInit x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_glInit_h cobj_x0
class QgrabFrameBuffer x0 x1 where
grabFrameBuffer :: x0 -> x1 -> IO (QImage ())
class QgrabFrameBuffer_nf x0 x1 where
grabFrameBuffer_nf :: x0 -> x1 -> IO (QImage ())
instance QgrabFrameBuffer (QGLWidget ()) (()) where
grabFrameBuffer x0 ()
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_grabFrameBuffer cobj_x0
foreign import ccall "qtc_QGLWidget_grabFrameBuffer" qtc_QGLWidget_grabFrameBuffer :: Ptr (TQGLWidget a) -> IO (Ptr (TQImage ()))
instance QgrabFrameBuffer (QGLWidgetSc a) (()) where
grabFrameBuffer x0 ()
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_grabFrameBuffer cobj_x0
instance QgrabFrameBuffer_nf (QGLWidget ()) (()) where
grabFrameBuffer_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_grabFrameBuffer cobj_x0
instance QgrabFrameBuffer_nf (QGLWidgetSc a) (()) where
grabFrameBuffer_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_grabFrameBuffer cobj_x0
instance QgrabFrameBuffer (QGLWidget ()) ((Bool)) where
grabFrameBuffer x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_grabFrameBuffer1 cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLWidget_grabFrameBuffer1" qtc_QGLWidget_grabFrameBuffer1 :: Ptr (TQGLWidget a) -> CBool -> IO (Ptr (TQImage ()))
instance QgrabFrameBuffer (QGLWidgetSc a) ((Bool)) where
grabFrameBuffer x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_grabFrameBuffer1 cobj_x0 (toCBool x1)
instance QgrabFrameBuffer_nf (QGLWidget ()) ((Bool)) where
grabFrameBuffer_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_grabFrameBuffer1 cobj_x0 (toCBool x1)
instance QgrabFrameBuffer_nf (QGLWidgetSc a) ((Bool)) where
grabFrameBuffer_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_grabFrameBuffer1 cobj_x0 (toCBool x1)
class QinitializeGL x0 x1 where
initializeGL :: x0 -> x1 -> IO ()
instance QinitializeGL (QGLWidget ()) (()) where
initializeGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_initializeGL_h cobj_x0
foreign import ccall "qtc_QGLWidget_initializeGL_h" qtc_QGLWidget_initializeGL_h :: Ptr (TQGLWidget a) -> IO ()
instance QinitializeGL (QGLWidgetSc a) (()) where
initializeGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_initializeGL_h cobj_x0
class QinitializeOverlayGL x0 x1 where
initializeOverlayGL :: x0 -> x1 -> IO ()
instance QinitializeOverlayGL (QGLWidget ()) (()) where
initializeOverlayGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_initializeOverlayGL_h cobj_x0
foreign import ccall "qtc_QGLWidget_initializeOverlayGL_h" qtc_QGLWidget_initializeOverlayGL_h :: Ptr (TQGLWidget a) -> IO ()
instance QinitializeOverlayGL (QGLWidgetSc a) (()) where
initializeOverlayGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_initializeOverlayGL_h cobj_x0
instance QisSharing (QGLWidget a) (()) where
isSharing x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_isSharing cobj_x0
foreign import ccall "qtc_QGLWidget_isSharing" qtc_QGLWidget_isSharing :: Ptr (TQGLWidget a) -> IO CBool
instance QqisValid (QGLWidget ()) (()) where
qisValid x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_isValid cobj_x0
foreign import ccall "qtc_QGLWidget_isValid" qtc_QGLWidget_isValid :: Ptr (TQGLWidget a) -> IO CBool
instance QqisValid (QGLWidgetSc a) (()) where
qisValid x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_isValid cobj_x0
instance QmakeCurrent (QGLWidget a) (()) (IO ()) where
makeCurrent x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_makeCurrent cobj_x0
foreign import ccall "qtc_QGLWidget_makeCurrent" qtc_QGLWidget_makeCurrent :: Ptr (TQGLWidget a) -> IO ()
makeOverlayCurrent :: QGLWidget a -> (()) -> IO ()
makeOverlayCurrent x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_makeOverlayCurrent cobj_x0
foreign import ccall "qtc_QGLWidget_makeOverlayCurrent" qtc_QGLWidget_makeOverlayCurrent :: Ptr (TQGLWidget a) -> IO ()
overlayContext :: QGLWidget a -> (()) -> IO (QGLContext ())
overlayContext x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_overlayContext cobj_x0
foreign import ccall "qtc_QGLWidget_overlayContext" qtc_QGLWidget_overlayContext :: Ptr (TQGLWidget a) -> IO (Ptr (TQGLContext ()))
instance QpaintEngine (QGLWidget ()) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_paintEngine_h cobj_x0
foreign import ccall "qtc_QGLWidget_paintEngine_h" qtc_QGLWidget_paintEngine_h :: Ptr (TQGLWidget a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine (QGLWidgetSc a) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_paintEngine_h cobj_x0
instance QpaintEvent (QGLWidget ()) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_paintEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_paintEvent_h" qtc_QGLWidget_paintEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent (QGLWidgetSc a) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_paintEvent_h cobj_x0 cobj_x1
class QpaintGL x0 x1 where
paintGL :: x0 -> x1 -> IO ()
instance QpaintGL (QGLWidget ()) (()) where
paintGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_paintGL_h cobj_x0
foreign import ccall "qtc_QGLWidget_paintGL_h" qtc_QGLWidget_paintGL_h :: Ptr (TQGLWidget a) -> IO ()
instance QpaintGL (QGLWidgetSc a) (()) where
paintGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_paintGL_h cobj_x0
class QpaintOverlayGL x0 x1 where
paintOverlayGL :: x0 -> x1 -> IO ()
instance QpaintOverlayGL (QGLWidget ()) (()) where
paintOverlayGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_paintOverlayGL_h cobj_x0
foreign import ccall "qtc_QGLWidget_paintOverlayGL_h" qtc_QGLWidget_paintOverlayGL_h :: Ptr (TQGLWidget a) -> IO ()
instance QpaintOverlayGL (QGLWidgetSc a) (()) where
paintOverlayGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_paintOverlayGL_h cobj_x0
qglClearColor :: QGLWidget a -> ((QColor t1)) -> IO ()
qglClearColor x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_qglClearColor cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_qglClearColor" qtc_QGLWidget_qglClearColor :: Ptr (TQGLWidget a) -> Ptr (TQColor t1) -> IO ()
qglColor :: QGLWidget a -> ((QColor t1)) -> IO ()
qglColor x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_qglColor cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_qglColor" qtc_QGLWidget_qglColor :: Ptr (TQGLWidget a) -> Ptr (TQColor t1) -> IO ()
class QrenderPixmap x0 x1 where
renderPixmap :: x0 -> x1 -> IO (QPixmap ())
class QrenderPixmap_nf x0 x1 where
renderPixmap_nf :: x0 -> x1 -> IO (QPixmap ())
instance QrenderPixmap (QGLWidget ()) (()) where
renderPixmap x0 ()
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap cobj_x0
foreign import ccall "qtc_QGLWidget_renderPixmap" qtc_QGLWidget_renderPixmap :: Ptr (TQGLWidget a) -> IO (Ptr (TQPixmap ()))
instance QrenderPixmap (QGLWidgetSc a) (()) where
renderPixmap x0 ()
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap cobj_x0
instance QrenderPixmap_nf (QGLWidget ()) (()) where
renderPixmap_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap cobj_x0
instance QrenderPixmap_nf (QGLWidgetSc a) (()) where
renderPixmap_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap cobj_x0
instance QrenderPixmap (QGLWidget ()) ((Int)) where
renderPixmap x0 (x1)
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap1 cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGLWidget_renderPixmap1" qtc_QGLWidget_renderPixmap1 :: Ptr (TQGLWidget a) -> CInt -> IO (Ptr (TQPixmap ()))
instance QrenderPixmap (QGLWidgetSc a) ((Int)) where
renderPixmap x0 (x1)
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap1 cobj_x0 (toCInt x1)
instance QrenderPixmap_nf (QGLWidget ()) ((Int)) where
renderPixmap_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap1 cobj_x0 (toCInt x1)
instance QrenderPixmap_nf (QGLWidgetSc a) ((Int)) where
renderPixmap_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap1 cobj_x0 (toCInt x1)
instance QrenderPixmap (QGLWidget ()) ((Int, Int)) where
renderPixmap x0 (x1, x2)
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap2 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QGLWidget_renderPixmap2" qtc_QGLWidget_renderPixmap2 :: Ptr (TQGLWidget a) -> CInt -> CInt -> IO (Ptr (TQPixmap ()))
instance QrenderPixmap (QGLWidgetSc a) ((Int, Int)) where
renderPixmap x0 (x1, x2)
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap2 cobj_x0 (toCInt x1) (toCInt x2)
instance QrenderPixmap_nf (QGLWidget ()) ((Int, Int)) where
renderPixmap_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap2 cobj_x0 (toCInt x1) (toCInt x2)
instance QrenderPixmap_nf (QGLWidgetSc a) ((Int, Int)) where
renderPixmap_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap2 cobj_x0 (toCInt x1) (toCInt x2)
instance QrenderPixmap (QGLWidget ()) ((Int, Int, Bool)) where
renderPixmap x0 (x1, x2, x3)
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap3 cobj_x0 (toCInt x1) (toCInt x2) (toCBool x3)
foreign import ccall "qtc_QGLWidget_renderPixmap3" qtc_QGLWidget_renderPixmap3 :: Ptr (TQGLWidget a) -> CInt -> CInt -> CBool -> IO (Ptr (TQPixmap ()))
instance QrenderPixmap (QGLWidgetSc a) ((Int, Int, Bool)) where
renderPixmap x0 (x1, x2, x3)
= withQPixmapResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap3 cobj_x0 (toCInt x1) (toCInt x2) (toCBool x3)
instance QrenderPixmap_nf (QGLWidget ()) ((Int, Int, Bool)) where
renderPixmap_nf x0 (x1, x2, x3)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap3 cobj_x0 (toCInt x1) (toCInt x2) (toCBool x3)
instance QrenderPixmap_nf (QGLWidgetSc a) ((Int, Int, Bool)) where
renderPixmap_nf x0 (x1, x2, x3)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_renderPixmap3 cobj_x0 (toCInt x1) (toCInt x2) (toCBool x3)
class QrenderText x1 where
renderText :: QGLWidget a -> x1 -> IO ()
instance QrenderText ((Double, Double, Double, String)) where
renderText x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x4 $ \cstr_x4 ->
qtc_QGLWidget_renderText2 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) cstr_x4
foreign import ccall "qtc_QGLWidget_renderText2" qtc_QGLWidget_renderText2 :: Ptr (TQGLWidget a) -> CDouble -> CDouble -> CDouble -> CWString -> IO ()
instance QrenderText ((Double, Double, Double, String, QFont t5)) where
renderText x0 (x1, x2, x3, x4, x5)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x4 $ \cstr_x4 ->
withObjectPtr x5 $ \cobj_x5 ->
qtc_QGLWidget_renderText3 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) cstr_x4 cobj_x5
foreign import ccall "qtc_QGLWidget_renderText3" qtc_QGLWidget_renderText3 :: Ptr (TQGLWidget a) -> CDouble -> CDouble -> CDouble -> CWString -> Ptr (TQFont t5) -> IO ()
instance QrenderText ((Double, Double, Double, String, QFont t5, Int)) where
renderText x0 (x1, x2, x3, x4, x5, x6)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x4 $ \cstr_x4 ->
withObjectPtr x5 $ \cobj_x5 ->
qtc_QGLWidget_renderText5 cobj_x0 (toCDouble x1) (toCDouble x2) (toCDouble x3) cstr_x4 cobj_x5 (toCInt x6)
foreign import ccall "qtc_QGLWidget_renderText5" qtc_QGLWidget_renderText5 :: Ptr (TQGLWidget a) -> CDouble -> CDouble -> CDouble -> CWString -> Ptr (TQFont t5) -> CInt -> IO ()
instance QrenderText ((Int, Int, String)) where
renderText x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x3 $ \cstr_x3 ->
qtc_QGLWidget_renderText cobj_x0 (toCInt x1) (toCInt x2) cstr_x3
foreign import ccall "qtc_QGLWidget_renderText" qtc_QGLWidget_renderText :: Ptr (TQGLWidget a) -> CInt -> CInt -> CWString -> IO ()
instance QrenderText ((Int, Int, String, QFont t4)) where
renderText x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x3 $ \cstr_x3 ->
withObjectPtr x4 $ \cobj_x4 ->
qtc_QGLWidget_renderText1 cobj_x0 (toCInt x1) (toCInt x2) cstr_x3 cobj_x4
foreign import ccall "qtc_QGLWidget_renderText1" qtc_QGLWidget_renderText1 :: Ptr (TQGLWidget a) -> CInt -> CInt -> CWString -> Ptr (TQFont t4) -> IO ()
instance QrenderText ((Int, Int, String, QFont t4, Int)) where
renderText x0 (x1, x2, x3, x4, x5)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x3 $ \cstr_x3 ->
withObjectPtr x4 $ \cobj_x4 ->
qtc_QGLWidget_renderText4 cobj_x0 (toCInt x1) (toCInt x2) cstr_x3 cobj_x4 (toCInt x5)
foreign import ccall "qtc_QGLWidget_renderText4" qtc_QGLWidget_renderText4 :: Ptr (TQGLWidget a) -> CInt -> CInt -> CWString -> Ptr (TQFont t4) -> CInt -> IO ()
instance QresizeEvent (QGLWidget ()) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_resizeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_resizeEvent_h" qtc_QGLWidget_resizeEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent (QGLWidgetSc a) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_resizeEvent_h cobj_x0 cobj_x1
class QresizeGL x0 x1 where
resizeGL :: x0 -> x1 -> IO ()
instance QresizeGL (QGLWidget ()) ((Int, Int)) where
resizeGL x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_resizeGL_h cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QGLWidget_resizeGL_h" qtc_QGLWidget_resizeGL_h :: Ptr (TQGLWidget a) -> CInt -> CInt -> IO ()
instance QresizeGL (QGLWidgetSc a) ((Int, Int)) where
resizeGL x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_resizeGL_h cobj_x0 (toCInt x1) (toCInt x2)
class QresizeOverlayGL x0 x1 where
resizeOverlayGL :: x0 -> x1 -> IO ()
instance QresizeOverlayGL (QGLWidget ()) ((Int, Int)) where
resizeOverlayGL x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_resizeOverlayGL_h cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QGLWidget_resizeOverlayGL_h" qtc_QGLWidget_resizeOverlayGL_h :: Ptr (TQGLWidget a) -> CInt -> CInt -> IO ()
instance QresizeOverlayGL (QGLWidgetSc a) ((Int, Int)) where
resizeOverlayGL x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_resizeOverlayGL_h cobj_x0 (toCInt x1) (toCInt x2)
class QsetAutoBufferSwap x0 x1 where
setAutoBufferSwap :: x0 -> x1 -> IO ()
instance QsetAutoBufferSwap (QGLWidget ()) ((Bool)) where
setAutoBufferSwap x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_setAutoBufferSwap cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLWidget_setAutoBufferSwap" qtc_QGLWidget_setAutoBufferSwap :: Ptr (TQGLWidget a) -> CBool -> IO ()
instance QsetAutoBufferSwap (QGLWidgetSc a) ((Bool)) where
setAutoBufferSwap x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_setAutoBufferSwap cobj_x0 (toCBool x1)
setColormap :: QGLWidget a -> ((QGLColormap t1)) -> IO ()
setColormap x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_setColormap cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_setColormap" qtc_QGLWidget_setColormap :: Ptr (TQGLWidget a) -> Ptr (TQGLColormap t1) -> IO ()
instance QsetContext (QGLWidget a) ((QGLContext t1)) where
setContext x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_setContext cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_setContext" qtc_QGLWidget_setContext :: Ptr (TQGLWidget a) -> Ptr (TQGLContext t1) -> IO ()
instance QsetContext (QGLWidget a) ((QGLContext t1, QGLContext t2)) where
setContext x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLWidget_setContext1 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGLWidget_setContext1" qtc_QGLWidget_setContext1 :: Ptr (TQGLWidget a) -> Ptr (TQGLContext t1) -> Ptr (TQGLContext t2) -> IO ()
instance QsetContext (QGLWidget a) ((QGLContext t1, QGLContext t2, Bool)) where
setContext x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLWidget_setContext2 cobj_x0 cobj_x1 cobj_x2 (toCBool x3)
foreign import ccall "qtc_QGLWidget_setContext2" qtc_QGLWidget_setContext2 :: Ptr (TQGLWidget a) -> Ptr (TQGLContext t1) -> Ptr (TQGLContext t2) -> CBool -> IO ()
instance QsetFormat (QGLWidget a) ((QGLFormat t1)) where
setFormat x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_setFormat cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_setFormat" qtc_QGLWidget_setFormat :: Ptr (TQGLWidget a) -> Ptr (TQGLFormat t1) -> IO ()
instance QsetMouseTracking (QGLWidget ()) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_setMouseTracking cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLWidget_setMouseTracking" qtc_QGLWidget_setMouseTracking :: Ptr (TQGLWidget a) -> CBool -> IO ()
instance QsetMouseTracking (QGLWidgetSc a) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_setMouseTracking cobj_x0 (toCBool x1)
instance QswapBuffers (QGLWidget a) (()) where
swapBuffers x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_swapBuffers cobj_x0
foreign import ccall "qtc_QGLWidget_swapBuffers" qtc_QGLWidget_swapBuffers :: Ptr (TQGLWidget a) -> IO ()
class QupdateGL x0 x1 where
updateGL :: x0 -> x1 -> IO ()
instance QupdateGL (QGLWidget ()) (()) where
updateGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_updateGL_h cobj_x0
foreign import ccall "qtc_QGLWidget_updateGL_h" qtc_QGLWidget_updateGL_h :: Ptr (TQGLWidget a) -> IO ()
instance QupdateGL (QGLWidgetSc a) (()) where
updateGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_updateGL_h cobj_x0
class QupdateOverlayGL x0 x1 where
updateOverlayGL :: x0 -> x1 -> IO ()
instance QupdateOverlayGL (QGLWidget ()) (()) where
updateOverlayGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_updateOverlayGL_h cobj_x0
foreign import ccall "qtc_QGLWidget_updateOverlayGL_h" qtc_QGLWidget_updateOverlayGL_h :: Ptr (TQGLWidget a) -> IO ()
instance QupdateOverlayGL (QGLWidgetSc a) (()) where
updateOverlayGL x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_updateOverlayGL_h cobj_x0
qGLWidget_delete :: QGLWidget a -> IO ()
qGLWidget_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_delete cobj_x0
foreign import ccall "qtc_QGLWidget_delete" qtc_QGLWidget_delete :: Ptr (TQGLWidget a) -> IO ()
qGLWidget_deleteLater :: QGLWidget a -> IO ()
qGLWidget_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_deleteLater cobj_x0
foreign import ccall "qtc_QGLWidget_deleteLater" qtc_QGLWidget_deleteLater :: Ptr (TQGLWidget a) -> IO ()
instance QactionEvent (QGLWidget ()) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_actionEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_actionEvent_h" qtc_QGLWidget_actionEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent (QGLWidgetSc a) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_actionEvent_h cobj_x0 cobj_x1
instance QaddAction (QGLWidget ()) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_addAction cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_addAction" qtc_QGLWidget_addAction :: Ptr (TQGLWidget a) -> Ptr (TQAction t1) -> IO ()
instance QaddAction (QGLWidgetSc a) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_addAction cobj_x0 cobj_x1
instance QchangeEvent (QGLWidget ()) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_changeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_changeEvent_h" qtc_QGLWidget_changeEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent (QGLWidgetSc a) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_changeEvent_h cobj_x0 cobj_x1
instance QcloseEvent (QGLWidget ()) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_closeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_closeEvent_h" qtc_QGLWidget_closeEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent (QGLWidgetSc a) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_closeEvent_h cobj_x0 cobj_x1
instance QcontextMenuEvent (QGLWidget ()) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_contextMenuEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_contextMenuEvent_h" qtc_QGLWidget_contextMenuEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent (QGLWidgetSc a) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_contextMenuEvent_h cobj_x0 cobj_x1
instance Qcreate (QGLWidget ()) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_create cobj_x0
foreign import ccall "qtc_QGLWidget_create" qtc_QGLWidget_create :: Ptr (TQGLWidget a) -> IO ()
instance Qcreate (QGLWidgetSc a) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_create cobj_x0
instance Qcreate (QGLWidget ()) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_create1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_create1" qtc_QGLWidget_create1 :: Ptr (TQGLWidget a) -> Ptr (TQVoid t1) -> IO ()
instance Qcreate (QGLWidgetSc a) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_create1 cobj_x0 cobj_x1
instance Qcreate (QGLWidget ()) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_create2 cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QGLWidget_create2" qtc_QGLWidget_create2 :: Ptr (TQGLWidget a) -> Ptr (TQVoid t1) -> CBool -> IO ()
instance Qcreate (QGLWidgetSc a) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_create2 cobj_x0 cobj_x1 (toCBool x2)
instance Qcreate (QGLWidget ()) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
foreign import ccall "qtc_QGLWidget_create3" qtc_QGLWidget_create3 :: Ptr (TQGLWidget a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO ()
instance Qcreate (QGLWidgetSc a) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
instance Qdestroy (QGLWidget ()) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_destroy cobj_x0
foreign import ccall "qtc_QGLWidget_destroy" qtc_QGLWidget_destroy :: Ptr (TQGLWidget a) -> IO ()
instance Qdestroy (QGLWidgetSc a) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_destroy cobj_x0
instance Qdestroy (QGLWidget ()) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_destroy1 cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLWidget_destroy1" qtc_QGLWidget_destroy1 :: Ptr (TQGLWidget a) -> CBool -> IO ()
instance Qdestroy (QGLWidgetSc a) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_destroy1 cobj_x0 (toCBool x1)
instance Qdestroy (QGLWidget ()) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
foreign import ccall "qtc_QGLWidget_destroy2" qtc_QGLWidget_destroy2 :: Ptr (TQGLWidget a) -> CBool -> CBool -> IO ()
instance Qdestroy (QGLWidgetSc a) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
instance QdevType (QGLWidget ()) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_devType_h cobj_x0
foreign import ccall "qtc_QGLWidget_devType_h" qtc_QGLWidget_devType_h :: Ptr (TQGLWidget a) -> IO CInt
instance QdevType (QGLWidgetSc a) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_devType_h cobj_x0
instance QdragEnterEvent (QGLWidget ()) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_dragEnterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_dragEnterEvent_h" qtc_QGLWidget_dragEnterEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent (QGLWidgetSc a) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_dragEnterEvent_h cobj_x0 cobj_x1
instance QdragLeaveEvent (QGLWidget ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_dragLeaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_dragLeaveEvent_h" qtc_QGLWidget_dragLeaveEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent (QGLWidgetSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_dragLeaveEvent_h cobj_x0 cobj_x1
instance QdragMoveEvent (QGLWidget ()) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_dragMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_dragMoveEvent_h" qtc_QGLWidget_dragMoveEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent (QGLWidgetSc a) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_dragMoveEvent_h cobj_x0 cobj_x1
instance QdropEvent (QGLWidget ()) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_dropEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_dropEvent_h" qtc_QGLWidget_dropEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent (QGLWidgetSc a) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_dropEvent_h cobj_x0 cobj_x1
instance QenabledChange (QGLWidget ()) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_enabledChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLWidget_enabledChange" qtc_QGLWidget_enabledChange :: Ptr (TQGLWidget a) -> CBool -> IO ()
instance QenabledChange (QGLWidgetSc a) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_enabledChange cobj_x0 (toCBool x1)
instance QenterEvent (QGLWidget ()) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_enterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_enterEvent_h" qtc_QGLWidget_enterEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent (QGLWidgetSc a) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_enterEvent_h cobj_x0 cobj_x1
instance QfocusInEvent (QGLWidget ()) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_focusInEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_focusInEvent_h" qtc_QGLWidget_focusInEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent (QGLWidgetSc a) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_focusInEvent_h cobj_x0 cobj_x1
instance QfocusNextChild (QGLWidget ()) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_focusNextChild cobj_x0
foreign import ccall "qtc_QGLWidget_focusNextChild" qtc_QGLWidget_focusNextChild :: Ptr (TQGLWidget a) -> IO CBool
instance QfocusNextChild (QGLWidgetSc a) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_focusNextChild cobj_x0
instance QfocusNextPrevChild (QGLWidget ()) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_focusNextPrevChild cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLWidget_focusNextPrevChild" qtc_QGLWidget_focusNextPrevChild :: Ptr (TQGLWidget a) -> CBool -> IO CBool
instance QfocusNextPrevChild (QGLWidgetSc a) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_focusNextPrevChild cobj_x0 (toCBool x1)
instance QfocusOutEvent (QGLWidget ()) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_focusOutEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_focusOutEvent_h" qtc_QGLWidget_focusOutEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent (QGLWidgetSc a) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_focusOutEvent_h cobj_x0 cobj_x1
instance QfocusPreviousChild (QGLWidget ()) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_focusPreviousChild cobj_x0
foreign import ccall "qtc_QGLWidget_focusPreviousChild" qtc_QGLWidget_focusPreviousChild :: Ptr (TQGLWidget a) -> IO CBool
instance QfocusPreviousChild (QGLWidgetSc a) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_focusPreviousChild cobj_x0
instance QfontChange (QGLWidget ()) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_fontChange cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_fontChange" qtc_QGLWidget_fontChange :: Ptr (TQGLWidget a) -> Ptr (TQFont t1) -> IO ()
instance QfontChange (QGLWidgetSc a) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_fontChange cobj_x0 cobj_x1
instance QheightForWidth (QGLWidget ()) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_heightForWidth_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGLWidget_heightForWidth_h" qtc_QGLWidget_heightForWidth_h :: Ptr (TQGLWidget a) -> CInt -> IO CInt
instance QheightForWidth (QGLWidgetSc a) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_heightForWidth_h cobj_x0 (toCInt x1)
instance QhideEvent (QGLWidget ()) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_hideEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_hideEvent_h" qtc_QGLWidget_hideEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent (QGLWidgetSc a) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_hideEvent_h cobj_x0 cobj_x1
instance QinputMethodEvent (QGLWidget ()) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_inputMethodEvent" qtc_QGLWidget_inputMethodEvent :: Ptr (TQGLWidget a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent (QGLWidgetSc a) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_inputMethodEvent cobj_x0 cobj_x1
instance QinputMethodQuery (QGLWidget ()) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGLWidget_inputMethodQuery_h" qtc_QGLWidget_inputMethodQuery_h :: Ptr (TQGLWidget a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery (QGLWidgetSc a) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyPressEvent (QGLWidget ()) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_keyPressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_keyPressEvent_h" qtc_QGLWidget_keyPressEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent (QGLWidgetSc a) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_keyPressEvent_h cobj_x0 cobj_x1
instance QkeyReleaseEvent (QGLWidget ()) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_keyReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_keyReleaseEvent_h" qtc_QGLWidget_keyReleaseEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent (QGLWidgetSc a) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_keyReleaseEvent_h cobj_x0 cobj_x1
instance QlanguageChange (QGLWidget ()) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_languageChange cobj_x0
foreign import ccall "qtc_QGLWidget_languageChange" qtc_QGLWidget_languageChange :: Ptr (TQGLWidget a) -> IO ()
instance QlanguageChange (QGLWidgetSc a) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_languageChange cobj_x0
instance QleaveEvent (QGLWidget ()) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_leaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_leaveEvent_h" qtc_QGLWidget_leaveEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent (QGLWidgetSc a) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_leaveEvent_h cobj_x0 cobj_x1
instance Qmetric (QGLWidget ()) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_metric cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGLWidget_metric" qtc_QGLWidget_metric :: Ptr (TQGLWidget a) -> CLong -> IO CInt
instance Qmetric (QGLWidgetSc a) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_metric cobj_x0 (toCLong $ qEnum_toInt x1)
instance QqminimumSizeHint (QGLWidget ()) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_minimumSizeHint_h cobj_x0
foreign import ccall "qtc_QGLWidget_minimumSizeHint_h" qtc_QGLWidget_minimumSizeHint_h :: Ptr (TQGLWidget a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint (QGLWidgetSc a) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_minimumSizeHint_h cobj_x0
instance QminimumSizeHint (QGLWidget ()) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QGLWidget_minimumSizeHint_qth_h" qtc_QGLWidget_minimumSizeHint_qth_h :: Ptr (TQGLWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint (QGLWidgetSc a) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QmouseDoubleClickEvent (QGLWidget ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_mouseDoubleClickEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_mouseDoubleClickEvent_h" qtc_QGLWidget_mouseDoubleClickEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent (QGLWidgetSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_mouseDoubleClickEvent_h cobj_x0 cobj_x1
instance QmouseMoveEvent (QGLWidget ()) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_mouseMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_mouseMoveEvent_h" qtc_QGLWidget_mouseMoveEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent (QGLWidgetSc a) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_mouseMoveEvent_h cobj_x0 cobj_x1
instance QmousePressEvent (QGLWidget ()) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_mousePressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_mousePressEvent_h" qtc_QGLWidget_mousePressEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent (QGLWidgetSc a) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_mousePressEvent_h cobj_x0 cobj_x1
instance QmouseReleaseEvent (QGLWidget ()) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_mouseReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_mouseReleaseEvent_h" qtc_QGLWidget_mouseReleaseEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent (QGLWidgetSc a) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_mouseReleaseEvent_h cobj_x0 cobj_x1
instance Qmove (QGLWidget ()) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_move1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QGLWidget_move1" qtc_QGLWidget_move1 :: Ptr (TQGLWidget a) -> CInt -> CInt -> IO ()
instance Qmove (QGLWidgetSc a) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_move1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qmove (QGLWidget ()) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QGLWidget_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QGLWidget_move_qth" qtc_QGLWidget_move_qth :: Ptr (TQGLWidget a) -> CInt -> CInt -> IO ()
instance Qmove (QGLWidgetSc a) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QGLWidget_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance Qqmove (QGLWidget ()) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_move cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_move" qtc_QGLWidget_move :: Ptr (TQGLWidget a) -> Ptr (TQPoint t1) -> IO ()
instance Qqmove (QGLWidgetSc a) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_move cobj_x0 cobj_x1
instance QmoveEvent (QGLWidget ()) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_moveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_moveEvent_h" qtc_QGLWidget_moveEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent (QGLWidgetSc a) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_moveEvent_h cobj_x0 cobj_x1
instance QpaletteChange (QGLWidget ()) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_paletteChange cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_paletteChange" qtc_QGLWidget_paletteChange :: Ptr (TQGLWidget a) -> Ptr (TQPalette t1) -> IO ()
instance QpaletteChange (QGLWidgetSc a) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_paletteChange cobj_x0 cobj_x1
instance Qrepaint (QGLWidget ()) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_repaint cobj_x0
foreign import ccall "qtc_QGLWidget_repaint" qtc_QGLWidget_repaint :: Ptr (TQGLWidget a) -> IO ()
instance Qrepaint (QGLWidgetSc a) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_repaint cobj_x0
instance Qrepaint (QGLWidget ()) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QGLWidget_repaint2" qtc_QGLWidget_repaint2 :: Ptr (TQGLWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance Qrepaint (QGLWidgetSc a) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance Qrepaint (QGLWidget ()) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_repaint1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_repaint1" qtc_QGLWidget_repaint1 :: Ptr (TQGLWidget a) -> Ptr (TQRegion t1) -> IO ()
instance Qrepaint (QGLWidgetSc a) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_repaint1 cobj_x0 cobj_x1
instance QresetInputContext (QGLWidget ()) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_resetInputContext cobj_x0
foreign import ccall "qtc_QGLWidget_resetInputContext" qtc_QGLWidget_resetInputContext :: Ptr (TQGLWidget a) -> IO ()
instance QresetInputContext (QGLWidgetSc a) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_resetInputContext cobj_x0
instance Qresize (QGLWidget ()) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_resize1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QGLWidget_resize1" qtc_QGLWidget_resize1 :: Ptr (TQGLWidget a) -> CInt -> CInt -> IO ()
instance Qresize (QGLWidgetSc a) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_resize1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qqresize (QGLWidget ()) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_resize cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_resize" qtc_QGLWidget_resize :: Ptr (TQGLWidget a) -> Ptr (TQSize t1) -> IO ()
instance Qqresize (QGLWidgetSc a) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_resize cobj_x0 cobj_x1
instance Qresize (QGLWidget ()) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QGLWidget_resize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QGLWidget_resize_qth" qtc_QGLWidget_resize_qth :: Ptr (TQGLWidget a) -> CInt -> CInt -> IO ()
instance Qresize (QGLWidgetSc a) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QGLWidget_resize_qth cobj_x0 csize_x1_w csize_x1_h
instance QsetGeometry (QGLWidget ()) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QGLWidget_setGeometry1" qtc_QGLWidget_setGeometry1 :: Ptr (TQGLWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QGLWidgetSc a) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance QqsetGeometry (QGLWidget ()) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_setGeometry cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_setGeometry" qtc_QGLWidget_setGeometry :: Ptr (TQGLWidget a) -> Ptr (TQRect t1) -> IO ()
instance QqsetGeometry (QGLWidgetSc a) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_setGeometry cobj_x0 cobj_x1
instance QsetGeometry (QGLWidget ()) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QGLWidget_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QGLWidget_setGeometry_qth" qtc_QGLWidget_setGeometry_qth :: Ptr (TQGLWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QGLWidgetSc a) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QGLWidget_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
instance QsetVisible (QGLWidget ()) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_setVisible_h cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLWidget_setVisible_h" qtc_QGLWidget_setVisible_h :: Ptr (TQGLWidget a) -> CBool -> IO ()
instance QsetVisible (QGLWidgetSc a) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_setVisible_h cobj_x0 (toCBool x1)
instance QshowEvent (QGLWidget ()) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_showEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_showEvent_h" qtc_QGLWidget_showEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent (QGLWidgetSc a) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_showEvent_h cobj_x0 cobj_x1
instance QqsizeHint (QGLWidget ()) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_sizeHint_h cobj_x0
foreign import ccall "qtc_QGLWidget_sizeHint_h" qtc_QGLWidget_sizeHint_h :: Ptr (TQGLWidget a) -> IO (Ptr (TQSize ()))
instance QqsizeHint (QGLWidgetSc a) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_sizeHint_h cobj_x0
instance QsizeHint (QGLWidget ()) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QGLWidget_sizeHint_qth_h" qtc_QGLWidget_sizeHint_qth_h :: Ptr (TQGLWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint (QGLWidgetSc a) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QtabletEvent (QGLWidget ()) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_tabletEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_tabletEvent_h" qtc_QGLWidget_tabletEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent (QGLWidgetSc a) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_tabletEvent_h cobj_x0 cobj_x1
instance QupdateMicroFocus (QGLWidget ()) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_updateMicroFocus cobj_x0
foreign import ccall "qtc_QGLWidget_updateMicroFocus" qtc_QGLWidget_updateMicroFocus :: Ptr (TQGLWidget a) -> IO ()
instance QupdateMicroFocus (QGLWidgetSc a) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_updateMicroFocus cobj_x0
instance QwheelEvent (QGLWidget ()) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_wheelEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_wheelEvent_h" qtc_QGLWidget_wheelEvent_h :: Ptr (TQGLWidget a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent (QGLWidgetSc a) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_wheelEvent_h cobj_x0 cobj_x1
instance QwindowActivationChange (QGLWidget ()) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_windowActivationChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLWidget_windowActivationChange" qtc_QGLWidget_windowActivationChange :: Ptr (TQGLWidget a) -> CBool -> IO ()
instance QwindowActivationChange (QGLWidgetSc a) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_windowActivationChange cobj_x0 (toCBool x1)
instance QchildEvent (QGLWidget ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_childEvent" qtc_QGLWidget_childEvent :: Ptr (TQGLWidget a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QGLWidgetSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QGLWidget ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGLWidget_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QGLWidget_connectNotify" qtc_QGLWidget_connectNotify :: Ptr (TQGLWidget a) -> CWString -> IO ()
instance QconnectNotify (QGLWidgetSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGLWidget_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QGLWidget ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_customEvent" qtc_QGLWidget_customEvent :: Ptr (TQGLWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QGLWidgetSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QGLWidget ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGLWidget_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QGLWidget_disconnectNotify" qtc_QGLWidget_disconnectNotify :: Ptr (TQGLWidget a) -> CWString -> IO ()
instance QdisconnectNotify (QGLWidgetSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGLWidget_disconnectNotify cobj_x0 cstr_x1
instance QeventFilter (QGLWidget ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLWidget_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGLWidget_eventFilter_h" qtc_QGLWidget_eventFilter_h :: Ptr (TQGLWidget a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QGLWidgetSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLWidget_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QGLWidget ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGLWidget_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QGLWidget_receivers" qtc_QGLWidget_receivers :: Ptr (TQGLWidget a) -> CWString -> IO CInt
instance Qreceivers (QGLWidgetSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGLWidget_receivers cobj_x0 cstr_x1
instance Qsender (QGLWidget ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_sender cobj_x0
foreign import ccall "qtc_QGLWidget_sender" qtc_QGLWidget_sender :: Ptr (TQGLWidget a) -> IO (Ptr (TQObject ()))
instance Qsender (QGLWidgetSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLWidget_sender cobj_x0
instance QtimerEvent (QGLWidget ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGLWidget_timerEvent" qtc_QGLWidget_timerEvent :: Ptr (TQGLWidget a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QGLWidgetSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLWidget_timerEvent cobj_x0 cobj_x1
|
uduki/hsQt
|
Qtc/Opengl/QGLWidget.hs
|
Haskell
|
bsd-2-clause
| 70,417
|
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module YesodDsl.ParserState (ParserMonad, initParserState, getParserState,
getPath, getParsed,
setParserState, runParser, pushScope, popScope,
declare, declareClassInstances, declareGlobal, SymType(..),
addClassInstances,
ParserState, mkLoc, parseErrorCount, withSymbol, withGlobalSymbol, withSymbolNow,
pError,
hasReserved,
getEntitySymbol,
symbolMatches,
requireClass,
requireEnumName,
requireEntity,
requireEntityResult,
requireEntityOrClass,
requireEntityId,
requireEntityField,
requireEntityFieldSelectedOrResult,
requireField,
requireEnum,
requireEnumValue,
requireParam,
requireFunction,
setCurrentHandlerType,
getCurrentHandlerType,
requireHandlerType,
validateExtractField,
validateInsert,
beginHandler,
statement,
lastStatement,
postValidation) where
import qualified Data.Map as Map
import Control.Monad.State.Lazy
import YesodDsl.AST
import YesodDsl.Lexer
import qualified Data.List as L
import Data.Maybe
import System.IO
data SymType = SEnum EnumType
| SEnumName EnumName
| SClass Class
| SEntity EntityName
| SEntityResult EntityName
| SEntityId EntityName
| SField Field
| SFieldType FieldType
| SUnique Unique
| SRoute Route
| SHandler Handler
| SParam
| SForParam FieldRef
| SReserved
| SFunction
instance Show SymType where
show st = case st of
SEnum _ -> "enum"
SEnumName _ -> "enum name"
SClass _ -> "class"
SEntity _ -> "entity"
SEntityResult _ -> "get-entity"
SEntityId _ -> "entity id"
SField _ -> "field"
SFieldType _ -> "field type"
SUnique _ -> "unique"
SRoute _ -> "route"
SHandler _ -> "handler"
SParam -> "param"
SForParam _ -> "for-param"
SReserved -> "reserved"
SFunction -> "function"
data Sym = Sym Int Location SymType deriving (Show)
type ParserMonad = StateT ParserState IO
type Syms = Map.Map String [Sym]
type EntityValidation = (EntityName, Entity -> ParserMonad ())
type PendingValidation = Syms -> ParserMonad ()
data ParserState = ParserState {
psSyms :: Syms,
psScopeId :: Int,
psPath :: FilePath,
psParsed :: [FilePath],
psErrors :: Int,
psHandlerType :: Maybe HandlerType,
psPendingValidations :: [[PendingValidation]],
psEntityValidations :: [EntityValidation],
psLastStatement :: Maybe (Location, String),
psChecks :: [(Location,String,FieldType)],
psClassInstances :: Map.Map ClassName [EntityName]
} deriving (Show)
instance Show (Syms -> ParserMonad ()) where
show _ = "<pendingvalidation>"
instance Show (Entity -> ParserMonad ()) where
show _ = "<entityvalidation>"
initParserState :: ParserState
initParserState = ParserState {
psSyms = Map.fromList [
("ClassInstance", [ Sym 0 (Loc "<builtin>" 0 0) (SEntity "ClassInstance") ])
],
psScopeId = 0,
psPath = "",
psParsed = [],
psErrors = 0,
psHandlerType = Nothing,
psPendingValidations = [],
psEntityValidations = [],
psLastStatement = Nothing,
psChecks = [],
psClassInstances = Map.empty
}
getParserState :: ParserMonad ParserState
getParserState = get
getPath :: ParserMonad FilePath
getPath = gets psPath
getParsed :: ParserMonad [FilePath]
getParsed = gets psParsed
addClassInstances :: EntityName -> [ClassName] -> ParserMonad ()
addClassInstances en cns = modify $ \ps -> ps {
psClassInstances = Map.unionWith (++) (psClassInstances ps) m
}
where
m = Map.fromListWith (++) [ (cn,[en]) | cn <- cns ]
setCurrentHandlerType :: HandlerType -> ParserMonad ()
setCurrentHandlerType ht = modify $ \ps -> ps {
psHandlerType = Just ht
}
requireHandlerType :: Location -> String -> (HandlerType -> Bool) -> ParserMonad ()
requireHandlerType l n f = do
mht <- gets psHandlerType
when (fmap f mht /= Just True) $
pError l $ n ++ " not allowed "
++ (fromMaybe "outside handler" $
mht >>= \ht' -> return $ "in " ++ show ht' ++ " handler")
getCurrentHandlerType :: ParserMonad (Maybe HandlerType)
getCurrentHandlerType = gets psHandlerType
setParserState :: ParserState -> ParserMonad ()
setParserState = put
runEntityValidation :: Module -> EntityValidation -> ParserMonad ()
runEntityValidation m (en,f) = do
case L.find (\e -> entityName e == en) $ modEntities m of
Just e -> f e
Nothing -> return ()
validateExtractField :: Location -> String -> ParserMonad ()
validateExtractField l s = if s `elem` validFields
then return ()
else pError l $ "Unknown subfield '" ++ s ++ "' to extract"
where
validFields = [
"century", "day", "decade", "dow", "doy", "epoch", "hour",
"isodow", "microseconds", "millennium", "milliseconds",
"minute", "month", "quarter", "second", "timezone",
"timezone_hour", "timezone_minute", "week", "year"
]
validateInsert :: Location -> Entity -> Maybe (Maybe VariableName, [FieldRefMapping]) -> ParserMonad ()
validateInsert l e (Just (Nothing, ifs)) = do
case [ fieldName f | f <- entityFields e,
(not . fieldOptional) f,
isNothing (fieldDefault f) ]
L.\\ [ fn | (fn,_,_) <- ifs ] of
fs@(_:_) -> pError l $ "Missing required fields without default value: " ++ (show fs)
_ -> return ()
validateInsert _ _ _ = return ()
beginHandler :: ParserMonad ()
beginHandler = modify $ \ps -> ps {
psLastStatement = Nothing
}
statement :: Location -> String -> ParserMonad ()
statement l s= do
mlast <- gets psLastStatement
fromMaybe (return ()) (mlast >>= \(l',s') -> do
return $ pError l $ "'" ++ s ++ "' not allowed after '" ++ s' ++ "' in "
++ show l')
lastStatement :: Location -> String -> ParserMonad ()
lastStatement l s = do
statement l s
modify $ \ps -> ps {
psLastStatement = listToMaybe $ catMaybes [
psLastStatement ps, Just (l,s)
]
}
postValidation :: Module -> ParserState -> IO Int
postValidation m ps = do
ps' <- execStateT f ps
return $ psErrors ps'
where
f = do
forM_ (psEntityValidations ps) (runEntityValidation m)
when (isNothing $ modName m) $ globalError "Missing top-level module name"
runParser :: FilePath -> ParserState -> ParserMonad a -> IO (a,ParserState)
runParser path ps m = do
(r,ps') <- runStateT m $ ps { psPath = path, psParsed = path:psParsed ps }
return (r, ps' { psPath = psPath ps} )
pushScope :: ParserMonad ()
pushScope = do
modify $ \ps -> ps {
psScopeId = psScopeId ps + 1,
psPendingValidations = []:psPendingValidations ps
}
popScope :: ParserMonad ()
popScope = do
(vs:_) <- gets psPendingValidations
syms <- gets psSyms
forM_ vs $ \v -> v syms
modify $ \ps -> ps {
psSyms = Map.filter (not . null) $
Map.map (filter (\(Sym s _ _) -> s < psScopeId ps)) $ psSyms ps,
psScopeId = psScopeId ps - 1,
psPendingValidations = tail $ psPendingValidations ps
}
pError :: Location -> String -> ParserMonad ()
pError l e = do
lift $ hPutStrLn stderr $ show l ++ ": " ++ e
modify $ \ps -> ps { psErrors = psErrors ps + 1 }
globalError :: String -> ParserMonad ()
globalError e = do
lift $ hPutStrLn stderr e
modify $ \ps -> ps { psErrors = psErrors ps + 1 }
declare :: Location -> String -> SymType -> ParserMonad ()
declare l n t = declare' False l n t
declareClassInstances :: ClassName -> Location -> String -> ParserMonad ()
declareClassInstances cn l n = do
ps <- get
forM_ (Map.findWithDefault [] cn $ psClassInstances ps) $ \en -> do
declare l (n ++ "_" ++ en) (SEntity en)
declareGlobal :: Location -> String -> SymType -> ParserMonad ()
declareGlobal l n t = declare' True l n t
declare' :: Bool -> Location -> String -> SymType -> ParserMonad ()
declare' global l n t = do
ps <- get
let scopeId = if global then 0 else psScopeId ps
sym = [Sym scopeId l t ]
case Map.lookup n (psSyms ps) of
Just ((Sym s l' _):_) -> if s == scopeId
then do
pError l $ "'" ++ n
++ "' already declared in " ++ show l'
return ()
else put $ ps {
psSyms = Map.adjust (sym++) n (psSyms ps)
}
_ -> put $ ps {
psSyms = Map.insert n sym $ psSyms ps
}
mkLoc :: Token -> ParserMonad Location
mkLoc t = do
path <- gets psPath
return $ Loc path (tokenLineNum t) (tokenColNum t)
parseErrorCount :: ParserState -> Int
parseErrorCount = psErrors
addEntityValidation :: EntityValidation -> ParserMonad ()
addEntityValidation ev = modify $ \ps -> ps {
psEntityValidations = psEntityValidations ps ++ [ev]
}
addPendingValidation :: (Syms -> ParserMonad ()) -> ParserMonad ()
addPendingValidation v = modify $ \ps -> let vs = psPendingValidations ps in ps {
psPendingValidations = (v:(head vs)):tail vs
}
addGlobalPendingValidation :: (Syms -> ParserMonad ()) -> ParserMonad ()
addGlobalPendingValidation v = modify $ \ps -> let vs = psPendingValidations ps in ps {
psPendingValidations = init vs ++ [v : last vs]
}
hasReserved :: String -> ParserMonad Bool
hasReserved n = do
syms <- gets psSyms
return $ fromMaybe False $
Map.lookup n syms >>= return . (not . null . (filter match))
where
match (Sym _ _ SReserved) = True
match _ = False
withSymbol' :: Syms -> a -> Location -> String -> (Location -> Location -> SymType -> ParserMonad a) -> ParserMonad a
withSymbol' syms d l n f = do
case Map.lookup n syms >>= return . (filter notReserved) of
Just ((Sym _ l' st):_) -> f l l' st
_ -> pError l ("Reference to an undeclared identifier '"
++ n ++ "'") >> return d
notReserved :: Sym -> Bool
notReserved (Sym _ _ SReserved) = False
notReserved _ = True
withSymbolNow :: a -> Location -> String -> (Location -> Location -> SymType -> ParserMonad a) -> ParserMonad a
withSymbolNow d l n f = do
syms <- gets psSyms
withSymbol' syms d l n f
withSymbol :: Location -> String -> (Location -> Location -> SymType -> ParserMonad ()) -> ParserMonad ()
withSymbol l n f = addPendingValidation $ \syms -> void $ withSymbol' syms () l n f
withGlobalSymbol :: Location -> String -> (Location -> Location -> SymType -> ParserMonad ()) -> ParserMonad ()
withGlobalSymbol l n f = addGlobalPendingValidation $ \syms -> void $ withSymbol' syms () l n f
getEntitySymbol :: Location -> Location -> SymType -> ParserMonad (Maybe EntityName)
getEntitySymbol _ _ (SEntity en) = return $ Just en
getEntitySymbol _ _ _ = return Nothing
symbolMatches :: String -> (SymType -> Bool) -> ParserMonad Bool
symbolMatches n f = do
syms <- gets psSyms
case Map.lookup n syms >>= return . (filter notReserved) of
Just ((Sym _ _ st):_) -> return $ f st
_ -> return False
requireClass :: (Class -> ParserMonad ()) -> (Location -> Location -> SymType -> ParserMonad ())
requireClass f = f'
where f' _ _ (SClass c) = f c
f' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected class)"
requireEntity :: (Entity -> ParserMonad ()) -> (Location -> Location -> SymType -> ParserMonad ())
requireEntity f = f'
where f' _ _ (SEntity en) = addEntityValidation (en, f)
f' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected entity)"
requireEntityResult :: (Entity -> ParserMonad ()) -> (Location -> Location -> SymType -> ParserMonad ())
requireEntityResult f = f'
where f' _ _ (SEntityResult en) = addEntityValidation (en, f)
f' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected get-entity)"
requireEntityOrClass :: (Location -> Location -> SymType -> ParserMonad ())
requireEntityOrClass = f'
where f' _ _ (SEntity _) = return ()
f' _ _ (SClass _) = return ()
f' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected entity or class)"
requireEntityId :: (EntityName -> ParserMonad (Maybe a)) -> (Location -> Location -> SymType -> ParserMonad (Maybe a))
requireEntityId f = f'
where f' _ _ (SEntityId en) = f en
f' l1 l2 st = pError l1 ("Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected entity id)") >> return Nothing
requireEnumName :: (EntityName -> ParserMonad (Maybe a)) -> (Location -> Location -> SymType -> ParserMonad (Maybe a))
requireEnumName f = f'
where f' _ _ (SEnumName en) = f en
f' l1 l2 st = pError l1 ("Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected enum name)") >> return Nothing
requireEntityField :: Location -> FieldName -> ((Entity,Field) -> ParserMonad ()) -> (Location -> Location -> SymType -> ParserMonad ())
requireEntityField l fn fun = fun'
where fun' _ _ (SEntity en) = addEntityValidation (en, \e ->
case L.find (\f -> fieldName f == fn) $ entityFields e ++ entityClassFields e of
Just f -> fun (e,f)
Nothing -> pError l ("Reference to undeclared field '"
++ fn ++ "' of entity '" ++ entityName e ++ "'"))
fun' l1 l2 st = pError l1 ( "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected entity)")
requireEntityFieldSelectedOrResult :: Location -> FieldName -> (Location -> Location -> SymType -> ParserMonad ())
requireEntityFieldSelectedOrResult l fn = fun'
where
fun' _ _ (SEntity en) = validate en
fun' _ _ (SEntityResult en) = validate en
fun' l1 l2 st = pError l1 ( "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected entity or get-entity)")
validate en = addEntityValidation (en, \e ->
case L.find (\f -> fieldName f == fn) $ entityFields e ++ entityClassFields e of
Just _ -> return ()
Nothing -> pError l ("Reference to undeclared field '"
++ fn ++ "' of entity '" ++ entityName e ++ "'"))
requireEnum :: Location -> Location -> SymType -> ParserMonad ()
requireEnum = fun'
where
fun' _ _ (SEnum e) = return ()
fun' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected enum)"
requireEnumValue :: Location -> EnumValue -> (Location -> Location -> SymType -> ParserMonad ())
requireEnumValue l ev = fun'
where
fun' _ _ (SEnum e) =
case L.find (\ev' -> ev' == ev) $ enumValues e of
Just _ -> return ()
Nothing -> pError l $ "Reference to undeclared enum value '"
++ ev ++ "' of enum '" ++ enumName e ++ "'"
fun' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected enum)"
requireParam :: (Location -> Location -> SymType -> ParserMonad ())
requireParam = fun'
where
fun' _ _ SParam = return ()
fun' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected param)"
requireField:: (Field -> ParserMonad ()) -> (Location -> Location -> SymType -> ParserMonad ())
requireField f = f'
where f' _ _ (SField sf) = f sf
f' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected field)"
requireFunction :: (Location -> Location -> SymType -> ParserMonad ())
requireFunction = fun'
where
fun' _ _ SFunction = return ()
fun' l1 l2 st = pError l1 $ "Reference to " ++ show st ++ " declared in " ++ show l2 ++ " (expected function)"
|
tlaitinen/yesod-dsl
|
YesodDsl/ParserState.hs
|
Haskell
|
bsd-2-clause
| 16,297
|
module HSH.Evaluate where
import HSH.CommandLineParse
import HSH.ShellState
import HSH.Exec
import Control.Monad
import Control.Monad.State
import System.IO
import qualified System.Environment as SysEnv
import qualified System.Posix.Directory as Posix
import qualified Data.Map as Map
import Data.Maybe
import Data.Foldable
import GHC.IO.Exception (ExitCode(..))
{-
- Command Evaluation
-}
-- | Evaluate a shell command abstract syntax tree.
evaluate :: ShellAST -> StateT ShellState IO ()
{- setenv -}
evaluate (SetEnv varname value) = do
candidateNewState <- setEnv varname value <$> get
newState <- if varname == "PATH"
then lift $ initialPathLoad candidateNewState
else return candidateNewState
put newState
{- getenv -}
evaluate (GetEnv varname) = do
env <- envVars <$> get
lift $ putStrLn $ fromMaybe
("Undefined environment variable '" ++ varname ++ "'.")
(Map.lookup varname env)
{- showstate -}
evaluate DebugState = get >>= lift . print
{- showparse -}
evaluate (ShowParse ast) = lift $ print ast
{- cd -}
evaluate (Chdir dir) = lift $ Posix.changeWorkingDirectory dir
{- Invoke external commands -}
evaluate (External command) = do
currentState <- get
(exitCode, messages) <- lift $ runExternalCommand command currentState
-- Report all execution errors
mapM_ (lift . hPutStrLn stderr) messages
-- Keep ${?} updated
put $ setEnv "?" (numericString exitCode) currentState
where
numericString ExitSuccess = numericString (ExitFailure 0)
numericString (ExitFailure num) = show num
{- REPL Functions -}
replEvaluate :: ShellAST -> StateT ShellState IO ()
replEvaluate ast = do
currentState <- get
newState <- lift $ refreshPath currentState
put newState
evaluate ast
-- | Read, evaluate, and print a single command.
rep :: StateT ShellState IO ()
rep = do
state <- get
lift $ putStr $ shellPrompt state
line <- lift getLine
case parseLine line state of
Just x -> replEvaluate x
Nothing -> lift $ hPutStrLn stderr "Parsing input line failed."
-- | Add looping to the REP.
repl :: StateT ShellState IO ()
repl = forever rep
-- | The 'clearEnv' function clears out the running process's ENV vars. This must be run
-- at shell start, otherwise 'System.Process.createProcess' will behave as if there is an
-- implicit merge between ShellState's envVars and the process's inherited `ENV`.
clearEnv :: IO ()
clearEnv = do
vars <- map fst <$> SysEnv.getEnvironment
traverse_ SysEnv.unsetEnv vars
-- | Run the Shell REPL.
runREPL :: IO ()
runREPL = do
hSetBuffering stdout NoBuffering
clearEnv
initialState <- initialPathLoad defaultShellState
evalStateT repl initialState
|
jessekempf/hsh
|
src/HSH/Evaluate.hs
|
Haskell
|
bsd-2-clause
| 2,746
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
Type checking of type signatures in interface files
-}
{-# LANGUAGE CPP #-}
module TcIface (
tcLookupImported_maybe,
importDecl, checkWiredInTyCon, tcHiBootIface, typecheckIface,
tcIfaceDecl, tcIfaceInst, tcIfaceFamInst, tcIfaceRules,
tcIfaceVectInfo, tcIfaceAnnotations,
tcIfaceExpr, -- Desired by HERMIT (Trac #7683)
tcIfaceGlobal
) where
#include "HsVersions.h"
import TcTypeNats(typeNatCoAxiomRules)
import IfaceSyn
import LoadIface
import IfaceEnv
import BuildTyCl
import TcRnMonad
import TcType
import Type
import Coercion
import CoAxiom
import TyCoRep -- needs to build types & coercions in a knot
import HscTypes
import Annotations
import InstEnv
import FamInstEnv
import CoreSyn
import CoreUtils
import CoreUnfold
import CoreLint
import MkCore
import Id
import MkId
import IdInfo
import Class
import TyCon
import ConLike
import DataCon
import PrelNames
import TysWiredIn
import Literal
import Var
import VarEnv
import VarSet
import Name
import NameEnv
import NameSet
import OccurAnal ( occurAnalyseExpr )
import Demand
import Module
import UniqFM
import UniqSupply
import Outputable
import Maybes
import SrcLoc
import DynFlags
import Util
import FastString
import BasicTypes hiding ( SuccessFlag(..) )
import ListSetOps
import Data.List
import Control.Monad
import qualified Data.Map as Map
{-
This module takes
IfaceDecl -> TyThing
IfaceType -> Type
etc
An IfaceDecl is populated with RdrNames, and these are not renamed to
Names before typechecking, because there should be no scope errors etc.
-- For (b) consider: f = \$(...h....)
-- where h is imported, and calls f via an hi-boot file.
-- This is bad! But it is not seen as a staging error, because h
-- is indeed imported. We don't want the type-checker to black-hole
-- when simplifying and compiling the splice!
--
-- Simple solution: discard any unfolding that mentions a variable
-- bound in this module (and hence not yet processed).
-- The discarding happens when forkM finds a type error.
************************************************************************
* *
Type-checking a complete interface
* *
************************************************************************
Suppose we discover we don't need to recompile. Then we must type
check the old interface file. This is a bit different to the
incremental type checking we do as we suck in interface files. Instead
we do things similarly as when we are typechecking source decls: we
bring into scope the type envt for the interface all at once, using a
knot. Remember, the decls aren't necessarily in dependency order --
and even if they were, the type decls might be mutually recursive.
-}
typecheckIface :: ModIface -- Get the decls from here
-> TcRnIf gbl lcl ModDetails
typecheckIface iface
= initIfaceTc iface $ \ tc_env_var -> do
-- The tc_env_var is freshly allocated, private to
-- type-checking this particular interface
{ -- Get the right set of decls and rules. If we are compiling without -O
-- we discard pragmas before typechecking, so that we don't "see"
-- information that we shouldn't. From a versioning point of view
-- It's not actually *wrong* to do so, but in fact GHCi is unable
-- to handle unboxed tuples, so it must not see unfoldings.
ignore_prags <- goptM Opt_IgnoreInterfacePragmas
-- Typecheck the decls. This is done lazily, so that the knot-tying
-- within this single module work out right. In the If monad there is
-- no global envt for the current interface; instead, the knot is tied
-- through the if_rec_types field of IfGblEnv
; names_w_things <- loadDecls ignore_prags (mi_decls iface)
; let type_env = mkNameEnv names_w_things
; writeMutVar tc_env_var type_env
-- Now do those rules, instances and annotations
; insts <- mapM tcIfaceInst (mi_insts iface)
; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
; rules <- tcIfaceRules ignore_prags (mi_rules iface)
; anns <- tcIfaceAnnotations (mi_anns iface)
-- Vectorisation information
; vect_info <- tcIfaceVectInfo (mi_module iface) type_env (mi_vect_info iface)
-- Exports
; exports <- ifaceExportNames (mi_exports iface)
-- Finished
; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
-- Careful! If we tug on the TyThing thunks too early
-- we'll infinite loop with hs-boot. See #10083 for
-- an example where this would cause non-termination.
text "Type envt:" <+> ppr (map fst names_w_things)])
; return $ ModDetails { md_types = type_env
, md_insts = insts
, md_fam_insts = fam_insts
, md_rules = rules
, md_anns = anns
, md_vect_info = vect_info
, md_exports = exports
}
}
{-
************************************************************************
* *
Type and class declarations
* *
************************************************************************
-}
tcHiBootIface :: HscSource -> Module -> TcRn SelfBootInfo
-- Load the hi-boot iface for the module being compiled,
-- if it indeed exists in the transitive closure of imports
-- Return the ModDetails; Nothing if no hi-boot iface
tcHiBootIface hsc_src mod
| HsBootFile <- hsc_src -- Already compiling a hs-boot file
= return NoSelfBoot
| otherwise
= do { traceIf (text "loadHiBootInterface" <+> ppr mod)
; mode <- getGhcMode
; if not (isOneShot mode)
-- In --make and interactive mode, if this module has an hs-boot file
-- we'll have compiled it already, and it'll be in the HPT
--
-- We check wheher the interface is a *boot* interface.
-- It can happen (when using GHC from Visual Studio) that we
-- compile a module in TypecheckOnly mode, with a stable,
-- fully-populated HPT. In that case the boot interface isn't there
-- (it's been replaced by the mother module) so we can't check it.
-- And that's fine, because if M's ModInfo is in the HPT, then
-- it's been compiled once, and we don't need to check the boot iface
then do { hpt <- getHpt
; case lookupHpt hpt (moduleName mod) of
Just info | mi_boot (hm_iface info)
-> return (mkSelfBootInfo (hm_details info))
_ -> return NoSelfBoot }
else do
-- OK, so we're in one-shot mode.
-- Re #9245, we always check if there is an hi-boot interface
-- to check consistency against, rather than just when we notice
-- that an hi-boot is necessary due to a circular import.
{ read_result <- findAndReadIface
need mod
True -- Hi-boot file
; case read_result of {
Succeeded (iface, _path) -> do { tc_iface <- typecheckIface iface
; return (mkSelfBootInfo tc_iface) } ;
Failed err ->
-- There was no hi-boot file. But if there is circularity in
-- the module graph, there really should have been one.
-- Since we've read all the direct imports by now,
-- eps_is_boot will record if any of our imports mention the
-- current module, which either means a module loop (not
-- a SOURCE import) or that our hi-boot file has mysteriously
-- disappeared.
do { eps <- getEps
; case lookupUFM (eps_is_boot eps) (moduleName mod) of
Nothing -> return NoSelfBoot -- The typical case
Just (_, False) -> failWithTc moduleLoop
-- Someone below us imported us!
-- This is a loop with no hi-boot in the way
Just (_mod, True) -> failWithTc (elaborate err)
-- The hi-boot file has mysteriously disappeared.
}}}}
where
need = text "Need the hi-boot interface for" <+> ppr mod
<+> text "to compare against the Real Thing"
moduleLoop = text "Circular imports: module" <+> quotes (ppr mod)
<+> text "depends on itself"
elaborate err = hang (text "Could not find hi-boot interface for" <+>
quotes (ppr mod) <> colon) 4 err
mkSelfBootInfo :: ModDetails -> SelfBootInfo
mkSelfBootInfo mds
= SelfBoot { sb_mds = mds
, sb_tcs = mkNameSet (map tyConName (typeEnvTyCons iface_env))
, sb_ids = mkNameSet (map idName (typeEnvIds iface_env)) }
where
iface_env = md_types mds
{-
************************************************************************
* *
Type and class declarations
* *
************************************************************************
When typechecking a data type decl, we *lazily* (via forkM) typecheck
the constructor argument types. This is in the hope that we may never
poke on those argument types, and hence may never need to load the
interface files for types mentioned in the arg types.
E.g.
data Foo.S = MkS Baz.T
Mabye we can get away without even loading the interface for Baz!
This is not just a performance thing. Suppose we have
data Foo.S = MkS Baz.T
data Baz.T = MkT Foo.S
(in different interface files, of course).
Now, first we load and typecheck Foo.S, and add it to the type envt.
If we do explore MkS's argument, we'll load and typecheck Baz.T.
If we explore MkT's argument we'll find Foo.S already in the envt.
If we typechecked constructor args eagerly, when loading Foo.S we'd try to
typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
which isn't done yet.
All very cunning. However, there is a rather subtle gotcha which bit
me when developing this stuff. When we typecheck the decl for S, we
extend the type envt with S, MkS, and all its implicit Ids. Suppose
(a bug, but it happened) that the list of implicit Ids depended in
turn on the constructor arg types. Then the following sequence of
events takes place:
* we build a thunk <t> for the constructor arg tys
* we build a thunk for the extended type environment (depends on <t>)
* we write the extended type envt into the global EPS mutvar
Now we look something up in the type envt
* that pulls on <t>
* which reads the global type envt out of the global EPS mutvar
* but that depends in turn on <t>
It's subtle, because, it'd work fine if we typechecked the constructor args
eagerly -- they don't need the extended type envt. They just get the extended
type envt by accident, because they look at it later.
What this means is that the implicitTyThings MUST NOT DEPEND on any of
the forkM stuff.
-}
tcIfaceDecl :: Bool -- ^ True <=> discard IdInfo on IfaceId bindings
-> IfaceDecl
-> IfL TyThing
tcIfaceDecl = tc_iface_decl Nothing
tc_iface_decl :: Maybe Class -- ^ For associated type/data family declarations
-> Bool -- ^ True <=> discard IdInfo on IfaceId bindings
-> IfaceDecl
-> IfL TyThing
tc_iface_decl _ ignore_prags (IfaceId {ifName = occ_name, ifType = iface_type,
ifIdDetails = details, ifIdInfo = info})
= do { name <- lookupIfaceTop occ_name
; ty <- tcIfaceType iface_type
; details <- tcIdDetails ty details
; info <- tcIdInfo ignore_prags name ty info
; return (AnId (mkGlobalId details name ty info)) }
tc_iface_decl _ _ (IfaceData {ifName = occ_name,
ifCType = cType,
ifBinders = binders,
ifResKind = res_kind,
ifRoles = roles,
ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
ifCons = rdr_cons,
ifParent = mb_parent })
= bindIfaceTyConBinders_AT binders $ \ binders' -> do
{ tc_name <- lookupIfaceTop occ_name
; res_kind' <- tcIfaceType res_kind
; tycon <- fixM $ \ tycon -> do
{ stupid_theta <- tcIfaceCtxt ctxt
; parent' <- tc_parent tc_name mb_parent
; cons <- tcIfaceDataCons tc_name tycon binders' rdr_cons
; return (mkAlgTyCon tc_name binders' res_kind'
roles cType stupid_theta
cons parent' gadt_syn) }
; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
; return (ATyCon tycon) }
where
tc_parent :: Name -> IfaceTyConParent -> IfL AlgTyConFlav
tc_parent tc_name IfNoParent
= do { tc_rep_name <- newTyConRepName tc_name
; return (VanillaAlgTyCon tc_rep_name) }
tc_parent _ (IfDataInstance ax_name _ arg_tys)
= do { ax <- tcIfaceCoAxiom ax_name
; let fam_tc = coAxiomTyCon ax
ax_unbr = toUnbranchedAxiom ax
; lhs_tys <- tcIfaceTcArgs arg_tys
; return (DataFamInstTyCon ax_unbr fam_tc lhs_tys) }
tc_iface_decl _ _ (IfaceSynonym {ifName = occ_name,
ifRoles = roles,
ifSynRhs = rhs_ty,
ifBinders = binders,
ifResKind = res_kind })
= bindIfaceTyConBinders_AT binders $ \ binders' -> do
{ tc_name <- lookupIfaceTop occ_name
; res_kind' <- tcIfaceType res_kind -- Note [Synonym kind loop]
; rhs <- forkM (mk_doc tc_name) $
tcIfaceType rhs_ty
; let tycon = mkSynonymTyCon tc_name binders' res_kind' roles rhs
; return (ATyCon tycon) }
where
mk_doc n = text "Type synonym" <+> ppr n
tc_iface_decl parent _ (IfaceFamily {ifName = occ_name,
ifFamFlav = fam_flav,
ifBinders = binders,
ifResKind = res_kind,
ifResVar = res, ifFamInj = inj })
= bindIfaceTyConBinders_AT binders $ \ binders' -> do
{ tc_name <- lookupIfaceTop occ_name
; res_kind' <- tcIfaceType res_kind -- Note [Synonym kind loop]
; rhs <- forkM (mk_doc tc_name) $
tc_fam_flav tc_name fam_flav
; res_name <- traverse (newIfaceName . mkTyVarOccFS) res
; let tycon = mkFamilyTyCon tc_name binders' res_kind' res_name rhs parent inj
; return (ATyCon tycon) }
where
mk_doc n = text "Type synonym" <+> ppr n
tc_fam_flav :: Name -> IfaceFamTyConFlav -> IfL FamTyConFlav
tc_fam_flav tc_name IfaceDataFamilyTyCon
= do { tc_rep_name <- newTyConRepName tc_name
; return (DataFamilyTyCon tc_rep_name) }
tc_fam_flav _ IfaceOpenSynFamilyTyCon= return OpenSynFamilyTyCon
tc_fam_flav _ (IfaceClosedSynFamilyTyCon mb_ax_name_branches)
= do { ax <- traverse (tcIfaceCoAxiom . fst) mb_ax_name_branches
; return (ClosedSynFamilyTyCon ax) }
tc_fam_flav _ IfaceAbstractClosedSynFamilyTyCon
= return AbstractClosedSynFamilyTyCon
tc_fam_flav _ IfaceBuiltInSynFamTyCon
= pprPanic "tc_iface_decl"
(text "IfaceBuiltInSynFamTyCon in interface file")
tc_iface_decl _parent ignore_prags
(IfaceClass {ifCtxt = rdr_ctxt, ifName = tc_occ,
ifRoles = roles,
ifBinders = binders,
ifFDs = rdr_fds,
ifATs = rdr_ats, ifSigs = rdr_sigs,
ifMinDef = mindef_occ })
-- ToDo: in hs-boot files we should really treat abstract classes specially,
-- as we do abstract tycons
= bindIfaceTyConBinders binders $ \ binders' -> do
{ tc_name <- lookupIfaceTop tc_occ
; traceIf (text "tc-iface-class1" <+> ppr tc_occ)
; ctxt <- mapM tc_sc rdr_ctxt
; traceIf (text "tc-iface-class2" <+> ppr tc_occ)
; sigs <- mapM tc_sig rdr_sigs
; fds <- mapM tc_fd rdr_fds
; traceIf (text "tc-iface-class3" <+> ppr tc_occ)
; mindef <- traverse (lookupIfaceTop . mkVarOccFS) mindef_occ
; cls <- fixM $ \ cls -> do
{ ats <- mapM (tc_at cls) rdr_ats
; traceIf (text "tc-iface-class4" <+> ppr tc_occ)
; buildClass tc_name binders' roles ctxt fds ats sigs mindef }
; return (ATyCon (classTyCon cls)) }
where
tc_sc pred = forkM (mk_sc_doc pred) (tcIfaceType pred)
-- The *length* of the superclasses is used by buildClass, and hence must
-- not be inside the thunk. But the *content* maybe recursive and hence
-- must be lazy (via forkM). Example:
-- class C (T a) => D a where
-- data T a
-- Here the associated type T is knot-tied with the class, and
-- so we must not pull on T too eagerly. See Trac #5970
tc_sig :: IfaceClassOp -> IfL TcMethInfo
tc_sig (IfaceClassOp occ rdr_ty dm)
= do { op_name <- lookupIfaceTop occ
; let doc = mk_op_doc op_name rdr_ty
; op_ty <- forkM (doc <+> text "ty") $ tcIfaceType rdr_ty
-- Must be done lazily for just the same reason as the
-- type of a data con; to avoid sucking in types that
-- it mentions unless it's necessary to do so
; dm' <- tc_dm doc dm
; return (op_name, op_ty, dm') }
tc_dm :: SDoc
-> Maybe (DefMethSpec IfaceType)
-> IfL (Maybe (DefMethSpec (SrcSpan, Type)))
tc_dm _ Nothing = return Nothing
tc_dm _ (Just VanillaDM) = return (Just VanillaDM)
tc_dm doc (Just (GenericDM ty))
= do { -- Must be done lazily to avoid sucking in types
; ty' <- forkM (doc <+> text "dm") $ tcIfaceType ty
; return (Just (GenericDM (noSrcSpan, ty'))) }
tc_at cls (IfaceAT tc_decl if_def)
= do ATyCon tc <- tc_iface_decl (Just cls) ignore_prags tc_decl
mb_def <- case if_def of
Nothing -> return Nothing
Just def -> forkM (mk_at_doc tc) $
extendIfaceTyVarEnv (tyConTyVars tc) $
do { tc_def <- tcIfaceType def
; return (Just (tc_def, noSrcSpan)) }
-- Must be done lazily in case the RHS of the defaults mention
-- the type constructor being defined here
-- e.g. type AT a; type AT b = AT [b] Trac #8002
return (ATI tc mb_def)
mk_sc_doc pred = text "Superclass" <+> ppr pred
mk_at_doc tc = text "Associated type" <+> ppr tc
mk_op_doc op_name op_ty = text "Class op" <+> sep [ppr op_name, ppr op_ty]
tc_fd (tvs1, tvs2) = do { tvs1' <- mapM tcIfaceTyVar tvs1
; tvs2' <- mapM tcIfaceTyVar tvs2
; return (tvs1', tvs2') }
tc_iface_decl _ _ (IfaceAxiom { ifName = ax_occ, ifTyCon = tc
, ifAxBranches = branches, ifRole = role })
= do { tc_name <- lookupIfaceTop ax_occ
; tc_tycon <- tcIfaceTyCon tc
; tc_branches <- tc_ax_branches branches
; let axiom = CoAxiom { co_ax_unique = nameUnique tc_name
, co_ax_name = tc_name
, co_ax_tc = tc_tycon
, co_ax_role = role
, co_ax_branches = manyBranches tc_branches
, co_ax_implicit = False }
; return (ACoAxiom axiom) }
tc_iface_decl _ _ (IfacePatSyn{ ifName = occ_name
, ifPatMatcher = if_matcher
, ifPatBuilder = if_builder
, ifPatIsInfix = is_infix
, ifPatUnivBndrs = univ_bndrs
, ifPatExBndrs = ex_bndrs
, ifPatProvCtxt = prov_ctxt
, ifPatReqCtxt = req_ctxt
, ifPatArgs = args
, ifPatTy = pat_ty
, ifFieldLabels = field_labels })
= do { name <- lookupIfaceTop occ_name
; traceIf (text "tc_iface_decl" <+> ppr name)
; matcher <- tc_pr if_matcher
; builder <- fmapMaybeM tc_pr if_builder
; bindIfaceForAllBndrs univ_bndrs $ \univ_tvs -> do
{ bindIfaceForAllBndrs ex_bndrs $ \ex_tvs -> do
{ patsyn <- forkM (mk_doc name) $
do { prov_theta <- tcIfaceCtxt prov_ctxt
; req_theta <- tcIfaceCtxt req_ctxt
; pat_ty <- tcIfaceType pat_ty
; arg_tys <- mapM tcIfaceType args
; return $ buildPatSyn name is_infix matcher builder
(univ_tvs, req_theta)
(ex_tvs, prov_theta)
arg_tys pat_ty field_labels }
; return $ AConLike . PatSynCon $ patsyn }}}
where
mk_doc n = text "Pattern synonym" <+> ppr n
tc_pr :: (IfExtName, Bool) -> IfL (Id, Bool)
tc_pr (nm, b) = do { id <- forkM (ppr nm) (tcIfaceExtId nm)
; return (id, b) }
tc_ax_branches :: [IfaceAxBranch] -> IfL [CoAxBranch]
tc_ax_branches if_branches = foldlM tc_ax_branch [] if_branches
tc_ax_branch :: [CoAxBranch] -> IfaceAxBranch -> IfL [CoAxBranch]
tc_ax_branch prev_branches
(IfaceAxBranch { ifaxbTyVars = tv_bndrs, ifaxbCoVars = cv_bndrs
, ifaxbLHS = lhs, ifaxbRHS = rhs
, ifaxbRoles = roles, ifaxbIncomps = incomps })
= bindIfaceTyConBinders_AT
(map (\b -> TvBndr b (NamedTCB Inferred)) tv_bndrs) $ \ tvs ->
-- The _AT variant is needed here; see Note [CoAxBranch type variables] in CoAxiom
bindIfaceIds cv_bndrs $ \ cvs -> do
{ tc_lhs <- tcIfaceTcArgs lhs
; tc_rhs <- tcIfaceType rhs
; let br = CoAxBranch { cab_loc = noSrcSpan
, cab_tvs = binderVars tvs
, cab_cvs = cvs
, cab_lhs = tc_lhs
, cab_roles = roles
, cab_rhs = tc_rhs
, cab_incomps = map (prev_branches `getNth`) incomps }
; return (prev_branches ++ [br]) }
tcIfaceDataCons :: Name -> TyCon -> [TyConBinder] -> IfaceConDecls -> IfL AlgTyConRhs
tcIfaceDataCons tycon_name tycon tc_tybinders if_cons
= case if_cons of
IfAbstractTyCon dis -> return (AbstractTyCon dis)
IfDataTyCon cons _ _ -> do { field_lbls <- mapM (traverse lookupIfaceTop) (ifaceConDeclFields if_cons)
; data_cons <- mapM (tc_con_decl field_lbls) cons
; return (mkDataTyConRhs data_cons) }
IfNewTyCon con _ _ -> do { field_lbls <- mapM (traverse lookupIfaceTop) (ifaceConDeclFields if_cons)
; data_con <- tc_con_decl field_lbls con
; mkNewTyConRhs tycon_name tycon data_con }
where
univ_tv_bndrs :: [TyVarBinder]
univ_tv_bndrs = mkDataConUnivTyVarBinders tc_tybinders
tc_con_decl field_lbls (IfCon { ifConInfix = is_infix,
ifConExTvs = ex_bndrs,
ifConOcc = occ, ifConCtxt = ctxt, ifConEqSpec = spec,
ifConArgTys = args, ifConFields = my_lbls,
ifConStricts = if_stricts,
ifConSrcStricts = if_src_stricts})
= -- Universally-quantified tyvars are shared with
-- parent TyCon, and are alrady in scope
bindIfaceForAllBndrs ex_bndrs $ \ ex_tv_bndrs -> do
{ traceIf (text "Start interface-file tc_con_decl" <+> ppr occ)
; dc_name <- lookupIfaceTop occ
-- Read the context and argument types, but lazily for two reasons
-- (a) to avoid looking tugging on a recursive use of
-- the type itself, which is knot-tied
-- (b) to avoid faulting in the component types unless
-- they are really needed
; ~(eq_spec, theta, arg_tys, stricts) <- forkM (mk_doc dc_name) $
do { eq_spec <- tcIfaceEqSpec spec
; theta <- tcIfaceCtxt ctxt
; arg_tys <- mapM tcIfaceType args
; stricts <- mapM tc_strict if_stricts
-- The IfBang field can mention
-- the type itself; hence inside forkM
; return (eq_spec, theta, arg_tys, stricts) }
-- Look up the field labels for this constructor; note that
-- they should be in the same order as my_lbls!
; let lbl_names = map find_lbl my_lbls
find_lbl x = case find (\ fl -> nameOccName (flSelector fl) == x) field_lbls of
Just fl -> fl
Nothing -> error $ "find_lbl missing " ++ occNameString x
-- Remember, tycon is the representation tycon
; let orig_res_ty = mkFamilyTyConApp tycon
(substTyVars (mkTvSubstPrs (map eqSpecPair eq_spec))
(binderVars tc_tybinders))
; prom_rep_name <- newTyConRepName dc_name
; con <- buildDataCon (pprPanic "tcIfaceDataCons: FamInstEnvs" (ppr dc_name))
dc_name is_infix prom_rep_name
(map src_strict if_src_stricts)
(Just stricts)
-- Pass the HsImplBangs (i.e. final
-- decisions) to buildDataCon; it'll use
-- these to guide the construction of a
-- worker.
-- See Note [Bangs on imported data constructors] in MkId
lbl_names
univ_tv_bndrs ex_tv_bndrs
eq_spec theta
arg_tys orig_res_ty tycon
; traceIf (text "Done interface-file tc_con_decl" <+> ppr dc_name)
; return con }
mk_doc con_name = text "Constructor" <+> ppr con_name
tc_strict :: IfaceBang -> IfL HsImplBang
tc_strict IfNoBang = return (HsLazy)
tc_strict IfStrict = return (HsStrict)
tc_strict IfUnpack = return (HsUnpack Nothing)
tc_strict (IfUnpackCo if_co) = do { co <- tcIfaceCo if_co
; return (HsUnpack (Just co)) }
src_strict :: IfaceSrcBang -> HsSrcBang
src_strict (IfSrcBang unpk bang) = HsSrcBang Nothing unpk bang
tcIfaceEqSpec :: IfaceEqSpec -> IfL [EqSpec]
tcIfaceEqSpec spec
= mapM do_item spec
where
do_item (occ, if_ty) = do { tv <- tcIfaceTyVar occ
; ty <- tcIfaceType if_ty
; return (mkEqSpec tv ty) }
{-
Note [Synonym kind loop]
~~~~~~~~~~~~~~~~~~~~~~~~
Notice that we eagerly grab the *kind* from the interface file, but
build a forkM thunk for the *rhs* (and family stuff). To see why,
consider this (Trac #2412)
M.hs: module M where { import X; data T = MkT S }
X.hs: module X where { import {-# SOURCE #-} M; type S = T }
M.hs-boot: module M where { data T }
When kind-checking M.hs we need S's kind. But we do not want to
find S's kind from (typeKind S-rhs), because we don't want to look at
S-rhs yet! Since S is imported from X.hi, S gets just one chance to
be defined, and we must not do that until we've finished with M.T.
Solution: record S's kind in the interface file; now we can safely
look at it.
************************************************************************
* *
Instances
* *
************************************************************************
-}
tcIfaceInst :: IfaceClsInst -> IfL ClsInst
tcIfaceInst (IfaceClsInst { ifDFun = dfun_occ, ifOFlag = oflag
, ifInstCls = cls, ifInstTys = mb_tcs
, ifInstOrph = orph })
= do { dfun <- forkM (text "Dict fun" <+> ppr dfun_occ) $
tcIfaceExtId dfun_occ
; let mb_tcs' = map (fmap ifaceTyConName) mb_tcs
; return (mkImportedInstance cls mb_tcs' dfun oflag orph) }
tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
tcIfaceFamInst (IfaceFamInst { ifFamInstFam = fam, ifFamInstTys = mb_tcs
, ifFamInstAxiom = axiom_name } )
= do { axiom' <- forkM (text "Axiom" <+> ppr axiom_name) $
tcIfaceCoAxiom axiom_name
-- will panic if branched, but that's OK
; let axiom'' = toUnbranchedAxiom axiom'
mb_tcs' = map (fmap ifaceTyConName) mb_tcs
; return (mkImportedFamInst fam mb_tcs' axiom'') }
{-
************************************************************************
* *
Rules
* *
************************************************************************
We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
are in the type environment. However, remember that typechecking a Rule may
(as a side effect) augment the type envt, and so we may need to iterate the process.
-}
tcIfaceRules :: Bool -- True <=> ignore rules
-> [IfaceRule]
-> IfL [CoreRule]
tcIfaceRules ignore_prags if_rules
| ignore_prags = return []
| otherwise = mapM tcIfaceRule if_rules
tcIfaceRule :: IfaceRule -> IfL CoreRule
tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
ifRuleAuto = auto, ifRuleOrph = orph })
= do { ~(bndrs', args', rhs') <-
-- Typecheck the payload lazily, in the hope it'll never be looked at
forkM (text "Rule" <+> pprRuleName name) $
bindIfaceBndrs bndrs $ \ bndrs' ->
do { args' <- mapM tcIfaceExpr args
; rhs' <- tcIfaceExpr rhs
; return (bndrs', args', rhs') }
; let mb_tcs = map ifTopFreeName args
; this_mod <- getIfModule
; return (Rule { ru_name = name, ru_fn = fn, ru_act = act,
ru_bndrs = bndrs', ru_args = args',
ru_rhs = occurAnalyseExpr rhs',
ru_rough = mb_tcs,
ru_origin = this_mod,
ru_orphan = orph,
ru_auto = auto,
ru_local = False }) } -- An imported RULE is never for a local Id
-- or, even if it is (module loop, perhaps)
-- we'll just leave it in the non-local set
where
-- This function *must* mirror exactly what Rules.roughTopNames does
-- We could have stored the ru_rough field in the iface file
-- but that would be redundant, I think.
-- The only wrinkle is that we must not be deceived by
-- type synonyms at the top of a type arg. Since
-- we can't tell at this point, we are careful not
-- to write them out in coreRuleToIfaceRule
ifTopFreeName :: IfaceExpr -> Maybe Name
ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
ifTopFreeName (IfaceType (IfaceTupleTy s _ ts)) = Just (tupleTyConName s (length (tcArgsIfaceTypes ts)))
ifTopFreeName (IfaceApp f _) = ifTopFreeName f
ifTopFreeName (IfaceExt n) = Just n
ifTopFreeName _ = Nothing
{-
************************************************************************
* *
Annotations
* *
************************************************************************
-}
tcIfaceAnnotations :: [IfaceAnnotation] -> IfL [Annotation]
tcIfaceAnnotations = mapM tcIfaceAnnotation
tcIfaceAnnotation :: IfaceAnnotation -> IfL Annotation
tcIfaceAnnotation (IfaceAnnotation target serialized) = do
target' <- tcIfaceAnnTarget target
return $ Annotation {
ann_target = target',
ann_value = serialized
}
tcIfaceAnnTarget :: IfaceAnnTarget -> IfL (AnnTarget Name)
tcIfaceAnnTarget (NamedTarget occ) = do
name <- lookupIfaceTop occ
return $ NamedTarget name
tcIfaceAnnTarget (ModuleTarget mod) = do
return $ ModuleTarget mod
{-
************************************************************************
* *
Vectorisation information
* *
************************************************************************
-}
-- We need access to the type environment as we need to look up information about type constructors
-- (i.e., their data constructors and whether they are class type constructors). If a vectorised
-- type constructor or class is defined in the same module as where it is vectorised, we cannot
-- look that information up from the type constructor that we obtained via a 'forkM'ed
-- 'tcIfaceTyCon' without recursively loading the interface that we are already type checking again
-- and again and again...
--
tcIfaceVectInfo :: Module -> TypeEnv -> IfaceVectInfo -> IfL VectInfo
tcIfaceVectInfo mod typeEnv (IfaceVectInfo
{ ifaceVectInfoVar = vars
, ifaceVectInfoTyCon = tycons
, ifaceVectInfoTyConReuse = tyconsReuse
, ifaceVectInfoParallelVars = parallelVars
, ifaceVectInfoParallelTyCons = parallelTyCons
})
= do { let parallelTyConsSet = mkNameSet parallelTyCons
; vVars <- mapM vectVarMapping vars
; let varsSet = mkVarSet (map fst vVars)
; tyConRes1 <- mapM (vectTyConVectMapping varsSet) tycons
; tyConRes2 <- mapM (vectTyConReuseMapping varsSet) tyconsReuse
; vParallelVars <- mapM vectVar parallelVars
; let (vTyCons, vDataCons, vScSels) = unzip3 (tyConRes1 ++ tyConRes2)
; return $ VectInfo
{ vectInfoVar = mkDVarEnv vVars `extendDVarEnvList` concat vScSels
, vectInfoTyCon = mkNameEnv vTyCons
, vectInfoDataCon = mkNameEnv (concat vDataCons)
, vectInfoParallelVars = mkDVarSet vParallelVars
, vectInfoParallelTyCons = parallelTyConsSet
}
}
where
vectVarMapping name
= do { vName <- lookupIfaceTop (mkLocalisedOccName mod mkVectOcc name)
; var <- forkM (text "vect var" <+> ppr name) $
tcIfaceExtId name
; vVar <- forkM (text "vect vVar [mod =" <+>
ppr mod <> text "; nameModule =" <+>
ppr (nameModule name) <> text "]" <+> ppr vName) $
tcIfaceExtId vName
; return (var, (var, vVar))
}
-- where
-- lookupLocalOrExternalId name
-- = do { let mb_id = lookupTypeEnv typeEnv name
-- ; case mb_id of
-- -- id is local
-- Just (AnId id) -> return id
-- -- name is not an Id => internal inconsistency
-- Just _ -> notAnIdErr
-- -- Id is external
-- Nothing -> tcIfaceExtId name
-- }
--
-- notAnIdErr = pprPanic "TcIface.tcIfaceVectInfo: not an id" (ppr name)
vectVar name
= forkM (text "vect scalar var" <+> ppr name) $
tcIfaceExtId name
vectTyConVectMapping vars name
= do { vName <- lookupIfaceTop (mkLocalisedOccName mod mkVectTyConOcc name)
; vectTyConMapping vars name vName
}
vectTyConReuseMapping vars name
= vectTyConMapping vars name name
vectTyConMapping vars name vName
= do { tycon <- lookupLocalOrExternalTyCon name
; vTycon <- forkM (text "vTycon of" <+> ppr vName) $
lookupLocalOrExternalTyCon vName
-- Map the data constructors of the original type constructor to those of the
-- vectorised type constructor /unless/ the type constructor was vectorised
-- abstractly; if it was vectorised abstractly, the workers of its data constructors
-- do not appear in the set of vectorised variables.
--
-- NB: This is lazy! We don't pull at the type constructors before we actually use
-- the data constructor mapping.
; let isAbstract | isClassTyCon tycon = False
| datacon:_ <- tyConDataCons tycon
= not $ dataConWrapId datacon `elemVarSet` vars
| otherwise = True
vDataCons | isAbstract = []
| otherwise = [ (dataConName datacon, (datacon, vDatacon))
| (datacon, vDatacon) <- zip (tyConDataCons tycon)
(tyConDataCons vTycon)
]
-- Map the (implicit) superclass and methods selectors as they don't occur in
-- the var map.
vScSels | Just cls <- tyConClass_maybe tycon
, Just vCls <- tyConClass_maybe vTycon
= [ (sel, (sel, vSel))
| (sel, vSel) <- zip (classAllSelIds cls) (classAllSelIds vCls)
]
| otherwise
= []
; return ( (name, (tycon, vTycon)) -- (T, T_v)
, vDataCons -- list of (Ci, Ci_v)
, vScSels -- list of (seli, seli_v)
)
}
where
-- we need a fully defined version of the type constructor to be able to extract
-- its data constructors etc.
lookupLocalOrExternalTyCon name
= do { let mb_tycon = lookupTypeEnv typeEnv name
; case mb_tycon of
-- tycon is local
Just (ATyCon tycon) -> return tycon
-- name is not a tycon => internal inconsistency
Just _ -> notATyConErr
-- tycon is external
Nothing -> tcIfaceTyConByName name
}
notATyConErr = pprPanic "TcIface.tcIfaceVectInfo: not a tycon" (ppr name)
{-
************************************************************************
* *
Types
* *
************************************************************************
-}
tcIfaceType :: IfaceType -> IfL Type
tcIfaceType = go
where
go (IfaceTyVar n) = TyVarTy <$> tcIfaceTyVar n
go (IfaceAppTy t1 t2) = AppTy <$> go t1 <*> go t2
go (IfaceLitTy l) = LitTy <$> tcIfaceTyLit l
go (IfaceFunTy t1 t2) = FunTy <$> go t1 <*> go t2
go (IfaceDFunTy t1 t2) = FunTy <$> go t1 <*> go t2
go (IfaceTupleTy s i tks) = tcIfaceTupleTy s i tks
go (IfaceTyConApp tc tks)
= do { tc' <- tcIfaceTyCon tc
; tks' <- mapM go (tcArgsIfaceTypes tks)
; return (mkTyConApp tc' tks') }
go (IfaceForAllTy bndr t)
= bindIfaceForAllBndr bndr $ \ tv' vis ->
ForAllTy (TvBndr tv' vis) <$> go t
go (IfaceCastTy ty co) = CastTy <$> go ty <*> tcIfaceCo co
go (IfaceCoercionTy co) = CoercionTy <$> tcIfaceCo co
tcIfaceTupleTy :: TupleSort -> IfaceTyConInfo -> IfaceTcArgs -> IfL Type
tcIfaceTupleTy sort info args
= do { args' <- tcIfaceTcArgs args
; let arity = length args'
; base_tc <- tcTupleTyCon True sort arity
; case info of
NoIfaceTyConInfo
-> return (mkTyConApp base_tc args')
IfacePromotedDataCon
-> do { let tc = promoteDataCon (tyConSingleDataCon base_tc)
kind_args = map typeKind args'
; return (mkTyConApp tc (kind_args ++ args')) } }
-- See Note [Unboxed tuple RuntimeRep vars] in TyCon
tcTupleTyCon :: Bool -- True <=> typechecking a *type* (vs. an expr)
-> TupleSort
-> Arity -- the number of args. *not* the tuple arity.
-> IfL TyCon
tcTupleTyCon in_type sort arity
= case sort of
ConstraintTuple -> do { thing <- tcIfaceGlobal (cTupleTyConName arity)
; return (tyThingTyCon thing) }
BoxedTuple -> return (tupleTyCon Boxed arity)
UnboxedTuple -> return (tupleTyCon Unboxed arity')
where arity' | in_type = arity `div` 2
| otherwise = arity
-- in expressions, we only have term args
tcIfaceTcArgs :: IfaceTcArgs -> IfL [Type]
tcIfaceTcArgs = mapM tcIfaceType . tcArgsIfaceTypes
-----------------------------------------
tcIfaceCtxt :: IfaceContext -> IfL ThetaType
tcIfaceCtxt sts = mapM tcIfaceType sts
-----------------------------------------
tcIfaceTyLit :: IfaceTyLit -> IfL TyLit
tcIfaceTyLit (IfaceNumTyLit n) = return (NumTyLit n)
tcIfaceTyLit (IfaceStrTyLit n) = return (StrTyLit n)
{-
%************************************************************************
%* *
Coercions
* *
************************************************************************
-}
tcIfaceCo :: IfaceCoercion -> IfL Coercion
tcIfaceCo = go
where
go (IfaceReflCo r t) = Refl r <$> tcIfaceType t
go (IfaceFunCo r c1 c2) = mkFunCo r <$> go c1 <*> go c2
go (IfaceTyConAppCo r tc cs)
= TyConAppCo r <$> tcIfaceTyCon tc <*> mapM go cs
go (IfaceAppCo c1 c2) = AppCo <$> go c1 <*> go c2
go (IfaceForAllCo tv k c) = do { k' <- go k
; bindIfaceTyVar tv $ \ tv' ->
ForAllCo tv' k' <$> go c }
go (IfaceCoVarCo n) = CoVarCo <$> go_var n
go (IfaceAxiomInstCo n i cs) = AxiomInstCo <$> tcIfaceCoAxiom n <*> pure i <*> mapM go cs
go (IfaceUnivCo p r t1 t2) = UnivCo <$> tcIfaceUnivCoProv p <*> pure r
<*> tcIfaceType t1 <*> tcIfaceType t2
go (IfaceSymCo c) = SymCo <$> go c
go (IfaceTransCo c1 c2) = TransCo <$> go c1
<*> go c2
go (IfaceInstCo c1 t2) = InstCo <$> go c1
<*> go t2
go (IfaceNthCo d c) = NthCo d <$> go c
go (IfaceLRCo lr c) = LRCo lr <$> go c
go (IfaceCoherenceCo c1 c2) = CoherenceCo <$> go c1
<*> go c2
go (IfaceKindCo c) = KindCo <$> go c
go (IfaceSubCo c) = SubCo <$> go c
go (IfaceAxiomRuleCo ax cos) = AxiomRuleCo <$> go_axiom_rule ax
<*> mapM go cos
go_var :: FastString -> IfL CoVar
go_var = tcIfaceLclId
go_axiom_rule :: FastString -> IfL CoAxiomRule
go_axiom_rule n =
case Map.lookup n typeNatCoAxiomRules of
Just ax -> return ax
_ -> pprPanic "go_axiom_rule" (ppr n)
tcIfaceUnivCoProv :: IfaceUnivCoProv -> IfL UnivCoProvenance
tcIfaceUnivCoProv IfaceUnsafeCoerceProv = return UnsafeCoerceProv
tcIfaceUnivCoProv (IfacePhantomProv kco) = PhantomProv <$> tcIfaceCo kco
tcIfaceUnivCoProv (IfaceProofIrrelProv kco) = ProofIrrelProv <$> tcIfaceCo kco
tcIfaceUnivCoProv (IfacePluginProv str) = return $ PluginProv str
{-
************************************************************************
* *
Core
* *
************************************************************************
-}
tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
tcIfaceExpr (IfaceType ty)
= Type <$> tcIfaceType ty
tcIfaceExpr (IfaceCo co)
= Coercion <$> tcIfaceCo co
tcIfaceExpr (IfaceCast expr co)
= Cast <$> tcIfaceExpr expr <*> tcIfaceCo co
tcIfaceExpr (IfaceLcl name)
= Var <$> tcIfaceLclId name
tcIfaceExpr (IfaceExt gbl)
= Var <$> tcIfaceExtId gbl
tcIfaceExpr (IfaceLit lit)
= do lit' <- tcIfaceLit lit
return (Lit lit')
tcIfaceExpr (IfaceFCall cc ty) = do
ty' <- tcIfaceType ty
u <- newUnique
dflags <- getDynFlags
return (Var (mkFCallId dflags u cc ty'))
tcIfaceExpr (IfaceTuple sort args)
= do { args' <- mapM tcIfaceExpr args
; tc <- tcTupleTyCon False sort arity
; let con_tys = map exprType args'
some_con_args = map Type con_tys ++ args'
con_args = case sort of
UnboxedTuple -> map (Type . getRuntimeRep "tcIfaceExpr") con_tys ++ some_con_args
_ -> some_con_args
-- Put the missing type arguments back in
con_id = dataConWorkId (tyConSingleDataCon tc)
; return (mkApps (Var con_id) con_args) }
where
arity = length args
tcIfaceExpr (IfaceLam (bndr, os) body)
= bindIfaceBndr bndr $ \bndr' ->
Lam (tcIfaceOneShot os bndr') <$> tcIfaceExpr body
where
tcIfaceOneShot IfaceOneShot b = setOneShotLambda b
tcIfaceOneShot _ b = b
tcIfaceExpr (IfaceApp fun arg)
= App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
tcIfaceExpr (IfaceECase scrut ty)
= do { scrut' <- tcIfaceExpr scrut
; ty' <- tcIfaceType ty
; return (castBottomExpr scrut' ty') }
tcIfaceExpr (IfaceCase scrut case_bndr alts) = do
scrut' <- tcIfaceExpr scrut
case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
let
scrut_ty = exprType scrut'
case_bndr' = mkLocalIdOrCoVar case_bndr_name scrut_ty
tc_app = splitTyConApp scrut_ty
-- NB: Won't always succeed (polymorphic case)
-- but won't be demanded in those cases
-- NB: not tcSplitTyConApp; we are looking at Core here
-- look through non-rec newtypes to find the tycon that
-- corresponds to the datacon in this case alternative
extendIfaceIdEnv [case_bndr'] $ do
alts' <- mapM (tcIfaceAlt scrut' tc_app) alts
return (Case scrut' case_bndr' (coreAltsType alts') alts')
tcIfaceExpr (IfaceLet (IfaceNonRec (IfLetBndr fs ty info) rhs) body)
= do { name <- newIfaceName (mkVarOccFS fs)
; ty' <- tcIfaceType ty
; id_info <- tcIdInfo False {- Don't ignore prags; we are inside one! -}
name ty' info
; let id = mkLocalIdOrCoVarWithInfo name ty' id_info
; rhs' <- tcIfaceExpr rhs
; body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
; return (Let (NonRec id rhs') body') }
tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
= do { ids <- mapM tc_rec_bndr (map fst pairs)
; extendIfaceIdEnv ids $ do
{ pairs' <- zipWithM tc_pair pairs ids
; body' <- tcIfaceExpr body
; return (Let (Rec pairs') body') } }
where
tc_rec_bndr (IfLetBndr fs ty _)
= do { name <- newIfaceName (mkVarOccFS fs)
; ty' <- tcIfaceType ty
; return (mkLocalIdOrCoVar name ty') }
tc_pair (IfLetBndr _ _ info, rhs) id
= do { rhs' <- tcIfaceExpr rhs
; id_info <- tcIdInfo False {- Don't ignore prags; we are inside one! -}
(idName id) (idType id) info
; return (setIdInfo id id_info, rhs') }
tcIfaceExpr (IfaceTick tickish expr) = do
expr' <- tcIfaceExpr expr
-- If debug flag is not set: Ignore source notes
dbgLvl <- fmap debugLevel getDynFlags
case tickish of
IfaceSource{} | dbgLvl > 0
-> return expr'
_otherwise -> do
tickish' <- tcIfaceTickish tickish
return (Tick tickish' expr')
-------------------------
tcIfaceTickish :: IfaceTickish -> IfM lcl (Tickish Id)
tcIfaceTickish (IfaceHpcTick modl ix) = return (HpcTick modl ix)
tcIfaceTickish (IfaceSCC cc tick push) = return (ProfNote cc tick push)
tcIfaceTickish (IfaceSource src name) = return (SourceNote src name)
-------------------------
tcIfaceLit :: Literal -> IfL Literal
-- Integer literals deserialise to (LitInteger i <error thunk>)
-- so tcIfaceLit just fills in the type.
-- See Note [Integer literals] in Literal
tcIfaceLit (LitInteger i _)
= do t <- tcIfaceTyConByName integerTyConName
return (mkLitInteger i (mkTyConTy t))
tcIfaceLit lit = return lit
-------------------------
tcIfaceAlt :: CoreExpr -> (TyCon, [Type])
-> (IfaceConAlt, [FastString], IfaceExpr)
-> IfL (AltCon, [TyVar], CoreExpr)
tcIfaceAlt _ _ (IfaceDefault, names, rhs)
= ASSERT( null names ) do
rhs' <- tcIfaceExpr rhs
return (DEFAULT, [], rhs')
tcIfaceAlt _ _ (IfaceLitAlt lit, names, rhs)
= ASSERT( null names ) do
lit' <- tcIfaceLit lit
rhs' <- tcIfaceExpr rhs
return (LitAlt lit', [], rhs')
-- A case alternative is made quite a bit more complicated
-- by the fact that we omit type annotations because we can
-- work them out. True enough, but its not that easy!
tcIfaceAlt scrut (tycon, inst_tys) (IfaceDataAlt data_occ, arg_strs, rhs)
= do { con <- tcIfaceDataCon data_occ
; when (debugIsOn && not (con `elem` tyConDataCons tycon))
(failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
; tcIfaceDataAlt con inst_tys arg_strs rhs }
tcIfaceDataAlt :: DataCon -> [Type] -> [FastString] -> IfaceExpr
-> IfL (AltCon, [TyVar], CoreExpr)
tcIfaceDataAlt con inst_tys arg_strs rhs
= do { us <- newUniqueSupply
; let uniqs = uniqsFromSupply us
; let (ex_tvs, arg_ids)
= dataConRepFSInstPat arg_strs uniqs con inst_tys
; rhs' <- extendIfaceEnvs ex_tvs $
extendIfaceIdEnv arg_ids $
tcIfaceExpr rhs
; return (DataAlt con, ex_tvs ++ arg_ids, rhs') }
{-
************************************************************************
* *
IdInfo
* *
************************************************************************
-}
tcIdDetails :: Type -> IfaceIdDetails -> IfL IdDetails
tcIdDetails _ IfVanillaId = return VanillaId
tcIdDetails ty IfDFunId
= return (DFunId (isNewTyCon (classTyCon cls)))
where
(_, _, cls, _) = tcSplitDFunTy ty
tcIdDetails _ (IfRecSelId tc naughty)
= do { tc' <- either (fmap RecSelData . tcIfaceTyCon)
(fmap (RecSelPatSyn . tyThingPatSyn) . tcIfaceDecl False)
tc
; return (RecSelId { sel_tycon = tc', sel_naughty = naughty }) }
where
tyThingPatSyn (AConLike (PatSynCon ps)) = ps
tyThingPatSyn _ = panic "tcIdDetails: expecting patsyn"
tcIdInfo :: Bool -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
tcIdInfo ignore_prags name ty info
| ignore_prags = return vanillaIdInfo
| otherwise = case info of
NoInfo -> return vanillaIdInfo
HasInfo info -> foldlM tcPrag init_info info
where
-- Set the CgInfo to something sensible but uninformative before
-- we start; default assumption is that it has CAFs
init_info = vanillaIdInfo
tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo
tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs)
tcPrag info (HsArity arity) = return (info `setArityInfo` arity)
tcPrag info (HsStrictness str) = return (info `setStrictnessInfo` str)
tcPrag info (HsInline prag) = return (info `setInlinePragInfo` prag)
-- The next two are lazy, so they don't transitively suck stuff in
tcPrag info (HsUnfold lb if_unf)
= do { unf <- tcUnfolding name ty info if_unf
; let info1 | lb = info `setOccInfo` strongLoopBreaker
| otherwise = info
; return (info1 `setUnfoldingInfoLazily` unf) }
tcUnfolding :: Name -> Type -> IdInfo -> IfaceUnfolding -> IfL Unfolding
tcUnfolding name _ info (IfCoreUnfold stable if_expr)
= do { dflags <- getDynFlags
; mb_expr <- tcPragExpr name if_expr
; let unf_src | stable = InlineStable
| otherwise = InlineRhs
; return $ case mb_expr of
Nothing -> NoUnfolding
Just expr -> mkUnfolding dflags unf_src
True {- Top level -}
(isBottomingSig strict_sig)
expr
}
where
-- Strictness should occur before unfolding!
strict_sig = strictnessInfo info
tcUnfolding name _ _ (IfCompulsory if_expr)
= do { mb_expr <- tcPragExpr name if_expr
; return (case mb_expr of
Nothing -> NoUnfolding
Just expr -> mkCompulsoryUnfolding expr) }
tcUnfolding name _ _ (IfInlineRule arity unsat_ok boring_ok if_expr)
= do { mb_expr <- tcPragExpr name if_expr
; return (case mb_expr of
Nothing -> NoUnfolding
Just expr -> mkCoreUnfolding InlineStable True expr guidance )}
where
guidance = UnfWhen { ug_arity = arity, ug_unsat_ok = unsat_ok, ug_boring_ok = boring_ok }
tcUnfolding name dfun_ty _ (IfDFunUnfold bs ops)
= bindIfaceBndrs bs $ \ bs' ->
do { mb_ops1 <- forkM_maybe doc $ mapM tcIfaceExpr ops
; return (case mb_ops1 of
Nothing -> noUnfolding
Just ops1 -> mkDFunUnfolding bs' (classDataCon cls) ops1) }
where
doc = text "Class ops for dfun" <+> ppr name
(_, _, cls, _) = tcSplitDFunTy dfun_ty
{-
For unfoldings we try to do the job lazily, so that we never type check
an unfolding that isn't going to be looked at.
-}
tcPragExpr :: Name -> IfaceExpr -> IfL (Maybe CoreExpr)
tcPragExpr name expr
= forkM_maybe doc $ do
core_expr' <- tcIfaceExpr expr
-- Check for type consistency in the unfolding
whenGOptM Opt_DoCoreLinting $ do
in_scope <- get_in_scope
dflags <- getDynFlags
case lintUnfolding dflags noSrcLoc in_scope core_expr' of
Nothing -> return ()
Just fail_msg -> do { mod <- getIfModule
; pprPanic "Iface Lint failure"
(vcat [ text "In interface for" <+> ppr mod
, hang doc 2 fail_msg
, ppr name <+> equals <+> ppr core_expr'
, text "Iface expr =" <+> ppr expr ]) }
return core_expr'
where
doc = text "Unfolding of" <+> ppr name
get_in_scope :: IfL VarSet -- Totally disgusting; but just for linting
get_in_scope
= do { (gbl_env, lcl_env) <- getEnvs
; rec_ids <- case if_rec_types gbl_env of
Nothing -> return []
Just (_, get_env) -> do
{ type_env <- setLclEnv () get_env
; return (typeEnvIds type_env) }
; return (bindingsVars (if_tv_env lcl_env) `unionVarSet`
bindingsVars (if_id_env lcl_env) `unionVarSet`
mkVarSet rec_ids) }
bindingsVars :: FastStringEnv Var -> VarSet
bindingsVars ufm = mkVarSet $ nonDetEltsUFM ufm
-- It's OK to use nonDetEltsUFM here because we immediately forget
-- the ordering by creating a set
{-
************************************************************************
* *
Getting from Names to TyThings
* *
************************************************************************
-}
tcIfaceGlobal :: Name -> IfL TyThing
tcIfaceGlobal name
| Just thing <- wiredInNameTyThing_maybe name
-- Wired-in things include TyCons, DataCons, and Ids
-- Even though we are in an interface file, we want to make
-- sure the instances and RULES of this thing (particularly TyCon) are loaded
-- Imagine: f :: Double -> Double
= do { ifCheckWiredInThing thing; return thing }
| otherwise
= do { env <- getGblEnv
; case if_rec_types env of { -- Note [Tying the knot]
Just (mod, get_type_env)
| nameIsLocalOrFrom mod name
-> do -- It's defined in the module being compiled
{ type_env <- setLclEnv () get_type_env -- yuk
; case lookupNameEnv type_env name of
Just thing -> return thing
Nothing ->
pprPanic "tcIfaceGlobal (local): not found"
(ifKnotErr name (if_doc env) type_env)
}
; _ -> do
{ hsc_env <- getTopEnv
; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
; case mb_thing of {
Just thing -> return thing ;
Nothing -> do
{ mb_thing <- importDecl name -- It's imported; go get it
; case mb_thing of
Failed err -> failIfM err
Succeeded thing -> return thing
}}}}}
ifKnotErr :: Name -> SDoc -> TypeEnv -> SDoc
ifKnotErr name env_doc type_env = vcat
[ text "You are in a maze of twisty little passages, all alike."
, text "While forcing the thunk for TyThing" <+> ppr name
, text "which was lazily initialized by" <+> env_doc <> text ","
, text "I tried to tie the knot, but I couldn't find" <+> ppr name
, text "in the current type environment."
, text "If you are developing GHC, please read Note [Tying the knot]"
, text "and Note [Type-checking inside the knot]."
, text "Consider rebuilding GHC with profiling for a better stack trace."
, hang (text "Contents of current type environment:")
2 (ppr type_env)
]
-- Note [Tying the knot]
-- ~~~~~~~~~~~~~~~~~~~~~
-- The if_rec_types field is used in two situations:
--
-- a) Compiling M.hs, which indirectly imports Foo.hi, which mentions M.T
-- Then we look up M.T in M's type environment, which is splatted into if_rec_types
-- after we've built M's type envt.
--
-- b) In ghc --make, during the upsweep, we encounter M.hs, whose interface M.hi
-- is up to date. So we call typecheckIface on M.hi. This splats M.T into
-- if_rec_types so that the (lazily typechecked) decls see all the other decls
--
-- In case (b) it's important to do the if_rec_types check *before* looking in the HPT
-- Because if M.hs also has M.hs-boot, M.T will *already be* in the HPT, but in its
-- emasculated form (e.g. lacking data constructors).
tcIfaceTyConByName :: IfExtName -> IfL TyCon
tcIfaceTyConByName name
= do { thing <- tcIfaceGlobal name
; return (tyThingTyCon thing) }
tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
tcIfaceTyCon (IfaceTyCon name info)
= do { thing <- tcIfaceGlobal name
; return $ case info of
NoIfaceTyConInfo -> tyThingTyCon thing
IfacePromotedDataCon -> promoteDataCon $ tyThingDataCon thing }
tcIfaceCoAxiom :: Name -> IfL (CoAxiom Branched)
tcIfaceCoAxiom name = do { thing <- tcIfaceGlobal name
; return (tyThingCoAxiom thing) }
tcIfaceDataCon :: Name -> IfL DataCon
tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
; case thing of
AConLike (RealDataCon dc) -> return dc
_ -> pprPanic "tcIfaceExtDC" (ppr name$$ ppr thing) }
tcIfaceExtId :: Name -> IfL Id
tcIfaceExtId name = do { thing <- tcIfaceGlobal name
; case thing of
AnId id -> return id
_ -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
{-
************************************************************************
* *
Bindings
* *
************************************************************************
-}
bindIfaceId :: IfaceIdBndr -> (Id -> IfL a) -> IfL a
bindIfaceId (fs, ty) thing_inside
= do { name <- newIfaceName (mkVarOccFS fs)
; ty' <- tcIfaceType ty
; let id = mkLocalIdOrCoVar name ty'
; extendIfaceIdEnv [id] (thing_inside id) }
bindIfaceIds :: [IfaceIdBndr] -> ([Id] -> IfL a) -> IfL a
bindIfaceIds [] thing_inside = thing_inside []
bindIfaceIds (b:bs) thing_inside
= bindIfaceId b $ \b' ->
bindIfaceIds bs $ \bs' ->
thing_inside (b':bs')
bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
bindIfaceBndr (IfaceIdBndr bndr) thing_inside
= bindIfaceId bndr thing_inside
bindIfaceBndr (IfaceTvBndr bndr) thing_inside
= bindIfaceTyVar bndr thing_inside
bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
bindIfaceBndrs [] thing_inside = thing_inside []
bindIfaceBndrs (b:bs) thing_inside
= bindIfaceBndr b $ \ b' ->
bindIfaceBndrs bs $ \ bs' ->
thing_inside (b':bs')
-----------------------
bindIfaceForAllBndrs :: [IfaceForAllBndr] -> ([TyVarBinder] -> IfL a) -> IfL a
bindIfaceForAllBndrs [] thing_inside = thing_inside []
bindIfaceForAllBndrs (bndr:bndrs) thing_inside
= bindIfaceForAllBndr bndr $ \tv vis ->
bindIfaceForAllBndrs bndrs $ \bndrs' ->
thing_inside (mkTyVarBinder vis tv : bndrs')
bindIfaceForAllBndr :: IfaceForAllBndr -> (TyVar -> ArgFlag -> IfL a) -> IfL a
bindIfaceForAllBndr (TvBndr tv vis) thing_inside
= bindIfaceTyVar tv $ \tv' -> thing_inside tv' vis
bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
bindIfaceTyVar (occ,kind) thing_inside
= do { name <- newIfaceName (mkTyVarOccFS occ)
; tyvar <- mk_iface_tyvar name kind
; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
mk_iface_tyvar name ifKind
= do { kind <- tcIfaceType ifKind
; return (Var.mkTyVar name kind) }
bindIfaceTyConBinders :: [IfaceTyConBinder]
-> ([TyConBinder] -> IfL a) -> IfL a
bindIfaceTyConBinders [] thing_inside = thing_inside []
bindIfaceTyConBinders (b:bs) thing_inside
= bindIfaceTyConBinderX bindIfaceTyVar b $ \ b' ->
bindIfaceTyConBinders bs $ \ bs' ->
thing_inside (b':bs')
bindIfaceTyConBinders_AT :: [IfaceTyConBinder]
-> ([TyConBinder] -> IfL a) -> IfL a
-- Used for type variable in nested associated data/type declarations
-- where some of the type variables are already in scope
-- class C a where { data T a b }
-- Here 'a' is in scope when we look at the 'data T'
bindIfaceTyConBinders_AT [] thing_inside
= thing_inside []
bindIfaceTyConBinders_AT (b : bs) thing_inside
= bindIfaceTyConBinderX bind_tv b $ \b' ->
bindIfaceTyConBinders_AT bs $ \bs' ->
thing_inside (b':bs')
where
bind_tv tv thing
= do { mb_tv <- lookupIfaceTyVar tv
; case mb_tv of
Just b' -> thing b'
Nothing -> bindIfaceTyVar tv thing }
bindIfaceTyConBinderX :: (IfaceTvBndr -> (TyVar -> IfL a) -> IfL a)
-> IfaceTyConBinder
-> (TyConBinder -> IfL a) -> IfL a
bindIfaceTyConBinderX bind_tv (TvBndr tv vis) thing_inside
= bind_tv tv $ \tv' ->
thing_inside (TvBndr tv' vis)
|
vTurbine/ghc
|
compiler/iface/TcIface.hs
|
Haskell
|
bsd-3-clause
| 66,022
|
module Benchmarks.Day04 (benchmarks) where
import Criterion (Benchmark, bench, nf)
import Day04
import Text.Heredoc
benchmarks :: [Benchmark]
benchmarks =
[ bench "findAdventCoin5"
$ nf (findAdventCoin input) 5
, bench "findAdventCoin6"
$ nf (findAdventCoin input) 6
]
input = [there|./inputs/Day04.txt|]
|
patrickherrmann/advent
|
bench/Benchmarks/Day04.hs
|
Haskell
|
bsd-3-clause
| 325
|
{-# LANGUAGE OverloadedStrings #-}
{-|
Module : Network.Spotify.Api.Types.Scope
Description : OAuth scopes for the Spotify Web API
Stability : experimental
Scopes let you specify exactly what types of data your application wants to
access, and the set of scopes you pass in your call determines what access
permissions the user is asked to grant.
-}
module Network.Spotify.Api.Types.Scope where
import Data.Aeson (FromJSON (parseJSON), ToJSON, toJSON, withText)
import Data.Text (Text, pack, unpack, words)
import Prelude hiding (words)
import Servant (ToHttpApiData (..), toQueryParam)
-- | If no scope is specified, access is permitted only to publicly available
-- information: that is, only information normally visible to normal
-- logged-in users of the Spotify desktop, web, and mobile clients
-- (e.g. public playlists).
data Scope = Scope
{ getScopes :: [Text]
}
instance Show Scope where
show s = unwords $ map unpack (getScopes s)
instance ToHttpApiData Scope where
toQueryParam = pack . show
instance FromJSON Scope where
parseJSON = withText "Scope" $ \scopes -> do
let parsedScope = scopeFromList (words scopes)
return parsedScope
instance ToJSON Scope where
toJSON = toJSON . show
-- | Create a 'Scope' from a textual list of scopes
scopeFromList :: [Text] -> Scope
scopeFromList scopes = Scope { getScopes = scopes }
-- * Available Spotify Web API Scopes
-- | Read access to user's private playlists.
playlistReadPrivate :: Text
playlistReadPrivate = "playlist-read-private"
-- | Include collaborative playlists when requesting a user's playlists.
playlistReadCollaborative :: Text
playlistReadCollaborative = "playlist-read-collaborative"
-- | Write access to a user's public playlists.
playlistModifyPublic :: Text
playlistModifyPublic = "playlist-modify-public"
-- | Write access to a user's private playlists.
playlistModifyPrivate :: Text
playlistModifyPrivate = "playlist-modify-private"
-- | Control playback of a Spotify track. This scope is currently only available
-- to Spotify native SDKs (for example, the iOS SDK and the Android SDK). The
-- user must have a Spotify Premium account.
streaming :: Text
streaming = "streaming"
-- | Write/delete access to the list of artists and other users that the user follows.
userFollowModify :: Text
userFollowModify = "user-follow-modify"
-- | Read access to the list of artists and other users that the user follows.
userFollowRead :: Text
userFollowRead = "user-follow-read"
-- | Read access to a user's 'Your Music' library.
userLibraryRead :: Text
userLibraryRead = "user-library-read"
-- | Write/delete access to a user's 'Your Music' library.
userLibraryModify :: Text
userLibraryModify = "user-library-modify"
-- | Read access to user's subscription details (type of user account).
userReadPrivate :: Text
userReadPrivate = "user-read-private"
-- | Read access to the user's birthdate.
userReadBirthdate :: Text
userReadBirthdate = "user-read-birthdate"
-- | Read access to user's email address.
userReadEmail :: Text
userReadEmail = "user-read-email"
-- | Read access to a user's top artists and tracks
userTopRead :: Text
userTopRead = "user-top-read"
|
chances/servant-spotify
|
src/Network/Spotify/Api/Types/Scope.hs
|
Haskell
|
bsd-3-clause
| 3,257
|
import Test.Hspec (hspec)
import ParseTest (parseSpecs)
import GeometryTest (geometrySpecs)
main :: IO ()
main = hspec $ do
parseSpecs
geometrySpecs
|
albertov/kml2obj
|
tests/main.hs
|
Haskell
|
bsd-3-clause
| 155
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE QuasiQuotes #-}
module Horbits.UI.Camera.Trace(logCamera, orthoCameraColatitudeDeg, orthoCameraLongitudeDeg) where
import Control.Lens
import Data.Foldable (mapM_)
import Data.StateVar
import Linear
import Prelude hiding (mapM_)
import Text.Printf.TH
import Horbits.Data.Binding
import Horbits.UI.Camera.Internal
degrees :: (Floating a) => Iso' a a
degrees = iso (* (180 / pi)) (* (pi / 180))
orthoCameraColatitudeDeg :: Floating a => Lens' (OrthoCamera a) a
orthoCameraColatitudeDeg = orthoCameraColatitude . degrees
orthoCameraLongitudeDeg :: Floating a => Lens' (OrthoCamera a) a
orthoCameraLongitudeDeg = orthoCameraLongitude . degrees
logCamera :: (HasGetter v (OrthoCamera a), Show a, RealFloat a, Epsilon a) => v -> IO ()
logCamera cam = do
c <- readVar cam
putStrLn $ [s|O: %.2e %.2e %.2e|] (c ^. orthoCameraCenter . _x)
(c ^. orthoCameraCenter . _y)
(c ^. orthoCameraCenter . _z)
putStrLn $ [s|r: %.2e th: %.2e la: %.2e|] (c ^. orthoCameraScale)
(c ^. orthoCameraLongitudeDeg)
(c ^. orthoCameraColatitudeDeg)
mapM_ showMRow . orthoCameraMatrix $ c
where
showMRow (V4 x y z w) = putStrLn $ [s|%8.2e %8.2e %8.2e %8.2e|] x y z w
|
chwthewke/horbits
|
src/horbits/Horbits/UI/Camera/Trace.hs
|
Haskell
|
bsd-3-clause
| 1,499
|
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-|
Module : Numeric.AERN.RealArithmetic.Basis.MPFR.FieldOps
Description : rounded arithmetic instances for MPFR
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : mikkonecny@gmail.com
Stability : experimental
Portability : portable
Rounded arithmetic instances for MPFR.
This is a private module reexported publicly via its parent.
-}
module Numeric.AERN.RealArithmetic.Basis.MPFR.FieldOps
()
where
import Numeric.AERN.RealArithmetic.Basis.MPFR.Basics
import Numeric.AERN.RealArithmetic.Basis.MPFR.ExactOps
import Numeric.AERN.RealArithmetic.Basis.MPFR.NumericOrder
import Numeric.AERN.RealArithmetic.Basis.MPFR.Utilities
import Numeric.AERN.RealArithmetic.NumericOrderRounding
import Numeric.AERN.Basics.Effort
import Numeric.AERN.Misc.Debug
instance RoundedAddEffort MPFR where
type AddEffortIndicator MPFR = ()
addDefaultEffort _ = ()
instance RoundedAdd MPFR where
addUpEff _ d1 d2 =
detectNaNUp ("addition " ++ show d1 ++ " +^ " ++ show d2 ) $
liftRoundedToMPFR2 "+^" (+) d1 d2
addDnEff _ d1 d2 =
detectNaNDn ("addition " ++ show d1 ++ " +. " ++ show d2 ) $
liftRoundedToMPFR2 "+." (\ a b -> -((-a) + (-b))) d1 d2
instance RoundedSubtr MPFR
instance RoundedAbsEffort MPFR where
type AbsEffortIndicator MPFR = ()
absDefaultEffort _ = ()
instance RoundedAbs MPFR where
absDnEff _ = liftRoundedToMPFR1 abs
absUpEff _ = liftRoundedToMPFR1 abs
instance RoundedMultiplyEffort MPFR where
type MultEffortIndicator MPFR = ()
multDefaultEffort _ = ()
instance RoundedMultiply MPFR where
multUpEff _ d1 d2 =
-- unsafePrintReturn
-- (
-- "MPFR multiplication UP with prec = " ++ show prec
-- ++ " " ++ show d1 ++ " * " ++ show d2 ++ " = "
-- ) $
detectNaNUp ("multiplication " ++ show d1 ++ " *^ " ++ show d2 ) $
liftRoundedToMPFR2 "*^" (*) d1 d2
multDnEff _ d1 d2 =
-- unsafePrintReturn
-- (
-- "MPFR multiplication DOWN with prec = " ++ show prec
-- ++ " " ++ show d1 ++ " * " ++ show d2 ++ " = "
-- ) $
detectNaNDn ("multiplication " ++ show d1 ++ " *. " ++ show d2 ) $
liftRoundedToMPFR2 "*." (\ a b -> -((-a) * b)) d1 d2
instance RoundedPowerNonnegToNonnegIntEffort MPFR where
type PowerNonnegToNonnegIntEffortIndicator MPFR = ()
powerNonnegToNonnegIntDefaultEffort _ = ()
instance RoundedPowerNonnegToNonnegInt MPFR where
-- TODO: add to rounded an interface to MPFR powi
powerNonnegToNonnegIntUpEff _ =
powerNonnegToNonnegIntUpEffFromMult ()
-- M.powi M.Up (M.getPrec x) x n
powerNonnegToNonnegIntDnEff _ =
powerNonnegToNonnegIntDnEffFromMult ()
-- M.powi M.Down (M.getPrec x) x n
instance RoundedPowerToNonnegIntEffort MPFR where
type PowerToNonnegIntEffortIndicator MPFR = ()
powerToNonnegIntDefaultEffort _ = ()
instance RoundedPowerToNonnegInt MPFR where
-- TODO: add to rounded an interface to MPFR powi
powerToNonnegIntUpEff _ =
powerToNonnegIntUpEffFromMult ((),(),())
-- M.powi M.Up (M.getPrec x) x n
powerToNonnegIntDnEff _ =
powerToNonnegIntDnEffFromMult ((),(),())
-- M.powi M.Down (M.getPrec x) x n
instance RoundedDivideEffort MPFR where
type DivEffortIndicator MPFR = ()
divDefaultEffort _ = ()
instance RoundedDivide MPFR where
divUpEff _ d1 d2 =
detectNaNUp ("division " ++ show d1 ++ " *^ " ++ show d2 ) $
liftRoundedToMPFR2 "/^" (/) d1 d2
divDnEff _ d1 d2 =
detectNaNDn ("division " ++ show d1 ++ " *. " ++ show d2 ) $
liftRoundedToMPFR2 "/." (\ a b -> -((-a) / b)) d1 d2
instance RoundedRingEffort MPFR
where
type RingOpsEffortIndicator MPFR = ()
ringOpsDefaultEffort _ = ()
ringEffortAdd _ _ = ()
ringEffortMult _ _ = ()
ringEffortPow _ _ = ()
instance RoundedRing MPFR
instance RoundedFieldEffort MPFR
where
type FieldOpsEffortIndicator MPFR = ()
fieldOpsDefaultEffort _ = ()
fldEffortAdd _ _ = ()
fldEffortMult _ _ = ()
fldEffortPow _ _ = ()
fldEffortDiv _ _ = ()
instance RoundedField MPFR
|
michalkonecny/aern
|
aern-mpfr-rounded/src/Numeric/AERN/RealArithmetic/Basis/MPFR/FieldOps.hs
|
Haskell
|
bsd-3-clause
| 4,335
|
module Sexy.Instances.Nil.Function where
import Sexy.Classes (Nil(..))
instance (Nil b) => Nil (a -> b) where
nil = (\_ -> nil)
|
DanBurton/sexy
|
src/Sexy/Instances/Nil/Function.hs
|
Haskell
|
bsd-3-clause
| 133
|
module Graphics.Gnuplot.Frame.OptionSet (
OptionSet.T,
deflt,
OptionSet.add,
OptionSet.remove,
OptionSet.boolean,
OptionSet.addBool,
size,
title,
key,
keyInside,
keyOutside,
xRange2d,
yRange2d,
xRange3d,
yRange3d,
zRange3d,
xLabel,
yLabel,
zLabel,
xTicks2d,
yTicks2d,
xTicks3d,
yTicks3d,
zTicks3d,
xLogScale,
yLogScale,
zLogScale,
grid,
gridXTicks,
gridYTicks,
gridZTicks,
xFormat,
yFormat,
zFormat,
view,
viewMap,
boxwidthRelative,
boxwidthAbsolute,
tmargin,
bmargin,
lmargin,
rmargin,
margin,
) where
import qualified Graphics.Gnuplot.Graph.ThreeDimensional as Graph3D
import qualified Graphics.Gnuplot.Graph.TwoDimensional as Graph2D
import qualified Graphics.Gnuplot.Private.FrameOptionSet as OptionSet
import qualified Graphics.Gnuplot.Private.FrameOption as Option
import qualified Graphics.Gnuplot.Private.Graph as Graph
import qualified Graphics.Gnuplot.Value.Atom as Atom
import qualified Graphics.Gnuplot.Value.Tuple as Tuple
import Graphics.Gnuplot.Private.FrameOptionSet (T, )
import Graphics.Gnuplot.Utility (quote, )
import qualified Data.List as List
deflt :: Graph.C graph => T graph
deflt = Graph.defltOptions
size :: Graph.C graph => Double -> Double -> T graph -> T graph
size x y =
OptionSet.add Option.sizeScale [show x ++ ", " ++ show y]
title :: Graph.C graph => String -> T graph -> T graph
title text =
OptionSet.add Option.title [quote text]
key :: Graph.C graph => Bool -> T graph -> T graph
key = OptionSet.boolean Option.keyShow
keyInside :: Graph.C graph => T graph -> T graph
keyInside = OptionSet.add Option.keyPosition ["inside"]
keyOutside :: Graph.C graph => T graph -> T graph
keyOutside = OptionSet.add Option.keyPosition ["outside"]
{-
xRange :: Graph.C graph => (Double, Double) -> T graph -> T graph
xRange = range Option.xRange
yRange :: Graph.C graph => (Double, Double) -> T graph -> T graph
yRange = range Option.yRange
zRange :: (Double, Double) -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
zRange = range Option.zRange
-}
xRange2d ::
(Atom.C x, Atom.C y, Tuple.C x) =>
(x, x) -> T (Graph2D.T x y) -> T (Graph2D.T x y)
xRange2d = range Option.xRangeBounds
yRange2d ::
(Atom.C x, Atom.C y, Tuple.C y) =>
(y, y) -> T (Graph2D.T x y) -> T (Graph2D.T x y)
yRange2d = range Option.yRangeBounds
xRange3d ::
(Atom.C x, Atom.C y, Atom.C z, Tuple.C x) =>
(x, x) -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
xRange3d = range Option.xRangeBounds
yRange3d ::
(Atom.C x, Atom.C y, Atom.C z, Tuple.C y) =>
(y, y) -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
yRange3d = range Option.yRangeBounds
zRange3d ::
(Atom.C x, Atom.C y, Atom.C z, Tuple.C z) =>
(z, z) -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
zRange3d = range Option.zRangeBounds
range ::
(Atom.C a, Tuple.C a, Graph.C graph) =>
Option.T -> (a, a) -> T graph -> T graph
range opt (x,y) =
OptionSet.add opt
[showString "[" . atomText x .
showString ":" . atomText y $
"]"]
atomText ::
(Atom.C a, Tuple.C a) =>
a -> ShowS
atomText x =
case Tuple.text x of
[s] -> s
_ -> error "OptionSet.fromSingleton: types of Atom class must generate single representation texts"
xLabel :: Graph.C graph => String -> T graph -> T graph
xLabel = label Option.xLabelText
yLabel :: Graph.C graph => String -> T graph -> T graph
yLabel = label Option.yLabelText
zLabel ::
(Atom.C x, Atom.C y, Atom.C z) =>
String -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
zLabel = label Option.zLabelText
label :: Graph.C graph => Option.T -> String -> T graph -> T graph
label opt x =
OptionSet.add opt [quote x]
xFormat :: Graph.C graph => String -> T graph -> T graph
xFormat = format Option.xFormat
yFormat :: Graph.C graph => String -> T graph -> T graph
yFormat = format Option.yFormat
zFormat ::
(Atom.C x, Atom.C y, Atom.C z) =>
String -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
zFormat = format Option.zFormat
format :: Graph.C graph => Option.T -> String -> T graph -> T graph
format opt x =
OptionSet.add opt [quote x]
{- |
Set parameters of viewing a surface graph.
See <info:gnuplot/view>
-}
view ::
Double {- ^ rotateX -} ->
Double {- ^ rotateZ -} ->
Double {- ^ scale -} ->
Double {- ^ scaleZ -} ->
T (Graph3D.T x y z) -> T (Graph3D.T x y z)
view rotateX rotateZ scale scaleZ =
OptionSet.add Option.view [show rotateX, show rotateZ, show scale, show scaleZ]
{- |
Show flat pixel map.
-}
viewMap :: T (Graph3D.T x y z) -> T (Graph3D.T x y z)
viewMap =
OptionSet.add Option.view ["map"]
xTicks2d ::
(Atom.C x, Atom.C y, Tuple.C x) =>
[(String, x)] -> T (Graph2D.T x y) -> T (Graph2D.T x y)
xTicks2d = ticks Option.xTickLabels
yTicks2d ::
(Atom.C x, Atom.C y, Tuple.C y) =>
[(String, y)] -> T (Graph2D.T x y) -> T (Graph2D.T x y)
yTicks2d = ticks Option.yTickLabels
xTicks3d ::
(Atom.C x, Atom.C y, Atom.C z, Tuple.C x) =>
[(String, x)] -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
xTicks3d = ticks Option.xTickLabels
yTicks3d ::
(Atom.C x, Atom.C y, Atom.C z, Tuple.C y) =>
[(String, y)] -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
yTicks3d = ticks Option.yTickLabels
zTicks3d ::
(Atom.C x, Atom.C y, Atom.C z, Tuple.C z) =>
[(String, z)] -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
zTicks3d = ticks Option.zTickLabels
ticks ::
(Atom.C a, Tuple.C a, Graph.C graph) =>
Option.T -> [(String, a)] -> T graph -> T graph
ticks opt labels =
OptionSet.add opt
[('(' :) $ foldr ($) ")" $
List.intersperse (showString ", ") $
map
(\(lab,pos) ->
showString (quote lab) .
showString " " .
atomText pos)
labels]
xLogScale :: Graph.C graph => T graph -> T graph
xLogScale = OptionSet.add Option.xLogScale []
yLogScale :: Graph.C graph => T graph -> T graph
yLogScale = OptionSet.add Option.yLogScale []
zLogScale ::
(Atom.C x, Atom.C y, Atom.C z) =>
T (Graph3D.T x y z) -> T (Graph3D.T x y z)
zLogScale = OptionSet.add Option.zLogScale []
grid :: Graph.C graph => Bool -> T graph -> T graph
grid b =
OptionSet.addBool Option.gridXTicks b .
OptionSet.addBool Option.gridYTicks b .
OptionSet.addBool Option.gridZTicks b
gridXTicks :: Graph.C graph => Bool -> T graph -> T graph
gridXTicks = OptionSet.addBool Option.gridXTicks
gridYTicks :: Graph.C graph => Bool -> T graph -> T graph
gridYTicks = OptionSet.addBool Option.gridYTicks
gridZTicks ::
(Atom.C x, Atom.C y, Atom.C z) =>
Bool -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
gridZTicks = OptionSet.addBool Option.gridZTicks
boxwidthRelative ::
(Graph.C graph) =>
Double -> T graph -> T graph
boxwidthRelative width =
OptionSet.add Option.boxwidth [show width, "relative"]
boxwidthAbsolute ::
(Graph.C graph) =>
Double -> T graph -> T graph
boxwidthAbsolute width =
OptionSet.add Option.boxwidth [show width, "absolute"]
tmargin :: Graph.C graph => Int -> T graph -> T graph
tmargin x =
OptionSet.add (Option.tmargin "") [show x]
bmargin :: Graph.C graph => Int -> T graph -> T graph
bmargin x =
OptionSet.add (Option.bmargin "") [show x]
lmargin :: Graph.C graph => Int -> T graph -> T graph
lmargin x =
OptionSet.add (Option.lmargin "") [show x]
rmargin :: Graph.C graph => Int -> T graph -> T graph
rmargin x =
OptionSet.add (Option.rmargin "") [show x]
margin :: Graph.C graph => Int -> T graph -> T graph
margin x = tmargin x . bmargin x . lmargin x . rmargin x
{-
cornerToColor :: CornersToColor -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
type3d :: Plot3dType -> T (Graph3D.T x y z) -> T (Graph3D.T x y z)
-}
|
kubkon/gnuplot
|
src/Graphics/Gnuplot/Frame/OptionSet.hs
|
Haskell
|
bsd-3-clause
| 7,742
|
-- |
-- This module reexports most of the types from \"containers\",
-- \"unordered-containers\", \"array\", and \"vector\". No
-- functions are exported.
--
module Prelude.Containers.Types
( module E
) where
-- array types
import Data.Array as E (Array)
import Data.Array.IArray as E (IArray)
import Data.Array.IO as E (IOArray,IOUArray)
import Data.Array.MArray as E (MArray)
import Data.Array.ST as E (STArray,STUArray)
import Data.Array.Storable as E (StorableArray)
import Data.Array.Unboxed as E (UArray)
-- containers
import Data.IntMap as E (IntMap)
import Data.IntSet as E (IntSet)
import Data.Map as E (Map)
import Data.Sequence as E (Seq)
import Data.Set as E (Set)
import Data.Tree as E (Tree)
-- unordered-containers
import Data.HashMap.Strict as E (HashMap)
import Data.HashSet as E (HashSet)
-- vector
import Data.Vector as E (Vector)
import Data.Vector.Mutable as E (MVector,IOVector,STVector)
|
andrewthad/lens-prelude
|
src/Prelude/Containers/Types.hs
|
Haskell
|
bsd-3-clause
| 953
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module Webcrank.Internal.ReqData where
import Control.Applicative
import Control.Lens
import Control.Monad.State
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LB
import qualified Data.HashMap.Strict as HashMap
import Data.Maybe
import Network.HTTP.Media
import Network.HTTP.Types
import Prelude
import Webcrank.Internal.Types
-- | Smart constructor for creating a @ReqData@ value with initial values.
newReqData :: ReqData
newReqData = ReqData
{ _reqDataDispPath = []
, _reqDataRespMediaType = "application" // "octet-stream"
, _reqDataRespCharset = Nothing
, _reqDataRespEncoding = Nothing
, _reqDataRespHeaders = HashMap.empty
, _reqDataRespBody = Nothing
}
-- | Lookup a response header.
getResponseHeader
:: (Functor m, MonadState s m, HasReqData s)
=> HeaderName
-> m (Maybe ByteString)
getResponseHeader h = (listToMaybe =<<) . HashMap.lookup h <$> use reqDataRespHeaders
-- | Replace any existing response headers for the header name with the
-- new value.
putResponseHeader
:: (MonadState s m, HasReqData s)
=> HeaderName
-> ByteString
-> m ()
putResponseHeader h v = reqDataRespHeaders %= HashMap.insert h [v]
-- | Replace any existing response headers for the header name with the
-- new values.
putResponseHeaders
:: (MonadState s m, HasReqData s)
=> ResponseHeaders
-> m ()
putResponseHeaders = mapM_ (uncurry putResponseHeader)
-- | Remove the response header.
removeResponseHeader
:: (MonadState s m, HasReqData s)
=> HeaderName
-> m ()
removeResponseHeader h = reqDataRespHeaders %= HashMap.delete h
-- | Lookup the response @Location@ header.
getResponseLocation
:: (Functor m, MonadState s m, HasReqData s)
=> m (Maybe ByteString)
getResponseLocation = getResponseHeader hLocation
-- | Set the response @Location@ header.
putResponseLocation
:: (MonadState s m, HasReqData s)
=> ByteString
-> m ()
putResponseLocation = putResponseHeader hLocation
-- | Use the lazy @ByteString@ as the response body.
writeLBS
:: (MonadState s m, HasReqData s)
=> LB.ByteString
-> m ()
writeLBS = (reqDataRespBody ?=)
|
webcrank/webcrank.hs
|
src/Webcrank/Internal/ReqData.hs
|
Haskell
|
bsd-3-clause
| 2,186
|
{-# LANGUAGE ScopedTypeVariables, GeneralizedNewtypeDeriving, TypeSynonymInstances, FlexibleInstances, OverlappingInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Actions.GridSelect
-- Copyright : Clemens Fruhwirth <clemens@endorphin.org>
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Clemens Fruhwirth <clemens@endorphin.org>
-- Stability : unstable
-- Portability : unportable
--
-- GridSelect displays items(e.g. the opened windows) in a 2D grid and lets
-- the user select from it with the cursor/hjkl keys or the mouse.
--
-----------------------------------------------------------------------------
module XMonad.Actions.GridSelect (
-- * Usage
-- $usage
-- ** Customizing
-- *** Using a common GSConfig
-- $commonGSConfig
-- *** Custom keybindings
-- $keybindings
-- * Configuration
GSConfig(..),
defaultGSConfig,
TwoDPosition,
buildDefaultGSConfig,
-- * Variations on 'gridselect'
gridselect,
gridselectWindow,
withSelectedWindow,
bringSelected,
goToSelected,
gridselectWorkspace,
spawnSelected,
runSelectedAction,
-- * Colorizers
HasColorizer(defaultColorizer),
fromClassName,
stringColorizer,
colorRangeFromClassName,
-- * Navigation Mode assembly
TwoD,
makeXEventhandler,
shadowWithKeymap,
-- * Built-in Navigation Mode
defaultNavigation,
substringSearch,
navNSearch,
-- * Navigation Components
setPos,
move,
select,
cancel,
transformSearchString
-- * Screenshots
-- $screenshots
) where
import Data.Maybe
import Data.Bits
import Data.Char
import Control.Applicative
import Control.Monad.State
import Control.Arrow
import Data.List as L
import qualified Data.Map as M
import XMonad hiding (liftX)
import XMonad.Util.Font
import XMonad.Prompt (mkUnmanagedWindow)
import XMonad.StackSet as W
import XMonad.Layout.Decoration
import XMonad.Util.NamedWindows
import XMonad.Actions.WindowBringer (bringWindow)
import Text.Printf
import System.Random (mkStdGen, genRange, next)
import Data.Word (Word8)
-- $usage
--
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Actions.GridSelect
--
-- Then add a keybinding, e.g.
--
-- > , ((modm, xK_g), goToSelected defaultGSConfig)
--
-- This module also supports displaying arbitrary information in a grid and letting
-- the user select from it. E.g. to spawn an application from a given list, you
-- can use the following:
--
-- > , ((modm, xK_s), spawnSelected defaultGSConfig ["xterm","gmplayer","gvim"])
-- $commonGSConfig
--
-- It is possible to bind a @gsconfig@ at top-level in your configuration. Like so:
--
-- > -- the top of your config
-- > {-# LANGUAGE NoMonomorphismRestriction #-}
-- > import XMonad
-- > ...
-- > gsconfig1 = defaultGSConfig { gs_cellheight = 30, gs_cellwidth = 100 }
--
-- An example where 'buildDefaultGSConfig' is used instead of 'defaultGSConfig'
-- in order to specify a custom colorizer is @gsconfig2@ (found in
-- "XMonad.Actions.GridSelect#Colorizers"):
--
-- > gsconfig2 colorizer = (buildDefaultGSConfig colorizer) { gs_cellheight = 30, gs_cellwidth = 100 }
--
-- > -- | A green monochrome colorizer based on window class
-- > greenColorizer = colorRangeFromClassName
-- > black -- lowest inactive bg
-- > (0x70,0xFF,0x70) -- highest inactive bg
-- > black -- active bg
-- > white -- inactive fg
-- > white -- active fg
-- > where black = minBound
-- > white = maxBound
--
-- Then you can bind to:
--
-- > ,((modm, xK_g), goToSelected $ gsconfig2 myWinColorizer)
-- > ,((modm, xK_p), spawnSelected $ spawnSelected defaultColorizer)
-- $keybindings
--
-- You can build you own navigation mode and submodes by combining the
-- exported action ingredients and assembling them using 'makeXEventhandler' and 'shadowWithKeymap'.
--
-- > myNavigation :: TwoD a (Maybe a)
-- > myNavigation = makeXEventhandler $ shadowWithKeymap navKeyMap navDefaultHandler
-- > where navKeyMap = M.fromList [
-- > ((0,xK_Escape), cancel)
-- > ,((0,xK_Return), select)
-- > ,((0,xK_slash) , substringSearch myNavigation)
-- > ,((0,xK_Left) , move (-1,0) >> myNavigation)
-- > ,((0,xK_h) , move (-1,0) >> myNavigation)
-- > ,((0,xK_Right) , move (1,0) >> myNavigation)
-- > ,((0,xK_l) , move (1,0) >> myNavigation)
-- > ,((0,xK_Down) , move (0,1) >> myNavigation)
-- > ,((0,xK_j) , move (0,1) >> myNavigation)
-- > ,((0,xK_Up) , move (0,-1) >> myNavigation)
-- > ,((0,xK_y) , move (-1,-1) >> myNavigation)
-- > ,((0,xK_i) , move (1,-1) >> myNavigation)
-- > ,((0,xK_n) , move (-1,1) >> myNavigation)
-- > ,((0,xK_m) , move (1,-1) >> myNavigation)
-- > ,((0,xK_space) , setPos (0,0) >> myNavigation)
-- > ]
-- > -- The navigation handler ignores unknown key symbols
-- > navDefaultHandler = const myNavigation
--
-- You can then define @gsconfig3@ which may be used in exactly the same manner as @gsconfig1@:
--
-- > gsconfig3 = defaultGSConfig
-- > { gs_cellheight = 30
-- > , gs_cellwidth = 100
-- > , gs_navigate = myNavigation
-- > }
-- $screenshots
--
-- Selecting a workspace:
--
-- <<http://haskell.org/wikiupload/a/a9/Xmonad-gridselect-workspace.png>>
--
-- Selecting a window by title:
--
-- <<http://haskell.org/wikiupload/3/35/Xmonad-gridselect-window-aavogt.png>>
data GSConfig a = GSConfig {
gs_cellheight :: Integer,
gs_cellwidth :: Integer,
gs_cellpadding :: Integer,
gs_colorizer :: a -> Bool -> X (String, String),
gs_font :: String,
gs_navigate :: TwoD a (Maybe a),
gs_originFractX :: Double,
gs_originFractY :: Double
}
-- | That is 'fromClassName' if you are selecting a 'Window', or
-- 'defaultColorizer' if you are selecting a 'String'. The catch-all instance
-- @HasColorizer a@ uses the 'focusedBorderColor' and 'normalBorderColor'
-- colors.
class HasColorizer a where
defaultColorizer :: a -> Bool -> X (String, String)
instance HasColorizer Window where
defaultColorizer = fromClassName
instance HasColorizer String where
defaultColorizer = stringColorizer
instance HasColorizer a where
defaultColorizer _ isFg =
let getColor = if isFg then focusedBorderColor else normalBorderColor
in asks $ flip (,) "black" . getColor . config
-- | A basic configuration for 'gridselect', with the colorizer chosen based on the type.
--
-- If you want to replace the 'gs_colorizer' field, use 'buildDefaultGSConfig'
-- instead, to avoid ambiguous type variables.
defaultGSConfig :: HasColorizer a => GSConfig a
defaultGSConfig = buildDefaultGSConfig defaultColorizer
type TwoDPosition = (Integer, Integer)
type TwoDElementMap a = [(TwoDPosition,(String,a))]
data TwoDState a = TwoDState { td_curpos :: TwoDPosition
, td_availSlots :: [TwoDPosition]
, td_elements :: [(String,a)]
, td_gsconfig :: GSConfig a
, td_font :: XMonadFont
, td_paneX :: Integer
, td_paneY :: Integer
, td_drawingWin :: Window
, td_searchString :: String
}
td_elementmap :: TwoDState a -> [(TwoDPosition,(String,a))]
td_elementmap s =
let positions = td_availSlots s
elements = L.filter (((td_searchString s) `isSubstringOf`) . fst) (td_elements s)
in zipWith (,) positions elements
where sub `isSubstringOf` string = or [ (upper sub) `isPrefixOf` t | t <- tails (upper string) ]
upper = map toUpper
newtype TwoD a b = TwoD { unTwoD :: StateT (TwoDState a) X b }
deriving (Monad,Functor,MonadState (TwoDState a))
instance Applicative (TwoD a) where
(<*>) = ap
pure = return
liftX :: X a1 -> TwoD a a1
liftX = TwoD . lift
evalTwoD :: TwoD a1 a -> TwoDState a1 -> X a
evalTwoD m s = flip evalStateT s $ unTwoD m
diamondLayer :: (Enum b', Num b') => b' -> [(b', b')]
diamondLayer 0 = [(0,0)]
diamondLayer n =
-- tr = top right
-- r = ur ++ 90 degree clock-wise rotation of ur
let tr = [ (x,n-x) | x <- [0..n-1] ]
r = tr ++ (map (\(x,y) -> (y,-x)) tr)
in r ++ (map (negate *** negate) r)
diamond :: (Enum a, Num a) => [(a, a)]
diamond = concatMap diamondLayer [0..]
diamondRestrict :: Integer -> Integer -> Integer -> Integer -> [(Integer, Integer)]
diamondRestrict x y originX originY =
L.filter (\(x',y') -> abs x' <= x && abs y' <= y) .
map (\(x', y') -> (x' + fromInteger originX, y' + fromInteger originY)) .
take 1000 $ diamond
findInElementMap :: (Eq a) => a -> [(a, b)] -> Maybe (a, b)
findInElementMap pos = find ((== pos) . fst)
drawWinBox :: Window -> XMonadFont -> (String, String) -> Integer -> Integer -> String -> Integer -> Integer -> Integer -> X ()
drawWinBox win font (fg,bg) ch cw text x y cp =
withDisplay $ \dpy -> do
gc <- liftIO $ createGC dpy win
bordergc <- liftIO $ createGC dpy win
liftIO $ do
Just fgcolor <- initColor dpy fg
Just bgcolor <- initColor dpy bg
Just bordercolor <- initColor dpy borderColor
setForeground dpy gc fgcolor
setBackground dpy gc bgcolor
setForeground dpy bordergc bordercolor
fillRectangle dpy win gc (fromInteger x) (fromInteger y) (fromInteger cw) (fromInteger ch)
drawRectangle dpy win bordergc (fromInteger x) (fromInteger y) (fromInteger cw) (fromInteger ch)
stext <- shrinkWhile (shrinkIt shrinkText)
(\n -> do size <- liftIO $ textWidthXMF dpy font n
return $ size > (fromInteger (cw-(2*cp))))
text
printStringXMF dpy win font gc bg fg (fromInteger (x+cp)) (fromInteger (y+(div ch 2))) stext
liftIO $ freeGC dpy gc
liftIO $ freeGC dpy bordergc
updateAllElements :: TwoD a ()
updateAllElements =
do
s <- get
updateElements (td_elementmap s)
grayoutAllElements :: TwoD a ()
grayoutAllElements =
do
s <- get
updateElementsWithColorizer grayOnly (td_elementmap s)
where grayOnly _ _ = return ("#808080", "#808080")
updateElements :: TwoDElementMap a -> TwoD a ()
updateElements elementmap = do
s <- get
updateElementsWithColorizer (gs_colorizer (td_gsconfig s)) elementmap
updateElementsWithColorizer :: (a -> Bool -> X (String, String)) -> TwoDElementMap a -> TwoD a ()
updateElementsWithColorizer colorizer elementmap = do
TwoDState { td_curpos = curpos,
td_drawingWin = win,
td_gsconfig = gsconfig,
td_font = font,
td_paneX = paneX,
td_paneY = paneY} <- get
let cellwidth = gs_cellwidth gsconfig
cellheight = gs_cellheight gsconfig
paneX' = div (paneX-cellwidth) 2
paneY' = div (paneY-cellheight) 2
updateElement (pos@(x,y),(text, element)) = liftX $ do
colors <- colorizer element (pos == curpos)
drawWinBox win font
colors
cellheight
cellwidth
text
(paneX'+x*cellwidth)
(paneY'+y*cellheight)
(gs_cellpadding gsconfig)
mapM_ updateElement elementmap
stdHandle :: Event -> TwoD a (Maybe a) -> TwoD a (Maybe a)
stdHandle (ButtonEvent { ev_event_type = t, ev_x = x, ev_y = y }) contEventloop
| t == buttonRelease = do
s @ TwoDState { td_paneX = px, td_paneY = py,
td_gsconfig = (GSConfig ch cw _ _ _ _ _ _) } <- get
let gridX = (fi x - (px - cw) `div` 2) `div` cw
gridY = (fi y - (py - ch) `div` 2) `div` ch
case lookup (gridX,gridY) (td_elementmap s) of
Just (_,el) -> return (Just el)
Nothing -> contEventloop
| otherwise = contEventloop
stdHandle (ExposeEvent { }) contEventloop = updateAllElements >> contEventloop
stdHandle _ contEventloop = contEventloop
-- | Embeds a key handler into the X event handler that dispatches key
-- events to the key handler, while non-key event go to the standard
-- handler.
makeXEventhandler :: ((KeySym, String, KeyMask) -> TwoD a (Maybe a)) -> TwoD a (Maybe a)
makeXEventhandler keyhandler = fix $ \me -> join $ liftX $ withDisplay $ \d -> liftIO $ allocaXEvent $ \e -> do
maskEvent d (exposureMask .|. keyPressMask .|. buttonReleaseMask) e
ev <- getEvent e
if ev_event_type ev == keyPress
then do
(ks,s) <- lookupString $ asKeyEvent e
return $ do
mask <- liftX $ cleanMask (ev_state ev)
keyhandler (fromMaybe xK_VoidSymbol ks, s, mask)
else
return $ stdHandle ev me
-- | When the map contains (KeySym,KeyMask) tuple for the given event,
-- the associated action in the map associated shadows the default key
-- handler
shadowWithKeymap :: M.Map (KeyMask, KeySym) a -> ((KeySym, String, KeyMask) -> a) -> (KeySym, String, KeyMask) -> a
shadowWithKeymap keymap dflt keyEvent@(ks,_,m') = fromMaybe (dflt keyEvent) (M.lookup (m',ks) keymap)
-- Helper functions to use for key handler functions
-- | Closes gridselect returning the element under the cursor
select :: TwoD a (Maybe a)
select = do
s <- get
return $ fmap (snd . snd) $ findInElementMap (td_curpos s) (td_elementmap s)
-- | Closes gridselect returning no element.
cancel :: TwoD a (Maybe a)
cancel = return Nothing
-- | Sets the absolute position of the cursor.
setPos :: (Integer, Integer) -> TwoD a ()
setPos newPos = do
s <- get
let elmap = td_elementmap s
newSelectedEl = findInElementMap newPos (td_elementmap s)
oldPos = td_curpos s
when (isJust newSelectedEl && newPos /= oldPos) $ do
put s { td_curpos = newPos }
updateElements (catMaybes [(findInElementMap oldPos elmap), newSelectedEl])
-- | Moves the cursor by the offsets specified
move :: (Integer, Integer) -> TwoD a ()
move (dx,dy) = do
s <- get
let (x,y) = td_curpos s
newPos = (x+dx,y+dy)
setPos newPos
-- | Apply a transformation function the current search string
transformSearchString :: (String -> String) -> TwoD a ()
transformSearchString f = do
s <- get
let oldSearchString = td_searchString s
newSearchString = f oldSearchString
when (newSearchString /= oldSearchString) $ do
-- FIXME: grayoutAllElements + updateAllElements paint some fields twice causing flickering
-- we would need a much smarter update strategy to fix that
when (length newSearchString > length oldSearchString) grayoutAllElements
-- FIXME curpos might end up outside new bounds
put s { td_searchString = newSearchString }
updateAllElements
-- | By default gridselect used the defaultNavigation action, which
-- binds left,right,up,down and vi-style h,l,j,k navigation. Return
-- quits gridselect, returning the selected element, while Escape
-- cancels the selection. Slash enters the substring search mode. In
-- substring search mode, every string-associated keystroke is
-- added to a search string, which narrows down the object
-- selection. Substring search mode comes back to regular navigation
-- via Return, while Escape cancels the search. If you want that
-- navigation style, add 'defaultNavigation' as 'gs_navigate' to your
-- 'GSConfig' object. This is done by 'buildDefaultGSConfig' automatically.
defaultNavigation :: TwoD a (Maybe a)
defaultNavigation = makeXEventhandler $ shadowWithKeymap navKeyMap navDefaultHandler
where navKeyMap = M.fromList [
((0,xK_Escape), cancel)
,((0,xK_Return), select)
,((0,xK_slash) , substringSearch defaultNavigation)
,((0,xK_Left) , move (-1,0) >> defaultNavigation)
,((0,xK_h) , move (-1,0) >> defaultNavigation)
,((0,xK_Right) , move (1,0) >> defaultNavigation)
,((0,xK_l) , move (1,0) >> defaultNavigation)
,((0,xK_Down) , move (0,1) >> defaultNavigation)
,((0,xK_j) , move (0,1) >> defaultNavigation)
,((0,xK_Up) , move (0,-1) >> defaultNavigation)
,((0,xK_k) , move (0,-1) >> defaultNavigation)
]
-- The navigation handler ignores unknown key symbols, therefore we const
navDefaultHandler = const defaultNavigation
-- | This navigation style combines navigation and search into one mode at the cost of losing vi style
-- navigation. With this style, there is no substring search submode,
-- but every typed character is added to the substring search.
navNSearch :: TwoD a (Maybe a)
navNSearch = makeXEventhandler $ shadowWithKeymap navNSearchKeyMap navNSearchDefaultHandler
where navNSearchKeyMap = M.fromList [
((0,xK_Escape), cancel)
,((0,xK_Return), select)
,((0,xK_Left) , move (-1,0) >> navNSearch)
,((0,xK_Right) , move (1,0) >> navNSearch)
,((0,xK_Down) , move (0,1) >> navNSearch)
,((0,xK_Up) , move (0,-1) >> navNSearch)
,((0,xK_BackSpace), transformSearchString (\s -> if (s == "") then "" else init s) >> navNSearch)
]
-- The navigation handler ignores unknown key symbols, therefore we const
navNSearchDefaultHandler (_,s,_) = do
transformSearchString (++ s)
navNSearch
-- | Navigation submode used for substring search. It returns to the
-- first argument navigation style when the user hits Return.
substringSearch :: TwoD a (Maybe a) -> TwoD a (Maybe a)
substringSearch returnNavigation = fix $ \me ->
let searchKeyMap = M.fromList [
((0,xK_Escape) , transformSearchString (const "") >> returnNavigation)
,((0,xK_Return) , returnNavigation)
,((0,xK_BackSpace), transformSearchString (\s -> if (s == "") then "" else init s) >> me)
]
searchDefaultHandler (_,s,_) = do
transformSearchString (++ s)
me
in makeXEventhandler $ shadowWithKeymap searchKeyMap searchDefaultHandler
-- FIXME probably move that into Utils?
-- Conversion scheme as in http://en.wikipedia.org/wiki/HSV_color_space
hsv2rgb :: Fractional a => (Integer,a,a) -> (a,a,a)
hsv2rgb (h,s,v) =
let hi = (div h 60) `mod` 6 :: Integer
f = (((fromInteger h)/60) - (fromInteger hi)) :: Fractional a => a
q = v * (1-f)
p = v * (1-s)
t = v * (1-(1-f)*s)
in case hi of
0 -> (v,t,p)
1 -> (q,v,p)
2 -> (p,v,t)
3 -> (p,q,v)
4 -> (t,p,v)
5 -> (v,p,q)
_ -> error "The world is ending. x mod a >= a."
-- | Default colorizer for Strings
stringColorizer :: String -> Bool -> X (String, String)
stringColorizer s active =
let seed x = toInteger (sum $ map ((*x).fromEnum) s) :: Integer
(r,g,b) = hsv2rgb ((seed 83) `mod` 360,
(fromInteger ((seed 191) `mod` 1000))/2500+0.4,
(fromInteger ((seed 121) `mod` 1000))/2500+0.4)
in if active
then return ("#faff69", "black")
else return ("#" ++ concat (map (twodigitHex.(round :: Double -> Word8).(*256)) [r, g, b] ), "white")
-- | Colorize a window depending on it's className.
fromClassName :: Window -> Bool -> X (String, String)
fromClassName w active = runQuery className w >>= flip defaultColorizer active
twodigitHex :: Word8 -> String
twodigitHex a = printf "%02x" a
-- | A colorizer that picks a color inside a range,
-- and depending on the window's class.
colorRangeFromClassName :: (Word8, Word8, Word8) -- ^ Beginning of the color range
-> (Word8, Word8, Word8) -- ^ End of the color range
-> (Word8, Word8, Word8) -- ^ Background of the active window
-> (Word8, Word8, Word8) -- ^ Inactive text color
-> (Word8, Word8, Word8) -- ^ Active text color
-> Window -> Bool -> X (String, String)
colorRangeFromClassName startC endC activeC inactiveT activeT w active =
do classname <- runQuery className w
if active
then return (rgbToHex activeC, rgbToHex activeT)
else return (rgbToHex $ mix startC endC
$ stringToRatio classname, rgbToHex inactiveT)
where rgbToHex :: (Word8, Word8, Word8) -> String
rgbToHex (r, g, b) = '#':twodigitHex r
++twodigitHex g++twodigitHex b
-- | Creates a mix of two colors according to a ratio
-- (1 -> first color, 0 -> second color).
mix :: (Word8, Word8, Word8) -> (Word8, Word8, Word8)
-> Double -> (Word8, Word8, Word8)
mix (r1, g1, b1) (r2, g2, b2) r = (mix' r1 r2, mix' g1 g2, mix' b1 b2)
where mix' a b = truncate $ (fi a * r) + (fi b * (1 - r))
-- | Generates a Double from a string, trying to
-- achieve a random distribution.
-- We create a random seed from the sum of all characters
-- in the string, and use it to generate a ratio between 0 and 1
stringToRatio :: String -> Double
stringToRatio "" = 0
stringToRatio s = let gen = mkStdGen $ sum $ map fromEnum s
range = (\(a, b) -> b - a) $ genRange gen
randomInt = foldr1 combine $ replicate 20 next
combine f1 f2 g = let (_, g') = f1 g in f2 g'
in fi (fst $ randomInt gen) / fi range
-- | Brings up a 2D grid of elements in the center of the screen, and one can
-- select an element with cursors keys. The selected element is returned.
gridselect :: GSConfig a -> [(String,a)] -> X (Maybe a)
gridselect _ [] = return Nothing
gridselect gsconfig elements =
withDisplay $ \dpy -> do
rootw <- asks theRoot
s <- gets $ screenRect . W.screenDetail . W.current . windowset
win <- liftIO $ mkUnmanagedWindow dpy (defaultScreenOfDisplay dpy) rootw
(rect_x s) (rect_y s) (rect_width s) (rect_height s)
liftIO $ mapWindow dpy win
liftIO $ selectInput dpy win (exposureMask .|. keyPressMask .|. buttonReleaseMask)
status <- io $ grabKeyboard dpy win True grabModeAsync grabModeAsync currentTime
io $ grabButton dpy button1 anyModifier win True buttonReleaseMask grabModeAsync grabModeAsync none none
font <- initXMF (gs_font gsconfig)
let screenWidth = toInteger $ rect_width s;
screenHeight = toInteger $ rect_height s;
selectedElement <- if (status == grabSuccess) then do
let restriction ss cs = (fromInteger ss/fromInteger (cs gsconfig)-1)/2 :: Double
restrictX = floor $ restriction screenWidth gs_cellwidth
restrictY = floor $ restriction screenHeight gs_cellheight
originPosX = floor $ ((gs_originFractX gsconfig) - (1/2)) * 2 * fromIntegral restrictX
originPosY = floor $ ((gs_originFractY gsconfig) - (1/2)) * 2 * fromIntegral restrictY
coords = diamondRestrict restrictX restrictY originPosX originPosY
evalTwoD (updateAllElements >> (gs_navigate gsconfig)) TwoDState { td_curpos = (head coords),
td_availSlots = coords,
td_elements = elements,
td_gsconfig = gsconfig,
td_font = font,
td_paneX = screenWidth,
td_paneY = screenHeight,
td_drawingWin = win,
td_searchString = "" }
else
return Nothing
liftIO $ do
unmapWindow dpy win
destroyWindow dpy win
sync dpy False
releaseXMF font
return selectedElement
-- | Like `gridSelect' but with the current windows and their titles as elements
gridselectWindow :: GSConfig Window -> X (Maybe Window)
gridselectWindow gsconf = windowMap >>= gridselect gsconf
-- | Brings up a 2D grid of windows in the center of the screen, and one can
-- select a window with cursors keys. The selected window is then passed to
-- a callback function.
withSelectedWindow :: (Window -> X ()) -> GSConfig Window -> X ()
withSelectedWindow callback conf = do
mbWindow <- gridselectWindow conf
case mbWindow of
Just w -> callback w
Nothing -> return ()
windowMap :: X [(String,Window)]
windowMap = do
ws <- gets windowset
wins <- mapM keyValuePair (W.allWindows ws)
return wins
where keyValuePair w = flip (,) w `fmap` decorateName' w
decorateName' :: Window -> X String
decorateName' w = do
fmap show $ getName w
-- | Builds a default gs config from a colorizer function.
buildDefaultGSConfig :: (a -> Bool -> X (String,String)) -> GSConfig a
buildDefaultGSConfig col = GSConfig 50 130 10 col "xft:Sans-8" defaultNavigation (1/2) (1/2)
borderColor :: String
borderColor = "white"
-- | Brings selected window to the current workspace.
bringSelected :: GSConfig Window -> X ()
bringSelected = withSelectedWindow $ \w -> do
windows (bringWindow w)
XMonad.focus w
windows W.shiftMaster
-- | Switches to selected window's workspace and focuses that window.
goToSelected :: GSConfig Window -> X ()
goToSelected = withSelectedWindow $ windows . W.focusWindow
-- | Select an application to spawn from a given list
spawnSelected :: GSConfig String -> [String] -> X ()
spawnSelected conf lst = gridselect conf (zip lst lst) >>= flip whenJust spawn
-- | Select an action and run it in the X monad
runSelectedAction :: GSConfig (X ()) -> [(String, X ())] -> X ()
runSelectedAction conf actions = do
selectedActionM <- gridselect conf actions
case selectedActionM of
Just selectedAction -> selectedAction
Nothing -> return ()
-- | Select a workspace and view it using the given function
-- (normally 'W.view' or 'W.greedyView')
--
-- Another option is to shift the current window to the selected workspace:
--
-- > gridselectWorkspace (\ws -> W.greedyView ws . W.shift ws)
gridselectWorkspace :: GSConfig WorkspaceId ->
(WorkspaceId -> WindowSet -> WindowSet) -> X ()
gridselectWorkspace conf viewFunc = withWindowSet $ \ws -> do
let wss = map W.tag $ W.hidden ws ++ map W.workspace (W.current ws : W.visible ws)
gridselect conf (zip wss wss) >>= flip whenJust (windows . viewFunc)
|
MasseR/xmonadcontrib
|
XMonad/Actions/GridSelect.hs
|
Haskell
|
bsd-3-clause
| 27,412
|
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.EXT.FogCoord
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- All raw functions and tokens from the EXT_fog_coord extension, see
-- <http://www.opengl.org/registry/specs/EXT/fog_coord.txt>.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.EXT.FogCoord (
-- * Functions
glFogCoordf,
glFogCoordd,
glFogCoordfv,
glFogCoorddv,
glFogCoordPointer,
-- * Tokens
gl_FOG_COORDINATE_SOURCE,
gl_FOG_COORDINATE,
gl_FRAGMENT_DEPTH,
gl_CURRENT_FOG_COORDINATE,
gl_FOG_COORDINATE_ARRAY_TYPE,
gl_FOG_COORDINATE_ARRAY_STRIDE,
gl_FOG_COORDINATE_ARRAY_POINTER,
gl_FOG_COORDINATE_ARRAY
) where
import Graphics.Rendering.OpenGL.Raw.ARB.Compatibility
|
mfpi/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/EXT/FogCoord.hs
|
Haskell
|
bsd-3-clause
| 1,004
|
module Main where
import System.Environment (getArgs)
import Data.Either.Combinators (fromRight')
import Text.Blaze.Html.Renderer.Pretty (renderHtml)
import Parse (iParse, doc)
import Semantics (semantic)
import Compile (compile)
main :: IO ()
main = do
[f] <- getArgs
s <- readFile f
case iParse doc f s of
Left err -> print err
Right result -> (putStr . renderHtml . compile . semantic) result
|
RoganMurley/dreamail
|
app/Main.hs
|
Haskell
|
bsd-3-clause
| 436
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
module NeuroSpider.UiManager
( setupMenuToolBars
, UiAction(..)
) where
import BasicPrelude hiding (empty, on)
import Data.Char (isUpper)
import Data.Text (pack, unpack, toLower, breakOn)
import Graphics.UI.Gtk
import Text.XML
import Text.XML.Writer
import qualified Data.Map as Map (insert, empty, lookup)
import qualified Data.Text.Lazy as Lazy
data UiAction =
File
| New | Open | Save | SaveAs | Quit |
Edit
| Cut | Copy | Paste | Delete |
Graph
| CreateNode | CreateEdge | Rename | Show |
Help
| About
deriving (Eq, Show, Read, Enum, Bounded, Ord)
name :: UiAction -> Text
name SaveAs = "Save _As"
name Cut = "Cu_t"
name CreateNode = "_Node"
name CreateEdge = "_Edge"
name a = ("_"<>) . unwords . upperSplit . show $ a
stock :: UiAction -> Text
stock CreateNode = stock_ "Add"
stock CreateEdge = stock_ "Connect"
stock Rename = stock_ "Convert"
stock Show = stock_ "Print"
stock a = stock_ $ show a
stock_ :: Text -> Text
stock_ = ("gtk-"<>) . toLower . intercalate "-" . upperSplit
data ActionActivate = Skip | FireEvent | DoIO (IO ())
activate :: UiAction -> ActionActivate
activate Quit = DoIO mainQuit
activate a | a `elem`
[File,Edit,Graph,Help] = Skip
| otherwise = FireEvent
uiXmlString :: Text
uiXmlString = snd . breakOn "<ui>" . Lazy.toStrict . renderText def $ uiXml
uiXml :: Document
uiXml = ui $ do
menubar $ do
menu File $ do
menuitem New
menuitem Open
menuitem Save
menuitem SaveAs
separator
menuitem Quit
menu Edit $ do
menuitem Cut
menuitem Copy
menuitem Paste
menuitem Delete
menu Graph $ do
menuitem CreateNode
menuitem CreateEdge
menuitem Rename
menuitem Show
menu Help $ do
menuitem About
toolbar $ do
toolitem New
toolitem Open
toolitem Save
separator
toolitem Cut
toolitem Copy
toolitem Paste
separator
toolitem CreateNode
toolitem CreateEdge
toolitem Rename
toolitem Delete
separator
toolitem Show
where
ui = document "ui"
menubar = element "menubar"
toolbar = element "toolbar"
menu = elemA "menu"
menuitem a = elemA "menuitem" a empty
toolitem a = elemA "toolitem" a empty
separator = element "separator" empty
elemA e a = elementA e [("action", show a), ("name", name a)]
setupMenuToolBars :: (WindowClass w, BoxClass b)
=> w -> b -> Map UiAction (IO ())
-> IO (Map UiAction Action)
setupMenuToolBars window box activations = do
stockIds <- stockListIds
actiongroup <- actionGroupNew "actiongroup"
actions <- forM [minBound..maxBound] $ \a -> do
let stock' = if stock a `elem` stockIds then Just (stock a) else Nothing
action <- actionNew (show a) (name a) Nothing stock'
actionGroupAddActionWithAccel actiongroup action (Nothing :: Maybe Text)
let activation = maybe (activate a) DoIO $ Map.lookup a activations
case activation of
Skip -> return id
FireEvent -> return $ Map.insert a action
DoIO io -> on action actionActivated io >> return id
uimanager <- uiManagerNew
uiManagerInsertActionGroup uimanager actiongroup 0
_ <- uiManagerAddUiFromString uimanager uiXmlString
accelgroup <- uiManagerGetAccelGroup uimanager
windowAddAccelGroup window accelgroup
menubar' <- uiManagerGetWidget uimanager "ui/menubar"
toolbar' <- uiManagerGetWidget uimanager "ui/toolbar"
let menubar = maybe (error "menubar setup") castToMenuBar menubar'
let toolbar = maybe (error "toolbar setup") castToToolbar toolbar'
boxPackStart box menubar PackNatural 0
boxPackStart box toolbar PackNatural 1
return $ foldr ($) Map.empty actions
upperSplit :: Text -> [Text]
upperSplit = map pack . takeWhile (/= "") . dropWhile (== "")
. map fst . iterate (upperSplit_ . snd) . ("",) . unpack
upperSplit_ :: String -> (String, String)
upperSplit_ s = if length startUpper > 1
then (startUpper, rest)
else (startUpper ++ s1, s2)
where (startUpper, rest) = span isUpper s
(s1, s2) = break isUpper rest
|
pavelkogan/NeuroSpider
|
src/NeuroSpider/UiManager.hs
|
Haskell
|
bsd-3-clause
| 4,273
|
{-# LANGUAGE GeneralizedNewtypeDeriving, DoRec, ExistentialQuantification, FlexibleContexts #-}
module TermSet2 where
import Control.Arrow((***))
import Control.Monad.State
import Control.Monad.Reader
import qualified Data.IntMap as IntMap
import Data.IntMap(IntMap)
import Test.QuickCheck hiding (label)
import Test.QuickCheck.Gen
import Test.QuickCheck.GenT hiding (liftGen)
import qualified Test.QuickCheck.GenT as GenT
import Data.Typeable
import TestTree
newtype Label v a = Label { unLabel :: State (Int, IntMap v) a } deriving (Functor, Monad, MonadFix)
label :: v -> Label v (Labelled v)
label x = Label $ do
(i, m) <- get
put (i+1, IntMap.insert i x m)
return (Labelled i x)
data Labelled a = Labelled Int a
runLabel :: Label v a -> (a, IntMap v)
runLabel = (id *** snd) . flip runState (0, IntMap.empty) . unLabel
-- test :: Assoc Int ()
-- test = do
-- rec x <- assoc y
-- y <- assoc x
-- return ()
data UntypedTestResults = forall a. Typeable a => UntypedTestResults (TestResults a)
newtype Univ a = Univ { unUniv :: ReaderT Int (GenT (Label UntypedTestResults)) a }
deriving (Functor, Monad, MonadFix, MonadReader Int)
testCases :: Gen a -> Gen [a]
testCases g = forM (cycle [1..50]) $ \n -> resize n g
generate :: Typeable a => TestTree a -> Univ (Labelled a)
generate t = do
n <- ask
liftLabel (label (UntypedTestResults (cutOff n t)))
liftGen :: Gen a -> Univ a
liftGen = Univ . lift . GenT.liftGen
liftLabel :: Label UntypedTestResults a -> Univ a
liftLabel = Univ . lift . lift
base :: (Ord a, Eval a, Typeable a, Arbitrary (TestCase a)) => [a] -> Univ (Labelled a)
base ts = do
tcs <- liftGen (testCases arbitrary)
generate (test tcs ts)
apply :: Labelled (a -> b) -> Labelled a -> Univ (Labelled b)
apply fs xs = do
tcs <- liftGen (testCases arbitrary)
undefined
-- generate (test tcs (
|
jystic/QuickSpec
|
TermSet2.hs
|
Haskell
|
bsd-3-clause
| 1,852
|
module Mud.Error
( MudError(..)
, humanReadableMudError
) where
import GHC.Conc.Signal
data MudError
= MudErrorNoConfigFound FilePath
| MudErrorNotInMudDirectory
| MudErrorUnreadableConfig String
| MudErrorUnreadableHistory String
| MudErrorNoRollbackPlanFound
| MudErrorScriptFailure (Either Int Signal)
| MudErrorString String
deriving (Show, Eq)
humanReadableMudError :: MudError -> String
humanReadableMudError mudError = case mudError of
MudErrorNoConfigFound path -> "no configuration file found for base: " ++ path
MudErrorNotInMudDirectory -> "configuration must be in the mud directory"
MudErrorUnreadableConfig str -> "can't read configuration file: " ++ str
MudErrorUnreadableHistory str -> "can't read history file: " ++ str
MudErrorNoRollbackPlanFound -> "can't find a rollback plan"
MudErrorScriptFailure (Left code) ->
"script failed with exit code " ++ show code
MudErrorScriptFailure (Right sig) ->
"script interrupted with signal " ++ show sig
MudErrorString str -> str
|
thoferon/mud
|
src/Mud/Error.hs
|
Haskell
|
bsd-3-clause
| 1,037
|
{-# LANGUAGE OverloadedStrings, GADTs, FlexibleInstances #-}
module D3JS.Reify where
import Data.Text (Text)
import qualified Data.Text as T
import D3JS.Type
instance Reifiable Var where
reify t = t
instance Reifiable (Var' r) where
reify (Var' name) = name
instance Reifiable (Chain a b) where
reify (Val name) = name
reify (Val' v) = reify v
reify (Val'' (Var' n)) = n
reify (Concat Nil g) = reify g
reify (Concat f g) = T.concat [reify g,".",reify f] -- method chain flows from left to right, so flips f and g.
-- reify (Func f) = reify f
reify Nil = ""
-- reify (ChainField name) = name
reify (Refine name) = name
reify (Apply args chain) = T.concat [reify chain,"(",T.intercalate "," $ map reify args,")"]
-- instance Reifiable D3Root where
-- reify D3Root = "d3"
instance Reifiable Data1D where
reify (Data1D ps) = surround $ T.intercalate "," $ map show' ps
instance Reifiable Data2D where
reify (Data2D ps) = surround $ T.intercalate "," $ map (\(x,y) -> T.concat ["[",show' x,",",show' y,"]"]) ps
instance Reifiable (JSFunc params r) where
reify (JSFunc name params) = T.concat [name,"(",T.intercalate "," $ map reify params,")"]
instance Reifiable JSParam where
reify (ParamVar name) = name
reify (PText t) = T.concat ["\"",t,"\""]
reify (PDouble d) = show' d
reify (PInt d) = show' d
reify (PFunc (FuncTxt t)) = t
reify (PFunc (FuncExp f)) = T.concat["function(d,i){return ",reify f,";}"]
reify (PFunc' f) = reify f
reify (PArray vs) = T.concat ["[",T.intercalate "," $ map reify vs,"]"]
reify (PChainValue v) = reify v
instance Reifiable (NumFunc r) where
reify (NInt i) = show' i
reify (NDouble d) = show' d
reify (NVar v) = v
reify (Add a b) = T.concat [reify a," + ",reify b]
reify (Mult a b) = T.concat [reify a," * ",reify b]
reify (Subt a b) = T.concat [reify a," - ",reify b]
reify (Mod a b) = T.concat [reify a," % ",reify b]
reify DataParam = "d"
reify DataIndex = "i"
reify DataIndexD = "i"
reify (ChainVal chain) = reify chain
reify (Index i ns) = T.concat [reify ns,"[",reify i,"]"]
reify (Field name obj) = T.concat [reify obj,".",name]
reify (Ternary cond a b) = T.concat ["(", reify cond, ") ? (", reify a, ") : (", reify b, ")"]
reify (ApplyFunc var params) = T.concat [unVar' var,"(",T.intercalate "," $ map reify params,")"]
reify (ApplyFunc' name params) = T.concat [name,"(",T.intercalate "," $ map reify params,")"]
reify (MkObject pairs) =
let f (key,val) = T.concat [key,": ",reify val]
in T.concat ["{",T.intercalate "," $ map f pairs,"}"]
-- Stub: incomplete!!
show' :: (Show a) => a -> Text
show' = T.pack . show
surround s = T.concat ["[",s,"]"]
|
nebuta/d3js-haskell
|
D3JS/Reify.hs
|
Haskell
|
bsd-3-clause
| 2,648
|
{-# LANGUAGE GeneralizedNewtypeDeriving, CPP, TypeFamilies, FlexibleInstances, FlexibleContexts, DeriveDataTypeable, TypeOperators #-}
import Development.Shake
import qualified Development.Shake.Core as Core
import Control.DeepSeq
import Control.Monad.IO.Class
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put
import Data.Typeable
#include "MyOracle.inc"
-- Make the question longer (tests that we check that question deserialization is tested)
instance Binary (Question MyOracle) where
get = do { 0 <- getWord8; return (MOQ ()) }
put (MOQ ()) = putWord8 0
instance Binary (Answer MyOracle) where
get = fmap (MOA . fromIntegral) getWord16le
put (MOA i) = putWord16le (fromIntegral i)
main :: IO ()
main = (Core.shake :: Shake (Question MyOracle :+: CanonicalFilePath) () -> IO ()) $ do
installOracle (MO 1)
"examplefile" *> \x -> do
MOA 1 <- query $ MOQ ()
liftIO $ writeFile "examplefile" "OK3"
want ["examplefile"]
|
batterseapower/openshake
|
tests/deserialization-changes/Shakefile-3.hs
|
Haskell
|
bsd-3-clause
| 991
|
--------------------------------------------------------------------
-- |
-- Module : Text.RSS1.Utils
-- Copyright : (c) Galois, Inc. 2008
-- License : BSD3
--
-- Maintainer: Sigbjorn Finne <sof@galois.com>
-- Stability : provisional
-- Portability:
--
--------------------------------------------------------------------
module Text.RSS1.Utils where
import Text.XML.Light as XML
import Text.XML.Light.Proc as XML
import Text.DublinCore.Types
import Data.Maybe (listToMaybe, mapMaybe)
pQNodes :: QName -> XML.Element -> [XML.Element]
pQNodes = XML.findChildren
pNode :: String -> XML.Element -> Maybe XML.Element
pNode x e = listToMaybe (pQNodes (qualName (rss10NS,Nothing) x) e)
pQNode :: QName -> XML.Element -> Maybe XML.Element
pQNode x e = listToMaybe (pQNodes x e)
pLeaf :: String -> XML.Element -> Maybe String
pLeaf x e = strContent `fmap` pQNode (qualName (rss10NS,Nothing) x) e
pQLeaf :: (Maybe String,Maybe String) -> String -> XML.Element -> Maybe String
pQLeaf ns x e = strContent `fmap` pQNode (qualName ns x) e
pAttr :: (Maybe String, Maybe String) -> String -> XML.Element -> Maybe String
pAttr ns x e = lookup (qualName ns x) [ (k,v) | Attr k v <- elAttribs e ]
pMany :: (Maybe String,Maybe String) -> String -> (XML.Element -> Maybe a) -> XML.Element -> [a]
pMany ns p f e = mapMaybe f (pQNodes (qualName ns p) e)
children :: XML.Element -> [XML.Element]
children e = onlyElems (elContent e)
qualName :: (Maybe String, Maybe String) -> String -> QName
qualName (ns,pre) x = QName{qName=x,qURI=ns,qPrefix=pre}
rssPrefix, rss10NS :: Maybe String
rss10NS = Just "http://purl.org/rss/1.0/"
rssPrefix = Nothing
rdfPrefix, rdfNS :: Maybe String
rdfNS = Just "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
rdfPrefix = Just "rdf"
synPrefix, synNS :: Maybe String
synNS = Just "http://purl.org/rss/1.0/modules/syndication/"
synPrefix = Just "sy"
taxPrefix, taxNS :: Maybe String
taxNS = Just "http://purl.org/rss/1.0/modules/taxonomy/"
taxPrefix = Just "taxo"
conPrefix, conNS :: Maybe String
conNS = Just "http://purl.org/rss/1.0/modules/content/"
conPrefix = Just "content"
dcPrefix, dcNS :: Maybe String
dcNS = Just "http://purl.org/dc/elements/1.1/"
dcPrefix = Just "dc"
rdfName :: String -> QName
rdfName x = QName{qName=x,qURI=rdfNS,qPrefix=rdfPrefix}
rssName :: String -> QName
rssName x = QName{qName=x,qURI=rss10NS,qPrefix=rssPrefix}
synName :: String -> QName
synName x = QName{qName=x,qURI=synNS,qPrefix=synPrefix}
known_rss_elts :: [QName]
known_rss_elts = map rssName [ "channel", "item", "image", "textinput" ]
known_syn_elts :: [QName]
known_syn_elts = map synName [ "updateBase", "updateFrequency", "updatePeriod" ]
known_dc_elts :: [QName]
known_dc_elts = map (qualName (dcNS,dcPrefix)) dc_element_names
known_tax_elts :: [QName]
known_tax_elts = map (qualName (taxNS,taxPrefix)) [ "topic", "topics" ]
known_con_elts :: [QName]
known_con_elts = map (qualName (conNS,conPrefix)) [ "items", "item", "format", "encoding" ]
removeKnownElts :: XML.Element -> [XML.Element]
removeKnownElts e =
filter (\ e1 -> not (elName e1 `elem` known_elts)) (children e)
where
known_elts =
concat [ known_rss_elts
, known_syn_elts
, known_dc_elts
, known_con_elts
, known_tax_elts
]
removeKnownAttrs :: XML.Element -> [XML.Attr]
removeKnownAttrs e =
filter (\ a -> not (attrKey a `elem` known_attrs)) (elAttribs e)
where
known_attrs =
map rdfName [ "about" ]
|
GaloisInc/feed
|
Text/RSS1/Utils.hs
|
Haskell
|
bsd-3-clause
| 3,511
|
<?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="sq-AL">
<title>Browser View | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
0xkasun/security-tools
|
src/org/zaproxy/zap/extension/browserView/resources/help_sq_AL/helpset_sq_AL.hs
|
Haskell
|
apache-2.0
| 974
|
-- | This module generates Netlist 'Decl's for a circuit graph.
module Language.KansasLava.Netlist.Decl where
import Language.KansasLava.Types
import Language.Netlist.AST
import Data.Reify.Graph (Unique)
import Language.KansasLava.Netlist.Utils
-- Entities that need a _next special *extra* signal.
--toAddNextSignal :: [Id]
--toAddNextSignal = [Prim "register"]
-- We have a few exceptions, where we generate some extra signals,
-- but in general, we generate a single signal decl for each
-- entity.
-- | Generate declarations.
genDecl :: (Unique, Entity Unique) -> [Decl]
-- Special cases
{-
genDecl (i,Entity nm outputs _)
| nm `elem` toAddNextSignal
= concat
[ [ NetDecl (next $ sigName n i) (sizedRange nTy) Nothing
, MemDecl (sigName n i) Nothing (sizedRange nTy)
]
| (n,nTy) <- outputs ]
genDecl (i,e@(Entity nm outputs@[_] inputs)) | nm == Prim "BRAM"
= concat
[ [ MemDecl (sigName n i) (memRange aTy) (sizedRange nTy)
, NetDecl (sigName n i) (sizedRange nTy) Nothing
]
| (n,nTy) <- outputs ]
where
aTy = lookupInputType "wAddr" e
genDecl (i,Entity nm outputs _)
| nm `elem` isVirtualEntity
= []
-}
-- General case
genDecl (i,e@(Entity _ outputs _))
= [ case toStdLogicTy nTy of
MatrixTy x (V y)
-> let x' = head [ po2 | po2 <- iterate (*2) 1
, po2 >= x
]
in MemDecl
(sigName n i)
(sizedRange (V x'))
(sizedRange (V y))
(case e of
Entity (Prim "rom")
[("o0",_)]
[("defs",RomTy _,Lits lits)]
-- This is reversed because we defined from (n-1) downto 0
-> Just $ reverse $ map (toTypedExpr (V y))
$ take x'
(lits ++ repeat (RepValue $ replicate y $ Just False))
_ -> Nothing
)
_ -> NetDecl
(sigName n i)
(sizedRange nTy)
(case e of
Entity (Prim "register")
[("o0",ty)]
[ _, ("def",GenericTy,gn), _, _, _] ->
Just (toTypedExpr ty gn)
_ -> Nothing)
| (n,nTy) <- outputs
, toStdLogicTy nTy /= V 0
]
|
andygill/kansas-lava
|
Language/KansasLava/Netlist/Decl.hs
|
Haskell
|
bsd-3-clause
| 2,443
|
{-# 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.
| 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 (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 stat = ppr stat
pprStaticArith :: LlvmStatic -> LlvmStatic -> LitString -> LitString -> 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"
-- Trac 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 (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 "readnon"
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"
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
-- | Reverse or leave byte data alone to fix endianness on this target.
fixEndian :: [a] -> [a]
#if defined(WORDS_BIGENDIAN)
fixEndian = id
#else
fixEndian = reverse
#endif
--------------------------------------------------------------------------------
-- * 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)
|
shlevy/ghc
|
compiler/llvmGen/Llvm/Types.hs
|
Haskell
|
bsd-3-clause
| 35,412
|
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
module IHaskell.Display.StaticCanvas (Canvas(..)) where
import Data.Text.Lazy.Builder (toLazyText)
import Data.Text.Lazy (unpack)
import Data.Text (pack, Text)
import System.IO.Unsafe
import Control.Concurrent.MVar
import Graphics.Static
import IHaskell.Display
{-# NOINLINE uniqueCounter #-}
uniqueCounter :: MVar Int
uniqueCounter = unsafePerformIO $ newMVar 0
getUniqueName :: IO Text
getUniqueName = do
val <- takeMVar uniqueCounter
let val' = val + 1
putMVar uniqueCounter val'
return $ pack $ "ihaskellStaticCanvasUniqueID" ++ show val
data Canvas = Canvas { width :: Int, height :: Int, canvas :: CanvasFree () }
instance IHaskellDisplay Canvas where
display cnv = do
name <- getUniqueName
let script = buildScript' (width cnv) (height cnv) name (canvas cnv)
return $ Display [html $ unpack $ toLazyText script]
|
artuuge/IHaskell
|
ihaskell-display/ihaskell-static-canvas/src/IHaskell/Display/StaticCanvas.hs
|
Haskell
|
mit
| 976
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE UnboxedSums #-}
{-# OPTIONS_GHC -O2 #-}
module Packed.Bytes.Stream.ST
( ByteStream(..)
, empty
, unpack
, fromBytes
) where
import Data.Primitive (Array,ByteArray(..))
import Data.Semigroup (Semigroup)
import Data.Word (Word8)
import GHC.Exts (RealWorld,State#,Int#,ByteArray#)
import GHC.Int (Int(I#))
import GHC.ST (ST(..))
import Packed.Bytes (Bytes(..))
import System.IO (Handle)
import qualified Data.Primitive as PM
import qualified Data.Semigroup as SG
import qualified Packed.Bytes as B
type Bytes# = (# ByteArray#, Int#, Int# #)
newtype ByteStream s = ByteStream
(State# s -> (# State# s, (# (# #) | (# Bytes# , ByteStream s #) #) #) )
fromBytes :: Bytes -> ByteStream s
fromBytes b = ByteStream
(\s0 -> (# s0, (# | (# unboxBytes b, empty #) #) #))
nextChunk :: ByteStream s -> ST s (Maybe (Bytes,ByteStream s))
nextChunk (ByteStream f) = ST $ \s0 -> case f s0 of
(# s1, r #) -> case r of
(# (# #) | #) -> (# s1, Nothing #)
(# | (# theBytes, theStream #) #) -> (# s1, Just (boxBytes theBytes, theStream) #)
empty :: ByteStream s
empty = ByteStream (\s -> (# s, (# (# #) | #) #) )
boxBytes :: Bytes# -> Bytes
boxBytes (# a, b, c #) = Bytes (ByteArray a) (I# b) (I# c)
unboxBytes :: Bytes -> Bytes#
unboxBytes (Bytes (ByteArray a) (I# b) (I# c)) = (# a,b,c #)
unpack :: ByteStream s -> ST s [Word8]
unpack stream = ST (unpackInternal stream)
unpackInternal :: ByteStream s -> State# s -> (# State# s, [Word8] #)
unpackInternal (ByteStream f) s0 = case f s0 of
(# s1, r #) -> case r of
(# (# #) | #) -> (# s1, [] #)
(# | (# bytes, stream #) #) -> case unpackInternal stream s1 of
(# s2, ws #) -> (# s2, B.unpack (boxBytes bytes) ++ ws #)
|
sdiehl/ghc
|
testsuite/tests/codeGen/should_run/T15038/src/Packed/Bytes/Stream/ST.hs
|
Haskell
|
bsd-3-clause
| 1,853
|
{-@ LIQUID "--no-termination" @-}
module Foo where
data RBTree a = Leaf
| Node Color !BlackHeight !(RBTree a) a !(RBTree a)
deriving (Show)
data Color = B -- ^ Black
| R -- ^ Red
deriving (Eq,Show)
type BlackHeight = Int
type RBTreeBDel a = (RBTree a, Bool)
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- delete :: Ord a => a -> RBTree a -> RBTree a
-- delete x t = turnB' s
-- where
-- (s,_) = delete' x t
--
-- delete' :: Ord a => a -> RBTree a -> RBTreeBDel a
-- delete' _ Leaf = (Leaf, False)
-- delete' x (Node c h l y r) = case compare x y of
-- LT -> let (l',d) = delete' x l
-- t = Node c h l' y r
-- in if d then unbalancedR c (h-1) l' y r else (t, False)
-- GT -> let (r',d) = delete' x r
-- t = Node c h l y r'
-- in if d then unbalancedL c (h-1) l y r' else (t, False)
-- EQ -> case r of
-- Leaf -> if c == B then blackify l else (l, False)
-- _ -> let ((r',d),m) = deleteMin' r
-- t = Node c h l m r'
-- in if d then unbalancedL c (h-1) l m r' else (t, False)
-- deleteMin :: RBTree a -> RBTree a
-- deleteMin Leaf = Leaf
-- deleteMin t = turnB' s
-- where
-- ((s, _), _) = deleteMin' t
{-@ deleteMin' :: t:RBT a -> (({v: ARBT a | ((IsB t) => (isRB v))}, Bool), a) @-}
deleteMin' :: RBTree a -> (RBTreeBDel a, a)
deleteMin' Leaf = error "deleteMin'"
deleteMin' (Node B _ Leaf x Leaf) = ((Leaf, True), x)
deleteMin' (Node B _ Leaf x r@(Node R _ _ _ _)) = ((turnB r, False), x)
deleteMin' (Node R _ Leaf x r) = ((r, False), x)
deleteMin' (Node c h l x r) = if d then (tD, m) else (tD', m)
where
((l',d),m) = deleteMin' l -- GUESS: black l --> red l' iff d is TRUE
tD = unbalancedR c (h-1) l' x r
tD' = (Node c h l' x r, False)
-- GUESS: black l --> red l' iff d is TRUE
{-@ unbalancedL :: Color -> BlackHeight -> RBT a -> a -> ARBT a -> RBTB a @-}
unbalancedL :: Color -> BlackHeight -> RBTree a -> a -> RBTree a -> RBTreeBDel a
unbalancedL c h l@(Node B _ _ _ _) x r
= (balanceL B h (turnR l) x r, c == B)
unbalancedL B h (Node R lh ll lx lr@(Node B _ _ _ _)) x r
= (Node B lh ll lx (balanceL B h (turnR lr) x r), False)
unbalancedL _ _ _ _ _ = error "unbalancedL"
-- The left tree lacks one Black node
{-@ unbalancedR :: Color -> BlackHeight -> ARBT a -> a -> RBT a -> RBTB a @-}
unbalancedR :: Color -> BlackHeight -> RBTree a -> a -> RBTree a -> RBTreeBDel a
-- Decreasing one Black node in the right
unbalancedR c h l x r@(Node B _ _ _ _)
= (balanceR B h l x (turnR r), c == B)
-- Taking one Red node from the right and adding it to the right as Black
unbalancedR B h l x (Node R rh rl@(Node B _ _ _ _) rx rr)
= (Node B rh (balanceR B h l x (turnR rl)) rx rr, False)
unbalancedR _ _ _ _ _ = error "unbalancedR"
{-@ balanceL :: k:Color -> BlackHeight -> {v:ARBT a | ((Red k) => (IsB v))} -> a -> {v:RBT a | ((Red k) => (IsB v))} -> RBT a @-}
balanceL B h (Node R _ (Node R _ a x b) y c) z d =
Node R (h+1) (Node B h a x b) y (Node B h c z d)
balanceL B h (Node R _ a x (Node R _ b y c)) z d =
Node R (h+1) (Node B h a x b) y (Node B h c z d)
balanceL k h l x r = Node k h l x r
{-@ balanceR :: k:Color -> BlackHeight -> {v:RBT a | ((Red k) => (IsB v))} -> a -> {v:ARBT a | ((Red k) => (IsB v))} -> RBT a @-}
balanceR :: Color -> BlackHeight -> RBTree a -> a -> RBTree a -> RBTree a
balanceR B h a x (Node R _ b y (Node R _ c z d)) =
Node R (h+1) (Node B h a x b) y (Node B h c z d)
balanceR B h a x (Node R _ (Node R _ b y c) z d) =
Node R (h+1) (Node B h a x b) y (Node B h c z d)
balanceR k h l x r = Node k h l x r
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
{-@ insert :: (Ord a) => a -> RBT a -> RBT a @-}
insert :: Ord a => a -> RBTree a -> RBTree a
insert kx t = turnB (insert' kx t)
{-@ turnB :: ARBT a -> RBT a @-}
turnB Leaf = error "turnB"
turnB (Node _ h l x r) = Node B h l x r
{-@ turnR :: RBT a -> ARBT a @-}
turnR Leaf = error "turnR"
turnR (Node _ h l x r) = Node R h l x r
{-@ turnB' :: ARBT a -> RBT a @-}
turnB' Leaf = Leaf
turnB' (Node _ h l x r) = Node B h l x r
{-@ insert' :: (Ord a) => a -> t:RBT a -> {v: ARBT a | ((IsB t) => (isRB v))} @-}
insert' :: Ord a => a -> RBTree a -> RBTree a
insert' kx Leaf = Node R 1 Leaf kx Leaf
insert' kx s@(Node B h l x r) = case compare kx x of
LT -> let zoo = balanceL' h (insert' kx l) x r in zoo
GT -> let zoo = balanceR' h l x (insert' kx r) in zoo
EQ -> s
insert' kx s@(Node R h l x r) = case compare kx x of
LT -> Node R h (insert' kx l) x r
GT -> Node R h l x (insert' kx r)
EQ -> s
{-@ balanceL' :: Int -> ARBT a -> a -> RBT a -> RBT a @-}
balanceL' :: BlackHeight -> RBTree a -> a -> RBTree a -> RBTree a
balanceL' h (Node R _ (Node R _ a x b) y c) z d =
Node R (h+1) (Node B h a x b) y (Node B h c z d)
balanceL' h (Node R _ a x (Node R _ b y c)) z d =
Node R (h+1) (Node B h a x b) y (Node B h c z d)
balanceL' h l x r = Node B h l x r
{-@ balanceR' :: Int -> RBT a -> a -> ARBT a -> RBT a @-}
balanceR' :: BlackHeight -> RBTree a -> a -> RBTree a -> RBTree a
balanceR' h a x (Node R _ b y (Node R _ c z d)) =
Node R (h+1) (Node B h a x b) y (Node B h c z d)
balanceR' h a x (Node R _ (Node R _ b y c) z d) =
Node R (h+1) (Node B h a x b) y (Node B h c z d)
balanceR' h l x r = Node B h l x r
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
{-@ type ARBTB a = (RBT a, Bool) @-}
{-@ type RBTB a = (RBT a, Bool) @-}
{-@ type RBT a = {v: (RBTree a) | (isRB v)} @-}
{- type ARBT a = {v: (RBTree a) | ((isARB v) && ((IsB v) => (isRB v)))} -}
{-@ type ARBT a = {v: (RBTree a) | (isARB v) } @-}
{-@ measure isRB :: RBTree a -> Prop
isRB (Leaf) = true
isRB (Node c h l x r) = ((isRB l) && (isRB r) && ((Red c) => ((IsB l) && (IsB r))))
@-}
{-@ measure isARB :: (RBTree a) -> Prop
isARB (Leaf) = true
isARB (Node c h l x r) = ((isRB l) && (isRB r))
@-}
{-@ measure col :: RBTree a -> Color
col (Node c h l x r) = c
col (Leaf) = B
@-}
{-@ predicate IsB T = not (Red (col T)) @-}
{-@ predicate Red C = C == R @-}
-------------------------------------------------------------------------------
-- Auxiliary Invariants -------------------------------------------------------
-------------------------------------------------------------------------------
{-@ predicate Invs V = ((Inv1 V) && (Inv2 V)) @-}
{-@ predicate Inv1 V = (((isARB V) && (IsB V)) => (isRB V)) @-}
{-@ predicate Inv2 V = ((isRB v) => (isARB v)) @-}
{-@ invariant {v: RBTree a | (Invs v)} @-}
{-@ inv :: RBTree a -> {v:RBTree a | (Invs v)} @-}
inv Leaf = Leaf
inv (Node c h l x r) = Node c h (inv l) x (inv r)
|
mightymoose/liquidhaskell
|
benchmarks/llrbtree-0.1.1/Data/Set/RBTree-mini-color.hs
|
Haskell
|
bsd-3-clause
| 7,444
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- experimental, not expected to work
{- our goal:
config = do
add layout Full
set terminal "urxvt"
add keys [blah blah blah]
-}
{-
ideas:
composability!
"only once" features like avoidStruts, ewmhDesktops
-}
module XMonad.Config.Monad where
import XMonad hiding (terminal, keys)
import qualified XMonad as X
import Control.Monad.Writer
import Data.Monoid
import Data.Accessor
import Data.Accessor.Basic hiding (set)
-- Ugly! To fix this we'll need to change the kind of XConfig.
newtype LayoutList a = LL [Layout a] deriving Monoid
type W = Dual (Endo (XConfig LayoutList))
mkW = Dual . Endo
newtype Config a = C (WriterT W IO a)
deriving (Functor, Monad, MonadWriter W)
-- references:
layout = fromSetGet (\x c -> c { layoutHook = x }) layoutHook
terminal = fromSetGet (\x c -> c { X.terminal = x }) X.terminal
keys = fromSetGet (\x c -> c { X.keys = x }) X.keys
set :: Accessor (XConfig LayoutList) a -> a -> Config ()
set r x = tell (mkW $ r ^= x)
add r x = tell (mkW (r ^: mappend x))
--
example :: Config ()
example = do
add layout $ LL [Layout $ Full] -- make this better
set terminal "urxvt"
|
pjones/xmonad-test
|
vendor/xmonad-contrib/XMonad/Config/Monad.hs
|
Haskell
|
bsd-2-clause
| 1,188
|
{-|
Module : Web.Facebook.Messenger
Copyright : (c) Felix Paulusma, 2016
License : MIT
Maintainer : felix.paulusma@gmail.com
Stability : semi-experimental
TODO: Explanation of this entire package (later)
-}
module Web.Facebook.Messenger (
module Web.Facebook.Messenger.Types
) where
import Web.Facebook.Messenger.Types
|
Vlix/facebookmessenger
|
src/Web/Facebook/Messenger.hs
|
Haskell
|
mit
| 343
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.